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