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