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