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