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