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