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