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