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