chiark / gitweb /
gnupg2 (2.1.17-3) unstable; urgency=medium
[gnupg2.git] / g10 / build-packet.c
1 /* build-packet.c - assemble packets and write them
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3  *               2006, 2010, 2011  Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26
27 #include "gpg.h"
28 #include "util.h"
29 #include "packet.h"
30 #include "status.h"
31 #include "iobuf.h"
32 #include "i18n.h"
33 #include "options.h"
34 #include "host2net.h"
35
36 static int do_user_id( IOBUF out, int ctb, PKT_user_id *uid );
37 static int do_key (iobuf_t out, int ctb, PKT_public_key *pk);
38 static int do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc );
39 static int do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc );
40 static u32 calc_plaintext( PKT_plaintext *pt );
41 static int do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt );
42 static int do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed );
43 static int do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed );
44 static int do_compressed( IOBUF out, int ctb, PKT_compressed *cd );
45 static int do_signature( IOBUF out, int ctb, PKT_signature *sig );
46 static int do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops );
47
48 static int calc_header_length( u32 len, int new_ctb );
49 static int write_16(IOBUF inp, u16 a);
50 static int write_32(IOBUF inp, u32 a);
51 static int write_header( IOBUF out, int ctb, u32 len );
52 static int write_sign_packet_header( IOBUF out, int ctb, u32 len );
53 static int write_header2( IOBUF out, int ctb, u32 len, int hdrlen );
54 static int write_new_header( IOBUF out, int ctb, u32 len, int hdrlen );
55
56 /* Returns 1 if CTB is a new format ctb and 0 if CTB is an old format
57    ctb.  */
58 static int
59 ctb_new_format_p (int ctb)
60 {
61   /* Bit 7 must always be set.  */
62   log_assert ((ctb & (1 << 7)));
63   /* Bit 6 indicates whether the packet is a new format packet.  */
64   return (ctb & (1 << 6));
65 }
66
67 /* Extract the packet type from a CTB.  */
68 static int
69 ctb_pkttype (int ctb)
70 {
71   if (ctb_new_format_p (ctb))
72     /* Bits 0 through 5 are the packet type.  */
73     return (ctb & ((1 << 6) - 1));
74   else
75     /* Bits 2 through 5 are the packet type.  */
76     return (ctb & ((1 << 6) - 1)) >> 2;
77 }
78
79 /****************
80  * Build a packet and write it to INP
81  * Returns: 0 := okay
82  *         >0 := error
83  * Note: Caller must free the packet
84  */
85 int
86 build_packet( IOBUF out, PACKET *pkt )
87 {
88     int new_ctb=0, rc=0, ctb;
89     int pkttype;
90
91     if( DBG_PACKET )
92         log_debug("build_packet() type=%d\n", pkt->pkttype );
93     log_assert( pkt->pkt.generic );
94
95     switch ((pkttype = pkt->pkttype))
96       {
97       case PKT_PUBLIC_KEY:
98         if (pkt->pkt.public_key->seckey_info)
99           pkttype = PKT_SECRET_KEY;
100         break;
101       case PKT_PUBLIC_SUBKEY:
102         if (pkt->pkt.public_key->seckey_info)
103           pkttype = PKT_SECRET_SUBKEY;
104         break;
105       case PKT_PLAINTEXT: new_ctb = pkt->pkt.plaintext->new_ctb; break;
106       case PKT_ENCRYPTED:
107       case PKT_ENCRYPTED_MDC: new_ctb = pkt->pkt.encrypted->new_ctb; break;
108       case PKT_COMPRESSED:new_ctb = pkt->pkt.compressed->new_ctb; break;
109       case PKT_USER_ID:
110         if( pkt->pkt.user_id->attrib_data )
111           pkttype = PKT_ATTRIBUTE;
112         break;
113       default: break;
114       }
115
116     if( new_ctb || pkttype > 15 ) /* new format */
117         ctb = 0xc0 | (pkttype & 0x3f);
118     else
119         ctb = 0x80 | ((pkttype & 15)<<2);
120     switch( pkttype )
121       {
122       case PKT_ATTRIBUTE:
123       case PKT_USER_ID:
124         rc = do_user_id( out, ctb, pkt->pkt.user_id );
125         break;
126       case PKT_OLD_COMMENT:
127       case PKT_COMMENT:
128         /*
129           Ignore these.  Theoretically, this will never be called as
130           we have no way to output comment packets any longer, but
131           just in case there is some code path that would end up
132           outputting a comment that was written before comments were
133           dropped (in the public key?) this is a no-op.
134         */
135         break;
136       case PKT_PUBLIC_SUBKEY:
137       case PKT_PUBLIC_KEY:
138       case PKT_SECRET_SUBKEY:
139       case PKT_SECRET_KEY:
140         rc = do_key (out, ctb, pkt->pkt.public_key);
141         break;
142       case PKT_SYMKEY_ENC:
143         rc = do_symkey_enc( out, ctb, pkt->pkt.symkey_enc );
144         break;
145       case PKT_PUBKEY_ENC:
146         rc = do_pubkey_enc( out, ctb, pkt->pkt.pubkey_enc );
147         break;
148       case PKT_PLAINTEXT:
149         rc = do_plaintext( out, ctb, pkt->pkt.plaintext );
150         break;
151       case PKT_ENCRYPTED:
152         rc = do_encrypted( out, ctb, pkt->pkt.encrypted );
153         break;
154       case PKT_ENCRYPTED_MDC:
155         rc = do_encrypted_mdc( out, ctb, pkt->pkt.encrypted );
156         break;
157       case PKT_COMPRESSED:
158         rc = do_compressed( out, ctb, pkt->pkt.compressed );
159         break;
160       case PKT_SIGNATURE:
161         rc = do_signature( out, ctb, pkt->pkt.signature );
162         break;
163       case PKT_ONEPASS_SIG:
164         rc = do_onepass_sig( out, ctb, pkt->pkt.onepass_sig );
165         break;
166       case PKT_RING_TRUST:
167         break; /* ignore it (keyring.c does write it directly)*/
168       case PKT_MDC: /* we write it directly, so we should never see it here. */
169       default:
170         log_bug("invalid packet type in build_packet()\n");
171         break;
172       }
173
174     return rc;
175 }
176
177
178 /*
179  * Write the mpi A to OUT.
180  */
181 gpg_error_t
182 gpg_mpi_write (iobuf_t out, gcry_mpi_t a)
183 {
184   int rc;
185
186   if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
187     {
188       unsigned int nbits;
189       const unsigned char *p;
190       unsigned char lenhdr[2];
191
192       /* gcry_log_debugmpi ("a", a); */
193       p = gcry_mpi_get_opaque (a, &nbits);
194       if (p)
195         {
196           /* Strip leading zero bits.  */
197           for (; nbits >= 8 && !*p; p++, nbits -= 8)
198             ;
199           if (nbits >= 8 && !(*p & 0x80))
200             if (--nbits >= 7 && !(*p & 0x40))
201               if (--nbits >= 6 && !(*p & 0x20))
202                 if (--nbits >= 5 && !(*p & 0x10))
203                   if (--nbits >= 4 && !(*p & 0x08))
204                     if (--nbits >= 3 && !(*p & 0x04))
205                       if (--nbits >= 2 && !(*p & 0x02))
206                         if (--nbits >= 1 && !(*p & 0x01))
207                           --nbits;
208         }
209       /* gcry_log_debug ("   [%u bit]\n", nbits); */
210       /* gcry_log_debughex (" ", p, (nbits+7)/8); */
211       lenhdr[0] = nbits >> 8;
212       lenhdr[1] = nbits;
213       rc = iobuf_write (out, lenhdr, 2);
214       if (!rc && p)
215         rc = iobuf_write (out, p, (nbits+7)/8);
216     }
217   else
218     {
219       char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
220       size_t nbytes;
221
222       nbytes = DIM(buffer);
223       rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
224       if( !rc )
225         rc = iobuf_write( out, buffer, nbytes );
226       else if (gpg_err_code(rc) == GPG_ERR_TOO_SHORT )
227         {
228           log_info ("mpi too large (%u bits)\n", gcry_mpi_get_nbits (a));
229           /* The buffer was too small. We better tell the user about the MPI. */
230           rc = gpg_error (GPG_ERR_TOO_LARGE);
231         }
232     }
233
234   return rc;
235 }
236
237
238 /*
239  * Write an opaque MPI to the output stream without length info.
240  */
241 gpg_error_t
242 gpg_mpi_write_nohdr (iobuf_t out, gcry_mpi_t a)
243 {
244   int rc;
245
246   if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
247     {
248       unsigned int nbits;
249       const void *p;
250
251       p = gcry_mpi_get_opaque (a, &nbits);
252       rc = p ? iobuf_write (out, p, (nbits+7)/8) : 0;
253     }
254   else
255     rc = gpg_error (GPG_ERR_BAD_MPI);
256
257   return rc;
258 }
259
260
261 /* Calculate the length of a packet described by PKT.  */
262 u32
263 calc_packet_length( PACKET *pkt )
264 {
265     u32 n=0;
266     int new_ctb = 0;
267
268     log_assert (pkt->pkt.generic);
269     switch( pkt->pkttype ) {
270       case PKT_PLAINTEXT:
271         n = calc_plaintext( pkt->pkt.plaintext );
272         new_ctb = pkt->pkt.plaintext->new_ctb;
273         break;
274       case PKT_ATTRIBUTE:
275       case PKT_USER_ID:
276       case PKT_COMMENT:
277       case PKT_PUBLIC_KEY:
278       case PKT_SECRET_KEY:
279       case PKT_SYMKEY_ENC:
280       case PKT_PUBKEY_ENC:
281       case PKT_ENCRYPTED:
282       case PKT_SIGNATURE:
283       case PKT_ONEPASS_SIG:
284       case PKT_RING_TRUST:
285       case PKT_COMPRESSED:
286       default:
287         log_bug("invalid packet type in calc_packet_length()");
288         break;
289     }
290
291     n += calc_header_length(n, new_ctb);
292     return n;
293 }
294
295
296 static gpg_error_t
297 write_fake_data (IOBUF out, gcry_mpi_t a)
298 {
299   unsigned int n;
300   void *p;
301
302   if (!a)
303     return 0;
304   if (!gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
305     return 0; /* e.g. due to generating a key with wrong usage.  */
306   p = gcry_mpi_get_opaque ( a, &n);
307   if (!p)
308     return 0; /* For example due to a read error in
309                  parse-packet.c:read_rest.  */
310   return iobuf_write (out, p, (n+7)/8 );
311 }
312
313
314 /* Serialize the user id (RFC 4880, Section 5.11) or the user
315    attribute UID (Section 5.12) and write it to OUT.
316
317    CTB is the serialization's CTB.  It specifies the header format and
318    the packet's type.  The header length must not be set.  */
319 static int
320 do_user_id( IOBUF out, int ctb, PKT_user_id *uid )
321 {
322   int rc;
323
324   log_assert (ctb_pkttype (ctb) == PKT_USER_ID
325               || ctb_pkttype (ctb) == PKT_ATTRIBUTE);
326
327   if (uid->attrib_data)
328     {
329       write_header(out, ctb, uid->attrib_len);
330       rc = iobuf_write( out, uid->attrib_data, uid->attrib_len );
331     }
332   else
333     {
334       write_header2( out, ctb, uid->len, 0 );
335       rc = iobuf_write( out, uid->name, uid->len );
336     }
337   return rc;
338 }
339
340
341 /* Serialize the key (RFC 4880, Section 5.5) described by PK and write
342    it to OUT.
343
344    This function serializes both primary keys and subkeys with or
345    without a secret part.
346
347    CTB is the serialization's CTB.  It specifies the header format and
348    the packet's type.  The header length must not be set.
349
350    PK->VERSION specifies the serialization format.  A value of 0 means
351    to use the default version.  Currently, only version 4 packets are
352    supported.
353  */
354 static int
355 do_key (iobuf_t out, int ctb, PKT_public_key *pk)
356 {
357   gpg_error_t err = 0;
358   /* The length of the body is stored in the packet's header, which
359      occurs before the body.  Unfortunately, we don't know the length
360      of the packet's body until we've written all of the data!  To
361      work around this, we first write the data into this temporary
362      buffer, then generate the header, and finally copy the contents
363      of this buffer to OUT.  */
364   iobuf_t a = iobuf_temp();
365   int i, nskey, npkey;
366
367   log_assert (pk->version == 0 || pk->version == 4);
368   log_assert (ctb_pkttype (ctb) == PKT_PUBLIC_KEY
369               || ctb_pkttype (ctb) == PKT_PUBLIC_SUBKEY
370               || ctb_pkttype (ctb) == PKT_SECRET_KEY
371               || ctb_pkttype (ctb) == PKT_SECRET_SUBKEY);
372
373   /* Write the version number - if none is specified, use 4 */
374   if ( !pk->version )
375     iobuf_put ( a, 4 );
376   else
377     iobuf_put ( a, pk->version );
378   write_32 (a, pk->timestamp );
379
380   iobuf_put (a, pk->pubkey_algo );
381
382   /* Get number of secret and public parameters.  They are held in one
383      array: the public ones followed by the secret ones.  */
384   nskey = pubkey_get_nskey (pk->pubkey_algo);
385   npkey = pubkey_get_npkey (pk->pubkey_algo);
386
387   /* If we don't have any public parameters - which is for example the
388      case if we don't know the algorithm used - the parameters are
389      stored as one blob in a faked (opaque) MPI. */
390   if (!npkey)
391     {
392       write_fake_data (a, pk->pkey[0]);
393       goto leave;
394     }
395   log_assert (npkey < nskey);
396
397   for (i=0; i < npkey; i++ )
398     {
399       if (   (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && (i == 0))
400           || (pk->pubkey_algo == PUBKEY_ALGO_EDDSA && (i == 0))
401           || (pk->pubkey_algo == PUBKEY_ALGO_ECDH  && (i == 0 || i == 2)))
402         err = gpg_mpi_write_nohdr (a, pk->pkey[i]);
403       else
404         err = gpg_mpi_write (a, pk->pkey[i]);
405       if (err)
406         goto leave;
407     }
408
409
410   if (pk->seckey_info)
411     {
412       /* This is a secret key packet.  */
413       struct seckey_info *ski = pk->seckey_info;
414
415       /* Build the header for protected (encrypted) secret parameters.  */
416       if (ski->is_protected)
417         {
418           /* OpenPGP protection according to rfc2440. */
419           iobuf_put (a, ski->sha1chk? 0xfe : 0xff);
420           iobuf_put (a, ski->algo);
421           if (ski->s2k.mode >= 1000)
422             {
423               /* These modes are not possible in OpenPGP, we use them
424                  to implement our extensions, 101 can be viewed as a
425                  private/experimental extension (this is not specified
426                  in rfc2440 but the same scheme is used for all other
427                  algorithm identifiers). */
428               iobuf_put (a, 101);
429               iobuf_put (a, ski->s2k.hash_algo);
430               iobuf_write (a, "GNU", 3 );
431               iobuf_put (a, ski->s2k.mode - 1000);
432             }
433           else
434             {
435               iobuf_put (a, ski->s2k.mode);
436               iobuf_put (a, ski->s2k.hash_algo);
437             }
438
439           if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
440             iobuf_write (a, ski->s2k.salt, 8);
441
442           if (ski->s2k.mode == 3)
443             iobuf_put (a, ski->s2k.count);
444
445           /* For our special modes 1001, 1002 we do not need an IV. */
446           if (ski->s2k.mode != 1001 && ski->s2k.mode != 1002)
447             iobuf_write (a, ski->iv, ski->ivlen);
448
449         }
450       else /* Not protected. */
451         iobuf_put (a, 0 );
452
453       if (ski->s2k.mode == 1001)
454         ; /* GnuPG extension - don't write a secret key at all. */
455       else if (ski->s2k.mode == 1002)
456         {
457           /* GnuPG extension - divert to OpenPGP smartcard. */
458           /* Length of the serial number or 0 for no serial number. */
459           iobuf_put (a, ski->ivlen );
460           /* The serial number gets stored in the IV field.  */
461           iobuf_write (a, ski->iv, ski->ivlen);
462         }
463       else if (ski->is_protected)
464         {
465           /* The secret key is protected - write it out as it is.  */
466           byte *p;
467           unsigned int ndatabits;
468
469           log_assert (gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE));
470           p = gcry_mpi_get_opaque (pk->pkey[npkey], &ndatabits);
471           if (p)
472             iobuf_write (a, p, (ndatabits+7)/8 );
473         }
474       else
475         {
476           /* Non-protected key. */
477           for ( ; i < nskey; i++ )
478             if ( (err = gpg_mpi_write (a, pk->pkey[i])))
479               goto leave;
480           write_16 (a, ski->csum );
481         }
482     }
483
484  leave:
485   if (!err)
486     {
487       /* Build the header of the packet - which we must do after
488          writing all the other stuff, so that we know the length of
489          the packet */
490       write_header2 (out, ctb, iobuf_get_temp_length(a), 0);
491        /* And finally write it out to the real stream. */
492       err = iobuf_write_temp (out, a);
493     }
494
495   iobuf_close (a); /* Close the temporary buffer */
496   return err;
497 }
498
499 /* Serialize the symmetric-key encrypted session key packet (RFC 4880,
500    5.3) described by ENC and write it to OUT.
501
502    CTB is the serialization's CTB.  It specifies the header format and
503    the packet's type.  The header length must not be set.  */
504 static int
505 do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc )
506 {
507     int rc = 0;
508     IOBUF a = iobuf_temp();
509
510     log_assert (ctb_pkttype (ctb) == PKT_SYMKEY_ENC);
511
512     /* The only acceptable version.  */
513     log_assert( enc->version == 4 );
514
515     /* RFC 4880, Section 3.7.  */
516     switch( enc->s2k.mode )
517       {
518       /* Simple S2K.  */
519       case 0:
520       /* Salted S2K.  */
521       case 1:
522       /* Iterated and salted S2K.  */
523       case 3:
524         /* Reasonable values.  */
525         break;
526
527       default:
528         log_bug("do_symkey_enc: s2k=%d\n", enc->s2k.mode );
529     }
530     iobuf_put( a, enc->version );
531     iobuf_put( a, enc->cipher_algo );
532     iobuf_put( a, enc->s2k.mode );
533     iobuf_put( a, enc->s2k.hash_algo );
534     if( enc->s2k.mode == 1 || enc->s2k.mode == 3 ) {
535         iobuf_write(a, enc->s2k.salt, 8 );
536         if( enc->s2k.mode == 3 )
537             iobuf_put(a, enc->s2k.count);
538     }
539     if( enc->seskeylen )
540         iobuf_write(a, enc->seskey, enc->seskeylen );
541
542     write_header(out, ctb, iobuf_get_temp_length(a) );
543     rc = iobuf_write_temp( out, a );
544
545     iobuf_close(a);
546     return rc;
547 }
548
549
550 /* Serialize the public-key encrypted session key packet (RFC 4880,
551    5.1) described by ENC and write it to OUT.
552
553    CTB is the serialization's CTB.  It specifies the header format and
554    the packet's type.  The header length must not be set.  */
555 static int
556 do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc )
557 {
558   int rc = 0;
559   int n, i;
560   IOBUF a = iobuf_temp();
561
562   log_assert (ctb_pkttype (ctb) == PKT_PUBKEY_ENC);
563
564   iobuf_put (a, 3); /* Version.  */
565
566   if ( enc->throw_keyid )
567     {
568       write_32(a, 0 );  /* Don't tell Eve who can decrypt the message.  */
569       write_32(a, 0 );
570     }
571   else
572     {
573       write_32(a, enc->keyid[0] );
574       write_32(a, enc->keyid[1] );
575     }
576   iobuf_put(a,enc->pubkey_algo );
577   n = pubkey_get_nenc( enc->pubkey_algo );
578   if ( !n )
579     write_fake_data( a, enc->data[0] );
580
581   for (i=0; i < n && !rc ; i++ )
582     {
583       if (enc->pubkey_algo == PUBKEY_ALGO_ECDH && i == 1)
584         rc = gpg_mpi_write_nohdr (a, enc->data[i]);
585       else
586         rc = gpg_mpi_write (a, enc->data[i]);
587     }
588
589   if (!rc)
590     {
591       write_header (out, ctb, iobuf_get_temp_length(a) );
592       rc = iobuf_write_temp (out, a);
593     }
594   iobuf_close(a);
595   return rc;
596 }
597
598
599 /* Calculate the length of the serialized plaintext packet PT (RFC
600    4480, Section 5.9).  */
601 static u32
602 calc_plaintext( PKT_plaintext *pt )
603 {
604   /* Truncate namelen to the maximum 255 characters.  Note this means
605      that a function that calls build_packet with an illegal literal
606      packet will get it back legalized. */
607
608   if(pt->namelen>255)
609     pt->namelen=255;
610
611   return pt->len? (1 + 1 + pt->namelen + 4 + pt->len) : 0;
612 }
613
614 /* Serialize the plaintext packet (RFC 4880, 5.9) described by PT and
615    write it to OUT.
616
617    The body of the message is stored in PT->BUF.  The amount of data
618    to write is PT->LEN.  (PT->BUF should be configured to return EOF
619    after this much data has been read.)  If PT->LEN is 0 and CTB
620    indicates that this is a new format packet, then partial block mode
621    is assumed to have been enabled on OUT.  On success, partial block
622    mode is disabled.
623
624    If PT->BUF is NULL, the the caller must write out the data.  In
625    this case, if PT->LEN was 0, then partial body length mode was
626    enabled and the caller must disable it by calling
627    iobuf_set_partial_body_length_mode (out, 0).  */
628 static int
629 do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt )
630 {
631     int rc = 0;
632     size_t nbytes;
633
634     log_assert (ctb_pkttype (ctb) == PKT_PLAINTEXT);
635
636     write_header(out, ctb, calc_plaintext( pt ) );
637     log_assert (pt->mode == 'b' || pt->mode == 't' || pt->mode == 'u'
638                 || pt->mode == 'm'
639                 || pt->mode == 'l' || pt->mode == '1');
640     iobuf_put(out, pt->mode );
641     iobuf_put(out, pt->namelen );
642     iobuf_write (out, pt->name, pt->namelen);
643     rc = write_32(out, pt->timestamp );
644     if (rc)
645       return rc;
646
647     if (pt->buf)
648       {
649         nbytes = iobuf_copy (out, pt->buf);
650         if(ctb_new_format_p (ctb) && !pt->len)
651           /* Turn off partial body length mode.  */
652           iobuf_set_partial_body_length_mode (out, 0);
653         if( pt->len && nbytes != pt->len )
654           log_error("do_plaintext(): wrote %lu bytes but expected %lu bytes\n",
655                     (ulong)nbytes, (ulong)pt->len );
656       }
657
658     return rc;
659 }
660
661
662
663 /* Serialize the symmetrically encrypted data packet (RFC 4880,
664    Section 5.7) described by ED and write it to OUT.
665
666    Note: this only writes the packets header!  The call must then
667    follow up and write the initial random data and the body to OUT.
668    (If you use the encryption iobuf filter (cipher_filter), then this
669    is done automatically.)  */
670 static int
671 do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed )
672 {
673     int rc = 0;
674     u32 n;
675
676     log_assert (! ed->mdc_method);
677     log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED);
678
679     n = ed->len ? (ed->len + ed->extralen) : 0;
680     write_header(out, ctb, n );
681
682     /* This is all. The caller has to write the real data */
683
684     return rc;
685 }
686
687 /* Serialize the symmetrically encrypted integrity protected data
688    packet (RFC 4880, Section 5.13) described by ED and write it to
689    OUT.
690
691    Note: this only writes the packet's header!  The caller must then
692    follow up and write the initial random data, the body and the MDC
693    packet to OUT.  (If you use the encryption iobuf filter
694    (cipher_filter), then this is done automatically.)  */
695 static int
696 do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed )
697 {
698     int rc = 0;
699     u32 n;
700
701     log_assert (ed->mdc_method);
702     log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED_MDC);
703
704     /* Take version number and the following MDC packet in account. */
705     n = ed->len ? (ed->len + ed->extralen + 1 + 22) : 0;
706     write_header(out, ctb, n );
707     iobuf_put(out, 1 );  /* version */
708
709     /* This is all. The caller has to write the real data */
710
711     return rc;
712 }
713
714
715 /* Serialize the compressed packet (RFC 4880, Section 5.6) described
716    by CD and write it to OUT.
717
718    Note: this only writes the packet's header!  The caller must then
719    follow up and write the body to OUT.  */
720 static int
721 do_compressed( IOBUF out, int ctb, PKT_compressed *cd )
722 {
723     int rc = 0;
724
725     log_assert (ctb_pkttype (ctb) == PKT_COMPRESSED);
726
727     /* We must use the old convention and don't use blockmode for the
728        sake of PGP 2 compatibility.  However if the new_ctb flag was
729        set, CTB is already formatted as new style and write_header2
730        does create a partial length encoding using new the new
731        style. */
732     write_header2(out, ctb, 0, 0);
733     iobuf_put(out, cd->algorithm );
734
735     /* This is all. The caller has to write the real data */
736
737     return rc;
738 }
739
740
741 /****************
742  * Delete all subpackets of type REQTYPE and return a bool whether a packet
743  * was deleted.
744  */
745 int
746 delete_sig_subpkt (subpktarea_t *area, sigsubpkttype_t reqtype )
747 {
748     int buflen;
749     sigsubpkttype_t type;
750     byte *buffer, *bufstart;
751     size_t n;
752     size_t unused = 0;
753     int okay = 0;
754
755     if( !area )
756         return 0;
757     buflen = area->len;
758     buffer = area->data;
759     for(;;) {
760         if( !buflen ) {
761             okay = 1;
762             break;
763         }
764         bufstart = buffer;
765         n = *buffer++; buflen--;
766         if( n == 255 ) {
767             if( buflen < 4 )
768                 break;
769             n = buf32_to_size_t (buffer);
770             buffer += 4;
771             buflen -= 4;
772         }
773         else if( n >= 192 ) {
774             if( buflen < 2 )
775                 break;
776             n = (( n - 192 ) << 8) + *buffer + 192;
777             buffer++;
778             buflen--;
779         }
780         if( buflen < n )
781             break;
782
783         type = *buffer & 0x7f;
784         if( type == reqtype ) {
785             buffer++;
786             buflen--;
787             n--;
788             if( n > buflen )
789                 break;
790             buffer += n; /* point to next subpkt */
791             buflen -= n;
792             memmove (bufstart, buffer, buflen); /* shift */
793             unused +=  buffer - bufstart;
794             buffer = bufstart;
795         }
796         else {
797             buffer += n; buflen -=n;
798         }
799     }
800
801     if (!okay)
802         log_error ("delete_subpkt: buffer shorter than subpacket\n");
803     log_assert (unused <= area->len);
804     area->len -= unused;
805     return !!unused;
806 }
807
808
809 /****************
810  * Create or update a signature subpacket for SIG of TYPE.  This
811  * functions knows where to put the data (hashed or unhashed).  The
812  * function may move data from the unhashed part to the hashed one.
813  * Note: All pointers into sig->[un]hashed (e.g. returned by
814  * parse_sig_subpkt) are not valid after a call to this function.  The
815  * data to put into the subpaket should be in a buffer with a length
816  * of buflen.
817  */
818 void
819 build_sig_subpkt (PKT_signature *sig, sigsubpkttype_t type,
820                   const byte *buffer, size_t buflen )
821 {
822     byte *p;
823     int critical, hashed;
824     subpktarea_t *oldarea, *newarea;
825     size_t nlen, n, n0;
826
827     critical = (type & SIGSUBPKT_FLAG_CRITICAL);
828     type &= ~SIGSUBPKT_FLAG_CRITICAL;
829
830     /* Sanity check buffer sizes */
831     if(parse_one_sig_subpkt(buffer,buflen,type)<0)
832       BUG();
833
834     switch(type)
835       {
836       case SIGSUBPKT_NOTATION:
837       case SIGSUBPKT_POLICY:
838       case SIGSUBPKT_REV_KEY:
839       case SIGSUBPKT_SIGNATURE:
840         /* we do allow multiple subpackets */
841         break;
842
843       default:
844         /* we don't allow multiple subpackets */
845         delete_sig_subpkt(sig->hashed,type);
846         delete_sig_subpkt(sig->unhashed,type);
847         break;
848       }
849
850     /* Any special magic that needs to be done for this type so the
851        packet doesn't need to be reparsed? */
852     switch(type)
853       {
854       case SIGSUBPKT_NOTATION:
855         sig->flags.notation=1;
856         break;
857
858       case SIGSUBPKT_POLICY:
859         sig->flags.policy_url=1;
860         break;
861
862       case SIGSUBPKT_PREF_KS:
863         sig->flags.pref_ks=1;
864         break;
865
866       case SIGSUBPKT_EXPORTABLE:
867         if(buffer[0])
868           sig->flags.exportable=1;
869         else
870           sig->flags.exportable=0;
871         break;
872
873       case SIGSUBPKT_REVOCABLE:
874         if(buffer[0])
875           sig->flags.revocable=1;
876         else
877           sig->flags.revocable=0;
878         break;
879
880       case SIGSUBPKT_TRUST:
881         sig->trust_depth=buffer[0];
882         sig->trust_value=buffer[1];
883         break;
884
885       case SIGSUBPKT_REGEXP:
886         sig->trust_regexp=buffer;
887         break;
888
889         /* This should never happen since we don't currently allow
890            creating such a subpacket, but just in case... */
891       case SIGSUBPKT_SIG_EXPIRE:
892         if(buf32_to_u32(buffer)+sig->timestamp<=make_timestamp())
893           sig->flags.expired=1;
894         else
895           sig->flags.expired=0;
896         break;
897
898       default:
899         break;
900       }
901
902     if( (buflen+1) >= 8384 )
903         nlen = 5; /* write 5 byte length header */
904     else if( (buflen+1) >= 192 )
905         nlen = 2; /* write 2 byte length header */
906     else
907         nlen = 1; /* just a 1 byte length header */
908
909     switch( type )
910       {
911         /* The issuer being unhashed is a historical oddity.  It
912            should work equally as well hashed.  Of course, if even an
913            unhashed issuer is tampered with, it makes it awfully hard
914            to verify the sig... */
915       case SIGSUBPKT_ISSUER:
916       case SIGSUBPKT_SIGNATURE:
917         hashed = 0;
918         break;
919       default:
920         hashed = 1;
921         break;
922       }
923
924     if( critical )
925         type |= SIGSUBPKT_FLAG_CRITICAL;
926
927     oldarea = hashed? sig->hashed : sig->unhashed;
928
929     /* Calculate new size of the area and allocate */
930     n0 = oldarea? oldarea->len : 0;
931     n = n0 + nlen + 1 + buflen; /* length, type, buffer */
932     if (oldarea && n <= oldarea->size) { /* fits into the unused space */
933         newarea = oldarea;
934         /*log_debug ("updating area for type %d\n", type );*/
935     }
936     else if (oldarea) {
937         newarea = xrealloc (oldarea, sizeof (*newarea) + n - 1);
938         newarea->size = n;
939         /*log_debug ("reallocating area for type %d\n", type );*/
940     }
941     else {
942         newarea = xmalloc (sizeof (*newarea) + n - 1);
943         newarea->size = n;
944         /*log_debug ("allocating area for type %d\n", type );*/
945     }
946     newarea->len = n;
947
948     p = newarea->data + n0;
949     if (nlen == 5) {
950         *p++ = 255;
951         *p++ = (buflen+1) >> 24;
952         *p++ = (buflen+1) >> 16;
953         *p++ = (buflen+1) >>  8;
954         *p++ = (buflen+1);
955         *p++ = type;
956         memcpy (p, buffer, buflen);
957     }
958     else if (nlen == 2) {
959         *p++ = (buflen+1-192) / 256 + 192;
960         *p++ = (buflen+1-192) % 256;
961         *p++ = type;
962         memcpy (p, buffer, buflen);
963     }
964     else {
965         *p++ = buflen+1;
966         *p++ = type;
967         memcpy (p, buffer, buflen);
968     }
969
970     if (hashed)
971         sig->hashed = newarea;
972     else
973         sig->unhashed = newarea;
974 }
975
976 /*
977  * Put all the required stuff from SIG into subpackets of sig.
978  * PKSK is the signing key.
979  * Hmmm, should we delete those subpackets which are in a wrong area?
980  */
981 void
982 build_sig_subpkt_from_sig (PKT_signature *sig, PKT_public_key *pksk)
983 {
984     u32  u;
985     byte buf[1+MAX_FINGERPRINT_LEN];
986     size_t fprlen;
987
988     /* For v4 keys we need to write the ISSUER subpacket.  We do not
989      * want that for a future v5 format.  */
990     if (pksk->version < 5)
991       {
992         u = sig->keyid[0];
993         buf[0] = (u >> 24) & 0xff;
994         buf[1] = (u >> 16) & 0xff;
995         buf[2] = (u >>  8) & 0xff;
996         buf[3] = u & 0xff;
997         u = sig->keyid[1];
998         buf[4] = (u >> 24) & 0xff;
999         buf[5] = (u >> 16) & 0xff;
1000         buf[6] = (u >>  8) & 0xff;
1001         buf[7] = u & 0xff;
1002         build_sig_subpkt (sig, SIGSUBPKT_ISSUER, buf, 8);
1003       }
1004
1005     /* Write the new ISSUER_FPR subpacket.  */
1006     fingerprint_from_pk (pksk, buf+1, &fprlen);
1007     if (fprlen == 20)
1008       {
1009         buf[0] = pksk->version;
1010         build_sig_subpkt (sig, SIGSUBPKT_ISSUER_FPR, buf, 21);
1011       }
1012
1013     /* Write the timestamp.  */
1014     u = sig->timestamp;
1015     buf[0] = (u >> 24) & 0xff;
1016     buf[1] = (u >> 16) & 0xff;
1017     buf[2] = (u >>  8) & 0xff;
1018     buf[3] = u & 0xff;
1019     build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
1020
1021     if(sig->expiredate)
1022       {
1023         if(sig->expiredate>sig->timestamp)
1024           u=sig->expiredate-sig->timestamp;
1025         else
1026           u=1; /* A 1-second expiration time is the shortest one
1027                   OpenPGP has */
1028
1029         buf[0] = (u >> 24) & 0xff;
1030         buf[1] = (u >> 16) & 0xff;
1031         buf[2] = (u >>  8) & 0xff;
1032         buf[3] = u & 0xff;
1033
1034         /* Mark this CRITICAL, so if any implementation doesn't
1035            understand sigs that can expire, it'll just disregard this
1036            sig altogether. */
1037
1038         build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
1039                           buf, 4 );
1040       }
1041 }
1042
1043 void
1044 build_attribute_subpkt(PKT_user_id *uid,byte type,
1045                        const void *buf,u32 buflen,
1046                        const void *header,u32 headerlen)
1047 {
1048   byte *attrib;
1049   int idx;
1050
1051   if(1+headerlen+buflen>8383)
1052     idx=5;
1053   else if(1+headerlen+buflen>191)
1054     idx=2;
1055   else
1056     idx=1;
1057
1058   /* realloc uid->attrib_data to the right size */
1059
1060   uid->attrib_data=xrealloc(uid->attrib_data,
1061                              uid->attrib_len+idx+1+headerlen+buflen);
1062
1063   attrib=&uid->attrib_data[uid->attrib_len];
1064
1065   if(idx==5)
1066     {
1067       attrib[0]=255;
1068       attrib[1]=(1+headerlen+buflen) >> 24;
1069       attrib[2]=(1+headerlen+buflen) >> 16;
1070       attrib[3]=(1+headerlen+buflen) >> 8;
1071       attrib[4]=1+headerlen+buflen;
1072     }
1073   else if(idx==2)
1074     {
1075       attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
1076       attrib[1]=(1+headerlen+buflen-192) % 256;
1077     }
1078   else
1079     attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
1080
1081   attrib[idx++]=type;
1082
1083   /* Tack on our data at the end */
1084
1085   if(headerlen>0)
1086     memcpy(&attrib[idx],header,headerlen);
1087   memcpy(&attrib[idx+headerlen],buf,buflen);
1088   uid->attrib_len+=idx+headerlen+buflen;
1089 }
1090
1091 /* Returns a human-readable string corresponding to the notation.
1092    This ignores notation->value.  The caller must free the result.  */
1093 static char *
1094 notation_value_to_human_readable_string (struct notation *notation)
1095 {
1096   if(notation->bdat)
1097     /* Binary data.  */
1098     {
1099       size_t len = notation->blen;
1100       int i;
1101       char preview[20];
1102
1103       for (i = 0; i < len && i < sizeof (preview) - 1; i ++)
1104         if (isprint (notation->bdat[i]))
1105           preview[i] = notation->bdat[i];
1106         else
1107           preview[i] = '?';
1108       preview[i] = 0;
1109
1110       return xasprintf (_("[ not human readable (%zu bytes: %s%s) ]"),
1111                         len, preview, i < len ? "..." : "");
1112     }
1113   else
1114     /* The value is human-readable.  */
1115     return xstrdup (notation->value);
1116 }
1117
1118 /* Turn the notation described by the string STRING into a notation.
1119
1120    STRING has the form:
1121
1122      - -name - Delete the notation.
1123      - name@domain.name=value - Normal notation
1124      - !name@domain.name=value - Notation with critical bit set.
1125
1126    The caller must free the result using free_notation().  */
1127 struct notation *
1128 string_to_notation(const char *string,int is_utf8)
1129 {
1130   const char *s;
1131   int saw_at=0;
1132   struct notation *notation;
1133
1134   notation=xmalloc_clear(sizeof(*notation));
1135
1136   if(*string=='-')
1137     {
1138       notation->flags.ignore=1;
1139       string++;
1140     }
1141
1142   if(*string=='!')
1143     {
1144       notation->flags.critical=1;
1145       string++;
1146     }
1147
1148   /* If and when the IETF assigns some official name tags, we'll have
1149      to add them here. */
1150
1151   for( s=string ; *s != '='; s++ )
1152     {
1153       if( *s=='@')
1154         saw_at++;
1155
1156       /* -notationname is legal without an = sign */
1157       if(!*s && notation->flags.ignore)
1158         break;
1159
1160       if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
1161         {
1162           log_error(_("a notation name must have only printable characters"
1163                       " or spaces, and end with an '='\n") );
1164           goto fail;
1165         }
1166     }
1167
1168   notation->name=xmalloc((s-string)+1);
1169   strncpy(notation->name,string,s-string);
1170   notation->name[s-string]='\0';
1171
1172   if(!saw_at && !opt.expert)
1173     {
1174       log_error(_("a user notation name must contain the '@' character\n"));
1175       goto fail;
1176     }
1177
1178   if (saw_at > 1)
1179     {
1180       log_error(_("a notation name must not contain more than"
1181                   " one '@' character\n"));
1182       goto fail;
1183     }
1184
1185   if(*s)
1186     {
1187       const char *i=s+1;
1188       int highbit=0;
1189
1190       /* we only support printable text - therefore we enforce the use
1191          of only printable characters (an empty value is valid) */
1192       for(s++; *s ; s++ )
1193         {
1194           if ( !isascii (*s) )
1195             highbit=1;
1196           else if (iscntrl(*s))
1197             {
1198               log_error(_("a notation value must not use any"
1199                           " control characters\n"));
1200               goto fail;
1201             }
1202         }
1203
1204       if(!highbit || is_utf8)
1205         notation->value=xstrdup(i);
1206       else
1207         notation->value=native_to_utf8(i);
1208     }
1209
1210   return notation;
1211
1212  fail:
1213   free_notation(notation);
1214   return NULL;
1215 }
1216
1217 /* Like string_to_notation, but store opaque data rather than human
1218    readable data.  */
1219 struct notation *
1220 blob_to_notation(const char *name, const char *data, size_t len)
1221 {
1222   const char *s;
1223   int saw_at=0;
1224   struct notation *notation;
1225
1226   notation=xmalloc_clear(sizeof(*notation));
1227
1228   if(*name=='-')
1229     {
1230       notation->flags.ignore=1;
1231       name++;
1232     }
1233
1234   if(*name=='!')
1235     {
1236       notation->flags.critical=1;
1237       name++;
1238     }
1239
1240   /* If and when the IETF assigns some official name tags, we'll have
1241      to add them here. */
1242
1243   for( s=name ; *s; s++ )
1244     {
1245       if( *s=='@')
1246         saw_at++;
1247
1248       /* -notationname is legal without an = sign */
1249       if(!*s && notation->flags.ignore)
1250         break;
1251
1252       if (*s == '=')
1253         {
1254           log_error(_("a notation name may not contain an '=' character\n"));
1255           goto fail;
1256         }
1257
1258       if (!isascii (*s) || (!isgraph(*s) && !isspace(*s)))
1259         {
1260           log_error(_("a notation name must have only printable characters"
1261                       " or spaces\n") );
1262           goto fail;
1263         }
1264     }
1265
1266   notation->name=xstrdup (name);
1267
1268   if(!saw_at && !opt.expert)
1269     {
1270       log_error(_("a user notation name must contain the '@' character\n"));
1271       goto fail;
1272     }
1273
1274   if (saw_at > 1)
1275     {
1276       log_error(_("a notation name must not contain more than"
1277                   " one '@' character\n"));
1278       goto fail;
1279     }
1280
1281   notation->bdat = xmalloc (len);
1282   memcpy (notation->bdat, data, len);
1283   notation->blen = len;
1284
1285   notation->value = notation_value_to_human_readable_string (notation);
1286
1287   return notation;
1288
1289  fail:
1290   free_notation(notation);
1291   return NULL;
1292 }
1293
1294 struct notation *
1295 sig_to_notation(PKT_signature *sig)
1296 {
1297   const byte *p;
1298   size_t len;
1299   int seq = 0;
1300   int crit;
1301   notation_t list = NULL;
1302
1303   /* See RFC 4880, 5.2.3.16 for the format of notation data.  In
1304      short, a notation has:
1305
1306        - 4 bytes of flags
1307        - 2 byte name length (n1)
1308        - 2 byte value length (n2)
1309        - n1 bytes of name data
1310        - n2 bytes of value data
1311    */
1312   while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
1313     {
1314       int n1,n2;
1315       struct notation *n=NULL;
1316
1317       if(len<8)
1318         {
1319           log_info(_("WARNING: invalid notation data found\n"));
1320           continue;
1321         }
1322
1323       /* name length.  */
1324       n1=(p[4]<<8)|p[5];
1325       /* value length.  */
1326       n2=(p[6]<<8)|p[7];
1327
1328       if(8+n1+n2!=len)
1329         {
1330           log_info(_("WARNING: invalid notation data found\n"));
1331           continue;
1332         }
1333
1334       n=xmalloc_clear(sizeof(*n));
1335       n->name=xmalloc(n1+1);
1336
1337       memcpy(n->name,&p[8],n1);
1338       n->name[n1]='\0';
1339
1340       if(p[0]&0x80)
1341         /* The value is human-readable.  */
1342         {
1343           n->value=xmalloc(n2+1);
1344           memcpy(n->value,&p[8+n1],n2);
1345           n->value[n2]='\0';
1346           n->flags.human = 1;
1347         }
1348       else
1349         /* Binary data.  */
1350         {
1351           n->bdat=xmalloc(n2);
1352           n->blen=n2;
1353           memcpy(n->bdat,&p[8+n1],n2);
1354
1355           n->value = notation_value_to_human_readable_string (n);
1356         }
1357
1358       n->flags.critical=crit;
1359
1360       n->next=list;
1361       list=n;
1362     }
1363
1364   return list;
1365 }
1366
1367 /* Release the resources associated with the *list* of notations.  To
1368    release a single notation, make sure that notation->next is
1369    NULL.  */
1370 void
1371 free_notation(struct notation *notation)
1372 {
1373   while(notation)
1374     {
1375       struct notation *n=notation;
1376
1377       xfree(n->name);
1378       xfree(n->value);
1379       xfree(n->altvalue);
1380       xfree(n->bdat);
1381       notation=n->next;
1382       xfree(n);
1383     }
1384 }
1385
1386 /* Serialize the signature packet (RFC 4880, Section 5.2) described by
1387    SIG and write it to OUT.  */
1388 static int
1389 do_signature( IOBUF out, int ctb, PKT_signature *sig )
1390 {
1391   int rc = 0;
1392   int n, i;
1393   IOBUF a = iobuf_temp();
1394
1395   log_assert (ctb_pkttype (ctb) == PKT_SIGNATURE);
1396
1397   if ( !sig->version || sig->version == 3)
1398     {
1399       iobuf_put( a, 3 );
1400
1401       /* Version 3 packets don't support subpackets.  */
1402       log_assert (! sig->hashed);
1403       log_assert (! sig->unhashed);
1404     }
1405   else
1406     iobuf_put( a, sig->version );
1407   if ( sig->version < 4 )
1408     iobuf_put (a, 5 ); /* Constant */
1409   iobuf_put (a, sig->sig_class );
1410   if ( sig->version < 4 )
1411     {
1412       write_32(a, sig->timestamp );
1413       write_32(a, sig->keyid[0] );
1414       write_32(a, sig->keyid[1] );
1415     }
1416   iobuf_put(a, sig->pubkey_algo );
1417   iobuf_put(a, sig->digest_algo );
1418   if ( sig->version >= 4 )
1419     {
1420       size_t nn;
1421       /* Timestamp and keyid must have been packed into the subpackets
1422          prior to the call of this function, because these subpackets
1423          are hashed. */
1424       nn = sig->hashed? sig->hashed->len : 0;
1425       write_16(a, nn);
1426       if (nn)
1427         iobuf_write( a, sig->hashed->data, nn );
1428       nn = sig->unhashed? sig->unhashed->len : 0;
1429       write_16(a, nn);
1430       if (nn)
1431         iobuf_write( a, sig->unhashed->data, nn );
1432     }
1433   iobuf_put(a, sig->digest_start[0] );
1434   iobuf_put(a, sig->digest_start[1] );
1435   n = pubkey_get_nsig( sig->pubkey_algo );
1436   if ( !n )
1437     write_fake_data( a, sig->data[0] );
1438   for (i=0; i < n && !rc ; i++ )
1439     rc = gpg_mpi_write (a, sig->data[i] );
1440
1441   if (!rc)
1442     {
1443       if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
1444         write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
1445       else
1446         write_header(out, ctb, iobuf_get_temp_length(a) );
1447       rc = iobuf_write_temp( out, a );
1448     }
1449
1450   iobuf_close(a);
1451   return rc;
1452 }
1453
1454
1455 /* Serialize the one-pass signature packet (RFC 4880, Section 5.4)
1456    described by OPS and write it to OUT.  */
1457 static int
1458 do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
1459 {
1460     log_assert (ctb_pkttype (ctb) == PKT_ONEPASS_SIG);
1461
1462     write_header(out, ctb, 4 + 8 + 1);
1463
1464     iobuf_put (out, 3);  /* Version.  */
1465     iobuf_put(out, ops->sig_class );
1466     iobuf_put(out, ops->digest_algo );
1467     iobuf_put(out, ops->pubkey_algo );
1468     write_32(out, ops->keyid[0] );
1469     write_32(out, ops->keyid[1] );
1470     iobuf_put(out, ops->last );
1471
1472     return 0;
1473 }
1474
1475
1476 /* Write a 16-bit quantity to OUT in big endian order.  */
1477 static int
1478 write_16(IOBUF out, u16 a)
1479 {
1480     iobuf_put(out, a>>8);
1481     if( iobuf_put(out,a) )
1482         return -1;
1483     return 0;
1484 }
1485
1486 /* Write a 32-bit quantity to OUT in big endian order.  */
1487 static int
1488 write_32(IOBUF out, u32 a)
1489 {
1490     iobuf_put(out, a>> 24);
1491     iobuf_put(out, a>> 16);
1492     iobuf_put(out, a>> 8);
1493     return iobuf_put(out, a);
1494 }
1495
1496
1497 /****************
1498  * calculate the length of a header.
1499  *
1500  * LEN is the length of the packet's body.  NEW_CTB is whether we are
1501  * using a new or old format packet.
1502  *
1503  * This function does not handle indeterminate lengths or partial body
1504  * lengths.  (If you pass LEN as 0, then this function assumes you
1505  * really mean an empty body.)
1506  */
1507 static int
1508 calc_header_length( u32 len, int new_ctb )
1509 {
1510     if( new_ctb ) {
1511         if( len < 192 )
1512             return 2;
1513         if( len < 8384 )
1514             return 3;
1515         else
1516             return 6;
1517     }
1518     if( len < 256 )
1519         return 2;
1520     if( len < 65536 )
1521         return 3;
1522
1523     return 5;
1524 }
1525
1526 /****************
1527  * Write the CTB and the packet length
1528  */
1529 static int
1530 write_header( IOBUF out, int ctb, u32 len )
1531 {
1532     return write_header2( out, ctb, len, 0 );
1533 }
1534
1535
1536 static int
1537 write_sign_packet_header (IOBUF out, int ctb, u32 len)
1538 {
1539   (void)ctb;
1540
1541   /* Work around a bug in the pgp read function for signature packets,
1542      which are not correctly coded and silently assume at some point 2
1543      byte length headers.*/
1544   iobuf_put (out, 0x89 );
1545   iobuf_put (out, len >> 8 );
1546   return iobuf_put (out, len) == -1 ? -1:0;
1547 }
1548
1549 /****************
1550  * Write a packet header to OUT.
1551  *
1552  * CTB is the ctb.  It determines whether a new or old format packet
1553  * header should be written.  The length field is adjusted, but the
1554  * CTB is otherwise written out as is.
1555  *
1556  * LEN is the length of the packet's body.
1557  *
1558  * If HDRLEN is set, then we don't necessarily use the most efficient
1559  * encoding to store LEN, but the specified length.  (If this is not
1560  * possible, this is a bug.)  In this case, LEN=0 means a 0 length
1561  * packet.  Note: setting HDRLEN is only supported for old format
1562  * packets!
1563  *
1564  * If HDRLEN is not set, then the shortest encoding is used.  In this
1565  * case, LEN=0 means the body has an indeterminate length and a
1566  * partial body length header (if a new format packet) or an
1567  * indeterminate length header (if an old format packet) is written
1568  * out.  Further, if using partial body lengths, this enables partial
1569  * body length mode on OUT.
1570  */
1571 static int
1572 write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
1573 {
1574   if (ctb_new_format_p (ctb))
1575     return write_new_header( out, ctb, len, hdrlen );
1576
1577   /* An old format packet.  Refer to RFC 4880, Section 4.2.1 to
1578      understand how lengths are encoded in this case.  */
1579
1580   /* The length encoding is stored in the two least significant bits.
1581      Make sure they are cleared.  */
1582   log_assert ((ctb & 3) == 0);
1583
1584   log_assert (hdrlen == 0 || hdrlen == 2 || hdrlen == 3 || hdrlen == 5);
1585
1586   if (hdrlen)
1587     /* Header length is given.  */
1588     {
1589       if( hdrlen == 2 && len < 256 )
1590         /* 00 => 1 byte length.  */
1591         ;
1592       else if( hdrlen == 3 && len < 65536 )
1593         /* 01 => 2 byte length.  If len < 256, this is not the most
1594            compact encoding, but it is a correct encoding.  */
1595         ctb |= 1;
1596       else if (hdrlen == 5)
1597         /* 10 => 4 byte length.  If len < 65536, this is not the most
1598            compact encoding, but it is a correct encoding.  */
1599         ctb |= 2;
1600       else
1601         log_bug ("Can't encode length=%d in a %d byte header!\n",
1602                  len, hdrlen);
1603     }
1604   else
1605     {
1606       if( !len )
1607         /* 11 => Indeterminate length.  */
1608         ctb |= 3;
1609       else if( len < 256 )
1610         /* 00 => 1 byte length.  */
1611         ;
1612       else if( len < 65536 )
1613         /* 01 => 2 byte length.  */
1614         ctb |= 1;
1615       else
1616         /* 10 => 4 byte length.  */
1617         ctb |= 2;
1618     }
1619
1620   if( iobuf_put(out, ctb ) )
1621     return -1;
1622
1623   if( len || hdrlen )
1624     {
1625       if( ctb & 2 )
1626         {
1627           if(iobuf_put(out, len >> 24 ))
1628             return -1;
1629           if(iobuf_put(out, len >> 16 ))
1630             return -1;
1631         }
1632
1633       if( ctb & 3 )
1634         if(iobuf_put(out, len >> 8 ))
1635           return -1;
1636
1637       if( iobuf_put(out, len ) )
1638         return -1;
1639     }
1640
1641   return 0;
1642 }
1643
1644
1645 /* Write a new format header to OUT.
1646
1647    CTB is the ctb.
1648
1649    LEN is the length of the packet's body.  If LEN is 0, then enables
1650    partial body length mode (i.e., the body is of an indeterminant
1651    length) on OUT.  Note: this function cannot be used to generate a
1652    header for a zero length packet.
1653
1654    HDRLEN is the length of the packet's header.  If HDRLEN is 0, the
1655    shortest encoding is chosen based on the length of the packet's
1656    body.  Currently, values other than 0 are not supported.
1657
1658    Returns 0 on success.  */
1659 static int
1660 write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
1661 {
1662     if( hdrlen )
1663         log_bug("can't cope with hdrlen yet\n");
1664
1665     if( iobuf_put(out, ctb ) )
1666         return -1;
1667     if( !len ) {
1668         iobuf_set_partial_body_length_mode(out, 512 );
1669     }
1670     else {
1671         if( len < 192 ) {
1672             if( iobuf_put(out, len ) )
1673                 return -1;
1674         }
1675         else if( len < 8384 ) {
1676             len -= 192;
1677             if( iobuf_put( out, (len / 256) + 192) )
1678                 return -1;
1679             if( iobuf_put( out, (len % 256) )  )
1680                 return -1;
1681         }
1682         else {
1683             if( iobuf_put( out, 0xff ) )
1684                 return -1;
1685             if( iobuf_put( out, (len >> 24)&0xff ) )
1686                 return -1;
1687             if( iobuf_put( out, (len >> 16)&0xff ) )
1688                 return -1;
1689             if( iobuf_put( out, (len >> 8)&0xff )  )
1690                 return -1;
1691             if( iobuf_put( out, len & 0xff ) )
1692                 return -1;
1693         }
1694     }
1695     return 0;
1696 }