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));
102 USER_ADDRESS_IN_STRING,
103 STRING_IN_USER_ADDRESS,
104 STRING_IS_USER_ADDRESS,
107 /* Match given string against given address according to mode. */
108 static notmuch_bool_t
109 match_address (const char *str, const char *address, address_match_t mode)
112 case USER_ADDRESS_IN_STRING:
113 return strcasestr (str, address) != NULL;
114 case STRING_IN_USER_ADDRESS:
115 return strcasestr (address, str) != NULL;
116 case STRING_IS_USER_ADDRESS:
117 return strcasecmp (address, str) == 0;
123 /* Match given string against user's configured "primary" and "other"
124 * addresses according to mode. */
126 address_match (const char *str, notmuch_config_t *config, address_match_t mode)
132 if (!str || *str == '\0')
135 primary = notmuch_config_get_user_primary_email (config);
136 if (match_address (str, primary, mode))
139 other = notmuch_config_get_user_other_email (config, &other_len);
140 for (i = 0; i < other_len; i++) {
141 if (match_address (str, other[i], mode))
148 /* Does the given string contain an address configured as one of the
149 * user's "primary" or "other" addresses. If so, return the matching
150 * address, NULL otherwise. */
152 user_address_in_string (const char *str, notmuch_config_t *config)
154 return address_match (str, config, USER_ADDRESS_IN_STRING);
157 /* Do any of the addresses configured as one of the user's "primary"
158 * or "other" addresses contain the given string. If so, return the
159 * matching address, NULL otherwise. */
161 string_in_user_address (const char *str, notmuch_config_t *config)
163 return address_match (str, config, STRING_IN_USER_ADDRESS);
166 /* Is the given address configured as one of the user's "primary" or
167 * "other" addresses. */
168 static notmuch_bool_t
169 address_is_users (const char *address, notmuch_config_t *config)
171 return address_match (address, config, STRING_IS_USER_ADDRESS) != NULL;
174 /* Scan addresses in 'list'.
176 * If 'message' is non-NULL, then for each address in 'list' that is
177 * not configured as one of the user's addresses in 'config', add that
178 * address to 'message' as an address of 'type'.
180 * If 'user_from' is non-NULL and *user_from is NULL, *user_from will
181 * be set to the first address encountered in 'list' that is the
184 * Return the number of addresses added to 'message'. (If 'message' is
185 * NULL, the function returns 0 by definition.)
188 scan_address_list (InternetAddressList *list,
189 notmuch_config_t *config,
190 GMimeMessage *message,
191 GMimeRecipientType type,
192 const char **user_from)
194 InternetAddress *address;
198 for (i = 0; i < internet_address_list_length (list); i++) {
199 address = internet_address_list_get_address (list, i);
200 if (INTERNET_ADDRESS_IS_GROUP (address)) {
201 InternetAddressGroup *group;
202 InternetAddressList *group_list;
204 group = INTERNET_ADDRESS_GROUP (address);
205 group_list = internet_address_group_get_members (group);
206 if (group_list == NULL)
209 n += scan_address_list (group_list, config, message, type, user_from);
211 InternetAddressMailbox *mailbox;
215 mailbox = INTERNET_ADDRESS_MAILBOX (address);
217 name = internet_address_get_name (address);
218 addr = internet_address_mailbox_get_addr (mailbox);
220 if (address_is_users (addr, config)) {
221 if (user_from && *user_from == NULL)
223 } else if (message) {
224 g_mime_message_add_recipient (message, type, name, addr);
233 /* Scan addresses in 'recipients'.
235 * See the documentation of scan_address_list() above. This function
236 * does exactly the same, but converts 'recipients' to an
237 * InternetAddressList first.
240 scan_address_string (const char *recipients,
241 notmuch_config_t *config,
242 GMimeMessage *message,
243 GMimeRecipientType type,
244 const char **user_from)
246 InternetAddressList *list;
248 if (recipients == NULL)
251 list = internet_address_list_parse_string (recipients);
255 return scan_address_list (list, config, message, type, user_from);
258 /* Does the address in the Reply-To header of 'message' already appear
259 * in either the 'To' or 'Cc' header of the message?
262 reply_to_header_is_redundant (notmuch_message_t *message)
264 const char *reply_to, *to, *cc, *addr;
265 InternetAddressList *list;
266 InternetAddress *address;
267 InternetAddressMailbox *mailbox;
269 reply_to = notmuch_message_get_header (message, "reply-to");
270 if (reply_to == NULL || *reply_to == '\0')
273 list = internet_address_list_parse_string (reply_to);
275 if (internet_address_list_length (list) != 1)
278 address = internet_address_list_get_address (list, 0);
279 if (INTERNET_ADDRESS_IS_GROUP (address))
282 mailbox = INTERNET_ADDRESS_MAILBOX (address);
283 addr = internet_address_mailbox_get_addr (mailbox);
285 to = notmuch_message_get_header (message, "to");
286 cc = notmuch_message_get_header (message, "cc");
288 if ((to && strstr (to, addr) != 0) ||
289 (cc && strstr (cc, addr) != 0))
297 /* Augment the recipients of 'reply' from the "Reply-to:", "From:",
298 * "To:", "Cc:", and "Bcc:" headers of 'message'.
300 * If 'reply_all' is true, use sender and all recipients, otherwise
301 * scan the headers for the first that contains something other than
302 * the user's addresses and add the recipients from this header
303 * (typically this would be reply-to-sender, but also handles reply to
304 * user's own message in a sensible way).
306 * If any of the user's addresses were found in these headers, the
307 * first of these returned, otherwise NULL is returned.
310 add_recipients_from_message (GMimeMessage *reply,
311 notmuch_config_t *config,
312 notmuch_message_t *message,
313 notmuch_bool_t reply_all)
317 const char *fallback;
318 GMimeRecipientType recipient_type;
320 { "reply-to", "from", GMIME_RECIPIENT_TYPE_TO },
321 { "to", NULL, GMIME_RECIPIENT_TYPE_TO },
322 { "cc", NULL, GMIME_RECIPIENT_TYPE_CC },
323 { "bcc", NULL, GMIME_RECIPIENT_TYPE_BCC }
325 const char *from_addr = NULL;
329 /* Some mailing lists munge the Reply-To header despite it being A Bad
330 * Thing, see http://www.unicom.com/pw/reply-to-harmful.html
332 * The munging is easy to detect, because it results in a
333 * redundant reply-to header, (with an address that already exists
334 * in either To or Cc). So in this case, we ignore the Reply-To
335 * field and use the From header. This ensures the original sender
336 * will get the reply even if not subscribed to the list. Note
337 * that the address in the Reply-To header will always appear in
340 if (reply_to_header_is_redundant (message)) {
341 reply_to_map[0].header = "from";
342 reply_to_map[0].fallback = NULL;
345 for (i = 0; i < ARRAY_SIZE (reply_to_map); i++) {
346 const char *recipients;
348 recipients = notmuch_message_get_header (message,
349 reply_to_map[i].header);
350 if ((recipients == NULL || recipients[0] == '\0') && reply_to_map[i].fallback)
351 recipients = notmuch_message_get_header (message,
352 reply_to_map[i].fallback);
354 n += scan_address_string (recipients, config, reply,
355 reply_to_map[i].recipient_type, &from_addr);
357 if (!reply_all && n) {
358 /* Stop adding new recipients in reply-to-sender mode if
359 * we have added some recipient(s) above.
361 * This also handles the case of user replying to his own
362 * message, where reply-to/from is not a recipient. In
363 * this case there may be more than one recipient even if
364 * not replying to all.
368 /* From address and some recipients are enough, bail out. */
378 guess_from_received_header (notmuch_config_t *config, notmuch_message_t *message)
380 const char *addr, *received, *by;
381 char *mta,*ptr,*token;
384 const char *delim=". \t";
387 const char *to_headers[] = {
393 /* sadly, there is no standard way to find out to which email
394 * address a mail was delivered - what is in the headers depends
395 * on the MTAs used along the way. So we are trying a number of
396 * heuristics which hopefully will answer this question.
398 * We only got here if none of the users email addresses are in
399 * the To: or Cc: header. From here we try the following in order:
400 * 1) check for an Envelope-to: header
401 * 2) check for an X-Original-To: header
402 * 3) check for a Delivered-To: header
403 * 4) check for a (for <email@add.res>) clause in Received: headers
404 * 5) check for the domain part of known email addresses in the
405 * 'by' part of Received headers
406 * If none of these work, we give up and return NULL
408 for (i = 0; i < ARRAY_SIZE (to_headers); i++) {
409 const char *tohdr = notmuch_message_get_header (message, to_headers[i]);
411 /* Note: tohdr potentially contains a list of email addresses. */
412 addr = user_address_in_string (tohdr, config);
417 /* We get the concatenated Received: headers and search from the
418 * front (last Received: header added) and try to extract from
419 * them indications to which email address this message was
421 * The Received: header is special in our get_header function
422 * and is always concatenated.
424 received = notmuch_message_get_header (message, "received");
425 if (received == NULL)
428 /* First we look for a " for <email@add.res>" in the received
431 ptr = strstr (received, " for ");
433 /* Note: ptr potentially contains a list of email addresses. */
434 addr = user_address_in_string (ptr, config);
438 /* Finally, we parse all the " by MTA ..." headers to guess the
439 * email address that this was originally delivered to.
440 * We extract just the MTA here by removing leading whitespace and
441 * assuming that the MTA name ends at the next whitespace.
442 * We test for *(by+4) to be non-'\0' to make sure there's
443 * something there at all - and then assume that the first
444 * whitespace delimited token that follows is the receiving
445 * system in this step of the receive chain
448 while((by = strstr (by, " by ")) != NULL) {
453 token = strtok(mta," \t");
458 /* Now extract the last two components of the MTA host name
462 while ((ptr = strsep (&token, delim)) != NULL) {
470 /* Recombine domain and tld and look for it among the configured
472 * This time we have a known domain name and nothing else - so
473 * the test is the other way around: we check if this is a
474 * substring of one of the email addresses.
478 addr = string_in_user_address (domain, config);
490 static GMimeMessage *
491 create_reply_message(void *ctx,
492 notmuch_config_t *config,
493 notmuch_message_t *message,
494 notmuch_bool_t reply_all)
496 const char *subject, *from_addr = NULL;
497 const char *in_reply_to, *orig_references, *references;
499 /* The 1 means we want headers in a "pretty" order. */
500 GMimeMessage *reply = g_mime_message_new (1);
502 fprintf (stderr, "Out of memory\n");
506 subject = notmuch_message_get_header (message, "subject");
508 if (strncasecmp (subject, "Re:", 3))
509 subject = talloc_asprintf (ctx, "Re: %s", subject);
510 g_mime_message_set_subject (reply, subject);
513 from_addr = add_recipients_from_message (reply, config,
516 if (from_addr == NULL)
517 from_addr = guess_from_received_header (config, message);
519 if (from_addr == NULL)
520 from_addr = notmuch_config_get_user_primary_email (config);
522 from_addr = talloc_asprintf (ctx, "%s <%s>",
523 notmuch_config_get_user_name (config),
525 g_mime_object_set_header (GMIME_OBJECT (reply),
528 in_reply_to = talloc_asprintf (ctx, "<%s>",
529 notmuch_message_get_message_id (message));
531 g_mime_object_set_header (GMIME_OBJECT (reply),
532 "In-Reply-To", in_reply_to);
534 orig_references = notmuch_message_get_header (message, "references");
535 references = talloc_asprintf (ctx, "%s%s%s",
536 orig_references ? orig_references : "",
537 orig_references ? " " : "",
539 g_mime_object_set_header (GMIME_OBJECT (reply),
540 "References", references);
546 notmuch_reply_format_default(void *ctx,
547 notmuch_config_t *config,
548 notmuch_query_t *query,
549 notmuch_show_params_t *params,
550 notmuch_bool_t reply_all)
553 notmuch_messages_t *messages;
554 notmuch_message_t *message;
557 for (messages = notmuch_query_search_messages (query);
558 notmuch_messages_valid (messages);
559 notmuch_messages_move_to_next (messages))
561 message = notmuch_messages_get (messages);
563 reply = create_reply_message (ctx, config, message, reply_all);
565 /* If reply creation failed, we're out of memory, so don't
566 * bother trying any more messages.
569 notmuch_message_destroy (message);
573 show_reply_headers (reply);
575 g_object_unref (G_OBJECT (reply));
578 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
579 &root) == NOTMUCH_STATUS_SUCCESS) {
580 format_part_reply (root);
584 notmuch_message_destroy (message);
590 notmuch_reply_format_json(void *ctx,
591 notmuch_config_t *config,
592 notmuch_query_t *query,
593 notmuch_show_params_t *params,
594 notmuch_bool_t reply_all)
597 notmuch_messages_t *messages;
598 notmuch_message_t *message;
601 if (notmuch_query_count_messages (query) != 1) {
602 fprintf (stderr, "Error: search term did not match precisely one message.\n");
606 messages = notmuch_query_search_messages (query);
607 message = notmuch_messages_get (messages);
608 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
609 &node) != NOTMUCH_STATUS_SUCCESS)
612 reply = create_reply_message (ctx, config, message, reply_all);
616 /* The headers of the reply message we've created */
617 printf ("{\"reply-headers\": ");
618 format_headers_json (ctx, reply, TRUE);
619 g_object_unref (G_OBJECT (reply));
622 /* Start the original */
623 printf (", \"original\": ");
625 format_part_json (ctx, node, TRUE);
629 notmuch_message_destroy (message);
634 /* This format is currently tuned for a git send-email --notmuch hook */
636 notmuch_reply_format_headers_only(void *ctx,
637 notmuch_config_t *config,
638 notmuch_query_t *query,
639 unused (notmuch_show_params_t *params),
640 notmuch_bool_t reply_all)
643 notmuch_messages_t *messages;
644 notmuch_message_t *message;
645 const char *in_reply_to, *orig_references, *references;
648 for (messages = notmuch_query_search_messages (query);
649 notmuch_messages_valid (messages);
650 notmuch_messages_move_to_next (messages))
652 message = notmuch_messages_get (messages);
654 /* The 0 means we do not want headers in a "pretty" order. */
655 reply = g_mime_message_new (0);
657 fprintf (stderr, "Out of memory\n");
661 in_reply_to = talloc_asprintf (ctx, "<%s>",
662 notmuch_message_get_message_id (message));
664 g_mime_object_set_header (GMIME_OBJECT (reply),
665 "In-Reply-To", in_reply_to);
668 orig_references = notmuch_message_get_header (message, "references");
670 /* We print In-Reply-To followed by References because git format-patch treats them
671 * specially. Git does not interpret the other headers specially
673 references = talloc_asprintf (ctx, "%s%s%s",
674 orig_references ? orig_references : "",
675 orig_references ? " " : "",
677 g_mime_object_set_header (GMIME_OBJECT (reply),
678 "References", references);
680 (void)add_recipients_from_message (reply, config, message, reply_all);
682 reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
683 printf ("%s", reply_headers);
684 free (reply_headers);
686 g_object_unref (G_OBJECT (reply));
689 notmuch_message_destroy (message);
701 notmuch_reply_command (void *ctx, int argc, char *argv[])
703 notmuch_config_t *config;
704 notmuch_database_t *notmuch;
705 notmuch_query_t *query;
707 int opt_index, ret = 0;
708 int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params, notmuch_bool_t reply_all);
709 notmuch_show_params_t params = { .part = -1 };
710 int format = FORMAT_DEFAULT;
711 int reply_all = TRUE;
713 notmuch_opt_desc_t options[] = {
714 { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
715 (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
716 { "json", FORMAT_JSON },
717 { "headers-only", FORMAT_HEADERS_ONLY },
719 { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
720 (notmuch_keyword_t []){ { "all", TRUE },
723 { NOTMUCH_OPT_BOOLEAN, ¶ms.decrypt, "decrypt", 'd', 0 },
727 opt_index = parse_arguments (argc, argv, options, 1);
729 /* diagnostics already printed */
733 if (format == FORMAT_HEADERS_ONLY)
734 reply_format_func = notmuch_reply_format_headers_only;
735 else if (format == FORMAT_JSON)
736 reply_format_func = notmuch_reply_format_json;
738 reply_format_func = notmuch_reply_format_default;
740 if (params.decrypt) {
741 #ifdef GMIME_ATLEAST_26
742 /* TODO: GMimePasswordRequestFunc */
743 params.cryptoctx = g_mime_gpg_context_new (NULL, "gpg");
745 GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
746 params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
748 if (params.cryptoctx) {
749 g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
751 params.decrypt = FALSE;
752 fprintf (stderr, "Failed to construct gpg context.\n");
754 #ifndef GMIME_ATLEAST_26
755 g_object_unref (session);
759 config = notmuch_config_open (ctx, NULL, NULL);
763 query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
764 if (query_string == NULL) {
765 fprintf (stderr, "Out of memory\n");
769 if (*query_string == '\0') {
770 fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
774 if (notmuch_database_open (notmuch_config_get_database_path (config),
775 NOTMUCH_DATABASE_MODE_READ_ONLY, ¬much))
778 query = notmuch_query_create (notmuch, query_string);
780 fprintf (stderr, "Out of memory\n");
784 if (reply_format_func (ctx, config, query, ¶ms, reply_all) != 0)
787 notmuch_query_destroy (query);
788 notmuch_database_destroy (notmuch);
790 if (params.cryptoctx)
791 g_object_unref(params.cryptoctx);