]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
show: Simplify talloc use in format_headers_json
[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 (const void *ctx, GMimeMessage *message)
295 {
296     void *local = talloc_new (ctx);
297     InternetAddressList *recipients;
298     const char *recipients_string;
299
300     printf ("%s: %s",
301             json_quote_str (local, "Subject"),
302             json_quote_str (local, g_mime_message_get_subject (message)));
303     printf (", %s: %s",
304             json_quote_str (local, "From"),
305             json_quote_str (local, g_mime_message_get_sender (message)));
306     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
307     recipients_string = internet_address_list_to_string (recipients, 0);
308     if (recipients_string)
309         printf (", %s: %s",
310                 json_quote_str (local, "To"),
311                 json_quote_str (local, recipients_string));
312     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
313     recipients_string = internet_address_list_to_string (recipients, 0);
314     if (recipients_string)
315         printf (", %s: %s",
316                 json_quote_str (local, "Cc"),
317                 json_quote_str (local, recipients_string));
318     printf (", %s: %s",
319             json_quote_str (local, "Date"),
320             json_quote_str (local, g_mime_message_get_date_as_string (message)));
321
322     talloc_free (local);
323 }
324
325 /* Write a MIME text part out to the given stream.
326  *
327  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
328  * UTF-8) will be performed, so it is inappropriate to call this
329  * function with a non-text part. Doing so will trigger an internal
330  * error.
331  */
332 static void
333 show_text_part_content (GMimeObject *part, GMimeStream *stream_out)
334 {
335     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
336     GMimeStream *stream_filter = NULL;
337     GMimeDataWrapper *wrapper;
338     const char *charset;
339
340     if (! g_mime_content_type_is_type (content_type, "text", "*"))
341         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
342                         g_mime_content_type_to_string (content_type));
343
344     if (stream_out == NULL)
345         return;
346
347     stream_filter = g_mime_stream_filter_new (stream_out);
348     g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
349                              g_mime_filter_crlf_new (FALSE, FALSE));
350
351     charset = g_mime_object_get_content_type_parameter (part, "charset");
352     if (charset) {
353         GMimeFilter *charset_filter;
354         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
355         /* This result can be NULL for things like "unknown-8bit".
356          * Don't set a NULL filter as that makes GMime print
357          * annoying assertion-failure messages on stderr. */
358         if (charset_filter) {
359             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
360                                       charset_filter);
361             g_object_unref (charset_filter);
362         }
363
364     }
365
366     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
367     if (wrapper && stream_filter)
368         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
369     if (stream_filter)
370         g_object_unref(stream_filter);
371 }
372
373 #ifdef GMIME_ATLEAST_26
374 static const char*
375 signature_status_to_string (GMimeSignatureStatus x)
376 {
377     switch (x) {
378     case GMIME_SIGNATURE_STATUS_GOOD:
379         return "good";
380     case GMIME_SIGNATURE_STATUS_BAD:
381         return "bad";
382     case GMIME_SIGNATURE_STATUS_ERROR:
383         return "error";
384     }
385     return "unknown";
386 }
387 #else
388 static const char*
389 signer_status_to_string (GMimeSignerStatus x)
390 {
391     switch (x) {
392     case GMIME_SIGNER_STATUS_NONE:
393         return "none";
394     case GMIME_SIGNER_STATUS_GOOD:
395         return "good";
396     case GMIME_SIGNER_STATUS_BAD:
397         return "bad";
398     case GMIME_SIGNER_STATUS_ERROR:
399         return "error";
400     }
401     return "unknown";
402 }
403 #endif
404
405 #ifdef GMIME_ATLEAST_26
406 static void
407 format_part_sigstatus_json (GMimeSignatureList *siglist)
408 {
409     printf (", \"sigstatus\": [");
410
411     if (!siglist) {
412         printf ("]");
413         return;
414     }
415
416     void *ctx_quote = talloc_new (NULL);
417     int i;
418     for (i = 0; i < g_mime_signature_list_length (siglist); i++) {
419         GMimeSignature *signature = g_mime_signature_list_get_signature (siglist, i);
420
421         if (i > 0)
422             printf (", ");
423
424         printf ("{");
425
426         /* status */
427         GMimeSignatureStatus status = g_mime_signature_get_status (signature);
428         printf ("\"status\": %s",
429                 json_quote_str (ctx_quote,
430                                 signature_status_to_string (status)));
431
432         GMimeCertificate *certificate = g_mime_signature_get_certificate (signature);
433         if (status == GMIME_SIGNATURE_STATUS_GOOD) {
434             if (certificate)
435                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, g_mime_certificate_get_fingerprint (certificate)));
436             /* these dates are seconds since the epoch; should we
437              * provide a more human-readable format string? */
438             time_t created = g_mime_signature_get_created (signature);
439             if (created != -1)
440                 printf (", \"created\": %d", (int) created);
441             time_t expires = g_mime_signature_get_expires (signature);
442             if (expires > 0)
443                 printf (", \"expires\": %d", (int) expires);
444             /* output user id only if validity is FULL or ULTIMATE. */
445             /* note that gmime is using the term "trust" here, which
446              * is WRONG.  It's actually user id "validity". */
447             if (certificate) {
448                 const char *name = g_mime_certificate_get_name (certificate);
449                 GMimeCertificateTrust trust = g_mime_certificate_get_trust (certificate);
450                 if (name && (trust == GMIME_CERTIFICATE_TRUST_FULLY || trust == GMIME_CERTIFICATE_TRUST_ULTIMATE))
451                     printf (", \"userid\": %s", json_quote_str (ctx_quote, name));
452             }
453         } else if (certificate) {
454             const char *key_id = g_mime_certificate_get_key_id (certificate);
455             if (key_id)
456                 printf (", \"keyid\": %s", json_quote_str (ctx_quote, key_id));
457         }
458
459         GMimeSignatureError errors = g_mime_signature_get_errors (signature);
460         if (errors != GMIME_SIGNATURE_ERROR_NONE) {
461             printf (", \"errors\": %d", errors);
462         }
463
464         printf ("}");
465      }
466
467     printf ("]");
468
469     talloc_free (ctx_quote);
470 }
471 #else
472 static void
473 format_part_sigstatus_json (const GMimeSignatureValidity* validity)
474 {
475     printf (", \"sigstatus\": [");
476
477     if (!validity) {
478         printf ("]");
479         return;
480     }
481
482     const GMimeSigner *signer = g_mime_signature_validity_get_signers (validity);
483     int first = 1;
484     void *ctx_quote = talloc_new (NULL);
485
486     while (signer) {
487         if (first)
488             first = 0;
489         else
490             printf (", ");
491
492         printf ("{");
493
494         /* status */
495         printf ("\"status\": %s",
496                 json_quote_str (ctx_quote,
497                                 signer_status_to_string (signer->status)));
498
499         if (signer->status == GMIME_SIGNER_STATUS_GOOD)
500         {
501             if (signer->fingerprint)
502                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, signer->fingerprint));
503             /* these dates are seconds since the epoch; should we
504              * provide a more human-readable format string? */
505             if (signer->created)
506                 printf (", \"created\": %d", (int) signer->created);
507             if (signer->expires)
508                 printf (", \"expires\": %d", (int) signer->expires);
509             /* output user id only if validity is FULL or ULTIMATE. */
510             /* note that gmime is using the term "trust" here, which
511              * is WRONG.  It's actually user id "validity". */
512             if ((signer->name) && (signer->trust)) {
513                 if ((signer->trust == GMIME_SIGNER_TRUST_FULLY) || (signer->trust == GMIME_SIGNER_TRUST_ULTIMATE))
514                     printf (", \"userid\": %s", json_quote_str (ctx_quote, signer->name));
515            }
516        } else {
517            if (signer->keyid)
518                printf (", \"keyid\": %s", json_quote_str (ctx_quote, signer->keyid));
519        }
520        if (signer->errors != GMIME_SIGNER_ERROR_NONE) {
521            printf (", \"errors\": %d", signer->errors);
522        }
523
524        printf ("}");
525        signer = signer->next;
526     }
527
528     printf ("]");
529
530     talloc_free (ctx_quote);
531 }
532 #endif
533
534 static void
535 format_part_content_raw (GMimeObject *part)
536 {
537     if (! GMIME_IS_PART (part))
538         return;
539
540     GMimeStream *stream_stdout;
541     GMimeStream *stream_filter = NULL;
542     GMimeDataWrapper *wrapper;
543
544     stream_stdout = g_mime_stream_file_new (stdout);
545     g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
546
547     stream_filter = g_mime_stream_filter_new (stream_stdout);
548
549     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
550
551     if (wrapper && stream_filter)
552         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
553
554     if (stream_filter)
555         g_object_unref (stream_filter);
556
557     if (stream_stdout)
558         g_object_unref(stream_stdout);
559 }
560
561 static void
562 format_part_text (const void *ctx, mime_node_t *node,
563                   int indent, const notmuch_show_params_t *params)
564 {
565     /* The disposition and content-type metadata are associated with
566      * the envelope for message parts */
567     GMimeObject *meta = node->envelope_part ?
568         GMIME_OBJECT (node->envelope_part) : node->part;
569     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
570     const notmuch_bool_t leaf = GMIME_IS_PART (node->part);
571     const char *part_type;
572     int i;
573
574     if (node->envelope_file) {
575         notmuch_message_t *message = node->envelope_file;
576
577         part_type = "message";
578         printf ("\f%s{ id:%s depth:%d match:%d filename:%s\n",
579                 part_type,
580                 notmuch_message_get_message_id (message),
581                 indent,
582                 notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH),
583                 notmuch_message_get_filename (message));
584     } else {
585         GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (meta);
586         const char *cid = g_mime_object_get_content_id (meta);
587         const char *filename = leaf ?
588             g_mime_part_get_filename (GMIME_PART (node->part)) : NULL;
589
590         if (disposition &&
591             strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
592             part_type = "attachment";
593         else
594             part_type = "part";
595
596         printf ("\f%s{ ID: %d", part_type, node->part_num);
597         if (filename)
598             printf (", Filename: %s", filename);
599         if (cid)
600             printf (", Content-id: %s", cid);
601         printf (", Content-type: %s\n", g_mime_content_type_to_string (content_type));
602     }
603
604     if (GMIME_IS_MESSAGE (node->part)) {
605         GMimeMessage *message = GMIME_MESSAGE (node->part);
606         InternetAddressList *recipients;
607         const char *recipients_string;
608
609         printf ("\fheader{\n");
610         if (node->envelope_file)
611             printf ("%s\n", _get_one_line_summary (ctx, node->envelope_file));
612         printf ("Subject: %s\n", g_mime_message_get_subject (message));
613         printf ("From: %s\n", g_mime_message_get_sender (message));
614         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
615         recipients_string = internet_address_list_to_string (recipients, 0);
616         if (recipients_string)
617             printf ("To: %s\n", recipients_string);
618         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
619         recipients_string = internet_address_list_to_string (recipients, 0);
620         if (recipients_string)
621             printf ("Cc: %s\n", recipients_string);
622         printf ("Date: %s\n", g_mime_message_get_date_as_string (message));
623         printf ("\fheader}\n");
624
625         printf ("\fbody{\n");
626     }
627
628     if (leaf) {
629         if (g_mime_content_type_is_type (content_type, "text", "*") &&
630             !g_mime_content_type_is_type (content_type, "text", "html"))
631         {
632             GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
633             g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
634             show_text_part_content (node->part, stream_stdout);
635             g_object_unref(stream_stdout);
636         } else {
637             printf ("Non-text part: %s\n",
638                     g_mime_content_type_to_string (content_type));
639         }
640     }
641
642     for (i = 0; i < node->nchildren; i++)
643         format_part_text (ctx, mime_node_child (node, i), indent, params);
644
645     if (GMIME_IS_MESSAGE (node->part))
646         printf ("\fbody}\n");
647
648     printf ("\f%s}\n", part_type);
649 }
650
651 static void
652 format_part_json (const void *ctx, mime_node_t *node, notmuch_bool_t first)
653 {
654     /* Any changes to the JSON format should be reflected in the file
655      * devel/schemata. */
656
657     if (node->envelope_file) {
658         printf ("{");
659         format_message_json (ctx, node->envelope_file);
660
661         printf ("\"headers\": {");
662         format_headers_json (ctx, GMIME_MESSAGE (node->part));
663         printf ("}");
664
665         printf (", \"body\": [");
666         format_part_json (ctx, mime_node_child (node, 0), first);
667
668         printf ("]}");
669         return;
670     }
671
672     void *local = talloc_new (ctx);
673     /* The disposition and content-type metadata are associated with
674      * the envelope for message parts */
675     GMimeObject *meta = node->envelope_part ?
676         GMIME_OBJECT (node->envelope_part) : node->part;
677     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
678     GMimeStream *stream_memory = g_mime_stream_mem_new ();
679     const char *cid = g_mime_object_get_content_id (meta);
680     GByteArray *part_content;
681     int i;
682
683     if (!first)
684         printf (", ");
685
686     printf ("{\"id\": %d", node->part_num);
687
688     if (node->decrypt_attempted) {
689         printf (", \"encstatus\": [{\"status\": ");
690         if (node->decrypt_success) {
691             printf ("\"good\"");
692         } else {
693             printf ("\"bad\"");
694         }
695         printf ("}]");
696     }
697
698     if (node->verify_attempted) {
699 #ifdef GMIME_ATLEAST_26
700         format_part_sigstatus_json (node->sig_list);
701 #else
702         format_part_sigstatus_json (node->sig_validity);
703 #endif
704     }
705
706     printf (", \"content-type\": %s",
707             json_quote_str (local, g_mime_content_type_to_string (content_type)));
708
709     if (cid != NULL)
710             printf(", \"content-id\": %s", json_quote_str (local, cid));
711
712     if (GMIME_IS_PART (node->part)) {
713         const char *filename = g_mime_part_get_filename (GMIME_PART (node->part));
714         if (filename)
715             printf (", \"filename\": %s", json_quote_str (local, filename));
716     }
717
718     if (g_mime_content_type_is_type (content_type, "text", "*")) {
719         /* For non-HTML text parts, we include the content in the
720          * JSON. Since JSON must be Unicode, we handle charset
721          * decoding here and do not report a charset to the caller.
722          * For text/html parts, we do not include the content. If a
723          * caller is interested in text/html parts, it should retrieve
724          * them separately and they will not be decoded. Since this
725          * makes charset decoding the responsibility on the caller, we
726          * report the charset for text/html parts.
727          */
728         if (g_mime_content_type_is_type (content_type, "text", "html")) {
729             const char *content_charset = g_mime_object_get_content_type_parameter (meta, "charset");
730
731             if (content_charset != NULL)
732                 printf (", \"content-charset\": %s", json_quote_str (local, content_charset));
733         } else {
734             show_text_part_content (node->part, stream_memory);
735             part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
736
737             printf (", \"content\": %s", json_quote_chararray (local, (char *) part_content->data, part_content->len));
738         }
739     } else if (g_mime_content_type_is_type (content_type, "multipart", "*")) {
740         printf (", \"content\": [");
741     } else if (g_mime_content_type_is_type (content_type, "message", "rfc822")) {
742         printf (", \"content\": [{");
743     }
744
745     if (stream_memory)
746         g_object_unref (stream_memory);
747
748     if (GMIME_IS_MESSAGE (node->part)) {
749         printf ("\"headers\": {");
750         format_headers_json (local, GMIME_MESSAGE (node->part));
751         printf ("}");
752
753         printf (", \"body\": [");
754     }
755
756     for (i = 0; i < node->nchildren; i++)
757         format_part_json (ctx, mime_node_child (node, i), i == 0);
758
759     if (GMIME_IS_MESSAGE (node->part))
760         printf ("]");
761
762     if (g_mime_content_type_is_type (content_type, "multipart", "*"))
763         printf ("]");
764     else if (g_mime_content_type_is_type (content_type, "message", "rfc822"))
765         printf ("}]");
766
767     printf ("}");
768
769     talloc_free (local);
770 }
771
772 static void
773 format_part_json_entry (const void *ctx, mime_node_t *node, unused (int indent),
774                         unused (const notmuch_show_params_t *params))
775 {
776     format_part_json (ctx, node, TRUE);
777 }
778
779 static void
780 show_message (void *ctx,
781               const notmuch_show_format_t *format,
782               notmuch_message_t *message,
783               int indent,
784               notmuch_show_params_t *params)
785 {
786     if (format->part) {
787         void *local = talloc_new (ctx);
788         mime_node_t *root, *part;
789
790         if (mime_node_open (local, message, params->cryptoctx, params->decrypt,
791                             &root) == NOTMUCH_STATUS_SUCCESS &&
792             (part = mime_node_seek_dfs (root, (params->part < 0 ?
793                                                0 : params->part))))
794             format->part (local, part, indent, params);
795         talloc_free (local);
796         return;
797     }
798
799     if (params->part <= 0) {
800         fputs (format->message_start, stdout);
801         if (format->message)
802             format->message(ctx, message, indent);
803
804         fputs (format->header_start, stdout);
805         if (format->header)
806             format->header(ctx, message);
807         fputs (format->header_end, stdout);
808
809         fputs (format->body_start, stdout);
810     }
811
812     if (format->part_content)
813         show_message_body (message, format, params);
814
815     if (params->part <= 0) {
816         fputs (format->body_end, stdout);
817
818         fputs (format->message_end, stdout);
819     }
820 }
821
822 static void
823 show_messages (void *ctx,
824                const notmuch_show_format_t *format,
825                notmuch_messages_t *messages,
826                int indent,
827                notmuch_show_params_t *params)
828 {
829     notmuch_message_t *message;
830     notmuch_bool_t match;
831     int first_set = 1;
832     int next_indent;
833
834     fputs (format->message_set_start, stdout);
835
836     for (;
837          notmuch_messages_valid (messages);
838          notmuch_messages_move_to_next (messages))
839     {
840         if (!first_set)
841             fputs (format->message_set_sep, stdout);
842         first_set = 0;
843
844         fputs (format->message_set_start, stdout);
845
846         message = notmuch_messages_get (messages);
847
848         match = notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
849
850         next_indent = indent;
851
852         if (match || params->entire_thread) {
853             show_message (ctx, format, message, indent, params);
854             next_indent = indent + 1;
855
856             fputs (format->message_set_sep, stdout);
857         }
858
859         show_messages (ctx,
860                        format,
861                        notmuch_message_get_replies (message),
862                        next_indent,
863                        params);
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
873 /* Formatted output of single message */
874 static int
875 do_show_single (void *ctx,
876                 notmuch_query_t *query,
877                 const notmuch_show_format_t *format,
878                 notmuch_show_params_t *params)
879 {
880     notmuch_messages_t *messages;
881     notmuch_message_t *message;
882
883     if (notmuch_query_count_messages (query) != 1) {
884         fprintf (stderr, "Error: search term did not match precisely one message.\n");
885         return 1;
886     }
887
888     messages = notmuch_query_search_messages (query);
889     message = notmuch_messages_get (messages);
890
891     if (message == NULL) {
892         fprintf (stderr, "Error: Cannot find matching message.\n");
893         return 1;
894     }
895
896     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
897
898     /* Special case for --format=raw of full single message, just cat out file */
899     if (params->raw && 0 == params->part) {
900
901         const char *filename;
902         FILE *file;
903         size_t size;
904         char buf[4096];
905
906         filename = notmuch_message_get_filename (message);
907         if (filename == NULL) {
908             fprintf (stderr, "Error: Cannot message filename.\n");
909             return 1;
910         }
911
912         file = fopen (filename, "r");
913         if (file == NULL) {
914             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
915             return 1;
916         }
917
918         while (!feof (file)) {
919             size = fread (buf, 1, sizeof (buf), file);
920             if (ferror (file)) {
921                 fprintf (stderr, "Error: Read failed from %s\n", filename);
922                 fclose (file);
923                 return 1;
924             }
925
926             if (fwrite (buf, size, 1, stdout) != 1) {
927                 fprintf (stderr, "Error: Write failed\n");
928                 fclose (file);
929                 return 1;
930             }
931         }
932
933         fclose (file);
934
935     } else {
936
937         show_message (ctx, format, message, 0, params);
938
939     }
940
941     return 0;
942 }
943
944 /* Formatted output of threads */
945 static int
946 do_show (void *ctx,
947          notmuch_query_t *query,
948          const notmuch_show_format_t *format,
949          notmuch_show_params_t *params)
950 {
951     notmuch_threads_t *threads;
952     notmuch_thread_t *thread;
953     notmuch_messages_t *messages;
954     int first_toplevel = 1;
955
956     fputs (format->message_set_start, stdout);
957
958     for (threads = notmuch_query_search_threads (query);
959          notmuch_threads_valid (threads);
960          notmuch_threads_move_to_next (threads))
961     {
962         thread = notmuch_threads_get (threads);
963
964         messages = notmuch_thread_get_toplevel_messages (thread);
965
966         if (messages == NULL)
967             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
968                             notmuch_thread_get_thread_id (thread));
969
970         if (!first_toplevel)
971             fputs (format->message_set_sep, stdout);
972         first_toplevel = 0;
973
974         show_messages (ctx, format, messages, 0, params);
975
976         notmuch_thread_destroy (thread);
977
978     }
979
980     fputs (format->message_set_end, stdout);
981
982     return 0;
983 }
984
985 enum {
986     NOTMUCH_FORMAT_NOT_SPECIFIED,
987     NOTMUCH_FORMAT_JSON,
988     NOTMUCH_FORMAT_TEXT,
989     NOTMUCH_FORMAT_MBOX,
990     NOTMUCH_FORMAT_RAW
991 };
992
993 int
994 notmuch_show_command (void *ctx, unused (int argc), unused (char *argv[]))
995 {
996     notmuch_config_t *config;
997     notmuch_database_t *notmuch;
998     notmuch_query_t *query;
999     char *query_string;
1000     int opt_index, ret;
1001     const notmuch_show_format_t *format = &format_text;
1002     notmuch_show_params_t params = { .part = -1 };
1003     int format_sel = NOTMUCH_FORMAT_NOT_SPECIFIED;
1004     notmuch_bool_t verify = FALSE;
1005
1006     notmuch_opt_desc_t options[] = {
1007         { NOTMUCH_OPT_KEYWORD, &format_sel, "format", 'f',
1008           (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
1009                                   { "text", NOTMUCH_FORMAT_TEXT },
1010                                   { "mbox", NOTMUCH_FORMAT_MBOX },
1011                                   { "raw", NOTMUCH_FORMAT_RAW },
1012                                   { 0, 0 } } },
1013         { NOTMUCH_OPT_INT, &params.part, "part", 'p', 0 },
1014         { NOTMUCH_OPT_BOOLEAN, &params.entire_thread, "entire-thread", 't', 0 },
1015         { NOTMUCH_OPT_BOOLEAN, &params.decrypt, "decrypt", 'd', 0 },
1016         { NOTMUCH_OPT_BOOLEAN, &verify, "verify", 'v', 0 },
1017         { 0, 0, 0, 0, 0 }
1018     };
1019
1020     opt_index = parse_arguments (argc, argv, options, 1);
1021     if (opt_index < 0) {
1022         /* diagnostics already printed */
1023         return 1;
1024     }
1025
1026     if (format_sel == NOTMUCH_FORMAT_NOT_SPECIFIED) {
1027         /* if part was requested and format was not specified, use format=raw */
1028         if (params.part >= 0)
1029             format_sel = NOTMUCH_FORMAT_RAW;
1030         else
1031             format_sel = NOTMUCH_FORMAT_TEXT;
1032     }
1033
1034     switch (format_sel) {
1035     case NOTMUCH_FORMAT_JSON:
1036         format = &format_json;
1037         params.entire_thread = TRUE;
1038         break;
1039     case NOTMUCH_FORMAT_TEXT:
1040         format = &format_text;
1041         break;
1042     case NOTMUCH_FORMAT_MBOX:
1043         if (params.part > 0) {
1044             fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
1045             return 1;
1046         }
1047         format = &format_mbox;
1048         break;
1049     case NOTMUCH_FORMAT_RAW:
1050         format = &format_raw;
1051         /* If --format=raw specified without specifying part, we can only
1052          * output single message, so set part=0 */
1053         if (params.part < 0)
1054             params.part = 0;
1055         params.raw = TRUE;
1056         break;
1057     }
1058
1059     if (params.decrypt || verify) {
1060 #ifdef GMIME_ATLEAST_26
1061         /* TODO: GMimePasswordRequestFunc */
1062         params.cryptoctx = g_mime_gpg_context_new (NULL, "gpg");
1063 #else
1064         GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
1065         params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
1066 #endif
1067         if (params.cryptoctx) {
1068             g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
1069         } else {
1070             params.decrypt = FALSE;
1071             fprintf (stderr, "Failed to construct gpg context.\n");
1072         }
1073 #ifndef GMIME_ATLEAST_26
1074         g_object_unref (session);
1075 #endif
1076     }
1077
1078     config = notmuch_config_open (ctx, NULL, NULL);
1079     if (config == NULL)
1080         return 1;
1081
1082     query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
1083     if (query_string == NULL) {
1084         fprintf (stderr, "Out of memory\n");
1085         return 1;
1086     }
1087
1088     if (*query_string == '\0') {
1089         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
1090         return 1;
1091     }
1092
1093     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
1094                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
1095     if (notmuch == NULL)
1096         return 1;
1097
1098     query = notmuch_query_create (notmuch, query_string);
1099     if (query == NULL) {
1100         fprintf (stderr, "Out of memory\n");
1101         return 1;
1102     }
1103
1104     if (params.part >= 0)
1105         ret = do_show_single (ctx, query, format, &params);
1106     else
1107         ret = do_show (ctx, query, format, &params);
1108
1109     notmuch_query_destroy (query);
1110     notmuch_database_close (notmuch);
1111
1112     if (params.cryptoctx)
1113         g_object_unref(params.cryptoctx);
1114
1115     return ret;
1116 }