xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/writer.c (revision 4e6df137e8e14049b5a701d249962c480449c141)
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  * This file contains the base functions used by the writers.
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: writer.c,v 1.19 2010/03/05 16:01:10 agc Exp $");
62 #endif
63 
64 #include <sys/types.h>
65 
66 #include <stdlib.h>
67 #include <string.h>
68 
69 #ifdef HAVE_UNISTD_H
70 #include <unistd.h>
71 #endif
72 
73 #ifdef HAVE_OPENSSL_CAST_H
74 #include <openssl/cast.h>
75 #endif
76 
77 #include "create.h"
78 #include "writer.h"
79 #include "keyring.h"
80 #include "signature.h"
81 #include "packet.h"
82 #include "packet-parse.h"
83 #include "readerwriter.h"
84 #include "memory.h"
85 #include "netpgpdefs.h"
86 #include "version.h"
87 #include "netpgpdigest.h"
88 
89 
90 /*
91  * return 1 if OK, otherwise 0
92  */
93 static unsigned
94 base_write(__ops_output_t *out, const void *src, unsigned len)
95 {
96 	return out->writer.writer(src, len, &out->errors, &out->writer);
97 }
98 
99 /**
100  * \ingroup Core_WritePackets
101  *
102  * \param src
103  * \param len
104  * \param output
105  * \return 1 if OK, otherwise 0
106  */
107 
108 unsigned
109 __ops_write(__ops_output_t *output, const void *src, unsigned len)
110 {
111 	return base_write(output, src, len);
112 }
113 
114 /**
115  * \ingroup Core_WritePackets
116  * \param n
117  * \param len
118  * \param output
119  * \return 1 if OK, otherwise 0
120  */
121 
122 unsigned
123 __ops_write_scalar(__ops_output_t *output, unsigned n, unsigned len)
124 {
125 	uint8_t   c;
126 
127 	while (len-- > 0) {
128 		c = n >> (len * 8);
129 		if (!base_write(output, &c, 1)) {
130 			return 0;
131 		}
132 	}
133 	return 1;
134 }
135 
136 /**
137  * \ingroup Core_WritePackets
138  * \param bn
139  * \param output
140  * \return 1 if OK, otherwise 0
141  */
142 
143 unsigned
144 __ops_write_mpi(__ops_output_t *output, const BIGNUM *bn)
145 {
146 	unsigned	bits;
147 	uint8_t		buf[NETPGP_BUFSIZ];
148 
149 	bits = (unsigned)BN_num_bits(bn);
150 	if (bits > 65535) {
151 		(void) fprintf(stderr, "__ops_write_mpi: too large %u\n", bits);
152 		return 0;
153 	}
154 	BN_bn2bin(bn, buf);
155 	return __ops_write_scalar(output, bits, 2) &&
156 		__ops_write(output, buf, (bits + 7) / 8);
157 }
158 
159 /**
160  * \ingroup Core_WritePackets
161  * \param tag
162  * \param output
163  * \return 1 if OK, otherwise 0
164  */
165 
166 unsigned
167 __ops_write_ptag(__ops_output_t *output, __ops_content_tag_t tag)
168 {
169 	uint8_t   c;
170 
171 	c = tag | OPS_PTAG_ALWAYS_SET | OPS_PTAG_NEW_FORMAT;
172 	return base_write(output, &c, 1);
173 }
174 
175 /**
176  * \ingroup Core_WritePackets
177  * \param len
178  * \param output
179  * \return 1 if OK, otherwise 0
180  */
181 
182 unsigned
183 __ops_write_length(__ops_output_t *output, unsigned len)
184 {
185 	uint8_t   c[2];
186 
187 	if (len < 192) {
188 		c[0] = len;
189 		return base_write(output, c, 1);
190 	}
191 	if (len < 8192 + 192) {
192 		c[0] = ((len - 192) >> 8) + 192;
193 		c[1] = (len - 192) % 256;
194 		return base_write(output, c, 2);
195 	}
196 	return __ops_write_scalar(output, 0xff, 1) &&
197 		__ops_write_scalar(output, len, 4);
198 }
199 
200 /*
201  * Note that we finalise from the top down, so we don't use writers below
202  * that have already been finalised
203  */
204 unsigned
205 __ops_writer_info_finalise(__ops_error_t **errors, __ops_writer_t *writer)
206 {
207 	unsigned   ret = 1;
208 
209 	if (writer->finaliser) {
210 		ret = writer->finaliser(errors, writer);
211 		writer->finaliser = NULL;
212 	}
213 	if (writer->next && !__ops_writer_info_finalise(errors, writer->next)) {
214 		writer->finaliser = NULL;
215 		return 0;
216 	}
217 	return ret;
218 }
219 
220 void
221 __ops_writer_info_delete(__ops_writer_t *writer)
222 {
223 	/* we should have finalised before deleting */
224 	if (writer->finaliser) {
225 		(void) fprintf(stderr, "__ops_writer_info_delete: not done\n");
226 		return;
227 	}
228 	if (writer->next) {
229 		__ops_writer_info_delete(writer->next);
230 		free(writer->next);
231 		writer->next = NULL;
232 	}
233 	if (writer->destroyer) {
234 		writer->destroyer(writer);
235 		writer->destroyer = NULL;
236 	}
237 	writer->writer = NULL;
238 }
239 
240 /**
241  * \ingroup Core_Writers
242  *
243  * Set a writer in output. There should not be another writer set.
244  *
245  * \param output The output structure
246  * \param writer
247  * \param finaliser
248  * \param destroyer
249  * \param arg The argument for the writer and destroyer
250  */
251 void
252 __ops_writer_set(__ops_output_t *output,
253 	       __ops_writer_func_t *writer,
254 	       __ops_writer_finaliser_t *finaliser,
255 	       __ops_writer_destroyer_t *destroyer,
256 	       void *arg)
257 {
258 	if (output->writer.writer) {
259 		(void) fprintf(stderr, "__ops_writer_set: already set\n");
260 	} else {
261 		output->writer.writer = writer;
262 		output->writer.finaliser = finaliser;
263 		output->writer.destroyer = destroyer;
264 		output->writer.arg = arg;
265 	}
266 }
267 
268 /**
269  * \ingroup Core_Writers
270  *
271  * Push a writer in output. There must already be another writer set.
272  *
273  * \param output The output structure
274  * \param writer
275  * \param finaliser
276  * \param destroyer
277  * \param arg The argument for the writer and destroyer
278  */
279 void
280 __ops_writer_push(__ops_output_t *output,
281 		__ops_writer_func_t *writer,
282 		__ops_writer_finaliser_t *finaliser,
283 		__ops_writer_destroyer_t *destroyer,
284 		void *arg)
285 {
286 	__ops_writer_t *copy;
287 
288 	if ((copy = calloc(1, sizeof(*copy))) == NULL) {
289 		(void) fprintf(stderr, "__ops_writer_push: bad alloc\n");
290 	} else if (output->writer.writer == NULL) {
291 		(void) fprintf(stderr, "__ops_writer_push: no orig writer\n");
292 	} else {
293 		*copy = output->writer;
294 		output->writer.next = copy;
295 
296 		output->writer.writer = writer;
297 		output->writer.finaliser = finaliser;
298 		output->writer.destroyer = destroyer;
299 		output->writer.arg = arg;
300 	}
301 }
302 
303 void
304 __ops_writer_pop(__ops_output_t *output)
305 {
306 	__ops_writer_t *next;
307 
308 	/* Make sure the finaliser has been called. */
309 	if (output->writer.finaliser) {
310 		(void) fprintf(stderr,
311 			"__ops_writer_pop: finaliser not called\n");
312 	} else if (output->writer.next == NULL) {
313 		(void) fprintf(stderr,
314 			"__ops_writer_pop: not a stacked writer\n");
315 	} else {
316 		if (output->writer.destroyer) {
317 			output->writer.destroyer(&output->writer);
318 		}
319 		next = output->writer.next;
320 		output->writer = *next;
321 		free(next);
322 	}
323 }
324 
325 /**
326  * \ingroup Core_Writers
327  *
328  * Close the writer currently set in output.
329  *
330  * \param output The output structure
331  */
332 unsigned
333 __ops_writer_close(__ops_output_t *output)
334 {
335 	unsigned   ret;
336 
337 	ret = __ops_writer_info_finalise(&output->errors, &output->writer);
338 	__ops_writer_info_delete(&output->writer);
339 	return ret;
340 }
341 
342 /**
343  * \ingroup Core_Writers
344  *
345  * Get the arg supplied to __ops_createinfo_set_writer().
346  *
347  * \param writer The writer_info structure
348  * \return The arg
349  */
350 void           *
351 __ops_writer_get_arg(__ops_writer_t *writer)
352 {
353 	return writer->arg;
354 }
355 
356 /**
357  * \ingroup Core_Writers
358  *
359  * Write to the next writer down in the stack.
360  *
361  * \param src The data to write.
362  * \param len The length of src.
363  * \param errors A place to store errors.
364  * \param writer The writer_info structure.
365  * \return Success - if 0, then errors should contain the error.
366  */
367 static unsigned
368 stacked_write(__ops_writer_t *writer, const void *src, unsigned len,
369 		  __ops_error_t ** errors)
370 {
371 	return writer->next->writer(src, len, errors, writer->next);
372 }
373 
374 /**
375  * \ingroup Core_Writers
376  *
377  * Free the arg. Many writers just have a calloc()ed lump of storage, this
378  * function releases it.
379  *
380  * \param writer the info structure.
381  */
382 static void
383 generic_destroyer(__ops_writer_t *writer)
384 {
385 	free(__ops_writer_get_arg(writer));
386 }
387 
388 /**
389  * \ingroup Core_Writers
390  *
391  * A writer that just writes to the next one down. Useful for when you
392  * want to insert just a finaliser into the stack.
393  */
394 unsigned
395 __ops_writer_passthrough(const uint8_t *src,
396 		       unsigned len,
397 		       __ops_error_t **errors,
398 		       __ops_writer_t *writer)
399 {
400 	return stacked_write(writer, src, len, errors);
401 }
402 
403 /**************************************************************************/
404 
405 /**
406  * \struct dashesc_t
407  */
408 typedef struct {
409 	unsigned   		 seen_nl:1;
410 	unsigned		 seen_cr:1;
411 	__ops_create_sig_t	*sig;
412 	__ops_memory_t		*trailing;
413 } dashesc_t;
414 
415 static unsigned
416 dash_esc_writer(const uint8_t *src,
417 		    unsigned len,
418 		    __ops_error_t **errors,
419 		    __ops_writer_t *writer)
420 {
421 	dashesc_t	*dash = __ops_writer_get_arg(writer);
422 	unsigned        n;
423 
424 	if (__ops_get_debug_level(__FILE__)) {
425 		unsigned    i = 0;
426 
427 		(void) fprintf(stderr, "dash_esc_writer writing %u:\n", len);
428 		for (i = 0; i < len; i++) {
429 			fprintf(stderr, "0x%02x ", src[i]);
430 			if (((i + 1) % 16) == 0) {
431 				(void) fprintf(stderr, "\n");
432 			} else if (((i + 1) % 8) == 0) {
433 				(void) fprintf(stderr, "  ");
434 			}
435 		}
436 		(void) fprintf(stderr, "\n");
437 	}
438 	/* XXX: make this efficient */
439 	for (n = 0; n < len; ++n) {
440 		unsigned        l;
441 
442 		if (dash->seen_nl) {
443 			if (src[n] == '-' &&
444 			    !stacked_write(writer, "- ", 2, errors)) {
445 				return 0;
446 			}
447 			dash->seen_nl = 0;
448 		}
449 		dash->seen_nl = src[n] == '\n';
450 
451 		if (dash->seen_nl && !dash->seen_cr) {
452 			if (!stacked_write(writer, "\r", 1, errors)) {
453 				return 0;
454 			}
455 			__ops_sig_add_data(dash->sig, "\r", 1);
456 		}
457 		dash->seen_cr = src[n] == '\r';
458 
459 		if (!stacked_write(writer, &src[n], 1, errors)) {
460 			return 0;
461 		}
462 
463 		/* trailing whitespace isn't included in the signature */
464 		if (src[n] == ' ' || src[n] == '\t') {
465 			__ops_memory_add(dash->trailing, &src[n], 1);
466 		} else {
467 			if ((l = __ops_mem_len(dash->trailing)) != 0) {
468 				if (!dash->seen_nl && !dash->seen_cr) {
469 					__ops_sig_add_data(dash->sig,
470 					__ops_mem_data(dash->trailing), l);
471 				}
472 				__ops_memory_clear(dash->trailing);
473 			}
474 			__ops_sig_add_data(dash->sig, &src[n], 1);
475 		}
476 	}
477 	return 1;
478 }
479 
480 /**
481  * \param writer
482  */
483 static void
484 dash_escaped_destroyer(__ops_writer_t *writer)
485 {
486 	dashesc_t	*dash;
487 
488 	dash = __ops_writer_get_arg(writer);
489 	__ops_memory_free(dash->trailing);
490 	free(dash);
491 }
492 
493 /**
494  * \ingroup Core_WritersNext
495  * \brief Push Clearsigned Writer onto stack
496  * \param output
497  * \param sig
498  */
499 unsigned
500 __ops_writer_push_clearsigned(__ops_output_t *output, __ops_create_sig_t *sig)
501 {
502 	static const char     header[] =
503 		"-----BEGIN PGP SIGNED MESSAGE-----\r\nHash: ";
504 	const char     *hash;
505 	dashesc_t      *dash;
506 	unsigned	ret;
507 
508 	hash = __ops_text_from_hash(__ops_sig_get_hash(sig));
509 	if ((dash = calloc(1, sizeof(*dash))) == NULL) {
510 		OPS_ERROR(&output->errors, OPS_E_W, "Bad alloc");
511 		return 0;
512 	}
513 	ret = (__ops_write(output, header, sizeof(header) - 1) &&
514 		__ops_write(output, hash, strlen(hash)) &&
515 		__ops_write(output, "\r\n\r\n", 4));
516 
517 	if (ret == 0) {
518 		OPS_ERROR(&output->errors, OPS_E_W,
519 			"Error pushing clearsigned header");
520 		free(dash);
521 		return ret;
522 	}
523 	dash->seen_nl = 1;
524 	dash->sig = sig;
525 	dash->trailing = __ops_memory_new();
526 	__ops_writer_push(output, dash_esc_writer, NULL,
527 			dash_escaped_destroyer, dash);
528 	return ret;
529 }
530 
531 
532 /**
533  * \struct base64_t
534  */
535 typedef struct {
536 	unsigned	pos;
537 	uint8_t		t;
538 	unsigned	checksum;
539 } base64_t;
540 
541 static const char     b64map[] =
542 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
543 
544 static unsigned
545 base64_writer(const uint8_t *src,
546 	      unsigned len,
547 	      __ops_error_t **errors,
548 	      __ops_writer_t *writer)
549 {
550 	base64_t	*base64;
551 	unsigned         n;
552 
553 	base64 = __ops_writer_get_arg(writer);
554 	for (n = 0; n < len;) {
555 		base64->checksum = __ops_crc24(base64->checksum, src[n]);
556 		if (base64->pos == 0) {
557 			/* XXXXXX00 00000000 00000000 */
558 			if (!stacked_write(writer,
559 					&b64map[(unsigned)src[n] >> 2],
560 					1, errors)) {
561 				return 0;
562 			}
563 
564 			/* 000000XX xxxx0000 00000000 */
565 			base64->t = (src[n++] & 3) << 4;
566 			base64->pos = 1;
567 		} else if (base64->pos == 1) {
568 			/* 000000xx XXXX0000 00000000 */
569 			base64->t += (unsigned)src[n] >> 4;
570 			if (!stacked_write(writer, &b64map[base64->t], 1,
571 					errors)) {
572 				return 0;
573 			}
574 
575 			/* 00000000 0000XXXX xx000000 */
576 			base64->t = (src[n++] & 0xf) << 2;
577 			base64->pos = 2;
578 		} else if (base64->pos == 2) {
579 			/* 00000000 0000xxxx XX000000 */
580 			base64->t += (unsigned)src[n] >> 6;
581 			if (!stacked_write(writer, &b64map[base64->t], 1,
582 					errors)) {
583 				return 0;
584 			}
585 
586 			/* 00000000 00000000 00XXXXXX */
587 			if (!stacked_write(writer,
588 					&b64map[src[n++] & 0x3f], 1, errors)) {
589 				return 0;
590 			}
591 
592 			base64->pos = 0;
593 		}
594 	}
595 
596 	return 1;
597 }
598 
599 static unsigned
600 sig_finaliser(__ops_error_t **errors, __ops_writer_t *writer)
601 {
602 	static const char	trail[] = "\r\n-----END PGP SIGNATURE-----\r\n";
603 	base64_t		*base64;
604 	uint8_t			c[3];
605 
606 	base64 = __ops_writer_get_arg(writer);
607 	if (base64->pos) {
608 		if (!stacked_write(writer, &b64map[base64->t], 1, errors)) {
609 			return 0;
610 		}
611 		if (base64->pos == 1 &&
612 		    !stacked_write(writer, "==", 2, errors)) {
613 			return 0;
614 		}
615 		if (base64->pos == 2 &&
616 		    !stacked_write(writer, "=", 1, errors)) {
617 			return 0;
618 		}
619 	}
620 	/* Ready for the checksum */
621 	if (!stacked_write(writer, "\r\n=", 3, errors)) {
622 		return 0;
623 	}
624 
625 	base64->pos = 0;		/* get ready to write the checksum */
626 
627 	c[0] = base64->checksum >> 16;
628 	c[1] = base64->checksum >> 8;
629 	c[2] = base64->checksum;
630 	/* push the checksum through our own writer */
631 	if (!base64_writer(c, 3, errors, writer)) {
632 		return 0;
633 	}
634 
635 	return stacked_write(writer, trail, sizeof(trail) - 1, errors);
636 }
637 
638 /**
639  * \struct linebreak_t
640  */
641 typedef struct {
642 	unsigned        pos;
643 } linebreak_t;
644 
645 #define BREAKPOS	76
646 
647 static unsigned
648 linebreak_writer(const uint8_t *src,
649 		 unsigned len,
650 		 __ops_error_t **errors,
651 		 __ops_writer_t *writer)
652 {
653 	linebreak_t	*linebreak;
654 	unsigned         n;
655 
656 	linebreak = __ops_writer_get_arg(writer);
657 	for (n = 0; n < len; ++n, ++linebreak->pos) {
658 		if (src[n] == '\r' || src[n] == '\n') {
659 			linebreak->pos = 0;
660 		}
661 		if (linebreak->pos == BREAKPOS) {
662 			if (!stacked_write(writer, "\r\n", 2, errors)) {
663 				return 0;
664 			}
665 			linebreak->pos = 0;
666 		}
667 		if (!stacked_write(writer, &src[n], 1, errors)) {
668 			return 0;
669 		}
670 	}
671 
672 	return 1;
673 }
674 
675 /**
676  * \ingroup Core_WritersNext
677  * \brief Push armoured signature on stack
678  * \param output
679  */
680 unsigned
681 __ops_writer_use_armored_sig(__ops_output_t *output)
682 {
683 	static const char     header[] =
684 			"\r\n-----BEGIN PGP SIGNATURE-----\r\nVersion: "
685 			NETPGP_VERSION_STRING
686 			"\r\n\r\n";
687 	linebreak_t	*linebreak;
688 	base64_t   	*base64;
689 
690 	__ops_writer_pop(output);
691 	if (__ops_write(output, header, sizeof(header) - 1) == 0) {
692 		OPS_ERROR(&output->errors, OPS_E_W,
693 			"Error switching to armoured signature");
694 		return 0;
695 	}
696 	if ((linebreak = calloc(1, sizeof(*linebreak))) == NULL) {
697 		OPS_ERROR(&output->errors, OPS_E_W,
698 			"__ops_writer_use_armored_sig: Bad alloc");
699 		return 0;
700 	}
701 	__ops_writer_push(output, linebreak_writer, NULL,
702 			generic_destroyer,
703 			linebreak);
704 	base64 = calloc(1, sizeof(*base64));
705 	if (!base64) {
706 		OPS_MEMORY_ERROR(&output->errors);
707 		return 0;
708 	}
709 	base64->checksum = CRC24_INIT;
710 	__ops_writer_push(output, base64_writer, sig_finaliser,
711 			generic_destroyer, base64);
712 	return 1;
713 }
714 
715 static unsigned
716 armoured_message_finaliser(__ops_error_t **errors, __ops_writer_t *writer)
717 {
718 	/* TODO: This is same as sig_finaliser apart from trailer. */
719 	static const char	 trailer[] =
720 			"\r\n-----END PGP MESSAGE-----\r\n";
721 	base64_t		*base64;
722 	uint8_t			 c[3];
723 
724 	base64 = __ops_writer_get_arg(writer);
725 	if (base64->pos) {
726 		if (!stacked_write(writer, &b64map[base64->t], 1, errors)) {
727 			return 0;
728 		}
729 		if (base64->pos == 1 &&
730 		    !stacked_write(writer, "==", 2, errors)) {
731 			return 0;
732 		}
733 		if (base64->pos == 2 &&
734 		    !stacked_write(writer, "=", 1, errors)) {
735 			return 0;
736 		}
737 	}
738 	/* Ready for the checksum */
739 	if (!stacked_write(writer, "\r\n=", 3, errors)) {
740 		return 0;
741 	}
742 
743 	base64->pos = 0;		/* get ready to write the checksum */
744 
745 	c[0] = base64->checksum >> 16;
746 	c[1] = base64->checksum >> 8;
747 	c[2] = base64->checksum;
748 	/* push the checksum through our own writer */
749 	if (!base64_writer(c, 3, errors, writer)) {
750 		return 0;
751 	}
752 
753 	return stacked_write(writer, trailer, strlen(trailer), errors);
754 }
755 
756 /**
757  \ingroup Core_WritersNext
758  \brief Write a PGP MESSAGE
759  \todo replace with generic function
760 */
761 void
762 __ops_writer_push_armor_msg(__ops_output_t *output)
763 {
764 	static const char	 header[] = "-----BEGIN PGP MESSAGE-----\r\n";
765 	linebreak_t		*linebreak;
766 	base64_t		*base64;
767 
768 	__ops_write(output, header, sizeof(header) - 1);
769 	__ops_write(output, "\r\n", 2);
770 	if ((linebreak = calloc(1, sizeof(*linebreak))) == NULL) {
771 		(void) fprintf(stderr,
772 			"__ops_writer_push_armor_msg: bad lb alloc\n");
773 		return;
774 	}
775 	__ops_writer_push(output, linebreak_writer, NULL,
776 		generic_destroyer,
777 		linebreak);
778 	if ((base64 = calloc(1, sizeof(*base64))) == NULL) {
779 		(void) fprintf(stderr,
780 			"__ops_writer_push_armor_msg: bad alloc\n");
781 		return;
782 	}
783 	base64->checksum = CRC24_INIT;
784 	__ops_writer_push(output, base64_writer,
785 		armoured_message_finaliser, generic_destroyer,
786 		base64);
787 }
788 
789 static unsigned
790 armoured_finaliser(__ops_armor_type_t type,
791 			__ops_error_t **errors,
792 			__ops_writer_t *writer)
793 {
794 	static const char     tail_pubkey[] =
795 			"\r\n-----END PGP PUBLIC KEY BLOCK-----\r\n";
796 	static const char     tail_private_key[] =
797 			"\r\n-----END PGP PRIVATE KEY BLOCK-----\r\n";
798 	const char		*tail = NULL;
799 	unsigned		 tailsize = 0;
800 	base64_t		*base64;
801 	uint8_t		 	 c[3];
802 
803 	switch (type) {
804 	case OPS_PGP_PUBLIC_KEY_BLOCK:
805 		tail = tail_pubkey;
806 		tailsize = sizeof(tail_pubkey) - 1;
807 		break;
808 
809 	case OPS_PGP_PRIVATE_KEY_BLOCK:
810 		tail = tail_private_key;
811 		tailsize = sizeof(tail_private_key) - 1;
812 		break;
813 
814 	default:
815 		(void) fprintf(stderr, "armoured_finaliser: unusual type\n");
816 		return 0;
817 	}
818 	base64 = __ops_writer_get_arg(writer);
819 	if (base64->pos) {
820 		if (!stacked_write(writer, &b64map[base64->t], 1,
821 					errors)) {
822 			return 0;
823 		}
824 		if (base64->pos == 1 && !stacked_write(writer, "==", 2,
825 				errors)) {
826 			return 0;
827 		}
828 		if (base64->pos == 2 && !stacked_write(writer, "=", 1,
829 				errors)) {
830 			return 0;
831 		}
832 	}
833 	/* Ready for the checksum */
834 	if (!stacked_write(writer, "\r\n=", 3, errors)) {
835 		return 0;
836 	}
837 	base64->pos = 0;		/* get ready to write the checksum */
838 	c[0] = base64->checksum >> 16;
839 	c[1] = base64->checksum >> 8;
840 	c[2] = base64->checksum;
841 	/* push the checksum through our own writer */
842 	if (!base64_writer(c, 3, errors, writer)) {
843 		return 0;
844 	}
845 	return stacked_write(writer, tail, tailsize, errors);
846 }
847 
848 static unsigned
849 armored_pubkey_fini(__ops_error_t **errors, __ops_writer_t *writer)
850 {
851 	return armoured_finaliser(OPS_PGP_PUBLIC_KEY_BLOCK, errors, writer);
852 }
853 
854 static unsigned
855 armored_privkey_fini(__ops_error_t **errors, __ops_writer_t *writer)
856 {
857 	return armoured_finaliser(OPS_PGP_PRIVATE_KEY_BLOCK, errors, writer);
858 }
859 
860 /* \todo use this for other armoured types */
861 /**
862  \ingroup Core_WritersNext
863  \brief Push Armoured Writer on stack (generic)
864 */
865 void
866 __ops_writer_push_armoured(__ops_output_t *output, __ops_armor_type_t type)
867 {
868 	static char     hdr_pubkey[] =
869 			"-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: "
870 			NETPGP_VERSION_STRING
871 			"\r\n\r\n";
872 	static char     hdr_private_key[] =
873 			"-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: "
874 			NETPGP_VERSION_STRING
875 			"\r\n\r\n";
876 	unsigned    	 hdrsize = 0;
877 	unsigned	(*finaliser) (__ops_error_t **, __ops_writer_t *);
878 	base64_t	*base64;
879 	linebreak_t	*linebreak;
880 	char           *header = NULL;
881 
882 	finaliser = NULL;
883 	switch (type) {
884 	case OPS_PGP_PUBLIC_KEY_BLOCK:
885 		header = hdr_pubkey;
886 		hdrsize = sizeof(hdr_pubkey) - 1;
887 		finaliser = armored_pubkey_fini;
888 		break;
889 
890 	case OPS_PGP_PRIVATE_KEY_BLOCK:
891 		header = hdr_private_key;
892 		hdrsize = sizeof(hdr_private_key) - 1;
893 		finaliser = armored_privkey_fini;
894 		break;
895 
896 	default:
897 		(void) fprintf(stderr,
898 			"__ops_writer_push_armoured: unusual type\n");
899 		return;
900 	}
901 	if ((linebreak = calloc(1, sizeof(*linebreak))) == NULL) {
902 		(void) fprintf(stderr,
903 			"__ops_writer_push_armoured: bad alloc\n");
904 		return;
905 	}
906 	__ops_write(output, header, hdrsize);
907 	__ops_writer_push(output, linebreak_writer, NULL,
908 			generic_destroyer,
909 			linebreak);
910 	if ((base64 = calloc(1, sizeof(*base64))) == NULL) {
911 		(void) fprintf(stderr,
912 			"__ops_writer_push_armoured: bad alloc\n");
913 		return;
914 	}
915 	base64->checksum = CRC24_INIT;
916 	__ops_writer_push(output, base64_writer, finaliser,
917 			generic_destroyer, base64);
918 }
919 
920 /**************************************************************************/
921 
922 typedef struct {
923 	__ops_crypt_t    *crypt;
924 	int             free_crypt;
925 } crypt_t;
926 
927 /*
928  * This writer simply takes plaintext as input,
929  * encrypts it with the given key
930  * and outputs the resulting encrypted text
931  */
932 static unsigned
933 encrypt_writer(const uint8_t *src,
934 	       unsigned len,
935 	       __ops_error_t **errors,
936 	       __ops_writer_t *writer)
937 {
938 #define BUFSZ 1024		/* arbitrary number */
939 	uint8_t		encbuf[BUFSZ];
940 	unsigned        remaining;
941 	unsigned        done = 0;
942 	crypt_t		*pgp_encrypt;
943 
944 	remaining = len;
945 	pgp_encrypt = (crypt_t *) __ops_writer_get_arg(writer);
946 	if (!__ops_is_sa_supported(pgp_encrypt->crypt->alg)) {
947 		(void) fprintf(stderr, "encrypt_writer: not supported\n");
948 		return 0;
949 	}
950 	while (remaining > 0) {
951 		unsigned        size = (remaining < BUFSZ) ? remaining : BUFSZ;
952 
953 		/* memcpy(buf,src,size); // \todo copy needed here? */
954 		pgp_encrypt->crypt->cfb_encrypt(pgp_encrypt->crypt, encbuf,
955 					src + done, size);
956 
957 		if (__ops_get_debug_level(__FILE__)) {
958 			int             i = 0;
959 
960 			(void) fprintf(stderr, "WRITING:\nunencrypted: ");
961 			for (i = 0; i < 16; i++) {
962 				(void) fprintf(stderr, "%2x ", src[done + i]);
963 			}
964 			(void) fprintf(stderr, "\nencrypted:   ");
965 			for (i = 0; i < 16; i++) {
966 				(void) fprintf(stderr, "%2x ", encbuf[i]);
967 			}
968 			(void) fprintf(stderr, "\n");
969 		}
970 		if (!stacked_write(writer, encbuf, size, errors)) {
971 			if (__ops_get_debug_level(__FILE__)) {
972 				fprintf(stderr,
973 					"encrypted_writer: stacked write\n");
974 			}
975 			return 0;
976 		}
977 		remaining -= size;
978 		done += size;
979 	}
980 
981 	return 1;
982 }
983 
984 static void
985 encrypt_destroyer(__ops_writer_t *writer)
986 {
987 	crypt_t    *pgp_encrypt;
988 
989 	pgp_encrypt = (crypt_t *) __ops_writer_get_arg(writer);
990 	if (pgp_encrypt->free_crypt) {
991 		free(pgp_encrypt->crypt);
992 	}
993 	free(pgp_encrypt);
994 }
995 
996 /**
997 \ingroup Core_WritersNext
998 \brief Push Encrypted Writer onto stack (create SE packets)
999 */
1000 void
1001 __ops_push_enc_crypt(__ops_output_t *output, __ops_crypt_t *pgp_crypt)
1002 {
1003 	/* Create encrypt to be used with this writer */
1004 	/* Remember to free this in the destroyer */
1005 	crypt_t    *pgp_encrypt;
1006 
1007 	if ((pgp_encrypt = calloc(1, sizeof(*pgp_encrypt))) == NULL) {
1008 		(void) fprintf(stderr, "__ops_push_enc_crypt: bad alloc\n");
1009 	} else {
1010 		/* Setup the encrypt */
1011 		pgp_encrypt->crypt = pgp_crypt;
1012 		pgp_encrypt->free_crypt = 0;
1013 		/* And push writer on stack */
1014 		__ops_writer_push(output, encrypt_writer, NULL,
1015 			encrypt_destroyer, pgp_encrypt);
1016 	}
1017 }
1018 
1019 /**************************************************************************/
1020 
1021 typedef struct {
1022 	__ops_crypt_t    *crypt;
1023 } encrypt_se_ip_t;
1024 
1025 static unsigned	encrypt_se_ip_writer(const uint8_t *,
1026 		     unsigned,
1027 		     __ops_error_t **,
1028 		     __ops_writer_t *);
1029 static void     encrypt_se_ip_destroyer(__ops_writer_t *);
1030 
1031 /* */
1032 
1033 /**
1034 \ingroup Core_WritersNext
1035 \brief Push Encrypted SE IP Writer onto stack
1036 */
1037 void
1038 __ops_push_enc_se_ip(__ops_output_t *output, const __ops_key_t *pubkey)
1039 {
1040 	__ops_pk_sesskey_t *encrypted_pk_sesskey;
1041 	encrypt_se_ip_t *se_ip;
1042 	__ops_crypt_t	*encrypted;
1043 	uint8_t		*iv;
1044 
1045 	if ((se_ip = calloc(1, sizeof(*se_ip))) == NULL) {
1046 		(void) fprintf(stderr, "__ops_push_enc_se_ip: bad alloc\n");
1047 		return;
1048 	}
1049 
1050 	/* Create and write encrypted PK session key */
1051 	encrypted_pk_sesskey = __ops_create_pk_sesskey(pubkey);
1052 	__ops_write_pk_sesskey(output, encrypted_pk_sesskey);
1053 
1054 	/* Setup the se_ip */
1055 	if ((encrypted = calloc(1, sizeof(*encrypted))) == NULL) {
1056 		free(se_ip);
1057 		(void) fprintf(stderr, "__ops_push_enc_se_ip: bad alloc\n");
1058 		return;
1059 	}
1060 	__ops_crypt_any(encrypted, encrypted_pk_sesskey->symm_alg);
1061 	if ((iv = calloc(1, encrypted->blocksize)) == NULL) {
1062 		free(se_ip);
1063 		free(encrypted);
1064 		(void) fprintf(stderr, "__ops_push_enc_se_ip: bad alloc\n");
1065 		return;
1066 	}
1067 	encrypted->set_iv(encrypted, iv);
1068 	encrypted->set_crypt_key(encrypted, &encrypted_pk_sesskey->key[0]);
1069 	__ops_encrypt_init(encrypted);
1070 
1071 	se_ip->crypt = encrypted;
1072 
1073 	/* And push writer on stack */
1074 	__ops_writer_push(output, encrypt_se_ip_writer, NULL,
1075 			encrypt_se_ip_destroyer, se_ip);
1076 	/* tidy up */
1077 	free(encrypted_pk_sesskey);
1078 	free(iv);
1079 }
1080 
1081 static unsigned
1082 encrypt_se_ip_writer(const uint8_t *src,
1083 		     unsigned len,
1084 		     __ops_error_t **errors,
1085 		     __ops_writer_t *writer)
1086 {
1087 	const unsigned	 bufsz = 128;
1088 	encrypt_se_ip_t	*se_ip = __ops_writer_get_arg(writer);
1089 	__ops_output_t	*litoutput;
1090 	__ops_output_t	*zoutput;
1091 	__ops_output_t	*output;
1092 	__ops_memory_t	*litmem;
1093 	__ops_memory_t	*zmem;
1094 	__ops_memory_t	*localmem;
1095 	unsigned	 ret = 1;
1096 
1097 	__ops_setup_memory_write(&litoutput, &litmem, bufsz);
1098 	__ops_setup_memory_write(&zoutput, &zmem, bufsz);
1099 	__ops_setup_memory_write(&output, &localmem, bufsz);
1100 
1101 	/* create literal data packet from source data */
1102 	__ops_write_litdata(litoutput, src, (const int)len, OPS_LDT_BINARY);
1103 	if (__ops_mem_len(litmem) <= len) {
1104 		(void) fprintf(stderr, "encrypt_se_ip_writer: bad len\n");
1105 		return 0;
1106 	}
1107 
1108 	/* create compressed packet from literal data packet */
1109 	__ops_writez(zoutput, __ops_mem_data(litmem), __ops_mem_len(litmem));
1110 
1111 	/* create SE IP packet set from this compressed literal data */
1112 	__ops_write_se_ip_pktset(output, __ops_mem_data(zmem),
1113 			       __ops_mem_len(zmem),
1114 			       se_ip->crypt);
1115 	if (__ops_mem_len(localmem) <= __ops_mem_len(zmem)) {
1116 		(void) fprintf(stderr,
1117 				"encrypt_se_ip_writer: bad comp len\n");
1118 		return 0;
1119 	}
1120 
1121 	/* now write memory to next writer */
1122 	ret = stacked_write(writer, __ops_mem_data(localmem),
1123 				__ops_mem_len(localmem), errors);
1124 
1125 	__ops_memory_free(localmem);
1126 	__ops_memory_free(zmem);
1127 	__ops_memory_free(litmem);
1128 
1129 	return ret;
1130 }
1131 
1132 static void
1133 encrypt_se_ip_destroyer(__ops_writer_t *writer)
1134 {
1135 	encrypt_se_ip_t	*se_ip;
1136 
1137 	se_ip = __ops_writer_get_arg(writer);
1138 	free(se_ip->crypt);
1139 	free(se_ip);
1140 }
1141 
1142 unsigned
1143 __ops_write_se_ip_pktset(__ops_output_t *output,
1144 			const uint8_t *data,
1145 			const unsigned len,
1146 			__ops_crypt_t *crypted)
1147 {
1148 	__ops_output_t	*mdcoutput;
1149 	__ops_memory_t	*mdc;
1150 	uint8_t		 hashed[OPS_SHA1_HASH_SIZE];
1151 	uint8_t		*preamble;
1152 	const size_t	 mdcsize = 1 + 1 + OPS_SHA1_HASH_SIZE;
1153 	size_t		 preamblesize;
1154 	size_t		 bufsize;
1155 
1156 	preamblesize = crypted->blocksize + 2;
1157 	if ((preamble = calloc(1, preamblesize)) == NULL) {
1158 		(void) fprintf(stderr, "__ops_write_se_ip_pktset: bad alloc\n");
1159 		return 0;
1160 	}
1161 	bufsize = preamblesize + len + mdcsize;
1162 
1163 	if (!__ops_write_ptag(output, OPS_PTAG_CT_SE_IP_DATA) ||
1164 	    !__ops_write_length(output, 1 + bufsize) ||
1165 	    !__ops_write_scalar(output, SE_IP_DATA_VERSION, 1)) {
1166 		free(preamble);
1167 		return 0;
1168 	}
1169 	__ops_random(preamble, crypted->blocksize);
1170 	preamble[crypted->blocksize] = preamble[crypted->blocksize - 2];
1171 	preamble[crypted->blocksize + 1] = preamble[crypted->blocksize - 1];
1172 
1173 	if (__ops_get_debug_level(__FILE__)) {
1174 		unsigned    i;
1175 
1176 		fprintf(stderr, "\npreamble: ");
1177 		for (i = 0; i < preamblesize; i++) {
1178 			fprintf(stderr, " 0x%02x", preamble[i]);
1179 		}
1180 		fprintf(stderr, "\n");
1181 	}
1182 
1183 	/* now construct MDC packet and add to the end of the buffer */
1184 	__ops_setup_memory_write(&mdcoutput, &mdc, mdcsize);
1185 	__ops_calc_mdc_hash(preamble, preamblesize, data, len, &hashed[0]);
1186 	__ops_write_mdc(mdcoutput, hashed);
1187 
1188 	if (__ops_get_debug_level(__FILE__)) {
1189 		unsigned    i;
1190 		size_t          sz_plaintext = len;
1191 		size_t          sz_mdc2 = 1 + 1 + OPS_SHA1_HASH_SIZE;
1192 		uint8_t  *digest;
1193 
1194 		(void) fprintf(stderr, "\nplaintext: ");
1195 		for (i = 0; i < sz_plaintext; i++) {
1196 			(void) fprintf(stderr, " 0x%02x", data[i]);
1197 		}
1198 		(void) fprintf(stderr, "\n");
1199 
1200 		(void) fprintf(stderr, "\nmdc: ");
1201 		digest = __ops_mem_data(mdc);
1202 		for (i = 0; i < sz_mdc2; i++) {
1203 			(void) fprintf(stderr, " 0x%02x", digest[i]);
1204 		}
1205 		(void) fprintf(stderr, "\n");
1206 	}
1207 
1208 	/* and write it out */
1209 	__ops_push_enc_crypt(output, crypted);
1210 	if (__ops_get_debug_level(__FILE__)) {
1211 		(void) fprintf(stderr,
1212 			"writing %" PRIsize "u + %u + %" PRIsize "u\n",
1213 			preamblesize, len, __ops_mem_len(mdc));
1214 	}
1215 	if (!__ops_write(output, preamble, preamblesize) ||
1216 	    !__ops_write(output, data, len) ||
1217 	    !__ops_write(output, __ops_mem_data(mdc), __ops_mem_len(mdc))) {
1218 		/* \todo fix cleanup here and in old code functions */
1219 		return 0;
1220 	}
1221 
1222 	__ops_writer_pop(output);
1223 
1224 	/* cleanup  */
1225 	__ops_teardown_memory_write(mdcoutput, mdc);
1226 	free(preamble);
1227 
1228 	return 1;
1229 }
1230 
1231 typedef struct {
1232 	int             fd;
1233 } writer_fd_t;
1234 
1235 static unsigned
1236 fd_writer(const uint8_t *src, unsigned len,
1237 	  __ops_error_t **errors,
1238 	  __ops_writer_t *writer)
1239 {
1240 	writer_fd_t	*writerfd;
1241 	int              n;
1242 
1243 	writerfd = __ops_writer_get_arg(writer);
1244 	n = write(writerfd->fd, src, len);
1245 	if (n == -1) {
1246 		OPS_SYSTEM_ERROR_1(errors, OPS_E_W_WRITE_FAILED, "write",
1247 				   "file descriptor %d", writerfd->fd);
1248 		return 0;
1249 	}
1250 	if ((unsigned) n != len) {
1251 		OPS_ERROR_1(errors, OPS_E_W_WRITE_TOO_SHORT,
1252 			    "file descriptor %d", writerfd->fd);
1253 		return 0;
1254 	}
1255 	return 1;
1256 }
1257 
1258 static void
1259 writer_fd_destroyer(__ops_writer_t *writer)
1260 {
1261 	free(__ops_writer_get_arg(writer));
1262 }
1263 
1264 /**
1265  * \ingroup Core_WritersFirst
1266  * \brief Write to a File
1267  *
1268  * Set the writer in output to be a stock writer that writes to a file
1269  * descriptor. If another writer has already been set, then that is
1270  * first destroyed.
1271  *
1272  * \param output The output structure
1273  * \param fd The file descriptor
1274  *
1275  */
1276 
1277 void
1278 __ops_writer_set_fd(__ops_output_t *output, int fd)
1279 {
1280 	writer_fd_t	*writer;
1281 
1282 	if ((writer = calloc(1, sizeof(*writer))) == NULL) {
1283 		(void) fprintf(stderr, "__ops_writer_set_fd: bad alloc\n");
1284 	} else {
1285 		writer->fd = fd;
1286 		__ops_writer_set(output, fd_writer, NULL, writer_fd_destroyer, writer);
1287 	}
1288 }
1289 
1290 static unsigned
1291 memory_writer(const uint8_t *src,
1292 		unsigned len,
1293 		__ops_error_t **errors,
1294 		__ops_writer_t *writer)
1295 {
1296 	__ops_memory_t   *mem;
1297 
1298 	__OPS_USED(errors);
1299 	mem = __ops_writer_get_arg(writer);
1300 	__ops_memory_add(mem, src, len);
1301 	return 1;
1302 }
1303 
1304 /**
1305  * \ingroup Core_WritersFirst
1306  * \brief Write to memory
1307  *
1308  * Set a memory writer.
1309  *
1310  * \param output The output structure
1311  * \param mem The memory structure
1312  * \note It is the caller's responsiblity to call __ops_memory_free(mem)
1313  * \sa __ops_memory_free()
1314  */
1315 
1316 void
1317 __ops_writer_set_memory(__ops_output_t *output, __ops_memory_t *mem)
1318 {
1319 	__ops_writer_set(output, memory_writer, NULL, NULL, mem);
1320 }
1321 
1322 /**************************************************************************/
1323 
1324 typedef struct {
1325 	__ops_hash_alg_t	 hash_alg;
1326 	__ops_hash_t		 hash;
1327 	uint8_t			*hashed;
1328 } skey_checksum_t;
1329 
1330 static unsigned
1331 skey_checksum_writer(const uint8_t *src,
1332 	const unsigned len,
1333 	__ops_error_t **errors,
1334 	__ops_writer_t *writer)
1335 {
1336 	skey_checksum_t	*sum;
1337 	unsigned	 ret = 1;
1338 
1339 	sum = __ops_writer_get_arg(writer);
1340 	/* add contents to hash */
1341 	sum->hash.add(&sum->hash, src, len);
1342 	/* write to next stacked writer */
1343 	ret = stacked_write(writer, src, len, errors);
1344 	/* tidy up and return */
1345 	return ret;
1346 }
1347 
1348 static unsigned
1349 skey_checksum_finaliser(__ops_error_t **errors, __ops_writer_t *writer)
1350 {
1351 	skey_checksum_t *sum;
1352 
1353 	sum = __ops_writer_get_arg(writer);
1354 	if (errors) {
1355 		printf("errors in skey_checksum_finaliser\n");
1356 	}
1357 	sum->hash.finish(&sum->hash, sum->hashed);
1358 	return 1;
1359 }
1360 
1361 static void
1362 skey_checksum_destroyer(__ops_writer_t *writer)
1363 {
1364 	skey_checksum_t *sum;
1365 
1366 	sum = __ops_writer_get_arg(writer);
1367 	free(sum);
1368 }
1369 
1370 /**
1371 \ingroup Core_WritersNext
1372 \param output
1373 \param seckey
1374 */
1375 void
1376 __ops_push_checksum_writer(__ops_output_t *output, __ops_seckey_t *seckey)
1377 {
1378 	/* XXX: push a SHA-1 checksum writer (and change s2k to 254). */
1379 	skey_checksum_t *sum;
1380 
1381 	if ((sum = calloc(1, sizeof(*sum))) == NULL) {
1382 		(void) fprintf(stderr,
1383 			"__ops_push_checksum_writer: bad alloc\n");
1384 	} else {
1385 		/* configure the arg */
1386 		sum->hash_alg = seckey->hash_alg;
1387 		sum->hashed = seckey->checkhash;
1388 		/* init the hash */
1389 		__ops_hash_any(&sum->hash, sum->hash_alg);
1390 		if (!sum->hash.init(&sum->hash)) {
1391 			(void) fprintf(stderr,
1392 				"__ops_push_checksum_writer: bad hash init\n");
1393 			/* just continue and die */
1394 			/* XXX - agc - no way to return failure */
1395 		}
1396 		__ops_writer_push(output, skey_checksum_writer,
1397 			skey_checksum_finaliser, skey_checksum_destroyer, sum);
1398 	}
1399 }
1400 
1401 /**************************************************************************/
1402 
1403 #define MAX_PARTIAL_DATA_LENGTH 1073741824
1404 
1405 typedef struct {
1406 	__ops_crypt_t	*crypt;
1407 	__ops_memory_t	*mem_data;
1408 	__ops_memory_t	*litmem;
1409 	__ops_output_t	*litoutput;
1410 	__ops_memory_t	*se_ip_mem;
1411 	__ops_output_t	*se_ip_out;
1412 	__ops_hash_t	 hash;
1413 } str_enc_se_ip_t;
1414 
1415 
1416 static unsigned
1417 str_enc_se_ip_writer(const uint8_t *src,
1418 			    unsigned len,
1419 			    __ops_error_t **errors,
1420 			    __ops_writer_t *writer);
1421 
1422 static unsigned
1423 str_enc_se_ip_finaliser(__ops_error_t **errors,
1424 			       __ops_writer_t * writer);
1425 
1426 static void     str_enc_se_ip_destroyer(__ops_writer_t *writer);
1427 
1428 /* */
1429 
1430 /**
1431 \ingroup Core_WritersNext
1432 \param output
1433 \param pubkey
1434 */
1435 void
1436 __ops_push_stream_enc_se_ip(__ops_output_t *output, const __ops_key_t *pubkey)
1437 {
1438 	__ops_pk_sesskey_t	*encrypted_pk_sesskey;
1439 	str_enc_se_ip_t		*se_ip;
1440 	const unsigned	 	 bufsz = 1024;
1441 	__ops_crypt_t		*encrypted;
1442 	uint8_t			*iv;
1443 
1444 	if ((se_ip = calloc(1, sizeof(*se_ip))) == NULL) {
1445 		(void) fprintf(stderr,
1446 			"__ops_push_stream_enc_se_ip: bad alloc\n");
1447 		return;
1448 	}
1449 	encrypted_pk_sesskey = __ops_create_pk_sesskey(pubkey);
1450 	__ops_write_pk_sesskey(output, encrypted_pk_sesskey);
1451 
1452 	/* Setup the se_ip */
1453 	if ((encrypted = calloc(1, sizeof(*encrypted))) == NULL) {
1454 		free(se_ip);
1455 		(void) fprintf(stderr,
1456 			"__ops_push_stream_enc_se_ip: bad alloc\n");
1457 		return;
1458 	}
1459 	__ops_crypt_any(encrypted, encrypted_pk_sesskey->symm_alg);
1460 	if ((iv = calloc(1, encrypted->blocksize)) == NULL) {
1461 		free(encrypted);
1462 		free(se_ip);
1463 		(void) fprintf(stderr,
1464 			"__ops_push_stream_enc_se_ip: bad alloc\n");
1465 		return;
1466 	}
1467 	encrypted->set_iv(encrypted, iv);
1468 	encrypted->set_crypt_key(encrypted, &encrypted_pk_sesskey->key[0]);
1469 	__ops_encrypt_init(encrypted);
1470 
1471 	se_ip->crypt = encrypted;
1472 
1473 	se_ip->mem_data = __ops_memory_new();
1474 	__ops_memory_init(se_ip->mem_data, bufsz);
1475 
1476 	se_ip->litmem = NULL;
1477 	se_ip->litoutput = NULL;
1478 
1479 	__ops_setup_memory_write(&se_ip->se_ip_out, &se_ip->se_ip_mem, bufsz);
1480 
1481 	/* And push writer on stack */
1482 	__ops_writer_push(output,
1483 			str_enc_se_ip_writer,
1484 			str_enc_se_ip_finaliser,
1485 			str_enc_se_ip_destroyer, se_ip);
1486 	/* tidy up */
1487 	free(encrypted_pk_sesskey);
1488 	free(iv);
1489 }
1490 
1491 
1492 /* calculate the partial data length */
1493 static unsigned
1494 __ops_partial_data_len(unsigned len)
1495 {
1496 	unsigned	mask;
1497 	int		i;
1498 
1499 	if (len == 0) {
1500 		(void) fprintf(stderr, "__ops_partial_data_len: 0 len\n");
1501 		return 0;
1502 	}
1503 	if (len > MAX_PARTIAL_DATA_LENGTH) {
1504 		return MAX_PARTIAL_DATA_LENGTH;
1505 	}
1506 	mask = MAX_PARTIAL_DATA_LENGTH;
1507 	for (i = 0; i <= 30; i++) {
1508 		if (mask & len) {
1509 			break;
1510 		}
1511 		mask >>= 1;
1512 	}
1513 	return mask;
1514 }
1515 
1516 static unsigned
1517 write_partial_len(__ops_output_t *output, unsigned len)
1518 {
1519 	/* len must be a power of 2 from 0 to 30 */
1520 	uint8_t	c;
1521 	int	i;
1522 
1523 	for (i = 0; i <= 30; i++) {
1524 		if ((len >> i) & 1) {
1525 			break;
1526 		}
1527 	}
1528 	c = 224 + i;
1529 	return __ops_write(output, &c, 1);
1530 }
1531 
1532 static unsigned
1533 stream_write_litdata(__ops_output_t *output,
1534 			const uint8_t *data,
1535 			unsigned len)
1536 {
1537 	size_t          pdlen;
1538 
1539 	while (len > 0) {
1540 		pdlen = __ops_partial_data_len(len);
1541 		write_partial_len(output, pdlen);
1542 		__ops_write(output, data, pdlen);
1543 		data += pdlen;
1544 		len -= pdlen;
1545 	}
1546 	return 1;
1547 }
1548 
1549 static unsigned
1550 stream_write_litdata_first(__ops_output_t *output,
1551 				const uint8_t *data,
1552 				unsigned len,
1553 				const __ops_litdata_type_t type)
1554 {
1555 	/* \todo add filename  */
1556 	/* \todo add date */
1557 	/* \todo do we need to check text data for <cr><lf> line endings ? */
1558 
1559 	size_t          sz_towrite;
1560 	size_t          sz_pd;
1561 
1562 	sz_towrite = 1 + 1 + 4 + len;
1563 	sz_pd = __ops_partial_data_len(sz_towrite);
1564 	if (sz_pd < 512) {
1565 		(void) fprintf(stderr,
1566 			"stream_write_litdata_first: bad sz_pd\n");
1567 		return 0;
1568 	}
1569 	__ops_write_ptag(output, OPS_PTAG_CT_LITDATA);
1570 	write_partial_len(output, sz_pd);
1571 	__ops_write_scalar(output, (unsigned)type, 1);
1572 	__ops_write_scalar(output, 0, 1);
1573 	__ops_write_scalar(output, 0, 4);
1574 	__ops_write(output, data, sz_pd - 6);
1575 
1576 	data += (sz_pd - 6);
1577 	sz_towrite -= sz_pd;
1578 
1579 	return stream_write_litdata(output, data, sz_towrite);
1580 }
1581 
1582 static unsigned
1583 stream_write_litdata_last(__ops_output_t *output,
1584 				const uint8_t *data,
1585 				unsigned len)
1586 {
1587 	__ops_write_length(output, len);
1588 	return __ops_write(output, data, len);
1589 }
1590 
1591 static unsigned
1592 stream_write_se_ip(__ops_output_t *output,
1593 			const uint8_t *data,
1594 			unsigned len,
1595 			str_enc_se_ip_t *se_ip)
1596 {
1597 	size_t          pdlen;
1598 
1599 	while (len > 0) {
1600 		pdlen = __ops_partial_data_len(len);
1601 		write_partial_len(output, pdlen);
1602 
1603 		__ops_push_enc_crypt(output, se_ip->crypt);
1604 		__ops_write(output, data, pdlen);
1605 		__ops_writer_pop(output);
1606 
1607 		se_ip->hash.add(&se_ip->hash, data, pdlen);
1608 
1609 		data += pdlen;
1610 		len -= pdlen;
1611 	}
1612 	return 1;
1613 }
1614 
1615 static unsigned
1616 stream_write_se_ip_first(__ops_output_t *output,
1617 			const uint8_t *data,
1618 			unsigned len,
1619 			str_enc_se_ip_t *se_ip)
1620 {
1621 	uint8_t	*preamble;
1622 	size_t	blocksize;
1623 	size_t 	preamblesize;
1624 	size_t 	sz_towrite;
1625 	size_t 	sz_pd;
1626 
1627 	blocksize = se_ip->crypt->blocksize;
1628 	preamblesize = blocksize + 2;
1629 	sz_towrite = preamblesize + 1 + len;
1630 	if ((preamble = calloc(1, preamblesize)) == NULL) {
1631 		(void) fprintf(stderr,
1632 			"stream_write_se_ip_first: bad alloc\n");
1633 		return 0;
1634 	}
1635 	sz_pd = __ops_partial_data_len(sz_towrite);
1636 	if (sz_pd < 512) {
1637 		free(preamble);
1638 		(void) fprintf(stderr,
1639 			"stream_write_se_ip_first: bad sz_pd\n");
1640 		return 0;
1641 	}
1642 	__ops_write_ptag(output, OPS_PTAG_CT_SE_IP_DATA);
1643 	write_partial_len(output, sz_pd);
1644 	__ops_write_scalar(output, SE_IP_DATA_VERSION, 1);
1645 	__ops_push_enc_crypt(output, se_ip->crypt);
1646 
1647 	__ops_random(preamble, blocksize);
1648 	preamble[blocksize] = preamble[blocksize - 2];
1649 	preamble[blocksize + 1] = preamble[blocksize - 1];
1650 	__ops_hash_any(&se_ip->hash, OPS_HASH_SHA1);
1651 	if (!se_ip->hash.init(&se_ip->hash)) {
1652 		free(preamble);
1653 		(void) fprintf(stderr,
1654 			"stream_write_se_ip_first: bad hash init\n");
1655 		return 0;
1656 	}
1657 	__ops_write(output, preamble, preamblesize);
1658 	se_ip->hash.add(&se_ip->hash, preamble, preamblesize);
1659 	__ops_write(output, data, sz_pd - preamblesize - 1);
1660 	se_ip->hash.add(&se_ip->hash, data, sz_pd - preamblesize - 1);
1661 	data += (sz_pd - preamblesize - 1);
1662 	sz_towrite -= sz_pd;
1663 	__ops_writer_pop(output);
1664 	stream_write_se_ip(output, data, sz_towrite, se_ip);
1665 	free(preamble);
1666 	return 1;
1667 }
1668 
1669 static unsigned
1670 stream_write_se_ip_last(__ops_output_t *output,
1671 			const uint8_t *data,
1672 			unsigned len,
1673 			str_enc_se_ip_t *se_ip)
1674 {
1675 	__ops_output_t	*mdcoutput;
1676 	__ops_memory_t	*mdcmem;
1677 	const size_t	 mdcsize = 1 + 1 + OPS_SHA1_HASH_SIZE;
1678 	uint8_t		 c;
1679 	uint8_t		 hashed[OPS_SHA1_HASH_SIZE];
1680 	size_t		 bufsize = len + mdcsize;
1681 
1682 	se_ip->hash.add(&se_ip->hash, data, len);
1683 
1684 	/* MDC packet tag */
1685 	c = MDC_PKT_TAG;
1686 	se_ip->hash.add(&se_ip->hash, &c, 1);
1687 
1688 	/* MDC packet len */
1689 	c = OPS_SHA1_HASH_SIZE;
1690 	se_ip->hash.add(&se_ip->hash, &c, 1);
1691 
1692 	/* finish */
1693 	se_ip->hash.finish(&se_ip->hash, hashed);
1694 
1695 	__ops_setup_memory_write(&mdcoutput, &mdcmem, mdcsize);
1696 	__ops_write_mdc(mdcoutput, hashed);
1697 
1698 	/* write length of last se_ip chunk */
1699 	__ops_write_length(output, bufsize);
1700 
1701 	/* encode everting */
1702 	__ops_push_enc_crypt(output, se_ip->crypt);
1703 
1704 	__ops_write(output, data, len);
1705 	__ops_write(output, __ops_mem_data(mdcmem), __ops_mem_len(mdcmem));
1706 
1707 	__ops_writer_pop(output);
1708 
1709 	__ops_teardown_memory_write(mdcoutput, mdcmem);
1710 
1711 	return 1;
1712 }
1713 
1714 static unsigned
1715 str_enc_se_ip_writer(const uint8_t *src,
1716 			    unsigned len,
1717 			    __ops_error_t **errors,
1718 			    __ops_writer_t *writer)
1719 {
1720 	str_enc_se_ip_t	*se_ip;
1721 	unsigned	 ret;
1722 	size_t           datalength;
1723 
1724 	se_ip = __ops_writer_get_arg(writer);
1725 	ret = 1;
1726 	if (se_ip->litoutput == NULL) {
1727 		/* first literal data chunk is not yet written */
1728 
1729 		__ops_memory_add(se_ip->mem_data, src, len);
1730 		datalength = __ops_mem_len(se_ip->mem_data);
1731 
1732 		/* 4.2.2.4. Partial Body Lengths */
1733 		/* The first partial length MUST be at least 512 octets long. */
1734 		if (datalength < 512) {
1735 			return 1;	/* will wait for more data or
1736 						 * end of stream             */
1737 		}
1738 		__ops_setup_memory_write(&se_ip->litoutput,
1739 				&se_ip->litmem, datalength + 32);
1740 		stream_write_litdata_first(se_ip->litoutput,
1741 				__ops_mem_data(se_ip->mem_data),
1742 				datalength,
1743 				OPS_LDT_BINARY);
1744 
1745 		stream_write_se_ip_first(se_ip->se_ip_out,
1746 				__ops_mem_data(se_ip->litmem),
1747 				__ops_mem_len(se_ip->litmem), se_ip);
1748 	} else {
1749 		stream_write_litdata(se_ip->litoutput, src, len);
1750 		stream_write_se_ip(se_ip->se_ip_out,
1751 				__ops_mem_data(se_ip->litmem),
1752 				__ops_mem_len(se_ip->litmem), se_ip);
1753 	}
1754 
1755 	/* now write memory to next writer */
1756 	ret = stacked_write(writer, __ops_mem_data(se_ip->se_ip_mem),
1757 				__ops_mem_len(se_ip->se_ip_mem), errors);
1758 
1759 	__ops_memory_clear(se_ip->litmem);
1760 	__ops_memory_clear(se_ip->se_ip_mem);
1761 
1762 	return ret;
1763 }
1764 
1765 /* write last chunk of data */
1766 static unsigned
1767 str_enc_se_ip_finaliser(__ops_error_t **errors, __ops_writer_t *writer)
1768 {
1769 	str_enc_se_ip_t	*se_ip;
1770 
1771 	se_ip = __ops_writer_get_arg(writer);
1772 	if (se_ip->litoutput == NULL) {
1773 		/* first literal data chunk was not written */
1774 		/* so we know the total length of data, write a simple packet */
1775 
1776 		/* create literal data packet from buffered data */
1777 		__ops_setup_memory_write(&se_ip->litoutput, &se_ip->litmem,
1778 				 __ops_mem_len(se_ip->mem_data) + 32);
1779 
1780 		__ops_write_litdata(se_ip->litoutput,
1781 			__ops_mem_data(se_ip->mem_data),
1782 			(const int)__ops_mem_len(se_ip->mem_data),
1783 			OPS_LDT_BINARY);
1784 
1785 		/* create SE IP packet set from this literal data */
1786 		__ops_write_se_ip_pktset(se_ip->se_ip_out,
1787 				__ops_mem_data(se_ip->litmem),
1788 				__ops_mem_len(se_ip->litmem),
1789 				se_ip->crypt);
1790 
1791 	} else {
1792 		/* finish writing */
1793 		stream_write_litdata_last(se_ip->litoutput, NULL, 0);
1794 		stream_write_se_ip_last(se_ip->se_ip_out,
1795 				__ops_mem_data(se_ip->litmem),
1796 				__ops_mem_len(se_ip->litmem), se_ip);
1797 	}
1798 
1799 	/* now write memory to next writer */
1800 	return stacked_write(writer, __ops_mem_data(se_ip->se_ip_mem),
1801 				 __ops_mem_len(se_ip->se_ip_mem), errors);
1802 }
1803 
1804 static void
1805 str_enc_se_ip_destroyer(__ops_writer_t *writer)
1806 {
1807 	str_enc_se_ip_t *se_ip;
1808 
1809 	se_ip = __ops_writer_get_arg(writer);
1810 	__ops_memory_free(se_ip->mem_data);
1811 	__ops_teardown_memory_write(se_ip->litoutput, se_ip->litmem);
1812 	__ops_teardown_memory_write(se_ip->se_ip_out, se_ip->se_ip_mem);
1813 
1814 	se_ip->crypt->decrypt_finish(se_ip->crypt);
1815 
1816 	free(se_ip->crypt);
1817 	free(se_ip);
1818 }
1819