Better reset the PIN verification stati after changing the key attributes.
[gnupg.git] / g10 / misc.c
blob5b9e652ab15e04c491e383ff8566f4fac896ba73
1 /* misc.c - miscellaneous functions
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3 * 2008, 2009 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. */
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 return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
406 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
407 string representation of the algorithm name. For unknown algorithm
408 IDs this function returns "?". */
409 const char *
410 openpgp_cipher_algo_name (int algo)
412 return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
416 openpgp_pk_test_algo( int algo )
418 /* Dont't allow type 20 keys unless in rfc2440 mode. */
419 if (!RFC2440 && algo == 20)
420 return gpg_error (GPG_ERR_PUBKEY_ALGO);
422 if (algo == GCRY_PK_ELG_E)
423 algo = GCRY_PK_ELG;
425 if (algo < 0 || algo > 110)
426 return gpg_error (GPG_ERR_PUBKEY_ALGO);
427 return gcry_pk_test_algo (algo);
431 openpgp_pk_test_algo2( int algo, unsigned int use )
433 size_t use_buf = use;
435 /* Dont't allow type 20 keys unless in rfc2440 mode. */
436 if (!RFC2440 && algo == 20)
437 return gpg_error (GPG_ERR_PUBKEY_ALGO);
439 if (algo == GCRY_PK_ELG_E)
440 algo = GCRY_PK_ELG;
442 if (algo < 0 || algo > 110)
443 return gpg_error (GPG_ERR_PUBKEY_ALGO);
445 return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
448 int
449 openpgp_pk_algo_usage ( int algo )
451 int use = 0;
453 /* They are hardwired in gpg 1.0. */
454 switch ( algo ) {
455 case PUBKEY_ALGO_RSA:
456 use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
457 | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
458 break;
459 case PUBKEY_ALGO_RSA_E:
460 use = PUBKEY_USAGE_ENC;
461 break;
462 case PUBKEY_ALGO_RSA_S:
463 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
464 break;
465 case PUBKEY_ALGO_ELGAMAL:
466 if (RFC2440)
467 use = PUBKEY_USAGE_ENC;
468 break;
469 case PUBKEY_ALGO_ELGAMAL_E:
470 use = PUBKEY_USAGE_ENC;
471 break;
472 case PUBKEY_ALGO_DSA:
473 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
474 break;
475 default:
476 break;
478 return use;
482 openpgp_md_test_algo( int algo )
484 /* Note: If the list of actual supported OpenPGP algorithms changes,
485 make sure that our hard coded values at
486 print_status_begin_signing() gets updated. */
487 /* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the
488 next revision of the standard. */
489 if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7))
490 return gpg_error (GPG_ERR_DIGEST_ALGO);
491 return gcry_md_test_algo (algo);
494 #ifdef USE_IDEA
495 /* Special warning for the IDEA cipher */
496 void
497 idea_cipher_warn(int show)
499 static int warned=0;
501 if(!warned || show)
503 log_info(_("the IDEA cipher plugin is not present\n"));
504 log_info(_("please see %s for more information\n"),
505 "http://www.gnupg.org/faq/why-not-idea.html");
506 warned=1;
509 #endif
512 static unsigned long
513 get_signature_count (PKT_secret_key *sk)
515 #ifdef ENABLE_CARD_SUPPORT
516 if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
518 struct agent_card_info_s info;
519 if(agent_scd_getattr("SIG-COUNTER",&info)==0)
520 return info.sig_counter;
522 #endif
524 /* How to do this without a card? */
526 return 0;
529 /* Expand %-strings. Returns a string which must be xfreed. Returns
530 NULL if the string cannot be expanded (too large). */
531 char *
532 pct_expando(const char *string,struct expando_args *args)
534 const char *ch=string;
535 int idx=0,maxlen=0,done=0;
536 u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
537 char *ret=NULL;
539 if(args->pk)
540 keyid_from_pk(args->pk,pk_keyid);
542 if(args->sk)
543 keyid_from_sk(args->sk,sk_keyid);
545 /* This is used so that %k works in photoid command strings in
546 --list-secret-keys (which of course has a sk, but no pk). */
547 if(!args->pk && args->sk)
548 keyid_from_sk(args->sk,pk_keyid);
550 while(*ch!='\0')
552 if(!done)
554 /* 8192 is way bigger than we'll need here */
555 if(maxlen>=8192)
556 goto fail;
558 maxlen+=1024;
559 ret=xrealloc(ret,maxlen);
562 done=0;
564 if(*ch=='%')
566 switch(*(ch+1))
568 case 's': /* short key id */
569 if(idx+8<maxlen)
571 sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
572 idx+=8;
573 done=1;
575 break;
577 case 'S': /* long key id */
578 if(idx+16<maxlen)
580 sprintf(&ret[idx],"%08lX%08lX",
581 (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
582 idx+=16;
583 done=1;
585 break;
587 case 'k': /* short key id */
588 if(idx+8<maxlen)
590 sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
591 idx+=8;
592 done=1;
594 break;
596 case 'K': /* long key id */
597 if(idx+16<maxlen)
599 sprintf(&ret[idx],"%08lX%08lX",
600 (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
601 idx+=16;
602 done=1;
604 break;
606 case 'c': /* signature count from card, if any. */
607 if(idx+10<maxlen)
609 sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
610 idx+=strlen(&ret[idx]);
611 done=1;
613 break;
615 case 'p': /* primary pk fingerprint of a sk */
616 case 'f': /* pk fingerprint */
617 case 'g': /* sk fingerprint */
619 byte array[MAX_FINGERPRINT_LEN];
620 size_t len;
621 int i;
623 if((*(ch+1))=='p' && args->sk)
625 if(args->sk->is_primary)
626 fingerprint_from_sk(args->sk,array,&len);
627 else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
629 PKT_public_key *pk=
630 xmalloc_clear(sizeof(PKT_public_key));
632 if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
633 fingerprint_from_pk(pk,array,&len);
634 else
635 memset(array,0,(len=MAX_FINGERPRINT_LEN));
636 free_public_key(pk);
638 else
639 memset(array,0,(len=MAX_FINGERPRINT_LEN));
641 else if((*(ch+1))=='f' && args->pk)
642 fingerprint_from_pk(args->pk,array,&len);
643 else if((*(ch+1))=='g' && args->sk)
644 fingerprint_from_sk(args->sk,array,&len);
645 else
646 memset(array,0,(len=MAX_FINGERPRINT_LEN));
648 if(idx+(len*2)<maxlen)
650 for(i=0;i<len;i++)
652 sprintf(&ret[idx],"%02X",array[i]);
653 idx+=2;
655 done=1;
658 break;
660 case 'v': /* validity letters */
661 if(args->validity_info && idx+1<maxlen)
663 ret[idx++]=args->validity_info;
664 ret[idx]='\0';
665 done=1;
667 break;
669 /* The text string types */
670 case 't':
671 case 'T':
672 case 'V':
674 const char *str=NULL;
676 switch(*(ch+1))
678 case 't': /* e.g. "jpg" */
679 str=image_type_to_string(args->imagetype,0);
680 break;
682 case 'T': /* e.g. "image/jpeg" */
683 str=image_type_to_string(args->imagetype,2);
684 break;
686 case 'V': /* e.g. "full", "expired", etc. */
687 str=args->validity_string;
688 break;
691 if(str && idx+strlen(str)<maxlen)
693 strcpy(&ret[idx],str);
694 idx+=strlen(str);
695 done=1;
698 break;
700 case '%':
701 if(idx+1<maxlen)
703 ret[idx++]='%';
704 ret[idx]='\0';
705 done=1;
707 break;
709 /* Any unknown %-keys (like %i, %o, %I, and %O) are
710 passed through for later expansion. Note this also
711 handles the case where the last character in the
712 string is a '%' - the terminating \0 will end up here
713 and properly terminate the string. */
714 default:
715 if(idx+2<maxlen)
717 ret[idx++]='%';
718 ret[idx++]=*(ch+1);
719 ret[idx]='\0';
720 done=1;
722 break;
725 if(done)
726 ch++;
728 else
730 if(idx+1<maxlen)
732 ret[idx++]=*ch;
733 ret[idx]='\0';
734 done=1;
738 if(done)
739 ch++;
742 return ret;
744 fail:
745 xfree(ret);
746 return NULL;
749 void
750 deprecated_warning(const char *configname,unsigned int configlineno,
751 const char *option,const char *repl1,const char *repl2)
753 if(configname)
755 if(strncmp("--",option,2)==0)
756 option+=2;
758 if(strncmp("--",repl1,2)==0)
759 repl1+=2;
761 log_info(_("%s:%d: deprecated option \"%s\"\n"),
762 configname,configlineno,option);
764 else
765 log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
767 log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
771 void
772 deprecated_command (const char *name)
774 log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
775 name);
779 void
780 obsolete_option (const char *configname, unsigned int configlineno,
781 const char *name)
783 if(configname)
784 log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
785 configname, configlineno, name);
786 else
787 log_info (_("WARNING: \"%s\" is an obsolete option - it has no effect\n"),
788 name);
793 * Wrapper around gcry_cipher_map_name to provide a fallback using the
794 * "Sn" syntax as used by the preference strings.
796 int
797 string_to_cipher_algo (const char *string)
799 int val;
801 val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
802 if (!val && string && (string[0]=='S' || string[0]=='s'))
804 char *endptr;
806 string++;
807 val = strtol (string, &endptr, 10);
808 if (!*string || *endptr || openpgp_cipher_test_algo (val))
809 val = 0;
812 return val;
816 * Wrapper around gcry_md_map_name to provide a fallback using the
817 * "Hn" syntax as used by the preference strings.
819 int
820 string_to_digest_algo (const char *string)
822 int val;
824 val = gcry_md_map_name (string);
825 if (!val && string && (string[0]=='H' || string[0]=='h'))
827 char *endptr;
829 string++;
830 val = strtol (string, &endptr, 10);
831 if (!*string || *endptr || openpgp_md_test_algo (val))
832 val = 0;
835 return val;
840 const char *
841 compress_algo_to_string(int algo)
843 const char *s=NULL;
845 switch(algo)
847 case COMPRESS_ALGO_NONE:
848 s=_("Uncompressed");
849 break;
851 case COMPRESS_ALGO_ZIP:
852 s="ZIP";
853 break;
855 case COMPRESS_ALGO_ZLIB:
856 s="ZLIB";
857 break;
859 #ifdef HAVE_BZIP2
860 case COMPRESS_ALGO_BZIP2:
861 s="BZIP2";
862 break;
863 #endif
866 return s;
870 string_to_compress_algo(const char *string)
872 /* TRANSLATORS: See doc/TRANSLATE about this string. */
873 if(match_multistr(_("uncompressed|none"),string))
874 return 0;
875 else if(ascii_strcasecmp(string,"uncompressed")==0)
876 return 0;
877 else if(ascii_strcasecmp(string,"none")==0)
878 return 0;
879 else if(ascii_strcasecmp(string,"zip")==0)
880 return 1;
881 else if(ascii_strcasecmp(string,"zlib")==0)
882 return 2;
883 #ifdef HAVE_BZIP2
884 else if(ascii_strcasecmp(string,"bzip2")==0)
885 return 3;
886 #endif
887 else if(ascii_strcasecmp(string,"z0")==0)
888 return 0;
889 else if(ascii_strcasecmp(string,"z1")==0)
890 return 1;
891 else if(ascii_strcasecmp(string,"z2")==0)
892 return 2;
893 #ifdef HAVE_BZIP2
894 else if(ascii_strcasecmp(string,"z3")==0)
895 return 3;
896 #endif
897 else
898 return -1;
902 check_compress_algo(int algo)
904 #ifdef HAVE_BZIP2
905 if(algo>=0 && algo<=3)
906 return 0;
907 #else
908 if(algo>=0 && algo<=2)
909 return 0;
910 #endif
912 return G10ERR_COMPR_ALGO;
916 default_cipher_algo(void)
918 if(opt.def_cipher_algo)
919 return opt.def_cipher_algo;
920 else if(opt.personal_cipher_prefs)
921 return opt.personal_cipher_prefs[0].value;
922 else
923 return opt.s2k_cipher_algo;
926 /* There is no default_digest_algo function, but see
927 sign.c:hash_for() */
930 default_compress_algo(void)
932 if(opt.compress_algo!=-1)
933 return opt.compress_algo;
934 else if(opt.personal_compress_prefs)
935 return opt.personal_compress_prefs[0].value;
936 else
937 return DEFAULT_COMPRESS_ALGO;
940 const char *
941 compliance_option_string(void)
943 char *ver="???";
945 switch(opt.compliance)
947 case CO_GNUPG: return "--gnupg";
948 case CO_RFC4880: return "--openpgp";
949 case CO_RFC2440: return "--rfc2440";
950 case CO_RFC1991: return "--rfc1991";
951 case CO_PGP2: return "--pgp2";
952 case CO_PGP6: return "--pgp6";
953 case CO_PGP7: return "--pgp7";
954 case CO_PGP8: return "--pgp8";
957 return ver;
960 void
961 compliance_failure(void)
963 char *ver="???";
965 switch(opt.compliance)
967 case CO_GNUPG:
968 ver="GnuPG";
969 break;
971 case CO_RFC4880:
972 ver="OpenPGP";
973 break;
975 case CO_RFC2440:
976 ver="OpenPGP (older)";
977 break;
979 case CO_RFC1991:
980 ver="old PGP";
981 break;
983 case CO_PGP2:
984 ver="PGP 2.x";
985 break;
987 case CO_PGP6:
988 ver="PGP 6.x";
989 break;
991 case CO_PGP7:
992 ver="PGP 7.x";
993 break;
995 case CO_PGP8:
996 ver="PGP 8.x";
997 break;
1000 log_info(_("this message may not be usable by %s\n"),ver);
1001 opt.compliance=CO_GNUPG;
1004 /* Break a string into successive option pieces. Accepts single word
1005 options and key=value argument options. */
1006 char *
1007 optsep(char **stringp)
1009 char *tok,*end;
1011 tok=*stringp;
1012 if(tok)
1014 end=strpbrk(tok," ,=");
1015 if(end)
1017 int sawequals=0;
1018 char *ptr=end;
1020 /* what we need to do now is scan along starting with *end,
1021 If the next character we see (ignoring spaces) is an =
1022 sign, then there is an argument. */
1024 while(*ptr)
1026 if(*ptr=='=')
1027 sawequals=1;
1028 else if(*ptr!=' ')
1029 break;
1030 ptr++;
1033 /* There is an argument, so grab that too. At this point,
1034 ptr points to the first character of the argument. */
1035 if(sawequals)
1037 /* Is it a quoted argument? */
1038 if(*ptr=='"')
1040 ptr++;
1041 end=strchr(ptr,'"');
1042 if(end)
1043 end++;
1045 else
1046 end=strpbrk(ptr," ,");
1049 if(end && *end)
1051 *end='\0';
1052 *stringp=end+1;
1054 else
1055 *stringp=NULL;
1057 else
1058 *stringp=NULL;
1061 return tok;
1064 /* Breaks an option value into key and value. Returns NULL if there
1065 is no value. Note that "string" is modified to remove the =value
1066 part. */
1067 char *
1068 argsplit(char *string)
1070 char *equals,*arg=NULL;
1072 equals=strchr(string,'=');
1073 if(equals)
1075 char *quote,*space;
1077 *equals='\0';
1078 arg=equals+1;
1080 /* Quoted arg? */
1081 quote=strchr(arg,'"');
1082 if(quote)
1084 arg=quote+1;
1086 quote=strchr(arg,'"');
1087 if(quote)
1088 *quote='\0';
1090 else
1092 size_t spaces;
1094 /* Trim leading spaces off of the arg */
1095 spaces=strspn(arg," ");
1096 arg+=spaces;
1099 /* Trim tailing spaces off of the tag */
1100 space=strchr(string,' ');
1101 if(space)
1102 *space='\0';
1105 return arg;
1108 /* Return the length of the initial token, leaving off any
1109 argument. */
1110 static size_t
1111 optlen(const char *s)
1113 char *end=strpbrk(s," =");
1115 if(end)
1116 return end-s;
1117 else
1118 return strlen(s);
1122 parse_options(char *str,unsigned int *options,
1123 struct parse_options *opts,int noisy)
1125 char *tok;
1127 if (str && !strcmp (str, "help"))
1129 int i,maxlen=0;
1131 /* Figure out the longest option name so we can line these up
1132 neatly. */
1133 for(i=0;opts[i].name;i++)
1134 if(opts[i].help && maxlen<strlen(opts[i].name))
1135 maxlen=strlen(opts[i].name);
1137 for(i=0;opts[i].name;i++)
1138 if(opts[i].help)
1139 printf("%s%*s%s\n",opts[i].name,
1140 maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1142 g10_exit(0);
1145 while((tok=optsep(&str)))
1147 int i,rev=0;
1148 char *otok=tok;
1150 if(tok[0]=='\0')
1151 continue;
1153 if(ascii_strncasecmp("no-",tok,3)==0)
1155 rev=1;
1156 tok+=3;
1159 for(i=0;opts[i].name;i++)
1161 size_t toklen=optlen(tok);
1163 if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1165 /* We have a match, but it might be incomplete */
1166 if(toklen!=strlen(opts[i].name))
1168 int j;
1170 for(j=i+1;opts[j].name;j++)
1172 if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1174 if(noisy)
1175 log_info(_("ambiguous option `%s'\n"),otok);
1176 return 0;
1181 if(rev)
1183 *options&=~opts[i].bit;
1184 if(opts[i].value)
1185 *opts[i].value=NULL;
1187 else
1189 *options|=opts[i].bit;
1190 if(opts[i].value)
1191 *opts[i].value=argsplit(tok);
1193 break;
1197 if(!opts[i].name)
1199 if(noisy)
1200 log_info(_("unknown option `%s'\n"),otok);
1201 return 0;
1205 return 1;
1209 /* Check whether the string has characters not valid in an RFC-822
1210 address. To cope with OpenPGP we ignore allow non-ascii characters
1211 so that for example umlauts are legal in an email address. An
1212 OpenPGP user ID must be utf-8 encoded but there is no strict
1213 requirement for RFC-822. Thus to avoid IDNA encoding we put the
1214 address verbatim as utf-8 into the user ID under the assumption
1215 that mail programs handle IDNA at a lower level and take OpenPGP
1216 user IDs as utf-8. Note that we can't do an utf-8 encoding
1217 checking here because in keygen.c this function is called with the
1218 native encoding and native to utf-8 encoding is only done later. */
1220 has_invalid_email_chars (const char *s)
1222 int at_seen=0;
1223 const char *valid_chars=
1224 "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1226 for ( ; *s; s++ )
1228 if ( (*s & 0x80) )
1229 continue; /* We only care about ASCII. */
1230 if ( *s == '@' )
1231 at_seen=1;
1232 else if ( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1233 return 1;
1234 else if ( at_seen && !strchr( valid_chars, *s ) )
1235 return 1;
1237 return 0;
1241 /* Check whether NAME represents a valid mailbox according to
1242 RFC822. Returns true if so. */
1244 is_valid_mailbox (const char *name)
1246 return !( !name
1247 || !*name
1248 || has_invalid_email_chars (name)
1249 || string_count_chr (name,'@') != 1
1250 || *name == '@'
1251 || name[strlen(name)-1] == '@'
1252 || name[strlen(name)-1] == '.'
1253 || strstr (name, "..") );
1257 /* Similar to access(2), but uses PATH to find the file. */
1259 path_access(const char *file,int mode)
1261 char *envpath;
1262 int ret=-1;
1264 envpath=getenv("PATH");
1266 if(!envpath
1267 #ifdef HAVE_DRIVE_LETTERS
1268 || (((file[0]>='A' && file[0]<='Z')
1269 || (file[0]>='a' && file[0]<='z'))
1270 && file[1]==':')
1271 #else
1272 || file[0]=='/'
1273 #endif
1275 return access(file,mode);
1276 else
1278 /* At least as large as, but most often larger than we need. */
1279 char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1280 char *split,*item,*path=xstrdup(envpath);
1282 split=path;
1284 while((item=strsep(&split,PATHSEP_S)))
1286 strcpy(buffer,item);
1287 strcat(buffer,"/");
1288 strcat(buffer,file);
1289 ret=access(buffer,mode);
1290 if(ret==0)
1291 break;
1294 xfree(path);
1295 xfree(buffer);
1298 return ret;
1303 /* Temporary helper. */
1305 pubkey_get_npkey( int algo )
1307 size_t n;
1309 if (algo == GCRY_PK_ELG_E)
1310 algo = GCRY_PK_ELG;
1311 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
1312 n = 0;
1313 return n;
1316 /* Temporary helper. */
1318 pubkey_get_nskey( int algo )
1320 size_t n;
1322 if (algo == GCRY_PK_ELG_E)
1323 algo = GCRY_PK_ELG;
1324 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
1325 n = 0;
1326 return n;
1329 /* Temporary helper. */
1331 pubkey_get_nsig( int algo )
1333 size_t n;
1335 if (algo == GCRY_PK_ELG_E)
1336 algo = GCRY_PK_ELG;
1337 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
1338 n = 0;
1339 return n;
1342 /* Temporary helper. */
1344 pubkey_get_nenc( int algo )
1346 size_t n;
1348 if (algo == GCRY_PK_ELG_E)
1349 algo = GCRY_PK_ELG;
1350 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
1351 n = 0;
1352 return n;
1356 /* Temporary helper. */
1357 unsigned int
1358 pubkey_nbits( int algo, gcry_mpi_t *key )
1360 int rc, nbits;
1361 gcry_sexp_t sexp;
1363 if( algo == GCRY_PK_DSA ) {
1364 rc = gcry_sexp_build ( &sexp, NULL,
1365 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1366 key[0], key[1], key[2], key[3] );
1368 else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
1369 rc = gcry_sexp_build ( &sexp, NULL,
1370 "(public-key(elg(p%m)(g%m)(y%m)))",
1371 key[0], key[1], key[2] );
1373 else if( algo == GCRY_PK_RSA ) {
1374 rc = gcry_sexp_build ( &sexp, NULL,
1375 "(public-key(rsa(n%m)(e%m)))",
1376 key[0], key[1] );
1378 else
1379 return 0;
1381 if ( rc )
1382 BUG ();
1384 nbits = gcry_pk_get_nbits( sexp );
1385 gcry_sexp_release( sexp );
1386 return nbits;
1391 /* FIXME: Use gcry_mpi_print directly. */
1393 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
1395 int n=0;
1397 if( !a )
1398 return fprintf(fp, "[MPI_NULL]");
1399 if( !mode ) {
1400 unsigned int n1;
1401 n1 = gcry_mpi_get_nbits(a);
1402 n += fprintf(fp, "[%u bits]", n1);
1404 else {
1405 unsigned char *buffer;
1407 if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
1408 BUG ();
1409 fputs( buffer, fp );
1410 n += strlen(buffer);
1411 gcry_free( buffer );
1413 return n;