2005-04-11 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / misc.c
blob7012a8a252d1496222f878b7f5711fd2235c3f68
1 /* misc.c - miscellaneous functions
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
3 * 2003 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
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 #include <assert.h>
29 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
30 #include <asm/sysinfo.h>
31 #include <asm/unistd.h>
32 #endif
33 #ifdef HAVE_SETRLIMIT
34 #include <time.h>
35 #include <sys/time.h>
36 #include <sys/resource.h>
37 #endif
39 #include "gpg.h"
40 #include "util.h"
41 #include "main.h"
42 #include "photoid.h"
43 #include "options.h"
44 #include "i18n.h"
46 #define MAX_EXTERN_MPI_BITS 16384
49 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
50 static int
51 setsysinfo(unsigned long op, void *buffer, unsigned long size,
52 int *start, void *arg, unsigned long flag)
54 return syscall(__NR_osf_setsysinfo, op, buffer, size, start, arg, flag);
57 void
58 trap_unaligned(void)
60 unsigned int buf[2];
62 buf[0] = SSIN_UACPROC;
63 buf[1] = UAC_SIGBUS | UAC_NOPRINT;
64 setsysinfo(SSI_NVPAIRS, buf, 1, 0, 0, 0);
66 #else
67 void
68 trap_unaligned(void)
69 { /* dummy */
71 #endif
74 int
75 disable_core_dumps()
77 #ifdef HAVE_DOSISH_SYSTEM
78 return 0;
79 #else
80 #ifdef HAVE_SETRLIMIT
81 struct rlimit limit;
83 limit.rlim_cur = 0;
84 limit.rlim_max = 0;
85 if( !setrlimit( RLIMIT_CORE, &limit ) )
86 return 0;
87 if( errno != EINVAL && errno != ENOSYS )
88 log_fatal(_("can't disable core dumps: %s\n"), strerror(errno) );
89 #endif
90 return 1;
91 #endif
96 u16
97 checksum_u16( unsigned n )
99 u16 a;
101 a = (n >> 8) & 0xff;
102 a += n & 0xff;
103 return a;
108 checksum( byte *p, unsigned n )
110 u16 a;
112 for(a=0; n; n-- )
113 a += *p++;
114 return a;
118 checksum_mpi( gcry_mpi_t a )
120 int rc;
121 u16 csum;
122 byte *buffer;
123 size_t nbytes;
125 rc = gcry_mpi_print( GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a );
126 if (rc)
127 BUG ();
128 /* fixme: for numbers not in secure memory we should use a stack
129 * based buffer and only allocate a larger one if mpi_print return
130 * an error */
131 buffer = gcry_is_secure(a)? gcry_xmalloc_secure(nbytes):gcry_xmalloc(nbytes);
132 rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a );
133 if (rc)
134 BUG ();
135 csum = checksum (buffer, nbytes );
136 xfree (buffer );
137 return csum;
141 buffer_to_u32( const byte *buffer )
143 unsigned long a;
144 a = *buffer << 24;
145 a |= buffer[1] << 16;
146 a |= buffer[2] << 8;
147 a |= buffer[3];
148 return a;
152 static void
153 no_exp_algo(void)
155 static int did_note = 0;
157 if( !did_note ) {
158 did_note = 1;
159 log_info(_("Experimental algorithms should not be used!\n"));
163 void
164 print_pubkey_algo_note( int algo )
166 if( algo >= 100 && algo <= 110 )
167 no_exp_algo();
170 void
171 print_cipher_algo_note( int algo )
173 if( algo >= 100 && algo <= 110 )
174 no_exp_algo();
175 else if( algo == CIPHER_ALGO_3DES
176 || algo == CIPHER_ALGO_CAST5
177 || algo == CIPHER_ALGO_BLOWFISH
178 || algo == CIPHER_ALGO_TWOFISH
179 || algo == CIPHER_ALGO_RIJNDAEL
180 || algo == CIPHER_ALGO_RIJNDAEL192
181 || algo == CIPHER_ALGO_RIJNDAEL256
184 else {
185 static int did_note = 0;
187 if( !did_note ) {
188 did_note = 1;
189 log_info(_("this cipher algorithm is deprecated; "
190 "please use a more standard one!\n"));
195 void
196 print_digest_algo_note( int algo )
198 if( algo >= 100 && algo <= 110 )
199 no_exp_algo();
203 /* Return a string which is used as a kind of process ID */
204 const byte *
205 get_session_marker( size_t *rlen )
207 static byte marker[SIZEOF_UNSIGNED_LONG*2];
208 static int initialized;
210 if ( !initialized ) {
211 volatile ulong aa, bb; /* we really want the uninitialized value */
212 ulong a, b;
214 initialized = 1;
215 /* also this marker is guessable it is not easy to use this
216 * for a faked control packet because an attacker does not
217 * have enough control about the time the verification does
218 * take place. Of course, we can add just more random but
219 * than we need the random generator even for verification
220 * tasks - which does not make sense. */
221 a = aa ^ (ulong)getpid();
222 b = bb ^ (ulong)time(NULL);
223 memcpy( marker, &a, SIZEOF_UNSIGNED_LONG );
224 memcpy( marker+SIZEOF_UNSIGNED_LONG, &b, SIZEOF_UNSIGNED_LONG );
226 *rlen = sizeof(marker);
227 return marker;
230 /****************
231 * Wrapper around the libgcrypt function with addional checks on
232 * openPGP contraints for the algo ID.
235 openpgp_cipher_test_algo( int algo )
237 if( algo < 0 || algo > 110 )
238 return GPG_ERR_CIPHER_ALGO;
239 return gcry_cipher_test_algo (algo);
243 openpgp_pk_test_algo( int algo, unsigned int usage_flags )
245 size_t value = usage_flags;
247 if (algo == GCRY_PK_ELG_E)
248 algo = GCRY_PK_ELG;
249 #ifdef __GNUC__
250 #warning need to handle the usage here?
251 #endif
252 if (algo < 0 || algo > 110)
253 return GPG_ERR_PUBKEY_ALGO;
254 return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &value);
257 int
258 openpgp_pk_algo_usage ( int algo )
260 int use = 0;
262 /* they are hardwired in gpg 1.0 */
263 switch ( algo ) {
264 case PUBKEY_ALGO_RSA:
265 use = PUBKEY_USAGE_SIG | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH;
266 break;
267 case PUBKEY_ALGO_RSA_E:
268 use = PUBKEY_USAGE_ENC;
269 break;
270 case PUBKEY_ALGO_RSA_S:
271 use = PUBKEY_USAGE_SIG;
272 break;
273 case PUBKEY_ALGO_ELGAMAL_E:
274 use = PUBKEY_USAGE_ENC;
275 break;
276 case PUBKEY_ALGO_DSA:
277 use = PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
278 break;
279 case PUBKEY_ALGO_ELGAMAL:
280 use = PUBKEY_USAGE_SIG | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH;
281 break;
282 default:
283 break;
285 return use;
289 openpgp_md_test_algo( int algo )
291 if( algo < 0 || algo > 110 )
292 return GPG_ERR_DIGEST_ALGO;
293 return gcry_md_test_algo (algo);
297 openpgp_md_map_name (const char *string)
299 int i = gcry_md_map_name (string);
301 if (!i && (string[0]=='H' || string[0]=='h'))
302 { /* Didn't find it, so try the Hx format */
303 long val;
304 char *endptr;
306 string++;
308 val=strtol(string,&endptr,10);
309 if (*string!='\0' && *endptr=='\0' && !openpgp_md_test_algo(val))
310 i = val;
312 return i < 0 || i > 110? 0 : i;
316 openpgp_cipher_map_name (const char *string)
318 int i = gcry_cipher_map_name (string);
320 if (!i && (string[0]=='S' || string[0]=='s'))
321 { /* Didn't find it, so try the Sx format */
322 long val;
323 char *endptr;
325 string++;
327 val=strtol(string,&endptr,10);
328 if (*string!='\0' && *endptr=='\0' && !openpgp_cipher_test_algo(val))
329 i = val;
331 return i < 0 || i > 110? 0 : i;
335 openpgp_pk_map_name (const char *string)
337 int i = gcry_pk_map_name (string);
338 return i < 0 || i > 110? 0 : i;
341 #ifdef USE_IDEA
342 /* Special warning for the IDEA cipher */
343 void
344 idea_cipher_warn(int show)
346 static int warned=0;
348 if(!warned || show)
350 log_info(_("the IDEA cipher plugin is not present\n"));
351 log_info(_("please see http://www.gnupg.org/why-not-idea.html "
352 "for more information\n"));
353 warned=1;
356 #endif
358 /* Expand %-strings. Returns a string which must be m_freed. Returns
359 NULL if the string cannot be expanded (too large). */
360 char *
361 pct_expando(const char *string,struct expando_args *args)
363 const char *ch=string;
364 int idx=0,maxlen=0,done=0;
365 u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
366 char *ret=NULL;
368 if(args->pk)
369 keyid_from_pk(args->pk,pk_keyid);
371 if(args->sk)
372 keyid_from_sk(args->sk,sk_keyid);
374 /* This is used so that %k works in photoid command strings in
375 --list-secret-keys (which of course has a sk, but no pk). */
376 if(!args->pk && args->sk)
377 keyid_from_sk(args->sk,pk_keyid);
379 while(*ch!='\0')
381 char *str=NULL;
383 if(!done)
385 /* 8192 is way bigger than we'll need here */
386 if(maxlen>=8192)
387 goto fail;
389 maxlen+=1024;
390 ret= xrealloc(ret,maxlen);
393 done=0;
395 if(*ch=='%')
397 switch(*(ch+1))
399 case 's': /* short key id */
400 if(idx+8<maxlen)
402 sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
403 idx+=8;
404 done=1;
406 break;
408 case 'S': /* long key id */
409 if(idx+16<maxlen)
411 sprintf(&ret[idx],"%08lX%08lX",
412 (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
413 idx+=16;
414 done=1;
416 break;
418 case 'k': /* short key id */
419 if(idx+8<maxlen)
421 sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
422 idx+=8;
423 done=1;
425 break;
427 case 'K': /* long key id */
428 if(idx+16<maxlen)
430 sprintf(&ret[idx],"%08lX%08lX",
431 (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
432 idx+=16;
433 done=1;
435 break;
437 case 'p': /* primary pk fingerprint of a sk */
438 case 'f': /* pk fingerprint */
439 case 'g': /* sk fingerprint */
441 byte array[MAX_FINGERPRINT_LEN];
442 size_t len;
443 int i;
445 if( ch[1]=='p' && args->sk)
447 if(args->sk->is_primary)
448 fingerprint_from_sk(args->sk,array,&len);
449 else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
451 PKT_public_key *pk= xcalloc(1, sizeof(PKT_public_key));
453 if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
454 fingerprint_from_pk(pk,array,&len);
455 else
456 memset(array,0,(len=MAX_FINGERPRINT_LEN));
457 free_public_key(pk);
459 else
460 memset(array,0,(len=MAX_FINGERPRINT_LEN));
462 else if( ch[1]=='f' && args->pk)
463 fingerprint_from_pk(args->pk,array,&len);
464 else if( ch[1]=='g' && args->sk)
465 fingerprint_from_sk(args->sk,array,&len);
466 else
467 memset(array, 0, (len=MAX_FINGERPRINT_LEN));
469 if(idx+(len*2)<maxlen)
471 for(i=0;i<len;i++)
473 sprintf(&ret[idx],"%02X",array[i]);
474 idx+=2;
476 done=1;
479 break;
481 case 't': /* e.g. "jpg" */
482 str=image_type_to_string(args->imagetype,0);
483 /* fall through */
485 case 'T': /* e.g. "image/jpeg" */
486 if(str==NULL)
487 str=image_type_to_string(args->imagetype,2);
489 if(idx+strlen(str)<maxlen)
491 strcpy(&ret[idx],str);
492 idx+=strlen(str);
493 done=1;
495 break;
497 case '%':
498 if(idx+1<maxlen)
500 ret[idx++]='%';
501 ret[idx]='\0';
502 done=1;
504 break;
506 /* Any unknown %-keys (like %i, %o, %I, and %O) are
507 passed through for later expansion. Note this also
508 handles the case where the last character in the
509 string is a '%' - the terminating \0 will end up here
510 and properly terminate the string. */
511 default:
512 if(idx+2<maxlen)
514 ret[idx++]='%';
515 ret[idx++]=*(ch+1);
516 ret[idx]='\0';
517 done=1;
519 break;
522 if(done)
523 ch++;
525 else
527 if(idx+1<maxlen)
529 ret[idx++]=*ch;
530 ret[idx]='\0';
531 done=1;
535 if(done)
536 ch++;
539 return ret;
541 fail:
542 xfree (ret);
543 return NULL;
547 hextobyte( const char *s )
549 int c;
551 if( *s >= '0' && *s <= '9' )
552 c = 16 * (*s - '0');
553 else if( *s >= 'A' && *s <= 'F' )
554 c = 16 * (10 + *s - 'A');
555 else if( *s >= 'a' && *s <= 'f' )
556 c = 16 * (10 + *s - 'a');
557 else
558 return -1;
559 s++;
560 if( *s >= '0' && *s <= '9' )
561 c += *s - '0';
562 else if( *s >= 'A' && *s <= 'F' )
563 c += 10 + *s - 'A';
564 else if( *s >= 'a' && *s <= 'f' )
565 c += 10 + *s - 'a';
566 else
567 return -1;
568 return c;
571 void
572 deprecated_warning(const char *configname,unsigned int configlineno,
573 const char *option,const char *repl1,const char *repl2)
575 if(configname)
577 if(strncmp("--",option,2)==0)
578 option+=2;
580 if(strncmp("--",repl1,2)==0)
581 repl1+=2;
583 log_info(_("%s:%d: deprecated option \"%s\"\n"),
584 configname,configlineno,option);
586 else
587 log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
589 log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
592 const char *
593 compress_algo_to_string(int algo)
595 const char *s="?";
597 switch(algo)
599 case 0:
600 s="Uncompressed";
601 break;
603 case 1:
604 s="ZIP";
605 break;
607 case 2:
608 s="ZLIB";
609 break;
612 return s;
616 string_to_compress_algo(const char *string)
618 if(ascii_strcasecmp(string,"uncompressed")==0)
619 return 0;
620 else if(ascii_strcasecmp(string,"zip")==0)
621 return 1;
622 else if(ascii_strcasecmp(string,"zlib")==0)
623 return 2;
624 else if(ascii_strcasecmp(string,"z0")==0)
625 return 0;
626 else if(ascii_strcasecmp(string,"z1")==0)
627 return 1;
628 else if(ascii_strcasecmp(string,"z2")==0)
629 return 2;
630 else
631 return -1;
635 check_compress_algo(int algo)
637 if(algo>=0 && algo<=2)
638 return 0;
640 return GPG_ERR_COMPR_ALGO;
644 default_cipher_algo(void)
646 if(opt.def_cipher_algo)
647 return opt.def_cipher_algo;
648 else if(opt.personal_cipher_prefs)
649 return opt.personal_cipher_prefs[0].value;
650 else
651 return opt.s2k_cipher_algo;
654 /* There is no default_digest_algo function, but see
655 sign.c:hash_for */
658 default_compress_algo(void)
660 if(opt.def_compress_algo!=-1)
661 return opt.def_compress_algo;
662 else if(opt.personal_compress_prefs)
663 return opt.personal_compress_prefs[0].value;
664 else
665 return DEFAULT_COMPRESS_ALGO;
668 const char *
669 compliance_option_string(void)
671 switch(opt.compliance)
673 case CO_RFC2440:
674 return "--openpgp";
675 case CO_PGP2:
676 return "--pgp2";
677 case CO_PGP6:
678 return "--pgp6";
679 case CO_PGP7:
680 return "--pgp7";
681 case CO_PGP8:
682 return "--pgp8";
683 default:
684 return "???";
688 static const char *
689 compliance_string(void)
691 switch(opt.compliance)
693 case CO_RFC2440:
694 return "OpenPGP";
695 case CO_PGP2:
696 return "PGP 2.x";
697 case CO_PGP6:
698 return "PGP 6.x";
699 case CO_PGP7:
700 return "PGP 7.x";
701 case CO_PGP8:
702 return "PGP 8.x";
703 default:
704 return "???";
708 void
709 compliance_failure(void)
711 log_info(_("this message may not be usable by %s\n"),compliance_string());
712 opt.compliance=CO_GNUPG;
716 parse_options(char *str,unsigned int *options,struct parse_options *opts)
718 char *tok;
720 while((tok=strsep(&str," ,")))
722 int i,rev=0;
724 if(tok[0]=='\0')
725 continue;
727 if(ascii_strncasecmp("no-",tok,3)==0)
729 rev=1;
730 tok+=3;
733 for(i=0;opts[i].name;i++)
735 if(ascii_strcasecmp(opts[i].name,tok)==0)
737 if(rev)
738 *options&=~opts[i].bit;
739 else
740 *options|=opts[i].bit;
741 break;
745 if(!opts[i].name)
746 return 0;
749 return 1;
754 /* Temporary helper. */
756 pubkey_get_npkey( int algo )
758 size_t n;
760 if (algo == GCRY_PK_ELG_E)
761 algo = GCRY_PK_ELG;
762 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
763 n = 0;
764 return n;
767 /* Temporary helper. */
769 pubkey_get_nskey( int algo )
771 size_t n;
773 if (algo == GCRY_PK_ELG_E)
774 algo = GCRY_PK_ELG;
775 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
776 n = 0;
777 return n;
780 /* Temporary helper. */
782 pubkey_get_nsig( int algo )
784 size_t n;
786 if (algo == GCRY_PK_ELG_E)
787 algo = GCRY_PK_ELG;
788 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
789 n = 0;
790 return n;
793 /* Temporary helper. */
795 pubkey_get_nenc( int algo )
797 size_t n;
799 if (algo == GCRY_PK_ELG_E)
800 algo = GCRY_PK_ELG;
801 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
802 n = 0;
803 return n;
807 /* Temporary helper. */
808 unsigned int
809 pubkey_nbits( int algo, gcry_mpi_t *key )
811 int rc, nbits;
812 gcry_sexp_t sexp;
814 if( algo == GCRY_PK_DSA ) {
815 rc = gcry_sexp_build ( &sexp, NULL,
816 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
817 key[0], key[1], key[2], key[3] );
819 else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
820 rc = gcry_sexp_build ( &sexp, NULL,
821 "(public-key(elg(p%m)(g%m)(y%m)))",
822 key[0], key[1], key[2] );
824 else if( algo == GCRY_PK_RSA ) {
825 rc = gcry_sexp_build ( &sexp, NULL,
826 "(public-key(rsa(n%m)(e%m)))",
827 key[0], key[1] );
829 else
830 return 0;
832 if ( rc )
833 BUG ();
835 nbits = gcry_pk_get_nbits( sexp );
836 gcry_sexp_release( sexp );
837 return nbits;
841 /* MPI helper functions. */
844 /****************
845 * write an mpi to out.
848 mpi_write( iobuf_t out, gcry_mpi_t a )
850 char buffer[(MAX_EXTERN_MPI_BITS+7)/8];
851 size_t nbytes;
852 int rc;
854 nbytes = (MAX_EXTERN_MPI_BITS+7)/8;
855 rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
856 if( !rc )
857 rc = iobuf_write( out, buffer, nbytes );
859 return rc;
862 /****************
863 * Writyeg a MPI to out, but in this case it is an opaque one,
864 * s used vor v3 protected keys.
867 mpi_write_opaque( iobuf_t out, gcry_mpi_t a )
869 size_t nbytes, nbits;
870 int rc;
871 char *p;
873 assert( gcry_mpi_get_flag( a, GCRYMPI_FLAG_OPAQUE ) );
874 p = gcry_mpi_get_opaque( a, &nbits );
875 nbytes = (nbits+7) / 8;
876 iobuf_put( out, nbits >> 8 );
877 iobuf_put( out, nbits );
878 rc = iobuf_write( out, p, nbytes );
879 return rc;
883 /****************
884 * Read an external representation of an mpi and return the MPI
885 * The external format is a 16 bit unsigned value stored in network byte order,
886 * giving the number of bits for the following integer. The integer is stored
887 * with MSB first (left padded with zeroes to align on a byte boundary).
889 gcry_mpi_t
890 mpi_read(iobuf_t inp, unsigned int *ret_nread, int secure)
892 int c, c1, c2, i;
893 unsigned int nbits, nbytes, nread=0;
894 gcry_mpi_t a = NULL;
895 byte *buf = NULL;
896 byte *p;
898 if( (c = c1 = iobuf_get(inp)) == -1 )
899 goto leave;
900 nbits = c << 8;
901 if( (c = c2 = iobuf_get(inp)) == -1 )
902 goto leave;
903 nbits |= c;
904 if( nbits > MAX_EXTERN_MPI_BITS ) {
905 log_error("mpi too large (%u bits)\n", nbits);
906 goto leave;
908 nread = 2;
909 nbytes = (nbits+7) / 8;
910 buf = secure? gcry_xmalloc_secure( nbytes+2 ) : gcry_xmalloc( nbytes+2 );
911 p = buf;
912 p[0] = c1;
913 p[1] = c2;
914 for( i=0 ; i < nbytes; i++ ) {
915 p[i+2] = iobuf_get(inp) & 0xff;
916 nread++;
918 nread += nbytes;
919 if( gcry_mpi_scan( &a, GCRYMPI_FMT_PGP, buf, nread, &nread ) )
920 a = NULL;
922 leave:
923 gcry_free(buf);
924 if( nread > *ret_nread )
925 log_bug("mpi larger than packet");
926 else
927 *ret_nread = nread;
928 return a;
931 /****************
932 * Same as mpi_read but the value is stored as an opaque MPI.
933 * This function is used to read encrypted MPI of v3 packets.
935 gcry_mpi_t
936 mpi_read_opaque(iobuf_t inp, unsigned *ret_nread )
938 int c, c1, c2, i;
939 unsigned nbits, nbytes, nread=0;
940 gcry_mpi_t a = NULL;
941 byte *buf = NULL;
942 byte *p;
944 if( (c = c1 = iobuf_get(inp)) == -1 )
945 goto leave;
946 nbits = c << 8;
947 if( (c = c2 = iobuf_get(inp)) == -1 )
948 goto leave;
949 nbits |= c;
950 if( nbits > MAX_EXTERN_MPI_BITS ) {
951 log_error("mpi too large (%u bits)\n", nbits);
952 goto leave;
954 nread = 2;
955 nbytes = (nbits+7) / 8;
956 buf = gcry_xmalloc( nbytes );
957 p = buf;
958 for( i=0 ; i < nbytes; i++ ) {
959 p[i] = iobuf_get(inp) & 0xff;
961 nread += nbytes;
962 a = gcry_mpi_set_opaque(NULL, buf, nbits );
963 buf = NULL;
965 leave:
966 gcry_free(buf);
967 if( nread > *ret_nread )
968 log_bug("mpi larger than packet");
969 else
970 *ret_nread = nread;
971 return a;
976 mpi_print( FILE *fp, gcry_mpi_t a, int mode )
978 int n=0;
980 if( !a )
981 return fprintf(fp, "[MPI_NULL]");
982 if( !mode ) {
983 unsigned int n1;
984 n1 = gcry_mpi_get_nbits(a);
985 n += fprintf(fp, "[%u bits]", n1);
987 else {
988 int rc;
989 unsigned char *buffer;
991 rc = gcry_mpi_aprint( GCRYMPI_FMT_HEX, &buffer, NULL, a );
992 assert( !rc );
993 fputs( buffer, fp );
994 n += strlen(buffer);
995 gcry_free( buffer );
997 return n;