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