]> git.notmuchmail.org Git - notmuch/blob - notmuch-reply.c
cli: slightly refactor "notmuch reply" address scanning functions
[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 /* Scan addresses in 'list'.
172  *
173  * If 'message' is non-NULL, then for each address in 'list' that is
174  * not configured as one of the user's addresses in 'config', add that
175  * address to 'message' as an address of 'type'.
176  *
177  * If 'user_from' is non-NULL and *user_from is NULL, *user_from will
178  * be set to the first address encountered in 'list' that is the
179  * user's address.
180  *
181  * Return the number of addresses added to 'message'. (If 'message' is
182  * NULL, the function returns 0 by definition.)
183  */
184 static unsigned int
185 scan_address_list (InternetAddressList *list,
186                    notmuch_config_t *config,
187                    GMimeMessage *message,
188                    GMimeRecipientType type,
189                    const char **user_from)
190 {
191     InternetAddress *address;
192     int i;
193     unsigned int n = 0;
194
195     for (i = 0; i < internet_address_list_length (list); i++) {
196         address = internet_address_list_get_address (list, i);
197         if (INTERNET_ADDRESS_IS_GROUP (address)) {
198             InternetAddressGroup *group;
199             InternetAddressList *group_list;
200
201             group = INTERNET_ADDRESS_GROUP (address);
202             group_list = internet_address_group_get_members (group);
203             if (group_list == NULL)
204                 continue;
205
206             n += scan_address_list (group_list, config, message, type, NULL);
207         } else {
208             InternetAddressMailbox *mailbox;
209             const char *name;
210             const char *addr;
211
212             mailbox = INTERNET_ADDRESS_MAILBOX (address);
213
214             name = internet_address_get_name (address);
215             addr = internet_address_mailbox_get_addr (mailbox);
216
217             if (address_is_users (addr, config)) {
218                 if (user_from && *user_from == NULL)
219                     *user_from = addr;
220             } else if (message) {
221                 g_mime_message_add_recipient (message, type, name, addr);
222                 n++;
223             }
224         }
225     }
226
227     return n;
228 }
229
230 /* Scan addresses in 'recipients'.
231  *
232  * See the documentation of scan_address_list() above. This function
233  * does exactly the same, but converts 'recipients' to an
234  * InternetAddressList first.
235  */
236 static unsigned int
237 scan_address_string (const char *recipients,
238                      notmuch_config_t *config,
239                      GMimeMessage *message,
240                      GMimeRecipientType type,
241                      const char **user_from)
242 {
243     InternetAddressList *list;
244
245     if (recipients == NULL)
246         return 0;
247
248     list = internet_address_list_parse_string (recipients);
249     if (list == NULL)
250         return 0;
251
252     return scan_address_list (list, config, message, type, user_from);
253 }
254
255 /* Does the address in the Reply-To header of 'message' already appear
256  * in either the 'To' or 'Cc' header of the message?
257  */
258 static int
259 reply_to_header_is_redundant (notmuch_message_t *message)
260 {
261     const char *reply_to, *to, *cc, *addr;
262     InternetAddressList *list;
263     InternetAddress *address;
264     InternetAddressMailbox *mailbox;
265
266     reply_to = notmuch_message_get_header (message, "reply-to");
267     if (reply_to == NULL || *reply_to == '\0')
268         return 0;
269
270     list = internet_address_list_parse_string (reply_to);
271
272     if (internet_address_list_length (list) != 1)
273         return 0;
274
275     address = internet_address_list_get_address (list, 0);
276     if (INTERNET_ADDRESS_IS_GROUP (address))
277         return 0;
278
279     mailbox = INTERNET_ADDRESS_MAILBOX (address);
280     addr = internet_address_mailbox_get_addr (mailbox);
281
282     to = notmuch_message_get_header (message, "to");
283     cc = notmuch_message_get_header (message, "cc");
284
285     if ((to && strstr (to, addr) != 0) ||
286         (cc && strstr (cc, addr) != 0))
287     {
288         return 1;
289     }
290
291     return 0;
292 }
293
294 /* Augments the recipients of reply from the headers of message.
295  *
296  * If any of the user's addresses were found in these headers, the first
297  * of these returned, otherwise NULL is returned.
298  */
299 static const char *
300 add_recipients_from_message (GMimeMessage *reply,
301                              notmuch_config_t *config,
302                              notmuch_message_t *message)
303 {
304     struct {
305         const char *header;
306         const char *fallback;
307         GMimeRecipientType recipient_type;
308     } reply_to_map[] = {
309         { "reply-to", "from", GMIME_RECIPIENT_TYPE_TO  },
310         { "to",         NULL, GMIME_RECIPIENT_TYPE_TO  },
311         { "cc",         NULL, GMIME_RECIPIENT_TYPE_CC  },
312         { "bcc",        NULL, GMIME_RECIPIENT_TYPE_BCC }
313     };
314     const char *from_addr = NULL;
315     unsigned int i;
316
317     /* Some mailing lists munge the Reply-To header despite it being A Bad
318      * Thing, see http://www.unicom.com/pw/reply-to-harmful.html
319      *
320      * The munging is easy to detect, because it results in a
321      * redundant reply-to header, (with an address that already exists
322      * in either To or Cc). So in this case, we ignore the Reply-To
323      * field and use the From header. This ensures the original sender
324      * will get the reply even if not subscribed to the list. Note
325      * that the address in the Reply-To header will always appear in
326      * the reply.
327      */
328     if (reply_to_header_is_redundant (message)) {
329         reply_to_map[0].header = "from";
330         reply_to_map[0].fallback = NULL;
331     }
332
333     for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
334         const char *recipients;
335
336         recipients = notmuch_message_get_header (message,
337                                                  reply_to_map[i].header);
338         if ((recipients == NULL || recipients[0] == '\0') && reply_to_map[i].fallback)
339             recipients = notmuch_message_get_header (message,
340                                                      reply_to_map[i].fallback);
341
342         scan_address_string (recipients, config, reply,
343                              reply_to_map[i].recipient_type, &from_addr);
344     }
345
346     return from_addr;
347 }
348
349 static const char *
350 guess_from_received_header (notmuch_config_t *config, notmuch_message_t *message)
351 {
352     const char *received,*primary,*by;
353     const char **other;
354     char *tohdr;
355     char *mta,*ptr,*token;
356     char *domain=NULL;
357     char *tld=NULL;
358     const char *delim=". \t";
359     size_t i,j,other_len;
360
361     const char *to_headers[] = {"Envelope-to", "X-Original-To"};
362
363     primary = notmuch_config_get_user_primary_email (config);
364     other = notmuch_config_get_user_other_email (config, &other_len);
365
366     /* sadly, there is no standard way to find out to which email
367      * address a mail was delivered - what is in the headers depends
368      * on the MTAs used along the way. So we are trying a number of
369      * heuristics which hopefully will answer this question.
370
371      * We only got here if none of the users email addresses are in
372      * the To: or Cc: header. From here we try the following in order:
373      * 1) check for an Envelope-to: header
374      * 2) check for an X-Original-To: header
375      * 3) check for a (for <email@add.res>) clause in Received: headers
376      * 4) check for the domain part of known email addresses in the
377      *    'by' part of Received headers
378      * If none of these work, we give up and return NULL
379      */
380     for (i = 0; i < sizeof(to_headers)/sizeof(*to_headers); i++) {
381         tohdr = xstrdup(notmuch_message_get_header (message, to_headers[i]));
382         if (tohdr && *tohdr) {
383             /* tohdr is potentialy a list of email addresses, so here we
384              * check if one of the email addresses is a substring of tohdr
385              */
386             if (strcasestr(tohdr, primary)) {
387                 free(tohdr);
388                 return primary;
389             }
390             for (j = 0; j < other_len; j++)
391                 if (strcasestr (tohdr, other[j])) {
392                     free(tohdr);
393                     return other[j];
394                 }
395             free(tohdr);
396         }
397     }
398
399     /* We get the concatenated Received: headers and search from the
400      * front (last Received: header added) and try to extract from
401      * them indications to which email address this message was
402      * delivered.
403      * The Received: header is special in our get_header function
404      * and is always concatenated.
405      */
406     received = notmuch_message_get_header (message, "received");
407     if (received == NULL)
408         return NULL;
409
410     /* First we look for a " for <email@add.res>" in the received
411      * header
412      */
413     ptr = strstr (received, " for ");
414     if (ptr) {
415         /* the text following is potentialy a list of email addresses,
416          * so again we check if one of the email addresses is a
417          * substring of ptr
418          */
419         if (strcasestr(ptr, primary)) {
420             return primary;
421         }
422         for (i = 0; i < other_len; i++)
423             if (strcasestr (ptr, other[i])) {
424                 return other[i];
425             }
426     }
427     /* Finally, we parse all the " by MTA ..." headers to guess the
428      * email address that this was originally delivered to.
429      * We extract just the MTA here by removing leading whitespace and
430      * assuming that the MTA name ends at the next whitespace.
431      * We test for *(by+4) to be non-'\0' to make sure there's
432      * something there at all - and then assume that the first
433      * whitespace delimited token that follows is the receiving
434      * system in this step of the receive chain
435      */
436     by = received;
437     while((by = strstr (by, " by ")) != NULL) {
438         by += 4;
439         if (*by == '\0')
440             break;
441         mta = xstrdup (by);
442         token = strtok(mta," \t");
443         if (token == NULL) {
444             free (mta);
445             break;
446         }
447         /* Now extract the last two components of the MTA host name
448          * as domain and tld.
449          */
450         domain = tld = NULL;
451         while ((ptr = strsep (&token, delim)) != NULL) {
452             if (*ptr == '\0')
453                 continue;
454             domain = tld;
455             tld = ptr;
456         }
457
458         if (domain) {
459             /* Recombine domain and tld and look for it among the configured
460              * email addresses.
461              * This time we have a known domain name and nothing else - so
462              * the test is the other way around: we check if this is a
463              * substring of one of the email addresses.
464              */
465             *(tld-1) = '.';
466
467             if (strcasestr(primary, domain)) {
468                 free(mta);
469                 return primary;
470             }
471             for (i = 0; i < other_len; i++)
472                 if (strcasestr (other[i],domain)) {
473                     free(mta);
474                     return other[i];
475                 }
476         }
477         free (mta);
478     }
479
480     return NULL;
481 }
482
483 static int
484 notmuch_reply_format_default(void *ctx,
485                              notmuch_config_t *config,
486                              notmuch_query_t *query,
487                              notmuch_show_params_t *params)
488 {
489     GMimeMessage *reply;
490     notmuch_messages_t *messages;
491     notmuch_message_t *message;
492     const char *subject, *from_addr = NULL;
493     const char *in_reply_to, *orig_references, *references;
494     const notmuch_show_format_t *format = &format_reply;
495
496     for (messages = notmuch_query_search_messages (query);
497          notmuch_messages_valid (messages);
498          notmuch_messages_move_to_next (messages))
499     {
500         message = notmuch_messages_get (messages);
501
502         /* The 1 means we want headers in a "pretty" order. */
503         reply = g_mime_message_new (1);
504         if (reply == NULL) {
505             fprintf (stderr, "Out of memory\n");
506             return 1;
507         }
508
509         subject = notmuch_message_get_header (message, "subject");
510         if (subject) {
511             if (strncasecmp (subject, "Re:", 3))
512                 subject = talloc_asprintf (ctx, "Re: %s", subject);
513             g_mime_message_set_subject (reply, subject);
514         }
515
516         from_addr = add_recipients_from_message (reply, config, message);
517
518         if (from_addr == NULL)
519             from_addr = guess_from_received_header (config, message);
520
521         if (from_addr == NULL)
522             from_addr = notmuch_config_get_user_primary_email (config);
523
524         from_addr = talloc_asprintf (ctx, "%s <%s>",
525                                      notmuch_config_get_user_name (config),
526                                      from_addr);
527         g_mime_object_set_header (GMIME_OBJECT (reply),
528                                   "From", from_addr);
529
530         in_reply_to = talloc_asprintf (ctx, "<%s>",
531                              notmuch_message_get_message_id (message));
532
533         g_mime_object_set_header (GMIME_OBJECT (reply),
534                                   "In-Reply-To", in_reply_to);
535
536         orig_references = notmuch_message_get_header (message, "references");
537         references = talloc_asprintf (ctx, "%s%s%s",
538                                       orig_references ? orig_references : "",
539                                       orig_references ? " " : "",
540                                       in_reply_to);
541         g_mime_object_set_header (GMIME_OBJECT (reply),
542                                   "References", references);
543
544         show_reply_headers (reply);
545
546         g_object_unref (G_OBJECT (reply));
547         reply = NULL;
548
549         printf ("On %s, %s wrote:\n",
550                 notmuch_message_get_header (message, "date"),
551                 notmuch_message_get_header (message, "from"));
552
553         show_message_body (message, format, params);
554
555         notmuch_message_destroy (message);
556     }
557     return 0;
558 }
559
560 /* This format is currently tuned for a git send-email --notmuch hook */
561 static int
562 notmuch_reply_format_headers_only(void *ctx,
563                                   notmuch_config_t *config,
564                                   notmuch_query_t *query,
565                                   unused (notmuch_show_params_t *params))
566 {
567     GMimeMessage *reply;
568     notmuch_messages_t *messages;
569     notmuch_message_t *message;
570     const char *in_reply_to, *orig_references, *references;
571     char *reply_headers;
572
573     for (messages = notmuch_query_search_messages (query);
574          notmuch_messages_valid (messages);
575          notmuch_messages_move_to_next (messages))
576     {
577         message = notmuch_messages_get (messages);
578
579         /* The 0 means we do not want headers in a "pretty" order. */
580         reply = g_mime_message_new (0);
581         if (reply == NULL) {
582             fprintf (stderr, "Out of memory\n");
583             return 1;
584         }
585
586         in_reply_to = talloc_asprintf (ctx, "<%s>",
587                              notmuch_message_get_message_id (message));
588
589         g_mime_object_set_header (GMIME_OBJECT (reply),
590                                   "In-Reply-To", in_reply_to);
591
592
593         orig_references = notmuch_message_get_header (message, "references");
594
595         /* We print In-Reply-To followed by References because git format-patch treats them
596          * specially.  Git does not interpret the other headers specially
597          */
598         references = talloc_asprintf (ctx, "%s%s%s",
599                                       orig_references ? orig_references : "",
600                                       orig_references ? " " : "",
601                                       in_reply_to);
602         g_mime_object_set_header (GMIME_OBJECT (reply),
603                                   "References", references);
604
605         (void)add_recipients_from_message (reply, config, message);
606
607         reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
608         printf ("%s", reply_headers);
609         free (reply_headers);
610
611         g_object_unref (G_OBJECT (reply));
612         reply = NULL;
613
614         notmuch_message_destroy (message);
615     }
616     return 0;
617 }
618
619 enum {
620     FORMAT_DEFAULT,
621     FORMAT_HEADERS_ONLY,
622 };
623
624 int
625 notmuch_reply_command (void *ctx, int argc, char *argv[])
626 {
627     notmuch_config_t *config;
628     notmuch_database_t *notmuch;
629     notmuch_query_t *query;
630     char *query_string;
631     int opt_index, ret = 0;
632     int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params);
633     notmuch_show_params_t params = { .part = -1 };
634     int format = FORMAT_DEFAULT;
635     notmuch_bool_t decrypt = FALSE;
636
637     notmuch_opt_desc_t options[] = {
638         { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
639           (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
640                                   { "headers-only", FORMAT_HEADERS_ONLY },
641                                   { 0, 0 } } },
642         { NOTMUCH_OPT_BOOLEAN, &decrypt, "decrypt", 'd', 0 },
643         { 0, 0, 0, 0, 0 }
644     };
645
646     opt_index = parse_arguments (argc, argv, options, 1);
647     if (opt_index < 0) {
648         /* diagnostics already printed */
649         return 1;
650     }
651
652     if (format == FORMAT_HEADERS_ONLY)
653         reply_format_func = notmuch_reply_format_headers_only;
654     else
655         reply_format_func = notmuch_reply_format_default;
656
657     if (decrypt) {
658         GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
659         params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
660         if (params.cryptoctx) {
661             g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
662             params.decrypt = TRUE;
663         } else {
664             fprintf (stderr, "Failed to construct gpg context.\n");
665         }
666         g_object_unref (session);
667     }
668
669     config = notmuch_config_open (ctx, NULL, NULL);
670     if (config == NULL)
671         return 1;
672
673     query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
674     if (query_string == NULL) {
675         fprintf (stderr, "Out of memory\n");
676         return 1;
677     }
678
679     if (*query_string == '\0') {
680         fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
681         return 1;
682     }
683
684     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
685                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
686     if (notmuch == NULL)
687         return 1;
688
689     query = notmuch_query_create (notmuch, query_string);
690     if (query == NULL) {
691         fprintf (stderr, "Out of memory\n");
692         return 1;
693     }
694
695     if (reply_format_func (ctx, config, query, &params) != 0)
696         return 1;
697
698     notmuch_query_destroy (query);
699     notmuch_database_close (notmuch);
700
701     if (params.cryptoctx)
702         g_object_unref(params.cryptoctx);
703
704     return ret;
705 }