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