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 *received,*primary,*by;
383 char *mta,*ptr,*token;
386 const char *delim=". \t";
387 size_t i,j,other_len;
389 const char *to_headers[] = {"Envelope-to", "X-Original-To"};
391 primary = notmuch_config_get_user_primary_email (config);
392 other = notmuch_config_get_user_other_email (config, &other_len);
394 /* sadly, there is no standard way to find out to which email
395 * address a mail was delivered - what is in the headers depends
396 * on the MTAs used along the way. So we are trying a number of
397 * heuristics which hopefully will answer this question.
399 * We only got here if none of the users email addresses are in
400 * the To: or Cc: header. From here we try the following in order:
401 * 1) check for an Envelope-to: header
402 * 2) check for an X-Original-To: header
403 * 3) check for a (for <email@add.res>) clause in Received: headers
404 * 4) 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 < sizeof(to_headers)/sizeof(*to_headers); i++) {
409 tohdr = xstrdup(notmuch_message_get_header (message, to_headers[i]));
410 if (tohdr && *tohdr) {
411 /* tohdr is potentialy a list of email addresses, so here we
412 * check if one of the email addresses is a substring of tohdr
414 if (strcasestr(tohdr, primary)) {
418 for (j = 0; j < other_len; j++)
419 if (strcasestr (tohdr, other[j])) {
427 /* We get the concatenated Received: headers and search from the
428 * front (last Received: header added) and try to extract from
429 * them indications to which email address this message was
431 * The Received: header is special in our get_header function
432 * and is always concatenated.
434 received = notmuch_message_get_header (message, "received");
435 if (received == NULL)
438 /* First we look for a " for <email@add.res>" in the received
441 ptr = strstr (received, " for ");
443 /* the text following is potentialy a list of email addresses,
444 * so again we check if one of the email addresses is a
447 if (strcasestr(ptr, primary)) {
450 for (i = 0; i < other_len; i++)
451 if (strcasestr (ptr, other[i])) {
455 /* Finally, we parse all the " by MTA ..." headers to guess the
456 * email address that this was originally delivered to.
457 * We extract just the MTA here by removing leading whitespace and
458 * assuming that the MTA name ends at the next whitespace.
459 * We test for *(by+4) to be non-'\0' to make sure there's
460 * something there at all - and then assume that the first
461 * whitespace delimited token that follows is the receiving
462 * system in this step of the receive chain
465 while((by = strstr (by, " by ")) != NULL) {
470 token = strtok(mta," \t");
475 /* Now extract the last two components of the MTA host name
479 while ((ptr = strsep (&token, delim)) != NULL) {
487 /* Recombine domain and tld and look for it among the configured
489 * This time we have a known domain name and nothing else - so
490 * the test is the other way around: we check if this is a
491 * substring of one of the email addresses.
495 if (strcasestr(primary, domain)) {
499 for (i = 0; i < other_len; i++)
500 if (strcasestr (other[i],domain)) {
511 static GMimeMessage *
512 create_reply_message(void *ctx,
513 notmuch_config_t *config,
514 notmuch_message_t *message,
515 notmuch_bool_t reply_all)
517 const char *subject, *from_addr = NULL;
518 const char *in_reply_to, *orig_references, *references;
520 /* The 1 means we want headers in a "pretty" order. */
521 GMimeMessage *reply = g_mime_message_new (1);
523 fprintf (stderr, "Out of memory\n");
527 subject = notmuch_message_get_header (message, "subject");
529 if (strncasecmp (subject, "Re:", 3))
530 subject = talloc_asprintf (ctx, "Re: %s", subject);
531 g_mime_message_set_subject (reply, subject);
534 from_addr = add_recipients_from_message (reply, config,
537 if (from_addr == NULL)
538 from_addr = guess_from_received_header (config, message);
540 if (from_addr == NULL)
541 from_addr = notmuch_config_get_user_primary_email (config);
543 from_addr = talloc_asprintf (ctx, "%s <%s>",
544 notmuch_config_get_user_name (config),
546 g_mime_object_set_header (GMIME_OBJECT (reply),
549 in_reply_to = talloc_asprintf (ctx, "<%s>",
550 notmuch_message_get_message_id (message));
552 g_mime_object_set_header (GMIME_OBJECT (reply),
553 "In-Reply-To", in_reply_to);
555 orig_references = notmuch_message_get_header (message, "references");
556 references = talloc_asprintf (ctx, "%s%s%s",
557 orig_references ? orig_references : "",
558 orig_references ? " " : "",
560 g_mime_object_set_header (GMIME_OBJECT (reply),
561 "References", references);
567 notmuch_reply_format_default(void *ctx,
568 notmuch_config_t *config,
569 notmuch_query_t *query,
570 notmuch_show_params_t *params,
571 notmuch_bool_t reply_all)
574 notmuch_messages_t *messages;
575 notmuch_message_t *message;
578 for (messages = notmuch_query_search_messages (query);
579 notmuch_messages_valid (messages);
580 notmuch_messages_move_to_next (messages))
582 message = notmuch_messages_get (messages);
584 reply = create_reply_message (ctx, config, message, reply_all);
586 /* If reply creation failed, we're out of memory, so don't
587 * bother trying any more messages.
590 notmuch_message_destroy (message);
594 show_reply_headers (reply);
596 g_object_unref (G_OBJECT (reply));
599 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
600 &root) == NOTMUCH_STATUS_SUCCESS) {
601 format_part_reply (root);
605 notmuch_message_destroy (message);
611 notmuch_reply_format_json(void *ctx,
612 notmuch_config_t *config,
613 notmuch_query_t *query,
614 notmuch_show_params_t *params,
615 notmuch_bool_t reply_all)
618 notmuch_messages_t *messages;
619 notmuch_message_t *message;
622 if (notmuch_query_count_messages (query) != 1) {
623 fprintf (stderr, "Error: search term did not match precisely one message.\n");
627 messages = notmuch_query_search_messages (query);
628 message = notmuch_messages_get (messages);
629 if (mime_node_open (ctx, message, params->cryptoctx, params->decrypt,
630 &node) != NOTMUCH_STATUS_SUCCESS)
633 reply = create_reply_message (ctx, config, message, reply_all);
637 /* The headers of the reply message we've created */
638 printf ("{\"reply-headers\": ");
639 format_headers_json (ctx, reply, TRUE);
640 g_object_unref (G_OBJECT (reply));
643 /* Start the original */
644 printf (", \"original\": ");
646 format_part_json (ctx, node, TRUE);
650 notmuch_message_destroy (message);
655 /* This format is currently tuned for a git send-email --notmuch hook */
657 notmuch_reply_format_headers_only(void *ctx,
658 notmuch_config_t *config,
659 notmuch_query_t *query,
660 unused (notmuch_show_params_t *params),
661 notmuch_bool_t reply_all)
664 notmuch_messages_t *messages;
665 notmuch_message_t *message;
666 const char *in_reply_to, *orig_references, *references;
669 for (messages = notmuch_query_search_messages (query);
670 notmuch_messages_valid (messages);
671 notmuch_messages_move_to_next (messages))
673 message = notmuch_messages_get (messages);
675 /* The 0 means we do not want headers in a "pretty" order. */
676 reply = g_mime_message_new (0);
678 fprintf (stderr, "Out of memory\n");
682 in_reply_to = talloc_asprintf (ctx, "<%s>",
683 notmuch_message_get_message_id (message));
685 g_mime_object_set_header (GMIME_OBJECT (reply),
686 "In-Reply-To", in_reply_to);
689 orig_references = notmuch_message_get_header (message, "references");
691 /* We print In-Reply-To followed by References because git format-patch treats them
692 * specially. Git does not interpret the other headers specially
694 references = talloc_asprintf (ctx, "%s%s%s",
695 orig_references ? orig_references : "",
696 orig_references ? " " : "",
698 g_mime_object_set_header (GMIME_OBJECT (reply),
699 "References", references);
701 (void)add_recipients_from_message (reply, config, message, reply_all);
703 reply_headers = g_mime_object_to_string (GMIME_OBJECT (reply));
704 printf ("%s", reply_headers);
705 free (reply_headers);
707 g_object_unref (G_OBJECT (reply));
710 notmuch_message_destroy (message);
722 notmuch_reply_command (void *ctx, int argc, char *argv[])
724 notmuch_config_t *config;
725 notmuch_database_t *notmuch;
726 notmuch_query_t *query;
728 int opt_index, ret = 0;
729 int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params, notmuch_bool_t reply_all);
730 notmuch_show_params_t params = { .part = -1 };
731 int format = FORMAT_DEFAULT;
732 int reply_all = TRUE;
734 notmuch_opt_desc_t options[] = {
735 { NOTMUCH_OPT_KEYWORD, &format, "format", 'f',
736 (notmuch_keyword_t []){ { "default", FORMAT_DEFAULT },
737 { "json", FORMAT_JSON },
738 { "headers-only", FORMAT_HEADERS_ONLY },
740 { NOTMUCH_OPT_KEYWORD, &reply_all, "reply-to", 'r',
741 (notmuch_keyword_t []){ { "all", TRUE },
744 { NOTMUCH_OPT_BOOLEAN, ¶ms.decrypt, "decrypt", 'd', 0 },
748 opt_index = parse_arguments (argc, argv, options, 1);
750 /* diagnostics already printed */
754 if (format == FORMAT_HEADERS_ONLY)
755 reply_format_func = notmuch_reply_format_headers_only;
756 else if (format == FORMAT_JSON)
757 reply_format_func = notmuch_reply_format_json;
759 reply_format_func = notmuch_reply_format_default;
761 if (params.decrypt) {
762 #ifdef GMIME_ATLEAST_26
763 /* TODO: GMimePasswordRequestFunc */
764 params.cryptoctx = g_mime_gpg_context_new (NULL, "gpg");
766 GMimeSession* session = g_object_new (g_mime_session_get_type(), NULL);
767 params.cryptoctx = g_mime_gpg_context_new (session, "gpg");
769 if (params.cryptoctx) {
770 g_mime_gpg_context_set_always_trust ((GMimeGpgContext*) params.cryptoctx, FALSE);
772 params.decrypt = FALSE;
773 fprintf (stderr, "Failed to construct gpg context.\n");
775 #ifndef GMIME_ATLEAST_26
776 g_object_unref (session);
780 config = notmuch_config_open (ctx, NULL, NULL);
784 query_string = query_string_from_args (ctx, argc-opt_index, argv+opt_index);
785 if (query_string == NULL) {
786 fprintf (stderr, "Out of memory\n");
790 if (*query_string == '\0') {
791 fprintf (stderr, "Error: notmuch reply requires at least one search term.\n");
795 if (notmuch_database_open (notmuch_config_get_database_path (config),
796 NOTMUCH_DATABASE_MODE_READ_ONLY, ¬much))
799 query = notmuch_query_create (notmuch, query_string);
801 fprintf (stderr, "Out of memory\n");
805 if (reply_format_func (ctx, config, query, ¶ms, reply_all) != 0)
808 notmuch_query_destroy (query);
809 notmuch_database_destroy (notmuch);
811 if (params.cryptoctx)
812 g_object_unref(params.cryptoctx);