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