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