]> git.notmuchmail.org Git - notmuch/blob - notmuch-reply.c
cli: clean up user address matching code in guess_from_received_header()
[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[] = {"Envelope-to", "X-Original-To"};
388
389     /* sadly, there is no standard way to find out to which email
390      * address a mail was delivered - what is in the headers depends
391      * on the MTAs used along the way. So we are trying a number of
392      * heuristics which hopefully will answer this question.
393
394      * We only got here if none of the users email addresses are in
395      * the To: or Cc: header. From here we try the following in order:
396      * 1) check for an Envelope-to: header
397      * 2) check for an X-Original-To: header
398      * 3) check for a (for <email@add.res>) clause in Received: headers
399      * 4) check for the domain part of known email addresses in the
400      *    'by' part of Received headers
401      * If none of these work, we give up and return NULL
402      */
403     for (i = 0; i < ARRAY_SIZE (to_headers); i++) {
404         const char *tohdr = notmuch_message_get_header (message, to_headers[i]);
405
406         /* Note: tohdr potentially contains a list of email addresses. */
407         addr = user_address_in_string (tohdr, config);
408         if (addr)
409             return addr;
410     }
411
412     /* We get the concatenated Received: headers and search from the
413      * front (last Received: header added) and try to extract from
414      * them indications to which email address this message was
415      * delivered.
416      * The Received: header is special in our get_header function
417      * and is always concatenated.
418      */
419     received = notmuch_message_get_header (message, "received");
420     if (received == NULL)
421         return NULL;
422
423     /* First we look for a " for <email@add.res>" in the received
424      * header
425      */
426     ptr = strstr (received, " for ");
427
428     /* Note: ptr potentially contains a list of email addresses. */
429     addr = user_address_in_string (ptr, config);
430     if (addr)
431         return addr;
432
433     /* Finally, we parse all the " by MTA ..." headers to guess the
434      * email address that this was originally delivered to.
435      * We extract just the MTA here by removing leading whitespace and
436      * assuming that the MTA name ends at the next whitespace.
437      * We test for *(by+4) to be non-'\0' to make sure there's
438      * something there at all - and then assume that the first
439      * whitespace delimited token that follows is the receiving
440      * system in this step of the receive chain
441      */
442     by = received;
443     while((by = strstr (by, " by ")) != NULL) {
444         by += 4;
445         if (*by == '\0')
446             break;
447         mta = xstrdup (by);
448         token = strtok(mta," \t");
449         if (token == NULL) {
450             free (mta);
451             break;
452         }
453         /* Now extract the last two components of the MTA host name
454          * as domain and tld.
455          */
456         domain = tld = NULL;
457         while ((ptr = strsep (&token, delim)) != NULL) {
458             if (*ptr == '\0')
459                 continue;
460             domain = tld;
461             tld = ptr;
462         }
463
464         if (domain) {
465             /* Recombine domain and tld and look for it among the configured
466              * email addresses.
467              * This time we have a known domain name and nothing else - so
468              * the test is the other way around: we check if this is a
469              * substring of one of the email addresses.
470              */
471             *(tld-1) = '.';
472
473             addr = string_in_user_address (domain, config);
474             if (addr) {
475                 free (mta);
476                 return addr;
477             }
478         }
479         free (mta);
480     }
481
482     return NULL;
483 }
484
485 static GMimeMessage *
486 create_reply_message(void *ctx,
487                      notmuch_config_t *config,
488                      notmuch_message_t *message,
489                      notmuch_bool_t reply_all)
490 {
491     const char *subject, *from_addr = NULL;
492     const char *in_reply_to, *orig_references, *references;
493
494     /* The 1 means we want headers in a "pretty" order. */
495     GMimeMessage *reply = g_mime_message_new (1);
496     if (reply == NULL) {
497         fprintf (stderr, "Out of memory\n");
498         return NULL;
499     }
500
501     subject = notmuch_message_get_header (message, "subject");
502     if (subject) {
503         if (strncasecmp (subject, "Re:", 3))
504             subject = talloc_asprintf (ctx, "Re: %s", subject);
505         g_mime_message_set_subject (reply, subject);
506     }
507
508     from_addr = add_recipients_from_message (reply, config,
509                                              message, reply_all);
510
511     if (from_addr == NULL)
512         from_addr = guess_from_received_header (config, message);
513
514     if (from_addr == NULL)
515         from_addr = notmuch_config_get_user_primary_email (config);
516
517     from_addr = talloc_asprintf (ctx, "%s <%s>",
518                                  notmuch_config_get_user_name (config),
519                                  from_addr);
520     g_mime_object_set_header (GMIME_OBJECT (reply),
521                               "From", from_addr);
522
523     in_reply_to = talloc_asprintf (ctx, "<%s>",
524                                    notmuch_message_get_message_id (message));
525
526     g_mime_object_set_header (GMIME_OBJECT (reply),
527                               "In-Reply-To", in_reply_to);
528
529     orig_references = notmuch_message_get_header (message, "references");
530     references = talloc_asprintf (ctx, "%s%s%s",
531                                   orig_references ? orig_references : "",
532                                   orig_references ? " " : "",
533                                   in_reply_to);
534     g_mime_object_set_header (GMIME_OBJECT (reply),
535                               "References", references);
536
537     return reply;
538 }
539
540 static int
541 notmuch_reply_format_default(void *ctx,
542                              notmuch_config_t *config,
543                              notmuch_query_t *query,
544                              notmuch_show_params_t *params,
545                              notmuch_bool_t reply_all)
546 {
547     GMimeMessage *reply;
548     notmuch_messages_t *messages;
549     notmuch_message_t *message;
550     mime_node_t *root;
551
552     for (messages = notmuch_query_search_messages (query);
553          notmuch_messages_valid (messages);
554          notmuch_messages_move_to_next (messages))
555     {
556         message = notmuch_messages_get (messages);
557
558         reply = create_reply_message (ctx, config, message, reply_all);
559
560         /* If reply creation failed, we're out of memory, so don't
561          * bother trying any more messages.
562          */
563         if (!reply) {
564             notmuch_message_destroy (message);
565             return 1;
566         }
567
568         show_reply_headers (reply);
569
570         g_object_unref (G_OBJECT (reply));
571         reply = NULL;
572
573         if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
574                             &root) == NOTMUCH_STATUS_SUCCESS) {
575             format_part_reply (root);
576             talloc_free (root);
577         }
578
579         notmuch_message_destroy (message);
580     }
581     return 0;
582 }
583
584 static int
585 notmuch_reply_format_json(void *ctx,
586                           notmuch_config_t *config,
587                           notmuch_query_t *query,
588                           notmuch_show_params_t *params,
589                           notmuch_bool_t reply_all)
590 {
591     GMimeMessage *reply;
592     notmuch_messages_t *messages;
593     notmuch_message_t *message;
594     mime_node_t *node;
595
596     if (notmuch_query_count_messages (query) != 1) {
597         fprintf (stderr, "Error: search term did not match precisely one message.\n");
598         return 1;
599     }
600
601     messages = notmuch_query_search_messages (query);
602     message = notmuch_messages_get (messages);
603     if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
604                         &node) != NOTMUCH_STATUS_SUCCESS)
605         return 1;
606
607     reply = create_reply_message (ctx, config, message, reply_all);
608     if (!reply)
609         return 1;
610
611     /* The headers of the reply message we've created */
612     printf ("{\"reply-headers\": ");
613     format_headers_json (ctx, reply, TRUE);
614     g_object_unref (G_OBJECT (reply));
615     reply = NULL;
616
617     /* Start the original */
618     printf (", \"original\": ");
619
620     format_part_json (ctx, node, TRUE);
621
622     /* End */
623     printf ("}\n");
624     notmuch_message_destroy (message);
625
626     return 0;
627 }
628
629 /* This format is currently tuned for a git send-email --notmuch hook */
630 static int
631 notmuch_reply_format_headers_only(void *ctx,
632                                   notmuch_config_t *config,
633                                   notmuch_query_t *query,
634                                   unused (notmuch_show_params_t *params),
635                                   notmuch_bool_t reply_all)
636 {
637     GMimeMessage *reply;
638     notmuch_messages_t *messages;
639     notmuch_message_t *message;
640     const char *in_reply_to, *orig_references, *references;
641     char *reply_headers;
642
643     for (messages = notmuch_query_search_messages (query);
644          notmuch_messages_valid (messages);
645          notmuch_messages_move_to_next (messages))
646     {
647         message = notmuch_messages_get (messages);
648
649         /* The 0 means we do not want headers in a "pretty" order. */
650         reply = g_mime_message_new (0);
651         if (reply == NULL) {
652             fprintf (stderr, "Out of memory\n");
653             return 1;
654         }
655
656         in_reply_to = talloc_asprintf (ctx, "<%s>",
657                              notmuch_message_get_message_id (message));
658
659         g_mime_object_set_header (GMIME_OBJECT (reply),
660                                   "In-Reply-To", in_reply_to);
661
662
663         orig_references = notmuch_message_get_header (message, "references");
664
665         /* We print In-Reply-To followed by References because git format-patch treats them
666          * specially.  Git does not interpret the other headers specially
667          */
668         references = talloc_asprintf (ctx, "%s%s%s",
669                                       orig_references ? orig_references : "",
670                                       orig_references ? " " : "",
671                                       in_reply_to);
672         g_mime_object_set_header (GMIME_OBJECT (reply),
673                                   "References", references);
674
675         (void)add_recipients_from_message (reply, config, message, reply_all);
676
677         reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
678         printf ("%s", reply_headers);
679         free (reply_headers);
680
681         g_object_unref (G_OBJECT (reply));
682         reply = NULL;
683
684         notmuch_message_destroy (message);
685     }
686     return 0;
687 }
688
689 enum {
690     FORMAT_DEFAULT,
691     FORMAT_JSON,
692     FORMAT_HEADERS_ONLY,
693 };
694
695 int
696 notmuch_reply_command (void *ctx, int argc, char *argv[])
697 {
698     notmuch_config_t *config;
699     notmuch_database_t *notmuch;
700     notmuch_query_t *query;
701     char *query_string;
702     int opt_index, ret = 0;
703     int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params, notmuch_bool_t reply_all);
704     notmuch_show_params_t params = { .part = -1 };
705     int format = FORMAT_DEFAULT;
706     int reply_all = TRUE;
707
708     notmuch_opt_desc_t options[] = {
709         { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
710           (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
711                                   { "json", FORMAT_JSON },
712                                   { "headers-only", FORMAT_HEADERS_ONLY },
713                                   { 0, 0 } } },
714         { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
715           (notmuch_keyword_t []){ { "all", TRUE },
716                                   { "sender", FALSE },
717                                   { 0, 0 } } },
718         { NOTMUCH_OPT_BOOLEAN, &params.decrypt, "decrypt", 'd', 0 },
719         { 0, 0, 0, 0, 0 }
720     };
721
722     opt_index = parse_arguments (argc, argv, options, 1);
723     if (opt_index < 0) {
724         /* diagnostics already printed */
725         return 1;
726     }
727
728     if (format == FORMAT_HEADERS_ONLY)
729         reply_format_func = notmuch_reply_format_headers_only;
730     else if (format == FORMAT_JSON)
731         reply_format_func = notmuch_reply_format_json;
732     else
733         reply_format_func = notmuch_reply_format_default;
734
735     if (params.decrypt) {
736 #ifdef GMIME_ATLEAST_26
737         /* TODO: GMimePasswordRequestFunc */
738         params.cryptoctx = g_mime_gpg_context_new (NULL, "gpg");
739 #else
740         GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
741         params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
742 #endif
743         if (params.cryptoctx) {
744             g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
745         } else {
746             params.decrypt = FALSE;
747             fprintf (stderr, "Failed to construct gpg context.\n");
748         }
749 #ifndef GMIME_ATLEAST_26
750         g_object_unref (session);
751 #endif
752     }
753
754     config = notmuch_config_open (ctx, NULL, NULL);
755     if (config == NULL)
756         return 1;
757
758     query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
759     if (query_string == NULL) {
760         fprintf (stderr, "Out of memory\n");
761         return 1;
762     }
763
764     if (*query_string == '\0') {
765         fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
766         return 1;
767     }
768
769     if (notmuch_database_open (notmuch_config_get_database_path (config),
770                                NOTMUCH_DATABASE_MODE_READ_ONLY, &notmuch))
771         return 1;
772
773     query = notmuch_query_create (notmuch, query_string);
774     if (query == NULL) {
775         fprintf (stderr, "Out of memory\n");
776         return 1;
777     }
778
779     if (reply_format_func (ctx, config, query, &params, reply_all) != 0)
780         return 1;
781
782     notmuch_query_destroy (query);
783     notmuch_database_destroy (notmuch);
784
785     if (params.cryptoctx)
786         g_object_unref(params.cryptoctx);
787
788     return ret;
789 }