Imported Upstream version 2.0.27
[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 #ifdef HAVE_WINSOCK2_H
44 # include <winsock2.h>
45 #endif
46 #include <windows.h>
47 #include <shlobj.h>
48 #ifndef CSIDL_APPDATA
49 #define CSIDL_APPDATA 0x001a
50 #endif
51 #ifndef CSIDL_LOCAL_APPDATA
52 #define CSIDL_LOCAL_APPDATA 0x001c
53 #endif
54 #ifndef CSIDL_FLAG_CREATE
55 #define CSIDL_FLAG_CREATE 0x8000
56 #endif
57 #endif /*HAVE_W32_SYSTEM*/
58
59 #include "gpg.h"
60 #ifdef HAVE_W32_SYSTEM
61 # include "status.h"
62 #endif /*HAVE_W32_SYSTEM*/
63 #include "util.h"
64 #include "main.h"
65 #include "photoid.h"
66 #include "options.h"
67 #include "call-agent.h"
68 #include "i18n.h"
69
70
71 static int
72 string_count_chr (const char *string, int c)
73 {
74   int count;
75
76   for (count=0; *string; string++ )
77     if ( *string == c )
78       count++;
79   return count;
80 }
81
82
83
84 #ifdef ENABLE_SELINUX_HACKS
85 /* A object and a global variable to keep track of files marked as
86    secured. */
87 struct secured_file_item
88 {
89   struct secured_file_item *next;
90   ino_t ino;
91   dev_t dev;
92 };
93 static struct secured_file_item *secured_files;
94 #endif /*ENABLE_SELINUX_HACKS*/
95
96
97
98
99 /* For the sake of SELinux we want to restrict access through gpg to
100    certain files we keep under our own control.  This function
101    registers such a file and is_secured_file may then be used to
102    check whether a file has ben registered as secured. */
103 void
104 register_secured_file (const char *fname)
105 {
106 #ifdef ENABLE_SELINUX_HACKS
107   struct stat buf;
108   struct secured_file_item *sf;
109
110   /* Note that we stop immediatley if something goes wrong here. */
111   if (stat (fname, &buf))
112     log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname,
113                "register_secured_file", strerror (errno));
114 /*   log_debug ("registering `%s' i=%lu.%lu\n", fname, */
115 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
116   for (sf=secured_files; sf; sf = sf->next)
117     {
118       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
119         return; /* Already registered.  */
120     }
121
122   sf = xmalloc (sizeof *sf);
123   sf->ino = buf.st_ino;
124   sf->dev = buf.st_dev;
125   sf->next = secured_files;
126   secured_files = sf;
127 #else /*!ENABLE_SELINUX_HACKS*/
128   (void)fname;
129 #endif /*!ENABLE_SELINUX_HACKS*/
130 }
131
132 /* Remove a file registered as secure. */
133 void
134 unregister_secured_file (const char *fname)
135 {
136 #ifdef ENABLE_SELINUX_HACKS
137   struct stat buf;
138   struct secured_file_item *sf, *sfprev;
139
140   if (stat (fname, &buf))
141     {
142       log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
143                  "unregister_secured_file", strerror (errno));
144       return;
145     }
146 /*   log_debug ("unregistering `%s' i=%lu.%lu\n", fname,  */
147 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
148   for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
149     {
150       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
151         {
152           if (sfprev)
153             sfprev->next = sf->next;
154           else
155             secured_files = sf->next;
156           xfree (sf);
157           return;
158         }
159     }
160 #else /*!ENABLE_SELINUX_HACKS*/
161   (void)fname;
162 #endif /*!ENABLE_SELINUX_HACKS*/
163 }
164
165 /* Return true if FD is corresponds to a secured file.  Using -1 for
166    FS is allowed and will return false. */
167 int
168 is_secured_file (int fd)
169 {
170 #ifdef ENABLE_SELINUX_HACKS
171   struct stat buf;
172   struct secured_file_item *sf;
173
174   if (fd == -1)
175     return 0; /* No file descriptor so it can't be secured either.  */
176
177   /* Note that we print out a error here and claim that a file is
178      secure if something went wrong. */
179   if (fstat (fd, &buf))
180     {
181       log_error (_("fstat(%d) failed in %s: %s\n"), fd,
182                  "is_secured_file", strerror (errno));
183       return 1;
184     }
185 /*   log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
186 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
187   for (sf=secured_files; sf; sf = sf->next)
188     {
189       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
190         return 1; /* Yes.  */
191     }
192 #else /*!ENABLE_SELINUX_HACKS*/
193   (void)fd;
194 #endif /*!ENABLE_SELINUX_HACKS*/
195   return 0; /* No. */
196 }
197
198 /* Return true if FNAME is corresponds to a secured file.  Using NULL,
199    "" or "-" for FS is allowed and will return false. This function is
200    used before creating a file, thus it won't fail if the file does
201    not exist. */
202 int
203 is_secured_filename (const char *fname)
204 {
205 #ifdef ENABLE_SELINUX_HACKS
206   struct stat buf;
207   struct secured_file_item *sf;
208
209   if (iobuf_is_pipe_filename (fname) || !*fname)
210     return 0;
211
212   /* Note that we print out a error here and claim that a file is
213      secure if something went wrong. */
214   if (stat (fname, &buf))
215     {
216       if (errno == ENOENT || errno == EPERM || errno == EACCES)
217         return 0;
218       log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
219                  "is_secured_filename", strerror (errno));
220       return 1;
221     }
222 /*   log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
223 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
224   for (sf=secured_files; sf; sf = sf->next)
225     {
226       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
227         return 1; /* Yes.  */
228     }
229 #else /*!ENABLE_SELINUX_HACKS*/
230   (void)fname;
231 #endif /*!ENABLE_SELINUX_HACKS*/
232   return 0; /* No. */
233 }
234
235
236
237 u16
238 checksum_u16( unsigned n )
239 {
240     u16 a;
241
242     a  = (n >> 8) & 0xff;
243     a += n & 0xff;
244     return a;
245 }
246
247
248 u16
249 checksum( byte *p, unsigned n )
250 {
251     u16 a;
252
253     for(a=0; n; n-- )
254         a += *p++;
255     return a;
256 }
257
258 u16
259 checksum_mpi (gcry_mpi_t a)
260 {
261   u16 csum;
262   byte *buffer;
263   size_t nbytes;
264
265   if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
266     BUG ();
267   /* Fixme: For numbers not in secure memory we should use a stack
268    * based buffer and only allocate a larger one if mpi_print returns
269    * an error. */
270   buffer = (gcry_is_secure(a)?
271             gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
272   if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
273     BUG ();
274   csum = checksum (buffer, nbytes);
275   xfree (buffer);
276   return csum;
277 }
278
279 void
280 print_pubkey_algo_note( int algo )
281 {
282   if(algo >= 100 && algo <= 110)
283     {
284       static int warn=0;
285       if(!warn)
286         {
287           warn=1;
288           log_info (_("WARNING: using experimental public key algorithm %s\n"),
289                     openpgp_pk_algo_name (algo));
290         }
291     }
292   else if (algo == 20)
293     {
294       log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
295     }
296 }
297
298 void
299 print_cipher_algo_note( int algo )
300 {
301   if(algo >= 100 && algo <= 110)
302     {
303       static int warn=0;
304       if(!warn)
305         {
306           warn=1;
307           log_info (_("WARNING: using experimental cipher algorithm %s\n"),
308                     openpgp_cipher_algo_name (algo));
309         }
310     }
311 }
312
313 void
314 print_digest_algo_note( int algo )
315 {
316   if(algo >= 100 && algo <= 110)
317     {
318       static int warn=0;
319       if(!warn)
320         {
321           warn=1;
322           log_info (_("WARNING: using experimental digest algorithm %s\n"),
323                     gcry_md_algo_name (algo));
324         }
325     }
326   else if(algo==DIGEST_ALGO_MD5)
327     log_info (_("WARNING: digest algorithm %s is deprecated\n"),
328               gcry_md_algo_name (algo));
329 }
330
331
332 void
333 print_md5_rejected_note (void)
334 {
335   static int shown;
336
337   if (!shown)
338     {
339       fflush (stdout);
340       log_info
341         (_("Note: signatures using the %s algorithm are rejected\n"),
342          "MD5");
343       shown = 1;
344     }
345 }
346
347
348 /* Map OpenPGP algo numbers to those used by Libgcrypt.  We need to do
349    this for algorithms we implemented in Libgcrypt after they become
350    part of OpenPGP.  */
351 int
352 map_cipher_openpgp_to_gcry (int algo)
353 {
354   switch (algo)
355     {
356     case CIPHER_ALGO_CAMELLIA128: return 310;
357     case CIPHER_ALGO_CAMELLIA192: return 311;
358     case CIPHER_ALGO_CAMELLIA256: return 312;
359     default: return algo;
360     }
361 }
362
363 /* The inverse fucntion of above.  */
364 static int
365 map_cipher_gcry_to_openpgp (int algo)
366 {
367   switch (algo)
368     {
369     case 310: return CIPHER_ALGO_CAMELLIA128;
370     case 311: return CIPHER_ALGO_CAMELLIA192;
371     case 312: return CIPHER_ALGO_CAMELLIA256;
372     default: return algo;
373     }
374 }
375
376
377 /* Return the block length of an OpenPGP cipher algorithm.  */
378 int
379 openpgp_cipher_blocklen (int algo)
380 {
381   /* We use the numbers from OpenPGP to be sure that we get the right
382      block length.  This is so that the packet parsing code works even
383      for unknown algorithms (for which we assume 8 due to tradition).
384
385      NOTE: If you change the the returned blocklen above 16, check
386      the callers because they may use a fixed size buffer of that
387      size. */
388   switch (algo)
389     {
390     case 7: case 8: case 9: /* AES */
391     case 10: /* Twofish */
392     case 11: case 12: case 13: /* Camellia */
393       return 16;
394
395     default:
396       return 8;
397     }
398 }
399
400 /****************
401  * Wrapper around the libgcrypt function with additonal checks on
402  * the OpenPGP contraints for the algo ID.
403  */
404 int
405 openpgp_cipher_test_algo( int algo )
406 {
407   /* (5 and 6 are marked reserved by rfc4880.)  */
408   if ( algo < 0 || algo > 110 || algo == 5 || algo == 6 )
409     return gpg_error (GPG_ERR_CIPHER_ALGO);
410
411   return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
412 }
413
414 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
415    string representation of the algorithm name.  For unknown algorithm
416    IDs this function returns "?".  */
417 const char *
418 openpgp_cipher_algo_name (int algo)
419 {
420   return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
421 }
422
423
424 /* Map OpenPGP public key algorithm numbers to those used by
425    Libgcrypt.  */
426 int
427 map_pk_openpgp_to_gcry (int algo)
428 {
429   switch (algo)
430     {
431     case PUBKEY_ALGO_ECDSA:     return 301 /*GCRY_PK_ECDSA*/;
432     case PUBKEY_ALGO_ECDH:      return 302 /*GCRY_PK_ECDH*/;
433     case PUBKEY_ALGO_ELGAMAL_E: return GCRY_PK_ELG;
434     default: return algo;
435     }
436 }
437
438
439 int
440 openpgp_pk_test_algo( int algo )
441 {
442   /* ECC is not yet supported even if supported by Libgcrypt.  */
443   if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
444     return gpg_error (GPG_ERR_PUBKEY_ALGO);
445
446   /* Dont't allow type 20 keys unless in rfc2440 mode.  */
447   if (!RFC2440 && algo == 20)
448     return gpg_error (GPG_ERR_PUBKEY_ALGO);
449
450   if (algo == PUBKEY_ALGO_ELGAMAL_E)
451     algo = GCRY_PK_ELG;
452
453   if (algo < 0 || algo > 110)
454     return gpg_error (GPG_ERR_PUBKEY_ALGO);
455   return gcry_pk_test_algo (map_pk_openpgp_to_gcry (algo));
456 }
457
458 int
459 openpgp_pk_test_algo2( int algo, unsigned int use )
460 {
461   size_t use_buf = use;
462
463   /* ECC is not yet supported even if supported by Libgcrypt.  */
464   if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
465     return gpg_error (GPG_ERR_PUBKEY_ALGO);
466
467   /* Dont't allow type 20 keys unless in rfc2440 mode.  */
468   if (!RFC2440 && algo == 20)
469     return gpg_error (GPG_ERR_PUBKEY_ALGO);
470
471   if (algo == PUBKEY_ALGO_ELGAMAL_E)
472     algo = GCRY_PK_ELG;
473
474   if (algo < 0 || algo > 110)
475     return gpg_error (GPG_ERR_PUBKEY_ALGO);
476
477   return gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
478                             GCRYCTL_TEST_ALGO, NULL, &use_buf);
479 }
480
481 int
482 openpgp_pk_algo_usage ( int algo )
483 {
484     int use = 0;
485
486     /* They are hardwired in gpg 1.0. */
487     switch ( algo ) {
488       case PUBKEY_ALGO_RSA:
489           use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
490                  | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
491           break;
492       case PUBKEY_ALGO_RSA_E:
493           use = PUBKEY_USAGE_ENC;
494           break;
495       case PUBKEY_ALGO_RSA_S:
496           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
497           break;
498       case PUBKEY_ALGO_ELGAMAL:
499           if (RFC2440)
500              use = PUBKEY_USAGE_ENC;
501           break;
502       case PUBKEY_ALGO_ELGAMAL_E:
503           use = PUBKEY_USAGE_ENC;
504           break;
505       case PUBKEY_ALGO_DSA:
506           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
507           break;
508       case PUBKEY_ALGO_ECDH:
509           use = PUBKEY_USAGE_ENC;
510           break;
511       case PUBKEY_ALGO_ECDSA:
512           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
513           break;
514       default:
515           break;
516     }
517     return use;
518 }
519
520
521 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
522    string representation of the algorithm name.  For unknown algorithm
523    IDs this function returns "?".  */
524 const char *
525 openpgp_pk_algo_name (int algo)
526 {
527   return gcry_pk_algo_name (map_pk_openpgp_to_gcry (algo));
528 }
529
530
531 int
532 openpgp_md_test_algo( int algo )
533 {
534   /* Note: If the list of actual supported OpenPGP algorithms changes,
535      make sure that our hard coded values at
536      print_status_begin_signing() gets updated. */
537   /* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the
538      next revision of the standard.  */
539   if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7))
540     return gpg_error (GPG_ERR_DIGEST_ALGO);
541   return gcry_md_test_algo (algo);
542 }
543
544 #ifdef USE_IDEA
545 /* Special warning for the IDEA cipher */
546 void
547 idea_cipher_warn(int show)
548 {
549   static int warned=0;
550
551   if(!warned || show)
552     {
553       log_info(_("the IDEA cipher plugin is not present\n"));
554       log_info(_("please see %s for more information\n"),
555                "https://gnupg.org/faq/why-not-idea.html");
556       warned=1;
557     }
558 }
559 #endif
560
561
562 static unsigned long
563 get_signature_count (PKT_secret_key *sk)
564 {
565 #ifdef ENABLE_CARD_SUPPORT
566   if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
567     {
568       struct agent_card_info_s info;
569       if(agent_scd_getattr("SIG-COUNTER",&info)==0)
570         return info.sig_counter;
571     }
572 #endif
573
574   /* How to do this without a card? */
575
576   return 0;
577 }
578
579 /* Expand %-strings.  Returns a string which must be xfreed.  Returns
580    NULL if the string cannot be expanded (too large). */
581 char *
582 pct_expando(const char *string,struct expando_args *args)
583 {
584   const char *ch=string;
585   int idx=0,maxlen=0,done=0;
586   u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
587   char *ret=NULL;
588
589   if(args->pk)
590     keyid_from_pk(args->pk,pk_keyid);
591
592   if(args->sk)
593     keyid_from_sk(args->sk,sk_keyid);
594
595   /* This is used so that %k works in photoid command strings in
596      --list-secret-keys (which of course has a sk, but no pk). */
597   if(!args->pk && args->sk)
598     keyid_from_sk(args->sk,pk_keyid);
599
600   while(*ch!='\0')
601     {
602       if(!done)
603         {
604           /* 8192 is way bigger than we'll need here */
605           if(maxlen>=8192)
606             goto fail;
607
608           maxlen+=1024;
609           ret=xrealloc(ret,maxlen);
610         }
611
612       done=0;
613
614       if(*ch=='%')
615         {
616           switch(*(ch+1))
617             {
618             case 's': /* short key id */
619               if(idx+8<maxlen)
620                 {
621                   sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
622                   idx+=8;
623                   done=1;
624                 }
625               break;
626
627             case 'S': /* long key id */
628               if(idx+16<maxlen)
629                 {
630                   sprintf(&ret[idx],"%08lX%08lX",
631                           (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
632                   idx+=16;
633                   done=1;
634                 }
635               break;
636
637             case 'k': /* short key id */
638               if(idx+8<maxlen)
639                 {
640                   sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
641                   idx+=8;
642                   done=1;
643                 }
644               break;
645
646             case 'K': /* long key id */
647               if(idx+16<maxlen)
648                 {
649                   sprintf(&ret[idx],"%08lX%08lX",
650                           (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
651                   idx+=16;
652                   done=1;
653                 }
654               break;
655
656             case 'U': /* z-base-32 encoded user id hash. */
657               if (args->namehash)
658                 {
659                   char *tmp = zb32_encode (args->namehash, 8*20);
660                   if (tmp)
661                     {
662                       if (idx + strlen (tmp) < maxlen)
663                         {
664                           strcpy (ret+idx, tmp);
665                           idx += strlen (tmp);
666                         }
667                       xfree (tmp);
668                       done = 1;
669                     }
670                 }
671               break;
672
673             case 'c': /* signature count from card, if any. */
674               if(idx+10<maxlen)
675                 {
676                   sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
677                   idx+=strlen(&ret[idx]);
678                   done=1;
679                 }
680               break;
681
682             case 'p': /* primary pk fingerprint of a sk */
683             case 'f': /* pk fingerprint */
684             case 'g': /* sk fingerprint */
685               {
686                 byte array[MAX_FINGERPRINT_LEN];
687                 size_t len;
688                 int i;
689
690                 if((*(ch+1))=='p' && args->sk)
691                   {
692                     if(args->sk->is_primary)
693                       fingerprint_from_sk(args->sk,array,&len);
694                     else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
695                       {
696                         PKT_public_key *pk=
697                           xmalloc_clear(sizeof(PKT_public_key));
698
699                         if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
700                           fingerprint_from_pk(pk,array,&len);
701                         else
702                           memset(array,0,(len=MAX_FINGERPRINT_LEN));
703                         free_public_key(pk);
704                       }
705                     else
706                       memset(array,0,(len=MAX_FINGERPRINT_LEN));
707                   }
708                 else if((*(ch+1))=='f' && args->pk)
709                   fingerprint_from_pk(args->pk,array,&len);
710                 else if((*(ch+1))=='g' && args->sk)
711                   fingerprint_from_sk(args->sk,array,&len);
712                 else
713                   memset(array,0,(len=MAX_FINGERPRINT_LEN));
714
715                 if(idx+(len*2)<maxlen)
716                   {
717                     for(i=0;i<len;i++)
718                       {
719                         sprintf(&ret[idx],"%02X",array[i]);
720                         idx+=2;
721                       }
722                     done=1;
723                   }
724               }
725               break;
726
727             case 'v': /* validity letters */
728               if(args->validity_info && idx+1<maxlen)
729                 {
730                   ret[idx++]=args->validity_info;
731                   ret[idx]='\0';
732                   done=1;
733                 }
734               break;
735
736               /* The text string types */
737             case 't':
738             case 'T':
739             case 'V':
740               {
741                 const char *str=NULL;
742
743                 switch(*(ch+1))
744                   {
745                   case 't': /* e.g. "jpg" */
746                     str=image_type_to_string(args->imagetype,0);
747                     break;
748
749                   case 'T': /* e.g. "image/jpeg" */
750                     str=image_type_to_string(args->imagetype,2);
751                     break;
752
753                   case 'V': /* e.g. "full", "expired", etc. */
754                     str=args->validity_string;
755                     break;
756                   }
757
758                 if(str && idx+strlen(str)<maxlen)
759                   {
760                     strcpy(&ret[idx],str);
761                     idx+=strlen(str);
762                     done=1;
763                   }
764               }
765               break;
766
767             case '%':
768               if(idx+1<maxlen)
769                 {
770                   ret[idx++]='%';
771                   ret[idx]='\0';
772                   done=1;
773                 }
774               break;
775
776               /* Any unknown %-keys (like %i, %o, %I, and %O) are
777                  passed through for later expansion.  Note this also
778                  handles the case where the last character in the
779                  string is a '%' - the terminating \0 will end up here
780                  and properly terminate the string. */
781             default:
782               if(idx+2<maxlen)
783                 {
784                   ret[idx++]='%';
785                   ret[idx++]=*(ch+1);
786                   ret[idx]='\0';
787                   done=1;
788                 }
789               break;
790               }
791
792           if(done)
793             ch++;
794         }
795       else
796         {
797           if(idx+1<maxlen)
798             {
799               ret[idx++]=*ch;
800               ret[idx]='\0';
801               done=1;
802             }
803         }
804
805       if(done)
806         ch++;
807     }
808
809   return ret;
810
811  fail:
812   xfree(ret);
813   return NULL;
814 }
815
816 void
817 deprecated_warning(const char *configname,unsigned int configlineno,
818                    const char *option,const char *repl1,const char *repl2)
819 {
820   if(configname)
821     {
822       if(strncmp("--",option,2)==0)
823         option+=2;
824
825       if(strncmp("--",repl1,2)==0)
826         repl1+=2;
827
828       log_info(_("%s:%d: deprecated option \"%s\"\n"),
829                configname,configlineno,option);
830     }
831   else
832     log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
833
834   log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
835 }
836
837
838 void
839 deprecated_command (const char *name)
840 {
841   log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
842            name);
843 }
844
845
846 void
847 obsolete_option (const char *configname, unsigned int configlineno,
848                  const char *name)
849 {
850   if(configname)
851     log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
852               configname, configlineno, name);
853   else
854     log_info (_("WARNING: \"%s\" is an obsolete option - it has no effect\n"),
855               name);
856 }
857
858
859 void
860 obsolete_scdaemon_option (const char *configname, unsigned int configlineno,
861                           const char *name)
862 {
863   if (configname)
864     log_info (_("%s:%u: \"%s%s\" is obsolete in this file"
865                 " - it only has effect in %s\n"),
866               configname, configlineno, name, "--", "scdaemon.conf");
867   else
868     log_info (_("WARNING: \"%s%s\" is an obsolete option"
869                 " - it has no effect except on %s\n"), "--", name, "scdaemon");
870 }
871
872
873 /*
874  * Wrapper around gcry_cipher_map_name to provide a fallback using the
875  * "Sn" syntax as used by the preference strings.
876  */
877 int
878 string_to_cipher_algo (const char *string)
879 {
880   int val;
881
882   val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
883   if (!val && string && (string[0]=='S' || string[0]=='s'))
884     {
885       char *endptr;
886
887       string++;
888       val = strtol (string, &endptr, 10);
889       if (!*string || *endptr || openpgp_cipher_test_algo (val))
890         val = 0;
891     }
892
893   return val;
894 }
895
896 /*
897  * Wrapper around gcry_md_map_name to provide a fallback using the
898  * "Hn" syntax as used by the preference strings.
899  */
900 int
901 string_to_digest_algo (const char *string)
902 {
903   int val;
904
905   val = gcry_md_map_name (string);
906   if (!val && string && (string[0]=='H' || string[0]=='h'))
907     {
908       char *endptr;
909
910       string++;
911       val = strtol (string, &endptr, 10);
912       if (!*string || *endptr || openpgp_md_test_algo (val))
913         val = 0;
914     }
915
916   return val;
917 }
918
919
920
921 const char *
922 compress_algo_to_string(int algo)
923 {
924   const char *s=NULL;
925
926   switch(algo)
927     {
928     case COMPRESS_ALGO_NONE:
929       s=_("Uncompressed");
930       break;
931
932     case COMPRESS_ALGO_ZIP:
933       s="ZIP";
934       break;
935
936     case COMPRESS_ALGO_ZLIB:
937       s="ZLIB";
938       break;
939
940 #ifdef HAVE_BZIP2
941     case COMPRESS_ALGO_BZIP2:
942       s="BZIP2";
943       break;
944 #endif
945     }
946
947   return s;
948 }
949
950 int
951 string_to_compress_algo(const char *string)
952 {
953   /* TRANSLATORS: See doc/TRANSLATE about this string. */
954   if(match_multistr(_("uncompressed|none"),string))
955     return 0;
956   else if(ascii_strcasecmp(string,"uncompressed")==0)
957     return 0;
958   else if(ascii_strcasecmp(string,"none")==0)
959     return 0;
960   else if(ascii_strcasecmp(string,"zip")==0)
961     return 1;
962   else if(ascii_strcasecmp(string,"zlib")==0)
963     return 2;
964 #ifdef HAVE_BZIP2
965   else if(ascii_strcasecmp(string,"bzip2")==0)
966     return 3;
967 #endif
968   else if(ascii_strcasecmp(string,"z0")==0)
969     return 0;
970   else if(ascii_strcasecmp(string,"z1")==0)
971     return 1;
972   else if(ascii_strcasecmp(string,"z2")==0)
973     return 2;
974 #ifdef HAVE_BZIP2
975   else if(ascii_strcasecmp(string,"z3")==0)
976     return 3;
977 #endif
978   else
979     return -1;
980 }
981
982 int
983 check_compress_algo(int algo)
984 {
985 #ifdef HAVE_BZIP2
986   if(algo>=0 && algo<=3)
987     return 0;
988 #else
989   if(algo>=0 && algo<=2)
990     return 0;
991 #endif
992
993   return G10ERR_COMPR_ALGO;
994 }
995
996 int
997 default_cipher_algo(void)
998 {
999   if(opt.def_cipher_algo)
1000     return opt.def_cipher_algo;
1001   else if(opt.personal_cipher_prefs)
1002     return opt.personal_cipher_prefs[0].value;
1003   else
1004     return opt.s2k_cipher_algo;
1005 }
1006
1007 /* There is no default_digest_algo function, but see
1008    sign.c:hash_for() */
1009
1010 int
1011 default_compress_algo(void)
1012 {
1013   if(opt.compress_algo!=-1)
1014     return opt.compress_algo;
1015   else if(opt.personal_compress_prefs)
1016     return opt.personal_compress_prefs[0].value;
1017   else
1018     return DEFAULT_COMPRESS_ALGO;
1019 }
1020
1021 const char *
1022 compliance_option_string(void)
1023 {
1024   char *ver="???";
1025
1026   switch(opt.compliance)
1027     {
1028     case CO_GNUPG:   return "--gnupg";
1029     case CO_RFC4880: return "--openpgp";
1030     case CO_RFC2440: return "--rfc2440";
1031     case CO_RFC1991: return "--rfc1991";
1032     case CO_PGP2:    return "--pgp2";
1033     case CO_PGP6:    return "--pgp6";
1034     case CO_PGP7:    return "--pgp7";
1035     case CO_PGP8:    return "--pgp8";
1036     }
1037
1038   return ver;
1039 }
1040
1041 void
1042 compliance_failure(void)
1043 {
1044   char *ver="???";
1045
1046   switch(opt.compliance)
1047     {
1048     case CO_GNUPG:
1049       ver="GnuPG";
1050       break;
1051
1052     case CO_RFC4880:
1053       ver="OpenPGP";
1054       break;
1055
1056     case CO_RFC2440:
1057       ver="OpenPGP (older)";
1058       break;
1059
1060     case CO_RFC1991:
1061       ver="old PGP";
1062       break;
1063
1064     case CO_PGP2:
1065       ver="PGP 2.x";
1066       break;
1067
1068     case CO_PGP6:
1069       ver="PGP 6.x";
1070       break;
1071
1072     case CO_PGP7:
1073       ver="PGP 7.x";
1074       break;
1075
1076     case CO_PGP8:
1077       ver="PGP 8.x";
1078       break;
1079     }
1080
1081   log_info(_("this message may not be usable by %s\n"),ver);
1082   opt.compliance=CO_GNUPG;
1083 }
1084
1085 /* Break a string into successive option pieces.  Accepts single word
1086    options and key=value argument options. */
1087 char *
1088 optsep(char **stringp)
1089 {
1090   char *tok,*end;
1091
1092   tok=*stringp;
1093   if(tok)
1094     {
1095       end=strpbrk(tok," ,=");
1096       if(end)
1097         {
1098           int sawequals=0;
1099           char *ptr=end;
1100
1101           /* what we need to do now is scan along starting with *end,
1102              If the next character we see (ignoring spaces) is an =
1103              sign, then there is an argument. */
1104
1105           while(*ptr)
1106             {
1107               if(*ptr=='=')
1108                 sawequals=1;
1109               else if(*ptr!=' ')
1110                 break;
1111               ptr++;
1112             }
1113
1114           /* There is an argument, so grab that too.  At this point,
1115              ptr points to the first character of the argument. */
1116           if(sawequals)
1117             {
1118               /* Is it a quoted argument? */
1119               if(*ptr=='"')
1120                 {
1121                   ptr++;
1122                   end=strchr(ptr,'"');
1123                   if(end)
1124                     end++;
1125                 }
1126               else
1127                 end=strpbrk(ptr," ,");
1128             }
1129
1130           if(end && *end)
1131             {
1132               *end='\0';
1133               *stringp=end+1;
1134             }
1135           else
1136             *stringp=NULL;
1137         }
1138       else
1139         *stringp=NULL;
1140     }
1141
1142   return tok;
1143 }
1144
1145 /* Breaks an option value into key and value.  Returns NULL if there
1146    is no value.  Note that "string" is modified to remove the =value
1147    part. */
1148 char *
1149 argsplit(char *string)
1150 {
1151   char *equals,*arg=NULL;
1152
1153   equals=strchr(string,'=');
1154   if(equals)
1155     {
1156       char *quote,*space;
1157
1158       *equals='\0';
1159       arg=equals+1;
1160
1161       /* Quoted arg? */
1162       quote=strchr(arg,'"');
1163       if(quote)
1164         {
1165           arg=quote+1;
1166
1167           quote=strchr(arg,'"');
1168           if(quote)
1169             *quote='\0';
1170         }
1171       else
1172         {
1173           size_t spaces;
1174
1175           /* Trim leading spaces off of the arg */
1176           spaces=strspn(arg," ");
1177           arg+=spaces;
1178         }
1179
1180       /* Trim tailing spaces off of the tag */
1181       space=strchr(string,' ');
1182       if(space)
1183         *space='\0';
1184     }
1185
1186   return arg;
1187 }
1188
1189 /* Return the length of the initial token, leaving off any
1190    argument. */
1191 static size_t
1192 optlen(const char *s)
1193 {
1194   char *end=strpbrk(s," =");
1195
1196   if(end)
1197     return end-s;
1198   else
1199     return strlen(s);
1200 }
1201
1202 int
1203 parse_options(char *str,unsigned int *options,
1204               struct parse_options *opts,int noisy)
1205 {
1206   char *tok;
1207
1208   if (str && !strcmp (str, "help"))
1209     {
1210       int i,maxlen=0;
1211
1212       /* Figure out the longest option name so we can line these up
1213          neatly. */
1214       for(i=0;opts[i].name;i++)
1215         if(opts[i].help && maxlen<strlen(opts[i].name))
1216           maxlen=strlen(opts[i].name);
1217
1218       for(i=0;opts[i].name;i++)
1219         if(opts[i].help)
1220           printf("%s%*s%s\n",opts[i].name,
1221                  maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1222
1223       g10_exit(0);
1224     }
1225
1226   while((tok=optsep(&str)))
1227     {
1228       int i,rev=0;
1229       char *otok=tok;
1230
1231       if(tok[0]=='\0')
1232         continue;
1233
1234       if(ascii_strncasecmp("no-",tok,3)==0)
1235         {
1236           rev=1;
1237           tok+=3;
1238         }
1239
1240       for(i=0;opts[i].name;i++)
1241         {
1242           size_t toklen=optlen(tok);
1243
1244           if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1245             {
1246               /* We have a match, but it might be incomplete */
1247               if(toklen!=strlen(opts[i].name))
1248                 {
1249                   int j;
1250
1251                   for(j=i+1;opts[j].name;j++)
1252                     {
1253                       if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1254                         {
1255                           if(noisy)
1256                             log_info(_("ambiguous option `%s'\n"),otok);
1257                           return 0;
1258                         }
1259                     }
1260                 }
1261
1262               if(rev)
1263                 {
1264                   *options&=~opts[i].bit;
1265                   if(opts[i].value)
1266                     *opts[i].value=NULL;
1267                 }
1268               else
1269                 {
1270                   *options|=opts[i].bit;
1271                   if(opts[i].value)
1272                     *opts[i].value=argsplit(tok);
1273                 }
1274               break;
1275             }
1276         }
1277
1278       if(!opts[i].name)
1279         {
1280           if(noisy)
1281             log_info(_("unknown option `%s'\n"),otok);
1282           return 0;
1283         }
1284     }
1285
1286   return 1;
1287 }
1288
1289
1290 /* Check whether the string has characters not valid in an RFC-822
1291    address.  To cope with OpenPGP we ignore non-ascii characters
1292    so that for example umlauts are legal in an email address.  An
1293    OpenPGP user ID must be utf-8 encoded but there is no strict
1294    requirement for RFC-822.  Thus to avoid IDNA encoding we put the
1295    address verbatim as utf-8 into the user ID under the assumption
1296    that mail programs handle IDNA at a lower level and take OpenPGP
1297    user IDs as utf-8.  Note that we can't do an utf-8 encoding
1298    checking here because in keygen.c this function is called with the
1299    native encoding and native to utf-8 encoding is only done  later.  */
1300 int
1301 has_invalid_email_chars (const char *s)
1302 {
1303   int at_seen=0;
1304   const char *valid_chars=
1305     "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1306
1307   for ( ; *s; s++ )
1308     {
1309       if ( (*s & 0x80) )
1310         continue; /* We only care about ASCII.  */
1311       if ( *s == '@' )
1312         at_seen=1;
1313       else if ( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1314         return 1;
1315       else if ( at_seen && !strchr( valid_chars, *s ) )
1316         return 1;
1317     }
1318   return 0;
1319 }
1320
1321
1322 /* Check whether NAME represents a valid mailbox according to
1323    RFC822. Returns true if so. */
1324 int
1325 is_valid_mailbox (const char *name)
1326 {
1327   return !( !name
1328             || !*name
1329             || has_invalid_email_chars (name)
1330             || string_count_chr (name,'@') != 1
1331             || *name == '@'
1332             || name[strlen(name)-1] == '@'
1333             || name[strlen(name)-1] == '.'
1334             || strstr (name, "..") );
1335 }
1336
1337
1338 /* Similar to access(2), but uses PATH to find the file. */
1339 int
1340 path_access(const char *file,int mode)
1341 {
1342   char *envpath;
1343   int ret=-1;
1344
1345   envpath=getenv("PATH");
1346
1347   if(!envpath
1348 #ifdef HAVE_DRIVE_LETTERS
1349      || (((file[0]>='A' && file[0]<='Z')
1350           || (file[0]>='a' && file[0]<='z'))
1351          && file[1]==':')
1352 #else
1353      || file[0]=='/'
1354 #endif
1355      )
1356     return access(file,mode);
1357   else
1358     {
1359       /* At least as large as, but most often larger than we need. */
1360       char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1361       char *split,*item,*path=xstrdup(envpath);
1362
1363       split=path;
1364
1365       while((item=strsep(&split,PATHSEP_S)))
1366         {
1367           strcpy(buffer,item);
1368           strcat(buffer,"/");
1369           strcat(buffer,file);
1370           ret=access(buffer,mode);
1371           if(ret==0)
1372             break;
1373         }
1374
1375       xfree(path);
1376       xfree(buffer);
1377     }
1378
1379   return ret;
1380 }
1381
1382
1383 \f
1384 /* Temporary helper. */
1385 int
1386 pubkey_get_npkey( int algo )
1387 {
1388   size_t n;
1389
1390   /* ECC is special in that domain parameters are given by an OID.  */
1391   if (algo == PUBKEY_ALGO_ECDSA)
1392     return 0; /* We don't support the key format.  */
1393   else if (algo == PUBKEY_ALGO_ECDH)
1394     return 0; /* We don't support the key format.  */
1395
1396   if (algo == GCRY_PK_ELG_E)
1397     algo = GCRY_PK_ELG;
1398   else if (algo == GCRY_PK_RSA_E || algo == GCRY_PK_RSA_S)
1399     algo = GCRY_PK_RSA;
1400
1401   if (gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
1402                          GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
1403     n = 0;
1404   return n;
1405 }
1406
1407 /* Temporary helper. */
1408 int
1409 pubkey_get_nskey( int algo )
1410 {
1411   size_t n;
1412
1413   /* ECC is special in that domain parameters are given by an OID.  */
1414   if (algo == PUBKEY_ALGO_ECDSA)
1415     return 0; /* We don't support the key format.  */
1416   else if (algo == PUBKEY_ALGO_ECDH)
1417     return 0; /* We don't support the key format.  */
1418
1419   if (algo == GCRY_PK_ELG_E)
1420     algo = GCRY_PK_ELG;
1421   else if (algo == GCRY_PK_RSA_E || algo == GCRY_PK_RSA_S)
1422     algo = GCRY_PK_RSA;
1423
1424   if (gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
1425                          GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
1426     n = 0;
1427   return n;
1428 }
1429
1430 /* Temporary helper. */
1431 int
1432 pubkey_get_nsig( int algo )
1433 {
1434   size_t n;
1435
1436   /* ECC is special.  */
1437   if (algo == PUBKEY_ALGO_ECDSA)
1438     return 0;  /* We don't support the key format.  */
1439   else if (algo == PUBKEY_ALGO_ECDH)
1440     return 0;
1441
1442   if (algo == GCRY_PK_ELG_E)
1443     algo = GCRY_PK_ELG;
1444   else if (algo == GCRY_PK_RSA_E || algo == GCRY_PK_RSA_S)
1445     algo = GCRY_PK_RSA;
1446
1447   if (gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
1448                          GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
1449     n = 0;
1450   return n;
1451 }
1452
1453 /* Temporary helper. */
1454 int
1455 pubkey_get_nenc( int algo )
1456 {
1457   size_t n;
1458
1459   /* ECC is special.  */
1460   if (algo == PUBKEY_ALGO_ECDSA)
1461     return 0;
1462   else if (algo == PUBKEY_ALGO_ECDH)
1463     return 0;  /* We don't support the key format.  */
1464
1465   if (algo == GCRY_PK_ELG_E)
1466     algo = GCRY_PK_ELG;
1467   else if (algo == GCRY_PK_RSA_E || algo == GCRY_PK_RSA_S)
1468     algo = GCRY_PK_RSA;
1469
1470   if (gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
1471                          GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
1472     n = 0;
1473   return n;
1474 }
1475
1476
1477 /* Temporary helper. */
1478 unsigned int
1479 pubkey_nbits( int algo, gcry_mpi_t *key )
1480 {
1481     int rc, nbits;
1482     gcry_sexp_t sexp;
1483
1484     if( algo == GCRY_PK_DSA ) {
1485         rc = gcry_sexp_build ( &sexp, NULL,
1486                               "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1487                                   key[0], key[1], key[2], key[3] );
1488     }
1489     else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
1490         rc = gcry_sexp_build ( &sexp, NULL,
1491                               "(public-key(elg(p%m)(g%m)(y%m)))",
1492                                   key[0], key[1], key[2] );
1493     }
1494     else if (algo == GCRY_PK_RSA
1495              || algo == GCRY_PK_RSA_S
1496              || algo == GCRY_PK_RSA_E ) {
1497         rc = gcry_sexp_build ( &sexp, NULL,
1498                               "(public-key(rsa(n%m)(e%m)))",
1499                                   key[0], key[1] );
1500     }
1501     else
1502         return 0;
1503
1504     if ( rc )
1505         BUG ();
1506
1507     nbits = gcry_pk_get_nbits( sexp );
1508     gcry_sexp_release( sexp );
1509     return nbits;
1510 }
1511
1512
1513
1514 /* FIXME: Use gcry_mpi_print directly. */
1515 int
1516 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
1517 {
1518     int n=0;
1519
1520     if( !a )
1521         return fprintf(fp, "[MPI_NULL]");
1522     if( !mode ) {
1523         unsigned int n1;
1524         n1 = gcry_mpi_get_nbits(a);
1525         n += fprintf(fp, "[%u bits]", n1);
1526     }
1527     else {
1528         unsigned char *buffer;
1529
1530         if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
1531           BUG ();
1532         fputs( buffer, fp );
1533         n += strlen(buffer);
1534         gcry_free( buffer );
1535     }
1536     return n;
1537 }
1538