rebase -i: call editor just once for a multi-squash
[git/spearce.git] / builtin-mailinfo.c
bloba37a4fff39afe6bafaace59b710e1dfdc56bf35a
1 /*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5 #include "cache.h"
6 #include "builtin.h"
7 #include "utf8.h"
9 static FILE *cmitmsg, *patchfile, *fin, *fout;
11 static int keep_subject;
12 static const char *metainfo_charset;
13 static char line[1000];
14 static char name[1000];
15 static char email[1000];
17 static enum {
18 TE_DONTCARE, TE_QP, TE_BASE64,
19 } transfer_encoding;
20 static enum {
21 TYPE_TEXT, TYPE_OTHER,
22 } message_type;
24 static char charset[256];
25 static int patch_lines;
26 static char **p_hdr_data, **s_hdr_data;
28 #define MAX_HDR_PARSED 10
29 #define MAX_BOUNDARIES 5
31 static char *sanity_check(char *name, char *email)
33 int len = strlen(name);
34 if (len < 3 || len > 60)
35 return email;
36 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
37 return email;
38 return name;
41 static int bogus_from(char *line)
43 /* John Doe <johndoe> */
44 char *bra, *ket, *dst, *cp;
46 /* This is fallback, so do not bother if we already have an
47 * e-mail address.
49 if (*email)
50 return 0;
52 bra = strchr(line, '<');
53 if (!bra)
54 return 0;
55 ket = strchr(bra, '>');
56 if (!ket)
57 return 0;
59 for (dst = email, cp = bra+1; cp < ket; )
60 *dst++ = *cp++;
61 *dst = 0;
62 for (cp = line; isspace(*cp); cp++)
64 for (bra--; isspace(*bra); bra--)
65 *bra = 0;
66 cp = sanity_check(cp, email);
67 strcpy(name, cp);
68 return 1;
71 static int handle_from(char *in_line)
73 char line[1000];
74 char *at;
75 char *dst;
77 strcpy(line, in_line);
78 at = strchr(line, '@');
79 if (!at)
80 return bogus_from(line);
83 * If we already have one email, don't take any confusing lines
85 if (*email && strchr(at+1, '@'))
86 return 0;
88 /* Pick up the string around '@', possibly delimited with <>
89 * pair; that is the email part. White them out while copying.
91 while (at > line) {
92 char c = at[-1];
93 if (isspace(c))
94 break;
95 if (c == '<') {
96 at[-1] = ' ';
97 break;
99 at--;
101 dst = email;
102 for (;;) {
103 unsigned char c = *at;
104 if (!c || c == '>' || isspace(c)) {
105 if (c == '>')
106 *at = ' ';
107 break;
109 *at++ = ' ';
110 *dst++ = c;
112 *dst++ = 0;
114 /* The remainder is name. It could be "John Doe <john.doe@xz>"
115 * or "john.doe@xz (John Doe)", but we have whited out the
116 * email part, so trim from both ends, possibly removing
117 * the () pair at the end.
119 at = line + strlen(line);
120 while (at > line) {
121 unsigned char c = *--at;
122 if (!isspace(c)) {
123 at[(c == ')') ? 0 : 1] = 0;
124 break;
128 at = line;
129 for (;;) {
130 unsigned char c = *at;
131 if (!c || !isspace(c)) {
132 if (c == '(')
133 at++;
134 break;
136 at++;
138 at = sanity_check(at, email);
139 strcpy(name, at);
140 return 1;
143 static int handle_header(char *line, char *data, int ofs)
145 if (!line || !data)
146 return 1;
148 strcpy(data, line+ofs);
150 return 0;
153 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
154 * to have enough heuristics to grok MIME encoded patches often found
155 * on our mailing lists. For example, we do not even treat header lines
156 * case insensitively.
159 static int slurp_attr(const char *line, const char *name, char *attr)
161 const char *ends, *ap = strcasestr(line, name);
162 size_t sz;
164 if (!ap) {
165 *attr = 0;
166 return 0;
168 ap += strlen(name);
169 if (*ap == '"') {
170 ap++;
171 ends = "\"";
173 else
174 ends = "; \t";
175 sz = strcspn(ap, ends);
176 memcpy(attr, ap, sz);
177 attr[sz] = 0;
178 return 1;
181 struct content_type {
182 char *boundary;
183 int boundary_len;
186 static struct content_type content[MAX_BOUNDARIES];
188 static struct content_type *content_top = content;
190 static int handle_content_type(char *line)
192 char boundary[256];
194 if (strcasestr(line, "text/") == NULL)
195 message_type = TYPE_OTHER;
196 if (slurp_attr(line, "boundary=", boundary + 2)) {
197 memcpy(boundary, "--", 2);
198 if (content_top++ >= &content[MAX_BOUNDARIES]) {
199 fprintf(stderr, "Too many boundaries to handle\n");
200 exit(1);
202 content_top->boundary_len = strlen(boundary);
203 content_top->boundary = xmalloc(content_top->boundary_len+1);
204 strcpy(content_top->boundary, boundary);
206 if (slurp_attr(line, "charset=", charset)) {
207 int i, c;
208 for (i = 0; (c = charset[i]) != 0; i++)
209 charset[i] = tolower(c);
211 return 0;
214 static int handle_content_transfer_encoding(char *line)
216 if (strcasestr(line, "base64"))
217 transfer_encoding = TE_BASE64;
218 else if (strcasestr(line, "quoted-printable"))
219 transfer_encoding = TE_QP;
220 else
221 transfer_encoding = TE_DONTCARE;
222 return 0;
225 static int is_multipart_boundary(const char *line)
227 return (!memcmp(line, content_top->boundary, content_top->boundary_len));
230 static int eatspace(char *line)
232 int len = strlen(line);
233 while (len > 0 && isspace(line[len-1]))
234 line[--len] = 0;
235 return len;
238 static char *cleanup_subject(char *subject)
240 if (keep_subject)
241 return subject;
242 for (;;) {
243 char *p;
244 int len, remove;
245 switch (*subject) {
246 case 'r': case 'R':
247 if (!memcmp("e:", subject+1, 2)) {
248 subject += 3;
249 continue;
251 break;
252 case ' ': case '\t': case ':':
253 subject++;
254 continue;
256 case '[':
257 p = strchr(subject, ']');
258 if (!p) {
259 subject++;
260 continue;
262 len = strlen(p);
263 remove = p - subject;
264 if (remove <= len *2) {
265 subject = p+1;
266 continue;
268 break;
270 eatspace(subject);
271 return subject;
275 static void cleanup_space(char *buf)
277 unsigned char c;
278 while ((c = *buf) != 0) {
279 buf++;
280 if (isspace(c)) {
281 buf[-1] = ' ';
282 c = *buf;
283 while (isspace(c)) {
284 int len = strlen(buf);
285 memmove(buf, buf+1, len);
286 c = *buf;
292 static void decode_header(char *it);
293 static char *header[MAX_HDR_PARSED] = {
294 "From","Subject","Date",
297 static int check_header(char *line, char **hdr_data, int overwrite)
299 int i;
301 /* search for the interesting parts */
302 for (i = 0; header[i]; i++) {
303 int len = strlen(header[i]);
304 if ((!hdr_data[i] || overwrite) &&
305 !strncasecmp(line, header[i], len) &&
306 line[len] == ':' && isspace(line[len + 1])) {
307 /* Unwrap inline B and Q encoding, and optionally
308 * normalize the meta information to utf8.
310 decode_header(line + len + 2);
311 hdr_data[i] = xmalloc(1000 * sizeof(char));
312 if (! handle_header(line, hdr_data[i], len + 2)) {
313 return 1;
318 /* Content stuff */
319 if (!strncasecmp(line, "Content-Type", 12) &&
320 line[12] == ':' && isspace(line[12 + 1])) {
321 decode_header(line + 12 + 2);
322 if (! handle_content_type(line)) {
323 return 1;
326 if (!strncasecmp(line, "Content-Transfer-Encoding", 25) &&
327 line[25] == ':' && isspace(line[25 + 1])) {
328 decode_header(line + 25 + 2);
329 if (! handle_content_transfer_encoding(line)) {
330 return 1;
334 /* for inbody stuff */
335 if (!memcmp(">From", line, 5) && isspace(line[5]))
336 return 1;
337 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
338 for (i = 0; header[i]; i++) {
339 if (!memcmp("Subject: ", header[i], 9)) {
340 if (! handle_header(line, hdr_data[i], 0)) {
341 return 1;
347 /* no match */
348 return 0;
351 static int is_rfc2822_header(char *line)
354 * The section that defines the loosest possible
355 * field name is "3.6.8 Optional fields".
357 * optional-field = field-name ":" unstructured CRLF
358 * field-name = 1*ftext
359 * ftext = %d33-57 / %59-126
361 int ch;
362 char *cp = line;
364 /* Count mbox From headers as headers */
365 if (!memcmp(line, "From ", 5) || !memcmp(line, ">From ", 6))
366 return 1;
368 while ((ch = *cp++)) {
369 if (ch == ':')
370 return cp != line;
371 if ((33 <= ch && ch <= 57) ||
372 (59 <= ch && ch <= 126))
373 continue;
374 break;
376 return 0;
380 * sz is size of 'line' buffer in bytes. Must be reasonably
381 * long enough to hold one physical real-world e-mail line.
383 static int read_one_header_line(char *line, int sz, FILE *in)
385 int len;
388 * We will read at most (sz-1) bytes and then potentially
389 * re-add NUL after it. Accessing line[sz] after this is safe
390 * and we can allow len to grow up to and including sz.
392 sz--;
394 /* Get the first part of the line. */
395 if (!fgets(line, sz, in))
396 return 0;
399 * Is it an empty line or not a valid rfc2822 header?
400 * If so, stop here, and return false ("not a header")
402 len = eatspace(line);
403 if (!len || !is_rfc2822_header(line)) {
404 /* Re-add the newline */
405 line[len] = '\n';
406 line[len + 1] = '\0';
407 return 0;
411 * Now we need to eat all the continuation lines..
412 * Yuck, 2822 header "folding"
414 for (;;) {
415 int peek, addlen;
416 static char continuation[1000];
418 peek = fgetc(in); ungetc(peek, in);
419 if (peek != ' ' && peek != '\t')
420 break;
421 if (!fgets(continuation, sizeof(continuation), in))
422 break;
423 addlen = eatspace(continuation);
424 if (len < sz - 1) {
425 if (addlen >= sz - len)
426 addlen = sz - len - 1;
427 memcpy(line + len, continuation, addlen);
428 len += addlen;
431 line[len] = 0;
433 return 1;
436 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
438 int c;
439 while ((c = *in++) != 0 && (in <= ep)) {
440 if (c == '=') {
441 int d = *in++;
442 if (d == '\n' || !d)
443 break; /* drop trailing newline */
444 *ot++ = ((hexval(d) << 4) | hexval(*in++));
445 continue;
447 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
448 c = 0x20;
449 *ot++ = c;
451 *ot = 0;
452 return 0;
455 static int decode_b_segment(char *in, char *ot, char *ep)
457 /* Decode in..ep, possibly in-place to ot */
458 int c, pos = 0, acc = 0;
460 while ((c = *in++) != 0 && (in <= ep)) {
461 if (c == '+')
462 c = 62;
463 else if (c == '/')
464 c = 63;
465 else if ('A' <= c && c <= 'Z')
466 c -= 'A';
467 else if ('a' <= c && c <= 'z')
468 c -= 'a' - 26;
469 else if ('0' <= c && c <= '9')
470 c -= '0' - 52;
471 else if (c == '=') {
472 /* padding is almost like (c == 0), except we do
473 * not output NUL resulting only from it;
474 * for now we just trust the data.
476 c = 0;
478 else
479 continue; /* garbage */
480 switch (pos++) {
481 case 0:
482 acc = (c << 2);
483 break;
484 case 1:
485 *ot++ = (acc | (c >> 4));
486 acc = (c & 15) << 4;
487 break;
488 case 2:
489 *ot++ = (acc | (c >> 2));
490 acc = (c & 3) << 6;
491 break;
492 case 3:
493 *ot++ = (acc | c);
494 acc = pos = 0;
495 break;
498 *ot = 0;
499 return 0;
503 * When there is no known charset, guess.
505 * Right now we assume that if the target is UTF-8 (the default),
506 * and it already looks like UTF-8 (which includes US-ASCII as its
507 * subset, of course) then that is what it is and there is nothing
508 * to do.
510 * Otherwise, we default to assuming it is Latin1 for historical
511 * reasons.
513 static const char *guess_charset(const char *line, const char *target_charset)
515 if (is_encoding_utf8(target_charset)) {
516 if (is_utf8(line))
517 return NULL;
519 return "latin1";
522 static void convert_to_utf8(char *line, const char *charset)
524 char *out;
526 if (!charset || !*charset) {
527 charset = guess_charset(line, metainfo_charset);
528 if (!charset)
529 return;
532 out = reencode_string(line, metainfo_charset, charset);
533 if (!out)
534 die("cannot convert from %s to %s\n",
535 charset, metainfo_charset);
536 strcpy(line, out);
537 free(out);
540 static int decode_header_bq(char *it)
542 char *in, *out, *ep, *cp, *sp;
543 char outbuf[1000];
544 int rfc2047 = 0;
546 in = it;
547 out = outbuf;
548 while ((ep = strstr(in, "=?")) != NULL) {
549 int sz, encoding;
550 char charset_q[256], piecebuf[256];
551 rfc2047 = 1;
553 if (in != ep) {
554 sz = ep - in;
555 memcpy(out, in, sz);
556 out += sz;
557 in += sz;
559 /* E.g.
560 * ep : "=?iso-2022-jp?B?GyR...?= foo"
561 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
563 ep += 2;
564 cp = strchr(ep, '?');
565 if (!cp)
566 return rfc2047; /* no munging */
567 for (sp = ep; sp < cp; sp++)
568 charset_q[sp - ep] = tolower(*sp);
569 charset_q[cp - ep] = 0;
570 encoding = cp[1];
571 if (!encoding || cp[2] != '?')
572 return rfc2047; /* no munging */
573 ep = strstr(cp + 3, "?=");
574 if (!ep)
575 return rfc2047; /* no munging */
576 switch (tolower(encoding)) {
577 default:
578 return rfc2047; /* no munging */
579 case 'b':
580 sz = decode_b_segment(cp + 3, piecebuf, ep);
581 break;
582 case 'q':
583 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
584 break;
586 if (sz < 0)
587 return rfc2047;
588 if (metainfo_charset)
589 convert_to_utf8(piecebuf, charset_q);
590 strcpy(out, piecebuf);
591 out += strlen(out);
592 in = ep + 2;
594 strcpy(out, in);
595 strcpy(it, outbuf);
596 return rfc2047;
599 static void decode_header(char *it)
602 if (decode_header_bq(it))
603 return;
604 /* otherwise "it" is a straight copy of the input.
605 * This can be binary guck but there is no charset specified.
607 if (metainfo_charset)
608 convert_to_utf8(it, "");
611 static void decode_transfer_encoding(char *line)
613 char *ep;
615 switch (transfer_encoding) {
616 case TE_QP:
617 ep = line + strlen(line);
618 decode_q_segment(line, line, ep, 0);
619 break;
620 case TE_BASE64:
621 ep = line + strlen(line);
622 decode_b_segment(line, line, ep);
623 break;
624 case TE_DONTCARE:
625 break;
629 static int handle_filter(char *line);
631 static int find_boundary(void)
633 while(fgets(line, sizeof(line), fin) != NULL) {
634 if (is_multipart_boundary(line))
635 return 1;
637 return 0;
640 static int handle_boundary(void)
642 char newline[]="\n";
643 again:
644 if (!memcmp(line+content_top->boundary_len, "--", 2)) {
645 /* we hit an end boundary */
646 /* pop the current boundary off the stack */
647 free(content_top->boundary);
649 /* technically won't happen as is_multipart_boundary()
650 will fail first. But just in case..
652 if (content_top-- < content) {
653 fprintf(stderr, "Detected mismatched boundaries, "
654 "can't recover\n");
655 exit(1);
657 handle_filter(newline);
659 /* skip to the next boundary */
660 if (!find_boundary())
661 return 0;
662 goto again;
665 /* set some defaults */
666 transfer_encoding = TE_DONTCARE;
667 charset[0] = 0;
668 message_type = TYPE_TEXT;
670 /* slurp in this section's info */
671 while (read_one_header_line(line, sizeof(line), fin))
672 check_header(line, p_hdr_data, 0);
674 /* eat the blank line after section info */
675 return (fgets(line, sizeof(line), fin) != NULL);
678 static inline int patchbreak(const char *line)
680 /* Beginning of a "diff -" header? */
681 if (!memcmp("diff -", line, 6))
682 return 1;
684 /* CVS "Index: " line? */
685 if (!memcmp("Index: ", line, 7))
686 return 1;
689 * "--- <filename>" starts patches without headers
690 * "---<sp>*" is a manual separator
692 if (!memcmp("---", line, 3)) {
693 line += 3;
694 /* space followed by a filename? */
695 if (line[0] == ' ' && !isspace(line[1]))
696 return 1;
697 /* Just whitespace? */
698 for (;;) {
699 unsigned char c = *line++;
700 if (c == '\n')
701 return 1;
702 if (!isspace(c))
703 break;
705 return 0;
707 return 0;
711 static int handle_commit_msg(char *line)
713 static int still_looking = 1;
715 if (!cmitmsg)
716 return 0;
718 if (still_looking) {
719 char *cp = line;
720 if (isspace(*line)) {
721 for (cp = line + 1; *cp; cp++) {
722 if (!isspace(*cp))
723 break;
725 if (!*cp)
726 return 0;
728 if ((still_looking = check_header(cp, s_hdr_data, 0)) != 0)
729 return 0;
732 /* normalize the log message to UTF-8. */
733 if (metainfo_charset)
734 convert_to_utf8(line, charset);
736 if (patchbreak(line)) {
737 fclose(cmitmsg);
738 cmitmsg = NULL;
739 return 1;
742 fputs(line, cmitmsg);
743 return 0;
746 static int handle_patch(char *line)
748 fputs(line, patchfile);
749 patch_lines++;
750 return 0;
753 static int handle_filter(char *line)
755 static int filter = 0;
757 /* filter tells us which part we left off on
758 * a non-zero return indicates we hit a filter point
760 switch (filter) {
761 case 0:
762 if (!handle_commit_msg(line))
763 break;
764 filter++;
765 case 1:
766 if (!handle_patch(line))
767 break;
768 filter++;
769 default:
770 return 1;
773 return 0;
776 static void handle_body(void)
778 int rc = 0;
779 static char newline[2000];
780 static char *np = newline;
782 /* Skip up to the first boundary */
783 if (content_top->boundary) {
784 if (!find_boundary())
785 return;
788 do {
789 /* process any boundary lines */
790 if (content_top->boundary && is_multipart_boundary(line)) {
791 /* flush any leftover */
792 if ((transfer_encoding == TE_BASE64) &&
793 (np != newline)) {
794 handle_filter(newline);
796 if (!handle_boundary())
797 return;
800 /* Unwrap transfer encoding */
801 decode_transfer_encoding(line);
803 switch (transfer_encoding) {
804 case TE_BASE64:
806 char *op = line;
808 /* binary data most likely doesn't have newlines */
809 if (message_type != TYPE_TEXT) {
810 rc = handle_filter(line);
811 break;
814 /* this is a decoded line that may contain
815 * multiple new lines. Pass only one chunk
816 * at a time to handle_filter()
819 do {
820 while (*op != '\n' && *op != 0)
821 *np++ = *op++;
822 *np = *op;
823 if (*np != 0) {
824 /* should be sitting on a new line */
825 *(++np) = 0;
826 op++;
827 rc = handle_filter(newline);
828 np = newline;
830 } while (*op != 0);
831 /* the partial chunk is saved in newline and
832 * will be appended by the next iteration of fgets
834 break;
836 default:
837 rc = handle_filter(line);
839 if (rc)
840 /* nothing left to filter */
841 break;
842 } while (fgets(line, sizeof(line), fin));
844 return;
847 static void handle_info(void)
849 char *sub;
850 char *hdr;
851 int i;
853 for (i = 0; header[i]; i++) {
855 /* only print inbody headers if we output a patch file */
856 if (patch_lines && s_hdr_data[i])
857 hdr = s_hdr_data[i];
858 else if (p_hdr_data[i])
859 hdr = p_hdr_data[i];
860 else
861 continue;
863 if (!memcmp(header[i], "Subject", 7)) {
864 sub = cleanup_subject(hdr);
865 cleanup_space(sub);
866 fprintf(fout, "Subject: %s\n", sub);
867 } else if (!memcmp(header[i], "From", 4)) {
868 handle_from(hdr);
869 fprintf(fout, "Author: %s\n", name);
870 fprintf(fout, "Email: %s\n", email);
871 } else {
872 cleanup_space(hdr);
873 fprintf(fout, "%s: %s\n", header[i], hdr);
876 fprintf(fout, "\n");
879 static int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
880 const char *msg, const char *patch)
882 keep_subject = ks;
883 metainfo_charset = encoding;
884 fin = in;
885 fout = out;
887 cmitmsg = fopen(msg, "w");
888 if (!cmitmsg) {
889 perror(msg);
890 return -1;
892 patchfile = fopen(patch, "w");
893 if (!patchfile) {
894 perror(patch);
895 fclose(cmitmsg);
896 return -1;
899 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(char *));
900 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(char *));
902 /* process the email header */
903 while (read_one_header_line(line, sizeof(line), fin))
904 check_header(line, p_hdr_data, 1);
906 handle_body();
907 handle_info();
909 return 0;
912 static const char mailinfo_usage[] =
913 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
915 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
917 const char *def_charset;
919 /* NEEDSWORK: might want to do the optional .git/ directory
920 * discovery
922 git_config(git_default_config);
924 def_charset = (git_commit_encoding ? git_commit_encoding : "utf-8");
925 metainfo_charset = def_charset;
927 while (1 < argc && argv[1][0] == '-') {
928 if (!strcmp(argv[1], "-k"))
929 keep_subject = 1;
930 else if (!strcmp(argv[1], "-u"))
931 metainfo_charset = def_charset;
932 else if (!strcmp(argv[1], "-n"))
933 metainfo_charset = NULL;
934 else if (!prefixcmp(argv[1], "--encoding="))
935 metainfo_charset = argv[1] + 11;
936 else
937 usage(mailinfo_usage);
938 argc--; argv++;
941 if (argc != 3)
942 usage(mailinfo_usage);
944 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);