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