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