]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
60370b62b99621f6d8ec1eea491d0b5b96c003ad
[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     while (*s) {
257         while (*s && isspace (*s))
258             s++;
259         if (strncasecmp (s, "re:", 3) == 0)
260             s += 3;
261         else
262             break;
263     }
264
265     return s;
266 }
267
268 static void
269 find_messages_by_term (Xapian::Database db,
270                        const char *prefix_name,
271                        const char *value,
272                        Xapian::PostingIterator *begin,
273                        Xapian::PostingIterator *end)
274 {
275     Xapian::PostingIterator i;
276     char *term;
277
278     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
279
280     *begin = db.postlist_begin (term);
281
282     if (end)
283         *end = db.postlist_end (term);
284
285     free (term);
286 }
287
288 Xapian::Document
289 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
290 {
291     return db.get_document (docid);
292 }
293
294 Xapian::Document
295 find_message_by_message_id (Xapian::Database db, const char *message_id)
296 {
297     Xapian::PostingIterator i, end;
298
299     find_messages_by_term (db, "msgid", message_id, &i, &end);
300
301     if (i != end)
302         return find_message_by_docid (db, *i);
303     else
304         return Xapian::Document ();
305 }
306
307 static void
308 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
309 {
310     string value_string;
311     const char *value, *id, *comma;
312
313     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
314     value = value_string.c_str();
315     if (strlen (value)) {
316         id = value;
317         while (*id) {
318             comma = strchr (id, ',');
319             if (comma == NULL)
320                 comma = id + strlen (id);
321             g_hash_table_insert (thread_ids,
322                                  strndup (id, comma - id), NULL);
323             id = comma;
324             if (*id)
325                 id++;
326         }
327     }
328 }
329
330 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
331  * given message based on looking into the database for any messages
332  * referenced in parents, and also for any messages in the database
333  * referencing message_id.
334  *
335  * Caller should free all strings in the array and the array itself,
336  * (g_ptr_array_free) when done. */
337 static GPtrArray *
338 find_thread_ids (Xapian::Database db,
339                  GPtrArray *parents,
340                  const char *message_id)
341 {
342     Xapian::PostingIterator child, children_end;
343     Xapian::Document doc;
344     GHashTable *thread_ids;
345     GList *keys, *l;
346     unsigned int i;
347     const char *parent_message_id;
348     GPtrArray *result;
349
350     thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
351
352     find_messages_by_term (db, "ref", message_id, &child, &children_end);
353     for ( ; child != children_end; child++) {
354         doc = find_message_by_docid (db, *child);
355         insert_thread_id (thread_ids, doc);
356     }
357
358     for (i = 0; i < parents->len; i++) {
359         parent_message_id = (char *) g_ptr_array_index (parents, i);
360         doc = find_message_by_message_id (db, parent_message_id);
361         insert_thread_id (thread_ids, doc);
362     }
363
364     result = g_ptr_array_new ();
365
366     keys = g_hash_table_get_keys (thread_ids);
367     for (l = keys; l; l = l->next) {
368         char *id = (char *) l->data;
369         g_ptr_array_add (result, id);
370     }
371
372     return result;
373 }
374
375 /* Add a term for each message-id in the References header of the
376  * message. */
377 static void
378 parse_references (GPtrArray *array,
379                   const char *refs_str)
380 {
381     GMimeReferences *refs, *r;
382     const char *message_id;
383
384     if (refs_str == NULL)
385         return;
386
387     refs = g_mime_references_decode (refs_str);
388
389     for (r = refs; r; r = r->next) {
390         message_id = g_mime_references_get_message_id (r);
391         g_ptr_array_add (array, g_strdup (message_id));
392     }
393
394     g_mime_references_free (refs);
395 }
396
397 /* Given a string representing the body of a message, generate terms
398  * for it, (skipping quoted portions and signatures). */
399 static void
400 gen_terms_body_str (Xapian::TermGenerator term_gen,
401                     char *body)
402 {
403     char *line, *line_end, *next_line;
404
405     if (body == NULL)
406         return;
407
408     next_line = body;
409
410     while (1) {
411         line = next_line;
412         if (*line == '\0')
413             break;
414
415         next_line = strchr (line, '\n');
416         if (next_line == NULL) {
417             next_line = line + strlen (line);
418         }
419         line_end = next_line - 1;
420
421         /* Get to the next non-blank line. */
422         while (*next_line == '\n')
423             next_line++;
424
425         /* Skip lines that are quotes. */
426         if (*line == '>')
427             continue;
428
429         /* Also skip lines introducing a quote on the next line. */
430         if (*line_end == ':' && *next_line == '>')
431             continue;
432
433         /* Finally, bail as soon as we see a signature. */
434         /* XXX: Should only do this if "near" the end of the message. */
435         if (strncmp (line, "-- ", 3) == 0 ||
436             strncmp (line, "----------", 10) == 0 ||
437             strncmp (line, "__________", 10) == 0)
438             break;
439
440         *(line_end + 1) = '\0';
441         gen_terms (term_gen, "body", line);
442     }
443 }
444
445
446 /* Callback to generate terms for each mime part of a message. */
447 static void
448 gen_terms_part (Xapian::TermGenerator term_gen,
449                 GMimeObject *part)
450 {
451     GMimeStream *stream;
452     GMimeDataWrapper *wrapper;
453     GByteArray *byte_array;
454     GMimeContentDisposition *disposition;
455     char *body;
456
457     if (GMIME_IS_MULTIPART (part)) {
458         GMimeMultipart *multipart = GMIME_MULTIPART (part);
459         int i;
460
461         for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
462             if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
463                 /* Don't index the signature. */
464                 if (i == 1)
465                     continue;
466                 if (i > 1)
467                     fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
468             }
469             gen_terms_part (term_gen,
470                             g_mime_multipart_get_part (multipart, i));
471         }
472         return;
473     }
474
475     if (! GMIME_IS_PART (part)) {
476         fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
477                  g_type_name (G_OBJECT_TYPE (part)));
478         return;
479     }
480
481     disposition = g_mime_object_get_content_disposition (part);
482     if (disposition &&
483         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
484     {
485         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
486         const char *extension;
487
488         add_term (term_gen.get_document (), "label", "attachment");
489         gen_terms (term_gen, "attachment", filename);
490
491         if (filename) {
492             extension = strchr (filename, '.');
493             if (extension) {
494                 add_term (term_gen.get_document (), "attachment_extension",
495                           extension + 1);
496             }
497         }
498
499         return;
500     }
501
502     byte_array = g_byte_array_new ();
503
504     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
505     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
506     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
507     if (wrapper)
508         g_mime_data_wrapper_write_to_stream (wrapper, stream);
509
510     g_object_unref (stream);
511
512     g_byte_array_append (byte_array, (guint8 *) "\0", 1);
513     body = (char *) g_byte_array_free (byte_array, FALSE);
514
515     gen_terms_body_str (term_gen, body);
516
517     free (body);
518 }
519
520 static void
521 index_file (Xapian::WritableDatabase db,
522             Xapian::TermGenerator term_gen,
523             const char *filename)
524 {
525     Xapian::Document doc;
526
527     GMimeStream *stream;
528     GMimeParser *parser;
529     GMimeMessage *message;
530     InternetAddressList *addresses;
531     GPtrArray *parents, *thread_ids;
532
533     FILE *file;
534
535     const char *subject, *refs, *in_reply_to, *from;
536     const char *message_id;
537
538     time_t time;
539     struct tm gm_time_tm;
540     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
541     unsigned int i;
542
543     file = fopen (filename, "r");
544     if (! file) {
545         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
546         exit (1);
547     }
548
549     stream = g_mime_stream_file_new (file);
550
551     parser = g_mime_parser_new_with_stream (stream);
552
553     message = g_mime_parser_construct_message (parser);
554
555     doc = Xapian::Document ();
556
557     doc.set_data (filename);
558
559     term_gen.set_stemmer (Xapian::Stem ("english"));
560
561     term_gen.set_document (doc);
562
563     from = g_mime_message_get_sender (message);
564     addresses = internet_address_list_parse_string (from);
565
566     gen_terms_address_names (term_gen, addresses, "from_name");
567
568     addresses = g_mime_message_get_all_recipients (message);
569     gen_terms_address_names (term_gen, addresses, "to_name");
570
571     subject = g_mime_message_get_subject (message);
572     subject = skip_re_in_subject (subject);
573     gen_terms (term_gen, "subject", subject);
574     gen_terms (term_gen, "body", subject);
575
576     gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
577
578     parents = g_ptr_array_new ();
579
580     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
581     parse_references (parents, refs);
582
583     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
584                                             "in-reply-to");
585     parse_references (parents, in_reply_to);
586
587     for (i = 0; i < parents->len; i++)
588         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
589
590     message_id = g_mime_message_get_message_id (message);
591
592     thread_ids = find_thread_ids (db, parents, message_id);
593
594     for (i = 0; i < parents->len; i++)
595         g_free (g_ptr_array_index (parents, i));
596     g_ptr_array_free (parents, TRUE);
597
598     from = g_mime_message_get_sender (message);
599     addresses = internet_address_list_parse_string (from);
600
601     add_terms_address_addrs (doc, addresses, "from_email");
602
603     add_terms_address_addrs (doc,
604                              g_mime_message_get_all_recipients (message),
605                              "to_email");
606
607     g_mime_message_get_date (message, &time, NULL);
608
609     gmtime_r (&time, &gm_time_tm);
610
611     if (strftime (date_str, sizeof (date_str),
612                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
613         fprintf (stderr, "Internal error formatting time\n");
614         exit (1);
615     }
616
617     add_term (doc, "date", date_str);
618
619     add_term (doc, "label", "inbox");
620     add_term (doc, "label", "unread");
621     add_term (doc, "type", "mail");
622     add_term (doc, "source_id", "1");
623
624     add_term (doc, "msgid", message_id);
625     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
626
627     if (thread_ids->len) {
628         unsigned int i;
629         GString *thread_id;
630         char *id;
631
632         for (i = 0; i < thread_ids->len; i++) {
633             id = (char *) thread_ids->pdata[i];
634
635             add_term (doc, "thread", id);
636
637             if (i == 0)
638                 thread_id = g_string_new (id);
639             else
640                 g_string_append_printf (thread_id, ",%s", id);
641
642             free (id);
643         }
644         g_ptr_array_free (thread_ids, TRUE);
645
646         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
647
648         g_string_free (thread_id, TRUE);
649     } else {
650         /* If not referenced thread, use the message ID */
651         add_term (doc, "thread", message_id);
652         doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
653     }
654
655     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
656
657     db.add_document (doc);
658
659     g_object_unref (message);
660     g_object_unref (parser);
661     g_object_unref (stream);
662 }
663
664 static void
665 usage (const char *argv0)
666 {
667     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
668     fprintf (stderr, "\n");
669     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
670     fprintf (stderr, "one file per line.");
671 }
672
673 int
674 main (int argc, char **argv)
675 {
676     const char *database_path;
677     char *filename;
678     GIOChannel *channel;
679     GIOStatus gio_status;
680     GError *error = NULL;
681     int count;
682     struct timeval tv_start, tv_now;
683
684     if (argc < 2) {
685         usage (argv[0]);
686         exit (1);
687     }
688
689     database_path = argv[1];
690
691     g_mime_init (0);
692
693     try {
694         Xapian::WritableDatabase db;
695         Xapian::TermGenerator term_gen;
696
697         db = Xapian::WritableDatabase (database_path,
698                                        Xapian::DB_CREATE_OR_OPEN);
699
700         term_gen = Xapian::TermGenerator ();
701
702         channel = g_io_channel_unix_new (fileno (stdin));
703
704         count = 0;
705
706         gettimeofday (&tv_start, NULL);
707
708         while (1) {
709             gio_status = g_io_channel_read_line (channel, &filename,
710                                                  NULL, NULL, &error);
711             if (gio_status == G_IO_STATUS_EOF)
712                 break;
713             if (gio_status != G_IO_STATUS_NORMAL) {
714                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
715                          error->message);
716                 exit (1);
717             }
718
719             g_strchomp (filename);
720             index_file (db, term_gen, filename);
721
722             g_free (filename);
723
724             count++;
725             if (count % 250 == 0) {
726                 gettimeofday (&tv_now, NULL);
727                 printf ("Indexed %d messages (%g messages/second)\n",
728                         count, count / ((tv_now.tv_sec - tv_start.tv_sec) +
729                                         (tv_now.tv_usec - tv_start.tv_usec) / 1e6));
730             }
731         }
732
733     } catch (const Xapian::Error &error) {
734         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
735         exit (1);
736     }
737
738     return 0;
739 }