xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/packet-parse.c (revision 62a8debe1dc62962e18a1c918def78666141273b)
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.30 2010/03/05 16:01:09 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.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) + 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 += n;
275 	/* and also the position */
276 	readinfo->position += n;
277 
278 	return 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 = r;
419 	do {
420 		region->readc += 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 static void
784 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(__ops_cleartext_trailer_t *trailer)
837 {
838 	free(trailer->hash);
839 	trailer->hash = 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 the memory used when parsing this signature sub-packet type
858 */
859 static void
860 ss_userdef_free(__ops_ss_userdef_t *ss_userdef)
861 {
862 	data_free(&ss_userdef->data);
863 }
864 
865 /**
866    \ingroup Core_Create
867    \brief Free the memory used when parsing this signature sub-packet type
868 */
869 static void
870 ss_reserved_free(__ops_ss_unknown_t *ss_unknown)
871 {
872 	data_free(&ss_unknown->data);
873 }
874 
875 /**
876    \ingroup Core_Create
877    \brief Free the memory used when parsing this packet type
878 */
879 static void
880 trust_free(__ops_trust_t *trust)
881 {
882 	data_free(&trust->data);
883 }
884 
885 /**
886  * \ingroup Core_Create
887  * \brief Free the memory used when parsing a private/experimental PKA signature
888  * \param unknown_sig
889  */
890 static void
891 free_unknown_sig_pka(__ops_unknown_sig_t *unknown_sig)
892 {
893 	data_free(&unknown_sig->data);
894 }
895 
896 /**
897 \ingroup Core_Create
898 \brief Free allocated memory
899 */
900 static void
901 free_BN(BIGNUM **pp)
902 {
903 	BN_free(*pp);
904 	*pp = NULL;
905 }
906 
907 /**
908  * \ingroup Core_Create
909  * \brief Free the memory used when parsing a signature
910  * \param sig
911  */
912 static void
913 sig_free(__ops_sig_t *sig)
914 {
915 	switch (sig->info.key_alg) {
916 	case OPS_PKA_RSA:
917 	case OPS_PKA_RSA_SIGN_ONLY:
918 		free_BN(&sig->info.sig.rsa.sig);
919 		break;
920 
921 	case OPS_PKA_DSA:
922 		free_BN(&sig->info.sig.dsa.r);
923 		free_BN(&sig->info.sig.dsa.s);
924 		break;
925 
926 	case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
927 		free_BN(&sig->info.sig.elgamal.r);
928 		free_BN(&sig->info.sig.elgamal.s);
929 		break;
930 
931 	case OPS_PKA_PRIVATE00:
932 	case OPS_PKA_PRIVATE01:
933 	case OPS_PKA_PRIVATE02:
934 	case OPS_PKA_PRIVATE03:
935 	case OPS_PKA_PRIVATE04:
936 	case OPS_PKA_PRIVATE05:
937 	case OPS_PKA_PRIVATE06:
938 	case OPS_PKA_PRIVATE07:
939 	case OPS_PKA_PRIVATE08:
940 	case OPS_PKA_PRIVATE09:
941 	case OPS_PKA_PRIVATE10:
942 		free_unknown_sig_pka(&sig->info.sig.unknown);
943 		break;
944 
945 	default:
946 		(void) fprintf(stderr, "sig_free: bad sig type\n");
947 	}
948 }
949 
950 /**
951  \ingroup Core_Create
952  \brief Free the memory used when parsing this signature sub-packet type
953  \param ss_skapref
954 */
955 static void
956 ss_skapref_free(__ops_ss_skapref_t *ss_skapref)
957 {
958 	data_free(&ss_skapref->data);
959 }
960 
961 /**
962    \ingroup Core_Create
963    \brief Free the memory used when parsing this signature sub-packet type
964    \param ss_hashpref
965 */
966 static void
967 ss_hashpref_free(__ops_ss_hashpref_t *ss_hashpref)
968 {
969 	data_free(&ss_hashpref->data);
970 }
971 
972 /**
973    \ingroup Core_Create
974    \brief Free the memory used when parsing this signature sub-packet type
975 */
976 static void
977 ss_zpref_free(__ops_ss_zpref_t *ss_zpref)
978 {
979 	data_free(&ss_zpref->data);
980 }
981 
982 /**
983    \ingroup Core_Create
984    \brief Free the memory used when parsing this signature sub-packet type
985 */
986 static void
987 ss_key_flags_free(__ops_ss_key_flags_t *ss_key_flags)
988 {
989 	data_free(&ss_key_flags->data);
990 }
991 
992 /**
993    \ingroup Core_Create
994    \brief Free the memory used when parsing this signature sub-packet type
995 */
996 static void
997 ss_key_server_prefs_free(__ops_ss_key_server_prefs_t *ss_key_server_prefs)
998 {
999 	data_free(&ss_key_server_prefs->data);
1000 }
1001 
1002 /**
1003    \ingroup Core_Create
1004    \brief Free the memory used when parsing this signature sub-packet type
1005 */
1006 static void
1007 ss_features_free(__ops_ss_features_t *ss_features)
1008 {
1009 	data_free(&ss_features->data);
1010 }
1011 
1012 /**
1013    \ingroup Core_Create
1014    \brief Free the memory used when parsing this signature sub-packet type
1015 */
1016 static void
1017 ss_notation_free(__ops_ss_notation_t *ss_notation)
1018 {
1019 	data_free(&ss_notation->name);
1020 	data_free(&ss_notation->value);
1021 }
1022 
1023 /**
1024 \ingroup Core_Create
1025 \brief Free allocated memory
1026 */
1027 /* ! Free the memory used when parsing this signature sub-packet type */
1028 static void
1029 ss_regexp_free(__ops_ss_regexp_t *regexp)
1030 {
1031 	string_free(&regexp->regexp);
1032 }
1033 
1034 /**
1035 \ingroup Core_Create
1036 \brief Free allocated memory
1037 */
1038 /* ! Free the memory used when parsing this signature sub-packet type */
1039 static void
1040 ss_policy_free(__ops_ss_policy_t *policy)
1041 {
1042 	string_free(&policy->url);
1043 }
1044 
1045 /**
1046 \ingroup Core_Create
1047 \brief Free allocated memory
1048 */
1049 /* ! Free the memory used when parsing this signature sub-packet type */
1050 static void
1051 ss_keyserv_free(__ops_ss_keyserv_t *preferred_key_server)
1052 {
1053 	string_free(&preferred_key_server->name);
1054 }
1055 
1056 /**
1057    \ingroup Core_Create
1058    \brief Free the memory used when parsing this signature sub-packet type
1059 */
1060 static void
1061 ss_revocation_free(__ops_ss_revocation_t *ss_revocation)
1062 {
1063 	string_free(&ss_revocation->reason);
1064 }
1065 
1066 static void
1067 ss_embedded_sig_free(__ops_ss_embedded_sig_t *ss_embedded_sig)
1068 {
1069 	data_free(&ss_embedded_sig->sig);
1070 }
1071 
1072 /**
1073 \ingroup Core_Create
1074 \brief Free allocated memory
1075 */
1076 /* ! Free any memory allocated when parsing the packet content */
1077 void
1078 __ops_parser_content_free(__ops_packet_t *c)
1079 {
1080 	switch (c->tag) {
1081 	case OPS_PARSER_PTAG:
1082 	case OPS_PTAG_CT_COMPRESSED:
1083 	case OPS_PTAG_SS_CREATION_TIME:
1084 	case OPS_PTAG_SS_EXPIRATION_TIME:
1085 	case OPS_PTAG_SS_KEY_EXPIRY:
1086 	case OPS_PTAG_SS_TRUST:
1087 	case OPS_PTAG_SS_ISSUER_KEY_ID:
1088 	case OPS_PTAG_CT_1_PASS_SIG:
1089 	case OPS_PTAG_SS_PRIMARY_USER_ID:
1090 	case OPS_PTAG_SS_REVOCABLE:
1091 	case OPS_PTAG_SS_REVOCATION_KEY:
1092 	case OPS_PTAG_CT_LITDATA_HEADER:
1093 	case OPS_PTAG_CT_LITDATA_BODY:
1094 	case OPS_PTAG_CT_SIGNED_CLEARTEXT_BODY:
1095 	case OPS_PTAG_CT_UNARMOURED_TEXT:
1096 	case OPS_PTAG_CT_ARMOUR_TRAILER:
1097 	case OPS_PTAG_CT_SIGNATURE_HEADER:
1098 	case OPS_PTAG_CT_SE_DATA_HEADER:
1099 	case OPS_PTAG_CT_SE_IP_DATA_HEADER:
1100 	case OPS_PTAG_CT_SE_IP_DATA_BODY:
1101 	case OPS_PTAG_CT_MDC:
1102 	case OPS_GET_SECKEY:
1103 		break;
1104 
1105 	case OPS_PTAG_CT_SIGNED_CLEARTEXT_HEADER:
1106 		__ops_headers_free(&c->u.cleartext_head.headers);
1107 		break;
1108 
1109 	case OPS_PTAG_CT_ARMOUR_HEADER:
1110 		__ops_headers_free(&c->u.armour_header.headers);
1111 		break;
1112 
1113 	case OPS_PTAG_CT_SIGNED_CLEARTEXT_TRAILER:
1114 		cleartext_trailer_free(&c->u.cleartext_trailer);
1115 		break;
1116 
1117 	case OPS_PTAG_CT_TRUST:
1118 		trust_free(&c->u.trust);
1119 		break;
1120 
1121 	case OPS_PTAG_CT_SIGNATURE:
1122 	case OPS_PTAG_CT_SIGNATURE_FOOTER:
1123 		sig_free(&c->u.sig);
1124 		break;
1125 
1126 	case OPS_PTAG_CT_PUBLIC_KEY:
1127 	case OPS_PTAG_CT_PUBLIC_SUBKEY:
1128 		__ops_pubkey_free(&c->u.pubkey);
1129 		break;
1130 
1131 	case OPS_PTAG_CT_USER_ID:
1132 		__ops_userid_free(&c->u.userid);
1133 		break;
1134 
1135 	case OPS_PTAG_SS_SIGNERS_USER_ID:
1136 		__ops_userid_free(&c->u.ss_signer);
1137 		break;
1138 
1139 	case OPS_PTAG_CT_USER_ATTR:
1140 		__ops_userattr_free(&c->u.userattr);
1141 		break;
1142 
1143 	case OPS_PTAG_SS_PREFERRED_SKA:
1144 		ss_skapref_free(&c->u.ss_skapref);
1145 		break;
1146 
1147 	case OPS_PTAG_SS_PREFERRED_HASH:
1148 		ss_hashpref_free(&c->u.ss_hashpref);
1149 		break;
1150 
1151 	case OPS_PTAG_SS_PREF_COMPRESS:
1152 		ss_zpref_free(&c->u.ss_zpref);
1153 		break;
1154 
1155 	case OPS_PTAG_SS_KEY_FLAGS:
1156 		ss_key_flags_free(&c->u.ss_key_flags);
1157 		break;
1158 
1159 	case OPS_PTAG_SS_KEYSERV_PREFS:
1160 		ss_key_server_prefs_free(&c->u.ss_key_server_prefs);
1161 		break;
1162 
1163 	case OPS_PTAG_SS_FEATURES:
1164 		ss_features_free(&c->u.ss_features);
1165 		break;
1166 
1167 	case OPS_PTAG_SS_NOTATION_DATA:
1168 		ss_notation_free(&c->u.ss_notation);
1169 		break;
1170 
1171 	case OPS_PTAG_SS_REGEXP:
1172 		ss_regexp_free(&c->u.ss_regexp);
1173 		break;
1174 
1175 	case OPS_PTAG_SS_POLICY_URI:
1176 		ss_policy_free(&c->u.ss_policy);
1177 		break;
1178 
1179 	case OPS_PTAG_SS_PREF_KEYSERV:
1180 		ss_keyserv_free(&c->u.ss_keyserv);
1181 		break;
1182 
1183 	case OPS_PTAG_SS_USERDEFINED00:
1184 	case OPS_PTAG_SS_USERDEFINED01:
1185 	case OPS_PTAG_SS_USERDEFINED02:
1186 	case OPS_PTAG_SS_USERDEFINED03:
1187 	case OPS_PTAG_SS_USERDEFINED04:
1188 	case OPS_PTAG_SS_USERDEFINED05:
1189 	case OPS_PTAG_SS_USERDEFINED06:
1190 	case OPS_PTAG_SS_USERDEFINED07:
1191 	case OPS_PTAG_SS_USERDEFINED08:
1192 	case OPS_PTAG_SS_USERDEFINED09:
1193 	case OPS_PTAG_SS_USERDEFINED10:
1194 		ss_userdef_free(&c->u.ss_userdef);
1195 		break;
1196 
1197 	case OPS_PTAG_SS_RESERVED:
1198 		ss_reserved_free(&c->u.ss_unknown);
1199 		break;
1200 
1201 	case OPS_PTAG_SS_REVOCATION_REASON:
1202 		ss_revocation_free(&c->u.ss_revocation);
1203 		break;
1204 
1205 	case OPS_PTAG_SS_EMBEDDED_SIGNATURE:
1206 		ss_embedded_sig_free(&c->u.ss_embedded_sig);
1207 		break;
1208 
1209 	case OPS_PARSER_PACKET_END:
1210 		__ops_subpacket_free(&c->u.packet);
1211 		break;
1212 
1213 	case OPS_PARSER_ERROR:
1214 	case OPS_PARSER_ERRCODE:
1215 		break;
1216 
1217 	case OPS_PTAG_CT_SECRET_KEY:
1218 	case OPS_PTAG_CT_ENCRYPTED_SECRET_KEY:
1219 		__ops_seckey_free(&c->u.seckey);
1220 		break;
1221 
1222 	case OPS_PTAG_CT_PK_SESSION_KEY:
1223 	case OPS_PTAG_CT_ENCRYPTED_PK_SESSION_KEY:
1224 		__ops_pk_sesskey_free(&c->u.pk_sesskey);
1225 		break;
1226 
1227 	case OPS_GET_PASSPHRASE:
1228 		__ops_cmd_get_passphrase_free(&c->u.skey_passphrase);
1229 		break;
1230 
1231 	default:
1232 		fprintf(stderr, "Can't free %d (0x%x)\n", c->tag, c->tag);
1233 	}
1234 }
1235 
1236 /**
1237 \ingroup Core_Create
1238 \brief Free allocated memory
1239 */
1240 void
1241 __ops_pk_sesskey_free(__ops_pk_sesskey_t *sk)
1242 {
1243 	switch (sk->alg) {
1244 	case OPS_PKA_RSA:
1245 		free_BN(&sk->params.rsa.encrypted_m);
1246 		break;
1247 
1248 	case OPS_PKA_ELGAMAL:
1249 		free_BN(&sk->params.elgamal.g_to_k);
1250 		free_BN(&sk->params.elgamal.encrypted_m);
1251 		break;
1252 
1253 	default:
1254 		(void) fprintf(stderr, "__ops_pk_sesskey_free: bad alg\n");
1255 		break;
1256 	}
1257 }
1258 
1259 /**
1260 \ingroup Core_Create
1261 \brief Free allocated memory
1262 */
1263 /* ! Free the memory used when parsing a public key */
1264 void
1265 __ops_pubkey_free(__ops_pubkey_t *p)
1266 {
1267 	switch (p->alg) {
1268 	case OPS_PKA_RSA:
1269 	case OPS_PKA_RSA_ENCRYPT_ONLY:
1270 	case OPS_PKA_RSA_SIGN_ONLY:
1271 		free_BN(&p->key.rsa.n);
1272 		free_BN(&p->key.rsa.e);
1273 		break;
1274 
1275 	case OPS_PKA_DSA:
1276 		free_BN(&p->key.dsa.p);
1277 		free_BN(&p->key.dsa.q);
1278 		free_BN(&p->key.dsa.g);
1279 		free_BN(&p->key.dsa.y);
1280 		break;
1281 
1282 	case OPS_PKA_ELGAMAL:
1283 	case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1284 		free_BN(&p->key.elgamal.p);
1285 		free_BN(&p->key.elgamal.g);
1286 		free_BN(&p->key.elgamal.y);
1287 		break;
1288 
1289 	case OPS_PKA_NOTHING:
1290 		/* nothing to free */
1291 		break;
1292 
1293 	default:
1294 		(void) fprintf(stderr, "__ops_pubkey_free: bad alg\n");
1295 	}
1296 }
1297 
1298 /**
1299    \ingroup Core_ReadPackets
1300 */
1301 static int
1302 parse_pubkey_data(__ops_pubkey_t *key, __ops_region_t *region,
1303 		      __ops_stream_t *stream)
1304 {
1305 	uint8_t   c = 0x0;
1306 
1307 	if (region->readc != 0) {
1308 		/* We should not have read anything so far */
1309 		(void) fprintf(stderr, "parse_pubkey_data: bad length\n");
1310 		return 0;
1311 	}
1312 	if (!limread(&c, 1, region, stream)) {
1313 		return 0;
1314 	}
1315 	key->version = (__ops_version_t)c;
1316 	switch (key->version) {
1317 	case OPS_V2:
1318 	case OPS_V3:
1319 	case OPS_V4:
1320 		break;
1321 	default:
1322 		OPS_ERROR_1(&stream->errors, OPS_E_PROTO_BAD_PUBLIC_KEY_VRSN,
1323 			    "Bad public key version (0x%02x)", key->version);
1324 		return 0;
1325 	}
1326 	if (!limited_read_time(&key->birthtime, region, stream)) {
1327 		return 0;
1328 	}
1329 
1330 	key->days_valid = 0;
1331 	if ((key->version == 2 || key->version == 3) &&
1332 	    !limread_scalar(&key->days_valid, 2, region, stream)) {
1333 		return 0;
1334 	}
1335 
1336 	if (!limread(&c, 1, region, stream)) {
1337 		return 0;
1338 	}
1339 	key->alg = c;
1340 
1341 	switch (key->alg) {
1342 	case OPS_PKA_DSA:
1343 		if (!limread_mpi(&key->key.dsa.p, region, stream) ||
1344 		    !limread_mpi(&key->key.dsa.q, region, stream) ||
1345 		    !limread_mpi(&key->key.dsa.g, region, stream) ||
1346 		    !limread_mpi(&key->key.dsa.y, region, stream)) {
1347 			return 0;
1348 		}
1349 		break;
1350 
1351 	case OPS_PKA_RSA:
1352 	case OPS_PKA_RSA_ENCRYPT_ONLY:
1353 	case OPS_PKA_RSA_SIGN_ONLY:
1354 		if (!limread_mpi(&key->key.rsa.n, region, stream) ||
1355 		    !limread_mpi(&key->key.rsa.e, region, stream)) {
1356 			return 0;
1357 		}
1358 		break;
1359 
1360 	case OPS_PKA_ELGAMAL:
1361 	case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1362 		if (!limread_mpi(&key->key.elgamal.p, region, stream) ||
1363 		    !limread_mpi(&key->key.elgamal.g, region, stream) ||
1364 		    !limread_mpi(&key->key.elgamal.y, region, stream)) {
1365 			return 0;
1366 		}
1367 		break;
1368 
1369 	default:
1370 		OPS_ERROR_1(&stream->errors,
1371 			OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
1372 			"Unsupported Public Key algorithm (%s)",
1373 			__ops_show_pka(key->alg));
1374 		return 0;
1375 	}
1376 
1377 	return 1;
1378 }
1379 
1380 
1381 /**
1382  * \ingroup Core_ReadPackets
1383  * \brief Parse a public key packet.
1384  *
1385  * This function parses an entire v3 (== v2) or v4 public key packet for RSA, ElGamal, and DSA keys.
1386  *
1387  * Once the key has been parsed successfully, it is passed to the callback.
1388  *
1389  * \param *ptag		Pointer to the current Packet Tag.  This function should consume the entire packet.
1390  * \param *reader	Our reader
1391  * \param *cb		The callback
1392  * \return		1 on success, 0 on error
1393  *
1394  * \see RFC4880 5.5.2
1395  */
1396 static int
1397 parse_pubkey(__ops_content_tag_t tag, __ops_region_t *region,
1398 		 __ops_stream_t *stream)
1399 {
1400 	__ops_packet_t pkt;
1401 
1402 	if (!parse_pubkey_data(&pkt.u.pubkey, region, stream))
1403 		return 0;
1404 
1405 	/* XXX: this test should be done for all packets, surely? */
1406 	if (region->readc != region->length) {
1407 		OPS_ERROR_1(&stream->errors, OPS_E_R_UNCONSUMED_DATA,
1408 			    "Unconsumed data (%d)", region->length - region->readc);
1409 		return 0;
1410 	}
1411 	CALLBACK(tag, &stream->cbinfo, &pkt);
1412 
1413 	return 1;
1414 }
1415 
1416 
1417 /**
1418 \ingroup Core_Create
1419 \brief Free allocated memory
1420 */
1421 /* ! Free the memory used when parsing this packet type */
1422 void
1423 __ops_userattr_free(__ops_userattr_t *user_att)
1424 {
1425 	data_free(&user_att->data);
1426 }
1427 
1428 /**
1429  * \ingroup Core_ReadPackets
1430  * \brief Parse one user attribute packet.
1431  *
1432  * User attribute packets contain one or more attribute subpackets.
1433  * For now, handle the whole packet as raw data.
1434  */
1435 
1436 static int
1437 parse_userattr(__ops_region_t *region, __ops_stream_t *stream)
1438 {
1439 
1440 	__ops_packet_t pkt;
1441 
1442 	/*
1443 	 * xxx- treat as raw data for now. Could break down further into
1444 	 * attribute sub-packets later - rachel
1445 	 */
1446 
1447 	if (region->readc != 0) {
1448 		/* We should not have read anything so far */
1449 		(void) fprintf(stderr, "parse_userattr: bad length\n");
1450 		return 0;
1451 	}
1452 
1453 	if (!read_data(&pkt.u.userattr.data, region, stream))
1454 		return 0;
1455 
1456 	CALLBACK(OPS_PTAG_CT_USER_ATTR, &stream->cbinfo, &pkt);
1457 
1458 	return 1;
1459 }
1460 
1461 /**
1462 \ingroup Core_Create
1463 \brief Free allocated memory
1464 */
1465 /* ! Free the memory used when parsing this packet type */
1466 void
1467 __ops_userid_free(__ops_userid_t *id)
1468 {
1469 	free(id->userid);
1470 	id->userid = NULL;
1471 }
1472 
1473 /**
1474  * \ingroup Core_ReadPackets
1475  * \brief Parse a user id.
1476  *
1477  * This function parses an user id packet, which is basically just a char array the size of the packet.
1478  *
1479  * The char array is to be treated as an UTF-8 string.
1480  *
1481  * The userid gets null terminated by this function.  Freeing it is the responsibility of the caller.
1482  *
1483  * Once the userid has been parsed successfully, it is passed to the callback.
1484  *
1485  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1486  * \param *reader	Our reader
1487  * \param *cb		The callback
1488  * \return		1 on success, 0 on error
1489  *
1490  * \see RFC4880 5.11
1491  */
1492 static int
1493 parse_userid(__ops_region_t *region, __ops_stream_t *stream)
1494 {
1495 	__ops_packet_t pkt;
1496 
1497 	 if (region->readc != 0) {
1498 		/* We should not have read anything so far */
1499 		(void) fprintf(stderr, "parse_userid: bad length\n");
1500 		return 0;
1501 	}
1502 
1503 	if ((pkt.u.userid.userid = calloc(1, region->length + 1)) == NULL) {
1504 		(void) fprintf(stderr, "parse_userid: bad alloc\n");
1505 		return 0;
1506 	}
1507 
1508 	if (region->length &&
1509 	    !limread(pkt.u.userid.userid, region->length, region,
1510 			stream)) {
1511 		return 0;
1512 	}
1513 	pkt.u.userid.userid[region->length] = '\0';
1514 	CALLBACK(OPS_PTAG_CT_USER_ID, &stream->cbinfo, &pkt);
1515 	return 1;
1516 }
1517 
1518 static __ops_hash_t     *
1519 parse_hash_find(__ops_stream_t *stream, const uint8_t *keyid)
1520 {
1521 	__ops_hashtype_t	*hp;
1522 	size_t			 n;
1523 
1524 	for (n = 0, hp = stream->hashes; n < stream->hashc; n++, hp++) {
1525 		if (memcmp(hp->keyid, keyid, OPS_KEY_ID_SIZE) == 0) {
1526 			return &hp->hash;
1527 		}
1528 	}
1529 	return NULL;
1530 }
1531 
1532 /**
1533  * \ingroup Core_Parse
1534  * \brief Parse a version 3 signature.
1535  *
1536  * This function parses an version 3 signature packet, handling RSA and DSA signatures.
1537  *
1538  * Once the signature has been parsed successfully, it is passed to the callback.
1539  *
1540  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire packet.
1541  * \param *reader	Our reader
1542  * \param *cb		The callback
1543  * \return		1 on success, 0 on error
1544  *
1545  * \see RFC4880 5.2.2
1546  */
1547 static int
1548 parse_v3_sig(__ops_region_t *region,
1549 		   __ops_stream_t *stream)
1550 {
1551 	__ops_packet_t	pkt;
1552 	uint8_t		c = 0x0;
1553 
1554 	/* clear signature */
1555 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
1556 
1557 	pkt.u.sig.info.version = OPS_V3;
1558 
1559 	/* hash info length */
1560 	if (!limread(&c, 1, region, stream)) {
1561 		return 0;
1562 	}
1563 	if (c != 5) {
1564 		ERRP(&stream->cbinfo, pkt, "bad hash info length");
1565 	}
1566 
1567 	if (!limread(&c, 1, region, stream)) {
1568 		return 0;
1569 	}
1570 	pkt.u.sig.info.type = (__ops_sig_type_t)c;
1571 	/* XXX: check signature type */
1572 
1573 	if (!limited_read_time(&pkt.u.sig.info.birthtime, region, stream)) {
1574 		return 0;
1575 	}
1576 	pkt.u.sig.info.birthtime_set = 1;
1577 
1578 	if (!limread(pkt.u.sig.info.signer_id, OPS_KEY_ID_SIZE, region,
1579 			stream)) {
1580 		return 0;
1581 	}
1582 	pkt.u.sig.info.signer_id_set = 1;
1583 
1584 	if (!limread(&c, 1, region, stream)) {
1585 		return 0;
1586 	}
1587 	pkt.u.sig.info.key_alg = (__ops_pubkey_alg_t)c;
1588 	/* XXX: check algorithm */
1589 
1590 	if (!limread(&c, 1, region, stream)) {
1591 		return 0;
1592 	}
1593 	pkt.u.sig.info.hash_alg = (__ops_hash_alg_t)c;
1594 	/* XXX: check algorithm */
1595 
1596 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
1597 		return 0;
1598 	}
1599 
1600 	switch (pkt.u.sig.info.key_alg) {
1601 	case OPS_PKA_RSA:
1602 	case OPS_PKA_RSA_SIGN_ONLY:
1603 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
1604 			return 0;
1605 		}
1606 		break;
1607 
1608 	case OPS_PKA_DSA:
1609 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream) ||
1610 		    !limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
1611 			return 0;
1612 		}
1613 		break;
1614 
1615 	case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
1616 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
1617 				stream) ||
1618 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
1619 		    		stream)) {
1620 			return 0;
1621 		}
1622 		break;
1623 
1624 	default:
1625 		OPS_ERROR_1(&stream->errors,
1626 			OPS_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
1627 			"Unsupported signature key algorithm (%s)",
1628 			__ops_show_pka(pkt.u.sig.info.key_alg));
1629 		return 0;
1630 	}
1631 
1632 	if (region->readc != region->length) {
1633 		OPS_ERROR_1(&stream->errors, OPS_E_R_UNCONSUMED_DATA,
1634 			"Unconsumed data (%d)",
1635 			region->length - region->readc);
1636 		return 0;
1637 	}
1638 	if (pkt.u.sig.info.signer_id_set) {
1639 		pkt.u.sig.hash = parse_hash_find(stream,
1640 				pkt.u.sig.info.signer_id);
1641 	}
1642 	CALLBACK(OPS_PTAG_CT_SIGNATURE, &stream->cbinfo, &pkt);
1643 	return 1;
1644 }
1645 
1646 /**
1647  * \ingroup Core_ReadPackets
1648  * \brief Parse one signature sub-packet.
1649  *
1650  * Version 4 signatures can have an arbitrary amount of (hashed and
1651  * unhashed) subpackets.  Subpackets are used to hold optional
1652  * attributes of subpackets.
1653  *
1654  * This function parses one such signature subpacket.
1655  *
1656  * Once the subpacket has been parsed successfully, it is passed to the callback.
1657  *
1658  * \param *ptag		Pointer to the Packet Tag.  This function should consume the entire subpacket.
1659  * \param *reader	Our reader
1660  * \param *cb		The callback
1661  * \return		1 on success, 0 on error
1662  *
1663  * \see RFC4880 5.2.3
1664  */
1665 static int
1666 parse_one_sig_subpacket(__ops_sig_t *sig,
1667 			      __ops_region_t *region,
1668 			      __ops_stream_t *stream)
1669 {
1670 	__ops_region_t	subregion;
1671 	__ops_packet_t	pkt;
1672 	uint8_t		bools = 0x0;
1673 	uint8_t		c = 0x0;
1674 	unsigned	doread = 1;
1675 	unsigned        t8;
1676 	unsigned        t7;
1677 
1678 	__ops_init_subregion(&subregion, region);
1679 	if (!limited_read_new_length(&subregion.length, region, stream)) {
1680 		return 0;
1681 	}
1682 
1683 	if (subregion.length > region->length) {
1684 		ERRP(&stream->cbinfo, pkt, "Subpacket too long");
1685 	}
1686 
1687 	if (!limread(&c, 1, &subregion, stream)) {
1688 		return 0;
1689 	}
1690 
1691 	t8 = (c & 0x7f) / 8;
1692 	t7 = 1 << (c & 7);
1693 
1694 	pkt.critical = (unsigned)c >> 7;
1695 	pkt.tag = (__ops_content_tag_t)(OPS_PTAG_SIG_SUBPKT_BASE + (c & 0x7f));
1696 
1697 	/* Application wants it delivered raw */
1698 	if (stream->ss_raw[t8] & t7) {
1699 		pkt.u.ss_raw.tag = pkt.tag;
1700 		pkt.u.ss_raw.length = subregion.length - 1;
1701 		pkt.u.ss_raw.raw = calloc(1, pkt.u.ss_raw.length);
1702 		if (pkt.u.ss_raw.raw == NULL) {
1703 			(void) fprintf(stderr, "parse_one_sig_subpacket: bad alloc\n");
1704 			return 0;
1705 		}
1706 		if (!limread(pkt.u.ss_raw.raw, pkt.u.ss_raw.length,
1707 				&subregion, stream)) {
1708 			return 0;
1709 		}
1710 		CALLBACK(OPS_PTAG_RAW_SS, &stream->cbinfo, &pkt);
1711 		return 1;
1712 	}
1713 	switch (pkt.tag) {
1714 	case OPS_PTAG_SS_CREATION_TIME:
1715 	case OPS_PTAG_SS_EXPIRATION_TIME:
1716 	case OPS_PTAG_SS_KEY_EXPIRY:
1717 		if (!limited_read_time(&pkt.u.ss_time.time, &subregion, stream))
1718 			return 0;
1719 		if (pkt.tag == OPS_PTAG_SS_CREATION_TIME) {
1720 			sig->info.birthtime = pkt.u.ss_time.time;
1721 			sig->info.birthtime_set = 1;
1722 		}
1723 		if (pkt.tag == OPS_PTAG_SS_EXPIRATION_TIME) {
1724 			sig->info.duration = pkt.u.ss_time.time;
1725 			sig->info.duration_set = 1;
1726 		}
1727 		break;
1728 
1729 	case OPS_PTAG_SS_TRUST:
1730 		if (!limread(&pkt.u.ss_trust.level, 1, &subregion, stream) ||
1731 		    !limread(&pkt.u.ss_trust.amount, 1, &subregion, stream)) {
1732 			return 0;
1733 		}
1734 		break;
1735 
1736 	case OPS_PTAG_SS_REVOCABLE:
1737 		if (!limread(&bools, 1, &subregion, stream)) {
1738 			return 0;
1739 		}
1740 		pkt.u.ss_revocable.revocable = !!bools;
1741 		break;
1742 
1743 	case OPS_PTAG_SS_ISSUER_KEY_ID:
1744 		if (!limread(pkt.u.ss_issuer.key_id, OPS_KEY_ID_SIZE,
1745 				&subregion, stream)) {
1746 			return 0;
1747 		}
1748 		(void) memcpy(sig->info.signer_id,
1749 			pkt.u.ss_issuer.key_id, OPS_KEY_ID_SIZE);
1750 		sig->info.signer_id_set = 1;
1751 		break;
1752 
1753 	case OPS_PTAG_SS_PREFERRED_SKA:
1754 		if (!read_data(&pkt.u.ss_skapref.data, &subregion, stream)) {
1755 			return 0;
1756 		}
1757 		break;
1758 
1759 	case OPS_PTAG_SS_PREFERRED_HASH:
1760 		if (!read_data(&pkt.u.ss_hashpref.data, &subregion, stream)) {
1761 			return 0;
1762 		}
1763 		break;
1764 
1765 	case OPS_PTAG_SS_PREF_COMPRESS:
1766 		if (!read_data(&pkt.u.ss_zpref.data,
1767 				&subregion, stream)) {
1768 			return 0;
1769 		}
1770 		break;
1771 
1772 	case OPS_PTAG_SS_PRIMARY_USER_ID:
1773 		if (!limread(&bools, 1, &subregion, stream)) {
1774 			return 0;
1775 		}
1776 		pkt.u.ss_primary_userid.primary_userid = !!bools;
1777 		break;
1778 
1779 	case OPS_PTAG_SS_KEY_FLAGS:
1780 		if (!read_data(&pkt.u.ss_key_flags.data, &subregion, stream)) {
1781 			return 0;
1782 		}
1783 		break;
1784 
1785 	case OPS_PTAG_SS_KEYSERV_PREFS:
1786 		if (!read_data(&pkt.u.ss_key_server_prefs.data, &subregion,
1787 				stream)) {
1788 			return 0;
1789 		}
1790 		break;
1791 
1792 	case OPS_PTAG_SS_FEATURES:
1793 		if (!read_data(&pkt.u.ss_features.data, &subregion, stream)) {
1794 			return 0;
1795 		}
1796 		break;
1797 
1798 	case OPS_PTAG_SS_SIGNERS_USER_ID:
1799 		if (!read_unsig_str(&pkt.u.ss_signer.userid, &subregion,
1800 				stream)) {
1801 			return 0;
1802 		}
1803 		break;
1804 
1805 	case OPS_PTAG_SS_EMBEDDED_SIGNATURE:
1806 		/* \todo should do something with this sig? */
1807 		if (!read_data(&pkt.u.ss_embedded_sig.sig, &subregion, stream)) {
1808 			return 0;
1809 		}
1810 		break;
1811 
1812 	case OPS_PTAG_SS_NOTATION_DATA:
1813 		if (!limread_data(&pkt.u.ss_notation.flags, 4,
1814 				&subregion, stream)) {
1815 			return 0;
1816 		}
1817 		if (!limread_size_t(&pkt.u.ss_notation.name.len, 2,
1818 				&subregion, stream)) {
1819 			return 0;
1820 		}
1821 		if (!limread_size_t(&pkt.u.ss_notation.value.len, 2,
1822 				&subregion, stream)) {
1823 			return 0;
1824 		}
1825 		if (!limread_data(&pkt.u.ss_notation.name,
1826 				pkt.u.ss_notation.name.len,
1827 				&subregion, stream)) {
1828 			return 0;
1829 		}
1830 		if (!limread_data(&pkt.u.ss_notation.value,
1831 			   pkt.u.ss_notation.value.len,
1832 			   &subregion, stream)) {
1833 			return 0;
1834 		}
1835 		break;
1836 
1837 	case OPS_PTAG_SS_POLICY_URI:
1838 		if (!read_string(&pkt.u.ss_policy.url, &subregion, stream)) {
1839 			return 0;
1840 		}
1841 		break;
1842 
1843 	case OPS_PTAG_SS_REGEXP:
1844 		if (!read_string(&pkt.u.ss_regexp.regexp, &subregion, stream)) {
1845 			return 0;
1846 		}
1847 		break;
1848 
1849 	case OPS_PTAG_SS_PREF_KEYSERV:
1850 		if (!read_string(&pkt.u.ss_keyserv.name, &subregion, stream)) {
1851 			return 0;
1852 		}
1853 		break;
1854 
1855 	case OPS_PTAG_SS_USERDEFINED00:
1856 	case OPS_PTAG_SS_USERDEFINED01:
1857 	case OPS_PTAG_SS_USERDEFINED02:
1858 	case OPS_PTAG_SS_USERDEFINED03:
1859 	case OPS_PTAG_SS_USERDEFINED04:
1860 	case OPS_PTAG_SS_USERDEFINED05:
1861 	case OPS_PTAG_SS_USERDEFINED06:
1862 	case OPS_PTAG_SS_USERDEFINED07:
1863 	case OPS_PTAG_SS_USERDEFINED08:
1864 	case OPS_PTAG_SS_USERDEFINED09:
1865 	case OPS_PTAG_SS_USERDEFINED10:
1866 		if (!read_data(&pkt.u.ss_userdef.data, &subregion, stream)) {
1867 			return 0;
1868 		}
1869 		break;
1870 
1871 	case OPS_PTAG_SS_RESERVED:
1872 		if (!read_data(&pkt.u.ss_unknown.data, &subregion, stream)) {
1873 			return 0;
1874 		}
1875 		break;
1876 
1877 	case OPS_PTAG_SS_REVOCATION_REASON:
1878 		/* first byte is the machine-readable code */
1879 		if (!limread(&pkt.u.ss_revocation.code, 1, &subregion, stream)) {
1880 			return 0;
1881 		}
1882 		/* the rest is a human-readable UTF-8 string */
1883 		if (!read_string(&pkt.u.ss_revocation.reason, &subregion,
1884 				stream)) {
1885 			return 0;
1886 		}
1887 		break;
1888 
1889 	case OPS_PTAG_SS_REVOCATION_KEY:
1890 		/* octet 0 = class. Bit 0x80 must be set */
1891 		if (!limread(&pkt.u.ss_revocation_key.class, 1,
1892 				&subregion, stream)) {
1893 			return 0;
1894 		}
1895 		if (!(pkt.u.ss_revocation_key.class & 0x80)) {
1896 			printf("Warning: OPS_PTAG_SS_REVOCATION_KEY class: "
1897 			       "Bit 0x80 should be set\n");
1898 			return 0;
1899 		}
1900 		/* octet 1 = algid */
1901 		if (!limread(&pkt.u.ss_revocation_key.algid, 1,
1902 				&subregion, stream)) {
1903 			return 0;
1904 		}
1905 		/* octets 2-21 = fingerprint */
1906 		if (!limread(&pkt.u.ss_revocation_key.fingerprint[0],
1907 				OPS_FINGERPRINT_SIZE, &subregion, stream)) {
1908 			return 0;
1909 		}
1910 		break;
1911 
1912 	default:
1913 		if (stream->ss_parsed[t8] & t7) {
1914 			OPS_ERROR_1(&stream->errors, OPS_E_PROTO_UNKNOWN_SS,
1915 				    "Unknown signature subpacket type (%d)",
1916 				    c & 0x7f);
1917 		}
1918 		doread = 0;
1919 		break;
1920 	}
1921 
1922 	/* Application doesn't want it delivered parsed */
1923 	if (!(stream->ss_parsed[t8] & t7)) {
1924 		if (pkt.critical) {
1925 			OPS_ERROR_1(&stream->errors,
1926 				OPS_E_PROTO_CRITICAL_SS_IGNORED,
1927 				"Critical signature subpacket ignored (%d)",
1928 				c & 0x7f);
1929 		}
1930 		if (!doread &&
1931 		    !limskip(subregion.length - 1, &subregion, stream)) {
1932 			return 0;
1933 		}
1934 		if (doread) {
1935 			__ops_parser_content_free(&pkt);
1936 		}
1937 		return 1;
1938 	}
1939 	if (doread && subregion.readc != subregion.length) {
1940 		OPS_ERROR_1(&stream->errors, OPS_E_R_UNCONSUMED_DATA,
1941 			    "Unconsumed data (%d)",
1942 			    subregion.length - subregion.readc);
1943 		return 0;
1944 	}
1945 	CALLBACK(pkt.tag, &stream->cbinfo, &pkt);
1946 	return 1;
1947 }
1948 
1949 /**
1950  * \ingroup Core_ReadPackets
1951  * \brief Parse several signature subpackets.
1952  *
1953  * Hashed and unhashed subpacket sets are preceded by an octet count that specifies the length of the complete set.
1954  * This function parses this length and then calls parse_one_sig_subpacket() for each subpacket until the
1955  * entire set is consumed.
1956  *
1957  * This function does not call the callback directly, parse_one_sig_subpacket() does for each subpacket.
1958  *
1959  * \param *ptag		Pointer to the Packet Tag.
1960  * \param *reader	Our reader
1961  * \param *cb		The callback
1962  * \return		1 on success, 0 on error
1963  *
1964  * \see RFC4880 5.2.3
1965  */
1966 static int
1967 parse_sig_subpkts(__ops_sig_t *sig,
1968 			   __ops_region_t *region,
1969 			   __ops_stream_t *stream)
1970 {
1971 	__ops_region_t	subregion;
1972 	__ops_packet_t	pkt;
1973 
1974 	__ops_init_subregion(&subregion, region);
1975 	if (!limread_scalar(&subregion.length, 2, region, stream)) {
1976 		return 0;
1977 	}
1978 
1979 	if (subregion.length > region->length) {
1980 		ERRP(&stream->cbinfo, pkt, "Subpacket set too long");
1981 	}
1982 
1983 	while (subregion.readc < subregion.length) {
1984 		if (!parse_one_sig_subpacket(sig, &subregion, stream)) {
1985 			return 0;
1986 		}
1987 	}
1988 
1989 	if (subregion.readc != subregion.length) {
1990 		if (!limskip(subregion.length - subregion.readc,
1991 				&subregion, stream)) {
1992 			ERRP(&stream->cbinfo, pkt,
1993 "parse_sig_subpkts: subpacket length read mismatch");
1994 		}
1995 		ERRP(&stream->cbinfo, pkt, "Subpacket length mismatch");
1996 	}
1997 	return 1;
1998 }
1999 
2000 /**
2001  * \ingroup Core_ReadPackets
2002  * \brief Parse a version 4 signature.
2003  *
2004  * This function parses a version 4 signature including all its hashed and unhashed subpackets.
2005  *
2006  * Once the signature packet has been parsed successfully, it is passed to the callback.
2007  *
2008  * \param *ptag		Pointer to the Packet Tag.
2009  * \param *reader	Our reader
2010  * \param *cb		The callback
2011  * \return		1 on success, 0 on error
2012  *
2013  * \see RFC4880 5.2.3
2014  */
2015 static int
2016 parse_v4_sig(__ops_region_t *region, __ops_stream_t *stream)
2017 {
2018 	__ops_packet_t	pkt;
2019 	uint8_t		c = 0x0;
2020 
2021 	if (__ops_get_debug_level(__FILE__)) {
2022 		fprintf(stderr, "\nparse_v4_sig\n");
2023 	}
2024 	/* clear signature */
2025 	(void) memset(&pkt.u.sig, 0x0, sizeof(pkt.u.sig));
2026 
2027 	/*
2028 	 * We need to hash the packet data from version through the hashed
2029 	 * subpacket data
2030 	 */
2031 
2032 	pkt.u.sig.v4_hashstart = stream->readinfo.alength - 1;
2033 
2034 	/* Set version,type,algorithms */
2035 
2036 	pkt.u.sig.info.version = OPS_V4;
2037 
2038 	if (!limread(&c, 1, region, stream)) {
2039 		return 0;
2040 	}
2041 	pkt.u.sig.info.type = (__ops_sig_type_t)c;
2042 	if (__ops_get_debug_level(__FILE__)) {
2043 		fprintf(stderr, "signature type=%d (%s)\n",
2044 			pkt.u.sig.info.type,
2045 			__ops_show_sig_type(pkt.u.sig.info.type));
2046 	}
2047 	/* XXX: check signature type */
2048 
2049 	if (!limread(&c, 1, region, stream)) {
2050 		return 0;
2051 	}
2052 	pkt.u.sig.info.key_alg = (__ops_pubkey_alg_t)c;
2053 	/* XXX: check key algorithm */
2054 	if (__ops_get_debug_level(__FILE__)) {
2055 		(void) fprintf(stderr, "key_alg=%d (%s)\n",
2056 			pkt.u.sig.info.key_alg,
2057 			__ops_show_pka(pkt.u.sig.info.key_alg));
2058 	}
2059 	if (!limread(&c, 1, region, stream)) {
2060 		return 0;
2061 	}
2062 	pkt.u.sig.info.hash_alg = (__ops_hash_alg_t)c;
2063 	/* XXX: check hash algorithm */
2064 	if (__ops_get_debug_level(__FILE__)) {
2065 		fprintf(stderr, "hash_alg=%d %s\n",
2066 			pkt.u.sig.info.hash_alg,
2067 		  __ops_show_hash_alg(pkt.u.sig.info.hash_alg));
2068 	}
2069 	CALLBACK(OPS_PTAG_CT_SIGNATURE_HEADER, &stream->cbinfo, &pkt);
2070 
2071 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
2072 		return 0;
2073 	}
2074 
2075 	pkt.u.sig.info.v4_hashlen = stream->readinfo.alength
2076 					- pkt.u.sig.v4_hashstart;
2077 	if (__ops_get_debug_level(__FILE__)) {
2078 		fprintf(stderr, "v4_hashlen=%zd\n", pkt.u.sig.info.v4_hashlen);
2079 	}
2080 
2081 	/* copy hashed subpackets */
2082 	if (pkt.u.sig.info.v4_hashed) {
2083 		free(pkt.u.sig.info.v4_hashed);
2084 	}
2085 	pkt.u.sig.info.v4_hashed = calloc(1, pkt.u.sig.info.v4_hashlen);
2086 	if (pkt.u.sig.info.v4_hashed == NULL) {
2087 		(void) fprintf(stderr, "parse_v4_sig: bad alloc\n");
2088 		return 0;
2089 	}
2090 
2091 	if (!stream->readinfo.accumulate) {
2092 		/* We must accumulate, else we can't check the signature */
2093 		fprintf(stderr, "*** ERROR: must set accumulate to 1\n");
2094 		return 0;
2095 	}
2096 	(void) memcpy(pkt.u.sig.info.v4_hashed,
2097 	       stream->readinfo.accumulated + pkt.u.sig.v4_hashstart,
2098 	       pkt.u.sig.info.v4_hashlen);
2099 
2100 	if (!parse_sig_subpkts(&pkt.u.sig, region, stream)) {
2101 		return 0;
2102 	}
2103 
2104 	if (!limread(pkt.u.sig.hash2, 2, region, stream)) {
2105 		return 0;
2106 	}
2107 
2108 	switch (pkt.u.sig.info.key_alg) {
2109 	case OPS_PKA_RSA:
2110 		if (!limread_mpi(&pkt.u.sig.info.sig.rsa.sig, region, stream)) {
2111 			return 0;
2112 		}
2113 		if (__ops_get_debug_level(__FILE__)) {
2114 			(void) fprintf(stderr, "parse_v4_sig: RSA: sig is\n");
2115 			BN_print_fp(stderr, pkt.u.sig.info.sig.rsa.sig);
2116 		}
2117 		break;
2118 
2119 	case OPS_PKA_DSA:
2120 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.r, region, stream)) {
2121 			/*
2122 			 * usually if this fails, it just means we've reached
2123 			 * the end of the keyring
2124 			 */
2125 			if (__ops_get_debug_level(__FILE__)) {
2126 				(void) fprintf(stderr,
2127 				"Error reading DSA r field in signature");
2128 			}
2129 			return 0;
2130 		}
2131 		if (!limread_mpi(&pkt.u.sig.info.sig.dsa.s, region, stream)) {
2132 			ERRP(&stream->cbinfo, pkt,
2133 			"Error reading DSA s field in signature");
2134 		}
2135 		break;
2136 
2137 	case OPS_PKA_ELGAMAL_ENCRYPT_OR_SIGN:
2138 		if (!limread_mpi(&pkt.u.sig.info.sig.elgamal.r, region,
2139 				stream) ||
2140 		    !limread_mpi(&pkt.u.sig.info.sig.elgamal.s, region,
2141 		    		stream)) {
2142 			return 0;
2143 		}
2144 		break;
2145 
2146 	case OPS_PKA_PRIVATE00:
2147 	case OPS_PKA_PRIVATE01:
2148 	case OPS_PKA_PRIVATE02:
2149 	case OPS_PKA_PRIVATE03:
2150 	case OPS_PKA_PRIVATE04:
2151 	case OPS_PKA_PRIVATE05:
2152 	case OPS_PKA_PRIVATE06:
2153 	case OPS_PKA_PRIVATE07:
2154 	case OPS_PKA_PRIVATE08:
2155 	case OPS_PKA_PRIVATE09:
2156 	case OPS_PKA_PRIVATE10:
2157 		if (!read_data(&pkt.u.sig.info.sig.unknown.data, region,
2158 				stream)) {
2159 			return 0;
2160 		}
2161 		break;
2162 
2163 	default:
2164 		OPS_ERROR_1(&stream->errors, OPS_E_ALG_UNSUPPORTED_SIGNATURE_ALG,
2165 			    "Bad v4 signature key algorithm (%s)",
2166 			    __ops_show_pka(pkt.u.sig.info.key_alg));
2167 		return 0;
2168 	}
2169 	if (region->readc != region->length) {
2170 		OPS_ERROR_1(&stream->errors, OPS_E_R_UNCONSUMED_DATA,
2171 			    "Unconsumed data (%d)",
2172 			    region->length - region->readc);
2173 		return 0;
2174 	}
2175 	CALLBACK(OPS_PTAG_CT_SIGNATURE_FOOTER, &stream->cbinfo, &pkt);
2176 	return 1;
2177 }
2178 
2179 /**
2180  * \ingroup Core_ReadPackets
2181  * \brief Parse a signature subpacket.
2182  *
2183  * This function calls the appropriate function to handle v3 or v4 signatures.
2184  *
2185  * Once the signature packet has been parsed successfully, it is passed to the callback.
2186  *
2187  * \param *ptag		Pointer to the Packet Tag.
2188  * \param *reader	Our reader
2189  * \param *cb		The callback
2190  * \return		1 on success, 0 on error
2191  */
2192 static int
2193 parse_sig(__ops_region_t *region, __ops_stream_t *stream)
2194 {
2195 	__ops_packet_t	pkt;
2196 	uint8_t		c = 0x0;
2197 
2198 	if (region->readc != 0) {
2199 		/* We should not have read anything so far */
2200 		(void) fprintf(stderr, "parse_sig: bad length\n");
2201 		return 0;
2202 	}
2203 
2204 	(void) memset(&pkt, 0x0, sizeof(pkt));
2205 	if (!limread(&c, 1, region, stream)) {
2206 		return 0;
2207 	}
2208 	if (c == 2 || c == 3) {
2209 		return parse_v3_sig(region, stream);
2210 	}
2211 	if (c == 4) {
2212 		return parse_v4_sig(region, stream);
2213 	}
2214 	OPS_ERROR_1(&stream->errors, OPS_E_PROTO_BAD_SIGNATURE_VRSN,
2215 		    "Bad signature version (%d)", c);
2216 	return 0;
2217 }
2218 
2219 /**
2220  \ingroup Core_ReadPackets
2221  \brief Parse Compressed packet
2222 */
2223 static int
2224 parse_compressed(__ops_region_t *region, __ops_stream_t *stream)
2225 {
2226 	__ops_packet_t	pkt;
2227 	uint8_t		c = 0x0;
2228 
2229 	if (!limread(&c, 1, region, stream)) {
2230 		return 0;
2231 	}
2232 
2233 	pkt.u.compressed.type = (__ops_compression_type_t)c;
2234 
2235 	CALLBACK(OPS_PTAG_CT_COMPRESSED, &stream->cbinfo, &pkt);
2236 
2237 	/*
2238 	 * The content of a compressed data packet is more OpenPGP packets
2239 	 * once decompressed, so recursively handle them
2240 	 */
2241 
2242 	return __ops_decompress(region, stream, pkt.u.compressed.type);
2243 }
2244 
2245 /* XXX: this could be improved by sharing all hashes that are the */
2246 /* same, then duping them just before checking the signature. */
2247 static void
2248 parse_hash_init(__ops_stream_t *stream, __ops_hash_alg_t type,
2249 		    const uint8_t *keyid)
2250 {
2251 	__ops_hashtype_t *hash;
2252 
2253 	hash = realloc(stream->hashes,
2254 			      (stream->hashc + 1) * sizeof(*stream->hashes));
2255 	if (hash == NULL) {
2256 		(void) fprintf(stderr, "parse_hash_init: bad alloc 0\n");
2257 		/* just continue and die here */
2258 		/* XXX - agc - no way to return failure */
2259 	} else {
2260 		stream->hashes = hash;
2261 	}
2262 	hash = &stream->hashes[stream->hashc++];
2263 
2264 	__ops_hash_any(&hash->hash, type);
2265 	if (!hash->hash.init(&hash->hash)) {
2266 		(void) fprintf(stderr, "parse_hash_init: bad alloc\n");
2267 		/* just continue and die here */
2268 		/* XXX - agc - no way to return failure */
2269 	}
2270 	(void) memcpy(hash->keyid, keyid, sizeof(hash->keyid));
2271 }
2272 
2273 /**
2274    \ingroup Core_ReadPackets
2275    \brief Parse a One Pass Signature packet
2276 */
2277 static int
2278 parse_one_pass(__ops_region_t * region, __ops_stream_t * stream)
2279 {
2280 	__ops_packet_t	pkt;
2281 	uint8_t		c = 0x0;
2282 
2283 	if (!limread(&pkt.u.one_pass_sig.version, 1, region, stream)) {
2284 		return 0;
2285 	}
2286 	if (pkt.u.one_pass_sig.version != 3) {
2287 		OPS_ERROR_1(&stream->errors, OPS_E_PROTO_BAD_ONE_PASS_SIG_VRSN,
2288 			    "Bad one-pass signature version (%d)",
2289 			    pkt.u.one_pass_sig.version);
2290 		return 0;
2291 	}
2292 	if (!limread(&c, 1, region, stream)) {
2293 		return 0;
2294 	}
2295 	pkt.u.one_pass_sig.sig_type = (__ops_sig_type_t)c;
2296 
2297 	if (!limread(&c, 1, region, stream)) {
2298 		return 0;
2299 	}
2300 	pkt.u.one_pass_sig.hash_alg = (__ops_hash_alg_t)c;
2301 
2302 	if (!limread(&c, 1, region, stream)) {
2303 		return 0;
2304 	}
2305 	pkt.u.one_pass_sig.key_alg = (__ops_pubkey_alg_t)c;
2306 
2307 	if (!limread(pkt.u.one_pass_sig.keyid,
2308 			  sizeof(pkt.u.one_pass_sig.keyid), region, stream)) {
2309 		return 0;
2310 	}
2311 
2312 	if (!limread(&c, 1, region, stream)) {
2313 		return 0;
2314 	}
2315 	pkt.u.one_pass_sig.nested = !!c;
2316 	CALLBACK(OPS_PTAG_CT_1_PASS_SIG, &stream->cbinfo, &pkt);
2317 	/* XXX: we should, perhaps, let the app choose whether to hash or not */
2318 	parse_hash_init(stream, pkt.u.one_pass_sig.hash_alg,
2319 			    pkt.u.one_pass_sig.keyid);
2320 	return 1;
2321 }
2322 
2323 /**
2324  \ingroup Core_ReadPackets
2325  \brief Parse a Trust packet
2326 */
2327 static int
2328 parse_trust(__ops_region_t *region, __ops_stream_t *stream)
2329 {
2330 	__ops_packet_t pkt;
2331 
2332 	if (!read_data(&pkt.u.trust.data, region, stream)) {
2333 		return 0;
2334 	}
2335 	CALLBACK(OPS_PTAG_CT_TRUST, &stream->cbinfo, &pkt);
2336 	return 1;
2337 }
2338 
2339 static void
2340 parse_hash_data(__ops_stream_t *stream, const void *data,
2341 		    size_t length)
2342 {
2343 	size_t          n;
2344 
2345 	for (n = 0; n < stream->hashc; ++n) {
2346 		stream->hashes[n].hash.add(&stream->hashes[n].hash, data, length);
2347 	}
2348 }
2349 
2350 /**
2351    \ingroup Core_ReadPackets
2352    \brief Parse a Literal Data packet
2353 */
2354 static int
2355 parse_litdata(__ops_region_t *region, __ops_stream_t *stream)
2356 {
2357 	__ops_memory_t	*mem;
2358 	__ops_packet_t	 pkt;
2359 	uint8_t		 c = 0x0;
2360 
2361 	if (!limread(&c, 1, region, stream)) {
2362 		return 0;
2363 	}
2364 	pkt.u.litdata_header.format = (__ops_litdata_type_t)c;
2365 	if (!limread(&c, 1, region, stream)) {
2366 		return 0;
2367 	}
2368 	if (!limread((uint8_t *)pkt.u.litdata_header.filename,
2369 			(unsigned)c, region, stream)) {
2370 		return 0;
2371 	}
2372 	pkt.u.litdata_header.filename[c] = '\0';
2373 	if (!limited_read_time(&pkt.u.litdata_header.mtime, region, stream)) {
2374 		return 0;
2375 	}
2376 	CALLBACK(OPS_PTAG_CT_LITDATA_HEADER, &stream->cbinfo, &pkt);
2377 	mem = pkt.u.litdata_body.mem = __ops_memory_new();
2378 	__ops_memory_init(pkt.u.litdata_body.mem,
2379 			(unsigned)((region->length * 101) / 100) + 12);
2380 	pkt.u.litdata_body.data = mem->buf;
2381 
2382 	while (region->readc < region->length) {
2383 		unsigned        readc = region->length - region->readc;
2384 
2385 		if (!limread(mem->buf, readc, region, stream)) {
2386 			return 0;
2387 		}
2388 		pkt.u.litdata_body.length = readc;
2389 		parse_hash_data(stream, pkt.u.litdata_body.data, region->length);
2390 		CALLBACK(OPS_PTAG_CT_LITDATA_BODY, &stream->cbinfo, &pkt);
2391 	}
2392 
2393 	/* XXX - get rid of mem here? */
2394 
2395 	return 1;
2396 }
2397 
2398 /**
2399  * \ingroup Core_Create
2400  *
2401  * __ops_seckey_free() frees the memory associated with "key". Note that
2402  * the key itself is not freed.
2403  *
2404  * \param key
2405  */
2406 
2407 void
2408 __ops_seckey_free(__ops_seckey_t *key)
2409 {
2410 	switch (key->pubkey.alg) {
2411 	case OPS_PKA_RSA:
2412 	case OPS_PKA_RSA_ENCRYPT_ONLY:
2413 	case OPS_PKA_RSA_SIGN_ONLY:
2414 		free_BN(&key->key.rsa.d);
2415 		free_BN(&key->key.rsa.p);
2416 		free_BN(&key->key.rsa.q);
2417 		free_BN(&key->key.rsa.u);
2418 		break;
2419 
2420 	case OPS_PKA_DSA:
2421 		free_BN(&key->key.dsa.x);
2422 		break;
2423 
2424 	default:
2425 		(void) fprintf(stderr,
2426 			"__ops_seckey_free: Unknown algorithm: %d (%s)\n",
2427 			key->pubkey.alg,
2428 			__ops_show_pka(key->pubkey.alg));
2429 	}
2430 	free(key->checkhash);
2431 	__ops_pubkey_free(&key->pubkey);
2432 }
2433 
2434 static int
2435 consume_packet(__ops_region_t *region, __ops_stream_t *stream, unsigned warn)
2436 {
2437 	__ops_packet_t	pkt;
2438 	__ops_data_t	remainder;
2439 
2440 	if (region->indeterminate) {
2441 		ERRP(&stream->cbinfo, pkt,
2442 			"Can't consume indeterminate packets");
2443 	}
2444 
2445 	if (read_data(&remainder, region, stream)) {
2446 		/* now throw it away */
2447 		data_free(&remainder);
2448 		if (warn) {
2449 			OPS_ERROR(&stream->errors, OPS_E_P_PACKET_CONSUMED,
2450 				"Warning: packet consumer");
2451 		}
2452 		return 1;
2453 	}
2454 	OPS_ERROR(&stream->errors, OPS_E_P_PACKET_NOT_CONSUMED,
2455 			(warn) ? "Warning: Packet was not consumed" :
2456 				"Packet was not consumed");
2457 	return warn;
2458 }
2459 
2460 /**
2461  * \ingroup Core_ReadPackets
2462  * \brief Parse a secret key
2463  */
2464 static int
2465 parse_seckey(__ops_region_t *region, __ops_stream_t *stream)
2466 {
2467 	__ops_packet_t		pkt;
2468 	__ops_region_t		encregion;
2469 	__ops_region_t	       *saved_region = NULL;
2470 	__ops_crypt_t		decrypt;
2471 	__ops_hash_t		checkhash;
2472 	unsigned		blocksize;
2473 	unsigned		crypted;
2474 	uint8_t			c = 0x0;
2475 	int			ret = 1;
2476 
2477 	if (__ops_get_debug_level(__FILE__)) {
2478 		fprintf(stderr, "\n---------\nparse_seckey:\n");
2479 		fprintf(stderr,
2480 			"region length=%u, readc=%u, remainder=%u\n",
2481 			region->length, region->readc,
2482 			region->length - region->readc);
2483 	}
2484 	(void) memset(&pkt, 0x0, sizeof(pkt));
2485 	if (!parse_pubkey_data(&pkt.u.seckey.pubkey, region, stream)) {
2486 		return 0;
2487 	}
2488 	if (__ops_get_debug_level(__FILE__)) {
2489 		fprintf(stderr, "parse_seckey: public key parsed\n");
2490 		__ops_print_pubkey(&pkt.u.seckey.pubkey);
2491 	}
2492 	stream->reading_v3_secret = (pkt.u.seckey.pubkey.version != OPS_V4);
2493 
2494 	if (!limread(&c, 1, region, stream)) {
2495 		return 0;
2496 	}
2497 	pkt.u.seckey.s2k_usage = (__ops_s2k_usage_t)c;
2498 
2499 	if (pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED ||
2500 	    pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED) {
2501 		if (!limread(&c, 1, region, stream)) {
2502 			return 0;
2503 		}
2504 		pkt.u.seckey.alg = (__ops_symm_alg_t)c;
2505 		if (!limread(&c, 1, region, stream)) {
2506 			return 0;
2507 		}
2508 		pkt.u.seckey.s2k_specifier = (__ops_s2k_specifier_t)c;
2509 		switch (pkt.u.seckey.s2k_specifier) {
2510 		case OPS_S2KS_SIMPLE:
2511 		case OPS_S2KS_SALTED:
2512 		case OPS_S2KS_ITERATED_AND_SALTED:
2513 			break;
2514 		default:
2515 			(void) fprintf(stderr,
2516 				"parse_seckey: bad seckey\n");
2517 			return 0;
2518 		}
2519 		if (!limread(&c, 1, region, stream)) {
2520 			return 0;
2521 		}
2522 		pkt.u.seckey.hash_alg = (__ops_hash_alg_t)c;
2523 		if (pkt.u.seckey.s2k_specifier != OPS_S2KS_SIMPLE &&
2524 		    !limread(pkt.u.seckey.salt, 8, region, stream)) {
2525 			return 0;
2526 		}
2527 		if (pkt.u.seckey.s2k_specifier ==
2528 					OPS_S2KS_ITERATED_AND_SALTED) {
2529 			if (!limread(&c, 1, region, stream)) {
2530 				return 0;
2531 			}
2532 			pkt.u.seckey.octetc =
2533 				(16 + ((unsigned)c & 15)) <<
2534 						(((unsigned)c >> 4) + 6);
2535 		}
2536 	} else if (pkt.u.seckey.s2k_usage != OPS_S2KU_NONE) {
2537 		/* this is V3 style, looks just like a V4 simple hash */
2538 		pkt.u.seckey.alg = (__ops_symm_alg_t)c;
2539 		pkt.u.seckey.s2k_usage = OPS_S2KU_ENCRYPTED;
2540 		pkt.u.seckey.s2k_specifier = OPS_S2KS_SIMPLE;
2541 		pkt.u.seckey.hash_alg = OPS_HASH_MD5;
2542 	}
2543 	crypted = pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED ||
2544 		pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED;
2545 
2546 	if (crypted) {
2547 		__ops_packet_t	seckey;
2548 		__ops_hash_t	hashes[(OPS_MAX_KEY_SIZE + OPS_MIN_HASH_SIZE - 1) / OPS_MIN_HASH_SIZE];
2549 		uint8_t   	key[OPS_MAX_KEY_SIZE + OPS_MAX_HASH_SIZE];
2550 		size_t          passlen;
2551 		char           *passphrase;
2552 		int             hashsize;
2553 		int             keysize;
2554 		int             n;
2555 
2556 		blocksize = __ops_block_size(pkt.u.seckey.alg);
2557 		if (blocksize == 0 || blocksize > OPS_MAX_BLOCK_SIZE) {
2558 			(void) fprintf(stderr,
2559 				"parse_seckey: bad blocksize\n");
2560 			return 0;
2561 		}
2562 
2563 		if (!limread(pkt.u.seckey.iv, blocksize, region, stream)) {
2564 			return 0;
2565 		}
2566 		(void) memset(&seckey, 0x0, sizeof(seckey));
2567 		passphrase = NULL;
2568 		seckey.u.skey_passphrase.passphrase = &passphrase;
2569 		seckey.u.skey_passphrase.seckey = &pkt.u.seckey;
2570 		CALLBACK(OPS_GET_PASSPHRASE, &stream->cbinfo, &seckey);
2571 		if (!passphrase) {
2572 			if (__ops_get_debug_level(__FILE__)) {
2573 				/* \todo make into proper error */
2574 				(void) fprintf(stderr,
2575 				"parse_seckey: can't get passphrase\n");
2576 			}
2577 			if (!consume_packet(region, stream, 0)) {
2578 				return 0;
2579 			}
2580 
2581 			CALLBACK(OPS_PTAG_CT_ENCRYPTED_SECRET_KEY,
2582 				&stream->cbinfo, &pkt);
2583 
2584 			return 1;
2585 		}
2586 		keysize = __ops_key_size(pkt.u.seckey.alg);
2587 		if (keysize == 0 || keysize > OPS_MAX_KEY_SIZE) {
2588 			(void) fprintf(stderr,
2589 				"parse_seckey: bad keysize\n");
2590 			return 0;
2591 		}
2592 
2593 		hashsize = __ops_hash_size(pkt.u.seckey.hash_alg);
2594 		if (hashsize == 0 || hashsize > OPS_MAX_HASH_SIZE) {
2595 			(void) fprintf(stderr,
2596 				"parse_seckey: bad hashsize\n");
2597 			return 0;
2598 		}
2599 
2600 		for (n = 0; n * hashsize < keysize; ++n) {
2601 			int             i;
2602 
2603 			__ops_hash_any(&hashes[n],
2604 				pkt.u.seckey.hash_alg);
2605 			if (!hashes[n].init(&hashes[n])) {
2606 				(void) fprintf(stderr,
2607 					"parse_seckey: bad alloc\n");
2608 				return 0;
2609 			}
2610 			/* preload hashes with zeroes... */
2611 			for (i = 0; i < n; ++i) {
2612 				hashes[n].add(&hashes[n],
2613 					(const uint8_t *) "", 1);
2614 			}
2615 		}
2616 		passlen = strlen(passphrase);
2617 		for (n = 0; n * hashsize < keysize; ++n) {
2618 			unsigned        i;
2619 
2620 			switch (pkt.u.seckey.s2k_specifier) {
2621 			case OPS_S2KS_SALTED:
2622 				hashes[n].add(&hashes[n],
2623 					pkt.u.seckey.salt,
2624 					OPS_SALT_SIZE);
2625 				/* FALLTHROUGH */
2626 			case OPS_S2KS_SIMPLE:
2627 				hashes[n].add(&hashes[n],
2628 					(uint8_t *) passphrase, passlen);
2629 				break;
2630 
2631 			case OPS_S2KS_ITERATED_AND_SALTED:
2632 				for (i = 0; i < pkt.u.seckey.octetc;
2633 						i += passlen + OPS_SALT_SIZE) {
2634 					unsigned	j;
2635 
2636 					j = passlen + OPS_SALT_SIZE;
2637 					if (i + j > pkt.u.seckey.octetc && i != 0) {
2638 						j = pkt.u.seckey.octetc - i;
2639 					}
2640 					hashes[n].add(&hashes[n],
2641 						pkt.u.seckey.salt,
2642 						(unsigned)(j > OPS_SALT_SIZE) ?
2643 							OPS_SALT_SIZE : j);
2644 					if (j > OPS_SALT_SIZE) {
2645 						hashes[n].add(&hashes[n],
2646 						(uint8_t *) passphrase,
2647 						j - OPS_SALT_SIZE);
2648 					}
2649 				}
2650 				break;
2651 			default:
2652 				break;
2653 			}
2654 		}
2655 
2656 		for (n = 0; n * hashsize < keysize; ++n) {
2657 			int	r;
2658 
2659 			r = hashes[n].finish(&hashes[n], key + n * hashsize);
2660 			if (r != hashsize) {
2661 				(void) fprintf(stderr,
2662 					"parse_seckey: bad r\n");
2663 				return 0;
2664 			}
2665 		}
2666 
2667 		__ops_forget(passphrase, passlen);
2668 
2669 		__ops_crypt_any(&decrypt, pkt.u.seckey.alg);
2670 		if (__ops_get_debug_level(__FILE__)) {
2671 			unsigned	i;
2672 
2673 			fprintf(stderr, "\nREADING:\niv=");
2674 			for (i = 0;
2675 			     i < __ops_block_size(pkt.u.seckey.alg);
2676 			     i++) {
2677 				fprintf(stderr, "%02x ", pkt.u.seckey.iv[i]);
2678 			}
2679 			fprintf(stderr, "\nkey=");
2680 			for (i = 0; i < CAST_KEY_LENGTH; i++) {
2681 				fprintf(stderr, "%02x ", key[i]);
2682 			}
2683 			fprintf(stderr, "\n");
2684 		}
2685 		decrypt.set_iv(&decrypt, pkt.u.seckey.iv);
2686 		decrypt.set_crypt_key(&decrypt, key);
2687 
2688 		/* now read encrypted data */
2689 
2690 		__ops_reader_push_decrypt(stream, &decrypt, region);
2691 
2692 		/*
2693 		 * Since all known encryption for PGP doesn't compress, we
2694 		 * can limit to the same length as the current region (for
2695 		 * now).
2696 		 */
2697 		__ops_init_subregion(&encregion, NULL);
2698 		encregion.length = region->length - region->readc;
2699 		if (pkt.u.seckey.pubkey.version != OPS_V4) {
2700 			encregion.length -= 2;
2701 		}
2702 		saved_region = region;
2703 		region = &encregion;
2704 	}
2705 	if (pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED) {
2706 		pkt.u.seckey.checkhash = calloc(1, OPS_CHECKHASH_SIZE);
2707 		if (pkt.u.seckey.checkhash == NULL) {
2708 			(void) fprintf(stderr, "parse_seckey: bad alloc\n");
2709 			return 0;
2710 		}
2711 		__ops_hash_sha1(&checkhash);
2712 		__ops_reader_push_hash(stream, &checkhash);
2713 	} else {
2714 		__ops_reader_push_sum16(stream);
2715 	}
2716 
2717 	switch (pkt.u.seckey.pubkey.alg) {
2718 	case OPS_PKA_RSA:
2719 	case OPS_PKA_RSA_ENCRYPT_ONLY:
2720 	case OPS_PKA_RSA_SIGN_ONLY:
2721 		if (!limread_mpi(&pkt.u.seckey.key.rsa.d, region, stream) ||
2722 		    !limread_mpi(&pkt.u.seckey.key.rsa.p, region, stream) ||
2723 		    !limread_mpi(&pkt.u.seckey.key.rsa.q, region, stream) ||
2724 		    !limread_mpi(&pkt.u.seckey.key.rsa.u, region, stream)) {
2725 			ret = 0;
2726 		}
2727 		break;
2728 
2729 	case OPS_PKA_DSA:
2730 		if (!limread_mpi(&pkt.u.seckey.key.dsa.x, region, stream)) {
2731 			ret = 0;
2732 		}
2733 		break;
2734 
2735 	default:
2736 		OPS_ERROR_2(&stream->errors,
2737 			OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2738 			"Unsupported Public Key algorithm %d (%s)",
2739 			pkt.u.seckey.pubkey.alg,
2740 			__ops_show_pka(pkt.u.seckey.pubkey.alg));
2741 		ret = 0;
2742 	}
2743 
2744 	if (__ops_get_debug_level(__FILE__)) {
2745 		(void) fprintf(stderr, "4 MPIs read\n");
2746 	}
2747 	stream->reading_v3_secret = 0;
2748 
2749 	if (pkt.u.seckey.s2k_usage == OPS_S2KU_ENCRYPTED_AND_HASHED) {
2750 		uint8_t   hash[OPS_CHECKHASH_SIZE];
2751 
2752 		__ops_reader_pop_hash(stream);
2753 		checkhash.finish(&checkhash, hash);
2754 
2755 		if (crypted &&
2756 		    pkt.u.seckey.pubkey.version != OPS_V4) {
2757 			__ops_reader_pop_decrypt(stream);
2758 			region = saved_region;
2759 		}
2760 		if (ret) {
2761 			if (!limread(pkt.u.seckey.checkhash,
2762 				OPS_CHECKHASH_SIZE, region, stream)) {
2763 				return 0;
2764 			}
2765 
2766 			if (memcmp(hash, pkt.u.seckey.checkhash,
2767 					OPS_CHECKHASH_SIZE) != 0) {
2768 				ERRP(&stream->cbinfo, pkt,
2769 					"Hash mismatch in secret key");
2770 			}
2771 		}
2772 	} else {
2773 		uint16_t  sum;
2774 
2775 		sum = __ops_reader_pop_sum16(stream);
2776 		if (crypted &&
2777 		    pkt.u.seckey.pubkey.version != OPS_V4) {
2778 			__ops_reader_pop_decrypt(stream);
2779 			region = saved_region;
2780 		}
2781 		if (ret) {
2782 			if (!limread_scalar(&pkt.u.seckey.checksum, 2,
2783 					region, stream))
2784 				return 0;
2785 
2786 			if (sum != pkt.u.seckey.checksum) {
2787 				ERRP(&stream->cbinfo, pkt,
2788 					"Checksum mismatch in secret key");
2789 			}
2790 		}
2791 	}
2792 
2793 	if (crypted && pkt.u.seckey.pubkey.version == OPS_V4) {
2794 		__ops_reader_pop_decrypt(stream);
2795 	}
2796 	if (region == NULL) {
2797 		(void) fprintf(stderr, "parse_seckey: NULL region\n");
2798 		return 0;
2799 	}
2800 	if (ret && region->readc != region->length) {
2801 		(void) fprintf(stderr, "parse_seckey: bad length\n");
2802 		return 0;
2803 	}
2804 	if (!ret) {
2805 		return 0;
2806 	}
2807 	CALLBACK(OPS_PTAG_CT_SECRET_KEY, &stream->cbinfo, &pkt);
2808 	if (__ops_get_debug_level(__FILE__)) {
2809 		(void) fprintf(stderr, "--- end of parse_seckey\n\n");
2810 	}
2811 	return 1;
2812 }
2813 
2814 /**
2815    \ingroup Core_ReadPackets
2816    \brief Parse a Public Key Session Key packet
2817 */
2818 static int
2819 parse_pk_sesskey(__ops_region_t *region,
2820 		     __ops_stream_t *stream)
2821 {
2822 	const __ops_seckey_t	*secret;
2823 	__ops_packet_t		 sesskey;
2824 	__ops_packet_t		 pkt;
2825 	uint8_t			*iv;
2826 	uint8_t		   	 c = 0x0;
2827 	uint8_t			 cs[2];
2828 	unsigned		 k;
2829 	BIGNUM			*enc_m;
2830 	int			 n;
2831 
2832 	/* Can't rely on it being CAST5 */
2833 	/* \todo FIXME RW */
2834 	/* const size_t sz_unencoded_m_buf=CAST_KEY_LENGTH+1+2; */
2835 	uint8_t		 unencoded_m_buf[1024];
2836 
2837 	if (!limread(&c, 1, region, stream)) {
2838 		return 0;
2839 	}
2840 	pkt.u.pk_sesskey.version = (__ops_pk_sesskey_version_t)c;
2841 	if (pkt.u.pk_sesskey.version != OPS_PKSK_V3) {
2842 		OPS_ERROR_1(&stream->errors, OPS_E_PROTO_BAD_PKSK_VRSN,
2843 			"Bad public-key encrypted session key version (%d)",
2844 			    pkt.u.pk_sesskey.version);
2845 		return 0;
2846 	}
2847 	if (!limread(pkt.u.pk_sesskey.key_id,
2848 			  sizeof(pkt.u.pk_sesskey.key_id), region, stream)) {
2849 		return 0;
2850 	}
2851 	if (__ops_get_debug_level(__FILE__)) {
2852 		int             i;
2853 		int             x = sizeof(pkt.u.pk_sesskey.key_id);
2854 
2855 		printf("session key: public key id: x=%d\n", x);
2856 		for (i = 0; i < x; i++) {
2857 			printf("%2x ", pkt.u.pk_sesskey.key_id[i]);
2858 		}
2859 		printf("\n");
2860 	}
2861 	if (!limread(&c, 1, region, stream)) {
2862 		return 0;
2863 	}
2864 	pkt.u.pk_sesskey.alg = (__ops_pubkey_alg_t)c;
2865 	switch (pkt.u.pk_sesskey.alg) {
2866 	case OPS_PKA_RSA:
2867 		if (!limread_mpi(&pkt.u.pk_sesskey.params.rsa.encrypted_m,
2868 				      region, stream)) {
2869 			return 0;
2870 		}
2871 		enc_m = pkt.u.pk_sesskey.params.rsa.encrypted_m;
2872 		break;
2873 
2874 	case OPS_PKA_ELGAMAL:
2875 		if (!limread_mpi(&pkt.u.pk_sesskey.params.elgamal.g_to_k,
2876 				      region, stream) ||
2877 		    !limread_mpi(
2878 			&pkt.u.pk_sesskey.params.elgamal.encrypted_m,
2879 					 region, stream)) {
2880 			return 0;
2881 		}
2882 		enc_m = pkt.u.pk_sesskey.params.elgamal.encrypted_m;
2883 		break;
2884 
2885 	default:
2886 		OPS_ERROR_1(&stream->errors,
2887 			OPS_E_ALG_UNSUPPORTED_PUBLIC_KEY_ALG,
2888 			"Unknown public key algorithm in session key (%s)",
2889 			__ops_show_pka(pkt.u.pk_sesskey.alg));
2890 		return 0;
2891 	}
2892 
2893 	(void) memset(&sesskey, 0x0, sizeof(sesskey));
2894 	secret = NULL;
2895 	sesskey.u.get_seckey.seckey = &secret;
2896 	sesskey.u.get_seckey.pk_sesskey = &pkt.u.pk_sesskey;
2897 
2898 	CALLBACK(OPS_GET_SECKEY, &stream->cbinfo, &sesskey);
2899 
2900 	if (!secret) {
2901 		CALLBACK(OPS_PTAG_CT_ENCRYPTED_PK_SESSION_KEY, &stream->cbinfo,
2902 			&pkt);
2903 		return 1;
2904 	}
2905 	n = __ops_decrypt_decode_mpi(unencoded_m_buf, sizeof(unencoded_m_buf),
2906 			enc_m, secret);
2907 	if (n < 1) {
2908 		ERRP(&stream->cbinfo, pkt, "decrypted message too short");
2909 		return 0;
2910 	}
2911 
2912 	/* PKA */
2913 	pkt.u.pk_sesskey.symm_alg = (__ops_symm_alg_t)unencoded_m_buf[0];
2914 
2915 	if (!__ops_is_sa_supported(pkt.u.pk_sesskey.symm_alg)) {
2916 		/* ERR1P */
2917 		OPS_ERROR_1(&stream->errors, OPS_E_ALG_UNSUPPORTED_SYMMETRIC_ALG,
2918 			    "Symmetric algorithm %s not supported",
2919 			    __ops_show_symm_alg(
2920 				pkt.u.pk_sesskey.symm_alg));
2921 		return 0;
2922 	}
2923 	k = __ops_key_size(pkt.u.pk_sesskey.symm_alg);
2924 
2925 	if ((unsigned) n != k + 3) {
2926 		OPS_ERROR_2(&stream->errors, OPS_E_PROTO_DECRYPTED_MSG_WRONG_LEN,
2927 		      "decrypted message wrong length (got %d expected %d)",
2928 			    n, k + 3);
2929 		return 0;
2930 	}
2931 	if (k > sizeof(pkt.u.pk_sesskey.key)) {
2932 		(void) fprintf(stderr, "parse_pk_sesskey: bad keylength\n");
2933 		return 0;
2934 	}
2935 
2936 	(void) memcpy(pkt.u.pk_sesskey.key, unencoded_m_buf + 1, k);
2937 
2938 	if (__ops_get_debug_level(__FILE__)) {
2939 		unsigned    j;
2940 		printf("session key recovered (len=%u):\n", k);
2941 		for (j = 0; j < k; j++)
2942 			printf("%2x ", pkt.u.pk_sesskey.key[j]);
2943 		printf("\n");
2944 	}
2945 	pkt.u.pk_sesskey.checksum = unencoded_m_buf[k + 1] +
2946 			(unencoded_m_buf[k + 2] << 8);
2947 	if (__ops_get_debug_level(__FILE__)) {
2948 		printf("session key checksum: %2x %2x\n",
2949 			unencoded_m_buf[k + 1], unencoded_m_buf[k + 2]);
2950 	}
2951 
2952 	/* Check checksum */
2953 	__ops_calc_sesskey_checksum(&pkt.u.pk_sesskey, &cs[0]);
2954 	if (unencoded_m_buf[k + 1] != cs[0] ||
2955 	    unencoded_m_buf[k + 2] != cs[1]) {
2956 		OPS_ERROR_4(&stream->errors, OPS_E_PROTO_BAD_SK_CHECKSUM,
2957 		"Session key checksum wrong: expected %2x %2x, got %2x %2x",
2958 		cs[0], cs[1], unencoded_m_buf[k + 1],
2959 		unencoded_m_buf[k + 2]);
2960 		return 0;
2961 	}
2962 	/* all is well */
2963 	CALLBACK(OPS_PTAG_CT_PK_SESSION_KEY, &stream->cbinfo, &pkt);
2964 
2965 	__ops_crypt_any(&stream->decrypt, pkt.u.pk_sesskey.symm_alg);
2966 	iv = calloc(1, stream->decrypt.blocksize);
2967 	if (iv == NULL) {
2968 		(void) fprintf(stderr, "parse_pk_sesskey: bad alloc\n");
2969 		return 0;
2970 	}
2971 	stream->decrypt.set_iv(&stream->decrypt, iv);
2972 	stream->decrypt.set_crypt_key(&stream->decrypt, pkt.u.pk_sesskey.key);
2973 	__ops_encrypt_init(&stream->decrypt);
2974 	free(iv);
2975 	return 1;
2976 }
2977 
2978 static int
2979 __ops_decrypt_se_data(__ops_content_tag_t tag, __ops_region_t *region,
2980 		    __ops_stream_t *stream)
2981 {
2982 	__ops_crypt_t	*decrypt;
2983 	const int	 printerrors = 1;
2984 	int		 r = 1;
2985 
2986 	decrypt = __ops_get_decrypt(stream);
2987 	if (decrypt) {
2988 		uint8_t   buf[OPS_MAX_BLOCK_SIZE + 2] = "";
2989 		size_t          b = decrypt->blocksize;
2990 		/* __ops_packet_t pkt; */
2991 		__ops_region_t    encregion;
2992 
2993 
2994 		__ops_reader_push_decrypt(stream, decrypt, region);
2995 
2996 		__ops_init_subregion(&encregion, NULL);
2997 		encregion.length = b + 2;
2998 
2999 		if (!exact_limread(buf, b + 2, &encregion, stream)) {
3000 			return 0;
3001 		}
3002 		if (buf[b - 2] != buf[b] || buf[b - 1] != buf[b + 1]) {
3003 			__ops_reader_pop_decrypt(stream);
3004 			OPS_ERROR_4(&stream->errors,
3005 				OPS_E_PROTO_BAD_SYMMETRIC_DECRYPT,
3006 				"Bad symmetric decrypt (%02x%02x vs %02x%02x)",
3007 				buf[b - 2], buf[b - 1], buf[b], buf[b + 1]);
3008 			return 0;
3009 		}
3010 		if (tag == OPS_PTAG_CT_SE_DATA_BODY) {
3011 			decrypt->decrypt_resync(decrypt);
3012 			decrypt->block_encrypt(decrypt, decrypt->civ,
3013 					decrypt->civ);
3014 		}
3015 		r = __ops_parse(stream, !printerrors);
3016 
3017 		__ops_reader_pop_decrypt(stream);
3018 	} else {
3019 		__ops_packet_t pkt;
3020 
3021 		while (region->readc < region->length) {
3022 			unsigned        len;
3023 
3024 			len = region->length - region->readc;
3025 			if (len > sizeof(pkt.u.se_data_body.data))
3026 				len = sizeof(pkt.u.se_data_body.data);
3027 
3028 			if (!limread(pkt.u.se_data_body.data, len,
3029 					region, stream)) {
3030 				return 0;
3031 			}
3032 			pkt.u.se_data_body.length = len;
3033 			CALLBACK(tag, &stream->cbinfo, &pkt);
3034 		}
3035 	}
3036 
3037 	return r;
3038 }
3039 
3040 static int
3041 __ops_decrypt_se_ip_data(__ops_content_tag_t tag, __ops_region_t *region,
3042 		       __ops_stream_t *stream)
3043 {
3044 	__ops_crypt_t	*decrypt;
3045 	const int	 printerrors = 1;
3046 	int		 r = 1;
3047 
3048 	decrypt = __ops_get_decrypt(stream);
3049 	if (decrypt) {
3050 		__ops_reader_push_decrypt(stream, decrypt, region);
3051 		__ops_reader_push_se_ip_data(stream, decrypt, region);
3052 
3053 		r = __ops_parse(stream, !printerrors);
3054 
3055 		__ops_reader_pop_se_ip_data(stream);
3056 		__ops_reader_pop_decrypt(stream);
3057 	} else {
3058 		__ops_packet_t pkt;
3059 
3060 		while (region->readc < region->length) {
3061 			unsigned        len;
3062 
3063 			len = region->length - region->readc;
3064 			if (len > sizeof(pkt.u.se_data_body.data)) {
3065 				len = sizeof(pkt.u.se_data_body.data);
3066 			}
3067 
3068 			if (!limread(pkt.u.se_data_body.data,
3069 					len, region, stream)) {
3070 				return 0;
3071 			}
3072 
3073 			pkt.u.se_data_body.length = len;
3074 
3075 			CALLBACK(tag, &stream->cbinfo, &pkt);
3076 		}
3077 	}
3078 
3079 	return r;
3080 }
3081 
3082 /**
3083    \ingroup Core_ReadPackets
3084    \brief Read a Symmetrically Encrypted packet
3085 */
3086 static int
3087 parse_se_data(__ops_region_t *region, __ops_stream_t *stream)
3088 {
3089 	__ops_packet_t pkt;
3090 
3091 	/* there's no info to go with this, so just announce it */
3092 	CALLBACK(OPS_PTAG_CT_SE_DATA_HEADER, &stream->cbinfo, &pkt);
3093 
3094 	/*
3095 	 * The content of an encrypted data packet is more OpenPGP packets
3096 	 * once decrypted, so recursively handle them
3097 	 */
3098 	return __ops_decrypt_se_data(OPS_PTAG_CT_SE_DATA_BODY, region, stream);
3099 }
3100 
3101 /**
3102    \ingroup Core_ReadPackets
3103    \brief Read a Symmetrically Encrypted Integrity Protected packet
3104 */
3105 static int
3106 parse_se_ip_data(__ops_region_t *region, __ops_stream_t *stream)
3107 {
3108 	__ops_packet_t	pkt;
3109 	uint8_t		c = 0x0;
3110 
3111 	if (!limread(&c, 1, region, stream)) {
3112 		return 0;
3113 	}
3114 	pkt.u.se_ip_data_header.version = (__ops_se_ip_version_t)c;
3115 
3116 	if (pkt.u.se_ip_data_header.version != OPS_SE_IP_V1) {
3117 		(void) fprintf(stderr, "parse_se_ip_data: bad version\n");
3118 		return 0;
3119 	}
3120 
3121 	/*
3122 	 * The content of an encrypted data packet is more OpenPGP packets
3123 	 * once decrypted, so recursively handle them
3124 	 */
3125 	return __ops_decrypt_se_ip_data(OPS_PTAG_CT_SE_IP_DATA_BODY, region,
3126 			stream);
3127 }
3128 
3129 /**
3130    \ingroup Core_ReadPackets
3131    \brief Read a MDC packet
3132 */
3133 static int
3134 parse_mdc(__ops_region_t *region, __ops_stream_t *stream)
3135 {
3136 	__ops_packet_t pkt;
3137 
3138 	pkt.u.mdc.length = OPS_SHA1_HASH_SIZE;
3139 	if ((pkt.u.mdc.data = calloc(1, OPS_SHA1_HASH_SIZE)) == NULL) {
3140 		(void) fprintf(stderr, "parse_mdc: bad alloc\n");
3141 		return 0;
3142 	}
3143 	if (!limread(pkt.u.mdc.data, OPS_SHA1_HASH_SIZE, region, stream)) {
3144 		return 0;
3145 	}
3146 	CALLBACK(OPS_PTAG_CT_MDC, &stream->cbinfo, &pkt);
3147 	free(pkt.u.mdc.data);
3148 	return 1;
3149 }
3150 
3151 /**
3152  * \ingroup Core_ReadPackets
3153  * \brief Parse one packet.
3154  *
3155  * This function parses the packet tag.  It computes the value of the
3156  * content tag and then calls the appropriate function to handle the
3157  * content.
3158  *
3159  * \param *stream	How to parse
3160  * \param *pktlen	On return, will contain number of bytes in packet
3161  * \return 1 on success, 0 on error, -1 on EOF */
3162 static int
3163 __ops_parse_packet(__ops_stream_t *stream, uint32_t *pktlen)
3164 {
3165 	__ops_packet_t	pkt;
3166 	__ops_region_t	region;
3167 	uint8_t		ptag;
3168 	unsigned	indeterminate = 0;
3169 	int		ret;
3170 
3171 	pkt.u.ptag.position = stream->readinfo.position;
3172 
3173 	ret = base_read(&ptag, 1, stream);
3174 
3175 	if (__ops_get_debug_level(__FILE__)) {
3176 		(void) fprintf(stderr,
3177 			"__ops_parse_packet: base_read returned %d\n",
3178 			ret);
3179 	}
3180 
3181 	/* errors in the base read are effectively EOF. */
3182 	if (ret <= 0) {
3183 		return -1;
3184 	}
3185 
3186 	*pktlen = 0;
3187 
3188 	if (!(ptag & OPS_PTAG_ALWAYS_SET)) {
3189 		pkt.u.error.error = "Format error (ptag bit not set)";
3190 		CALLBACK(OPS_PARSER_ERROR, &stream->cbinfo, &pkt);
3191 		return 0;
3192 	}
3193 	pkt.u.ptag.new_format = !!(ptag & OPS_PTAG_NEW_FORMAT);
3194 	if (pkt.u.ptag.new_format) {
3195 		pkt.u.ptag.type = (ptag & OPS_PTAG_NF_CONTENT_TAG_MASK);
3196 		pkt.u.ptag.length_type = 0;
3197 		if (!read_new_length(&pkt.u.ptag.length, stream)) {
3198 			return 0;
3199 		}
3200 	} else {
3201 		unsigned   rb;
3202 
3203 		rb = 0;
3204 		pkt.u.ptag.type = ((unsigned)ptag &
3205 				OPS_PTAG_OF_CONTENT_TAG_MASK)
3206 			>> OPS_PTAG_OF_CONTENT_TAG_SHIFT;
3207 		pkt.u.ptag.length_type = ptag & OPS_PTAG_OF_LENGTH_TYPE_MASK;
3208 		switch (pkt.u.ptag.length_type) {
3209 		case OPS_PTAG_OLD_LEN_1:
3210 			rb = _read_scalar(&pkt.u.ptag.length, 1, stream);
3211 			break;
3212 
3213 		case OPS_PTAG_OLD_LEN_2:
3214 			rb = _read_scalar(&pkt.u.ptag.length, 2, stream);
3215 			break;
3216 
3217 		case OPS_PTAG_OLD_LEN_4:
3218 			rb = _read_scalar(&pkt.u.ptag.length, 4, stream);
3219 			break;
3220 
3221 		case OPS_PTAG_OLD_LEN_INDETERMINATE:
3222 			pkt.u.ptag.length = 0;
3223 			indeterminate = 1;
3224 			rb = 1;
3225 			break;
3226 		}
3227 		if (!rb) {
3228 			return 0;
3229 		}
3230 	}
3231 
3232 	CALLBACK(OPS_PARSER_PTAG, &stream->cbinfo, &pkt);
3233 
3234 	__ops_init_subregion(&region, NULL);
3235 	region.length = pkt.u.ptag.length;
3236 	region.indeterminate = indeterminate;
3237 	if (__ops_get_debug_level(__FILE__)) {
3238 		(void) fprintf(stderr, "__ops_parse_packet: type %u\n",
3239 			       pkt.u.ptag.type);
3240 	}
3241 	switch (pkt.u.ptag.type) {
3242 	case OPS_PTAG_CT_SIGNATURE:
3243 		ret = parse_sig(&region, stream);
3244 		break;
3245 
3246 	case OPS_PTAG_CT_PUBLIC_KEY:
3247 	case OPS_PTAG_CT_PUBLIC_SUBKEY:
3248 		ret = parse_pubkey(pkt.u.ptag.type, &region, stream);
3249 		break;
3250 
3251 	case OPS_PTAG_CT_TRUST:
3252 		ret = parse_trust(&region, stream);
3253 		break;
3254 
3255 	case OPS_PTAG_CT_USER_ID:
3256 		ret = parse_userid(&region, stream);
3257 		break;
3258 
3259 	case OPS_PTAG_CT_COMPRESSED:
3260 		ret = parse_compressed(&region, stream);
3261 		break;
3262 
3263 	case OPS_PTAG_CT_1_PASS_SIG:
3264 		ret = parse_one_pass(&region, stream);
3265 		break;
3266 
3267 	case OPS_PTAG_CT_LITDATA:
3268 		ret = parse_litdata(&region, stream);
3269 		break;
3270 
3271 	case OPS_PTAG_CT_USER_ATTR:
3272 		ret = parse_userattr(&region, stream);
3273 		break;
3274 
3275 	case OPS_PTAG_CT_SECRET_KEY:
3276 		ret = parse_seckey(&region, stream);
3277 		break;
3278 
3279 	case OPS_PTAG_CT_SECRET_SUBKEY:
3280 		ret = parse_seckey(&region, stream);
3281 		break;
3282 
3283 	case OPS_PTAG_CT_PK_SESSION_KEY:
3284 		ret = parse_pk_sesskey(&region, stream);
3285 		break;
3286 
3287 	case OPS_PTAG_CT_SE_DATA:
3288 		ret = parse_se_data(&region, stream);
3289 		break;
3290 
3291 	case OPS_PTAG_CT_SE_IP_DATA:
3292 		ret = parse_se_ip_data(&region, stream);
3293 		break;
3294 
3295 	case OPS_PTAG_CT_MDC:
3296 		ret = parse_mdc(&region, stream);
3297 		break;
3298 
3299 	default:
3300 		OPS_ERROR_1(&stream->errors, OPS_E_P_UNKNOWN_TAG,
3301 			    "Unknown content tag 0x%x",
3302 			    pkt.u.ptag.type);
3303 		ret = 0;
3304 	}
3305 
3306 	/* Ensure that the entire packet has been consumed */
3307 
3308 	if (region.length != region.readc && !region.indeterminate) {
3309 		if (!consume_packet(&region, stream, 0)) {
3310 			ret = -1;
3311 		}
3312 	}
3313 
3314 	/* also consume it if there's been an error? */
3315 	/* \todo decide what to do about an error on an */
3316 	/* indeterminate packet */
3317 	if (ret == 0) {
3318 		if (!consume_packet(&region, stream, 0)) {
3319 			ret = -1;
3320 		}
3321 	}
3322 	/* set pktlen */
3323 
3324 	*pktlen = stream->readinfo.alength;
3325 
3326 	/* do callback on entire packet, if desired and there was no error */
3327 
3328 	if (ret > 0 && stream->readinfo.accumulate) {
3329 		pkt.u.packet.length = stream->readinfo.alength;
3330 		pkt.u.packet.raw = stream->readinfo.accumulated;
3331 		stream->readinfo.accumulated = NULL;
3332 		stream->readinfo.asize = 0;
3333 		CALLBACK(OPS_PARSER_PACKET_END, &stream->cbinfo, &pkt);
3334 	}
3335 	stream->readinfo.alength = 0;
3336 
3337 	return (ret < 0) ? -1 : (ret) ? 1 : 0;
3338 }
3339 
3340 /**
3341  * \ingroup Core_ReadPackets
3342  *
3343  * \brief Parse packets from an input stream until EOF or error.
3344  *
3345  * \details Setup the necessary parsing configuration in "stream"
3346  * before calling __ops_parse().
3347  *
3348  * That information includes :
3349  *
3350  * - a "reader" function to be used to get the data to be parsed
3351  *
3352  * - a "callback" function to be called when this library has identified
3353  * a parseable object within the data
3354  *
3355  * - whether the calling function wants the signature subpackets
3356  * returned raw, parsed or not at all.
3357  *
3358  * After returning, stream->errors holds any errors encountered while parsing.
3359  *
3360  * \param stream	Parsing configuration
3361  * \return		1 on success in all packets, 0 on error in any packet
3362  *
3363  * \sa CoreAPI Overview
3364  *
3365  * \sa __ops_print_errors()
3366  *
3367  */
3368 
3369 int
3370 __ops_parse(__ops_stream_t *stream, const int perrors)
3371 {
3372 	uint32_t   pktlen;
3373 	int             r;
3374 
3375 	do {
3376 		r = __ops_parse_packet(stream, &pktlen);
3377 	} while (r != -1);
3378 	if (perrors) {
3379 		__ops_print_errors(stream->errors);
3380 	}
3381 	return (stream->errors == NULL);
3382 }
3383 
3384 /**
3385  * \ingroup Core_ReadPackets
3386  *
3387  * \brief Specifies whether one or more signature
3388  * subpacket types should be returned parsed; or raw; or ignored.
3389  *
3390  * \param	stream	Pointer to previously allocated structure
3391  * \param	tag	Packet tag. OPS_PTAG_SS_ALL for all SS tags; or one individual signature subpacket tag
3392  * \param	type	Parse type
3393  * \todo Make all packet types optional, not just subpackets */
3394 void
3395 __ops_parse_options(__ops_stream_t *stream,
3396 		  __ops_content_tag_t tag,
3397 		  __ops_parse_type_t type)
3398 {
3399 	unsigned	t7;
3400 	unsigned	t8;
3401 
3402 	if (tag == OPS_PTAG_SS_ALL) {
3403 		int             n;
3404 
3405 		for (n = 0; n < 256; ++n) {
3406 			__ops_parse_options(stream,
3407 				OPS_PTAG_SIG_SUBPKT_BASE + n,
3408 				type);
3409 		}
3410 		return;
3411 	}
3412 	if (tag < OPS_PTAG_SIG_SUBPKT_BASE ||
3413 	    tag > OPS_PTAG_SIG_SUBPKT_BASE + NTAGS - 1) {
3414 		(void) fprintf(stderr, "__ops_parse_options: bad tag\n");
3415 		return;
3416 	}
3417 	t8 = (tag - OPS_PTAG_SIG_SUBPKT_BASE) / 8;
3418 	t7 = 1 << ((tag - OPS_PTAG_SIG_SUBPKT_BASE) & 7);
3419 	switch (type) {
3420 	case OPS_PARSE_RAW:
3421 		stream->ss_raw[t8] |= t7;
3422 		stream->ss_parsed[t8] &= ~t7;
3423 		break;
3424 
3425 	case OPS_PARSE_PARSED:
3426 		stream->ss_raw[t8] &= ~t7;
3427 		stream->ss_parsed[t8] |= t7;
3428 		break;
3429 
3430 	case OPS_PARSE_IGNORE:
3431 		stream->ss_raw[t8] &= ~t7;
3432 		stream->ss_parsed[t8] &= ~t7;
3433 		break;
3434 	}
3435 }
3436 
3437 /**
3438 \ingroup Core_ReadPackets
3439 \brief Free __ops_stream_t struct and its contents
3440 */
3441 void
3442 __ops_stream_delete(__ops_stream_t *stream)
3443 {
3444 	__ops_cbdata_t	*cbinfo;
3445 	__ops_cbdata_t	*next;
3446 
3447 	for (cbinfo = stream->cbinfo.next; cbinfo; cbinfo = next) {
3448 		next = cbinfo->next;
3449 		free(cbinfo);
3450 	}
3451 	if (stream->readinfo.destroyer) {
3452 		stream->readinfo.destroyer(&stream->readinfo);
3453 	}
3454 	__ops_free_errors(stream->errors);
3455 	if (stream->readinfo.accumulated) {
3456 		free(stream->readinfo.accumulated);
3457 	}
3458 	free(stream);
3459 }
3460 
3461 /**
3462 \ingroup Core_ReadPackets
3463 \brief Returns the parse_info's reader_info
3464 \return Pointer to the reader_info inside the parse_info
3465 */
3466 __ops_reader_t *
3467 __ops_readinfo(__ops_stream_t *stream)
3468 {
3469 	return &stream->readinfo;
3470 }
3471 
3472 /**
3473 \ingroup Core_ReadPackets
3474 \brief Sets the parse_info's callback
3475 This is used when adding the first callback in a stack of callbacks.
3476 \sa __ops_callback_push()
3477 */
3478 
3479 void
3480 __ops_set_callback(__ops_stream_t *stream, __ops_cbfunc_t *cb, void *arg)
3481 {
3482 	stream->cbinfo.cbfunc = cb;
3483 	stream->cbinfo.arg = arg;
3484 	stream->cbinfo.errors = &stream->errors;
3485 }
3486 
3487 /**
3488 \ingroup Core_ReadPackets
3489 \brief Adds a further callback to a stack of callbacks
3490 \sa __ops_set_callback()
3491 */
3492 void
3493 __ops_callback_push(__ops_stream_t *stream, __ops_cbfunc_t *cb, void *arg)
3494 {
3495 	__ops_cbdata_t	*cbinfo;
3496 
3497 	if ((cbinfo = calloc(1, sizeof(*cbinfo))) == NULL) {
3498 		(void) fprintf(stderr, "__ops_callback_push: bad alloc\n");
3499 		return;
3500 	}
3501 	(void) memcpy(cbinfo, &stream->cbinfo, sizeof(*cbinfo));
3502 	cbinfo->io = stream->io;
3503 	stream->cbinfo.next = cbinfo;
3504 	__ops_set_callback(stream, cb, arg);
3505 }
3506 
3507 /**
3508 \ingroup Core_ReadPackets
3509 \brief Returns callback's arg
3510 */
3511 void *
3512 __ops_callback_arg(__ops_cbdata_t *cbinfo)
3513 {
3514 	return cbinfo->arg;
3515 }
3516 
3517 /**
3518 \ingroup Core_ReadPackets
3519 \brief Returns callback's errors
3520 */
3521 void *
3522 __ops_callback_errors(__ops_cbdata_t *cbinfo)
3523 {
3524 	return cbinfo->errors;
3525 }
3526 
3527 /**
3528 \ingroup Core_ReadPackets
3529 \brief Calls the parse_cb_info's callback if present
3530 \return Return value from callback, if present; else OPS_FINISHED
3531 */
3532 __ops_cb_ret_t
3533 __ops_callback(const __ops_packet_t *pkt, __ops_cbdata_t *cbinfo)
3534 {
3535 	return (cbinfo->cbfunc) ? cbinfo->cbfunc(pkt, cbinfo) : OPS_FINISHED;
3536 }
3537 
3538 /**
3539 \ingroup Core_ReadPackets
3540 \brief Calls the next callback  in the stack
3541 \return Return value from callback
3542 */
3543 __ops_cb_ret_t
3544 __ops_stacked_callback(const __ops_packet_t *pkt, __ops_cbdata_t *cbinfo)
3545 {
3546 	return __ops_callback(pkt, cbinfo->next);
3547 }
3548 
3549 /**
3550 \ingroup Core_ReadPackets
3551 \brief Returns the parse_info's errors
3552 \return parse_info's errors
3553 */
3554 __ops_error_t    *
3555 __ops_stream_get_errors(__ops_stream_t *stream)
3556 {
3557 	return stream->errors;
3558 }
3559 
3560 __ops_crypt_t    *
3561 __ops_get_decrypt(__ops_stream_t *stream)
3562 {
3563 	return (stream->decrypt.alg) ? &stream->decrypt : NULL;
3564 }
3565