summaryrefslogtreecommitdiffstats
path: root/tools/mime-maker.c
blob: 91eab8258bccd5ab4a81e186c76986c568e8464e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
/* mime-maker.c - Create MIME structures
 * Copyright (C) 2016 g10 Code GmbH
 * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik
 *
 * This file is part of GnuPG.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../common/util.h"
#include "../common/zb32.h"
#include "rfc822parse.h"
#include "mime-maker.h"


/* An object to store an header.  Also used for a list of headers.  */
struct header_s
{
  struct header_s *next;
  char *value;   /* Malloced value.  */
  char name[1]; /* Name.  */
};
typedef struct header_s *header_t;


/* An object to store a MIME part.  A part is the header plus the
 * content (body). */
struct part_s
{
  struct part_s *next;  /* Next part in the current container.  */
  struct part_s *child; /* Child container.  */
  char *boundary;       /* Malloced boundary string.  */
  header_t headers;     /* List of headers.  */
  header_t *headers_tail;/* Address of last header in chain.  */
  size_t bodylen;       /* Length of BODY.   */
  char *body;           /* Malloced buffer with the body.  This is the
                         * non-encoded value.  */
  unsigned int partid;   /* The part ID.  */
};
typedef struct part_s *part_t;



/* Definition of the mime parser object.  */
struct mime_maker_context_s
{
  void *cookie;                /* Cookie passed to all callbacks.  */

  unsigned int verbose:1;      /* Enable verbose mode.  */
  unsigned int debug:1;        /* Enable debug mode.  */

  part_t mail;                 /* The MIME tree.  */
  part_t current_part;

  unsigned int partid_counter; /* Counter assign part ids.  */

  int boundary_counter;  /* Used to create easy to read boundaries.  */
  char *boundary_suffix; /* Random string used in the boundaries.  */

  struct b64state *b64state;     /* NULL or malloced Base64 decoder state.  */

  /* Helper to convey the output stream to recursive functions. */
  estream_t outfp;
};


/* Create a new mime make object.  COOKIE is a values woich will be
 * used as first argument for all callbacks registered with this
 * object.  */
gpg_error_t
mime_maker_new (mime_maker_t *r_maker, void *cookie)
{
  mime_maker_t ctx;

  *r_maker = NULL;

  ctx = xtrycalloc (1, sizeof *ctx);
  if (!ctx)
    return gpg_error_from_syserror ();
  ctx->cookie = cookie;

  *r_maker = ctx;
  return 0;
}


static void
release_parts (part_t part)
{
  while (part)
    {
      part_t partnext = part->next;
      while (part->headers)
        {
          header_t hdrnext = part->headers->next;
          xfree (part->headers);
          part->headers = hdrnext;
        }
      release_parts (part->child);
      xfree (part->boundary);
      xfree (part->body);
      xfree (part);
      part = partnext;
    }
}


/* Release a mime maker object.  */
void
mime_maker_release (mime_maker_t ctx)
{
  if (!ctx)
    return;

  release_parts (ctx->mail);
  xfree (ctx->boundary_suffix);
  xfree (ctx);
}


/* Set verbose and debug mode.  */
void
mime_maker_set_verbose (mime_maker_t ctx, int level)
{
  if (!level)
    {
      ctx->verbose = 0;
      ctx->debug = 0;
    }
  else
    {
      ctx->verbose = 1;
      if (level > 10)
        ctx->debug = 1;
    }
}


static void
dump_parts (part_t part, int level)
{
  header_t hdr;

  for (; part; part = part->next)
    {
      log_debug ("%*s[part %u]\n", level*2, "", part->partid);
      for (hdr = part->headers; hdr; hdr = hdr->next)
        {
          log_debug ("%*s%s: %s\n", level*2, "", hdr->name, hdr->value);
        }
      if (part->body)
        log_debug ("%*s[body %zu bytes]\n", level*2, "", part->bodylen);
      if (part->child)
        {
          log_debug ("%*s[container]\n", level*2, "");
          dump_parts (part->child, level+1);
        }
    }
}


