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