1 /* notmuch - Not much of an email program, (just index and search)
3 * Copyright © 2009 Carl Worth
4 * Copyright © 2009 Keith Packard
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see http://www.gnu.org/licenses/ .
19 * Authors: Carl Worth <cworth@cworth.org>
20 * Keith Packard <keithp@keithp.com>
23 #include "notmuch-client.h"
24 #include "gmime-filter-headers.h"
27 show_reply_headers (GMimeMessage *message)
29 GMimeStream *stream_stdout = NULL, *stream_filter = NULL;
31 stream_stdout = g_mime_stream_file_new (stdout);
33 g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
34 stream_filter = g_mime_stream_filter_new(stream_stdout);
36 g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream_filter),
37 g_mime_filter_headers_new());
38 g_mime_object_write_to_stream(GMIME_OBJECT(message), stream_filter);
39 g_object_unref(stream_filter);
41 g_object_unref(stream_stdout);
46 format_part_reply (mime_node_t *node)
50 if (node->envelope_file) {
51 printf ("On %s, %s wrote:\n",
52 notmuch_message_get_header (node->envelope_file, "date"),
53 notmuch_message_get_header (node->envelope_file, "from"));
54 } else if (GMIME_IS_MESSAGE (node->part)) {
55 GMimeMessage *message = GMIME_MESSAGE (node->part);
56 InternetAddressList *recipients;
57 const char *recipients_string;
59 printf ("> From: %s\n", g_mime_message_get_sender (message));
60 recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
61 recipients_string = internet_address_list_to_string (recipients, 0);
62 if (recipients_string)
65 recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
66 recipients_string = internet_address_list_to_string (recipients, 0);
67 if (recipients_string)
70 printf ("> Subject: %s\n", g_mime_message_get_subject (message));
71 printf ("> Date: %s\n", g_mime_message_get_date_as_string (message));
73 } else if (GMIME_IS_PART (node->part)) {
74 GMimeContentType *content_type = g_mime_object_get_content_type (node->part);
75 GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (node->part);
77 if (g_mime_content_type_is_type (content_type, "application", "pgp-encrypted") ||
78 g_mime_content_type_is_type (content_type, "application", "pgp-signature")) {
79 /* Ignore PGP/MIME cruft parts */
80 } else if (g_mime_content_type_is_type (content_type, "text", "*") &&
81 !g_mime_content_type_is_type (content_type, "text", "html")) {
82 GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
83 g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
84 show_text_part_content (node->part, stream_stdout, NOTMUCH_SHOW_TEXT_PART_REPLY);
85 g_object_unref(stream_stdout);
86 } else if (disposition &&
87 strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0) {
88 const char *filename = g_mime_part_get_filename (GMIME_PART (node->part));
89 printf ("Attachment: %s (%s)\n", filename,
90 g_mime_content_type_to_string (content_type));
92 printf ("Non-text part: %s\n",
93 g_mime_content_type_to_string (content_type));
97 for (i = 0; i < node->nchildren; i++)
98 format_part_reply (mime_node_child (node, i));
101 /* Is the given address configured as one of the user's "personal" or
102 * "other" addresses. */
104 address_is_users (const char *address, notmuch_config_t *config)
110 primary = notmuch_config_get_user_primary_email (config);
111 if (strcasecmp (primary, address) == 0)
114 other = notmuch_config_get_user_other_email (config, &other_len);
115 for (i = 0; i < other_len; i++)
116 if (strcasecmp (other[i], address) == 0)
122 /* Scan addresses in 'list'.
124 * If 'message' is non-NULL, then for each address in 'list' that is
125 * not configured as one of the user's addresses in 'config', add that
126 * address to 'message' as an address of 'type'.
128 * If 'user_from' is non-NULL and *user_from is NULL, *user_from will
129 * be set to the first address encountered in 'list' that is the
132 * Return the number of addresses added to 'message'. (If 'message' is
133 * NULL, the function returns 0 by definition.)
136 scan_address_list (InternetAddressList *list,
137 notmuch_config_t *config,
138 GMimeMessage *message,
139 GMimeRecipientType type,
140 const char **user_from)
142 InternetAddress *address;
146 for (i = 0; i < internet_address_list_length (list); i++) {
147 address = internet_address_list_get_address (list, i);
148 if (INTERNET_ADDRESS_IS_GROUP (address)) {
149 InternetAddressGroup *group;
150 InternetAddressList *group_list;
152 group = INTERNET_ADDRESS_GROUP (address);
153 group_list = internet_address_group_get_members (group);
154 if (group_list == NULL)
157 n += scan_address_list (group_list, config, message, type, user_from);
159 InternetAddressMailbox *mailbox;
163 mailbox = INTERNET_ADDRESS_MAILBOX (address);
165 name = internet_address_get_name (address);
166 addr = internet_address_mailbox_get_addr (mailbox);
168 if (address_is_users (addr, config)) {
169 if (user_from && *user_from == NULL)
171 } else if (message) {
172 g_mime_message_add_recipient (message, type, name, addr);
181 /* Scan addresses in 'recipients'.
183 * See the documentation of scan_address_list() above. This function
184 * does exactly the same, but converts 'recipients' to an
185 * InternetAddressList first.
188 scan_address_string (const char *recipients,
189 notmuch_config_t *config,
190 GMimeMessage *message,
191 GMimeRecipientType type,
192 const char **user_from)
194 InternetAddressList *list;
196 if (recipients == NULL)
199 list = internet_address_list_parse_string (recipients);
203 return scan_address_list (list, config, message, type, user_from);
206 /* Does the address in the Reply-To header of 'message' already appear
207 * in either the 'To' or 'Cc' header of the message?
210 reply_to_header_is_redundant (notmuch_message_t *message)
212 const char *reply_to, *to, *cc, *addr;
213 InternetAddressList *list;
214 InternetAddress *address;
215 InternetAddressMailbox *mailbox;
217 reply_to = notmuch_message_get_header (message, "reply-to");
218 if (reply_to == NULL || *reply_to == '\0')
221 list = internet_address_list_parse_string (reply_to);
223 if (internet_address_list_length (list) != 1)
226 address = internet_address_list_get_address (list, 0);
227 if (INTERNET_ADDRESS_IS_GROUP (address))
230 mailbox = INTERNET_ADDRESS_MAILBOX (address);
231 addr = internet_address_mailbox_get_addr (mailbox);
233 to = notmuch_message_get_header (message, "to");
234 cc = notmuch_message_get_header (message, "cc");
236 if ((to && strstr (to, addr) != 0) ||
237 (cc && strstr (cc, addr) != 0))
245 /* Augment the recipients of 'reply' from the "Reply-to:", "From:",
246 * "To:", "Cc:", and "Bcc:" headers of 'message'.
248 * If 'reply_all' is true, use sender and all recipients, otherwise
249 * scan the headers for the first that contains something other than
250 * the user's addresses and add the recipients from this header
251 * (typically this would be reply-to-sender, but also handles reply to
252 * user's own message in a sensible way).
254 * If any of the user's addresses were found in these headers, the
255 * first of these returned, otherwise NULL is returned.
258 add_recipients_from_message (GMimeMessage *reply,
259 notmuch_config_t *config,
260 notmuch_message_t *message,
261 notmuch_bool_t reply_all)
265 const char *fallback;
266 GMimeRecipientType recipient_type;
268 { "reply-to", "from", GMIME_RECIPIENT_TYPE_TO },
269 { "to", NULL, GMIME_RECIPIENT_TYPE_TO },
270 { "cc", NULL, GMIME_RECIPIENT_TYPE_CC },
271 { "bcc", NULL, GMIME_RECIPIENT_TYPE_BCC }
273 const char *from_addr = NULL;
277 /* Some mailing lists munge the Reply-To header despite it being A Bad
278 * Thing, see http://www.unicom.com/pw/reply-to-harmful.html
280 * The munging is easy to detect, because it results in a
281 * redundant reply-to header, (with an address that already exists
282 * in either To or Cc). So in this case, we ignore the Reply-To
283 * field and use the From header. This ensures the original sender
284 * will get the reply even if not subscribed to the list. Note
285 * that the address in the Reply-To header will always appear in
288 if (reply_to_header_is_redundant (message)) {
289 reply_to_map[0].header = "from";
290 reply_to_map[0].fallback = NULL;
293 for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
294 const char *recipients;
296 recipients = notmuch_message_get_header (message,
297 reply_to_map[i].header);
298 if ((recipients == NULL || recipients[0] == '\0') && reply_to_map[i].fallback)
299 recipients = notmuch_message_get_header (message,
300 reply_to_map[i].fallback);
302 n += scan_address_string (recipients, config, reply,
303 reply_to_map[i].recipient_type, &from_addr);
305 if (!reply_all && n) {
306 /* Stop adding new recipients in reply-to-sender mode if
307 * we have added some recipient(s) above.
309 * This also handles the case of user replying to his own
310 * message, where reply-to/from is not a recipient. In
311 * this case there may be more than one recipient even if
312 * not replying to all.
316 /* From address and some recipients are enough, bail out. */
326 guess_from_received_header (notmuch_config_t *config, notmuch_message_t *message)
328 const char *received,*primary,*by;
331 char *mta,*ptr,*token;
334 const char *delim=". \t";
335 size_t i,j,other_len;
337 const char *to_headers[] = {"Envelope-to", "X-Original-To"};
339 primary = notmuch_config_get_user_primary_email (config);
340 other = notmuch_config_get_user_other_email (config, &other_len);
342 /* sadly, there is no standard way to find out to which email
343 * address a mail was delivered - what is in the headers depends
344 * on the MTAs used along the way. So we are trying a number of
345 * heuristics which hopefully will answer this question.
347 * We only got here if none of the users email addresses are in
348 * the To: or Cc: header. From here we try the following in order:
349 * 1) check for an Envelope-to: header
350 * 2) check for an X-Original-To: header
351 * 3) check for a (for <email@add.res>) clause in Received: headers
352 * 4) check for the domain part of known email addresses in the
353 * 'by' part of Received headers
354 * If none of these work, we give up and return NULL
356 for (i = 0; i < sizeof(to_headers)/sizeof(*to_headers); i++) {
357 tohdr = xstrdup(notmuch_message_get_header (message, to_headers[i]));
358 if (tohdr && *tohdr) {
359 /* tohdr is potentialy a list of email addresses, so here we
360 * check if one of the email addresses is a substring of tohdr
362 if (strcasestr(tohdr, primary)) {
366 for (j = 0; j < other_len; j++)
367 if (strcasestr (tohdr, other[j])) {
375 /* We get the concatenated Received: headers and search from the
376 * front (last Received: header added) and try to extract from
377 * them indications to which email address this message was
379 * The Received: header is special in our get_header function
380 * and is always concatenated.
382 received = notmuch_message_get_header (message, "received");
383 if (received == NULL)
386 /* First we look for a " for <email@add.res>" in the received
389 ptr = strstr (received, " for ");
391 /* the text following is potentialy a list of email addresses,
392 * so again we check if one of the email addresses is a
395 if (strcasestr(ptr, primary)) {
398 for (i = 0; i < other_len; i++)
399 if (strcasestr (ptr, other[i])) {
403 /* Finally, we parse all the " by MTA ..." headers to guess the
404 * email address that this was originally delivered to.
405 * We extract just the MTA here by removing leading whitespace and
406 * assuming that the MTA name ends at the next whitespace.
407 * We test for *(by+4) to be non-'\0' to make sure there's
408 * something there at all - and then assume that the first
409 * whitespace delimited token that follows is the receiving
410 * system in this step of the receive chain
413 while((by = strstr (by, " by ")) != NULL) {
418 token = strtok(mta," \t");
423 /* Now extract the last two components of the MTA host name
427 while ((ptr = strsep (&token, delim)) != NULL) {
435 /* Recombine domain and tld and look for it among the configured
437 * This time we have a known domain name and nothing else - so
438 * the test is the other way around: we check if this is a
439 * substring of one of the email addresses.
443 if (strcasestr(primary, domain)) {
447 for (i = 0; i < other_len; i++)
448 if (strcasestr (other[i],domain)) {
459 static GMimeMessage *
460 create_reply_message(void *ctx,
461 notmuch_config_t *config,
462 notmuch_message_t *message,
463 notmuch_bool_t reply_all)
465 const char *subject, *from_addr = NULL;
466 const char *in_reply_to, *orig_references, *references;
468 /* The 1 means we want headers in a "pretty" order. */
469 GMimeMessage *reply = g_mime_message_new (1);
471 fprintf (stderr, "Out of memory\n");
475 subject = notmuch_message_get_header (message, "subject");
477 if (strncasecmp (subject, "Re:", 3))
478 subject = talloc_asprintf (ctx, "Re: %s", subject);
479 g_mime_message_set_subject (reply, subject);
482 from_addr = add_recipients_from_message (reply, config,
485 if (from_addr == NULL)
486 from_addr = guess_from_received_header (config, message);
488 if (from_addr == NULL)
489 from_addr = notmuch_config_get_user_primary_email (config);
491 from_addr = talloc_asprintf (ctx, "%s <%s>",
492 notmuch_config_get_user_name (config),
494 g_mime_object_set_header (GMIME_OBJECT (reply),
497 in_reply_to = talloc_asprintf (ctx, "<%s>",
498 notmuch_message_get_message_id (message));
500 g_mime_object_set_header (GMIME_OBJECT (reply),
501 "In-Reply-To", in_reply_to);
503 orig_references = notmuch_message_get_header (message, "references");
504 references = talloc_asprintf (ctx, "%s%s%s",
505 orig_references ? orig_references : "",
506 orig_references ? " " : "",
508 g_mime_object_set_header (GMIME_OBJECT (reply),
509 "References", references);
515 notmuch_reply_format_default(void *ctx,
516 notmuch_config_t *config,
517 notmuch_query_t *query,
518 notmuch_show_params_t *params,
519 notmuch_bool_t reply_all)
522 notmuch_messages_t *messages;
523 notmuch_message_t *message;
526 for (messages = notmuch_query_search_messages (query);
527 notmuch_messages_valid (messages);
528 notmuch_messages_move_to_next (messages))
530 message = notmuch_messages_get (messages);
532 reply = create_reply_message (ctx, config, message, reply_all);
534 /* If reply creation failed, we're out of memory, so don't
535 * bother trying any more messages.
538 notmuch_message_destroy (message);
542 show_reply_headers (reply);
544 g_object_unref (G_OBJECT (reply));
547 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
548 &root) == NOTMUCH_STATUS_SUCCESS) {
549 format_part_reply (root);
553 notmuch_message_destroy (message);
559 notmuch_reply_format_json(void *ctx,
560 notmuch_config_t *config,
561 notmuch_query_t *query,
562 notmuch_show_params_t *params,
563 notmuch_bool_t reply_all)
566 notmuch_messages_t *messages;
567 notmuch_message_t *message;
570 if (notmuch_query_count_messages (query) != 1) {
571 fprintf (stderr, "Error: search term did not match precisely one message.\n");
575 messages = notmuch_query_search_messages (query);
576 message = notmuch_messages_get (messages);
577 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
578 &node) != NOTMUCH_STATUS_SUCCESS)
581 reply = create_reply_message (ctx, config, message, reply_all);
585 /* The headers of the reply message we've created */
586 printf ("{\"reply-headers\": ");
587 format_headers_json (ctx, reply, TRUE);
588 g_object_unref (G_OBJECT (reply));
591 /* Start the original */
592 printf (", \"original\": ");
594 format_part_json (ctx, node, TRUE);
598 notmuch_message_destroy (message);
603 /* This format is currently tuned for a git send-email --notmuch hook */
605 notmuch_reply_format_headers_only(void *ctx,
606 notmuch_config_t *config,
607 notmuch_query_t *query,
608 unused (notmuch_show_params_t *params),
609 notmuch_bool_t reply_all)
612 notmuch_messages_t *messages;
613 notmuch_message_t *message;
614 const char *in_reply_to, *orig_references, *references;
617 for (messages = notmuch_query_search_messages (query);
618 notmuch_messages_valid (messages);
619 notmuch_messages_move_to_next (messages))
621 message = notmuch_messages_get (messages);
623 /* The 0 means we do not want headers in a "pretty" order. */
624 reply = g_mime_message_new (0);
626 fprintf (stderr, "Out of memory\n");
630 in_reply_to = talloc_asprintf (ctx, "<%s>",
631 notmuch_message_get_message_id (message));
633 g_mime_object_set_header (GMIME_OBJECT (reply),
634 "In-Reply-To", in_reply_to);
637 orig_references = notmuch_message_get_header (message, "references");
639 /* We print In-Reply-To followed by References because git format-patch treats them
640 * specially. Git does not interpret the other headers specially
642 references = talloc_asprintf (ctx, "%s%s%s",
643 orig_references ? orig_references : "",
644 orig_references ? " " : "",
646 g_mime_object_set_header (GMIME_OBJECT (reply),
647 "References", references);
649 (void)add_recipients_from_message (reply, config, message, reply_all);
651 reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
652 printf ("%s", reply_headers);
653 free (reply_headers);
655 g_object_unref (G_OBJECT (reply));
658 notmuch_message_destroy (message);
670 notmuch_reply_command (void *ctx, int argc, char *argv[])
672 notmuch_config_t *config;
673 notmuch_database_t *notmuch;
674 notmuch_query_t *query;
676 int opt_index, ret = 0;
677 int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params, notmuch_bool_t reply_all);
678 notmuch_show_params_t params = { .part = -1 };
679 int format = FORMAT_DEFAULT;
680 int reply_all = TRUE;
682 notmuch_opt_desc_t options[] = {
683 { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
684 (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
685 { "json", FORMAT_JSON },
686 { "headers-only", FORMAT_HEADERS_ONLY },
688 { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
689 (notmuch_keyword_t []){ { "all", TRUE },
692 { NOTMUCH_OPT_BOOLEAN, ¶ms.decrypt, "decrypt", 'd', 0 },
696 opt_index = parse_arguments (argc, argv, options, 1);
698 /* diagnostics already printed */
702 if (format == FORMAT_HEADERS_ONLY)
703 reply_format_func = notmuch_reply_format_headers_only;
704 else if (format == FORMAT_JSON)
705 reply_format_func = notmuch_reply_format_json;
707 reply_format_func = notmuch_reply_format_default;
709 if (params.decrypt) {
710 #ifdef GMIME_ATLEAST_26
711 /* TODO: GMimePasswordRequestFunc */
712 params.cryptoctx = g_mime_gpg_context_new (NULL, "gpg");
714 GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
715 params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
717 if (params.cryptoctx) {
718 g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
720 params.decrypt = FALSE;
721 fprintf (stderr, "Failed to construct gpg context.\n");
723 #ifndef GMIME_ATLEAST_26
724 g_object_unref (session);
728 config = notmuch_config_open (ctx, NULL, NULL);
732 query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
733 if (query_string == NULL) {
734 fprintf (stderr, "Out of memory\n");
738 if (*query_string == '\0') {
739 fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
743 notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
744 NOTMUCH_DATABASE_MODE_READ_ONLY);
748 query = notmuch_query_create (notmuch, query_string);
750 fprintf (stderr, "Out of memory\n");
754 if (reply_format_func (ctx, config, query, ¶ms, reply_all) != 0)
757 notmuch_query_destroy (query);
758 notmuch_database_destroy (notmuch);
760 if (params.cryptoctx)
761 g_object_unref(params.cryptoctx);