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