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