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