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