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