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