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