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