summaryrefslogtreecommitdiffstats
path: root/tools/gpgparsemail.c
blob: 9001b45114f24fe3e5cbea24a7e5d26c7fe0a191 (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
/* gpgparsemail.c - Standalone crypto mail parser
 *	Copyright (C) 2004 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */


/* This utility prints an RFC8222, possible MIME structured, message
   in an annotated format with the first column having an indicator
   for the content of the line.  Several options are available to
   scrutinize the message.  S/MIME and OpenPGP support is included. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

#include "rfc822parse.h"


#define PGM "gpgparsemail"

/* Option flags. */
static int verbose;
static int debug;
static int opt_crypto;    /* Decrypt or verify messages. */
static int opt_no_header; /* Don't output the header lines. */

/* Structure used to communicate with the parser callback. */
struct parse_info_s {
  int show_header;             /* Show the header lines. */
  int show_data;               /* Show the data lines. */
  unsigned int skip_show;      /* Temporary disable above for these
                                   number of lines. */
  int show_data_as_note;       /* The next data line should be shown
                                  as a note. */
  int show_boundary;
  int nesting_level;

  int is_pkcs7;                /* Old style S/MIME message. */

  int gpgsm_mime;              /* gpgsm shall be used from S/MIME. */
  char *signing_protocol;
  int hashing_level;           /* The nesting level we are hashing. */
  int hashing;                 
  FILE *hash_file;

  FILE *sig_file;              /* Signature part with MIME or full
                                  pkcs7 data if IS_PCKS7 is set. */
  int  verify_now;             /* Flag set when all signature data is
                                  available. */
};


/* Print diagnostic message and exit with failure. */
static void
die (const char *format, ...)
{
  va_list arg_ptr;

  fflush (stdout);
  fprintf (stderr, "%s: ", PGM);

  va_start (arg_ptr, format);
  vfprintf (stderr, format, arg_ptr);
  va_end (arg_ptr);
  putc ('\n', stderr);

  exit (1);
}


/* Print diagnostic message. */
static void
err (const char *format, ...)
{
  va_list arg_ptr;

  fflush (stdout);
  fprintf (stderr, "%s: ", PGM);

  va_start (arg_ptr, format);
  vfprintf (stderr, format, arg_ptr);
  va_end (arg_ptr);
  putc ('\n', stderr);
}

static void *
xmalloc (size_t n)
{
  void *p = malloc (n);
  if (!p)
    die ("out of core: %s", strerror (errno));
  return p;
}

/* static void * */
/* xcalloc (size_t n, size_t m) */
/* { */
/*   void *p = calloc (n, m); */
/*   if (!p) */
/*     die ("out of core: %s", strerror (errno)); */
/*   return p; */
/* } */

/* static void * */
/* xrealloc (void *old, size_t n) */
/* { */
/*   void *p = realloc (old, n); */
/*   if (!p) */
/*     die ("out of core: %s", strerror (errno)); */
/*   return p; */
/* } */

static char *
xstrdup (const char *string)
{
  void *p = malloc (strlen (string)+1);
  if (!p)
    die ("out of core: %s", strerror (errno));
  strcpy (p, string);
  return p;
}

#ifndef HAVE_STPCPY
static char *
stpcpy (char *a,const char *b)
{
  while (*b)
    *a++ = *b++;
  *a = 0;
  
  return (char*)a;
}
#endif

static int
run_gnupg (int smime, int sig_fd, int data_fd, int *close_list)
{
  int rp[2];
  pid_t pid;
  int i, c, is_status;
  unsigned int pos;
  char status_buf[10];
  const char *cmd = smime? "gpgsm":"gpg";
  FILE *fp;

  if (pipe (rp) == -1)
    die ("error creating a pipe: %s", strerror (errno));

  pid = fork ();
  if (pid == -1)
    die ("error forking process: %s", strerror (errno));

  if (!pid)
    { /* Child. */
      char data_fd_buf[50];
      int fd;

      /* Connect our signature fd to stdin. */
      if (sig_fd != 0)
        {
          if (dup2 (sig_fd, 0) == -1)
            die ("dup2 stdin failed: %s", strerror (errno));
        }
      
      /* Keep our data fd and format it for gpg/gpgsm use. */
      if (data_fd == -1)
        *data_fd_buf = 0;
      else
        sprintf (data_fd_buf, "-&%d", data_fd);

      /* Send stdout to the bit bucket. */
      fd = open ("/dev/null", O_WRONLY);
      if (fd == -1)
        die ("can't open `/dev/null': %s", strerror (errno));
      if (fd != 1)
	{
          if (dup2 (fd, 1) == -1)
            die ("dup2 stderr failed: %s", strerror (errno));
        }
      
      /* Connect stderr to our pipe. */
      if (rp[1] != 2)
	{
	  if (dup2 (rp[1], 2) == -1)
	    die ("dup2 stderr failed: %s", strerror (errno));
	}

      /* Close other files. */
      for (i=0; (fd=close_list[i]) != -1; i++)
        if (fd > 2 && fd != data_fd)
          close (fd);
      errno = 0;

      execlp (cmd, cmd,
              "--enable-special-filenames",
              "--status-fd", "2",
              "--assume-base64",
              "--verify",
              "--",
              "-", data_fd == -1? NULL : data_fd_buf,
              NULL);

      die ("failed to exec the crypto command: %s", strerror (errno));
    }

  /* Parent. */ 
  close (rp[1]);

  fp = fdopen (rp[0], "r");
  if (!fp)
    die ("can't fdopen pipe for reading: %s", strerror (errno));

  pos = 0;
  is_status = 0;
  assert (sizeof status_buf > 9);
  while ((c=getc (fp)) != EOF)
    {
      if (pos < 9)
        status_buf[pos] = c;
      else 
        {
          if (pos == 9)
            {
              is_status = !memcmp (status_buf, "[GNUPG:] ", 9);
              if (is_status)
                fputs ( "c ", stdout);
              else if (verbose)
                fputs ( "# ", stdout);
              fwrite (status_buf, 9, 1, stdout);
            }
          putchar (c);
        }
      if (c == '\n')
        {
          if (verbose && pos < 9)
            {
              fputs ( "# ", stdout);
              fwrite (status_buf, pos+1, 1, stdout);
            }
          pos = 0;
        }
      else
        pos++;
    }
  if (pos)
    {
      if (verbose && pos < 9)
        {
          fputs ( "# ", stdout);
          fwrite (status_buf, pos+1, 1, stdout);
        }
      putchar ('\n');
    }
  fclose (fp);

  while ( (i=waitpid (pid, NULL, 0)) == -1 && errno == EINTR)
    ;
  if (i == -1)
    die ("waiting for child failed: %s", strerror (errno));

  return 0;
}




/* Verify the signature in the current temp files. */
static void
verify_signature (struct parse_info_s *info)
{
  int close_list[10];

  if (info->is_pkcs7)
    {
      assert (!info->hash_file);
      assert (info->sig_file);
      rewind (info->sig_file);
    }
  else
    {
      assert (info->hash_file);
      assert (info->sig_file);
      rewind (info->hash_file);
      rewind (info->sig_file);
    }

/*   printf ("# Begin hashed data\n"); */
/*   while ( (c=getc (info->hash_file)) != EOF) */
/*     putchar (c); */
/*   printf ("# End hashed data signature\n"); */
/*   printf ("# Begin signature\n"); */
/*   while ( (c=getc (info->sig_file)) != EOF) */
/*     putchar (c); */
/*   printf ("# End signature\n"); */
/*   rewind (info->hash_file); */
/*   rewind (info->sig_file); */

  close_list[0] = -1;
  run_gnupg (1, fileno (info->sig_file),
             info->hash_file ? fileno (info->hash_file) : -1, close_list);
}





/* Prepare for a multipart/signed. 
   FIELD_CTX is the parsed context of the content-type header.*/
static void
mime_signed_begin (struct parse_info_s *info, rfc822parse_t msg,
                   rfc822parse_field_t field_ctx)
{
  const char *s;
  s = rfc822parse_query_parameter (field_ctx, "protocol", 1);
  if (s)
    {
      printf ("h signed.protocol: %s\n", s);
      if (!strcmp (s, "application/pkcs7-signature")
          || !strcmp (s, "application/x-pkcs7-signature"))
        {
          if (info->gpgsm_mime)
            err ("note: ignoring nested pkcs7-signature");
          else
            {
              info->gpgsm_mime = 1;
              free (info->signing_protocol);
              info->signing_protocol = xstrdup (s);
            }
        }
      else if (verbose)
        printf ("# this protocol is not supported\n");
    }
}


/* Prepare for a multipart/encrypted. 
   FIELD_CTX is the parsed context of the content-type header.*/
static void
mime_encrypted_begin (struct parse_info_s *info, rfc822parse_t msg,
                      rfc822parse_field_t field_ctx)
{
  const char *s;
  s = rfc822parse_query_parameter (field_ctx, "protocol", 0);
  if (s)
    printf ("h encrypted.protocol: %s\n", s);
}


/* Prepare for old-style pkcs7 messages. */
static void
pkcs7_begin (struct parse_info_s *info, rfc822parse_t msg,
             rfc822parse_field_t field_ctx)
{
  const char *s;
  s = rfc822parse_query_parameter (field_ctx, "name", 0);
  if (s)
    printf ("h pkcs7.name: %s\n", s);
  if (info->is_pkcs7)
    err ("note: ignoring nested pkcs7 data");
  else
    {
      info->is_pkcs7 = 1;
      if (opt_crypto)
        {
          assert (!info->sig_file);
          info->sig_file = tmpfile ();
          if (!info->sig_file)
            die ("error creating temp file: %s", strerror (errno));
        }
    }
}


/* Print the event received by the parser for debugging as comment
   line. */
static void
show_event (rfc822parse_event_t event)
{
  const char *s;

  switch (event)
    {
    case RFC822PARSE_OPEN: s= "Open"; break;
    case RFC822PARSE_CLOSE: s= "Close"; break;
    case RFC822PARSE_CANCEL: s= "Cancel"; break;
    case RFC822PARSE_T2BODY: s= "T2Body"; break;
    case RFC822PARSE_FINISH: s= "Finish"; break;
    case RFC822PARSE_RCVD_SEEN: s= "Rcvd_Seen"; break;
    case RFC822PARSE_LEVEL_DOWN: s= "Level_Down"; break;
    case RFC822PARSE_LEVEL_UP: s= "Level_Up"; break;
    case RFC822PARSE_BOUNDARY: s= "Boundary"; break;
    case RFC822PARSE_LAST_BOUNDARY: s= "Last_Boundary"; break;
    case RFC822PARSE_BEGIN_HEADER: s= "Begin_Header"; break;
    case RFC822PARSE_PREAMBLE: s= "Preamble"; break;
    case RFC822PARSE_EPILOGUE: s= "Epilogue"; break;
    default: s= "[unknown event]"; break;
    }
  printf ("# *** got RFC822 event %s\n", s);
}

/* This function is called by the parser to communicate events.  This
   callback comminucates with the main program using a structure
   passed in OPAQUE. Should retrun 0 or set errno and return -1. */
static int
message_cb (void *opaque, rfc822parse_event_t event, rfc822parse_t msg)
{
  struct parse_info_s *info = opaque;

  if (debug)
    show_event (event);
  if (event == RFC822PARSE_OPEN)
    {
      /* Initialize for a new message. */
      info->show_header = 1;
    }
  else if (event == RFC822PARSE_T2BODY)
    {
      rfc822parse_field_t ctx;

      ctx = rfc822parse_parse_field (msg, "Content-Type", -1);
      if (ctx)
        {
          const char *s1, *s2;
          s1 = rfc822parse_query_media_type (ctx, &s2);
          if (s1)
            {
              printf ("h media: %*s%s %s\n", 
                      info->nesting_level*2, "", s1, s2);
              if (info->gpgsm_mime == 3)
                {
                  char *buf = xmalloc (strlen (s1) + strlen (s2) + 2);
                  strcpy (stpcpy (stpcpy (buf, s1), "/"), s2);
                  assert (info->signing_protocol);
                  if (strcmp (buf, info->signing_protocol))
                    err ("invalid S/MIME structure; expected `%s', found `%s'",
                         info->signing_protocol, buf);
                  else
                    {
                      printf ("c begin_signature\n");
                      info->gpgsm_mime++;
                      if (opt_crypto)
                        {
                          assert (!info->sig_file);
                          info->sig_file = tmpfile ();
                          if (!info->sig_file)
                            die ("error creating temp file: %s",
                                 strerror (errno));
                        }
                    }
                  free (buf);
                }
              else if (!strcmp (s1, "multipart"))
                {
                  if (!strcmp (s2, "signed"))
                    mime_signed_begin (info, msg, ctx);
                  else if (!strcmp (s2, "encrypted"))
                    mime_encrypted_begin (info, msg, ctx);
                }
              else if (!strcmp (s1, "application")
                       && (!strcmp (s2, "pkcs7-mime")
                           || !strcmp (s2, "x-pkcs7-mime")))
                pkcs7_begin (info, msg, ctx);
            }
          else
            printf ("h media: %*s none\n", info->nesting_level*2, "");

          rfc822parse_release_field (ctx);
        }
      else
        printf ("h media: %*stext plain [assumed]\n",
                info->nesting_level*2, "");
      info->show_header = 0;
      info->show_data = 1;
      info->skip_show = 1;
    }
  else if (event == RFC822PARSE_PREAMBLE)
    info->show_data_as_note = 1;
  else if (event == RFC822PARSE_LEVEL_DOWN)
    {
      printf ("b down\n");
      info->nesting_level++;
    }
  else if (event == RFC822PARSE_LEVEL_UP)
    {
      printf ("b up\n");
      if (info->nesting_level)
        info->nesting_level--;
      else 
        err ("invalid structure (bad nesting level)");
    }
  else if (event == RFC822PARSE_BOUNDARY || event == RFC822PARSE_LAST_BOUNDARY)
    {
      info->show_data = 0;
      info->show_boundary = 1;
      if (event == RFC822PARSE_BOUNDARY)
        {
          info->show_header = 1;
          info->skip_show = 1;
          printf ("b part\n");
        }
      else 
        printf ("b last\n");

      if (info->gpgsm_mime == 2 && info->nesting_level == info->hashing_level)
        {
          printf ("c end_hash\n");
          info->gpgsm_mime++;
          info->hashing = 0;
        }
      else if (info->gpgsm_mime == 4)
        {
          printf ("c end_signature\n");
          info->verify_now = 1;
        }
    }
  else if (event == RFC822PARSE_BEGIN_HEADER)
    {
      if (info->gpgsm_mime == 1)
        {
          printf ("c begin_hash\n");
          info->hashing = 1;
          info->hashing_level = info->nesting_level;
          info->gpgsm_mime++;

          if (opt_crypto)
            {
              assert (!info->hash_file);
              info->hash_file = tmpfile ();
              if (!info->hash_file)
                die ("failed to create temporary file: %s", strerror (errno));
            }
        }
    }

  return 0;
}


/* Read a message from FP and process it according to the global
   options. */
static void
parse_message (FILE *fp)
{
  char line[5000];
  size_t length;
  rfc822parse_t msg;
  unsigned int lineno = 0;
  int no_cr_reported = 0;
  struct parse_info_s info;

  memset (&info, 0, sizeof info);

  msg = rfc822parse_open (message_cb, &info);
  if (!msg)
    die ("can't open parser: %s", strerror (errno));

  /* Fixme: We should not use fgets becuase it can't cope with
     embedded nul characters. */
  while (fgets (line, sizeof (line), fp))
    {
      lineno++;
      if (lineno == 1 && !strncmp (line, "From ", 5))
        continue;  /* We better ignore a leading From line. */

      length = strlen (line);
      if (length && line[length - 1] == '\n')
	line[--length] = 0;
      else
        err ("line number %u too long or last line not terminated", lineno);
      if (length && line[length - 1] == '\r')
	line[--length] = 0;
      else if (verbose && !no_cr_reported)
        {
          err ("non canonical ended line detected (line %u)", lineno);
          no_cr_reported = 1;
        }


      if (rfc822parse_insert (msg, line, length))
	die ("parser failed: %s", strerror (errno));
      
      if (info.hashing)
        {
          /* Delay hashing of the CR/LF because the last line ending
             belongs to the next boundary. */
          if (debug)
            printf ("# hashing %s`%s'\n", info.hashing==2?"CR,LF+":"", line);
          if (opt_crypto)
            {
              if (info.hashing == 2)
                fputs ("\r\n", info.hash_file);
              fputs (line, info.hash_file);
              if (ferror (info.hash_file))
                die ("error writing to temporary file: %s", strerror (errno));
            }

          info.hashing = 2;
        }

      if (info.sig_file && opt_crypto)
        {
          if (info.verify_now)
            {
              verify_signature (&info);
              if (info.hash_file)
                fclose (info.hash_file);
              info.hash_file = NULL;
              fclose (info.sig_file);
              info.sig_file = NULL;
              info.gpgsm_mime = 0;
              info.is_pkcs7 = 0;
            }
          else
            {
              fputs (line, info.sig_file);
              fputs ("\r\n", info.sig_file);
              if (ferror (info.sig_file))
                die ("error writing to temporary file: %s", strerror (errno));
            }
        }
      
      if (info.show_boundary)
        {
          if (!opt_no_header)
            printf (":%s\n", line);
          info.show_boundary = 0;
        }

      if (info.skip_show)
        info.skip_show--;
      else if (info.show_data)
        {
          if (info.show_data_as_note)
            {
              if (verbose)
                printf ("# DATA: %s\n", line);
              info.show_data_as_note = 0;
            }
          else
            printf (" %s\n", line);
        }
      else if (info.show_header && !opt_no_header)
        printf (".%s\n", line);

    }

  if (info.sig_file && opt_crypto && info.is_pkcs7)
    {
      verify_signature (&info);
      fclose (info.sig_file);
      info.sig_file = NULL;
      info.is_pkcs7 = 0;
    }

  rfc822parse_close (msg);
}


int 
main (int argc, char **argv)
{
  int last_argc = -1;
 
  if (argc)
    {
      argc--; argv++;
    }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          puts (
                "Usage: " PGM " [OPTION] [FILE]\n"
                "Parse a mail message into an annotated format.\n\n"
                "  --crypto    decrypt or verify messages\n"
                "  --no-header don't output the header lines\n"
                "  --verbose   enable extra informational output\n"
                "  --debug     enable additional debug output\n"
                "  --help      display this help and exit\n\n"
                "With no FILE, or when FILE is -, read standard input.\n\n"
                "WARNING: This tool is under development.\n"
                "         The semantics may change without notice\n\n"
                "Report bugs to <bug-gnupg@gnu.org>.");
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose = debug = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--crypto"))
        {
          opt_crypto = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-header"))
        {
          opt_no_header = 1;
          argc--; argv++;
        }
    }          
 
  if (argc > 1)
    die ("usage: " PGM " [OPTION] [FILE] (try --help for more information)\n");

  signal (SIGPIPE, SIG_IGN);

  if (argc && strcmp (*argv, "-"))
    {
      FILE *fp = fopen (*argv, "rb");
      if (!fp)
        die ("can't open `%s': %s", *argv, strerror (errno));
      parse_message (fp);
      fclose (fp);
    }
  else
    parse_message (stdin);

  return 0;
}


/*
Local Variables:
compile-command: "gcc -Wall -g -o gpgparsemail rfc822parse.c gpgparsemail.c"
End:
*/