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