Imported Upstream version 2.0.19
[platform/upstream/gpg2.git] / g10 / misc.c
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.
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
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
39
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*/
55
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"
66
67
68 static int
69 string_count_chr (const char *string, int c)
70 {
71   int count;
72
73   for (count=0; *string; string++ )
74     if ( *string == c )
75       count++;
76   return count;
77 }
78
79
80
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 
85 {
86   struct secured_file_item *next;
87   ino_t ino;
88   dev_t dev;
89 };
90 static struct secured_file_item *secured_files;
91 #endif /*ENABLE_SELINUX_HACKS*/
92
93
94
95
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)
102 {
103 #ifdef ENABLE_SELINUX_HACKS
104   struct stat buf;
105   struct secured_file_item *sf;
106
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)
114     {
115       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
116         return; /* Already registered.  */
117     }
118
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*/
127 }
128
129 /* Remove a file registered as secure. */
130 void
131 unregister_secured_file (const char *fname)
132 {
133 #ifdef ENABLE_SELINUX_HACKS
134   struct stat buf;
135   struct secured_file_item *sf, *sfprev;
136
137   if (stat (fname, &buf))
138     {
139       log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
140                  "unregister_secured_file", strerror (errno));
141       return;
142     }
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)
146     {
147       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
148         {
149           if (sfprev)
150             sfprev->next = sf->next;
151           else
152             secured_files = sf->next;
153           xfree (sf);
154           return;
155         }
156     }
157 #else /*!ENABLE_SELINUX_HACKS*/
158   (void)fname;
159 #endif /*!ENABLE_SELINUX_HACKS*/
160 }
161
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)
166 {
167 #ifdef ENABLE_SELINUX_HACKS
168   struct stat buf;
169   struct secured_file_item *sf;
170
171   if (fd == -1)
172     return 0; /* No file descriptor so it can't be secured either.  */
173
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))
177     {
178       log_error (_("fstat(%d) failed in %s: %s\n"), fd, 
179                  "is_secured_file", strerror (errno));
180       return 1;
181     }
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)
185     {
186       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
187         return 1; /* Yes.  */
188     }
189 #else /*!ENABLE_SELINUX_HACKS*/
190   (void)fd;
191 #endif /*!ENABLE_SELINUX_HACKS*/
192   return 0; /* No. */
193 }
194
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)
201 {
202 #ifdef ENABLE_SELINUX_HACKS
203   struct stat buf;
204   struct secured_file_item *sf;
205
206   if (iobuf_is_pipe_filename (fname) || !*fname)
207     return 0; 
208
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))
212     {
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;
218     }
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)
222     {
223       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
224         return 1; /* Yes.  */
225     }
226 #else /*!ENABLE_SELINUX_HACKS*/
227   (void)fname;
228 #endif /*!ENABLE_SELINUX_HACKS*/
229   return 0; /* No. */
230 }
231
232
233
234 u16
235 checksum_u16( unsigned n )
236 {
237     u16 a;
238
239     a  = (n >> 8) & 0xff;
240     a += n & 0xff;
241     return a;
242 }
243
244
245 u16
246 checksum( byte *p, unsigned n )
247 {
248     u16 a;
249
250     for(a=0; n; n-- )
251         a += *p++;
252     return a;
253 }
254
255 u16
256 checksum_mpi (gcry_mpi_t a)
257 {
258   u16 csum;
259   byte *buffer;
260   size_t nbytes;
261
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;
274 }
275
276 u32
277 buffer_to_u32( const byte *buffer )
278 {
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;
285 }
286
287 void
288 print_pubkey_algo_note( int algo )
289 {
290   if(algo >= 100 && algo <= 110)
291     {
292       static int warn=0;
293       if(!warn)
294         {
295           warn=1;
296           log_info (_("WARNING: using experimental public key algorithm %s\n"),
297                     gcry_pk_algo_name (algo));
298         }
299     }
300   else if (algo == 20)
301     {
302       log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
303     }
304 }
305
306 void
307 print_cipher_algo_note( int algo )
308 {
309   if(algo >= 100 && algo <= 110)
310     {
311       static int warn=0;
312       if(!warn)
313         {
314           warn=1;
315           log_info (_("WARNING: using experimental cipher algorithm %s\n"),
316                     openpgp_cipher_algo_name (algo));
317         }
318     }
319 }
320
321 void
322 print_digest_algo_note( int algo )
323 {
324   if(algo >= 100 && algo <= 110)
325     {
326       static int warn=0;
327       if(!warn)
328         {
329           warn=1;
330           log_info (_("WARNING: using experimental digest algorithm %s\n"),
331                     gcry_md_algo_name (algo));
332         }
333     }
334   else if(algo==DIGEST_ALGO_MD5)
335     log_info (_("WARNING: digest algorithm %s is deprecated\n"),
336               gcry_md_algo_name (algo));
337 }
338
339
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 int
344 map_cipher_openpgp_to_gcry (int algo)
345 {
346   switch (algo)
347     {
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;
352     }
353 }
354
355 /* The inverse fucntion of above.  */
356 static int
357 map_cipher_gcry_to_openpgp (int algo)
358 {
359   switch (algo)
360     {
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;
365     }
366 }
367
368
369 /* Return the block length of an OpenPGP cipher algorithm.  */
370 int 
371 openpgp_cipher_blocklen (int algo)
372 {
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).
376
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)
381     {
382     case 7: case 8: case 9: /* AES */
383     case 10: /* Twofish */
384     case 11: case 12: case 13: /* Camellia */
385       return 16;
386
387     default:
388       return 8;
389     }
390 }
391
392 /****************
393  * Wrapper around the libgcrypt function with additonal checks on
394  * the OpenPGP contraints for the algo ID.
395  */
396 int
397 openpgp_cipher_test_algo( int algo )
398 {
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);
402
403   return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
404 }
405
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) 
411 {
412   return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
413 }
414
415 int
416 openpgp_pk_test_algo( int algo )
417 {
418   /* Dont't allow type 20 keys unless in rfc2440 mode.  */
419   if (!RFC2440 && algo == 20)
420     return gpg_error (GPG_ERR_PUBKEY_ALGO);
421     
422   if (algo == GCRY_PK_ELG_E)
423     algo = GCRY_PK_ELG;
424
425   if (algo < 0 || algo > 110)
426     return gpg_error (GPG_ERR_PUBKEY_ALGO);
427   return gcry_pk_test_algo (algo);
428 }
429
430 int
431 openpgp_pk_test_algo2( int algo, unsigned int use )
432 {
433   size_t use_buf = use;
434
435   /* Dont't allow type 20 keys unless in rfc2440 mode.  */
436   if (!RFC2440 && algo == 20)
437     return gpg_error (GPG_ERR_PUBKEY_ALGO);
438
439   if (algo == GCRY_PK_ELG_E)
440     algo = GCRY_PK_ELG;
441
442   if (algo < 0 || algo > 110)
443     return gpg_error (GPG_ERR_PUBKEY_ALGO);
444
445   return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
446 }
447
448 int 
449 openpgp_pk_algo_usage ( int algo )
450 {
451     int use = 0; 
452     
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;
477     }
478     return use;
479 }
480
481 int
482 openpgp_md_test_algo( int algo )
483 {
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);
492 }
493
494 #ifdef USE_IDEA
495 /* Special warning for the IDEA cipher */
496 void
497 idea_cipher_warn(int show)
498 {
499   static int warned=0;
500
501   if(!warned || show)
502     {
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;
507     }
508 }
509 #endif
510
511
512 static unsigned long 
513 get_signature_count (PKT_secret_key *sk)
514 {
515 #ifdef ENABLE_CARD_SUPPORT
516   if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
517     {
518       struct agent_card_info_s info;
519       if(agent_scd_getattr("SIG-COUNTER",&info)==0)
520         return info.sig_counter;
521     }  
522 #endif
523
524   /* How to do this without a card? */
525
526   return 0;
527 }
528
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)
533 {
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;
538
539   if(args->pk)
540     keyid_from_pk(args->pk,pk_keyid);
541
542   if(args->sk)
543     keyid_from_sk(args->sk,sk_keyid);
544
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);
549
550   while(*ch!='\0')
551     {
552       if(!done)
553         {
554           /* 8192 is way bigger than we'll need here */
555           if(maxlen>=8192)
556             goto fail;
557
558           maxlen+=1024;
559           ret=xrealloc(ret,maxlen);
560         }
561
562       done=0;
563
564       if(*ch=='%')
565         {
566           switch(*(ch+1))
567             {
568             case 's': /* short key id */
569               if(idx+8<maxlen)
570                 {
571                   sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
572                   idx+=8;
573                   done=1;
574                 }
575               break;
576
577             case 'S': /* long key id */
578               if(idx+16<maxlen)
579                 {
580                   sprintf(&ret[idx],"%08lX%08lX",
581                           (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
582                   idx+=16;
583                   done=1;
584                 }
585               break;
586
587             case 'k': /* short key id */
588               if(idx+8<maxlen)
589                 {
590                   sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
591                   idx+=8;
592                   done=1;
593                 }
594               break;
595
596             case 'K': /* long key id */
597               if(idx+16<maxlen)
598                 {
599                   sprintf(&ret[idx],"%08lX%08lX",
600                           (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
601                   idx+=16;
602                   done=1;
603                 }
604               break;
605
606             case 'c': /* signature count from card, if any. */
607               if(idx+10<maxlen)
608                 {
609                   sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
610                   idx+=strlen(&ret[idx]);
611                   done=1;
612                 }             
613               break;
614
615             case 'p': /* primary pk fingerprint of a sk */
616             case 'f': /* pk fingerprint */
617             case 'g': /* sk fingerprint */
618               {
619                 byte array[MAX_FINGERPRINT_LEN];
620                 size_t len;
621                 int i;
622
623                 if((*(ch+1))=='p' && args->sk)
624                   {
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])
628                       {
629                         PKT_public_key *pk=
630                           xmalloc_clear(sizeof(PKT_public_key));
631
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);
637                       }
638                     else
639                       memset(array,0,(len=MAX_FINGERPRINT_LEN));
640                   }
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));
647
648                 if(idx+(len*2)<maxlen)
649                   {
650                     for(i=0;i<len;i++)
651                       {
652                         sprintf(&ret[idx],"%02X",array[i]);
653                         idx+=2;
654                       }
655                     done=1;
656                   }
657               }
658               break;
659
660             case 'v': /* validity letters */
661               if(args->validity_info && idx+1<maxlen)
662                 {
663                   ret[idx++]=args->validity_info;
664                   ret[idx]='\0';
665                   done=1;
666                 }
667               break;
668
669               /* The text string types */
670             case 't':
671             case 'T':
672             case 'V':
673               {
674                 const char *str=NULL;
675
676                 switch(*(ch+1))
677                   {
678                   case 't': /* e.g. "jpg" */
679                     str=image_type_to_string(args->imagetype,0);
680                     break;
681                   
682                   case 'T': /* e.g. "image/jpeg" */
683                     str=image_type_to_string(args->imagetype,2);
684                     break;
685
686                   case 'V': /* e.g. "full", "expired", etc. */
687                     str=args->validity_string;
688                     break;
689                   }
690
691                 if(str && idx+strlen(str)<maxlen)
692                   {
693                     strcpy(&ret[idx],str);
694                     idx+=strlen(str);
695                     done=1;
696                   }
697               }
698               break;
699
700             case '%':
701               if(idx+1<maxlen)
702                 {
703                   ret[idx++]='%';
704                   ret[idx]='\0';
705                   done=1;
706                 }
707               break;
708
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)
716                 {
717                   ret[idx++]='%';
718                   ret[idx++]=*(ch+1);
719                   ret[idx]='\0';
720                   done=1;
721                 }
722               break;
723               }
724
725           if(done)
726             ch++;
727         }
728       else
729         {
730           if(idx+1<maxlen)
731             {
732               ret[idx++]=*ch;
733               ret[idx]='\0';
734               done=1;
735             }
736         }
737
738       if(done)
739         ch++;
740     }
741
742   return ret;
743
744  fail:
745   xfree(ret);
746   return NULL;
747 }
748
749 void
750 deprecated_warning(const char *configname,unsigned int configlineno,
751                    const char *option,const char *repl1,const char *repl2)
752 {
753   if(configname)
754     {
755       if(strncmp("--",option,2)==0)
756         option+=2;
757
758       if(strncmp("--",repl1,2)==0)
759         repl1+=2;
760
761       log_info(_("%s:%d: deprecated option \"%s\"\n"),
762                configname,configlineno,option);
763     }
764   else
765     log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
766
767   log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
768 }
769
770
771 void
772 deprecated_command (const char *name)
773 {
774   log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
775            name);
776 }
777
778
779 void
780 obsolete_option (const char *configname, unsigned int configlineno, 
781                  const char *name)
782 {
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);
789 }
790
791
792 /*
793  * Wrapper around gcry_cipher_map_name to provide a fallback using the
794  * "Sn" syntax as used by the preference strings.
795  */
796 int 
797 string_to_cipher_algo (const char *string) 
798
799   int val;
800
801   val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
802   if (!val && string && (string[0]=='S' || string[0]=='s'))
803     {
804       char *endptr;
805
806       string++;
807       val = strtol (string, &endptr, 10);
808       if (!*string || *endptr || openpgp_cipher_test_algo (val))
809         val = 0;
810     }
811
812   return val;
813 }
814
815 /*
816  * Wrapper around gcry_md_map_name to provide a fallback using the
817  * "Hn" syntax as used by the preference strings.
818  */
819 int 
820 string_to_digest_algo (const char *string) 
821
822   int val;
823
824   val = gcry_md_map_name (string);
825   if (!val && string && (string[0]=='H' || string[0]=='h'))
826     {
827       char *endptr;
828
829       string++;
830       val = strtol (string, &endptr, 10);
831       if (!*string || *endptr || openpgp_md_test_algo (val))
832         val = 0;
833     }
834
835   return val;
836 }
837
838
839
840 const char *
841 compress_algo_to_string(int algo)
842 {
843   const char *s=NULL;
844
845   switch(algo)
846     {
847     case COMPRESS_ALGO_NONE:
848       s=_("Uncompressed");
849       break;
850
851     case COMPRESS_ALGO_ZIP:
852       s="ZIP";
853       break;
854
855     case COMPRESS_ALGO_ZLIB:
856       s="ZLIB";
857       break;
858
859 #ifdef HAVE_BZIP2
860     case COMPRESS_ALGO_BZIP2:
861       s="BZIP2";
862       break;
863 #endif
864     }
865
866   return s;
867 }
868
869 int
870 string_to_compress_algo(const char *string)
871 {
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;
899 }
900
901 int
902 check_compress_algo(int algo)
903 {
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
911
912   return G10ERR_COMPR_ALGO;
913 }
914
915 int
916 default_cipher_algo(void)
917 {
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;
924 }
925
926 /* There is no default_digest_algo function, but see
927    sign.c:hash_for() */
928
929 int
930 default_compress_algo(void)
931 {
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;
938 }
939
940 const char *
941 compliance_option_string(void)
942 {
943   char *ver="???";
944
945   switch(opt.compliance)
946     {
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";
955     }
956
957   return ver;
958 }
959
960 void
961 compliance_failure(void)
962 {
963   char *ver="???";
964
965   switch(opt.compliance)
966     {
967     case CO_GNUPG:
968       ver="GnuPG";
969       break;
970
971     case CO_RFC4880:
972       ver="OpenPGP";
973       break;
974
975     case CO_RFC2440:
976       ver="OpenPGP (older)";
977       break;
978
979     case CO_RFC1991:
980       ver="old PGP";
981       break;
982
983     case CO_PGP2:
984       ver="PGP 2.x";
985       break;
986
987     case CO_PGP6:
988       ver="PGP 6.x";
989       break;
990
991     case CO_PGP7:
992       ver="PGP 7.x";
993       break;
994
995     case CO_PGP8:
996       ver="PGP 8.x";
997       break;
998     }
999
1000   log_info(_("this message may not be usable by %s\n"),ver);
1001   opt.compliance=CO_GNUPG;
1002 }
1003
1004 /* Break a string into successive option pieces.  Accepts single word
1005    options and key=value argument options. */
1006 char *
1007 optsep(char **stringp)
1008 {
1009   char *tok,*end;
1010
1011   tok=*stringp;
1012   if(tok)
1013     {
1014       end=strpbrk(tok," ,=");
1015       if(end)
1016         {
1017           int sawequals=0;
1018           char *ptr=end;
1019
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. */
1023
1024           while(*ptr)
1025             {
1026               if(*ptr=='=')
1027                 sawequals=1;
1028               else if(*ptr!=' ')
1029                 break;
1030               ptr++;
1031             }
1032
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)
1036             {
1037               /* Is it a quoted argument? */
1038               if(*ptr=='"')
1039                 {
1040                   ptr++;
1041                   end=strchr(ptr,'"');
1042                   if(end)
1043                     end++;
1044                 }
1045               else
1046                 end=strpbrk(ptr," ,");
1047             }
1048
1049           if(end && *end)
1050             {
1051               *end='\0';
1052               *stringp=end+1;
1053             }
1054           else
1055             *stringp=NULL;
1056         }
1057       else
1058         *stringp=NULL;
1059     }
1060
1061   return tok;
1062 }
1063
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)
1069 {
1070   char *equals,*arg=NULL;
1071
1072   equals=strchr(string,'=');
1073   if(equals)
1074     {
1075       char *quote,*space;
1076
1077       *equals='\0';
1078       arg=equals+1;
1079
1080       /* Quoted arg? */
1081       quote=strchr(arg,'"');
1082       if(quote)
1083         {
1084           arg=quote+1;
1085
1086           quote=strchr(arg,'"');
1087           if(quote)
1088             *quote='\0';
1089         }
1090       else
1091         {
1092           size_t spaces;
1093
1094           /* Trim leading spaces off of the arg */
1095           spaces=strspn(arg," ");
1096           arg+=spaces;
1097         }
1098
1099       /* Trim tailing spaces off of the tag */
1100       space=strchr(string,' ');
1101       if(space)
1102         *space='\0';
1103     }
1104
1105   return arg;
1106 }
1107
1108 /* Return the length of the initial token, leaving off any
1109    argument. */
1110 static size_t
1111 optlen(const char *s)
1112 {
1113   char *end=strpbrk(s," =");
1114
1115   if(end)
1116     return end-s;
1117   else
1118     return strlen(s);
1119 }
1120
1121 int
1122 parse_options(char *str,unsigned int *options,
1123               struct parse_options *opts,int noisy)
1124 {
1125   char *tok;
1126
1127   if (str && !strcmp (str, "help"))
1128     {
1129       int i,maxlen=0;
1130
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);
1136
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));
1141
1142       g10_exit(0);
1143     }
1144
1145   while((tok=optsep(&str)))
1146     {
1147       int i,rev=0;
1148       char *otok=tok;
1149
1150       if(tok[0]=='\0')
1151         continue;
1152
1153       if(ascii_strncasecmp("no-",tok,3)==0)
1154         {
1155           rev=1;
1156           tok+=3;
1157         }
1158
1159       for(i=0;opts[i].name;i++)
1160         {
1161           size_t toklen=optlen(tok);
1162
1163           if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1164             {
1165               /* We have a match, but it might be incomplete */
1166               if(toklen!=strlen(opts[i].name))
1167                 {
1168                   int j;
1169
1170                   for(j=i+1;opts[j].name;j++)
1171                     {
1172                       if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1173                         {
1174                           if(noisy)
1175                             log_info(_("ambiguous option `%s'\n"),otok);
1176                           return 0;
1177                         }
1178                     }
1179                 }
1180
1181               if(rev)
1182                 {
1183                   *options&=~opts[i].bit;
1184                   if(opts[i].value)
1185                     *opts[i].value=NULL;
1186                 }
1187               else
1188                 {
1189                   *options|=opts[i].bit;
1190                   if(opts[i].value)
1191                     *opts[i].value=argsplit(tok);
1192                 }
1193               break;
1194             }
1195         }
1196
1197       if(!opts[i].name)
1198         {
1199           if(noisy)
1200             log_info(_("unknown option `%s'\n"),otok);
1201           return 0;
1202         }
1203     }
1204
1205   return 1;
1206 }
1207
1208
1209 /* Check whether the string has characters not valid in an RFC-822
1210    address.  To cope with OpenPGP we ignore 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.  */
1219 int
1220 has_invalid_email_chars (const char *s)
1221 {
1222   int at_seen=0;
1223   const char *valid_chars=
1224     "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1225
1226   for ( ; *s; s++ ) 
1227     {
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;
1236     }
1237   return 0;
1238 }
1239
1240
1241 /* Check whether NAME represents a valid mailbox according to
1242    RFC822. Returns true if so. */
1243 int
1244 is_valid_mailbox (const char *name)
1245 {
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, "..") );
1254 }
1255
1256
1257 /* Similar to access(2), but uses PATH to find the file. */
1258 int
1259 path_access(const char *file,int mode)
1260 {
1261   char *envpath;
1262   int ret=-1;
1263
1264   envpath=getenv("PATH");
1265
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
1274      )
1275     return access(file,mode);
1276   else
1277     {
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);
1281
1282       split=path;
1283
1284       while((item=strsep(&split,PATHSEP_S)))
1285         {
1286           strcpy(buffer,item);
1287           strcat(buffer,"/");
1288           strcat(buffer,file);
1289           ret=access(buffer,mode);
1290           if(ret==0)
1291             break;
1292         }
1293
1294       xfree(path);
1295       xfree(buffer);
1296     }
1297
1298   return ret;
1299 }
1300
1301
1302 \f
1303 /* Temporary helper. */
1304 int
1305 pubkey_get_npkey( int algo )
1306 {
1307   size_t n;
1308
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;
1314 }
1315
1316 /* Temporary helper. */
1317 int
1318 pubkey_get_nskey( int algo )
1319 {
1320   size_t n;
1321
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;
1327 }
1328
1329 /* Temporary helper. */
1330 int
1331 pubkey_get_nsig( int algo )
1332 {
1333   size_t n;
1334
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;
1340 }
1341
1342 /* Temporary helper. */
1343 int
1344 pubkey_get_nenc( int algo )
1345 {
1346   size_t n;
1347   
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;
1353 }
1354
1355
1356 /* Temporary helper. */
1357 unsigned int
1358 pubkey_nbits( int algo, gcry_mpi_t *key )
1359 {
1360     int rc, nbits;
1361     gcry_sexp_t sexp;
1362
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] );
1367     }
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] );
1372     }
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] );
1377     }
1378     else
1379         return 0;
1380
1381     if ( rc )
1382         BUG ();
1383
1384     nbits = gcry_pk_get_nbits( sexp );
1385     gcry_sexp_release( sexp );
1386     return nbits;
1387 }
1388
1389
1390
1391 /* FIXME: Use gcry_mpi_print directly. */
1392 int
1393 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
1394 {
1395     int n=0;
1396
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);
1403     }
1404     else {
1405         unsigned char *buffer;
1406
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 );
1412     }
1413     return n;
1414 }
1415