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