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