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