]> git.notmuchmail.org Git - notmuch/blob - notmuch-reply.c
notmuch part: Fix part numbering to match what's reported by "notmuch show"
[notmuch] / notmuch-reply.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  * Copyright © 2009 Keith Packard
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see http://www.gnu.org/licenses/ .
18  *
19  * Authors: Carl Worth <cworth@cworth.org>
20  *          Keith Packard <keithp@keithp.com>
21  */
22
23 #include "notmuch-client.h"
24 #include "gmime-filter-reply.h"
25 #include "gmime-filter-headers.h"
26
27 static void
28 reply_part (GMimeObject *part,
29             unused (int *part_count),
30             unused (int first));
31
32 static const notmuch_show_format_t format_reply = {
33     NULL,
34         NULL, NULL,
35             NULL, NULL, NULL,
36             NULL, reply_part, NULL, NULL,
37         NULL, NULL,
38     NULL
39 };
40
41 static void
42 reply_part_content (GMimeObject *part)
43 {
44     GMimeStream *stream_stdout = NULL, *stream_filter = NULL;
45     GMimeDataWrapper *wrapper;
46     const char *charset;
47
48     charset = g_mime_object_get_content_type_parameter (part, "charset");
49     stream_stdout = g_mime_stream_file_new (stdout);
50     if (stream_stdout) {
51         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
52         stream_filter = g_mime_stream_filter_new(stream_stdout);
53         if (charset) {
54           g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream_filter),
55                                    g_mime_filter_charset_new(charset, "UTF-8"));
56         }
57     }
58     g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream_filter),
59                              g_mime_filter_reply_new(TRUE));
60     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
61     if (wrapper && stream_filter)
62         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
63     if (stream_filter)
64         g_object_unref(stream_filter);
65     if (stream_stdout)
66         g_object_unref(stream_stdout);
67 }
68
69 static void
70 show_reply_headers (GMimeMessage *message)
71 {
72     GMimeStream *stream_stdout = NULL, *stream_filter = NULL;
73
74     stream_stdout = g_mime_stream_file_new (stdout);
75     if (stream_stdout) {
76         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
77         stream_filter = g_mime_stream_filter_new(stream_stdout);
78         if (stream_filter) {
79                 g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream_filter),
80                                          g_mime_filter_headers_new());
81                 g_mime_object_write_to_stream(GMIME_OBJECT(message), stream_filter);
82                 g_object_unref(stream_filter);
83         }
84         g_object_unref(stream_stdout);
85     }
86 }
87
88 static void
89 reply_part (GMimeObject *part,
90             unused (int *part_count),
91             unused (int first))
92 {
93     GMimeContentDisposition *disposition;
94     GMimeContentType *content_type;
95
96     disposition = g_mime_object_get_content_disposition (part);
97     if (disposition &&
98         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
99     {
100         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
101         content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
102
103         if (g_mime_content_type_is_type (content_type, "text", "*") &&
104             !g_mime_content_type_is_type (content_type, "text", "html"))
105         {
106             reply_part_content (part);
107         }
108         else
109         {
110             printf ("Attachment: %s (%s)\n", filename,
111                     g_mime_content_type_to_string (content_type));
112         }
113
114         return;
115     }
116
117     content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
118
119     if (g_mime_content_type_is_type (content_type, "text", "*") &&
120         !g_mime_content_type_is_type (content_type, "text", "html"))
121     {
122         reply_part_content (part);
123     }
124     else
125     {
126         printf ("Non-text part: %s\n",
127                 g_mime_content_type_to_string (content_type));
128     }
129 }
130
131 /* Is the given address configured as one of the user's "personal" or
132  * "other" addresses. */
133 static int
134 address_is_users (const char *address, notmuch_config_t *config)
135 {
136     const char *primary;
137     const char **other;
138     size_t i, other_len;
139
140     primary = notmuch_config_get_user_primary_email (config);
141     if (strcasecmp (primary, address) == 0)
142         return 1;
143
144     other = notmuch_config_get_user_other_email (config, &other_len);
145     for (i = 0; i < other_len; i++)
146         if (strcasecmp (other[i], address) == 0)
147             return 1;
148
149     return 0;
150 }
151
152 /* For each address in 'list' that is not configured as one of the
153  * user's addresses in 'config', add that address to 'message' as an
154  * address of 'type'.
155  *
156  * The first address encountered that *is* the user's address will be
157  * returned, (otherwise NULL is returned).
158  */
159 static const char *
160 add_recipients_for_address_list (GMimeMessage *message,
161                                  notmuch_config_t *config,
162                                  GMimeRecipientType type,
163                                  InternetAddressList *list)
164 {
165     InternetAddress *address;
166     int i;
167     const char *ret = NULL;
168
169     for (i = 0; i < internet_address_list_length (list); i++) {
170         address = internet_address_list_get_address (list, i);
171         if (INTERNET_ADDRESS_IS_GROUP (address)) {
172             InternetAddressGroup *group;
173             InternetAddressList *group_list;
174
175             group = INTERNET_ADDRESS_GROUP (address);
176             group_list = internet_address_group_get_members (group);
177             if (group_list == NULL)
178                 continue;
179
180             add_recipients_for_address_list (message, config,
181                                              type, group_list);
182         } else {
183             InternetAddressMailbox *mailbox;
184             const char *name;
185             const char *addr;
186
187             mailbox = INTERNET_ADDRESS_MAILBOX (address);
188
189             name = internet_address_get_name (address);
190             addr = internet_address_mailbox_get_addr (mailbox);
191
192             if (address_is_users (addr, config)) {
193                 if (ret == NULL)
194                     ret = addr;
195             } else {
196                 g_mime_message_add_recipient (message, type, name, addr);
197             }
198         }
199     }
200
201     return ret;
202 }
203
204 /* For each address in 'recipients' that is not configured as one of
205  * the user's addresses in 'config', add that address to 'message' as
206  * an address of 'type'.
207  *
208  * The first address encountered that *is* the user's address will be
209  * returned, (otherwise NULL is returned).
210  */
211 static const char *
212 add_recipients_for_string (GMimeMessage *message,
213                            notmuch_config_t *config,
214                            GMimeRecipientType type,
215                            const char *recipients)
216 {
217     InternetAddressList *list;
218
219     if (recipients == NULL)
220         return NULL;
221
222     list = internet_address_list_parse_string (recipients);
223     if (list == NULL)
224         return NULL;
225
226     return add_recipients_for_address_list (message, config, type, list);
227 }
228
229 /* Does the address in the Reply-To header of 'message' already appear
230  * in either the 'To' or 'Cc' header of the message?
231  */
232 static int
233 reply_to_header_is_redundant (notmuch_message_t *message)
234 {
235     const char *reply_to, *to, *cc, *addr;
236     InternetAddressList *list;
237     InternetAddress *address;
238     InternetAddressMailbox *mailbox;
239
240     reply_to = notmuch_message_get_header (message, "reply-to");
241     if (reply_to == NULL || *reply_to == '\0')
242         return 0;
243
244     list = internet_address_list_parse_string (reply_to);
245
246     if (internet_address_list_length (list) != 1)
247         return 0;
248
249     address = internet_address_list_get_address (list, 0);
250     if (INTERNET_ADDRESS_IS_GROUP (address))
251         return 0;
252
253     mailbox = INTERNET_ADDRESS_MAILBOX (address);
254     addr = internet_address_mailbox_get_addr (mailbox);
255
256     to = notmuch_message_get_header (message, "to");
257     cc = notmuch_message_get_header (message, "cc");
258
259     if ((to && strstr (to, addr) != 0) ||
260         (cc && strstr (cc, addr) != 0))
261     {
262         return 1;
263     }
264
265     return 0;
266 }
267
268 /* Augments the recipients of reply from the headers of message.
269  *
270  * If any of the user's addresses were found in these headers, the first
271  * of these returned, otherwise NULL is returned.
272  */
273 static const char *
274 add_recipients_from_message (GMimeMessage *reply,
275                              notmuch_config_t *config,
276                              notmuch_message_t *message)
277 {
278     struct {
279         const char *header;
280         const char *fallback;
281         GMimeRecipientType recipient_type;
282     } reply_to_map[] = {
283         { "reply-to", "from", GMIME_RECIPIENT_TYPE_TO  },
284         { "to",         NULL, GMIME_RECIPIENT_TYPE_TO  },
285         { "cc",         NULL, GMIME_RECIPIENT_TYPE_CC  },
286         { "bcc",        NULL, GMIME_RECIPIENT_TYPE_BCC }
287     };
288     const char *from_addr = NULL;
289     unsigned int i;
290
291     /* Some mailing lists munge the Reply-To header despite it being A Bad
292      * Thing, see http://www.unicom.com/pw/reply-to-harmful.html
293      *
294      * The munging is easy to detect, because it results in a
295      * redundant reply-to header, (with an address that already exists
296      * in either To or Cc). So in this case, we ignore the Reply-To
297      * field and use the From header. Thie ensures the original sender
298      * will get the reply even if not subscribed to the list. Note
299      * that the address in the Reply-To header will always appear in
300      * the reply.
301      */
302     if (reply_to_header_is_redundant (message)) {
303         reply_to_map[0].header = "from";
304         reply_to_map[0].fallback = NULL;
305     }
306
307     for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
308         const char *addr, *recipients;
309
310         recipients = notmuch_message_get_header (message,
311                                                  reply_to_map[i].header);
312         if ((recipients == NULL || recipients[0] == '\0') && reply_to_map[i].fallback)
313             recipients = notmuch_message_get_header (message,
314                                                      reply_to_map[i].fallback);
315
316         addr = add_recipients_for_string (reply, config,
317                                           reply_to_map[i].recipient_type,
318                                           recipients);
319         if (from_addr == NULL)
320             from_addr = addr;
321     }
322
323     return from_addr;
324 }
325
326 static const char *
327 guess_from_received_header (notmuch_config_t *config, notmuch_message_t *message)
328 {
329     const char *received,*primary,*by;
330     const char **other;
331     char *tohdr;
332     char *mta,*ptr,*token;
333     char *domain=NULL;
334     char *tld=NULL;
335     const char *delim=". \t";
336     size_t i,j,other_len;
337
338     const char *to_headers[] = {"Envelope-to", "X-Original-To"};
339
340     primary = notmuch_config_get_user_primary_email (config);
341     other = notmuch_config_get_user_other_email (config, &other_len);
342
343     /* sadly, there is no standard way to find out to which email
344      * address a mail was delivered - what is in the headers depends
345      * on the MTAs used along the way. So we are trying a number of
346      * heuristics which hopefully will answer this question.
347
348      * We only got here if none of the users email addresses are in
349      * the To: or Cc: header. From here we try the following in order:
350      * 1) check for an Envelope-to: header
351      * 2) check for an X-Original-To: header
352      * 3) check for a (for <email@add.res>) clause in Received: headers
353      * 4) check for the domain part of known email addresses in the
354      *    'by' part of Received headers
355      * If none of these work, we give up and return NULL
356      */
357     for (i = 0; i < sizeof(to_headers)/sizeof(*to_headers); i++) {
358         tohdr = xstrdup(notmuch_message_get_header (message, to_headers[i]));
359         if (tohdr && *tohdr) {
360             /* tohdr is potentialy a list of email addresses, so here we
361              * check if one of the email addresses is a substring of tohdr
362              */
363             if (strcasestr(tohdr, primary)) {
364                 free(tohdr);
365                 return primary;
366             }
367             for (j = 0; j < other_len; j++)
368                 if (strcasestr (tohdr, other[j])) {
369                     free(tohdr);
370                     return other[j];
371                 }
372             free(tohdr);
373         }
374     }
375
376     /* We get the concatenated Received: headers and search from the
377      * front (last Received: header added) and try to extract from
378      * them indications to which email address this message was
379      * delivered.
380      * The Received: header is special in our get_header function
381      * and is always concated.
382      */
383     received = notmuch_message_get_header (message, "received");
384     if (received == NULL)
385         return NULL;
386
387     /* First we look for a " for <email@add.res>" in the received
388      * header
389      */
390     ptr = strstr (received, " for ");
391     if (ptr) {
392         /* the text following is potentialy a list of email addresses,
393          * so again we check if one of the email addresses is a
394          * substring of ptr
395          */
396         if (strcasestr(ptr, primary)) {
397             return primary;
398         }
399         for (i = 0; i < other_len; i++)
400             if (strcasestr (ptr, other[i])) {
401                 return other[i];
402             }
403     }
404     /* Finally, we parse all the " by MTA ..." headers to guess the
405      * email address that this was originally delivered to.
406      * We extract just the MTA here by removing leading whitespace and
407      * assuming that the MTA name ends at the next whitespace.
408      * We test for *(by+4) to be non-'\0' to make sure there's
409      * something there at all - and then assume that the first
410      * whitespace delimited token that follows is the receiving
411      * system in this step of the receive chain
412      */
413     by = received;
414     while((by = strstr (by, " by ")) != NULL) {
415         by += 4;
416         if (*by == '\0')
417             break;
418         mta = xstrdup (by);
419         token = strtok(mta," \t");
420         if (token == NULL)
421             break;
422         /* Now extract the last two components of the MTA host name
423          * as domain and tld.
424          */
425         while ((ptr = strsep (&token, delim)) != NULL) {
426             if (*ptr == '\0')
427                 continue;
428             domain = tld;
429             tld = ptr;
430         }
431
432         if (domain) {
433             /* Recombine domain and tld and look for it among the configured
434              * email addresses.
435              * This time we have a known domain name and nothing else - so
436              * the test is the other way around: we check if this is a
437              * substring of one of the email addresses.
438              */
439             *(tld-1) = '.';
440
441             if (strcasestr(primary, domain)) {
442                 free(mta);
443             return primary;
444         }
445         for (i = 0; i < other_len; i++)
446             if (strcasestr (other[i],domain)) {
447                 free(mta);
448                 return other[i];
449             }
450         }
451         free (mta);
452     }
453
454     return NULL;
455 }
456
457 static int
458 notmuch_reply_format_default(void *ctx, notmuch_config_t *config, notmuch_query_t *query)
459 {
460     GMimeMessage *reply;
461     notmuch_messages_t *messages;
462     notmuch_message_t *message;
463     const char *subject, *from_addr = NULL;
464     const char *in_reply_to, *orig_references, *references;
465     const notmuch_show_format_t *format = &format_reply;
466
467     for (messages = notmuch_query_search_messages (query);
468          notmuch_messages_valid (messages);
469          notmuch_messages_move_to_next (messages))
470     {
471         message = notmuch_messages_get (messages);
472
473         /* The 1 means we want headers in a "pretty" order. */
474         reply = g_mime_message_new (1);
475         if (reply == NULL) {
476             fprintf (stderr, "Out of memory\n");
477             return 1;
478         }
479
480         subject = notmuch_message_get_header (message, "subject");
481         if (subject) {
482             if (strncasecmp (subject, "Re:", 3))
483                 subject = talloc_asprintf (ctx, "Re: %s", subject);
484             g_mime_message_set_subject (reply, subject);
485         }
486
487         from_addr = add_recipients_from_message (reply, config, message);
488
489         if (from_addr == NULL)
490             from_addr = guess_from_received_header (config, message);
491
492         if (from_addr == NULL)
493             from_addr = notmuch_config_get_user_primary_email (config);
494
495         from_addr = talloc_asprintf (ctx, "%s <%s>",
496                                      notmuch_config_get_user_name (config),
497                                      from_addr);
498         g_mime_object_set_header (GMIME_OBJECT (reply),
499                                   "From", from_addr);
500
501         in_reply_to = talloc_asprintf (ctx, "<%s>",
502                              notmuch_message_get_message_id (message));
503
504         g_mime_object_set_header (GMIME_OBJECT (reply),
505                                   "In-Reply-To", in_reply_to);
506
507         orig_references = notmuch_message_get_header (message, "references");
508         references = talloc_asprintf (ctx, "%s%s%s",
509                                       orig_references ? orig_references : "",
510                                       orig_references ? " " : "",
511                                       in_reply_to);
512         g_mime_object_set_header (GMIME_OBJECT (reply),
513                                   "References", references);
514
515         show_reply_headers (reply);
516
517         g_object_unref (G_OBJECT (reply));
518         reply = NULL;
519
520         printf ("On %s, %s wrote:\n",
521                 notmuch_message_get_header (message, "date"),
522                 notmuch_message_get_header (message, "from"));
523
524         show_message_body (notmuch_message_get_filename (message),
525                            format);
526
527         notmuch_message_destroy (message);
528     }
529     return 0;
530 }
531
532 /* This format is currently tuned for a git send-email --notmuch hook */
533 static int
534 notmuch_reply_format_headers_only(void *ctx, notmuch_config_t *config, notmuch_query_t *query)
535 {
536     GMimeMessage *reply;
537     notmuch_messages_t *messages;
538     notmuch_message_t *message;
539     const char *in_reply_to, *orig_references, *references;
540     char *reply_headers;
541
542     for (messages = notmuch_query_search_messages (query);
543          notmuch_messages_valid (messages);
544          notmuch_messages_move_to_next (messages))
545     {
546         message = notmuch_messages_get (messages);
547
548         /* The 0 means we do not want headers in a "pretty" order. */
549         reply = g_mime_message_new (0);
550         if (reply == NULL) {
551             fprintf (stderr, "Out of memory\n");
552             return 1;
553         }
554
555         in_reply_to = talloc_asprintf (ctx, "<%s>",
556                              notmuch_message_get_message_id (message));
557
558         g_mime_object_set_header (GMIME_OBJECT (reply),
559                                   "In-Reply-To", in_reply_to);
560
561
562         orig_references = notmuch_message_get_header (message, "references");
563
564         /* We print In-Reply-To followed by References because git format-patch treats them
565          * specially.  Git does not interpret the other headers specially
566          */
567         references = talloc_asprintf (ctx, "%s%s%s",
568                                       orig_references ? orig_references : "",
569                                       orig_references ? " " : "",
570                                       in_reply_to);
571         g_mime_object_set_header (GMIME_OBJECT (reply),
572                                   "References", references);
573
574         (void)add_recipients_from_message (reply, config, message);
575
576         reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
577         printf ("%s", reply_headers);
578         free (reply_headers);
579
580         g_object_unref (G_OBJECT (reply));
581         reply = NULL;
582
583         notmuch_message_destroy (message);
584     }
585     return 0;
586 }
587
588 int
589 notmuch_reply_command (void *ctx, int argc, char *argv[])
590 {
591     notmuch_config_t *config;
592     notmuch_database_t *notmuch;
593     notmuch_query_t *query;
594     char *opt, *query_string;
595     int i, ret = 0;
596     int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query);
597
598     reply_format_func = notmuch_reply_format_default;
599
600     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
601         if (strcmp (argv[i], "--") == 0) {
602             i++;
603             break;
604         }
605         if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
606             opt = argv[i] + sizeof ("--format=") - 1;
607             if (strcmp (opt, "default") == 0) {
608                 reply_format_func = notmuch_reply_format_default;
609             } else if (strcmp (opt, "headers-only") == 0) {
610                 reply_format_func = notmuch_reply_format_headers_only;
611             } else {
612                 fprintf (stderr, "Invalid value for --format: %s\n", opt);
613                 return 1;
614             }
615         } else {
616             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
617             return 1;
618         }
619     }
620
621     argc -= i;
622     argv += i;
623
624     config = notmuch_config_open (ctx, NULL, NULL);
625     if (config == NULL)
626         return 1;
627
628     query_string = query_string_from_args (ctx, argc, argv);
629     if (query_string == NULL) {
630         fprintf (stderr, "Out of memory\n");
631         return 1;
632     }
633
634     if (*query_string == '\0') {
635         fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
636         return 1;
637     }
638
639     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
640                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
641     if (notmuch == NULL)
642         return 1;
643
644     query = notmuch_query_create (notmuch, query_string);
645     if (query == NULL) {
646         fprintf (stderr, "Out of memory\n");
647         return 1;
648     }
649
650     if (reply_format_func (ctx, config, query) != 0)
651         return 1;
652
653     notmuch_query_destroy (query);
654     notmuch_database_close (notmuch);
655
656     return ret;
657 }