]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
7610aa41f97c455ef0cf650ad3a52ac03886f2d8
[notmuch] / notmuch-index-message.cc
1 /*
2  * Copyright © 2009 Carl Worth
3  *
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.
8  *
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.
13  *
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/ .
16  *
17  * Author: Carl Worth <cworth@cworth.org>
18  */
19
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).
26  *
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.
31  *
32  * Other differences between sup and notmuch-index identified so far:
33  *
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.
38  *
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
43  *     character.
44  *
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
49  *     in notmuch.
50  */
51
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <errno.h>
56 #include <time.h>
57 #include <sys/time.h>
58
59 #include <iostream>
60
61 #include <gmime/gmime.h>
62
63 #include <xapian.h>
64
65 using namespace std;
66
67 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
68
69 /* Xapian complains if we provide a term longer than this. */
70 #define NOTMUCH_MAX_TERM 245
71
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.
76  */
77
78 typedef struct {
79     const char *name;
80     const char *prefix;
81 } prefix_t;
82
83 prefix_t NORMAL_PREFIX[] = {
84     { "subject", "S" },
85     { "body", "B" },
86     { "from_name", "FN" },
87     { "to_name", "TN" },
88     { "name", "N" },
89     { "attachment", "A" }
90 };
91
92 prefix_t BOOLEAN_PREFIX[] = {
93     { "type", "K" },
94     { "from_email", "FE" },
95     { "to_email", "TE" },
96     { "email", "E" },
97     { "date", "D" },
98     { "label", "L" },
99     { "source_id", "I" },
100     { "attachment_extension", "O" },
101     { "msgid", "Q" },
102     { "thread", "H" },
103     { "ref", "R" }
104 };
105
106 /* Similarly, these value numbers are also chosen to be sup
107  * compatible. */
108
109 typedef enum {
110     NOTMUCH_VALUE_MESSAGE_ID = 0,
111     NOTMUCH_VALUE_THREAD = 1,
112     NOTMUCH_VALUE_DATE = 2
113 } notmuch_value_t;
114
115 static const char *
116 find_prefix (const char *name)
117 {
118     unsigned int i;
119
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;
123
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;
127
128     return "";
129 }
130
131 int TERM_COMBINED = 0;
132
133 static void
134 add_term (Xapian::Document doc,
135           const char *prefix_name,
136           const char *value)
137 {
138     const char *prefix;
139     char *term;
140
141     if (value == NULL)
142         return;
143
144     prefix = find_prefix (prefix_name);
145
146     term = g_strdup_printf ("%s%s", prefix, value);
147
148     if (strlen (term) <= NOTMUCH_MAX_TERM)
149         doc.add_term (term);
150
151     g_free (term);
152 }
153
154 static void
155 gen_terms (Xapian::TermGenerator term_gen,
156            const char *prefix_name,
157            const char *text)
158 {
159     const char *prefix;
160
161     if (text == NULL)
162         return;
163
164     prefix = find_prefix (prefix_name);
165
166     term_gen.index_text (text, 1, prefix);
167 }
168
169 static void
170 gen_terms_address_name (Xapian::TermGenerator term_gen,
171                         InternetAddress *address,
172                         const char *prefix_name)
173 {
174     if (INTERNET_ADDRESS_IS_MAILBOX(address)) {
175         const char *name;
176         int own_name = 0;
177
178         name = internet_address_get_name (address);
179
180         /* In the absence of a name, we'll strip the part before the @
181          * from the address. */
182         if (! name) {
183             InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
184             const char *addr = internet_address_mailbox_get_addr (mailbox);
185             const char *at;
186
187             at = strchr (addr, '@');
188             if (at) {
189                 name = strndup (addr, at - addr);
190                 own_name = 1;
191             }
192         }
193
194         if (name)
195             gen_terms (term_gen, prefix_name, name);
196
197         if (own_name)
198             free ((void *) name);
199     } else if (INTERNET_ADDRESS_IS_GROUP (address)) {
200         InternetAddressGroup *group = INTERNET_ADDRESS_GROUP (address);
201         InternetAddressList *list = internet_address_group_get_members(group);
202         if (list) {
203             int length = internet_address_list_length(list);
204             int i;
205
206             for (i = 0; i < length; i++)
207                 gen_terms_address_name(term_gen,
208                                        internet_address_list_get_address(list, i),
209                                        prefix_name);
210         }
211     }
212 }
213
214 static void
215 gen_terms_address_names (Xapian::TermGenerator term_gen,
216                          InternetAddressList *addresses,
217                          const char *address_type)
218 {
219     int i;
220     InternetAddress *address;
221
222     if (addresses == NULL)
223         return;
224
225     for (i = 0; i < internet_address_list_length (addresses); i++) {
226         address = internet_address_list_get_address (addresses, i);
227         gen_terms_address_name (term_gen, address, address_type);
228         gen_terms_address_name (term_gen, address, "name");
229         gen_terms_address_name (term_gen, address, "body");
230     }
231 }
232
233 static void
234 add_term_address_addr (Xapian::Document doc,
235                        InternetAddress *address,
236                        const char *prefix_name)
237 {
238     if (INTERNET_ADDRESS_IS_MAILBOX(address)) {
239         InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
240         const char *addr;
241
242         addr = internet_address_mailbox_get_addr (mailbox);
243
244         if (addr)
245             add_term (doc, prefix_name, addr);
246     } else if (INTERNET_ADDRESS_IS_GROUP (address)) {
247         InternetAddressGroup *group = INTERNET_ADDRESS_GROUP (address);
248         InternetAddressList *list = internet_address_group_get_members(group);
249         if (list) {
250             int length = internet_address_list_length(list);
251             int i;
252
253             for (i = 0; i < length; i++)
254                 add_term_address_addr(doc,
255                                       internet_address_list_get_address(list, i),
256                                       prefix_name);
257         }
258     }
259 }
260
261 static void
262 add_terms_address_addrs (Xapian::Document doc,
263                          InternetAddressList *addresses,
264                          const char *address_type)
265 {
266     int i;
267     InternetAddress *address;
268
269     if (addresses == NULL)
270         return;
271
272     for (i = 0; i < internet_address_list_length (addresses); i++) {
273         address = internet_address_list_get_address (addresses, i);
274         add_term_address_addr (doc, address, address_type);
275         add_term_address_addr (doc, address, "email");
276     }
277 }
278
279 static const char *
280 skip_re_in_subject (const char *subject)
281 {
282     const char *s = subject;
283
284     if (subject == NULL)
285         return NULL;
286
287     while (*s) {
288         while (*s && isspace (*s))
289             s++;
290         if (strncasecmp (s, "re:", 3) == 0)
291             s += 3;
292         else
293             break;
294     }
295
296     return s;
297 }
298
299 static void
300 find_messages_by_term (Xapian::Database db,
301                        const char *prefix_name,
302                        const char *value,
303                        Xapian::PostingIterator *begin,
304                        Xapian::PostingIterator *end)
305 {
306     Xapian::PostingIterator i;
307     char *term;
308
309     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
310
311     *begin = db.postlist_begin (term);
312
313     if (end)
314         *end = db.postlist_end (term);
315
316     free (term);
317 }
318
319 Xapian::Document
320 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
321 {
322     return db.get_document (docid);
323 }
324
325 Xapian::Document
326 find_message_by_message_id (Xapian::Database db, const char *message_id)
327 {
328     Xapian::PostingIterator i, end;
329
330     find_messages_by_term (db, "msgid", message_id, &i, &end);
331
332     if (i != end)
333         return find_message_by_docid (db, *i);
334     else
335         return Xapian::Document ();
336 }
337
338 static void
339 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
340 {
341     string value_string;
342     const char *value, *id, *comma;
343
344     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
345     value = value_string.c_str();
346     if (strlen (value)) {
347         id = value;
348         while (*id) {
349             comma = strchr (id, ',');
350             if (comma == NULL)
351                 comma = id + strlen (id);
352             g_hash_table_insert (thread_ids,
353                                  strndup (id, comma - id), NULL);
354             id = comma;
355             if (*id)
356                 id++;
357         }
358     }
359 }
360
361 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
362  * given message based on looking into the database for any messages
363  * referenced in parents, and also for any messages in the database
364  * referencing message_id.
365  *
366  * Caller should free all strings in the array and the array itself,
367  * (g_ptr_array_free) when done. */
368 static GPtrArray *
369 find_thread_ids (Xapian::Database db,
370                  GPtrArray *parents,
371                  const char *message_id)
372 {
373     Xapian::PostingIterator child, children_end;
374     Xapian::Document doc;
375     GHashTable *thread_ids;
376     GList *keys, *l;
377     unsigned int i;
378     const char *parent_message_id;
379     GPtrArray *result;
380
381     thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
382
383     find_messages_by_term (db, "ref", message_id, &child, &children_end);
384     for ( ; child != children_end; child++) {
385         doc = find_message_by_docid (db, *child);
386         insert_thread_id (thread_ids, doc);
387     }
388
389     for (i = 0; i < parents->len; i++) {
390         parent_message_id = (char *) g_ptr_array_index (parents, i);
391         doc = find_message_by_message_id (db, parent_message_id);
392         insert_thread_id (thread_ids, doc);
393     }
394
395     result = g_ptr_array_new ();
396
397     keys = g_hash_table_get_keys (thread_ids);
398     for (l = keys; l; l = l->next) {
399         char *id = (char *) l->data;
400         g_ptr_array_add (result, id);
401     }
402
403     return result;
404 }
405
406 /* Add a term for each message-id in the References header of the
407  * message. */
408 static void
409 parse_references (GPtrArray *array,
410                   const char *refs_str)
411 {
412     GMimeReferences *refs, *r;
413     const char *message_id;
414
415     if (refs_str == NULL)
416         return;
417
418     refs = g_mime_references_decode (refs_str);
419
420     for (r = refs; r; r = r->next) {
421         message_id = g_mime_references_get_message_id (r);
422         g_ptr_array_add (array, g_strdup (message_id));
423     }
424
425     g_mime_references_free (refs);
426 }
427
428 /* Given a string representing the body of a message, generate terms
429  * for it, (skipping quoted portions and signatures). */
430 static void
431 gen_terms_body_str (Xapian::TermGenerator term_gen,
432                     char *body)
433 {
434     char *line, *line_end, *next_line;
435
436     if (body == NULL)
437         return;
438
439     next_line = body;
440
441     while (1) {
442         line = next_line;
443         if (*line == '\0')
444             break;
445
446         next_line = strchr (line, '\n');
447         if (next_line == NULL) {
448             next_line = line + strlen (line);
449         }
450         line_end = next_line - 1;
451
452         /* Get to the next non-blank line. */
453         while (*next_line == '\n')
454             next_line++;
455
456         /* Skip lines that are quotes. */
457         if (*line == '>')
458             continue;
459
460         /* Also skip lines introducing a quote on the next line. */
461         if (*line_end == ':' && *next_line == '>')
462             continue;
463
464         /* Finally, bail as soon as we see a signature. */
465         /* XXX: Should only do this if "near" the end of the message. */
466         if (strncmp (line, "-- ", 3) == 0 ||
467             strncmp (line, "----------", 10) == 0 ||
468             strncmp (line, "__________", 10) == 0)
469             break;
470
471         *(line_end + 1) = '\0';
472         gen_terms (term_gen, "body", line);
473     }
474 }
475
476
477 /* Callback to generate terms for each mime part of a message. */
478 static void
479 gen_terms_part (Xapian::TermGenerator term_gen,
480                 GMimeObject *part)
481 {
482     GMimeStream *stream;
483     GMimeDataWrapper *wrapper;
484     GByteArray *byte_array;
485     GMimeContentDisposition *disposition;
486     char *body;
487
488     if (GMIME_IS_MULTIPART (part)) {
489         GMimeMultipart *multipart = GMIME_MULTIPART (part);
490         int i;
491
492         for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
493             if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
494                 /* Don't index the signature. */
495                 if (i == 1)
496                     continue;
497                 if (i > 1)
498                     fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
499             }
500             gen_terms_part (term_gen,
501                             g_mime_multipart_get_part (multipart, i));
502         }
503         return;
504     }
505
506     if (GMIME_IS_MESSAGE_PART (part)) {
507         GMimeMessage *message;
508
509         message = g_mime_message_part_get_message (GMIME_MESSAGE_PART (part));
510
511         gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
512
513         return;
514     }
515
516     if (! (GMIME_IS_PART (part))) {
517         fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
518                  g_type_name (G_OBJECT_TYPE (part)));
519         return;
520     }
521
522     disposition = g_mime_object_get_content_disposition (part);
523     if (disposition &&
524         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
525     {
526         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
527         const char *extension;
528
529         add_term (term_gen.get_document (), "label", "attachment");
530         gen_terms (term_gen, "attachment", filename);
531
532         if (filename) {
533             extension = strchr (filename, '.');
534             if (extension) {
535                 add_term (term_gen.get_document (), "attachment_extension",
536                           extension + 1);
537             }
538         }
539
540         return;
541     }
542
543     byte_array = g_byte_array_new ();
544
545     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
546     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
547     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
548     if (wrapper)
549         g_mime_data_wrapper_write_to_stream (wrapper, stream);
550
551     g_object_unref (stream);
552
553     g_byte_array_append (byte_array, (guint8 *) "\0", 1);
554     body = (char *) g_byte_array_free (byte_array, FALSE);
555
556     gen_terms_body_str (term_gen, body);
557
558     free (body);
559 }
560
561 static void
562 index_file (Xapian::WritableDatabase db,
563             Xapian::TermGenerator term_gen,
564             const char *filename)
565 {
566     Xapian::Document doc;
567
568     GMimeStream *stream;
569     GMimeParser *parser;
570     GMimeMessage *message;
571     InternetAddressList *addresses;
572     GPtrArray *parents, *thread_ids;
573
574     FILE *file;
575
576     const char *subject, *refs, *in_reply_to, *from;
577     const char *message_id;
578
579     time_t time;
580     struct tm gm_time_tm;
581     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
582     unsigned int i;
583
584     file = fopen (filename, "r");
585     if (! file) {
586         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
587         exit (1);
588     }
589
590     stream = g_mime_stream_file_new (file);
591
592     parser = g_mime_parser_new_with_stream (stream);
593
594     message = g_mime_parser_construct_message (parser);
595
596     doc = Xapian::Document ();
597
598     doc.set_data (filename);
599
600     term_gen.set_stemmer (Xapian::Stem ("english"));
601
602     term_gen.set_document (doc);
603
604     from = g_mime_message_get_sender (message);
605     addresses = internet_address_list_parse_string (from);
606
607     gen_terms_address_names (term_gen, addresses, "from_name");
608
609     addresses = g_mime_message_get_all_recipients (message);
610     gen_terms_address_names (term_gen, addresses, "to_name");
611
612     subject = g_mime_message_get_subject (message);
613     subject = skip_re_in_subject (subject);
614     gen_terms (term_gen, "subject", subject);
615     gen_terms (term_gen, "body", subject);
616
617     gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
618
619     parents = g_ptr_array_new ();
620
621     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
622     parse_references (parents, refs);
623
624     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
625                                             "in-reply-to");
626     parse_references (parents, in_reply_to);
627
628     for (i = 0; i < parents->len; i++)
629         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
630
631     message_id = g_mime_message_get_message_id (message);
632
633     thread_ids = find_thread_ids (db, parents, message_id);
634
635     for (i = 0; i < parents->len; i++)
636         g_free (g_ptr_array_index (parents, i));
637     g_ptr_array_free (parents, TRUE);
638
639     from = g_mime_message_get_sender (message);
640     addresses = internet_address_list_parse_string (from);
641
642     add_terms_address_addrs (doc, addresses, "from_email");
643
644     add_terms_address_addrs (doc,
645                              g_mime_message_get_all_recipients (message),
646                              "to_email");
647
648     g_mime_message_get_date (message, &time, NULL);
649
650     gmtime_r (&time, &gm_time_tm);
651
652     if (strftime (date_str, sizeof (date_str),
653                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
654         fprintf (stderr, "Internal error formatting time\n");
655         exit (1);
656     }
657
658     add_term (doc, "date", date_str);
659
660     add_term (doc, "label", "inbox");
661     add_term (doc, "label", "unread");
662     add_term (doc, "type", "mail");
663     add_term (doc, "source_id", "1");
664
665     if (message_id) {
666         add_term (doc, "msgid", message_id);
667         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
668     }
669
670     if (thread_ids->len) {
671         unsigned int i;
672         GString *thread_id;
673         char *id;
674
675         for (i = 0; i < thread_ids->len; i++) {
676             id = (char *) thread_ids->pdata[i];
677
678             add_term (doc, "thread", id);
679
680             if (i == 0)
681                 thread_id = g_string_new (id);
682             else
683                 g_string_append_printf (thread_id, ",%s", id);
684
685             free (id);
686         }
687         g_ptr_array_free (thread_ids, TRUE);
688
689         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
690
691         g_string_free (thread_id, TRUE);
692     } else if (message_id) {
693         /* If not referenced thread, use the message ID */
694         add_term (doc, "thread", message_id);
695         doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
696     }
697
698     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
699
700     db.add_document (doc);
701
702     g_object_unref (message);
703     g_object_unref (parser);
704     g_object_unref (stream);
705 }
706
707 static void
708 usage (const char *argv0)
709 {
710     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
711     fprintf (stderr, "\n");
712     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
713     fprintf (stderr, "one file per line.");
714 }
715
716 int
717 main (int argc, char **argv)
718 {
719     const char *database_path;
720     char *filename;
721     GIOChannel *channel;
722     GIOStatus gio_status;
723     GError *error = NULL;
724     int count;
725     struct timeval tv_start, tv_last, tv_now;
726     double elapsed;
727
728     if (argc < 2) {
729         usage (argv[0]);
730         exit (1);
731     }
732
733     database_path = argv[1];
734
735     g_mime_init (0);
736
737     try {
738         Xapian::WritableDatabase db;
739         Xapian::TermGenerator term_gen;
740
741         db = Xapian::WritableDatabase (database_path,
742                                        Xapian::DB_CREATE_OR_OPEN);
743
744         term_gen = Xapian::TermGenerator ();
745
746         channel = g_io_channel_unix_new (fileno (stdin));
747
748         count = 0;
749
750         gettimeofday (&tv_start, NULL);
751         tv_last = tv_start;
752
753         while (1) {
754             gio_status = g_io_channel_read_line (channel, &filename,
755                                                  NULL, NULL, &error);
756             if (gio_status == G_IO_STATUS_EOF)
757                 break;
758             if (gio_status != G_IO_STATUS_NORMAL) {
759                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
760                          error->message);
761                 exit (1);
762             }
763
764             g_strchomp (filename);
765             index_file (db, term_gen, filename);
766
767             g_free (filename);
768
769             count++;
770             if (count % 1000 == 0) {
771                 gettimeofday (&tv_now, NULL);
772                 printf ("Indexed %d messages (%g messages/second)\n",
773                         count, 1000 / ((tv_now.tv_sec - tv_last.tv_sec) +
774                                        (tv_now.tv_usec - tv_last.tv_usec) / 1e6));
775                 tv_last = tv_now;
776             }
777         }
778
779         gettimeofday (&tv_now, NULL);
780         elapsed = (tv_now.tv_sec - tv_start.tv_sec +
781                    (tv_now.tv_usec - tv_start.tv_usec) / 1e6);
782         printf ("Completed indexing of %d messages in %g seconds (%g messages/second)\n",
783                 count, elapsed, count / elapsed);
784
785     } catch (const Xapian::Error &error) {
786         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
787         exit (1);
788     }
789
790     return 0;
791 }