* gpg.texi (GPG Configuration Options): Make http_proxy option
[gnupg.git] / g10 / misc.c
blobbf32228c3e149bc56c5603381fdbbdabcd33f1df
1 /* misc.c - miscellaneous functions
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2006 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
30 #include <asm/sysinfo.h>
31 #include <asm/unistd.h>
32 #endif
33 #ifdef HAVE_SETRLIMIT
34 #include <time.h>
35 #include <sys/time.h>
36 #include <sys/resource.h>
37 #endif
38 #ifdef ENABLE_SELINUX_HACKS
39 #include <sys/stat.h>
40 #endif
42 #ifdef HAVE_W32_SYSTEM
43 #include <time.h>
44 #include <process.h>
45 #include <windows.h>
46 #include <shlobj.h>
47 #ifndef CSIDL_APPDATA
48 #define CSIDL_APPDATA 0x001a
49 #endif
50 #ifndef CSIDL_LOCAL_APPDATA
51 #define CSIDL_LOCAL_APPDATA 0x001c
52 #endif
53 #ifndef CSIDL_FLAG_CREATE
54 #define CSIDL_FLAG_CREATE 0x8000
55 #endif
56 #endif /*HAVE_W32_SYSTEM*/
58 #include "gpg.h"
59 #ifdef HAVE_W32_SYSTEM
60 # include "errors.h"
61 # include "dynload.h"
62 #endif /*HAVE_W32_SYSTEM*/
63 #include "util.h"
64 #include "main.h"
65 #include "photoid.h"
66 #include "options.h"
67 #include "call-agent.h"
68 #include "i18n.h"
71 static int
72 string_count_chr (const char *string, int c)
74 int count;
76 for (count=0; *string; string++ )
77 if ( *string == c )
78 count++;
79 return count;
84 #ifdef ENABLE_SELINUX_HACKS
85 /* A object and a global variable to keep track of files marked as
86 secured. */
87 struct secured_file_item
89 struct secured_file_item *next;
90 ino_t ino;
91 dev_t dev;
93 static struct secured_file_item *secured_files;
94 #endif /*ENABLE_SELINUX_HACKS*/
98 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
99 static int
100 setsysinfo(unsigned long op, void *buffer, unsigned long size,
101 int *start, void *arg, unsigned long flag)
103 return syscall(__NR_osf_setsysinfo, op, buffer, size, start, arg, flag);
106 void
107 trap_unaligned(void)
109 unsigned int buf[2];
111 buf[0] = SSIN_UACPROC;
112 buf[1] = UAC_SIGBUS | UAC_NOPRINT;
113 setsysinfo(SSI_NVPAIRS, buf, 1, 0, 0, 0);
115 #else
116 void
117 trap_unaligned(void)
118 { /* dummy */
120 #endif
124 disable_core_dumps()
126 #ifdef HAVE_DOSISH_SYSTEM
127 return 0;
128 #else
129 #ifdef HAVE_SETRLIMIT
130 struct rlimit limit;
132 limit.rlim_cur = 0;
133 limit.rlim_max = 0;
134 if( !setrlimit( RLIMIT_CORE, &limit ) )
135 return 0;
136 if( errno != EINVAL && errno != ENOSYS )
137 log_fatal(_("can't disable core dumps: %s\n"), strerror(errno) );
138 #endif
139 return 1;
140 #endif
144 /* For the sake of SELinux we want to restrict access through gpg to
145 certain files we keep under our own control. This function
146 registers such a file and is_secured_file may then be used to
147 check whether a file has ben registered as secured. */
148 void
149 register_secured_file (const char *fname)
151 #ifdef ENABLE_SELINUX_HACKS
152 struct stat buf;
153 struct secured_file_item *sf;
155 /* Note that we stop immediatley if something goes wrong here. */
156 if (stat (fname, &buf))
157 log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname,
158 "register_secured_file", strerror (errno));
159 /* log_debug ("registering `%s' i=%lu.%lu\n", fname, */
160 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
161 for (sf=secured_files; sf; sf = sf->next)
163 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
164 return; /* Already registered. */
167 sf = xmalloc (sizeof *sf);
168 sf->ino = buf.st_ino;
169 sf->dev = buf.st_dev;
170 sf->next = secured_files;
171 secured_files = sf;
172 #endif /*ENABLE_SELINUX_HACKS*/
175 /* Remove a file registered as secure. */
176 void
177 unregister_secured_file (const char *fname)
179 #ifdef ENABLE_SELINUX_HACKS
180 struct stat buf;
181 struct secured_file_item *sf, *sfprev;
183 if (stat (fname, &buf))
185 log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
186 "unregister_secured_file", strerror (errno));
187 return;
189 /* log_debug ("unregistering `%s' i=%lu.%lu\n", fname, */
190 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
191 for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
193 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
195 if (sfprev)
196 sfprev->next = sf->next;
197 else
198 secured_files = sf->next;
199 xfree (sf);
200 return;
203 #endif /*ENABLE_SELINUX_HACKS*/
206 /* Return true if FD is corresponds to a secured file. Using -1 for
207 FS is allowed and will return false. */
208 int
209 is_secured_file (int fd)
211 #ifdef ENABLE_SELINUX_HACKS
212 struct stat buf;
213 struct secured_file_item *sf;
215 if (fd == -1)
216 return 0; /* No file descriptor so it can't be secured either. */
218 /* Note that we print out a error here and claim that a file is
219 secure if something went wrong. */
220 if (fstat (fd, &buf))
222 log_error (_("fstat(%d) failed in %s: %s\n"), fd,
223 "is_secured_file", strerror (errno));
224 return 1;
226 /* log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
227 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
228 for (sf=secured_files; sf; sf = sf->next)
230 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
231 return 1; /* Yes. */
233 #endif /*ENABLE_SELINUX_HACKS*/
234 return 0; /* No. */
237 /* Return true if FNAME is corresponds to a secured file. Using NULL,
238 "" or "-" for FS is allowed and will return false. This function is
239 used before creating a file, thus it won't fail if the file does
240 not exist. */
241 int
242 is_secured_filename (const char *fname)
244 #ifdef ENABLE_SELINUX_HACKS
245 struct stat buf;
246 struct secured_file_item *sf;
248 if (iobuf_is_pipe_filename (fname) || !*fname)
249 return 0;
251 /* Note that we print out a error here and claim that a file is
252 secure if something went wrong. */
253 if (stat (fname, &buf))
255 if (errno == ENOENT || errno == EPERM || errno == EACCES)
256 return 0;
257 log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
258 "is_secured_filename", strerror (errno));
259 return 1;
261 /* log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
262 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
263 for (sf=secured_files; sf; sf = sf->next)
265 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
266 return 1; /* Yes. */
268 #endif /*ENABLE_SELINUX_HACKS*/
269 return 0; /* No. */
275 checksum_u16( unsigned n )
277 u16 a;
279 a = (n >> 8) & 0xff;
280 a += n & 0xff;
281 return a;
286 checksum( byte *p, unsigned n )
288 u16 a;
290 for(a=0; n; n-- )
291 a += *p++;
292 return a;
296 checksum_mpi (gcry_mpi_t a)
298 u16 csum;
299 byte *buffer;
300 size_t nbytes;
302 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
303 BUG ();
304 /* Fixme: For numbers not in secure memory we should use a stack
305 * based buffer and only allocate a larger one if mpi_print returns
306 * an error. */
307 buffer = (gcry_is_secure(a)?
308 gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
309 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
310 BUG ();
311 csum = checksum (buffer, nbytes);
312 xfree (buffer);
313 return csum;
317 buffer_to_u32( const byte *buffer )
319 unsigned long a;
320 a = *buffer << 24;
321 a |= buffer[1] << 16;
322 a |= buffer[2] << 8;
323 a |= buffer[3];
324 return a;
327 void
328 print_pubkey_algo_note( int algo )
330 if(algo >= 100 && algo <= 110)
332 static int warn=0;
333 if(!warn)
335 warn=1;
336 log_info (_("WARNING: using experimental public key algorithm %s\n"),
337 gcry_pk_algo_name (algo));
342 void
343 print_cipher_algo_note( int algo )
345 if(algo >= 100 && algo <= 110)
347 static int warn=0;
348 if(!warn)
350 warn=1;
351 log_info (_("WARNING: using experimental cipher algorithm %s\n"),
352 gcry_cipher_algo_name (algo));
357 void
358 print_digest_algo_note( int algo )
360 if(algo >= 100 && algo <= 110)
362 static int warn=0;
363 if(!warn)
365 warn=1;
366 log_info (_("WARNING: using experimental digest algorithm %s\n"),
367 gcry_md_algo_name (algo));
370 else if(algo==DIGEST_ALGO_MD5)
371 log_info (_("WARNING: digest algorithm %s is deprecated\n"),
372 gcry_md_algo_name (algo));
375 /* Return a string which is used as a kind of process ID */
376 const byte *
377 get_session_marker( size_t *rlen )
379 static byte marker[SIZEOF_UNSIGNED_LONG*2];
380 static int initialized;
382 if ( !initialized )
384 volatile ulong aa, bb; /* We really want the uninitialized value. */
385 ulong a, b;
387 initialized = 1;
388 /* Although this marker is guessable it is not easy to use this
389 * for a faked control packet because an attacker does not have
390 * enough control about the time the verification takes place.
391 * Of course, we could add just more random but than we need the
392 * random generator even for verification tasks - which does not
393 * make sense. */
394 a = aa ^ (ulong)getpid();
395 b = bb ^ (ulong)time(NULL);
396 memcpy ( marker, &a, SIZEOF_UNSIGNED_LONG );
397 memcpy ( marker+SIZEOF_UNSIGNED_LONG, &b, SIZEOF_UNSIGNED_LONG );
399 *rlen = sizeof(marker);
400 return marker;
403 /****************
404 * Wrapper around the libgcrypt function with additonal checks on
405 * the OpenPGP contraints for the algo ID.
408 openpgp_cipher_test_algo( int algo )
410 if ( algo < 0 || algo > 110 )
411 return gpg_error (GPG_ERR_CIPHER_ALGO);
412 return gcry_cipher_test_algo (algo);
416 openpgp_pk_test_algo( int algo )
418 if (algo == GCRY_PK_ELG_E)
419 algo = GCRY_PK_ELG;
421 if (algo < 0 || algo > 110)
422 return gpg_error (GPG_ERR_PUBKEY_ALGO);
423 return gcry_pk_test_algo (algo);
427 openpgp_pk_test_algo2( int algo, unsigned int use )
429 size_t use_buf = use;
431 if (algo == GCRY_PK_ELG_E)
432 algo = GCRY_PK_ELG;
434 if (algo < 0 || algo > 110)
435 return gpg_error (GPG_ERR_PUBKEY_ALGO);
437 return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
440 int
441 openpgp_pk_algo_usage ( int algo )
443 int use = 0;
445 /* They are hardwired in gpg 1.0. */
446 switch ( algo ) {
447 case PUBKEY_ALGO_RSA:
448 use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
449 | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
450 break;
451 case PUBKEY_ALGO_RSA_E:
452 use = PUBKEY_USAGE_ENC;
453 break;
454 case PUBKEY_ALGO_RSA_S:
455 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
456 break;
457 case PUBKEY_ALGO_ELGAMAL_E:
458 use = PUBKEY_USAGE_ENC;
459 break;
460 case PUBKEY_ALGO_DSA:
461 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
462 break;
463 default:
464 break;
466 return use;
470 openpgp_md_test_algo( int algo )
472 if (algo < 0 || algo > 110)
473 return gpg_error (GPG_ERR_DIGEST_ALGO);
474 return gcry_md_test_algo (algo);
477 #ifdef USE_IDEA
478 /* Special warning for the IDEA cipher */
479 void
480 idea_cipher_warn(int show)
482 static int warned=0;
484 if(!warned || show)
486 log_info(_("the IDEA cipher plugin is not present\n"));
487 log_info(_("please see %s for more information\n"),
488 "http://www.gnupg.org/faq/why-not-idea.html");
489 warned=1;
492 #endif
495 static unsigned long
496 get_signature_count (PKT_secret_key *sk)
498 #ifdef ENABLE_CARD_SUPPORT
499 if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
501 struct agent_card_info_s info;
502 if(agent_scd_getattr("SIG-COUNTER",&info)==0)
503 return info.sig_counter;
505 #endif
507 /* How to do this without a card? */
509 return 0;
512 /* Expand %-strings. Returns a string which must be xfreed. Returns
513 NULL if the string cannot be expanded (too large). */
514 char *
515 pct_expando(const char *string,struct expando_args *args)
517 const char *ch=string;
518 int idx=0,maxlen=0,done=0;
519 u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
520 char *ret=NULL;
522 if(args->pk)
523 keyid_from_pk(args->pk,pk_keyid);
525 if(args->sk)
526 keyid_from_sk(args->sk,sk_keyid);
528 /* This is used so that %k works in photoid command strings in
529 --list-secret-keys (which of course has a sk, but no pk). */
530 if(!args->pk && args->sk)
531 keyid_from_sk(args->sk,pk_keyid);
533 while(*ch!='\0')
535 char *str=NULL;
537 if(!done)
539 /* 8192 is way bigger than we'll need here */
540 if(maxlen>=8192)
541 goto fail;
543 maxlen+=1024;
544 ret=xrealloc(ret,maxlen);
547 done=0;
549 if(*ch=='%')
551 switch(*(ch+1))
553 case 's': /* short key id */
554 if(idx+8<maxlen)
556 sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
557 idx+=8;
558 done=1;
560 break;
562 case 'S': /* long key id */
563 if(idx+16<maxlen)
565 sprintf(&ret[idx],"%08lX%08lX",
566 (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
567 idx+=16;
568 done=1;
570 break;
572 case 'k': /* short key id */
573 if(idx+8<maxlen)
575 sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
576 idx+=8;
577 done=1;
579 break;
581 case 'K': /* long key id */
582 if(idx+16<maxlen)
584 sprintf(&ret[idx],"%08lX%08lX",
585 (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
586 idx+=16;
587 done=1;
589 break;
591 case 'c': /* signature count from card, if any. */
592 if(idx+10<maxlen)
594 sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
595 idx+=strlen(&ret[idx]);
596 done=1;
598 break;
600 case 'p': /* primary pk fingerprint of a sk */
601 case 'f': /* pk fingerprint */
602 case 'g': /* sk fingerprint */
604 byte array[MAX_FINGERPRINT_LEN];
605 size_t len;
606 int i;
608 if((*(ch+1))=='p' && args->sk)
610 if(args->sk->is_primary)
611 fingerprint_from_sk(args->sk,array,&len);
612 else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
614 PKT_public_key *pk=
615 xmalloc_clear(sizeof(PKT_public_key));
617 if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
618 fingerprint_from_pk(pk,array,&len);
619 else
620 memset(array,0,(len=MAX_FINGERPRINT_LEN));
621 free_public_key(pk);
623 else
624 memset(array,0,(len=MAX_FINGERPRINT_LEN));
626 else if((*(ch+1))=='f' && args->pk)
627 fingerprint_from_pk(args->pk,array,&len);
628 else if((*(ch+1))=='g' && args->sk)
629 fingerprint_from_sk(args->sk,array,&len);
630 else
631 memset(array,0,(len=MAX_FINGERPRINT_LEN));
633 if(idx+(len*2)<maxlen)
635 for(i=0;i<len;i++)
637 sprintf(&ret[idx],"%02X",array[i]);
638 idx+=2;
640 done=1;
643 break;
645 case 't': /* e.g. "jpg" */
646 str=image_type_to_string(args->imagetype,0);
647 /* fall through */
649 case 'T': /* e.g. "image/jpeg" */
650 if(str==NULL)
651 str=image_type_to_string(args->imagetype,2);
653 if(idx+strlen(str)<maxlen)
655 strcpy(&ret[idx],str);
656 idx+=strlen(str);
657 done=1;
659 break;
661 case '%':
662 if(idx+1<maxlen)
664 ret[idx++]='%';
665 ret[idx]='\0';
666 done=1;
668 break;
670 /* Any unknown %-keys (like %i, %o, %I, and %O) are
671 passed through for later expansion. Note this also
672 handles the case where the last character in the
673 string is a '%' - the terminating \0 will end up here
674 and properly terminate the string. */
675 default:
676 if(idx+2<maxlen)
678 ret[idx++]='%';
679 ret[idx++]=*(ch+1);
680 ret[idx]='\0';
681 done=1;
683 break;
686 if(done)
687 ch++;
689 else
691 if(idx+1<maxlen)
693 ret[idx++]=*ch;
694 ret[idx]='\0';
695 done=1;
699 if(done)
700 ch++;
703 return ret;
705 fail:
706 xfree(ret);
707 return NULL;
710 void
711 deprecated_warning(const char *configname,unsigned int configlineno,
712 const char *option,const char *repl1,const char *repl2)
714 if(configname)
716 if(strncmp("--",option,2)==0)
717 option+=2;
719 if(strncmp("--",repl1,2)==0)
720 repl1+=2;
722 log_info(_("%s:%d: deprecated option \"%s\"\n"),
723 configname,configlineno,option);
725 else
726 log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
728 log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
732 void
733 deprecated_command (const char *name)
735 log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
736 name);
741 * Wrapper around gcry_cipher_map_name to provide a fallback using the
742 * "Sn" syntax as used by the preference strings.
744 int
745 string_to_cipher_algo (const char *string)
747 int val;
749 val = gcry_cipher_map_name (string);
750 if (!val && string && (string[0]=='S' || string[0]=='s'))
752 char *endptr;
754 string++;
755 val = strtol (string, &endptr, 10);
756 if (!*string || *endptr || openpgp_cipher_test_algo (val))
757 val = 0;
760 return val;
764 * Wrapper around gcry_md_map_name to provide a fallback using the
765 * "Hn" syntax as used by the preference strings.
767 int
768 string_to_digest_algo (const char *string)
770 int val;
772 val = gcry_md_map_name (string);
773 if (!val && string && (string[0]=='H' || string[0]=='h'))
775 char *endptr;
777 string++;
778 val = strtol (string, &endptr, 10);
779 if (!*string || *endptr || openpgp_md_test_algo (val))
780 val = 0;
783 return val;
788 const char *
789 compress_algo_to_string(int algo)
791 const char *s=NULL;
793 switch(algo)
795 case COMPRESS_ALGO_NONE:
796 s=_("Uncompressed");
797 break;
799 case COMPRESS_ALGO_ZIP:
800 s="ZIP";
801 break;
803 case COMPRESS_ALGO_ZLIB:
804 s="ZLIB";
805 break;
807 #ifdef HAVE_BZIP2
808 case COMPRESS_ALGO_BZIP2:
809 s="BZIP2";
810 break;
811 #endif
814 return s;
818 string_to_compress_algo(const char *string)
820 /* TRANSLATORS: See doc/TRANSLATE about this string. */
821 if(match_multistr(_("uncompressed|none"),string))
822 return 0;
823 else if(ascii_strcasecmp(string,"uncompressed")==0)
824 return 0;
825 else if(ascii_strcasecmp(string,"none")==0)
826 return 0;
827 else if(ascii_strcasecmp(string,"zip")==0)
828 return 1;
829 else if(ascii_strcasecmp(string,"zlib")==0)
830 return 2;
831 #ifdef HAVE_BZIP2
832 else if(ascii_strcasecmp(string,"bzip2")==0)
833 return 3;
834 #endif
835 else if(ascii_strcasecmp(string,"z0")==0)
836 return 0;
837 else if(ascii_strcasecmp(string,"z1")==0)
838 return 1;
839 else if(ascii_strcasecmp(string,"z2")==0)
840 return 2;
841 #ifdef HAVE_BZIP2
842 else if(ascii_strcasecmp(string,"z3")==0)
843 return 3;
844 #endif
845 else
846 return -1;
850 check_compress_algo(int algo)
852 #ifdef HAVE_BZIP2
853 if(algo>=0 && algo<=3)
854 return 0;
855 #else
856 if(algo>=0 && algo<=2)
857 return 0;
858 #endif
860 return G10ERR_COMPR_ALGO;
864 default_cipher_algo(void)
866 if(opt.def_cipher_algo)
867 return opt.def_cipher_algo;
868 else if(opt.personal_cipher_prefs)
869 return opt.personal_cipher_prefs[0].value;
870 else
871 return opt.s2k_cipher_algo;
874 /* There is no default_digest_algo function, but see
875 sign.c:hash_for() */
878 default_compress_algo(void)
880 if(opt.compress_algo!=-1)
881 return opt.compress_algo;
882 else if(opt.personal_compress_prefs)
883 return opt.personal_compress_prefs[0].value;
884 else
885 return DEFAULT_COMPRESS_ALGO;
888 const char *
889 compliance_option_string(void)
891 switch(opt.compliance)
893 case CO_RFC2440:
894 return "--openpgp";
895 case CO_PGP2:
896 return "--pgp2";
897 case CO_PGP6:
898 return "--pgp6";
899 case CO_PGP7:
900 return "--pgp7";
901 case CO_PGP8:
902 return "--pgp8";
903 default:
904 return "???";
908 static const char *
909 compliance_string(void)
911 switch(opt.compliance)
913 case CO_RFC2440:
914 return "OpenPGP";
915 case CO_PGP2:
916 return "PGP 2.x";
917 case CO_PGP6:
918 return "PGP 6.x";
919 case CO_PGP7:
920 return "PGP 7.x";
921 case CO_PGP8:
922 return "PGP 8.x";
923 default:
924 return "???";
928 void
929 compliance_failure(void)
931 log_info(_("this message may not be usable by %s\n"),compliance_string());
932 opt.compliance=CO_GNUPG;
935 /* Break a string into successive option pieces. Accepts single word
936 options and key=value argument options. */
937 char *
938 optsep(char **stringp)
940 char *tok,*end;
942 tok=*stringp;
943 if(tok)
945 end=strpbrk(tok," ,=");
946 if(end)
948 int sawequals=0;
949 char *ptr=end;
951 /* what we need to do now is scan along starting with *end,
952 If the next character we see (ignoring spaces) is an =
953 sign, then there is an argument. */
955 while(*ptr)
957 if(*ptr=='=')
958 sawequals=1;
959 else if(*ptr!=' ')
960 break;
961 ptr++;
964 /* There is an argument, so grab that too. At this point,
965 ptr points to the first character of the argument. */
966 if(sawequals)
968 /* Is it a quoted argument? */
969 if(*ptr=='"')
971 ptr++;
972 end=strchr(ptr,'"');
973 if(end)
974 end++;
976 else
977 end=strpbrk(ptr," ,");
980 if(end && *end)
982 *end='\0';
983 *stringp=end+1;
985 else
986 *stringp=NULL;
988 else
989 *stringp=NULL;
992 return tok;
995 /* Breaks an option value into key and value. Returns NULL if there
996 is no value. Note that "string" is modified to remove the =value
997 part. */
998 char *
999 argsplit(char *string)
1001 char *equals,*arg=NULL;
1003 equals=strchr(string,'=');
1004 if(equals)
1006 char *quote,*space;
1008 *equals='\0';
1009 arg=equals+1;
1011 /* Quoted arg? */
1012 quote=strchr(arg,'"');
1013 if(quote)
1015 arg=quote+1;
1017 quote=strchr(arg,'"');
1018 if(quote)
1019 *quote='\0';
1021 else
1023 size_t spaces;
1025 /* Trim leading spaces off of the arg */
1026 spaces=strspn(arg," ");
1027 arg+=spaces;
1030 /* Trim tailing spaces off of the tag */
1031 space=strchr(string,' ');
1032 if(space)
1033 *space='\0';
1036 return arg;
1039 /* Return the length of the initial token, leaving off any
1040 argument. */
1041 static size_t
1042 optlen(const char *s)
1044 char *end=strpbrk(s," =");
1046 if(end)
1047 return end-s;
1048 else
1049 return strlen(s);
1053 parse_options(char *str,unsigned int *options,
1054 struct parse_options *opts,int noisy)
1056 char *tok;
1058 if (str && !strcmp (str, "help"))
1060 int i,maxlen=0;
1062 /* Figure out the longest option name so we can line these up
1063 neatly. */
1064 for(i=0;opts[i].name;i++)
1065 if(opts[i].help && maxlen<strlen(opts[i].name))
1066 maxlen=strlen(opts[i].name);
1068 for(i=0;opts[i].name;i++)
1069 if(opts[i].help)
1070 printf("%s%*s%s\n",opts[i].name,
1071 maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1073 g10_exit(0);
1076 while((tok=optsep(&str)))
1078 int i,rev=0;
1079 char *otok=tok;
1081 if(tok[0]=='\0')
1082 continue;
1084 if(ascii_strncasecmp("no-",tok,3)==0)
1086 rev=1;
1087 tok+=3;
1090 for(i=0;opts[i].name;i++)
1092 size_t toklen=optlen(tok);
1094 if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1096 /* We have a match, but it might be incomplete */
1097 if(toklen!=strlen(opts[i].name))
1099 int j;
1101 for(j=i+1;opts[j].name;j++)
1103 if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1105 if(noisy)
1106 log_info(_("ambiguous option `%s'\n"),otok);
1107 return 0;
1112 if(rev)
1114 *options&=~opts[i].bit;
1115 if(opts[i].value)
1116 *opts[i].value=NULL;
1118 else
1120 *options|=opts[i].bit;
1121 if(opts[i].value)
1122 *opts[i].value=argsplit(tok);
1124 break;
1128 if(!opts[i].name)
1130 if(noisy)
1131 log_info(_("unknown option `%s'\n"),otok);
1132 return 0;
1136 return 1;
1140 /* Return a new malloced string by unescaping the string S. Escaping
1141 is percent escaping and '+'/space mapping. A binary nul will
1142 silently be replaced by a 0xFF. */
1143 char *
1144 unescape_percent_string (const unsigned char *s)
1146 char *buffer, *d;
1148 buffer = d = xmalloc (strlen (s)+1);
1149 while (*s)
1151 if (*s == '%' && s[1] && s[2])
1153 s++;
1154 *d = xtoi_2 (s);
1155 if (!*d)
1156 *d = '\xff';
1157 d++;
1158 s += 2;
1160 else if (*s == '+')
1162 *d++ = ' ';
1163 s++;
1165 else
1166 *d++ = *s++;
1168 *d = 0;
1169 return buffer;
1174 has_invalid_email_chars (const char *s)
1176 int at_seen=0;
1177 const char *valid_chars=
1178 "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1180 for ( ; *s; s++ )
1182 if ( *s & 0x80 )
1183 return 1;
1184 if ( *s == '@' )
1185 at_seen=1;
1186 else if ( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1187 return 1;
1188 else if ( at_seen && !strchr( valid_chars, *s ) )
1189 return 1;
1191 return 0;
1195 /* Check whether NAME represents a valid mailbox according to
1196 RFC822. Returns true if so. */
1198 is_valid_mailbox (const char *name)
1200 return !( !name
1201 || !*name
1202 || has_invalid_email_chars (name)
1203 || string_count_chr (name,'@') != 1
1204 || *name == '@'
1205 || name[strlen(name)-1] == '@'
1206 || name[strlen(name)-1] == '.'
1207 || strstr (name, "..") );
1211 /* This is a helper function to load a Windows function from either of
1212 one DLLs. */
1213 #ifdef HAVE_W32_SYSTEM
1214 static HRESULT
1215 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1217 static int initialized;
1218 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1220 if (!initialized)
1222 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1223 void *handle;
1224 int i;
1226 initialized = 1;
1228 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1230 handle = dlopen (dllnames[i], RTLD_LAZY);
1231 if (handle)
1233 func = dlsym (handle, "SHGetFolderPathA");
1234 if (!func)
1236 dlclose (handle);
1237 handle = NULL;
1243 if (func)
1244 return func (a,b,c,d,e);
1245 else
1246 return -1;
1248 #endif /*HAVE_W32_SYSTEM*/
1251 /* Return the name of the libexec directory. The name is allocated in
1252 a static area on the first use. This function won't fail. */
1253 const char *
1254 get_libexecdir (void)
1256 #ifdef HAVE_W32_SYSTEM
1257 static int got_dir;
1258 static char dir[MAX_PATH+5];
1260 if (!got_dir)
1262 char *p;
1264 if ( !GetModuleFileName ( NULL, dir, MAX_PATH) )
1266 log_debug ("GetModuleFileName failed: %s\n", w32_strerror (0));
1267 *dir = 0;
1269 got_dir = 1;
1270 p = strrchr (dir, DIRSEP_C);
1271 if (p)
1272 *p = 0;
1273 else
1275 log_debug ("bad filename `%s' returned for this process\n", dir);
1276 *dir = 0;
1280 if (*dir)
1281 return dir;
1282 /* Fallback to the hardwired value. */
1283 #endif /*HAVE_W32_SYSTEM*/
1285 return GNUPG_LIBEXECDIR;
1288 /* Similar to access(2), but uses PATH to find the file. */
1290 path_access(const char *file,int mode)
1292 char *envpath;
1293 int ret=-1;
1295 envpath=getenv("PATH");
1297 if(!envpath
1298 #ifdef HAVE_DRIVE_LETTERS
1299 || (((file[0]>='A' && file[0]<='Z')
1300 || (file[0]>='a' && file[0]<='z'))
1301 && file[1]==':')
1302 #else
1303 || file[0]=='/'
1304 #endif
1306 return access(file,mode);
1307 else
1309 /* At least as large as, but most often larger than we need. */
1310 char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1311 char *split,*item,*path=xstrdup(envpath);
1313 split=path;
1315 while((item=strsep(&split,PATHSEP_S)))
1317 strcpy(buffer,item);
1318 strcat(buffer,"/");
1319 strcat(buffer,file);
1320 ret=access(buffer,mode);
1321 if(ret==0)
1322 break;
1325 xfree(path);
1326 xfree(buffer);
1329 return ret;
1334 /* Temporary helper. */
1336 pubkey_get_npkey( int algo )
1338 size_t n;
1340 if (algo == GCRY_PK_ELG_E)
1341 algo = GCRY_PK_ELG;
1342 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
1343 n = 0;
1344 return n;
1347 /* Temporary helper. */
1349 pubkey_get_nskey( int algo )
1351 size_t n;
1353 if (algo == GCRY_PK_ELG_E)
1354 algo = GCRY_PK_ELG;
1355 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
1356 n = 0;
1357 return n;
1360 /* Temporary helper. */
1362 pubkey_get_nsig( int algo )
1364 size_t n;
1366 if (algo == GCRY_PK_ELG_E)
1367 algo = GCRY_PK_ELG;
1368 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
1369 n = 0;
1370 return n;
1373 /* Temporary helper. */
1375 pubkey_get_nenc( int algo )
1377 size_t n;
1379 if (algo == GCRY_PK_ELG_E)
1380 algo = GCRY_PK_ELG;
1381 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
1382 n = 0;
1383 return n;
1387 /* Temporary helper. */
1388 unsigned int
1389 pubkey_nbits( int algo, gcry_mpi_t *key )
1391 int rc, nbits;
1392 gcry_sexp_t sexp;
1394 if( algo == GCRY_PK_DSA ) {
1395 rc = gcry_sexp_build ( &sexp, NULL,
1396 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1397 key[0], key[1], key[2], key[3] );
1399 else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
1400 rc = gcry_sexp_build ( &sexp, NULL,
1401 "(public-key(elg(p%m)(g%m)(y%m)))",
1402 key[0], key[1], key[2] );
1404 else if( algo == GCRY_PK_RSA ) {
1405 rc = gcry_sexp_build ( &sexp, NULL,
1406 "(public-key(rsa(n%m)(e%m)))",
1407 key[0], key[1] );
1409 else
1410 return 0;
1412 if ( rc )
1413 BUG ();
1415 nbits = gcry_pk_get_nbits( sexp );
1416 gcry_sexp_release( sexp );
1417 return nbits;
1422 /* FIXME: Use gcry_mpi_print directly. */
1424 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
1426 int n=0;
1428 if( !a )
1429 return fprintf(fp, "[MPI_NULL]");
1430 if( !mode ) {
1431 unsigned int n1;
1432 n1 = gcry_mpi_get_nbits(a);
1433 n += fprintf(fp, "[%u bits]", n1);
1435 else {
1436 unsigned char *buffer;
1438 if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
1439 BUG ();
1440 fputs( buffer, fp );
1441 n += strlen(buffer);
1442 gcry_free( buffer );
1444 return n;