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