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