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