git
/
mailinfo.c
1304 строки · 28.8 Кб
1#define USE_THE_REPOSITORY_VARIABLE2
3#include "git-compat-util.h"4#include "config.h"5#include "gettext.h"6#include "hex-ll.h"7#include "utf8.h"8#include "strbuf.h"9#include "mailinfo.h"10
11static void cleanup_space(struct strbuf *sb)12{
13size_t pos, cnt;14for (pos = 0; pos < sb->len; pos++) {15if (isspace(sb->buf[pos])) {16sb->buf[pos] = ' ';17for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);18strbuf_remove(sb, pos + 1, cnt);19}20}21}
22
23static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)24{
25struct strbuf *src = name;26if (!name->len || 60 < name->len || strpbrk(name->buf, "@<>"))27src = email;28else if (name == out)29return;30strbuf_reset(out);31strbuf_addbuf(out, src);32}
33
34static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)35{
36/* John Doe <johndoe> */37
38char *bra, *ket;39/* This is fallback, so do not bother if we already have an40* e-mail address.
41*/
42if (mi->email.len)43return;44
45bra = strchr(line->buf, '<');46if (!bra)47return;48ket = strchr(bra, '>');49if (!ket)50return;51
52strbuf_reset(&mi->email);53strbuf_add(&mi->email, bra + 1, ket - bra - 1);54
55strbuf_reset(&mi->name);56strbuf_add(&mi->name, line->buf, bra - line->buf);57strbuf_trim(&mi->name);58get_sane_name(&mi->name, &mi->name, &mi->email);59}
60
61static const char *unquote_comment(struct strbuf *outbuf, const char *in)62{
63int take_next_literally = 0;64int depth = 1;65
66strbuf_addch(outbuf, '(');67
68while (*in) {69int c = *in++;70if (take_next_literally == 1) {71take_next_literally = 0;72} else {73switch (c) {74case '\\':75take_next_literally = 1;76continue;77case '(':78strbuf_addch(outbuf, '(');79depth++;80continue;81case ')':82strbuf_addch(outbuf, ')');83if (!--depth)84return in;85continue;86}87}88
89strbuf_addch(outbuf, c);90}91
92return in;93}
94
95static const char *unquote_quoted_string(struct strbuf *outbuf, const char *in)96{
97int take_next_literally = 0;98
99while (*in) {100int c = *in++;101if (take_next_literally == 1) {102take_next_literally = 0;103} else {104switch (c) {105case '\\':106take_next_literally = 1;107continue;108case '"':109return in;110}111}112
113strbuf_addch(outbuf, c);114}115
116return in;117}
118
119static void unquote_quoted_pair(struct strbuf *line)120{
121struct strbuf outbuf;122const char *in = line->buf;123int c;124
125strbuf_init(&outbuf, line->len);126
127while ((c = *in++) != 0) {128switch (c) {129case '"':130in = unquote_quoted_string(&outbuf, in);131continue;132case '(':133in = unquote_comment(&outbuf, in);134continue;135}136
137strbuf_addch(&outbuf, c);138}139
140strbuf_swap(&outbuf, line);141strbuf_release(&outbuf);142
143}
144
145static void handle_from(struct mailinfo *mi, const struct strbuf *from)146{
147char *at;148size_t el;149struct strbuf f;150
151strbuf_init(&f, from->len);152strbuf_addbuf(&f, from);153
154unquote_quoted_pair(&f);155
156at = strchr(f.buf, '@');157if (!at) {158parse_bogus_from(mi, from);159goto out;160}161
162/*163* If we already have one email, don't take any confusing lines
164*/
165if (mi->email.len && strchr(at + 1, '@'))166goto out;167
168/* Pick up the string around '@', possibly delimited with <>169* pair; that is the email part.
170*/
171while (at > f.buf) {172char c = at[-1];173if (isspace(c))174break;175if (c == '<') {176at[-1] = ' ';177break;178}179at--;180}181el = strcspn(at, " \n\t\r\v\f>");182strbuf_reset(&mi->email);183strbuf_add(&mi->email, at, el);184strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));185
186/* The remainder is name. It could be187*
188* - "John Doe <john.doe@xz>" (a), or
189* - "john.doe@xz (John Doe)" (b), or
190* - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
191*
192* but we have removed the email part, so
193*
194* - remove extra spaces which could stay after email (case 'c'), and
195* - trim from both ends, possibly removing the () pair at the end
196* (cases 'a' and 'b').
197*/
198cleanup_space(&f);199strbuf_trim(&f);200if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {201strbuf_remove(&f, 0, 1);202strbuf_setlen(&f, f.len - 1);203}204
205get_sane_name(&mi->name, &f, &mi->email);206out:207strbuf_release(&f);208}
209
210static void handle_header(struct strbuf **out, const struct strbuf *line)211{
212if (!*out) {213*out = xmalloc(sizeof(struct strbuf));214strbuf_init(*out, line->len);215} else216strbuf_reset(*out);217
218strbuf_addbuf(*out, line);219}
220
221/* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
222* to have enough heuristics to grok MIME encoded patches often found
223* on our mailing lists. For example, we do not even treat header lines
224* case insensitively.
225*/
226
227static int slurp_attr(const char *line, const char *name, struct strbuf *attr)228{
229const char *ends, *ap = strcasestr(line, name);230size_t sz;231
232strbuf_setlen(attr, 0);233if (!ap)234return 0;235ap += strlen(name);236if (*ap == '"') {237ap++;238ends = "\"";239}240else241ends = "; \t";242sz = strcspn(ap, ends);243strbuf_add(attr, ap, sz);244return 1;245}
246
247static int has_attr_value(const char *line, const char *name, const char *value)248{
249struct strbuf sb = STRBUF_INIT;250int rc = slurp_attr(line, name, &sb) && !strcasecmp(sb.buf, value);251strbuf_release(&sb);252return rc;253}
254
255static void handle_content_type(struct mailinfo *mi, struct strbuf *line)256{
257struct strbuf *boundary = xmalloc(sizeof(struct strbuf));258strbuf_init(boundary, line->len);259
260mi->format_flowed = has_attr_value(line->buf, "format=", "flowed");261mi->delsp = has_attr_value(line->buf, "delsp=", "yes");262
263if (slurp_attr(line->buf, "boundary=", boundary)) {264strbuf_insertstr(boundary, 0, "--");265if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {266error("Too many boundaries to handle");267mi->input_error = -1;268mi->content_top = &mi->content[MAX_BOUNDARIES] - 1;269return;270}271*(mi->content_top) = boundary;272boundary = NULL;273}274slurp_attr(line->buf, "charset=", &mi->charset);275
276if (boundary) {277strbuf_release(boundary);278free(boundary);279}280}
281
282static void handle_content_transfer_encoding(struct mailinfo *mi,283const struct strbuf *line)284{
285if (strcasestr(line->buf, "base64"))286mi->transfer_encoding = TE_BASE64;287else if (strcasestr(line->buf, "quoted-printable"))288mi->transfer_encoding = TE_QP;289else290mi->transfer_encoding = TE_DONTCARE;291}
292
293static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)294{
295struct strbuf *content_top = *(mi->content_top);296
297return ((content_top->len <= line->len) &&298!memcmp(line->buf, content_top->buf, content_top->len));299}
300
301static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)302{
303size_t at = 0;304
305while (at < subject->len) {306char *pos;307size_t remove;308
309switch (subject->buf[at]) {310case 'r': case 'R':311if (subject->len <= at + 3)312break;313if ((subject->buf[at + 1] == 'e' ||314subject->buf[at + 1] == 'E') &&315subject->buf[at + 2] == ':') {316strbuf_remove(subject, at, 3);317continue;318}319at++;320break;321case ' ': case '\t': case ':':322strbuf_remove(subject, at, 1);323continue;324case '[':325pos = strchr(subject->buf + at, ']');326if (!pos)327break;328remove = pos - (subject->buf + at) + 1;329if (!mi->keep_non_patch_brackets_in_subject ||330(7 <= remove &&331memmem(subject->buf + at, remove, "PATCH", 5)))332strbuf_remove(subject, at, remove);333else {334at += remove;335/*336* If the input had a space after the ], keep
337* it. We don't bother with finding the end of
338* the space, since we later normalize it
339* anyway.
340*/
341if (isspace(subject->buf[at]))342at += 1;343}344continue;345}346break;347}348strbuf_trim(subject);349}
350
351#define MAX_HDR_PARSED 10352static const char *header[MAX_HDR_PARSED] = {353"From","Subject","Date",354};355
356static inline int skip_header(const struct strbuf *line, const char *hdr,357const char **outval)358{
359const char *val;360if (!skip_iprefix(line->buf, hdr, &val) ||361*val++ != ':')362return 0;363while (isspace(*val))364val++;365*outval = val;366return 1;367}
368
369static int is_format_patch_separator(const char *line, int len)370{
371static const char SAMPLE[] =372"From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";373const char *cp;374
375if (len != strlen(SAMPLE))376return 0;377if (!skip_prefix(line, "From ", &cp))378return 0;379if (strspn(cp, "0123456789abcdef") != 40)380return 0;381cp += 40;382return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));383}
384
385static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)386{
387const char *in = q_seg->buf;388int c;389struct strbuf *out = xmalloc(sizeof(struct strbuf));390strbuf_init(out, q_seg->len);391
392while ((c = *in++) != 0) {393if (c == '=') {394int ch, d = *in;395if (d == '\n' || !d)396break; /* drop trailing newline */397ch = hex2chr(in);398if (ch >= 0) {399strbuf_addch(out, ch);400in += 2;401continue;402}403/* garbage -- fall through */404}405if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */406c = 0x20;407strbuf_addch(out, c);408}409return out;410}
411
412static struct strbuf *decode_b_segment(const struct strbuf *b_seg)413{
414/* Decode in..ep, possibly in-place to ot */415int c, pos = 0, acc = 0;416const char *in = b_seg->buf;417struct strbuf *out = xmalloc(sizeof(struct strbuf));418strbuf_init(out, b_seg->len);419
420while ((c = *in++) != 0) {421if (c == '+')422c = 62;423else if (c == '/')424c = 63;425else if ('A' <= c && c <= 'Z')426c -= 'A';427else if ('a' <= c && c <= 'z')428c -= 'a' - 26;429else if ('0' <= c && c <= '9')430c -= '0' - 52;431else432continue; /* garbage */433switch (pos++) {434case 0:435acc = (c << 2);436break;437case 1:438strbuf_addch(out, (acc | (c >> 4)));439acc = (c & 15) << 4;440break;441case 2:442strbuf_addch(out, (acc | (c >> 2)));443acc = (c & 3) << 6;444break;445case 3:446strbuf_addch(out, (acc | c));447acc = pos = 0;448break;449}450}451return out;452}
453
454static int convert_to_utf8(struct mailinfo *mi,455struct strbuf *line, const char *charset)456{
457char *out;458size_t out_len;459
460if (!mi->metainfo_charset || !charset || !*charset)461return 0;462
463if (same_encoding(mi->metainfo_charset, charset))464return 0;465out = reencode_string_len(line->buf, line->len,466mi->metainfo_charset, charset, &out_len);467if (!out) {468mi->input_error = -1;469return error("cannot convert from %s to %s",470charset, mi->metainfo_charset);471}472strbuf_attach(line, out, out_len, out_len);473return 0;474}
475
476static void decode_header(struct mailinfo *mi, struct strbuf *it)477{
478char *in, *ep, *cp;479struct strbuf outbuf = STRBUF_INIT, *dec;480struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;481int found_error = 1; /* pessimism */482
483in = it->buf;484while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {485int encoding;486strbuf_reset(&charset_q);487strbuf_reset(&piecebuf);488
489if (in != ep) {490/*491* We are about to process an encoded-word
492* that begins at ep, but there is something
493* before the encoded word.
494*/
495char *scan;496for (scan = in; scan < ep; scan++)497if (!isspace(*scan))498break;499
500if (scan != ep || in == it->buf) {501/*502* We should not lose that "something",
503* unless we have just processed an
504* encoded-word, and there is only LWS
505* before the one we are about to process.
506*/
507strbuf_add(&outbuf, in, ep - in);508}509}510/* E.g.511* ep : "=?iso-2022-jp?B?GyR...?= foo"
512* ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
513*/
514ep += 2;515
516if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))517goto release_return;518
519if (cp + 3 - it->buf > it->len)520goto release_return;521strbuf_add(&charset_q, ep, cp - ep);522
523encoding = cp[1];524if (!encoding || cp[2] != '?')525goto release_return;526ep = strstr(cp + 3, "?=");527if (!ep)528goto release_return;529strbuf_add(&piecebuf, cp + 3, ep - cp - 3);530switch (tolower(encoding)) {531default:532goto release_return;533case 'b':534dec = decode_b_segment(&piecebuf);535break;536case 'q':537dec = decode_q_segment(&piecebuf, 1);538break;539}540if (convert_to_utf8(mi, dec, charset_q.buf))541goto release_return;542
543strbuf_addbuf(&outbuf, dec);544strbuf_release(dec);545free(dec);546in = ep + 2;547}548strbuf_addstr(&outbuf, in);549strbuf_reset(it);550strbuf_addbuf(it, &outbuf);551found_error = 0;552release_return:553strbuf_release(&outbuf);554strbuf_release(&charset_q);555strbuf_release(&piecebuf);556
557if (found_error)558mi->input_error = -1;559}
560
561/*
562* Returns true if "line" contains a header matching "hdr", in which case "val"
563* will contain the value of the header with any RFC2047 B and Q encoding
564* unwrapped, and optionally normalize the meta information to utf8.
565*/
566static int parse_header(const struct strbuf *line,567const char *hdr,568struct mailinfo *mi,569struct strbuf *val)570{
571const char *val_str;572
573if (!skip_header(line, hdr, &val_str))574return 0;575strbuf_addstr(val, val_str);576decode_header(mi, val);577return 1;578}
579
580static int check_header(struct mailinfo *mi,581const struct strbuf *line,582struct strbuf *hdr_data[], int overwrite)583{
584int i, ret = 0;585struct strbuf sb = STRBUF_INIT;586
587/* search for the interesting parts */588for (i = 0; header[i]; i++) {589if ((!hdr_data[i] || overwrite) &&590parse_header(line, header[i], mi, &sb)) {591handle_header(&hdr_data[i], &sb);592ret = 1;593goto check_header_out;594}595}596
597/* Content stuff */598if (parse_header(line, "Content-Type", mi, &sb)) {599handle_content_type(mi, &sb);600ret = 1;601goto check_header_out;602}603if (parse_header(line, "Content-Transfer-Encoding", mi, &sb)) {604handle_content_transfer_encoding(mi, &sb);605ret = 1;606goto check_header_out;607}608if (parse_header(line, "Message-ID", mi, &sb)) {609if (mi->add_message_id)610mi->message_id = strbuf_detach(&sb, NULL);611ret = 1;612goto check_header_out;613}614
615check_header_out:616strbuf_release(&sb);617return ret;618}
619
620/*
621* Returns 1 if the given line or any line beginning with the given line is an
622* in-body header (that is, check_header will succeed when passed
623* mi->s_hdr_data).
624*/
625static int is_inbody_header(const struct mailinfo *mi,626const struct strbuf *line)627{
628int i;629const char *val;630for (i = 0; header[i]; i++)631if (!mi->s_hdr_data[i] && skip_header(line, header[i], &val))632return 1;633return 0;634}
635
636static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)637{
638struct strbuf *ret;639
640switch (mi->transfer_encoding) {641case TE_QP:642ret = decode_q_segment(line, 0);643break;644case TE_BASE64:645ret = decode_b_segment(line);646break;647case TE_DONTCARE:648default:649return;650}651strbuf_reset(line);652strbuf_addbuf(line, ret);653strbuf_release(ret);654free(ret);655}
656
657static inline int patchbreak(const struct strbuf *line)658{
659size_t i;660
661/* Beginning of a "diff -" header? */662if (starts_with(line->buf, "diff -"))663return 1;664
665/* CVS "Index: " line? */666if (starts_with(line->buf, "Index: "))667return 1;668
669/*670* "--- <filename>" starts patches without headers
671* "---<sp>*" is a manual separator
672*/
673if (line->len < 4)674return 0;675
676if (starts_with(line->buf, "---")) {677/* space followed by a filename? */678if (line->buf[3] == ' ' && !isspace(line->buf[4]))679return 1;680/* Just whitespace? */681for (i = 3; i < line->len; i++) {682unsigned char c = line->buf[i];683if (c == '\n')684return 1;685if (!isspace(c))686break;687}688return 0;689}690return 0;691}
692
693static int is_scissors_line(const char *line)694{
695const char *c;696int scissors = 0, gap = 0;697const char *first_nonblank = NULL, *last_nonblank = NULL;698int visible, perforation = 0, in_perforation = 0;699
700for (c = line; *c; c++) {701if (isspace(*c)) {702if (in_perforation) {703perforation++;704gap++;705}706continue;707}708last_nonblank = c;709if (!first_nonblank)710first_nonblank = c;711if (*c == '-') {712in_perforation = 1;713perforation++;714continue;715}716if (starts_with(c, ">8") || starts_with(c, "8<") ||717starts_with(c, ">%") || starts_with(c, "%<")) {718in_perforation = 1;719perforation += 2;720scissors += 2;721c++;722continue;723}724in_perforation = 0;725}726
727/*728* The mark must be at least 8 bytes long (e.g. "-- >8 --").
729* Even though there can be arbitrary cruft on the same line
730* (e.g. "cut here"), in order to avoid misidentification, the
731* perforation must occupy more than a third of the visible
732* width of the line, and dashes and scissors must occupy more
733* than half of the perforation.
734*/
735
736if (first_nonblank && last_nonblank)737visible = last_nonblank - first_nonblank + 1;738else739visible = 0;740return (scissors && 8 <= visible &&741visible < perforation * 3 &&742gap * 2 < perforation);743}
744
745static void flush_inbody_header_accum(struct mailinfo *mi)746{
747if (!mi->inbody_header_accum.len)748return;749if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))750BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");751strbuf_reset(&mi->inbody_header_accum);752}
753
754static int check_inbody_header(struct mailinfo *mi, const struct strbuf *line)755{
756if (mi->inbody_header_accum.len &&757(line->buf[0] == ' ' || line->buf[0] == '\t')) {758if (mi->use_scissors && is_scissors_line(line->buf)) {759/*760* This is a scissors line; do not consider this line
761* as a header continuation line.
762*/
763flush_inbody_header_accum(mi);764return 0;765}766strbuf_strip_suffix(&mi->inbody_header_accum, "\n");767strbuf_addbuf(&mi->inbody_header_accum, line);768return 1;769}770
771flush_inbody_header_accum(mi);772
773if (starts_with(line->buf, ">From") && isspace(line->buf[5]))774return is_format_patch_separator(line->buf + 1, line->len - 1);775if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {776int i;777for (i = 0; header[i]; i++)778if (!strcmp("Subject", header[i])) {779handle_header(&mi->s_hdr_data[i], line);780return 1;781}782return 0;783}784if (is_inbody_header(mi, line)) {785strbuf_addbuf(&mi->inbody_header_accum, line);786return 1;787}788return 0;789}
790
791static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)792{
793assert(!mi->filter_stage);794
795if (mi->header_stage) {796if (!line->len || (line->len == 1 && line->buf[0] == '\n')) {797if (mi->inbody_header_accum.len) {798flush_inbody_header_accum(mi);799mi->header_stage = 0;800}801return 0;802}803}804
805if (mi->use_inbody_headers && mi->header_stage) {806mi->header_stage = check_inbody_header(mi, line);807if (mi->header_stage)808return 0;809} else810/* Only trim the first (blank) line of the commit message811* when ignoring in-body headers.
812*/
813mi->header_stage = 0;814
815/* normalize the log message to UTF-8. */816if (convert_to_utf8(mi, line, mi->charset.buf))817return 0; /* mi->input_error already set */818
819if (mi->use_scissors && is_scissors_line(line->buf)) {820int i;821
822strbuf_setlen(&mi->log_message, 0);823mi->header_stage = 1;824
825/*826* We may have already read "secondary headers"; purge
827* them to give ourselves a clean restart.
828*/
829for (i = 0; header[i]; i++) {830if (mi->s_hdr_data[i])831strbuf_release(mi->s_hdr_data[i]);832FREE_AND_NULL(mi->s_hdr_data[i]);833}834return 0;835}836
837if (patchbreak(line)) {838if (mi->message_id)839strbuf_addf(&mi->log_message,840"Message-ID: %s\n", mi->message_id);841return 1;842}843
844strbuf_addbuf(&mi->log_message, line);845return 0;846}
847
848static void handle_patch(struct mailinfo *mi, const struct strbuf *line)849{
850fwrite(line->buf, 1, line->len, mi->patchfile);851mi->patch_lines++;852}
853
854static void handle_filter(struct mailinfo *mi, struct strbuf *line)855{
856switch (mi->filter_stage) {857case 0:858if (!handle_commit_msg(mi, line))859break;860mi->filter_stage++;861/* fallthrough */862case 1:863handle_patch(mi, line);864break;865}866}
867
868static int is_rfc2822_header(const struct strbuf *line)869{
870/*871* The section that defines the loosest possible
872* field name is "3.6.8 Optional fields".
873*
874* optional-field = field-name ":" unstructured CRLF
875* field-name = 1*ftext
876* ftext = %d33-57 / %59-126
877*/
878int ch;879char *cp = line->buf;880
881/* Count mbox From headers as headers */882if (starts_with(cp, "From ") || starts_with(cp, ">From "))883return 1;884
885while ((ch = *cp++)) {886if (ch == ':')887return 1;888if ((33 <= ch && ch <= 57) ||889(59 <= ch && ch <= 126))890continue;891break;892}893return 0;894}
895
896static int read_one_header_line(struct strbuf *line, FILE *in)897{
898struct strbuf continuation = STRBUF_INIT;899
900/* Get the first part of the line. */901if (strbuf_getline_lf(line, in))902return 0;903
904/*905* Is it an empty line or not a valid rfc2822 header?
906* If so, stop here, and return false ("not a header")
907*/
908strbuf_rtrim(line);909if (!line->len || !is_rfc2822_header(line)) {910/* Re-add the newline */911strbuf_addch(line, '\n');912return 0;913}914
915/*916* Now we need to eat all the continuation lines..
917* Yuck, 2822 header "folding"
918*/
919for (;;) {920int peek;921
922peek = fgetc(in);923if (peek == EOF)924break;925ungetc(peek, in);926if (peek != ' ' && peek != '\t')927break;928if (strbuf_getline_lf(&continuation, in))929break;930continuation.buf[0] = ' ';931strbuf_rtrim(&continuation);932strbuf_addbuf(line, &continuation);933}934strbuf_release(&continuation);935
936return 1;937}
938
939static int find_boundary(struct mailinfo *mi, struct strbuf *line)940{
941while (!strbuf_getline_lf(line, mi->input)) {942if (*(mi->content_top) && is_multipart_boundary(mi, line))943return 1;944}945return 0;946}
947
948static int handle_boundary(struct mailinfo *mi, struct strbuf *line)949{
950struct strbuf newline = STRBUF_INIT;951
952strbuf_addch(&newline, '\n');953again:954if (line->len >= (*(mi->content_top))->len + 2 &&955!memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {956/* we hit an end boundary */957/* pop the current boundary off the stack */958strbuf_release(*(mi->content_top));959FREE_AND_NULL(*(mi->content_top));960
961/* technically won't happen as is_multipart_boundary()962will fail first. But just in case..
963*/
964if (--mi->content_top < mi->content) {965error("Detected mismatched boundaries, can't recover");966mi->input_error = -1;967mi->content_top = mi->content;968strbuf_release(&newline);969return 0;970}971handle_filter(mi, &newline);972strbuf_release(&newline);973if (mi->input_error)974return 0;975
976/* skip to the next boundary */977if (!find_boundary(mi, line))978return 0;979goto again;980}981
982/* set some defaults */983mi->transfer_encoding = TE_DONTCARE;984strbuf_reset(&mi->charset);985
986/* slurp in this section's info */987while (read_one_header_line(line, mi->input))988check_header(mi, line, mi->p_hdr_data, 0);989
990strbuf_release(&newline);991/* replenish line */992if (strbuf_getline_lf(line, mi->input))993return 0;994strbuf_addch(line, '\n');995return 1;996}
997
998static void handle_filter_flowed(struct mailinfo *mi, struct strbuf *line,999struct strbuf *prev)1000{
1001size_t len = line->len;1002const char *rest;1003
1004if (!mi->format_flowed) {1005if (len >= 2 &&1006line->buf[len - 2] == '\r' &&1007line->buf[len - 1] == '\n') {1008mi->have_quoted_cr = 1;1009if (mi->quoted_cr == quoted_cr_strip) {1010strbuf_setlen(line, len - 2);1011strbuf_addch(line, '\n');1012len--;1013}1014}1015handle_filter(mi, line);1016return;1017}1018
1019if (line->buf[len - 1] == '\n') {1020len--;1021if (len && line->buf[len - 1] == '\r')1022len--;1023}1024
1025/* Keep signature separator as-is. */1026if (skip_prefix(line->buf, "-- ", &rest) && rest - line->buf == len) {1027if (prev->len) {1028handle_filter(mi, prev);1029strbuf_reset(prev);1030}1031handle_filter(mi, line);1032return;1033}1034
1035/* Unstuff space-stuffed line. */1036if (len && line->buf[0] == ' ') {1037strbuf_remove(line, 0, 1);1038len--;1039}1040
1041/* Save flowed line for later, but without the soft line break. */1042if (len && line->buf[len - 1] == ' ') {1043strbuf_add(prev, line->buf, len - !!mi->delsp);1044return;1045}1046
1047/* Prepend any previous partial lines */1048strbuf_insert(line, 0, prev->buf, prev->len);1049strbuf_reset(prev);1050
1051handle_filter(mi, line);1052}
1053
1054static void summarize_quoted_cr(struct mailinfo *mi)1055{
1056if (mi->have_quoted_cr &&1057mi->quoted_cr == quoted_cr_warn)1058warning(_("quoted CRLF detected"));1059}
1060
1061static void handle_body(struct mailinfo *mi, struct strbuf *line)1062{
1063struct strbuf prev = STRBUF_INIT;1064
1065/* Skip up to the first boundary */1066if (*(mi->content_top)) {1067if (!find_boundary(mi, line))1068goto handle_body_out;1069}1070
1071do {1072/* process any boundary lines */1073if (*(mi->content_top) && is_multipart_boundary(mi, line)) {1074/* flush any leftover */1075if (prev.len) {1076handle_filter(mi, &prev);1077strbuf_reset(&prev);1078}1079summarize_quoted_cr(mi);1080mi->have_quoted_cr = 0;1081if (!handle_boundary(mi, line))1082goto handle_body_out;1083}1084
1085/* Unwrap transfer encoding */1086decode_transfer_encoding(mi, line);1087
1088switch (mi->transfer_encoding) {1089case TE_BASE64:1090case TE_QP:1091{1092struct strbuf **lines, **it, *sb;1093
1094/* Prepend any previous partial lines */1095strbuf_insert(line, 0, prev.buf, prev.len);1096strbuf_reset(&prev);1097
1098/*1099* This is a decoded line that may contain
1100* multiple new lines. Pass only one chunk
1101* at a time to handle_filter()
1102*/
1103lines = strbuf_split(line, '\n');1104for (it = lines; (sb = *it); it++) {1105if (!*(it + 1)) /* The last line */1106if (sb->buf[sb->len - 1] != '\n') {1107/* Partial line, save it for later. */1108strbuf_addbuf(&prev, sb);1109break;1110}1111handle_filter_flowed(mi, sb, &prev);1112}1113/*1114* The partial chunk is saved in "prev" and will be
1115* appended by the next iteration of read_line_with_nul().
1116*/
1117strbuf_list_free(lines);1118break;1119}1120default:1121handle_filter_flowed(mi, line, &prev);1122}1123
1124if (mi->input_error)1125break;1126} while (!strbuf_getwholeline(line, mi->input, '\n'));1127
1128if (prev.len)1129handle_filter(mi, &prev);1130summarize_quoted_cr(mi);1131
1132flush_inbody_header_accum(mi);1133
1134handle_body_out:1135strbuf_release(&prev);1136}
1137
1138static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)1139{
1140const char *sp = data->buf;1141while (1) {1142char *ep = strchr(sp, '\n');1143int len;1144if (!ep)1145len = strlen(sp);1146else1147len = ep - sp;1148fprintf(fout, "%s: %.*s\n", hdr, len, sp);1149if (!ep)1150break;1151sp = ep + 1;1152}1153}
1154
1155static void handle_info(struct mailinfo *mi)1156{
1157struct strbuf *hdr;1158int i;1159
1160for (i = 0; header[i]; i++) {1161/* only print inbody headers if we output a patch file */1162if (mi->patch_lines && mi->s_hdr_data[i])1163hdr = mi->s_hdr_data[i];1164else if (mi->p_hdr_data[i])1165hdr = mi->p_hdr_data[i];1166else1167continue;1168
1169if (memchr(hdr->buf, '\0', hdr->len)) {1170error("a NUL byte in '%s' is not allowed.", header[i]);1171mi->input_error = -1;1172}1173
1174if (!strcmp(header[i], "Subject")) {1175if (!mi->keep_subject) {1176cleanup_subject(mi, hdr);1177cleanup_space(hdr);1178}1179output_header_lines(mi->output, "Subject", hdr);1180} else if (!strcmp(header[i], "From")) {1181cleanup_space(hdr);1182handle_from(mi, hdr);1183fprintf(mi->output, "Author: %s\n", mi->name.buf);1184fprintf(mi->output, "Email: %s\n", mi->email.buf);1185} else {1186cleanup_space(hdr);1187fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);1188}1189}1190fprintf(mi->output, "\n");1191}
1192
1193int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)1194{
1195FILE *cmitmsg;1196int peek;1197struct strbuf line = STRBUF_INIT;1198
1199cmitmsg = fopen(msg, "w");1200if (!cmitmsg) {1201perror(msg);1202return -1;1203}1204mi->patchfile = fopen(patch, "w");1205if (!mi->patchfile) {1206perror(patch);1207fclose(cmitmsg);1208return -1;1209}1210
1211mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));1212mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));1213
1214do {1215peek = fgetc(mi->input);1216if (peek == EOF) {1217fclose(cmitmsg);1218return error("empty patch: '%s'", patch);1219}1220} while (isspace(peek));1221ungetc(peek, mi->input);1222
1223/* process the email header */1224while (read_one_header_line(&line, mi->input))1225check_header(mi, &line, mi->p_hdr_data, 1);1226
1227handle_body(mi, &line);1228fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);1229fclose(cmitmsg);1230fclose(mi->patchfile);1231
1232handle_info(mi);1233strbuf_release(&line);1234return mi->input_error;1235}
1236
1237int mailinfo_parse_quoted_cr_action(const char *actionstr, int *action)1238{
1239if (!strcmp(actionstr, "nowarn"))1240*action = quoted_cr_nowarn;1241else if (!strcmp(actionstr, "warn"))1242*action = quoted_cr_warn;1243else if (!strcmp(actionstr, "strip"))1244*action = quoted_cr_strip;1245else1246return -1;1247return 0;1248}
1249
1250static int git_mailinfo_config(const char *var, const char *value,1251const struct config_context *ctx, void *mi_)1252{
1253struct mailinfo *mi = mi_;1254
1255if (!starts_with(var, "mailinfo."))1256return git_default_config(var, value, ctx, NULL);1257if (!strcmp(var, "mailinfo.scissors")) {1258mi->use_scissors = git_config_bool(var, value);1259return 0;1260}1261if (!strcmp(var, "mailinfo.quotedcr")) {1262if (!value)1263return config_error_nonbool(var);1264if (mailinfo_parse_quoted_cr_action(value, &mi->quoted_cr) != 0)1265return error(_("bad action '%s' for '%s'"), value, var);1266return 0;1267}1268/* perhaps others here */1269return 0;1270}
1271
1272void setup_mailinfo(struct mailinfo *mi)1273{
1274memset(mi, 0, sizeof(*mi));1275strbuf_init(&mi->name, 0);1276strbuf_init(&mi->email, 0);1277strbuf_init(&mi->charset, 0);1278strbuf_init(&mi->log_message, 0);1279strbuf_init(&mi->inbody_header_accum, 0);1280mi->quoted_cr = quoted_cr_warn;1281mi->header_stage = 1;1282mi->use_inbody_headers = 1;1283mi->content_top = mi->content;1284git_config(git_mailinfo_config, mi);1285}
1286
1287void clear_mailinfo(struct mailinfo *mi)1288{
1289strbuf_release(&mi->name);1290strbuf_release(&mi->email);1291strbuf_release(&mi->charset);1292strbuf_release(&mi->inbody_header_accum);1293free(mi->message_id);1294
1295strbuf_list_free(mi->p_hdr_data);1296strbuf_list_free(mi->s_hdr_data);1297
1298while (mi->content < mi->content_top) {1299free(*(mi->content_top));1300mi->content_top--;1301}1302
1303strbuf_release(&mi->log_message);1304}
1305