Move B and Q decoding into check header.
[git/debian.git] / mailinfo.c
blobbee7b202cfc5d8c1a2b7e642cf62539973ea514d
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
241 /* First lines of body can have From:, Date:, and Subject: */
242 static int handle_inbody_header(int *seen, char *line)
244 if (!memcmp("From:", line, 5) && isspace(line[5])) {
245 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
246 *seen |= SEEN_FROM;
247 return 1;
250 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
251 if (!(*seen & SEEN_DATE)) {
252 handle_date(line+6);
253 *seen |= SEEN_DATE;
254 return 1;
257 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
258 if (!(*seen & SEEN_SUBJECT)) {
259 handle_subject(line+9);
260 *seen |= SEEN_SUBJECT;
261 return 1;
264 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
265 if (!(*seen & SEEN_SUBJECT)) {
266 handle_subject(line);
267 *seen |= SEEN_SUBJECT;
268 return 1;
271 return 0;
274 static char *cleanup_subject(char *subject)
276 if (keep_subject)
277 return subject;
278 for (;;) {
279 char *p;
280 int len, remove;
281 switch (*subject) {
282 case 'r': case 'R':
283 if (!memcmp("e:", subject+1, 2)) {
284 subject +=3;
285 continue;
287 break;
288 case ' ': case '\t': case ':':
289 subject++;
290 continue;
292 case '[':
293 p = strchr(subject, ']');
294 if (!p) {
295 subject++;
296 continue;
298 len = strlen(p);
299 remove = p - subject;
300 if (remove <= len *2) {
301 subject = p+1;
302 continue;
304 break;
306 return subject;
310 static void cleanup_space(char *buf)
312 unsigned char c;
313 while ((c = *buf) != 0) {
314 buf++;
315 if (isspace(c)) {
316 buf[-1] = ' ';
317 c = *buf;
318 while (isspace(c)) {
319 int len = strlen(buf);
320 memmove(buf, buf+1, len);
321 c = *buf;
327 static void decode_header_bq(char *it);
328 typedef int (*header_fn_t)(char *);
329 struct header_def {
330 const char *name;
331 header_fn_t func;
332 int namelen;
335 static void check_header(char *line, struct header_def *header)
337 int i;
339 if (header[0].namelen <= 0) {
340 for (i = 0; header[i].name; i++)
341 header[i].namelen = strlen(header[i].name);
343 for (i = 0; header[i].name; i++) {
344 int len = header[i].namelen;
345 if (!strncasecmp(line, header[i].name, len) &&
346 line[len] == ':' && isspace(line[len + 1])) {
347 /* Unwrap inline B and Q encoding, and optionally
348 * normalize the meta information to utf8.
350 decode_header_bq(line + len + 2);
351 header[i].func(line + len + 2);
352 break;
357 static void check_subheader_line(char *line)
359 static struct header_def header[] = {
360 { "Content-Type", handle_subcontent_type },
361 { "Content-Transfer-Encoding",
362 handle_content_transfer_encoding },
363 { NULL },
365 check_header(line, header);
367 static void check_header_line(char *line)
369 static struct header_def header[] = {
370 { "From", handle_from },
371 { "Date", handle_date },
372 { "Subject", handle_subject },
373 { "Content-Type", handle_content_type },
374 { "Content-Transfer-Encoding",
375 handle_content_transfer_encoding },
376 { NULL },
378 check_header(line, header);
381 static int read_one_header_line(char *line, int sz, FILE *in)
383 int ofs = 0;
384 while (ofs < sz) {
385 int peek, len;
386 if (fgets(line + ofs, sz - ofs, in) == NULL)
387 return ofs;
388 len = eatspace(line + ofs);
389 if (len == 0)
390 return ofs;
391 peek = fgetc(in); ungetc(peek, in);
392 if (peek == ' ' || peek == '\t') {
393 /* Yuck, 2822 header "folding" */
394 ofs += len;
395 continue;
397 return ofs + len;
399 return ofs;
402 static unsigned hexval(int c)
404 if (c >= '0' && c <= '9')
405 return c - '0';
406 if (c >= 'a' && c <= 'f')
407 return c - 'a' + 10;
408 if (c >= 'A' && c <= 'F')
409 return c - 'A' + 10;
410 return ~0;
413 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
415 int c;
416 while ((c = *in++) != 0 && (in <= ep)) {
417 if (c == '=') {
418 int d = *in++;
419 if (d == '\n' || !d)
420 break; /* drop trailing newline */
421 *ot++ = ((hexval(d) << 4) | hexval(*in++));
422 continue;
424 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
425 c = 0x20;
426 *ot++ = c;
428 *ot = 0;
429 return 0;
432 static int decode_b_segment(char *in, char *ot, char *ep)
434 /* Decode in..ep, possibly in-place to ot */
435 int c, pos = 0, acc = 0;
437 while ((c = *in++) != 0 && (in <= ep)) {
438 if (c == '+')
439 c = 62;
440 else if (c == '/')
441 c = 63;
442 else if ('A' <= c && c <= 'Z')
443 c -= 'A';
444 else if ('a' <= c && c <= 'z')
445 c -= 'a' - 26;
446 else if ('0' <= c && c <= '9')
447 c -= '0' - 52;
448 else if (c == '=') {
449 /* padding is almost like (c == 0), except we do
450 * not output NUL resulting only from it;
451 * for now we just trust the data.
453 c = 0;
455 else
456 continue; /* garbage */
457 switch (pos++) {
458 case 0:
459 acc = (c << 2);
460 break;
461 case 1:
462 *ot++ = (acc | (c >> 4));
463 acc = (c & 15) << 4;
464 break;
465 case 2:
466 *ot++ = (acc | (c >> 2));
467 acc = (c & 3) << 6;
468 break;
469 case 3:
470 *ot++ = (acc | c);
471 acc = pos = 0;
472 break;
475 *ot = 0;
476 return 0;
479 static void convert_to_utf8(char *line, char *charset)
481 #ifndef NO_ICONV
482 char *in, *out;
483 size_t insize, outsize, nrc;
484 char outbuf[4096]; /* cheat */
485 static char latin_one[] = "latin1";
486 char *input_charset = *charset ? charset : latin_one;
487 iconv_t conv = iconv_open(metainfo_charset, input_charset);
489 if (conv == (iconv_t) -1) {
490 static int warned_latin1_once = 0;
491 if (input_charset != latin_one) {
492 fprintf(stderr, "cannot convert from %s to %s\n",
493 input_charset, metainfo_charset);
494 *charset = 0;
496 else if (!warned_latin1_once) {
497 warned_latin1_once = 1;
498 fprintf(stderr, "tried to convert from %s to %s, "
499 "but your iconv does not work with it.\n",
500 input_charset, metainfo_charset);
502 return;
504 in = line;
505 insize = strlen(in);
506 out = outbuf;
507 outsize = sizeof(outbuf);
508 nrc = iconv(conv, &in, &insize, &out, &outsize);
509 iconv_close(conv);
510 if (nrc == (size_t) -1)
511 return;
512 *out = 0;
513 strcpy(line, outbuf);
514 #endif
517 static void decode_header_bq(char *it)
519 char *in, *out, *ep, *cp, *sp;
520 char outbuf[1000];
522 in = it;
523 out = outbuf;
524 while ((ep = strstr(in, "=?")) != NULL) {
525 int sz, encoding;
526 char charset_q[256], piecebuf[256];
527 if (in != ep) {
528 sz = ep - in;
529 memcpy(out, in, sz);
530 out += sz;
531 in += sz;
533 /* E.g.
534 * ep : "=?iso-2022-jp?B?GyR...?= foo"
535 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
537 ep += 2;
538 cp = strchr(ep, '?');
539 if (!cp)
540 return; /* no munging */
541 for (sp = ep; sp < cp; sp++)
542 charset_q[sp - ep] = tolower(*sp);
543 charset_q[cp - ep] = 0;
544 encoding = cp[1];
545 if (!encoding || cp[2] != '?')
546 return; /* no munging */
547 ep = strstr(cp + 3, "?=");
548 if (!ep)
549 return; /* no munging */
550 switch (tolower(encoding)) {
551 default:
552 return; /* no munging */
553 case 'b':
554 sz = decode_b_segment(cp + 3, piecebuf, ep);
555 break;
556 case 'q':
557 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
558 break;
560 if (sz < 0)
561 return;
562 if (metainfo_charset)
563 convert_to_utf8(piecebuf, charset_q);
564 strcpy(out, piecebuf);
565 out += strlen(out);
566 in = ep + 2;
568 strcpy(out, in);
569 strcpy(it, outbuf);
572 static void decode_transfer_encoding(char *line)
574 char *ep;
576 switch (transfer_encoding) {
577 case TE_QP:
578 ep = line + strlen(line);
579 decode_q_segment(line, line, ep, 0);
580 break;
581 case TE_BASE64:
582 ep = line + strlen(line);
583 decode_b_segment(line, line, ep);
584 break;
585 case TE_DONTCARE:
586 break;
590 static void handle_info(void)
592 char *sub;
593 static int done_info = 0;
595 if (done_info)
596 return;
598 done_info = 1;
599 sub = cleanup_subject(subject);
600 cleanup_space(name);
601 cleanup_space(date);
602 cleanup_space(email);
603 cleanup_space(sub);
605 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
606 name, email, sub, date);
609 /* We are inside message body and have read line[] already.
610 * Spit out the commit log.
612 static int handle_commit_msg(void)
614 if (!cmitmsg)
615 return 0;
616 do {
617 if (!memcmp("diff -", line, 6) ||
618 !memcmp("---", line, 3) ||
619 !memcmp("Index: ", line, 7))
620 break;
621 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
622 /* We come here when the first part had only
623 * the commit message without any patch. We
624 * pretend we have not seen this line yet, and
625 * go back to the loop.
627 return 1;
630 /* Unwrap transfer encoding and optionally
631 * normalize the log message to UTF-8.
633 decode_transfer_encoding(line);
634 if (metainfo_charset)
635 convert_to_utf8(line, charset);
636 fputs(line, cmitmsg);
637 } while (fgets(line, sizeof(line), stdin) != NULL);
638 fclose(cmitmsg);
639 cmitmsg = NULL;
640 return 0;
643 /* We have done the commit message and have the first
644 * line of the patch in line[].
646 static void handle_patch(void)
648 do {
649 if (multipart_boundary[0] && is_multipart_boundary(line))
650 break;
651 /* Only unwrap transfer encoding but otherwise do not
652 * do anything. We do *NOT* want UTF-8 conversion
653 * here; we are dealing with the user payload.
655 decode_transfer_encoding(line);
656 fputs(line, patchfile);
657 patch_lines++;
658 } while (fgets(line, sizeof(line), stdin) != NULL);
661 /* multipart boundary and transfer encoding are set up for us, and we
662 * are at the end of the sub header. do equivalent of handle_body up
663 * to the next boundary without closing patchfile --- we will expect
664 * that the first part to contain commit message and a patch, and
665 * handle other parts as pure patches.
667 static int handle_multipart_one_part(void)
669 int seen = 0;
670 int n = 0;
671 int len;
673 while (fgets(line, sizeof(line), stdin) != NULL) {
674 again:
675 len = eatspace(line);
676 n++;
677 if (!len)
678 continue;
679 if (is_multipart_boundary(line))
680 break;
681 if (0 <= seen && handle_inbody_header(&seen, line))
682 continue;
683 seen = -1; /* no more inbody headers */
684 line[len] = '\n';
685 handle_info();
686 if (handle_commit_msg())
687 goto again;
688 handle_patch();
689 break;
691 if (n == 0)
692 return -1;
693 return 0;
696 static void handle_multipart_body(void)
698 int part_num = 0;
700 /* Skip up to the first boundary */
701 while (fgets(line, sizeof(line), stdin) != NULL)
702 if (is_multipart_boundary(line)) {
703 part_num = 1;
704 break;
706 if (!part_num)
707 return;
708 /* We are on boundary line. Start slurping the subhead. */
709 while (1) {
710 int hdr = read_one_header_line(line, sizeof(line), stdin);
711 if (!hdr) {
712 if (handle_multipart_one_part() < 0)
713 return;
714 /* Reset per part headers */
715 transfer_encoding = TE_DONTCARE;
716 charset[0] = 0;
718 else
719 check_subheader_line(line);
721 fclose(patchfile);
722 if (!patch_lines) {
723 fprintf(stderr, "No patch found\n");
724 exit(1);
728 /* Non multipart message */
729 static void handle_body(void)
731 int seen = 0;
733 while (fgets(line, sizeof(line), stdin) != NULL) {
734 int len = eatspace(line);
735 if (!len)
736 continue;
737 if (0 <= seen && handle_inbody_header(&seen, line))
738 continue;
739 seen = -1; /* no more inbody headers */
740 line[len] = '\n';
741 handle_info();
742 handle_commit_msg();
743 handle_patch();
744 break;
746 fclose(patchfile);
747 if (!patch_lines) {
748 fprintf(stderr, "No patch found\n");
749 exit(1);
753 static const char mailinfo_usage[] =
754 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
756 int main(int argc, char **argv)
758 /* NEEDSWORK: might want to do the optional .git/ directory
759 * discovery
761 git_config(git_default_config);
763 while (1 < argc && argv[1][0] == '-') {
764 if (!strcmp(argv[1], "-k"))
765 keep_subject = 1;
766 else if (!strcmp(argv[1], "-u"))
767 metainfo_charset = git_commit_encoding;
768 else if (!strncmp(argv[1], "--encoding=", 11))
769 metainfo_charset = argv[1] + 11;
770 else
771 usage(mailinfo_usage);
772 argc--; argv++;
775 if (argc != 3)
776 usage(mailinfo_usage);
777 cmitmsg = fopen(argv[1], "w");
778 if (!cmitmsg) {
779 perror(argv[1]);
780 exit(1);
782 patchfile = fopen(argv[2], "w");
783 if (!patchfile) {
784 perror(argv[2]);
785 exit(1);
787 while (1) {
788 int hdr = read_one_header_line(line, sizeof(line), stdin);
789 if (!hdr) {
790 if (multipart_boundary[0])
791 handle_multipart_body();
792 else
793 handle_body();
794 break;
796 check_header_line(line);
798 return 0;