2 * Copyright © 2009 Carl Worth
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see http://www.gnu.org/licenses/ .
17 * Author: Carl Worth <cworth@cworth.org>
20 /* This indexer creates a Xapian mail index that is remarkably similar
21 * to that created by sup. The big difference, (and the thing that
22 * will keep a notmuch index from being used by sup directly), is that
23 * sup expects a serialized ruby data structure in the document's data
24 * field, but notmuch just puts the mail's filename there (trusting
25 * that the email client can get the data in needs from the filename).
27 * Note: One bug here is that sup actually merges together fields such
28 * as To, CC, Bcc etc. when finding multiple emails with the same
29 * message ID. To support something similar, notmuch should list
30 * multiple files in the data field.
32 * Other differences between sup and notmuch-index identified so far:
34 * o sup supports encrypted mime parts by prompting for a passphrase
35 * to decrypt the message. So far, notmuch doesn't support this,
36 * both because I'm lazy to code it, and I also think doing so
37 * would present a security leak.
39 * o sup and notmuch have different heuristics for identifying (and
40 * thus ignoring) signatures. For example, sup considers a line
41 * consisting of two hypens as a signature separator, while
42 * notmuch expects those two hyphens to be followed by a space
45 * o sup as been seen to split some numbers before indexing
46 * them. For example, the number 1754 in an email message was
47 * indexed by sup as separate terms 17 and 54. I couldn't find any
48 * explanation for this behavior and did not try to replicate it
61 #include <gmime/gmime.h>
67 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
69 /* Xapian complains if we provide a term longer than this. */
70 #define NOTMUCH_MAX_TERM 245
72 /* These prefix values are specifically chosen to be compatible
73 * with sup, (http://sup.rubyforge.org), written by
74 * William Morgan <wmorgan-sup@masanjin.net>, and released
75 * under the GNU GPL v2.
83 prefix_t NORMAL_PREFIX[] = {
86 { "from_name", "FN" },
92 prefix_t BOOLEAN_PREFIX[] = {
94 { "from_email", "FE" },
100 { "attachment_extension", "O" },
106 /* Similarly, these value numbers are also chosen to be sup
110 NOTMUCH_VALUE_MESSAGE_ID = 0,
111 NOTMUCH_VALUE_THREAD = 1,
112 NOTMUCH_VALUE_DATE = 2
116 find_prefix (const char *name)
120 for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
121 if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
122 return NORMAL_PREFIX[i].prefix;
124 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
125 if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
126 return BOOLEAN_PREFIX[i].prefix;
131 /* "128 bits of thread-id ought to be enough for anybody" */
132 #define NOTMUCH_THREAD_ID_BITS 128
133 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
134 typedef struct _thread_id {
135 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
139 thread_id_generate (thread_id_t *thread_id)
146 urandom = fopen ("/dev/urandom", "r");
147 if (urandom == NULL) {
148 fprintf (stderr, "Error opening /dev/urandom: %s\n",
150 fprintf (stderr, "Perhaps notmuch needs some portability fixes for your platform?\n");
155 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
156 fread ((void *) &value, sizeof (value), 1, urandom);
157 sprintf (s, "%08x", value);
163 printf ("Generated thread id: %s\n", thread_id->str);
167 add_term (Xapian::Document doc,
168 const char *prefix_name,
177 prefix = find_prefix (prefix_name);
179 term = g_strdup_printf ("%s%s", prefix, value);
181 if (strlen (term) <= NOTMUCH_MAX_TERM)
188 gen_terms (Xapian::TermGenerator term_gen,
189 const char *prefix_name,
197 prefix = find_prefix (prefix_name);
199 term_gen.index_text (text, 1, prefix);
203 gen_terms_address_name (Xapian::TermGenerator term_gen,
204 InternetAddress *address,
205 const char *prefix_name)
207 if (INTERNET_ADDRESS_IS_MAILBOX(address)) {
211 name = internet_address_get_name (address);
213 /* In the absence of a name, we'll strip the part before the @
214 * from the address. */
216 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
217 const char *addr = internet_address_mailbox_get_addr (mailbox);
220 at = strchr (addr, '@');
222 name = strndup (addr, at - addr);
228 gen_terms (term_gen, prefix_name, name);
231 free ((void *) name);
232 } else if (INTERNET_ADDRESS_IS_GROUP (address)) {
233 InternetAddressGroup *group = INTERNET_ADDRESS_GROUP (address);
234 InternetAddressList *list = internet_address_group_get_members(group);
236 int length = internet_address_list_length(list);
239 for (i = 0; i < length; i++)
240 gen_terms_address_name(term_gen,
241 internet_address_list_get_address(list, i),
248 gen_terms_address_names (Xapian::TermGenerator term_gen,
249 InternetAddressList *addresses,
250 const char *address_type)
253 InternetAddress *address;
255 if (addresses == NULL)
258 for (i = 0; i < internet_address_list_length (addresses); i++) {
259 address = internet_address_list_get_address (addresses, i);
260 gen_terms_address_name (term_gen, address, address_type);
261 gen_terms_address_name (term_gen, address, "name");
262 gen_terms_address_name (term_gen, address, "body");
267 add_term_address_addr (Xapian::Document doc,
268 InternetAddress *address,
269 const char *prefix_name)
271 if (INTERNET_ADDRESS_IS_MAILBOX(address)) {
272 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
275 addr = internet_address_mailbox_get_addr (mailbox);
278 add_term (doc, prefix_name, addr);
279 } else if (INTERNET_ADDRESS_IS_GROUP (address)) {
280 InternetAddressGroup *group = INTERNET_ADDRESS_GROUP (address);
281 InternetAddressList *list = internet_address_group_get_members(group);
283 int length = internet_address_list_length(list);
286 for (i = 0; i < length; i++)
287 add_term_address_addr(doc,
288 internet_address_list_get_address(list, i),
295 add_terms_address_addrs (Xapian::Document doc,
296 InternetAddressList *addresses,
297 const char *address_type)
300 InternetAddress *address;
302 if (addresses == NULL)
305 for (i = 0; i < internet_address_list_length (addresses); i++) {
306 address = internet_address_list_get_address (addresses, i);
307 add_term_address_addr (doc, address, address_type);
308 add_term_address_addr (doc, address, "email");
313 skip_re_in_subject (const char *subject)
315 const char *s = subject;
321 while (*s && isspace (*s))
323 if (strncasecmp (s, "re:", 3) == 0)
333 find_messages_by_term (Xapian::Database db,
334 const char *prefix_name,
336 Xapian::PostingIterator *begin,
337 Xapian::PostingIterator *end)
339 Xapian::PostingIterator i;
342 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
344 *begin = db.postlist_begin (term);
347 *end = db.postlist_end (term);
353 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
355 return db.get_document (docid);
359 find_message_by_message_id (Xapian::Database db, const char *message_id)
361 Xapian::PostingIterator i, end;
363 find_messages_by_term (db, "msgid", message_id, &i, &end);
366 return find_message_by_docid (db, *i);
368 return Xapian::Document ();
372 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
375 const char *value, *id, *comma;
377 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
378 value = value_string.c_str();
379 if (strlen (value)) {
382 comma = strchr (id, ',');
384 comma = id + strlen (id);
385 g_hash_table_insert (thread_ids,
386 strndup (id, comma - id), NULL);
394 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
395 * given message based on looking into the database for any messages
396 * referenced in parents, and also for any messages in the database
397 * referencing message_id.
399 * Caller should free all strings in the array and the array itself,
400 * (g_ptr_array_free) when done. */
402 find_thread_ids (Xapian::Database db,
404 const char *message_id)
406 Xapian::PostingIterator child, children_end;
407 Xapian::Document doc;
408 GHashTable *thread_ids;
411 const char *parent_message_id;
414 thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
416 find_messages_by_term (db, "ref", message_id, &child, &children_end);
417 for ( ; child != children_end; child++) {
418 doc = find_message_by_docid (db, *child);
419 insert_thread_id (thread_ids, doc);
422 for (i = 0; i < parents->len; i++) {
423 parent_message_id = (char *) g_ptr_array_index (parents, i);
424 doc = find_message_by_message_id (db, parent_message_id);
425 insert_thread_id (thread_ids, doc);
428 result = g_ptr_array_new ();
430 keys = g_hash_table_get_keys (thread_ids);
431 for (l = keys; l; l = l->next) {
432 char *id = (char *) l->data;
433 g_ptr_array_add (result, id);
439 /* Add a term for each message-id in the References header of the
442 parse_references (GPtrArray *array,
443 const char *refs_str)
445 GMimeReferences *refs, *r;
446 const char *message_id;
448 if (refs_str == NULL)
451 refs = g_mime_references_decode (refs_str);
453 for (r = refs; r; r = r->next) {
454 message_id = g_mime_references_get_message_id (r);
455 g_ptr_array_add (array, g_strdup (message_id));
458 g_mime_references_free (refs);
461 /* Given a string representing the body of a message, generate terms
462 * for it, (skipping quoted portions and signatures). */
464 gen_terms_body_str (Xapian::TermGenerator term_gen,
467 char *line, *line_end, *next_line;
479 next_line = strchr (line, '\n');
480 if (next_line == NULL) {
481 next_line = line + strlen (line);
483 line_end = next_line - 1;
485 /* Get to the next non-blank line. */
486 while (*next_line == '\n')
489 /* Skip blank lines. */
493 /* Skip lines that are quotes. */
497 /* Also skip lines introducing a quote on the next line. */
498 if (*line_end == ':' && *next_line == '>')
501 /* Finally, bail as soon as we see a signature. */
502 /* XXX: Should only do this if "near" the end of the message. */
503 if (strncmp (line, "-- ", 3) == 0 ||
504 strncmp (line, "----------", 10) == 0 ||
505 strncmp (line, "__________", 10) == 0)
508 *(line_end + 1) = '\0';
509 gen_terms (term_gen, "body", line);
514 /* Callback to generate terms for each mime part of a message. */
516 gen_terms_part (Xapian::TermGenerator term_gen,
520 GMimeDataWrapper *wrapper;
521 GByteArray *byte_array;
522 GMimeContentDisposition *disposition;
525 if (GMIME_IS_MULTIPART (part)) {
526 GMimeMultipart *multipart = GMIME_MULTIPART (part);
529 for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
530 if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
531 /* Don't index the signature. */
535 fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
537 gen_terms_part (term_gen,
538 g_mime_multipart_get_part (multipart, i));
543 if (GMIME_IS_MESSAGE_PART (part)) {
544 GMimeMessage *message;
546 message = g_mime_message_part_get_message (GMIME_MESSAGE_PART (part));
548 gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
553 if (! (GMIME_IS_PART (part))) {
554 fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
555 g_type_name (G_OBJECT_TYPE (part)));
559 disposition = g_mime_object_get_content_disposition (part);
561 strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
563 const char *filename = g_mime_part_get_filename (GMIME_PART (part));
564 const char *extension;
566 add_term (term_gen.get_document (), "label", "attachment");
567 gen_terms (term_gen, "attachment", filename);
570 extension = strchr (filename, '.');
572 add_term (term_gen.get_document (), "attachment_extension",
580 byte_array = g_byte_array_new ();
582 stream = g_mime_stream_mem_new_with_byte_array (byte_array);
583 g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
584 wrapper = g_mime_part_get_content_object (GMIME_PART (part));
586 g_mime_data_wrapper_write_to_stream (wrapper, stream);
588 g_object_unref (stream);
590 g_byte_array_append (byte_array, (guint8 *) "\0", 1);
591 body = (char *) g_byte_array_free (byte_array, FALSE);
593 gen_terms_body_str (term_gen, body);
599 index_file (Xapian::WritableDatabase db,
600 Xapian::TermGenerator term_gen,
601 const char *filename)
603 Xapian::Document doc;
607 GMimeMessage *message;
608 InternetAddressList *addresses;
609 GPtrArray *parents, *thread_ids;
613 const char *subject, *refs, *in_reply_to, *from;
614 const char *message_id;
617 struct tm gm_time_tm;
618 char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
621 file = fopen (filename, "r");
623 fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
627 stream = g_mime_stream_file_new (file);
629 parser = g_mime_parser_new_with_stream (stream);
631 message = g_mime_parser_construct_message (parser);
633 doc = Xapian::Document ();
635 doc.set_data (filename);
637 term_gen.set_stemmer (Xapian::Stem ("english"));
639 term_gen.set_document (doc);
641 from = g_mime_message_get_sender (message);
642 addresses = internet_address_list_parse_string (from);
644 gen_terms_address_names (term_gen, addresses, "from_name");
646 addresses = g_mime_message_get_all_recipients (message);
647 gen_terms_address_names (term_gen, addresses, "to_name");
649 subject = g_mime_message_get_subject (message);
650 subject = skip_re_in_subject (subject);
651 gen_terms (term_gen, "subject", subject);
652 gen_terms (term_gen, "body", subject);
654 gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
656 parents = g_ptr_array_new ();
658 refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
659 parse_references (parents, refs);
661 in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
663 parse_references (parents, in_reply_to);
665 for (i = 0; i < parents->len; i++)
666 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
668 message_id = g_mime_message_get_message_id (message);
670 thread_ids = find_thread_ids (db, parents, message_id);
672 for (i = 0; i < parents->len; i++)
673 g_free (g_ptr_array_index (parents, i));
674 g_ptr_array_free (parents, TRUE);
676 from = g_mime_message_get_sender (message);
677 addresses = internet_address_list_parse_string (from);
679 add_terms_address_addrs (doc, addresses, "from_email");
681 add_terms_address_addrs (doc,
682 g_mime_message_get_all_recipients (message),
685 g_mime_message_get_date (message, &time, NULL);
687 gmtime_r (&time, &gm_time_tm);
689 if (strftime (date_str, sizeof (date_str),
690 "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
691 fprintf (stderr, "Internal error formatting time\n");
695 add_term (doc, "date", date_str);
697 add_term (doc, "label", "inbox");
698 add_term (doc, "label", "unread");
699 add_term (doc, "type", "mail");
700 add_term (doc, "source_id", "1");
703 add_term (doc, "msgid", message_id);
704 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
707 if (thread_ids->len) {
712 for (i = 0; i < thread_ids->len; i++) {
713 id = (char *) thread_ids->pdata[i];
715 add_term (doc, "thread", id);
718 thread_id = g_string_new (id);
720 g_string_append_printf (thread_id, ",%s", id);
724 g_ptr_array_free (thread_ids, TRUE);
726 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
728 g_string_free (thread_id, TRUE);
729 } else if (message_id) {
730 /* If not part of any existing thread, generate a new thread_id. */
731 thread_id_t thread_id;
733 thread_id_generate (&thread_id);
735 add_term (doc, "thread", thread_id.str);
736 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
739 doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
741 db.add_document (doc);
743 g_object_unref (message);
744 g_object_unref (parser);
745 g_object_unref (stream);
749 usage (const char *argv0)
751 fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
752 fprintf (stderr, "\n");
753 fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
754 fprintf (stderr, "one file per line.");
758 main (int argc, char **argv)
760 const char *database_path;
763 GIOStatus gio_status;
764 GError *error = NULL;
766 struct timeval tv_start, tv_last, tv_now;
774 database_path = argv[1];
779 Xapian::WritableDatabase db;
780 Xapian::TermGenerator term_gen;
782 db = Xapian::WritableDatabase (database_path,
783 Xapian::DB_CREATE_OR_OPEN);
785 term_gen = Xapian::TermGenerator ();
787 channel = g_io_channel_unix_new (fileno (stdin));
791 gettimeofday (&tv_start, NULL);
795 gio_status = g_io_channel_read_line (channel, &filename,
797 if (gio_status == G_IO_STATUS_EOF)
799 if (gio_status != G_IO_STATUS_NORMAL) {
800 fprintf (stderr, "An error occurred reading from stdin: %s\n",
805 g_strchomp (filename);
806 index_file (db, term_gen, filename);
811 if (count % 1000 == 0) {
812 gettimeofday (&tv_now, NULL);
813 printf ("Indexed %d messages (%g messages/second)\n",
814 count, 1000 / ((tv_now.tv_sec - tv_last.tv_sec) +
815 (tv_now.tv_usec - tv_last.tv_usec) / 1e6));
820 g_io_channel_unref (channel);
822 gettimeofday (&tv_now, NULL);
823 elapsed = (tv_now.tv_sec - tv_start.tv_sec +
824 (tv_now.tv_usec - tv_start.tv_usec) / 1e6);
825 printf ("Completed indexing of %d messages in %g seconds (%g messages/second)\n",
826 count, elapsed, count / elapsed);
828 } catch (const Xapian::Error &error) {
829 cerr << "A Xapian exception occurred: " << error.get_msg () << endl;