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