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