Fix bug#1011.
[gnupg.git] / tools / gpgsplit.c
blob3f093c360234aa4843ad46be6973df04eaf9cc73
1 /* gpgsplit.c - An OpenPGP packet splitting tool
2 * Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <unistd.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #ifdef HAVE_DOSISH_SYSTEM
30 # include <fcntl.h> /* for setmode() */
31 #endif
32 #include <zlib.h>
33 #ifdef HAVE_BZIP2
34 #include <bzlib.h>
35 #endif /* HAVE_BZIP2 */
36 #if defined(__riscos__) && defined(USE_ZLIBRISCOS)
37 # include "zlib-riscos.h"
38 #endif
40 #define INCLUDED_BY_MAIN_MODULE 1
41 #include "util.h"
42 #include "openpgpdefs.h"
44 static int opt_verbose;
45 static const char *opt_prefix = "";
46 static int opt_uncompress;
47 static int opt_secret_to_public;
48 static int opt_no_split;
50 static void g10_exit( int rc );
51 static void split_packets (const char *fname);
54 enum cmd_and_opt_values {
55 aNull = 0,
56 oVerbose = 'v',
57 oPrefix = 'p',
58 oUncompress = 500,
59 oSecretToPublic,
60 oNoSplit,
62 aTest
66 static ARGPARSE_OPTS opts[] = {
68 { 301, NULL, 0, "@Options:\n " },
70 { oVerbose, "verbose", 0, "verbose" },
71 { oPrefix, "prefix", 2, "|STRING|Prepend filenames with STRING" },
72 { oUncompress, "uncompress", 0, "uncompress a packet"},
73 { oSecretToPublic, "secret-to-public", 0, "convert secret keys to public keys"},
74 { oNoSplit, "no-split", 0, "write to stdout and don't actually split"},
75 {0} };
78 static const char *
79 my_strusage (int level)
81 const char *p;
82 switch (level)
84 case 11: p = "gpgsplit (GnuPG)";
85 break;
86 case 13: p = VERSION; break;
87 case 17: p = PRINTABLE_OS_NAME; break;
88 case 19: p = "Please report bugs to <@EMAIL@>.\n"; break;
90 case 1:
91 case 40: p =
92 "Usage: gpgsplit [options] [files] (-h for help)";
93 break;
94 case 41: p =
95 "Syntax: gpgsplit [options] [files]\n"
96 "Split an OpenPGP message into packets\n";
97 break;
99 default: p = NULL;
101 return p;
107 main (int argc, char **argv)
109 ARGPARSE_ARGS pargs;
111 #ifdef HAVE_DOSISH_SYSTEM
112 setmode( fileno(stdin), O_BINARY );
113 setmode( fileno(stdout), O_BINARY );
114 #endif
115 log_set_prefix ("gpgsplit", JNLIB_LOG_WITH_PREFIX);
116 set_strusage (my_strusage);
118 pargs.argc = &argc;
119 pargs.argv = &argv;
120 pargs.flags= 1; /* do not remove the args */
121 while (optfile_parse( NULL, NULL, NULL, &pargs, opts))
123 switch (pargs.r_opt)
125 case oVerbose: opt_verbose = 1; break;
126 case oPrefix: opt_prefix = pargs.r.ret_str; break;
127 case oUncompress: opt_uncompress = 1; break;
128 case oSecretToPublic: opt_secret_to_public = 1; break;
129 case oNoSplit: opt_no_split = 1; break;
130 default : pargs.err = 2; break;
134 if (log_get_errorcount(0))
135 g10_exit (2);
137 if (!argc)
138 split_packets (NULL);
139 else
141 for ( ;argc; argc--, argv++)
142 split_packets (*argv);
145 g10_exit (0);
146 return 0;
150 static void
151 g10_exit (int rc)
153 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
154 exit(rc );
157 static const char *
158 pkttype_to_string (int pkttype)
160 const char *s;
162 switch (pkttype)
164 case PKT_PUBKEY_ENC : s = "pk_enc"; break;
165 case PKT_SIGNATURE : s = "sig"; break;
166 case PKT_SYMKEY_ENC : s = "sym_enc"; break;
167 case PKT_ONEPASS_SIG : s = "onepass_sig"; break;
168 case PKT_SECRET_KEY : s = "secret_key"; break;
169 case PKT_PUBLIC_KEY : s = "public_key"; break;
170 case PKT_SECRET_SUBKEY : s = "secret_subkey"; break;
171 case PKT_COMPRESSED :
172 s = opt_uncompress? "uncompressed":"compressed";
173 break;
174 case PKT_ENCRYPTED : s = "encrypted"; break;
175 case PKT_MARKER : s = "marker"; break;
176 case PKT_PLAINTEXT : s = "plaintext"; break;
177 case PKT_RING_TRUST : s = "ring_trust"; break;
178 case PKT_USER_ID : s = "user_id"; break;
179 case PKT_PUBLIC_SUBKEY : s = "public_subkey"; break;
180 case PKT_OLD_COMMENT : s = "old_comment"; break;
181 case PKT_ATTRIBUTE : s = "attribute"; break;
182 case PKT_ENCRYPTED_MDC : s = "encrypted_mdc"; break;
183 case PKT_MDC : s = "mdc"; break;
184 case PKT_COMMENT : s = "comment"; break;
185 case PKT_GPG_CONTROL : s = "gpg_control"; break;
186 default: s = "unknown"; break;
188 return s;
193 * Create a new filename and a return a pointer to a statically
194 * allocated buffer
196 static char *
197 create_filename (int pkttype)
199 static unsigned int partno = 0;
200 static char *name;
202 if (!name)
203 name = xmalloc (strlen (opt_prefix) + 100 );
205 assert (pkttype < 1000 && pkttype >= 0 );
206 partno++;
207 sprintf (name, "%s%06u-%03d" EXTSEP_S "%.40s",
208 opt_prefix, partno, pkttype, pkttype_to_string (pkttype));
209 return name;
212 static int
213 read_u16 (FILE *fp, size_t *rn)
215 int c;
217 if ( (c = getc (fp)) == EOF )
218 return -1;
219 *rn = c << 8;
220 if ( (c = getc (fp)) == EOF )
221 return -1;
222 *rn |= c;
223 return 0;
226 static int
227 read_u32 (FILE *fp, unsigned long *rn)
229 size_t tmp;
231 if (read_u16 (fp, &tmp))
232 return -1;
233 *rn = tmp << 16;
234 if (read_u16 (fp, &tmp))
235 return -1;
236 *rn |= tmp;
237 return 0;
240 static int
241 write_old_header (FILE *fp, int pkttype, unsigned int len)
243 int ctb = (0x80 | ((pkttype & 15)<<2));
245 if (len < 256)
247 else if (len < 65536)
248 ctb |= 1;
249 else
250 ctb |= 2;
252 if ( putc ( ctb, fp) == EOF )
253 return -1;
255 if ( (ctb & 2) )
257 if (putc ((len>>24), fp) == EOF)
258 return -1;
259 if (putc ((len>>16), fp) == EOF)
260 return -1;
262 if ( (ctb & 3) )
264 if (putc ((len>>8), fp) == EOF)
265 return -1;
267 if (putc ((len&0xff), fp) == EOF)
268 return -1;
269 return 0;
272 static int
273 write_new_header (FILE *fp, int pkttype, unsigned int len)
275 if ( putc ((0xc0 | (pkttype & 0x3f)), fp) == EOF )
276 return -1;
278 if (len < 192)
280 if (putc (len, fp) == EOF)
281 return -1;
283 else if (len < 8384)
285 len -= 192;
286 if (putc ((len/256)+192, fp) == EOF)
287 return -1;
288 if (putc ((len%256), fp) == EOF)
289 return -1;
291 else
293 if (putc ( 0xff, fp) == EOF)
294 return -1;
295 if (putc ( (len >> 24), fp) == EOF)
296 return -1;
297 if (putc ( (len >> 16), fp) == EOF)
298 return -1;
299 if (putc ( (len >> 8), fp) == EOF)
300 return -1;
301 if (putc ( (len & 0xff), fp) == EOF)
302 return -1;
304 return 0;
307 /* Return the length of the public key given BUF of BUFLEN with a
308 secret key. */
309 static int
310 public_key_length (const unsigned char *buf, size_t buflen)
312 const unsigned char *s;
313 int nmpis;
315 /* byte version number (3 or 4)
316 u32 creation time
317 [u16 valid days (version 3 only)]
318 byte algorithm
319 n MPIs (n and e) */
320 if (!buflen)
321 return 0;
322 if (buf[0] < 2 || buf[0] > 4)
323 return 0; /* wrong version number */
324 if (buflen < (buf[0] == 4? 6:8))
325 return 0;
326 s = buf + (buf[0] == 4? 6:8);
327 buflen -= (buf[0] == 4? 6:8);
328 switch (s[-1])
330 case 1:
331 case 2:
332 case 3:
333 nmpis = 2;
334 break;
335 case 16:
336 case 20:
337 nmpis = 3;
338 break;
339 case 17:
340 nmpis = 4;
341 break;
342 default:
343 return 0;
346 for (; nmpis; nmpis--)
348 unsigned int nbits, nbytes;
350 if (buflen < 2)
351 return 0;
352 nbits = (s[0] << 8) | s[1];
353 s += 2; buflen -= 2;
354 nbytes = (nbits+7) / 8;
355 if (buflen < nbytes)
356 return 0;
357 s += nbytes; buflen -= nbytes;
360 return s - buf;
363 static int
364 handle_zlib(int algo,FILE *fpin,FILE *fpout)
366 z_stream zs;
367 byte *inbuf, *outbuf;
368 unsigned int inbufsize, outbufsize;
369 int c,zinit_done, zrc, nread, count;
370 size_t n;
372 memset (&zs, 0, sizeof zs);
373 inbufsize = 2048;
374 inbuf = xmalloc (inbufsize);
375 outbufsize = 8192;
376 outbuf = xmalloc (outbufsize);
377 zs.avail_in = 0;
378 zinit_done = 0;
382 if (zs.avail_in < inbufsize)
384 n = zs.avail_in;
385 if (!n)
386 zs.next_in = (Bytef *) inbuf;
387 count = inbufsize - n;
388 for (nread=0;
389 nread < count && (c=getc (fpin)) != EOF;
390 nread++)
391 inbuf[n+nread] = c;
393 n += nread;
394 if (nread < count && algo == 1)
396 inbuf[n] = 0xFF; /* chew dummy byte */
397 n++;
399 zs.avail_in = n;
401 zs.next_out = (Bytef *) outbuf;
402 zs.avail_out = outbufsize;
404 if (!zinit_done)
406 zrc = (algo == 1? inflateInit2 ( &zs, -13)
407 : inflateInit ( &zs ));
408 if (zrc != Z_OK)
410 log_fatal ("zlib problem: %s\n", zs.msg? zs.msg :
411 zrc == Z_MEM_ERROR ? "out of core" :
412 zrc == Z_VERSION_ERROR ?
413 "invalid lib version" :
414 "unknown error" );
416 zinit_done = 1;
418 else
420 #ifdef Z_SYNC_FLUSH
421 zrc = inflate (&zs, Z_SYNC_FLUSH);
422 #else
423 zrc = inflate (&zs, Z_PARTIAL_FLUSH);
424 #endif
425 if (zrc == Z_STREAM_END)
426 ; /* eof */
427 else if (zrc != Z_OK && zrc != Z_BUF_ERROR)
429 if (zs.msg)
430 log_fatal ("zlib inflate problem: %s\n", zs.msg );
431 else
432 log_fatal ("zlib inflate problem: rc=%d\n", zrc );
434 for (n=0; n < outbufsize - zs.avail_out; n++)
436 if (putc (outbuf[n], fpout) == EOF )
437 return 1;
441 while (zrc != Z_STREAM_END && zrc != Z_BUF_ERROR);
443 int i;
445 fputs ("Left over bytes:", stderr);
446 for (i=0; i < zs.avail_in; i++)
447 fprintf (stderr, " %02X", zs.next_in[i]);
448 putc ('\n', stderr);
451 inflateEnd (&zs);
453 return 0;
456 #ifdef HAVE_BZIP2
457 static int
458 handle_bzip2(int algo,FILE *fpin,FILE *fpout)
460 bz_stream bzs;
461 byte *inbuf, *outbuf;
462 unsigned int inbufsize, outbufsize;
463 int c,zinit_done, zrc, nread, count;
464 size_t n;
466 memset (&bzs, 0, sizeof bzs);
467 inbufsize = 2048;
468 inbuf = xmalloc (inbufsize);
469 outbufsize = 8192;
470 outbuf = xmalloc (outbufsize);
471 bzs.avail_in = 0;
472 zinit_done = 0;
476 if (bzs.avail_in < inbufsize)
478 n = bzs.avail_in;
479 if (!n)
480 bzs.next_in = inbuf;
481 count = inbufsize - n;
482 for (nread=0;
483 nread < count && (c=getc (fpin)) != EOF;
484 nread++)
485 inbuf[n+nread] = c;
487 n += nread;
488 if (nread < count && algo == 1)
490 inbuf[n] = 0xFF; /* chew dummy byte */
491 n++;
493 bzs.avail_in = n;
495 bzs.next_out = outbuf;
496 bzs.avail_out = outbufsize;
498 if (!zinit_done)
500 zrc = BZ2_bzDecompressInit(&bzs,0,0);
501 if (zrc != BZ_OK)
502 log_fatal ("bz2lib problem: %d\n",zrc);
503 zinit_done = 1;
505 else
507 zrc = BZ2_bzDecompress(&bzs);
508 if (zrc == BZ_STREAM_END)
509 ; /* eof */
510 else if (zrc != BZ_OK && zrc != BZ_PARAM_ERROR)
511 log_fatal ("bz2lib inflate problem: %d\n", zrc );
512 for (n=0; n < outbufsize - bzs.avail_out; n++)
514 if (putc (outbuf[n], fpout) == EOF )
515 return 1;
519 while (zrc != BZ_STREAM_END && zrc != BZ_PARAM_ERROR);
520 BZ2_bzDecompressEnd(&bzs);
522 return 0;
524 #endif /* HAVE_BZIP2 */
526 /* hdr must point to a buffer large enough to hold all header bytes */
527 static int
528 write_part (FILE *fpin, unsigned long pktlen,
529 int pkttype, int partial, unsigned char *hdr, size_t hdrlen)
531 FILE *fpout;
532 int c, first;
533 unsigned char *p;
534 const char *outname = create_filename (pkttype);
536 #if defined(__riscos__) && defined(USE_ZLIBRISCOS)
537 static int initialized = 0;
539 if (!initialized)
540 initialized = riscos_load_module("ZLib", zlib_path, 1);
541 #endif
542 if (opt_no_split)
543 fpout = stdout;
544 else
546 if (opt_verbose)
547 log_info ("writing `%s'\n", outname);
548 fpout = fopen (outname, "wb");
549 if (!fpout)
551 log_error ("error creating `%s': %s\n", outname, strerror(errno));
552 /* stop right now, otherwise we would mess up the sequence
553 of the part numbers */
554 g10_exit (1);
558 if (opt_secret_to_public
559 && (pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY))
561 unsigned char *blob = xmalloc (pktlen);
562 int i, len;
564 pkttype = pkttype == PKT_SECRET_KEY? PKT_PUBLIC_KEY:PKT_PUBLIC_SUBKEY;
566 for (i=0; i < pktlen; i++)
568 c = getc (fpin);
569 if (c == EOF)
570 goto read_error;
571 blob[i] = c;
573 len = public_key_length (blob, pktlen);
574 if (!len)
576 log_error ("error calcualting public key length\n");
577 g10_exit (1);
579 if ( (hdr[0] & 0x40) )
581 if (write_new_header (fpout, pkttype, len))
582 goto write_error;
584 else
586 if (write_old_header (fpout, pkttype, len))
587 goto write_error;
590 for (i=0; i < len; i++)
592 if ( putc (blob[i], fpout) == EOF )
593 goto write_error;
596 goto ready;
600 if (!opt_uncompress)
602 for (p=hdr; hdrlen; p++, hdrlen--)
604 if ( putc (*p, fpout) == EOF )
605 goto write_error;
609 first = 1;
610 while (partial)
612 size_t partlen;
614 if (partial == 1)
615 { /* openpgp */
616 if (first )
618 c = pktlen;
619 assert( c >= 224 && c < 255 );
620 first = 0;
622 else if ((c = getc (fpin)) == EOF )
623 goto read_error;
624 else
625 hdr[hdrlen++] = c;
627 if (c < 192)
629 pktlen = c;
630 partial = 0; /* (last segment may follow) */
632 else if (c < 224 )
634 pktlen = (c - 192) * 256;
635 if ((c = getc (fpin)) == EOF)
636 goto read_error;
637 hdr[hdrlen++] = c;
638 pktlen += c + 192;
639 partial = 0;
641 else if (c == 255)
643 if (read_u32 (fpin, &pktlen))
644 goto read_error;
645 hdr[hdrlen++] = pktlen >> 24;
646 hdr[hdrlen++] = pktlen >> 16;
647 hdr[hdrlen++] = pktlen >> 8;
648 hdr[hdrlen++] = pktlen;
649 partial = 0;
651 else
652 { /* next partial body length */
653 for (p=hdr; hdrlen; p++, hdrlen--)
655 if ( putc (*p, fpout) == EOF )
656 goto write_error;
658 partlen = 1 << (c & 0x1f);
659 for (; partlen; partlen--)
661 if ((c = getc (fpin)) == EOF)
662 goto read_error;
663 if ( putc (c, fpout) == EOF )
664 goto write_error;
668 else if (partial == 2)
669 { /* old gnupg */
670 assert (!pktlen);
671 if ( read_u16 (fpin, &partlen) )
672 goto read_error;
673 hdr[hdrlen++] = partlen >> 8;
674 hdr[hdrlen++] = partlen;
675 for (p=hdr; hdrlen; p++, hdrlen--)
677 if ( putc (*p, fpout) == EOF )
678 goto write_error;
680 if (!partlen)
681 partial = 0; /* end of packet */
682 for (; partlen; partlen--)
684 c = getc (fpin);
685 if (c == EOF)
686 goto read_error;
687 if ( putc (c, fpout) == EOF )
688 goto write_error;
691 else
692 { /* compressed: read to end */
693 pktlen = 0;
694 partial = 0;
695 hdrlen = 0;
696 if (opt_uncompress)
698 if ((c = getc (fpin)) == EOF)
699 goto read_error;
701 if(c==1 || c==2)
703 if(handle_zlib(c,fpin,fpout))
704 goto write_error;
706 #ifdef HAVE_BZIP2
707 else if(c==3)
709 if(handle_bzip2(c,fpin,fpout))
710 goto write_error;
712 #endif /* HAVE_BZIP2 */
713 else
715 log_error("invalid compression algorithm (%d)\n",c);
716 goto read_error;
719 else
721 while ( (c=getc (fpin)) != EOF )
723 if ( putc (c, fpout) == EOF )
724 goto write_error;
727 if (!feof (fpin))
728 goto read_error;
732 for (p=hdr; hdrlen; p++, hdrlen--)
734 if ( putc (*p, fpout) == EOF )
735 goto write_error;
738 /* standard packet or last segment of partial length encoded packet */
739 for (; pktlen; pktlen--)
741 c = getc (fpin);
742 if (c == EOF)
743 goto read_error;
744 if ( putc (c, fpout) == EOF )
745 goto write_error;
748 ready:
749 if ( !opt_no_split && fclose (fpout) )
750 log_error ("error closing `%s': %s\n", outname, strerror (errno));
751 return 0;
753 write_error:
754 log_error ("error writing `%s': %s\n", outname, strerror (errno));
755 if (!opt_no_split)
756 fclose (fpout);
757 return 2;
759 read_error:
760 if (!opt_no_split)
762 int save = errno;
763 fclose (fpout);
764 errno = save;
766 return -1;
771 static int
772 do_split (FILE *fp)
774 int c, ctb, pkttype;
775 unsigned long pktlen = 0;
776 int partial = 0;
777 unsigned char header[20];
778 int header_idx = 0;
780 ctb = getc (fp);
781 if (ctb == EOF)
782 return 3; /* ready */
783 header[header_idx++] = ctb;
785 if (!(ctb & 0x80))
787 log_error("invalid CTB %02x\n", ctb );
788 return 1;
790 if ( (ctb & 0x40) )
791 { /* new CTB */
792 pkttype = (ctb & 0x3f);
793 if( (c = getc (fp)) == EOF )
794 return -1;
795 header[header_idx++] = c;
797 if ( c < 192 )
798 pktlen = c;
799 else if ( c < 224 )
801 pktlen = (c - 192) * 256;
802 if( (c = getc (fp)) == EOF )
803 return -1;
804 header[header_idx++] = c;
805 pktlen += c + 192;
807 else if ( c == 255 )
809 if (read_u32 (fp, &pktlen))
810 return -1;
811 header[header_idx++] = pktlen >> 24;
812 header[header_idx++] = pktlen >> 16;
813 header[header_idx++] = pktlen >> 8;
814 header[header_idx++] = pktlen;
816 else
817 { /* partial body length */
818 pktlen = c;
819 partial = 1;
822 else
824 int lenbytes;
826 pkttype = (ctb>>2)&0xf;
827 lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
828 if (!lenbytes )
830 pktlen = 0; /* don't know the value */
831 if( pkttype == PKT_COMPRESSED )
832 partial = 3;
833 else
834 partial = 2; /* the old GnuPG partial length encoding */
836 else
838 for ( ; lenbytes; lenbytes-- )
840 pktlen <<= 8;
841 if( (c = getc (fp)) == EOF )
842 return -1;
843 header[header_idx++] = c;
845 pktlen |= c;
850 return write_part (fp, pktlen, pkttype, partial, header, header_idx);
854 static void
855 split_packets (const char *fname)
857 FILE *fp;
858 int rc;
860 if (!fname || !strcmp (fname, "-"))
862 fp = stdin;
863 fname = "-";
865 else if ( !(fp = fopen (fname,"rb")) )
867 log_error ("can't open `%s': %s\n", fname, strerror (errno));
868 return;
871 while ( !(rc = do_split (fp)) )
873 if ( rc > 0 )
874 ; /* error already handled */
875 else if ( ferror (fp) )
876 log_error ("error reading `%s': %s\n", fname, strerror (errno));
877 else
878 log_error ("premature EOF while reading `%s'\n", fname );
880 if ( fp != stdin )
881 fclose (fp);