]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
bf56f5206d0f950290ec31637e6fc68516acfe25
[notmuch] / lib / database.cc
1 /* database.cc - The database interfaces of the notmuch mail library
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "database-private.h"
22
23 #include <iostream>
24
25 #include <xapian.h>
26
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
28
29 using namespace std;
30
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
32
33 typedef struct {
34     const char *name;
35     const char *prefix;
36 } prefix_t;
37
38 /* Here's the current schema for our database:
39  *
40  * We currently have two different types of documents: mail and directory.
41  *
42  * Mail document
43  * -------------
44  * A mail document is associated with a particular email message file
45  * on disk. It is indexed with the following prefixed terms which the
46  * database uses to construct threads, etc.:
47  *
48  *    Single terms of given prefix:
49  *
50  *      type:   mail
51  *
52  *      id:     Unique ID of mail, (from Message-ID header or generated
53  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
54  *
55  *      thread: The ID of the thread to which the mail belongs
56  *
57  *      replyto: The ID from the In-Reply-To header of the mail (if any).
58  *
59  *    Multiple terms of given prefix:
60  *
61  *      reference: All message IDs from In-Reply-To and Re ferences
62  *                 headers in the message.
63  *
64  *      tag:       Any tags associated with this message by the user.
65  *
66  *    A mail document also has two values:
67  *
68  *      TIMESTAMP:      The time_t value corresponding to the message's
69  *                      Date header.
70  *
71  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
72  *
73  * In addition, terms from the content of the message are added with
74  * "from", "to", "attachment", and "subject" prefixes for use by the
75  * user in searching. But the database doesn't really care itself
76  * about any of these.
77  *
78  * Finally, the data portion of a mail document contains the path name
79  * of the mail message (relative to the database path).
80  *
81  * Directory document
82  * ------------------
83  * A directory document is used by a client of the notmuch library to
84  * maintain data necessary to allow for efficient polling of mail
85  * directories.
86  *
87  * The directory document contains the following terms:
88  *
89  *      directory:      The directory path (relative to the database path)
90  *      parent:         The document ID of the parent directory document.
91  *                      Top-level directories will have a parent value of 0.
92  *
93  * and has a single value:
94  *
95  *      TIMESTAMP:      The mtime of the directory (at last scan)
96  */
97
98 /* With these prefix values we follow the conventions published here:
99  *
100  * http://xapian.org/docs/omega/termprefixes.html
101  *
102  * as much as makes sense. Note that I took some liberty in matching
103  * the reserved prefix values to notmuch concepts, (for example, 'G'
104  * is documented as "newsGroup (or similar entity - e.g. a web forum
105  * name)", for which I think the thread is the closest analogue in
106  * notmuch. This in spite of the fact that we will eventually be
107  * storing mailing-list messages where 'G' for "mailing list name"
108  * might be even a closer analogue. I'm treating the single-character
109  * prefixes preferentially for core notmuch concepts (which will be
110  * nearly universal to all mail messages).
111  */
112
113 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
114     { "type", "T" },
115     { "reference", "XREFERENCE" },
116     { "replyto", "XREPLYTO" },
117     { "directory", "XDIRECTORY" },
118     { "parent", "XPARENT" },
119 };
120
121 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
122     { "thread", "G" },
123     { "tag", "K" },
124     { "id", "Q" }
125 };
126
127 prefix_t PROBABILISTIC_PREFIX[]= {
128     { "from", "XFROM" },
129     { "to", "XTO" },
130     { "attachment", "XATTACHMENT" },
131     { "subject", "XSUBJECT"}
132 };
133
134 int
135 _internal_error (const char *format, ...)
136 {
137     va_list va_args;
138
139     va_start (va_args, format);
140
141     fprintf (stderr, "Internal error: ");
142     vfprintf (stderr, format, va_args);
143
144     exit (1);
145
146     return 1;
147 }
148
149 const char *
150 _find_prefix (const char *name)
151 {
152     unsigned int i;
153
154     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
155         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
156             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
157     }
158
159     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
160         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
161             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
162     }
163
164     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
165         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
166             return PROBABILISTIC_PREFIX[i].prefix;
167     }
168
169     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
170
171     return "";
172 }
173
174 const char *
175 notmuch_status_to_string (notmuch_status_t status)
176 {
177     switch (status) {
178     case NOTMUCH_STATUS_SUCCESS:
179         return "No error occurred";
180     case NOTMUCH_STATUS_OUT_OF_MEMORY:
181         return "Out of memory";
182     case NOTMUCH_STATUS_READONLY_DATABASE:
183         return "The database is read-only";
184     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
185         return "A Xapian exception occurred";
186     case NOTMUCH_STATUS_FILE_ERROR:
187         return "Something went wrong trying to read or write a file";
188     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
189         return "File is not an email";
190     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
191         return "Message ID is identical to a message in database";
192     case NOTMUCH_STATUS_NULL_POINTER:
193         return "Erroneous NULL pointer";
194     case NOTMUCH_STATUS_TAG_TOO_LONG:
195         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
196     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
197         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
198     default:
199     case NOTMUCH_STATUS_LAST_STATUS:
200         return "Unknown error status value";
201     }
202 }
203
204 static void
205 find_doc_ids (notmuch_database_t *notmuch,
206               const char *prefix_name,
207               const char *value,
208               Xapian::PostingIterator *begin,
209               Xapian::PostingIterator *end)
210 {
211     Xapian::PostingIterator i;
212     char *term;
213
214     term = talloc_asprintf (notmuch, "%s%s",
215                             _find_prefix (prefix_name), value);
216
217     *begin = notmuch->xapian_db->postlist_begin (term);
218
219     *end = notmuch->xapian_db->postlist_end (term);
220
221     talloc_free (term);
222 }
223
224 static notmuch_private_status_t
225 find_unique_doc_id (notmuch_database_t *notmuch,
226                     const char *prefix_name,
227                     const char *value,
228                     unsigned int *doc_id)
229 {
230     Xapian::PostingIterator i, end;
231
232     find_doc_ids (notmuch, prefix_name, value, &i, &end);
233
234     if (i == end) {
235         *doc_id = 0;
236         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
237     } else {
238         *doc_id = *i;
239         return NOTMUCH_PRIVATE_STATUS_SUCCESS;
240     }
241 }
242
243 static Xapian::Document
244 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
245 {
246     return notmuch->xapian_db->get_document (doc_id);
247 }
248
249 static notmuch_private_status_t
250 find_unique_document (notmuch_database_t *notmuch,
251                       const char *prefix_name,
252                       const char *value,
253                       Xapian::Document *document,
254                       unsigned int *doc_id)
255 {
256     notmuch_private_status_t status;
257
258     status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
259
260     if (status) {
261         *document = Xapian::Document ();
262         return status;
263     }
264
265     *document = find_document_for_doc_id (notmuch, *doc_id);
266     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
267 }
268
269 notmuch_message_t *
270 notmuch_database_find_message (notmuch_database_t *notmuch,
271                                const char *message_id)
272 {
273     notmuch_private_status_t status;
274     unsigned int doc_id;
275
276     status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
277
278     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
279         return NULL;
280
281     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
282 }
283
284 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
285  * a (potentially nested) parenthesized sequence with '\' used to
286  * escape any character (including parentheses).
287  *
288  * If the sequence to be skipped continues to the end of the string,
289  * then 'str' will be left pointing at the final terminating '\0'
290  * character.
291  */
292 static void
293 skip_space_and_comments (const char **str)
294 {
295     const char *s;
296
297     s = *str;
298     while (*s && (isspace (*s) || *s == '(')) {
299         while (*s && isspace (*s))
300             s++;
301         if (*s == '(') {
302             int nesting = 1;
303             s++;
304             while (*s && nesting) {
305                 if (*s == '(') {
306                     nesting++;
307                 } else if (*s == ')') {
308                     nesting--;
309                 } else if (*s == '\\') {
310                     if (*(s+1))
311                         s++;
312                 }
313                 s++;
314             }
315         }
316     }
317
318     *str = s;
319 }
320
321 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
322  * comments, and the '<' and '>' delimeters.
323  *
324  * If not NULL, then *next will be made to point to the first character
325  * not parsed, (possibly pointing to the final '\0' terminator.
326  *
327  * Returns a newly talloc'ed string belonging to 'ctx'.
328  *
329  * Returns NULL if there is any error parsing the message-id. */
330 static char *
331 _parse_message_id (void *ctx, const char *message_id, const char **next)
332 {
333     const char *s, *end;
334     char *result;
335
336     if (message_id == NULL || *message_id == '\0')
337         return NULL;
338
339     s = message_id;
340
341     skip_space_and_comments (&s);
342
343     /* Skip any unstructured text as well. */
344     while (*s && *s != '<')
345         s++;
346
347     if (*s == '<') {
348         s++;
349     } else {
350         if (next)
351             *next = s;
352         return NULL;
353     }
354
355     skip_space_and_comments (&s);
356
357     end = s;
358     while (*end && *end != '>')
359         end++;
360     if (next) {
361         if (*end)
362             *next = end + 1;
363         else
364             *next = end;
365     }
366
367     if (end > s && *end == '>')
368         end--;
369     if (end <= s)
370         return NULL;
371
372     result = talloc_strndup (ctx, s, end - s + 1);
373
374     /* Finally, collapse any whitespace that is within the message-id
375      * itself. */
376     {
377         char *r;
378         int len;
379
380         for (r = result, len = strlen (r); *r; r++, len--)
381             if (*r == ' ' || *r == '\t')
382                 memmove (r, r+1, len);
383     }
384
385     return result;
386 }
387
388 /* Parse a References header value, putting a (talloc'ed under 'ctx')
389  * copy of each referenced message-id into 'hash'.
390  *
391  * We explicitly avoid including any reference identical to
392  * 'message_id' in the result (to avoid mass confusion when a single
393  * message references itself cyclically---and yes, mail messages are
394  * not infrequent in the wild that do this---don't ask me why).
395 */
396 static void
397 parse_references (void *ctx,
398                   const char *message_id,
399                   GHashTable *hash,
400                   const char *refs)
401 {
402     char *ref;
403
404     if (refs == NULL || *refs == '\0')
405         return;
406
407     while (*refs) {
408         ref = _parse_message_id (ctx, refs, &refs);
409
410         if (ref && strcmp (ref, message_id))
411             g_hash_table_insert (hash, ref, NULL);
412     }
413 }
414
415 notmuch_database_t *
416 notmuch_database_create (const char *path)
417 {
418     notmuch_database_t *notmuch = NULL;
419     char *notmuch_path = NULL;
420     struct stat st;
421     int err;
422
423     if (path == NULL) {
424         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
425         goto DONE;
426     }
427
428     err = stat (path, &st);
429     if (err) {
430         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
431                  path, strerror (errno));
432         goto DONE;
433     }
434
435     if (! S_ISDIR (st.st_mode)) {
436         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
437                  path);
438         goto DONE;
439     }
440
441     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
442
443     err = mkdir (notmuch_path, 0755);
444
445     if (err) {
446         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
447                  notmuch_path, strerror (errno));
448         goto DONE;
449     }
450
451     notmuch = notmuch_database_open (path,
452                                      NOTMUCH_DATABASE_MODE_READ_WRITE);
453
454   DONE:
455     if (notmuch_path)
456         talloc_free (notmuch_path);
457
458     return notmuch;
459 }
460
461 notmuch_database_t *
462 notmuch_database_open (const char *path,
463                        notmuch_database_mode_t mode)
464 {
465     notmuch_database_t *notmuch = NULL;
466     char *notmuch_path = NULL, *xapian_path = NULL;
467     struct stat st;
468     int err;
469     unsigned int i;
470
471     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
472         notmuch_path = NULL;
473         fprintf (stderr, "Out of memory\n");
474         goto DONE;
475     }
476
477     err = stat (notmuch_path, &st);
478     if (err) {
479         fprintf (stderr, "Error opening database at %s: %s\n",
480                  notmuch_path, strerror (errno));
481         goto DONE;
482     }
483
484     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
485         xapian_path = NULL;
486         fprintf (stderr, "Out of memory\n");
487         goto DONE;
488     }
489
490     notmuch = talloc (NULL, notmuch_database_t);
491     notmuch->exception_reported = FALSE;
492     notmuch->path = talloc_strdup (notmuch, path);
493
494     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
495         notmuch->path[strlen (notmuch->path) - 1] = '\0';
496
497     notmuch->mode = mode;
498     try {
499         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
500             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
501                                                                Xapian::DB_CREATE_OR_OPEN);
502         } else {
503             notmuch->xapian_db = new Xapian::Database (xapian_path);
504         }
505         notmuch->query_parser = new Xapian::QueryParser;
506         notmuch->term_gen = new Xapian::TermGenerator;
507         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
508         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
509
510         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
511         notmuch->query_parser->set_database (*notmuch->xapian_db);
512         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
513         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
514         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
515
516         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
517             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
518             notmuch->query_parser->add_boolean_prefix (prefix->name,
519                                                        prefix->prefix);
520         }
521
522         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
523             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
524             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
525         }
526     } catch (const Xapian::Error &error) {
527         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
528                  error.get_msg().c_str());
529         notmuch = NULL;
530     }
531
532   DONE:
533     if (notmuch_path)
534         free (notmuch_path);
535     if (xapian_path)
536         free (xapian_path);
537
538     return notmuch;
539 }
540
541 void
542 notmuch_database_close (notmuch_database_t *notmuch)
543 {
544     try {
545         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
546             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
547     } catch (const Xapian::Error &error) {
548         if (! notmuch->exception_reported) {
549             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
550                      error.get_msg().c_str());
551         }
552     }
553
554     delete notmuch->term_gen;
555     delete notmuch->query_parser;
556     delete notmuch->xapian_db;
557     delete notmuch->value_range_processor;
558     talloc_free (notmuch);
559 }
560
561 const char *
562 notmuch_database_get_path (notmuch_database_t *notmuch)
563 {
564     return notmuch->path;
565 }
566
567 static notmuch_private_status_t
568 find_directory_document (notmuch_database_t *notmuch, const char *db_path,
569                          Xapian::Document *doc, unsigned int *doc_id)
570 {
571     return find_unique_document (notmuch, "directory", db_path, doc, doc_id);
572 }
573
574 /* We allow the user to use arbitrarily long paths for directories. But
575  * we have a term-length limit. So if we exceed that, we'll use the
576  * SHA-1 of the path for the database term.
577  *
578  * Note: This function may return the original value of 'path'. If it
579  * does not, then the caller is responsible to free() the returned
580  * value.
581  */
582 static const char *
583 directory_db_path (const char *path)
584 {
585     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
586
587     if (term_len > NOTMUCH_TERM_MAX)
588         return notmuch_sha1_of_string (path);
589     else
590         return path;
591 }
592
593 /* Given a 'path' (relative to the database path) return the document
594  * ID of the directory document corresponding to the parent directory
595  * of 'path' in 'parent_id'.
596  *
597  * The original 'path' can represent either a regular file or a
598  * directory, (in either case, the document ID of the parent will be
599  * returned). Trailing slashes on 'path' will be ignored, and any
600  * cases of multiple '/' characters appearing in series will be
601  * treated as a single '/'.
602  *
603  * If no directory document exists in the database for the parent, (or
604  * for any of its parents up to the top-level database path), then
605  * directory documents will be created for these (each with an mtime
606  * of 0).
607  *
608  * Return value:
609  *
610  * NOTMUCH_STATUS_SUCCESS: Valid value available in parent_id.
611  *
612  * NOTMUCH_STATUS_XAPIAN_EXCEPTION: A Xapian exception
613  *      occurred and parent_id will be set to (unsigned) -1.
614  */
615 notmuch_status_t
616 _notmuch_database_find_parent_id (notmuch_database_t *notmuch,
617                                   const char *path,
618                                   unsigned int *parent_id)
619 {
620     const char *slash, *parent_db_path;
621     char *parent_path;
622     notmuch_private_status_t private_status;
623     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
624
625     if (path == NULL || *path == '\0') {
626         *parent_id = 0;
627         return NOTMUCH_STATUS_SUCCESS;
628     }
629
630     /* Find the last slash (not counting a trailing slash), if any. */
631
632     slash = path + strlen (path) - 1;
633
634     /* First, skip trailing slashes. */
635     while (slash != path) {
636         if (*slash != '/')
637             break;
638
639         --slash;
640     }
641
642     /* Then, find a slash. */
643     while (slash != path) {
644         if (*slash == '/')
645             break;
646
647         --slash;
648     }
649
650     /* Finally, skip multiple slashes. */
651     while (slash != path) {
652         if (*slash != '/')
653             break;
654
655         --slash;
656     }
657
658     if (slash == path)
659         parent_path = talloc_strdup (notmuch, "");
660     else
661         parent_path = talloc_strndup (notmuch, path, slash - path + 1);
662
663     parent_db_path = directory_db_path (parent_path);
664
665     private_status = find_unique_doc_id (notmuch, "directory",
666                                          parent_db_path, parent_id);
667     if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
668         status = notmuch_database_set_directory_mtime (notmuch,
669                                                        parent_path, 0);
670         if (status)
671             return status;
672         private_status = find_unique_doc_id (notmuch, "directory",
673                                              parent_db_path, parent_id);
674         status = COERCE_STATUS (private_status, "_find_parent_id");
675     }
676
677     if (parent_db_path != parent_path)
678         free ((char *) parent_db_path);
679
680     talloc_free (parent_path);
681
682     if (status)
683         *parent_id = -1;
684
685     return status;
686 }
687
688 /* Given a legal 'path' for the database, return the relative path.
689  *
690  * The return value will be a pointer to the originl path contents,
691  * and will be either the original string (if 'path' was relative) or
692  * a portion of the string (if path was absolute and begins with the
693  * database path).
694  */
695 const char *
696 _notmuch_database_relative_path (notmuch_database_t *notmuch,
697                                  const char *path)
698 {
699     const char *db_path, *relative;
700     unsigned int db_path_len;
701
702     db_path = notmuch_database_get_path (notmuch);
703     db_path_len = strlen (db_path);
704
705     relative = path;
706
707     if (*relative == '/') {
708         while (*relative == '/' && *(relative+1) == '/')
709             relative++;
710
711         if (strncmp (relative, db_path, db_path_len) == 0)
712         {
713             relative += db_path_len;
714             while (*relative == '/')
715                 relative++;
716         }
717     }
718
719     return relative;
720 }
721
722 notmuch_status_t
723 notmuch_database_set_directory_mtime (notmuch_database_t *notmuch,
724                                       const char *path,
725                                       time_t mtime)
726 {
727     Xapian::Document doc;
728     Xapian::WritableDatabase *db;
729     unsigned int doc_id;
730     notmuch_private_status_t status;
731     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
732     const char *db_path = NULL;
733     unsigned int parent_id;
734
735     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
736         fprintf (stderr, "Attempted to update a read-only database.\n");
737         return NOTMUCH_STATUS_READONLY_DATABASE;
738     }
739
740     path = _notmuch_database_relative_path (notmuch, path);
741
742     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
743     db_path = directory_db_path (path);
744
745     try {
746         status = find_directory_document (notmuch, db_path, &doc, &doc_id);
747
748         doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
749                        Xapian::sortable_serialise (mtime));
750
751         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
752             char *term = talloc_asprintf (NULL, "%s%s",
753                                           _find_prefix ("directory"), db_path);
754             doc.add_term (term);
755             talloc_free (term);
756
757             ret = _notmuch_database_find_parent_id (notmuch, path,
758                                                     &parent_id);
759             if (ret)
760                 return ret;
761
762             term = talloc_asprintf (NULL, "%s%u",
763                                     _find_prefix ("parent"),
764                                     parent_id);
765             doc.add_term (term);
766             talloc_free (term);
767
768             db->add_document (doc);
769         } else {
770             db->replace_document (doc_id, doc);
771         }
772
773     } catch (const Xapian::Error &error) {
774         fprintf (stderr, "A Xapian exception occurred setting directory mtime: %s.\n",
775                  error.get_msg().c_str());
776         notmuch->exception_reported = TRUE;
777         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
778     }
779
780     if (db_path != path)
781         free ((char *) db_path);
782
783     return ret;
784 }
785
786 time_t
787 notmuch_database_get_directory_mtime (notmuch_database_t *notmuch,
788                                       const char *path)
789 {
790     Xapian::Document doc;
791     unsigned int doc_id;
792     notmuch_private_status_t status;
793     const char *db_path = NULL;
794     time_t ret = 0;
795
796     db_path = directory_db_path (path);
797
798     try {
799         status = find_directory_document (notmuch, db_path, &doc, &doc_id);
800
801         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
802             goto DONE;
803
804         ret =  Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
805     } catch (Xapian::Error &error) {
806         ret = 0;
807         goto DONE;
808     }
809
810   DONE:
811     if (db_path != path)
812         free ((char *) db_path);
813
814     return ret;
815 }
816
817 /* Find the thread ID to which the message with 'message_id' belongs.
818  *
819  * Returns NULL if no message with message ID 'message_id' is in the
820  * database.
821  *
822  * Otherwise, returns a newly talloced string belonging to 'ctx'.
823  */
824 static const char *
825 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
826                                   void *ctx,
827                                   const char *message_id)
828 {
829     notmuch_message_t *message;
830     const char *ret = NULL;
831
832     message = notmuch_database_find_message (notmuch, message_id);
833     if (message == NULL)
834         goto DONE;
835
836     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
837
838   DONE:
839     if (message)
840         notmuch_message_destroy (message);
841
842     return ret;
843 }
844
845 static notmuch_status_t
846 _merge_threads (notmuch_database_t *notmuch,
847                 const char *winner_thread_id,
848                 const char *loser_thread_id)
849 {
850     Xapian::PostingIterator loser, loser_end;
851     notmuch_message_t *message = NULL;
852     notmuch_private_status_t private_status;
853     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
854
855     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
856
857     for ( ; loser != loser_end; loser++) {
858         message = _notmuch_message_create (notmuch, notmuch,
859                                            *loser, &private_status);
860         if (message == NULL) {
861             ret = COERCE_STATUS (private_status,
862                                  "Cannot find document for doc_id from query");
863             goto DONE;
864         }
865
866         _notmuch_message_remove_term (message, "thread", loser_thread_id);
867         _notmuch_message_add_term (message, "thread", winner_thread_id);
868         _notmuch_message_sync (message);
869
870         notmuch_message_destroy (message);
871         message = NULL;
872     }
873
874   DONE:
875     if (message)
876         notmuch_message_destroy (message);
877
878     return ret;
879 }
880
881 static void
882 _my_talloc_free_for_g_hash (void *ptr)
883 {
884     talloc_free (ptr);
885 }
886
887 static notmuch_status_t
888 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
889                                            notmuch_message_t *message,
890                                            notmuch_message_file_t *message_file,
891                                            const char **thread_id)
892 {
893     GHashTable *parents = NULL;
894     const char *refs, *in_reply_to, *in_reply_to_message_id;
895     GList *l, *keys = NULL;
896     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
897
898     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
899                                      _my_talloc_free_for_g_hash, NULL);
900
901     refs = notmuch_message_file_get_header (message_file, "references");
902     parse_references (message, notmuch_message_get_message_id (message),
903                       parents, refs);
904
905     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
906     parse_references (message, notmuch_message_get_message_id (message),
907                       parents, in_reply_to);
908
909     /* Carefully avoid adding any self-referential in-reply-to term. */
910     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
911     if (in_reply_to_message_id &&
912         strcmp (in_reply_to_message_id,
913                 notmuch_message_get_message_id (message)))
914     {
915         _notmuch_message_add_term (message, "replyto",
916                              _parse_message_id (message, in_reply_to, NULL));
917     }
918
919     keys = g_hash_table_get_keys (parents);
920     for (l = keys; l; l = l->next) {
921         char *parent_message_id;
922         const char *parent_thread_id;
923
924         parent_message_id = (char *) l->data;
925         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
926                                                              message,
927                                                              parent_message_id);
928
929         if (parent_thread_id == NULL) {
930             _notmuch_message_add_term (message, "reference",
931                                        parent_message_id);
932         } else {
933             if (*thread_id == NULL) {
934                 *thread_id = talloc_strdup (message, parent_thread_id);
935                 _notmuch_message_add_term (message, "thread", *thread_id);
936             } else if (strcmp (*thread_id, parent_thread_id)) {
937                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
938                 if (ret)
939                     goto DONE;
940             }
941         }
942     }
943
944   DONE:
945     if (keys)
946         g_list_free (keys);
947     if (parents)
948         g_hash_table_unref (parents);
949
950     return ret;
951 }
952
953 static notmuch_status_t
954 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
955                                             notmuch_message_t *message,
956                                             const char **thread_id)
957 {
958     const char *message_id = notmuch_message_get_message_id (message);
959     Xapian::PostingIterator child, children_end;
960     notmuch_message_t *child_message = NULL;
961     const char *child_thread_id;
962     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
963     notmuch_private_status_t private_status;
964
965     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
966
967     for ( ; child != children_end; child++) {
968
969         child_message = _notmuch_message_create (message, notmuch,
970                                                  *child, &private_status);
971         if (child_message == NULL) {
972             ret = COERCE_STATUS (private_status,
973                                  "Cannot find document for doc_id from query");
974             goto DONE;
975         }
976
977         child_thread_id = notmuch_message_get_thread_id (child_message);
978         if (*thread_id == NULL) {
979             *thread_id = talloc_strdup (message, child_thread_id);
980             _notmuch_message_add_term (message, "thread", *thread_id);
981         } else if (strcmp (*thread_id, child_thread_id)) {
982             _notmuch_message_remove_term (child_message, "reference",
983                                           message_id);
984             _notmuch_message_sync (child_message);
985             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
986             if (ret)
987                 goto DONE;
988         }
989
990         notmuch_message_destroy (child_message);
991         child_message = NULL;
992     }
993
994   DONE:
995     if (child_message)
996         notmuch_message_destroy (child_message);
997
998     return ret;
999 }
1000
1001 /* Given a (mostly empty) 'message' and its corresponding
1002  * 'message_file' link it to existing threads in the database.
1003  *
1004  * We first look at 'message_file' and its link-relevant headers
1005  * (References and In-Reply-To) for message IDs. We also look in the
1006  * database for existing message that reference 'message'.
1007  *
1008  * The end result is to call _notmuch_message_ensure_thread_id which
1009  * generates a new thread ID if the message doesn't connect to any
1010  * existing threads.
1011  */
1012 static notmuch_status_t
1013 _notmuch_database_link_message (notmuch_database_t *notmuch,
1014                                 notmuch_message_t *message,
1015                                 notmuch_message_file_t *message_file)
1016 {
1017     notmuch_status_t status;
1018     const char *thread_id = NULL;
1019
1020     status = _notmuch_database_link_message_to_parents (notmuch, message,
1021                                                         message_file,
1022                                                         &thread_id);
1023     if (status)
1024         return status;
1025
1026     status = _notmuch_database_link_message_to_children (notmuch, message,
1027                                                          &thread_id);
1028     if (status)
1029         return status;
1030
1031     if (thread_id == NULL)
1032         _notmuch_message_ensure_thread_id (message);
1033
1034     return NOTMUCH_STATUS_SUCCESS;
1035 }
1036
1037 notmuch_status_t
1038 notmuch_database_add_message (notmuch_database_t *notmuch,
1039                               const char *filename,
1040                               notmuch_message_t **message_ret)
1041 {
1042     notmuch_message_file_t *message_file;
1043     notmuch_message_t *message = NULL;
1044     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1045     notmuch_private_status_t private_status;
1046
1047     const char *date, *header;
1048     const char *from, *to, *subject;
1049     char *message_id = NULL;
1050
1051     if (message_ret)
1052         *message_ret = NULL;
1053
1054     message_file = notmuch_message_file_open (filename);
1055     if (message_file == NULL) {
1056         ret = NOTMUCH_STATUS_FILE_ERROR;
1057         goto DONE;
1058     }
1059
1060     notmuch_message_file_restrict_headers (message_file,
1061                                            "date",
1062                                            "from",
1063                                            "in-reply-to",
1064                                            "message-id",
1065                                            "references",
1066                                            "subject",
1067                                            "to",
1068                                            (char *) NULL);
1069
1070     try {
1071         /* Before we do any real work, (especially before doing a
1072          * potential SHA-1 computation on the entire file's contents),
1073          * let's make sure that what we're looking at looks like an
1074          * actual email message.
1075          */
1076         from = notmuch_message_file_get_header (message_file, "from");
1077         subject = notmuch_message_file_get_header (message_file, "subject");
1078         to = notmuch_message_file_get_header (message_file, "to");
1079
1080         if ((from == NULL || *from == '\0') &&
1081             (subject == NULL || *subject == '\0') &&
1082             (to == NULL || *to == '\0'))
1083         {
1084             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1085             goto DONE;
1086         }
1087
1088         /* Now that we're sure it's mail, the first order of business
1089          * is to find a message ID (or else create one ourselves). */
1090
1091         header = notmuch_message_file_get_header (message_file, "message-id");
1092         if (header && *header != '\0') {
1093             message_id = _parse_message_id (message_file, header, NULL);
1094
1095             /* So the header value isn't RFC-compliant, but it's
1096              * better than no message-id at all. */
1097             if (message_id == NULL)
1098                 message_id = talloc_strdup (message_file, header);
1099
1100             /* Reject a Message ID that's too long. */
1101             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1102                 talloc_free (message_id);
1103                 message_id = NULL;
1104             }
1105         }
1106
1107         if (message_id == NULL ) {
1108             /* No message-id at all, let's generate one by taking a
1109              * hash over the file's contents. */
1110             char *sha1 = notmuch_sha1_of_file (filename);
1111
1112             /* If that failed too, something is really wrong. Give up. */
1113             if (sha1 == NULL) {
1114                 ret = NOTMUCH_STATUS_FILE_ERROR;
1115                 goto DONE;
1116             }
1117
1118             message_id = talloc_asprintf (message_file,
1119                                           "notmuch-sha1-%s", sha1);
1120             free (sha1);
1121         }
1122
1123         /* Now that we have a message ID, we get a message object,
1124          * (which may or may not reference an existing document in the
1125          * database). */
1126
1127         message = _notmuch_message_create_for_message_id (notmuch,
1128                                                           message_id,
1129                                                           &private_status);
1130
1131         talloc_free (message_id);
1132
1133         if (message == NULL) {
1134             ret = COERCE_STATUS (private_status,
1135                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1136             goto DONE;
1137         }
1138
1139         /* Is this a newly created message object? */
1140         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1141             _notmuch_message_set_filename (message, filename);
1142             _notmuch_message_add_term (message, "type", "mail");
1143         } else {
1144             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1145             goto DONE;
1146         }
1147
1148         ret = _notmuch_database_link_message (notmuch, message, message_file);
1149         if (ret)
1150             goto DONE;
1151
1152         date = notmuch_message_file_get_header (message_file, "date");
1153         _notmuch_message_set_date (message, date);
1154
1155         _notmuch_message_index_file (message, filename);
1156
1157         _notmuch_message_sync (message);
1158     } catch (const Xapian::Error &error) {
1159         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1160                  error.get_description().c_str());
1161         notmuch->exception_reported = TRUE;
1162         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1163         goto DONE;
1164     }
1165
1166   DONE:
1167     if (message) {
1168         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1169             *message_ret = message;
1170         else
1171             notmuch_message_destroy (message);
1172     }
1173
1174     if (message_file)
1175         notmuch_message_file_close (message_file);
1176
1177     return ret;
1178 }
1179
1180 notmuch_tags_t *
1181 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1182                        Xapian::TermIterator &end)
1183 {
1184     const char *prefix = _find_prefix ("tag");
1185     notmuch_tags_t *tags;
1186     std::string tag;
1187
1188     /* Currently this iteration is written with the assumption that
1189      * "tag" has a single-character prefix. */
1190     assert (strlen (prefix) == 1);
1191
1192     tags = _notmuch_tags_create (ctx);
1193     if (unlikely (tags == NULL))
1194         return NULL;
1195
1196     i.skip_to (prefix);
1197
1198     while (i != end) {
1199         tag = *i;
1200
1201         if (tag.empty () || tag[0] != *prefix)
1202             break;
1203
1204         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1205
1206         i++;
1207     }
1208
1209     _notmuch_tags_prepare_iterator (tags);
1210
1211     return tags;
1212 }
1213
1214 notmuch_tags_t *
1215 notmuch_database_get_all_tags (notmuch_database_t *db)
1216 {
1217     Xapian::TermIterator i, end;
1218     i = db->xapian_db->allterms_begin();
1219     end = db->xapian_db->allterms_end();
1220     return _notmuch_convert_tags(db, i, end);
1221 }