]> git.cworth.org Git - notmuch/blob - notmuch-show.c
CLI: print extra headers in structured output
[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     format_extra_headers_sprinter (sp, message);
298     sp->end (sp);
299     talloc_free (local);
300 }
301
302 /* Write a MIME text part out to the given stream.
303  *
304  * If (flags & NOTMUCH_SHOW_TEXT_PART_REPLY), this prepends "> " to
305  * each output line.
306  *
307  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
308  * UTF-8) will be performed, so it is inappropriate to call this
309  * function with a non-text part. Doing so will trigger an internal
310  * error.
311  */
312 void
313 show_text_part_content (GMimeObject *part, GMimeStream *stream_out,
314                         notmuch_show_text_part_flags flags)
315 {
316     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
317     GMimeStream *stream_filter = NULL;
318     GMimeFilter *crlf_filter = NULL;
319     GMimeFilter *windows_filter = NULL;
320     GMimeDataWrapper *wrapper;
321     const char *charset;
322
323     if (! g_mime_content_type_is_type (content_type, "text", "*"))
324         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
325                         g_mime_content_type_get_mime_type (content_type));
326
327     if (stream_out == NULL)
328         return;
329
330     charset = g_mime_object_get_content_type_parameter (part, "charset");
331     charset = charset ? g_mime_charset_canon_name (charset) : NULL;
332     wrapper = g_mime_part_get_content (GMIME_PART (part));
333     if (wrapper && charset && ! g_ascii_strncasecmp (charset, "iso-8859-", 9)) {
334         GMimeStream *null_stream = NULL;
335         GMimeStream *null_stream_filter = NULL;
336
337         /* Check for mislabeled Windows encoding */
338         null_stream = g_mime_stream_null_new ();
339         null_stream_filter = g_mime_stream_filter_new (null_stream);
340         windows_filter = g_mime_filter_windows_new (charset);
341         g_mime_stream_filter_add (GMIME_STREAM_FILTER (null_stream_filter),
342                                   windows_filter);
343         g_mime_data_wrapper_write_to_stream (wrapper, null_stream_filter);
344         charset = g_mime_filter_windows_real_charset (
345             (GMimeFilterWindows *) windows_filter);
346
347         if (null_stream_filter)
348             g_object_unref (null_stream_filter);
349         if (null_stream)
350             g_object_unref (null_stream);
351         /* Keep a reference to windows_filter in order to prevent the
352          * charset string from deallocation. */
353     }
354
355     stream_filter = g_mime_stream_filter_new (stream_out);
356     crlf_filter = g_mime_filter_dos2unix_new (false);
357     g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
358                               crlf_filter);
359     g_object_unref (crlf_filter);
360
361     if (charset) {
362         GMimeFilter *charset_filter;
363         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
364         /* This result can be NULL for things like "unknown-8bit".
365          * Don't set a NULL filter as that makes GMime print
366          * annoying assertion-failure messages on stderr. */
367         if (charset_filter) {
368             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
369                                       charset_filter);
370             g_object_unref (charset_filter);
371         }
372
373     }
374
375     if (flags & NOTMUCH_SHOW_TEXT_PART_REPLY) {
376         GMimeFilter *reply_filter;
377         reply_filter = g_mime_filter_reply_new (true);
378         if (reply_filter) {
379             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
380                                       reply_filter);
381             g_object_unref (reply_filter);
382         }
383     }
384
385     if (wrapper && stream_filter)
386         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
387     if (stream_filter)
388         g_object_unref (stream_filter);
389     if (windows_filter)
390         g_object_unref (windows_filter);
391 }
392
393 static const char *
394 signature_status_to_string (GMimeSignatureStatus status)
395 {
396     if (g_mime_signature_status_bad (status))
397         return "bad";
398
399     if (g_mime_signature_status_error (status))
400         return "error";
401
402     if (g_mime_signature_status_good (status))
403         return "good";
404
405     return "unknown";
406 }
407
408 /* Print signature flags */
409 struct key_map_struct {
410     GMimeSignatureStatus bit;
411     const char *string;
412 };
413
414 static void
415 do_format_signature_errors (sprinter_t *sp, struct key_map_struct *key_map,
416                             unsigned int array_map_len, GMimeSignatureStatus errors)
417 {
418     sp->map_key (sp, "errors");
419     sp->begin_map (sp);
420
421     for (unsigned int i = 0; i < array_map_len; i++) {
422         if (errors & key_map[i].bit) {
423             sp->map_key (sp, key_map[i].string);
424             sp->boolean (sp, true);
425         }
426     }
427
428     sp->end (sp);
429 }
430
431 static void
432 format_signature_errors (sprinter_t *sp, GMimeSignature *signature)
433 {
434     GMimeSignatureStatus errors = g_mime_signature_get_status (signature);
435
436     if (! (errors & GMIME_SIGNATURE_STATUS_ERROR_MASK))
437         return;
438
439     struct key_map_struct key_map[] = {
440         { GMIME_SIGNATURE_STATUS_KEY_REVOKED, "key-revoked" },
441         { GMIME_SIGNATURE_STATUS_KEY_EXPIRED, "key-expired" },
442         { GMIME_SIGNATURE_STATUS_SIG_EXPIRED, "sig-expired" },
443         { GMIME_SIGNATURE_STATUS_KEY_MISSING, "key-missing" },
444         { GMIME_SIGNATURE_STATUS_CRL_MISSING, "crl-missing" },
445         { GMIME_SIGNATURE_STATUS_CRL_TOO_OLD, "crl-too-old" },
446         { GMIME_SIGNATURE_STATUS_BAD_POLICY, "bad-policy" },
447         { GMIME_SIGNATURE_STATUS_SYS_ERROR, "sys-error" },
448         { GMIME_SIGNATURE_STATUS_TOFU_CONFLICT, "tofu-conflict" },
449     };
450
451     do_format_signature_errors (sp, key_map, ARRAY_SIZE (key_map), errors);
452 }
453
454 /* Signature status sprinter */
455 static void
456 format_part_sigstatus_sprinter (sprinter_t *sp, GMimeSignatureList *siglist)
457 {
458     /* Any changes to the JSON or S-Expression format should be
459      * reflected in the file devel/schemata. */
460
461     sp->begin_list (sp);
462
463     if (! siglist) {
464         sp->end (sp);
465         return;
466     }
467
468     int i;
469
470     for (i = 0; i < g_mime_signature_list_length (siglist); i++) {
471         GMimeSignature *signature = g_mime_signature_list_get_signature (siglist, i);
472
473         sp->begin_map (sp);
474
475         /* status */
476         GMimeSignatureStatus status = g_mime_signature_get_status (signature);
477         sp->map_key (sp, "status");
478         sp->string (sp, signature_status_to_string (status));
479
480         GMimeCertificate *certificate = g_mime_signature_get_certificate (signature);
481         if (g_mime_signature_status_good (status)) {
482             if (certificate) {
483                 sp->map_key (sp, "fingerprint");
484                 sp->string (sp, g_mime_certificate_get_fingerprint (certificate));
485             }
486             /* these dates are seconds since the epoch; should we
487              * provide a more human-readable format string? */
488             time_t created = g_mime_signature_get_created (signature);
489             if (created != -1) {
490                 sp->map_key (sp, "created");
491                 sp->integer (sp, created);
492             }
493             time_t expires = g_mime_signature_get_expires (signature);
494             if (expires > 0) {
495                 sp->map_key (sp, "expires");
496                 sp->integer (sp, expires);
497             }
498             if (certificate) {
499                 const char *uid = g_mime_certificate_get_valid_userid (certificate);
500                 if (uid) {
501                     sp->map_key (sp, "userid");
502                     sp->string (sp, uid);
503                 }
504                 const char *email = g_mime_certificate_get_valid_email (certificate);
505                 if (email) {
506                     sp->map_key (sp, "email");
507                     sp->string (sp, email);
508                 }
509             }
510         } else if (certificate) {
511             const char *key_id = g_mime_certificate_get_fpr16 (certificate);
512             if (key_id) {
513                 sp->map_key (sp, "keyid");
514                 sp->string (sp, key_id);
515             }
516         }
517
518         if (notmuch_format_version <= 3) {
519             GMimeSignatureStatus errors = g_mime_signature_get_status (signature);
520             if (g_mime_signature_status_error (errors)) {
521                 sp->map_key (sp, "errors");
522                 sp->integer (sp, errors);
523             }
524         } else {
525             format_signature_errors (sp, signature);
526         }
527
528         sp->end (sp);
529     }
530
531     sp->end (sp);
532 }
533
534 static notmuch_status_t
535 format_part_text (const void *ctx, sprinter_t *sp, mime_node_t *node,
536                   int indent, const notmuch_show_params_t *params)
537 {
538     /* The disposition and content-type metadata are associated with
539      * the envelope for message parts */
540     GMimeObject *meta = node->envelope_part ? (
541         GMIME_OBJECT (node->envelope_part) ) : node->part;
542     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
543     const bool leaf = GMIME_IS_PART (node->part);
544     GMimeStream *stream = params->out_stream;
545     const char *part_type;
546     int i;
547
548     if (node->envelope_file) {
549         notmuch_message_t *message = node->envelope_file;
550
551         part_type = "message";
552         g_mime_stream_printf (stream, "\f%s{ id:%s depth:%d match:%d excluded:%d filename:%s\n",
553                               part_type,
554                               notmuch_message_get_message_id (message),
555                               indent,
556                               _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? 1 : 0,
557                               _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED) ? 1 : 0,
558                               notmuch_message_get_filename (message));
559     } else {
560         char *content_string;
561         const char *disposition = _get_disposition (meta);
562         const char *cid = g_mime_object_get_content_id (meta);
563         const char *filename = leaf ? (
564             g_mime_part_get_filename (GMIME_PART (node->part)) ) : NULL;
565
566         if (disposition &&
567             strcasecmp (disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
568             part_type = "attachment";
569         else
570             part_type = "part";
571
572         g_mime_stream_printf (stream, "\f%s{ ID: %d", part_type, node->part_num);
573         if (filename)
574             g_mime_stream_printf (stream, ", Filename: %s", filename);
575         if (cid)
576             g_mime_stream_printf (stream, ", Content-id: %s", cid);
577
578         content_string = g_mime_content_type_get_mime_type (content_type);
579         g_mime_stream_printf (stream, ", Content-type: %s\n", content_string);
580         g_free (content_string);
581     }
582
583     if (GMIME_IS_MESSAGE (node->part)) {
584         GMimeMessage *message = GMIME_MESSAGE (node->part);
585         char *recipients_string;
586         char *date_string;
587
588         g_mime_stream_printf (stream, "\fheader{\n");
589         if (node->envelope_file)
590             g_mime_stream_printf (stream, "%s\n", _get_one_line_summary (ctx, node->envelope_file));
591         g_mime_stream_printf (stream, "Subject: %s\n", g_mime_message_get_subject (message));
592         g_mime_stream_printf (stream, "From: %s\n", g_mime_message_get_from_string (message));
593         recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_TO);
594         if (recipients_string)
595             g_mime_stream_printf (stream, "To: %s\n", recipients_string);
596         g_free (recipients_string);
597         recipients_string = g_mime_message_get_address_string (message, GMIME_ADDRESS_TYPE_CC);
598         if (recipients_string)
599             g_mime_stream_printf (stream, "Cc: %s\n", recipients_string);
600         g_free (recipients_string);
601         date_string = g_mime_message_get_date_string (node, message);
602         g_mime_stream_printf (stream, "Date: %s\n", date_string);
603         g_mime_stream_printf (stream, "\fheader}\n");
604
605         if (! params->output_body) {
606             g_mime_stream_printf (stream, "\f%s}\n", part_type);
607             return NOTMUCH_STATUS_SUCCESS;
608         }
609         g_mime_stream_printf (stream, "\fbody{\n");
610     }
611
612     if (leaf) {
613         if (g_mime_content_type_is_type (content_type, "text", "*") &&
614             (params->include_html ||
615              ! g_mime_content_type_is_type (content_type, "text", "html"))) {
616             show_text_part_content (node->part, stream, 0);
617         } else {
618             char *content_string = g_mime_content_type_get_mime_type (content_type);
619             g_mime_stream_printf (stream, "Non-text part: %s\n", content_string);
620             g_free (content_string);
621         }
622     }
623
624     for (i = 0; i < node->nchildren; i++)
625         format_part_text (ctx, sp, mime_node_child (node, i), indent, params);
626
627     if (GMIME_IS_MESSAGE (node->part))
628         g_mime_stream_printf (stream, "\fbody}\n");
629
630     g_mime_stream_printf (stream, "\f%s}\n", part_type);
631
632     return NOTMUCH_STATUS_SUCCESS;
633 }
634
635 static void
636 format_omitted_part_meta_sprinter (sprinter_t *sp, GMimeObject *meta, GMimePart *part)
637 {
638     const char *content_charset = g_mime_object_get_content_type_parameter (meta, "charset");
639     const char *cte = g_mime_object_get_header (meta, "content-transfer-encoding");
640     GMimeDataWrapper *wrapper = g_mime_part_get_content (part);
641     GMimeStream *stream = g_mime_data_wrapper_get_stream (wrapper);
642     ssize_t content_length = g_mime_stream_length (stream);
643
644     if (content_charset != NULL) {
645         sp->map_key (sp, "content-charset");
646         sp->string (sp, content_charset);
647     }
648     if (cte != NULL) {
649         sp->map_key (sp, "content-transfer-encoding");
650         sp->string (sp, cte);
651     }
652     if (content_length >= 0) {
653         sp->map_key (sp, "content-length");
654         sp->integer (sp, content_length);
655     }
656 }
657
658 void
659 format_part_sprinter (const void *ctx, sprinter_t *sp, mime_node_t *node,
660                       bool output_body,
661                       bool include_html)
662 {
663     /* Any changes to the JSON or S-Expression format should be
664      * reflected in the file devel/schemata. */
665
666     if (node->envelope_file) {
667         const _notmuch_message_crypto_t *msg_crypto = NULL;
668         sp->begin_map (sp);
669         format_message_sprinter (sp, node->envelope_file);
670
671         if (output_body) {
672             sp->map_key (sp, "body");
673             sp->begin_list (sp);
674             format_part_sprinter (ctx, sp, mime_node_child (node, 0), true, include_html);
675             sp->end (sp);
676         }
677
678         msg_crypto = mime_node_get_message_crypto_status (node);
679         if (notmuch_format_version >= 4) {
680             sp->map_key (sp, "crypto");
681             sp->begin_map (sp);
682             if (msg_crypto->sig_list ||
683                 msg_crypto->decryption_status != NOTMUCH_MESSAGE_DECRYPTED_NONE) {
684                 if (msg_crypto->sig_list) {
685                     sp->map_key (sp, "signed");
686                     sp->begin_map (sp);
687                     sp->map_key (sp, "status");
688                     format_part_sigstatus_sprinter (sp, msg_crypto->sig_list);
689                     if (msg_crypto->signature_encrypted) {
690                         sp->map_key (sp, "encrypted");
691                         sp->boolean (sp, msg_crypto->signature_encrypted);
692                     }
693                     if (msg_crypto->payload_subject) {
694                         sp->map_key (sp, "headers");
695                         sp->begin_list (sp);
696                         sp->string (sp, "Subject");
697                         sp->end (sp);
698                     }
699                     sp->end (sp);
700                 }
701                 if (msg_crypto->decryption_status != NOTMUCH_MESSAGE_DECRYPTED_NONE) {
702                     sp->map_key (sp, "decrypted");
703                     sp->begin_map (sp);
704                     sp->map_key (sp, "status");
705                     sp->string (sp, msg_crypto->decryption_status == NOTMUCH_MESSAGE_DECRYPTED_FULL ?
706                                 "full" : "partial");
707
708                     if (msg_crypto->payload_subject) {
709                         const char *subject = g_mime_message_get_subject GMIME_MESSAGE (node->part);
710                         if (subject == NULL || strcmp (subject, msg_crypto->payload_subject)) {
711                             /* protected subject differs from the external header */
712                             sp->map_key (sp, "header-mask");
713                             sp->begin_map (sp);
714                             sp->map_key (sp, "Subject");
715                             if (subject == NULL)
716                                 sp->null (sp);
717                             else
718                                 sp->string (sp, subject);
719                             sp->end (sp);
720                         }
721                     }
722                     sp->end (sp);
723                 }
724             }
725             sp->end (sp);
726         }
727
728         sp->map_key (sp, "headers");
729         format_headers_sprinter (sp, GMIME_MESSAGE (node->part), false, msg_crypto);
730
731         sp->end (sp);
732         return;
733     }
734
735     /* The disposition and content-type metadata are associated with
736      * the envelope for message parts */
737     GMimeObject *meta = node->envelope_part ? (
738         GMIME_OBJECT (node->envelope_part) ) : node->part;
739     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
740     char *content_string;
741     const char *disposition = _get_disposition (meta);
742     const char *cid = g_mime_object_get_content_id (meta);
743     const char *filename = GMIME_IS_PART (node->part) ? (
744         g_mime_part_get_filename (GMIME_PART (node->part) ) ) : NULL;
745     int nclose = 0;
746     int i;
747
748     sp->begin_map (sp);
749
750     sp->map_key (sp, "id");
751     sp->integer (sp, node->part_num);
752
753     if (node->decrypt_attempted) {
754         sp->map_key (sp, "encstatus");
755         sp->begin_list (sp);
756         sp->begin_map (sp);
757         sp->map_key (sp, "status");
758         sp->string (sp, node->decrypt_success ? "good" : "bad");
759         sp->end (sp);
760         sp->end (sp);
761     }
762
763     if (node->verify_attempted) {
764         sp->map_key (sp, "sigstatus");
765         format_part_sigstatus_sprinter (sp, node->sig_list);
766     }
767
768     sp->map_key (sp, "content-type");
769     content_string = g_mime_content_type_get_mime_type (content_type);
770     sp->string (sp, content_string);
771     g_free (content_string);
772
773     if (disposition) {
774         sp->map_key (sp, "content-disposition");
775         sp->string (sp, disposition);
776     }
777
778     if (cid) {
779         sp->map_key (sp, "content-id");
780         sp->string (sp, cid);
781     }
782
783     if (filename) {
784         sp->map_key (sp, "filename");
785         sp->string (sp, filename);
786     }
787
788     if (GMIME_IS_PART (node->part)) {
789         /* For non-HTML text parts, we include the content in the
790          * JSON. Since JSON must be Unicode, we handle charset
791          * decoding here and do not report a charset to the caller.
792          * For text/html parts, we do not include the content unless
793          * the --include-html option has been passed. If a html part
794          * is not included, it can be requested directly. This makes
795          * charset decoding the responsibility on the caller so we
796          * report the charset for text/html parts.
797          */
798         if (g_mime_content_type_is_type (content_type, "text", "*") &&
799             (include_html ||
800              ! g_mime_content_type_is_type (content_type, "text", "html"))) {
801             GMimeStream *stream_memory = g_mime_stream_mem_new ();
802             GByteArray *part_content;
803             show_text_part_content (node->part, stream_memory, 0);
804             part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
805             sp->map_key (sp, "content");
806             sp->string_len (sp, (char *) part_content->data, part_content->len);
807             g_object_unref (stream_memory);
808         } else {
809             /* if we have a child part despite being a standard
810              * (non-multipart) MIME part, that means there is
811              * something to unwrap, which we will present in
812              * content: */
813             if (node->nchildren) {
814                 sp->map_key (sp, "content");
815                 sp->begin_list (sp);
816                 nclose = 1;
817             } else
818                 format_omitted_part_meta_sprinter (sp, meta, GMIME_PART (node->part));
819         }
820     } else if (GMIME_IS_MULTIPART (node->part)) {
821         sp->map_key (sp, "content");
822         sp->begin_list (sp);
823         nclose = 1;
824     } else if (GMIME_IS_MESSAGE (node->part)) {
825         sp->map_key (sp, "content");
826         sp->begin_list (sp);
827         sp->begin_map (sp);
828
829         sp->map_key (sp, "headers");
830         format_headers_sprinter (sp, GMIME_MESSAGE (node->part), false, NULL);
831
832         sp->map_key (sp, "body");
833         sp->begin_list (sp);
834         nclose = 3;
835     }
836
837     for (i = 0; i < node->nchildren; i++)
838         format_part_sprinter (ctx, sp, mime_node_child (node, i), true, include_html);
839
840     /* Close content structures */
841     for (i = 0; i < nclose; i++)
842         sp->end (sp);
843     /* Close part map */
844     sp->end (sp);
845 }
846
847 static notmuch_status_t
848 format_part_sprinter_entry (const void *ctx, sprinter_t *sp,
849                             mime_node_t *node, unused (int indent),
850                             const notmuch_show_params_t *params)
851 {
852     format_part_sprinter (ctx, sp, node, params->output_body, params->include_html);
853
854     return NOTMUCH_STATUS_SUCCESS;
855 }
856
857 /* Print a message in "mboxrd" format as documented, for example,
858  * here:
859  *
860  * http://qmail.org/qmail-manual-html/man5/mbox.html
861  */
862 static notmuch_status_t
863 format_part_mbox (const void *ctx, unused (sprinter_t *sp), mime_node_t *node,
864                   unused (int indent),
865                   unused (const notmuch_show_params_t *params))
866 {
867     notmuch_message_t *message = node->envelope_file;
868
869     const char *filename;
870     gzFile file;
871     const char *from;
872
873     time_t date;
874     struct tm date_gmtime;
875     char date_asctime[26];
876
877     char *line = NULL;
878     ssize_t line_size;
879     ssize_t line_len;
880
881     if (! message)
882         INTERNAL_ERROR ("format_part_mbox requires a root part");
883
884     filename = notmuch_message_get_filename (message);
885     file = gzopen (filename, "r");
886     if (file == NULL) {
887         fprintf (stderr, "Failed to open %s: %s\n",
888                  filename, strerror (errno));
889         return NOTMUCH_STATUS_FILE_ERROR;
890     }
891
892     from = notmuch_message_get_header (message, "from");
893     from = _extract_email_address (ctx, from);
894
895     date = notmuch_message_get_date (message);
896     gmtime_r (&date, &date_gmtime);
897     asctime_r (&date_gmtime, date_asctime);
898
899     printf ("From %s %s", from, date_asctime);
900
901     while ((line_len = gz_getline (message, &line, &line_size, file)) != UTIL_EOF ) {
902         if (_is_from_line (line))
903             putchar ('>');
904         printf ("%s", line);
905     }
906
907     printf ("\n");
908
909     gzclose (file);
910
911     return NOTMUCH_STATUS_SUCCESS;
912 }
913
914 static notmuch_status_t
915 format_part_raw (unused (const void *ctx), unused (sprinter_t *sp),
916                  mime_node_t *node, unused (int indent),
917                  const notmuch_show_params_t *params)
918 {
919     if (node->envelope_file) {
920         /* Special case the entire message to avoid MIME parsing. */
921         const char *filename;
922         GMimeStream *stream = NULL;
923         ssize_t ssize;
924         char buf[4096];
925         notmuch_status_t ret = NOTMUCH_STATUS_FILE_ERROR;
926
927         filename = notmuch_message_get_filename (node->envelope_file);
928         if (filename == NULL) {
929             fprintf (stderr, "Error: Cannot get message filename.\n");
930             goto DONE;
931         }
932
933         stream = g_mime_stream_gzfile_open (filename);
934         if (stream == NULL) {
935             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
936             goto DONE;
937         }
938
939         while (! g_mime_stream_eos (stream)) {
940             ssize = g_mime_stream_read (stream, buf, sizeof (buf));
941             if (ssize < 0) {
942                 fprintf (stderr, "Error: Read failed from %s\n", filename);
943                 goto DONE;
944             }
945
946             if (ssize > 0 && fwrite (buf, ssize, 1, stdout) != 1) {
947                 fprintf (stderr, "Error: Write %zd chars to stdout failed\n", ssize);
948                 goto DONE;
949             }
950         }
951
952         ret = NOTMUCH_STATUS_SUCCESS;
953
954         /* XXX This DONE is just for the special case of a node in a single file */
955       DONE:
956         if (stream)
957             g_object_unref (stream);
958
959         return ret;
960     }
961
962     GMimeStream *stream_filter = g_mime_stream_filter_new (params->out_stream);
963
964     if (GMIME_IS_PART (node->part)) {
965         /* For leaf parts, we emit only the transfer-decoded
966          * body. */
967         GMimeDataWrapper *wrapper;
968         wrapper = g_mime_part_get_content (GMIME_PART (node->part));
969
970         if (wrapper && stream_filter)
971             g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
972     } else {
973         /* Write out the whole part.  For message parts (the root
974          * part and embedded message parts), this will be the
975          * message including its headers (but not the
976          * encapsulating part's headers).  For multipart parts,
977          * this will include the headers. */
978         if (stream_filter)
979             g_mime_object_write_to_stream (node->part, NULL, stream_filter);
980     }
981
982     if (stream_filter)
983         g_object_unref (stream_filter);
984
985     return NOTMUCH_STATUS_SUCCESS;
986 }
987
988 static notmuch_status_t
989 show_message (void *ctx,
990               const notmuch_show_format_t *format,
991               sprinter_t *sp,
992               notmuch_message_t *message,
993               int indent,
994               notmuch_show_params_t *params)
995 {
996     void *local = talloc_new (ctx);
997     mime_node_t *root, *part;
998     notmuch_status_t status;
999     unsigned int session_keys = 0;
1000     notmuch_status_t session_key_count_error = NOTMUCH_STATUS_SUCCESS;
1001
1002     if (params->crypto.decrypt == NOTMUCH_DECRYPT_TRUE)
1003         session_key_count_error = notmuch_message_count_properties (message, "session-key",
1004                                                                     &session_keys);
1005
1006     status = mime_node_open (local, message, &(params->crypto), &root);
1007     if (status)
1008         goto DONE;
1009     part = mime_node_seek_dfs (root, (params->part < 0 ? 0 : params->part));
1010     if (part)
1011         status = format->part (local, sp, part, indent, params);
1012     if (params->crypto.decrypt == NOTMUCH_DECRYPT_TRUE && session_key_count_error ==
1013         NOTMUCH_STATUS_SUCCESS) {
1014         unsigned int new_session_keys = 0;
1015         if (notmuch_message_count_properties (message, "session-key", &new_session_keys) ==
1016             NOTMUCH_STATUS_SUCCESS &&
1017             new_session_keys > session_keys) {
1018             /* try a quiet re-indexing */
1019             notmuch_indexopts_t *indexopts = notmuch_database_get_default_indexopts (
1020                 notmuch_message_get_database (message));
1021             if (indexopts) {
1022                 notmuch_indexopts_set_decrypt_policy (indexopts, NOTMUCH_DECRYPT_AUTO);
1023                 print_status_message ("Error re-indexing message with --decrypt=stash",
1024                                       message, notmuch_message_reindex (message, indexopts));
1025             }
1026         }
1027     }
1028   DONE:
1029     talloc_free (local);
1030     return status;
1031 }
1032
1033 static notmuch_status_t
1034 show_messages (void *ctx,
1035                const notmuch_show_format_t *format,
1036                sprinter_t *sp,
1037                notmuch_messages_t *messages,
1038                int indent,
1039                notmuch_show_params_t *params)
1040 {
1041     notmuch_message_t *message;
1042     bool match;
1043     bool excluded;
1044     int next_indent;
1045     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1046
1047     sp->begin_list (sp);
1048
1049     for (;
1050          notmuch_messages_valid (messages);
1051          notmuch_messages_move_to_next (messages)) {
1052         sp->begin_list (sp);
1053
1054         message = notmuch_messages_get (messages);
1055
1056         match = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
1057         excluded = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED);
1058
1059         next_indent = indent;
1060
1061         if ((match && (! excluded || ! params->omit_excluded)) || params->entire_thread) {
1062             status = show_message (ctx, format, sp, message, indent, params);
1063             if (status && ! res)
1064                 res = status;
1065             next_indent = indent + 1;
1066         } else {
1067             sp->null (sp);
1068         }
1069
1070         status = show_messages (ctx,
1071                                 format, sp,
1072                                 notmuch_message_get_replies (message),
1073                                 next_indent,
1074                                 params);
1075         if (status && ! res)
1076             res = status;
1077
1078         notmuch_message_destroy (message);
1079
1080         sp->end (sp);
1081     }
1082
1083     sp->end (sp);
1084
1085     return res;
1086 }
1087
1088 /* Formatted output of single message */
1089 static int
1090 do_show_single (void *ctx,
1091                 notmuch_query_t *query,
1092                 const notmuch_show_format_t *format,
1093                 sprinter_t *sp,
1094                 notmuch_show_params_t *params)
1095 {
1096     notmuch_messages_t *messages;
1097     notmuch_message_t *message;
1098     notmuch_status_t status;
1099     unsigned int count;
1100
1101     status = notmuch_query_count_messages (query, &count);
1102     if (print_status_query ("notmuch show", query, status))
1103         return 1;
1104
1105     if (count != 1) {
1106         fprintf (stderr,
1107                  "Error: search term did not match precisely one message (matched %u messages).\n",
1108                  count);
1109         return 1;
1110     }
1111
1112     status = notmuch_query_search_messages (query, &messages);
1113     if (print_status_query ("notmuch show", query, status))
1114         return 1;
1115
1116     message = notmuch_messages_get (messages);
1117
1118     if (message == NULL) {
1119         fprintf (stderr, "Error: Cannot find matching message.\n");
1120         return 1;
1121     }
1122
1123     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
1124
1125     return show_message (ctx, format, sp, message, 0, params)
1126            != NOTMUCH_STATUS_SUCCESS;
1127 }
1128
1129 /* Formatted output of threads */
1130 static int
1131 do_show_threaded (void *ctx,
1132                   notmuch_query_t *query,
1133                   const notmuch_show_format_t *format,
1134                   sprinter_t *sp,
1135                   notmuch_show_params_t *params)
1136 {
1137     notmuch_threads_t *threads;
1138     notmuch_thread_t *thread;
1139     notmuch_messages_t *messages;
1140     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1141
1142     status = notmuch_query_search_threads (query, &threads);
1143     if (print_status_query ("notmuch show", query, status))
1144         return 1;
1145
1146     sp->begin_list (sp);
1147
1148     for (;
1149          notmuch_threads_valid (threads);
1150          notmuch_threads_move_to_next (threads)) {
1151         thread = notmuch_threads_get (threads);
1152
1153         messages = notmuch_thread_get_toplevel_messages (thread);
1154
1155         if (messages == NULL)
1156             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
1157                             notmuch_thread_get_thread_id (thread));
1158
1159         status = show_messages (ctx, format, sp, messages, 0, params);
1160         if (status && ! res)
1161             res = status;
1162
1163         notmuch_thread_destroy (thread);
1164
1165     }
1166
1167     sp->end (sp);
1168
1169     return res != NOTMUCH_STATUS_SUCCESS;
1170 }
1171
1172 static int
1173 do_show_unthreaded (void *ctx,
1174                     notmuch_query_t *query,
1175                     const notmuch_show_format_t *format,
1176                     sprinter_t *sp,
1177                     notmuch_show_params_t *params)
1178 {
1179     notmuch_messages_t *messages;
1180     notmuch_message_t *message;
1181     notmuch_status_t status, res = NOTMUCH_STATUS_SUCCESS;
1182     notmuch_bool_t excluded;
1183
1184     status = notmuch_query_search_messages (query, &messages);
1185     if (print_status_query ("notmuch show", query, status))
1186         return 1;
1187
1188     sp->begin_list (sp);
1189
1190     for (;
1191          notmuch_messages_valid (messages);
1192          notmuch_messages_move_to_next (messages)) {
1193         sp->begin_list (sp);
1194         sp->begin_list (sp);
1195
1196         message = notmuch_messages_get (messages);
1197
1198         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, TRUE);
1199         excluded = _get_message_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED);
1200
1201         if (! excluded || ! params->omit_excluded) {
1202             status = show_message (ctx, format, sp, message, 0, params);
1203             if (status && ! res)
1204                 res = status;
1205         } else {
1206             sp->null (sp);
1207         }
1208         notmuch_message_destroy (message);
1209         sp->end (sp);
1210         sp->end (sp);
1211     }
1212     sp->end (sp);
1213     return res;
1214 }
1215
1216 enum {
1217     NOTMUCH_FORMAT_NOT_SPECIFIED,
1218     NOTMUCH_FORMAT_JSON,
1219     NOTMUCH_FORMAT_SEXP,
1220     NOTMUCH_FORMAT_TEXT,
1221     NOTMUCH_FORMAT_MBOX,
1222     NOTMUCH_FORMAT_RAW
1223 };
1224
1225 static const notmuch_show_format_t format_json = {
1226     .new_sprinter = sprinter_json_create,
1227     .part = format_part_sprinter_entry,
1228 };
1229
1230 static const notmuch_show_format_t format_sexp = {
1231     .new_sprinter = sprinter_sexp_create,
1232     .part = format_part_sprinter_entry,
1233 };
1234
1235 static const notmuch_show_format_t format_text = {
1236     .new_sprinter = sprinter_text_create,
1237     .part = format_part_text,
1238 };
1239
1240 static const notmuch_show_format_t format_mbox = {
1241     .new_sprinter = sprinter_text_create,
1242     .part = format_part_mbox,
1243 };
1244
1245 static const notmuch_show_format_t format_raw = {
1246     .new_sprinter = sprinter_text_create,
1247     .part = format_part_raw,
1248 };
1249
1250 static const notmuch_show_format_t *formatters[] = {
1251     [NOTMUCH_FORMAT_JSON] = &format_json,
1252     [NOTMUCH_FORMAT_SEXP] = &format_sexp,
1253     [NOTMUCH_FORMAT_TEXT] = &format_text,
1254     [NOTMUCH_FORMAT_MBOX] = &format_mbox,
1255     [NOTMUCH_FORMAT_RAW] = &format_raw,
1256 };
1257
1258 int
1259 notmuch_show_command (notmuch_database_t *notmuch, int argc, char *argv[])
1260 {
1261     notmuch_query_t *query;
1262     char *query_string;
1263     int opt_index, ret;
1264     const notmuch_show_format_t *formatter;
1265     sprinter_t *sprinter;
1266     notmuch_show_params_t params = {
1267         .part = -1,
1268         .omit_excluded = true,
1269         .output_body = true,
1270         .crypto = { .decrypt = NOTMUCH_DECRYPT_AUTO },
1271     };
1272     int format = NOTMUCH_FORMAT_NOT_SPECIFIED;
1273     bool exclude = true;
1274     bool entire_thread_set = false;
1275     bool single_message;
1276     bool unthreaded = FALSE;
1277     notmuch_status_t status;
1278     int sort = NOTMUCH_SORT_NEWEST_FIRST;
1279
1280     notmuch_opt_desc_t options[] = {
1281         { .opt_keyword = &sort, .name = "sort", .keywords =
1282               (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
1283                                       { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
1284                                       { 0, 0 } } },
1285         { .opt_keyword = &format, .name = "format", .keywords =
1286               (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
1287                                       { "text", NOTMUCH_FORMAT_TEXT },
1288                                       { "sexp", NOTMUCH_FORMAT_SEXP },
1289                                       { "mbox", NOTMUCH_FORMAT_MBOX },
1290                                       { "raw", NOTMUCH_FORMAT_RAW },
1291                                       { 0, 0 } } },
1292         { .opt_int = &notmuch_format_version, .name = "format-version" },
1293         { .opt_bool = &exclude, .name = "exclude" },
1294         { .opt_bool = &params.entire_thread, .name = "entire-thread",
1295           .present = &entire_thread_set },
1296         { .opt_bool = &unthreaded, .name = "unthreaded" },
1297         { .opt_int = &params.part, .name = "part" },
1298         { .opt_keyword = (int *) (&params.crypto.decrypt), .name = "decrypt",
1299           .keyword_no_arg_value = "true", .keywords =
1300               (notmuch_keyword_t []){ { "false", NOTMUCH_DECRYPT_FALSE },
1301                                       { "auto", NOTMUCH_DECRYPT_AUTO },
1302                                       { "true", NOTMUCH_DECRYPT_NOSTASH },
1303                                       { "stash", NOTMUCH_DECRYPT_TRUE },
1304                                       { 0, 0 } } },
1305         { .opt_bool = &params.crypto.verify, .name = "verify" },
1306         { .opt_bool = &params.output_body, .name = "body" },
1307         { .opt_bool = &params.include_html, .name = "include-html" },
1308         { .opt_inherit = notmuch_shared_options },
1309         { }
1310     };
1311
1312     opt_index = parse_arguments (argc, argv, options, 1);
1313     if (opt_index < 0)
1314         return EXIT_FAILURE;
1315
1316     notmuch_process_shared_options (notmuch, argv[0]);
1317
1318     /* explicit decryption implies verification */
1319     if (params.crypto.decrypt == NOTMUCH_DECRYPT_NOSTASH ||
1320         params.crypto.decrypt == NOTMUCH_DECRYPT_TRUE)
1321         params.crypto.verify = true;
1322
1323     /* specifying a part implies single message display */
1324     single_message = params.part >= 0;
1325
1326     if (format == NOTMUCH_FORMAT_NOT_SPECIFIED) {
1327         /* if part was requested and format was not specified, use format=raw */
1328         if (params.part >= 0)
1329             format = NOTMUCH_FORMAT_RAW;
1330         else
1331             format = NOTMUCH_FORMAT_TEXT;
1332     }
1333
1334     if (format == NOTMUCH_FORMAT_MBOX) {
1335         if (params.part > 0) {
1336             fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
1337             return EXIT_FAILURE;
1338         }
1339     } else if (format == NOTMUCH_FORMAT_RAW) {
1340         /* raw format only supports single message display */
1341         single_message = true;
1342     }
1343
1344     notmuch_exit_if_unsupported_format ();
1345
1346     /* Default is entire-thread = false except for format=json and
1347      * format=sexp. */
1348     if (! entire_thread_set &&
1349         (format == NOTMUCH_FORMAT_JSON || format == NOTMUCH_FORMAT_SEXP))
1350         params.entire_thread = true;
1351
1352     if (! params.output_body) {
1353         if (params.part > 0) {
1354             fprintf (stderr, "Warning: --body=false is incompatible with --part > 0. Disabling.\n");
1355             params.output_body = true;
1356         } else {
1357             if (format != NOTMUCH_FORMAT_TEXT &&
1358                 format != NOTMUCH_FORMAT_JSON &&
1359                 format != NOTMUCH_FORMAT_SEXP)
1360                 fprintf (stderr,
1361                          "Warning: --body=false only implemented for format=text, format=json and format=sexp\n");
1362         }
1363     }
1364
1365     if (params.include_html &&
1366         (format != NOTMUCH_FORMAT_TEXT &&
1367          format != NOTMUCH_FORMAT_JSON &&
1368          format != NOTMUCH_FORMAT_SEXP)) {
1369         fprintf (stderr,
1370                  "Warning: --include-html only implemented for format=text, format=json and format=sexp\n");
1371     }
1372
1373     if (params.crypto.decrypt == NOTMUCH_DECRYPT_TRUE) {
1374         status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1375         if (status) {
1376             fprintf (stderr, "Error reopening database for READ_WRITE: %s\n",
1377                      notmuch_status_to_string (status));
1378             return EXIT_FAILURE;
1379         }
1380     }
1381
1382     query_string = query_string_from_args (notmuch, argc - opt_index, argv + opt_index);
1383     if (query_string == NULL) {
1384         fprintf (stderr, "Out of memory\n");
1385         return EXIT_FAILURE;
1386     }
1387
1388     if (*query_string == '\0') {
1389         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
1390         return EXIT_FAILURE;
1391     }
1392
1393     status = notmuch_query_create_with_syntax (notmuch, query_string,
1394                                                shared_option_query_syntax (),
1395                                                &query);
1396     if (print_status_database ("notmuch show", notmuch, status))
1397         return EXIT_FAILURE;
1398
1399     notmuch_query_set_sort (query, sort);
1400
1401     /* Create structure printer. */
1402     formatter = formatters[format];
1403     sprinter = formatter->new_sprinter (notmuch, stdout);
1404
1405     params.out_stream = g_mime_stream_stdout_new ();
1406
1407     /* If a single message is requested we do not use search_excludes. */
1408     if (single_message) {
1409         ret = do_show_single (notmuch, query, formatter, sprinter, &params);
1410     } else {
1411         /* We always apply set the exclude flag. The
1412          * exclude=true|false option controls whether or not we return
1413          * threads that only match in an excluded message */
1414         notmuch_config_values_t *exclude_tags;
1415         notmuch_status_t status;
1416
1417         for (exclude_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_EXCLUDE_TAGS);
1418              notmuch_config_values_valid (exclude_tags);
1419              notmuch_config_values_move_to_next (exclude_tags)) {
1420
1421             status = notmuch_query_add_tag_exclude (query,
1422                                                     notmuch_config_values_get (exclude_tags));
1423             if (status && status != NOTMUCH_STATUS_IGNORED) {
1424                 print_status_query ("notmuch show", query, status);
1425                 ret = -1;
1426                 goto DONE;
1427             }
1428         }
1429
1430         if (exclude == false) {
1431             notmuch_query_set_omit_excluded (query, false);
1432             params.omit_excluded = false;
1433         }
1434
1435         if (unthreaded)
1436             ret = do_show_unthreaded (notmuch, query, formatter, sprinter, &params);
1437         else
1438             ret = do_show_threaded (notmuch, query, formatter, sprinter, &params);
1439     }
1440
1441   DONE:
1442     g_mime_stream_flush (params.out_stream);
1443     g_object_unref (params.out_stream);
1444
1445     _notmuch_crypto_cleanup (&params.crypto);
1446     notmuch_query_destroy (query);
1447     notmuch_database_destroy (notmuch);
1448
1449     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
1450 }