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