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