/* Dump the mime tree for debugging.  */
void
mime_maker_dump_tree (mime_maker_t ctx)
{
  dump_parts (ctx->mail, 0);
}


/* Find the parent node for NEEDLE starting at ROOT.  */
static part_t
find_parent (part_t root, part_t needle)
{
  part_t node, n;

  for (node = root->child; node; node = node->next)
    {
      if (node == needle)
        return root;
      if ((n = find_parent (node, needle)))
        return n;
    }
  return NULL;
}

/* Find the part node from the PARTID.  */
static part_t
find_part (part_t root, unsigned int partid)
{
  part_t node, n;

  for (node = root->child; node; node = node->next)
    {
      if (node->partid == partid)
        return root;
      if ((n = find_part (node, partid)))
        return n;
    }
  return NULL;
}


/* Create a boundary string.  Outr codes is aware of the general
 * structure of that string (gebins with "=-=") so that
 * it can protect against accidentally-used boundaries within the
 * content.   */
static char *
generate_boundary (mime_maker_t ctx)
{
  if (!ctx->boundary_suffix)
    {
      char buffer[12];

      gcry_create_nonce (buffer, sizeof buffer);
      ctx->boundary_suffix = zb32_encode (buffer, 8 * sizeof buffer);
      if (!ctx->boundary_suffix)
        return NULL;
    }

  ctx->boundary_counter++;
  return es_bsprintf ("=-=%02d-%s=-=",
                      ctx->boundary_counter, ctx->boundary_suffix);
}


/* Ensure that the context has a MAIL and CURRENT_PART object and
 * return the parent object if available  */
static gpg_error_t
ensure_part (mime_maker_t ctx, part_t *r_parent)
{
  if (!ctx->mail)
    {
      ctx->mail = xtrycalloc (1, sizeof *ctx->mail);
      if (!ctx->mail)
        {
          if (r_parent)
            *r_parent = NULL;
          return gpg_error_from_syserror ();
        }
      log_assert (!ctx->current_part);
      ctx->current_part = ctx->mail;
      ctx->current_part->headers_tail = &ctx->current_part->headers;
    }
  log_assert (ctx->current_part);
  if (r_parent)
    *r_parent = find_parent (ctx->mail, ctx->current_part);

  return 0;
}


/* Check whether a header with NAME has already been set into PART.
 * NAME must be in canonical capitalized format.  Return true or
 * false. */
static int
have_header (part_t part, const char *name)
{
  header_t hdr;

  for (hdr = part->headers; hdr; hdr = hdr->next)
    if (!strcmp (hdr->name, name))
      return 1;
  return 0;
}


