]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
show: Move format_message_mbox with the other new-style formats
[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 static void
224 format_headers_message_part_text (GMimeMessage *message)
225 {
226     InternetAddressList *recipients;
227     const char *recipients_string;
228
229     printf ("Subject: %s\n", g_mime_message_get_subject (message));
230     printf ("From: %s\n", g_mime_message_get_sender (message));
231     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
232     recipients_string = internet_address_list_to_string (recipients, 0);
233     if (recipients_string)
234         printf ("To: %s\n",
235                 recipients_string);
236     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
237     recipients_string = internet_address_list_to_string (recipients, 0);
238     if (recipients_string)
239         printf ("Cc: %s\n",
240                 recipients_string);
241     printf ("Date: %s\n", g_mime_message_get_date_as_string (message));
242 }
243
244 static void
245 format_headers_json (const void *ctx, GMimeMessage *message)
246 {
247     void *local = talloc_new (ctx);
248     InternetAddressList *recipients;
249     const char *recipients_string;
250
251     printf ("{%s: %s",
252             json_quote_str (local, "Subject"),
253             json_quote_str (local, g_mime_message_get_subject (message)));
254     printf (", %s: %s",
255             json_quote_str (local, "From"),
256             json_quote_str (local, g_mime_message_get_sender (message)));
257     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
258     recipients_string = internet_address_list_to_string (recipients, 0);
259     if (recipients_string)
260         printf (", %s: %s",
261                 json_quote_str (local, "To"),
262                 json_quote_str (local, recipients_string));
263     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
264     recipients_string = internet_address_list_to_string (recipients, 0);
265     if (recipients_string)
266         printf (", %s: %s",
267                 json_quote_str (local, "Cc"),
268                 json_quote_str (local, recipients_string));
269     printf (", %s: %s}",
270             json_quote_str (local, "Date"),
271             json_quote_str (local, g_mime_message_get_date_as_string (message)));
272
273     talloc_free (local);
274 }
275
276 /* Write a MIME text part out to the given stream.
277  *
278  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
279  * UTF-8) will be performed, so it is inappropriate to call this
280  * function with a non-text part. Doing so will trigger an internal
281  * error.
282  */
283 static void
284 show_text_part_content (GMimeObject *part, GMimeStream *stream_out)
285 {
286     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
287     GMimeStream *stream_filter = NULL;
288     GMimeDataWrapper *wrapper;
289     const char *charset;
290
291     if (! g_mime_content_type_is_type (content_type, "text", "*"))
292         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
293                         g_mime_content_type_to_string (content_type));
294
295     if (stream_out == NULL)
296         return;
297
298     stream_filter = g_mime_stream_filter_new (stream_out);
299     g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
300                              g_mime_filter_crlf_new (FALSE, FALSE));
301
302     charset = g_mime_object_get_content_type_parameter (part, "charset");
303     if (charset) {
304         GMimeFilter *charset_filter;
305         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
306         /* This result can be NULL for things like "unknown-8bit".
307          * Don't set a NULL filter as that makes GMime print
308          * annoying assertion-failure messages on stderr. */
309         if (charset_filter) {
310             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
311                                       charset_filter);
312             g_object_unref (charset_filter);
313         }
314
315     }
316
317     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
318     if (wrapper && stream_filter)
319         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
320     if (stream_filter)
321         g_object_unref(stream_filter);
322 }
323
324 #ifdef GMIME_ATLEAST_26
325 static const char*
326 signature_status_to_string (GMimeSignatureStatus x)
327 {
328     switch (x) {
329     case GMIME_SIGNATURE_STATUS_GOOD:
330         return "good";
331     case GMIME_SIGNATURE_STATUS_BAD:
332         return "bad";
333     case GMIME_SIGNATURE_STATUS_ERROR:
334         return "error";
335     }
336     return "unknown";
337 }
338 #else
339 static const char*
340 signer_status_to_string (GMimeSignerStatus x)
341 {
342     switch (x) {
343     case GMIME_SIGNER_STATUS_NONE:
344         return "none";
345     case GMIME_SIGNER_STATUS_GOOD:
346         return "good";
347     case GMIME_SIGNER_STATUS_BAD:
348         return "bad";
349     case GMIME_SIGNER_STATUS_ERROR:
350         return "error";
351     }
352     return "unknown";
353 }
354 #endif
355
356 #ifdef GMIME_ATLEAST_26
357 static void
358 format_part_sigstatus_json (mime_node_t *node)
359 {
360     GMimeSignatureList *siglist = node->sig_list;
361
362     printf ("[");
363
364     if (!siglist) {
365         printf ("]");
366         return;
367     }
368
369     void *ctx_quote = talloc_new (NULL);
370     int i;
371     for (i = 0; i < g_mime_signature_list_length (siglist); i++) {
372         GMimeSignature *signature = g_mime_signature_list_get_signature (siglist, i);
373
374         if (i > 0)
375             printf (", ");
376
377         printf ("{");
378
379         /* status */
380         GMimeSignatureStatus status = g_mime_signature_get_status (signature);
381         printf ("\"status\": %s",
382                 json_quote_str (ctx_quote,
383                                 signature_status_to_string (status)));
384
385         GMimeCertificate *certificate = g_mime_signature_get_certificate (signature);
386         if (status == GMIME_SIGNATURE_STATUS_GOOD) {
387             if (certificate)
388                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, g_mime_certificate_get_fingerprint (certificate)));
389             /* these dates are seconds since the epoch; should we
390              * provide a more human-readable format string? */
391             time_t created = g_mime_signature_get_created (signature);
392             if (created != -1)
393                 printf (", \"created\": %d", (int) created);
394             time_t expires = g_mime_signature_get_expires (signature);
395             if (expires > 0)
396                 printf (", \"expires\": %d", (int) expires);
397             /* output user id only if validity is FULL or ULTIMATE. */
398             /* note that gmime is using the term "trust" here, which
399              * is WRONG.  It's actually user id "validity". */
400             if (certificate) {
401                 const char *name = g_mime_certificate_get_name (certificate);
402                 GMimeCertificateTrust trust = g_mime_certificate_get_trust (certificate);
403                 if (name && (trust == GMIME_CERTIFICATE_TRUST_FULLY || trust == GMIME_CERTIFICATE_TRUST_ULTIMATE))
404                     printf (", \"userid\": %s", json_quote_str (ctx_quote, name));
405             }
406         } else if (certificate) {
407             const char *key_id = g_mime_certificate_get_key_id (certificate);
408             if (key_id)
409                 printf (", \"keyid\": %s", json_quote_str (ctx_quote, key_id));
410         }
411
412         GMimeSignatureError errors = g_mime_signature_get_errors (signature);
413         if (errors != GMIME_SIGNATURE_ERROR_NONE) {
414             printf (", \"errors\": %d", errors);
415         }
416
417         printf ("}");
418      }
419
420     printf ("]");
421
422     talloc_free (ctx_quote);
423 }
424 #else
425 static void
426 format_part_sigstatus_json (mime_node_t *node)
427 {
428     const GMimeSignatureValidity* validity = node->sig_validity;
429
430     printf ("[");
431
432     if (!validity) {
433         printf ("]");
434         return;
435     }
436
437     const GMimeSigner *signer = g_mime_signature_validity_get_signers (validity);
438     int first = 1;
439     void *ctx_quote = talloc_new (NULL);
440
441     while (signer) {
442         if (first)
443             first = 0;
444         else
445             printf (", ");
446
447         printf ("{");
448
449         /* status */
450         printf ("\"status\": %s",
451                 json_quote_str (ctx_quote,
452                                 signer_status_to_string (signer->status)));
453
454         if (signer->status == GMIME_SIGNER_STATUS_GOOD)
455         {
456             if (signer->fingerprint)
457                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, signer->fingerprint));
458             /* these dates are seconds since the epoch; should we
459              * provide a more human-readable format string? */
460             if (signer->created)
461                 printf (", \"created\": %d", (int) signer->created);
462             if (signer->expires)
463                 printf (", \"expires\": %d", (int) signer->expires);
464             /* output user id only if validity is FULL or ULTIMATE. */
465             /* note that gmime is using the term "trust" here, which
466              * is WRONG.  It's actually user id "validity". */
467             if ((signer->name) && (signer->trust)) {
468                 if ((signer->trust == GMIME_SIGNER_TRUST_FULLY) || (signer->trust == GMIME_SIGNER_TRUST_ULTIMATE))
469                     printf (", \"userid\": %s", json_quote_str (ctx_quote, signer->name));
470            }
471        } else {
472            if (signer->keyid)
473                printf (", \"keyid\": %s", json_quote_str (ctx_quote, signer->keyid));
474        }
475        if (signer->errors != GMIME_SIGNER_ERROR_NONE) {
476            printf (", \"errors\": %d", signer->errors);
477        }
478
479        printf ("}");
480        signer = signer->next;
481     }
482
483     printf ("]");
484
485     talloc_free (ctx_quote);
486 }
487 #endif
488
489 static void
490 format_part_content_raw (GMimeObject *part)
491 {
492     if (! GMIME_IS_PART (part))
493         return;
494
495     GMimeStream *stream_stdout;
496     GMimeStream *stream_filter = NULL;
497     GMimeDataWrapper *wrapper;
498
499     stream_stdout = g_mime_stream_file_new (stdout);
500     g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
501
502     stream_filter = g_mime_stream_filter_new (stream_stdout);
503
504     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
505
506     if (wrapper && stream_filter)
507         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
508
509     if (stream_filter)
510         g_object_unref (stream_filter);
511
512     if (stream_stdout)
513         g_object_unref(stream_stdout);
514 }
515
516 static notmuch_status_t
517 format_part_text (const void *ctx, mime_node_t *node,
518                   int indent, const notmuch_show_params_t *params)
519 {
520     /* The disposition and content-type metadata are associated with
521      * the envelope for message parts */
522     GMimeObject *meta = node->envelope_part ?
523         GMIME_OBJECT (node->envelope_part) : node->part;
524     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
525     const notmuch_bool_t leaf = GMIME_IS_PART (node->part);
526     const char *part_type;
527     int i;
528
529     if (node->envelope_file) {
530         notmuch_message_t *message = node->envelope_file;
531
532         part_type = "message";
533         printf ("\f%s{ id:%s depth:%d match:%d excluded:%d filename:%s\n",
534                 part_type,
535                 notmuch_message_get_message_id (message),
536                 indent,
537                 notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? 1 : 0,
538                 notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED) ? 1 : 0,
539                 notmuch_message_get_filename (message));
540     } else {
541         GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (meta);
542         const char *cid = g_mime_object_get_content_id (meta);
543         const char *filename = leaf ?
544             g_mime_part_get_filename (GMIME_PART (node->part)) : NULL;
545
546         if (disposition &&
547             strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
548             part_type = "attachment";
549         else
550             part_type = "part";
551
552         printf ("\f%s{ ID: %d", part_type, node->part_num);
553         if (filename)
554             printf (", Filename: %s", filename);
555         if (cid)
556             printf (", Content-id: %s", cid);
557         printf (", Content-type: %s\n", g_mime_content_type_to_string (content_type));
558     }
559
560     if (GMIME_IS_MESSAGE (node->part)) {
561         GMimeMessage *message = GMIME_MESSAGE (node->part);
562         InternetAddressList *recipients;
563         const char *recipients_string;
564
565         printf ("\fheader{\n");
566         if (node->envelope_file)
567             printf ("%s\n", _get_one_line_summary (ctx, node->envelope_file));
568         printf ("Subject: %s\n", g_mime_message_get_subject (message));
569         printf ("From: %s\n", g_mime_message_get_sender (message));
570         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
571         recipients_string = internet_address_list_to_string (recipients, 0);
572         if (recipients_string)
573             printf ("To: %s\n", recipients_string);
574         recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
575         recipients_string = internet_address_list_to_string (recipients, 0);
576         if (recipients_string)
577             printf ("Cc: %s\n", recipients_string);
578         printf ("Date: %s\n", g_mime_message_get_date_as_string (message));
579         printf ("\fheader}\n");
580
581         printf ("\fbody{\n");
582     }
583
584     if (leaf) {
585         if (g_mime_content_type_is_type (content_type, "text", "*") &&
586             !g_mime_content_type_is_type (content_type, "text", "html"))
587         {
588             GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
589             g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
590             show_text_part_content (node->part, stream_stdout);
591             g_object_unref(stream_stdout);
592         } else {
593             printf ("Non-text part: %s\n",
594                     g_mime_content_type_to_string (content_type));
595         }
596     }
597
598     for (i = 0; i < node->nchildren; i++)
599         format_part_text (ctx, mime_node_child (node, i), indent, params);
600
601     if (GMIME_IS_MESSAGE (node->part))
602         printf ("\fbody}\n");
603
604     printf ("\f%s}\n", part_type);
605
606     return NOTMUCH_STATUS_SUCCESS;
607 }
608
609 static void
610 format_part_json (const void *ctx, mime_node_t *node, notmuch_bool_t first)
611 {
612     /* Any changes to the JSON format should be reflected in the file
613      * devel/schemata. */
614
615     if (node->envelope_file) {
616         printf ("{");
617         format_message_json (ctx, node->envelope_file);
618
619         printf ("\"headers\": ");
620         format_headers_json (ctx, GMIME_MESSAGE (node->part));
621
622         printf (", \"body\": [");
623         format_part_json (ctx, mime_node_child (node, 0), first);
624
625         printf ("]}");
626         return;
627     }
628
629     void *local = talloc_new (ctx);
630     /* The disposition and content-type metadata are associated with
631      * the envelope for message parts */
632     GMimeObject *meta = node->envelope_part ?
633         GMIME_OBJECT (node->envelope_part) : node->part;
634     GMimeContentType *content_type = g_mime_object_get_content_type (meta);
635     const char *cid = g_mime_object_get_content_id (meta);
636     const char *filename = GMIME_IS_PART (node->part) ?
637         g_mime_part_get_filename (GMIME_PART (node->part)) : NULL;
638     const char *terminator = "";
639     int i;
640
641     if (!first)
642         printf (", ");
643
644     printf ("{\"id\": %d", node->part_num);
645
646     if (node->decrypt_attempted)
647         printf (", \"encstatus\": [{\"status\": \"%s\"}]",
648                 node->decrypt_success ? "good" : "bad");
649
650     if (node->verify_attempted) {
651         printf (", \"sigstatus\": ");
652         format_part_sigstatus_json (node);
653     }
654
655     printf (", \"content-type\": %s",
656             json_quote_str (local, g_mime_content_type_to_string (content_type)));
657
658     if (cid)
659         printf (", \"content-id\": %s", json_quote_str (local, cid));
660
661     if (filename)
662         printf (", \"filename\": %s", json_quote_str (local, filename));
663
664     if (GMIME_IS_PART (node->part)) {
665         /* For non-HTML text parts, we include the content in the
666          * JSON. Since JSON must be Unicode, we handle charset
667          * decoding here and do not report a charset to the caller.
668          * For text/html parts, we do not include the content. If a
669          * caller is interested in text/html parts, it should retrieve
670          * them separately and they will not be decoded. Since this
671          * makes charset decoding the responsibility on the caller, we
672          * report the charset for text/html parts.
673          */
674         if (g_mime_content_type_is_type (content_type, "text", "html")) {
675             const char *content_charset = g_mime_object_get_content_type_parameter (meta, "charset");
676
677             if (content_charset != NULL)
678                 printf (", \"content-charset\": %s", json_quote_str (local, content_charset));
679         } else if (g_mime_content_type_is_type (content_type, "text", "*")) {
680             GMimeStream *stream_memory = g_mime_stream_mem_new ();
681             GByteArray *part_content;
682             show_text_part_content (node->part, stream_memory);
683             part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
684
685             printf (", \"content\": %s", json_quote_chararray (local, (char *) part_content->data, part_content->len));
686             g_object_unref (stream_memory);
687         }
688     } else if (GMIME_IS_MULTIPART (node->part)) {
689         printf (", \"content\": [");
690         terminator = "]";
691     } else if (GMIME_IS_MESSAGE (node->part)) {
692         printf (", \"content\": [{");
693         printf ("\"headers\": ");
694         format_headers_json (local, GMIME_MESSAGE (node->part));
695
696         printf (", \"body\": [");
697         terminator = "]}]";
698     }
699
700     talloc_free (local);
701
702     for (i = 0; i < node->nchildren; i++)
703         format_part_json (ctx, mime_node_child (node, i), i == 0);
704
705     printf ("%s}", terminator);
706 }
707
708 static notmuch_status_t
709 format_part_json_entry (const void *ctx, mime_node_t *node, unused (int indent),
710                         unused (const notmuch_show_params_t *params))
711 {
712     format_part_json (ctx, node, TRUE);
713
714     return NOTMUCH_STATUS_SUCCESS;
715 }
716
717 /* Print a message in "mboxrd" format as documented, for example,
718  * here:
719  *
720  * http://qmail.org/qmail-manual-html/man5/mbox.html
721  */
722 static void
723 format_message_mbox (const void *ctx,
724                      notmuch_message_t *message,
725                      unused (int indent))
726 {
727     const char *filename;
728     FILE *file;
729     const char *from;
730
731     time_t date;
732     struct tm date_gmtime;
733     char date_asctime[26];
734
735     char *line = NULL;
736     size_t line_size;
737     ssize_t line_len;
738
739     filename = notmuch_message_get_filename (message);
740     file = fopen (filename, "r");
741     if (file == NULL) {
742         fprintf (stderr, "Failed to open %s: %s\n",
743                  filename, strerror (errno));
744         return;
745     }
746
747     from = notmuch_message_get_header (message, "from");
748     from = _extract_email_address (ctx, from);
749
750     date = notmuch_message_get_date (message);
751     gmtime_r (&date, &date_gmtime);
752     asctime_r (&date_gmtime, date_asctime);
753
754     printf ("From %s %s", from, date_asctime);
755
756     while ((line_len = getline (&line, &line_size, file)) != -1 ) {
757         if (_is_from_line (line))
758             putchar ('>');
759         printf ("%s", line);
760     }
761
762     printf ("\n");
763
764     fclose (file);
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 }