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