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