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