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