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