]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
Add signature verification of PGP/MIME-signed parts with --verify.
[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
23 static void
24 format_message_text (unused (const void *ctx),
25                      notmuch_message_t *message,
26                      int indent);
27 static void
28 format_headers_text (const void *ctx,
29                      notmuch_message_t *message);
30
31 static void
32 format_part_start_text (GMimeObject *part,
33                         int *part_count);
34
35 static void
36 format_part_content_text (GMimeObject *part);
37
38 static void
39 format_part_end_text (GMimeObject *part);
40
41 static const notmuch_show_format_t format_text = {
42     "",
43         "\fmessage{ ", format_message_text,
44             "\fheader{\n", format_headers_text, "\fheader}\n",
45             "\fbody{\n",
46                 format_part_start_text,
47                 NULL,
48                 format_part_content_text,
49                 format_part_end_text,
50                 "",
51             "\fbody}\n",
52         "\fmessage}\n", "",
53     ""
54 };
55
56 static void
57 format_message_json (const void *ctx,
58                      notmuch_message_t *message,
59                      unused (int indent));
60 static void
61 format_headers_json (const void *ctx,
62                      notmuch_message_t *message);
63
64 static void
65 format_part_start_json (unused (GMimeObject *part),
66                         int *part_count);
67
68 static void
69 format_part_sigstatus_json (const GMimeSignatureValidity* validity);
70
71 static void
72 format_part_content_json (GMimeObject *part);
73
74 static void
75 format_part_end_json (GMimeObject *part);
76
77 static const notmuch_show_format_t format_json = {
78     "[",
79         "{", format_message_json,
80             ", \"headers\": {", format_headers_json, "}",
81             ", \"body\": [",
82                 format_part_start_json,
83                 format_part_sigstatus_json,
84                 format_part_content_json,
85                 format_part_end_json,
86                 ", ",
87             "]",
88         "}", ", ",
89     "]"
90 };
91
92 static void
93 format_message_mbox (const void *ctx,
94                      notmuch_message_t *message,
95                      unused (int indent));
96
97 static const notmuch_show_format_t format_mbox = {
98     "",
99         "", format_message_mbox,
100             "", NULL, "",
101             "",
102                 NULL,
103                 NULL,
104                 NULL,
105                 NULL,
106                 "",
107             "",
108         "", "",
109     ""
110 };
111
112 static void
113 format_part_content_raw (GMimeObject *part);
114
115 static const notmuch_show_format_t format_raw = {
116     "",
117         "", NULL,
118             "", NULL, "",
119             "",
120                 NULL,
121                 NULL,
122                 format_part_content_raw,
123                 NULL,
124                 "",
125             "",
126         "", "",
127     ""
128 };
129
130 static const char *
131 _get_tags_as_string (const void *ctx, notmuch_message_t *message)
132 {
133     notmuch_tags_t *tags;
134     int first = 1;
135     const char *tag;
136     char *result;
137
138     result = talloc_strdup (ctx, "");
139     if (result == NULL)
140         return NULL;
141
142     for (tags = notmuch_message_get_tags (message);
143          notmuch_tags_valid (tags);
144          notmuch_tags_move_to_next (tags))
145     {
146         tag = notmuch_tags_get (tags);
147
148         result = talloc_asprintf_append (result, "%s%s",
149                                          first ? "" : " ", tag);
150         first = 0;
151     }
152
153     return result;
154 }
155
156 /* Get a nice, single-line summary of message. */
157 static const char *
158 _get_one_line_summary (const void *ctx, notmuch_message_t *message)
159 {
160     const char *from;
161     time_t date;
162     const char *relative_date;
163     const char *tags;
164
165     from = notmuch_message_get_header (message, "from");
166
167     date = notmuch_message_get_date (message);
168     relative_date = notmuch_time_relative_date (ctx, date);
169
170     tags = _get_tags_as_string (ctx, message);
171
172     return talloc_asprintf (ctx, "%s (%s) (%s)",
173                             from, relative_date, tags);
174 }
175
176 static void
177 format_message_text (unused (const void *ctx), notmuch_message_t *message, int indent)
178 {
179     printf ("id:%s depth:%d match:%d filename:%s\n",
180             notmuch_message_get_message_id (message),
181             indent,
182             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH),
183             notmuch_message_get_filename (message));
184 }
185
186 static void
187 format_message_json (const void *ctx, notmuch_message_t *message, unused (int indent))
188 {
189     notmuch_tags_t *tags;
190     int first = 1;
191     void *ctx_quote = talloc_new (ctx);
192     time_t date;
193     const char *relative_date;
194
195     date = notmuch_message_get_date (message);
196     relative_date = notmuch_time_relative_date (ctx, date);
197
198     printf ("\"id\": %s, \"match\": %s, \"filename\": %s, \"timestamp\": %ld, \"date_relative\": \"%s\", \"tags\": [",
199             json_quote_str (ctx_quote, notmuch_message_get_message_id (message)),
200             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? "true" : "false",
201             json_quote_str (ctx_quote, notmuch_message_get_filename (message)),
202             date, relative_date);
203
204     for (tags = notmuch_message_get_tags (message);
205          notmuch_tags_valid (tags);
206          notmuch_tags_move_to_next (tags))
207     {
208          printf("%s%s", first ? "" : ",",
209                json_quote_str (ctx_quote, notmuch_tags_get (tags)));
210          first = 0;
211     }
212     printf("]");
213     talloc_free (ctx_quote);
214 }
215
216 /* Extract just the email address from the contents of a From:
217  * header. */
218 static const char *
219 _extract_email_address (const void *ctx, const char *from)
220 {
221     InternetAddressList *addresses;
222     InternetAddress *address;
223     InternetAddressMailbox *mailbox;
224     const char *email = "MAILER-DAEMON";
225
226     addresses = internet_address_list_parse_string (from);
227
228     /* Bail if there is no address here. */
229     if (addresses == NULL || internet_address_list_length (addresses) < 1)
230         goto DONE;
231
232     /* Otherwise, just use the first address. */
233     address = internet_address_list_get_address (addresses, 0);
234
235     /* The From header should never contain an address group rather
236      * than a mailbox. So bail if it does. */
237     if (! INTERNET_ADDRESS_IS_MAILBOX (address))
238         goto DONE;
239
240     mailbox = INTERNET_ADDRESS_MAILBOX (address);
241     email = internet_address_mailbox_get_addr (mailbox);
242     email = talloc_strdup (ctx, email);
243
244   DONE:
245     /* XXX: How to free addresses here? */
246     return email;
247    }
248
249 /* Return 1 if 'line' is an mbox From_ line---that is, a line
250  * beginning with zero or more '>' characters followed by the
251  * characters 'F', 'r', 'o', 'm', and space.
252  *
253  * Any characters at all may appear after that in the line.
254  */
255 static int
256 _is_from_line (const char *line)
257 {
258     const char *s = line;
259
260     if (line == NULL)
261         return 0;
262
263     while (*s == '>')
264         s++;
265
266     if (STRNCMP_LITERAL (s, "From ") == 0)
267         return 1;
268     else
269         return 0;
270 }
271
272 /* Print a message in "mboxrd" format as documented, for example,
273  * here:
274  *
275  * http://qmail.org/qmail-manual-html/man5/mbox.html
276  */
277 static void
278 format_message_mbox (const void *ctx,
279                      notmuch_message_t *message,
280                      unused (int indent))
281 {
282     const char *filename;
283     FILE *file;
284     const char *from;
285
286     time_t date;
287     struct tm date_gmtime;
288     char date_asctime[26];
289
290     char *line = NULL;
291     size_t line_size;
292     ssize_t line_len;
293
294     filename = notmuch_message_get_filename (message);
295     file = fopen (filename, "r");
296     if (file == NULL) {
297         fprintf (stderr, "Failed to open %s: %s\n",
298                  filename, strerror (errno));
299         return;
300     }
301
302     from = notmuch_message_get_header (message, "from");
303     from = _extract_email_address (ctx, from);
304
305     date = notmuch_message_get_date (message);
306     gmtime_r (&date, &date_gmtime);
307     asctime_r (&date_gmtime, date_asctime);
308
309     printf ("From %s %s", from, date_asctime);
310
311     while ((line_len = getline (&line, &line_size, file)) != -1 ) {
312         if (_is_from_line (line))
313             putchar ('>');
314         printf ("%s", line);
315     }
316
317     printf ("\n");
318
319     fclose (file);
320 }
321
322 static void
323 format_headers_text (const void *ctx, notmuch_message_t *message)
324 {
325     const char *headers[] = {
326         "Subject", "From", "To", "Cc", "Bcc", "Date"
327     };
328     const char *name, *value;
329     unsigned int i;
330
331     printf ("%s\n", _get_one_line_summary (ctx, message));
332
333     for (i = 0; i < ARRAY_SIZE (headers); i++) {
334         name = headers[i];
335         value = notmuch_message_get_header (message, name);
336         if (value && strlen (value))
337             printf ("%s: %s\n", name, value);
338     }
339 }
340
341 static void
342 format_headers_json (const void *ctx, notmuch_message_t *message)
343 {
344     const char *headers[] = {
345         "Subject", "From", "To", "Cc", "Bcc", "Date"
346     };
347     const char *name, *value;
348     unsigned int i;
349     int first_header = 1;
350     void *ctx_quote = talloc_new (ctx);
351
352     for (i = 0; i < ARRAY_SIZE (headers); i++) {
353         name = headers[i];
354         value = notmuch_message_get_header (message, name);
355         if (value)
356         {
357             if (!first_header)
358                 fputs (", ", stdout);
359             first_header = 0;
360
361             printf ("%s: %s",
362                     json_quote_str (ctx_quote, name),
363                     json_quote_str (ctx_quote, value));
364         }
365     }
366
367     talloc_free (ctx_quote);
368 }
369
370 static void
371 show_part_content (GMimeObject *part, GMimeStream *stream_out)
372 {
373     GMimeStream *stream_filter = NULL;
374     GMimeDataWrapper *wrapper;
375     const char *charset;
376
377     /* do nothing if this is a multipart */
378     if (GMIME_IS_MULTIPART (part) || GMIME_IS_MESSAGE_PART (part))
379         return;
380
381     charset = g_mime_object_get_content_type_parameter (part, "charset");
382
383     if (stream_out) {
384         stream_filter = g_mime_stream_filter_new (stream_out);
385         g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
386                                  g_mime_filter_crlf_new (FALSE, FALSE));
387         if (charset) {
388             GMimeFilter *charset_filter;
389             charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
390             /* This result can be NULL for things like "unknown-8bit".
391              * Don't set a NULL filter as that makes GMime print
392              * annoying assertion-failure messages on stderr. */
393             if (charset_filter)
394                 g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
395                                           charset_filter);
396         }
397     }
398
399     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
400     if (wrapper && stream_filter)
401         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
402     if (stream_filter)
403         g_object_unref(stream_filter);
404 }
405
406 static const char*
407 signerstatustostring (GMimeSignerStatus x)
408 {
409     switch (x) {
410     case GMIME_SIGNER_STATUS_NONE:
411         return "none";
412     case GMIME_SIGNER_STATUS_GOOD:
413         return "good";
414     case GMIME_SIGNER_STATUS_BAD:
415         return "bad";
416     case GMIME_SIGNER_STATUS_ERROR:
417         return "error";
418     }
419     return "unknown";
420 }
421
422 static void
423 format_part_start_text (GMimeObject *part, int *part_count)
424 {
425     GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (part);
426
427     if (disposition &&
428         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
429     {
430         printf ("\fattachment{ ID: %d", *part_count);
431
432     } else {
433
434         printf ("\fpart{ ID: %d", *part_count);
435     }
436 }
437
438 static void
439 format_part_content_text (GMimeObject *part)
440 {
441     GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (part);
442     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
443     GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
444
445     printf (", Content-type: %s\n", g_mime_content_type_to_string (content_type));
446
447     if (disposition &&
448         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
449     {
450         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
451         printf ("Attachment: %s (%s)\n", filename,
452                 g_mime_content_type_to_string (content_type));
453     }
454
455     if (g_mime_content_type_is_type (content_type, "text", "*") &&
456         !g_mime_content_type_is_type (content_type, "text", "html"))
457     {
458         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
459         show_part_content (part, stream_stdout);
460         g_object_unref(stream_stdout);
461     }
462     else if (g_mime_content_type_is_type (content_type, "multipart", "*") ||
463              g_mime_content_type_is_type (content_type, "message", "rfc822"))
464     {
465         /* Do nothing for multipart since its content will be printed
466          * when recursing. */
467     }
468     else
469     {
470         printf ("Non-text part: %s\n",
471                 g_mime_content_type_to_string (content_type));
472     }
473 }
474
475 static void
476 format_part_end_text (GMimeObject *part)
477 {
478     GMimeContentDisposition *disposition;
479
480     disposition = g_mime_object_get_content_disposition (part);
481     if (disposition &&
482         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
483     {
484         printf ("\fattachment}\n");
485     }
486     else
487     {
488         printf ("\fpart}\n");
489     }
490 }
491
492 static void
493 format_part_start_json (unused (GMimeObject *part), int *part_count)
494 {
495     printf ("{\"id\": %d", *part_count);
496 }
497
498 static void
499 format_part_sigstatus_json (const GMimeSignatureValidity* validity)
500 {
501     printf (", \"sigstatus\": [");
502
503     if (!validity) {
504         printf ("]");
505         return;
506     }
507
508     const GMimeSigner *signer = g_mime_signature_validity_get_signers (validity);
509     int first = 1;
510     void *ctx_quote = talloc_new (NULL);
511
512     while (signer) {
513         if (first)
514             first = 0;
515         else
516             printf (", ");
517
518         printf ("{");
519
520         /* status */
521         printf ("\"status\": %s", json_quote_str (ctx_quote, signerstatustostring(signer->status)));
522
523         if (signer->status == GMIME_SIGNER_STATUS_GOOD)
524         {
525             if (signer->fingerprint)
526                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, signer->fingerprint));
527             /* these dates are seconds since the epoch; should we
528              * provide a more human-readable format string? */
529             if (signer->created)
530                 printf (", \"created\": %d", (int) signer->created);
531             if (signer->expires)
532                 printf (", \"expires\": %d", (int) signer->expires);
533             /* output user id only if validity is FULL or ULTIMATE. */
534             /* note that gmime is using the term "trust" here, which
535              * is WRONG.  It's actually user id "validity". */
536             if ((signer->name) && (signer->trust)) {
537                 if ((signer->trust == GMIME_SIGNER_TRUST_FULLY) || (signer->trust == GMIME_SIGNER_TRUST_ULTIMATE))
538                     printf (", \"userid\": %s", json_quote_str (ctx_quote, signer->name));
539            }
540        } else {
541            if (signer->keyid)
542                printf (", \"keyid\": %s", json_quote_str (ctx_quote, signer->keyid));
543        }
544        if (signer->errors != GMIME_SIGNER_ERROR_NONE) {
545            printf (", \"errors\": %x", signer->errors);
546        }
547
548        printf ("}");
549        signer = signer->next;
550     }
551
552     printf ("]");
553
554     talloc_free (ctx_quote);
555 }
556
557 static void
558 format_part_content_json (GMimeObject *part)
559 {
560     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
561     GMimeStream *stream_memory = g_mime_stream_mem_new ();
562     const char *cid = g_mime_object_get_content_id (part);
563     void *ctx = talloc_new (NULL);
564     GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (part);
565     GByteArray *part_content;
566
567     printf (", \"content-type\": %s",
568             json_quote_str (ctx, g_mime_content_type_to_string (content_type)));
569
570     if (cid != NULL)
571             printf(", \"content-id\": %s", json_quote_str (ctx, cid));
572
573     if (disposition &&
574         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
575     {
576         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
577
578         printf (", \"filename\": %s", json_quote_str (ctx, filename));
579     }
580
581     if (g_mime_content_type_is_type (content_type, "text", "*") &&
582         !g_mime_content_type_is_type (content_type, "text", "html"))
583     {
584         show_part_content (part, stream_memory);
585         part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
586
587         printf (", \"content\": %s", json_quote_chararray (ctx, (char *) part_content->data, part_content->len));
588     }
589     else if (g_mime_content_type_is_type (content_type, "multipart", "*") ||
590              g_mime_content_type_is_type (content_type, "message", "rfc822"))
591     {
592         printf (", \"content\": [");
593     }
594
595     talloc_free (ctx);
596     if (stream_memory)
597         g_object_unref (stream_memory);
598 }
599
600 static void
601 format_part_end_json (GMimeObject *part)
602 {
603     GMimeContentType *content_type;
604
605     content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
606
607     if (g_mime_content_type_is_type (content_type, "multipart", "*") ||
608         g_mime_content_type_is_type (content_type, "message", "rfc822"))
609         printf ("]");
610
611     printf ("}");
612 }
613
614 static void
615 format_part_content_raw (GMimeObject *part)
616 {
617     GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
618     g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
619     show_part_content (part, stream_stdout);
620     g_object_unref(stream_stdout);
621 }
622
623 static void
624 show_message (void *ctx,
625               const notmuch_show_format_t *format,
626               notmuch_message_t *message,
627               int indent,
628               notmuch_show_params_t *params)
629 {
630     if (params->part <= 0) {
631         fputs (format->message_start, stdout);
632         if (format->message)
633             format->message(ctx, message, indent);
634
635         fputs (format->header_start, stdout);
636         if (format->header)
637             format->header(ctx, message);
638         fputs (format->header_end, stdout);
639
640         fputs (format->body_start, stdout);
641     }
642
643     if (format->part_content)
644         show_message_body (notmuch_message_get_filename (message),
645                            format, params);
646
647     if (params->part <= 0) {
648         fputs (format->body_end, stdout);
649
650         fputs (format->message_end, stdout);
651     }
652 }
653
654 static void
655 show_messages (void *ctx,
656                const notmuch_show_format_t *format,
657                notmuch_messages_t *messages,
658                int indent,
659                notmuch_show_params_t *params)
660 {
661     notmuch_message_t *message;
662     notmuch_bool_t match;
663     int first_set = 1;
664     int next_indent;
665
666     fputs (format->message_set_start, stdout);
667
668     for (;
669          notmuch_messages_valid (messages);
670          notmuch_messages_move_to_next (messages))
671     {
672         if (!first_set)
673             fputs (format->message_set_sep, stdout);
674         first_set = 0;
675
676         fputs (format->message_set_start, stdout);
677
678         message = notmuch_messages_get (messages);
679
680         match = notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
681
682         next_indent = indent;
683
684         if (match || params->entire_thread) {
685             show_message (ctx, format, message, indent, params);
686             next_indent = indent + 1;
687
688             fputs (format->message_set_sep, stdout);
689         }
690
691         show_messages (ctx,
692                        format,
693                        notmuch_message_get_replies (message),
694                        next_indent,
695                        params);
696
697         notmuch_message_destroy (message);
698
699         fputs (format->message_set_end, stdout);
700     }
701
702     fputs (format->message_set_end, stdout);
703 }
704
705 /* Formatted output of single message */
706 static int
707 do_show_single (void *ctx,
708                 notmuch_query_t *query,
709                 const notmuch_show_format_t *format,
710                 notmuch_show_params_t *params)
711 {
712     notmuch_messages_t *messages;
713     notmuch_message_t *message;
714
715     if (notmuch_query_count_messages (query) != 1) {
716         fprintf (stderr, "Error: search term did not match precisely one message.\n");
717         return 1;
718     }
719
720     messages = notmuch_query_search_messages (query);
721     message = notmuch_messages_get (messages);
722
723     if (message == NULL) {
724         fprintf (stderr, "Error: Cannot find matching message.\n");
725         return 1;
726     }
727
728     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
729
730     /* Special case for --format=raw of full single message, just cat out file */
731     if (params->raw && 0 == params->part) {
732
733         const char *filename;
734         FILE *file;
735         size_t size;
736         char buf[4096];
737
738         filename = notmuch_message_get_filename (message);
739         if (filename == NULL) {
740             fprintf (stderr, "Error: Cannot message filename.\n");
741             return 1;
742         }
743
744         file = fopen (filename, "r");
745         if (file == NULL) {
746             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
747             return 1;
748         }
749
750         while (!feof (file)) {
751             size = fread (buf, 1, sizeof (buf), file);
752             fwrite (buf, size, 1, stdout);
753         }
754
755         fclose (file);
756
757     } else {
758
759         show_message (ctx, format, message, 0, params);
760
761     }
762
763     return 0;
764 }
765
766 /* Formatted output of threads */
767 static int
768 do_show (void *ctx,
769          notmuch_query_t *query,
770          const notmuch_show_format_t *format,
771          notmuch_show_params_t *params)
772 {
773     notmuch_threads_t *threads;
774     notmuch_thread_t *thread;
775     notmuch_messages_t *messages;
776     int first_toplevel = 1;
777
778     fputs (format->message_set_start, stdout);
779
780     for (threads = notmuch_query_search_threads (query);
781          notmuch_threads_valid (threads);
782          notmuch_threads_move_to_next (threads))
783     {
784         thread = notmuch_threads_get (threads);
785
786         messages = notmuch_thread_get_toplevel_messages (thread);
787
788         if (messages == NULL)
789             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
790                             notmuch_thread_get_thread_id (thread));
791
792         if (!first_toplevel)
793             fputs (format->message_set_sep, stdout);
794         first_toplevel = 0;
795
796         show_messages (ctx, format, messages, 0, params);
797
798         notmuch_thread_destroy (thread);
799
800     }
801
802     fputs (format->message_set_end, stdout);
803
804     return 0;
805 }
806
807 int
808 notmuch_show_command (void *ctx, unused (int argc), unused (char *argv[]))
809 {
810     notmuch_config_t *config;
811     notmuch_database_t *notmuch;
812     notmuch_query_t *query;
813     char *query_string;
814     char *opt;
815     const notmuch_show_format_t *format = &format_text;
816     notmuch_show_params_t params;
817     int mbox = 0;
818     int format_specified = 0;
819     int i;
820
821     params.entire_thread = 0;
822     params.raw = 0;
823     params.part = -1;
824     params.cryptoctx = NULL;
825
826     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
827         if (strcmp (argv[i], "--") == 0) {
828             i++;
829             break;
830         }
831         if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
832             opt = argv[i] + sizeof ("--format=") - 1;
833             if (strcmp (opt, "text") == 0) {
834                 format = &format_text;
835             } else if (strcmp (opt, "json") == 0) {
836                 format = &format_json;
837                 params.entire_thread = 1;
838             } else if (strcmp (opt, "mbox") == 0) {
839                 format = &format_mbox;
840                 mbox = 1;
841             } else if (strcmp (opt, "raw") == 0) {
842                 format = &format_raw;
843                 params.raw = 1;
844             } else {
845                 fprintf (stderr, "Invalid value for --format: %s\n", opt);
846                 return 1;
847             }
848             format_specified = 1;
849         } else if (STRNCMP_LITERAL (argv[i], "--part=") == 0) {
850             params.part = atoi(argv[i] + sizeof ("--part=") - 1);
851         } else if (STRNCMP_LITERAL (argv[i], "--entire-thread") == 0) {
852             params.entire_thread = 1;
853         } else if (STRNCMP_LITERAL (argv[i], "--verify") == 0) {
854             if (params.cryptoctx == NULL) {
855                 GMimeSession* session = g_object_new(notmuch_gmime_session_get_type(), NULL);
856                 if (NULL == (params.cryptoctx = g_mime_gpg_context_new(session, "gpg")))
857                     fprintf (stderr, "Failed to construct gpg context.\n");
858                 else
859                     g_mime_gpg_context_set_always_trust((GMimeGpgContext*)params.cryptoctx, FALSE);
860                 g_object_unref (session);
861                 session = NULL;
862             }
863         } else {
864             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
865             return 1;
866         }
867     }
868
869     argc -= i;
870     argv += i;
871
872     config = notmuch_config_open (ctx, NULL, NULL);
873     if (config == NULL)
874         return 1;
875
876     query_string = query_string_from_args (ctx, argc, argv);
877     if (query_string == NULL) {
878         fprintf (stderr, "Out of memory\n");
879         return 1;
880     }
881
882     if (mbox && params.part > 0) {
883         fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
884         return 1;
885     }
886
887     if (*query_string == '\0') {
888         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
889         return 1;
890     }
891
892     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
893                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
894     if (notmuch == NULL)
895         return 1;
896
897     query = notmuch_query_create (notmuch, query_string);
898     if (query == NULL) {
899         fprintf (stderr, "Out of memory\n");
900         return 1;
901     }
902
903     /* if part was requested and format was not specified, use format=raw */
904     if (params.part >= 0 && !format_specified)
905         format = &format_raw;
906
907     /* If --format=raw specified without specifying part, we can only
908      * output single message, so set part=0 */
909     if (params.raw && params.part < 0)
910         params.part = 0;
911
912     if (params.part >= 0)
913         return do_show_single (ctx, query, format, &params);
914     else
915         return do_show (ctx, query, format, &params);
916
917     notmuch_query_destroy (query);
918     notmuch_database_close (notmuch);
919
920     if (params.cryptoctx)
921         g_object_unref(params.cryptoctx);
922
923     return 0;
924 }