/* Helper to add a header to a part.  */
static gpg_error_t
add_header (part_t part, const char *name, const char *value)
{
  gpg_error_t err;
  header_t hdr;
  size_t namelen;
  const char *s;
  char *p;

  if (!value)
    {
      s = strchr (name, '=');
      if (!s)
        return gpg_error (GPG_ERR_INV_ARG);
      namelen = s - name;
      value = s+1;
    }
  else
    namelen = strlen (name);

  hdr = xtrymalloc (sizeof *hdr + namelen);
  if (!hdr)
    return gpg_error_from_syserror ();
  hdr->next = NULL;
  memcpy (hdr->name, name, namelen);
  hdr->name[namelen] = 0;

  /* Check that the header name is valid.  */
  if (!rfc822_valid_header_name_p (hdr->name))
    {
      xfree (hdr);
      return gpg_error (GPG_ERR_INV_NAME);
    }

  rfc822_capitalize_header_name (hdr->name);
  hdr->value = xtrystrdup (value);
  if (!hdr->value)
    {
      err = gpg_error_from_syserror ();
      xfree (hdr);
      return err;
    }

  for (p = hdr->value + strlen (hdr->value) - 1;
       (p >= hdr->value
        && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'));
       p--)
    *p = 0;
  if (!(p >= hdr->value))
    {
      xfree (hdr->value);
      xfree (hdr);
      return gpg_error (GPG_ERR_INV_VALUE);  /* Only spaces.  */
    }

  if (part)
    {
      *part->headers_tail = hdr;
      part->headers_tail = &hdr->next;
    }
  else
    xfree (hdr);

  return 0;
}


/* Add a header with NAME and VALUE to the current mail.  A LF in the
 * VALUE will be handled automagically.  If NULL is used for VALUE it
 * is expected that the NAME has the format "NAME=VALUE" and VALUE is
 * taken from there.
 *
 * If no container has been added, the header will be used for the
 * regular mail headers and not for a MIME part.  If the current part
 * is in a container and a body has been added, we append a new part
 * to the current container.  Thus for a non-MIME mail the caller
 * needs to call this function followed by a call to add a body.  When
 * adding a Content-Type the boundary parameter must not be included.
 */
gpg_error_t
mime_maker_add_header (mime_maker_t ctx, const char *name, const char *value)
{
  gpg_error_t err;
  part_t part, parent;

  /* Hack to use this function for a syntax check of NAME and VALUE.  */
  if (!ctx)
    return add_header (NULL, name, value);

  err = ensure_part (ctx, &parent);
  if (err)
    return err;
  part = ctx->current_part;

  if ((part->body || part->child) && !parent)
    {
      /* We already have a body but no parent.  Adding another part is
       * thus not possible.  */
      return gpg_error (GPG_ERR_CONFLICT);
    }
  if (part->body || part->child)
    {
      /* We already have a body and there is a parent.  We now append
       * a new part to the current container.  */
      part = xtrycalloc (1, sizeof *part);
      if (!part)
        return gpg_error_from_syserror ();
      part->partid = ++ctx->partid_counter;
      part->headers_tail = &part->headers;
      log_assert (!ctx->current_part->next);
      ctx->current_part->next = part;
      ctx->current_part = part;
    }

  /* If no NAME and no VALUE has been given we do not add a header.
   * This can be used to create a new part without any header.  */
  if (!name && !value)
    return 0;

  /* If we add Content-Type, make sure that we have a MIME-version
   * header first; this simply looks better.  */
  if (!ascii_strcasecmp (name, "Content-Type")
      && !have_header (ctx->mail, "MIME-Version"))
    {
      err = add_header (ctx->mail, "MIME-Version", "1.0");
      if (err)
        return err;
    }
  return add_header (part, name, value);
}


/* Helper for mime_maker_add_{body,stream}.  */
static gpg_error_t
add_body (mime_maker_t ctx, const void *data, size_t datalen)
{
  gpg_error_t err;
  part_t part, parent;

  err = ensure_part (ctx, &parent);
  if (err)
    return err;
  part = ctx->current_part;
  if (part->body)
    return gpg_error (GPG_ERR_CONFLICT);

  part->body = xtrymalloc (datalen? datalen : 1);
  if (!part->body)
    return gpg_error_from_syserror ();
  part->bodylen = datalen;
  if (data)
    memcpy (part->body, data, datalen);

  return 0;
}


/* Add STRING as body to the mail or the current MIME container.  A
 * second call to this function or mime_make_add_body_data is not
 * allowed.
 *
 * FIXME: We may want to have an append_body to add more data to a body.
 */
gpg_error_t
mime_maker_add_body (mime_maker_t ctx, const char *string)
{
  return add_body (ctx, string, strlen (string));
}


/* Add (DATA,DATALEN) as body to the mail or the current MIME
 * container.  Note that a second call to this function or to
 * mime_make_add_body is not allowed.  */
gpg_error_t
mime_maker_add_body_data (mime_maker_t ctx, const void *data, size_t datalen)
{
  return add_body (ctx, data, datalen);
}


/* This is the same as mime_maker_add_body but takes a stream as
 * argument.  As of now the stream is copied to the MIME object but
 * eventually we may delay that and read the stream only at the time
 * it is needed.  Note that the address of the stream object must be
 * passed and that the ownership of the stream is transferred to this
 * MIME object.  To indicate the latter the function will store NULL
 * at the ADDR_STREAM so that a caller can't use that object anymore
 * except for es_fclose which accepts a NULL pointer.  */
gpg_error_t
mime_maker_add_stream (mime_maker_t ctx, estream_t *stream_addr)
{
  void *data;
  size_t datalen;

  es_rewind (*stream_addr);
  if (es_fclose_snatch (*stream_addr, &data, &datalen))
    return gpg_error_from_syserror ();
  *stream_addr = NULL;
  return add_body (ctx, data, datalen);
}


/* Add a new MIME container.  A container can be used instead of a
 * body.  */
gpg_error_t
mime_maker_add_container (mime_maker_t ctx)
{
  gpg_error_t err;
  part_t part;

  err = ensure_part (ctx, NULL);
  if (err)
    return err;
  part = ctx->current_part;

  if (part->body)
    return gpg_error (GPG_ERR_CONFLICT); /* There is already a body. */
  if (part->child || part->boundary)
    return gpg_error (GPG_ERR_CONFLICT); /* There is already a container. */

  /* Create a child node.  */
  part->child = xtrycalloc (1, sizeof *part->child);
  if (!part->child)
    return gpg_error_from_syserror ();
  part->child->headers_tail = &part->child->headers;

  part->boundary = generate_boundary (ctx);
  if (!part->boundary)
    {
      err = gpg_error_from_syserror ();
      xfree (part->child);
      part->child = NULL;
      return err;
    }

  part = part->child;
  part->partid = ++ctx->partid_counter;
  ctx->current_part = part;

  return 0;
}


/* Finish the current container.  */
gpg_error_t
mime_maker_end_container (mime_maker_t ctx)
{
  gpg_error_t err;
  part_t parent;

  err = ensure_part (ctx, &parent);
  if (err)
    return err;
  if (!parent)
    return gpg_error (GPG_ERR_CONFLICT); /* No container.  */
  while (parent->next)
    parent = parent->next;
  ctx->current_part = parent;
  return 0;
}


/* Return the part-ID of the current part. */
unsigned int
mime_maker_get_partid (mime_maker_t ctx)
{
  if (ensure_part (ctx, NULL))
    return 0; /* Ooops.  */
  return ctx->current_part->partid;
}


/* Write a header and handle emdedded LFs.  If BOUNDARY is not NULL it
 * is appended to the value.  */
/* Fixme: Add automatic line wrapping.  */
static gpg_error_t
write_header (mime_maker_t ctx, const char *name, const char *value,
              const char *boundary)
{
  const char *s;

  es_fprintf (ctx->outfp, "%s: ", name);

  /* Note that add_header made sure that VALUE does not end with a LF.
   * Thus we can assume that a LF is followed by non-whitespace.  */
  for (s = value; *s; s++)
    {
      if (*s == '\n')
        es_fputs ("\r\n\t", ctx->outfp);
      else
        es_fputc (*s, ctx->outfp);
    }
  if (boundary)
    {
      if (s > value && s[-1] != ';')
        es_fputc (';', ctx->outfp);
      es_fprintf (ctx->outfp, "\r\n\tboundary=\"%s\"", boundary);
    }

  es_fputs ("\r\n", ctx->outfp);

  return es_ferror (ctx->outfp)? gpg_error_from_syserror () : 0;
}


static gpg_error_t
write_gap (mime_maker_t ctx)
{
  es_fputs ("\r\n", ctx->outfp);
  return es_ferror (ctx->outfp)? gpg_error_from_syserror () : 0;
}


static gpg_error_t
write_boundary (mime_maker_t ctx, const char *boundary, int last)
{
  es_fprintf (ctx->outfp, "\r\n--%s%s\r\n", boundary, last?"--":"");
  return es_ferror (ctx->outfp)? gpg_error_from_syserror () : 0;
}


/* Fixme: Apply required encoding.  */
static gpg_error_t
write_body (mime_maker_t ctx, const void *body, size_t bodylen)
{
  const char *s;

  for (s = body; bodylen; s++, bodylen--)
    {
      if (*s == '\n' && !(s > (const char *)body && s[-1] == '\r'))
        es_fputc ('\r', ctx->outfp);
      es_fputc (*s, ctx->outfp);
    }

  return es_ferror (ctx->outfp)? gpg_error_from_syserror () : 0;
}


/* Recursive worker for mime_maker_make.  */
static gpg_error_t
write_tree (mime_maker_t ctx, part_t parent, part_t part)
{
  gpg_error_t err;
  header_t hdr;

  for (; part; part = part->next)
    {
      for (hdr = part->headers; hdr; hdr = hdr->next)
        {
          if (part->child && !strcmp (hdr->name, "Content-Type"))
            err = write_header (ctx, hdr->name, hdr->value, part->boundary);
          else
            err = write_header (ctx, hdr->name, hdr->value, NULL);
          if (err)
            return err;
        }
      err = write_gap (ctx);
      if (err)
        return err;
      if (part->body)
        {
          err = write_body (ctx, part->body, part->bodylen);
          if (err)
            return err;
        }
      if (part->child)
        {
          log_assert (part->boundary);
          err = write_boundary (ctx, part->boundary, 0);
          if (!err)
            err = write_tree (ctx, part, part->child);
          if (!err)
            err = write_boundary (ctx, part->boundary, 1);
          if (err)
            return err;
        }

      if (part->next)
        {
          log_assert (parent && parent->boundary);
          err = write_boundary (ctx, parent->boundary, 0);
          if (err)
            return err;
        }
    }
  return 0;
}


/* Add headers we always require.  */
static gpg_error_t
add_missing_headers (mime_maker_t ctx)
{
  gpg_error_t err;

  if (!ctx->mail)
    return gpg_error (GPG_ERR_NO_DATA);
  if (!have_header (ctx->mail, "MIME-Version"))
    {
      /* Even if a Content-Type has never been set, we want to
       * announce that we do MIME.  */
      err = add_header (ctx->mail, "MIME-Version", "1.0");
      if (err)
        goto leave;
    }

  if (!have_header (ctx->mail, "Date"))
    {
      char *p = rfctimestamp (make_timestamp ());
      if (!p)
        err = gpg_error_from_syserror ();
      else
        err = add_header (ctx->mail, "Date", p);
      xfree (p);
      if (err)
        goto leave;
    }

  err = 0;

 leave:
  return err;
}


/* Create message from the tree MIME and write it to FP.  Note that
 * the output uses only a LF and a later called sendmail(1) is
 * expected to convert them to network line endings.  */
gpg_error_t
mime_maker_make (mime_maker_t ctx, estream_t fp)
{
  gpg_error_t err;

  err = add_missing_headers (ctx);
  if (err)
    return err;

  ctx->outfp = fp;
  err = write_tree (ctx, NULL, ctx->mail);

  ctx->outfp = NULL;
  return err;
}


/* Create a stream object from the MIME part identified by PARTID and
 * store it at R_STREAM.  If PARTID identifies a container the entire
 * tree is returned. Using that function may read stream objects
 * which have been added as MIME bodies.  The caller must close the
 * stream object. */
gpg_error_t
mime_maker_get_part (mime_maker_t ctx, unsigned int partid, estream_t *r_stream)
{
  gpg_error_t err;
  part_t part;
  estream_t fp;

  *r_stream = NULL;

  /* When the entire tree is requested, we make sure that all missing
   * headers are applied.  We don't do that if only a part is
   * requested because the additional headers (like Date:) will only
   * be added to part 0 headers anyway. */
  if (!partid)
    {
       err = add_missing_headers (ctx);
       if (err)
         return err;
       part = ctx->mail;
    }
  else
    part = find_part (ctx->mail, partid);

  /* For now we use a memory stream object; however it would also be
   * possible to create an object created on the fly while the caller
   * is reading the returned stream.  */
  fp = es_fopenmem (0, "w+b");
  if (!fp)
    return gpg_error_from_syserror ();

  ctx->outfp = fp;
  err = write_tree (ctx, NULL, part);
  ctx->outfp = NULL;

  if (!err)
    {
      es_rewind (fp);
      *r_stream = fp;
    }
  else
    es_fclose (fp);

  return err;
}