]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
Avoid segfault on message with no subject.
[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_PART (part)) {
479         fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
480                  g_type_name (G_OBJECT_TYPE (part)));
481         return;
482     }
483
484     disposition = g_mime_object_get_content_disposition (part);
485     if (disposition &&
486         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
487     {
488         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
489         const char *extension;
490
491         add_term (term_gen.get_document (), "label", "attachment");
492         gen_terms (term_gen, "attachment", filename);
493
494         if (filename) {
495             extension = strchr (filename, '.');
496             if (extension) {
497                 add_term (term_gen.get_document (), "attachment_extension",
498                           extension + 1);
499             }
500         }
501
502         return;
503     }
504
505     byte_array = g_byte_array_new ();
506
507     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
508     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
509     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
510     if (wrapper)
511         g_mime_data_wrapper_write_to_stream (wrapper, stream);
512
513     g_object_unref (stream);
514
515     g_byte_array_append (byte_array, (guint8 *) "\0", 1);
516     body = (char *) g_byte_array_free (byte_array, FALSE);
517
518     gen_terms_body_str (term_gen, body);
519
520     free (body);
521 }
522
523 static void
524 index_file (Xapian::WritableDatabase db,
525             Xapian::TermGenerator term_gen,
526             const char *filename)
527 {
528     Xapian::Document doc;
529
530     GMimeStream *stream;
531     GMimeParser *parser;
532     GMimeMessage *message;
533     InternetAddressList *addresses;
534     GPtrArray *parents, *thread_ids;
535
536     FILE *file;
537
538     const char *subject, *refs, *in_reply_to, *from;
539     const char *message_id;
540
541     time_t time;
542     struct tm gm_time_tm;
543     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
544     unsigned int i;
545
546     file = fopen (filename, "r");
547     if (! file) {
548         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
549         exit (1);
550     }
551
552     stream = g_mime_stream_file_new (file);
553
554     parser = g_mime_parser_new_with_stream (stream);
555
556     message = g_mime_parser_construct_message (parser);
557
558     doc = Xapian::Document ();
559
560     doc.set_data (filename);
561
562     term_gen.set_stemmer (Xapian::Stem ("english"));
563
564     term_gen.set_document (doc);
565
566     from = g_mime_message_get_sender (message);
567     addresses = internet_address_list_parse_string (from);
568
569     gen_terms_address_names (term_gen, addresses, "from_name");
570
571     addresses = g_mime_message_get_all_recipients (message);
572     gen_terms_address_names (term_gen, addresses, "to_name");
573
574     subject = g_mime_message_get_subject (message);
575     subject = skip_re_in_subject (subject);
576     gen_terms (term_gen, "subject", subject);
577     gen_terms (term_gen, "body", subject);
578
579     gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
580
581     parents = g_ptr_array_new ();
582
583     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
584     parse_references (parents, refs);
585
586     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
587                                             "in-reply-to");
588     parse_references (parents, in_reply_to);
589
590     for (i = 0; i < parents->len; i++)
591         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
592
593     message_id = g_mime_message_get_message_id (message);
594
595     thread_ids = find_thread_ids (db, parents, message_id);
596
597     for (i = 0; i < parents->len; i++)
598         g_free (g_ptr_array_index (parents, i));
599     g_ptr_array_free (parents, TRUE);
600
601     from = g_mime_message_get_sender (message);
602     addresses = internet_address_list_parse_string (from);
603
604     add_terms_address_addrs (doc, addresses, "from_email");
605
606     add_terms_address_addrs (doc,
607                              g_mime_message_get_all_recipients (message),
608                              "to_email");
609
610     g_mime_message_get_date (message, &time, NULL);
611
612     gmtime_r (&time, &gm_time_tm);
613
614     if (strftime (date_str, sizeof (date_str),
615                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
616         fprintf (stderr, "Internal error formatting time\n");
617         exit (1);
618     }
619
620     add_term (doc, "date", date_str);
621
622     add_term (doc, "label", "inbox");
623     add_term (doc, "label", "unread");
624     add_term (doc, "type", "mail");
625     add_term (doc, "source_id", "1");
626
627     add_term (doc, "msgid", message_id);
628     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
629
630     if (thread_ids->len) {
631         unsigned int i;
632         GString *thread_id;
633         char *id;
634
635         for (i = 0; i < thread_ids->len; i++) {
636             id = (char *) thread_ids->pdata[i];
637
638             add_term (doc, "thread", id);
639
640             if (i == 0)
641                 thread_id = g_string_new (id);
642             else
643                 g_string_append_printf (thread_id, ",%s", id);
644
645             free (id);
646         }
647         g_ptr_array_free (thread_ids, TRUE);
648
649         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
650
651         g_string_free (thread_id, TRUE);
652     } else {
653         /* If not referenced thread, use the message ID */
654         add_term (doc, "thread", message_id);
655         doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
656     }
657
658     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
659
660     db.add_document (doc);
661
662     g_object_unref (message);
663     g_object_unref (parser);
664     g_object_unref (stream);
665 }
666
667 static void
668 usage (const char *argv0)
669 {
670     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
671     fprintf (stderr, "\n");
672     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
673     fprintf (stderr, "one file per line.");
674 }
675
676 int
677 main (int argc, char **argv)
678 {
679     const char *database_path;
680     char *filename;
681     GIOChannel *channel;
682     GIOStatus gio_status;
683     GError *error = NULL;
684     int count;
685     struct timeval tv_start, tv_now;
686
687     if (argc < 2) {
688         usage (argv[0]);
689         exit (1);
690     }
691
692     database_path = argv[1];
693
694     g_mime_init (0);
695
696     try {
697         Xapian::WritableDatabase db;
698         Xapian::TermGenerator term_gen;
699
700         db = Xapian::WritableDatabase (database_path,
701                                        Xapian::DB_CREATE_OR_OPEN);
702
703         term_gen = Xapian::TermGenerator ();
704
705         channel = g_io_channel_unix_new (fileno (stdin));
706
707         count = 0;
708
709         gettimeofday (&tv_start, NULL);
710
711         while (1) {
712             gio_status = g_io_channel_read_line (channel, &filename,
713                                                  NULL, NULL, &error);
714             if (gio_status == G_IO_STATUS_EOF)
715                 break;
716             if (gio_status != G_IO_STATUS_NORMAL) {
717                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
718                          error->message);
719                 exit (1);
720             }
721
722             g_strchomp (filename);
723             index_file (db, term_gen, filename);
724
725             g_free (filename);
726
727             count++;
728             if (count % 250 == 0) {
729                 gettimeofday (&tv_now, NULL);
730                 printf ("Indexed %d messages (%g messages/second)\n",
731                         count, count / ((tv_now.tv_sec - tv_start.tv_sec) +
732                                         (tv_now.tv_usec - tv_start.tv_usec) / 1e6));
733             }
734         }
735
736     } catch (const Xapian::Error &error) {
737         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
738         exit (1);
739     }
740
741     return 0;
742 }