mailinfo: skip bogus UNIX From line inside body
[git/platforms/storm.git] / mailinfo.c
bloba133e6d08aa69a5b19f6f232729b7dd108a630d6
1 /*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5 #define _GNU_SOURCE
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #ifndef NO_ICONV
11 #include <iconv.h>
12 #endif
13 #include "git-compat-util.h"
14 #include "cache.h"
16 static FILE *cmitmsg, *patchfile;
18 static int keep_subject = 0;
19 static char *metainfo_charset = NULL;
20 static char line[1000];
21 static char date[1000];
22 static char name[1000];
23 static char email[1000];
24 static char subject[1000];
26 static enum {
27 TE_DONTCARE, TE_QP, TE_BASE64,
28 } transfer_encoding;
29 static char charset[256];
31 static char multipart_boundary[1000];
32 static int multipart_boundary_len;
33 static int patch_lines = 0;
35 static char *sanity_check(char *name, char *email)
37 int len = strlen(name);
38 if (len < 3 || len > 60)
39 return email;
40 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
41 return email;
42 return name;
45 static int bogus_from(char *line)
47 /* John Doe <johndoe> */
48 char *bra, *ket, *dst, *cp;
50 /* This is fallback, so do not bother if we already have an
51 * e-mail address.
52 */
53 if (*email)
54 return 0;
56 bra = strchr(line, '<');
57 if (!bra)
58 return 0;
59 ket = strchr(bra, '>');
60 if (!ket)
61 return 0;
63 for (dst = email, cp = bra+1; cp < ket; )
64 *dst++ = *cp++;
65 *dst = 0;
66 for (cp = line; isspace(*cp); cp++)
68 for (bra--; isspace(*bra); bra--)
69 *bra = 0;
70 cp = sanity_check(cp, email);
71 strcpy(name, cp);
72 return 1;
75 static int handle_from(char *line)
77 char *at = strchr(line, '@');
78 char *dst;
80 if (!at)
81 return bogus_from(line);
84 * If we already have one email, don't take any confusing lines
86 if (*email && strchr(at+1, '@'))
87 return 0;
89 /* Pick up the string around '@', possibly delimited with <>
90 * pair; that is the email part. White them out while copying.
92 while (at > line) {
93 char c = at[-1];
94 if (isspace(c))
95 break;
96 if (c == '<') {
97 at[-1] = ' ';
98 break;
100 at--;
102 dst = email;
103 for (;;) {
104 unsigned char c = *at;
105 if (!c || c == '>' || isspace(c)) {
106 if (c == '>')
107 *at = ' ';
108 break;
110 *at++ = ' ';
111 *dst++ = c;
113 *dst++ = 0;
115 /* The remainder is name. It could be "John Doe <john.doe@xz>"
116 * or "john.doe@xz (John Doe)", but we have whited out the
117 * email part, so trim from both ends, possibly removing
118 * the () pair at the end.
120 at = line + strlen(line);
121 while (at > line) {
122 unsigned char c = *--at;
123 if (!isspace(c)) {
124 at[(c == ')') ? 0 : 1] = 0;
125 break;
129 at = line;
130 for (;;) {
131 unsigned char c = *at;
132 if (!c || !isspace(c)) {
133 if (c == '(')
134 at++;
135 break;
137 at++;
139 at = sanity_check(at, email);
140 strcpy(name, at);
141 return 1;
144 static int handle_date(char *line)
146 strcpy(date, line);
147 return 0;
150 static int handle_subject(char *line)
152 strcpy(subject, line);
153 return 0;
156 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
157 * to have enough heuristics to grok MIME encoded patches often found
158 * on our mailing lists. For example, we do not even treat header lines
159 * case insensitively.
162 static int slurp_attr(const char *line, const char *name, char *attr)
164 char *ends, *ap = strcasestr(line, name);
165 size_t sz;
167 if (!ap) {
168 *attr = 0;
169 return 0;
171 ap += strlen(name);
172 if (*ap == '"') {
173 ap++;
174 ends = "\"";
176 else
177 ends = "; \t";
178 sz = strcspn(ap, ends);
179 memcpy(attr, ap, sz);
180 attr[sz] = 0;
181 return 1;
184 static int handle_subcontent_type(char *line)
186 /* We do not want to mess with boundary. Note that we do not
187 * handle nested multipart.
189 if (strcasestr(line, "boundary=")) {
190 fprintf(stderr, "Not handling nested multipart message.\n");
191 exit(1);
193 slurp_attr(line, "charset=", charset);
194 if (*charset) {
195 int i, c;
196 for (i = 0; (c = charset[i]) != 0; i++)
197 charset[i] = tolower(c);
199 return 0;
202 static int handle_content_type(char *line)
204 *multipart_boundary = 0;
205 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
206 memcpy(multipart_boundary, "--", 2);
207 multipart_boundary_len = strlen(multipart_boundary);
209 slurp_attr(line, "charset=", charset);
210 return 0;
213 static int handle_content_transfer_encoding(char *line)
215 if (strcasestr(line, "base64"))
216 transfer_encoding = TE_BASE64;
217 else if (strcasestr(line, "quoted-printable"))
218 transfer_encoding = TE_QP;
219 else
220 transfer_encoding = TE_DONTCARE;
221 return 0;
224 static int is_multipart_boundary(const char *line)
226 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
229 static int eatspace(char *line)
231 int len = strlen(line);
232 while (len > 0 && isspace(line[len-1]))
233 line[--len] = 0;
234 return len;
237 #define SEEN_FROM 01
238 #define SEEN_DATE 02
239 #define SEEN_SUBJECT 04
240 #define SEEN_BOGUS_UNIX_FROM 010
242 /* First lines of body can have From:, Date:, and Subject: */
243 static int handle_inbody_header(int *seen, char *line)
245 if (!memcmp(">From", line, 5) && isspace(line[5])) {
246 if (!(*seen & SEEN_BOGUS_UNIX_FROM)) {
247 *seen |= SEEN_BOGUS_UNIX_FROM;
248 return 1;
251 if (!memcmp("From:", line, 5) && isspace(line[5])) {
252 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
253 *seen |= SEEN_FROM;
254 return 1;
257 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
258 if (!(*seen & SEEN_DATE)) {
259 handle_date(line+6);
260 *seen |= SEEN_DATE;
261 return 1;
264 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
265 if (!(*seen & SEEN_SUBJECT)) {
266 handle_subject(line+9);
267 *seen |= SEEN_SUBJECT;
268 return 1;
271 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
272 if (!(*seen & SEEN_SUBJECT)) {
273 handle_subject(line);
274 *seen |= SEEN_SUBJECT;
275 return 1;
278 return 0;
281 static char *cleanup_subject(char *subject)
283 if (keep_subject)
284 return subject;
285 for (;;) {
286 char *p;
287 int len, remove;
288 switch (*subject) {
289 case 'r': case 'R':
290 if (!memcmp("e:", subject+1, 2)) {
291 subject +=3;
292 continue;
294 break;
295 case ' ': case '\t': case ':':
296 subject++;
297 continue;
299 case '[':
300 p = strchr(subject, ']');
301 if (!p) {
302 subject++;
303 continue;
305 len = strlen(p);
306 remove = p - subject;
307 if (remove <= len *2) {
308 subject = p+1;
309 continue;
311 break;
313 return subject;
317 static void cleanup_space(char *buf)
319 unsigned char c;
320 while ((c = *buf) != 0) {
321 buf++;
322 if (isspace(c)) {
323 buf[-1] = ' ';
324 c = *buf;
325 while (isspace(c)) {
326 int len = strlen(buf);
327 memmove(buf, buf+1, len);
328 c = *buf;
334 typedef int (*header_fn_t)(char *);
335 struct header_def {
336 const char *name;
337 header_fn_t func;
338 int namelen;
341 static void check_header(char *line, int len, struct header_def *header)
343 int i;
345 if (header[0].namelen <= 0) {
346 for (i = 0; header[i].name; i++)
347 header[i].namelen = strlen(header[i].name);
349 for (i = 0; header[i].name; i++) {
350 int len = header[i].namelen;
351 if (!strncasecmp(line, header[i].name, len) &&
352 line[len] == ':' && isspace(line[len + 1])) {
353 header[i].func(line + len + 2);
354 break;
359 static void check_subheader_line(char *line, int len)
361 static struct header_def header[] = {
362 { "Content-Type", handle_subcontent_type },
363 { "Content-Transfer-Encoding",
364 handle_content_transfer_encoding },
365 { NULL },
367 check_header(line, len, header);
369 static void check_header_line(char *line, int len)
371 static struct header_def header[] = {
372 { "From", handle_from },
373 { "Date", handle_date },
374 { "Subject", handle_subject },
375 { "Content-Type", handle_content_type },
376 { "Content-Transfer-Encoding",
377 handle_content_transfer_encoding },
378 { NULL },
380 check_header(line, len, header);
383 static int read_one_header_line(char *line, int sz, FILE *in)
385 int ofs = 0;
386 while (ofs < sz) {
387 int peek, len;
388 if (fgets(line + ofs, sz - ofs, in) == NULL)
389 return ofs;
390 len = eatspace(line + ofs);
391 if (len == 0)
392 return ofs;
393 peek = fgetc(in); ungetc(peek, in);
394 if (peek == ' ' || peek == '\t') {
395 /* Yuck, 2822 header "folding" */
396 ofs += len;
397 continue;
399 return ofs + len;
401 return ofs;
404 static unsigned hexval(int c)
406 if (c >= '0' && c <= '9')
407 return c - '0';
408 if (c >= 'a' && c <= 'f')
409 return c - 'a' + 10;
410 if (c >= 'A' && c <= 'F')
411 return c - 'A' + 10;
412 return ~0;
415 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
417 int c;
418 while ((c = *in++) != 0 && (in <= ep)) {
419 if (c == '=') {
420 int d = *in++;
421 if (d == '\n' || !d)
422 break; /* drop trailing newline */
423 *ot++ = ((hexval(d) << 4) | hexval(*in++));
424 continue;
426 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
427 c = 0x20;
428 *ot++ = c;
430 *ot = 0;
431 return 0;
434 static int decode_b_segment(char *in, char *ot, char *ep)
436 /* Decode in..ep, possibly in-place to ot */
437 int c, pos = 0, acc = 0;
439 while ((c = *in++) != 0 && (in <= ep)) {
440 if (c == '+')
441 c = 62;
442 else if (c == '/')
443 c = 63;
444 else if ('A' <= c && c <= 'Z')
445 c -= 'A';
446 else if ('a' <= c && c <= 'z')
447 c -= 'a' - 26;
448 else if ('0' <= c && c <= '9')
449 c -= '0' - 52;
450 else if (c == '=') {
451 /* padding is almost like (c == 0), except we do
452 * not output NUL resulting only from it;
453 * for now we just trust the data.
455 c = 0;
457 else
458 continue; /* garbage */
459 switch (pos++) {
460 case 0:
461 acc = (c << 2);
462 break;
463 case 1:
464 *ot++ = (acc | (c >> 4));
465 acc = (c & 15) << 4;
466 break;
467 case 2:
468 *ot++ = (acc | (c >> 2));
469 acc = (c & 3) << 6;
470 break;
471 case 3:
472 *ot++ = (acc | c);
473 acc = pos = 0;
474 break;
477 *ot = 0;
478 return 0;
481 static void convert_to_utf8(char *line, char *charset)
483 #ifndef NO_ICONV
484 char *in, *out;
485 size_t insize, outsize, nrc;
486 char outbuf[4096]; /* cheat */
487 static char latin_one[] = "latin1";
488 char *input_charset = *charset ? charset : latin_one;
489 iconv_t conv = iconv_open(metainfo_charset, input_charset);
491 if (conv == (iconv_t) -1) {
492 static int warned_latin1_once = 0;
493 if (input_charset != latin_one) {
494 fprintf(stderr, "cannot convert from %s to %s\n",
495 input_charset, metainfo_charset);
496 *charset = 0;
498 else if (!warned_latin1_once) {
499 warned_latin1_once = 1;
500 fprintf(stderr, "tried to convert from %s to %s, "
501 "but your iconv does not work with it.\n",
502 input_charset, metainfo_charset);
504 return;
506 in = line;
507 insize = strlen(in);
508 out = outbuf;
509 outsize = sizeof(outbuf);
510 nrc = iconv(conv, &in, &insize, &out, &outsize);
511 iconv_close(conv);
512 if (nrc == (size_t) -1)
513 return;
514 *out = 0;
515 strcpy(line, outbuf);
516 #endif
519 static void decode_header_bq(char *it)
521 char *in, *out, *ep, *cp, *sp;
522 char outbuf[1000];
524 in = it;
525 out = outbuf;
526 while ((ep = strstr(in, "=?")) != NULL) {
527 int sz, encoding;
528 char charset_q[256], piecebuf[256];
529 if (in != ep) {
530 sz = ep - in;
531 memcpy(out, in, sz);
532 out += sz;
533 in += sz;
535 /* E.g.
536 * ep : "=?iso-2022-jp?B?GyR...?= foo"
537 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
539 ep += 2;
540 cp = strchr(ep, '?');
541 if (!cp)
542 return; /* no munging */
543 for (sp = ep; sp < cp; sp++)
544 charset_q[sp - ep] = tolower(*sp);
545 charset_q[cp - ep] = 0;
546 encoding = cp[1];
547 if (!encoding || cp[2] != '?')
548 return; /* no munging */
549 ep = strstr(cp + 3, "?=");
550 if (!ep)
551 return; /* no munging */
552 switch (tolower(encoding)) {
553 default:
554 return; /* no munging */
555 case 'b':
556 sz = decode_b_segment(cp + 3, piecebuf, ep);
557 break;
558 case 'q':
559 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
560 break;
562 if (sz < 0)
563 return;
564 if (metainfo_charset)
565 convert_to_utf8(piecebuf, charset_q);
566 strcpy(out, piecebuf);
567 out += strlen(out);
568 in = ep + 2;
570 strcpy(out, in);
571 strcpy(it, outbuf);
574 static void decode_transfer_encoding(char *line)
576 char *ep;
578 switch (transfer_encoding) {
579 case TE_QP:
580 ep = line + strlen(line);
581 decode_q_segment(line, line, ep, 0);
582 break;
583 case TE_BASE64:
584 ep = line + strlen(line);
585 decode_b_segment(line, line, ep);
586 break;
587 case TE_DONTCARE:
588 break;
592 static void handle_info(void)
594 char *sub;
595 static int done_info = 0;
597 if (done_info)
598 return;
600 done_info = 1;
601 sub = cleanup_subject(subject);
602 cleanup_space(name);
603 cleanup_space(date);
604 cleanup_space(email);
605 cleanup_space(sub);
607 /* Unwrap inline B and Q encoding, and optionally
608 * normalize the meta information to utf8.
610 decode_header_bq(name);
611 decode_header_bq(date);
612 decode_header_bq(email);
613 decode_header_bq(sub);
614 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
615 name, email, sub, date);
618 /* We are inside message body and have read line[] already.
619 * Spit out the commit log.
621 static int handle_commit_msg(void)
623 if (!cmitmsg)
624 return 0;
625 do {
626 if (!memcmp("diff -", line, 6) ||
627 !memcmp("---", line, 3) ||
628 !memcmp("Index: ", line, 7))
629 break;
630 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
631 /* We come here when the first part had only
632 * the commit message without any patch. We
633 * pretend we have not seen this line yet, and
634 * go back to the loop.
636 return 1;
639 /* Unwrap transfer encoding and optionally
640 * normalize the log message to UTF-8.
642 decode_transfer_encoding(line);
643 if (metainfo_charset)
644 convert_to_utf8(line, charset);
645 fputs(line, cmitmsg);
646 } while (fgets(line, sizeof(line), stdin) != NULL);
647 fclose(cmitmsg);
648 cmitmsg = NULL;
649 return 0;
652 /* We have done the commit message and have the first
653 * line of the patch in line[].
655 static void handle_patch(void)
657 do {
658 if (multipart_boundary[0] && is_multipart_boundary(line))
659 break;
660 /* Only unwrap transfer encoding but otherwise do not
661 * do anything. We do *NOT* want UTF-8 conversion
662 * here; we are dealing with the user payload.
664 decode_transfer_encoding(line);
665 fputs(line, patchfile);
666 patch_lines++;
667 } while (fgets(line, sizeof(line), stdin) != NULL);
670 /* multipart boundary and transfer encoding are set up for us, and we
671 * are at the end of the sub header. do equivalent of handle_body up
672 * to the next boundary without closing patchfile --- we will expect
673 * that the first part to contain commit message and a patch, and
674 * handle other parts as pure patches.
676 static int handle_multipart_one_part(void)
678 int seen = 0;
679 int n = 0;
680 int len;
682 while (fgets(line, sizeof(line), stdin) != NULL) {
683 again:
684 len = eatspace(line);
685 n++;
686 if (!len)
687 continue;
688 if (is_multipart_boundary(line))
689 break;
690 if (0 <= seen && handle_inbody_header(&seen, line))
691 continue;
692 seen = -1; /* no more inbody headers */
693 line[len] = '\n';
694 handle_info();
695 if (handle_commit_msg())
696 goto again;
697 handle_patch();
698 break;
700 if (n == 0)
701 return -1;
702 return 0;
705 static void handle_multipart_body(void)
707 int part_num = 0;
709 /* Skip up to the first boundary */
710 while (fgets(line, sizeof(line), stdin) != NULL)
711 if (is_multipart_boundary(line)) {
712 part_num = 1;
713 break;
715 if (!part_num)
716 return;
717 /* We are on boundary line. Start slurping the subhead. */
718 while (1) {
719 int len = read_one_header_line(line, sizeof(line), stdin);
720 if (!len) {
721 if (handle_multipart_one_part() < 0)
722 return;
723 /* Reset per part headers */
724 transfer_encoding = TE_DONTCARE;
725 charset[0] = 0;
727 else
728 check_subheader_line(line, len);
730 fclose(patchfile);
731 if (!patch_lines) {
732 fprintf(stderr, "No patch found\n");
733 exit(1);
737 /* Non multipart message */
738 static void handle_body(void)
740 int seen = 0;
742 while (fgets(line, sizeof(line), stdin) != NULL) {
743 int len = eatspace(line);
744 if (!len)
745 continue;
746 if (0 <= seen && handle_inbody_header(&seen, line))
747 continue;
748 seen = -1; /* no more inbody headers */
749 line[len] = '\n';
750 handle_info();
751 handle_commit_msg();
752 handle_patch();
753 break;
755 fclose(patchfile);
756 if (!patch_lines) {
757 fprintf(stderr, "No patch found\n");
758 exit(1);
762 static const char mailinfo_usage[] =
763 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
765 int main(int argc, char **argv)
767 /* NEEDSWORK: might want to do the optional .git/ directory
768 * discovery
770 git_config(git_default_config);
772 while (1 < argc && argv[1][0] == '-') {
773 if (!strcmp(argv[1], "-k"))
774 keep_subject = 1;
775 else if (!strcmp(argv[1], "-u"))
776 metainfo_charset = git_commit_encoding;
777 else if (!strncmp(argv[1], "--encoding=", 11))
778 metainfo_charset = argv[1] + 11;
779 else
780 usage(mailinfo_usage);
781 argc--; argv++;
784 if (argc != 3)
785 usage(mailinfo_usage);
786 cmitmsg = fopen(argv[1], "w");
787 if (!cmitmsg) {
788 perror(argv[1]);
789 exit(1);
791 patchfile = fopen(argv[2], "w");
792 if (!patchfile) {
793 perror(argv[2]);
794 exit(1);
796 while (1) {
797 int len = read_one_header_line(line, sizeof(line), stdin);
798 if (!len) {
799 if (multipart_boundary[0])
800 handle_multipart_body();
801 else
802 handle_body();
803 break;
805 check_header_line(line, len);
807 return 0;