root/openpgpsdk/trunk/src/packet-parse.c

Revision 365 (checked in by ben, 7 years ago)

Fix decryption.

  • Property svn:keywords set to Id
Line 
1 /** \file
2  * \brief Parser for OpenPGP packets
3  */
4
5 #include <openpgpsdk/packet.h>
6 #include <openpgpsdk/packet-parse.h>
7 #include <openpgpsdk/util.h>
8 #include <openpgpsdk/compress.h>
9 #include <openpgpsdk/errors.h>
10 #include "parse_local.h"
11
12 #include <assert.h>
13 #include <stdarg.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <errno.h>
18
19 /**
20  * limited_read_data reads the specified amount of the subregion's data
21  * into a data_t structure
22  *
23  * \param data  Empty structure which will be filled with data
24  * \param len   Number of octets to read
25  * \param subregion
26  * \param parse_info    How to parse
27  *
28  * \return 1 on success, 0 on failure
29  */
30 static int limited_read_data(ops_data_t *data,unsigned int len,
31                              ops_region_t *subregion,ops_parse_info_t *parse_info)
32     {
33     data->len = len;
34
35     assert(subregion->length-subregion->length_read >= len);
36
37     data->contents=malloc(data->len);
38     if (!data->contents)
39         return 0;
40
41     if (!ops_limited_read(data->contents, data->len,subregion,
42                           &parse_info->errors,&parse_info->rinfo,
43                           &parse_info->cbinfo))
44         return 0;
45    
46     return 1;
47     }
48
49 /**
50  * read_data reads the remainder of the subregion's data
51  * into a data_t structure
52  *
53  * \param data
54  * \param subregion
55  * \param parse_info
56  *
57  * \return 1 on success, 0 on failure
58  */
59 static int read_data(ops_data_t *data,ops_region_t *subregion,
60                      ops_parse_info_t *parse_info)
61     {
62     int len;
63
64     len=subregion->length-subregion->length_read;
65
66     return(limited_read_data(data,len,subregion,parse_info));
67     }
68
69 /**
70  * Reads the remainder of the subregion as a string.
71  * It is the user's responsibility to free the memory allocated here.
72  */
73
74 static int read_unsigned_string(unsigned char **str,ops_region_t *subregion,
75                                 ops_parse_info_t *pinfo)
76     {
77     int len=0;
78
79     len=subregion->length-subregion->length_read;
80
81     *str=malloc(len+1);
82     if(!(*str))
83         return 0;
84
85     if(len && !ops_limited_read(*str,len,subregion,&pinfo->errors,
86                                 &pinfo->rinfo,&pinfo->cbinfo))
87         return 0;
88
89     /*! ensure the string is NULL-terminated */
90
91     (*str)[len]=(char) NULL;
92
93     return 1;
94     }
95
96 static int read_string(char **str, ops_region_t *subregion, ops_parse_info_t *parse_info)
97     {
98     return (read_unsigned_string((unsigned char **)str, subregion, parse_info));
99     }
100
101 void ops_init_subregion(ops_region_t *subregion,ops_region_t *region)
102     {
103     memset(subregion,'\0',sizeof *subregion);
104     subregion->parent=region;
105     }
106
107 /*! \todo descr for CB macro */
108 /*! \todo check other callback functions to check they match this usage */
109 #define CB(cbinfo,t,pc) do { (pc)->tag=(t); if((cbinfo)->cb(pc,(cbinfo)) == OPS_RELEASE_MEMORY) ops_parser_content_free(pc); } while(0)
110 #define CBP(info,t,pc) CB(&(info)->cbinfo,t,pc)
111 /*! macro to save typing */
112 #define C               content.content
113 /*! set error code in content and run CallBack to handle error */
114 #define ERRCODE(cbinfo,err)     do { C.errcode.errcode=err; CB(cbinfo,OPS_PARSER_ERRCODE,&content); } while(0)
115 #define ERRCODEP(pinfo,err)     do { C.errcode.errcode=err; CBP(pinfo,OPS_PARSER_ERRCODE,&content); } while(0)
116 /*! set error text in content and run CallBack to handle error, then return */
117 #define ERR(cbinfo,err) do { C.error.error=err; CB(cbinfo,OPS_PARSER_ERROR,&content); return ops_false; } while(0)
118 #define ERRP(info,err)  do { C.error.error=err; CBP(info,OPS_PARSER_ERROR,&content); return ops_false; } while(0)
119 /*! set error text in content and run CallBack to handle warning, do not return */
120 #define WARN(warn)      do { C.error.error=warn; CB(OPS_PARSER_ERROR,&content);; } while(0)
121 #define WARNP(info,warn)        do { C.error.error=warn; CBP(info,OPS_PARSER_ERROR,&content); } while(0)
122 /*! \todo descr ERR1 macro */
123 #define ERR1P(info,fmt,x)       do { format_error(&content,(fmt),(x)); CBP(info,OPS_PARSER_ERROR,&content); return ops_false; } while(0)
124
125 /* XXX: replace ops_ptag_t with something more appropriate for limiting
126    reads */
127
128 /* Note that this makes the parser non-reentrant, in a limited way */
129 /* It is the caller's responsibility to avoid overflow in the buffer */
130 static void format_error(ops_parser_content_t *content,
131                          const char *const fmt,...)
132     {
133     va_list va;
134     static char buf[8192];
135
136     va_start(va,fmt);
137     vsnprintf(buf,sizeof buf,fmt,va);
138     va_end(va);
139     content->content.error.error=buf;
140     }
141
142 /**
143  * low-level function to read data from reader function
144  *
145  * Use this function, rather than calling the reader directly.
146  *
147  * If the accumulate flag is set in *parse_info, the function
148  * adds the read data to the accumulated data, and updates
149  * the accumulated length. This is useful if, for example,
150  * the application wants access to the raw data as well as the
151  * parsed data.
152  *
153  * \param *dest
154  * \param *plength
155  * \param flags
156  * \param *parse_info
157  *
158  * \return OPS_R_OK
159  * \return OPS_R_PARTIAL_READ
160  * \return OPS_R_EOF
161  * \return OPS_R_EARLY_EOF
162  *
163  * \sa #ops_reader_ret_t, ops_reader_fd() for details of return codes
164  */
165
166 static ops_reader_ret_t sub_base_read(unsigned char *dest,unsigned *plength,
167                                       ops_reader_flags_t flags,
168                                       ops_error_t **errors,
169                                       ops_reader_info_t *rinfo,
170                                       ops_parse_cb_info_t *cbinfo)
171     {
172     ops_reader_ret_t ret=rinfo->reader(dest,plength,flags,errors,rinfo,cbinfo);
173
174     if(ret != OPS_R_OK && ret != OPS_R_PARTIAL_READ)
175         return ret;
176
177     if(rinfo->accumulate)
178         {
179         assert(rinfo->asize >= rinfo->alength);
180         if(rinfo->alength+*plength > rinfo->asize)
181             {
182             rinfo->asize=rinfo->asize*2+*plength;
183             rinfo->accumulated=realloc(rinfo->accumulated,rinfo->asize);
184             }
185         assert(rinfo->asize >= rinfo->alength+*plength);
186         memcpy(rinfo->accumulated+rinfo->alength,dest,*plength);
187         }
188     // we track length anyway, because it is used for packet offsets
189     rinfo->alength+=*plength;
190     // and also the position
191     rinfo->position+=*plength;
192
193     return ret;
194     }
195
196 ops_reader_ret_t ops_stacked_read(unsigned char *dest,unsigned *length,
197                                   ops_reader_flags_t flags,
198                                   ops_error_t **errors,
199                                   ops_reader_info_t *rinfo,
200                                   ops_parse_cb_info_t *cbinfo)
201     { return sub_base_read(dest,length,flags,errors,rinfo->next,cbinfo); }
202
203 static ops_reader_ret_t base_read(unsigned char *dest,unsigned *plength,
204                                   ops_reader_flags_t flags,
205                                   ops_parse_info_t *info)
206     {
207     return sub_base_read(dest,plength,flags,&info->errors,&info->rinfo,
208                          &info->cbinfo);
209     }
210
211 /** Read a scalar value of selected length from reader.
212  *
213  * Read an unsigned scalar value from reader in Big Endian representation.
214  *
215  * This function does not know or care about packet boundaries.
216  *
217  * \param *result       The scalar value is stored here
218  * \param *reader       Our reader
219  * \param length        How many bytes to read
220  * \return              OPS_R_OK on success, reader's return value otherwise
221  *
222  * \sa #ops_reader_ret_t for possible return codes
223  */
224 static ops_reader_ret_t read_scalar(unsigned *result,unsigned length,
225                                     ops_parse_info_t *parse_info)
226     {
227     unsigned t=0;
228     ops_reader_ret_t ret;
229
230     assert (length <= sizeof(*result));
231
232     while(length--)
233         {
234         unsigned char c[1];
235         unsigned one=1;
236
237         ret=base_read(c,&one,0,parse_info);
238         if(ret != OPS_R_OK)
239             return ret;
240         t=(t << 8)+c[0];
241         }
242     *result=t;
243     return OPS_R_OK;
244     }
245
246 /** Read bytes from a region within the packet.
247  *
248  * Read length bytes into the buffer pointed to by *dest.  Make sure
249  * we do not read over the packet boundary.  Updates the Packet Tag's
250  * ops_ptag_t::length_read.
251  *
252  * If length would make us read over the packet boundary, or if
253  * reading fails, we call the callback with an OPS_PARSER_ERROR.
254  *
255  * This function makes sure to respect packet boundaries.
256  *
257  * \param *dest         The destination buffer
258  * \param length        How many bytes to read
259  * \param *region       Pointer to packet region
260  * \param *parse_info   How to parse, including callback function
261  * \return              1 on success, 0 on error
262  */
263 ops_boolean_t ops_limited_read(unsigned char *dest,unsigned length,
264                                ops_region_t *region,ops_error_t **errors,
265                                ops_reader_info_t *rinfo,
266                                ops_parse_cb_info_t *cbinfo)
267     {
268     ops_parser_content_t content;
269     ops_reader_ret_t ret;
270
271     if(!region->indeterminate && region->length_read+length > region->length)
272         {
273         ERRCODE(cbinfo,OPS_E_P_NOT_ENOUGH_DATA);
274         return 0;
275         }
276
277     ret=sub_base_read(dest,&length,
278                       region->indeterminate ? OPS_RETURN_LENGTH : 0,errors,
279                       rinfo,cbinfo);
280
281     if(ret != OPS_R_OK && ret != OPS_R_PARTIAL_READ)
282         {
283         ERRCODE(cbinfo,OPS_E_R_READ_FAILED);
284         return 0;
285         }
286
287     region->last_read=length;
288     do
289         {
290         region->length_read+=length;
291         assert(!region->parent || region->length <= region->parent->length);
292         }
293     while((region=region->parent));
294
295     return 1;
296     }
297
298 ops_boolean_t ops_stacked_limited_read(unsigned char *dest,unsigned length,
299                                        ops_region_t *region,
300                                        ops_error_t **errors,
301                                        ops_reader_info_t *rinfo,
302                                        ops_parse_cb_info_t *cbinfo)
303     { return ops_limited_read(dest,length,region,errors,rinfo->next,cbinfo); }
304
305 static ops_boolean_t limited_read(unsigned char *dest,unsigned length,
306                                   ops_region_t *region,ops_parse_info_t *info)
307     {
308     return ops_limited_read(dest,length,region,&info->errors,
309                             &info->rinfo,&info->cbinfo);
310     }
311
312 /** Skip over length bytes of this packet.
313  *
314  * Calls limited_read() to skip over some data.
315  *
316  * This function makes sure to respect packet boundaries.
317  *
318  * \param length        How many bytes to skip
319  * \param *region       Pointer to packet region
320  * \param *parse_info   How to parse
321  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
322  */
323 static int limited_skip(unsigned length,ops_region_t *region,
324                         ops_parse_info_t *parse_info)
325     {
326     unsigned char buf[8192];
327
328     while(length)
329         {
330         int n=length%8192;
331         if(!limited_read(buf,n,region,parse_info))
332             return 0;
333         length-=n;
334         }
335     return 1;
336     }
337
338 /** Read a scalar.
339  *
340  * Read a big-endian scalar of length bytes, respecting packet
341  * boundaries (by calling limited_read() to read the raw data).
342  *
343  * This function makes sure to respect packet boundaries.
344  *
345  * \param *dest         The scalar value is stored here
346  * \param length        How many bytes make up this scalar (at most 4)
347  * \param *region       Pointer to current packet region
348  * \param *parse_info   How to parse
349  * \param *cb           The callback
350  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
351  *
352  * \see RFC2440bis-12 3.1
353  */
354 static int limited_read_scalar(unsigned *dest,unsigned length,
355                                ops_region_t *region,
356                                ops_parse_info_t *parse_info)
357     {
358     unsigned char c[4];
359     unsigned t;
360     unsigned n;
361
362     assert(length <= 4);
363     assert(sizeof(*dest) >= 4);
364     if(!limited_read(c,length,region,parse_info))
365         return 0;
366
367     for(t=0,n=0 ; n < length ; ++n)
368         t=(t << 8)+c[n];
369     *dest=t;
370
371     return 1;
372     }
373
374 /** Read a scalar.
375  *
376  * Read a big-endian scalar of length bytes, respecting packet
377  * boundaries (by calling limited_read() to read the raw data).
378  *
379  * The value read is stored in a size_t, which is a different size
380  * from an unsigned on some platforms.
381  *
382  * This function makes sure to respect packet boundaries.
383  *
384  * \param *dest         The scalar value is stored here
385  * \param length        How many bytes make up this scalar (at most 4)
386  * \param *region       Pointer to current packet region
387  * \param *parse_info   How to parse
388  * \param *cb           The callback
389  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
390  *
391  * \see RFC2440bis-12 3.1
392  */
393 static int limited_read_size_t_scalar(size_t *dest,unsigned length,
394                                       ops_region_t *region,
395                                       ops_parse_info_t *parse_info)
396     {
397     unsigned tmp;
398
399     assert(sizeof(*dest) >= 4);
400
401     /* Note that because the scalar is at most 4 bytes, we don't care
402        if size_t is bigger than usigned */
403     if(!limited_read_scalar(&tmp,length,region,parse_info))
404         return 0;
405
406     *dest=tmp;
407     return 1;
408     }
409
410 /** Read a timestamp.
411  *
412  * Timestamps in OpenPGP are unix time, i.e. seconds since The Epoch (1.1.1970).  They are stored in an unsigned scalar
413  * of 4 bytes.
414  *
415  * This function reads the timestamp using limited_read_scalar().
416  *
417  * This function makes sure to respect packet boundaries.
418  *
419  * \param *dest         The timestamp is stored here
420  * \param *ptag         Pointer to current packet's Packet Tag.
421  * \param *reader       Our reader
422  * \param *cb           The callback
423  * \return              see limited_read_scalar()
424  *
425  * \see RFC2440bis-12 3.5
426  */
427 static int limited_read_time(time_t *dest,ops_region_t *region,
428                              ops_parse_info_t *parse_info)
429     {
430     return limited_read_scalar((unsigned *)dest,4,region,parse_info);
431     }
432
433 /** Read a multiprecision integer.
434  *
435  * Large numbers (multiprecision integers, MPI) are stored in OpenPGP in two parts.  First there is a 2 byte scalar
436  * indicating the length of the following MPI in Bits.  Then follow the bits that make up the actual number, most
437  * significant bits first (Big Endian).  The most significant bit in the MPI is supposed to be 1 (unless the MPI is
438  * encrypted - then it may be different as the bit count refers to the plain text but the bits are encrypted).
439  *
440  * Unused bits (i.e. those filling up the most significant byte from the left to the first bits that counts) are
441  * supposed to be cleared - I guess. XXX - does anything actually say so?
442  *
443  * This function makes sure to respect packet boundaries.
444  *
445  * \param **pgn         return the integer there - the BIGNUM is created by BN_bin2bn() and probably needs to be freed
446  *                              by the caller XXX right ben?
447  * \param *ptag         Pointer to current packet's Packet Tag.
448  * \param *reader       Our reader
449  * \param *cb           The callback
450  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
451  *                               see comment below - the callback is called with a OPS_PARSER_ERROR in case of an error)
452  *
453  * \see RFC2440bis-12 3.2
454  */
455 static int limited_read_mpi(BIGNUM **pbn,ops_region_t *region,
456                             ops_parse_info_t *parse_info)
457     {
458     unsigned length;
459     unsigned nonzero;
460     unsigned char buf[8192]; /* an MPI has a 2 byte length part.  Length
461                                 is given in bits, so the largest we should
462                                 ever need for the buffer is 8192 bytes. */
463     ops_parser_content_t content;
464     ops_boolean_t ret;
465
466     parse_info->reading_mpi_length=ops_true;
467     ret=limited_read_scalar(&length,2,region,parse_info);
468     parse_info->reading_mpi_length=ops_false;
469     if(!ret)
470         return 0;
471
472     nonzero=length&7; /* there should be this many zero bits in the MS byte */
473     if(!nonzero)
474         nonzero=8;
475     length=(length+7)/8;
476
477     assert(length <= 8192);
478     if(!limited_read(buf,length,region,parse_info))
479         return 0;
480
481     if((buf[0] >> nonzero) != 0 || !(buf[0]&(1 << (nonzero-1))))
482         {
483         ERRCODEP(parse_info,OPS_E_P_MPI_FORMAT_ERROR);  /* XXX: Ben, one part of this constraint does not apply to encrypted MPIs the draft says. -- peter */
484         return 0;
485         }
486
487     *pbn=BN_bin2bn(buf,length,NULL);
488     return 1;
489     }
490
491 /** Read some data with a New-Format length from reader.
492  *
493  * \sa Internet-Draft RFC2440bis-13.txt Section 4.2.2
494  *
495  * \param *length       Where the decoded length will be put
496  * \param *parse_info   How to parse
497  * \return              1 if OK, else 0
498  *
499  */
500
501 static int read_new_length(unsigned *length,ops_parse_info_t *parse_info)
502     {
503     unsigned char c[1];
504     unsigned one=1;
505
506     if(base_read(c,&one,0,parse_info) != OPS_R_OK)
507         return 0;
508     if(c[0] < 192)
509         {
510         *length=c[0];
511         return 1;
512         }
513     if(c[0] < 255)
514         {
515         unsigned t=(c[0]-192) << 8;
516
517         if(base_read(c,&one,0,parse_info) != OPS_R_OK)
518             return 0;
519         *length=t+c[0]+192;
520         return 1;
521         }
522     return (read_scalar(length,4,parse_info) == OPS_R_OK ? 1 : 0);
523     }
524
525 /** Read the length information for a new format Packet Tag.
526  *
527  * New style Packet Tags encode the length in one to five octets.  This function reads the right amount of bytes and
528  * decodes it to the proper length information.
529  *
530  * This function makes sure to respect packet boundaries.
531  *
532  * \param *length       return the length here
533  * \param *ptag         Pointer to current packet's Packet Tag.
534  * \param *reader       Our reader
535  * \param *cb           The callback
536  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
537  *                               see comment below)
538  *
539  * \see RFC2440bis-12 4.2.2
540  * \see ops_ptag_t
541  */
542 static int limited_read_new_length(unsigned *length,ops_region_t *region,
543                                    ops_parse_info_t *parse_info)
544     {
545     unsigned char c[1];
546
547     if(!limited_read(c,1,region,parse_info))
548         return 0;
549     if(c[0] < 192)
550         {
551         *length=c[0];
552         return 1;
553         }
554     if(c[0] < 255)
555         {
556         unsigned t=(c[0]-192) << 8;
557
558         if(!limited_read(c,1,region,parse_info))
559             return 0;
560         *length=t+c[0]+192;
561         return 1;
562         }
563     return limited_read_scalar(length,4,region,parse_info);
564     }
565
566 static void data_free(ops_data_t *data)
567     {
568     free(data->contents);
569     data->contents=NULL;
570     data->len=0;
571     }
572
573 static void string_free(char **str)
574     {
575     free(*str);
576     *str=NULL;
577     }
578
579 /*! Free packet memory, set pointer to NULL */
580 void ops_packet_free(ops_packet_t *packet)
581     {
582     free(packet->raw);
583     packet->raw=NULL;
584     }
585
586 void ops_headers_free(ops_headers_t *headers)
587     {
588     unsigned n;
589
590     for(n=0 ; n < headers->nheaders ; ++n)
591         {
592         free(headers->headers[n].key);
593         free(headers->headers[n].value);
594         }
595     free(headers->headers);
596     headers->headers=NULL;
597     }
598
599 void ops_signed_cleartext_trailer_free(ops_signed_cleartext_trailer_t *trailer)
600     {
601     free(trailer->hash);
602     trailer->hash=NULL;
603     }
604
605 void ops_cmd_get_passphrase_free(ops_secret_key_passphrase_t *skp)
606     {
607     free(skp->passphrase);
608     skp->passphrase=NULL;
609     }
610
611 /*! Free any memory allocated when parsing the packet content */
612 void ops_parser_content_free(ops_parser_content_t *c)
613     {
614     switch(c->tag)
615         {
616     case OPS_PARSER_PTAG:
617     case OPS_PTAG_CT_COMPRESSED:
618     case OPS_PTAG_SS_CREATION_TIME:
619     case OPS_PTAG_SS_EXPIRATION_TIME:
620     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
621     case OPS_PTAG_SS_TRUST:
622     case OPS_PTAG_SS_ISSUER_KEY_ID:
623     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
624     case OPS_PTAG_SS_PRIMARY_USER_ID:
625     case OPS_PTAG_SS_REVOCABLE:
626     case OPS_PTAG_SS_REVOCATION_KEY:
627     case OPS_PTAG_CT_LITERAL_DATA_HEADER:
628     case OPS_PTAG_CT_LITERAL_DATA_BODY:
629     case OPS_PTAG_CT_SIGNED_CLEARTEXT_BODY:
630     case OPS_PTAG_CT_UNARMOURED_TEXT:
631     case OPS_PTAG_CT_ARMOUR_TRAILER:
632     case OPS_PTAG_CT_SIGNATURE_HEADER:
633     case OPS_PTAG_CT_SE_DATA:
634         break;
635
636     case OPS_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
637         ops_headers_free(&c->content.signed_cleartext_header.headers);
638         break;
639
640     case OPS_PTAG_CT_ARMOUR_HEADER:
641         ops_headers_free(&c->content.armour_header.headers);
642         break;
643
644     case OPS_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
645         ops_signed_cleartext_trailer_free(&c->content.signed_cleartext_trailer);
646         break;
647
648     case OPS_PTAG_CT_TRUST:
649         ops_trust_free(&c->content.trust);
650         break;
651
652     case OPS_PTAG_CT_SIGNATURE:
653     case OPS_PTAG_CT_SIGNATURE_FOOTER:
654         ops_signature_free(&c->content.signature);
655         break;
656
657     case OPS_PTAG_CT_PUBLIC_KEY:
658     case OPS_PTAG_CT_PUBLIC_SUBKEY:
659         ops_public_key_free(&c->content.public_key);
660         break;
661
662     case OPS_PTAG_CT_USER_ID:
663         ops_user_id_free(&c->content.user_id);
664         break;
665
666     case OPS_PTAG_SS_SIGNERS_USER_ID:
667         ops_user_id_free(&c->content.ss_signers_user_id);
668         break;
669
670     case OPS_PTAG_CT_USER_ATTRIBUTE:
671         ops_user_attribute_free(&c->content.user_attribute);
672         break;
673
674     case OPS_PTAG_SS_PREFERRED_SKA:
675         ops_ss_preferred_ska_free(&c->content.ss_preferred_ska);
676         break;
677
678     case OPS_PTAG_SS_PREFERRED_HASH:
679         ops_ss_preferred_hash_free(&c->content.ss_preferred_hash);
680         break;
681
682     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
683         ops_ss_preferred_compression_free(&c->content.ss_preferred_compression);
684         break;
685
686     case OPS_PTAG_SS_KEY_FLAGS:
687         ops_ss_key_flags_free(&c->content.ss_key_flags);
688         break;
689
690     case OPS_PTAG_SS_KEY_SERVER_PREFS:
691         ops_ss_key_server_prefs_free(&c->content.ss_key_server_prefs);
692         break;
693
694     case OPS_PTAG_SS_FEATURES:
695         ops_ss_features_free(&c->content.ss_features);
696         break;
697
698     case OPS_PTAG_SS_NOTATION_DATA:
699         ops_ss_notation_data_free(&c->content.ss_notation_data);
700         break;
701
702     case OPS_PTAG_SS_REGEXP:
703         ops_ss_regexp_free(&c->content.ss_regexp);
704         break;
705
706     case OPS_PTAG_SS_POLICY_URL:
707         ops_ss_policy_url_free(&c->content.ss_policy_url);
708         break;
709
710     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
711         ops_ss_preferred_key_server_free(&c->content.ss_preferred_key_server);
712         break;
713
714     case OPS_PTAG_SS_USERDEFINED00:
715     case OPS_PTAG_SS_USERDEFINED01:
716     case OPS_PTAG_SS_USERDEFINED02:
717     case OPS_PTAG_SS_USERDEFINED03:
718     case OPS_PTAG_SS_USERDEFINED04:
719     case OPS_PTAG_SS_USERDEFINED05:
720     case OPS_PTAG_SS_USERDEFINED06:
721     case OPS_PTAG_SS_USERDEFINED07:
722     case OPS_PTAG_SS_USERDEFINED08:
723     case OPS_PTAG_SS_USERDEFINED09:
724     case OPS_PTAG_SS_USERDEFINED10:
725         ops_ss_userdefined_free(&c->content.ss_userdefined);
726         break;
727
728     case OPS_PTAG_SS_RESERVED:
729         ops_ss_reserved_free(&c->content.ss_unknown);
730         break;
731
732     case OPS_PTAG_SS_REVOCATION_REASON:
733         ops_ss_revocation_reason_free(&c->content.ss_revocation_reason);
734         break;
735
736     case OPS_PARSER_PACKET_END:
737         ops_packet_free(&c->content.packet);
738         break;
739
740     case OPS_PARSER_ERROR:
741     case OPS_PARSER_ERRCODE:
742         break;
743
744     case OPS_PTAG_CT_SECRET_KEY:
745     case OPS_PTAG_CT_ENCRYPTED_SECRET_KEY:
746         ops_secret_key_free(&c->content.secret_key);
747         break;
748
749     case OPS_PTAG_CT_PK_SESSION_KEY:
750         ops_pk_session_key_free(&c->content.pk_session_key);
751         break;
752
753     case OPS_PARSER_CMD_GET_SK_PASSPHRASE:
754         ops_cmd_get_passphrase_free(&c->content.secret_key_passphrase);
755         break;
756
757     default:
758         fprintf(stderr,"Can't free %d (0x%x)\n",c->tag,c->tag);
759         assert(0);
760         }
761     }
762
763 static void free_BN(BIGNUM **pp)
764     {
765     BN_free(*pp);
766     *pp=NULL;
767     }
768
769 void ops_pk_session_key_free(ops_pk_session_key_t *sk)
770     {
771     switch(sk->algorithm)
772         {
773     case OPS_PKA_RSA:
774         free_BN(&sk->parameters.rsa.encrypted_m);
775         break;
776
777     case OPS_PKA_ELGAMAL:
778         free_BN(&sk->parameters.elgamal.g_to_k);
779         free_BN(&sk->parameters.elgamal.encrypted_m);
780         break;
781
782     default:
783         assert(0);
784         }
785     }
786
787 /*! Free the memory used when parsing a public key */
788 void ops_public_key_free(ops_public_key_t *p)
789     {
790     switch(p->algorithm)
791         {
792     case OPS_PKA_RSA:
793     case OPS_PKA_RSA_ENCRYPT_ONLY:
794     case OPS_PKA_RSA_SIGN_ONLY:
795         free_BN(&p->key.rsa.n);
796         free_BN(&p->key.rsa.e);
797         break;
798
799     case OPS_PKA_DSA:
800         free_BN(&p->key.dsa.p);
801         free_BN(&p->key.dsa.q);
802         free_BN(&p->key.dsa.g);
803         free_BN(&p->key.dsa.y);
804         break;
805
806     case OPS_PKA_ELGAMAL:
807     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
808         free_BN(&p->key.elgamal.p);
809         free_BN(&p->key.elgamal.g);
810         free_BN(&p->key.elgamal.y);
811         break;
812
813     default:
814         assert(0);
815         }
816     }
817
818 static int parse_public_key_data(ops_public_key_t *key,ops_region_t *region,
819                                  ops_parse_info_t *parse_info)
820     {
821     ops_parser_content_t content;
822     unsigned char c[1];
823
824     assert (region->length_read == 0);  /* We should not have read anything so far */
825
826     if(!limited_read(c,1,region,parse_info))
827         return 0;
828     key->version=c[0];
829     if(key->version < 2 || key->version > 4)
830         ERR1P(parse_info,"Bad public key version (0x%02x)",key->version);
831
832     if(!limited_read_time(&key->creation_time,region,parse_info))
833         return 0;
834
835     key->days_valid=0;
836     if((key->version == 2 || key->version == 3)
837        && !limited_read_scalar(&key->days_valid,2,region,parse_info))
838         return 0;
839
840     if(!limited_read(c,1,region,parse_info))
841         return 0;
842
843     key->algorithm=c[0];
844
845     switch(key->algorithm)
846         {
847     case OPS_PKA_DSA:
848         if(!limited_read_mpi(&key->key.dsa.p,region,parse_info)
849            || !limited_read_mpi(&key->key.dsa.q,region,parse_info)
850            || !limited_read_mpi(&key->key.dsa.g,region,parse_info)
851            || !limited_read_mpi(&key->key.dsa.y,region,parse_info))
852             return 0;
853         break;
854
855     case OPS_PKA_RSA:
856     case OPS_PKA_RSA_ENCRYPT_ONLY:
857     case OPS_PKA_RSA_SIGN_ONLY:
858         if(!limited_read_mpi(&key->key.rsa.n,region,parse_info)
859            || !limited_read_mpi(&key->key.rsa.e,region,parse_info))
860             return 0;
861         break;
862
863     case OPS_PKA_ELGAMAL:
864     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
865         if(!limited_read_mpi(&key->key.elgamal.p,region,parse_info)
866            || !limited_read_mpi(&key->key.elgamal.g,region,parse_info)
867            || !limited_read_mpi(&key->key.elgamal.y,region,parse_info))
868             return 0;
869         break;
870
871     default:
872         ERR1P(parse_info,"Unknown public key algorithm (%d)",key->algorithm);
873         }
874
875     return 1;
876     }
877
878
879 /** Parse a public key packet.
880  *
881  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
882  *
883  * Once the key has been parsed successfully, it is passed to the callback.
884  *
885  * \param *ptag         Pointer to the current Packet Tag.  This function should consume the entire packet.
886  * \param *reader       Our reader
887  * \param *cb           The callback
888  * \return              1 on success, 0 on error
889  *
890  * \see RFC2440bis-12 5.5.2
891  */
892 static int parse_public_key(ops_content_tag_t tag,ops_region_t *region,
893                             ops_parse_info_t *parse_info)
894     {
895     ops_parser_content_t content;
896
897     if(!parse_public_key_data(&C.public_key,region,parse_info))
898         return 0;
899
900     // XXX: this test should be done for all packets, surely?
901     if(region->length_read != region->length)
902         ERR1P(parse_info,"Unconsumed data (%d)",
903               region->length-region->length_read);
904
905     CBP(parse_info,tag,&content);
906
907     return 1;
908     }
909
910
911 /*! Free the memory used when parsing this signature sub-packet type */
912 void ops_ss_regexp_free(ops_ss_regexp_t *regexp)
913     {
914     string_free(&regexp->text);
915     }
916
917 /*! Free the memory used when parsing this signature sub-packet type */
918 void ops_ss_policy_url_free(ops_ss_policy_url_t *policy_url)
919     {
920     string_free(&policy_url->text);
921     }
922
923 /*! Free the memory used when parsing this signature sub-packet type */
924 void ops_ss_preferred_key_server_free(ops_ss_preferred_key_server_t *preferred_key_server)
925     {
926     string_free(&preferred_key_server->text);
927     }
928
929 /*! Free the memory used when parsing this packet type */
930 void ops_user_attribute_free(ops_user_attribute_t *user_att)
931     {
932     data_free(&user_att->data);
933     }
934
935 /** Parse one user attribute packet.
936  *
937  * User attribute packets contain one or more attribute subpackets.
938  * For now, handle the whole packet as raw data.
939  */
940
941 static int parse_user_attribute(ops_region_t *region, ops_parse_info_t *parse_info)
942     {
943
944     ops_parser_content_t content;
945
946     /* xxx- treat as raw data for now. Could break down further
947        into attribute sub-packets later - rachel */
948
949     assert(region->length_read == 0);  /* We should not have read anything so far */
950
951     if(!read_data(&C.user_attribute.data,region,parse_info))
952         return 0;
953
954     CBP(parse_info,OPS_PTAG_CT_USER_ATTRIBUTE,&content);
955
956     return 1;
957     }
958
959 /*! Free the memory used when parsing this packet type */
960 void ops_user_id_free(ops_user_id_t *id)
961     {
962     free(id->user_id);
963     id->user_id=NULL;
964     }
965
966 /** Parse a user id.
967  *
968  * This function parses an user id packet, which is basically just a char array the size of the packet.
969  *
970  * The char array is to be treated as an UTF-8 string.
971  *
972  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
973  *
974  * Once the userid has been parsed successfully, it is passed to the callback.
975  *
976  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
977  * \param *reader       Our reader
978  * \param *cb           The callback
979  * \return              1 on success, 0 on error
980  *
981  * \see RFC2440bis-12 5.11
982  */
983 static int parse_user_id(ops_region_t *region,ops_parse_info_t *parse_info)
984     {
985     ops_parser_content_t content;
986
987     assert(region->length_read == 0);  /* We should not have read anything so far */
988
989     C.user_id.user_id=malloc(region->length+1);  /* XXX should we not like check malloc's return value? */
990
991     if(region->length && !limited_read(C.user_id.user_id,region->length,region,
992                                        parse_info))
993         return 0;
994
995     C.user_id.user_id[region->length]='\0'; /* terminate the string */
996
997     CBP(parse_info,OPS_PTAG_CT_USER_ID,&content);
998
999     return 1;
1000     }
1001
1002 /**
1003  * \ingroup Memory
1004  *
1005  * Free the memory used when parsing a private/experimental PKA signature
1006  *
1007  * \param unknown_sig
1008  */
1009 void free_unknown_sig_pka(ops_unknown_signature_t *unknown_sig)
1010     {
1011     data_free(&unknown_sig->data);
1012     }
1013
1014 /**
1015  * \ingroup Memory
1016  *
1017  * Free the memory used when parsing a signature
1018  *
1019  * \param sig
1020  */
1021 void ops_signature_free(ops_signature_t *sig)
1022     {
1023     switch(sig->key_algorithm)
1024         {
1025     case OPS_PKA_RSA:
1026     case OPS_PKA_RSA_SIGN_ONLY:
1027         free_BN(&sig->signature.rsa.sig);
1028         break;
1029
1030     case OPS_PKA_DSA:
1031         free_BN(&sig->signature.dsa.r);
1032         free_BN(&sig->signature.dsa.s);
1033         break;
1034
1035     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1036         free_BN(&sig->signature.elgamal.r);
1037         free_BN(&sig->signature.elgamal.s);
1038         break;
1039
1040     case OPS_PKA_PRIVATE00:
1041     case OPS_PKA_PRIVATE01:
1042     case OPS_PKA_PRIVATE02:
1043     case OPS_PKA_PRIVATE03:
1044     case OPS_PKA_PRIVATE04:
1045     case OPS_PKA_PRIVATE05:
1046     case OPS_PKA_PRIVATE06:
1047     case OPS_PKA_PRIVATE07:
1048     case OPS_PKA_PRIVATE08:
1049     case OPS_PKA_PRIVATE09:
1050     case OPS_PKA_PRIVATE10:
1051         free_unknown_sig_pka(&sig->signature.unknown);
1052         break;
1053
1054     default:
1055         assert(0);
1056         }
1057     }
1058
1059 /** Parse a version 3 signature.
1060  *
1061  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1062  *
1063  * Once the signature has been parsed successfully, it is passed to the callback.
1064  *
1065  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
1066  * \param *reader       Our reader
1067  * \param *cb           The callback
1068  * \return              1 on success, 0 on error
1069  *
1070  * \see RFC2440bis-12 5.2.2
1071  */
1072 static int parse_v3_signature(ops_region_t *region,
1073                               ops_parse_info_t *parse_info)
1074     {
1075     unsigned char c[1];
1076     ops_parser_content_t content;
1077
1078     C.signature.version=OPS_V3;
1079
1080     /* hash info length */
1081     if(!limited_read(c,1,region,parse_info))
1082         return 0;
1083     if(c[0] != 5)
1084         ERRP(parse_info,"bad hash info length");
1085
1086     if(!limited_read(c,1,region,parse_info))
1087         return 0;
1088     C.signature.type=c[0];
1089     /* XXX: check signature type */
1090
1091     if(!limited_read_time(&C.signature.creation_time,region,parse_info))
1092         return 0;
1093     C.signature.creation_time_set=ops_true;
1094
1095     if(!limited_read(C.signature.signer_id,OPS_KEY_ID_SIZE,region,parse_info))
1096         return 0;
1097     C.signature.signer_id_set=ops_true;
1098
1099     if(!limited_read(c,1,region,parse_info))
1100         return 0;
1101     C.signature.key_algorithm=c[0];
1102     /* XXX: check algorithm */
1103
1104     if(!limited_read(c,1,region,parse_info))
1105         return 0;
1106     C.signature.hash_algorithm=c[0];
1107     /* XXX: check algorithm */
1108    
1109     if(!limited_read(C.signature.hash2,2,region,parse_info))
1110         return 0;
1111
1112     switch(C.signature.key_algorithm)
1113         {
1114     case OPS_PKA_RSA:
1115     case OPS_PKA_RSA_SIGN_ONLY:
1116         if(!limited_read_mpi(&C.signature.signature.rsa.sig,region,parse_info))
1117             return 0;
1118         break;
1119
1120     case OPS_PKA_DSA:
1121         if(!limited_read_mpi(&C.signature.signature.dsa.r,region,parse_info)
1122            || !limited_read_mpi(&C.signature.signature.dsa.s,region,parse_info))
1123             return 0;
1124         break;
1125
1126     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1127         if(!limited_read_mpi(&C.signature.signature.elgamal.r,region,parse_info)
1128            || !limited_read_mpi(&C.signature.signature.elgamal.s,region,parse_info))
1129             return 0;
1130         break;
1131
1132     default:
1133         ERR1P(parse_info,"Bad signature key algorithm (%d)",C.signature.key_algorithm);
1134         }
1135
1136     if(region->length_read != region->length)
1137         ERR1P(parse_info,"Unconsumed data (%d)",region->length-region->length_read);
1138
1139     CBP(parse_info,OPS_PTAG_CT_SIGNATURE,&content);
1140
1141     return 1;
1142     }
1143
1144 /** Parse one signature sub-packet.
1145  *
1146  * Version 4 signatures can have an arbitrary amount of (hashed and unhashed) subpackets.  Subpackets are used to hold
1147  * optional attributes of subpackets.
1148  *
1149  * This function parses one such signature subpacket.
1150  *
1151  * Once the subpacket has been parsed successfully, it is passed to the callback.
1152  *
1153  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire subpacket.
1154  * \param *reader       Our reader
1155  * \param *cb           The callback
1156  * \return              1 on success, 0 on error
1157  *
1158  * \see RFC2440bis-12 5.2.3
1159  */
1160 static int parse_one_signature_subpacket(ops_signature_t *sig,
1161                                          ops_region_t *region,
1162                                          ops_parse_info_t *parse_info)
1163     {
1164     ops_region_t subregion;
1165     unsigned char c[1];
1166     ops_parser_content_t content;
1167     unsigned t8,t7;
1168     ops_boolean_t read=ops_true;
1169     unsigned char bool[1];
1170
1171     ops_init_subregion(&subregion,region);
1172     if(!limited_read_new_length(&subregion.length,region,parse_info))
1173         return 0;
1174
1175     if(subregion.length > region->length)
1176         ERRP(parse_info,"Subpacket too long");
1177
1178     if(!limited_read(c,1,&subregion,parse_info))
1179         return 0;
1180
1181     t8=(c[0]&0x7f)/8;
1182     t7=1 << (c[0]&7);
1183
1184     content.critical=c[0] >> 7;
1185     content.tag=OPS_PTAG_SIGNATURE_SUBPACKET_BASE+(c[0]&0x7f);
1186
1187     /* Application wants it delivered raw */
1188     if(parse_info->ss_raw[t8]&t7)
1189         {
1190         C.ss_raw.tag=content.tag;
1191         C.ss_raw.length=subregion.length-1;
1192         C.ss_raw.raw=malloc(C.ss_raw.length);
1193         if(!limited_read(C.ss_raw.raw,C.ss_raw.length,&subregion,parse_info))
1194             return 0;
1195         CBP(parse_info,OPS_PTAG_RAW_SS,&content);
1196         return 1;
1197         }
1198
1199     switch(content.tag)
1200         {
1201     case OPS_PTAG_SS_CREATION_TIME:
1202     case OPS_PTAG_SS_EXPIRATION_TIME:
1203     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
1204         if(!limited_read_time(&C.ss_time.time,&subregion,parse_info))
1205             return 0;
1206         if(content.tag == OPS_PTAG_SS_CREATION_TIME)
1207             {
1208             sig->creation_time=C.ss_time.time;
1209             sig->creation_time_set=ops_true;
1210             }
1211         break;
1212
1213     case OPS_PTAG_SS_TRUST:
1214         if(!limited_read(&C.ss_trust.level,1,&subregion,parse_info)
1215            || !limited_read(&C.ss_trust.amount,1,&subregion,parse_info))
1216             return 0;
1217         break;
1218
1219     case OPS_PTAG_SS_REVOCABLE:
1220         if(!limited_read(bool,1,&subregion,parse_info))
1221             return 0;
1222         C.ss_revocable.revocable=!!bool;
1223         break;
1224
1225     case OPS_PTAG_SS_ISSUER_KEY_ID:
1226         if(!limited_read(C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE,
1227                              &subregion,parse_info))
1228             return 0;
1229         memcpy(sig->signer_id,C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE);
1230         sig->signer_id_set=ops_true;
1231         break;
1232
1233     case OPS_PTAG_SS_PREFERRED_SKA:
1234         if(!read_data(&C.ss_preferred_ska.data,&subregion,parse_info))
1235             return 0;
1236         break;
1237                                
1238     case OPS_PTAG_SS_PREFERRED_HASH:
1239         if(!read_data(&C.ss_preferred_hash.data,&subregion,parse_info))
1240             return 0;
1241         break;
1242                                
1243     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
1244         if(!read_data(&C.ss_preferred_compression.data,&subregion,parse_info))
1245             return 0;
1246         break;
1247                                
1248     case OPS_PTAG_SS_PRIMARY_USER_ID:
1249         if(!limited_read (bool,1,&subregion,parse_info))
1250             return 0;
1251         C.ss_primary_user_id.primary_user_id = !!bool;
1252         break;
1253  
1254     case OPS_PTAG_SS_KEY_FLAGS:
1255         if(!read_data(&C.ss_key_flags.data,&subregion,parse_info))
1256             return 0;
1257         break;
1258
1259     case OPS_PTAG_SS_KEY_SERVER_PREFS:
1260         if(!read_data(&C.ss_key_server_prefs.data,&subregion,parse_info))
1261             return 0;
1262         break;
1263
1264     case OPS_PTAG_SS_FEATURES:
1265         if(!read_data(&C.ss_features.data,&subregion,parse_info))
1266             return 0;
1267         break;
1268
1269     case OPS_PTAG_SS_SIGNERS_USER_ID:
1270         if(!read_unsigned_string(&C.ss_signers_user_id.user_id,&subregion,parse_info))
1271             return 0;
1272         break;
1273
1274     case OPS_PTAG_SS_NOTATION_DATA:
1275         if(!limited_read_data(&C.ss_notation_data.flags,4,&subregion,parse_info))
1276             return 0;
1277         if(!limited_read_size_t_scalar(&C.ss_notation_data.name.len,2,
1278                                        &subregion,parse_info))
1279             return 0;
1280         if(!limited_read_size_t_scalar(&C.ss_notation_data.value.len,2,
1281                                        &subregion,parse_info))
1282             return 0;
1283         if(!limited_read_data(&C.ss_notation_data.name,
1284                               C.ss_notation_data.name.len,&subregion,parse_info))
1285             return 0;
1286         if(!limited_read_data(&C.ss_notation_data.value,
1287                               C.ss_notation_data.value.len,&subregion,parse_info))
1288             return 0;
1289         break;
1290
1291     case OPS_PTAG_SS_POLICY_URL:
1292         if(!read_string(&C.ss_policy_url.text,&subregion,parse_info))
1293             return 0;
1294         break;
1295
1296     case OPS_PTAG_SS_REGEXP:
1297         if(!read_string(&C.ss_regexp.text,&subregion, parse_info))
1298             return 0;
1299         break;
1300
1301     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
1302         if(!read_string(&C.ss_preferred_key_server.text,&subregion,parse_info))
1303             return 0;
1304         break;
1305
1306     case OPS_PTAG_SS_USERDEFINED00:
1307     case OPS_PTAG_SS_USERDEFINED01:
1308     case OPS_PTAG_SS_USERDEFINED02:
1309     case OPS_PTAG_SS_USERDEFINED03:
1310     case OPS_PTAG_SS_USERDEFINED04:
1311     case OPS_PTAG_SS_USERDEFINED05:
1312     case OPS_PTAG_SS_USERDEFINED06:
1313     case OPS_PTAG_SS_USERDEFINED07:
1314     case OPS_PTAG_SS_USERDEFINED08:
1315     case OPS_PTAG_SS_USERDEFINED09:
1316     case OPS_PTAG_SS_USERDEFINED10:
1317         if(!read_data(&C.ss_userdefined.data,&subregion,parse_info))
1318             return 0;
1319         break;
1320
1321     case OPS_PTAG_SS_RESERVED:
1322         if(!read_data(&C.ss_unknown.data,&subregion,parse_info))
1323             return 0;
1324         break;
1325
1326     case OPS_PTAG_SS_REVOCATION_REASON:
1327         /* first byte is the machine-readable code */
1328         if(!limited_read(&C.ss_revocation_reason.code,1,&subregion,parse_info))
1329             return 0;
1330
1331         /* the rest is a human-readable UTF-8 string */
1332         if(!read_string(&C.ss_revocation_reason.text,&subregion,parse_info))
1333             return 0;
1334         break;
1335
1336     case OPS_PTAG_SS_REVOCATION_KEY:
1337         /* octet 0 = class. Bit 0x80 must be set */
1338         if(!limited_read (&C.ss_revocation_key.class,1,&subregion,parse_info))
1339             return 0;
1340         if(!(C.ss_revocation_key.class&0x80))
1341             {
1342             printf("Warning: OPS_PTAG_SS_REVOCATION_KEY class: "
1343                    "Bit 0x80 should be set\n");
1344             return 0;
1345             }
1346  
1347         /* octet 1 = algid */
1348         if(!limited_read(&C.ss_revocation_key.algid,1,&subregion,parse_info))
1349             return 0;
1350  
1351         /* octets 2-21 = fingerprint */
1352         if(!limited_read(&C.ss_revocation_key.fingerprint[0],20,&subregion,
1353                          parse_info))
1354             return 0;
1355         break;
1356  
1357     default:
1358         if(parse_info->ss_parsed[t8]&t7)
1359             ERR1P(parse_info,"Unknown signature subpacket type (%d)",
1360                   c[0]&0x7f);
1361         read=ops_false;
1362         break;
1363         }
1364
1365     /* Application doesn't want it delivered parsed */
1366     if(!(parse_info->ss_parsed[t8]&t7))
1367         {
1368         if(content.critical)
1369             ERR1P(parse_info,"Critical signature subpacket ignored (%d)",
1370                   c[0]&0x7f);
1371         if(!read && !limited_skip(subregion.length-1,&subregion,parse_info))
1372             return 0;
1373         //      printf("skipped %d length %d\n",c[0]&0x7f,subregion.length);
1374         if(read)
1375             ops_parser_content_free(&content);
1376         return 1;
1377         }
1378
1379     if(read && subregion.length_read != subregion.length)
1380         ERR1P(parse_info,"Unconsumed data (%d)", subregion.length-subregion.length_read);
1381  
1382     CBP(parse_info,content.tag,&content);
1383
1384     return 1;
1385     }
1386
1387 /*! Free the memory used when parsing this signature sub-packet type */
1388 void ops_ss_preferred_ska_free(ops_ss_preferred_ska_t *ss_preferred_ska)
1389     {
1390     data_free(&ss_preferred_ska->data);
1391     }
1392
1393 /*! Free the memory used when parsing this signature sub-packet type */
1394 void ops_ss_preferred_hash_free(ops_ss_preferred_hash_t *ss_preferred_hash)
1395     {
1396     data_free(&ss_preferred_hash->data);
1397     }
1398
1399 /*! Free the memory used when parsing this signature sub-packet type */
1400 void ops_ss_preferred_compression_free(ops_ss_preferred_compression_t *ss_preferred_compression)
1401     {
1402     data_free(&ss_preferred_compression->data);
1403     }
1404
1405 /*! Free the memory used when parsing this signature sub-packet type */
1406 void ops_ss_key_flags_free(ops_ss_key_flags_t *ss_key_flags)
1407     {
1408     data_free(&ss_key_flags->data);
1409     }
1410
1411 /*! Free the memory used when parsing this signature sub-packet type */
1412 void ops_ss_features_free(ops_ss_features_t *ss_features)
1413     {
1414     data_free(&ss_features->data);
1415     }
1416
1417 /*! Free the memory used when parsing this signature sub-packet type */
1418 void ops_ss_key_server_prefs_free(ops_ss_key_server_prefs_t *ss_key_server_prefs)
1419     {
1420     data_free(&ss_key_server_prefs->data);
1421     }
1422
1423 /** Parse several signature subpackets.
1424  *
1425  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1426  * This function parses this length and then calls parse_one_signature_subpacket() for each subpacket until the
1427  * entire set is consumed.
1428  *
1429  * This function does not call the callback directly, parse_one_signature_subpacket() does for each subpacket.
1430  *
1431  * \param *ptag         Pointer to the Packet Tag.
1432  * \param *reader       Our reader
1433  * \param *cb           The callback
1434  * \return              1 on success, 0 on error
1435  *
1436  * \see RFC2440bis-12 5.2.3
1437  */
1438 static int parse_signature_subpackets(ops_signature_t *sig,
1439                                       ops_region_t *region,
1440                                       ops_parse_info_t *parse_info)
1441     {
1442     ops_region_t subregion;
1443     ops_parser_content_t content;
1444
1445     ops_init_subregion(&subregion,region);
1446     if(!limited_read_scalar(&subregion.length,2,region,parse_info))
1447         return 0;
1448
1449     if(subregion.length > region->length)
1450         ERRP(parse_info,"Subpacket set too long");
1451
1452     while(subregion.length_read < subregion.length)
1453         if(!parse_one_signature_subpacket(sig,&subregion,parse_info))
1454             return 0;
1455
1456     if(subregion.length_read != subregion.length)
1457         {
1458         if(!limited_skip(subregion.length-subregion.length_read,&subregion,
1459                          parse_info))
1460             ERRP(parse_info,"Read failed while recovering from subpacket length mismatch");
1461         ERRP(parse_info,"Subpacket length mismatch");
1462         }
1463
1464     return 1;
1465     }
1466
1467 /** Parse a version 4 signature.
1468  *
1469  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1470  *
1471  * Once the signature packet has been parsed successfully, it is passed to the callback.
1472  *
1473  * \param *ptag         Pointer to the Packet Tag.
1474  * \param *reader       Our reader
1475  * \param *cb           The callback
1476  * \return              1 on success, 0 on error
1477  *
1478  * \see RFC2440bis-12 5.2.3
1479  */
1480 static int parse_v4_signature(ops_region_t *region,ops_parse_info_t *parse_info,
1481                               size_t v4_hashed_data_start)
1482     {
1483     unsigned char c[1];
1484     ops_parser_content_t content;
1485
1486     memset(&C.signature,'\0',sizeof C.signature);
1487     C.signature.version=OPS_V4;
1488     C.signature.v4_hashed_data_start=v4_hashed_data_start;
1489
1490     if(!limited_read(c,1,region,parse_info))
1491         return 0;
1492     C.signature.type=c[0];
1493     /* XXX: check signature type */
1494
1495     if(!limited_read(c,1,region,parse_info))
1496         return 0;
1497     C.signature.key_algorithm=c[0];
1498     /* XXX: check algorithm */
1499
1500     if(!limited_read(c,1,region,parse_info))
1501         return 0;
1502     C.signature.hash_algorithm=c[0];
1503     /* XXX: check algorithm */
1504
1505     CBP(parse_info,OPS_PTAG_CT_SIGNATURE_HEADER,&content);
1506
1507     if(!parse_signature_subpackets(&C.signature,region,parse_info))
1508         return 0;
1509     C.signature.v4_hashed_data_length=parse_info->rinfo.alength
1510         -C.signature.v4_hashed_data_start;
1511
1512     if(!parse_signature_subpackets(&C.signature,region,parse_info))
1513         return 0;
1514    
1515     if(!limited_read(C.signature.hash2,2,region,parse_info))
1516         return 0;
1517
1518     switch(C.signature.key_algorithm)
1519         {
1520     case OPS_PKA_RSA:
1521         if(!limited_read_mpi(&C.signature.signature.rsa.sig,region,parse_info))
1522             return 0;
1523         break;
1524
1525     case OPS_PKA_DSA:
1526         if(!limited_read_mpi(&C.signature.signature.dsa.r,region,parse_info))
1527             ERRP(parse_info,"Error reading DSA r field in signature");
1528         if (!limited_read_mpi(&C.signature.signature.dsa.s,region,parse_info))
1529             ERRP(parse_info,"Error reading DSA s field in signature");
1530         break;
1531
1532     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1533         if(!limited_read_mpi(&C.signature.signature.elgamal.r,region,parse_info)
1534            || !limited_read_mpi(&C.signature.signature.elgamal.s,region,parse_info))
1535             return 0;
1536         break;
1537
1538     case OPS_PKA_PRIVATE00:
1539     case OPS_PKA_PRIVATE01:
1540     case OPS_PKA_PRIVATE02:
1541     case OPS_PKA_PRIVATE03:
1542     case OPS_PKA_PRIVATE04:
1543     case OPS_PKA_PRIVATE05:
1544     case OPS_PKA_PRIVATE06:
1545     case OPS_PKA_PRIVATE07:
1546     case OPS_PKA_PRIVATE08:
1547     case OPS_PKA_PRIVATE09:
1548     case OPS_PKA_PRIVATE10:
1549         if (!read_data(&C.signature.signature.unknown.data,region,parse_info))
1550             return 0;
1551         break;
1552
1553     default:
1554         ERR1P(parse_info,"Bad v4 signature key algorithm (%d)",
1555               C.signature.key_algorithm);
1556         }
1557
1558     if(region->length_read != region->length)
1559         ERR1P(parse_info,"Unconsumed data (%d)",
1560               region->length-region->length_read);
1561
1562     CBP(parse_info,OPS_PTAG_CT_SIGNATURE_FOOTER,&content);
1563
1564     return 1;
1565     }
1566
1567 /** Parse a signature subpacket.
1568  *
1569  * This function calls the appropriate function to handle v3 or v4 signatures.
1570  *
1571  * Once the signature packet has been parsed successfully, it is passed to the callback.
1572  *
1573  * \param *ptag         Pointer to the Packet Tag.
1574  * \param *reader       Our reader
1575  * \param *cb           The callback
1576  * \return              1 on success, 0 on error
1577  */
1578 static int parse_signature(ops_region_t *region,ops_parse_info_t *parse_info)
1579     {
1580     unsigned char c[1];
1581     ops_parser_content_t content;
1582     size_t v4_hashed_data_start;
1583
1584     assert(region->length_read == 0);  /* We should not have read anything so far */
1585
1586     memset(&content,'\0',sizeof content);
1587
1588     v4_hashed_data_start=parse_info->rinfo.alength;
1589     if(!limited_read(c,1,region,parse_info))
1590         return 0;
1591
1592     if(c[0] == 2 || c[0] == 3)
1593         return parse_v3_signature(region,parse_info);
1594     else if(c[0] == 4)
1595         return parse_v4_signature(region,parse_info,v4_hashed_data_start);
1596     ERR1P(parse_info,"Bad signature version (%d)",c[0]);
1597     }
1598
1599 static int parse_compressed(ops_region_t *region,ops_parse_info_t *parse_info)
1600     {
1601     unsigned char c[1];
1602     ops_parser_content_t content;
1603
1604     if(!limited_read(c,1,region,parse_info))
1605         return 0;
1606
1607     C.compressed.type=c[0];
1608
1609     CBP(parse_info,OPS_PTAG_CT_COMPRESSED,&content);
1610
1611     /* The content of a compressed data packet is more OpenPGP packets
1612        once decompressed, so recursively handle them */
1613
1614     return ops_decompress(region,parse_info);
1615     }
1616
1617 static int parse_one_pass(ops_region_t *region,ops_parse_info_t *parse_info)
1618     {
1619     unsigned char c[1];
1620     ops_parser_content_t content;
1621
1622     if(!limited_read(&C.one_pass_signature.version,1,region,parse_info))
1623         return 0;
1624     if(C.one_pass_signature.version != 3)
1625         ERR1P(parse_info,"Bad one-pass signature version (%d)",
1626              C.one_pass_signature.version);
1627
1628     if(!limited_read(c,1,region,parse_info))
1629         return 0;
1630     C.one_pass_signature.sig_type=c[0];
1631
1632     if(!limited_read(c,1,region,parse_info))
1633         return 0;
1634     C.one_pass_signature.hash_algorithm=c[0];
1635
1636     if(!limited_read(c,1,region,parse_info))
1637         return 0;
1638     C.one_pass_signature.key_algorithm=c[0];
1639
1640     if(!limited_read(C.one_pass_signature.keyid,
1641                          sizeof C.one_pass_signature.keyid,region,parse_info))
1642         return 0;
1643
1644     if(!limited_read(c,1,region,parse_info))
1645         return 0;
1646     C.one_pass_signature.nested=!!c[0];
1647
1648     CBP(parse_info,OPS_PTAG_CT_ONE_PASS_SIGNATURE,&content);
1649
1650     return 1;
1651     }
1652
1653 /*! Free the memory used when parsing this signature sub-packet type */
1654 void ops_ss_userdefined_free(ops_ss_userdefined_t *ss_userdefined)
1655     {
1656     data_free(&ss_userdefined->data);
1657     }
1658
1659 /*! Free the memory used when parsing this signature sub-packet type */
1660 void ops_ss_reserved_free(ops_ss_unknown_t *ss_unknown)
1661     {
1662     data_free(&ss_unknown->data);
1663     }
1664
1665 /*! Free the memory used when parsing this signature sub-packet type */
1666 void ops_ss_notation_data_free(ops_ss_notation_data_t *ss_notation_data)
1667      {
1668      data_free(&ss_notation_data->name);
1669      data_free(&ss_notation_data->value);
1670      }
1671
1672 /*! Free the memory used when parsing this signature sub-packet type */
1673 void ops_ss_revocation_reason_free(ops_ss_revocation_reason_t *ss_revocation_reason)
1674     {
1675     string_free(&ss_revocation_reason->text);
1676     }
1677
1678 /*! Free the memory used when parsing this packet type */
1679 void ops_trust_free(ops_trust_t *trust)
1680     {
1681     data_free(&trust->data);
1682     }
1683
1684 static int
1685 parse_trust (ops_region_t *region, ops_parse_info_t *parse_info)
1686     {
1687     ops_parser_content_t content;
1688
1689     if(!read_data(&C.trust.data,region,parse_info))
1690             return 0;
1691
1692     CBP(parse_info,OPS_PTAG_CT_TRUST, &content);
1693
1694     return 1;
1695     }
1696
1697 static int parse_literal_data(ops_region_t *region,ops_parse_info_t *parse_info)
1698     {
1699     ops_parser_content_t content;
1700     unsigned char c[1];
1701
1702     if(!limited_read(c,1,region,parse_info))
1703         return 0;
1704     C.literal_data_header.format=c[0];
1705
1706     if(!limited_read(c,1,region,parse_info))
1707         return 0;
1708     if(!limited_read((unsigned char *)C.literal_data_header.filename,c[0],
1709                      region,parse_info))
1710         return 0;
1711     C.literal_data_header.filename[c[0]]='\0';
1712
1713     if(!limited_read_time(&C.literal_data_header.modification_time,region,parse_info))
1714         return 0;
1715
1716     CBP(parse_info,OPS_PTAG_CT_LITERAL_DATA_HEADER,&content);
1717
1718     while(region->length_read < region->length)
1719         {
1720         unsigned l=region->length-region->length_read;
1721
1722         if(l > sizeof C.literal_data_body.data)
1723             l=sizeof C.literal_data_body.data;
1724
1725         if(!limited_read(C.literal_data_body.data,l,region,parse_info))
1726             return 0;
1727
1728         C.literal_data_body.length=l;
1729
1730         CBP(parse_info,OPS_PTAG_CT_LITERAL_DATA_BODY,&content);
1731         }
1732
1733     return 1;
1734     }
1735
1736 /**
1737  * \ingroup Memory
1738  *
1739  * ops_secret_key_free() frees the memory associated with "key". Note that
1740  * the key itself is not freed.
1741  *
1742  * \param key
1743  */
1744
1745 void ops_secret_key_free(ops_secret_key_t *key)
1746     {
1747     switch(key->public_key.algorithm)
1748         {
1749     case OPS_PKA_RSA:
1750     case OPS_PKA_RSA_ENCRYPT_ONLY:
1751     case OPS_PKA_RSA_SIGN_ONLY:
1752         free_BN(&key->key.rsa.d);
1753         free_BN(&key->key.rsa.p);
1754         free_BN(&key->key.rsa.q);
1755         free_BN(&key->key.rsa.u);
1756         break;
1757
1758     case OPS_PKA_DSA:
1759         free_BN(&key->key.dsa.x);
1760         break;
1761
1762     default:
1763         fprintf(stderr,"Unknown algorithm: %d\n",key->public_key.algorithm);
1764         assert(0);
1765         }
1766
1767     ops_public_key_free(&key->public_key);
1768     }
1769
1770 static int consume_packet(ops_region_t *region,ops_parse_info_t *parse_info,
1771                           ops_boolean_t warn)
1772     {
1773     ops_data_t remainder;
1774     ops_parser_content_t content;
1775
1776     if(read_data(&remainder,region,parse_info))
1777         {
1778         /* now throw it away */
1779         data_free(&remainder);
1780         if(warn)
1781             ERRCODEP(parse_info,OPS_E_P_PACKET_CONSUMED);
1782         }
1783     else if(warn)
1784         WARNP(parse_info,"Problem consuming remainder of error packet.");
1785     else
1786         return 0;
1787
1788     return 1;
1789     }
1790
1791 static int parse_secret_key(ops_region_t *region,ops_parse_info_t *parse_info)
1792     {
1793     ops_parser_content_t content;
1794     unsigned char c[1];
1795     ops_decrypt_t decrypt;
1796     int ret=1;
1797     ops_region_t encregion;
1798     ops_region_t *saved_region=NULL;
1799     size_t checksum_length=2;
1800     ops_hash_t checkhash;
1801     int blocksize;
1802     ops_boolean_t crypted;
1803
1804     memset(&content,'\0',sizeof content);
1805     if(!parse_public_key_data(&C.secret_key.public_key,region,parse_info))
1806         return 0;
1807
1808     parse_info->reading_v3_secret=C.secret_key.public_key.version != OPS_V4;
1809
1810     if(!limited_read(c,1,region,parse_info))
1811         return 0;
1812     C.secret_key.s2k_usage=c[0];
1813
1814     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
1815         checksum_length=20;
1816
1817     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED
1818        || C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
1819         {
1820         if(!limited_read(c,1,region,parse_info))
1821             return 0;
1822         C.secret_key.algorithm=c[0];
1823
1824         if(!limited_read(c,1,region,parse_info))
1825             return 0;
1826         C.secret_key.s2k_specifier=c[0];
1827
1828         assert(C.secret_key.s2k_specifier == OPS_S2KS_SIMPLE
1829                || C.secret_key.s2k_specifier == OPS_S2KS_SALTED
1830                || C.secret_key.s2k_specifier == OPS_S2KS_ITERATED_AND_SALTED);
1831
1832         if(!limited_read(c,1,region,parse_info))
1833             return 0;
1834         C.secret_key.hash_algorithm=c[0];
1835
1836         if(C.secret_key.s2k_specifier != OPS_S2KS_SIMPLE
1837            && !limited_read(C.secret_key.salt,8,region,parse_info))
1838             return 0;
1839
1840         if(C.secret_key.s2k_specifier == OPS_S2KS_ITERATED_AND_SALTED)
1841             {
1842             if(!limited_read(c,1,region,parse_info))
1843                 return 0;
1844             C.secret_key.octet_count=(16+(c[0]&15)) << ((c[0] >> 4)+6);
1845             }
1846         }
1847     else if(C.secret_key.s2k_usage != OPS_S2KU_NONE)
1848         {
1849         // this is V3 style, looks just like a V4 simple hash
1850         C.secret_key.algorithm=C.secret_key.s2k_usage;
1851         C.secret_key.s2k_usage=OPS_S2KU_ENCRYPTED;
1852         C.secret_key.s2k_specifier=OPS_S2KS_SIMPLE;
1853         C.secret_key.hash_algorithm=OPS_HASH_MD5;
1854         }
1855
1856     crypted=C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED
1857         || C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED;
1858
1859     if(crypted)
1860         {
1861         int n;
1862         ops_parser_content_t pc;
1863         char *passphrase;
1864         unsigned char key[OPS_MAX_KEY_SIZE+OPS_MAX_HASH_SIZE];
1865         ops_hash_t hashes[(OPS_MAX_KEY_SIZE+OPS_MIN_HASH_SIZE-1)/OPS_MIN_HASH_SIZE];
1866         int keysize;
1867         int hashsize;
1868         size_t l;
1869
1870         blocksize=ops_block_size(C.secret_key.algorithm);
1871         assert(blocksize > 0 && blocksize <= OPS_MAX_BLOCK_SIZE);
1872
1873         if(!limited_read(C.secret_key.iv,blocksize,region,parse_info))
1874             return 0;
1875
1876         memset(&pc,'\0',sizeof pc);
1877         passphrase=NULL;
1878         pc.content.secret_key_passphrase.passphrase=&passphrase;
1879         pc.content.secret_key_passphrase.secret_key=&C.secret_key;
1880         CBP(parse_info,OPS_PARSER_CMD_GET_SK_PASSPHRASE,&pc);
1881         if(!passphrase)
1882             {
1883             if(!consume_packet(region,parse_info,ops_false))
1884                return 0;
1885
1886             CBP(parse_info,OPS_PTAG_CT_ENCRYPTED_SECRET_KEY,&content);
1887
1888             return 1;
1889             }
1890
1891         keysize=ops_key_size(C.secret_key.algorithm);
1892         assert(keysize > 0 && keysize <= OPS_MAX_KEY_SIZE);
1893
1894         hashsize=ops_hash_size(C.secret_key.hash_algorithm);
1895         assert(hashsize > 0 && hashsize <= OPS_MAX_HASH_SIZE);
1896
1897         for(n=0 ; n*hashsize < keysize ; ++n)
1898             {
1899             int i;
1900
1901             ops_hash_any(&hashes[n],C.secret_key.hash_algorithm);
1902             hashes[n].init(&hashes[n]);
1903             // preload hashes with zeroes...
1904             for(i=0 ; i < n ; ++i)
1905                 hashes[n].add(&hashes[n],"",1);
1906             }
1907
1908         l=strlen(passphrase);
1909
1910         for(n=0 ; n*hashsize < keysize ; ++n)
1911             {
1912             unsigned i;
1913
1914             switch(C.secret_key.s2k_specifier)
1915                 {
1916             case OPS_S2KS_SALTED:
1917                 hashes[n].add(&hashes[n],C.secret_key.salt,OPS_SALT_SIZE);
1918                 // flow through...
1919             case OPS_S2KS_SIMPLE:
1920                 hashes[n].add(&hashes[n],passphrase,l);
1921                 break;
1922
1923             case OPS_S2KS_ITERATED_AND_SALTED:
1924                 for(i=0 ; i < C.secret_key.octet_count ; i+=l+OPS_SALT_SIZE)
1925                     {
1926                     int j=l+OPS_SALT_SIZE;
1927
1928                     if(i+j > C.secret_key.octet_count && i != 0)
1929                         j=C.secret_key.octet_count-i;
1930
1931                     hashes[n].add(&hashes[n],C.secret_key.salt,
1932                                   j > OPS_SALT_SIZE ? OPS_SALT_SIZE : j);
1933                     if(j > OPS_SALT_SIZE)
1934                         hashes[n].add(&hashes[n],passphrase,j-OPS_SALT_SIZE);
1935                     }
1936                        
1937                 }
1938             }
1939
1940         for(n=0 ; n*hashsize < keysize ; ++n)
1941             {
1942             int r=hashes[n].finish(&hashes[n],key+n*hashsize);
1943             assert(r == hashsize);
1944             }
1945
1946         free(passphrase);
1947
1948         ops_decrypt_any(&decrypt,C.secret_key.algorithm);
1949         decrypt.set_iv(&decrypt,C.secret_key.iv);
1950         decrypt.set_key(&decrypt,key);
1951
1952         ops_reader_push_decrypt(parse_info,&decrypt,region);
1953
1954         /* Since all known encryption for PGP doesn't compress, we can
1955            limit to the same length as the current region (for now).
1956         */
1957         ops_init_subregion(&encregion,NULL);
1958         encregion.length=region->length-region->length_read;
1959         if(C.secret_key.public_key.version != OPS_V4)
1960             encregion.length-=2;
1961         saved_region=region;
1962         region=&encregion;
1963         }
1964
1965     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
1966         {
1967         ops_hash_sha1(&checkhash);
1968         ops_reader_push_hash(parse_info,&checkhash);
1969         }
1970     else
1971         ops_reader_push_sum16(parse_info);
1972
1973     switch(C.secret_key.public_key.algorithm)
1974         {
1975     case OPS_PKA_RSA:
1976     case OPS_PKA_RSA_ENCRYPT_ONLY:
1977     case OPS_PKA_RSA_SIGN_ONLY:
1978         if(!limited_read_mpi(&C.secret_key.key.rsa.d,region,parse_info)
1979            || !limited_read_mpi(&C.secret_key.key.rsa.p,region,parse_info)
1980            || !limited_read_mpi(&C.secret_key.key.rsa.q,region,parse_info)
1981            || !limited_read_mpi(&C.secret_key.key.rsa.u,region,parse_info))
1982             ret=0;
1983         break;
1984
1985     case OPS_PKA_DSA:
1986         if(!limited_read_mpi(&C.secret_key.key.dsa.x,region,parse_info))
1987             ret=0;
1988         break;
1989
1990     default:
1991         fprintf(stderr,"Unexpected aglorithm: %d\n",
1992                 C.secret_key.public_key.algorithm);
1993         ret=0;
1994         assert(0);
1995         }
1996
1997     parse_info->reading_v3_secret=ops_false;
1998
1999     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
2000         {
2001         unsigned char hash[20];
2002
2003         ops_reader_pop_hash(parse_info);
2004         checkhash.finish(&checkhash,hash);
2005            
2006         if(crypted && C.secret_key.public_key.version != OPS_V4)
2007             {
2008             ops_reader_pop_decrypt(parse_info);
2009             region=saved_region;
2010             }
2011
2012         if(ret)
2013             {
2014             if(!limited_read(C.secret_key.checkhash,20,region,parse_info))
2015                 return 0;
2016
2017             if(memcmp(hash,C.secret_key.checkhash,20))
2018                 ERRP(parse_info,"Hash mismatch in secret key");
2019             }
2020         }
2021     else
2022         {
2023         unsigned short sum;
2024
2025         sum=ops_reader_pop_sum16(parse_info);
2026
2027         if(crypted && C.secret_key.public_key.version != OPS_V4)
2028             {
2029             ops_reader_pop_decrypt(parse_info);
2030             region=saved_region;
2031             }
2032
2033         if(ret)
2034             {
2035             if(!limited_read_scalar(&C.secret_key.checksum,2,region,
2036                                     parse_info))
2037                 return 0;
2038
2039             if(sum != C.secret_key.checksum)
2040                 ERRP(parse_info,"Checksum mismatch in secret key");
2041             }
2042         }
2043
2044     if(crypted && C.secret_key.public_key.version == OPS_V4)
2045         ops_reader_pop_decrypt(parse_info);
2046
2047     assert(!ret || region->length_read == region->length);
2048
2049     if(!ret)
2050         return 0;
2051
2052     CBP(parse_info,OPS_PTAG_CT_SECRET_KEY,&content);
2053
2054     return 1;
2055     }
2056
2057 static int parse_pk_session_key(ops_region_t *region,
2058                                 ops_parse_info_t *parse_info)
2059     {
2060     unsigned char c[1];
2061     ops_parser_content_t content;
2062
2063     if(!limited_read(c,1,region,parse_info))
2064         return 0;
2065     C.pk_session_key.version=c[0];
2066     if(C.pk_session_key.version != OPS_PKSK_V3)
2067         ERR1P(parse_info,
2068               "Bad public-key encrypted session key version (%d)",
2069               C.pk_session_key.version);
2070
2071     if(!limited_read(C.pk_session_key.key_id,
2072                      sizeof C.pk_session_key.key_id,region,parse_info))
2073         return 0;
2074
2075     if(!limited_read(c,1,region,parse_info))
2076         return 0;
2077     C.pk_session_key.algorithm=c[0];
2078     switch(C.pk_session_key.algorithm)
2079         {
2080     case OPS_PKA_RSA:
2081         if(!limited_read_mpi(&C.pk_session_key.parameters.rsa.encrypted_m,
2082                              region,parse_info))
2083             return 0;
2084         break;
2085
2086     case OPS_PKA_ELGAMAL:
2087         if(!limited_read_mpi(&C.pk_session_key.parameters.elgamal.g_to_k,
2088                              region,parse_info)
2089            || limited_read_mpi(&C.pk_session_key.parameters.elgamal.encrypted_m,
2090                              region,parse_info))
2091             return 0;
2092         break;
2093
2094     default:
2095         ERR1P(parse_info,
2096               "Unknown public key algorithm in session key (%d)",
2097               C.pk_session_key.algorithm);
2098         return 0;
2099         }
2100
2101     CBP(parse_info,OPS_PTAG_CT_PK_SESSION_KEY,&content);
2102
2103     return 1;
2104     }
2105
2106 static int parse_se_data(ops_region_t *region,ops_parse_info_t *parse_info)
2107     {
2108     ops_parser_content_t content;
2109
2110     /* there's no info to go with this, so just announce it */
2111     CBP(parse_info,OPS_PTAG_CT_SE_DATA,&content);
2112
2113     /* The content of an encrypted data packet is more OpenPGP packets
2114        once decompressed, so recursively handle them */
2115     return ops_decrypt_data(region,parse_info);
2116     }
2117
2118 /** Parse one packet.
2119  *
2120  * This function parses the packet tag.  It computes the value of the
2121  * content tag and then calls the appropriate function to handle the
2122  * content.
2123  *
2124  * \param *parse_info   How to parse
2125  * \param *pktlen       On return, will contain number of bytes in packet
2126  * \return 1 on success, 0 on error, -1 on EOF */
2127 static int ops_parse_one_packet(ops_parse_info_t *parse_info,
2128                                 unsigned long *pktlen)
2129     {
2130     unsigned char ptag[1];
2131     ops_reader_ret_t ret;
2132     ops_parser_content_t content;
2133     int r;
2134     ops_region_t region;
2135     unsigned one=1;
2136     ops_boolean_t indeterminate=ops_false;
2137
2138     C.ptag.position=parse_info->rinfo.position;
2139
2140     ret=base_read(ptag,&one,0,parse_info);
2141     if(ret == OPS_R_EOF || ret == OPS_R_EARLY_EOF)
2142         return -1;
2143
2144     *pktlen=0;
2145
2146     assert(ret == OPS_R_OK);
2147     if(!(*ptag&OPS_PTAG_ALWAYS_SET))
2148         {
2149         C.error.error="Format error (ptag bit not set)";
2150         CBP(parse_info,OPS_PARSER_ERROR,&content);
2151         return 0;
2152         }
2153     C.ptag.new_format=!!(*ptag&OPS_PTAG_NEW_FORMAT);
2154     if(C.ptag.new_format)
2155         {
2156         C.ptag.content_tag=*ptag&OPS_PTAG_NF_CONTENT_TAG_MASK;
2157         C.ptag.length_type=0;
2158         if(!read_new_length(&C.ptag.length,parse_info))
2159             return 0;
2160
2161         }
2162     else
2163         {
2164         C.ptag.content_tag=(*ptag&OPS_PTAG_OF_CONTENT_TAG_MASK)
2165             >> OPS_PTAG_OF_CONTENT_TAG_SHIFT;
2166         C.ptag.length_type=*ptag&OPS_PTAG_OF_LENGTH_TYPE_MASK;
2167         switch(C.ptag.length_type)
2168             {
2169         case OPS_PTAG_OF_LT_ONE_BYTE:
2170             ret=read_scalar(&C.ptag.length,1,parse_info);
2171             break;
2172
2173         case OPS_PTAG_OF_LT_TWO_BYTE:
2174             ret=read_scalar(&C.ptag.length,2,parse_info);
2175             break;
2176
2177         case OPS_PTAG_OF_LT_FOUR_BYTE:
2178             ret=read_scalar(&C.ptag.length,4,parse_info);
2179             break;
2180
2181         case OPS_PTAG_OF_LT_INDETERMINATE:
2182             C.ptag.length=0;
2183             indeterminate=ops_true;
2184             ret=OPS_R_OK;
2185             break;
2186             }
2187         if(ret == OPS_R_EOF || ret == OPS_R_EARLY_EOF)
2188             return -1;
2189         }
2190
2191     CBP(parse_info,OPS_PARSER_PTAG,&content);
2192
2193     ops_init_subregion(&region,NULL);
2194     region.length=C.ptag.length;
2195     region.indeterminate=indeterminate;
2196     switch(C.ptag.content_tag)
2197         {
2198     case OPS_PTAG_CT_SIGNATURE:
2199         r=parse_signature(&region,parse_info);
2200         break;
2201
2202     case OPS_PTAG_CT_PUBLIC_KEY:
2203     case OPS_PTAG_CT_PUBLIC_SUBKEY:
2204         r=parse_public_key(C.ptag.content_tag,&region,parse_info);
2205         break;
2206
2207     case OPS_PTAG_CT_TRUST:
2208         r=parse_trust(&region, parse_info);
2209         break;
2210      
2211     case OPS_PTAG_CT_USER_ID:
2212         r=parse_user_id(&region,parse_info);
2213         break;
2214
2215     case OPS_PTAG_CT_COMPRESSED:
2216         r=parse_compressed(&region,parse_info);
2217         break;
2218
2219     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
2220         r=parse_one_pass(&region,parse_info);
2221         break;
2222
2223     case OPS_PTAG_CT_LITERAL_DATA:
2224         r=parse_literal_data(&region,parse_info);
2225         break;
2226
2227     case OPS_PTAG_CT_USER_ATTRIBUTE:
2228         r=parse_user_attribute(&region,parse_info);
2229         break;
2230
2231     case OPS_PTAG_CT_SECRET_KEY:
2232         r=parse_secret_key(&region,parse_info);
2233         break;
2234
2235     case OPS_PTAG_CT_PK_SESSION_KEY:
2236         r=parse_pk_session_key(&region,parse_info);
2237         break;
2238
2239     case OPS_PTAG_CT_SE_DATA:
2240         r=parse_se_data(&region,parse_info);
2241         break;
2242
2243     default:
2244         format_error(&content,"Format error (unknown content tag %d)",
2245                      C.ptag.content_tag);
2246         ERRCODEP(parse_info,OPS_E_P_UNKNOWN_TAG);
2247         r=0;
2248         }
2249
2250     /* Ensure that the entire packet has been consumed */
2251
2252     if(region.length != region.length_read)
2253         consume_packet(&region,parse_info,ops_true);
2254
2255     /* set pktlen */
2256
2257     *pktlen=parse_info->rinfo.alength;
2258
2259     /* do callback on entire packet, if desired */
2260
2261     if(parse_info->rinfo.accumulate)
2262         {
2263         C.packet.length=parse_info->rinfo.alength;
2264         C.packet.raw=parse_info->rinfo.accumulated;
2265         parse_info->rinfo.accumulated=NULL;
2266         parse_info->rinfo.asize=0;
2267         CBP(parse_info,OPS_PARSER_PACKET_END,&content);
2268         }
2269     parse_info->rinfo.alength=0;
2270        
2271     return r ? 1 : 0;
2272     }
2273
2274 /**
2275  * \ingroup Parse
2276  *
2277  * ops_parse() parses packets from an input stream until EOF or error.
2278  *
2279  * All the necessary information for parsing should have been set up by the
2280  * calling function in "*parse_info" beforehand.
2281  *
2282  * That information includes :
2283  *
2284  * - a "reader" function to be used to get the data to be parsed
2285  *
2286  * - a "callback" function to be called when this library has identified
2287  * a parseable object within the data
2288  *
2289  * - whether the calling function wants the signature subpackets returned raw, parsed or not at all.
2290  *
2291  * \sa See Detailed Description for usage.
2292  *
2293  * \param *parse_info   How to parse
2294  * \return              1 on success in all packets, 0 on error in any packet
2295  * \todo Add some error checking to make sure *parse_info contains a sensible setup?
2296  */
2297
2298 int ops_parse(ops_parse_info_t *parse_info)
2299     {
2300     int r;
2301     unsigned long pktlen;
2302     do
2303         {
2304         r=ops_parse_one_packet(parse_info,&pktlen);
2305         //      offset+=pktlen;
2306         } while (r!=-1);
2307
2308     return parse_info->errors ? 0 : 1;
2309     }
2310
2311 #if 0
2312 /**
2313  *
2314  * \return 1 if success, 0 otherwise
2315  * XXX may not now be needed? RW
2316  */
2317
2318 int ops_parse_errs(ops_parse_info_t *parse_info, ops_ulong_list_t *errs)
2319     {
2320     unsigned err;
2321     int r;
2322     unsigned long pktlen;
2323     ops_reader_fd_arg_t *arg;
2324     int orig_acc;
2325
2326     /* can only handle ops_reader_fd for now */
2327
2328     if (parse_info->rinfo.reader != ops_reader_fd)
2329         {
2330         fprintf(stderr,"ops_parse_errs: can only handle ops_reader_fd\n");
2331         return 0;
2332         }
2333
2334     arg=parse_info->rinfo.arg;
2335
2336     /* store current state of accumulate flag */
2337
2338     orig_acc=parse_info->rinfo.accumulate;
2339
2340     /* set accumulate flag */
2341
2342     parse_info->rinfo.accumulate=1;
2343
2344     /* now parse each error in turn. */
2345
2346     for(err=0; err < errs->used ; err++)
2347         {
2348
2349         //      printf("\n***\n*** Error at offset %lu \n***\n",errs->ulongs[err]);
2350
2351         /* move stream to offset of error */
2352
2353         r=lseek(arg->fd,errs->ulongs[err],SEEK_SET);
2354         if (r==-1)
2355             {
2356             printf("error %d in first lseek to offset\n", errno);
2357             return 0;
2358             }
2359
2360         /* parse packet */
2361
2362         ops_parse_one_packet(parse_info,&pktlen);
2363
2364         }
2365
2366     /* restore accumulate flag original value */
2367     parse_info->rinfo.accumulate=orig_acc;
2368
2369     return 1;
2370     }
2371 #endif
2372
2373 /**
2374  * \ingroup Parse
2375  *
2376  * ops_parse_options() specifies whether one or more signature
2377  * subpacket types should be returned parsed or raw or ignored.
2378  *
2379  * \param       parse_info      Pointer to previously allocated structure
2380  * \param       tag     Packet tag. OPS_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
2381  * \param       type    Parse type
2382  * \todo XXX: Make all packet types optional, not just subpackets */
2383 void ops_parse_options(ops_parse_info_t *parse_info,
2384                        ops_content_tag_t tag,
2385                        ops_parse_type_t type)
2386     {
2387     int t8,t7;
2388
2389     if(tag == OPS_PTAG_SS_ALL)
2390         {
2391         int n;
2392
2393         for(n=0 ; n < 256 ; ++n)
2394             ops_parse_options(parse_info,OPS_PTAG_SIGNATURE_SUBPACKET_BASE+n,
2395                               type);
2396         return;
2397         }
2398
2399     assert(tag >= OPS_PTAG_SIGNATURE_SUBPACKET_BASE
2400            && tag <= OPS_PTAG_SIGNATURE_SUBPACKET_BASE+NTAGS-1);
2401     t8=(tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)/8;
2402     t7=1 << ((tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)&7);
2403     switch(type)
2404         {
2405     case OPS_PARSE_RAW:
2406         parse_info->ss_raw[t8] |= t7;
2407         parse_info->ss_parsed[t8] &= ~t7;
2408         break;
2409
2410     case OPS_PARSE_PARSED:
2411         parse_info->ss_raw[t8] &= ~t7;
2412         parse_info->ss_parsed[t8] |= t7;
2413         break;
2414
2415     case OPS_PARSE_IGNORE:
2416         parse_info->ss_raw[t8] &= ~t7;
2417         parse_info->ss_parsed[t8] &= ~t7;
2418         break;
2419         }
2420     }
2421
2422 ops_parse_info_t *ops_parse_info_new(void)
2423     { return ops_mallocz(sizeof(ops_parse_info_t)); }
2424
2425 void ops_parse_info_delete(ops_parse_info_t *pinfo)
2426     { free(pinfo); }
2427
2428 ops_reader_info_t *ops_parse_get_rinfo(ops_parse_info_t *pinfo)
2429     { return &pinfo->rinfo; }
2430
2431 void ops_parse_cb_set(ops_parse_info_t *pinfo,ops_parse_cb_t *cb,void *arg)
2432     {
2433     pinfo->cbinfo.cb=cb;
2434     pinfo->cbinfo.arg=arg;
2435     }
2436
2437 void ops_parse_cb_push(ops_parse_info_t *pinfo,ops_parse_cb_t *cb,void *arg)
2438     {
2439     ops_parse_cb_info_t *cbinfo=malloc(sizeof *cbinfo);
2440
2441     *cbinfo=pinfo->cbinfo;
2442     pinfo->cbinfo.next=cbinfo;
2443     ops_parse_cb_set(pinfo,cb,arg);
2444     }
2445
2446 void *ops_parse_cb_get_arg(ops_parse_cb_info_t *cbinfo)
2447     { return cbinfo->arg; }
2448
2449 ops_parse_cb_return_t ops_parse_cb(const ops_parser_content_t *content,
2450                                    ops_parse_cb_info_t *cbinfo)
2451     {
2452     if(cbinfo->cb)
2453         return cbinfo->cb(content,cbinfo);
2454     else
2455         return OPS_FINISHED;
2456     }
2457
2458 ops_parse_cb_return_t ops_parse_stacked_cb(const ops_parser_content_t *content,
2459                                            ops_parse_cb_info_t *cbinfo)
2460     { return ops_parse_cb(content,cbinfo->next); }
2461
2462 void ops_reader_set(ops_parse_info_t *pinfo,ops_reader_t *reader,void *arg)
2463     {
2464     pinfo->rinfo.reader=reader;
2465     pinfo->rinfo.arg=arg;
2466     }
2467
2468 void ops_reader_push(ops_parse_info_t *pinfo,ops_reader_t *reader,void *arg)
2469     {
2470     ops_reader_info_t *rinfo=malloc(sizeof *rinfo);
2471
2472     *rinfo=pinfo->rinfo;
2473     pinfo->rinfo.next=rinfo;
2474     rinfo->pinfo=pinfo;
2475     ops_reader_set(pinfo,reader,arg);
2476     }
2477
2478 void ops_reader_pop(ops_parse_info_t *pinfo)
2479     {
2480     ops_reader_info_t *next=pinfo->rinfo.next;
2481
2482     pinfo->rinfo=*next;
2483     free(next);
2484     }
2485
2486 void *ops_reader_get_arg(ops_reader_info_t *rinfo)
2487     { return rinfo->arg; }
2488
2489 void *ops_reader_get_arg_from_pinfo(ops_parse_info_t *pinfo)
2490     { return pinfo->rinfo.arg; }
2491
2492 ops_error_t *ops_parse_info_get_errors(ops_parse_info_t *pinfo)
2493     { return pinfo->errors; }
2494
2495 ops_decrypt_t *ops_parse_get_decrypt(ops_parse_info_t *pinfo)
2496     { return pinfo->decrypt; }
2497
2498 /* vim:set textwidth=120: */
2499 /* vim:set ts=8: */
Note: See TracBrowser for help on using the browser.