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