Everyday: a bit more examples.
[alt-git.git] / mailinfo.c
blobd4b4163628e582185e8a28defe009c75aa62edab
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 #include <iconv.h>
11 #include "git-compat-util.h"
12 #include "cache.h"
14 static FILE *cmitmsg, *patchfile;
16 static int keep_subject = 0;
17 static char *metainfo_charset = NULL;
18 static char line[1000];
19 static char date[1000];
20 static char name[1000];
21 static char email[1000];
22 static char subject[1000];
24 static enum {
25 TE_DONTCARE, TE_QP, TE_BASE64,
26 } transfer_encoding;
27 static char charset[256];
29 static char multipart_boundary[1000];
30 static int multipart_boundary_len;
31 static int patch_lines = 0;
33 static char *sanity_check(char *name, char *email)
35 int len = strlen(name);
36 if (len < 3 || len > 60)
37 return email;
38 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
39 return email;
40 return name;
43 static int handle_from(char *line)
45 char *at = strchr(line, '@');
46 char *dst;
48 if (!at)
49 return 0;
52 * If we already have one email, don't take any confusing lines
54 if (*email && strchr(at+1, '@'))
55 return 0;
57 /* Pick up the string around '@', possibly delimited with <>
58 * pair; that is the email part. White them out while copying.
60 while (at > line) {
61 char c = at[-1];
62 if (isspace(c))
63 break;
64 if (c == '<') {
65 at[-1] = ' ';
66 break;
68 at--;
70 dst = email;
71 for (;;) {
72 unsigned char c = *at;
73 if (!c || c == '>' || isspace(c)) {
74 if (c == '>')
75 *at = ' ';
76 break;
78 *at++ = ' ';
79 *dst++ = c;
81 *dst++ = 0;
83 /* The remainder is name. It could be "John Doe <john.doe@xz>"
84 * or "john.doe@xz (John Doe)", but we have whited out the
85 * email part, so trim from both ends, possibly removing
86 * the () pair at the end.
88 at = line + strlen(line);
89 while (at > line) {
90 unsigned char c = *--at;
91 if (!isspace(c)) {
92 at[(c == ')') ? 0 : 1] = 0;
93 break;
97 at = line;
98 for (;;) {
99 unsigned char c = *at;
100 if (!c || !isspace(c)) {
101 if (c == '(')
102 at++;
103 break;
105 at++;
107 at = sanity_check(at, email);
108 strcpy(name, at);
109 return 1;
112 static int handle_date(char *line)
114 strcpy(date, line);
115 return 0;
118 static int handle_subject(char *line)
120 strcpy(subject, line);
121 return 0;
124 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
125 * to have enough heuristics to grok MIME encoded patches often found
126 * on our mailing lists. For example, we do not even treat header lines
127 * case insensitively.
130 static int slurp_attr(const char *line, const char *name, char *attr)
132 char *ends, *ap = strcasestr(line, name);
133 size_t sz;
135 if (!ap) {
136 *attr = 0;
137 return 0;
139 ap += strlen(name);
140 if (*ap == '"') {
141 ap++;
142 ends = "\"";
144 else
145 ends = "; \t";
146 sz = strcspn(ap, ends);
147 memcpy(attr, ap, sz);
148 attr[sz] = 0;
149 return 1;
152 static int handle_subcontent_type(char *line)
154 /* We do not want to mess with boundary. Note that we do not
155 * handle nested multipart.
157 if (strcasestr(line, "boundary=")) {
158 fprintf(stderr, "Not handling nested multipart message.\n");
159 exit(1);
161 slurp_attr(line, "charset=", charset);
162 if (*charset) {
163 int i, c;
164 for (i = 0; (c = charset[i]) != 0; i++)
165 charset[i] = tolower(c);
167 return 0;
170 static int handle_content_type(char *line)
172 *multipart_boundary = 0;
173 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
174 memcpy(multipart_boundary, "--", 2);
175 multipart_boundary_len = strlen(multipart_boundary);
177 slurp_attr(line, "charset=", charset);
178 return 0;
181 static int handle_content_transfer_encoding(char *line)
183 if (strcasestr(line, "base64"))
184 transfer_encoding = TE_BASE64;
185 else if (strcasestr(line, "quoted-printable"))
186 transfer_encoding = TE_QP;
187 else
188 transfer_encoding = TE_DONTCARE;
189 return 0;
192 static int is_multipart_boundary(const char *line)
194 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
197 static int eatspace(char *line)
199 int len = strlen(line);
200 while (len > 0 && isspace(line[len-1]))
201 line[--len] = 0;
202 return len;
205 #define SEEN_FROM 01
206 #define SEEN_DATE 02
207 #define SEEN_SUBJECT 04
209 /* First lines of body can have From:, Date:, and Subject: */
210 static int handle_inbody_header(int *seen, char *line)
212 if (!memcmp("From:", line, 5) && isspace(line[5])) {
213 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
214 *seen |= SEEN_FROM;
215 return 1;
218 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
219 if (!(*seen & SEEN_DATE)) {
220 handle_date(line+6);
221 *seen |= SEEN_DATE;
222 return 1;
225 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
226 if (!(*seen & SEEN_SUBJECT)) {
227 handle_subject(line+9);
228 *seen |= SEEN_SUBJECT;
229 return 1;
232 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
233 if (!(*seen & SEEN_SUBJECT)) {
234 handle_subject(line);
235 *seen |= SEEN_SUBJECT;
236 return 1;
239 return 0;
242 static char *cleanup_subject(char *subject)
244 if (keep_subject)
245 return subject;
246 for (;;) {
247 char *p;
248 int len, remove;
249 switch (*subject) {
250 case 'r': case 'R':
251 if (!memcmp("e:", subject+1, 2)) {
252 subject +=3;
253 continue;
255 break;
256 case ' ': case '\t': case ':':
257 subject++;
258 continue;
260 case '[':
261 p = strchr(subject, ']');
262 if (!p) {
263 subject++;
264 continue;
266 len = strlen(p);
267 remove = p - subject;
268 if (remove <= len *2) {
269 subject = p+1;
270 continue;
272 break;
274 return subject;
278 static void cleanup_space(char *buf)
280 unsigned char c;
281 while ((c = *buf) != 0) {
282 buf++;
283 if (isspace(c)) {
284 buf[-1] = ' ';
285 c = *buf;
286 while (isspace(c)) {
287 int len = strlen(buf);
288 memmove(buf, buf+1, len);
289 c = *buf;
295 typedef int (*header_fn_t)(char *);
296 struct header_def {
297 const char *name;
298 header_fn_t func;
299 int namelen;
302 static void check_header(char *line, int len, struct header_def *header)
304 int i;
306 if (header[0].namelen <= 0) {
307 for (i = 0; header[i].name; i++)
308 header[i].namelen = strlen(header[i].name);
310 for (i = 0; header[i].name; i++) {
311 int len = header[i].namelen;
312 if (!strncasecmp(line, header[i].name, len) &&
313 line[len] == ':' && isspace(line[len + 1])) {
314 header[i].func(line + len + 2);
315 break;
320 static void check_subheader_line(char *line, int len)
322 static struct header_def header[] = {
323 { "Content-Type", handle_subcontent_type },
324 { "Content-Transfer-Encoding",
325 handle_content_transfer_encoding },
326 { NULL },
328 check_header(line, len, header);
330 static void check_header_line(char *line, int len)
332 static struct header_def header[] = {
333 { "From", handle_from },
334 { "Date", handle_date },
335 { "Subject", handle_subject },
336 { "Content-Type", handle_content_type },
337 { "Content-Transfer-Encoding",
338 handle_content_transfer_encoding },
339 { NULL },
341 check_header(line, len, header);
344 static int read_one_header_line(char *line, int sz, FILE *in)
346 int ofs = 0;
347 while (ofs < sz) {
348 int peek, len;
349 if (fgets(line + ofs, sz - ofs, in) == NULL)
350 return ofs;
351 len = eatspace(line + ofs);
352 if (len == 0)
353 return ofs;
354 peek = fgetc(in); ungetc(peek, in);
355 if (peek == ' ' || peek == '\t') {
356 /* Yuck, 2822 header "folding" */
357 ofs += len;
358 continue;
360 return ofs + len;
362 return ofs;
365 static unsigned hexval(int c)
367 if (c >= '0' && c <= '9')
368 return c - '0';
369 if (c >= 'a' && c <= 'f')
370 return c - 'a' + 10;
371 if (c >= 'A' && c <= 'F')
372 return c - 'A' + 10;
373 return ~0;
376 static int decode_q_segment(char *in, char *ot, char *ep)
378 int c;
379 while ((c = *in++) != 0 && (in <= ep)) {
380 if (c == '=') {
381 int d = *in++;
382 if (d == '\n' || !d)
383 break; /* drop trailing newline */
384 *ot++ = ((hexval(d) << 4) | hexval(*in++));
386 else
387 *ot++ = c;
389 *ot = 0;
390 return 0;
393 static int decode_b_segment(char *in, char *ot, char *ep)
395 /* Decode in..ep, possibly in-place to ot */
396 int c, pos = 0, acc = 0;
398 while ((c = *in++) != 0 && (in <= ep)) {
399 if (c == '+')
400 c = 62;
401 else if (c == '/')
402 c = 63;
403 else if ('A' <= c && c <= 'Z')
404 c -= 'A';
405 else if ('a' <= c && c <= 'z')
406 c -= 'a' - 26;
407 else if ('0' <= c && c <= '9')
408 c -= '0' - 52;
409 else if (c == '=') {
410 /* padding is almost like (c == 0), except we do
411 * not output NUL resulting only from it;
412 * for now we just trust the data.
414 c = 0;
416 else
417 continue; /* garbage */
418 switch (pos++) {
419 case 0:
420 acc = (c << 2);
421 break;
422 case 1:
423 *ot++ = (acc | (c >> 4));
424 acc = (c & 15) << 4;
425 break;
426 case 2:
427 *ot++ = (acc | (c >> 2));
428 acc = (c & 3) << 6;
429 break;
430 case 3:
431 *ot++ = (acc | c);
432 acc = pos = 0;
433 break;
436 *ot = 0;
437 return 0;
440 static void convert_to_utf8(char *line, char *charset)
442 char *in, *out;
443 size_t insize, outsize, nrc;
444 char outbuf[4096]; /* cheat */
445 static char latin_one[] = "latin-1";
446 char *input_charset = *charset ? charset : latin_one;
447 iconv_t conv = iconv_open(metainfo_charset, input_charset);
449 if (conv == (iconv_t) -1) {
450 static int warned_latin1_once = 0;
451 if (input_charset != latin_one) {
452 fprintf(stderr, "cannot convert from %s to %s\n",
453 input_charset, metainfo_charset);
454 *charset = 0;
456 else if (!warned_latin1_once) {
457 warned_latin1_once = 1;
458 fprintf(stderr, "tried to convert from %s to %s, "
459 "but your iconv does not work with it.\n",
460 input_charset, metainfo_charset);
462 return;
464 in = line;
465 insize = strlen(in);
466 out = outbuf;
467 outsize = sizeof(outbuf);
468 nrc = iconv(conv, &in, &insize, &out, &outsize);
469 iconv_close(conv);
470 if (nrc == (size_t) -1)
471 return;
472 *out = 0;
473 strcpy(line, outbuf);
476 static void decode_header_bq(char *it)
478 char *in, *out, *ep, *cp, *sp;
479 char outbuf[1000];
481 in = it;
482 out = outbuf;
483 while ((ep = strstr(in, "=?")) != NULL) {
484 int sz, encoding;
485 char charset_q[256], piecebuf[256];
486 if (in != ep) {
487 sz = ep - in;
488 memcpy(out, in, sz);
489 out += sz;
490 in += sz;
492 /* E.g.
493 * ep : "=?iso-2022-jp?B?GyR...?= foo"
494 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
496 ep += 2;
497 cp = strchr(ep, '?');
498 if (!cp)
499 return; /* no munging */
500 for (sp = ep; sp < cp; sp++)
501 charset_q[sp - ep] = tolower(*sp);
502 charset_q[cp - ep] = 0;
503 encoding = cp[1];
504 if (!encoding || cp[2] != '?')
505 return; /* no munging */
506 ep = strstr(cp + 3, "?=");
507 if (!ep)
508 return; /* no munging */
509 switch (tolower(encoding)) {
510 default:
511 return; /* no munging */
512 case 'b':
513 sz = decode_b_segment(cp + 3, piecebuf, ep);
514 break;
515 case 'q':
516 sz = decode_q_segment(cp + 3, piecebuf, ep);
517 break;
519 if (sz < 0)
520 return;
521 if (metainfo_charset)
522 convert_to_utf8(piecebuf, charset_q);
523 strcpy(out, piecebuf);
524 out += strlen(out);
525 in = ep + 2;
527 strcpy(out, in);
528 strcpy(it, outbuf);
531 static void decode_transfer_encoding(char *line)
533 char *ep;
535 switch (transfer_encoding) {
536 case TE_QP:
537 ep = line + strlen(line);
538 decode_q_segment(line, line, ep);
539 break;
540 case TE_BASE64:
541 ep = line + strlen(line);
542 decode_b_segment(line, line, ep);
543 break;
544 case TE_DONTCARE:
545 break;
549 static void handle_info(void)
551 char *sub;
552 static int done_info = 0;
554 if (done_info)
555 return;
557 done_info = 1;
558 sub = cleanup_subject(subject);
559 cleanup_space(name);
560 cleanup_space(date);
561 cleanup_space(email);
562 cleanup_space(sub);
564 /* Unwrap inline B and Q encoding, and optionally
565 * normalize the meta information to utf8.
567 decode_header_bq(name);
568 decode_header_bq(date);
569 decode_header_bq(email);
570 decode_header_bq(sub);
571 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
572 name, email, sub, date);
575 /* We are inside message body and have read line[] already.
576 * Spit out the commit log.
578 static int handle_commit_msg(void)
580 if (!cmitmsg)
581 return 0;
582 do {
583 if (!memcmp("diff -", line, 6) ||
584 !memcmp("---", line, 3) ||
585 !memcmp("Index: ", line, 7))
586 break;
587 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
588 /* We come here when the first part had only
589 * the commit message without any patch. We
590 * pretend we have not seen this line yet, and
591 * go back to the loop.
593 return 1;
596 /* Unwrap transfer encoding and optionally
597 * normalize the log message to UTF-8.
599 decode_transfer_encoding(line);
600 if (metainfo_charset)
601 convert_to_utf8(line, charset);
602 fputs(line, cmitmsg);
603 } while (fgets(line, sizeof(line), stdin) != NULL);
604 fclose(cmitmsg);
605 cmitmsg = NULL;
606 return 0;
609 /* We have done the commit message and have the first
610 * line of the patch in line[].
612 static void handle_patch(void)
614 do {
615 if (multipart_boundary[0] && is_multipart_boundary(line))
616 break;
617 /* Only unwrap transfer encoding but otherwise do not
618 * do anything. We do *NOT* want UTF-8 conversion
619 * here; we are dealing with the user payload.
621 decode_transfer_encoding(line);
622 fputs(line, patchfile);
623 patch_lines++;
624 } while (fgets(line, sizeof(line), stdin) != NULL);
627 /* multipart boundary and transfer encoding are set up for us, and we
628 * are at the end of the sub header. do equivalent of handle_body up
629 * to the next boundary without closing patchfile --- we will expect
630 * that the first part to contain commit message and a patch, and
631 * handle other parts as pure patches.
633 static int handle_multipart_one_part(void)
635 int seen = 0;
636 int n = 0;
637 int len;
639 while (fgets(line, sizeof(line), stdin) != NULL) {
640 again:
641 len = eatspace(line);
642 n++;
643 if (!len)
644 continue;
645 if (is_multipart_boundary(line))
646 break;
647 if (0 <= seen && handle_inbody_header(&seen, line))
648 continue;
649 seen = -1; /* no more inbody headers */
650 line[len] = '\n';
651 handle_info();
652 if (handle_commit_msg())
653 goto again;
654 handle_patch();
655 break;
657 if (n == 0)
658 return -1;
659 return 0;
662 static void handle_multipart_body(void)
664 int part_num = 0;
666 /* Skip up to the first boundary */
667 while (fgets(line, sizeof(line), stdin) != NULL)
668 if (is_multipart_boundary(line)) {
669 part_num = 1;
670 break;
672 if (!part_num)
673 return;
674 /* We are on boundary line. Start slurping the subhead. */
675 while (1) {
676 int len = read_one_header_line(line, sizeof(line), stdin);
677 if (!len) {
678 if (handle_multipart_one_part() < 0)
679 return;
681 else
682 check_subheader_line(line, len);
684 fclose(patchfile);
685 if (!patch_lines) {
686 fprintf(stderr, "No patch found\n");
687 exit(1);
691 /* Non multipart message */
692 static void handle_body(void)
694 int seen = 0;
696 while (fgets(line, sizeof(line), stdin) != NULL) {
697 int len = eatspace(line);
698 if (!len)
699 continue;
700 if (0 <= seen && handle_inbody_header(&seen, line))
701 continue;
702 seen = -1; /* no more inbody headers */
703 line[len] = '\n';
704 handle_info();
705 handle_commit_msg();
706 handle_patch();
707 break;
709 fclose(patchfile);
710 if (!patch_lines) {
711 fprintf(stderr, "No patch found\n");
712 exit(1);
716 static const char mailinfo_usage[] =
717 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
719 int main(int argc, char **argv)
721 /* NEEDSWORK: might want to do the optional .git/ directory
722 * discovery
724 git_config(git_default_config);
726 while (1 < argc && argv[1][0] == '-') {
727 if (!strcmp(argv[1], "-k"))
728 keep_subject = 1;
729 else if (!strcmp(argv[1], "-u"))
730 metainfo_charset = git_commit_encoding;
731 else if (!strncmp(argv[1], "--encoding=", 11))
732 metainfo_charset = argv[1] + 11;
733 else
734 usage(mailinfo_usage);
735 argc--; argv++;
738 if (argc != 3)
739 usage(mailinfo_usage);
740 cmitmsg = fopen(argv[1], "w");
741 if (!cmitmsg) {
742 perror(argv[1]);
743 exit(1);
745 patchfile = fopen(argv[2], "w");
746 if (!patchfile) {
747 perror(argv[2]);
748 exit(1);
750 while (1) {
751 int len = read_one_header_line(line, sizeof(line), stdin);
752 if (!len) {
753 if (multipart_boundary[0])
754 handle_multipart_body();
755 else
756 handle_body();
757 break;
759 check_header_line(line, len);
761 return 0;