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