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