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