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