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 int TERM_COMBINED = 0;
134 add_term (Xapian::Document doc,
135 const char *prefix_name,
144 prefix = find_prefix (prefix_name);
146 term = g_strdup_printf ("%s%s", prefix, value);
148 if (strlen (term) <= NOTMUCH_MAX_TERM)
155 gen_terms (Xapian::TermGenerator term_gen,
156 const char *prefix_name,
164 prefix = find_prefix (prefix_name);
166 term_gen.index_text (text, 1, prefix);
170 gen_terms_address_name (Xapian::TermGenerator term_gen,
171 InternetAddress *address,
172 const char *prefix_name)
177 name = internet_address_get_name (address);
179 /* In the absence of a name, we'll strip the part before the @
180 * from the address. */
182 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
183 const char *addr = internet_address_mailbox_get_addr (mailbox);
186 at = strchr (addr, '@');
188 name = strndup (addr, at - addr);
194 gen_terms (term_gen, prefix_name, name);
197 free ((void *) name);
201 gen_terms_address_names (Xapian::TermGenerator term_gen,
202 InternetAddressList *addresses,
203 const char *address_type)
206 InternetAddress *address;
208 if (addresses == NULL)
211 for (i = 0; i < internet_address_list_length (addresses); i++) {
212 address = internet_address_list_get_address (addresses, i);
213 gen_terms_address_name (term_gen, address, address_type);
214 gen_terms_address_name (term_gen, address, "name");
215 gen_terms_address_name (term_gen, address, "body");
220 add_term_address_addr (Xapian::Document doc,
221 InternetAddress *address,
222 const char *prefix_name)
224 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
227 addr = internet_address_mailbox_get_addr (mailbox);
230 add_term (doc, prefix_name, addr);
234 add_terms_address_addrs (Xapian::Document doc,
235 InternetAddressList *addresses,
236 const char *address_type)
239 InternetAddress *address;
241 if (addresses == NULL)
244 for (i = 0; i < internet_address_list_length (addresses); i++) {
245 address = internet_address_list_get_address (addresses, i);
246 add_term_address_addr (doc, address, address_type);
247 add_term_address_addr (doc, address, "email");
252 skip_re_in_subject (const char *subject)
254 const char *s = subject;
260 while (*s && isspace (*s))
262 if (strncasecmp (s, "re:", 3) == 0)
272 find_messages_by_term (Xapian::Database db,
273 const char *prefix_name,
275 Xapian::PostingIterator *begin,
276 Xapian::PostingIterator *end)
278 Xapian::PostingIterator i;
281 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
283 *begin = db.postlist_begin (term);
286 *end = db.postlist_end (term);
292 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
294 return db.get_document (docid);
298 find_message_by_message_id (Xapian::Database db, const char *message_id)
300 Xapian::PostingIterator i, end;
302 find_messages_by_term (db, "msgid", message_id, &i, &end);
305 return find_message_by_docid (db, *i);
307 return Xapian::Document ();
311 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
314 const char *value, *id, *comma;
316 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
317 value = value_string.c_str();
318 if (strlen (value)) {
321 comma = strchr (id, ',');
323 comma = id + strlen (id);
324 g_hash_table_insert (thread_ids,
325 strndup (id, comma - id), NULL);
333 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
334 * given message based on looking into the database for any messages
335 * referenced in parents, and also for any messages in the database
336 * referencing message_id.
338 * Caller should free all strings in the array and the array itself,
339 * (g_ptr_array_free) when done. */
341 find_thread_ids (Xapian::Database db,
343 const char *message_id)
345 Xapian::PostingIterator child, children_end;
346 Xapian::Document doc;
347 GHashTable *thread_ids;
350 const char *parent_message_id;
353 thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
355 find_messages_by_term (db, "ref", message_id, &child, &children_end);
356 for ( ; child != children_end; child++) {
357 doc = find_message_by_docid (db, *child);
358 insert_thread_id (thread_ids, doc);
361 for (i = 0; i < parents->len; i++) {
362 parent_message_id = (char *) g_ptr_array_index (parents, i);
363 doc = find_message_by_message_id (db, parent_message_id);
364 insert_thread_id (thread_ids, doc);
367 result = g_ptr_array_new ();
369 keys = g_hash_table_get_keys (thread_ids);
370 for (l = keys; l; l = l->next) {
371 char *id = (char *) l->data;
372 g_ptr_array_add (result, id);
378 /* Add a term for each message-id in the References header of the
381 parse_references (GPtrArray *array,
382 const char *refs_str)
384 GMimeReferences *refs, *r;
385 const char *message_id;
387 if (refs_str == NULL)
390 refs = g_mime_references_decode (refs_str);
392 for (r = refs; r; r = r->next) {
393 message_id = g_mime_references_get_message_id (r);
394 g_ptr_array_add (array, g_strdup (message_id));
397 g_mime_references_free (refs);
400 /* Given a string representing the body of a message, generate terms
401 * for it, (skipping quoted portions and signatures). */
403 gen_terms_body_str (Xapian::TermGenerator term_gen,
406 char *line, *line_end, *next_line;
418 next_line = strchr (line, '\n');
419 if (next_line == NULL) {
420 next_line = line + strlen (line);
422 line_end = next_line - 1;
424 /* Get to the next non-blank line. */
425 while (*next_line == '\n')
428 /* Skip lines that are quotes. */
432 /* Also skip lines introducing a quote on the next line. */
433 if (*line_end == ':' && *next_line == '>')
436 /* Finally, bail as soon as we see a signature. */
437 /* XXX: Should only do this if "near" the end of the message. */
438 if (strncmp (line, "-- ", 3) == 0 ||
439 strncmp (line, "----------", 10) == 0 ||
440 strncmp (line, "__________", 10) == 0)
443 *(line_end + 1) = '\0';
444 gen_terms (term_gen, "body", line);
449 /* Callback to generate terms for each mime part of a message. */
451 gen_terms_part (Xapian::TermGenerator term_gen,
455 GMimeDataWrapper *wrapper;
456 GByteArray *byte_array;
457 GMimeContentDisposition *disposition;
460 if (GMIME_IS_MULTIPART (part)) {
461 GMimeMultipart *multipart = GMIME_MULTIPART (part);
464 for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
465 if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
466 /* Don't index the signature. */
470 fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
472 gen_terms_part (term_gen,
473 g_mime_multipart_get_part (multipart, i));
478 if (GMIME_IS_MESSAGE_PART (part)) {
479 GMimeMessage *message;
481 message = g_mime_message_part_get_message (GMIME_MESSAGE_PART (part));
483 gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
488 if (! (GMIME_IS_PART (part))) {
489 fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
490 g_type_name (G_OBJECT_TYPE (part)));
494 disposition = g_mime_object_get_content_disposition (part);
496 strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
498 const char *filename = g_mime_part_get_filename (GMIME_PART (part));
499 const char *extension;
501 add_term (term_gen.get_document (), "label", "attachment");
502 gen_terms (term_gen, "attachment", filename);
505 extension = strchr (filename, '.');
507 add_term (term_gen.get_document (), "attachment_extension",
515 byte_array = g_byte_array_new ();
517 stream = g_mime_stream_mem_new_with_byte_array (byte_array);
518 g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
519 wrapper = g_mime_part_get_content_object (GMIME_PART (part));
521 g_mime_data_wrapper_write_to_stream (wrapper, stream);
523 g_object_unref (stream);
525 g_byte_array_append (byte_array, (guint8 *) "\0", 1);
526 body = (char *) g_byte_array_free (byte_array, FALSE);
528 gen_terms_body_str (term_gen, body);
534 index_file (Xapian::WritableDatabase db,
535 Xapian::TermGenerator term_gen,
536 const char *filename)
538 Xapian::Document doc;
542 GMimeMessage *message;
543 InternetAddressList *addresses;
544 GPtrArray *parents, *thread_ids;
548 const char *subject, *refs, *in_reply_to, *from;
549 const char *message_id;
552 struct tm gm_time_tm;
553 char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
556 file = fopen (filename, "r");
558 fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
562 stream = g_mime_stream_file_new (file);
564 parser = g_mime_parser_new_with_stream (stream);
566 message = g_mime_parser_construct_message (parser);
568 doc = Xapian::Document ();
570 doc.set_data (filename);
572 term_gen.set_stemmer (Xapian::Stem ("english"));
574 term_gen.set_document (doc);
576 from = g_mime_message_get_sender (message);
577 addresses = internet_address_list_parse_string (from);
579 gen_terms_address_names (term_gen, addresses, "from_name");
581 addresses = g_mime_message_get_all_recipients (message);
582 gen_terms_address_names (term_gen, addresses, "to_name");
584 subject = g_mime_message_get_subject (message);
585 subject = skip_re_in_subject (subject);
586 gen_terms (term_gen, "subject", subject);
587 gen_terms (term_gen, "body", subject);
589 gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
591 parents = g_ptr_array_new ();
593 refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
594 parse_references (parents, refs);
596 in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
598 parse_references (parents, in_reply_to);
600 for (i = 0; i < parents->len; i++)
601 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
603 message_id = g_mime_message_get_message_id (message);
605 thread_ids = find_thread_ids (db, parents, message_id);
607 for (i = 0; i < parents->len; i++)
608 g_free (g_ptr_array_index (parents, i));
609 g_ptr_array_free (parents, TRUE);
611 from = g_mime_message_get_sender (message);
612 addresses = internet_address_list_parse_string (from);
614 add_terms_address_addrs (doc, addresses, "from_email");
616 add_terms_address_addrs (doc,
617 g_mime_message_get_all_recipients (message),
620 g_mime_message_get_date (message, &time, NULL);
622 gmtime_r (&time, &gm_time_tm);
624 if (strftime (date_str, sizeof (date_str),
625 "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
626 fprintf (stderr, "Internal error formatting time\n");
630 add_term (doc, "date", date_str);
632 add_term (doc, "label", "inbox");
633 add_term (doc, "label", "unread");
634 add_term (doc, "type", "mail");
635 add_term (doc, "source_id", "1");
637 add_term (doc, "msgid", message_id);
638 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
640 if (thread_ids->len) {
645 for (i = 0; i < thread_ids->len; i++) {
646 id = (char *) thread_ids->pdata[i];
648 add_term (doc, "thread", id);
651 thread_id = g_string_new (id);
653 g_string_append_printf (thread_id, ",%s", id);
657 g_ptr_array_free (thread_ids, TRUE);
659 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
661 g_string_free (thread_id, TRUE);
663 /* If not referenced thread, use the message ID */
664 add_term (doc, "thread", message_id);
665 doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
668 doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
670 db.add_document (doc);
672 g_object_unref (message);
673 g_object_unref (parser);
674 g_object_unref (stream);
678 usage (const char *argv0)
680 fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
681 fprintf (stderr, "\n");
682 fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
683 fprintf (stderr, "one file per line.");
687 main (int argc, char **argv)
689 const char *database_path;
692 GIOStatus gio_status;
693 GError *error = NULL;
695 struct timeval tv_start, tv_now;
702 database_path = argv[1];
707 Xapian::WritableDatabase db;
708 Xapian::TermGenerator term_gen;
710 db = Xapian::WritableDatabase (database_path,
711 Xapian::DB_CREATE_OR_OPEN);
713 term_gen = Xapian::TermGenerator ();
715 channel = g_io_channel_unix_new (fileno (stdin));
719 gettimeofday (&tv_start, NULL);
722 gio_status = g_io_channel_read_line (channel, &filename,
724 if (gio_status == G_IO_STATUS_EOF)
726 if (gio_status != G_IO_STATUS_NORMAL) {
727 fprintf (stderr, "An error occurred reading from stdin: %s\n",
732 g_strchomp (filename);
733 index_file (db, term_gen, filename);
738 if (count % 1000 == 0) {
739 gettimeofday (&tv_now, NULL);
740 printf ("Indexed %d messages (%g messages/second)\n",
741 count, count / ((tv_now.tv_sec - tv_start.tv_sec) +
742 (tv_now.tv_usec - tv_start.tv_usec) / 1e6));
746 } catch (const Xapian::Error &error) {
747 cerr << "A Xapian exception occurred: " << error.get_msg () << endl;