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