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

Revision 705 (checked in by ben, 3 years ago)

Fix gcc 4.6 warnings (one of which was an actual bug).

  • Property svn:keywords set to Id
Line 
1 /*
2  * Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
3  * All rights reserved.
4  * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
5  * their moral rights under the UK Copyright Design and Patents Act 1988 to
6  * be recorded as the authors of this copyright work.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9  * use this file except in compliance with the License.
10  *
11  * You may obtain a copy of the License at
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */
21
22 /** \file
23  * \brief Parser for OpenPGP packets
24  */
25
26 #include <openssl/cast.h>
27
28 #include <openpgpsdk/callback.h>
29 #include <openpgpsdk/packet.h>
30 #include <openpgpsdk/packet-parse.h>
31 #include <openpgpsdk/keyring.h>
32 #include <openpgpsdk/util.h>
33 #include <openpgpsdk/compress.h>
34 #include <openpgpsdk/errors.h>
35 #include <openpgpsdk/readerwriter.h>
36 #include <openpgpsdk/packet-show.h>
37 #include <openpgpsdk/std_print.h>
38 #include <openpgpsdk/create.h>
39 #include <openpgpsdk/hash.h>
40
41 #include "parse_local.h"
42
43 #include <assert.h>
44 #include <stdarg.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #ifndef WIN32
48 #include <unistd.h>
49 #endif
50 #include <errno.h>
51 #include <limits.h>
52
53 #include <openpgpsdk/final.h>
54
55 static int debug=0;
56
57 /**
58  * limited_read_data reads the specified amount of the subregion's data
59  * into a data_t structure
60  *
61  * \param data  Empty structure which will be filled with data
62  * \param len   Number of octets to read
63  * \param subregion
64  * \param pinfo How to parse
65  *
66  * \return 1 on success, 0 on failure
67  */
68 static int limited_read_data(ops_data_t *data,unsigned int len,
69                              ops_region_t *subregion,ops_parse_info_t *pinfo)
70     {
71     data->len = len;
72
73     assert(subregion->length-subregion->length_read >= len);
74
75     data->contents=malloc(data->len);
76     if (!data->contents)
77         return 0;
78
79     if (!ops_limited_read(data->contents, data->len,subregion,&pinfo->errors,
80                           &pinfo->rinfo,&pinfo->cbinfo))
81         return 0;
82    
83     return 1;
84     }
85
86 /**
87  * read_data reads the remainder of the subregion's data
88  * into a data_t structure
89  *
90  * \param data
91  * \param subregion
92  * \param pinfo
93  *
94  * \return 1 on success, 0 on failure
95  */
96 static int read_data(ops_data_t *data,ops_region_t *subregion,
97                      ops_parse_info_t *pinfo)
98     {
99     int len;
100
101     len=subregion->length-subregion->length_read;
102
103     if ( len >= 0 ) {
104         return(limited_read_data(data,len,subregion,pinfo));
105     }
106     return 0;
107     }
108
109 /**
110  * Reads the remainder of the subregion as a string.
111  * It is the user's responsibility to free the memory allocated here.
112  */
113
114 static int read_unsigned_string(unsigned char **str,ops_region_t *subregion,
115                                 ops_parse_info_t *pinfo)
116     {
117     int len=0;
118
119     len=subregion->length-subregion->length_read;
120
121     *str=malloc(len+1);
122     if(!(*str))
123         return 0;
124
125     if(len && !ops_limited_read(*str,len,subregion,&pinfo->errors,
126                                 &pinfo->rinfo,&pinfo->cbinfo))
127         return 0;
128
129     /*! ensure the string is NULL-terminated */
130
131     (*str)[len]='\0';
132
133     return 1;
134     }
135
136 static int read_string(char **str, ops_region_t *subregion, ops_parse_info_t *pinfo)
137     {
138     return (read_unsigned_string((unsigned char **)str, subregion, pinfo));
139     }
140
141 void ops_init_subregion(ops_region_t *subregion,ops_region_t *region)
142     {
143     memset(subregion,'\0',sizeof *subregion);
144     subregion->parent=region;
145     }
146
147 /*! macro to save typing */
148 #define C               content.content
149
150 /* XXX: replace ops_ptag_t with something more appropriate for limiting
151    reads */
152
153 /**
154  * low-level function to read data from reader function
155  *
156  * Use this function, rather than calling the reader directly.
157  *
158  * If the accumulate flag is set in *pinfo, the function
159  * adds the read data to the accumulated data, and updates
160  * the accumulated length. This is useful if, for example,
161  * the application wants access to the raw data as well as the
162  * parsed data.
163  *
164  * This function will also try to read the entire amount asked for, but not
165  * if it is over INT_MAX. Obviously many callers will know that they
166  * never ask for that much and so can avoid the extra complexity of
167  * dealing with return codes and filled-in lengths.
168  *
169  * \param *dest
170  * \param *plength
171  * \param flags
172  * \param *pinfo
173  *
174  * \return OPS_R_OK
175  * \return OPS_R_PARTIAL_READ
176  * \return OPS_R_EOF
177  * \return OPS_R_EARLY_EOF
178  *
179  * \sa #ops_reader_ret_t for details of return codes
180  */
181
182 static int sub_base_read(void *dest,size_t length,ops_error_t **errors,
183                          ops_reader_info_t *rinfo,ops_parse_cb_info_t *cbinfo)
184     {
185     size_t n;
186
187     /* reading more than this would look like an error */
188     if(length > INT_MAX)
189         length=INT_MAX;
190
191     for(n=0 ; n < length ; )
192         {
193         int r=rinfo->reader((char*)dest+n,length-n,errors,rinfo,cbinfo);
194
195         assert(r <= (int)(length-n));
196
197         // XXX: should we save the error and return what was read so far?
198         if(r < 0)
199             return r;
200
201         if(r == 0)
202             break;
203
204         n+=r;
205         }
206
207     if(n == 0)
208         return 0;
209
210     if(rinfo->accumulate)
211         {
212         assert(rinfo->asize >= rinfo->alength);
213         if(rinfo->alength+n > rinfo->asize)
214             {
215             rinfo->asize=rinfo->asize*2+n;
216             rinfo->accumulated=realloc(rinfo->accumulated,rinfo->asize);
217             }
218         assert(rinfo->asize >= rinfo->alength+n);
219         memcpy(rinfo->accumulated+rinfo->alength,dest,n);
220         }
221     // we track length anyway, because it is used for packet offsets
222     rinfo->alength+=n;
223     // and also the position
224     rinfo->position+=n;
225
226     return n;
227     }
228
229 int ops_stacked_read(void *dest,size_t length,ops_error_t **errors,
230                      ops_reader_info_t *rinfo,ops_parse_cb_info_t *cbinfo)
231     { return sub_base_read(dest,length,errors,rinfo->next,cbinfo); }
232
233 /* This will do a full read so long as length < MAX_INT */
234 static int base_read(unsigned char *dest,size_t length,
235                      ops_parse_info_t *pinfo)
236     {
237     return sub_base_read(dest,length,&pinfo->errors,&pinfo->rinfo,
238                          &pinfo->cbinfo);
239     }
240
241 /* Read a full size_t's worth. If the return is < than length, then
242  * *last_read tells you why - < 0 for an error, == 0 for EOF */
243
244 static size_t full_read(unsigned char *dest,size_t length,int *last_read,
245                         ops_error_t **errors,ops_reader_info_t *rinfo,
246                         ops_parse_cb_info_t *cbinfo)
247     {
248     size_t t;
249     int r=0; /* preset in case some loon calls with length == 0 */
250
251     for(t=0 ; t < length ; )
252         {
253         r=sub_base_read(dest+t,length-t,errors,rinfo,cbinfo);
254
255         if(r <= 0)
256             {
257             *last_read=r;
258             return t;
259             }
260
261         t+=r;
262         }
263
264     *last_read=r;
265
266     return t;
267     }
268        
269        
270
271 /** Read a scalar value of selected length from reader.
272  *
273  * Read an unsigned scalar value from reader in Big Endian representation.
274  *
275  * This function does not know or care about packet boundaries. It
276  * also assumes that an EOF is an error.
277  *
278  * \param *result       The scalar value is stored here
279  * \param *reader       Our reader
280  * \param length        How many bytes to read
281  * \return              ops_true on success, ops_false on failure
282  */
283 static ops_boolean_t _read_scalar(unsigned *result,unsigned length,
284                                     ops_parse_info_t *pinfo)
285     {
286     unsigned t=0;
287
288     assert (length <= sizeof(*result));
289
290     while(length--)
291         {
292         unsigned char c[1];
293         int r;
294
295         r=base_read(c,1,pinfo);
296         if(r != 1)
297             return ops_false;
298         t=(t << 8)+c[0];
299         }
300
301     *result=t;
302     return ops_true;
303     }
304
305 /**
306  * \ingroup Core_ReadPackets
307  * \brief Read bytes from a region within the packet.
308  *
309  * Read length bytes into the buffer pointed to by *dest. 
310  * Make sure we do not read over the packet boundary. 
311  * Updates the Packet Tag's ops_ptag_t::length_read.
312  *
313  * If length would make us read over the packet boundary, or if
314  * reading fails, we call the callback with an error.
315  *
316  * Note that if the region is indeterminate, this can return a short
317  * read - check region->last_read for the length. EOF is indicated by
318  * a success return and region->last_read == 0 in this case (for a
319  * region of known length, EOF is an error).
320  *
321  * This function makes sure to respect packet boundaries.
322  *
323  * \param dest          The destination buffer
324  * \param length        How many bytes to read
325  * \param region        Pointer to packet region
326  * \param errors    Error stack
327  * \param rinfo         Reader info
328  * \param cbinfo        Callback info
329  * \return              ops_true on success, ops_false on error
330  */
331 ops_boolean_t ops_limited_read(unsigned char *dest,size_t length,
332                                ops_region_t *region,ops_error_t **errors,
333                                ops_reader_info_t *rinfo,
334                                ops_parse_cb_info_t *cbinfo)
335     {
336     size_t r;
337     int lr;
338
339     if(!region->indeterminate && region->length_read+length > region->length)
340         {
341         OPS_ERROR(errors,OPS_E_P_NOT_ENOUGH_DATA,"Not enough data");
342         return ops_false;
343         }
344
345     r=full_read(dest,length,&lr,errors,rinfo,cbinfo);
346
347     if(lr < 0)
348         {
349         OPS_ERROR(errors,OPS_E_R_READ_FAILED,"Read failed");
350         return ops_false;
351         }
352
353     if(!region->indeterminate && r != length)
354         {
355         OPS_ERROR(errors,OPS_E_R_READ_FAILED,"Read failed");
356         return ops_false;
357         }
358
359     region->last_read=r;
360     do
361         {
362         region->length_read+=r;
363         assert(!region->parent || region->length <= region->parent->length);
364         }
365     while((region=region->parent));
366
367     return ops_true;
368     }
369
370 /**
371    \ingroup Core_ReadPackets
372    \brief Call ops_limited_read on next in stack
373 */
374 ops_boolean_t ops_stacked_limited_read(void *dest, unsigned length,
375                                        ops_region_t *region,
376                                        ops_error_t **errors,
377                                        ops_reader_info_t *rinfo,
378                                        ops_parse_cb_info_t *cbinfo)
379     {
380     return ops_limited_read(dest, length, region, errors, rinfo->next, cbinfo);
381     }
382
383 static ops_boolean_t limited_read(unsigned char *dest,unsigned length,
384                                   ops_region_t *region,ops_parse_info_t *info)
385     {
386     return ops_limited_read(dest,length,region,&info->errors,
387                             &info->rinfo,&info->cbinfo);
388     }
389
390 static ops_boolean_t exact_limited_read(unsigned char *dest,unsigned length,
391                                         ops_region_t *region,
392                                         ops_parse_info_t *pinfo)
393     {
394     ops_boolean_t ret;
395
396     pinfo->exact_read=ops_true;
397     ret=limited_read(dest,length,region,pinfo);
398     pinfo->exact_read=ops_false;
399
400     return ret;
401     }
402
403 /** Skip over length bytes of this packet.
404  *
405  * Calls limited_read() to skip over some data.
406  *
407  * This function makes sure to respect packet boundaries.
408  *
409  * \param length        How many bytes to skip
410  * \param *region       Pointer to packet region
411  * \param *pinfo        How to parse
412  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
413  */
414 static int limited_skip(unsigned length,ops_region_t *region,
415                         ops_parse_info_t *pinfo)
416     {
417     unsigned char buf[8192];
418
419     while(length)
420         {
421         int n=length%8192;
422         if(!limited_read(buf,n,region,pinfo))
423             return 0;
424         length-=n;
425         }
426     return 1;
427     }
428
429 /** Read a scalar.
430  *
431  * Read a big-endian scalar of length bytes, respecting packet
432  * boundaries (by calling limited_read() to read the raw data).
433  *
434  * This function makes sure to respect packet boundaries.
435  *
436  * \param *dest         The scalar value is stored here
437  * \param length        How many bytes make up this scalar (at most 4)
438  * \param *region       Pointer to current packet region
439  * \param *pinfo        How to parse
440  * \param *cb           The callback
441  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
442  *
443  * \see RFC4880 3.1
444  */
445 static int limited_read_scalar(unsigned *dest,unsigned length,
446                                ops_region_t *region,
447                                ops_parse_info_t *pinfo)
448     {
449     unsigned char c[4]="";
450     unsigned t;
451     unsigned n;
452
453     assert(length <= 4);
454     assert(sizeof(*dest) >= 4);
455     if(!limited_read(c,length,region,pinfo))
456         return 0;
457
458     for(t=0,n=0 ; n < length ; ++n)
459         t=(t << 8)+c[n];
460     *dest=t;
461
462     return 1;
463     }
464
465 /** Read a scalar.
466  *
467  * Read a big-endian scalar of length bytes, respecting packet
468  * boundaries (by calling limited_read() to read the raw data).
469  *
470  * The value read is stored in a size_t, which is a different size
471  * from an unsigned on some platforms.
472  *
473  * This function makes sure to respect packet boundaries.
474  *
475  * \param *dest         The scalar value is stored here
476  * \param length        How many bytes make up this scalar (at most 4)
477  * \param *region       Pointer to current packet region
478  * \param *pinfo        How to parse
479  * \param *cb           The callback
480  * \return              1 on success, 0 on error (calls the cb with OPS_PARSER_ERROR in limited_read()).
481  *
482  * \see RFC4880 3.1
483  */
484 static int limited_read_size_t_scalar(size_t *dest,unsigned length,
485                                       ops_region_t *region,
486                                       ops_parse_info_t *pinfo)
487     {
488     unsigned tmp;
489
490     assert(sizeof(*dest) >= 4);
491
492     /* Note that because the scalar is at most 4 bytes, we don't care
493        if size_t is bigger than usigned */
494     if(!limited_read_scalar(&tmp,length,region,pinfo))
495         return 0;
496
497     *dest=tmp;
498     return 1;
499     }
500
501 /** Read a timestamp.
502  *
503  * Timestamps in OpenPGP are unix time, i.e. seconds since The Epoch (1.1.1970).  They are stored in an unsigned scalar
504  * of 4 bytes.
505  *
506  * This function reads the timestamp using limited_read_scalar().
507  *
508  * This function makes sure to respect packet boundaries.
509  *
510  * \param *dest         The timestamp is stored here
511  * \param *ptag         Pointer to current packet's Packet Tag.
512  * \param *reader       Our reader
513  * \param *cb           The callback
514  * \return              see limited_read_scalar()
515  *
516  * \see RFC4880 3.5
517  */
518 static int limited_read_time(time_t *dest,ops_region_t *region,
519                              ops_parse_info_t *pinfo)
520     {
521     /*
522      * Cannot assume that time_t is 4 octets long -
523      * there is at least one architecture (SunOS 5.10) where it is 8.
524      */
525     if (sizeof(*dest)==4)
526         {
527         return limited_read_scalar((unsigned *)dest,4,region,pinfo);
528         }
529     else
530         {
531         time_t mytime=0;
532         int i=0;
533         unsigned char c[1];
534         for (i=0; i<4; i++)
535             {
536             if (!limited_read(c,1,region,pinfo))
537                 return 0;
538             mytime=(mytime << 8) + c[0];
539             }
540         *dest=mytime;
541         return 1;
542         }
543     }
544
545 /**
546  * \ingroup Core_MPI
547  * Read a multiprecision integer.
548  *
549  * Large numbers (multiprecision integers, MPI) are stored in OpenPGP in two parts.  First there is a 2 byte scalar
550  * indicating the length of the following MPI in Bits.  Then follow the bits that make up the actual number, most
551  * significant bits first (Big Endian).  The most significant bit in the MPI is supposed to be 1 (unless the MPI is
552  * encrypted - then it may be different as the bit count refers to the plain text but the bits are encrypted).
553  *
554  * Unused bits (i.e. those filling up the most significant byte from the left to the first bits that counts) are
555  * supposed to be cleared - I guess. XXX - does anything actually say so?
556  *
557  * This function makes sure to respect packet boundaries.
558  *
559  * \param **pgn         return the integer there - the BIGNUM is created by BN_bin2bn() and probably needs to be freed
560  *                              by the caller XXX right ben?
561  * \param *ptag         Pointer to current packet's Packet Tag.
562  * \param *reader       Our reader
563  * \param *cb           The callback
564  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
565  *                               see comment below - the callback is called with a OPS_PARSER_ERROR in case of an error)
566  *
567  * \see RFC4880 3.2
568  */
569 static int limited_read_mpi(BIGNUM **pbn,ops_region_t *region,
570                             ops_parse_info_t *pinfo)
571     {
572     unsigned length;
573     unsigned nonzero;
574     unsigned char buf[8192]=""; /* an MPI has a 2 byte length part.  Length
575                                 is given in bits, so the largest we should
576                                 ever need for the buffer is 8192 bytes. */
577     ops_boolean_t ret;
578
579     pinfo->reading_mpi_length=ops_true;
580     ret=limited_read_scalar(&length,2,region,pinfo);
581
582     pinfo->reading_mpi_length=ops_false;
583     if(!ret)
584         return 0;
585
586     nonzero=length&7; /* there should be this many zero bits in the MS byte */
587     if(!nonzero)
588         nonzero=8;
589     length=(length+7)/8;
590
591     assert(length <= 8192);
592     if(!limited_read(buf,length,region,pinfo))
593         return 0;
594
595     if((buf[0] >> nonzero) != 0 || !(buf[0]&(1 << (nonzero-1))))
596         {
597         OPS_ERROR(&pinfo->errors,OPS_E_P_MPI_FORMAT_ERROR,"MPI Format error");  /* XXX: Ben, one part of this constraint does not apply to encrypted MPIs the draft says. -- peter */
598         return 0;
599         }
600
601     *pbn=BN_bin2bn(buf,length,NULL);
602     return 1;
603     }
604
605 /** Read some data with a New-Format length from reader.
606  *
607  * \sa Internet-Draft RFC4880.txt Section 4.2.2
608  *
609  * \param *length       Where the decoded length will be put
610  * \param *pinfo        How to parse
611  * \return              ops_true if OK, else ops_false
612  *
613  */
614
615 static ops_boolean_t read_new_length(unsigned *length,ops_parse_info_t *pinfo)
616     {
617     unsigned char c[1];
618
619     if(base_read(c,1,pinfo) != 1)
620         return ops_false;
621     if(c[0] < 192)
622         {
623     // 1. One-octet packet
624         *length=c[0];
625         return ops_true;
626         }
627
628     else if (c[0]>=192 && c[0]<=223)
629         {
630         // 2. Two-octet packet
631         unsigned t=(c[0]-192) << 8;
632        
633         if(base_read(c,1,pinfo) != 1)
634             return ops_false;
635         *length=t+c[0]+192;
636         return ops_true;
637         }
638
639     else if (c[0]==255)
640         {
641         // 3. Five-Octet packet
642         return _read_scalar(length,4,pinfo);
643         }
644
645     else if (c[0]>=224 && c[0]<255)
646         {
647         // 4. Partial Body Length
648         OPS_ERROR(&pinfo->errors,OPS_E_UNIMPLEMENTED,
649                     "New format Partial Body Length fields not yet implemented");
650         return ops_false;
651         }
652     return ops_false;
653     }
654
655 /** Read the length information for a new format Packet Tag.
656  *
657  * New style Packet Tags encode the length in one to five octets.  This function reads the right amount of bytes and
658  * decodes it to the proper length information.
659  *
660  * This function makes sure to respect packet boundaries.
661  *
662  * \param *length       return the length here
663  * \param *ptag         Pointer to current packet's Packet Tag.
664  * \param *reader       Our reader
665  * \param *cb           The callback
666  * \return              1 on success, 0 on error (by limited_read_scalar() or limited_read() or if the MPI is not properly formed (XXX
667  *                               see comment below)
668  *
669  * \see RFC4880 4.2.2
670  * \see ops_ptag_t
671  */
672 static int limited_read_new_length(unsigned *length,ops_region_t *region,
673                                    ops_parse_info_t *pinfo)
674     {
675     unsigned char c[1]="";
676
677     if(!limited_read(c,1,region,pinfo))
678         return 0;
679     if(c[0] < 192)
680         {
681         *length=c[0];
682         return 1;
683         }
684     if(c[0] < 255)
685         {
686         unsigned t=(c[0]-192) << 8;
687
688         if(!limited_read(c,1,region,pinfo))
689             return 0;
690         *length=t+c[0]+192;
691         return 1;
692         }
693     return limited_read_scalar(length,4,region,pinfo);
694     }
695
696 /**
697 \ingroup Core_Create
698 \brief Free allocated memory
699 */
700 static void data_free(ops_data_t *data)
701     {
702     free(data->contents);
703     data->contents=NULL;
704     data->len=0;
705     }
706
707 /**
708 \ingroup Core_Create
709 \brief Free allocated memory
710 */
711 static void string_free(char **str)
712     {
713     free(*str);
714     *str=NULL;
715     }
716
717 /**
718 \ingroup Core_Create
719 \brief Free allocated memory
720 */
721 /*! Free packet memory, set pointer to NULL */
722 void ops_packet_free(ops_packet_t *packet)
723     {
724     free(packet->raw);
725     packet->raw=NULL;
726     }
727
728 /**
729 \ingroup Core_Create
730 \brief Free allocated memory
731 */
732 void ops_headers_free(ops_headers_t *headers)
733     {
734     unsigned n;
735
736     for(n=0 ; n < headers->nheaders ; ++n)
737         {
738         free(headers->headers[n].key);
739         free(headers->headers[n].value);
740         }
741     free(headers->headers);
742     headers->headers=NULL;
743     }
744
745 /**
746 \ingroup Core_Create
747 \brief Free allocated memory
748 */
749 void ops_signed_cleartext_trailer_free(ops_signed_cleartext_trailer_t *trailer)
750     {
751     free(trailer->hash);
752     trailer->hash=NULL;
753     }
754
755 /**
756 \ingroup Core_Create
757 \brief Free allocated memory
758 */
759 void ops_cmd_get_passphrase_free(ops_secret_key_passphrase_t *skp)
760     {
761     if (skp->passphrase && *skp->passphrase)
762         {
763         free(*skp->passphrase);
764         *skp->passphrase=NULL;
765         }
766     }
767
768 /**
769 \ingroup Core_Create
770 \brief Free allocated memory
771 */
772 /*! Free any memory allocated when parsing the packet content */
773 void ops_parser_content_free(ops_parser_content_t *c)
774     {
775     switch(c->tag)
776         {
777     case OPS_PARSER_PTAG:
778     case OPS_PTAG_CT_COMPRESSED:
779     case OPS_PTAG_SS_CREATION_TIME:
780     case OPS_PTAG_SS_EXPIRATION_TIME:
781     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
782     case OPS_PTAG_SS_TRUST:
783     case OPS_PTAG_SS_ISSUER_KEY_ID:
784     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
785     case OPS_PTAG_SS_PRIMARY_USER_ID:
786     case OPS_PTAG_SS_REVOCABLE:
787     case OPS_PTAG_SS_REVOCATION_KEY:
788     case OPS_PTAG_CT_LITERAL_DATA_HEADER:
789     case OPS_PTAG_CT_LITERAL_DATA_BODY:
790     case OPS_PTAG_CT_SIGNED_CLEARTEXT_BODY:
791     case OPS_PTAG_CT_UNARMOURED_TEXT:
792     case OPS_PTAG_CT_ARMOUR_TRAILER:
793     case OPS_PTAG_CT_SIGNATURE_HEADER:
794     case OPS_PTAG_CT_SE_DATA_HEADER:
795     case OPS_PTAG_CT_SE_IP_DATA_HEADER:
796     case OPS_PTAG_CT_SE_IP_DATA_BODY:
797     case OPS_PTAG_CT_MDC:
798     case OPS_PARSER_CMD_GET_SECRET_KEY:
799         break;
800
801     case OPS_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
802         ops_headers_free(&c->content.signed_cleartext_header.headers);
803         break;
804
805     case OPS_PTAG_CT_ARMOUR_HEADER:
806         ops_headers_free(&c->content.armour_header.headers);
807         break;
808
809     case OPS_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
810         ops_signed_cleartext_trailer_free(&c->content.signed_cleartext_trailer);
811         break;
812
813     case OPS_PTAG_CT_TRUST:
814         ops_trust_free(&c->content.trust);
815         break;
816
817     case OPS_PTAG_CT_SIGNATURE:
818     case OPS_PTAG_CT_SIGNATURE_FOOTER:
819         ops_signature_free(&c->content.signature);
820         break;
821
822     case OPS_PTAG_CT_PUBLIC_KEY:
823     case OPS_PTAG_CT_PUBLIC_SUBKEY:
824         ops_public_key_free(&c->content.public_key);
825         break;
826
827     case OPS_PTAG_CT_USER_ID:
828         ops_user_id_free(&c->content.user_id);
829         break;
830
831     case OPS_PTAG_SS_SIGNERS_USER_ID:
832         ops_user_id_free(&c->content.ss_signers_user_id);
833         break;
834
835     case OPS_PTAG_CT_USER_ATTRIBUTE:
836         ops_user_attribute_free(&c->content.user_attribute);
837         break;
838
839     case OPS_PTAG_SS_PREFERRED_SKA:
840         ops_ss_preferred_ska_free(&c->content.ss_preferred_ska);
841         break;
842
843     case OPS_PTAG_SS_PREFERRED_HASH:
844         ops_ss_preferred_hash_free(&c->content.ss_preferred_hash);
845         break;
846
847     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
848         ops_ss_preferred_compression_free(&c->content.ss_preferred_compression);
849         break;
850
851     case OPS_PTAG_SS_KEY_FLAGS:
852         ops_ss_key_flags_free(&c->content.ss_key_flags);
853         break;
854
855     case OPS_PTAG_SS_KEY_SERVER_PREFS:
856         ops_ss_key_server_prefs_free(&c->content.ss_key_server_prefs);
857         break;
858
859     case OPS_PTAG_SS_FEATURES:
860         ops_ss_features_free(&c->content.ss_features);
861         break;
862
863     case OPS_PTAG_SS_NOTATION_DATA:
864         ops_ss_notation_data_free(&c->content.ss_notation_data);
865         break;
866
867     case OPS_PTAG_SS_REGEXP:
868         ops_ss_regexp_free(&c->content.ss_regexp);
869         break;
870
871     case OPS_PTAG_SS_POLICY_URI:
872         ops_ss_policy_url_free(&c->content.ss_policy_url);
873         break;
874
875     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
876         ops_ss_preferred_key_server_free(&c->content.ss_preferred_key_server);
877         break;
878
879     case OPS_PTAG_SS_USERDEFINED00:
880     case OPS_PTAG_SS_USERDEFINED01:
881     case OPS_PTAG_SS_USERDEFINED02:
882     case OPS_PTAG_SS_USERDEFINED03:
883     case OPS_PTAG_SS_USERDEFINED04:
884     case OPS_PTAG_SS_USERDEFINED05:
885     case OPS_PTAG_SS_USERDEFINED06:
886     case OPS_PTAG_SS_USERDEFINED07:
887     case OPS_PTAG_SS_USERDEFINED08:
888     case OPS_PTAG_SS_USERDEFINED09:
889     case OPS_PTAG_SS_USERDEFINED10:
890         ops_ss_userdefined_free(&c->content.ss_userdefined);
891         break;
892
893     case OPS_PTAG_SS_RESERVED:
894         ops_ss_reserved_free(&c->content.ss_unknown);
895         break;
896
897     case OPS_PTAG_SS_REVOCATION_REASON:
898         ops_ss_revocation_reason_free(&c->content.ss_revocation_reason);
899         break;
900
901  case OPS_PTAG_SS_EMBEDDED_SIGNATURE:
902      ops_ss_embedded_signature_free(&c->content.ss_embedded_signature);
903      break;
904
905     case OPS_PARSER_PACKET_END:
906         ops_packet_free(&c->content.packet);
907         break;
908
909     case OPS_PARSER_ERROR:
910     case OPS_PARSER_ERRCODE:
911         break;
912
913     case OPS_PTAG_CT_SECRET_KEY:
914     case OPS_PTAG_CT_ENCRYPTED_SECRET_KEY:
915         ops_secret_key_free(&c->content.secret_key);
916         break;
917
918     case OPS_PTAG_CT_PK_SESSION_KEY:
919     case OPS_PTAG_CT_ENCRYPTED_PK_SESSION_KEY:
920         ops_pk_session_key_free(&c->content.pk_session_key);
921         break;
922
923     case OPS_PARSER_CMD_GET_SK_PASSPHRASE:
924         ops_cmd_get_passphrase_free(&c->content.secret_key_passphrase);
925         break;
926
927     default:
928         fprintf(stderr,"Can't free %d (0x%x)\n",c->tag,c->tag);
929         assert(0);
930         }
931     }
932
933 /**
934 \ingroup Core_Create
935 \brief Free allocated memory
936 */
937 static void free_BN(BIGNUM **pp)
938     {
939     BN_free(*pp);
940     *pp=NULL;
941     }
942
943 /**
944 \ingroup Core_Create
945 \brief Free allocated memory
946 */
947 void ops_pk_session_key_free(ops_pk_session_key_t *sk)
948     {
949     switch(sk->algorithm)
950         {
951     case OPS_PKA_RSA:
952         free_BN(&sk->parameters.rsa.encrypted_m);
953         break;
954
955     case OPS_PKA_ELGAMAL:
956         free_BN(&sk->parameters.elgamal.g_to_k);
957         free_BN(&sk->parameters.elgamal.encrypted_m);
958         break;
959
960     default:
961         assert(0);
962         }
963     }
964
965 /**
966 \ingroup Core_Create
967 \brief Free allocated memory
968 */
969 /*! Free the memory used when parsing a public key */
970 void ops_public_key_free(ops_public_key_t *p)
971     {
972     switch(p->algorithm)
973         {
974     case OPS_PKA_RSA:
975     case OPS_PKA_RSA_ENCRYPT_ONLY:
976     case OPS_PKA_RSA_SIGN_ONLY:
977         free_BN(&p->key.rsa.n);
978         free_BN(&p->key.rsa.e);
979         break;
980
981     case OPS_PKA_DSA:
982         free_BN(&p->key.dsa.p);
983         free_BN(&p->key.dsa.q);
984         free_BN(&p->key.dsa.g);
985         free_BN(&p->key.dsa.y);
986         break;
987
988     case OPS_PKA_ELGAMAL:
989     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
990         free_BN(&p->key.elgamal.p);
991         free_BN(&p->key.elgamal.g);
992         free_BN(&p->key.elgamal.y);
993         break;
994      
995     default:
996         assert(0);
997         }
998     }
999
1000 /**
1001    \ingroup Core_ReadPackets
1002 */
1003 static int parse_public_key_data(ops_public_key_t *key,ops_region_t *region,
1004                                  ops_parse_info_t *pinfo)
1005     {
1006     unsigned char c[1]="";
1007
1008     assert (region->length_read == 0);  /* We should not have read anything so far */
1009
1010     if(!limited_read(c,1,region,pinfo))
1011         return 0;
1012     key->version=c[0];
1013     if(key->version < 2 || key->version > 4)
1014         {
1015         OPS_ERROR_1(&pinfo->errors,OPS_E_PROTO_BAD_PUBLIC_KEY_VRSN,
1016                     "Bad public key version (0x%02x)",key->version);
1017         return 0;
1018         }
1019
1020     if(!limited_read_time(&key->creation_time,region,pinfo))
1021         return 0;
1022
1023     key->days_valid=0;
1024     if((key->version == 2 || key->version == 3)
1025        && !limited_read_scalar(&key->days_valid,2,region,pinfo))
1026         return 0;
1027
1028     if(!limited_read(c,1,region,pinfo))
1029         return 0;
1030
1031     key->algorithm=c[0];
1032
1033     switch(key->algorithm)
1034         {
1035     case OPS_PKA_DSA:
1036         if(!limited_read_mpi(&key->key.dsa.p,region,pinfo)
1037            || !limited_read_mpi(&key->key.dsa.q,region,pinfo)
1038            || !limited_read_mpi(&key->key.dsa.g,region,pinfo)
1039            || !limited_read_mpi(&key->key.dsa.y,region,pinfo))
1040             return 0;
1041         break;
1042
1043     case OPS_PKA_RSA:
1044     case OPS_PKA_RSA_ENCRYPT_ONLY:
1045     case OPS_PKA_RSA_SIGN_ONLY:
1046         if(!limited_read_mpi(&key->key.rsa.n,region,pinfo)
1047            || !limited_read_mpi(&key->key.rsa.e,region,pinfo))
1048             return 0;
1049         break;
1050
1051     case OPS_PKA_ELGAMAL:
1052     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1053         if(!limited_read_mpi(&key->key.elgamal.p,region,pinfo)
1054            || !limited_read_mpi(&key->key.elgamal.g,region,pinfo)
1055            || !limited_read_mpi(&key->key.elgamal.y,region,pinfo))
1056             return 0;
1057         break;
1058
1059     default:
1060         OPS_ERROR_1(&pinfo->errors,OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,"Unsupported Public Key algorithm (%s)",ops_show_pka(key->algorithm));
1061         return 0;
1062         }
1063
1064     return 1;
1065     }
1066
1067
1068 /**
1069  * \ingroup Core_ReadPackets
1070  * \brief Parse a public key packet.
1071  *
1072  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
1073  *
1074  * Once the key has been parsed successfully, it is passed to the callback.
1075  *
1076  * \param *ptag         Pointer to the current Packet Tag.  This function should consume the entire packet.
1077  * \param *reader       Our reader
1078  * \param *cb           The callback
1079  * \return              1 on success, 0 on error
1080  *
1081  * \see RFC4880 5.5.2
1082  */
1083 static int parse_public_key(ops_content_tag_t tag,ops_region_t *region,
1084                             ops_parse_info_t *pinfo)
1085     {
1086     ops_parser_content_t content;
1087
1088     if(!parse_public_key_data(&C.public_key,region,pinfo))
1089         return 0;
1090
1091     // XXX: this test should be done for all packets, surely?
1092     if(region->length_read != region->length)
1093         {
1094         OPS_ERROR_1(&pinfo->errors,OPS_E_R_UNCONSUMED_DATA,
1095                     "Unconsumed data (%d)", region->length-region->length_read);
1096         return 0;
1097         }
1098
1099     CBP(pinfo,tag,&content);
1100
1101     return 1;
1102     }
1103
1104
1105 /**
1106 \ingroup Core_Create
1107 \brief Free allocated memory
1108 */
1109 /*! Free the memory used when parsing this signature sub-packet type */
1110 void ops_ss_regexp_free(ops_ss_regexp_t *regexp)
1111     {
1112     string_free(&regexp->text);
1113     }
1114
1115 /**
1116 \ingroup Core_Create
1117 \brief Free allocated memory
1118 */
1119 /*! Free the memory used when parsing this signature sub-packet type */
1120 void ops_ss_policy_url_free(ops_ss_policy_url_t *policy_url)
1121     {
1122     string_free(&policy_url->text);
1123     }
1124
1125 /**
1126 \ingroup Core_Create
1127 \brief Free allocated memory
1128 */
1129 /*! Free the memory used when parsing this signature sub-packet type */
1130 void ops_ss_preferred_key_server_free(ops_ss_preferred_key_server_t *preferred_key_server)
1131     {
1132     string_free(&preferred_key_server->text);
1133     }
1134
1135 /**
1136 \ingroup Core_Create
1137 \brief Free allocated memory
1138 */
1139 /*! Free the memory used when parsing this packet type */
1140 void ops_user_attribute_free(ops_user_attribute_t *user_att)
1141     {
1142     data_free(&user_att->data);
1143     }
1144
1145 /**
1146  * \ingroup Core_ReadPackets
1147  * \brief Parse one user attribute packet.
1148  *
1149  * User attribute packets contain one or more attribute subpackets.
1150  * For now, handle the whole packet as raw data.
1151  */
1152
1153 static int parse_user_attribute(ops_region_t *region, ops_parse_info_t *pinfo)
1154     {
1155
1156     ops_parser_content_t content;
1157
1158     /* xxx- treat as raw data for now. Could break down further
1159        into attribute sub-packets later - rachel */
1160
1161     assert(region->length_read == 0);  /* We should not have read anything so far */
1162
1163     if(!read_data(&C.user_attribute.data,region,pinfo))
1164         return 0;
1165
1166     CBP(pinfo,OPS_PTAG_CT_USER_ATTRIBUTE,&content);
1167
1168     return 1;
1169     }
1170
1171 /**
1172 \ingroup Core_Create
1173 \brief Free allocated memory
1174 */
1175 /*! Free the memory used when parsing this packet type */
1176 void ops_user_id_free(ops_user_id_t *id)
1177     {
1178     free(id->user_id);
1179     id->user_id=NULL;
1180     }
1181
1182 /**
1183  * \ingroup Core_ReadPackets
1184  * \brief Parse a user id.
1185  *
1186  * This function parses an user id packet, which is basically just a char array the size of the packet.
1187  *
1188  * The char array is to be treated as an UTF-8 string.
1189  *
1190  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
1191  *
1192  * Once the userid has been parsed successfully, it is passed to the callback.
1193  *
1194  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
1195  * \param *reader       Our reader
1196  * \param *cb           The callback
1197  * \return              1 on success, 0 on error
1198  *
1199  * \see RFC4880 5.11
1200  */
1201 static int parse_user_id(ops_region_t *region,ops_parse_info_t *pinfo)
1202     {
1203     ops_parser_content_t content;
1204
1205     assert(region->length_read == 0);  /* We should not have read anything so far */
1206
1207     C.user_id.user_id=malloc(region->length+1);  /* XXX should we not like check malloc's return value? */
1208
1209     if(region->length && !limited_read(C.user_id.user_id,region->length,region,
1210                                        pinfo))
1211         return 0;
1212
1213     C.user_id.user_id[region->length]='\0'; /* terminate the string */
1214
1215     CBP(pinfo,OPS_PTAG_CT_USER_ID,&content);
1216     return 1;
1217     }
1218
1219 /**
1220  * \ingroup Core_Create
1221  * \brief Free the memory used when parsing a private/experimental PKA signature
1222  * \param unknown_sig
1223  */
1224 void free_unknown_sig_pka(ops_unknown_signature_t *unknown_sig)
1225     {
1226     data_free(&unknown_sig->data);
1227     }
1228
1229 /**
1230  * \ingroup Core_Create
1231  * \brief Free the memory used when parsing a signature
1232  * \param sig
1233  */
1234 void ops_signature_free(ops_signature_t *sig)
1235     {
1236     switch(sig->info.key_algorithm)
1237         {
1238     case OPS_PKA_RSA:
1239     case OPS_PKA_RSA_SIGN_ONLY:
1240         free_BN(&sig->info.signature.rsa.sig);
1241         break;
1242
1243     case OPS_PKA_DSA:
1244         free_BN(&sig->info.signature.dsa.r);
1245         free_BN(&sig->info.signature.dsa.s);
1246         break;
1247
1248     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1249         free_BN(&sig->info.signature.elgamal.r);
1250         free_BN(&sig->info.signature.elgamal.s);
1251         break;
1252
1253     case OPS_PKA_PRIVATE00:
1254     case OPS_PKA_PRIVATE01:
1255     case OPS_PKA_PRIVATE02:
1256     case OPS_PKA_PRIVATE03:
1257     case OPS_PKA_PRIVATE04:
1258     case OPS_PKA_PRIVATE05:
1259     case OPS_PKA_PRIVATE06:
1260     case OPS_PKA_PRIVATE07:
1261     case OPS_PKA_PRIVATE08:
1262     case OPS_PKA_PRIVATE09:
1263     case OPS_PKA_PRIVATE10:
1264         free_unknown_sig_pka(&sig->info.signature.unknown);
1265         break;
1266
1267     default:
1268         assert(0);
1269         }
1270     free(sig->info.v4_hashed_data);
1271     }
1272
1273 /**
1274  * \ingroup Core_Parse
1275  * \brief Parse a version 3 signature.
1276  *
1277  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1278  *
1279  * Once the signature has been parsed successfully, it is passed to the callback.
1280  *
1281  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire packet.
1282  * \param *reader       Our reader
1283  * \param *cb           The callback
1284  * \return              1 on success, 0 on error
1285  *
1286  * \see RFC4880 5.2.2
1287  */
1288 static int parse_v3_signature(ops_region_t *region,
1289                               ops_parse_info_t *pinfo)
1290     {
1291     unsigned char c[1]="";
1292     ops_parser_content_t content;
1293
1294     // clear signature
1295     memset(&C.signature,'\0',sizeof C.signature);
1296
1297     C.signature.info.version=OPS_V3;
1298
1299     /* hash info length */
1300     if(!limited_read(c,1,region,pinfo))
1301         return 0;
1302     if(c[0] != 5)
1303         ERRP(pinfo,"bad hash info length");
1304
1305     if(!limited_read(c,1,region,pinfo))
1306         return 0;
1307     C.signature.info.type=c[0];
1308     /* XXX: check signature type */
1309
1310     if(!limited_read_time(&C.signature.info.creation_time,region,pinfo))
1311         return 0;
1312     C.signature.info.creation_time_set=ops_true;
1313
1314     if(!limited_read(C.signature.info.signer_id,OPS_KEY_ID_SIZE,region,pinfo))
1315         return 0;
1316     C.signature.info.signer_id_set=ops_true;
1317
1318     if(!limited_read(c,1,region,pinfo))
1319         return 0;
1320     C.signature.info.key_algorithm=c[0];
1321     /* XXX: check algorithm */
1322
1323     if(!limited_read(c,1,region,pinfo))
1324         return 0;
1325     C.signature.info.hash_algorithm=c[0];
1326     /* XXX: check algorithm */
1327    
1328     if(!limited_read(C.signature.hash2,2,region,pinfo))
1329         return 0;
1330
1331     switch(C.signature.info.key_algorithm)
1332         {
1333     case OPS_PKA_RSA:
1334     case OPS_PKA_RSA_SIGN_ONLY:
1335         if(!limited_read_mpi(&C.signature.info.signature.rsa.sig,region,pinfo))
1336             return 0;
1337         break;
1338
1339     case OPS_PKA_DSA:
1340         if(!limited_read_mpi(&C.signature.info.signature.dsa.r,region,pinfo)
1341            || !limited_read_mpi(&C.signature.info.signature.dsa.s,region,pinfo))
1342             return 0;
1343         break;
1344
1345     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1346         if(!limited_read_mpi(&C.signature.info.signature.elgamal.r,region,pinfo)
1347            || !limited_read_mpi(&C.signature.info.signature.elgamal.s,region,pinfo))
1348             return 0;
1349         break;
1350
1351     default:
1352         OPS_ERROR_1(&pinfo->errors,OPS_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1353                     "Unsupported signature key algorithm (%s)",
1354                     ops_show_pka(C.signature.info.key_algorithm));
1355         return 0;
1356         }
1357
1358     if(region->length_read != region->length)
1359         {
1360         OPS_ERROR_1(&pinfo->errors,OPS_E_R_UNCONSUMED_DATA,"Unconsumed data (%d)",region->length-region->length_read);
1361         return 0;
1362         }
1363
1364     if(C.signature.info.signer_id_set)
1365         C.signature.hash=ops_parse_hash_find(pinfo,C.signature.info.signer_id);
1366
1367     CBP(pinfo,OPS_PTAG_CT_SIGNATURE,&content);
1368
1369     return 1;
1370     }
1371
1372 /**
1373  * \ingroup Core_ReadPackets
1374  * \brief Parse one signature sub-packet.
1375  *
1376  * Version 4 signatures can have an arbitrary amount of (hashed and unhashed) subpackets.  Subpackets are used to hold
1377  * optional attributes of subpackets.
1378  *
1379  * This function parses one such signature subpacket.
1380  *
1381  * Once the subpacket has been parsed successfully, it is passed to the callback.
1382  *
1383  * \param *ptag         Pointer to the Packet Tag.  This function should consume the entire subpacket.
1384  * \param *reader       Our reader
1385  * \param *cb           The callback
1386  * \return              1 on success, 0 on error
1387  *
1388  * \see RFC4880 5.2.3
1389  */
1390 static int parse_one_signature_subpacket(ops_signature_t *sig,
1391                                          ops_region_t *region,
1392                                          ops_parse_info_t *pinfo)
1393     {
1394     ops_region_t subregion;
1395     unsigned char c[1]="";
1396     ops_parser_content_t content;
1397     unsigned t8,t7;
1398     ops_boolean_t read=ops_true;
1399     unsigned char bool[1]="";
1400
1401     ops_init_subregion(&subregion,region);
1402     if(!limited_read_new_length(&subregion.length,region,pinfo))
1403         return 0;
1404
1405     if(subregion.length > region->length)
1406         ERRP(pinfo,"Subpacket too long");
1407
1408     if(!limited_read(c,1,&subregion,pinfo))
1409         return 0;
1410
1411     t8=(c[0]&0x7f)/8;
1412     t7=1 << (c[0]&7);
1413
1414     content.critical=c[0] >> 7;
1415     content.tag=OPS_PTAG_SIGNATURE_SUBPACKET_BASE+(c[0]&0x7f);
1416
1417     /* Application wants it delivered raw */
1418     if(pinfo->ss_raw[t8]&t7)
1419         {
1420         C.ss_raw.tag=content.tag;
1421         C.ss_raw.length=subregion.length-1;
1422         C.ss_raw.raw=malloc(C.ss_raw.length);
1423         if(!limited_read(C.ss_raw.raw,C.ss_raw.length,&subregion,pinfo))
1424             return 0;
1425         CBP(pinfo,OPS_PTAG_RAW_SS,&content);
1426     return 1;
1427         }
1428
1429     switch(content.tag)
1430         {
1431     case OPS_PTAG_SS_CREATION_TIME:
1432     case OPS_PTAG_SS_EXPIRATION_TIME:
1433     case OPS_PTAG_SS_KEY_EXPIRATION_TIME:
1434         if(!limited_read_time(&C.ss_time.time,&subregion,pinfo))
1435             return 0;
1436         if(content.tag == OPS_PTAG_SS_CREATION_TIME)
1437             {
1438             sig->info.creation_time=C.ss_time.time;
1439             sig->info.creation_time_set=ops_true;
1440             }
1441         break;
1442
1443     case OPS_PTAG_SS_TRUST:
1444         if(!limited_read(&C.ss_trust.level,1,&subregion,pinfo)
1445            || !limited_read(&C.ss_trust.amount,1,&subregion,pinfo))
1446             return 0;
1447         break;
1448
1449     case OPS_PTAG_SS_REVOCABLE:
1450         if(!limited_read(bool,1,&subregion,pinfo))
1451             return 0;
1452         C.ss_revocable.revocable=!!bool[0];
1453         break;
1454
1455     case OPS_PTAG_SS_ISSUER_KEY_ID:
1456         if(!limited_read(C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE,
1457                              &subregion,pinfo))
1458             return 0;
1459         memcpy(sig->info.signer_id,C.ss_issuer_key_id.key_id,OPS_KEY_ID_SIZE);
1460         sig->info.signer_id_set=ops_true;
1461         break;
1462
1463     case OPS_PTAG_SS_PREFERRED_SKA:
1464         if(!read_data(&C.ss_preferred_ska.data,&subregion,pinfo))
1465             return 0;
1466         break;
1467                                
1468     case OPS_PTAG_SS_PREFERRED_HASH:
1469         if(!read_data(&C.ss_preferred_hash.data,&subregion,pinfo))
1470             return 0;
1471         break;
1472                                
1473     case OPS_PTAG_SS_PREFERRED_COMPRESSION:
1474         if(!read_data(&C.ss_preferred_compression.data,&subregion,pinfo))
1475             return 0;
1476         break;
1477                                
1478     case OPS_PTAG_SS_PRIMARY_USER_ID:
1479         if(!limited_read (bool,1,&subregion,pinfo))
1480             return 0;
1481         C.ss_primary_user_id.primary_user_id = !!bool[0];
1482         break;
1483  
1484     case OPS_PTAG_SS_KEY_FLAGS:
1485         if(!read_data(&C.ss_key_flags.data,&subregion,pinfo))
1486             return 0;
1487         break;
1488
1489     case OPS_PTAG_SS_KEY_SERVER_PREFS:
1490         if(!read_data(&C.ss_key_server_prefs.data,&subregion,pinfo))
1491             return 0;
1492         break;
1493
1494     case OPS_PTAG_SS_FEATURES:
1495         if(!read_data(&C.ss_features.data,&subregion,pinfo))
1496             return 0;
1497         break;
1498
1499     case OPS_PTAG_SS_SIGNERS_USER_ID:
1500         if(!read_unsigned_string(&C.ss_signers_user_id.user_id,&subregion,pinfo))
1501             return 0;
1502         break;
1503
1504  case OPS_PTAG_SS_EMBEDDED_SIGNATURE:
1505      // \todo should do something with this sig?
1506      if (!read_data(&C.ss_embedded_signature.sig,&subregion,pinfo))
1507          return 0;
1508      break;
1509
1510     case OPS_PTAG_SS_NOTATION_DATA:
1511         if(!limited_read_data(&C.ss_notation_data.flags,4,&subregion,pinfo))
1512             return 0;
1513         if(!limited_read_size_t_scalar(&C.ss_notation_data.name.len,2,
1514                                        &subregion,pinfo))
1515             return 0;
1516         if(!limited_read_size_t_scalar(&C.ss_notation_data.value.len,2,
1517                                        &subregion,pinfo))
1518             return 0;
1519         if(!limited_read_data(&C.ss_notation_data.name,
1520                               C.ss_notation_data.name.len,&subregion,pinfo))
1521             return 0;
1522         if(!limited_read_data(&C.ss_notation_data.value,
1523                               C.ss_notation_data.value.len,&subregion,pinfo))
1524             return 0;
1525         break;
1526
1527     case OPS_PTAG_SS_POLICY_URI:
1528         if(!read_string(&C.ss_policy_url.text,&subregion,pinfo))
1529             return 0;
1530         break;
1531
1532     case OPS_PTAG_SS_REGEXP:
1533         if(!read_string(&C.ss_regexp.text,&subregion, pinfo))
1534             return 0;
1535         break;
1536
1537     case OPS_PTAG_SS_PREFERRED_KEY_SERVER:
1538         if(!read_string(&C.ss_preferred_key_server.text,&subregion,pinfo))
1539             return 0;
1540         break;
1541
1542     case OPS_PTAG_SS_USERDEFINED00:
1543     case OPS_PTAG_SS_USERDEFINED01:
1544     case OPS_PTAG_SS_USERDEFINED02:
1545     case OPS_PTAG_SS_USERDEFINED03:
1546     case OPS_PTAG_SS_USERDEFINED04:
1547     case OPS_PTAG_SS_USERDEFINED05:
1548     case OPS_PTAG_SS_USERDEFINED06:
1549     case OPS_PTAG_SS_USERDEFINED07:
1550     case OPS_PTAG_SS_USERDEFINED08:
1551     case OPS_PTAG_SS_USERDEFINED09:
1552     case OPS_PTAG_SS_USERDEFINED10:
1553         if(!read_data(&C.ss_userdefined.data,&subregion,pinfo))
1554             return 0;
1555         break;
1556
1557     case OPS_PTAG_SS_RESERVED:
1558         if(!read_data(&C.ss_unknown.data,&subregion,pinfo))
1559             return 0;
1560         break;
1561
1562     case OPS_PTAG_SS_REVOCATION_REASON:
1563         /* first byte is the machine-readable code */
1564         if(!limited_read(&C.ss_revocation_reason.code,1,&subregion,pinfo))
1565             return 0;
1566
1567         /* the rest is a human-readable UTF-8 string */
1568         if(!read_string(&C.ss_revocation_reason.text,&subregion,pinfo))
1569             return 0;
1570         break;
1571
1572     case OPS_PTAG_SS_REVOCATION_KEY:
1573         /* octet 0 = clss. Bit 0x80 must be set */
1574         if(!limited_read (&C.ss_revocation_key.clss,1,&subregion,pinfo))
1575             return 0;
1576         if(!(C.ss_revocation_key.clss&0x80))
1577             {
1578             printf("Warning: OPS_PTAG_SS_REVOCATION_KEY class: "
1579                    "Bit 0x80 should be set\n");
1580             return 0;
1581             }
1582  
1583         /* octet 1 = algid */
1584         if(!limited_read(&C.ss_revocation_key.algid,1,&subregion,pinfo))
1585             return 0;
1586  
1587         /* octets 2-21 = fingerprint */
1588         if(!limited_read(&C.ss_revocation_key.fingerprint[0],20,&subregion,
1589                          pinfo))
1590             return 0;
1591         break;
1592  
1593     default:
1594         if(pinfo->ss_parsed[t8]&t7)
1595             OPS_ERROR_1(&pinfo->errors, OPS_E_PROTO_UNKNOWN_SS,
1596                         "Unknown signature subpacket type (%d)", c[0]&0x7f);
1597         read=ops_false;
1598         break;
1599         }
1600
1601     /* Application doesn't want it delivered parsed */
1602     if(!(pinfo->ss_parsed[t8]&t7))
1603         {
1604         if(content.critical)
1605             OPS_ERROR_1(&pinfo->errors,OPS_E_PROTO_CRITICAL_SS_IGNORED,
1606                         "Critical signature subpacket ignored (%d)",
1607                         c[0]&0x7f);
1608         if(!read && !limited_skip(subregion.length-1,&subregion,pinfo))
1609             return 0;
1610         //      printf("skipped %d length %d\n",c[0]&0x7f,subregion.length);
1611         if(read)
1612             ops_parser_content_free(&content);
1613         return 1;
1614         }
1615
1616     if(read && subregion.length_read != subregion.length)
1617         {
1618         OPS_ERROR_1(&pinfo->errors,OPS_E_R_UNCONSUMED_DATA,
1619                     "Unconsumed data (%d)",
1620                     subregion.length-subregion.length_read);
1621         return 0;
1622         }
1623  
1624     CBP(pinfo,content.tag,&content);
1625
1626     return 1;
1627     }
1628
1629 /**
1630  \ingroup Core_Create
1631  \brief Free the memory used when parsing this signature sub-packet type
1632  \param ss_preferred_ska
1633 */
1634 void ops_ss_preferred_ska_free(ops_ss_preferred_ska_t *ss_preferred_ska)
1635     {
1636     data_free(&ss_preferred_ska->data);
1637     }
1638
1639 /**
1640    \ingroup Core_Create
1641    \brief Free the memory used when parsing this signature sub-packet type
1642    \param ss_preferred_hash
1643 */
1644 void ops_ss_preferred_hash_free(ops_ss_preferred_hash_t *ss_preferred_hash)
1645     {
1646     data_free(&ss_preferred_hash->data);
1647     }
1648
1649 /**
1650    \ingroup Core_Create
1651    \brief Free the memory used when parsing this signature sub-packet type
1652 */
1653 void ops_ss_preferred_compression_free(ops_ss_preferred_compression_t *ss_preferred_compression)
1654     {
1655     data_free(&ss_preferred_compression->data);
1656     }
1657
1658 /**
1659    \ingroup Core_Create
1660    \brief Free the memory used when parsing this signature sub-packet type
1661 */
1662 void ops_ss_key_flags_free(ops_ss_key_flags_t *ss_key_flags)
1663     {
1664     data_free(&ss_key_flags->data);
1665     }
1666
1667 /**
1668    \ingroup Core_Create
1669    \brief Free the memory used when parsing this signature sub-packet type
1670 */
1671 void ops_ss_features_free(ops_ss_features_t *ss_features)
1672     {
1673     data_free(&ss_features->data);
1674     }
1675
1676 /**
1677    \ingroup Core_Create
1678    \brief Free the memory used when parsing this signature sub-packet type
1679 */
1680 void ops_ss_key_server_prefs_free(ops_ss_key_server_prefs_t *ss_key_server_prefs)
1681     {
1682     data_free(&ss_key_server_prefs->data);
1683     }
1684
1685 /**
1686  * \ingroup Core_ReadPackets
1687  * \brief Parse several signature subpackets.
1688  *
1689  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1690  * This function parses this length and then calls parse_one_signature_subpacket() for each subpacket until the
1691  * entire set is consumed.
1692  *
1693  * This function does not call the callback directly, parse_one_signature_subpacket() does for each subpacket.
1694  *
1695  * \param *ptag         Pointer to the Packet Tag.
1696  * \param *reader       Our reader
1697  * \param *cb           The callback
1698  * \return              1 on success, 0 on error
1699  *
1700  * \see RFC4880 5.2.3
1701  */
1702 static int parse_signature_subpackets(ops_signature_t *sig,
1703                                       ops_region_t *region,
1704                                       ops_parse_info_t *pinfo)
1705     {
1706     ops_region_t subregion;
1707     ops_parser_content_t content;
1708
1709     ops_init_subregion(&subregion,region);
1710     if(!limited_read_scalar(&subregion.length,2,region,pinfo))
1711         return 0;
1712
1713     if(subregion.length > region->length)
1714         ERRP(pinfo,"Subpacket set too long");
1715
1716     while(subregion.length_read < subregion.length)
1717         if(!parse_one_signature_subpacket(sig,&subregion,pinfo))
1718             return 0;
1719
1720     if(subregion.length_read != subregion.length)
1721         {
1722         if(!limited_skip(subregion.length-subregion.length_read,&subregion,
1723                          pinfo))
1724             ERRP(pinfo,"Read failed while recovering from subpacket length mismatch");
1725         ERRP(pinfo,"Subpacket length mismatch");
1726         }
1727
1728     return 1;
1729     }
1730
1731 /**
1732  * \ingroup Core_ReadPackets
1733  * \brief Parse a version 4 signature.
1734  *
1735  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1736  *
1737  * Once the signature packet has been parsed successfully, it is passed to the callback.
1738  *
1739  * \param *ptag         Pointer to the Packet Tag.
1740  * \param *reader       Our reader
1741  * \param *cb           The callback
1742  * \return              1 on success, 0 on error
1743  *
1744  * \see RFC4880 5.2.3
1745  */
1746 static int parse_v4_signature(ops_region_t *region,ops_parse_info_t *pinfo)
1747     {
1748     unsigned char c[1]="";
1749     ops_parser_content_t content;
1750    
1751     //debug=1;
1752     if (debug)
1753         { fprintf(stderr, "\nparse_v4_signature\n"); }
1754    
1755     // clear signature
1756     memset(&C.signature,'\0',sizeof C.signature);
1757
1758     /* We need to hash the packet data from version through the hashed subpacket data */
1759
1760     C.signature.v4_hashed_data_start=pinfo->rinfo.alength-1;
1761
1762     /* Set version,type,algorithms */
1763
1764     C.signature.info.version=OPS_V4;
1765
1766     if(!limited_read(c,1,region,pinfo))
1767         return 0;
1768     C.signature.info.type=c[0];
1769     if (debug)
1770         { fprintf(stderr, "signature type=%d\n", C.signature.info.type); }
1771
1772     /* XXX: check signature type */
1773
1774     if(!limited_read(c,1,region,pinfo))
1775         return 0;
1776     C.signature.info.key_algorithm=c[0];
1777     /* XXX: check algorithm */
1778     if (debug)
1779         { fprintf(stderr, "key_algorithm=%d\n", C.signature.info.key_algorithm); }
1780
1781     if(!limited_read(c,1,region,pinfo))
1782         return 0;
1783     C.signature.info.hash_algorithm=c[0];
1784     /* XXX: check algorithm */
1785     if (debug)
1786         { fprintf(stderr, "hash_algorithm=%d %s\n", C.signature.info.hash_algorithm, ops_show_hash_algorithm(C.signature.info.hash_algorithm)); }
1787
1788     CBP(pinfo,OPS_PTAG_CT_SIGNATURE_HEADER,&content);
1789
1790     if(!parse_signature_subpackets(&C.signature,region,pinfo))
1791         return 0;
1792
1793     C.signature.info.v4_hashed_data_length=pinfo->rinfo.alength
1794         -C.signature.v4_hashed_data_start;
1795
1796     // copy hashed subpackets
1797     if (C.signature.info.v4_hashed_data)
1798         free(C.signature.info.v4_hashed_data);
1799     C.signature.info.v4_hashed_data=ops_mallocz(C.signature.info.v4_hashed_data_length);
1800
1801     if (!pinfo->rinfo.accumulate)
1802         {
1803         /* We must accumulate, else we can't check the signature */
1804         fprintf(stderr,"*** ERROR: must set accumulate to true\n");
1805         assert(0);
1806         }
1807
1808     memcpy(C.signature.info.v4_hashed_data,
1809            pinfo->rinfo.accumulated+C.signature.v4_hashed_data_start,
1810            C.signature.info.v4_hashed_data_length);
1811
1812     if(!parse_signature_subpackets(&C.signature,region,pinfo))
1813         return 0;
1814    
1815     if(!limited_read(C.signature.hash2,2,region,pinfo))
1816         return 0;
1817
1818     switch(C.signature.info.key_algorithm)
1819         {
1820     case OPS_PKA_RSA:
1821         if(!limited_read_mpi(&C.signature.info.signature.rsa.sig,region,pinfo))
1822             return 0;
1823         break;
1824
1825     case OPS_PKA_DSA:
1826         if(!limited_read_mpi(&C.signature.info.signature.dsa.r,region,pinfo))
1827             ERRP(pinfo,"Error reading DSA r field in signature");
1828         if (!limited_read_mpi(&C.signature.info.signature.dsa.s,region,pinfo))
1829             ERRP(pinfo,"Error reading DSA s field in signature");
1830         break;
1831
1832     case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1833         if(!limited_read_mpi(&C.signature.info.signature.elgamal.r,region,pinfo)
1834            || !limited_read_mpi(&C.signature.info.signature.elgamal.s,region,pinfo))
1835             return 0;
1836         break;
1837
1838     case OPS_PKA_PRIVATE00:
1839     case OPS_PKA_PRIVATE01:
1840     case OPS_PKA_PRIVATE02:
1841     case OPS_PKA_PRIVATE03:
1842     case OPS_PKA_PRIVATE04:
1843     case OPS_PKA_PRIVATE05:
1844     case OPS_PKA_PRIVATE06:
1845     case OPS_PKA_PRIVATE07:
1846     case OPS_PKA_PRIVATE08:
1847     case OPS_PKA_PRIVATE09:
1848     case OPS_PKA_PRIVATE10:
1849         if (!read_data(&C.signature.info.signature.unknown.data,region,pinfo))
1850             return 0;
1851         break;
1852
1853     default:
1854         OPS_ERROR_1(&pinfo->errors,OPS_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1855                     "Bad v4 signature key algorithm (%s)",
1856                     ops_show_pka(C.signature.info.key_algorithm));
1857         return 0;
1858         }
1859
1860     if(region->length_read != region->length)
1861         {
1862         OPS_ERROR_1(&pinfo->errors,OPS_E_R_UNCONSUMED_DATA,
1863                     "Unconsumed data (%d)",
1864                     region->length-region->length_read);
1865         return 0;
1866         }
1867
1868     CBP(pinfo,OPS_PTAG_CT_SIGNATURE_FOOTER,&content);
1869
1870     return 1;
1871     }
1872
1873 /**
1874  * \ingroup Core_ReadPackets
1875  * \brief Parse a signature subpacket.
1876  *
1877  * This function calls the appropriate function to handle v3 or v4 signatures.
1878  *
1879  * Once the signature packet has been parsed successfully, it is passed to the callback.
1880  *
1881  * \param *ptag         Pointer to the Packet Tag.
1882  * \param *reader       Our reader
1883  * \param *cb           The callback
1884  * \return              1 on success, 0 on error
1885  */
1886 static int parse_signature(ops_region_t *region,ops_parse_info_t *pinfo)
1887     {
1888     unsigned char c[1]="";
1889     ops_parser_content_t content;
1890
1891     assert(region->length_read == 0);  /* We should not have read anything so far */
1892
1893     memset(&content,'\0',sizeof content);
1894
1895     if(!limited_read(c,1,region,pinfo))
1896         return 0;
1897
1898     if(c[0] == 2 || c[0] == 3)
1899         return parse_v3_signature(region,pinfo);
1900     else if(c[0] == 4)
1901         return parse_v4_signature(region,pinfo);
1902
1903     OPS_ERROR_1(&pinfo->errors,OPS_E_PROTO_BAD_SIGNATURE_VRSN,
1904                 "Bad signature version (%d)",c[0]);
1905     return 0;
1906     }
1907
1908 /**
1909  \ingroup Core_ReadPackets
1910  \brief Parse Compressed packet
1911 */
1912 static int parse_compressed(ops_region_t *region,ops_parse_info_t *pinfo)
1913     {
1914     unsigned char c[1]="";
1915     ops_parser_content_t content;
1916
1917     if(!limited_read(c,1,region,pinfo))
1918         return 0;
1919
1920     C.compressed.type=c[0];
1921
1922     CBP(pinfo,OPS_PTAG_CT_COMPRESSED,&content);
1923
1924     /* The content of a compressed data packet is more OpenPGP packets
1925        once decompressed, so recursively handle them */
1926
1927     return ops_decompress(region,pinfo,C.compressed.type);
1928     }
1929
1930 /**
1931    \ingroup Core_ReadPackets
1932    \brief Parse a One Pass Signature packet
1933 */
1934 static int parse_one_pass(ops_region_t *region,ops_parse_info_t *pinfo)
1935     {
1936     unsigned char c[1]="";
1937     ops_parser_content_t content;
1938
1939     if(!limited_read(&C.one_pass_signature.version,1,region,pinfo))
1940         return 0;
1941     if(C.one_pass_signature.version != 3)
1942         {
1943         OPS_ERROR_1(&pinfo->errors,OPS_E_PROTO_BAD_ONE_PASS_SIG_VRSN,
1944                     "Bad one-pass signature version (%d)",
1945                     C.one_pass_signature.version);
1946         return 0;
1947         }
1948
1949     if(!limited_read(c,1,region,pinfo))
1950         return 0;
1951     C.one_pass_signature.sig_type=c[0];
1952
1953     if(!limited_read(c,1,region,pinfo))
1954         return 0;
1955     C.one_pass_signature.hash_algorithm=c[0];
1956
1957     if(!limited_read(c,1,region,pinfo))
1958         return 0;
1959     C.one_pass_signature.key_algorithm=c[0];
1960
1961     if(!limited_read(C.one_pass_signature.keyid,
1962                          sizeof C.one_pass_signature.keyid,region,pinfo))
1963         return 0;
1964
1965     if(!limited_read(c,1,region,pinfo))
1966         return 0;
1967     C.one_pass_signature.nested=!!c[0];
1968
1969     CBP(pinfo,OPS_PTAG_CT_ONE_PASS_SIGNATURE,&content);
1970
1971     // XXX: we should, perhaps, let the app choose whether to hash or not
1972     ops_parse_hash_init(pinfo,C.one_pass_signature.hash_algorithm,
1973                         C.one_pass_signature.keyid);
1974
1975     return 1;
1976     }
1977
1978 /**
1979    \ingroup Core_Create
1980    \brief Free the memory used when parsing this signature sub-packet type
1981 */
1982 void ops_ss_userdefined_free(ops_ss_userdefined_t *ss_userdefined)
1983     {
1984     data_free(&ss_userdefined->data);
1985     }
1986
1987 /**
1988    \ingroup Core_Create
1989    \brief Free the memory used when parsing this signature sub-packet type
1990 */
1991 void ops_ss_reserved_free(ops_ss_unknown_t *ss_unknown)
1992     {
1993     data_free(&ss_unknown->data);
1994     }
1995
1996 /**
1997    \ingroup Core_Create
1998    \brief Free the memory used when parsing this signature sub-packet type
1999 */
2000 void ops_ss_notation_data_free(ops_ss_notation_data_t *ss_notation_data)
2001      {
2002      data_free(&ss_notation_data->name);
2003      data_free(&ss_notation_data->value);
2004      }
2005
2006 void ops_ss_embedded_signature_free(ops_ss_embedded_signature_t *ss_embedded_signature)
2007     {
2008     data_free(&ss_embedded_signature->sig);
2009     }
2010
2011 /**
2012    \ingroup Core_Create
2013    \brief Free the memory used when parsing this signature sub-packet type
2014 */
2015 void ops_ss_revocation_reason_free(ops_ss_revocation_reason_t *ss_revocation_reason)
2016     {
2017     string_free(&ss_revocation_reason->text);
2018     }
2019
2020 /**
2021    \ingroup Core_Create
2022    \brief Free the memory used when parsing this packet type
2023 */
2024 void ops_trust_free(ops_trust_t *trust)
2025     {
2026     data_free(&trust->data);
2027     }
2028
2029 /**
2030  \ingroup Core_ReadPackets
2031  \brief Parse a Trust packet
2032 */
2033 static int
2034 parse_trust (ops_region_t *region, ops_parse_info_t *pinfo)
2035     {
2036     ops_parser_content_t content;
2037
2038     if(!read_data(&C.trust.data,region,pinfo))
2039             return 0;
2040
2041     CBP(pinfo,OPS_PTAG_CT_TRUST, &content);
2042
2043     return 1;
2044     }
2045
2046 /**
2047    \ingroup Core_ReadPackets
2048    \brief Parse a Literal Data packet
2049 */
2050 static int parse_literal_data(ops_region_t *region,ops_parse_info_t *pinfo)
2051     {
2052     ops_parser_content_t content;
2053     unsigned char c[1]="";
2054
2055     if(!limited_read(c,1,region,pinfo))
2056         return 0;
2057     C.literal_data_header.format=c[0];
2058
2059     if(!limited_read(c,1,region,pinfo))
2060         return 0;
2061     if(!limited_read((unsigned char *)C.literal_data_header.filename,c[0],
2062                      region,pinfo))
2063         return 0;
2064     C.literal_data_header.filename[c[0]]='\0';
2065
2066     if(!limited_read_time(&C.literal_data_header.modification_time,region,pinfo))
2067         return 0;
2068
2069     CBP(pinfo,OPS_PTAG_CT_LITERAL_DATA_HEADER,&content);
2070
2071     while(region->length_read < region->length)
2072         {
2073         unsigned l=region->length-region->length_read;
2074
2075         if(l > sizeof C.literal_data_body.data)
2076             l=sizeof C.literal_data_body.data;
2077
2078         if(!limited_read(C.literal_data_body.data,l,region,pinfo))
2079             return 0;
2080
2081         C.literal_data_body.length=l;
2082
2083         ops_parse_hash_data(pinfo,C.literal_data_body.data,l);
2084
2085         CBP(pinfo,OPS_PTAG_CT_LITERAL_DATA_BODY,&content);
2086         }
2087
2088     return 1;
2089     }
2090
2091 /**
2092  * \ingroup Core_Create
2093  *
2094  * ops_secret_key_free() frees the memory associated with "key". Note that
2095  * the key itself is not freed.
2096  *
2097  * \param key
2098  */
2099
2100 void ops_secret_key_free(ops_secret_key_t *key)
2101     {
2102     switch(key->public_key.algorithm)
2103         {
2104     case OPS_PKA_RSA:
2105     case OPS_PKA_RSA_ENCRYPT_ONLY:
2106     case OPS_PKA_RSA_SIGN_ONLY:
2107         free_BN(&key->key.rsa.d);
2108         free_BN(&key->key.rsa.p);
2109         free_BN(&key->key.rsa.q);
2110         free_BN(&key->key.rsa.u);
2111         break;
2112
2113     case OPS_PKA_DSA:
2114         free_BN(&key->key.dsa.x);
2115         break;
2116
2117     default:
2118         fprintf(stderr,"ops_secret_key_free: Unknown algorithm: %d (%s)\n",key->public_key.algorithm, ops_show_pka(key->public_key.algorithm));
2119         //assert(0);
2120         }
2121
2122     ops_public_key_free(&key->public_key);
2123     }
2124
2125 static int consume_packet(ops_region_t *region,ops_parse_info_t *pinfo,
2126                           ops_boolean_t warn)
2127     {
2128     ops_data_t remainder;
2129     ops_parser_content_t content;
2130
2131     if(region->indeterminate)
2132         ERRP(pinfo,"Can't consume indeterminate packets");
2133
2134     if(read_data(&remainder,region,pinfo))
2135         {
2136         /* now throw it away */
2137         data_free(&remainder);
2138         if(warn)
2139             OPS_ERROR(&pinfo->errors,OPS_E_P_PACKET_CONSUMED,"Warning: packet consumer");
2140         }
2141     else if(warn)
2142         OPS_ERROR(&pinfo->errors,OPS_E_P_PACKET_NOT_CONSUMED,"Warning: Packet was not consumed");
2143     else
2144         {
2145         OPS_ERROR(&pinfo->errors,OPS_E_P_PACKET_NOT_CONSUMED,"Packet was not consumed");
2146         return 0;
2147         }
2148
2149     return 1;
2150     }
2151
2152 /**
2153  * \ingroup Core_ReadPackets
2154  * \brief Parse a secret key
2155  */
2156 static int parse_secret_key(ops_region_t *region,ops_parse_info_t *pinfo)
2157     {
2158     ops_parser_content_t content;
2159     unsigned char c[1]="";
2160     ops_crypt_t decrypt;
2161     int ret=1;
2162     ops_region_t encregion;
2163     ops_region_t *saved_region=NULL;
2164     ops_hash_t checkhash;
2165     int blocksize;
2166     ops_boolean_t crypted;
2167
2168     if (debug)
2169         { fprintf(stderr,"\n---------\nparse_secret_key:\n");
2170         fprintf(stderr,"region length=%d, length_read=%d, remainder=%d\n", region->length, region->length_read, region->length-region->length_read);
2171         }
2172
2173     memset(&content,'\0',sizeof content);
2174     if(!parse_public_key_data(&C.secret_key.public_key,region,pinfo))
2175         return 0;
2176
2177     if (debug)
2178         {
2179         fprintf(stderr,"parse_secret_key: public key parsed\n");
2180         ops_print_public_key(&C.secret_key.public_key);
2181         }
2182
2183     pinfo->reading_v3_secret=C.secret_key.public_key.version != OPS_V4;
2184
2185     if(!limited_read(c,1,region,pinfo))
2186         return 0;
2187     C.secret_key.s2k_usage=c[0];
2188
2189     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED
2190        || C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
2191         {
2192         if(!limited_read(c,1,region,pinfo))
2193             return 0;
2194         C.secret_key.algorithm=c[0];
2195
2196         if(!limited_read(c,1,region,pinfo))
2197             return 0;
2198         C.secret_key.s2k_specifier=c[0];
2199
2200         assert(C.secret_key.s2k_specifier == OPS_S2KS_SIMPLE
2201                || C.secret_key.s2k_specifier == OPS_S2KS_SALTED
2202                || C.secret_key.s2k_specifier == OPS_S2KS_ITERATED_AND_SALTED);
2203
2204         if(!limited_read(c,1,region,pinfo))
2205             return 0;
2206         C.secret_key.hash_algorithm=c[0];
2207
2208         if(C.secret_key.s2k_specifier != OPS_S2KS_SIMPLE
2209            && !limited_read(C.secret_key.salt,8,region,pinfo))
2210         {
2211             return 0;
2212         }
2213
2214         if(C.secret_key.s2k_specifier == OPS_S2KS_ITERATED_AND_SALTED)
2215             {
2216             if(!limited_read(c,1,region,pinfo))
2217                 return 0;
2218             C.secret_key.octet_count=(16+(c[0]&15)) << ((c[0] >> 4)+6);
2219             }
2220         }
2221     else if(C.secret_key.s2k_usage != OPS_S2KU_NONE)
2222         {
2223         // this is V3 style, looks just like a V4 simple hash
2224         C.secret_key.algorithm=C.secret_key.s2k_usage;
2225         C.secret_key.s2k_usage=OPS_S2KU_ENCRYPTED;
2226         C.secret_key.s2k_specifier=OPS_S2KS_SIMPLE;
2227         C.secret_key.hash_algorithm=OPS_HASH_MD5;
2228         }
2229
2230     crypted=C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED
2231         || C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED;
2232
2233     if(crypted)
2234         {
2235         int n;
2236         ops_parser_content_t pc;
2237         char *passphrase;
2238         unsigned char key[OPS_MAX_KEY_SIZE+OPS_MAX_HASH_SIZE];
2239         ops_hash_t hashes[(OPS_MAX_KEY_SIZE+OPS_MIN_HASH_SIZE-1)/OPS_MIN_HASH_SIZE];
2240         int keysize;
2241         int hashsize;
2242         size_t l;
2243
2244         blocksize=ops_block_size(C.secret_key.algorithm);
2245         assert(blocksize > 0 && blocksize <= OPS_MAX_BLOCK_SIZE);
2246
2247         if(!limited_read(C.secret_key.iv,blocksize,region,pinfo))
2248             return 0;
2249
2250         memset(&pc,'\0',sizeof pc);
2251         passphrase=NULL;
2252         pc.content.secret_key_passphrase.passphrase=&passphrase;
2253         pc.content.secret_key_passphrase.secret_key=&C.secret_key;
2254         CBP(pinfo,OPS_PARSER_CMD_GET_SK_PASSPHRASE,&pc);
2255         if(!passphrase)
2256             {
2257         if (debug)
2258             {
2259             // \todo make into proper error
2260             fprintf(stderr,"parse_secret_key: can't get passphrase\n");
2261             }
2262
2263             if(!consume_packet(region,pinfo,ops_false))
2264                return 0;
2265
2266             CBP(pinfo,OPS_PTAG_CT_ENCRYPTED_SECRET_KEY,&content);
2267
2268             return 1;
2269             }
2270
2271         keysize=ops_key_size(C.secret_key.algorithm);
2272         assert(keysize > 0 && keysize <= OPS_MAX_KEY_SIZE);
2273
2274         hashsize=ops_hash_size(C.secret_key.hash_algorithm);
2275         assert(hashsize > 0 && hashsize <= OPS_MAX_HASH_SIZE);
2276
2277         for(n=0 ; n*hashsize < keysize ; ++n)
2278             {
2279             int i;
2280
2281             ops_hash_any(&hashes[n],C.secret_key.hash_algorithm);
2282             hashes[n].init(&hashes[n]);
2283             // preload hashes with zeroes...
2284             for(i=0 ; i < n ; ++i)
2285                 hashes[n].add(&hashes[n],(unsigned char *)"",1);
2286             }
2287
2288         l=strlen(passphrase);
2289
2290         for(n=0 ; n*hashsize < keysize ; ++n)
2291             {
2292             unsigned i;
2293
2294             switch(C.secret_key.s2k_specifier)
2295                 {
2296             case OPS_S2KS_SALTED:
2297                 hashes[n].add(&hashes[n],C.secret_key.salt,OPS_SALT_SIZE);
2298                 // flow through...
2299             case OPS_S2KS_SIMPLE:
2300                 hashes[n].add(&hashes[n],(unsigned char*)passphrase,l);
2301                 break;
2302
2303             case OPS_S2KS_ITERATED_AND_SALTED:
2304                 for(i=0 ; i < C.secret_key.octet_count ; i+=l+OPS_SALT_SIZE)
2305                     {
2306                     int j=l+OPS_SALT_SIZE;
2307
2308                     if(i+j > C.secret_key.octet_count && i != 0)
2309                         j=C.secret_key.octet_count-i;
2310
2311                     hashes[n].add(&hashes[n],C.secret_key.salt,
2312                                   j > OPS_SALT_SIZE ? OPS_SALT_SIZE : j);
2313                     if(j > OPS_SALT_SIZE)
2314                         hashes[n].add(&hashes[n],(unsigned char *)passphrase,j-OPS_SALT_SIZE);
2315                     }
2316                        
2317                 }
2318             }
2319
2320         for(n=0 ; n*hashsize < keysize ; ++n)
2321             {
2322             int r=hashes[n].finish(&hashes[n],key+n*hashsize);
2323             assert(r == hashsize);
2324             }
2325
2326         free(passphrase);
2327
2328         ops_crypt_any(&decrypt,C.secret_key.algorithm);
2329     if (debug)
2330         {
2331         unsigned int i=0;
2332         fprintf(stderr,"\nREADING:\niv=");
2333         for (i=0; i<ops_block_size(C.secret_key.algorithm); i++)
2334             {
2335             fprintf(stderr, "%02x ", C.secret_key.iv[i]);
2336             }
2337         fprintf(stderr,"\n");
2338         fprintf(stderr,"key=");
2339         for (i=0; i<CAST_KEY_LENGTH; i++)
2340             {
2341             fprintf(stderr, "%02x ", key[i]);
2342             }
2343         fprintf(stderr,"\n");
2344         }
2345         decrypt.set_iv(&decrypt,C.secret_key.iv);
2346         decrypt.set_key(&decrypt,key);
2347
2348     // now read encrypted data
2349
2350     ops_reader_push_decrypt(pinfo,&decrypt,region);
2351
2352         /* Since all known encryption for PGP doesn't compress, we can
2353            limit to the same length as the current region (for now).
2354         */
2355         ops_init_subregion(&encregion,NULL);
2356         encregion.length=region->length-region->length_read;
2357         if(C.secret_key.public_key.version != OPS_V4)
2358         {
2359             encregion.length-=2;
2360         }
2361         saved_region=region;
2362         region=&encregion;
2363         }
2364
2365     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
2366         {
2367         ops_hash_sha1(&checkhash);
2368         ops_reader_push_hash(pinfo,&checkhash);
2369         }
2370     else
2371         {
2372         ops_reader_push_sum16(pinfo);
2373         }
2374
2375     switch(C.secret_key.public_key.algorithm)
2376         {
2377     case OPS_PKA_RSA:
2378     case OPS_PKA_RSA_ENCRYPT_ONLY:
2379     case OPS_PKA_RSA_SIGN_ONLY:
2380         if(!limited_read_mpi(&C.secret_key.key.rsa.d,region,pinfo)
2381            || !limited_read_mpi(&C.secret_key.key.rsa.p,region,pinfo)
2382            || !limited_read_mpi(&C.secret_key.key.rsa.q,region,pinfo)
2383            || !limited_read_mpi(&C.secret_key.key.rsa.u,region,pinfo))
2384             ret=0;
2385
2386         break;
2387
2388     case OPS_PKA_DSA:
2389        
2390         if(!limited_read_mpi(&C.secret_key.key.dsa.x,region,pinfo))
2391             ret=0;
2392         break;
2393  
2394     default:
2395         OPS_ERROR_2(&pinfo->errors,OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,"Unsupported Public Key algorithm %d (%s)",C.secret_key.public_key.algorithm,ops_show_pka(C.secret_key.public_key.algorithm));
2396         ret=0;
2397         //      assert(0);
2398         }
2399
2400     if (debug)
2401         {
2402         fprintf(stderr,"4 MPIs read\n");
2403         //        ops_print_secret_key_verbose(OPS_PTAG_CT_SECRET_KEY, &C.secret_key);
2404         }
2405
2406     pinfo->reading_v3_secret=ops_false;
2407
2408     if(C.secret_key.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED)
2409         {
2410         unsigned char hash[20];
2411
2412         ops_reader_pop_hash(pinfo);
2413         checkhash.finish(&checkhash,hash);
2414            
2415         if(crypted && C.secret_key.public_key.version != OPS_V4)
2416             {
2417             ops_reader_pop_decrypt(pinfo);
2418             region=saved_region;
2419             }
2420
2421         if(ret)
2422             {
2423             if(!limited_read(C.secret_key.checkhash,20,region,pinfo))
2424                 return 0;
2425
2426             if(memcmp(hash,C.secret_key.checkhash,20))
2427                 ERRP(pinfo,"Hash mismatch in secret key");
2428             }
2429         }
2430     else
2431         {
2432         unsigned short sum;
2433
2434         sum=ops_reader_pop_sum16(pinfo);
2435
2436         if(crypted && C.secret_key.public_key.version != OPS_V4)
2437             {
2438             ops_reader_pop_decrypt(pinfo);
2439             region=saved_region;
2440             }
2441
2442         if(ret)
2443             {
2444             if(!limited_read_scalar(&C.secret_key.checksum,2,region,
2445                                     pinfo))
2446                 return 0;
2447
2448             if(sum != C.secret_key.checksum)
2449                 ERRP(pinfo,"Checksum mismatch in secret key");
2450             }
2451         }
2452
2453     if(crypted && C.secret_key.public_key.version == OPS_V4)
2454         {
2455         ops_reader_pop_decrypt(pinfo);
2456         }
2457
2458     assert(!ret || region->length_read == region->length);
2459
2460     if(!ret)
2461         return 0;
2462
2463     CBP(pinfo,OPS_PTAG_CT_SECRET_KEY,&content);
2464
2465     if (debug)
2466         { fprintf(stderr, "--- end of parse_secret_key\n\n"); }
2467
2468     return 1;
2469     }
2470
2471 /**
2472    \ingroup Core_ReadPackets
2473    \brief Parse a Public Key Session Key packet
2474 */
2475 static int parse_pk_session_key(ops_region_t *region,
2476                                 ops_parse_info_t *pinfo)
2477     {
2478     unsigned char c[1]="";
2479     ops_parser_content_t content;
2480     ops_parser_content_t pc;
2481
2482     int n;
2483     BIGNUM *enc_m;
2484     unsigned k;
2485     const ops_secret_key_t *secret;
2486     unsigned char cs[2];
2487     unsigned char* iv;
2488
2489     // Can't rely on it being CAST5
2490     // \todo FIXME RW
2491     //    const size_t sz_unencoded_m_buf=CAST_KEY_LENGTH+1+2;
2492     const size_t sz_unencoded_m_buf=1024;
2493     unsigned char unencoded_m_buf[sz_unencoded_m_buf];
2494    
2495     if(!limited_read(c,1,region,pinfo))
2496         return 0;
2497     C.pk_session_key.version=c[0];
2498     if(C.pk_session_key.version != OPS_PKSK_V3)
2499         {
2500         OPS_ERROR_1(&pinfo->errors, OPS_E_PROTO_BAD_PKSK_VRSN,
2501               "Bad public-key encrypted session key version (%d)",
2502               C.pk_session_key.version);
2503         return 0;
2504         }
2505
2506     if(!limited_read(C.pk_session_key.key_id,
2507                      sizeof C.pk_session_key.key_id,region,pinfo))
2508         return 0;
2509
2510     if (debug)
2511         {
2512         int i;
2513         int x=sizeof C.pk_session_key.key_id;
2514         printf("session key: public key id: x=%d\n",x);
2515         for (i=0; i<x; i++)
2516             printf("%2x ", C.pk_session_key.key_id[i]);
2517         printf("\n");
2518         }
2519
2520     if(!limited_read(c,1,region,pinfo))
2521         return 0;
2522     C.pk_session_key.algorithm=c[0];
2523     switch(C.pk_session_key.algorithm)
2524         {
2525     case OPS_PKA_RSA:
2526         if(!limited_read_mpi(&C.pk_session_key.parameters.rsa.encrypted_m,
2527                              region,pinfo))
2528             return 0;
2529         enc_m=C.pk_session_key.parameters.rsa.encrypted_m;
2530         break;
2531
2532     case OPS_PKA_ELGAMAL:
2533         if(!limited_read_mpi(&C.pk_session_key.parameters.elgamal.g_to_k,
2534                              region,pinfo)
2535            || !limited_read_mpi(&C.pk_session_key.parameters.elgamal.encrypted_m,
2536                              region,pinfo))
2537             return 0;
2538         enc_m=C.pk_session_key.parameters.elgamal.encrypted_m;
2539         break;
2540
2541     default:
2542         OPS_ERROR_1(&pinfo->errors, OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2543                     "Unknown public key algorithm in session key (%s)",
2544                     ops_show_pka(C.pk_session_key.algorithm));
2545         return 0;
2546         }
2547
2548     memset(&pc,'\0',sizeof pc);
2549     secret=NULL;
2550     pc.content.get_secret_key.secret_key=&secret;
2551     pc.content.get_secret_key.pk_session_key=&C.pk_session_key;
2552
2553     CBP(pinfo,OPS_PARSER_CMD_GET_SECRET_KEY,&pc);
2554
2555     if(!secret)
2556         {
2557         CBP(pinfo,OPS_PTAG_CT_ENCRYPTED_PK_SESSION_KEY,&content);
2558
2559         return 1;
2560         }
2561
2562     //    n=ops_decrypt_mpi(buf,sizeof buf,enc_m,secret);
2563     n=ops_decrypt_and_unencode_mpi(unencoded_m_buf,sizeof unencoded_m_buf,enc_m,secret);
2564
2565     if(n < 1)
2566         {
2567         ERRP(pinfo,"decrypted message too short");
2568         return 0;
2569         }
2570
2571     // PKA
2572     C.pk_session_key.symmetric_algorithm=unencoded_m_buf[0];
2573
2574     if (!ops_is_sa_supported(C.pk_session_key.symmetric_algorithm))
2575         {
2576         // ERR1P
2577         OPS_ERROR_1(&pinfo->errors,OPS_E_ALG_UNSUPPORTED_SYMMETRIC_ALG,
2578                     "Symmetric algorithm %s not supported",
2579                     ops_show_symmetric_algorithm(C.pk_session_key.symmetric_algorithm));
2580         return 0;
2581         }
2582
2583     k=ops_key_size(C.pk_session_key.symmetric_algorithm);
2584
2585     if((unsigned)n != k+3)
2586         {
2587         OPS_ERROR_2(&pinfo->errors,OPS_E_PROTO_DECRYPTED_MSG_WRONG_LEN,
2588                     "decrypted message wrong length (got %d expected %d)",
2589                     n,k+3);
2590         return 0;
2591         }
2592    
2593     assert(k <= sizeof C.pk_session_key.key);
2594
2595     memcpy(C.pk_session_key.key,unencoded_m_buf+1,k);
2596
2597     if (debug)
2598         {
2599         printf("session key recovered (len=%d):\n",k);
2600         unsigned int j;
2601         for(j=0; j<k; j++)
2602             printf("%2x ", C.pk_session_key.key[j]);
2603         printf("\n");
2604         }
2605
2606     C.pk_session_key.checksum=unencoded_m_buf[k+1]+(unencoded_m_buf[k+2] << 8);
2607     if (debug)
2608         {
2609         printf("session key checksum: %2x %2x\n", unencoded_m_buf[k+1], unencoded_m_buf[k+2]);
2610         }
2611
2612     // Check checksum
2613
2614     ops_calc_session_key_checksum(&C.pk_session_key, &cs[0]);
2615     if (unencoded_m_buf[k+1]!=cs[0] || unencoded_m_buf[k+2]!=cs[1])
2616         {
2617         OPS_ERROR_4(&pinfo->errors, OPS_E_PROTO_BAD_SK_CHECKSUM,
2618                     "Session key checksum wrong: expected %2x %2x, got %2x %2x",
2619               cs[0], cs[1], unencoded_m_buf[k+1], unencoded_m_buf[k+2]);
2620         return 0;
2621         }
2622
2623     // all is well
2624     CBP(pinfo,OPS_PTAG_CT_PK_SESSION_KEY,&content);
2625
2626     ops_crypt_any(&pinfo->decrypt,C.pk_session_key.symmetric_algorithm);
2627     iv=ops_mallocz(pinfo->decrypt.blocksize);
2628     pinfo->decrypt.set_iv(&pinfo->decrypt, iv);
2629     pinfo->decrypt.set_key(&pinfo->decrypt,C.pk_session_key.key);
2630     ops_encrypt_init(&pinfo->decrypt);
2631     return 1;
2632     }
2633
2634 // XXX: make this static?
2635 int ops_decrypt_se_data(ops_content_tag_t tag,ops_region_t *region,
2636                      ops_parse_info_t *pinfo)
2637     {
2638     int r=1;
2639     ops_crypt_t *decrypt=ops_parse_get_decrypt(pinfo);
2640
2641     if(decrypt)
2642         {
2643         unsigned char buf[OPS_MAX_BLOCK_SIZE+2]="";
2644         size_t b=decrypt->blocksize;
2645         //      ops_parser_content_t content;
2646         ops_region_t encregion;
2647
2648
2649         ops_reader_push_decrypt(pinfo,decrypt,region);
2650
2651         ops_init_subregion(&encregion,NULL);
2652         encregion.length=b+2;
2653
2654         if(!exact_limited_read(buf,b+2,&encregion,pinfo))
2655             return 0;
2656
2657         if(buf[b-2] != buf[b] || buf[b-1] != buf[b+1])
2658             {
2659             ops_reader_pop_decrypt(pinfo);
2660             OPS_ERROR_4(&pinfo->errors, OPS_E_PROTO_BAD_SYMMETRIC_DECRYPT,
2661                         "Bad symmetric decrypt (%02x%02x vs %02x%02x)",
2662                         buf[b-2],buf[b-1],buf[b],buf[b+1]);
2663             return 0;
2664             }
2665
2666         if(tag == OPS_PTAG_CT_SE_DATA_BODY)
2667             {
2668             decrypt->decrypt_resync(decrypt);
2669             decrypt->block_encrypt(decrypt,decrypt->civ,decrypt->civ);
2670             }
2671
2672
2673         r=ops_parse(pinfo);
2674
2675         ops_reader_pop_decrypt(pinfo);
2676     }
2677     else
2678         {
2679         ops_parser_content_t content;
2680
2681         while(region->length_read < region->length)
2682             {
2683             unsigned l=region->length-region->length_read;
2684
2685             if(l > sizeof C.se_data_body.data)
2686                 l=sizeof C.se_data_body.data;
2687
2688             if(!limited_read(C.se_data_body.data,l,region,pinfo))
2689                 return 0;
2690
2691             C.se_data_body.length=l;
2692
2693             CBP(pinfo,tag,&content);
2694             }
2695         }
2696
2697     return r;
2698     }
2699
2700 int ops_decrypt_se_ip_data(ops_content_tag_t tag,ops_region_t *region,
2701                      ops_parse_info_t *pinfo)
2702     {
2703     int r=1;
2704     ops_crypt_t *decrypt=ops_parse_get_decrypt(pinfo);
2705
2706     if(decrypt)
2707         {
2708         ops_reader_push_decrypt(pinfo,decrypt,region);
2709         ops_reader_push_se_ip_data(pinfo,decrypt,region);
2710
2711         r=ops_parse(pinfo);
2712
2713         //        assert(0);
2714         ops_reader_pop_se_ip_data(pinfo);
2715         ops_reader_pop_decrypt(pinfo);
2716         }
2717     else
2718         {
2719         ops_parser_content_t content;
2720        
2721         while(region->length_read < region->length)
2722             {
2723             unsigned l=region->length-region->length_read;
2724            
2725             if(l > sizeof C.se_data_body.data)
2726                 l=sizeof C.se_data_body.data;
2727            
2728             if(!limited_read(C.se_data_body.data,l,region,pinfo))
2729                 return 0;
2730            
2731             C.se_data_body.length=l;
2732            
2733             CBP(pinfo,tag,&content);
2734             }
2735         }
2736
2737     return r;
2738     }
2739
2740 /**
2741    \ingroup Core_ReadPackets
2742    \brief Read a Symmetrically Encrypted packet
2743 */
2744 static int parse_se_data(ops_region_t *region,ops_parse_info_t *pinfo)
2745     {
2746     ops_parser_content_t content;
2747
2748     /* there's no info to go with this, so just announce it */
2749     CBP(pinfo,OPS_PTAG_CT_SE_DATA_HEADER,&content);
2750
2751     /* The content of an encrypted data packet is more OpenPGP packets
2752        once decrypted, so recursively handle them */
2753     return ops_decrypt_se_data(OPS_PTAG_CT_SE_DATA_BODY,region,pinfo);
2754     }
2755
2756 /**
2757    \ingroup Core_ReadPackets
2758    \brief Read a Symmetrically Encrypted Integrity Protected packet
2759 */
2760 static int parse_se_ip_data(ops_region_t *region,ops_parse_info_t *pinfo)
2761     {
2762     unsigned char c[1]="";
2763     ops_parser_content_t content;
2764
2765     if(!limited_read(c,1,region,pinfo))
2766         return 0;
2767     C.se_ip_data_header.version=c[0];
2768     assert(C.se_ip_data_header.version == OPS_SE_IP_V1);
2769
2770     /* The content of an encrypted data packet is more OpenPGP packets
2771        once decrypted, so recursively handle them */
2772     return ops_decrypt_se_ip_data(OPS_PTAG_CT_SE_IP_DATA_BODY,region,pinfo);
2773     }
2774
2775 /**
2776    \ingroup Core_ReadPackets
2777    \brief Read a MDC packet
2778 */
2779 static int parse_mdc(ops_region_t *region, ops_parse_info_t *pinfo)
2780         {
2781         ops_parser_content_t content;
2782
2783         if (!limited_read((unsigned char *)&C.mdc,OPS_SHA1_HASH_SIZE,region,pinfo))
2784                 return 0;
2785
2786         CBP(pinfo,OPS_PTAG_CT_MDC,&content);
2787
2788         return 1;
2789         }
2790
2791 /**
2792  * \ingroup Core_ReadPackets
2793  * \brief Parse one packet.
2794  *
2795  * This function parses the packet tag.  It computes the value of the
2796  * content tag and then calls the appropriate function to handle the
2797  * content.
2798  *
2799  * \param *pinfo        How to parse
2800  * \param *pktlen       On return, will contain number of bytes in packet
2801  * \return 1 on success, 0 on error, -1 on EOF */
2802 static int ops_parse_one_packet(ops_parse_info_t *pinfo,
2803                                 unsigned long *pktlen)
2804     {
2805     unsigned char ptag[1];
2806     ops_parser_content_t content;
2807     int r;
2808     ops_region_t region;
2809     ops_boolean_t indeterminate=ops_false;
2810
2811     C.ptag.position=pinfo->rinfo.position;
2812
2813     r=base_read(ptag,1,pinfo);
2814
2815     // errors in the base read are effectively EOF.
2816     if(r <= 0)
2817         return -1;
2818
2819     *pktlen=0;
2820
2821     if(!(*ptag&OPS_PTAG_ALWAYS_SET))
2822         {
2823         C.error.error="Format error (ptag bit not set)";
2824         CBP(pinfo,OPS_PARSER_ERROR,&content);
2825         OPS_ERROR(&pinfo->errors, OPS_E_P_UNKNOWN_TAG, C.error.error);
2826         return 0;
2827         }
2828     C.ptag.new_format=!!(*ptag&OPS_PTAG_NEW_FORMAT);
2829     if(C.ptag.new_format)
2830         {
2831         C.ptag.content_tag=*ptag&OPS_PTAG_NF_CONTENT_TAG_MASK;
2832         C.ptag.length_type=0;
2833         if(!read_new_length(&C.ptag.length,pinfo))
2834             return 0;
2835
2836         }
2837     else
2838         {
2839         ops_boolean_t rb = ops_false;
2840
2841         C.ptag.content_tag=(*ptag&OPS_PTAG_OF_CONTENT_TAG_MASK)
2842             >> OPS_PTAG_OF_CONTENT_TAG_SHIFT;
2843         C.ptag.length_type=*ptag&OPS_PTAG_OF_LENGTH_TYPE_MASK;
2844         switch(C.ptag.length_type)
2845             {
2846         case OPS_PTAG_OF_LT_ONE_BYTE:
2847             rb=_read_scalar(&C.ptag.length,1,pinfo);
2848             break;
2849
2850         case OPS_PTAG_OF_LT_TWO_BYTE:
2851             rb=_read_scalar(&C.ptag.length,2,pinfo);
2852             break;
2853
2854         case OPS_PTAG_OF_LT_FOUR_BYTE:
2855             rb=_read_scalar(&C.ptag.length,4,pinfo);
2856             break;
2857
2858         case OPS_PTAG_OF_LT_INDETERMINATE:
2859             C.ptag.length=0;
2860             indeterminate=ops_true;
2861             rb=ops_true;
2862             break;
2863             }
2864         if(!rb)
2865             {
2866             OPS_ERROR(&pinfo->errors, OPS_E_P, "Cannot read tag length");
2867             return 0;
2868             }
2869         }
2870
2871     CBP(pinfo,OPS_PARSER_PTAG,&content);
2872
2873     ops_init_subregion(&region,NULL);
2874     region.length=C.ptag.length;
2875     region.indeterminate=indeterminate;
2876     switch(C.ptag.content_tag)
2877         {
2878     case OPS_PTAG_CT_SIGNATURE:
2879         r=parse_signature(&region,pinfo);
2880         break;
2881
2882     case OPS_PTAG_CT_PUBLIC_KEY:
2883     case OPS_PTAG_CT_PUBLIC_SUBKEY:
2884         r=parse_public_key(C.ptag.content_tag,&region,pinfo);
2885         break;
2886
2887     case OPS_PTAG_CT_TRUST:
2888         r=parse_trust(&region, pinfo);
2889         break;
2890      
2891     case OPS_PTAG_CT_USER_ID:
2892         r=parse_user_id(&region,pinfo);
2893         break;
2894
2895     case OPS_PTAG_CT_COMPRESSED:
2896         r=parse_compressed(&region,pinfo);
2897         break;
2898
2899     case OPS_PTAG_CT_ONE_PASS_SIGNATURE:
2900         r=parse_one_pass(&region,pinfo);
2901         break;
2902
2903     case OPS_PTAG_CT_LITERAL_DATA:
2904         r=parse_literal_data(&region,pinfo);
2905         break;
2906
2907     case OPS_PTAG_CT_USER_ATTRIBUTE:
2908         r=parse_user_attribute(&region,pinfo);
2909         break;
2910
2911     case OPS_PTAG_CT_SECRET_KEY:
2912         r=parse_secret_key(&region,pinfo);
2913         break;
2914
2915     case OPS_PTAG_CT_SECRET_SUBKEY:
2916         r=parse_secret_key(&region,pinfo);
2917         break;
2918
2919     case OPS_PTAG_CT_PK_SESSION_KEY:
2920         r=parse_pk_session_key(&region,pinfo);
2921         break;
2922
2923     case OPS_PTAG_CT_SE_DATA:
2924         r=parse_se_data(&region,pinfo);
2925         break;
2926
2927     case OPS_PTAG_CT_SE_IP_DATA:
2928         r=parse_se_ip_data(&region,pinfo);
2929         break;
2930
2931     case OPS_PTAG_CT_MDC:
2932          r=parse_mdc(&region, pinfo);
2933          break;
2934
2935     default:
2936         OPS_ERROR_1(&pinfo->errors,OPS_E_P_UNKNOWN_TAG,
2937                     "Unknown content tag 0x%x", C.ptag.content_tag);
2938         r=0;
2939         }
2940
2941     /* Ensure that the entire packet has been consumed */
2942
2943     if(region.length != region.length_read && !region.indeterminate)
2944         if(!consume_packet(&region,pinfo,ops_false))
2945             r=-1;
2946
2947     // also consume it if there's been an error?
2948     // \todo decide what to do about an error on an
2949     //       indeterminate packet
2950     if (r==0)
2951         {
2952         if (!consume_packet(&region,pinfo,ops_false))
2953             r=-1;
2954         }
2955
2956     /* set pktlen */
2957
2958     *pktlen=pinfo->rinfo.alength;
2959
2960     /* do callback on entire packet, if desired and there was no error */
2961
2962     if(r > 0 && pinfo->rinfo.accumulate)
2963         {
2964         C.packet.length=pinfo->rinfo.alength;
2965         C.packet.raw=pinfo->rinfo.accumulated;
2966        
2967         CBP(pinfo,OPS_PARSER_PACKET_END,&content);
2968         //free(pinfo->rinfo.accumulated);
2969         pinfo->rinfo.accumulated=NULL;
2970         pinfo->rinfo.asize=0;
2971         }
2972     pinfo->rinfo.alength=0;
2973        
2974     if(r < 0)
2975         return -1;
2976
2977     return r ? 1 : 0;
2978     }
2979
2980 /**
2981  * \ingroup Core_ReadPackets
2982  *
2983  * \brief Parse packets from an input stream until EOF or error.
2984  *
2985  * \details Setup the necessary parsing configuration in "pinfo" before calling ops_parse().
2986  *
2987  * That information includes :
2988  *
2989  * - a "reader" function to be used to get the data to be parsed
2990  *
2991  * - a "callback" function to be called when this library has identified
2992  * a parseable object within the data
2993  *
2994  * - whether the calling function wants the signature subpackets returned raw, parsed or not at all.
2995  *
2996  * After returning, pinfo->errors holds any errors encountered while parsing.
2997  *
2998  * \param pinfo Parsing configuration
2999  * \return              1 on success in all packets, 0 on error in any packet
3000  *
3001  * \sa CoreAPI Overview
3002  *
3003  * \sa ops_print_errors(), ops_parse_and_print_errors()
3004  *
3005  * Example code
3006  * \code
3007 ops_parse_cb_t* example_callback();
3008 void example()
3009  {
3010  int fd=0;
3011  ops_parse_info_t *pinfo=NULL;
3012  char *filename="pubring.gpg";
3013
3014  // setup pinfo to read from file with example callback
3015  fd=ops_setup_file_read(&pinfo, filename, NULL, example_callback, ops_false);
3016
3017  // specify how we handle signature subpackets
3018  ops_parse_options(pinfo, OPS_PTAG_SS_ALL, OPS_PARSE_PARSED);
3019  
3020  if (!ops_parse(pinfo))
3021    ops_print_errors(pinfo->errors);
3022
3023  ops_teardown_file_read(pinfo,fd);
3024  }
3025  * \endcode
3026  */
3027
3028 int ops_parse(ops_parse_info_t *pinfo)
3029     {
3030     int r;
3031     unsigned long pktlen;
3032
3033     do
3034         // Parse until we get a return code of 0 (error) or -1 (EOF)
3035         {
3036         r=ops_parse_one_packet(pinfo,&pktlen);
3037         } while (r > 0);
3038
3039     return pinfo->errors ? 0 : 1;
3040     return r == -1 ? 0 : 1;
3041     }
3042
3043 /**
3044 \ingroup Core_ReadPackets
3045 \brief Parse packets and print any errors
3046  * \param pinfo Parsing configuration
3047  * \return              1 on success in all packets, 0 on error in any packet
3048  * \sa CoreAPI Overview
3049  * \sa ops_parse()
3050 */
3051
3052 int ops_parse_and_print_errors(ops_parse_info_t *pinfo)
3053     {
3054     ops_parse(pinfo);
3055     ops_print_errors(pinfo->errors);
3056     return pinfo->errors ? 0 : 1;
3057     }
3058
3059 /**
3060  * \ingroup Core_ReadPackets
3061  *
3062  * \brief Specifies whether one or more signature
3063  * subpacket types should be returned parsed; or raw; or ignored.
3064  *
3065  * \param       pinfo   Pointer to previously allocated structure
3066  * \param       tag     Packet tag. OPS_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
3067  * \param       type    Parse type
3068  * \todo Make all packet types optional, not just subpackets */
3069 void ops_parse_options(ops_parse_info_t *pinfo,
3070                        ops_content_tag_t tag,
3071                        ops_parse_type_t type)
3072     {
3073     int t8,t7;
3074
3075     if(tag == OPS_PTAG_SS_ALL)
3076         {
3077         int n;
3078
3079         for(n=0 ; n < 256 ; ++n)
3080             ops_parse_options(pinfo,OPS_PTAG_SIGNATURE_SUBPACKET_BASE+n,
3081                               type);
3082         return;
3083         }
3084
3085     assert(tag >= OPS_PTAG_SIGNATURE_SUBPACKET_BASE
3086            && tag <= OPS_PTAG_SIGNATURE_SUBPACKET_BASE+NTAGS-1);
3087     t8=(tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)/8;
3088     t7=1 << ((tag-OPS_PTAG_SIGNATURE_SUBPACKET_BASE)&7);
3089     switch(type)
3090         {
3091     case OPS_PARSE_RAW:
3092         pinfo->ss_raw[t8] |= t7;
3093         pinfo->ss_parsed[t8] &= ~t7;
3094         break;
3095
3096     case OPS_PARSE_PARSED:
3097         pinfo->ss_raw[t8] &= ~t7;
3098         pinfo->ss_parsed[t8] |= t7;
3099         break;
3100
3101     case OPS_PARSE_IGNORE:
3102         pinfo->ss_raw[t8] &= ~t7;
3103         pinfo->ss_parsed[t8] &= ~t7;
3104         break;
3105         }
3106     }
3107
3108 /**
3109 \ingroup Core_ReadPackets
3110 \brief Creates a new zero-ed ops_parse_info_t struct
3111 \sa ops_parse_info_delete()
3112 */
3113 ops_parse_info_t *ops_parse_info_new(void)
3114     { return ops_mallocz(sizeof(ops_parse_info_t)); }
3115
3116 /**
3117 \ingroup Core_ReadPackets
3118 \brief Free ops_parse_info_t struct and its contents
3119 \sa ops_parse_info_new()
3120 */
3121 void ops_parse_info_delete(ops_parse_info_t *pinfo)
3122     {
3123     ops_parse_cb_info_t *cbinfo,*next;
3124
3125     for(cbinfo=pinfo->cbinfo.next ; cbinfo ; cbinfo=next)
3126         {
3127         next=cbinfo->next;
3128         free(cbinfo);
3129         }
3130     if(pinfo->rinfo.destroyer)
3131         pinfo->rinfo.destroyer(&pinfo->rinfo);
3132     ops_free_errors(pinfo->errors);
3133     if(pinfo->rinfo.accumulated)
3134         free(pinfo->rinfo.accumulated);
3135     free(pinfo);
3136     }
3137
3138 /**
3139 \ingroup Core_ReadPackets
3140 \brief Returns the parse_info's reader_info
3141 \return Pointer to the reader_info inside the parse_info
3142 */
3143 ops_reader_info_t *ops_parse_get_rinfo(ops_parse_info_t *pinfo)
3144     { return &pinfo->rinfo; }
3145
3146 /**
3147 \ingroup Core_ReadPackets
3148 \brief Sets the parse_info's callback
3149 This is used when adding the first callback in a stack of callbacks.
3150 \sa ops_parse_cb_push()
3151 */
3152
3153 void ops_parse_cb_set(ops_parse_info_t *pinfo,ops_parse_cb_t *cb,void *arg)
3154     {
3155     pinfo->cbinfo.cb=cb;
3156     pinfo->cbinfo.arg=arg;
3157     pinfo->cbinfo.errors=&pinfo->errors;
3158     }
3159
3160 /**
3161 \ingroup Core_ReadPackets
3162 \brief Adds a further callback to a stack of callbacks
3163 \sa ops_parse_cb_set()
3164 */
3165 void ops_parse_cb_push(ops_parse_info_t *pinfo,ops_parse_cb_t *cb,void *arg)
3166     {
3167     ops_parse_cb_info_t *cbinfo=malloc(sizeof *cbinfo);
3168
3169     *cbinfo=pinfo->cbinfo;
3170     pinfo->cbinfo.next=cbinfo;
3171     ops_parse_cb_set(pinfo,cb,arg);
3172     }
3173
3174 /**
3175 \ingroup Core_ReadPackets
3176 \brief Returns callback's arg
3177 */
3178 void *ops_parse_cb_get_arg(ops_parse_cb_info_t *cbinfo)
3179     { return cbinfo->arg; }
3180
3181 /**
3182 \ingroup Core_ReadPackets
3183 \brief Returns callback's errors
3184 */
3185 void *ops_parse_cb_get_errors(ops_parse_cb_info_t *cbinfo)
3186     { return cbinfo->errors; }
3187
3188 /**
3189 \ingroup Core_ReadPackets
3190 \brief Calls the parse_cb_info's callback if present
3191 \return Return value from callback, if present; else OPS_FINISHED
3192 */
3193 ops_parse_cb_return_t ops_parse_cb(const ops_parser_content_t *content,
3194                                    ops_parse_cb_info_t *cbinfo)
3195     {
3196     if(cbinfo->cb)
3197         return cbinfo->cb(content,cbinfo);
3198     else
3199         return OPS_FINISHED;
3200     }
3201
3202 /**
3203 \ingroup Core_ReadPackets
3204 \brief Calls the next callback  in the stack
3205 \return Return value from callback
3206 */
3207 ops_parse_cb_return_t ops_parse_stacked_cb(const ops_parser_content_t *content,
3208                                            ops_parse_cb_info_t *cbinfo)
3209     { return ops_parse_cb(content,cbinfo->next); }
3210
3211 /**
3212 \ingroup Core_ReadPackets
3213 \brief Returns the parse_info's errors
3214 \return parse_info's errors
3215 */
3216 ops_error_t *ops_parse_info_get_errors(ops_parse_info_t *pinfo)
3217     { return pinfo->errors; }
3218
3219 ops_crypt_t *ops_parse_get_decrypt(ops_parse_info_t *pinfo)
3220     {
3221     if(pinfo->decrypt.algorithm)
3222         return &pinfo->decrypt;
3223     return NULL;
3224     }
3225
3226 // XXX: this could be improved by sharing all hashes that are the
3227 // same, then duping them just before checking the signature.
3228 void ops_parse_hash_init(ops_parse_info_t *pinfo,ops_hash_algorithm_t type,
3229                          const unsigned char *keyid)
3230     {
3231     ops_parse_hash_info_t *hash;
3232
3233     pinfo->hashes=realloc(pinfo->hashes,
3234                           (pinfo->nhashes+1)*sizeof *pinfo->hashes);
3235     hash=&pinfo->hashes[pinfo->nhashes++];
3236
3237     ops_hash_any(&hash->hash,type);
3238     hash->hash.init(&hash->hash);
3239     memcpy(hash->keyid,keyid,sizeof hash->keyid);
3240     }
3241
3242 void ops_parse_hash_data(ops_parse_info_t *pinfo,const void *data,
3243                          size_t length)
3244     {
3245     size_t n;
3246
3247     for(n=0 ; n < pinfo->nhashes ; ++n)
3248         pinfo->hashes[n].hash.add(&pinfo->hashes[n].hash,data,length);
3249     }
3250
3251 ops_hash_t *ops_parse_hash_find(ops_parse_info_t *pinfo,
3252                                 const unsigned char keyid[OPS_KEY_ID_SIZE])
3253     {
3254     size_t n;
3255
3256     for(n=0 ; n < pinfo->nhashes ; ++n)
3257         if(!memcmp(pinfo->hashes[n].keyid,keyid,OPS_KEY_ID_SIZE))
3258             return &pinfo->hashes[n].hash;
3259     return NULL;
3260     }
3261
3262 /* vim:set textwidth=120: */
3263 /* vim:set ts=8: */
Note: See TracBrowser for help on using the browser.