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