]> git.notmuchmail.org Git - notmuch/blob - notmuch-reply.c
update link to Chip Rosenthal article about reply-to munging
[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 "string-util.h"
25 #include "sprinter.h"
26
27 static void
28 show_reply_headers (GMimeMessage *message)
29 {
30     GMimeStream *stream_stdout = NULL;
31
32     stream_stdout = g_mime_stream_file_new (stdout);
33     if (stream_stdout) {
34         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
35         /* Output RFC 2822 formatted (and RFC 2047 encoded) headers. */
36         g_mime_object_write_to_stream (GMIME_OBJECT(message), stream_stdout);
37         g_object_unref(stream_stdout);
38     }
39 }
40
41 static void
42 format_part_reply (mime_node_t *node)
43 {
44     int i;
45
46     if (node->envelope_file) {
47         printf ("On %s, %s wrote:\n",
48                 notmuch_message_get_header (node->envelope_file, "date"),
49                 notmuch_message_get_header (node->envelope_file, "from"));
50     } else if (GMIME_IS_MESSAGE (node->part)) {
51         GMimeMessage *message = GMIME_MESSAGE (node->part);
52         InternetAddressList *recipients;
53         const char *recipients_string;
54
55         printf ("> From: %s\n", g_mime_message_get_sender (message));
56         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
57         recipients_string = internet_address_list_to_string (recipients, 0);
58         if (recipients_string)
59             printf ("> To: %s\n",
60                     recipients_string);
61         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
62         recipients_string = internet_address_list_to_string (recipients, 0);
63         if (recipients_string)
64             printf ("> Cc: %s\n",
65                     recipients_string);
66         printf ("> Subject: %s\n", g_mime_message_get_subject (message));
67         printf ("> Date: %s\n", g_mime_message_get_date_as_string (message));
68         printf (">\n");
69     } else if (GMIME_IS_PART (node->part)) {
70         GMimeContentType *content_type = g_mime_object_get_content_type (node->part);
71         GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (node->part);
72
73         if (g_mime_content_type_is_type (content_type, "application", "pgp-encrypted") ||
74             g_mime_content_type_is_type (content_type, "application", "pgp-signature")) {
75             /* Ignore PGP/MIME cruft parts */
76         } else if (g_mime_content_type_is_type (content_type, "text", "*") &&
77                    !g_mime_content_type_is_type (content_type, "text", "html")) {
78             GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
79             g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
80             show_text_part_content (node->part, stream_stdout, NOTMUCH_SHOW_TEXT_PART_REPLY);
81             g_object_unref(stream_stdout);
82         } else if (disposition &&
83                    strcasecmp (g_mime_content_disposition_get_disposition (disposition),
84                                GMIME_DISPOSITION_ATTACHMENT) == 0) {
85             const char *filename = g_mime_part_get_filename (GMIME_PART (node->part));
86             printf ("Attachment: %s (%s)\n", filename,
87                     g_mime_content_type_to_string (content_type));
88         } else {
89             printf ("Non-text part: %s\n",
90                     g_mime_content_type_to_string (content_type));
91         }
92     }
93
94     for (i = 0; i < node->nchildren; i++)
95         format_part_reply (mime_node_child (node, i));
96 }
97
98 typedef enum {
99     USER_ADDRESS_IN_STRING,
100     STRING_IN_USER_ADDRESS,
101     STRING_IS_USER_ADDRESS,
102 } address_match_t;
103
104 /* Match given string against given address according to mode. */
105 static notmuch_bool_t
106 match_address (const char *str, const char *address, address_match_t mode)
107 {
108     switch (mode) {
109     case USER_ADDRESS_IN_STRING:
110         return strcasestr (str, address) != NULL;
111     case STRING_IN_USER_ADDRESS:
112         return strcasestr (address, str) != NULL;
113     case STRING_IS_USER_ADDRESS:
114         return strcasecmp (address, str) == 0;
115     }
116
117     return FALSE;
118 }
119
120 /* Match given string against user's configured "primary" and "other"
121  * addresses according to mode. */
122 static const char *
123 address_match (const char *str, notmuch_config_t *config, address_match_t mode)
124 {
125     const char *primary;
126     const char **other;
127     size_t i, other_len;
128
129     if (!str || *str == '\0')
130         return NULL;
131
132     primary = notmuch_config_get_user_primary_email (config);
133     if (match_address (str, primary, mode))
134         return primary;
135
136     other = notmuch_config_get_user_other_email (config, &other_len);
137     for (i = 0; i < other_len; i++) {
138         if (match_address (str, other[i], mode))
139             return other[i];
140     }
141
142     return NULL;
143 }
144
145 /* Does the given string contain an address configured as one of the
146  * user's "primary" or "other" addresses. If so, return the matching
147  * address, NULL otherwise. */
148 static const char *
149 user_address_in_string (const char *str, notmuch_config_t *config)
150 {
151     return address_match (str, config, USER_ADDRESS_IN_STRING);
152 }
153
154 /* Do any of the addresses configured as one of the user's "primary"
155  * or "other" addresses contain the given string. If so, return the
156  * matching address, NULL otherwise. */
157 static const char *
158 string_in_user_address (const char *str, notmuch_config_t *config)
159 {
160     return address_match (str, config, STRING_IN_USER_ADDRESS);
161 }
162
163 /* Is the given address configured as one of the user's "primary" or
164  * "other" addresses. */
165 static notmuch_bool_t
166 address_is_users (const char *address, notmuch_config_t *config)
167 {
168     return address_match (address, config, STRING_IS_USER_ADDRESS) != NULL;
169 }
170
171 /* Scan addresses in 'list'.
172  *
173  * If 'message' is non-NULL, then for each address in 'list' that is
174  * not configured as one of the user's addresses in 'config', add that
175  * address to 'message' as an address of 'type'.
176  *
177  * If 'user_from' is non-NULL and *user_from is NULL, *user_from will
178  * be set to the first address encountered in 'list' that is the
179  * user's address.
180  *
181  * Return the number of addresses added to 'message'. (If 'message' is
182  * NULL, the function returns 0 by definition.)
183  */
184 static unsigned int
185 scan_address_list (InternetAddressList *list,
186                    notmuch_config_t *config,
187                    GMimeMessage *message,
188                    GMimeRecipientType type,
189                    const char **user_from)
190 {
191     InternetAddress *address;
192     int i;
193     unsigned int n = 0;
194
195     for (i = 0; i < internet_address_list_length (list); i++) {
196         address = internet_address_list_get_address (list, i);
197         if (INTERNET_ADDRESS_IS_GROUP (address)) {
198             InternetAddressGroup *group;
199             InternetAddressList *group_list;
200
201             group = INTERNET_ADDRESS_GROUP (address);
202             group_list = internet_address_group_get_members (group);
203             if (group_list == NULL)
204                 continue;
205
206             n += scan_address_list (group_list, config, message, type, user_from);
207         } else {
208             InternetAddressMailbox *mailbox;
209             const char *name;
210             const char *addr;
211
212             mailbox = INTERNET_ADDRESS_MAILBOX (address);
213
214             name = internet_address_get_name (address);
215             addr = internet_address_mailbox_get_addr (mailbox);
216
217             if (address_is_users (addr, config)) {
218                 if (user_from && *user_from == NULL)
219                     *user_from = addr;
220             } else if (message) {
221                 g_mime_message_add_recipient (message, type, name, addr);
222                 n++;
223             }
224         }
225     }
226
227     return n;
228 }
229
230 /* Scan addresses in 'recipients'.
231  *
232  * See the documentation of scan_address_list() above. This function
233  * does exactly the same, but converts 'recipients' to an
234  * InternetAddressList first.
235  */
236 static unsigned int
237 scan_address_string (const char *recipients,
238                      notmuch_config_t *config,
239                      GMimeMessage *message,
240                      GMimeRecipientType type,
241                      const char **user_from)
242 {
243     InternetAddressList *list;
244
245     if (recipients == NULL)
246         return 0;
247
248     list = internet_address_list_parse_string (recipients);
249     if (list == NULL)
250         return 0;
251
252     return scan_address_list (list, config, message, type, user_from);
253 }
254
255 /* Does the address in the Reply-To header of 'message' already appear
256  * in either the 'To' or 'Cc' header of the message?
257  */
258 static int
259 reply_to_header_is_redundant (notmuch_message_t *message)
260 {
261     const char *reply_to, *to, *cc, *addr;
262     InternetAddressList *list;
263     InternetAddress *address;
264     InternetAddressMailbox *mailbox;
265
266     reply_to = notmuch_message_get_header (message, "reply-to");
267     if (reply_to == NULL || *reply_to == '\0')
268         return 0;
269
270     list = internet_address_list_parse_string (reply_to);
271
272     if (internet_address_list_length (list) != 1)
273         return 0;
274
275     address = internet_address_list_get_address (list, 0);
276     if (INTERNET_ADDRESS_IS_GROUP (address))
277         return 0;
278
279     mailbox = INTERNET_ADDRESS_MAILBOX (address);
280     addr = internet_address_mailbox_get_addr (mailbox);
281
282     to = notmuch_message_get_header (message, "to");
283     cc = notmuch_message_get_header (message, "cc");
284
285     if ((to && strstr (to, addr) != 0) ||
286         (cc && strstr (cc, addr) != 0))
287     {
288         return 1;
289     }
290
291     return 0;
292 }
293
294 /* Augment the recipients of 'reply' from the "Reply-to:", "From:",
295  * "To:", "Cc:", and "Bcc:" headers of 'message'.
296  *
297  * If 'reply_all' is true, use sender and all recipients, otherwise
298  * scan the headers for the first that contains something other than
299  * the user's addresses and add the recipients from this header
300  * (typically this would be reply-to-sender, but also handles reply to
301  * user's own message in a sensible way).
302  *
303  * If any of the user's addresses were found in these headers, the
304  * first of these returned, otherwise NULL is returned.
305  */
306 static const char *
307 add_recipients_from_message (GMimeMessage *reply,
308                              notmuch_config_t *config,
309                              notmuch_message_t *message,
310                              notmuch_bool_t reply_all)
311 {
312     struct {
313         const char *header;
314         const char *fallback;
315         GMimeRecipientType recipient_type;
316     } reply_to_map[] = {
317         { "reply-to", "from", GMIME_RECIPIENT_TYPE_TO  },
318         { "to",         NULL, GMIME_RECIPIENT_TYPE_TO  },
319         { "cc",         NULL, GMIME_RECIPIENT_TYPE_CC  },
320         { "bcc",        NULL, GMIME_RECIPIENT_TYPE_BCC }
321     };
322     const char *from_addr = NULL;
323     unsigned int i;
324     unsigned int n = 0;
325
326     /* Some mailing lists munge the Reply-To header despite it being A Bad
327      * Thing, see http://marc.merlins.org/netrants/reply-to-harmful.html
328      *
329      * The munging is easy to detect, because it results in a
330      * redundant reply-to header, (with an address that already exists
331      * in either To or Cc). So in this case, we ignore the Reply-To
332      * field and use the From header. This ensures the original sender
333      * will get the reply even if not subscribed to the list. Note
334      * that the address in the Reply-To header will always appear in
335      * the reply if reply_all is true.
336      */
337     if (reply_to_header_is_redundant (message)) {
338         reply_to_map[0].header = "from";
339         reply_to_map[0].fallback = NULL;
340     }
341
342     for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
343         const char *recipients;
344
345         recipients = notmuch_message_get_header (message,
346                                                  reply_to_map[i].header);
347         if ((recipients == NULL || recipients[0] == '\0') && reply_to_map[i].fallback)
348             recipients = notmuch_message_get_header (message,
349                                                      reply_to_map[i].fallback);
350
351         n += scan_address_string (recipients, config, reply,
352                                   reply_to_map[i].recipient_type, &from_addr);
353
354         if (!reply_all && n) {
355             /* Stop adding new recipients in reply-to-sender mode if
356              * we have added some recipient(s) above.
357              *
358              * This also handles the case of user replying to his own
359              * message, where reply-to/from is not a recipient. In
360              * this case there may be more than one recipient even if
361              * not replying to all.
362              */
363             reply = NULL;
364
365             /* From address and some recipients are enough, bail out. */
366             if (from_addr)
367                 break;
368         }
369     }
370
371     return from_addr;
372 }
373
374 /*
375  * Look for the user's address in " for <email@add.res>" in the
376  * received headers.
377  *
378  * Return the address that was found, if any, and NULL otherwise.
379  */
380 static const char *
381 guess_from_in_received_for (notmuch_config_t *config, const char *received)
382 {
383     const char *ptr;
384
385     ptr = strstr (received, " for ");
386     if (! ptr)
387         return NULL;
388
389     return user_address_in_string (ptr, config);
390 }
391
392 /*
393  * Parse all the " by MTA ..." parts in received headers to guess the
394  * email address that this was originally delivered to.
395  *
396  * Extract just the MTA here by removing leading whitespace and
397  * assuming that the MTA name ends at the next whitespace. Test for
398  * *(by+4) to be non-'\0' to make sure there's something there at all
399  * - and then assume that the first whitespace delimited token that
400  * follows is the receiving system in this step of the receive chain.
401  *
402  * Return the address that was found, if any, and NULL otherwise.
403  */
404 static const char *
405 guess_from_in_received_by (notmuch_config_t *config, const char *received)
406 {
407     const char *addr;
408     const char *by = received;
409     char *domain, *tld, *mta, *ptr, *token;
410
411     while ((by = strstr (by, " by ")) != NULL) {
412         by += 4;
413         if (*by == '\0')
414             break;
415         mta = xstrdup (by);
416         token = strtok(mta," \t");
417         if (token == NULL) {
418             free (mta);
419             break;
420         }
421         /*
422          * Now extract the last two components of the MTA host name as
423          * domain and tld.
424          */
425         domain = tld = NULL;
426         while ((ptr = strsep (&token, ". \t")) != NULL) {
427             if (*ptr == '\0')
428                 continue;
429             domain = tld;
430             tld = ptr;
431         }
432
433         if (domain) {
434             /*
435              * Recombine domain and tld and look for it among the
436              * configured email addresses. This time we have a known
437              * domain name and nothing else - so the test is the other
438              * way around: we check if this is a substring of one of
439              * the email addresses.
440              */
441             *(tld - 1) = '.';
442
443             addr = string_in_user_address (domain, config);
444             if (addr) {
445                 free (mta);
446                 return addr;
447             }
448         }
449         free (mta);
450     }
451
452     return NULL;
453 }
454
455 /*
456  * Get the concatenated Received: headers and search from the front
457  * (last Received: header added) and try to extract from them
458  * indications to which email address this message was delivered.
459  *
460  * The Received: header is special in our get_header function and is
461  * always concatenated.
462  *
463  * Return the address that was found, if any, and NULL otherwise.
464  */
465 static const char *
466 guess_from_in_received_headers (notmuch_config_t *config,
467                                 notmuch_message_t *message)
468 {
469     const char *received, *addr;
470     char *sanitized;
471
472     received = notmuch_message_get_header (message, "received");
473     if (! received)
474         return NULL;
475
476     sanitized = sanitize_string (NULL, received);
477     if (! sanitized)
478         return NULL;
479
480     addr = guess_from_in_received_for (config, sanitized);
481     if (! addr)
482         addr = guess_from_in_received_by (config, sanitized);
483
484     talloc_free (sanitized);
485
486     return addr;
487 }
488
489 /*
490  * Try to find user's email address in one of the extra To-like
491  * headers: Envelope-To, X-Original-To, and Delivered-To (searched in
492  * that order).
493  *
494  * Return the address that was found, if any, and NULL otherwise.
495  */
496 static const char *
497 get_from_in_to_headers (notmuch_config_t *config, notmuch_message_t *message)
498 {
499     size_t i;
500     const char *tohdr, *addr;
501     const char *to_headers[] = {
502         "Envelope-to",
503         "X-Original-To",
504         "Delivered-To",
505     };
506
507     for (i = 0; i < ARRAY_SIZE (to_headers); i++) {
508         tohdr = notmuch_message_get_header (message, to_headers[i]);
509
510         /* Note: tohdr potentially contains a list of email addresses. */
511         addr = user_address_in_string (tohdr, config);
512         if (addr)
513             return addr;
514     }
515
516     return NULL;
517 }
518
519 static GMimeMessage *
520 create_reply_message(void *ctx,
521                      notmuch_config_t *config,
522                      notmuch_message_t *message,
523                      notmuch_bool_t reply_all)
524 {
525     const char *subject, *from_addr = NULL;
526     const char *in_reply_to, *orig_references, *references;
527
528     /* The 1 means we want headers in a "pretty" order. */
529     GMimeMessage *reply = g_mime_message_new (1);
530     if (reply == NULL) {
531         fprintf (stderr, "Out of memory\n");
532         return NULL;
533     }
534
535     subject = notmuch_message_get_header (message, "subject");
536     if (subject) {
537         if (strncasecmp (subject, "Re:", 3))
538             subject = talloc_asprintf (ctx, "Re: %s", subject);
539         g_mime_message_set_subject (reply, subject);
540     }
541
542     from_addr = add_recipients_from_message (reply, config,
543                                              message, reply_all);
544
545     /*
546      * Sadly, there is no standard way to find out to which email
547      * address a mail was delivered - what is in the headers depends
548      * on the MTAs used along the way.
549      *
550      * If none of the user's email addresses are in the To: or Cc:
551      * headers, we try a number of heuristics which hopefully will
552      * answer this question.
553      *
554      * First, check for Envelope-To:, X-Original-To:, and
555      * Delivered-To: headers.
556      */
557     if (from_addr == NULL)
558         from_addr = get_from_in_to_headers (config, message);
559
560     /*
561      * Check for a (for <email@add.res>) clause in Received: headers,
562      * and the domain part of known email addresses in the 'by' part
563      * of Received: headers
564      */
565     if (from_addr == NULL)
566         from_addr = guess_from_in_received_headers (config, message);
567
568     /* Default to user's primary address. */
569     if (from_addr == NULL)
570         from_addr = notmuch_config_get_user_primary_email (config);
571
572     from_addr = talloc_asprintf (ctx, "%s <%s>",
573                                  notmuch_config_get_user_name (config),
574                                  from_addr);
575     g_mime_object_set_header (GMIME_OBJECT (reply),
576                               "From", from_addr);
577
578     in_reply_to = talloc_asprintf (ctx, "<%s>",
579                                    notmuch_message_get_message_id (message));
580
581     g_mime_object_set_header (GMIME_OBJECT (reply),
582                               "In-Reply-To", in_reply_to);
583
584     orig_references = notmuch_message_get_header (message, "references");
585     if (!orig_references)
586         /* Treat errors like missing References headers. */
587         orig_references = "";
588     references = talloc_asprintf (ctx, "%s%s%s",
589                                   *orig_references ? orig_references : "",
590                                   *orig_references ? " " : "",
591                                   in_reply_to);
592     g_mime_object_set_header (GMIME_OBJECT (reply),
593                               "References", references);
594
595     return reply;
596 }
597
598 static int
599 notmuch_reply_format_default(void *ctx,
600                              notmuch_config_t *config,
601                              notmuch_query_t *query,
602                              notmuch_show_params_t *params,
603                              notmuch_bool_t reply_all,
604                              unused (sprinter_t *sp))
605 {
606     GMimeMessage *reply;
607     notmuch_messages_t *messages;
608     notmuch_message_t *message;
609     mime_node_t *root;
610     notmuch_status_t status;
611
612     status = notmuch_query_search_messages_st (query, &messages);
613     if (print_status_query ("notmuch reply", query, status))
614         return 1;
615
616     for (;
617          notmuch_messages_valid (messages);
618          notmuch_messages_move_to_next (messages))
619     {
620         message = notmuch_messages_get (messages);
621
622         reply = create_reply_message (ctx, config, message, reply_all);
623
624         /* If reply creation failed, we're out of memory, so don't
625          * bother trying any more messages.
626          */
627         if (!reply) {
628             notmuch_message_destroy (message);
629             return 1;
630         }
631
632         show_reply_headers (reply);
633
634         g_object_unref (G_OBJECT (reply));
635         reply = NULL;
636
637         if (mime_node_open (ctx, message, &(params->crypto), &root) == NOTMUCH_STATUS_SUCCESS) {
638             format_part_reply (root);
639             talloc_free (root);
640         }
641
642         notmuch_message_destroy (message);
643     }
644     return 0;
645 }
646
647 static int
648 notmuch_reply_format_sprinter(void *ctx,
649                               notmuch_config_t *config,
650                               notmuch_query_t *query,
651                               notmuch_show_params_t *params,
652                               notmuch_bool_t reply_all,
653                               sprinter_t *sp)
654 {
655     GMimeMessage *reply;
656     notmuch_messages_t *messages;
657     notmuch_message_t *message;
658     mime_node_t *node;
659     unsigned count;
660     notmuch_status_t status;
661
662     status = notmuch_query_count_messages_st (query, &count);
663     if (print_status_query ("notmuch reply", query, status))
664         return 1;
665
666     if (count != 1) {
667         fprintf (stderr, "Error: search term did not match precisely one message (matched %d messages).\n", count);
668         return 1;
669     }
670
671     status = notmuch_query_search_messages_st (query, &messages);
672     if (print_status_query ("notmuch reply", query, status))
673         return 1;
674
675     message = notmuch_messages_get (messages);
676     if (mime_node_open (ctx, message, &(params->crypto), &node) != NOTMUCH_STATUS_SUCCESS)
677         return 1;
678
679     reply = create_reply_message (ctx, config, message, reply_all);
680     if (!reply)
681         return 1;
682
683     sp->begin_map (sp);
684
685     /* The headers of the reply message we've created */
686     sp->map_key (sp, "reply-headers");
687     format_headers_sprinter (sp, reply, TRUE);
688     g_object_unref (G_OBJECT (reply));
689     reply = NULL;
690
691     /* Start the original */
692     sp->map_key (sp, "original");
693     format_part_sprinter (ctx, sp, node, TRUE, TRUE, FALSE);
694
695     /* End */
696     sp->end (sp);
697     notmuch_message_destroy (message);
698
699     return 0;
700 }
701
702 /* This format is currently tuned for a git send-email --notmuch hook */
703 static int
704 notmuch_reply_format_headers_only(void *ctx,
705                                   notmuch_config_t *config,
706                                   notmuch_query_t *query,
707                                   unused (notmuch_show_params_t *params),
708                                   notmuch_bool_t reply_all,
709                                   unused (sprinter_t *sp))
710 {
711     GMimeMessage *reply;
712     notmuch_messages_t *messages;
713     notmuch_message_t *message;
714     const char *in_reply_to, *orig_references, *references;
715     char *reply_headers;
716     notmuch_status_t status;
717
718     status = notmuch_query_search_messages_st (query, &messages);
719     if (print_status_query ("notmuch reply", query, status))
720         return 1;
721
722     for (;
723          notmuch_messages_valid (messages);
724          notmuch_messages_move_to_next (messages))
725     {
726         message = notmuch_messages_get (messages);
727
728         /* The 0 means we do not want headers in a "pretty" order. */
729         reply = g_mime_message_new (0);
730         if (reply == NULL) {
731             fprintf (stderr, "Out of memory\n");
732             return 1;
733         }
734
735         in_reply_to = talloc_asprintf (ctx, "<%s>",
736                              notmuch_message_get_message_id (message));
737
738         g_mime_object_set_header (GMIME_OBJECT (reply),
739                                   "In-Reply-To", in_reply_to);
740
741
742         orig_references = notmuch_message_get_header (message, "references");
743
744         /* We print In-Reply-To followed by References because git format-patch treats them
745          * specially.  Git does not interpret the other headers specially
746          */
747         references = talloc_asprintf (ctx, "%s%s%s",
748                                       orig_references ? orig_references : "",
749                                       orig_references ? " " : "",
750                                       in_reply_to);
751         g_mime_object_set_header (GMIME_OBJECT (reply),
752                                   "References", references);
753
754         (void)add_recipients_from_message (reply, config, message, reply_all);
755
756         reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
757         printf ("%s", reply_headers);
758         free (reply_headers);
759
760         g_object_unref (G_OBJECT (reply));
761         reply = NULL;
762
763         notmuch_message_destroy (message);
764     }
765     return 0;
766 }
767
768 enum {
769     FORMAT_DEFAULT,
770     FORMAT_JSON,
771     FORMAT_SEXP,
772     FORMAT_HEADERS_ONLY,
773 };
774
775 int
776 notmuch_reply_command (notmuch_config_t *config, int argc, char *argv[])
777 {
778     notmuch_database_t *notmuch;
779     notmuch_query_t *query;
780     char *query_string;
781     int opt_index;
782     int (*reply_format_func) (void *ctx,
783                               notmuch_config_t *config,
784                               notmuch_query_t *query,
785                               notmuch_show_params_t *params,
786                               notmuch_bool_t reply_all,
787                               struct sprinter *sp);
788     notmuch_show_params_t params = {
789         .part = -1,
790         .crypto = {
791             .verify = FALSE,
792             .decrypt = FALSE,
793             .gpgpath = NULL
794         }
795     };
796     int format = FORMAT_DEFAULT;
797     int reply_all = TRUE;
798     struct sprinter *sp = NULL;
799
800     notmuch_opt_desc_t options[] = {
801         { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
802           (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
803                                   { "json", FORMAT_JSON },
804                                   { "sexp", FORMAT_SEXP },
805                                   { "headers-only", FORMAT_HEADERS_ONLY },
806                                   { 0, 0 } } },
807         { NOTMUCH_OPT_INT, &notmuch_format_version, "format-version", 0, 0 },
808         { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
809           (notmuch_keyword_t []){ { "all", TRUE },
810                                   { "sender", FALSE },
811                                   { 0, 0 } } },
812         { NOTMUCH_OPT_BOOLEAN, &params.crypto.decrypt, "decrypt", 'd', 0 },
813         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
814         { 0, 0, 0, 0, 0 }
815     };
816
817     opt_index = parse_arguments (argc, argv, options, 1);
818     if (opt_index < 0)
819         return EXIT_FAILURE;
820
821     notmuch_process_shared_options (argv[0]);
822
823     if (format == FORMAT_HEADERS_ONLY) {
824         reply_format_func = notmuch_reply_format_headers_only;
825     } else if (format == FORMAT_JSON) {
826         reply_format_func = notmuch_reply_format_sprinter;
827         sp = sprinter_json_create (config, stdout);
828     } else if (format == FORMAT_SEXP) {
829         reply_format_func = notmuch_reply_format_sprinter;
830         sp = sprinter_sexp_create (config, stdout);
831     } else {
832         reply_format_func = notmuch_reply_format_default;
833     }
834
835     notmuch_exit_if_unsupported_format ();
836
837     query_string = query_string_from_args (config, argc-opt_index, argv+opt_index);
838     if (query_string == NULL) {
839         fprintf (stderr, "Out of memory\n");
840         return EXIT_FAILURE;
841     }
842
843     if (*query_string == '\0') {
844         fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
845         return EXIT_FAILURE;
846     }
847
848     params.crypto.gpgpath = notmuch_config_get_crypto_gpg_path (config);
849
850     if (notmuch_database_open (notmuch_config_get_database_path (config),
851                                NOTMUCH_DATABASE_MODE_READ_ONLY, &notmuch))
852         return EXIT_FAILURE;
853
854     notmuch_exit_if_unmatched_db_uuid (notmuch);
855
856     query = notmuch_query_create (notmuch, query_string);
857     if (query == NULL) {
858         fprintf (stderr, "Out of memory\n");
859         return EXIT_FAILURE;
860     }
861
862     if (reply_format_func (config, config, query, &params, reply_all, sp) != 0)
863         return EXIT_FAILURE;
864
865     notmuch_crypto_cleanup (&params.crypto);
866     notmuch_query_destroy (query);
867     notmuch_database_destroy (notmuch);
868
869     return EXIT_SUCCESS;
870 }