]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
lib/database: delete stemmer on destroy
[notmuch] / notmuch-show.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "gmime-filter-reply.h"
23 #include "sprinter.h"
24 #include "zlib-extra.h"
25
26 static const char *
27 _get_tags_as_string (const void *ctx, notmuch_message_t *message)
28 {
29     notmuch_tags_t *tags;
30     int first = 1;
31     const char *tag;
32     char *result;
33
34     result = talloc_strdup (ctx, "");
35     if (result == NULL)
36         return NULL;
37
38     for (tags = notmuch_message_get_tags (message);
39          notmuch_tags_valid (tags);
40          notmuch_tags_move_to_next (tags)) {
41         tag = notmuch_tags_get (tags);
42
43         result = talloc_asprintf_append (result, "%s%s",
44                                          first ? "" : " ", tag);
45         first = 0;
46     }
47
48     return result;
49 }
50
51 /* Get a nice, single-line summary of message. */
52 static const char *
53 _get_one_line_summary (const void *ctx, notmuch_message_t *message)
54 {
55     const char *from;
56     time_t date;
57     const char *relative_date;
58     const char *tags;
59
60     from = notmuch_message_get_header (message, "from");
61
62     date = notmuch_message_get_date (message);
63     relative_date = notmuch_time_relative_date (ctx, date);
64
65     tags = _get_tags_as_string (ctx, message);
66
67     return talloc_asprintf (ctx, "%s (%s) (%s)",
68                             from, relative_date, tags);
69 }
70
71 static const char *
72 _get_disposition (GMimeObject *meta)
73 {
74     GMimeContentDisposition *disposition;
75
76     disposition = g_mime_object_get_content_disposition (meta);
77     if (! disposition)
78         return NULL;
79
80     return g_mime_content_disposition_get_disposition (disposition);
81 }
82
83 static bool
84 _get_message_flag (notmuch_message_t *message, notmuch_message_flag_t flag)
85 {
86     notmuch_bool_t is_set;
87     notmuch_status_t status;
88
89     status = notmuch_message_get_flag_st (message, flag, &is_set);
90
91     if (print_status_message ("notmuch show", message, status))
92         INTERNAL_ERROR ("unexpected error getting message flag\n");
93
94     return is_set;
95 }
96
97 /* Emit a sequence of key/value pairs for the metadata of message.
98  * The caller should begin a map before calling this. */
99 static void
100 format_message_sprinter (sprinter_t *sp, notmuch_message_t *message)
101 {
102     /* Any changes to the JSON or S-Expression format should be
103      * reflected in the file devel/schemata. */
104
105     void *local = talloc_new (NULL);
106     notmuch_tags_t *tags;
107     time_t date;
108     const char *relative_date;
109
110     sp->map_key (sp, "id");
111     sp->string (sp, notmuch_message_get_message_id (message));
112
113     sp->map_key (sp, "match");
114     sp->boolean (sp, _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH));
115
116     sp->map_key (sp, "excluded");
117     sp->boolean (sp, _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED));
118
119     sp->map_key (sp, "filename");
120     if (notmuch_format_version >= 3) {
121         notmuch_filenames_t *filenames;
122
123         sp->begin_list (sp);
124         for (filenames = notmuch_message_get_filenames (message);
125              notmuch_filenames_valid (filenames);
126              notmuch_filenames_move_to_next (filenames)) {
127             sp->string (sp, notmuch_filenames_get (filenames));
128         }
129         notmuch_filenames_destroy (filenames);
130         sp->end (sp);
131     } else {
132         sp->string (sp, notmuch_message_get_filename (message));
133     }
134
135     sp->map_key (sp, "timestamp");
136     date = notmuch_message_get_date (message);
137     sp->integer (sp, date);
138
139     sp->map_key (sp, "date_relative");
140     relative_date = notmuch_time_relative_date (local, date);
141     sp->string (sp, relative_date);
142
143     sp->map_key (sp, "tags");
144     sp->begin_list (sp);
145     for (tags = notmuch_message_get_tags (message);
146          notmuch_tags_valid (tags);
147          notmuch_tags_move_to_next (tags))
148         sp->string (sp, notmuch_tags_get (tags));
149     sp->end (sp);
150
151     talloc_free (local);
152 }
153
154 /* Extract just the email address from the contents of a From:
155  * header. */
156 static const char *
157 _extract_email_address (const void *ctx, const char *from)
158 {
159     InternetAddressList *addresses;
160     InternetAddress *address;
161     InternetAddressMailbox *mailbox;
162     const char *email = "MAILER-DAEMON";
163
164     addresses = internet_address_list_parse (NULL, from);
165
166     /* Bail if there is no address here. */
167     if (addresses == NULL || internet_address_list_length (addresses) < 1)
168         goto DONE;
169
170     /* Otherwise, just use the first address. */
171     address = internet_address_list_get_address (addresses, 0);
172
173     /* The From header should never contain an address group rather
174      * than a mailbox. So bail if it does. */
175     if (! INTERNET_ADDRESS_IS_MAILBOX (address))
176         goto DONE;
177
178     mailbox = INTERNET_ADDRESS_MAILBOX (address);
179     email = internet_address_mailbox_get_addr (mailbox);
180     email = talloc_strdup (ctx, email);
181
182   DONE:
183     if (addresses)
184         g_object_unref (addresses);
185
186     return email;
187 }
188
189 /* Return 1 if 'line' is an mbox From_ line---that is, a line
190  * beginning with zero or more '>' characters followed by the
191  * characters 'F', 'r', 'o', 'm', and space.
192  *
193  * Any characters at all may appear after that in the line.
194  */
195 static int
196 _is_from_line (const char *line)
197 {
198     const char *s = line;
199
200     if (line == NULL)
201         return 0;
202
203     while (*s == '>')
204         s++;
205
206     if (STRNCMP_LITERAL (s, "From ") == 0)
207         return 1;
208     else
209         return 0;
210 }
211
212 /* Output extra headers if configured with the `show.extra_headers'
213  * configuration option
214  */
215 static void
216 format_extra_headers_sprinter (sprinter_t *sp, GMimeMessage *message)
217 {
218     GMimeHeaderList *header_list = g_mime_object_get_header_list (GMIME_OBJECT (message));
219
220     for (notmuch_config_values_t *extra_headers = notmuch_config_get_values (
221              sp->notmuch, NOTMUCH_CONFIG_EXTRA_HEADERS);
222          notmuch_config_values_valid (extra_headers);
223          notmuch_config_values_move_to_next (extra_headers)) {
224         GMimeHeader *header;
225         const char *header_name = notmuch_config_values_get (extra_headers);
226
227         header = g_mime_header_list_get_header (header_list, header_name);
228         if (header == NULL)
229             continue;
230
231         sp->map_key (sp, g_mime_header_get_name (header));
232         sp->string (sp, g_mime_header_get_value (header));
233     }
234 }
235
236 void
237 format_headers_sprinter (sprinter_t *sp, GMimeMessage *message,
238                          bool reply, const _notmuch_message_crypto_t *msg_crypto)
239 {
240     /* Any changes to the JSON or S-Expression format should be
241      * reflected in the file devel/schemata. */
242
243     char *recipients_string;
244     const char *reply_to_string;
245     void *local = talloc_new (sp);
246
247     sp->begin_map (sp);
248
249     sp->map_key (sp, "Subject");
250     if (msg_crypto && msg_crypto->payload_subject) {
251         sp->string (sp, msg_crypto->payload_subject);
252     } else
253         sp->string (sp, g_mime_message_get_subject (message));
254
255     sp->map_key (sp, "From");
256     sp->string (sp, g_mime_message_get_from_string (message));
257
258     recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_TO);
259     if (recipients_string) {
260         sp->map_key (sp, "To");
261         sp->string (sp, recipients_string);
262         g_free (recipients_string);
263     }
264
265     recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_CC);
266     if (recipients_string) {
267         sp->map_key (sp, "Cc");
268         sp->string (sp, recipients_string);
269         g_free (recipients_string);
270     }
271
272     recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_BCC);
273     if (recipients_string) {
274         sp->map_key (sp, "Bcc");
275         sp->string (sp, recipients_string);
276         g_free (recipients_string);
277     }
278
279     reply_to_string = g_mime_message_get_reply_to_string (local, message);
280     if (reply_to_string) {
281         sp->map_key (sp, "Reply-To");
282         sp->string (sp, reply_to_string);
283     }
284
285     if (reply) {
286         sp->map_key (sp, "In-reply-to");
287         sp->string (sp, g_mime_object_get_header (GMIME_OBJECT (message), "In-reply-to"));
288
289         sp->map_key (sp, "References");
290         sp->string (sp, g_mime_object_get_header (GMIME_OBJECT (message), "References"));
291     } else {
292         sp->map_key (sp, "Date");
293         sp->string (sp, g_mime_message_get_date_string (sp, message));
294     }
295
296     /* Output extra headers the user has configured, if any */
297     if (! reply)
298         format_extra_headers_sprinter (sp, message);
299     sp->end (sp);
300     talloc_free (local);
301 }
302
303 /* Write a MIME text part out to the given stream.
304  *
305  * If (flags & NOTMUCH_SHOW_TEXT_PART_REPLY), this prepends "> " to
306  * each output line.
307  *
308  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
309  * UTF-8) will be performed, so it is inappropriate to call this
310  * function with a non-text part. Doing so will trigger an internal
311  * error.
312  */
313 void
314 show_text_part_content (GMimeObject *part, GMimeStream *stream_out,
315                         notmuch_show_text_part_flags flags)
316 {
317     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
318     GMimeStream *stream_filter = NULL;
319     GMimeFilter *crlf_filter = NULL;
320     GMimeFilter *windows_filter = NULL;
321     GMimeDataWrapper *wrapper;
322     const char *charset;
323
324     if (! g_mime_content_type_is_type (content_type, "text", "*"))
325         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
326                         g_mime_content_type_get_mime_type (content_type));
327
328     if (stream_out == NULL)
329         return;
330
331     charset = g_mime_object_get_content_type_parameter (part, "charset");
332     charset = charset ? g_mime_charset_canon_name (charset) : NULL;
333     wrapper = g_mime_part_get_content (GMIME_PART (part));
334     if (wrapper && charset && ! g_ascii_strncasecmp (charset, "iso-8859-", 9)) {
335         GMimeStream *null_stream = NULL;
336         GMimeStream *null_stream_filter = NULL;
337
338         /* Check for mislabeled Windows encoding */
339         null_stream = g_mime_stream_null_new ();
340         null_stream_filter = g_mime_stream_filter_new (null_stream);
341         windows_filter = g_mime_filter_windows_new (charset);
342         g_mime_stream_filter_add (GMIME_STREAM_FILTER (null_stream_filter),
343                                   windows_filter);
344         g_mime_data_wrapper_write_to_stream (wrapper, null_stream_filter);
345         charset = g_mime_filter_windows_real_charset (
346             (GMimeFilterWindows *) windows_filter);
347
348         if (null_stream_filter)
349             g_object_unref (null_stream_filter);
350         if (null_stream)
351             g_object_unref (null_stream);
352         /* Keep a reference to windows_filter in order to prevent the
353          * charset string from deallocation. */
354     }
355
356     stream_filter = g_mime_stream_filter_new (stream_out);
357     crlf_filter = g_mime_filter_dos2unix_new (false);
358     g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
359                               crlf_filter);
360     g_object_unref (crlf_filter);
361
362     if (charset) {
363         GMimeFilter *charset_filter;
364         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
365         /* This result can be NULL for things like "unknown-8bit".
366          * Don't set a NULL filter as that makes GMime print
367          * annoying assertion-failure messages on stderr. */
368         if (charset_filter) {
369             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
370                                       charset_filter);
371             g_object_unref (charset_filter);
372         }
373
374     }
375
376     if (flags & NOTMUCH_SHOW_TEXT_PART_REPLY) {
377         GMimeFilter *reply_filter;
378         reply_filter = g_mime_filter_reply_new (true);
379         if (reply_filter) {
380             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
381                                       reply_filter);
382             g_object_unref (reply_filter);
383         }
384     }
385
386     if (wrapper && stream_filter)
387         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
388     if (stream_filter)
389         g_object_unref (stream_filter);
390     if (windows_filter)
391         g_object_unref (windows_filter);
392 }
393
394 static const char *
395 signature_status_to_string (GMimeSignatureStatus status)
396 {
397     if (g_mime_signature_status_bad (status))
398         return "bad";
399
400     if (g_mime_signature_status_error (status))
401         return "error";
402
403     if (g_mime_signature_status_good (status))
404         return "good";
405
406     return "unknown";
407 }
408
409 /* Print signature flags */
410 struct key_map_struct {
411     GMimeSignatureStatus bit;
412     const char *string;
413 };
414
415 static void
416 do_format_signature_errors (sprinter_t *sp, struct key_map_struct *key_map,
417                             unsigned int array_map_len, GMimeSignatureStatus errors)
418 {
419     sp->map_key (sp, "errors");
420     sp->begin_map (sp);
421
422     for (unsigned int i = 0; i < array_map_len; i++) {
423         if (errors & key_map[i].bit) {
424             sp->map_key (sp, key_map[i].string);
425             sp->boolean (sp, true);
426         }
427     }
428
429     sp->end (sp);
430 }
431
432 static void
433 format_signature_errors (sprinter_t *sp, GMimeSignature *signature)
434 {
435     GMimeSignatureStatus errors = g_mime_signature_get_status (signature);
436
437     if (! (errors & GMIME_SIGNATURE_STATUS_ERROR_MASK))
438         return;
439
440     struct key_map_struct key_map[] = {
441         { GMIME_SIGNATURE_STATUS_KEY_REVOKED, "key-revoked" },
442         { GMIME_SIGNATURE_STATUS_KEY_EXPIRED, "key-expired" },
443         { GMIME_SIGNATURE_STATUS_SIG_EXPIRED, "sig-expired" },
444         { GMIME_SIGNATURE_STATUS_KEY_MISSING, "key-missing" },
445         { GMIME_SIGNATURE_STATUS_CRL_MISSING, "crl-missing" },
446         { GMIME_SIGNATURE_STATUS_CRL_TOO_OLD, "crl-too-old" },
447         { GMIME_SIGNATURE_STATUS_BAD_POLICY, "bad-policy" },
448         { GMIME_SIGNATURE_STATUS_SYS_ERROR, "sys-error" },
449         { GMIME_SIGNATURE_STATUS_TOFU_CONFLICT, "tofu-conflict" },
450     };
451
452     do_format_signature_errors (sp, key_map, ARRAY_SIZE (key_map), errors);
453 }
454
455 /* Signature status sprinter */
456 static void
457 format_part_sigstatus_sprinter (sprinter_t *sp, GMimeSignatureList *siglist)
458 {
459     /* Any changes to the JSON or S-Expression format should be
460      * reflected in the file devel/schemata. */
461
462     sp->begin_list (sp);
463
464     if (! siglist) {
465         sp->end (sp);
466         return;
467     }
468
469     int i;
470
471     for (i = 0; i < g_mime_signature_list_length (siglist); i++) {
472         GMimeSignature *signature = g_mime_signature_list_get_signature (siglist, i);
473
474         sp->begin_map (sp);
475
476         /* status */
477         GMimeSignatureStatus status = g_mime_signature_get_status (signature);
478         sp->map_key (sp, "status");
479         sp->string (sp, signature_status_to_string (status));
480
481         GMimeCertificate *certificate = g_mime_signature_get_certificate (signature);
482         if (g_mime_signature_status_good (status)) {
483             if (certificate) {
484                 sp->map_key (sp, "fingerprint");
485                 sp->string (sp, g_mime_certificate_get_fingerprint (certificate));
486             }
487             /* these dates are seconds since the epoch; should we
488              * provide a more human-readable format string? */
489             time_t created = g_mime_signature_get_created (signature);
490             if (created != -1) {
491                 sp->map_key (sp, "created");
492                 sp->integer (sp, created);
493             }
494             time_t expires = g_mime_signature_get_expires (signature);
495             if (expires > 0) {
496                 sp->map_key (sp, "expires");
497                 sp->integer (sp, expires);
498             }
499             if (certificate) {
500                 const char *uid = g_mime_certificate_get_valid_userid (certificate);
501                 if (uid) {
502                     sp->map_key (sp, "userid");
503                     sp->string (sp, uid);
504                 }
505                 const char *email = g_mime_certificate_get_valid_email (certificate);
506                 if (email) {
507                     sp->map_key (sp, "email");
508                     sp->string (sp, email);
509                 }
510             }
511         } else if (certificate) {
512             const char *key_id = g_mime_certificate_get_fpr16 (certificate);
513             if (key_id) {
514                 sp->map_key (sp, "keyid");
515                 sp->string (sp, key_id);
516             }
517         }
518
519         if (notmuch_format_version <= 3) {
520             GMimeSignatureStatus errors = g_mime_signature_get_status (signature);
521             if (g_mime_signature_status_error (errors)) {
522                 sp->map_key (sp, "errors");
523                 sp->integer (sp, errors);
524             }
525         } else {
526             format_signature_errors (sp, signature);
527         }
528
529         sp->end (sp);
530     }
531
532     sp->end (sp);
533 }
534
535 static notmuch_status_t
536 format_part_text (const void *ctx, sprinter_t *sp, mime_node_t *node,
537                   int indent, const notmuch_show_params_t *params)
538 {
539     /* The disposition and content-type metadata are associated with
540      * the envelope for message parts */
541     GMimeObject *meta = node->envelope_part ? (
542         GMIME_OBJECT (node->envelope_part) ) : node->part;
543     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
544     const bool leaf = GMIME_IS_PART (node->part);
545     GMimeStream *stream = params->out_stream;
546     const char *part_type;
547     int i;
548
549     if (node->envelope_file) {
550         notmuch_message_t *message = node->envelope_file;
551
552         part_type = "message";
553         g_mime_stream_printf (stream, "\f%s{ id:%s depth:%d match:%d excluded:%d filename:%s\n",
554                               part_type,
555                               notmuch_message_get_message_id (message),
556                               indent,
557                               _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? 1 : 0,
558                               _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED) ? 1 : 0,
559                               notmuch_message_get_filename (message));
560     } else {
561         char *content_string;
562         const char *disposition = _get_disposition (meta);
563         const char *cid = g_mime_object_get_content_id (meta);
564         const char *filename = leaf ? (
565             g_mime_part_get_filename (GMIME_PART (node->part)) ) : NULL;
566
567         if (disposition &&
568             strcasecmp (disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
569             part_type = "attachment";
570         else
571             part_type = "part";
572
573         g_mime_stream_printf (stream, "\f%s{ ID: %d", part_type, node->part_num);
574         if (filename)
575             g_mime_stream_printf (stream, ", Filename: %s", filename);
576         if (cid)
577             g_mime_stream_printf (stream, ", Content-id: %s", cid);
578
579         content_string = g_mime_content_type_get_mime_type (content_type);
580         g_mime_stream_printf (stream, ", Content-type: %s\n", content_string);
581         g_free (content_string);
582     }
583
584     if (GMIME_IS_MESSAGE (node->part)) {
585         GMimeMessage *message = GMIME_MESSAGE (node->part);
586         char *recipients_string;
587         char *date_string;
588
589         g_mime_stream_printf (stream, "\fheader{\n");
590         if (node->envelope_file)
591             g_mime_stream_printf (stream, "%s\n", _get_one_line_summary (ctx, node->envelope_file));
592         g_mime_stream_printf (stream, "Subject: %s\n", g_mime_message_get_subject (message));
593         g_mime_stream_printf (stream, "From: %s\n", g_mime_message_get_from_string (message));
594         recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_TO);
595         if (recipients_string)
596             g_mime_stream_printf (stream, "To: %s\n", recipients_string);
597         g_free (recipients_string);
598         recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_CC);
599         if (recipients_string)
600             g_mime_stream_printf (stream, "Cc: %s\n", recipients_string);
601         g_free (recipients_string);
602         date_string = g_mime_message_get_date_string (node, message);
603         g_mime_stream_printf (stream, "Date: %s\n", date_string);
604         g_mime_stream_printf (stream, "\fheader}\n");
605
606         if (! params->output_body) {
607             g_mime_stream_printf (stream, "\f%s}\n", part_type);
608             return NOTMUCH_STATUS_SUCCESS;
609         }
610         g_mime_stream_printf (stream, "\fbody{\n");
611     }
612
613     if (leaf) {
614         if (g_mime_content_type_is_type (content_type, "text", "*") &&
615             (params->include_html ||
616              ! g_mime_content_type_is_type (content_type, "text", "html"))) {
617             show_text_part_content (node->part, stream, 0);
618         } else {
619             char *content_string = g_mime_content_type_get_mime_type (content_type);
620             g_mime_stream_printf (stream, "Non-text part: %s\n", content_string);
621             g_free (content_string);
622         }
623     }
624
625     for (i = 0; i < node->nchildren; i++)
626         format_part_text (ctx, sp, mime_node_child (node, i), indent, params);
627
628     if (GMIME_IS_MESSAGE (node->part))
629         g_mime_stream_printf (stream, "\fbody}\n");
630
631     g_mime_stream_printf (stream, "\f%s}\n", part_type);
632
633     return NOTMUCH_STATUS_SUCCESS;
634 }
635
636 static void
637 format_omitted_part_meta_sprinter (sprinter_t *sp, GMimeObject *meta, GMimePart *part)
638 {
639     const char *content_charset = g_mime_object_get_content_type_parameter (meta, "charset");
640     const char *cte = g_mime_object_get_header (meta, "content-transfer-encoding");
641     GMimeDataWrapper *wrapper = g_mime_part_get_content (part);
642     GMimeStream *stream = g_mime_data_wrapper_get_stream (wrapper);
643     ssize_t content_length = g_mime_stream_length (stream);
644
645     if (content_charset != NULL) {
646         sp->map_key (sp, "content-charset");
647         sp->string (sp, content_charset);
648     }
649     if (cte != NULL) {
650         sp->map_key (sp, "content-transfer-encoding");
651         sp->string (sp, cte);
652     }
653     if (content_length >= 0) {
654         sp->map_key (sp, "content-length");
655         sp->integer (sp, content_length);
656     }
657 }
658
659 void
660 format_part_sprinter (const void *ctx, sprinter_t *sp, mime_node_t *node,
661                       bool output_body,
662                       bool include_html)
663 {
664     /* Any changes to the JSON or S-Expression format should be
665      * reflected in the file devel/schemata. */
666
667     if (node->envelope_file) {
668         const _notmuch_message_crypto_t *msg_crypto = NULL;
669         sp->begin_map (sp);
670         format_message_sprinter (sp, node->envelope_file);
671
672         if (output_body) {
673             sp->map_key (sp, "body");
674             sp->begin_list (sp);
675             format_part_sprinter (ctx, sp, mime_node_child (node, 0), true, include_html);
676             sp->end (sp);
677         }
678
679         msg_crypto = mime_node_get_message_crypto_status (node);
680         if (notmuch_format_version >= 4) {
681             sp->map_key (sp, "crypto");
682             sp->begin_map (sp);
683             if (msg_crypto->sig_list ||
684                 msg_crypto->decryption_status != NOTMUCH_MESSAGE_DECRYPTED_NONE) {
685                 if (msg_crypto->sig_list) {
686                     sp->map_key (sp, "signed");
687                     sp->begin_map (sp);
688                     sp->map_key (sp, "status");
689                     format_part_sigstatus_sprinter (sp, msg_crypto->sig_list);
690                     if (msg_crypto->signature_encrypted) {
691                         sp->map_key (sp, "encrypted");
692                         sp->boolean (sp, msg_crypto->signature_encrypted);
693                     }
694                     if (msg_crypto->payload_subject) {
695                         sp->map_key (sp, "headers");
696                         sp->begin_list (sp);
697                         sp->string (sp, "Subject");
698                         sp->end (sp);
699                     }
700                     sp->end (sp);
701                 }
702                 if (msg_crypto->decryption_status != NOTMUCH_MESSAGE_DECRYPTED_NONE) {
703                     sp->map_key (sp, "decrypted");
704                     sp->begin_map (sp);
705                     sp->map_key (sp, "status");
706                     sp->string (sp, msg_crypto->decryption_status == NOTMUCH_MESSAGE_DECRYPTED_FULL ?
707                                 "full" : "partial");
708
709                     if (msg_crypto->payload_subject) {
710                         const char *subject = g_mime_message_get_subject GMIME_MESSAGE (node->part);
711                         if (subject == NULL || strcmp (subject, msg_crypto->payload_subject)) {
712                             /* protected subject differs from the external header */
713                             sp->map_key (sp, "header-mask");
714                             sp->begin_map (sp);
715                             sp->map_key (sp, "Subject");
716                             if (subject == NULL)
717                                 sp->null (sp);
718                             else
719                                 sp->string (sp, subject);
720                             sp->end (sp);
721                         }
722                     }
723                     sp->end (sp);
724                 }
725             }
726             sp->end (sp);
727         }
728
729         sp->map_key (sp, "headers");
730         format_headers_sprinter (sp, GMIME_MESSAGE (node->part), false, msg_crypto);
731
732         sp->end (sp);
733         return;
734     }
735
736     /* The disposition and content-type metadata are associated with
737      * the envelope for message parts */
738     GMimeObject *meta = node->envelope_part ? (
739         GMIME_OBJECT (node->envelope_part) ) : node->part;
740     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
741     char *content_string;
742     const char *disposition = _get_disposition (meta);
743     const char *cid = g_mime_object_get_content_id (meta);
744     const char *filename = GMIME_IS_PART (node->part) ? (
745         g_mime_part_get_filename (GMIME_PART (node->part) ) ) : NULL;
746     int nclose = 0;
747     int i;
748
749     sp->begin_map (sp);
750
751     sp->map_key (sp, "id");
752     sp->integer (sp, node->part_num);
753
754     if (node->decrypt_attempted) {
755         sp->map_key (sp, "encstatus");
756         sp->begin_list (sp);
757         sp->begin_map (sp);
758         sp->map_key (sp, "status");
759         sp->string (sp, node->decrypt_success ? "good" : "bad");
760         sp->end (sp);
761         sp->end (sp);
762     }
763
764     if (node->verify_attempted) {
765         sp->map_key (sp, "sigstatus");
766         format_part_sigstatus_sprinter (sp, node->sig_list);
767     }
768
769     sp->map_key (sp, "content-type");
770     content_string = g_mime_content_type_get_mime_type (content_type);
771     sp->string (sp, content_string);
772     g_free (content_string);
773
774     if (disposition) {
775         sp->map_key (sp, "content-disposition");
776         sp->string (sp, disposition);
777     }
778
779     if (cid) {
780         sp->map_key (sp, "content-id");
781         sp->string (sp, cid);
782     }
783
784     if (filename) {
785         sp->map_key (sp, "filename");
786         sp->string (sp, filename);
787     }
788
789     if (GMIME_IS_PART (node->part)) {
790         /* For non-HTML text parts, we include the content in the
791          * JSON. Since JSON must be Unicode, we handle charset
792          * decoding here and do not report a charset to the caller.
793          * For text/html parts, we do not include the content unless
794          * the --include-html option has been passed. If a html part
795          * is not included, it can be requested directly. This makes
796          * charset decoding the responsibility on the caller so we
797          * report the charset for text/html parts.
798          */
799         if (g_mime_content_type_is_type (content_type, "text", "*") &&
800             (include_html ||
801              ! g_mime_content_type_is_type (content_type, "text", "html"))) {
802             GMimeStream *stream_memory = g_mime_stream_mem_new ();
803             GByteArray *part_content;
804             show_text_part_content (node->part, stream_memory, 0);
805             part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
806             sp->map_key (sp, "content");
807             sp->string_len (sp, (char *) part_content->data, part_content->len);
808             g_object_unref (stream_memory);
809         } else {
810             /* if we have a child part despite being a standard
811              * (non-multipart) MIME part, that means there is
812              * something to unwrap, which we will present in
813              * content: */
814             if (node->nchildren) {
815                 sp->map_key (sp, "content");
816                 sp->begin_list (sp);
817                 nclose = 1;
818             } else
819                 format_omitted_part_meta_sprinter (sp, meta, GMIME_PART (node->part));
820         }
821     } else if (GMIME_IS_MULTIPART (node->part)) {
822         sp->map_key (sp, "content");
823         sp->begin_list (sp);
824         nclose = 1;
825     } else if (GMIME_IS_MESSAGE (node->part)) {
826         sp->map_key (sp, "content");
827         sp->begin_list (sp);
828         sp->begin_map (sp);
829
830         sp->map_key (sp, "headers");
831         format_headers_sprinter (sp, GMIME_MESSAGE (node->part), false, NULL);
832
833         sp->map_key (sp, "body");
834         sp->begin_list (sp);
835         nclose = 3;
836     }
837
838     for (i = 0; i < node->nchildren; i++)
839         format_part_sprinter (ctx, sp, mime_node_child (node, i), true, include_html);
840
841     /* Close content structures */
842     for (i = 0; i < nclose; i++)
843         sp->end (sp);
844     /* Close part map */
845     sp->end (sp);
846 }
847
848 static notmuch_status_t
849 format_part_sprinter_entry (const void *ctx, sprinter_t *sp,
850                             mime_node_t *node, unused (int indent),
851                             const notmuch_show_params_t *params)
852 {
853     format_part_sprinter (ctx, sp, node, params->output_body, params->include_html);
854
855     return NOTMUCH_STATUS_SUCCESS;
856 }
857
858 /* Print a message in "mboxrd" format as documented, for example,
859  * here:
860  *
861  * http://qmail.org/qmail-manual-html/man5/mbox.html
862  */
863 static notmuch_status_t
864 format_part_mbox (const void *ctx, unused (sprinter_t *sp), mime_node_t *node,
865                   unused (int indent),
866                   unused (const notmuch_show_params_t *params))
867 {
868     notmuch_message_t *message = node->envelope_file;
869
870     const char *filename;
871     gzFile file;
872     const char *from;
873
874     time_t date;
875     struct tm date_gmtime;
876     char date_asctime[26];
877
878     char *line = NULL;
879     ssize_t line_size;
880     ssize_t line_len;
881
882     if (! message)
883         INTERNAL_ERROR ("format_part_mbox requires a root part");
884
885     filename = notmuch_message_get_filename (message);
886     file = gzopen (filename, "r");
887     if (file == NULL) {
888         fprintf (stderr, "Failed to open %s: %s\n",
889                  filename, strerror (errno));
890         return NOTMUCH_STATUS_FILE_ERROR;
891     }
892
893     from = notmuch_message_get_header (message, "from");
894     from = _extract_email_address (ctx, from);
895
896     date = notmuch_message_get_date (message);
897     gmtime_r (&date, &date_gmtime);
898     asctime_r (&date_gmtime, date_asctime);
899
900     printf ("From %s %s", from, date_asctime);
901
902     while ((line_len = gz_getline (message, &line, &line_size, file)) != UTIL_EOF ) {
903         if (_is_from_line (line))
904             putchar ('>');
905         printf ("%s", line);
906     }
907
908     printf ("\n");
909
910     gzclose (file);
911
912     return NOTMUCH_STATUS_SUCCESS;
913 }
914
915 static notmuch_status_t
916 format_part_raw (unused (const void *ctx), unused (sprinter_t *sp),
917                  mime_node_t *node, unused (int indent),
918                  const notmuch_show_params_t *params)
919 {
920     if (node->envelope_file) {
921         /* Special case the entire message to avoid MIME parsing. */
922         const char *filename;
923         GMimeStream *stream = NULL;
924         ssize_t ssize;
925         char buf[4096];
926         notmuch_status_t ret = NOTMUCH_STATUS_FILE_ERROR;
927
928         filename = notmuch_message_get_filename (node->envelope_file);
929         if (filename == NULL) {
930             fprintf (stderr, "Error: Cannot get message filename.\n");
931             goto DONE;
932         }
933
934         stream = g_mime_stream_gzfile_open (filename);
935         if (stream == NULL) {
936             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
937             goto DONE;
938         }
939
940         while (! g_mime_stream_eos (stream)) {
941             ssize = g_mime_stream_read (stream, buf, sizeof (buf));
942             if (ssize < 0) {
943                 fprintf (stderr, "Error: Read failed from %s\n", filename);
944                 goto DONE;
945             }
946
947             if (ssize > 0 && fwrite (buf, ssize, 1, stdout) != 1) {
948                 fprintf (stderr, "Error: Write %zd chars to stdout failed\n", ssize);
949                 goto DONE;
950             }
951         }
952
953         ret = NOTMUCH_STATUS_SUCCESS;
954
955         /* XXX This DONE is just for the special case of a node in a single file */
956       DONE:
957         if (stream)
958             g_object_unref (stream);
959
960         return ret;
961     }
962
963     GMimeStream *stream_filter = g_mime_stream_filter_new (params->out_stream);
964
965     if (GMIME_IS_PART (node->part)) {
966         /* For leaf parts, we emit only the transfer-decoded
967          * body. */
968         GMimeDataWrapper *wrapper;
969         wrapper = g_mime_part_get_content (GMIME_PART (node->part));
970
971         if (wrapper && stream_filter)
972             g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
973     } else {
974         /* Write out the whole part.  For message parts (the root
975          * part and embedded message parts), this will be the
976          * message including its headers (but not the
977          * encapsulating part's headers).  For multipart parts,
978          * this will include the headers. */
979         if (stream_filter)
980             g_mime_object_write_to_stream (node->part, NULL, stream_filter);
981     }
982
983     if (stream_filter)
984         g_object_unref (stream_filter);
985
986     return NOTMUCH_STATUS_SUCCESS;
987 }
988
989 static notmuch_status_t
990 show_message (void *ctx,
991               const notmuch_show_format_t *format,
992               sprinter_t *sp,
993               notmuch_message_t *message,
994               int indent,
995               notmuch_show_params_t *params)
996 {
997     void *local = talloc_new (ctx);
998     mime_node_t *root, *part;
999     notmuch_status_t status;
1000     unsigned int session_keys = 0;
1001     notmuch_status_t session_key_count_error = NOTMUCH_STATUS_SUCCESS;
1002
1003     if (params->crypto.decrypt == NOTMUCH_DECRYPT_TRUE)
1004         session_key_count_error = notmuch_message_count_properties (message, "session-key",
1005                                                                     &session_keys);
1006
1007     status = mime_node_open (local, message, &(params->crypto), &root);
1008     if (status)
1009         goto DONE;
1010     part = mime_node_seek_dfs (root, (params->part < 0 ? 0 : params->part));
1011     if (part)
1012         status = format->part (local, sp, part, indent, params);
1013     if (params->crypto.decrypt == NOTMUCH_DECRYPT_TRUE && session_key_count_error ==
1014         NOTMUCH_STATUS_SUCCESS) {
1015         unsigned int new_session_keys = 0;
1016         if (notmuch_message_count_properties (message, "session-key", &new_session_keys) ==
1017             NOTMUCH_STATUS_SUCCESS &&
1018             new_session_keys > session_keys) {
1019             /* try a quiet re-indexing */
1020             notmuch_indexopts_t *indexopts = notmuch_database_get_default_indexopts (
1021                 notmuch_message_get_database (message));
1022             if (indexopts) {
1023                 notmuch_indexopts_set_decrypt_policy (indexopts, NOTMUCH_DECRYPT_AUTO);
1024                 print_status_message ("Error re-indexing message with --decrypt=stash",
1025                                       message, notmuch_message_reindex (message, indexopts));
1026             }
1027         }
1028     }
1029   DONE:
1030     talloc_free (local);
1031     return status;
1032 }
1033
1034 static notmuch_status_t
1035 show_messages (void *ctx,
1036                const notmuch_show_format_t *format,
1037                sprinter_t *sp,
1038                notmuch_messages_t *messages,
1039                int indent,
1040                notmuch_show_params_t *params)
1041 {
1042     notmuch_message_t *message;
1043     bool match;
1044     bool excluded;
1045     int next_indent;
1046     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1047
1048     sp->begin_list (sp);
1049
1050     for (;
1051          notmuch_messages_valid (messages);
1052          notmuch_messages_move_to_next (messages)) {
1053         sp->begin_list (sp);
1054
1055         message = notmuch_messages_get (messages);
1056
1057         match = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
1058         excluded = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED);
1059
1060         next_indent = indent;
1061
1062         if ((match && (! excluded || ! params->omit_excluded)) || params->entire_thread) {
1063             status = show_message (ctx, format, sp, message, indent, params);
1064             if (status && ! res)
1065                 res = status;
1066             next_indent = indent + 1;
1067         } else {
1068             sp->null (sp);
1069         }
1070
1071         status = show_messages (ctx,
1072                                 format, sp,
1073                                 notmuch_message_get_replies (message),
1074                                 next_indent,
1075                                 params);
1076         if (status && ! res)
1077             res = status;
1078
1079         notmuch_message_destroy (message);
1080
1081         sp->end (sp);
1082     }
1083
1084     sp->end (sp);
1085
1086     return res;
1087 }
1088
1089 /* Formatted output of single message */
1090 static int
1091 do_show_single (void *ctx,
1092                 notmuch_query_t *query,
1093                 const notmuch_show_format_t *format,
1094                 sprinter_t *sp,
1095                 notmuch_show_params_t *params)
1096 {
1097     notmuch_messages_t *messages;
1098     notmuch_message_t *message;
1099     notmuch_status_t status;
1100     unsigned int count;
1101
1102     status = notmuch_query_count_messages (query, &count);
1103     if (print_status_query ("notmuch show", query, status))
1104         return 1;
1105
1106     if (count != 1) {
1107         fprintf (stderr,
1108                  "Error: search term did not match precisely one message (matched %u messages).\n",
1109                  count);
1110         return 1;
1111     }
1112
1113     status = notmuch_query_search_messages (query, &messages);
1114     if (print_status_query ("notmuch show", query, status))
1115         return 1;
1116
1117     message = notmuch_messages_get (messages);
1118
1119     if (message == NULL) {
1120         fprintf (stderr, "Error: Cannot find matching message.\n");
1121         return 1;
1122     }
1123
1124     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
1125
1126     return show_message (ctx, format, sp, message, 0, params)
1127            != NOTMUCH_STATUS_SUCCESS;
1128 }
1129
1130 /* Formatted output of threads */
1131 static int
1132 do_show_threaded (void *ctx,
1133                   notmuch_query_t *query,
1134                   const notmuch_show_format_t *format,
1135                   sprinter_t *sp,
1136                   notmuch_show_params_t *params)
1137 {
1138     notmuch_threads_t *threads;
1139     notmuch_thread_t *thread;
1140     notmuch_messages_t *messages;
1141     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1142
1143     status = notmuch_query_search_threads (query, &threads);
1144     if (print_status_query ("notmuch show", query, status))
1145         return 1;
1146
1147     sp->begin_list (sp);
1148
1149     for (;
1150          notmuch_threads_valid (threads);
1151          notmuch_threads_move_to_next (threads)) {
1152         thread = notmuch_threads_get (threads);
1153
1154         messages = notmuch_thread_get_toplevel_messages (thread);
1155
1156         if (messages == NULL)
1157             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
1158                             notmuch_thread_get_thread_id (thread));
1159
1160         status = show_messages (ctx, format, sp, messages, 0, params);
1161         if (status && ! res)
1162             res = status;
1163
1164         notmuch_thread_destroy (thread);
1165
1166     }
1167
1168     sp->end (sp);
1169
1170     return res != NOTMUCH_STATUS_SUCCESS;
1171 }
1172
1173 static int
1174 do_show_unthreaded (void *ctx,
1175                     notmuch_query_t *query,
1176                     const notmuch_show_format_t *format,
1177                     sprinter_t *sp,
1178                     notmuch_show_params_t *params)
1179 {
1180     notmuch_messages_t *messages;
1181     notmuch_message_t *message;
1182     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1183     notmuch_bool_t excluded;
1184
1185     status = notmuch_query_search_messages (query, &messages);
1186     if (print_status_query ("notmuch show", query, status))
1187         return 1;
1188
1189     sp->begin_list (sp);
1190
1191     for (;
1192          notmuch_messages_valid (messages);
1193          notmuch_messages_move_to_next (messages)) {
1194         sp->begin_list (sp);
1195         sp->begin_list (sp);
1196
1197         message = notmuch_messages_get (messages);
1198
1199         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, TRUE);
1200         excluded = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED);
1201
1202         if (! excluded || ! params->omit_excluded) {
1203             status = show_message (ctx, format, sp, message, 0, params);
1204             if (status && ! res)
1205                 res = status;
1206         } else {
1207             sp->null (sp);
1208         }
1209         notmuch_message_destroy (message);
1210         sp->end (sp);
1211         sp->end (sp);
1212     }
1213     sp->end (sp);
1214     return res;
1215 }
1216
1217 enum {
1218     NOTMUCH_FORMAT_NOT_SPECIFIED,
1219     NOTMUCH_FORMAT_JSON,
1220     NOTMUCH_FORMAT_SEXP,
1221     NOTMUCH_FORMAT_TEXT,
1222     NOTMUCH_FORMAT_MBOX,
1223     NOTMUCH_FORMAT_RAW
1224 };
1225
1226 static const notmuch_show_format_t format_json = {
1227     .new_sprinter = sprinter_json_create,
1228     .part = format_part_sprinter_entry,
1229 };
1230
1231 static const notmuch_show_format_t format_sexp = {
1232     .new_sprinter = sprinter_sexp_create,
1233     .part = format_part_sprinter_entry,
1234 };
1235
1236 static const notmuch_show_format_t format_text = {
1237     .new_sprinter = sprinter_text_create,
1238     .part = format_part_text,
1239 };
1240
1241 static const notmuch_show_format_t format_mbox = {
1242     .new_sprinter = sprinter_text_create,
1243     .part = format_part_mbox,
1244 };
1245
1246 static const notmuch_show_format_t format_raw = {
1247     .new_sprinter = sprinter_text_create,
1248     .part = format_part_raw,
1249 };
1250
1251 static const notmuch_show_format_t *formatters[] = {
1252     [NOTMUCH_FORMAT_JSON] = &format_json,
1253     [NOTMUCH_FORMAT_SEXP] = &format_sexp,
1254     [NOTMUCH_FORMAT_TEXT] = &format_text,
1255     [NOTMUCH_FORMAT_MBOX] = &format_mbox,
1256     [NOTMUCH_FORMAT_RAW] = &format_raw,
1257 };
1258
1259 int
1260 notmuch_show_command (notmuch_database_t *notmuch, int argc, char *argv[])
1261 {
1262     notmuch_query_t *query;
1263     char *query_string;
1264     int opt_index, ret;
1265     const notmuch_show_format_t *formatter;
1266     sprinter_t *sprinter;
1267     notmuch_show_params_t params = {
1268         .part = -1,
1269         .omit_excluded = true,
1270         .output_body = true,
1271         .crypto = { .decrypt = NOTMUCH_DECRYPT_AUTO },
1272     };
1273     int format = NOTMUCH_FORMAT_NOT_SPECIFIED;
1274     bool exclude = true;
1275     bool entire_thread_set = false;
1276     bool single_message;
1277     bool unthreaded = FALSE;
1278     notmuch_status_t status;
1279     int sort = NOTMUCH_SORT_NEWEST_FIRST;
1280
1281     notmuch_opt_desc_t options[] = {
1282         { .opt_keyword = &sort, .name = "sort", .keywords =
1283               (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
1284                                       { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
1285                                       { 0, 0 } } },
1286         { .opt_keyword = &format, .name = "format", .keywords =
1287               (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
1288                                       { "text", NOTMUCH_FORMAT_TEXT },
1289                                       { "sexp", NOTMUCH_FORMAT_SEXP },
1290                                       { "mbox", NOTMUCH_FORMAT_MBOX },
1291                                       { "raw", NOTMUCH_FORMAT_RAW },
1292                                       { 0, 0 } } },
1293         { .opt_int = &notmuch_format_version, .name = "format-version" },
1294         { .opt_bool = &exclude, .name = "exclude" },
1295         { .opt_bool = &params.entire_thread, .name = "entire-thread",
1296           .present = &entire_thread_set },
1297         { .opt_bool = &unthreaded, .name = "unthreaded" },
1298         { .opt_int = &params.part, .name = "part" },
1299         { .opt_keyword = (int *) (&params.crypto.decrypt), .name = "decrypt",
1300           .keyword_no_arg_value = "true", .keywords =
1301               (notmuch_keyword_t []){ { "false", NOTMUCH_DECRYPT_FALSE },
1302                                       { "auto", NOTMUCH_DECRYPT_AUTO },
1303                                       { "true", NOTMUCH_DECRYPT_NOSTASH },
1304                                       { "stash", NOTMUCH_DECRYPT_TRUE },
1305                                       { 0, 0 } } },
1306         { .opt_bool = &params.crypto.verify, .name = "verify" },
1307         { .opt_bool = &params.output_body, .name = "body" },
1308         { .opt_bool = &params.include_html, .name = "include-html" },
1309         { .opt_inherit = notmuch_shared_options },
1310         { }
1311     };
1312
1313     opt_index = parse_arguments (argc, argv, options, 1);
1314     if (opt_index < 0)
1315         return EXIT_FAILURE;
1316
1317     notmuch_process_shared_options (notmuch, argv[0]);
1318
1319     /* explicit decryption implies verification */
1320     if (params.crypto.decrypt == NOTMUCH_DECRYPT_NOSTASH ||
1321         params.crypto.decrypt == NOTMUCH_DECRYPT_TRUE)
1322         params.crypto.verify = true;
1323
1324     /* specifying a part implies single message display */
1325     single_message = params.part >= 0;
1326
1327     if (format == NOTMUCH_FORMAT_NOT_SPECIFIED) {
1328         /* if part was requested and format was not specified, use format=raw */
1329         if (params.part >= 0)
1330             format = NOTMUCH_FORMAT_RAW;
1331         else
1332             format = NOTMUCH_FORMAT_TEXT;
1333     }
1334
1335     if (format == NOTMUCH_FORMAT_MBOX) {
1336         if (params.part > 0) {
1337             fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
1338             return EXIT_FAILURE;
1339         }
1340     } else if (format == NOTMUCH_FORMAT_RAW) {
1341         /* raw format only supports single message display */
1342         single_message = true;
1343     }
1344
1345     notmuch_exit_if_unsupported_format ();
1346
1347     /* Default is entire-thread = false except for format=json and
1348      * format=sexp. */
1349     if (! entire_thread_set &&
1350         (format == NOTMUCH_FORMAT_JSON || format == NOTMUCH_FORMAT_SEXP))
1351         params.entire_thread = true;
1352
1353     if (! params.output_body) {
1354         if (params.part > 0) {
1355             fprintf (stderr, "Warning: --body=false is incompatible with --part > 0. Disabling.\n");
1356             params.output_body = true;
1357         } else {
1358             if (format != NOTMUCH_FORMAT_TEXT &&
1359                 format != NOTMUCH_FORMAT_JSON &&
1360                 format != NOTMUCH_FORMAT_SEXP)
1361                 fprintf (stderr,
1362                          "Warning: --body=false only implemented for format=text, format=json and format=sexp\n");
1363         }
1364     }
1365
1366     if (params.include_html &&
1367         (format != NOTMUCH_FORMAT_TEXT &&
1368          format != NOTMUCH_FORMAT_JSON &&
1369          format != NOTMUCH_FORMAT_SEXP)) {
1370         fprintf (stderr,
1371                  "Warning: --include-html only implemented for format=text, format=json and format=sexp\n");
1372     }
1373
1374     if (params.crypto.decrypt == NOTMUCH_DECRYPT_TRUE) {
1375         status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1376         if (status) {
1377             fprintf (stderr, "Error reopening database for READ_WRITE: %s\n",
1378                      notmuch_status_to_string (status));
1379             return EXIT_FAILURE;
1380         }
1381     }
1382
1383     query_string = query_string_from_args (notmuch, argc - opt_index, argv + opt_index);
1384     if (query_string == NULL) {
1385         fprintf (stderr, "Out of memory\n");
1386         return EXIT_FAILURE;
1387     }
1388
1389     if (*query_string == '\0') {
1390         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
1391         return EXIT_FAILURE;
1392     }
1393
1394     status = notmuch_query_create_with_syntax (notmuch, query_string,
1395                                                shared_option_query_syntax (),
1396                                                &query);
1397     if (print_status_database ("notmuch show", notmuch, status))
1398         return EXIT_FAILURE;
1399
1400     notmuch_query_set_sort (query, sort);
1401
1402     /* Create structure printer. */
1403     formatter = formatters[format];
1404     sprinter = formatter->new_sprinter (notmuch, stdout);
1405
1406     params.out_stream = g_mime_stream_stdout_new ();
1407
1408     /* If a single message is requested we do not use search_excludes. */
1409     if (single_message) {
1410         ret = do_show_single (notmuch, query, formatter, sprinter, &params);
1411     } else {
1412         /* We always apply set the exclude flag. The
1413          * exclude=true|false option controls whether or not we return
1414          * threads that only match in an excluded message */
1415         notmuch_config_values_t *exclude_tags;
1416         notmuch_status_t status;
1417
1418         for (exclude_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_EXCLUDE_TAGS);
1419              notmuch_config_values_valid (exclude_tags);
1420              notmuch_config_values_move_to_next (exclude_tags)) {
1421
1422             status = notmuch_query_add_tag_exclude (query,
1423                                                     notmuch_config_values_get (exclude_tags));
1424             if (status && status != NOTMUCH_STATUS_IGNORED) {
1425                 print_status_query ("notmuch show", query, status);
1426                 ret = -1;
1427                 goto DONE;
1428             }
1429         }
1430
1431         if (exclude == false) {
1432             notmuch_query_set_omit_excluded (query, false);
1433             params.omit_excluded = false;
1434         }
1435
1436         if (unthreaded)
1437             ret = do_show_unthreaded (notmuch, query, formatter, sprinter, &params);
1438         else
1439             ret = do_show_threaded (notmuch, query, formatter, sprinter, &params);
1440     }
1441
1442   DONE:
1443     g_mime_stream_flush (params.out_stream);
1444     g_object_unref (params.out_stream);
1445
1446     _notmuch_crypto_cleanup (&params.crypto);
1447     notmuch_query_destroy (query);
1448     notmuch_database_destroy (notmuch);
1449
1450     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
1451 }