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