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