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