xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/packet-parse.c (revision 88fcb00c0357f2d7c1774f86a352637bfda96184)
1 /*-
2  * Copyright (c) 2009 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Alistair Crooks (agc@NetBSD.org)
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 /*
30  * Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
31  * All rights reserved.
32  * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
33  * their moral rights under the UK Copyright Design and Patents Act 1988 to
34  * be recorded as the authors of this copyright work.
35  *
36  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
37  * use this file except in compliance with the License.
38  *
39  * You may obtain a copy of the License at
40  *     http://www.apache.org/licenses/LICENSE-2.0
41  *
42  * Unless required by applicable law or agreed to in writing, software
43  * distributed under the License is distributed on an "AS IS" BASIS,
44  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45  *
46  * See the License for the specific language governing permissions and
47  * limitations under the License.
48  */
49 
50 /** \file
51  * \brief Parser for OpenPGP packets
52  */
53 #include "config.h"
54 
55 #ifdef HAVE_SYS_CDEFS_H
56 #include <sys/cdefs.h>
57 #endif
58 
59 #if defined(__NetBSD__)
60 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
61 __RCSID("$NetBSD: packet-parse.c,v 1.50 2010/11/15 08:56:30 agc Exp $");
62 #endif
63 
64 #include <sys/types.h>
65 #include <sys/param.h>
66 
67 #ifdef HAVE_OPENSSL_CAST_H
68 #include <openssl/cast.h>
69 #endif
70 
71 #include <stdarg.h>
72 #include <stdlib.h>
73 #include <string.h>
74 
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 
79 #ifdef HAVE_LIMITS_H
80 #include <limits.h>
81 #endif
82 
83 #include "packet.h"
84 #include "packet-parse.h"
85 #include "keyring.h"
86 #include "errors.h"
87 #include "packet-show.h"
88 #include "create.h"
89 #include "readerwriter.h"
90 #include "netpgpdefs.h"
91 #include "crypto.h"
92 #include "netpgpdigest.h"
93 
94 #define ERRP(cbinfo, cont, err)	do {					\
95 	cont.u.error = err;						\
96 	CALLBACK(PGP_PARSER_ERROR, cbinfo, &cont);			\
97 	return 0;							\
98 	/*NOTREACHED*/							\
99 } while(/*CONSTCOND*/0)
100 
101 /**
102  * limread_data reads the specified amount of the subregion's data
103  * into a data_t structure
104  *
105  * \param data	Empty structure which will be filled with data
106  * \param len	Number of octets to read
107  * \param subregion
108  * \param stream	How to parse
109  *
110  * \return 1 on success, 0 on failure
111  */
112 static int
113 limread_data(pgp_data_t *data, unsigned len,
114 		  pgp_region_t *subregion, pgp_stream_t *stream)
115 {
116 	data->len = len;
117 
118 	if (subregion->length - subregion->readc < len) {
119 		(void) fprintf(stderr, "limread_data: bad length\n");
120 		return 0;
121 	}
122 
123 	data->contents = calloc(1, data->len);
124 	if (!data->contents) {
125 		return 0;
126 	}
127 
128 	return pgp_limited_read(stream, data->contents, data->len, subregion,
129 			&stream->errors, &stream->readinfo, &stream->cbinfo);
130 }
131 
132 /**
133  * read_data reads the remainder of the subregion's data
134  * into a data_t structure
135  *
136  * \param data
137  * \param subregion
138  * \param stream
139  *
140  * \return 1 on success, 0 on failure
141  */
142 static int
143 read_data(pgp_data_t *data, pgp_region_t *region, pgp_stream_t *stream)
144 {
145 	int	cc;
146 
147 	cc = region->length - region->readc;
148 	return (cc >= 0) ? limread_data(data, (unsigned)cc, region, stream) : 0;
149 }
150 
151 /**
152  * Reads the remainder of the subregion as a string.
153  * It is the user's responsibility to free the memory allocated here.
154  */
155 
156 static int
157 read_unsig_str(uint8_t **str, pgp_region_t *subregion,
158 		     pgp_stream_t *stream)
159 {
160 	size_t	len;
161 
162 	len = subregion->length - subregion->readc;
163 	if ((*str = calloc(1, len + 1)) == NULL) {
164 		return 0;
165 	}
166 	if (len &&
167 	    !pgp_limited_read(stream, *str, len, subregion, &stream->errors,
168 				     &stream->readinfo, &stream->cbinfo)) {
169 		return 0;
170 	}
171 	(*str)[len] = '\0';
172 	return 1;
173 }
174 
175 static int
176 read_string(char **str, pgp_region_t *subregion, pgp_stream_t *stream)
177 {
178 	return read_unsig_str((uint8_t **) str, subregion, stream);
179 }
180 
181 void
182 pgp_init_subregion(pgp_region_t *subregion, pgp_region_t *region)
183 {
184 	(void) memset(subregion, 0x0, sizeof(*subregion));
185 	subregion->parent = region;
186 }
187 
188 /*
189  * XXX: replace pgp_ptag_t with something more appropriate for limiting reads
190  */
191 
192 /**
193  * low-level function to read data from reader function
194  *
195  * Use this function, rather than calling the reader directly.
196  *
197  * If the accumulate flag is set in *stream, the function
198  * adds the read data to the accumulated data, and updates
199  * the accumulated length. This is useful if, for example,
200  * the application wants access to the raw data as well as the
201  * parsed data.
202  *
203  * This function will also try to read the entire amount asked for, but not
204  * if it is over INT_MAX. Obviously many callers will know that they
205  * never ask for that much and so can avoid the extra complexity of
206  * dealing with return codes and filled-in lengths.
207  *
208  * \param *dest
209  * \param *plength
210  * \param flags
211  * \param *stream
212  *
213  * \return PGP_R_OK
214  * \return PGP_R_PARTIAL_READ
215  * \return PGP_R_EOF
216  * \return PGP_R_EARLY_EOF
217  *
218  * \sa #pgp_reader_ret_t for details of return codes
219  */
220 
221 static int
222 sub_base_read(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
223 	      pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
224 {
225 	size_t          n;
226 
227 	/* reading more than this would look like an error */
228 	if (length > INT_MAX)
229 		length = INT_MAX;
230 
231 	for (n = 0; n < length;) {
232 		int	r;
233 
234 		r = readinfo->reader(stream, (char *) dest + n, length - n, errors,
235 			readinfo, cbinfo);
236 		if (r > (int)(length - n)) {
237 			(void) fprintf(stderr, "sub_base_read: bad read\n");
238 			return 0;
239 		}
240 		if (r < 0) {
241 			return r;
242 		}
243 		if (r == 0) {
244 			break;
245 		}
246 		n += (unsigned)r;
247 	}
248 
249 	if (n == 0) {
250 		return 0;
251 	}
252 	if (readinfo->accumulate) {
253 		if (readinfo->asize < readinfo->alength) {
254 			(void) fprintf(stderr, "sub_base_read: bad size\n");
255 			return 0;
256 		}
257 		if (readinfo->alength + n > readinfo->asize) {
258 			uint8_t	*temp;
259 
260 			readinfo->asize = (readinfo->asize * 2) + (unsigned)n;
261 			temp = realloc(readinfo->accumulated, readinfo->asize);
262 			if (temp == NULL) {
263 				(void) fprintf(stderr,
264 					"sub_base_read: bad alloc\n");
265 				return 0;
266 			}
267 			readinfo->accumulated = temp;
268 		}
269 		if (readinfo->asize < readinfo->alength + n) {
270 			(void) fprintf(stderr, "sub_base_read: bad realloc\n");
271 			return 0;
272 		}
273 		(void) memcpy(readinfo->accumulated + readinfo->alength, dest,
274 				n);
275 	}
276 	/* we track length anyway, because it is used for packet offsets */
277 	readinfo->alength += (unsigned)n;
278 	/* and also the position */
279 	readinfo->position += (unsigned)n;
280 
281 	return (int)n;
282 }
283 
284 int
285 pgp_stacked_read(pgp_stream_t *stream, void *dest, size_t length, pgp_error_t **errors,
286 		 pgp_reader_t *readinfo, pgp_cbdata_t *cbinfo)
287 {
288 	return sub_base_read(stream, dest, length, errors, readinfo->next, cbinfo);
289 }
290 
291 /* This will do a full read so long as length < MAX_INT */
292 static int
293 base_read(uint8_t *dest, size_t length, pgp_stream_t *stream)
294 {
295 	return sub_base_read(stream, dest, length, &stream->errors, &stream->readinfo,
296 			     &stream->cbinfo);
297 }
298 
299 /*
300  * Read a full size_t's worth. If the return is < than length, then
301  * *last_read tells you why - < 0 for an error, == 0 for EOF
302  */
303 
304 static size_t
305 full_read(pgp_stream_t *stream, uint8_t *dest,
306 		size_t length,
307 		int *last_read,
308 		pgp_error_t **errors,
309 		pgp_reader_t *readinfo,
310 		pgp_cbdata_t *cbinfo)
311 {
312 	size_t          t;
313 	int             r = 0;	/* preset in case some loon calls with length
314 				 * == 0 */
315 
316 	for (t = 0; t < length;) {
317 		r = sub_base_read(stream, dest + t, length - t, errors, readinfo,
318 				cbinfo);
319 		if (r <= 0) {
320 			*last_read = r;
321 			return t;
322 		}
323 		t += (size_t)r;
324 	}
325 
326 	*last_read = r;
327 
328 	return t;
329 }
330 
331 
332 
333 /** Read a scalar value of selected length from reader.
334  *
335  * Read an unsigned scalar value from reader in Big Endian representation.
336  *
337  * This function does not know or care about packet boundaries. It
338  * also assumes that an EOF is an error.
339  *
340  * \param *result	The scalar value is stored here
341  * \param *reader	Our reader
342  * \param length	How many bytes to read
343  * \return		1 on success, 0 on failure
344  */
345 static unsigned
346 _read_scalar(unsigned *result, unsigned length,
347 	     pgp_stream_t *stream)
348 {
349 	unsigned        t = 0;
350 
351 	if (length > sizeof(*result)) {
352 		(void) fprintf(stderr, "_read_scalar: bad length\n");
353 		return 0;
354 	}
355 
356 	while (length--) {
357 		uint8_t	c;
358 		int	r;
359 
360 		r = base_read(&c, 1, stream);
361 		if (r != 1)
362 			return 0;
363 		t = (t << 8) + c;
364 	}
365 
366 	*result = t;
367 	return 1;
368 }
369 
370 /**
371  * \ingroup Core_ReadPackets
372  * \brief Read bytes from a region within the packet.
373  *
374  * Read length bytes into the buffer pointed to by *dest.
375  * Make sure we do not read over the packet boundary.
376  * Updates the Packet Tag's pgp_ptag_t::readc.
377  *
378  * If length would make us read over the packet boundary, or if
379  * reading fails, we call the callback with an error.
380  *
381  * Note that if the region is indeterminate, this can return a short
382  * read - check region->last_read for the length. EOF is indicated by
383  * a success return and region->last_read == 0 in this case (for a
384  * region of known length, EOF is an error).
385  *
386  * This function makes sure to respect packet boundaries.
387  *
388  * \param dest		The destination buffer
389  * \param length	How many bytes to read
390  * \param region	Pointer to packet region
391  * \param errors    Error stack
392  * \param readinfo		Reader info
393  * \param cbinfo	Callback info
394  * \return		1 on success, 0 on error
395  */
396 unsigned
397 pgp_limited_read(pgp_stream_t *stream, uint8_t *dest,
398 			size_t length,
399 			pgp_region_t *region,
400 			pgp_error_t **errors,
401 			pgp_reader_t *readinfo,
402 			pgp_cbdata_t *cbinfo)
403 {
404 	size_t	r;
405 	int	lr;
406 
407 	if (!region->indeterminate &&
408 	    region->readc + length > region->length) {
409 		PGP_ERROR(errors, PGP_E_P_NOT_ENOUGH_DATA, "Not enough data");
410 		return 0;
411 	}
412 	r = full_read(stream, dest, length, &lr, errors, readinfo, cbinfo);
413 	if (lr < 0) {
414 		PGP_ERROR(errors, PGP_E_R_READ_FAILED, "Read failed");
415 		return 0;
416 	}
417 	if (!region->indeterminate && r != length) {
418 		PGP_ERROR(errors, PGP_E_R_READ_FAILED, "Read failed");
419 		return 0;
420 	}
421 	region->last_read = (unsigned)r;
422 	do {
423 		region->readc += (unsigned)r;
424 		if (region->parent && region->length > region->parent->length) {
425 			(void) fprintf(stderr,
426 				"ops_limited_read: bad length\n");
427 			return 0;
428 		}
429 	} while ((region = region->parent) != NULL);
430 	return 1;
431 }
432 
433 /**
434    \ingroup Core_ReadPackets
435    \brief Call pgp_limited_read on next in stack
436 */
437 unsigned
438 pgp_stacked_limited_read(pgp_stream_t *stream, uint8_t *dest, unsigned length,
439 			 pgp_region_t *region,
440 			 pgp_error_t **errors,
441 			 pgp_reader_t *readinfo,
442 			 pgp_cbdata_t *cbinfo)
443 {
444 	return pgp_limited_read(stream, dest, length, region, errors,
445 				readinfo->next, cbinfo);
446 }
447 
448 static unsigned
449 limread(uint8_t *dest, unsigned length,
450 	     pgp_region_t *region, pgp_stream_t *info)
451 {
452 	return pgp_limited_read(info, dest, length, region, &info->errors,
453 				&info->readinfo, &info->cbinfo);
454 }
455 
456 static unsigned
457 exact_limread(uint8_t *dest, unsigned len,
458 		   pgp_region_t *region,
459 		   pgp_stream_t *stream)
460 {
461 	unsigned   ret;
462 
463 	stream->exact_read = 1;
464 	ret = limread(dest, len, region, stream);
465 	stream->exact_read = 0;
466 	return ret;
467 }
468 
469 /** Skip over length bytes of this packet.
470  *
471  * Calls limread() to skip over some data.
472  *
473  * This function makes sure to respect packet boundaries.
474  *
475  * \param length	How many bytes to skip
476  * \param *region	Pointer to packet region
477  * \param *stream	How to parse
478  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
479  */
480 static int
481 limskip(unsigned length, pgp_region_t *region, pgp_stream_t *stream)
482 {
483 	uint8_t   buf[NETPGP_BUFSIZ];
484 
485 	while (length > 0) {
486 		unsigned	n = length % NETPGP_BUFSIZ;
487 
488 		if (!limread(buf, n, region, stream)) {
489 			return 0;
490 		}
491 		length -= n;
492 	}
493 	return 1;
494 }
495 
496 /** Read a scalar.
497  *
498  * Read a big-endian scalar of length bytes, respecting packet
499  * boundaries (by calling limread() to read the raw data).
500  *
501  * This function makes sure to respect packet boundaries.
502  *
503  * \param *dest		The scalar value is stored here
504  * \param length	How many bytes make up this scalar (at most 4)
505  * \param *region	Pointer to current packet region
506  * \param *stream	How to parse
507  * \param *cb		The callback
508  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
509  *
510  * \see RFC4880 3.1
511  */
512 static int
513 limread_scalar(unsigned *dest,
514 			unsigned len,
515 			pgp_region_t *region,
516 			pgp_stream_t *stream)
517 {
518 	uint8_t		c[4] = "";
519 	unsigned        t;
520 	unsigned        n;
521 
522 	if (len > 4) {
523 		(void) fprintf(stderr, "limread_scalar: bad length\n");
524 		return 0;
525 	}
526 	/*LINTED*/
527 	if (/*CONSTCOND*/sizeof(*dest) < 4) {
528 		(void) fprintf(stderr, "limread_scalar: bad dest\n");
529 		return 0;
530 	}
531 	if (!limread(c, len, region, stream)) {
532 		return 0;
533 	}
534 	for (t = 0, n = 0; n < len; ++n) {
535 		t = (t << 8) + c[n];
536 	}
537 	*dest = t;
538 	return 1;
539 }
540 
541 /** Read a scalar.
542  *
543  * Read a big-endian scalar of length bytes, respecting packet
544  * boundaries (by calling limread() to read the raw data).
545  *
546  * The value read is stored in a size_t, which is a different size
547  * from an unsigned on some platforms.
548  *
549  * This function makes sure to respect packet boundaries.
550  *
551  * \param *dest		The scalar value is stored here
552  * \param length	How many bytes make up this scalar (at most 4)
553  * \param *region	Pointer to current packet region
554  * \param *stream	How to parse
555  * \param *cb		The callback
556  * \return		1 on success, 0 on error (calls the cb with PGP_PARSER_ERROR in limread()).
557  *
558  * \see RFC4880 3.1
559  */
560 static int
561 limread_size_t(size_t *dest,
562 				unsigned length,
563 				pgp_region_t *region,
564 				pgp_stream_t *stream)
565 {
566 	unsigned        tmp;
567 
568 	/*
569 	 * Note that because the scalar is at most 4 bytes, we don't care if
570 	 * size_t is bigger than usigned
571 	 */
572 	if (!limread_scalar(&tmp, length, region, stream))
573 		return 0;
574 
575 	*dest = tmp;
576 	return 1;
577 }
578 
579 /** Read a timestamp.
580  *
581  * Timestamps in OpenPGP are unix time, i.e. seconds since The Epoch (1.1.1970).  They are stored in an unsigned scalar
582  * of 4 bytes.
583  *
584  * This function reads the timestamp using limread_scalar().
585  *
586  * This function makes sure to respect packet boundaries.
587  *
588  * \param *dest		The timestamp is stored here
589  * \param *ptag		Pointer to current packet's Packet Tag.
590  * \param *reader	Our reader
591  * \param *cb		The callback
592  * \return		see limread_scalar()
593  *
594  * \see RFC4880 3.5
595  */
596 static int
597 limited_read_time(time_t *dest, pgp_region_t *region,
598 		  pgp_stream_t *stream)
599 {
600 	uint8_t	c;
601 	time_t	mytime = 0;
602 	int	i;
603 
604 	/*
605          * Cannot assume that time_t is 4 octets long -
606 	 * SunOS 5.10 and NetBSD both have 64-bit time_ts.
607          */
608 	if (/* CONSTCOND */sizeof(time_t) == 4) {
609 		return limread_scalar((unsigned *)(void *)dest, 4, region, stream);
610 	}
611 	for (i = 0; i < 4; i++) {
612 		if (!limread(&c, 1, region, stream)) {
613 			return 0;
614 		}
615 		mytime = (mytime << 8) + c;
616 	}
617 	*dest = mytime;
618 	return 1;
619 }
620 
621 /**
622  * \ingroup Core_MPI
623  * Read a multiprecision integer.
624  *
625  * Large numbers (multiprecision integers, MPI) are stored in OpenPGP in two parts.  First there is a 2 byte scalar
626  * indicating the length of the following MPI in Bits.  Then follow the bits that make up the actual number, most
627  * significant bits first (Big Endian).  The most significant bit in the MPI is supposed to be 1 (unless the MPI is
628  * encrypted - then it may be different as the bit count refers to the plain text but the bits are encrypted).
629  *
630  * Unused bits (i.e. those filling up the most significant byte from the left to the first bits that counts) are
631  * supposed to be cleared - I guess. XXX - does anything actually say so?
632  *
633  * This function makes sure to respect packet boundaries.
634  *
635  * \param **pgn		return the integer there - the BIGNUM is created by BN_bin2bn() and probably needs to be freed
636  * 				by the caller XXX right ben?
637  * \param *ptag		Pointer to current packet's Packet Tag.
638  * \param *reader	Our reader
639  * \param *cb		The callback
640  * \return		1 on success, 0 on error (by limread_scalar() or limread() or if the MPI is not properly formed (XXX
641  * 				 see comment below - the callback is called with a PGP_PARSER_ERROR in case of an error)
642  *
643  * \see RFC4880 3.2
644  */
645 static int
646 limread_mpi(BIGNUM **pbn, pgp_region_t *region, pgp_stream_t *stream)
647 {
648 	uint8_t   buf[NETPGP_BUFSIZ] = "";
649 					/* an MPI has a 2 byte length part.
650 					 * Length is given in bits, so the
651 					 * largest we should ever need for
652 					 * the buffer is NETPGP_BUFSIZ bytes. */
653 	unsigned        length;
654 	unsigned        nonzero;
655 	unsigned	ret;
656 
657 	stream->reading_mpi_len = 1;
658 	ret = (unsigned)limread_scalar(&length, 2, region, stream);
659 
660 	stream->reading_mpi_len = 0;
661 	if (!ret)
662 		return 0;
663 
664 	nonzero = length & 7;	/* there should be this many zero bits in the
665 				 * MS byte */
666 	if (!nonzero)
667 		nonzero = 8;
668 	length = (length + 7) / 8;
669 
670 	if (length == 0) {
671 		/* if we try to read a length of 0, then fail */
672 		if (pgp_get_debug_level(__FILE__)) {
673 			(void) fprintf(stderr, "limread_mpi: 0 length\n");
674 		}
675 		return 0;
676 	}
677 	if (length > NETPGP_BUFSIZ) {
678 		(void) fprintf(stderr, "limread_mpi: bad length\n");
679 		return 0;
680 	}
681 	if (!limread(buf, length, region, stream)) {
682 		return 0;
683 	}
684 	if (((unsigned)buf[0] >> nonzero) != 0 ||
685 	    !((unsigned)buf[0] & (1U << (nonzero - 1U)))) {
686 		PGP_ERROR(&stream->errors, PGP_E_P_MPI_FORMAT_ERROR, "MPI Format error");
687 		/* XXX: Ben, one part of
688 		 * this constraint does
689 		 * not apply to
690 		 * encrypted MPIs the
691 		 * draft says. -- peter */
692 		return 0;
693 	}
694 	*pbn = BN_bin2bn(buf, (int)length, NULL);
695 	return 1;
696 }
697 
698 static unsigned read_new_length(unsigned *, pgp_stream_t *);
699 
700 /* allocate space, read, and stash data away in a virtual pkt */
701 static void
702 streamread(pgp_stream_t *stream, unsigned c)
703 {
704 	int	cc;
705 
706 	stream->virtualpkt = realloc(stream->virtualpkt, stream->virtualc + c);
707 	cc = stream->readinfo.reader(stream, &stream->virtualpkt[stream->virtualc],
708 		c, &stream->errors, &stream->readinfo, &stream->cbinfo);
709 	stream->virtualc += cc;
710 }
711 
712 /* coalesce all the partial blocks together */
713 static int
714 coalesce_blocks(pgp_stream_t *stream, unsigned length)
715 {
716 	unsigned	c;
717 
718 	stream->coalescing = 1;
719 	/* already read a partial block length - prime the array */
720 	streamread(stream, length);
721 	while (read_new_length(&c, stream) && stream->partial_read) {
722 		/* length we read is partial - add to end of array */
723 		streamread(stream, c);
724 	}
725 	/* not partial - add the last extent to the end of the array */
726 	streamread(stream, c);
727 	stream->coalescing = 0;
728 	return 1;
729 }
730 
731 /** Read some data with a New-Format length from reader.
732  *
733  * \sa Internet-Draft RFC4880.txt Section 4.2.2
734  *
735  * \param *length	Where the decoded length will be put
736  * \param *stream	How to parse
737  * \return		1 if OK, else 0
738  *
739  */
740 
741 static unsigned
742 read_new_length(unsigned *length, pgp_stream_t *stream)
743 {
744 	uint8_t   c;
745 
746 	stream->partial_read = 0;
747 	if (base_read(&c, 1, stream) != 1) {
748 		return 0;
749 	}
750 	if (c < 192) {
751 		/* 1. One-octet packet */
752 		*length = c;
753 		return 1;
754 	}
755 	if (c < 224) {
756 		/* 2. Two-octet packet */
757 		unsigned        t = (c - 192) << 8;
758 
759 		if (base_read(&c, 1, stream) != 1) {
760 			return 0;
761 		}
762 		*length = t + c + 192;
763 		return 1;
764 	}
765 	if (c < 255) {
766 		/* 3. Partial Body Length */
767 		stream->partial_read = 1;
768 		*length = 1 << (c & 0x1f);
769 		if (!stream->coalescing) {
770 			/* we have been called from coalesce_blocks -
771 			 * just return with the partial length */
772 			coalesce_blocks(stream, *length);
773 			*length = stream->virtualc;
774 		}
775 		return 1;
776 	}
777 	/* 4. Five-Octet packet */
778 	return _read_scalar(length, 4, stream);
779 }
780 
781 /** Read the length information for a new format Packet Tag.
782  *
783  * New style Packet Tags encode the length in one to five octets.  This function reads the right amount of bytes and
784  * decodes it to the proper length information.
785  *
786  * This function makes sure to respect packet boundaries.
787  *
788  * \param *length	return the length here
789  * \param *ptag		Pointer to current packet's Packet Tag.
790  * \param *reader	Our reader
791  * \param *cb		The callback
792  * \return		1 on success, 0 on error (by limread_scalar() or limread() or if the MPI is not properly formed (XXX
793  * 				 see comment below)
794  *
795  * \see RFC4880 4.2.2
796  * \see pgp_ptag_t
797  */
798 static int
799 limited_read_new_length(unsigned *length, pgp_region_t *region,
800 			pgp_stream_t *stream)
801 {
802 	uint8_t   c = 0x0;
803 
804 	if (!limread(&c, 1, region, stream)) {
805 		return 0;
806 	}
807 	if (c < 192) {
808 		*length = c;
809 		return 1;
810 	}
811 	if (c < 224) {
812 		unsigned        t = (c - 192) << 8;
813 
814 		if (!limread(&c, 1, region, stream)) {
815 			return 0;
816 		}
817 		*length = t + c + 192;
818 		return 1;
819 	}
820 	if (c < 255) {
821 		stream->partial_read = 1;
822 		*length = 1 << (c & 0x1f);
823 		if (!stream->coalescing) {
824 			/* we have been called from coalesce_blocks -
825 			 * just return with the partial length */
826 			coalesce_blocks(stream, *length);
827 			*length = stream->virtualc;
828 		}
829 		return 1;
830 	}
831 	return limread_scalar(length, 4, region, stream);
832 }
833 
834 /**
835 \ingroup Core_Create
836 \brief Free allocated memory
837 */
838 void
839 pgp_data_free(pgp_data_t *data)
840 {
841 	free(data->contents);
842 	data->contents = NULL;
843 	data->len = 0;
844 }
845 
846 /**
847 \ingroup Core_Create
848 \brief Free allocated memory
849 */
850 static void
851 string_free(char **str)
852 {
853 	free(*str);
854 	*str = NULL;
855 }
856 
857 /**
858 \ingroup Core_Create
859 \brief Free allocated memory
860 */
861 /* ! Free packet memory, set pointer to NULL */
862 void
863 pgp_subpacket_free(pgp_subpacket_t *packet)
864 {
865 	free(packet->raw);
866 	packet->raw = NULL;
867 }
868 
869 /**
870 \ingroup Core_Create
871 \brief Free allocated memory
872 */
873 static void
874 headers_free(pgp_headers_t *headers)
875 {
876 	unsigned        n;
877 
878 	for (n = 0; n < headers->headerc; ++n) {
879 		free(headers->headers[n].key);
880 		free(headers->headers[n].value);
881 	}
882 	free(headers->headers);
883 	headers->headers = NULL;
884 }
885 
886 /**
887 \ingroup Core_Create
888 \brief Free allocated memory
889 */
890 static void
891 cleartext_trailer_free(struct pgp_hash_t **trailer)
892 {
893 	free(*trailer);
894 	*trailer = NULL;
895 }
896 
897 /**
898 \ingroup Core_Create
899 \brief Free allocated memory
900 */
901 static void
902 cmd_get_passphrase_free(pgp_seckey_passphrase_t *skp)
903 {
904 	if (skp->passphrase && *skp->passphrase) {
905 		free(*skp->passphrase);
906 		*skp->passphrase = NULL;
907 	}
908 }
909 
910 /**
911 \ingroup Core_Create
912 \brief Free allocated memory
913 */
914 static void
915 free_BN(BIGNUM **pp)
916 {
917 	BN_free(*pp);
918 	*pp = NULL;
919 }
920 
921 /**
922  * \ingroup Core_Create
923  * \brief Free the memory used when parsing a signature
924  * \param sig
925  */
926 static void
927 sig_free(pgp_sig_t *sig)
928 {
929 	switch (sig->info.key_alg) {
930 	case PGP_PKA_RSA:
931 	case PGP_PKA_RSA_SIGN_ONLY:
932 		free_BN(&sig->info.sig.rsa.sig);
933 		break;
934 
935 	case PGP_PKA_DSA:
936 		free_BN(&sig->info.sig.dsa.r);
937 		free_BN(&sig->info.sig.dsa.s);
938 		break;
939 
940 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
941 		free_BN(&sig->info.sig.elgamal.r);
942 		free_BN(&sig->info.sig.elgamal.s);
943 		break;
944 
945 	case PGP_PKA_PRIVATE00:
946 	case PGP_PKA_PRIVATE01:
947 	case PGP_PKA_PRIVATE02:
948 	case PGP_PKA_PRIVATE03:
949 	case PGP_PKA_PRIVATE04:
950 	case PGP_PKA_PRIVATE05:
951 	case PGP_PKA_PRIVATE06:
952 	case PGP_PKA_PRIVATE07:
953 	case PGP_PKA_PRIVATE08:
954 	case PGP_PKA_PRIVATE09:
955 	case PGP_PKA_PRIVATE10:
956 		pgp_data_free(&sig->info.sig.unknown);
957 		break;
958 
959 	default:
960 		(void) fprintf(stderr, "sig_free: bad sig type\n");
961 	}
962 }
963 
964 /**
965 \ingroup Core_Create
966 \brief Free allocated memory
967 */
968 /* ! Free any memory allocated when parsing the packet content */
969 void
970 pgp_parser_content_free(pgp_packet_t *c)
971 {
972 	switch (c->tag) {
973 	case PGP_PARSER_PTAG:
974 	case PGP_PTAG_CT_COMPRESSED:
975 	case PGP_PTAG_SS_CREATION_TIME:
976 	case PGP_PTAG_SS_EXPIRATION_TIME:
977 	case PGP_PTAG_SS_KEY_EXPIRY:
978 	case PGP_PTAG_SS_TRUST:
979 	case PGP_PTAG_SS_ISSUER_KEY_ID:
980 	case PGP_PTAG_CT_1_PASS_SIG:
981 	case PGP_PTAG_SS_PRIMARY_USER_ID:
982 	case PGP_PTAG_SS_REVOCABLE:
983 	case PGP_PTAG_SS_REVOCATION_KEY:
984 	case PGP_PTAG_CT_LITDATA_HEADER:
985 	case PGP_PTAG_CT_LITDATA_BODY:
986 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_BODY:
987 	case PGP_PTAG_CT_UNARMOURED_TEXT:
988 	case PGP_PTAG_CT_ARMOUR_TRAILER:
989 	case PGP_PTAG_CT_SIGNATURE_HEADER:
990 	case PGP_PTAG_CT_SE_DATA_HEADER:
991 	case PGP_PTAG_CT_SE_IP_DATA_HEADER:
992 	case PGP_PTAG_CT_SE_IP_DATA_BODY:
993 	case PGP_PTAG_CT_MDC:
994 	case PGP_GET_SECKEY:
995 		break;
996 
997 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
998 		headers_free(&c->u.cleartext_head);
999 		break;
1000 
1001 	case PGP_PTAG_CT_ARMOUR_HEADER:
1002 		headers_free(&c->u.armour_header.headers);
1003 		break;
1004 
1005 	case PGP_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
1006 		cleartext_trailer_free(&c->u.cleartext_trailer);
1007 		break;
1008 
1009 	case PGP_PTAG_CT_TRUST:
1010 		pgp_data_free(&c->u.trust);
1011 		break;
1012 
1013 	case PGP_PTAG_CT_SIGNATURE:
1014 	case PGP_PTAG_CT_SIGNATURE_FOOTER:
1015 		sig_free(&c->u.sig);
1016 		break;
1017 
1018 	case PGP_PTAG_CT_PUBLIC_KEY:
1019 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
1020 		pgp_pubkey_free(&c->u.pubkey);
1021 		break;
1022 
1023 	case PGP_PTAG_CT_USER_ID:
1024 		pgp_userid_free(&c->u.userid);
1025 		break;
1026 
1027 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1028 		pgp_userid_free(&c->u.ss_signer);
1029 		break;
1030 
1031 	case PGP_PTAG_CT_USER_ATTR:
1032 		pgp_data_free(&c->u.userattr);
1033 		break;
1034 
1035 	case PGP_PTAG_SS_PREFERRED_SKA:
1036 		pgp_data_free(&c->u.ss_skapref);
1037 		break;
1038 
1039 	case PGP_PTAG_SS_PREFERRED_HASH:
1040 		pgp_data_free(&c->u.ss_hashpref);
1041 		break;
1042 
1043 	case PGP_PTAG_SS_PREF_COMPRESS:
1044 		pgp_data_free(&c->u.ss_zpref);
1045 		break;
1046 
1047 	case PGP_PTAG_SS_KEY_FLAGS:
1048 		pgp_data_free(&c->u.ss_key_flags);
1049 		break;
1050 
1051 	case PGP_PTAG_SS_KEYSERV_PREFS:
1052 		pgp_data_free(&c->u.ss_key_server_prefs);
1053 		break;
1054 
1055 	case PGP_PTAG_SS_FEATURES:
1056 		pgp_data_free(&c->u.ss_features);
1057 		break;
1058 
1059 	case PGP_PTAG_SS_NOTATION_DATA:
1060 		pgp_data_free(&c->u.ss_notation.name);
1061 		pgp_data_free(&c->u.ss_notation.value);
1062 		break;
1063 
1064 	case PGP_PTAG_SS_REGEXP:
1065 		string_free(&c->u.ss_regexp);
1066 		break;
1067 
1068 	case PGP_PTAG_SS_POLICY_URI:
1069 		string_free(&c->u.ss_policy);
1070 		break;
1071 
1072 	case PGP_PTAG_SS_PREF_KEYSERV:
1073 		string_free(&c->u.ss_keyserv);
1074 		break;
1075 
1076 	case PGP_PTAG_SS_USERDEFINED00:
1077 	case PGP_PTAG_SS_USERDEFINED01:
1078 	case PGP_PTAG_SS_USERDEFINED02:
1079 	case PGP_PTAG_SS_USERDEFINED03:
1080 	case PGP_PTAG_SS_USERDEFINED04:
1081 	case PGP_PTAG_SS_USERDEFINED05:
1082 	case PGP_PTAG_SS_USERDEFINED06:
1083 	case PGP_PTAG_SS_USERDEFINED07:
1084 	case PGP_PTAG_SS_USERDEFINED08:
1085 	case PGP_PTAG_SS_USERDEFINED09:
1086 	case PGP_PTAG_SS_USERDEFINED10:
1087 		pgp_data_free(&c->u.ss_userdef);
1088 		break;
1089 
1090 	case PGP_PTAG_SS_RESERVED:
1091 		pgp_data_free(&c->u.ss_unknown);
1092 		break;
1093 
1094 	case PGP_PTAG_SS_REVOCATION_REASON:
1095 		string_free(&c->u.ss_revocation.reason);
1096 		break;
1097 
1098 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1099 		pgp_data_free(&c->u.ss_embedded_sig);
1100 		break;
1101 
1102 	case PGP_PARSER_PACKET_END:
1103 		pgp_subpacket_free(&c->u.packet);
1104 		break;
1105 
1106 	case PGP_PARSER_ERROR:
1107 	case PGP_PARSER_ERRCODE:
1108 		break;
1109 
1110 	case PGP_PTAG_CT_SECRET_KEY:
1111 	case PGP_PTAG_CT_ENCRYPTED_SECRET_KEY:
1112 		pgp_seckey_free(&c->u.seckey);
1113 		break;
1114 
1115 	case PGP_PTAG_CT_PK_SESSION_KEY:
1116 	case PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY:
1117 		pgp_pk_sesskey_free(&c->u.pk_sesskey);
1118 		break;
1119 
1120 	case PGP_GET_PASSPHRASE:
1121 		cmd_get_passphrase_free(&c->u.skey_passphrase);
1122 		break;
1123 
1124 	default:
1125 		fprintf(stderr, "Can't free %d (0x%x)\n", c->tag, c->tag);
1126 	}
1127 }
1128 
1129 /**
1130 \ingroup Core_Create
1131 \brief Free allocated memory
1132 */
1133 void
1134 pgp_pk_sesskey_free(pgp_pk_sesskey_t *sk)
1135 {
1136 	switch (sk->alg) {
1137 	case PGP_PKA_RSA:
1138 		free_BN(&sk->params.rsa.encrypted_m);
1139 		break;
1140 
1141 	case PGP_PKA_ELGAMAL:
1142 		free_BN(&sk->params.elgamal.g_to_k);
1143 		free_BN(&sk->params.elgamal.encrypted_m);
1144 		break;
1145 
1146 	default:
1147 		(void) fprintf(stderr, "pgp_pk_sesskey_free: bad alg\n");
1148 		break;
1149 	}
1150 }
1151 
1152 /**
1153 \ingroup Core_Create
1154 \brief Free allocated memory
1155 */
1156 /* ! Free the memory used when parsing a public key */
1157 void
1158 pgp_pubkey_free(pgp_pubkey_t *p)
1159 {
1160 	switch (p->alg) {
1161 	case PGP_PKA_RSA:
1162 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1163 	case PGP_PKA_RSA_SIGN_ONLY:
1164 		free_BN(&p->key.rsa.n);
1165 		free_BN(&p->key.rsa.e);
1166 		break;
1167 
1168 	case PGP_PKA_DSA:
1169 		free_BN(&p->key.dsa.p);
1170 		free_BN(&p->key.dsa.q);
1171 		free_BN(&p->key.dsa.g);
1172 		free_BN(&p->key.dsa.y);
1173 		break;
1174 
1175 	case PGP_PKA_ELGAMAL:
1176 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1177 		free_BN(&p->key.elgamal.p);
1178 		free_BN(&p->key.elgamal.g);
1179 		free_BN(&p->key.elgamal.y);
1180 		break;
1181 
1182 	case PGP_PKA_NOTHING:
1183 		/* nothing to free */
1184 		break;
1185 
1186 	default:
1187 		(void) fprintf(stderr, "pgp_pubkey_free: bad alg\n");
1188 	}
1189 }
1190 
1191 /**
1192    \ingroup Core_ReadPackets
1193 */
1194 static int
1195 parse_pubkey_data(pgp_pubkey_t *key, pgp_region_t *region,
1196 		      pgp_stream_t *stream)
1197 {
1198 	uint8_t   c = 0x0;
1199 
1200 	if (region->readc != 0) {
1201 		/* We should not have read anything so far */
1202 		(void) fprintf(stderr, "parse_pubkey_data: bad length\n");
1203 		return 0;
1204 	}
1205 	if (!limread(&c, 1, region, stream)) {
1206 		return 0;
1207 	}
1208 	key->version = (pgp_version_t)c;
1209 	switch (key->version) {
1210 	case PGP_V2:
1211 	case PGP_V3:
1212 	case PGP_V4:
1213 		break;
1214 	default:
1215 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PUBLIC_KEY_VRSN,
1216 			    "Bad public key version (0x%02x)", key->version);
1217 		return 0;
1218 	}
1219 	if (!limited_read_time(&key->birthtime, region, stream)) {
1220 		return 0;
1221 	}
1222 
1223 	key->days_valid = 0;
1224 	if ((key->version == 2 || key->version == 3) &&
1225 	    !limread_scalar(&key->days_valid, 2, region, stream)) {
1226 		return 0;
1227 	}
1228 
1229 	if (!limread(&c, 1, region, stream)) {
1230 		return 0;
1231 	}
1232 	key->alg = c;
1233 
1234 	switch (key->alg) {
1235 	case PGP_PKA_DSA:
1236 		if (!limread_mpi(&key->key.dsa.p, region, stream) ||
1237 		    !limread_mpi(&key->key.dsa.q, region, stream) ||
1238 		    !limread_mpi(&key->key.dsa.g, region, stream) ||
1239 		    !limread_mpi(&key->key.dsa.y, region, stream)) {
1240 			return 0;
1241 		}
1242 		break;
1243 
1244 	case PGP_PKA_RSA:
1245 	case PGP_PKA_RSA_ENCRYPT_ONLY:
1246 	case PGP_PKA_RSA_SIGN_ONLY:
1247 		if (!limread_mpi(&key->key.rsa.n, region, stream) ||
1248 		    !limread_mpi(&key->key.rsa.e, region, stream)) {
1249 			return 0;
1250 		}
1251 		break;
1252 
1253 	case PGP_PKA_ELGAMAL:
1254 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1255 		if (!limread_mpi(&key->key.elgamal.p, region, stream) ||
1256 		    !limread_mpi(&key->key.elgamal.g, region, stream) ||
1257 		    !limread_mpi(&key->key.elgamal.y, region, stream)) {
1258 			return 0;
1259 		}
1260 		break;
1261 
1262 	default:
1263 		PGP_ERROR_1(&stream->errors,
1264 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
1265 			"Unsupported Public Key algorithm (%s)",
1266 			pgp_show_pka(key->alg));
1267 		return 0;
1268 	}
1269 
1270 	return 1;
1271 }
1272 
1273 
1274 /**
1275  * \ingroup Core_ReadPackets
1276  * \brief Parse a public key packet.
1277  *
1278  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
1279  *
1280  * Once the key has been parsed successfully, it is passed to the callback.
1281  *
1282  * \param *ptag		Pointer to the current Packet Tag.  This function should consume the entire packet.
1283  * \param *reader	Our reader
1284  * \param *cb		The callback
1285  * \return		1 on success, 0 on error
1286  *
1287  * \see RFC4880 5.5.2
1288  */
1289 static int
1290 parse_pubkey(pgp_content_enum tag, pgp_region_t *region,
1291 		 pgp_stream_t *stream)
1292 {
1293 	pgp_packet_t pkt;
1294 
1295 	if (!parse_pubkey_data(&pkt.u.pubkey, region, stream)) {
1296 		(void) fprintf(stderr, "parse_pubkey: parse_pubkey_data failed\n");
1297 		return 0;
1298 	}
1299 
1300 	/* XXX: this test should be done for all packets, surely? */
1301 	if (region->readc != region->length) {
1302 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1303 			    "Unconsumed data (%d)", region->length - region->readc);
1304 		return 0;
1305 	}
1306 	CALLBACK(tag, &stream->cbinfo, &pkt);
1307 
1308 	return 1;
1309 }
1310 
1311 /**
1312  * \ingroup Core_ReadPackets
1313  * \brief Parse one user attribute packet.
1314  *
1315  * User attribute packets contain one or more attribute subpackets.
1316  * For now, handle the whole packet as raw data.
1317  */
1318 
1319 static int
1320 parse_userattr(pgp_region_t *region, pgp_stream_t *stream)
1321 {
1322 
1323 	pgp_packet_t pkt;
1324 
1325 	/*
1326 	 * xxx- treat as raw data for now. Could break down further into
1327 	 * attribute sub-packets later - rachel
1328 	 */
1329 	if (region->readc != 0) {
1330 		/* We should not have read anything so far */
1331 		(void) fprintf(stderr, "parse_userattr: bad length\n");
1332 		return 0;
1333 	}
1334 	if (!read_data(&pkt.u.userattr, region, stream)) {
1335 		return 0;
1336 	}
1337 	CALLBACK(PGP_PTAG_CT_USER_ATTR, &stream->cbinfo, &pkt);
1338 	return 1;
1339 }
1340 
1341 /**
1342 \ingroup Core_Create
1343 \brief Free allocated memory
1344 */
1345 /* ! Free the memory used when parsing this packet type */
1346 void
1347 pgp_userid_free(uint8_t **id)
1348 {
1349 	free(*id);
1350 	*id = NULL;
1351 }
1352 
1353 /**
1354  * \ingroup Core_ReadPackets
1355  * \brief Parse a user id.
1356  *
1357  * This function parses an user id packet, which is basically just a char array the size of the packet.
1358  *
1359  * The char array is to be treated as an UTF-8 string.
1360  *
1361  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
1362  *
1363  * Once the userid has been parsed successfully, it is passed to the callback.
1364  *
1365  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1366  * \param *reader	Our reader
1367  * \param *cb		The callback
1368  * \return		1 on success, 0 on error
1369  *
1370  * \see RFC4880 5.11
1371  */
1372 static int
1373 parse_userid(pgp_region_t *region, pgp_stream_t *stream)
1374 {
1375 	pgp_packet_t pkt;
1376 
1377 	 if (region->readc != 0) {
1378 		/* We should not have read anything so far */
1379 		(void) fprintf(stderr, "parse_userid: bad length\n");
1380 		return 0;
1381 	}
1382 
1383 	if ((pkt.u.userid = calloc(1, region->length + 1)) == NULL) {
1384 		(void) fprintf(stderr, "parse_userid: bad alloc\n");
1385 		return 0;
1386 	}
1387 
1388 	if (region->length &&
1389 	    !limread(pkt.u.userid, region->length, region,
1390 			stream)) {
1391 		return 0;
1392 	}
1393 	pkt.u.userid[region->length] = 0x0;
1394 	CALLBACK(PGP_PTAG_CT_USER_ID, &stream->cbinfo, &pkt);
1395 	return 1;
1396 }
1397 
1398 static pgp_hash_t     *
1399 parse_hash_find(pgp_stream_t *stream, const uint8_t *keyid)
1400 {
1401 	pgp_hashtype_t	*hp;
1402 	size_t			 n;
1403 
1404 	for (n = 0, hp = stream->hashes; n < stream->hashc; n++, hp++) {
1405 		if (memcmp(hp->keyid, keyid, PGP_KEY_ID_SIZE) == 0) {
1406 			return &hp->hash;
1407 		}
1408 	}
1409 	return NULL;
1410 }
1411 
1412 /**
1413  * \ingroup Core_Parse
1414  * \brief Parse a version 3 signature.
1415  *
1416  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1417  *
1418  * Once the signature has been parsed successfully, it is passed to the callback.
1419  *
1420  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1421  * \param *reader	Our reader
1422  * \param *cb		The callback
1423  * \return		1 on success, 0 on error
1424  *
1425  * \see RFC4880 5.2.2
1426  */
1427 static int
1428 parse_v3_sig(pgp_region_t *region,
1429 		   pgp_stream_t *stream)
1430 {
1431 	pgp_packet_t	pkt;
1432 	uint8_t		c = 0x0;
1433 
1434 	/* clear signature */
1435 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1436 
1437 	pkt.u.sig.info.version = PGP_V3;
1438 
1439 	/* hash info length */
1440 	if (!limread(&c, 1, region, stream)) {
1441 		return 0;
1442 	}
1443 	if (c != 5) {
1444 		ERRP(&stream->cbinfo, pkt, "bad hash info length");
1445 	}
1446 
1447 	if (!limread(&c, 1, region, stream)) {
1448 		return 0;
1449 	}
1450 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1451 	/* XXX: check signature type */
1452 
1453 	if (!limited_read_time(&pkt.u.sig.info.birthtime, region, stream)) {
1454 		return 0;
1455 	}
1456 	pkt.u.sig.info.birthtime_set = 1;
1457 
1458 	if (!limread(pkt.u.sig.info.signer_id, PGP_KEY_ID_SIZE, region,
1459 			stream)) {
1460 		return 0;
1461 	}
1462 	pkt.u.sig.info.signer_id_set = 1;
1463 
1464 	if (!limread(&c, 1, region, stream)) {
1465 		return 0;
1466 	}
1467 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1468 	/* XXX: check algorithm */
1469 
1470 	if (!limread(&c, 1, region, stream)) {
1471 		return 0;
1472 	}
1473 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1474 	/* XXX: check algorithm */
1475 
1476 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1477 		return 0;
1478 	}
1479 
1480 	switch (pkt.u.sig.info.key_alg) {
1481 	case PGP_PKA_RSA:
1482 	case PGP_PKA_RSA_SIGN_ONLY:
1483 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1484 			return 0;
1485 		}
1486 		break;
1487 
1488 	case PGP_PKA_DSA:
1489 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream) ||
1490 		    !limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
1491 			return 0;
1492 		}
1493 		break;
1494 
1495 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1496 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
1497 				stream) ||
1498 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
1499 		    		stream)) {
1500 			return 0;
1501 		}
1502 		break;
1503 
1504 	default:
1505 		PGP_ERROR_1(&stream->errors,
1506 			PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1507 			"Unsupported signature key algorithm (%s)",
1508 			pgp_show_pka(pkt.u.sig.info.key_alg));
1509 		return 0;
1510 	}
1511 
1512 	if (region->readc != region->length) {
1513 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1514 			"Unconsumed data (%d)",
1515 			region->length - region->readc);
1516 		return 0;
1517 	}
1518 	if (pkt.u.sig.info.signer_id_set) {
1519 		pkt.u.sig.hash = parse_hash_find(stream,
1520 				pkt.u.sig.info.signer_id);
1521 	}
1522 	CALLBACK(PGP_PTAG_CT_SIGNATURE, &stream->cbinfo, &pkt);
1523 	return 1;
1524 }
1525 
1526 /**
1527  * \ingroup Core_ReadPackets
1528  * \brief Parse one signature sub-packet.
1529  *
1530  * Version 4 signatures can have an arbitrary amount of (hashed and
1531  * unhashed) subpackets.  Subpackets are used to hold optional
1532  * attributes of subpackets.
1533  *
1534  * This function parses one such signature subpacket.
1535  *
1536  * Once the subpacket has been parsed successfully, it is passed to the callback.
1537  *
1538  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire subpacket.
1539  * \param *reader	Our reader
1540  * \param *cb		The callback
1541  * \return		1 on success, 0 on error
1542  *
1543  * \see RFC4880 5.2.3
1544  */
1545 static int
1546 parse_one_sig_subpacket(pgp_sig_t *sig,
1547 			      pgp_region_t *region,
1548 			      pgp_stream_t *stream)
1549 {
1550 	pgp_region_t	subregion;
1551 	pgp_packet_t	pkt;
1552 	uint8_t		bools = 0x0;
1553 	uint8_t		c = 0x0;
1554 	unsigned	doread = 1;
1555 	unsigned        t8;
1556 	unsigned        t7;
1557 
1558 	pgp_init_subregion(&subregion, region);
1559 	if (!limited_read_new_length(&subregion.length, region, stream)) {
1560 		return 0;
1561 	}
1562 
1563 	if (subregion.length > region->length) {
1564 		ERRP(&stream->cbinfo, pkt, "Subpacket too long");
1565 	}
1566 
1567 	if (!limread(&c, 1, &subregion, stream)) {
1568 		return 0;
1569 	}
1570 
1571 	t8 = (c & 0x7f) / 8;
1572 	t7 = 1 << (c & 7);
1573 
1574 	pkt.critical = (unsigned)c >> 7;
1575 	pkt.tag = (pgp_content_enum)(PGP_PTAG_SIG_SUBPKT_BASE + (c & 0x7f));
1576 
1577 	/* Application wants it delivered raw */
1578 	if (stream->ss_raw[t8] & t7) {
1579 		pkt.u.ss_raw.tag = pkt.tag;
1580 		pkt.u.ss_raw.length = subregion.length - 1;
1581 		pkt.u.ss_raw.raw = calloc(1, pkt.u.ss_raw.length);
1582 		if (pkt.u.ss_raw.raw == NULL) {
1583 			(void) fprintf(stderr, "parse_one_sig_subpacket: bad alloc\n");
1584 			return 0;
1585 		}
1586 		if (!limread(pkt.u.ss_raw.raw, (unsigned)pkt.u.ss_raw.length,
1587 				&subregion, stream)) {
1588 			return 0;
1589 		}
1590 		CALLBACK(PGP_PTAG_RAW_SS, &stream->cbinfo, &pkt);
1591 		return 1;
1592 	}
1593 	switch (pkt.tag) {
1594 	case PGP_PTAG_SS_CREATION_TIME:
1595 	case PGP_PTAG_SS_EXPIRATION_TIME:
1596 	case PGP_PTAG_SS_KEY_EXPIRY:
1597 		if (!limited_read_time(&pkt.u.ss_time, &subregion, stream))
1598 			return 0;
1599 		if (pkt.tag == PGP_PTAG_SS_CREATION_TIME) {
1600 			sig->info.birthtime = pkt.u.ss_time;
1601 			sig->info.birthtime_set = 1;
1602 		}
1603 		if (pkt.tag == PGP_PTAG_SS_EXPIRATION_TIME) {
1604 			sig->info.duration = pkt.u.ss_time;
1605 			sig->info.duration_set = 1;
1606 		}
1607 		break;
1608 
1609 	case PGP_PTAG_SS_TRUST:
1610 		if (!limread(&pkt.u.ss_trust.level, 1, &subregion, stream) ||
1611 		    !limread(&pkt.u.ss_trust.amount, 1, &subregion, stream)) {
1612 			return 0;
1613 		}
1614 		break;
1615 
1616 	case PGP_PTAG_SS_REVOCABLE:
1617 		if (!limread(&bools, 1, &subregion, stream)) {
1618 			return 0;
1619 		}
1620 		pkt.u.ss_revocable = !!bools;
1621 		break;
1622 
1623 	case PGP_PTAG_SS_ISSUER_KEY_ID:
1624 		if (!limread(pkt.u.ss_issuer, PGP_KEY_ID_SIZE, &subregion, stream)) {
1625 			return 0;
1626 		}
1627 		(void) memcpy(sig->info.signer_id, pkt.u.ss_issuer, PGP_KEY_ID_SIZE);
1628 		sig->info.signer_id_set = 1;
1629 		break;
1630 
1631 	case PGP_PTAG_SS_PREFERRED_SKA:
1632 		if (!read_data(&pkt.u.ss_skapref, &subregion, stream)) {
1633 			return 0;
1634 		}
1635 		break;
1636 
1637 	case PGP_PTAG_SS_PREFERRED_HASH:
1638 		if (!read_data(&pkt.u.ss_hashpref, &subregion, stream)) {
1639 			return 0;
1640 		}
1641 		break;
1642 
1643 	case PGP_PTAG_SS_PREF_COMPRESS:
1644 		if (!read_data(&pkt.u.ss_zpref, &subregion, stream)) {
1645 			return 0;
1646 		}
1647 		break;
1648 
1649 	case PGP_PTAG_SS_PRIMARY_USER_ID:
1650 		if (!limread(&bools, 1, &subregion, stream)) {
1651 			return 0;
1652 		}
1653 		pkt.u.ss_primary_userid = !!bools;
1654 		break;
1655 
1656 	case PGP_PTAG_SS_KEY_FLAGS:
1657 		if (!read_data(&pkt.u.ss_key_flags, &subregion, stream)) {
1658 			return 0;
1659 		}
1660 		break;
1661 
1662 	case PGP_PTAG_SS_KEYSERV_PREFS:
1663 		if (!read_data(&pkt.u.ss_key_server_prefs, &subregion, stream)) {
1664 			return 0;
1665 		}
1666 		break;
1667 
1668 	case PGP_PTAG_SS_FEATURES:
1669 		if (!read_data(&pkt.u.ss_features, &subregion, stream)) {
1670 			return 0;
1671 		}
1672 		break;
1673 
1674 	case PGP_PTAG_SS_SIGNERS_USER_ID:
1675 		if (!read_unsig_str(&pkt.u.ss_signer, &subregion, stream)) {
1676 			return 0;
1677 		}
1678 		break;
1679 
1680 	case PGP_PTAG_SS_EMBEDDED_SIGNATURE:
1681 		/* \todo should do something with this sig? */
1682 		if (!read_data(&pkt.u.ss_embedded_sig, &subregion, stream)) {
1683 			return 0;
1684 		}
1685 		break;
1686 
1687 	case PGP_PTAG_SS_NOTATION_DATA:
1688 		if (!limread_data(&pkt.u.ss_notation.flags, 4,
1689 				&subregion, stream)) {
1690 			return 0;
1691 		}
1692 		if (!limread_size_t(&pkt.u.ss_notation.name.len, 2,
1693 				&subregion, stream)) {
1694 			return 0;
1695 		}
1696 		if (!limread_size_t(&pkt.u.ss_notation.value.len, 2,
1697 				&subregion, stream)) {
1698 			return 0;
1699 		}
1700 		if (!limread_data(&pkt.u.ss_notation.name,
1701 				(unsigned)pkt.u.ss_notation.name.len,
1702 				&subregion, stream)) {
1703 			return 0;
1704 		}
1705 		if (!limread_data(&pkt.u.ss_notation.value,
1706 			   (unsigned)pkt.u.ss_notation.value.len,
1707 			   &subregion, stream)) {
1708 			return 0;
1709 		}
1710 		break;
1711 
1712 	case PGP_PTAG_SS_POLICY_URI:
1713 		if (!read_string(&pkt.u.ss_policy, &subregion, stream)) {
1714 			return 0;
1715 		}
1716 		break;
1717 
1718 	case PGP_PTAG_SS_REGEXP:
1719 		if (!read_string(&pkt.u.ss_regexp, &subregion, stream)) {
1720 			return 0;
1721 		}
1722 		break;
1723 
1724 	case PGP_PTAG_SS_PREF_KEYSERV:
1725 		if (!read_string(&pkt.u.ss_keyserv, &subregion, stream)) {
1726 			return 0;
1727 		}
1728 		break;
1729 
1730 	case PGP_PTAG_SS_USERDEFINED00:
1731 	case PGP_PTAG_SS_USERDEFINED01:
1732 	case PGP_PTAG_SS_USERDEFINED02:
1733 	case PGP_PTAG_SS_USERDEFINED03:
1734 	case PGP_PTAG_SS_USERDEFINED04:
1735 	case PGP_PTAG_SS_USERDEFINED05:
1736 	case PGP_PTAG_SS_USERDEFINED06:
1737 	case PGP_PTAG_SS_USERDEFINED07:
1738 	case PGP_PTAG_SS_USERDEFINED08:
1739 	case PGP_PTAG_SS_USERDEFINED09:
1740 	case PGP_PTAG_SS_USERDEFINED10:
1741 		if (!read_data(&pkt.u.ss_userdef, &subregion, stream)) {
1742 			return 0;
1743 		}
1744 		break;
1745 
1746 	case PGP_PTAG_SS_RESERVED:
1747 		if (!read_data(&pkt.u.ss_unknown, &subregion, stream)) {
1748 			return 0;
1749 		}
1750 		break;
1751 
1752 	case PGP_PTAG_SS_REVOCATION_REASON:
1753 		/* first byte is the machine-readable code */
1754 		if (!limread(&pkt.u.ss_revocation.code, 1, &subregion, stream)) {
1755 			return 0;
1756 		}
1757 		/* the rest is a human-readable UTF-8 string */
1758 		if (!read_string(&pkt.u.ss_revocation.reason, &subregion,
1759 				stream)) {
1760 			return 0;
1761 		}
1762 		break;
1763 
1764 	case PGP_PTAG_SS_REVOCATION_KEY:
1765 		/* octet 0 = class. Bit 0x80 must be set */
1766 		if (!limread(&pkt.u.ss_revocation_key.class, 1,
1767 				&subregion, stream)) {
1768 			return 0;
1769 		}
1770 		if (!(pkt.u.ss_revocation_key.class & 0x80)) {
1771 			printf("Warning: PGP_PTAG_SS_REVOCATION_KEY class: "
1772 			       "Bit 0x80 should be set\n");
1773 			return 0;
1774 		}
1775 		/* octet 1 = algid */
1776 		if (!limread(&pkt.u.ss_revocation_key.algid, 1,
1777 				&subregion, stream)) {
1778 			return 0;
1779 		}
1780 		/* octets 2-21 = fingerprint */
1781 		if (!limread(&pkt.u.ss_revocation_key.fingerprint[0],
1782 				PGP_FINGERPRINT_SIZE, &subregion, stream)) {
1783 			return 0;
1784 		}
1785 		break;
1786 
1787 	default:
1788 		if (stream->ss_parsed[t8] & t7) {
1789 			PGP_ERROR_1(&stream->errors, PGP_E_PROTO_UNKNOWN_SS,
1790 				    "Unknown signature subpacket type (%d)",
1791 				    c & 0x7f);
1792 		}
1793 		doread = 0;
1794 		break;
1795 	}
1796 
1797 	/* Application doesn't want it delivered parsed */
1798 	if (!(stream->ss_parsed[t8] & t7)) {
1799 		if (pkt.critical) {
1800 			PGP_ERROR_1(&stream->errors,
1801 				PGP_E_PROTO_CRITICAL_SS_IGNORED,
1802 				"Critical signature subpacket ignored (%d)",
1803 				c & 0x7f);
1804 		}
1805 		if (!doread &&
1806 		    !limskip(subregion.length - 1, &subregion, stream)) {
1807 			return 0;
1808 		}
1809 		if (doread) {
1810 			pgp_parser_content_free(&pkt);
1811 		}
1812 		return 1;
1813 	}
1814 	if (doread && subregion.readc != subregion.length) {
1815 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
1816 			    "Unconsumed data (%d)",
1817 			    subregion.length - subregion.readc);
1818 		return 0;
1819 	}
1820 	CALLBACK(pkt.tag, &stream->cbinfo, &pkt);
1821 	return 1;
1822 }
1823 
1824 /**
1825  * \ingroup Core_ReadPackets
1826  * \brief Parse several signature subpackets.
1827  *
1828  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1829  * This function parses this length and then calls parse_one_sig_subpacket() for each subpacket until the
1830  * entire set is consumed.
1831  *
1832  * This function does not call the callback directly, parse_one_sig_subpacket() does for each subpacket.
1833  *
1834  * \param *ptag		Pointer to the Packet Tag.
1835  * \param *reader	Our reader
1836  * \param *cb		The callback
1837  * \return		1 on success, 0 on error
1838  *
1839  * \see RFC4880 5.2.3
1840  */
1841 static int
1842 parse_sig_subpkts(pgp_sig_t *sig,
1843 			   pgp_region_t *region,
1844 			   pgp_stream_t *stream)
1845 {
1846 	pgp_region_t	subregion;
1847 	pgp_packet_t	pkt;
1848 
1849 	pgp_init_subregion(&subregion, region);
1850 	if (!limread_scalar(&subregion.length, 2, region, stream)) {
1851 		return 0;
1852 	}
1853 
1854 	if (subregion.length > region->length) {
1855 		ERRP(&stream->cbinfo, pkt, "Subpacket set too long");
1856 	}
1857 
1858 	while (subregion.readc < subregion.length) {
1859 		if (!parse_one_sig_subpacket(sig, &subregion, stream)) {
1860 			return 0;
1861 		}
1862 	}
1863 
1864 	if (subregion.readc != subregion.length) {
1865 		if (!limskip(subregion.length - subregion.readc,
1866 				&subregion, stream)) {
1867 			ERRP(&stream->cbinfo, pkt,
1868 "parse_sig_subpkts: subpacket length read mismatch");
1869 		}
1870 		ERRP(&stream->cbinfo, pkt, "Subpacket length mismatch");
1871 	}
1872 	return 1;
1873 }
1874 
1875 /**
1876  * \ingroup Core_ReadPackets
1877  * \brief Parse a version 4 signature.
1878  *
1879  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
1880  *
1881  * Once the signature packet has been parsed successfully, it is passed to the callback.
1882  *
1883  * \param *ptag		Pointer to the Packet Tag.
1884  * \param *reader	Our reader
1885  * \param *cb		The callback
1886  * \return		1 on success, 0 on error
1887  *
1888  * \see RFC4880 5.2.3
1889  */
1890 static int
1891 parse_v4_sig(pgp_region_t *region, pgp_stream_t *stream)
1892 {
1893 	pgp_packet_t	pkt;
1894 	uint8_t		c = 0x0;
1895 
1896 	if (pgp_get_debug_level(__FILE__)) {
1897 		fprintf(stderr, "\nparse_v4_sig\n");
1898 	}
1899 	/* clear signature */
1900 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1901 
1902 	/*
1903 	 * We need to hash the packet data from version through the hashed
1904 	 * subpacket data
1905 	 */
1906 
1907 	pkt.u.sig.v4_hashstart = stream->readinfo.alength - 1;
1908 
1909 	/* Set version,type,algorithms */
1910 
1911 	pkt.u.sig.info.version = PGP_V4;
1912 
1913 	if (!limread(&c, 1, region, stream)) {
1914 		return 0;
1915 	}
1916 	pkt.u.sig.info.type = (pgp_sig_type_t)c;
1917 	if (pgp_get_debug_level(__FILE__)) {
1918 		fprintf(stderr, "signature type=%d (%s)\n",
1919 			pkt.u.sig.info.type,
1920 			pgp_show_sig_type(pkt.u.sig.info.type));
1921 	}
1922 	/* XXX: check signature type */
1923 
1924 	if (!limread(&c, 1, region, stream)) {
1925 		return 0;
1926 	}
1927 	pkt.u.sig.info.key_alg = (pgp_pubkey_alg_t)c;
1928 	/* XXX: check key algorithm */
1929 	if (pgp_get_debug_level(__FILE__)) {
1930 		(void) fprintf(stderr, "key_alg=%d (%s)\n",
1931 			pkt.u.sig.info.key_alg,
1932 			pgp_show_pka(pkt.u.sig.info.key_alg));
1933 	}
1934 	if (!limread(&c, 1, region, stream)) {
1935 		return 0;
1936 	}
1937 	pkt.u.sig.info.hash_alg = (pgp_hash_alg_t)c;
1938 	/* XXX: check hash algorithm */
1939 	if (pgp_get_debug_level(__FILE__)) {
1940 		fprintf(stderr, "hash_alg=%d %s\n",
1941 			pkt.u.sig.info.hash_alg,
1942 		  pgp_show_hash_alg(pkt.u.sig.info.hash_alg));
1943 	}
1944 	CALLBACK(PGP_PTAG_CT_SIGNATURE_HEADER, &stream->cbinfo, &pkt);
1945 
1946 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
1947 		return 0;
1948 	}
1949 
1950 	pkt.u.sig.info.v4_hashlen = stream->readinfo.alength
1951 					- pkt.u.sig.v4_hashstart;
1952 	if (pgp_get_debug_level(__FILE__)) {
1953 		fprintf(stderr, "v4_hashlen=%zd\n", pkt.u.sig.info.v4_hashlen);
1954 	}
1955 
1956 	/* copy hashed subpackets */
1957 	if (pkt.u.sig.info.v4_hashed) {
1958 		free(pkt.u.sig.info.v4_hashed);
1959 	}
1960 	pkt.u.sig.info.v4_hashed = calloc(1, pkt.u.sig.info.v4_hashlen);
1961 	if (pkt.u.sig.info.v4_hashed == NULL) {
1962 		(void) fprintf(stderr, "parse_v4_sig: bad alloc\n");
1963 		return 0;
1964 	}
1965 
1966 	if (!stream->readinfo.accumulate) {
1967 		/* We must accumulate, else we can't check the signature */
1968 		fprintf(stderr, "*** ERROR: must set accumulate to 1\n");
1969 		return 0;
1970 	}
1971 	(void) memcpy(pkt.u.sig.info.v4_hashed,
1972 	       stream->readinfo.accumulated + pkt.u.sig.v4_hashstart,
1973 	       pkt.u.sig.info.v4_hashlen);
1974 
1975 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
1976 		return 0;
1977 	}
1978 
1979 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1980 		return 0;
1981 	}
1982 
1983 	switch (pkt.u.sig.info.key_alg) {
1984 	case PGP_PKA_RSA:
1985 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1986 			return 0;
1987 		}
1988 		if (pgp_get_debug_level(__FILE__)) {
1989 			(void) fprintf(stderr, "parse_v4_sig: RSA: sig is\n");
1990 			BN_print_fp(stderr, pkt.u.sig.info.sig.rsa.sig);
1991 			(void) fprintf(stderr, "\n");
1992 		}
1993 		break;
1994 
1995 	case PGP_PKA_DSA:
1996 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream)) {
1997 			/*
1998 			 * usually if this fails, it just means we've reached
1999 			 * the end of the keyring
2000 			 */
2001 			if (pgp_get_debug_level(__FILE__)) {
2002 				(void) fprintf(stderr,
2003 				"Error reading DSA r field in signature");
2004 			}
2005 			return 0;
2006 		}
2007 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
2008 			ERRP(&stream->cbinfo, pkt,
2009 			"Error reading DSA s field in signature");
2010 		}
2011 		break;
2012 
2013 	case PGP_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
2014 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
2015 				stream) ||
2016 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
2017 		    		stream)) {
2018 			return 0;
2019 		}
2020 		break;
2021 
2022 	case PGP_PKA_PRIVATE00:
2023 	case PGP_PKA_PRIVATE01:
2024 	case PGP_PKA_PRIVATE02:
2025 	case PGP_PKA_PRIVATE03:
2026 	case PGP_PKA_PRIVATE04:
2027 	case PGP_PKA_PRIVATE05:
2028 	case PGP_PKA_PRIVATE06:
2029 	case PGP_PKA_PRIVATE07:
2030 	case PGP_PKA_PRIVATE08:
2031 	case PGP_PKA_PRIVATE09:
2032 	case PGP_PKA_PRIVATE10:
2033 		if (!read_data(&pkt.u.sig.info.sig.unknown, region, stream)) {
2034 			return 0;
2035 		}
2036 		break;
2037 
2038 	default:
2039 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
2040 			    "Bad v4 signature key algorithm (%s)",
2041 			    pgp_show_pka(pkt.u.sig.info.key_alg));
2042 		return 0;
2043 	}
2044 	if (region->readc != region->length) {
2045 		PGP_ERROR_1(&stream->errors, PGP_E_R_UNCONSUMED_DATA,
2046 			    "Unconsumed data (%d)",
2047 			    region->length - region->readc);
2048 		return 0;
2049 	}
2050 	CALLBACK(PGP_PTAG_CT_SIGNATURE_FOOTER, &stream->cbinfo, &pkt);
2051 	return 1;
2052 }
2053 
2054 /**
2055  * \ingroup Core_ReadPackets
2056  * \brief Parse a signature subpacket.
2057  *
2058  * This function calls the appropriate function to handle v3 or v4 signatures.
2059  *
2060  * Once the signature packet has been parsed successfully, it is passed to the callback.
2061  *
2062  * \param *ptag		Pointer to the Packet Tag.
2063  * \param *reader	Our reader
2064  * \param *cb		The callback
2065  * \return		1 on success, 0 on error
2066  */
2067 static int
2068 parse_sig(pgp_region_t *region, pgp_stream_t *stream)
2069 {
2070 	pgp_packet_t	pkt;
2071 	uint8_t		c = 0x0;
2072 
2073 	if (region->readc != 0) {
2074 		/* We should not have read anything so far */
2075 		(void) fprintf(stderr, "parse_sig: bad length\n");
2076 		return 0;
2077 	}
2078 
2079 	(void) memset(&pkt, 0x0, sizeof(pkt));
2080 	if (!limread(&c, 1, region, stream)) {
2081 		return 0;
2082 	}
2083 	if (c == 2 || c == 3) {
2084 		return parse_v3_sig(region, stream);
2085 	}
2086 	if (c == 4) {
2087 		return parse_v4_sig(region, stream);
2088 	}
2089 	PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_SIGNATURE_VRSN,
2090 		    "Bad signature version (%d)", c);
2091 	return 0;
2092 }
2093 
2094 /**
2095  \ingroup Core_ReadPackets
2096  \brief Parse Compressed packet
2097 */
2098 static int
2099 parse_compressed(pgp_region_t *region, pgp_stream_t *stream)
2100 {
2101 	pgp_packet_t	pkt;
2102 	uint8_t		c = 0x0;
2103 
2104 	if (!limread(&c, 1, region, stream)) {
2105 		return 0;
2106 	}
2107 
2108 	pkt.u.compressed = (pgp_compression_type_t)c;
2109 
2110 	CALLBACK(PGP_PTAG_CT_COMPRESSED, &stream->cbinfo, &pkt);
2111 
2112 	/*
2113 	 * The content of a compressed data packet is more OpenPGP packets
2114 	 * once decompressed, so recursively handle them
2115 	 */
2116 
2117 	return pgp_decompress(region, stream, pkt.u.compressed);
2118 }
2119 
2120 /* XXX: this could be improved by sharing all hashes that are the */
2121 /* same, then duping them just before checking the signature. */
2122 static void
2123 parse_hash_init(pgp_stream_t *stream, pgp_hash_alg_t type,
2124 		    const uint8_t *keyid)
2125 {
2126 	pgp_hashtype_t *hash;
2127 
2128 	hash = realloc(stream->hashes,
2129 			      (stream->hashc + 1) * sizeof(*stream->hashes));
2130 	if (hash == NULL) {
2131 		(void) fprintf(stderr, "parse_hash_init: bad alloc 0\n");
2132 		/* just continue and die here */
2133 		/* XXX - agc - no way to return failure */
2134 	} else {
2135 		stream->hashes = hash;
2136 	}
2137 	hash = &stream->hashes[stream->hashc++];
2138 
2139 	pgp_hash_any(&hash->hash, type);
2140 	if (!hash->hash.init(&hash->hash)) {
2141 		(void) fprintf(stderr, "parse_hash_init: bad alloc\n");
2142 		/* just continue and die here */
2143 		/* XXX - agc - no way to return failure */
2144 	}
2145 	(void) memcpy(hash->keyid, keyid, sizeof(hash->keyid));
2146 }
2147 
2148 /**
2149    \ingroup Core_ReadPackets
2150    \brief Parse a One Pass Signature packet
2151 */
2152 static int
2153 parse_one_pass(pgp_region_t * region, pgp_stream_t * stream)
2154 {
2155 	pgp_packet_t	pkt;
2156 	uint8_t		c = 0x0;
2157 
2158 	if (!limread(&pkt.u.one_pass_sig.version, 1, region, stream)) {
2159 		return 0;
2160 	}
2161 	if (pkt.u.one_pass_sig.version != 3) {
2162 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_ONE_PASS_SIG_VRSN,
2163 			    "Bad one-pass signature version (%d)",
2164 			    pkt.u.one_pass_sig.version);
2165 		return 0;
2166 	}
2167 	if (!limread(&c, 1, region, stream)) {
2168 		return 0;
2169 	}
2170 	pkt.u.one_pass_sig.sig_type = (pgp_sig_type_t)c;
2171 
2172 	if (!limread(&c, 1, region, stream)) {
2173 		return 0;
2174 	}
2175 	pkt.u.one_pass_sig.hash_alg = (pgp_hash_alg_t)c;
2176 
2177 	if (!limread(&c, 1, region, stream)) {
2178 		return 0;
2179 	}
2180 	pkt.u.one_pass_sig.key_alg = (pgp_pubkey_alg_t)c;
2181 
2182 	if (!limread(pkt.u.one_pass_sig.keyid,
2183 			  (unsigned)sizeof(pkt.u.one_pass_sig.keyid),
2184 			  region, stream)) {
2185 		return 0;
2186 	}
2187 
2188 	if (!limread(&c, 1, region, stream)) {
2189 		return 0;
2190 	}
2191 	pkt.u.one_pass_sig.nested = !!c;
2192 	CALLBACK(PGP_PTAG_CT_1_PASS_SIG, &stream->cbinfo, &pkt);
2193 	/* XXX: we should, perhaps, let the app choose whether to hash or not */
2194 	parse_hash_init(stream, pkt.u.one_pass_sig.hash_alg,
2195 			    pkt.u.one_pass_sig.keyid);
2196 	return 1;
2197 }
2198 
2199 /**
2200  \ingroup Core_ReadPackets
2201  \brief Parse a Trust packet
2202 */
2203 static int
2204 parse_trust(pgp_region_t *region, pgp_stream_t *stream)
2205 {
2206 	pgp_packet_t pkt;
2207 
2208 	if (!read_data(&pkt.u.trust, region, stream)) {
2209 		return 0;
2210 	}
2211 	CALLBACK(PGP_PTAG_CT_TRUST, &stream->cbinfo, &pkt);
2212 	return 1;
2213 }
2214 
2215 static void
2216 parse_hash_data(pgp_stream_t *stream, const void *data,
2217 		    size_t length)
2218 {
2219 	size_t          n;
2220 
2221 	for (n = 0; n < stream->hashc; ++n) {
2222 		stream->hashes[n].hash.add(&stream->hashes[n].hash, data, (unsigned)length);
2223 	}
2224 }
2225 
2226 /**
2227    \ingroup Core_ReadPackets
2228    \brief Parse a Literal Data packet
2229 */
2230 static int
2231 parse_litdata(pgp_region_t *region, pgp_stream_t *stream)
2232 {
2233 	pgp_memory_t	*mem;
2234 	pgp_packet_t	 pkt;
2235 	uint8_t		 c = 0x0;
2236 
2237 	if (!limread(&c, 1, region, stream)) {
2238 		return 0;
2239 	}
2240 	pkt.u.litdata_header.format = (pgp_litdata_enum)c;
2241 	if (!limread(&c, 1, region, stream)) {
2242 		return 0;
2243 	}
2244 	if (!limread((uint8_t *)pkt.u.litdata_header.filename,
2245 			(unsigned)c, region, stream)) {
2246 		return 0;
2247 	}
2248 	pkt.u.litdata_header.filename[c] = '\0';
2249 	if (!limited_read_time(&pkt.u.litdata_header.mtime, region, stream)) {
2250 		return 0;
2251 	}
2252 	CALLBACK(PGP_PTAG_CT_LITDATA_HEADER, &stream->cbinfo, &pkt);
2253 	mem = pkt.u.litdata_body.mem = pgp_memory_new();
2254 	pgp_memory_init(pkt.u.litdata_body.mem,
2255 			(unsigned)((region->length * 101) / 100) + 12);
2256 	pkt.u.litdata_body.data = mem->buf;
2257 
2258 	while (region->readc < region->length) {
2259 		unsigned        readc = region->length - region->readc;
2260 
2261 		if (!limread(mem->buf, readc, region, stream)) {
2262 			return 0;
2263 		}
2264 		pkt.u.litdata_body.length = readc;
2265 		parse_hash_data(stream, pkt.u.litdata_body.data, region->length);
2266 		CALLBACK(PGP_PTAG_CT_LITDATA_BODY, &stream->cbinfo, &pkt);
2267 	}
2268 
2269 	/* XXX - get rid of mem here? */
2270 
2271 	return 1;
2272 }
2273 
2274 /**
2275  * \ingroup Core_Create
2276  *
2277  * pgp_seckey_free() frees the memory associated with "key". Note that
2278  * the key itself is not freed.
2279  *
2280  * \param key
2281  */
2282 
2283 void
2284 pgp_seckey_free(pgp_seckey_t *key)
2285 {
2286 	switch (key->pubkey.alg) {
2287 	case PGP_PKA_RSA:
2288 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2289 	case PGP_PKA_RSA_SIGN_ONLY:
2290 		free_BN(&key->key.rsa.d);
2291 		free_BN(&key->key.rsa.p);
2292 		free_BN(&key->key.rsa.q);
2293 		free_BN(&key->key.rsa.u);
2294 		break;
2295 
2296 	case PGP_PKA_DSA:
2297 		free_BN(&key->key.dsa.x);
2298 		break;
2299 
2300 	default:
2301 		(void) fprintf(stderr,
2302 			"pgp_seckey_free: Unknown algorithm: %d (%s)\n",
2303 			key->pubkey.alg,
2304 			pgp_show_pka(key->pubkey.alg));
2305 	}
2306 	free(key->checkhash);
2307 }
2308 
2309 static int
2310 consume_packet(pgp_region_t *region, pgp_stream_t *stream, unsigned warn)
2311 {
2312 	pgp_packet_t	pkt;
2313 	pgp_data_t	remainder;
2314 
2315 	if (region->indeterminate) {
2316 		ERRP(&stream->cbinfo, pkt,
2317 			"Can't consume indeterminate packets");
2318 	}
2319 
2320 	if (read_data(&remainder, region, stream)) {
2321 		/* now throw it away */
2322 		pgp_data_free(&remainder);
2323 		if (warn) {
2324 			PGP_ERROR(&stream->errors, PGP_E_P_PACKET_CONSUMED,
2325 				"Warning: packet consumer");
2326 		}
2327 		return 1;
2328 	}
2329 	PGP_ERROR(&stream->errors, PGP_E_P_PACKET_NOT_CONSUMED,
2330 			(warn) ? "Warning: Packet was not consumed" :
2331 				"Packet was not consumed");
2332 	return warn;
2333 }
2334 
2335 /**
2336  * \ingroup Core_ReadPackets
2337  * \brief Parse a secret key
2338  */
2339 static int
2340 parse_seckey(pgp_region_t *region, pgp_stream_t *stream)
2341 {
2342 	pgp_packet_t		pkt;
2343 	pgp_region_t		encregion;
2344 	pgp_region_t	       *saved_region = NULL;
2345 	pgp_crypt_t		decrypt;
2346 	pgp_hash_t		checkhash;
2347 	unsigned		blocksize;
2348 	unsigned		crypted;
2349 	uint8_t			c = 0x0;
2350 	int			ret = 1;
2351 
2352 	if (pgp_get_debug_level(__FILE__)) {
2353 		fprintf(stderr, "\n---------\nparse_seckey:\n");
2354 		fprintf(stderr,
2355 			"region length=%u, readc=%u, remainder=%u\n",
2356 			region->length, region->readc,
2357 			region->length - region->readc);
2358 	}
2359 	(void) memset(&pkt, 0x0, sizeof(pkt));
2360 	if (!parse_pubkey_data(&pkt.u.seckey.pubkey, region, stream)) {
2361 		return 0;
2362 	}
2363 	if (pgp_get_debug_level(__FILE__)) {
2364 		fprintf(stderr, "parse_seckey: public key parsed\n");
2365 		pgp_print_pubkey(&pkt.u.seckey.pubkey);
2366 	}
2367 	stream->reading_v3_secret = (pkt.u.seckey.pubkey.version != PGP_V4);
2368 
2369 	if (!limread(&c, 1, region, stream)) {
2370 		return 0;
2371 	}
2372 	pkt.u.seckey.s2k_usage = (pgp_s2k_usage_t)c;
2373 
2374 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2375 	    pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2376 		if (!limread(&c, 1, region, stream)) {
2377 			return 0;
2378 		}
2379 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2380 		if (!limread(&c, 1, region, stream)) {
2381 			return 0;
2382 		}
2383 		pkt.u.seckey.s2k_specifier = (pgp_s2k_specifier_t)c;
2384 		switch (pkt.u.seckey.s2k_specifier) {
2385 		case PGP_S2KS_SIMPLE:
2386 		case PGP_S2KS_SALTED:
2387 		case PGP_S2KS_ITERATED_AND_SALTED:
2388 			break;
2389 		default:
2390 			(void) fprintf(stderr,
2391 				"parse_seckey: bad seckey\n");
2392 			return 0;
2393 		}
2394 		if (!limread(&c, 1, region, stream)) {
2395 			return 0;
2396 		}
2397 		pkt.u.seckey.hash_alg = (pgp_hash_alg_t)c;
2398 		if (pkt.u.seckey.s2k_specifier != PGP_S2KS_SIMPLE &&
2399 		    !limread(pkt.u.seckey.salt, 8, region, stream)) {
2400 			return 0;
2401 		}
2402 		if (pkt.u.seckey.s2k_specifier ==
2403 					PGP_S2KS_ITERATED_AND_SALTED) {
2404 			if (!limread(&c, 1, region, stream)) {
2405 				return 0;
2406 			}
2407 			pkt.u.seckey.octetc =
2408 				(16 + ((unsigned)c & 15)) <<
2409 						(((unsigned)c >> 4) + 6);
2410 		}
2411 	} else if (pkt.u.seckey.s2k_usage != PGP_S2KU_NONE) {
2412 		/* this is V3 style, looks just like a V4 simple hash */
2413 		pkt.u.seckey.alg = (pgp_symm_alg_t)c;
2414 		pkt.u.seckey.s2k_usage = PGP_S2KU_ENCRYPTED;
2415 		pkt.u.seckey.s2k_specifier = PGP_S2KS_SIMPLE;
2416 		pkt.u.seckey.hash_alg = PGP_HASH_MD5;
2417 	}
2418 	crypted = pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED ||
2419 		pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED;
2420 
2421 	if (crypted) {
2422 		pgp_packet_t	seckey;
2423 		pgp_hash_t	hashes[(PGP_MAX_KEY_SIZE + PGP_MIN_HASH_SIZE - 1) / PGP_MIN_HASH_SIZE];
2424 		unsigned	passlen;
2425 		uint8_t   	key[PGP_MAX_KEY_SIZE + PGP_MAX_HASH_SIZE];
2426 		char           *passphrase;
2427 		int             hashsize;
2428 		int             keysize;
2429 		int             n;
2430 
2431 		if (pgp_get_debug_level(__FILE__)) {
2432 			(void) fprintf(stderr, "crypted seckey\n");
2433 		}
2434 		blocksize = pgp_block_size(pkt.u.seckey.alg);
2435 		if (blocksize == 0 || blocksize > PGP_MAX_BLOCK_SIZE) {
2436 			(void) fprintf(stderr,
2437 				"parse_seckey: bad blocksize\n");
2438 			return 0;
2439 		}
2440 
2441 		if (!limread(pkt.u.seckey.iv, blocksize, region, stream)) {
2442 			return 0;
2443 		}
2444 		(void) memset(&seckey, 0x0, sizeof(seckey));
2445 		passphrase = NULL;
2446 		seckey.u.skey_passphrase.passphrase = &passphrase;
2447 		seckey.u.skey_passphrase.seckey = &pkt.u.seckey;
2448 		CALLBACK(PGP_GET_PASSPHRASE, &stream->cbinfo, &seckey);
2449 		if (!passphrase) {
2450 			if (pgp_get_debug_level(__FILE__)) {
2451 				/* \todo make into proper error */
2452 				(void) fprintf(stderr,
2453 				"parse_seckey: can't get passphrase\n");
2454 			}
2455 			if (!consume_packet(region, stream, 0)) {
2456 				return 0;
2457 			}
2458 
2459 			CALLBACK(PGP_PTAG_CT_ENCRYPTED_SECRET_KEY,
2460 				&stream->cbinfo, &pkt);
2461 
2462 			return 1;
2463 		}
2464 		keysize = pgp_key_size(pkt.u.seckey.alg);
2465 		if (keysize == 0 || keysize > PGP_MAX_KEY_SIZE) {
2466 			(void) fprintf(stderr,
2467 				"parse_seckey: bad keysize\n");
2468 			return 0;
2469 		}
2470 
2471 		/* Hardcoded SHA1 for just now */
2472 		pkt.u.seckey.hash_alg = PGP_HASH_SHA1;
2473 		hashsize = pgp_hash_size(pkt.u.seckey.hash_alg);
2474 		if (hashsize == 0 || hashsize > PGP_MAX_HASH_SIZE) {
2475 			(void) fprintf(stderr,
2476 				"parse_seckey: bad hashsize\n");
2477 			return 0;
2478 		}
2479 
2480 		for (n = 0; n * hashsize < keysize; ++n) {
2481 			int             i;
2482 
2483 			pgp_hash_any(&hashes[n],
2484 				pkt.u.seckey.hash_alg);
2485 			if (!hashes[n].init(&hashes[n])) {
2486 				(void) fprintf(stderr,
2487 					"parse_seckey: bad alloc\n");
2488 				return 0;
2489 			}
2490 			/* preload hashes with zeroes... */
2491 			for (i = 0; i < n; ++i) {
2492 				hashes[n].add(&hashes[n],
2493 					(const uint8_t *) "", 1);
2494 			}
2495 		}
2496 		passlen = (unsigned)strlen(passphrase);
2497 		for (n = 0; n * hashsize < keysize; ++n) {
2498 			unsigned        i;
2499 
2500 			switch (pkt.u.seckey.s2k_specifier) {
2501 			case PGP_S2KS_SALTED:
2502 				hashes[n].add(&hashes[n],
2503 					pkt.u.seckey.salt,
2504 					PGP_SALT_SIZE);
2505 				/* FALLTHROUGH */
2506 			case PGP_S2KS_SIMPLE:
2507 				hashes[n].add(&hashes[n],
2508 					(uint8_t *)passphrase, (unsigned)passlen);
2509 				break;
2510 
2511 			case PGP_S2KS_ITERATED_AND_SALTED:
2512 				for (i = 0; i < pkt.u.seckey.octetc;
2513 						i += passlen + PGP_SALT_SIZE) {
2514 					unsigned	j;
2515 
2516 					j = passlen + PGP_SALT_SIZE;
2517 					if (i + j > pkt.u.seckey.octetc && i != 0) {
2518 						j = pkt.u.seckey.octetc - i;
2519 					}
2520 					hashes[n].add(&hashes[n],
2521 						pkt.u.seckey.salt,
2522 						(unsigned)(j > PGP_SALT_SIZE) ?
2523 							PGP_SALT_SIZE : j);
2524 					if (j > PGP_SALT_SIZE) {
2525 						hashes[n].add(&hashes[n],
2526 						(uint8_t *) passphrase,
2527 						j - PGP_SALT_SIZE);
2528 					}
2529 				}
2530 				break;
2531 			default:
2532 				break;
2533 			}
2534 		}
2535 
2536 		for (n = 0; n * hashsize < keysize; ++n) {
2537 			int	r;
2538 
2539 			r = hashes[n].finish(&hashes[n], key + n * hashsize);
2540 			if (r != hashsize) {
2541 				(void) fprintf(stderr,
2542 					"parse_seckey: bad r\n");
2543 				return 0;
2544 			}
2545 		}
2546 
2547 		pgp_forget(passphrase, passlen);
2548 
2549 		pgp_crypt_any(&decrypt, pkt.u.seckey.alg);
2550 		if (pgp_get_debug_level(__FILE__)) {
2551 			hexdump(stderr, "input iv", pkt.u.seckey.iv, pgp_block_size(pkt.u.seckey.alg));
2552 			hexdump(stderr, "key", key, CAST_KEY_LENGTH);
2553 		}
2554 		decrypt.set_iv(&decrypt, pkt.u.seckey.iv);
2555 		decrypt.set_crypt_key(&decrypt, key);
2556 
2557 		/* now read encrypted data */
2558 
2559 		pgp_reader_push_decrypt(stream, &decrypt, region);
2560 
2561 		/*
2562 		 * Since all known encryption for PGP doesn't compress, we
2563 		 * can limit to the same length as the current region (for
2564 		 * now).
2565 		 */
2566 		pgp_init_subregion(&encregion, NULL);
2567 		encregion.length = region->length - region->readc;
2568 		if (pkt.u.seckey.pubkey.version != PGP_V4) {
2569 			encregion.length -= 2;
2570 		}
2571 		saved_region = region;
2572 		region = &encregion;
2573 	}
2574 	if (pgp_get_debug_level(__FILE__)) {
2575 		fprintf(stderr, "parse_seckey: end of crypted passphrase\n");
2576 	}
2577 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2578 		/* XXX - Hard-coded SHA1 here ?? Check */
2579 		pkt.u.seckey.checkhash = calloc(1, PGP_SHA1_HASH_SIZE);
2580 		if (pkt.u.seckey.checkhash == NULL) {
2581 			(void) fprintf(stderr, "parse_seckey: bad alloc\n");
2582 			return 0;
2583 		}
2584 		pgp_hash_sha1(&checkhash);
2585 		pgp_reader_push_hash(stream, &checkhash);
2586 	} else {
2587 		pgp_reader_push_sum16(stream);
2588 	}
2589 	if (pgp_get_debug_level(__FILE__)) {
2590 		fprintf(stderr, "parse_seckey: checkhash, reading MPIs\n");
2591 	}
2592 	switch (pkt.u.seckey.pubkey.alg) {
2593 	case PGP_PKA_RSA:
2594 	case PGP_PKA_RSA_ENCRYPT_ONLY:
2595 	case PGP_PKA_RSA_SIGN_ONLY:
2596 		if (!limread_mpi(&pkt.u.seckey.key.rsa.d, region, stream) ||
2597 		    !limread_mpi(&pkt.u.seckey.key.rsa.p, region, stream) ||
2598 		    !limread_mpi(&pkt.u.seckey.key.rsa.q, region, stream) ||
2599 		    !limread_mpi(&pkt.u.seckey.key.rsa.u, region, stream)) {
2600 			ret = 0;
2601 		}
2602 		break;
2603 
2604 	case PGP_PKA_DSA:
2605 		if (!limread_mpi(&pkt.u.seckey.key.dsa.x, region, stream)) {
2606 			ret = 0;
2607 		}
2608 		break;
2609 
2610 	case PGP_PKA_ELGAMAL:
2611 		if (!limread_mpi(&pkt.u.seckey.key.elgamal.x, region, stream)) {
2612 			ret = 0;
2613 		}
2614 		break;
2615 
2616 	default:
2617 		PGP_ERROR_2(&stream->errors,
2618 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2619 			"Unsupported Public Key algorithm %d (%s)",
2620 			pkt.u.seckey.pubkey.alg,
2621 			pgp_show_pka(pkt.u.seckey.pubkey.alg));
2622 		ret = 0;
2623 	}
2624 
2625 	if (pgp_get_debug_level(__FILE__)) {
2626 		(void) fprintf(stderr, "4 MPIs read\n");
2627 	}
2628 	stream->reading_v3_secret = 0;
2629 
2630 	if (pkt.u.seckey.s2k_usage == PGP_S2KU_ENCRYPTED_AND_HASHED) {
2631 		uint8_t   hash[PGP_CHECKHASH_SIZE];
2632 
2633 		pgp_reader_pop_hash(stream);
2634 		checkhash.finish(&checkhash, hash);
2635 
2636 		if (crypted &&
2637 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2638 			pgp_reader_pop_decrypt(stream);
2639 			region = saved_region;
2640 		}
2641 		if (ret) {
2642 			if (!limread(pkt.u.seckey.checkhash,
2643 				PGP_CHECKHASH_SIZE, region, stream)) {
2644 				return 0;
2645 			}
2646 
2647 			if (memcmp(hash, pkt.u.seckey.checkhash,
2648 					PGP_CHECKHASH_SIZE) != 0) {
2649 				ERRP(&stream->cbinfo, pkt,
2650 					"Hash mismatch in secret key");
2651 			}
2652 		}
2653 	} else {
2654 		uint16_t  sum;
2655 
2656 		sum = pgp_reader_pop_sum16(stream);
2657 		if (crypted &&
2658 		    pkt.u.seckey.pubkey.version != PGP_V4) {
2659 			pgp_reader_pop_decrypt(stream);
2660 			region = saved_region;
2661 		}
2662 		if (ret) {
2663 			if (!limread_scalar(&pkt.u.seckey.checksum, 2,
2664 					region, stream))
2665 				return 0;
2666 
2667 			if (sum != pkt.u.seckey.checksum) {
2668 				ERRP(&stream->cbinfo, pkt,
2669 					"Checksum mismatch in secret key");
2670 			}
2671 		}
2672 	}
2673 
2674 	if (crypted && pkt.u.seckey.pubkey.version == PGP_V4) {
2675 		pgp_reader_pop_decrypt(stream);
2676 	}
2677 	if (region == NULL) {
2678 		(void) fprintf(stderr, "parse_seckey: NULL region\n");
2679 		return 0;
2680 	}
2681 	if (ret && region->readc != region->length) {
2682 		(void) fprintf(stderr, "parse_seckey: bad length\n");
2683 		return 0;
2684 	}
2685 	if (!ret) {
2686 		return 0;
2687 	}
2688 	CALLBACK(PGP_PTAG_CT_SECRET_KEY, &stream->cbinfo, &pkt);
2689 	if (pgp_get_debug_level(__FILE__)) {
2690 		(void) fprintf(stderr, "--- end of parse_seckey\n\n");
2691 	}
2692 	return 1;
2693 }
2694 
2695 /**
2696    \ingroup Core_ReadPackets
2697    \brief Parse a Public Key Session Key packet
2698 */
2699 static int
2700 parse_pk_sesskey(pgp_region_t *region,
2701 		     pgp_stream_t *stream)
2702 {
2703 	const pgp_seckey_t	*secret;
2704 	pgp_packet_t		 sesskey;
2705 	pgp_packet_t		 pkt;
2706 	uint8_t			*iv;
2707 	uint8_t		   	 c = 0x0;
2708 	uint8_t			 cs[2];
2709 	unsigned		 k;
2710 	BIGNUM			*g_to_k;
2711 	BIGNUM			*enc_m;
2712 	int			 n;
2713 	uint8_t		 	 unencoded_m_buf[1024];
2714 
2715 	if (!limread(&c, 1, region, stream)) {
2716 		(void) fprintf(stderr, "parse_pk_sesskey - can't read char in region\n");
2717 		return 0;
2718 	}
2719 	pkt.u.pk_sesskey.version = c;
2720 	if (pkt.u.pk_sesskey.version != 3) {
2721 		PGP_ERROR_1(&stream->errors, PGP_E_PROTO_BAD_PKSK_VRSN,
2722 			"Bad public-key encrypted session key version (%d)",
2723 			    pkt.u.pk_sesskey.version);
2724 		return 0;
2725 	}
2726 	if (!limread(pkt.u.pk_sesskey.key_id,
2727 			  (unsigned)sizeof(pkt.u.pk_sesskey.key_id), region, stream)) {
2728 		return 0;
2729 	}
2730 	if (pgp_get_debug_level(__FILE__)) {
2731 		hexdump(stderr, "sesskey: pubkey id", pkt.u.pk_sesskey.key_id, sizeof(pkt.u.pk_sesskey.key_id));
2732 	}
2733 	if (!limread(&c, 1, region, stream)) {
2734 		return 0;
2735 	}
2736 	pkt.u.pk_sesskey.alg = (pgp_pubkey_alg_t)c;
2737 	switch (pkt.u.pk_sesskey.alg) {
2738 	case PGP_PKA_RSA:
2739 		if (!limread_mpi(&pkt.u.pk_sesskey.params.rsa.encrypted_m,
2740 				      region, stream)) {
2741 			return 0;
2742 		}
2743 		enc_m = pkt.u.pk_sesskey.params.rsa.encrypted_m;
2744 		g_to_k = NULL;
2745 		break;
2746 
2747 	case PGP_PKA_DSA:
2748 	case PGP_PKA_ELGAMAL:
2749 		if (!limread_mpi(&pkt.u.pk_sesskey.params.elgamal.g_to_k,
2750 				      region, stream) ||
2751 		    !limread_mpi(
2752 			&pkt.u.pk_sesskey.params.elgamal.encrypted_m,
2753 					 region, stream)) {
2754 			return 0;
2755 		}
2756 		g_to_k = pkt.u.pk_sesskey.params.elgamal.g_to_k;
2757 		enc_m = pkt.u.pk_sesskey.params.elgamal.encrypted_m;
2758 		break;
2759 
2760 	default:
2761 		PGP_ERROR_1(&stream->errors,
2762 			PGP_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2763 			"Unknown public key algorithm in session key (%s)",
2764 			pgp_show_pka(pkt.u.pk_sesskey.alg));
2765 		return 0;
2766 	}
2767 
2768 	(void) memset(&sesskey, 0x0, sizeof(sesskey));
2769 	secret = NULL;
2770 	sesskey.u.get_seckey.seckey = &secret;
2771 	sesskey.u.get_seckey.pk_sesskey = &pkt.u.pk_sesskey;
2772 
2773 	if (pgp_get_debug_level(__FILE__)) {
2774 		(void) fprintf(stderr, "getting secret key via callback\n");
2775 	}
2776 
2777 	CALLBACK(PGP_GET_SECKEY, &stream->cbinfo, &sesskey);
2778 
2779 	if (pgp_get_debug_level(__FILE__)) {
2780 		(void) fprintf(stderr, "got secret key via callback\n");
2781 	}
2782 	if (!secret) {
2783 		CALLBACK(PGP_PTAG_CT_ENCRYPTED_PK_SESSION_KEY, &stream->cbinfo,
2784 			&pkt);
2785 		return 1;
2786 	}
2787 	n = pgp_decrypt_decode_mpi(unencoded_m_buf,
2788 		(unsigned)sizeof(unencoded_m_buf), g_to_k, enc_m, secret);
2789 
2790 	if (n < 1) {
2791 		ERRP(&stream->cbinfo, pkt, "decrypted message too short");
2792 		return 0;
2793 	}
2794 
2795 	/* PKA */
2796 	pkt.u.pk_sesskey.symm_alg = (pgp_symm_alg_t)unencoded_m_buf[0];
2797 	if (pgp_get_debug_level(__FILE__)) {
2798 		(void) fprintf(stderr, "symm alg %d\n", pkt.u.pk_sesskey.symm_alg);
2799 	}
2800 
2801 	if (!pgp_is_sa_supported(pkt.u.pk_sesskey.symm_alg)) {
2802 		/* ERR1P */
2803 		PGP_ERROR_1(&stream->errors, PGP_E_ALG_UNSUPPORTED_SYMMETRIC_ALG,
2804 			    "Symmetric algorithm %s not supported",
2805 			    pgp_show_symm_alg(
2806 				pkt.u.pk_sesskey.symm_alg));
2807 		return 0;
2808 	}
2809 	k = pgp_key_size(pkt.u.pk_sesskey.symm_alg);
2810 	if (pgp_get_debug_level(__FILE__)) {
2811 		(void) fprintf(stderr, "key size %d\n", k);
2812 	}
2813 
2814 	if ((unsigned) n != k + 3) {
2815 		PGP_ERROR_2(&stream->errors, PGP_E_PROTO_DECRYPTED_MSG_WRONG_LEN,
2816 		      "decrypted message wrong length (got %d expected %d)",
2817 			    n, k + 3);
2818 		return 0;
2819 	}
2820 	if (k > sizeof(pkt.u.pk_sesskey.key)) {
2821 		(void) fprintf(stderr, "parse_pk_sesskey: bad keylength\n");
2822 		return 0;
2823 	}
2824 
2825 	(void) memcpy(pkt.u.pk_sesskey.key, unencoded_m_buf + 1, k);
2826 
2827 	if (pgp_get_debug_level(__FILE__)) {
2828 		hexdump(stderr, "recovered sesskey", pkt.u.pk_sesskey.key, k);
2829 	}
2830 	pkt.u.pk_sesskey.checksum = unencoded_m_buf[k + 1] +
2831 			(unencoded_m_buf[k + 2] << 8);
2832 	if (pgp_get_debug_level(__FILE__)) {
2833 		(void) fprintf(stderr, "session key checksum: %2x %2x\n",
2834 			unencoded_m_buf[k + 1], unencoded_m_buf[k + 2]);
2835 	}
2836 
2837 	/* Check checksum */
2838 	pgp_calc_sesskey_checksum(&pkt.u.pk_sesskey, &cs[0]);
2839 	if (unencoded_m_buf[k + 1] != cs[0] ||
2840 	    unencoded_m_buf[k + 2] != cs[1]) {
2841 		PGP_ERROR_4(&stream->errors, PGP_E_PROTO_BAD_SK_CHECKSUM,
2842 		"Session key checksum wrong: expected %2x %2x, got %2x %2x",
2843 		cs[0], cs[1], unencoded_m_buf[k + 1],
2844 		unencoded_m_buf[k + 2]);
2845 		return 0;
2846 	}
2847 
2848 	if (pgp_get_debug_level(__FILE__)) {
2849 		(void) fprintf(stderr, "getting pk session key via callback\n");
2850 	}
2851 	/* all is well */
2852 	CALLBACK(PGP_PTAG_CT_PK_SESSION_KEY, &stream->cbinfo, &pkt);
2853 	if (pgp_get_debug_level(__FILE__)) {
2854 		(void) fprintf(stderr, "got pk session key via callback\n");
2855 	}
2856 
2857 	pgp_crypt_any(&stream->decrypt, pkt.u.pk_sesskey.symm_alg);
2858 	iv = calloc(1, stream->decrypt.blocksize);
2859 	if (iv == NULL) {
2860 		(void) fprintf(stderr, "parse_pk_sesskey: bad alloc\n");
2861 		return 0;
2862 	}
2863 	stream->decrypt.set_iv(&stream->decrypt, iv);
2864 	stream->decrypt.set_crypt_key(&stream->decrypt, pkt.u.pk_sesskey.key);
2865 	pgp_encrypt_init(&stream->decrypt);
2866 	free(iv);
2867 	return 1;
2868 }
2869 
2870 static int
2871 decrypt_se_data(pgp_content_enum tag, pgp_region_t *region,
2872 		    pgp_stream_t *stream)
2873 {
2874 	pgp_crypt_t	*decrypt;
2875 	const int	 printerrors = 1;
2876 	int		 r = 1;
2877 
2878 	decrypt = pgp_get_decrypt(stream);
2879 	if (decrypt) {
2880 		pgp_region_t	encregion;
2881 		unsigned	b = (unsigned)decrypt->blocksize;
2882 		uint8_t		buf[PGP_MAX_BLOCK_SIZE + 2] = "";
2883 
2884 		pgp_reader_push_decrypt(stream, decrypt, region);
2885 
2886 		pgp_init_subregion(&encregion, NULL);
2887 		encregion.length = b + 2;
2888 
2889 		if (!exact_limread(buf, b + 2, &encregion, stream)) {
2890 			return 0;
2891 		}
2892 		if (buf[b - 2] != buf[b] || buf[b - 1] != buf[b + 1]) {
2893 			pgp_reader_pop_decrypt(stream);
2894 			PGP_ERROR_4(&stream->errors,
2895 				PGP_E_PROTO_BAD_SYMMETRIC_DECRYPT,
2896 				"Bad symmetric decrypt (%02x%02x vs %02x%02x)",
2897 				buf[b - 2], buf[b - 1], buf[b], buf[b + 1]);
2898 			return 0;
2899 		}
2900 		if (tag == PGP_PTAG_CT_SE_DATA_BODY) {
2901 			decrypt->decrypt_resync(decrypt);
2902 			decrypt->block_encrypt(decrypt, decrypt->civ,
2903 					decrypt->civ);
2904 		}
2905 		r = pgp_parse(stream, !printerrors);
2906 
2907 		pgp_reader_pop_decrypt(stream);
2908 	} else {
2909 		pgp_packet_t pkt;
2910 
2911 		while (region->readc < region->length) {
2912 			unsigned        len;
2913 
2914 			len = region->length - region->readc;
2915 			if (len > sizeof(pkt.u.se_data_body.data))
2916 				len = sizeof(pkt.u.se_data_body.data);
2917 
2918 			if (!limread(pkt.u.se_data_body.data, len,
2919 					region, stream)) {
2920 				return 0;
2921 			}
2922 			pkt.u.se_data_body.length = len;
2923 			CALLBACK(tag, &stream->cbinfo, &pkt);
2924 		}
2925 	}
2926 
2927 	return r;
2928 }
2929 
2930 static int
2931 decrypt_se_ip_data(pgp_content_enum tag, pgp_region_t *region,
2932 		       pgp_stream_t *stream)
2933 {
2934 	pgp_crypt_t	*decrypt;
2935 	const int	 printerrors = 1;
2936 	int		 r = 1;
2937 
2938 	decrypt = pgp_get_decrypt(stream);
2939 	if (decrypt) {
2940 		if (pgp_get_debug_level(__FILE__)) {
2941 			(void) fprintf(stderr, "decrypt_se_ip_data: decrypt\n");
2942 		}
2943 		pgp_reader_push_decrypt(stream, decrypt, region);
2944 		pgp_reader_push_se_ip_data(stream, decrypt, region);
2945 
2946 		r = pgp_parse(stream, !printerrors);
2947 
2948 		pgp_reader_pop_se_ip_data(stream);
2949 		pgp_reader_pop_decrypt(stream);
2950 	} else {
2951 		pgp_packet_t pkt;
2952 
2953 		if (pgp_get_debug_level(__FILE__)) {
2954 			(void) fprintf(stderr, "decrypt_se_ip_data: no decrypt\n");
2955 		}
2956 		while (region->readc < region->length) {
2957 			unsigned        len;
2958 
2959 			len = region->length - region->readc;
2960 			if (len > sizeof(pkt.u.se_data_body.data)) {
2961 				len = sizeof(pkt.u.se_data_body.data);
2962 			}
2963 
2964 			if (!limread(pkt.u.se_data_body.data,
2965 					len, region, stream)) {
2966 				return 0;
2967 			}
2968 
2969 			pkt.u.se_data_body.length = len;
2970 
2971 			CALLBACK(tag, &stream->cbinfo, &pkt);
2972 		}
2973 	}
2974 
2975 	return r;
2976 }
2977 
2978 /**
2979    \ingroup Core_ReadPackets
2980    \brief Read a Symmetrically Encrypted packet
2981 */
2982 static int
2983 parse_se_data(pgp_region_t *region, pgp_stream_t *stream)
2984 {
2985 	pgp_packet_t pkt;
2986 
2987 	/* there's no info to go with this, so just announce it */
2988 	CALLBACK(PGP_PTAG_CT_SE_DATA_HEADER, &stream->cbinfo, &pkt);
2989 
2990 	/*
2991 	 * The content of an encrypted data packet is more OpenPGP packets
2992 	 * once decrypted, so recursively handle them
2993 	 */
2994 	return decrypt_se_data(PGP_PTAG_CT_SE_DATA_BODY, region, stream);
2995 }
2996 
2997 /**
2998    \ingroup Core_ReadPackets
2999    \brief Read a Symmetrically Encrypted Integrity Protected packet
3000 */
3001 static int
3002 parse_se_ip_data(pgp_region_t *region, pgp_stream_t *stream)
3003 {
3004 	pgp_packet_t	pkt;
3005 	uint8_t		c = 0x0;
3006 
3007 	if (!limread(&c, 1, region, stream)) {
3008 		return 0;
3009 	}
3010 	pkt.u.se_ip_data_header = c;
3011 	if (pgp_get_debug_level(__FILE__)) {
3012 		(void) fprintf(stderr, "parse_se_ip_data: data header %d\n", c);
3013 	}
3014 	if (pkt.u.se_ip_data_header != PGP_SE_IP_DATA_VERSION) {
3015 		(void) fprintf(stderr, "parse_se_ip_data: bad version\n");
3016 		return 0;
3017 	}
3018 
3019 	if (pgp_get_debug_level(__FILE__)) {
3020 		(void) fprintf(stderr, "parse_se_ip_data: region %d,%d\n",
3021 			region->readc, region->length);
3022 		hexdump(stderr, "compressed region", stream->virtualpkt, stream->virtualc);
3023 	}
3024 	/*
3025 	 * The content of an encrypted data packet is more OpenPGP packets
3026 	 * once decrypted, so recursively handle them
3027 	 */
3028 	return decrypt_se_ip_data(PGP_PTAG_CT_SE_IP_DATA_BODY, region, stream);
3029 }
3030 
3031 /**
3032    \ingroup Core_ReadPackets
3033    \brief Read a MDC packet
3034 */
3035 static int
3036 parse_mdc(pgp_region_t *region, pgp_stream_t *stream)
3037 {
3038 	pgp_packet_t pkt;
3039 
3040 	pkt.u.mdc.length = PGP_SHA1_HASH_SIZE;
3041 	if ((pkt.u.mdc.data = calloc(1, PGP_SHA1_HASH_SIZE)) == NULL) {
3042 		(void) fprintf(stderr, "parse_mdc: bad alloc\n");
3043 		return 0;
3044 	}
3045 	if (!limread(pkt.u.mdc.data, PGP_SHA1_HASH_SIZE, region, stream)) {
3046 		return 0;
3047 	}
3048 	CALLBACK(PGP_PTAG_CT_MDC, &stream->cbinfo, &pkt);
3049 	free(pkt.u.mdc.data);
3050 	return 1;
3051 }
3052 
3053 /**
3054  * \ingroup Core_ReadPackets
3055  * \brief Parse one packet.
3056  *
3057  * This function parses the packet tag.  It computes the value of the
3058  * content tag and then calls the appropriate function to handle the
3059  * content.
3060  *
3061  * \param *stream	How to parse
3062  * \param *pktlen	On return, will contain number of bytes in packet
3063  * \return 1 on success, 0 on error, -1 on EOF */
3064 static int
3065 parse_packet(pgp_stream_t *stream, uint32_t *pktlen)
3066 {
3067 	pgp_packet_t	pkt;
3068 	pgp_region_t	region;
3069 	uint8_t		ptag;
3070 	unsigned	indeterminate = 0;
3071 	int		ret;
3072 
3073 	pkt.u.ptag.position = stream->readinfo.position;
3074 
3075 	ret = base_read(&ptag, 1, stream);
3076 
3077 	if (pgp_get_debug_level(__FILE__)) {
3078 		(void) fprintf(stderr,
3079 			"parse_packet: base_read returned %d, ptag %d\n",
3080 			ret, ptag);
3081 	}
3082 
3083 	/* errors in the base read are effectively EOF. */
3084 	if (ret <= 0) {
3085 		return -1;
3086 	}
3087 
3088 	*pktlen = 0;
3089 
3090 	if (!(ptag & PGP_PTAG_ALWAYS_SET)) {
3091 		pkt.u.error = "Format error (ptag bit not set)";
3092 		CALLBACK(PGP_PARSER_ERROR, &stream->cbinfo, &pkt);
3093 		return 0;
3094 	}
3095 	pkt.u.ptag.new_format = !!(ptag & PGP_PTAG_NEW_FORMAT);
3096 	if (pkt.u.ptag.new_format) {
3097 		pkt.u.ptag.type = (ptag & PGP_PTAG_NF_CONTENT_TAG_MASK);
3098 		pkt.u.ptag.length_type = 0;
3099 		if (!read_new_length(&pkt.u.ptag.length, stream)) {
3100 			return 0;
3101 		}
3102 	} else {
3103 		unsigned   rb;
3104 
3105 		rb = 0;
3106 		pkt.u.ptag.type = ((unsigned)ptag &
3107 				PGP_PTAG_OF_CONTENT_TAG_MASK)
3108 			>> PGP_PTAG_OF_CONTENT_TAG_SHIFT;
3109 		pkt.u.ptag.length_type = ptag & PGP_PTAG_OF_LENGTH_TYPE_MASK;
3110 		switch (pkt.u.ptag.length_type) {
3111 		case PGP_PTAG_OLD_LEN_1:
3112 			rb = _read_scalar(&pkt.u.ptag.length, 1, stream);
3113 			break;
3114 
3115 		case PGP_PTAG_OLD_LEN_2:
3116 			rb = _read_scalar(&pkt.u.ptag.length, 2, stream);
3117 			break;
3118 
3119 		case PGP_PTAG_OLD_LEN_4:
3120 			rb = _read_scalar(&pkt.u.ptag.length, 4, stream);
3121 			break;
3122 
3123 		case PGP_PTAG_OLD_LEN_INDETERMINATE:
3124 			pkt.u.ptag.length = 0;
3125 			indeterminate = 1;
3126 			rb = 1;
3127 			break;
3128 		}
3129 		if (!rb) {
3130 			return 0;
3131 		}
3132 	}
3133 
3134 	CALLBACK(PGP_PARSER_PTAG, &stream->cbinfo, &pkt);
3135 
3136 	pgp_init_subregion(&region, NULL);
3137 	region.length = pkt.u.ptag.length;
3138 	region.indeterminate = indeterminate;
3139 	if (pgp_get_debug_level(__FILE__)) {
3140 		(void) fprintf(stderr, "parse_packet: type %u\n",
3141 			       pkt.u.ptag.type);
3142 	}
3143 	switch (pkt.u.ptag.type) {
3144 	case PGP_PTAG_CT_SIGNATURE:
3145 		ret = parse_sig(&region, stream);
3146 		break;
3147 
3148 	case PGP_PTAG_CT_PUBLIC_KEY:
3149 	case PGP_PTAG_CT_PUBLIC_SUBKEY:
3150 		ret = parse_pubkey((pgp_content_enum)pkt.u.ptag.type, &region, stream);
3151 		break;
3152 
3153 	case PGP_PTAG_CT_TRUST:
3154 		ret = parse_trust(&region, stream);
3155 		break;
3156 
3157 	case PGP_PTAG_CT_USER_ID:
3158 		ret = parse_userid(&region, stream);
3159 		break;
3160 
3161 	case PGP_PTAG_CT_COMPRESSED:
3162 		ret = parse_compressed(&region, stream);
3163 		break;
3164 
3165 	case PGP_PTAG_CT_1_PASS_SIG:
3166 		ret = parse_one_pass(&region, stream);
3167 		break;
3168 
3169 	case PGP_PTAG_CT_LITDATA:
3170 		ret = parse_litdata(&region, stream);
3171 		break;
3172 
3173 	case PGP_PTAG_CT_USER_ATTR:
3174 		ret = parse_userattr(&region, stream);
3175 		break;
3176 
3177 	case PGP_PTAG_CT_SECRET_KEY:
3178 		ret = parse_seckey(&region, stream);
3179 		break;
3180 
3181 	case PGP_PTAG_CT_SECRET_SUBKEY:
3182 		ret = parse_seckey(&region, stream);
3183 		break;
3184 
3185 	case PGP_PTAG_CT_PK_SESSION_KEY:
3186 		ret = parse_pk_sesskey(&region, stream);
3187 		break;
3188 
3189 	case PGP_PTAG_CT_SE_DATA:
3190 		ret = parse_se_data(&region, stream);
3191 		break;
3192 
3193 	case PGP_PTAG_CT_SE_IP_DATA:
3194 		ret = parse_se_ip_data(&region, stream);
3195 		break;
3196 
3197 	case PGP_PTAG_CT_MDC:
3198 		ret = parse_mdc(&region, stream);
3199 		break;
3200 
3201 	default:
3202 		PGP_ERROR_1(&stream->errors, PGP_E_P_UNKNOWN_TAG,
3203 			    "Unknown content tag 0x%x",
3204 			    pkt.u.ptag.type);
3205 		ret = 0;
3206 	}
3207 
3208 	/* Ensure that the entire packet has been consumed */
3209 
3210 	if (region.length != region.readc && !region.indeterminate) {
3211 		if (!consume_packet(&region, stream, 0)) {
3212 			ret = -1;
3213 		}
3214 	}
3215 
3216 	/* also consume it if there's been an error? */
3217 	/* \todo decide what to do about an error on an */
3218 	/* indeterminate packet */
3219 	if (ret == 0) {
3220 		if (!consume_packet(&region, stream, 0)) {
3221 			ret = -1;
3222 		}
3223 	}
3224 	/* set pktlen */
3225 
3226 	*pktlen = stream->readinfo.alength;
3227 
3228 	/* do callback on entire packet, if desired and there was no error */
3229 
3230 	if (ret > 0 && stream->readinfo.accumulate) {
3231 		pkt.u.packet.length = stream->readinfo.alength;
3232 		pkt.u.packet.raw = stream->readinfo.accumulated;
3233 		stream->readinfo.accumulated = NULL;
3234 		stream->readinfo.asize = 0;
3235 		CALLBACK(PGP_PARSER_PACKET_END, &stream->cbinfo, &pkt);
3236 	}
3237 	stream->readinfo.alength = 0;
3238 
3239 	return (ret < 0) ? -1 : (ret) ? 1 : 0;
3240 }
3241 
3242 /**
3243  * \ingroup Core_ReadPackets
3244  *
3245  * \brief Parse packets from an input stream until EOF or error.
3246  *
3247  * \details Setup the necessary parsing configuration in "stream"
3248  * before calling pgp_parse().
3249  *
3250  * That information includes :
3251  *
3252  * - a "reader" function to be used to get the data to be parsed
3253  *
3254  * - a "callback" function to be called when this library has identified
3255  * a parseable object within the data
3256  *
3257  * - whether the calling function wants the signature subpackets
3258  * returned raw, parsed or not at all.
3259  *
3260  * After returning, stream->errors holds any errors encountered while parsing.
3261  *
3262  * \param stream	Parsing configuration
3263  * \return		1 on success in all packets, 0 on error in any packet
3264  *
3265  * \sa CoreAPI Overview
3266  *
3267  * \sa pgp_print_errors()
3268  *
3269  */
3270 
3271 int
3272 pgp_parse(pgp_stream_t *stream, const int perrors)
3273 {
3274 	uint32_t   pktlen;
3275 	int             r;
3276 
3277 	do {
3278 		r = parse_packet(stream, &pktlen);
3279 	} while (r != -1);
3280 	if (perrors) {
3281 		pgp_print_errors(stream->errors);
3282 	}
3283 	return (stream->errors == NULL);
3284 }
3285 
3286 /**
3287  * \ingroup Core_ReadPackets
3288  *
3289  * \brief Specifies whether one or more signature
3290  * subpacket types should be returned parsed; or raw; or ignored.
3291  *
3292  * \param	stream	Pointer to previously allocated structure
3293  * \param	tag	Packet tag. PGP_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
3294  * \param	type	Parse type
3295  * \todo Make all packet types optional, not just subpackets */
3296 void
3297 pgp_parse_options(pgp_stream_t *stream,
3298 		  pgp_content_enum tag,
3299 		  pgp_parse_type_t type)
3300 {
3301 	unsigned	t7;
3302 	unsigned	t8;
3303 
3304 	if (tag == PGP_PTAG_SS_ALL) {
3305 		int             n;
3306 
3307 		for (n = 0; n < 256; ++n) {
3308 			pgp_parse_options(stream,
3309 				PGP_PTAG_SIG_SUBPKT_BASE + n,
3310 				type);
3311 		}
3312 		return;
3313 	}
3314 	if (tag < PGP_PTAG_SIG_SUBPKT_BASE ||
3315 	    tag > PGP_PTAG_SIG_SUBPKT_BASE + NTAGS - 1) {
3316 		(void) fprintf(stderr, "pgp_parse_options: bad tag\n");
3317 		return;
3318 	}
3319 	t8 = (tag - PGP_PTAG_SIG_SUBPKT_BASE) / 8;
3320 	t7 = 1 << ((tag - PGP_PTAG_SIG_SUBPKT_BASE) & 7);
3321 	switch (type) {
3322 	case PGP_PARSE_RAW:
3323 		stream->ss_raw[t8] |= t7;
3324 		stream->ss_parsed[t8] &= ~t7;
3325 		break;
3326 
3327 	case PGP_PARSE_PARSED:
3328 		stream->ss_raw[t8] &= ~t7;
3329 		stream->ss_parsed[t8] |= t7;
3330 		break;
3331 
3332 	case PGP_PARSE_IGNORE:
3333 		stream->ss_raw[t8] &= ~t7;
3334 		stream->ss_parsed[t8] &= ~t7;
3335 		break;
3336 	}
3337 }
3338 
3339 /**
3340 \ingroup Core_ReadPackets
3341 \brief Free pgp_stream_t struct and its contents
3342 */
3343 void
3344 pgp_stream_delete(pgp_stream_t *stream)
3345 {
3346 	pgp_cbdata_t	*cbinfo;
3347 	pgp_cbdata_t	*next;
3348 
3349 	for (cbinfo = stream->cbinfo.next; cbinfo; cbinfo = next) {
3350 		next = cbinfo->next;
3351 		free(cbinfo);
3352 	}
3353 	if (stream->readinfo.destroyer) {
3354 		stream->readinfo.destroyer(&stream->readinfo);
3355 	}
3356 	pgp_free_errors(stream->errors);
3357 	if (stream->readinfo.accumulated) {
3358 		free(stream->readinfo.accumulated);
3359 	}
3360 	free(stream);
3361 }
3362 
3363 /**
3364 \ingroup Core_ReadPackets
3365 \brief Returns the parse_info's reader_info
3366 \return Pointer to the reader_info inside the parse_info
3367 */
3368 pgp_reader_t *
3369 pgp_readinfo(pgp_stream_t *stream)
3370 {
3371 	return &stream->readinfo;
3372 }
3373 
3374 /**
3375 \ingroup Core_ReadPackets
3376 \brief Sets the parse_info's callback
3377 This is used when adding the first callback in a stack of callbacks.
3378 \sa pgp_callback_push()
3379 */
3380 
3381 void
3382 pgp_set_callback(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3383 {
3384 	stream->cbinfo.cbfunc = cb;
3385 	stream->cbinfo.arg = arg;
3386 	stream->cbinfo.errors = &stream->errors;
3387 }
3388 
3389 /**
3390 \ingroup Core_ReadPackets
3391 \brief Adds a further callback to a stack of callbacks
3392 \sa pgp_set_callback()
3393 */
3394 void
3395 pgp_callback_push(pgp_stream_t *stream, pgp_cbfunc_t *cb, void *arg)
3396 {
3397 	pgp_cbdata_t	*cbinfo;
3398 
3399 	if ((cbinfo = calloc(1, sizeof(*cbinfo))) == NULL) {
3400 		(void) fprintf(stderr, "pgp_callback_push: bad alloc\n");
3401 		return;
3402 	}
3403 	(void) memcpy(cbinfo, &stream->cbinfo, sizeof(*cbinfo));
3404 	cbinfo->io = stream->io;
3405 	stream->cbinfo.next = cbinfo;
3406 	pgp_set_callback(stream, cb, arg);
3407 }
3408 
3409 /**
3410 \ingroup Core_ReadPackets
3411 \brief Returns callback's arg
3412 */
3413 void *
3414 pgp_callback_arg(pgp_cbdata_t *cbinfo)
3415 {
3416 	return cbinfo->arg;
3417 }
3418 
3419 /**
3420 \ingroup Core_ReadPackets
3421 \brief Returns callback's errors
3422 */
3423 void *
3424 pgp_callback_errors(pgp_cbdata_t *cbinfo)
3425 {
3426 	return cbinfo->errors;
3427 }
3428 
3429 /**
3430 \ingroup Core_ReadPackets
3431 \brief Calls the parse_cb_info's callback if present
3432 \return Return value from callback, if present; else PGP_FINISHED
3433 */
3434 pgp_cb_ret_t
3435 pgp_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3436 {
3437 	return (cbinfo->cbfunc) ? cbinfo->cbfunc(pkt, cbinfo) : PGP_FINISHED;
3438 }
3439 
3440 /**
3441 \ingroup Core_ReadPackets
3442 \brief Calls the next callback  in the stack
3443 \return Return value from callback
3444 */
3445 pgp_cb_ret_t
3446 pgp_stacked_callback(const pgp_packet_t *pkt, pgp_cbdata_t *cbinfo)
3447 {
3448 	return pgp_callback(pkt, cbinfo->next);
3449 }
3450 
3451 /**
3452 \ingroup Core_ReadPackets
3453 \brief Returns the parse_info's errors
3454 \return parse_info's errors
3455 */
3456 pgp_error_t    *
3457 pgp_stream_get_errors(pgp_stream_t *stream)
3458 {
3459 	return stream->errors;
3460 }
3461 
3462 pgp_crypt_t    *
3463 pgp_get_decrypt(pgp_stream_t *stream)
3464 {
3465 	return (stream->decrypt.alg) ? &stream->decrypt : NULL;
3466 }
3467