]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
39cbc68342eccb58d93f7534fe6a30c43bedbc5a
[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 <sys/time.h>
26 #include <signal.h>
27 #include <xapian.h>
28
29 #include <glib.h> /* g_free, GPtrArray, GHashTable */
30
31 using namespace std;
32
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
34
35 typedef struct {
36     const char *name;
37     const char *prefix;
38 } prefix_t;
39
40 #define NOTMUCH_DATABASE_VERSION 1
41
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
44
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
46  *
47  * We currently have two different types of documents: mail and directory.
48  *
49  * Mail document
50  * -------------
51  * A mail document is associated with a particular email message file
52  * on disk. It is indexed with the following prefixed terms which the
53  * database uses to construct threads, etc.:
54  *
55  *    Single terms of given prefix:
56  *
57  *      type:   mail
58  *
59  *      id:     Unique ID of mail, (from Message-ID header or generated
60  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
61  *
62  *      thread: The ID of the thread to which the mail belongs
63  *
64  *      replyto: The ID from the In-Reply-To header of the mail (if any).
65  *
66  *    Multiple terms of given prefix:
67  *
68  *      reference: All message IDs from In-Reply-To and Re ferences
69  *                 headers in the message.
70  *
71  *      tag:       Any tags associated with this message by the user.
72  *
73  *      file-direntry:  A colon-separated pair of values
74  *                      (INTEGER:STRING), where INTEGER is the
75  *                      document ID of a directory document, and
76  *                      STRING is the name of a file within that
77  *                      directory for this mail message.
78  *
79  *    A mail document also has two values:
80  *
81  *      TIMESTAMP:      The time_t value corresponding to the message's
82  *                      Date header.
83  *
84  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
85  *
86  * In addition, terms from the content of the message are added with
87  * "from", "to", "attachment", and "subject" prefixes for use by the
88  * user in searching. But the database doesn't really care itself
89  * about any of these.
90  *
91  * The data portion of a mail document is empty.
92  *
93  * Directory document
94  * ------------------
95  * A directory document is used by a client of the notmuch library to
96  * maintain data necessary to allow for efficient polling of mail
97  * directories.
98  *
99  * All directory documents contain one term:
100  *
101  *      directory:      The directory path (relative to the database path)
102  *                      Or the SHA1 sum of the directory path (if the
103  *                      path itself is too long to fit in a Xapian
104  *                      term).
105  *
106  * And all directory documents for directories other than top-level
107  * directories also contain the following term:
108  *
109  *      directory-direntry: A colon-separated pair of values
110  *                          (INTEGER:STRING), where INTEGER is the
111  *                          document ID of the parent directory
112  *                          document, and STRING is the name of this
113  *                          directory within that parent.
114  *
115  * All directory documents have a single value:
116  *
117  *      TIMESTAMP:      The mtime of the directory (at last scan)
118  *
119  * The data portion of a directory document contains the path of the
120  * directory (relative to the database path).
121  */
122
123 /* With these prefix values we follow the conventions published here:
124  *
125  * http://xapian.org/docs/omega/termprefixes.html
126  *
127  * as much as makes sense. Note that I took some liberty in matching
128  * the reserved prefix values to notmuch concepts, (for example, 'G'
129  * is documented as "newsGroup (or similar entity - e.g. a web forum
130  * name)", for which I think the thread is the closest analogue in
131  * notmuch. This in spite of the fact that we will eventually be
132  * storing mailing-list messages where 'G' for "mailing list name"
133  * might be even a closer analogue. I'm treating the single-character
134  * prefixes preferentially for core notmuch concepts (which will be
135  * nearly universal to all mail messages).
136  */
137
138 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
139     { "type",                   "T" },
140     { "reference",              "XREFERENCE" },
141     { "replyto",                "XREPLYTO" },
142     { "directory",              "XDIRECTORY" },
143     { "file-direntry",          "XFDIRENTRY" },
144     { "directory-direntry",     "XDDIRENTRY" },
145 };
146
147 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
148     { "thread",                 "G" },
149     { "tag",                    "K" },
150     { "is",                     "K" },
151     { "id",                     "Q" }
152 };
153
154 prefix_t PROBABILISTIC_PREFIX[]= {
155     { "from",                   "XFROM" },
156     { "to",                     "XTO" },
157     { "attachment",             "XATTACHMENT" },
158     { "subject",                "XSUBJECT"}
159 };
160
161 int
162 _internal_error (const char *format, ...)
163 {
164     va_list va_args;
165
166     va_start (va_args, format);
167
168     fprintf (stderr, "Internal error: ");
169     vfprintf (stderr, format, va_args);
170
171     exit (1);
172
173     return 1;
174 }
175
176 const char *
177 _find_prefix (const char *name)
178 {
179     unsigned int i;
180
181     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
182         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
183             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
184     }
185
186     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
187         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
188             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
189     }
190
191     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
192         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
193             return PROBABILISTIC_PREFIX[i].prefix;
194     }
195
196     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
197
198     return "";
199 }
200
201 const char *
202 notmuch_status_to_string (notmuch_status_t status)
203 {
204     switch (status) {
205     case NOTMUCH_STATUS_SUCCESS:
206         return "No error occurred";
207     case NOTMUCH_STATUS_OUT_OF_MEMORY:
208         return "Out of memory";
209     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
210         return "Attempt to write to a read-only database";
211     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
212         return "A Xapian exception occurred";
213     case NOTMUCH_STATUS_FILE_ERROR:
214         return "Something went wrong trying to read or write a file";
215     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
216         return "File is not an email";
217     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
218         return "Message ID is identical to a message in database";
219     case NOTMUCH_STATUS_NULL_POINTER:
220         return "Erroneous NULL pointer";
221     case NOTMUCH_STATUS_TAG_TOO_LONG:
222         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
223     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
224         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
225     default:
226     case NOTMUCH_STATUS_LAST_STATUS:
227         return "Unknown error status value";
228     }
229 }
230
231 static void
232 find_doc_ids_for_term (notmuch_database_t *notmuch,
233                        const char *term,
234                        Xapian::PostingIterator *begin,
235                        Xapian::PostingIterator *end)
236 {
237     *begin = notmuch->xapian_db->postlist_begin (term);
238
239     *end = notmuch->xapian_db->postlist_end (term);
240 }
241
242 static void
243 find_doc_ids (notmuch_database_t *notmuch,
244               const char *prefix_name,
245               const char *value,
246               Xapian::PostingIterator *begin,
247               Xapian::PostingIterator *end)
248 {
249     char *term;
250
251     term = talloc_asprintf (notmuch, "%s%s",
252                             _find_prefix (prefix_name), value);
253
254     find_doc_ids_for_term (notmuch, term, begin, end);
255
256     talloc_free (term);
257 }
258
259 notmuch_private_status_t
260 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
261                                       const char *prefix_name,
262                                       const char *value,
263                                       unsigned int *doc_id)
264 {
265     Xapian::PostingIterator i, end;
266
267     find_doc_ids (notmuch, prefix_name, value, &i, &end);
268
269     if (i == end) {
270         *doc_id = 0;
271         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
272     }
273
274     *doc_id = *i;
275
276 #if DEBUG_DATABASE_SANITY
277     i++;
278
279     if (i != end)
280         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
281                         prefix_name, value);
282 #endif
283
284     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
285 }
286
287 static Xapian::Document
288 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
289 {
290     return notmuch->xapian_db->get_document (doc_id);
291 }
292
293 notmuch_message_t *
294 notmuch_database_find_message (notmuch_database_t *notmuch,
295                                const char *message_id)
296 {
297     notmuch_private_status_t status;
298     unsigned int doc_id;
299
300     status = _notmuch_database_find_unique_doc_id (notmuch, "id",
301                                                    message_id, &doc_id);
302
303     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
304         return NULL;
305
306     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
307 }
308
309 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
310  * a (potentially nested) parenthesized sequence with '\' used to
311  * escape any character (including parentheses).
312  *
313  * If the sequence to be skipped continues to the end of the string,
314  * then 'str' will be left pointing at the final terminating '\0'
315  * character.
316  */
317 static void
318 skip_space_and_comments (const char **str)
319 {
320     const char *s;
321
322     s = *str;
323     while (*s && (isspace (*s) || *s == '(')) {
324         while (*s && isspace (*s))
325             s++;
326         if (*s == '(') {
327             int nesting = 1;
328             s++;
329             while (*s && nesting) {
330                 if (*s == '(') {
331                     nesting++;
332                 } else if (*s == ')') {
333                     nesting--;
334                 } else if (*s == '\\') {
335                     if (*(s+1))
336                         s++;
337                 }
338                 s++;
339             }
340         }
341     }
342
343     *str = s;
344 }
345
346 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
347  * comments, and the '<' and '>' delimeters.
348  *
349  * If not NULL, then *next will be made to point to the first character
350  * not parsed, (possibly pointing to the final '\0' terminator.
351  *
352  * Returns a newly talloc'ed string belonging to 'ctx'.
353  *
354  * Returns NULL if there is any error parsing the message-id. */
355 static char *
356 _parse_message_id (void *ctx, const char *message_id, const char **next)
357 {
358     const char *s, *end;
359     char *result;
360
361     if (message_id == NULL || *message_id == '\0')
362         return NULL;
363
364     s = message_id;
365
366     skip_space_and_comments (&s);
367
368     /* Skip any unstructured text as well. */
369     while (*s && *s != '<')
370         s++;
371
372     if (*s == '<') {
373         s++;
374     } else {
375         if (next)
376             *next = s;
377         return NULL;
378     }
379
380     skip_space_and_comments (&s);
381
382     end = s;
383     while (*end && *end != '>')
384         end++;
385     if (next) {
386         if (*end)
387             *next = end + 1;
388         else
389             *next = end;
390     }
391
392     if (end > s && *end == '>')
393         end--;
394     if (end <= s)
395         return NULL;
396
397     result = talloc_strndup (ctx, s, end - s + 1);
398
399     /* Finally, collapse any whitespace that is within the message-id
400      * itself. */
401     {
402         char *r;
403         int len;
404
405         for (r = result, len = strlen (r); *r; r++, len--)
406             if (*r == ' ' || *r == '\t')
407                 memmove (r, r+1, len);
408     }
409
410     return result;
411 }
412
413 /* Parse a References header value, putting a (talloc'ed under 'ctx')
414  * copy of each referenced message-id into 'hash'.
415  *
416  * We explicitly avoid including any reference identical to
417  * 'message_id' in the result (to avoid mass confusion when a single
418  * message references itself cyclically---and yes, mail messages are
419  * not infrequent in the wild that do this---don't ask me why).
420 */
421 static void
422 parse_references (void *ctx,
423                   const char *message_id,
424                   GHashTable *hash,
425                   const char *refs)
426 {
427     char *ref;
428
429     if (refs == NULL || *refs == '\0')
430         return;
431
432     while (*refs) {
433         ref = _parse_message_id (ctx, refs, &refs);
434
435         if (ref && strcmp (ref, message_id))
436             g_hash_table_insert (hash, ref, NULL);
437     }
438 }
439
440 notmuch_database_t *
441 notmuch_database_create (const char *path)
442 {
443     notmuch_database_t *notmuch = NULL;
444     char *notmuch_path = NULL;
445     struct stat st;
446     int err;
447
448     if (path == NULL) {
449         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
450         goto DONE;
451     }
452
453     err = stat (path, &st);
454     if (err) {
455         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
456                  path, strerror (errno));
457         goto DONE;
458     }
459
460     if (! S_ISDIR (st.st_mode)) {
461         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
462                  path);
463         goto DONE;
464     }
465
466     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
467
468     err = mkdir (notmuch_path, 0755);
469
470     if (err) {
471         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
472                  notmuch_path, strerror (errno));
473         goto DONE;
474     }
475
476     notmuch = notmuch_database_open (path,
477                                      NOTMUCH_DATABASE_MODE_READ_WRITE);
478     notmuch_database_upgrade (notmuch, NULL, NULL);
479
480   DONE:
481     if (notmuch_path)
482         talloc_free (notmuch_path);
483
484     return notmuch;
485 }
486
487 notmuch_status_t
488 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
489 {
490     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
491         fprintf (stderr, "Cannot write to a read-only database.\n");
492         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
493     }
494
495     return NOTMUCH_STATUS_SUCCESS;
496 }
497
498 notmuch_database_t *
499 notmuch_database_open (const char *path,
500                        notmuch_database_mode_t mode)
501 {
502     notmuch_database_t *notmuch = NULL;
503     char *notmuch_path = NULL, *xapian_path = NULL;
504     struct stat st;
505     int err;
506     unsigned int i, version;
507
508     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
509         notmuch_path = NULL;
510         fprintf (stderr, "Out of memory\n");
511         goto DONE;
512     }
513
514     err = stat (notmuch_path, &st);
515     if (err) {
516         fprintf (stderr, "Error opening database at %s: %s\n",
517                  notmuch_path, strerror (errno));
518         goto DONE;
519     }
520
521     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
522         xapian_path = NULL;
523         fprintf (stderr, "Out of memory\n");
524         goto DONE;
525     }
526
527     notmuch = talloc (NULL, notmuch_database_t);
528     notmuch->exception_reported = FALSE;
529     notmuch->path = talloc_strdup (notmuch, path);
530
531     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
532         notmuch->path[strlen (notmuch->path) - 1] = '\0';
533
534     notmuch->needs_upgrade = FALSE;
535     notmuch->mode = mode;
536     try {
537         string last_thread_id;
538
539         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
540             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
541                                                                Xapian::DB_CREATE_OR_OPEN);
542             version = notmuch_database_get_version (notmuch);
543
544             if (version > NOTMUCH_DATABASE_VERSION) {
545                 fprintf (stderr,
546                          "Error: Notmuch database at %s\n"
547                          "       has a newer database format version (%u) than supported by this\n"
548                          "       version of notmuch (%u). Refusing to open this database in\n"
549                          "       read-write mode.\n",
550                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
551                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
552                 notmuch_database_close (notmuch);
553                 notmuch = NULL;
554                 goto DONE;
555             }
556
557             if (version < NOTMUCH_DATABASE_VERSION)
558                 notmuch->needs_upgrade = TRUE;
559         } else {
560             notmuch->xapian_db = new Xapian::Database (xapian_path);
561             version = notmuch_database_get_version (notmuch);
562             if (version > NOTMUCH_DATABASE_VERSION)
563             {
564                 fprintf (stderr,
565                          "Warning: Notmuch database at %s\n"
566                          "         has a newer database format version (%u) than supported by this\n"
567                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
568                          "         (but the database will not be harmed since it is being opened\n"
569                          "         in read-only mode).\n",
570                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
571             }
572         }
573
574         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
575         if (last_thread_id.empty ()) {
576             notmuch->last_thread_id = 0;
577         } else {
578             const char *str;
579             char *end;
580
581             str = last_thread_id.c_str ();
582             notmuch->last_thread_id = strtoull (str, &end, 16);
583             if (*end != '\0')
584                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
585         }
586
587         notmuch->query_parser = new Xapian::QueryParser;
588         notmuch->term_gen = new Xapian::TermGenerator;
589         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
590         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
591
592         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
593         notmuch->query_parser->set_database (*notmuch->xapian_db);
594         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
595         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
596         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
597
598         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
599             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
600             notmuch->query_parser->add_boolean_prefix (prefix->name,
601                                                        prefix->prefix);
602         }
603
604         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
605             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
606             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
607         }
608     } catch (const Xapian::Error &error) {
609         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
610                  error.get_msg().c_str());
611         notmuch = NULL;
612     }
613
614   DONE:
615     if (notmuch_path)
616         free (notmuch_path);
617     if (xapian_path)
618         free (xapian_path);
619
620     return notmuch;
621 }
622
623 void
624 notmuch_database_close (notmuch_database_t *notmuch)
625 {
626     try {
627         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
628             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
629     } catch (const Xapian::Error &error) {
630         if (! notmuch->exception_reported) {
631             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
632                      error.get_msg().c_str());
633         }
634     }
635
636     delete notmuch->term_gen;
637     delete notmuch->query_parser;
638     delete notmuch->xapian_db;
639     delete notmuch->value_range_processor;
640     talloc_free (notmuch);
641 }
642
643 const char *
644 notmuch_database_get_path (notmuch_database_t *notmuch)
645 {
646     return notmuch->path;
647 }
648
649 unsigned int
650 notmuch_database_get_version (notmuch_database_t *notmuch)
651 {
652     unsigned int version;
653     string version_string;
654     const char *str;
655     char *end;
656
657     version_string = notmuch->xapian_db->get_metadata ("version");
658     if (version_string.empty ())
659         return 0;
660
661     str = version_string.c_str ();
662     if (str == NULL || *str == '\0')
663         return 0;
664
665     version = strtoul (str, &end, 10);
666     if (*end != '\0')
667         INTERNAL_ERROR ("Malformed database version: %s", str);
668
669     return version;
670 }
671
672 notmuch_bool_t
673 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
674 {
675     return notmuch->needs_upgrade;
676 }
677
678 static volatile sig_atomic_t do_progress_notify = 0;
679
680 static void
681 handle_sigalrm (unused (int signal))
682 {
683     do_progress_notify = 1;
684 }
685
686 /* Upgrade the current database.
687  *
688  * After opening a database in read-write mode, the client should
689  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
690  * if so, upgrade with this function before making any modifications.
691  *
692  * The optional progress_notify callback can be used by the caller to
693  * provide progress indication to the user. If non-NULL it will be
694  * called periodically with 'count' as the number of messages upgraded
695  * so far and 'total' the overall number of messages that will be
696  * converted.
697  */
698 notmuch_status_t
699 notmuch_database_upgrade (notmuch_database_t *notmuch,
700                           void (*progress_notify) (void *closure,
701                                                    double progress),
702                           void *closure)
703 {
704     Xapian::WritableDatabase *db;
705     struct sigaction action;
706     struct itimerval timerval;
707     notmuch_bool_t timer_is_active = FALSE;
708     unsigned int version;
709     notmuch_status_t status;
710     unsigned int count = 0, total = 0;
711
712     status = _notmuch_database_ensure_writable (notmuch);
713     if (status)
714         return status;
715
716     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
717
718     version = notmuch_database_get_version (notmuch);
719
720     if (version >= NOTMUCH_DATABASE_VERSION)
721         return NOTMUCH_STATUS_SUCCESS;
722
723     if (progress_notify) {
724         /* Setup our handler for SIGALRM */
725         memset (&action, 0, sizeof (struct sigaction));
726         action.sa_handler = handle_sigalrm;
727         sigemptyset (&action.sa_mask);
728         action.sa_flags = SA_RESTART;
729         sigaction (SIGALRM, &action, NULL);
730
731         /* Then start a timer to send SIGALRM once per second. */
732         timerval.it_interval.tv_sec = 1;
733         timerval.it_interval.tv_usec = 0;
734         timerval.it_value.tv_sec = 1;
735         timerval.it_value.tv_usec = 0;
736         setitimer (ITIMER_REAL, &timerval, NULL);
737
738         timer_is_active = TRUE;
739     }
740
741     /* Before version 1, each message document had its filename in the
742      * data field. Copy that into the new format by calling
743      * notmuch_message_add_filename.
744      */
745     if (version < 1) {
746         notmuch_query_t *query = notmuch_query_create (notmuch, "");
747         notmuch_messages_t *messages;
748         notmuch_message_t *message;
749         char *filename;
750         Xapian::TermIterator t, t_end;
751
752         total = notmuch_query_count_messages (query);
753
754         for (messages = notmuch_query_search_messages (query);
755              notmuch_messages_valid (messages);
756              notmuch_messages_move_to_next (messages))
757         {
758             if (do_progress_notify) {
759                 progress_notify (closure, (double) count / total);
760                 do_progress_notify = 0;
761             }
762
763             message = notmuch_messages_get (messages);
764
765             filename = _notmuch_message_talloc_copy_data (message);
766             if (filename && *filename != '\0') {
767                 _notmuch_message_add_filename (message, filename);
768                 _notmuch_message_sync (message);
769             }
770             talloc_free (filename);
771
772             notmuch_message_destroy (message);
773
774             count++;
775         }
776
777         notmuch_query_destroy (query);
778
779         /* Also, before version 1 we stored directory timestamps in
780          * XTIMESTAMP documents instead of the current XDIRECTORY
781          * documents. So copy those as well. */
782
783         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
784
785         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
786              t != t_end;
787              t++)
788         {
789             Xapian::PostingIterator p, p_end;
790             std::string term = *t;
791
792             p_end = notmuch->xapian_db->postlist_end (term);
793
794             for (p = notmuch->xapian_db->postlist_begin (term);
795                  p != p_end;
796                  p++)
797             {
798                 Xapian::Document document;
799                 time_t mtime;
800                 notmuch_directory_t *directory;
801
802                 if (do_progress_notify) {
803                     progress_notify (closure, (double) count / total);
804                     do_progress_notify = 0;
805                 }
806
807                 document = find_document_for_doc_id (notmuch, *p);
808                 mtime = Xapian::sortable_unserialise (
809                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
810
811                 directory = notmuch_database_get_directory (notmuch,
812                                                             term.c_str() + 10);
813                 notmuch_directory_set_mtime (directory, mtime);
814                 notmuch_directory_destroy (directory);
815             }
816         }
817     }
818
819     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
820     db->flush ();
821
822     /* Now that the upgrade is complete we can remove the old data
823      * and documents that are no longer needed. */
824     if (version < 1) {
825         notmuch_query_t *query = notmuch_query_create (notmuch, "");
826         notmuch_messages_t *messages;
827         notmuch_message_t *message;
828         char *filename;
829
830         for (messages = notmuch_query_search_messages (query);
831              notmuch_messages_valid (messages);
832              notmuch_messages_move_to_next (messages))
833         {
834             if (do_progress_notify) {
835                 progress_notify (closure, (double) count / total);
836                 do_progress_notify = 0;
837             }
838
839             message = notmuch_messages_get (messages);
840
841             filename = _notmuch_message_talloc_copy_data (message);
842             if (filename && *filename != '\0') {
843                 _notmuch_message_clear_data (message);
844                 _notmuch_message_sync (message);
845             }
846             talloc_free (filename);
847
848             notmuch_message_destroy (message);
849         }
850
851         notmuch_query_destroy (query);
852     }
853
854     if (version < 1) {
855         Xapian::TermIterator t, t_end;
856
857         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
858
859         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
860              t != t_end;
861              t++)
862         {
863             Xapian::PostingIterator p, p_end;
864             std::string term = *t;
865
866             p_end = notmuch->xapian_db->postlist_end (term);
867
868             for (p = notmuch->xapian_db->postlist_begin (term);
869                  p != p_end;
870                  p++)
871             {
872                 if (do_progress_notify) {
873                     progress_notify (closure, (double) count / total);
874                     do_progress_notify = 0;
875                 }
876
877                 db->delete_document (*p);
878             }
879         }
880     }
881
882     if (timer_is_active) {
883         /* Now stop the timer. */
884         timerval.it_interval.tv_sec = 0;
885         timerval.it_interval.tv_usec = 0;
886         timerval.it_value.tv_sec = 0;
887         timerval.it_value.tv_usec = 0;
888         setitimer (ITIMER_REAL, &timerval, NULL);
889
890         /* And disable the signal handler. */
891         action.sa_handler = SIG_IGN;
892         sigaction (SIGALRM, &action, NULL);
893     }
894
895     return NOTMUCH_STATUS_SUCCESS;
896 }
897
898 /* We allow the user to use arbitrarily long paths for directories. But
899  * we have a term-length limit. So if we exceed that, we'll use the
900  * SHA-1 of the path for the database term.
901  *
902  * Note: This function may return the original value of 'path'. If it
903  * does not, then the caller is responsible to free() the returned
904  * value.
905  */
906 const char *
907 _notmuch_database_get_directory_db_path (const char *path)
908 {
909     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
910
911     if (term_len > NOTMUCH_TERM_MAX)
912         return notmuch_sha1_of_string (path);
913     else
914         return path;
915 }
916
917 /* Given a path, split it into two parts: the directory part is all
918  * components except for the last, and the basename is that last
919  * component. Getting the return-value for either part is optional
920  * (the caller can pass NULL).
921  *
922  * The original 'path' can represent either a regular file or a
923  * directory---the splitting will be carried out in the same way in
924  * either case. Trailing slashes on 'path' will be ignored, and any
925  * cases of multiple '/' characters appearing in series will be
926  * treated as a single '/'.
927  *
928  * Allocation (if any) will have 'ctx' as the talloc owner. But
929  * pointers will be returned within the original path string whenever
930  * possible.
931  *
932  * Note: If 'path' is non-empty and contains no non-trailing slash,
933  * (that is, consists of a filename with no parent directory), then
934  * the directory returned will be an empty string. However, if 'path'
935  * is an empty string, then both directory and basename will be
936  * returned as NULL.
937  */
938 notmuch_status_t
939 _notmuch_database_split_path (void *ctx,
940                               const char *path,
941                               const char **directory,
942                               const char **basename)
943 {
944     const char *slash;
945
946     if (path == NULL || *path == '\0') {
947         if (directory)
948             *directory = NULL;
949         if (basename)
950             *basename = NULL;
951         return NOTMUCH_STATUS_SUCCESS;
952     }
953
954     /* Find the last slash (not counting a trailing slash), if any. */
955
956     slash = path + strlen (path) - 1;
957
958     /* First, skip trailing slashes. */
959     while (slash != path) {
960         if (*slash != '/')
961             break;
962
963         --slash;
964     }
965
966     /* Then, find a slash. */
967     while (slash != path) {
968         if (*slash == '/')
969             break;
970
971         if (basename)
972             *basename = slash;
973
974         --slash;
975     }
976
977     /* Finally, skip multiple slashes. */
978     while (slash != path) {
979         if (*slash != '/')
980             break;
981
982         --slash;
983     }
984
985     if (slash == path) {
986         if (directory)
987             *directory = talloc_strdup (ctx, "");
988         if (basename)
989             *basename = path;
990     } else {
991         if (directory)
992             *directory = talloc_strndup (ctx, path, slash - path + 1);
993     }
994
995     return NOTMUCH_STATUS_SUCCESS;
996 }
997
998 notmuch_status_t
999 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1000                                      const char *path,
1001                                      unsigned int *directory_id)
1002 {
1003     notmuch_directory_t *directory;
1004     notmuch_status_t status;
1005
1006     if (path == NULL) {
1007         *directory_id = 0;
1008         return NOTMUCH_STATUS_SUCCESS;
1009     }
1010
1011     directory = _notmuch_directory_create (notmuch, path, &status);
1012     if (status) {
1013         *directory_id = -1;
1014         return status;
1015     }
1016
1017     *directory_id = _notmuch_directory_get_document_id (directory);
1018
1019     notmuch_directory_destroy (directory);
1020
1021     return NOTMUCH_STATUS_SUCCESS;
1022 }
1023
1024 const char *
1025 _notmuch_database_get_directory_path (void *ctx,
1026                                       notmuch_database_t *notmuch,
1027                                       unsigned int doc_id)
1028 {
1029     Xapian::Document document;
1030
1031     document = find_document_for_doc_id (notmuch, doc_id);
1032
1033     return talloc_strdup (ctx, document.get_data ().c_str ());
1034 }
1035
1036 /* Given a legal 'filename' for the database, (either relative to
1037  * database path or absolute with initial components identical to
1038  * database path), return a new string (with 'ctx' as the talloc
1039  * owner) suitable for use as a direntry term value.
1040  *
1041  * The necessary directory documents will be created in the database
1042  * as needed.
1043  */
1044 notmuch_status_t
1045 _notmuch_database_filename_to_direntry (void *ctx,
1046                                         notmuch_database_t *notmuch,
1047                                         const char *filename,
1048                                         char **direntry)
1049 {
1050     const char *relative, *directory, *basename;
1051     Xapian::docid directory_id;
1052     notmuch_status_t status;
1053
1054     relative = _notmuch_database_relative_path (notmuch, filename);
1055
1056     status = _notmuch_database_split_path (ctx, relative,
1057                                            &directory, &basename);
1058     if (status)
1059         return status;
1060
1061     status = _notmuch_database_find_directory_id (notmuch, directory,
1062                                                   &directory_id);
1063     if (status)
1064         return status;
1065
1066     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1067
1068     return NOTMUCH_STATUS_SUCCESS;
1069 }
1070
1071 /* Given a legal 'path' for the database, return the relative path.
1072  *
1073  * The return value will be a pointer to the originl path contents,
1074  * and will be either the original string (if 'path' was relative) or
1075  * a portion of the string (if path was absolute and begins with the
1076  * database path).
1077  */
1078 const char *
1079 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1080                                  const char *path)
1081 {
1082     const char *db_path, *relative;
1083     unsigned int db_path_len;
1084
1085     db_path = notmuch_database_get_path (notmuch);
1086     db_path_len = strlen (db_path);
1087
1088     relative = path;
1089
1090     if (*relative == '/') {
1091         while (*relative == '/' && *(relative+1) == '/')
1092             relative++;
1093
1094         if (strncmp (relative, db_path, db_path_len) == 0)
1095         {
1096             relative += db_path_len;
1097             while (*relative == '/')
1098                 relative++;
1099         }
1100     }
1101
1102     return relative;
1103 }
1104
1105 notmuch_directory_t *
1106 notmuch_database_get_directory (notmuch_database_t *notmuch,
1107                                 const char *path)
1108 {
1109     notmuch_status_t status;
1110
1111     return _notmuch_directory_create (notmuch, path, &status);
1112 }
1113
1114 static const char *
1115 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1116 {
1117     /* 16 bytes (+ terminator) for hexadecimal representation of
1118      * a 64-bit integer. */
1119     static char thread_id[17];
1120     Xapian::WritableDatabase *db;
1121
1122     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1123
1124     notmuch->last_thread_id++;
1125
1126     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1127
1128     db->set_metadata ("last_thread_id", thread_id);
1129
1130     return thread_id;
1131 }
1132
1133 static char *
1134 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1135 {
1136     return talloc_asprintf (ctx, "thread_id_%s", message_id);
1137 }
1138
1139 /* Find the thread ID to which the message with 'message_id' belongs.
1140  *
1141  * Always returns a newly talloced string belonging to 'ctx'.
1142  *
1143  * Note: If there is no message in the database with the given
1144  * 'message_id' then a new thread_id will be allocated for this
1145  * message and stored in the database metadata, (where this same
1146  * thread ID can be looked up if the message is added to the database
1147  * later).
1148  */
1149 static const char *
1150 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1151                                   void *ctx,
1152                                   const char *message_id)
1153 {
1154     notmuch_message_t *message;
1155     string thread_id_string;
1156     const char *thread_id;
1157     char *metadata_key;
1158     Xapian::WritableDatabase *db;
1159
1160     message = notmuch_database_find_message (notmuch, message_id);
1161
1162     if (message) {
1163         thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1164
1165         notmuch_message_destroy (message);
1166
1167         return thread_id;
1168     }
1169
1170     /* Message has not been seen yet.
1171      *
1172      * We may have seen a reference to it already, in which case, we
1173      * can return the thread ID stored in the metadata. Otherwise, we
1174      * generate a new thread ID and store it there.
1175      */
1176     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1177     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1178     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1179
1180     if (thread_id_string.empty()) {
1181         thread_id = _notmuch_database_generate_thread_id (notmuch);
1182         db->set_metadata (metadata_key, thread_id);
1183     } else {
1184         thread_id = thread_id_string.c_str();
1185     }
1186
1187     talloc_free (metadata_key);
1188
1189     return thread_id;
1190 }
1191
1192 static notmuch_status_t
1193 _merge_threads (notmuch_database_t *notmuch,
1194                 const char *winner_thread_id,
1195                 const char *loser_thread_id)
1196 {
1197     Xapian::PostingIterator loser, loser_end;
1198     notmuch_message_t *message = NULL;
1199     notmuch_private_status_t private_status;
1200     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1201
1202     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1203
1204     for ( ; loser != loser_end; loser++) {
1205         message = _notmuch_message_create (notmuch, notmuch,
1206                                            *loser, &private_status);
1207         if (message == NULL) {
1208             ret = COERCE_STATUS (private_status,
1209                                  "Cannot find document for doc_id from query");
1210             goto DONE;
1211         }
1212
1213         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1214         _notmuch_message_add_term (message, "thread", winner_thread_id);
1215         _notmuch_message_sync (message);
1216
1217         notmuch_message_destroy (message);
1218         message = NULL;
1219     }
1220
1221   DONE:
1222     if (message)
1223         notmuch_message_destroy (message);
1224
1225     return ret;
1226 }
1227
1228 static void
1229 _my_talloc_free_for_g_hash (void *ptr)
1230 {
1231     talloc_free (ptr);
1232 }
1233
1234 static notmuch_status_t
1235 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1236                                            notmuch_message_t *message,
1237                                            notmuch_message_file_t *message_file,
1238                                            const char **thread_id)
1239 {
1240     GHashTable *parents = NULL;
1241     const char *refs, *in_reply_to, *in_reply_to_message_id;
1242     GList *l, *keys = NULL;
1243     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1244
1245     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1246                                      _my_talloc_free_for_g_hash, NULL);
1247
1248     refs = notmuch_message_file_get_header (message_file, "references");
1249     parse_references (message, notmuch_message_get_message_id (message),
1250                       parents, refs);
1251
1252     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1253     parse_references (message, notmuch_message_get_message_id (message),
1254                       parents, in_reply_to);
1255
1256     /* Carefully avoid adding any self-referential in-reply-to term. */
1257     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1258     if (in_reply_to_message_id &&
1259         strcmp (in_reply_to_message_id,
1260                 notmuch_message_get_message_id (message)))
1261     {
1262         _notmuch_message_add_term (message, "replyto",
1263                              _parse_message_id (message, in_reply_to, NULL));
1264     }
1265
1266     keys = g_hash_table_get_keys (parents);
1267     for (l = keys; l; l = l->next) {
1268         char *parent_message_id;
1269         const char *parent_thread_id;
1270
1271         parent_message_id = (char *) l->data;
1272         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1273                                                              message,
1274                                                              parent_message_id);
1275
1276         if (parent_thread_id == NULL) {
1277             _notmuch_message_add_term (message, "reference",
1278                                        parent_message_id);
1279         } else {
1280             if (*thread_id == NULL) {
1281                 *thread_id = talloc_strdup (message, parent_thread_id);
1282                 _notmuch_message_add_term (message, "thread", *thread_id);
1283             } else if (strcmp (*thread_id, parent_thread_id)) {
1284                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1285                 if (ret)
1286                     goto DONE;
1287             }
1288         }
1289     }
1290
1291   DONE:
1292     if (keys)
1293         g_list_free (keys);
1294     if (parents)
1295         g_hash_table_unref (parents);
1296
1297     return ret;
1298 }
1299
1300 static notmuch_status_t
1301 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1302                                             notmuch_message_t *message,
1303                                             const char **thread_id)
1304 {
1305     const char *message_id = notmuch_message_get_message_id (message);
1306     Xapian::PostingIterator child, children_end;
1307     notmuch_message_t *child_message = NULL;
1308     const char *child_thread_id;
1309     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1310     notmuch_private_status_t private_status;
1311
1312     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1313
1314     for ( ; child != children_end; child++) {
1315
1316         child_message = _notmuch_message_create (message, notmuch,
1317                                                  *child, &private_status);
1318         if (child_message == NULL) {
1319             ret = COERCE_STATUS (private_status,
1320                                  "Cannot find document for doc_id from query");
1321             goto DONE;
1322         }
1323
1324         child_thread_id = notmuch_message_get_thread_id (child_message);
1325         if (*thread_id == NULL) {
1326             *thread_id = talloc_strdup (message, child_thread_id);
1327             _notmuch_message_add_term (message, "thread", *thread_id);
1328         } else if (strcmp (*thread_id, child_thread_id)) {
1329             _notmuch_message_remove_term (child_message, "reference",
1330                                           message_id);
1331             _notmuch_message_sync (child_message);
1332             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1333             if (ret)
1334                 goto DONE;
1335         }
1336
1337         notmuch_message_destroy (child_message);
1338         child_message = NULL;
1339     }
1340
1341   DONE:
1342     if (child_message)
1343         notmuch_message_destroy (child_message);
1344
1345     return ret;
1346 }
1347
1348 /* Given a (mostly empty) 'message' and its corresponding
1349  * 'message_file' link it to existing threads in the database.
1350  *
1351  * The first check is in the metadata of the database to see if we
1352  * have pre-allocated a thread_id in advance for this message, (which
1353  * would have happened if a message was previously added that
1354  * referenced this one).
1355  *
1356  * Second, we look at 'message_file' and its link-relevant headers
1357  * (References and In-Reply-To) for message IDs.
1358  *
1359  * Finally, we look in the database for existing message that
1360  * reference 'message'.
1361  *
1362  * In all cases, we assign to the current message the first thread_id
1363  * found (through either parent or child). We will also merge any
1364  * existing, distinct threads where this message belongs to both,
1365  * (which is not uncommon when mesages are processed out of order).
1366  *
1367  * Finally, if no thread ID has been found through parent or child, we
1368  * call _notmuch_message_generate_thread_id to generate a new thread
1369  * ID. This should only happen for new, top-level messages, (no
1370  * References or In-Reply-To header in this message, and no previously
1371  * added message refers to this message).
1372  */
1373 static notmuch_status_t
1374 _notmuch_database_link_message (notmuch_database_t *notmuch,
1375                                 notmuch_message_t *message,
1376                                 notmuch_message_file_t *message_file)
1377 {
1378     notmuch_status_t status;
1379     const char *message_id, *thread_id = NULL;
1380     char *metadata_key;
1381     string stored_id;
1382
1383     message_id = notmuch_message_get_message_id (message);
1384     metadata_key = _get_metadata_thread_id_key (message, message_id);
1385
1386     /* Check if we have already seen related messages to this one.
1387      * If we have then use the thread_id that we stored at that time.
1388      */
1389     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1390     if (! stored_id.empty()) {
1391         Xapian::WritableDatabase *db;
1392
1393         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1394
1395         /* Clear the metadata for this message ID. We don't need it
1396          * anymore. */
1397         db->set_metadata (metadata_key, "");
1398         thread_id = stored_id.c_str();
1399
1400         _notmuch_message_add_term (message, "thread", thread_id);
1401     }
1402     talloc_free (metadata_key);
1403
1404     status = _notmuch_database_link_message_to_parents (notmuch, message,
1405                                                         message_file,
1406                                                         &thread_id);
1407     if (status)
1408         return status;
1409
1410     status = _notmuch_database_link_message_to_children (notmuch, message,
1411                                                          &thread_id);
1412     if (status)
1413         return status;
1414
1415     /* If not part of any existing thread, generate a new thread ID. */
1416     if (thread_id == NULL) {
1417         thread_id = _notmuch_database_generate_thread_id (notmuch);
1418
1419         _notmuch_message_add_term (message, "thread", thread_id);
1420     }
1421
1422     return NOTMUCH_STATUS_SUCCESS;
1423 }
1424
1425 notmuch_status_t
1426 notmuch_database_add_message (notmuch_database_t *notmuch,
1427                               const char *filename,
1428                               notmuch_message_t **message_ret)
1429 {
1430     notmuch_message_file_t *message_file;
1431     notmuch_message_t *message = NULL;
1432     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1433     notmuch_private_status_t private_status;
1434
1435     const char *date, *header;
1436     const char *from, *to, *subject;
1437     char *message_id = NULL;
1438
1439     if (message_ret)
1440         *message_ret = NULL;
1441
1442     ret = _notmuch_database_ensure_writable (notmuch);
1443     if (ret)
1444         return ret;
1445
1446     message_file = notmuch_message_file_open (filename);
1447     if (message_file == NULL)
1448         return NOTMUCH_STATUS_FILE_ERROR;
1449
1450     notmuch_message_file_restrict_headers (message_file,
1451                                            "date",
1452                                            "from",
1453                                            "in-reply-to",
1454                                            "message-id",
1455                                            "references",
1456                                            "subject",
1457                                            "to",
1458                                            (char *) NULL);
1459
1460     try {
1461         /* Before we do any real work, (especially before doing a
1462          * potential SHA-1 computation on the entire file's contents),
1463          * let's make sure that what we're looking at looks like an
1464          * actual email message.
1465          */
1466         from = notmuch_message_file_get_header (message_file, "from");
1467         subject = notmuch_message_file_get_header (message_file, "subject");
1468         to = notmuch_message_file_get_header (message_file, "to");
1469
1470         if ((from == NULL || *from == '\0') &&
1471             (subject == NULL || *subject == '\0') &&
1472             (to == NULL || *to == '\0'))
1473         {
1474             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1475             goto DONE;
1476         }
1477
1478         /* Now that we're sure it's mail, the first order of business
1479          * is to find a message ID (or else create one ourselves). */
1480
1481         header = notmuch_message_file_get_header (message_file, "message-id");
1482         if (header && *header != '\0') {
1483             message_id = _parse_message_id (message_file, header, NULL);
1484
1485             /* So the header value isn't RFC-compliant, but it's
1486              * better than no message-id at all. */
1487             if (message_id == NULL)
1488                 message_id = talloc_strdup (message_file, header);
1489
1490             /* Reject a Message ID that's too long. */
1491             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1492                 talloc_free (message_id);
1493                 message_id = NULL;
1494             }
1495         }
1496
1497         if (message_id == NULL ) {
1498             /* No message-id at all, let's generate one by taking a
1499              * hash over the file's contents. */
1500             char *sha1 = notmuch_sha1_of_file (filename);
1501
1502             /* If that failed too, something is really wrong. Give up. */
1503             if (sha1 == NULL) {
1504                 ret = NOTMUCH_STATUS_FILE_ERROR;
1505                 goto DONE;
1506             }
1507
1508             message_id = talloc_asprintf (message_file,
1509                                           "notmuch-sha1-%s", sha1);
1510             free (sha1);
1511         }
1512
1513         /* Now that we have a message ID, we get a message object,
1514          * (which may or may not reference an existing document in the
1515          * database). */
1516
1517         message = _notmuch_message_create_for_message_id (notmuch,
1518                                                           message_id,
1519                                                           &private_status);
1520
1521         talloc_free (message_id);
1522
1523         if (message == NULL) {
1524             ret = COERCE_STATUS (private_status,
1525                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1526             goto DONE;
1527         }
1528
1529         _notmuch_message_add_filename (message, filename);
1530
1531         /* Is this a newly created message object? */
1532         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1533             _notmuch_message_add_term (message, "type", "mail");
1534
1535             ret = _notmuch_database_link_message (notmuch, message,
1536                                                   message_file);
1537             if (ret)
1538                 goto DONE;
1539
1540             date = notmuch_message_file_get_header (message_file, "date");
1541             _notmuch_message_set_date (message, date);
1542
1543             _notmuch_message_index_file (message, filename);
1544         } else {
1545             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1546         }
1547
1548         _notmuch_message_sync (message);
1549     } catch (const Xapian::Error &error) {
1550         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1551                  error.get_description().c_str());
1552         notmuch->exception_reported = TRUE;
1553         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1554         goto DONE;
1555     }
1556
1557   DONE:
1558     if (message) {
1559         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1560             *message_ret = message;
1561         else
1562             notmuch_message_destroy (message);
1563     }
1564
1565     if (message_file)
1566         notmuch_message_file_close (message_file);
1567
1568     return ret;
1569 }
1570
1571 notmuch_status_t
1572 notmuch_database_remove_message (notmuch_database_t *notmuch,
1573                                  const char *filename)
1574 {
1575     Xapian::WritableDatabase *db;
1576     void *local = talloc_new (notmuch);
1577     const char *prefix = _find_prefix ("file-direntry");
1578     char *direntry, *term;
1579     Xapian::PostingIterator i, end;
1580     Xapian::Document document;
1581     notmuch_status_t status;
1582
1583     status = _notmuch_database_ensure_writable (notmuch);
1584     if (status)
1585         return status;
1586
1587     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1588
1589     status = _notmuch_database_filename_to_direntry (local, notmuch,
1590                                                      filename, &direntry);
1591     if (status)
1592         return status;
1593
1594     term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1595
1596     find_doc_ids_for_term (notmuch, term, &i, &end);
1597
1598     for ( ; i != end; i++) {
1599         Xapian::TermIterator j;
1600
1601         document = find_document_for_doc_id (notmuch, *i);
1602
1603         document.remove_term (term);
1604
1605         j = document.termlist_begin ();
1606         j.skip_to (prefix);
1607
1608         /* Was this the last file-direntry in the message? */
1609         if (j == document.termlist_end () ||
1610             strncmp ((*j).c_str (), prefix, strlen (prefix)))
1611         {
1612             db->delete_document (document.get_docid ());
1613             status = NOTMUCH_STATUS_SUCCESS;
1614         } else {
1615             db->replace_document (document.get_docid (), document);
1616             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1617         }
1618     }
1619
1620     talloc_free (local);
1621
1622     return status;
1623 }
1624
1625 notmuch_tags_t *
1626 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1627                        Xapian::TermIterator &end)
1628 {
1629     const char *prefix = _find_prefix ("tag");
1630     notmuch_tags_t *tags;
1631     std::string tag;
1632
1633     /* Currently this iteration is written with the assumption that
1634      * "tag" has a single-character prefix. */
1635     assert (strlen (prefix) == 1);
1636
1637     tags = _notmuch_tags_create (ctx);
1638     if (unlikely (tags == NULL))
1639         return NULL;
1640
1641     i.skip_to (prefix);
1642
1643     while (i != end) {
1644         tag = *i;
1645
1646         if (tag.empty () || tag[0] != *prefix)
1647             break;
1648
1649         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1650
1651         i++;
1652     }
1653
1654     _notmuch_tags_prepare_iterator (tags);
1655
1656     return tags;
1657 }
1658
1659 notmuch_tags_t *
1660 notmuch_database_get_all_tags (notmuch_database_t *db)
1661 {
1662     Xapian::TermIterator i, end;
1663     i = db->xapian_db->allterms_begin();
1664     end = db->xapian_db->allterms_end();
1665     return _notmuch_convert_tags(db, i, end);
1666 }