]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
a3483b93b6b35b01c1bb95caa8beba2b55d70526
[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     const char *name;
175     int own_name = 0;
176
177     name = internet_address_get_name (address);
178
179     /* In the absence of a name, we'll strip the part before the @
180      * from the address. */
181     if (! name) {
182         InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
183         const char *addr = internet_address_mailbox_get_addr (mailbox);
184         const char *at;
185
186         at = strchr (addr, '@');
187         if (at) {
188             name = strndup (addr, at - addr);
189             own_name = 1;
190         }
191     }
192
193     if (name)
194         gen_terms (term_gen, prefix_name, name);
195
196     if (own_name)
197         free ((void *) name);
198 }
199
200 static void
201 gen_terms_address_names (Xapian::TermGenerator term_gen,
202                          InternetAddressList *addresses,
203                          const char *address_type)
204 {
205     int i;
206     InternetAddress *address;
207
208     if (addresses == NULL)
209         return;
210
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");
216     }
217 }
218
219 static void
220 add_term_address_addr (Xapian::Document doc,
221                        InternetAddress *address,
222                        const char *prefix_name)
223 {
224     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
225     const char *addr;
226
227     addr = internet_address_mailbox_get_addr (mailbox);
228
229     if (addr)
230         add_term (doc, prefix_name, addr);
231 }
232
233 static void
234 add_terms_address_addrs (Xapian::Document doc,
235                          InternetAddressList *addresses,
236                          const char *address_type)
237 {
238     int i;
239     InternetAddress *address;
240
241     if (addresses == NULL)
242         return;
243
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");
248     }
249 }
250
251 static const char *
252 skip_re_in_subject (const char *subject)
253 {
254     const char *s = subject;
255
256     if (subject == NULL)
257         return NULL;
258
259     while (*s) {
260         while (*s && isspace (*s))
261             s++;
262         if (strncasecmp (s, "re:", 3) == 0)
263             s += 3;
264         else
265             break;
266     }
267
268     return s;
269 }
270
271 static void
272 find_messages_by_term (Xapian::Database db,
273                        const char *prefix_name,
274                        const char *value,
275                        Xapian::PostingIterator *begin,
276                        Xapian::PostingIterator *end)
277 {
278     Xapian::PostingIterator i;
279     char *term;
280
281     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
282
283     *begin = db.postlist_begin (term);
284
285     if (end)
286         *end = db.postlist_end (term);
287
288     free (term);
289 }
290
291 Xapian::Document
292 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
293 {
294     return db.get_document (docid);
295 }
296
297 Xapian::Document
298 find_message_by_message_id (Xapian::Database db, const char *message_id)
299 {
300     Xapian::PostingIterator i, end;
301
302     find_messages_by_term (db, "msgid", message_id, &i, &end);
303
304     if (i != end)
305         return find_message_by_docid (db, *i);
306     else
307         return Xapian::Document ();
308 }
309
310 static void
311 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
312 {
313     string value_string;
314     const char *value, *id, *comma;
315
316     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
317     value = value_string.c_str();
318     if (strlen (value)) {
319         id = value;
320         while (*id) {
321             comma = strchr (id, ',');
322             if (comma == NULL)
323                 comma = id + strlen (id);
324             g_hash_table_insert (thread_ids,
325                                  strndup (id, comma - id), NULL);
326             id = comma;
327             if (*id)
328                 id++;
329         }
330     }
331 }
332
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.
337  *
338  * Caller should free all strings in the array and the array itself,
339  * (g_ptr_array_free) when done. */
340 static GPtrArray *
341 find_thread_ids (Xapian::Database db,
342                  GPtrArray *parents,
343                  const char *message_id)
344 {
345     Xapian::PostingIterator child, children_end;
346     Xapian::Document doc;
347     GHashTable *thread_ids;
348     GList *keys, *l;
349     unsigned int i;
350     const char *parent_message_id;
351     GPtrArray *result;
352
353     thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
354
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);
359     }
360
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);
365     }
366
367     result = g_ptr_array_new ();
368
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);
373     }
374
375     return result;
376 }
377
378 /* Add a term for each message-id in the References header of the
379  * message. */
380 static void
381 parse_references (GPtrArray *array,
382                   const char *refs_str)
383 {
384     GMimeReferences *refs, *r;
385     const char *message_id;
386
387     if (refs_str == NULL)
388         return;
389
390     refs = g_mime_references_decode (refs_str);
391
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));
395     }
396
397     g_mime_references_free (refs);
398 }
399
400 /* Given a string representing the body of a message, generate terms
401  * for it, (skipping quoted portions and signatures). */
402 static void
403 gen_terms_body_str (Xapian::TermGenerator term_gen,
404                     char *body)
405 {
406     char *line, *line_end, *next_line;
407
408     if (body == NULL)
409         return;
410
411     next_line = body;
412
413     while (1) {
414         line = next_line;
415         if (*line == '\0')
416             break;
417
418         next_line = strchr (line, '\n');
419         if (next_line == NULL) {
420             next_line = line + strlen (line);
421         }
422         line_end = next_line - 1;
423
424         /* Get to the next non-blank line. */
425         while (*next_line == '\n')
426             next_line++;
427
428         /* Skip lines that are quotes. */
429         if (*line == '>')
430             continue;
431
432         /* Also skip lines introducing a quote on the next line. */
433         if (*line_end == ':' && *next_line == '>')
434             continue;
435
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)
441             break;
442
443         *(line_end + 1) = '\0';
444         gen_terms (term_gen, "body", line);
445     }
446 }
447
448
449 /* Callback to generate terms for each mime part of a message. */
450 static void
451 gen_terms_part (Xapian::TermGenerator term_gen,
452                 GMimeObject *part)
453 {
454     GMimeStream *stream;
455     GMimeDataWrapper *wrapper;
456     GByteArray *byte_array;
457     GMimeContentDisposition *disposition;
458     char *body;
459
460     if (GMIME_IS_MULTIPART (part)) {
461         GMimeMultipart *multipart = GMIME_MULTIPART (part);
462         int i;
463
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. */
467                 if (i == 1)
468                     continue;
469                 if (i > 1)
470                     fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
471             }
472             gen_terms_part (term_gen,
473                             g_mime_multipart_get_part (multipart, i));
474         }
475         return;
476     }
477
478     if (GMIME_IS_MESSAGE_PART (part)) {
479         GMimeMessage *message;
480
481         message = g_mime_message_part_get_message (GMIME_MESSAGE_PART (part));
482
483         gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
484
485         return;
486     }
487
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)));
491         return;
492     }
493
494     disposition = g_mime_object_get_content_disposition (part);
495     if (disposition &&
496         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
497     {
498         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
499         const char *extension;
500
501         add_term (term_gen.get_document (), "label", "attachment");
502         gen_terms (term_gen, "attachment", filename);
503
504         if (filename) {
505             extension = strchr (filename, '.');
506             if (extension) {
507                 add_term (term_gen.get_document (), "attachment_extension",
508                           extension + 1);
509             }
510         }
511
512         return;
513     }
514
515     byte_array = g_byte_array_new ();
516
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));
520     if (wrapper)
521         g_mime_data_wrapper_write_to_stream (wrapper, stream);
522
523     g_object_unref (stream);
524
525     g_byte_array_append (byte_array, (guint8 *) "\0", 1);
526     body = (char *) g_byte_array_free (byte_array, FALSE);
527
528     gen_terms_body_str (term_gen, body);
529
530     free (body);
531 }
532
533 static void
534 index_file (Xapian::WritableDatabase db,
535             Xapian::TermGenerator term_gen,
536             const char *filename)
537 {
538     Xapian::Document doc;
539
540     GMimeStream *stream;
541     GMimeParser *parser;
542     GMimeMessage *message;
543     InternetAddressList *addresses;
544     GPtrArray *parents, *thread_ids;
545
546     FILE *file;
547
548     const char *subject, *refs, *in_reply_to, *from;
549     const char *message_id;
550
551     time_t time;
552     struct tm gm_time_tm;
553     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
554     unsigned int i;
555
556     file = fopen (filename, "r");
557     if (! file) {
558         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
559         exit (1);
560     }
561
562     stream = g_mime_stream_file_new (file);
563
564     parser = g_mime_parser_new_with_stream (stream);
565
566     message = g_mime_parser_construct_message (parser);
567
568     doc = Xapian::Document ();
569
570     doc.set_data (filename);
571
572     term_gen.set_stemmer (Xapian::Stem ("english"));
573
574     term_gen.set_document (doc);
575
576     from = g_mime_message_get_sender (message);
577     addresses = internet_address_list_parse_string (from);
578
579     gen_terms_address_names (term_gen, addresses, "from_name");
580
581     addresses = g_mime_message_get_all_recipients (message);
582     gen_terms_address_names (term_gen, addresses, "to_name");
583
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);
588
589     gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
590
591     parents = g_ptr_array_new ();
592
593     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
594     parse_references (parents, refs);
595
596     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
597                                             "in-reply-to");
598     parse_references (parents, in_reply_to);
599
600     for (i = 0; i < parents->len; i++)
601         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
602
603     message_id = g_mime_message_get_message_id (message);
604
605     thread_ids = find_thread_ids (db, parents, message_id);
606
607     for (i = 0; i < parents->len; i++)
608         g_free (g_ptr_array_index (parents, i));
609     g_ptr_array_free (parents, TRUE);
610
611     from = g_mime_message_get_sender (message);
612     addresses = internet_address_list_parse_string (from);
613
614     add_terms_address_addrs (doc, addresses, "from_email");
615
616     add_terms_address_addrs (doc,
617                              g_mime_message_get_all_recipients (message),
618                              "to_email");
619
620     g_mime_message_get_date (message, &time, NULL);
621
622     gmtime_r (&time, &gm_time_tm);
623
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");
627         exit (1);
628     }
629
630     add_term (doc, "date", date_str);
631
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");
636
637     add_term (doc, "msgid", message_id);
638     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
639
640     if (thread_ids->len) {
641         unsigned int i;
642         GString *thread_id;
643         char *id;
644
645         for (i = 0; i < thread_ids->len; i++) {
646             id = (char *) thread_ids->pdata[i];
647
648             add_term (doc, "thread", id);
649
650             if (i == 0)
651                 thread_id = g_string_new (id);
652             else
653                 g_string_append_printf (thread_id, ",%s", id);
654
655             free (id);
656         }
657         g_ptr_array_free (thread_ids, TRUE);
658
659         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
660
661         g_string_free (thread_id, TRUE);
662     } else {
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);
666     }
667
668     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
669
670     db.add_document (doc);
671
672     g_object_unref (message);
673     g_object_unref (parser);
674     g_object_unref (stream);
675 }
676
677 static void
678 usage (const char *argv0)
679 {
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.");
684 }
685
686 int
687 main (int argc, char **argv)
688 {
689     const char *database_path;
690     char *filename;
691     GIOChannel *channel;
692     GIOStatus gio_status;
693     GError *error = NULL;
694     int count;
695     struct timeval tv_start, tv_now;
696
697     if (argc < 2) {
698         usage (argv[0]);
699         exit (1);
700     }
701
702     database_path = argv[1];
703
704     g_mime_init (0);
705
706     try {
707         Xapian::WritableDatabase db;
708         Xapian::TermGenerator term_gen;
709
710         db = Xapian::WritableDatabase (database_path,
711                                        Xapian::DB_CREATE_OR_OPEN);
712
713         term_gen = Xapian::TermGenerator ();
714
715         channel = g_io_channel_unix_new (fileno (stdin));
716
717         count = 0;
718
719         gettimeofday (&tv_start, NULL);
720
721         while (1) {
722             gio_status = g_io_channel_read_line (channel, &filename,
723                                                  NULL, NULL, &error);
724             if (gio_status == G_IO_STATUS_EOF)
725                 break;
726             if (gio_status != G_IO_STATUS_NORMAL) {
727                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
728                          error->message);
729                 exit (1);
730             }
731
732             g_strchomp (filename);
733             index_file (db, term_gen, filename);
734
735             g_free (filename);
736
737             count++;
738             if (count % 250 == 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));
743             }
744         }
745
746     } catch (const Xapian::Error &error) {
747         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
748         exit (1);
749     }
750
751     return 0;
752 }