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