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