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