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