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