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 https://www.gnu.org/licenses/ .
19 * Authors: Carl Worth <cworth@cworth.org>
20 * Keith Packard <keithp@keithp.com>
23 #include "notmuch-client.h"
24 #include "string-util.h"
28 show_reply_headers (GMimeStream *stream, GMimeMessage *message)
30 /* Output RFC 2822 formatted (and RFC 2047 encoded) headers. */
31 if (g_mime_object_write_to_stream (GMIME_OBJECT(message), stream) < 0) {
32 INTERNAL_ERROR("failed to write headers to stdout\n");
37 format_part_reply (GMimeStream *stream, mime_node_t *node)
41 if (node->envelope_file) {
42 g_mime_stream_printf (stream, "On %s, %s wrote:\n",
43 notmuch_message_get_header (node->envelope_file, "date"),
44 notmuch_message_get_header (node->envelope_file, "from"));
45 } else if (GMIME_IS_MESSAGE (node->part)) {
46 GMimeMessage *message = GMIME_MESSAGE (node->part);
47 InternetAddressList *recipients;
48 const char *recipients_string;
50 g_mime_stream_printf (stream, "> From: %s\n", g_mime_message_get_sender (message));
51 recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
52 recipients_string = internet_address_list_to_string (recipients, 0);
53 if (recipients_string)
54 g_mime_stream_printf (stream, "> To: %s\n",
56 recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
57 recipients_string = internet_address_list_to_string (recipients, 0);
58 if (recipients_string)
59 g_mime_stream_printf (stream, "> Cc: %s\n",
61 g_mime_stream_printf (stream, "> Subject: %s\n", g_mime_message_get_subject (message));
62 g_mime_stream_printf (stream, "> Date: %s\n", g_mime_message_get_date_as_string (message));
63 g_mime_stream_printf (stream, ">\n");
64 } else if (GMIME_IS_PART (node->part)) {
65 GMimeContentType *content_type = g_mime_object_get_content_type (node->part);
66 GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (node->part);
68 if (g_mime_content_type_is_type (content_type, "application", "pgp-encrypted") ||
69 g_mime_content_type_is_type (content_type, "application", "pgp-signature")) {
70 /* Ignore PGP/MIME cruft parts */
71 } else if (g_mime_content_type_is_type (content_type, "text", "*") &&
72 !g_mime_content_type_is_type (content_type, "text", "html")) {
73 show_text_part_content (node->part, stream, NOTMUCH_SHOW_TEXT_PART_REPLY);
74 } else if (disposition &&
75 strcasecmp (g_mime_content_disposition_get_disposition (disposition),
76 GMIME_DISPOSITION_ATTACHMENT) == 0) {
77 const char *filename = g_mime_part_get_filename (GMIME_PART (node->part));
78 g_mime_stream_printf (stream, "Attachment: %s (%s)\n", filename,
79 g_mime_content_type_to_string (content_type));
81 g_mime_stream_printf (stream, "Non-text part: %s\n",
82 g_mime_content_type_to_string (content_type));
86 for (i = 0; i < node->nchildren; i++)
87 format_part_reply (stream, mime_node_child (node, i));
91 USER_ADDRESS_IN_STRING,
92 STRING_IN_USER_ADDRESS,
93 STRING_IS_USER_ADDRESS,
96 /* Match given string against given address according to mode. */
98 match_address (const char *str, const char *address, address_match_t mode)
101 case USER_ADDRESS_IN_STRING:
102 return strcasestr (str, address) != NULL;
103 case STRING_IN_USER_ADDRESS:
104 return strcasestr (address, str) != NULL;
105 case STRING_IS_USER_ADDRESS:
106 return strcasecmp (address, str) == 0;
112 /* Match given string against user's configured "primary" and "other"
113 * addresses according to mode. */
115 address_match (const char *str, notmuch_config_t *config, address_match_t mode)
121 if (!str || *str == '\0')
124 primary = notmuch_config_get_user_primary_email (config);
125 if (match_address (str, primary, mode))
128 other = notmuch_config_get_user_other_email (config, &other_len);
129 for (i = 0; i < other_len; i++) {
130 if (match_address (str, other[i], mode))
137 /* Does the given string contain an address configured as one of the
138 * user's "primary" or "other" addresses. If so, return the matching
139 * address, NULL otherwise. */
141 user_address_in_string (const char *str, notmuch_config_t *config)
143 return address_match (str, config, USER_ADDRESS_IN_STRING);
146 /* Do any of the addresses configured as one of the user's "primary"
147 * or "other" addresses contain the given string. If so, return the
148 * matching address, NULL otherwise. */
150 string_in_user_address (const char *str, notmuch_config_t *config)
152 return address_match (str, config, STRING_IN_USER_ADDRESS);
155 /* Is the given address configured as one of the user's "primary" or
156 * "other" addresses. */
157 static notmuch_bool_t
158 address_is_users (const char *address, notmuch_config_t *config)
160 return address_match (address, config, STRING_IS_USER_ADDRESS) != NULL;
163 /* Scan addresses in 'list'.
165 * If 'message' is non-NULL, then for each address in 'list' that is
166 * not configured as one of the user's addresses in 'config', add that
167 * address to 'message' as an address of 'type'.
169 * If 'user_from' is non-NULL and *user_from is NULL, *user_from will
170 * be set to the first address encountered in 'list' that is the
173 * Return the number of addresses added to 'message'. (If 'message' is
174 * NULL, the function returns 0 by definition.)
177 scan_address_list (InternetAddressList *list,
178 notmuch_config_t *config,
179 GMimeMessage *message,
180 GMimeRecipientType type,
181 const char **user_from)
183 InternetAddress *address;
190 for (i = 0; i < internet_address_list_length (list); i++) {
191 address = internet_address_list_get_address (list, i);
192 if (INTERNET_ADDRESS_IS_GROUP (address)) {
193 InternetAddressGroup *group;
194 InternetAddressList *group_list;
196 group = INTERNET_ADDRESS_GROUP (address);
197 group_list = internet_address_group_get_members (group);
198 n += scan_address_list (group_list, config, message, type, user_from);
200 InternetAddressMailbox *mailbox;
204 mailbox = INTERNET_ADDRESS_MAILBOX (address);
206 name = internet_address_get_name (address);
207 addr = internet_address_mailbox_get_addr (mailbox);
209 if (address_is_users (addr, config)) {
210 if (user_from && *user_from == NULL)
212 } else if (message) {
213 g_mime_message_add_recipient (message, type, name, addr);
222 /* Does the address in the Reply-To header of 'message' already appear
223 * in either the 'To' or 'Cc' header of the message?
225 static notmuch_bool_t
226 reply_to_header_is_redundant (GMimeMessage *message,
227 InternetAddressList *reply_to_list)
229 const char *addr, *reply_to;
230 InternetAddress *address;
231 InternetAddressMailbox *mailbox;
232 InternetAddressList *recipients;
233 notmuch_bool_t ret = FALSE;
236 if (reply_to_list == NULL ||
237 internet_address_list_length (reply_to_list) != 1)
240 address = internet_address_list_get_address (reply_to_list, 0);
241 if (INTERNET_ADDRESS_IS_GROUP (address))
244 mailbox = INTERNET_ADDRESS_MAILBOX (address);
245 reply_to = internet_address_mailbox_get_addr (mailbox);
247 recipients = g_mime_message_get_all_recipients (message);
249 for (i = 0; i < internet_address_list_length (recipients); i++) {
250 address = internet_address_list_get_address (recipients, i);
251 if (INTERNET_ADDRESS_IS_GROUP (address))
254 mailbox = INTERNET_ADDRESS_MAILBOX (address);
255 addr = internet_address_mailbox_get_addr (mailbox);
256 if (strcmp (addr, reply_to) == 0) {
262 g_object_unref (G_OBJECT (recipients));
267 static InternetAddressList *get_sender(GMimeMessage *message)
269 const char *reply_to;
271 reply_to = g_mime_message_get_reply_to (message);
272 if (reply_to && *reply_to) {
273 InternetAddressList *reply_to_list;
276 * Some mailing lists munge the Reply-To header despite it
277 * being A Bad Thing, see
278 * http://marc.merlins.org/netrants/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
282 * exists in either To or Cc). So in this case, we ignore the
283 * Reply-To field and use the From header. This ensures the
284 * original sender will get the reply even if not subscribed
285 * to the list. Note that the address in the Reply-To header
286 * will always appear in the reply if reply_all is true.
288 reply_to_list = internet_address_list_parse_string (reply_to);
289 if (! reply_to_header_is_redundant (message, reply_to_list))
290 return reply_to_list;
292 g_object_unref (G_OBJECT (reply_to_list));
295 return internet_address_list_parse_string (
296 g_mime_message_get_sender (message));
299 static InternetAddressList *get_to(GMimeMessage *message)
301 return g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
304 static InternetAddressList *get_cc(GMimeMessage *message)
306 return g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
309 static InternetAddressList *get_bcc(GMimeMessage *message)
311 return g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_BCC);
314 /* Augment the recipients of 'reply' from the "Reply-to:", "From:",
315 * "To:", "Cc:", and "Bcc:" headers of 'message'.
317 * If 'reply_all' is true, use sender and all recipients, otherwise
318 * scan the headers for the first that contains something other than
319 * the user's addresses and add the recipients from this header
320 * (typically this would be reply-to-sender, but also handles reply to
321 * user's own message in a sensible way).
323 * If any of the user's addresses were found in these headers, the
324 * first of these returned, otherwise NULL is returned.
327 add_recipients_from_message (GMimeMessage *reply,
328 notmuch_config_t *config,
329 GMimeMessage *message,
330 notmuch_bool_t reply_all)
333 InternetAddressList * (*get_header)(GMimeMessage *message);
334 GMimeRecipientType recipient_type;
336 { get_sender, GMIME_RECIPIENT_TYPE_TO },
337 { get_to, GMIME_RECIPIENT_TYPE_TO },
338 { get_cc, GMIME_RECIPIENT_TYPE_CC },
339 { get_bcc, GMIME_RECIPIENT_TYPE_BCC },
341 const char *from_addr = NULL;
345 for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
346 InternetAddressList *recipients;
348 recipients = reply_to_map[i].get_header (message);
350 n += scan_address_list (recipients, config, reply,
351 reply_to_map[i].recipient_type, &from_addr);
353 if (!reply_all && n) {
354 /* Stop adding new recipients in reply-to-sender mode if
355 * we have added some recipient(s) above.
357 * This also handles the case of user replying to his own
358 * message, where reply-to/from is not a recipient. In
359 * this case there may be more than one recipient even if
360 * not replying to all.
364 /* From address and some recipients are enough, bail out. */
374 * Look for the user's address in " for <email@add.res>" in the
377 * Return the address that was found, if any, and NULL otherwise.
380 guess_from_in_received_for (notmuch_config_t *config, const char *received)
384 ptr = strstr (received, " for ");
388 return user_address_in_string (ptr, config);
392 * Parse all the " by MTA ..." parts in received headers to guess the
393 * email address that this was originally delivered to.
395 * Extract just the MTA here by removing leading whitespace and
396 * assuming that the MTA name ends at the next whitespace. Test for
397 * *(by+4) to be non-'\0' to make sure there's something there at all
398 * - and then assume that the first whitespace delimited token that
399 * follows is the receiving system in this step of the receive chain.
401 * Return the address that was found, if any, and NULL otherwise.
404 guess_from_in_received_by (notmuch_config_t *config, const char *received)
407 const char *by = received;
408 char *domain, *tld, *mta, *ptr, *token;
410 while ((by = strstr (by, " by ")) != NULL) {
415 token = strtok(mta," \t");
421 * Now extract the last two components of the MTA host name as
425 while ((ptr = strsep (&token, ". \t")) != NULL) {
434 * Recombine domain and tld and look for it among the
435 * configured email addresses. This time we have a known
436 * domain name and nothing else - so the test is the other
437 * way around: we check if this is a substring of one of
438 * the email addresses.
442 addr = string_in_user_address (domain, config);
455 * Get the concatenated Received: headers and search from the front
456 * (last Received: header added) and try to extract from them
457 * indications to which email address this message was delivered.
459 * The Received: header is special in our get_header function and is
460 * always concatenated.
462 * Return the address that was found, if any, and NULL otherwise.
465 guess_from_in_received_headers (notmuch_config_t *config,
466 notmuch_message_t *message)
468 const char *received, *addr;
471 received = notmuch_message_get_header (message, "received");
475 sanitized = sanitize_string (NULL, received);
479 addr = guess_from_in_received_for (config, sanitized);
481 addr = guess_from_in_received_by (config, sanitized);
483 talloc_free (sanitized);
489 * Try to find user's email address in one of the extra To-like
490 * headers: Envelope-To, X-Original-To, and Delivered-To (searched in
493 * Return the address that was found, if any, and NULL otherwise.
496 get_from_in_to_headers (notmuch_config_t *config, notmuch_message_t *message)
499 const char *tohdr, *addr;
500 const char *to_headers[] = {
506 for (i = 0; i < ARRAY_SIZE (to_headers); i++) {
507 tohdr = notmuch_message_get_header (message, to_headers[i]);
509 /* Note: tohdr potentially contains a list of email addresses. */
510 addr = user_address_in_string (tohdr, config);
518 static GMimeMessage *
519 create_reply_message(void *ctx,
520 notmuch_config_t *config,
521 notmuch_message_t *message,
522 GMimeMessage *mime_message,
523 notmuch_bool_t reply_all,
524 notmuch_bool_t limited)
526 const char *subject, *from_addr = NULL;
527 const char *in_reply_to, *orig_references, *references;
530 * Use the below header order for limited headers, "pretty" order
533 GMimeMessage *reply = g_mime_message_new (limited ? 0 : 1);
535 fprintf (stderr, "Out of memory\n");
539 in_reply_to = talloc_asprintf (ctx, "<%s>",
540 notmuch_message_get_message_id (message));
542 g_mime_object_set_header (GMIME_OBJECT (reply), "In-Reply-To", in_reply_to);
544 orig_references = notmuch_message_get_header (message, "references");
545 if (orig_references && *orig_references)
546 references = talloc_asprintf (ctx, "%s %s", orig_references,
549 references = talloc_strdup (ctx, in_reply_to);
551 g_mime_object_set_header (GMIME_OBJECT (reply), "References", references);
553 from_addr = add_recipients_from_message (reply, config,
554 mime_message, reply_all);
556 /* The above is all that is needed for limited headers. */
561 * Sadly, there is no standard way to find out to which email
562 * address a mail was delivered - what is in the headers depends
563 * on the MTAs used along the way.
565 * If none of the user's email addresses are in the To: or Cc:
566 * headers, we try a number of heuristics which hopefully will
567 * answer this question.
569 * First, check for Envelope-To:, X-Original-To:, and
570 * Delivered-To: headers.
572 if (from_addr == NULL)
573 from_addr = get_from_in_to_headers (config, message);
576 * Check for a (for <email@add.res>) clause in Received: headers,
577 * and the domain part of known email addresses in the 'by' part
578 * of Received: headers
580 if (from_addr == NULL)
581 from_addr = guess_from_in_received_headers (config, message);
583 /* Default to user's primary address. */
584 if (from_addr == NULL)
585 from_addr = notmuch_config_get_user_primary_email (config);
587 from_addr = talloc_asprintf (ctx, "%s <%s>",
588 notmuch_config_get_user_name (config),
590 g_mime_object_set_header (GMIME_OBJECT (reply), "From", from_addr);
592 subject = notmuch_message_get_header (message, "subject");
594 if (strncasecmp (subject, "Re:", 3))
595 subject = talloc_asprintf (ctx, "Re: %s", subject);
596 g_mime_message_set_subject (reply, subject);
609 static int do_reply(notmuch_config_t *config,
610 notmuch_query_t *query,
611 notmuch_show_params_t *params,
613 notmuch_bool_t reply_all)
617 notmuch_messages_t *messages;
618 notmuch_message_t *message;
619 notmuch_status_t status;
620 struct sprinter *sp = NULL;
622 if (format == FORMAT_JSON || format == FORMAT_SEXP) {
625 status = notmuch_query_count_messages (query, &count);
626 if (print_status_query ("notmuch reply", query, status))
630 fprintf (stderr, "Error: search term did not match precisely one message (matched %d messages).\n", count);
634 if (format == FORMAT_JSON)
635 sp = sprinter_json_create (config, stdout);
637 sp = sprinter_sexp_create (config, stdout);
640 status = notmuch_query_search_messages (query, &messages);
641 if (print_status_query ("notmuch reply", query, status))
645 notmuch_messages_valid (messages);
646 notmuch_messages_move_to_next (messages))
648 message = notmuch_messages_get (messages);
650 if (mime_node_open (config, message, ¶ms->crypto, &node))
653 reply = create_reply_message (config, config, message,
654 GMIME_MESSAGE (node->part), reply_all,
655 format == FORMAT_HEADERS_ONLY);
659 if (format == FORMAT_JSON || format == FORMAT_SEXP) {
662 /* The headers of the reply message we've created */
663 sp->map_key (sp, "reply-headers");
664 format_headers_sprinter (sp, reply, TRUE);
666 /* Start the original */
667 sp->map_key (sp, "original");
668 format_part_sprinter (config, sp, node, TRUE, TRUE, FALSE);
673 GMimeStream *stream_stdout = stream_stdout = g_mime_stream_stdout_new ();
675 show_reply_headers (stream_stdout, reply);
676 if (format == FORMAT_DEFAULT)
677 format_part_reply (stream_stdout, node);
679 g_mime_stream_flush (stream_stdout);
680 g_object_unref(stream_stdout);
683 g_object_unref (G_OBJECT (reply));
686 notmuch_message_destroy (message);
693 notmuch_reply_command (notmuch_config_t *config, int argc, char *argv[])
695 notmuch_database_t *notmuch;
696 notmuch_query_t *query;
699 notmuch_show_params_t params = {
702 int format = FORMAT_DEFAULT;
703 int reply_all = TRUE;
705 notmuch_opt_desc_t options[] = {
706 { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
707 (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
708 { "json", FORMAT_JSON },
709 { "sexp", FORMAT_SEXP },
710 { "headers-only", FORMAT_HEADERS_ONLY },
712 { NOTMUCH_OPT_INT, ¬much_format_version, "format-version", 0, 0 },
713 { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
714 (notmuch_keyword_t []){ { "all", TRUE },
717 { NOTMUCH_OPT_BOOLEAN, ¶ms.crypto.decrypt, "decrypt", 'd', 0 },
718 { NOTMUCH_OPT_INHERIT, (void *) ¬much_shared_options, NULL, 0, 0 },
722 opt_index = parse_arguments (argc, argv, options, 1);
726 notmuch_process_shared_options (argv[0]);
728 notmuch_exit_if_unsupported_format ();
730 query_string = query_string_from_args (config, argc-opt_index, argv+opt_index);
731 if (query_string == NULL) {
732 fprintf (stderr, "Out of memory\n");
736 if (*query_string == '\0') {
737 fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
741 params.crypto.gpgpath = notmuch_config_get_crypto_gpg_path (config);
743 if (notmuch_database_open (notmuch_config_get_database_path (config),
744 NOTMUCH_DATABASE_MODE_READ_ONLY, ¬much))
747 notmuch_exit_if_unmatched_db_uuid (notmuch);
749 query = notmuch_query_create (notmuch, query_string);
751 fprintf (stderr, "Out of memory\n");
755 if (do_reply (config, query, ¶ms, format, reply_all) != 0)
758 notmuch_crypto_cleanup (¶ms.crypto);
759 notmuch_query_destroy (query);
760 notmuch_database_destroy (notmuch);