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