Replace a call to BUG by an error return.
[gnupg.git] / g10 / misc.c
blobb0e5e2ce1348952997401e4748b5cd81f5fb6bfd
1 /* misc.c - miscellaneous functions
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3 * 2008 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 3 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, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
28 #include <asm/sysinfo.h>
29 #include <asm/unistd.h>
30 #endif
31 #ifdef HAVE_SETRLIMIT
32 #include <time.h>
33 #include <sys/time.h>
34 #include <sys/resource.h>
35 #endif
36 #ifdef ENABLE_SELINUX_HACKS
37 #include <sys/stat.h>
38 #endif
40 #ifdef HAVE_W32_SYSTEM
41 #include <time.h>
42 #include <process.h>
43 #include <windows.h>
44 #include <shlobj.h>
45 #ifndef CSIDL_APPDATA
46 #define CSIDL_APPDATA 0x001a
47 #endif
48 #ifndef CSIDL_LOCAL_APPDATA
49 #define CSIDL_LOCAL_APPDATA 0x001c
50 #endif
51 #ifndef CSIDL_FLAG_CREATE
52 #define CSIDL_FLAG_CREATE 0x8000
53 #endif
54 #endif /*HAVE_W32_SYSTEM*/
56 #include "gpg.h"
57 #ifdef HAVE_W32_SYSTEM
58 # include "status.h"
59 #endif /*HAVE_W32_SYSTEM*/
60 #include "util.h"
61 #include "main.h"
62 #include "photoid.h"
63 #include "options.h"
64 #include "call-agent.h"
65 #include "i18n.h"
68 static int
69 string_count_chr (const char *string, int c)
71 int count;
73 for (count=0; *string; string++ )
74 if ( *string == c )
75 count++;
76 return count;
81 #ifdef ENABLE_SELINUX_HACKS
82 /* A object and a global variable to keep track of files marked as
83 secured. */
84 struct secured_file_item
86 struct secured_file_item *next;
87 ino_t ino;
88 dev_t dev;
90 static struct secured_file_item *secured_files;
91 #endif /*ENABLE_SELINUX_HACKS*/
96 /* For the sake of SELinux we want to restrict access through gpg to
97 certain files we keep under our own control. This function
98 registers such a file and is_secured_file may then be used to
99 check whether a file has ben registered as secured. */
100 void
101 register_secured_file (const char *fname)
103 #ifdef ENABLE_SELINUX_HACKS
104 struct stat buf;
105 struct secured_file_item *sf;
107 /* Note that we stop immediatley if something goes wrong here. */
108 if (stat (fname, &buf))
109 log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname,
110 "register_secured_file", strerror (errno));
111 /* log_debug ("registering `%s' i=%lu.%lu\n", fname, */
112 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
113 for (sf=secured_files; sf; sf = sf->next)
115 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
116 return; /* Already registered. */
119 sf = xmalloc (sizeof *sf);
120 sf->ino = buf.st_ino;
121 sf->dev = buf.st_dev;
122 sf->next = secured_files;
123 secured_files = sf;
124 #else /*!ENABLE_SELINUX_HACKS*/
125 (void)fname;
126 #endif /*!ENABLE_SELINUX_HACKS*/
129 /* Remove a file registered as secure. */
130 void
131 unregister_secured_file (const char *fname)
133 #ifdef ENABLE_SELINUX_HACKS
134 struct stat buf;
135 struct secured_file_item *sf, *sfprev;
137 if (stat (fname, &buf))
139 log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
140 "unregister_secured_file", strerror (errno));
141 return;
143 /* log_debug ("unregistering `%s' i=%lu.%lu\n", fname, */
144 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
145 for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
147 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
149 if (sfprev)
150 sfprev->next = sf->next;
151 else
152 secured_files = sf->next;
153 xfree (sf);
154 return;
157 #else /*!ENABLE_SELINUX_HACKS*/
158 (void)fname;
159 #endif /*!ENABLE_SELINUX_HACKS*/
162 /* Return true if FD is corresponds to a secured file. Using -1 for
163 FS is allowed and will return false. */
164 int
165 is_secured_file (int fd)
167 #ifdef ENABLE_SELINUX_HACKS
168 struct stat buf;
169 struct secured_file_item *sf;
171 if (fd == -1)
172 return 0; /* No file descriptor so it can't be secured either. */
174 /* Note that we print out a error here and claim that a file is
175 secure if something went wrong. */
176 if (fstat (fd, &buf))
178 log_error (_("fstat(%d) failed in %s: %s\n"), fd,
179 "is_secured_file", strerror (errno));
180 return 1;
182 /* log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
183 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
184 for (sf=secured_files; sf; sf = sf->next)
186 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
187 return 1; /* Yes. */
189 #else /*!ENABLE_SELINUX_HACKS*/
190 (void)fd;
191 #endif /*!ENABLE_SELINUX_HACKS*/
192 return 0; /* No. */
195 /* Return true if FNAME is corresponds to a secured file. Using NULL,
196 "" or "-" for FS is allowed and will return false. This function is
197 used before creating a file, thus it won't fail if the file does
198 not exist. */
199 int
200 is_secured_filename (const char *fname)
202 #ifdef ENABLE_SELINUX_HACKS
203 struct stat buf;
204 struct secured_file_item *sf;
206 if (iobuf_is_pipe_filename (fname) || !*fname)
207 return 0;
209 /* Note that we print out a error here and claim that a file is
210 secure if something went wrong. */
211 if (stat (fname, &buf))
213 if (errno == ENOENT || errno == EPERM || errno == EACCES)
214 return 0;
215 log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
216 "is_secured_filename", strerror (errno));
217 return 1;
219 /* log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
220 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
221 for (sf=secured_files; sf; sf = sf->next)
223 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
224 return 1; /* Yes. */
226 #else /*!ENABLE_SELINUX_HACKS*/
227 (void)fname;
228 #endif /*!ENABLE_SELINUX_HACKS*/
229 return 0; /* No. */
235 checksum_u16( unsigned n )
237 u16 a;
239 a = (n >> 8) & 0xff;
240 a += n & 0xff;
241 return a;
246 checksum( byte *p, unsigned n )
248 u16 a;
250 for(a=0; n; n-- )
251 a += *p++;
252 return a;
256 checksum_mpi (gcry_mpi_t a)
258 u16 csum;
259 byte *buffer;
260 size_t nbytes;
262 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
263 BUG ();
264 /* Fixme: For numbers not in secure memory we should use a stack
265 * based buffer and only allocate a larger one if mpi_print returns
266 * an error. */
267 buffer = (gcry_is_secure(a)?
268 gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
269 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
270 BUG ();
271 csum = checksum (buffer, nbytes);
272 xfree (buffer);
273 return csum;
277 buffer_to_u32( const byte *buffer )
279 unsigned long a;
280 a = *buffer << 24;
281 a |= buffer[1] << 16;
282 a |= buffer[2] << 8;
283 a |= buffer[3];
284 return a;
287 void
288 print_pubkey_algo_note( int algo )
290 if(algo >= 100 && algo <= 110)
292 static int warn=0;
293 if(!warn)
295 warn=1;
296 log_info (_("WARNING: using experimental public key algorithm %s\n"),
297 gcry_pk_algo_name (algo));
300 else if (algo == 20)
302 log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
306 void
307 print_cipher_algo_note( int algo )
309 if(algo >= 100 && algo <= 110)
311 static int warn=0;
312 if(!warn)
314 warn=1;
315 log_info (_("WARNING: using experimental cipher algorithm %s\n"),
316 openpgp_cipher_algo_name (algo));
321 void
322 print_digest_algo_note( int algo )
324 if(algo >= 100 && algo <= 110)
326 static int warn=0;
327 if(!warn)
329 warn=1;
330 log_info (_("WARNING: using experimental digest algorithm %s\n"),
331 gcry_md_algo_name (algo));
334 else if(algo==DIGEST_ALGO_MD5)
335 log_info (_("WARNING: digest algorithm %s is deprecated\n"),
336 gcry_md_algo_name (algo));
340 /* Map OpenPGP algo numbers to those used by Libgcrypt. We need to do
341 this for algorithms we implemented in Libgcrypt after they become
342 part of OpenPGP. */
343 static int
344 map_cipher_openpgp_to_gcry (int algo)
346 switch (algo)
348 case CIPHER_ALGO_CAMELLIA128: return 310;
349 case CIPHER_ALGO_CAMELLIA192: return 311;
350 case CIPHER_ALGO_CAMELLIA256: return 312;
351 default: return algo;
355 /* The inverse fucntion of above. */
356 static int
357 map_cipher_gcry_to_openpgp (int algo)
359 switch (algo)
361 case 310: return CIPHER_ALGO_CAMELLIA128;
362 case 311: return CIPHER_ALGO_CAMELLIA192;
363 case 312: return CIPHER_ALGO_CAMELLIA256;
364 default: return algo;
369 /* Return the block length of an OpenPGP cipher algorithm. */
370 int
371 openpgp_cipher_blocklen (int algo)
373 /* We use the numbers from OpenPGP to be sure that we get the right
374 block length. This is so that the packet parsing code works even
375 for unknown algorithms (for which we assume 8 due to tradition).
377 NOTE: If you change the the returned blocklen above 16, check
378 the callers because they may use a fixed size buffer of that
379 size. */
380 switch (algo)
382 case 7: case 8: case 9: /* AES */
383 case 10: /* Twofish */
384 case 11: case 12: case 13: /* Camellia */
385 return 16;
387 default:
388 return 8;
392 /****************
393 * Wrapper around the libgcrypt function with additonal checks on
394 * the OpenPGP contraints for the algo ID.
397 openpgp_cipher_test_algo( int algo )
399 /* (5 and 6 are marked reserved by rfc4880.) */
400 if ( algo < 0 || algo > 110 || algo == 5 || algo == 6 )
401 return gpg_error (GPG_ERR_CIPHER_ALGO);
403 /* Camellia is not yet defined for OpenPGP thus only allow it if
404 requested. */
405 #ifndef USE_CAMELLIA
406 if (algo == CIPHER_ALGO_CAMELLIA128
407 || algo == CIPHER_ALGO_CAMELLIA192
408 || algo == CIPHER_ALGO_CAMELLIA256)
409 return gpg_error (GPG_ERR_CIPHER_ALGO);
410 #endif
412 return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
415 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
416 string representation of the algorithm name. For unknown algorithm
417 IDs this function returns "?". */
418 const char *
419 openpgp_cipher_algo_name (int algo)
421 return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
425 openpgp_pk_test_algo( int algo )
427 /* Dont't allow type 20 keys unless in rfc2440 mode. */
428 if (!RFC2440 && algo == 20)
429 return gpg_error (GPG_ERR_PUBKEY_ALGO);
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);
436 return gcry_pk_test_algo (algo);
440 openpgp_pk_test_algo2( int algo, unsigned int use )
442 size_t use_buf = use;
444 /* Dont't allow type 20 keys unless in rfc2440 mode. */
445 if (!RFC2440 && algo == 20)
446 return gpg_error (GPG_ERR_PUBKEY_ALGO);
448 if (algo == GCRY_PK_ELG_E)
449 algo = GCRY_PK_ELG;
451 if (algo < 0 || algo > 110)
452 return gpg_error (GPG_ERR_PUBKEY_ALGO);
454 return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
457 int
458 openpgp_pk_algo_usage ( int algo )
460 int use = 0;
462 /* They are hardwired in gpg 1.0. */
463 switch ( algo ) {
464 case PUBKEY_ALGO_RSA:
465 use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
466 | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
467 break;
468 case PUBKEY_ALGO_RSA_E:
469 use = PUBKEY_USAGE_ENC;
470 break;
471 case PUBKEY_ALGO_RSA_S:
472 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
473 break;
474 case PUBKEY_ALGO_ELGAMAL:
475 if (RFC2440)
476 use = PUBKEY_USAGE_ENC;
477 break;
478 case PUBKEY_ALGO_ELGAMAL_E:
479 use = PUBKEY_USAGE_ENC;
480 break;
481 case PUBKEY_ALGO_DSA:
482 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
483 break;
484 default:
485 break;
487 return use;
491 openpgp_md_test_algo( int algo )
493 /* Note: If the list of actual supported OpenPGP algorithms changes,
494 make sure that our hard coded values at
495 print_status_begin_signing() gets updated. */
496 /* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the
497 next revision of the standard. */
498 if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7))
499 return gpg_error (GPG_ERR_DIGEST_ALGO);
500 return gcry_md_test_algo (algo);
503 #ifdef USE_IDEA
504 /* Special warning for the IDEA cipher */
505 void
506 idea_cipher_warn(int show)
508 static int warned=0;
510 if(!warned || show)
512 log_info(_("the IDEA cipher plugin is not present\n"));
513 log_info(_("please see %s for more information\n"),
514 "http://www.gnupg.org/faq/why-not-idea.html");
515 warned=1;
518 #endif
521 static unsigned long
522 get_signature_count (PKT_secret_key *sk)
524 #ifdef ENABLE_CARD_SUPPORT
525 if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
527 struct agent_card_info_s info;
528 if(agent_scd_getattr("SIG-COUNTER",&info)==0)
529 return info.sig_counter;
531 #endif
533 /* How to do this without a card? */
535 return 0;
538 /* Expand %-strings. Returns a string which must be xfreed. Returns
539 NULL if the string cannot be expanded (too large). */
540 char *
541 pct_expando(const char *string,struct expando_args *args)
543 const char *ch=string;
544 int idx=0,maxlen=0,done=0;
545 u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
546 char *ret=NULL;
548 if(args->pk)
549 keyid_from_pk(args->pk,pk_keyid);
551 if(args->sk)
552 keyid_from_sk(args->sk,sk_keyid);
554 /* This is used so that %k works in photoid command strings in
555 --list-secret-keys (which of course has a sk, but no pk). */
556 if(!args->pk && args->sk)
557 keyid_from_sk(args->sk,pk_keyid);
559 while(*ch!='\0')
561 if(!done)
563 /* 8192 is way bigger than we'll need here */
564 if(maxlen>=8192)
565 goto fail;
567 maxlen+=1024;
568 ret=xrealloc(ret,maxlen);
571 done=0;
573 if(*ch=='%')
575 switch(*(ch+1))
577 case 's': /* short key id */
578 if(idx+8<maxlen)
580 sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
581 idx+=8;
582 done=1;
584 break;
586 case 'S': /* long key id */
587 if(idx+16<maxlen)
589 sprintf(&ret[idx],"%08lX%08lX",
590 (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
591 idx+=16;
592 done=1;
594 break;
596 case 'k': /* short key id */
597 if(idx+8<maxlen)
599 sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
600 idx+=8;
601 done=1;
603 break;
605 case 'K': /* long key id */
606 if(idx+16<maxlen)
608 sprintf(&ret[idx],"%08lX%08lX",
609 (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
610 idx+=16;
611 done=1;
613 break;
615 case 'c': /* signature count from card, if any. */
616 if(idx+10<maxlen)
618 sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
619 idx+=strlen(&ret[idx]);
620 done=1;
622 break;
624 case 'p': /* primary pk fingerprint of a sk */
625 case 'f': /* pk fingerprint */
626 case 'g': /* sk fingerprint */
628 byte array[MAX_FINGERPRINT_LEN];
629 size_t len;
630 int i;
632 if((*(ch+1))=='p' && args->sk)
634 if(args->sk->is_primary)
635 fingerprint_from_sk(args->sk,array,&len);
636 else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
638 PKT_public_key *pk=
639 xmalloc_clear(sizeof(PKT_public_key));
641 if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
642 fingerprint_from_pk(pk,array,&len);
643 else
644 memset(array,0,(len=MAX_FINGERPRINT_LEN));
645 free_public_key(pk);
647 else
648 memset(array,0,(len=MAX_FINGERPRINT_LEN));
650 else if((*(ch+1))=='f' && args->pk)
651 fingerprint_from_pk(args->pk,array,&len);
652 else if((*(ch+1))=='g' && args->sk)
653 fingerprint_from_sk(args->sk,array,&len);
654 else
655 memset(array,0,(len=MAX_FINGERPRINT_LEN));
657 if(idx+(len*2)<maxlen)
659 for(i=0;i<len;i++)
661 sprintf(&ret[idx],"%02X",array[i]);
662 idx+=2;
664 done=1;
667 break;
669 case 'v': /* validity letters */
670 if(args->validity_info && idx+1<maxlen)
672 ret[idx++]=args->validity_info;
673 ret[idx]='\0';
674 done=1;
676 break;
678 /* The text string types */
679 case 't':
680 case 'T':
681 case 'V':
683 const char *str=NULL;
685 switch(*(ch+1))
687 case 't': /* e.g. "jpg" */
688 str=image_type_to_string(args->imagetype,0);
689 break;
691 case 'T': /* e.g. "image/jpeg" */
692 str=image_type_to_string(args->imagetype,2);
693 break;
695 case 'V': /* e.g. "full", "expired", etc. */
696 str=args->validity_string;
697 break;
700 if(str && idx+strlen(str)<maxlen)
702 strcpy(&ret[idx],str);
703 idx+=strlen(str);
704 done=1;
707 break;
709 case '%':
710 if(idx+1<maxlen)
712 ret[idx++]='%';
713 ret[idx]='\0';
714 done=1;
716 break;
718 /* Any unknown %-keys (like %i, %o, %I, and %O) are
719 passed through for later expansion. Note this also
720 handles the case where the last character in the
721 string is a '%' - the terminating \0 will end up here
722 and properly terminate the string. */
723 default:
724 if(idx+2<maxlen)
726 ret[idx++]='%';
727 ret[idx++]=*(ch+1);
728 ret[idx]='\0';
729 done=1;
731 break;
734 if(done)
735 ch++;
737 else
739 if(idx+1<maxlen)
741 ret[idx++]=*ch;
742 ret[idx]='\0';
743 done=1;
747 if(done)
748 ch++;
751 return ret;
753 fail:
754 xfree(ret);
755 return NULL;
758 void
759 deprecated_warning(const char *configname,unsigned int configlineno,
760 const char *option,const char *repl1,const char *repl2)
762 if(configname)
764 if(strncmp("--",option,2)==0)
765 option+=2;
767 if(strncmp("--",repl1,2)==0)
768 repl1+=2;
770 log_info(_("%s:%d: deprecated option \"%s\"\n"),
771 configname,configlineno,option);
773 else
774 log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
776 log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
780 void
781 deprecated_command (const char *name)
783 log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
784 name);
788 void
789 obsolete_option (const char *configname, unsigned int configlineno,
790 const char *name)
792 if(configname)
793 log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
794 configname, configlineno, name);
795 else
796 log_info (_("WARNING: \"%s\" is an obsolete option - it has no effect\n"),
797 name);
802 * Wrapper around gcry_cipher_map_name to provide a fallback using the
803 * "Sn" syntax as used by the preference strings.
805 int
806 string_to_cipher_algo (const char *string)
808 int val;
810 val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
811 if (!val && string && (string[0]=='S' || string[0]=='s'))
813 char *endptr;
815 string++;
816 val = strtol (string, &endptr, 10);
817 if (!*string || *endptr || openpgp_cipher_test_algo (val))
818 val = 0;
821 return val;
825 * Wrapper around gcry_md_map_name to provide a fallback using the
826 * "Hn" syntax as used by the preference strings.
828 int
829 string_to_digest_algo (const char *string)
831 int val;
833 val = gcry_md_map_name (string);
834 if (!val && string && (string[0]=='H' || string[0]=='h'))
836 char *endptr;
838 string++;
839 val = strtol (string, &endptr, 10);
840 if (!*string || *endptr || openpgp_md_test_algo (val))
841 val = 0;
844 return val;
849 const char *
850 compress_algo_to_string(int algo)
852 const char *s=NULL;
854 switch(algo)
856 case COMPRESS_ALGO_NONE:
857 s=_("Uncompressed");
858 break;
860 case COMPRESS_ALGO_ZIP:
861 s="ZIP";
862 break;
864 case COMPRESS_ALGO_ZLIB:
865 s="ZLIB";
866 break;
868 #ifdef HAVE_BZIP2
869 case COMPRESS_ALGO_BZIP2:
870 s="BZIP2";
871 break;
872 #endif
875 return s;
879 string_to_compress_algo(const char *string)
881 /* TRANSLATORS: See doc/TRANSLATE about this string. */
882 if(match_multistr(_("uncompressed|none"),string))
883 return 0;
884 else if(ascii_strcasecmp(string,"uncompressed")==0)
885 return 0;
886 else if(ascii_strcasecmp(string,"none")==0)
887 return 0;
888 else if(ascii_strcasecmp(string,"zip")==0)
889 return 1;
890 else if(ascii_strcasecmp(string,"zlib")==0)
891 return 2;
892 #ifdef HAVE_BZIP2
893 else if(ascii_strcasecmp(string,"bzip2")==0)
894 return 3;
895 #endif
896 else if(ascii_strcasecmp(string,"z0")==0)
897 return 0;
898 else if(ascii_strcasecmp(string,"z1")==0)
899 return 1;
900 else if(ascii_strcasecmp(string,"z2")==0)
901 return 2;
902 #ifdef HAVE_BZIP2
903 else if(ascii_strcasecmp(string,"z3")==0)
904 return 3;
905 #endif
906 else
907 return -1;
911 check_compress_algo(int algo)
913 #ifdef HAVE_BZIP2
914 if(algo>=0 && algo<=3)
915 return 0;
916 #else
917 if(algo>=0 && algo<=2)
918 return 0;
919 #endif
921 return G10ERR_COMPR_ALGO;
925 default_cipher_algo(void)
927 if(opt.def_cipher_algo)
928 return opt.def_cipher_algo;
929 else if(opt.personal_cipher_prefs)
930 return opt.personal_cipher_prefs[0].value;
931 else
932 return opt.s2k_cipher_algo;
935 /* There is no default_digest_algo function, but see
936 sign.c:hash_for() */
939 default_compress_algo(void)
941 if(opt.compress_algo!=-1)
942 return opt.compress_algo;
943 else if(opt.personal_compress_prefs)
944 return opt.personal_compress_prefs[0].value;
945 else
946 return DEFAULT_COMPRESS_ALGO;
949 const char *
950 compliance_option_string(void)
952 char *ver="???";
954 switch(opt.compliance)
956 case CO_GNUPG: return "--gnupg";
957 case CO_RFC4880: return "--openpgp";
958 case CO_RFC2440: return "--rfc2440";
959 case CO_RFC1991: return "--rfc1991";
960 case CO_PGP2: return "--pgp2";
961 case CO_PGP6: return "--pgp6";
962 case CO_PGP7: return "--pgp7";
963 case CO_PGP8: return "--pgp8";
966 return ver;
969 void
970 compliance_failure(void)
972 char *ver="???";
974 switch(opt.compliance)
976 case CO_GNUPG:
977 ver="GnuPG";
978 break;
980 case CO_RFC4880:
981 ver="OpenPGP";
982 break;
984 case CO_RFC2440:
985 ver="OpenPGP (older)";
986 break;
988 case CO_RFC1991:
989 ver="old PGP";
990 break;
992 case CO_PGP2:
993 ver="PGP 2.x";
994 break;
996 case CO_PGP6:
997 ver="PGP 6.x";
998 break;
1000 case CO_PGP7:
1001 ver="PGP 7.x";
1002 break;
1004 case CO_PGP8:
1005 ver="PGP 8.x";
1006 break;
1009 log_info(_("this message may not be usable by %s\n"),ver);
1010 opt.compliance=CO_GNUPG;
1013 /* Break a string into successive option pieces. Accepts single word
1014 options and key=value argument options. */
1015 char *
1016 optsep(char **stringp)
1018 char *tok,*end;
1020 tok=*stringp;
1021 if(tok)
1023 end=strpbrk(tok," ,=");
1024 if(end)
1026 int sawequals=0;
1027 char *ptr=end;
1029 /* what we need to do now is scan along starting with *end,
1030 If the next character we see (ignoring spaces) is an =
1031 sign, then there is an argument. */
1033 while(*ptr)
1035 if(*ptr=='=')
1036 sawequals=1;
1037 else if(*ptr!=' ')
1038 break;
1039 ptr++;
1042 /* There is an argument, so grab that too. At this point,
1043 ptr points to the first character of the argument. */
1044 if(sawequals)
1046 /* Is it a quoted argument? */
1047 if(*ptr=='"')
1049 ptr++;
1050 end=strchr(ptr,'"');
1051 if(end)
1052 end++;
1054 else
1055 end=strpbrk(ptr," ,");
1058 if(end && *end)
1060 *end='\0';
1061 *stringp=end+1;
1063 else
1064 *stringp=NULL;
1066 else
1067 *stringp=NULL;
1070 return tok;
1073 /* Breaks an option value into key and value. Returns NULL if there
1074 is no value. Note that "string" is modified to remove the =value
1075 part. */
1076 char *
1077 argsplit(char *string)
1079 char *equals,*arg=NULL;
1081 equals=strchr(string,'=');
1082 if(equals)
1084 char *quote,*space;
1086 *equals='\0';
1087 arg=equals+1;
1089 /* Quoted arg? */
1090 quote=strchr(arg,'"');
1091 if(quote)
1093 arg=quote+1;
1095 quote=strchr(arg,'"');
1096 if(quote)
1097 *quote='\0';
1099 else
1101 size_t spaces;
1103 /* Trim leading spaces off of the arg */
1104 spaces=strspn(arg," ");
1105 arg+=spaces;
1108 /* Trim tailing spaces off of the tag */
1109 space=strchr(string,' ');
1110 if(space)
1111 *space='\0';
1114 return arg;
1117 /* Return the length of the initial token, leaving off any
1118 argument. */
1119 static size_t
1120 optlen(const char *s)
1122 char *end=strpbrk(s," =");
1124 if(end)
1125 return end-s;
1126 else
1127 return strlen(s);
1131 parse_options(char *str,unsigned int *options,
1132 struct parse_options *opts,int noisy)
1134 char *tok;
1136 if (str && !strcmp (str, "help"))
1138 int i,maxlen=0;
1140 /* Figure out the longest option name so we can line these up
1141 neatly. */
1142 for(i=0;opts[i].name;i++)
1143 if(opts[i].help && maxlen<strlen(opts[i].name))
1144 maxlen=strlen(opts[i].name);
1146 for(i=0;opts[i].name;i++)
1147 if(opts[i].help)
1148 printf("%s%*s%s\n",opts[i].name,
1149 maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1151 g10_exit(0);
1154 while((tok=optsep(&str)))
1156 int i,rev=0;
1157 char *otok=tok;
1159 if(tok[0]=='\0')
1160 continue;
1162 if(ascii_strncasecmp("no-",tok,3)==0)
1164 rev=1;
1165 tok+=3;
1168 for(i=0;opts[i].name;i++)
1170 size_t toklen=optlen(tok);
1172 if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1174 /* We have a match, but it might be incomplete */
1175 if(toklen!=strlen(opts[i].name))
1177 int j;
1179 for(j=i+1;opts[j].name;j++)
1181 if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1183 if(noisy)
1184 log_info(_("ambiguous option `%s'\n"),otok);
1185 return 0;
1190 if(rev)
1192 *options&=~opts[i].bit;
1193 if(opts[i].value)
1194 *opts[i].value=NULL;
1196 else
1198 *options|=opts[i].bit;
1199 if(opts[i].value)
1200 *opts[i].value=argsplit(tok);
1202 break;
1206 if(!opts[i].name)
1208 if(noisy)
1209 log_info(_("unknown option `%s'\n"),otok);
1210 return 0;
1214 return 1;
1218 /* Return a new malloced string by unescaping the string S. Escaping
1219 is percent escaping and '+'/space mapping. A binary nul will
1220 silently be replaced by a 0xFF. */
1221 char *
1222 unescape_percent_string (const unsigned char *s)
1224 char *buffer, *d;
1226 buffer = d = xmalloc (strlen (s)+1);
1227 while (*s)
1229 if (*s == '%' && s[1] && s[2])
1231 s++;
1232 *d = xtoi_2 (s);
1233 if (!*d)
1234 *d = '\xff';
1235 d++;
1236 s += 2;
1238 else if (*s == '+')
1240 *d++ = ' ';
1241 s++;
1243 else
1244 *d++ = *s++;
1246 *d = 0;
1247 return buffer;
1251 /* Check whether the string has characters not valid in an RFC-822
1252 address. To cope with OpenPGP we ignore allow non-ascii characters
1253 so that for example umlauts are legal in an email address. An
1254 OpenPGP user ID must be utf-8 encoded but there is no strict
1255 requirement for RFC-822. Thus to avoid IDNA encoding we put the
1256 address verbatim as utf-8 into the user ID under the assumption
1257 that mail programs handle IDNA at a lower level and take OpenPGP
1258 user IDs as utf-8. Note that we can't do an utf-8 encoding
1259 checking here because in keygen.c this function is called with the
1260 native encoding and native to utf-8 encoding is only done later. */
1262 has_invalid_email_chars (const char *s)
1264 int at_seen=0;
1265 const char *valid_chars=
1266 "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1268 for ( ; *s; s++ )
1270 if ( (*s & 0x80) )
1271 continue; /* We only care about ASCII. */
1272 if ( *s == '@' )
1273 at_seen=1;
1274 else if ( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1275 return 1;
1276 else if ( at_seen && !strchr( valid_chars, *s ) )
1277 return 1;
1279 return 0;
1283 /* Check whether NAME represents a valid mailbox according to
1284 RFC822. Returns true if so. */
1286 is_valid_mailbox (const char *name)
1288 return !( !name
1289 || !*name
1290 || has_invalid_email_chars (name)
1291 || string_count_chr (name,'@') != 1
1292 || *name == '@'
1293 || name[strlen(name)-1] == '@'
1294 || name[strlen(name)-1] == '.'
1295 || strstr (name, "..") );
1299 /* Similar to access(2), but uses PATH to find the file. */
1301 path_access(const char *file,int mode)
1303 char *envpath;
1304 int ret=-1;
1306 envpath=getenv("PATH");
1308 if(!envpath
1309 #ifdef HAVE_DRIVE_LETTERS
1310 || (((file[0]>='A' && file[0]<='Z')
1311 || (file[0]>='a' && file[0]<='z'))
1312 && file[1]==':')
1313 #else
1314 || file[0]=='/'
1315 #endif
1317 return access(file,mode);
1318 else
1320 /* At least as large as, but most often larger than we need. */
1321 char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1322 char *split,*item,*path=xstrdup(envpath);
1324 split=path;
1326 while((item=strsep(&split,PATHSEP_S)))
1328 strcpy(buffer,item);
1329 strcat(buffer,"/");
1330 strcat(buffer,file);
1331 ret=access(buffer,mode);
1332 if(ret==0)
1333 break;
1336 xfree(path);
1337 xfree(buffer);
1340 return ret;
1345 /* Temporary helper. */
1347 pubkey_get_npkey( int algo )
1349 size_t n;
1351 if (algo == GCRY_PK_ELG_E)
1352 algo = GCRY_PK_ELG;
1353 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
1354 n = 0;
1355 return n;
1358 /* Temporary helper. */
1360 pubkey_get_nskey( int algo )
1362 size_t n;
1364 if (algo == GCRY_PK_ELG_E)
1365 algo = GCRY_PK_ELG;
1366 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
1367 n = 0;
1368 return n;
1371 /* Temporary helper. */
1373 pubkey_get_nsig( int algo )
1375 size_t n;
1377 if (algo == GCRY_PK_ELG_E)
1378 algo = GCRY_PK_ELG;
1379 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
1380 n = 0;
1381 return n;
1384 /* Temporary helper. */
1386 pubkey_get_nenc( int algo )
1388 size_t n;
1390 if (algo == GCRY_PK_ELG_E)
1391 algo = GCRY_PK_ELG;
1392 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
1393 n = 0;
1394 return n;
1398 /* Temporary helper. */
1399 unsigned int
1400 pubkey_nbits( int algo, gcry_mpi_t *key )
1402 int rc, nbits;
1403 gcry_sexp_t sexp;
1405 if( algo == GCRY_PK_DSA ) {
1406 rc = gcry_sexp_build ( &sexp, NULL,
1407 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1408 key[0], key[1], key[2], key[3] );
1410 else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
1411 rc = gcry_sexp_build ( &sexp, NULL,
1412 "(public-key(elg(p%m)(g%m)(y%m)))",
1413 key[0], key[1], key[2] );
1415 else if( algo == GCRY_PK_RSA ) {
1416 rc = gcry_sexp_build ( &sexp, NULL,
1417 "(public-key(rsa(n%m)(e%m)))",
1418 key[0], key[1] );
1420 else
1421 return 0;
1423 if ( rc )
1424 BUG ();
1426 nbits = gcry_pk_get_nbits( sexp );
1427 gcry_sexp_release( sexp );
1428 return nbits;
1433 /* FIXME: Use gcry_mpi_print directly. */
1435 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
1437 int n=0;
1439 if( !a )
1440 return fprintf(fp, "[MPI_NULL]");
1441 if( !mode ) {
1442 unsigned int n1;
1443 n1 = gcry_mpi_get_nbits(a);
1444 n += fprintf(fp, "[%u bits]", n1);
1446 else {
1447 unsigned char *buffer;
1449 if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
1450 BUG ();
1451 fputs( buffer, fp );
1452 n += strlen(buffer);
1453 gcry_free( buffer );
1455 return n;