]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
Fix target dependencies for multiple jobs
[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 /* Find the thread ID to which the message with 'message_id' belongs.
1115  *
1116  * Returns NULL if no message with message ID 'message_id' is in the
1117  * database.
1118  *
1119  * Otherwise, returns a newly talloced string belonging to 'ctx'.
1120  */
1121 static const char *
1122 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1123                                   void *ctx,
1124                                   const char *message_id)
1125 {
1126     notmuch_message_t *message;
1127     const char *ret = NULL;
1128
1129     message = notmuch_database_find_message (notmuch, message_id);
1130     if (message == NULL)
1131         goto DONE;
1132
1133     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1134
1135   DONE:
1136     if (message)
1137         notmuch_message_destroy (message);
1138
1139     return ret;
1140 }
1141
1142 static notmuch_status_t
1143 _merge_threads (notmuch_database_t *notmuch,
1144                 const char *winner_thread_id,
1145                 const char *loser_thread_id)
1146 {
1147     Xapian::PostingIterator loser, loser_end;
1148     notmuch_message_t *message = NULL;
1149     notmuch_private_status_t private_status;
1150     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1151
1152     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1153
1154     for ( ; loser != loser_end; loser++) {
1155         message = _notmuch_message_create (notmuch, notmuch,
1156                                            *loser, &private_status);
1157         if (message == NULL) {
1158             ret = COERCE_STATUS (private_status,
1159                                  "Cannot find document for doc_id from query");
1160             goto DONE;
1161         }
1162
1163         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1164         _notmuch_message_add_term (message, "thread", winner_thread_id);
1165         _notmuch_message_sync (message);
1166
1167         notmuch_message_destroy (message);
1168         message = NULL;
1169     }
1170
1171   DONE:
1172     if (message)
1173         notmuch_message_destroy (message);
1174
1175     return ret;
1176 }
1177
1178 static void
1179 _my_talloc_free_for_g_hash (void *ptr)
1180 {
1181     talloc_free (ptr);
1182 }
1183
1184 static notmuch_status_t
1185 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1186                                            notmuch_message_t *message,
1187                                            notmuch_message_file_t *message_file,
1188                                            const char **thread_id)
1189 {
1190     GHashTable *parents = NULL;
1191     const char *refs, *in_reply_to, *in_reply_to_message_id;
1192     GList *l, *keys = NULL;
1193     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1194
1195     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1196                                      _my_talloc_free_for_g_hash, NULL);
1197
1198     refs = notmuch_message_file_get_header (message_file, "references");
1199     parse_references (message, notmuch_message_get_message_id (message),
1200                       parents, refs);
1201
1202     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1203     parse_references (message, notmuch_message_get_message_id (message),
1204                       parents, in_reply_to);
1205
1206     /* Carefully avoid adding any self-referential in-reply-to term. */
1207     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1208     if (in_reply_to_message_id &&
1209         strcmp (in_reply_to_message_id,
1210                 notmuch_message_get_message_id (message)))
1211     {
1212         _notmuch_message_add_term (message, "replyto",
1213                              _parse_message_id (message, in_reply_to, NULL));
1214     }
1215
1216     keys = g_hash_table_get_keys (parents);
1217     for (l = keys; l; l = l->next) {
1218         char *parent_message_id;
1219         const char *parent_thread_id;
1220
1221         parent_message_id = (char *) l->data;
1222         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1223                                                              message,
1224                                                              parent_message_id);
1225
1226         if (parent_thread_id == NULL) {
1227             _notmuch_message_add_term (message, "reference",
1228                                        parent_message_id);
1229         } else {
1230             if (*thread_id == NULL) {
1231                 *thread_id = talloc_strdup (message, parent_thread_id);
1232                 _notmuch_message_add_term (message, "thread", *thread_id);
1233             } else if (strcmp (*thread_id, parent_thread_id)) {
1234                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1235                 if (ret)
1236                     goto DONE;
1237             }
1238         }
1239     }
1240
1241   DONE:
1242     if (keys)
1243         g_list_free (keys);
1244     if (parents)
1245         g_hash_table_unref (parents);
1246
1247     return ret;
1248 }
1249
1250 static notmuch_status_t
1251 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1252                                             notmuch_message_t *message,
1253                                             const char **thread_id)
1254 {
1255     const char *message_id = notmuch_message_get_message_id (message);
1256     Xapian::PostingIterator child, children_end;
1257     notmuch_message_t *child_message = NULL;
1258     const char *child_thread_id;
1259     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1260     notmuch_private_status_t private_status;
1261
1262     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1263
1264     for ( ; child != children_end; child++) {
1265
1266         child_message = _notmuch_message_create (message, notmuch,
1267                                                  *child, &private_status);
1268         if (child_message == NULL) {
1269             ret = COERCE_STATUS (private_status,
1270                                  "Cannot find document for doc_id from query");
1271             goto DONE;
1272         }
1273
1274         child_thread_id = notmuch_message_get_thread_id (child_message);
1275         if (*thread_id == NULL) {
1276             *thread_id = talloc_strdup (message, child_thread_id);
1277             _notmuch_message_add_term (message, "thread", *thread_id);
1278         } else if (strcmp (*thread_id, child_thread_id)) {
1279             _notmuch_message_remove_term (child_message, "reference",
1280                                           message_id);
1281             _notmuch_message_sync (child_message);
1282             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1283             if (ret)
1284                 goto DONE;
1285         }
1286
1287         notmuch_message_destroy (child_message);
1288         child_message = NULL;
1289     }
1290
1291   DONE:
1292     if (child_message)
1293         notmuch_message_destroy (child_message);
1294
1295     return ret;
1296 }
1297
1298 static const char *
1299 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1300 {
1301     /* 16 bytes (+ terminator) for hexadecimal representation of
1302      * a 64-bit integer. */
1303     static char thread_id[17];
1304     Xapian::WritableDatabase *db;
1305
1306     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1307
1308     notmuch->last_thread_id++;
1309
1310     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1311
1312     db->set_metadata ("last_thread_id", thread_id);
1313
1314     return thread_id;
1315 }
1316
1317 /* Given a (mostly empty) 'message' and its corresponding
1318  * 'message_file' link it to existing threads in the database.
1319  *
1320  * We first look at 'message_file' and its link-relevant headers
1321  * (References and In-Reply-To) for message IDs. We also look in the
1322  * database for existing message that reference 'message'. In either
1323  * case, we will assign to the current message the first thread_id
1324  * found (through either parent or child). We will also merge any
1325  * existing, distinct threads where this message belongs to both,
1326  * (which is not uncommon when mesages are processed out of order).
1327  *
1328  * Finally, if not thread ID has been found through parent or child,
1329  * we call _notmuch_message_generate_thread_id to generate a new
1330  * generates a new thread ID if the message doesn't connect to any
1331  * existing threads.
1332  */
1333 static notmuch_status_t
1334 _notmuch_database_link_message (notmuch_database_t *notmuch,
1335                                 notmuch_message_t *message,
1336                                 notmuch_message_file_t *message_file)
1337 {
1338     notmuch_status_t status;
1339     const char *thread_id = NULL;
1340
1341     status = _notmuch_database_link_message_to_parents (notmuch, message,
1342                                                         message_file,
1343                                                         &thread_id);
1344     if (status)
1345         return status;
1346
1347     status = _notmuch_database_link_message_to_children (notmuch, message,
1348                                                          &thread_id);
1349     if (status)
1350         return status;
1351
1352     /* If not part of any existing thread, generate a new thread ID. */
1353     if (thread_id == NULL) {
1354         thread_id = _notmuch_database_generate_thread_id (notmuch);
1355
1356         _notmuch_message_add_term (message, "thread", thread_id);
1357     }
1358
1359     return NOTMUCH_STATUS_SUCCESS;
1360 }
1361
1362 notmuch_status_t
1363 notmuch_database_add_message (notmuch_database_t *notmuch,
1364                               const char *filename,
1365                               notmuch_message_t **message_ret)
1366 {
1367     notmuch_message_file_t *message_file;
1368     notmuch_message_t *message = NULL;
1369     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1370     notmuch_private_status_t private_status;
1371
1372     const char *date, *header;
1373     const char *from, *to, *subject;
1374     char *message_id = NULL;
1375
1376     if (message_ret)
1377         *message_ret = NULL;
1378
1379     ret = _notmuch_database_ensure_writable (notmuch);
1380     if (ret)
1381         return ret;
1382
1383     message_file = notmuch_message_file_open (filename);
1384     if (message_file == NULL)
1385         return NOTMUCH_STATUS_FILE_ERROR;
1386
1387     notmuch_message_file_restrict_headers (message_file,
1388                                            "date",
1389                                            "from",
1390                                            "in-reply-to",
1391                                            "message-id",
1392                                            "references",
1393                                            "subject",
1394                                            "to",
1395                                            (char *) NULL);
1396
1397     try {
1398         /* Before we do any real work, (especially before doing a
1399          * potential SHA-1 computation on the entire file's contents),
1400          * let's make sure that what we're looking at looks like an
1401          * actual email message.
1402          */
1403         from = notmuch_message_file_get_header (message_file, "from");
1404         subject = notmuch_message_file_get_header (message_file, "subject");
1405         to = notmuch_message_file_get_header (message_file, "to");
1406
1407         if ((from == NULL || *from == '\0') &&
1408             (subject == NULL || *subject == '\0') &&
1409             (to == NULL || *to == '\0'))
1410         {
1411             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1412             goto DONE;
1413         }
1414
1415         /* Now that we're sure it's mail, the first order of business
1416          * is to find a message ID (or else create one ourselves). */
1417
1418         header = notmuch_message_file_get_header (message_file, "message-id");
1419         if (header && *header != '\0') {
1420             message_id = _parse_message_id (message_file, header, NULL);
1421
1422             /* So the header value isn't RFC-compliant, but it's
1423              * better than no message-id at all. */
1424             if (message_id == NULL)
1425                 message_id = talloc_strdup (message_file, header);
1426
1427             /* Reject a Message ID that's too long. */
1428             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1429                 talloc_free (message_id);
1430                 message_id = NULL;
1431             }
1432         }
1433
1434         if (message_id == NULL ) {
1435             /* No message-id at all, let's generate one by taking a
1436              * hash over the file's contents. */
1437             char *sha1 = notmuch_sha1_of_file (filename);
1438
1439             /* If that failed too, something is really wrong. Give up. */
1440             if (sha1 == NULL) {
1441                 ret = NOTMUCH_STATUS_FILE_ERROR;
1442                 goto DONE;
1443             }
1444
1445             message_id = talloc_asprintf (message_file,
1446                                           "notmuch-sha1-%s", sha1);
1447             free (sha1);
1448         }
1449
1450         /* Now that we have a message ID, we get a message object,
1451          * (which may or may not reference an existing document in the
1452          * database). */
1453
1454         message = _notmuch_message_create_for_message_id (notmuch,
1455                                                           message_id,
1456                                                           &private_status);
1457
1458         talloc_free (message_id);
1459
1460         if (message == NULL) {
1461             ret = COERCE_STATUS (private_status,
1462                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1463             goto DONE;
1464         }
1465
1466         _notmuch_message_add_filename (message, filename);
1467
1468         /* Is this a newly created message object? */
1469         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1470             _notmuch_message_add_term (message, "type", "mail");
1471
1472             ret = _notmuch_database_link_message (notmuch, message,
1473                                                   message_file);
1474             if (ret)
1475                 goto DONE;
1476
1477             date = notmuch_message_file_get_header (message_file, "date");
1478             _notmuch_message_set_date (message, date);
1479
1480             _notmuch_message_index_file (message, filename);
1481         } else {
1482             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1483         }
1484
1485         _notmuch_message_sync (message);
1486     } catch (const Xapian::Error &error) {
1487         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1488                  error.get_description().c_str());
1489         notmuch->exception_reported = TRUE;
1490         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1491         goto DONE;
1492     }
1493
1494   DONE:
1495     if (message) {
1496         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1497             *message_ret = message;
1498         else
1499             notmuch_message_destroy (message);
1500     }
1501
1502     if (message_file)
1503         notmuch_message_file_close (message_file);
1504
1505     return ret;
1506 }
1507
1508 notmuch_status_t
1509 notmuch_database_remove_message (notmuch_database_t *notmuch,
1510                                  const char *filename)
1511 {
1512     Xapian::WritableDatabase *db;
1513     void *local = talloc_new (notmuch);
1514     const char *prefix = _find_prefix ("file-direntry");
1515     char *direntry, *term;
1516     Xapian::PostingIterator i, end;
1517     Xapian::Document document;
1518     notmuch_status_t status;
1519
1520     status = _notmuch_database_ensure_writable (notmuch);
1521     if (status)
1522         return status;
1523
1524     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1525
1526     status = _notmuch_database_filename_to_direntry (local, notmuch,
1527                                                      filename, &direntry);
1528     if (status)
1529         return status;
1530
1531     term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1532
1533     find_doc_ids_for_term (notmuch, term, &i, &end);
1534
1535     for ( ; i != end; i++) {
1536         Xapian::TermIterator j;
1537
1538         document = find_document_for_doc_id (notmuch, *i);
1539
1540         document.remove_term (term);
1541
1542         j = document.termlist_begin ();
1543         j.skip_to (prefix);
1544
1545         /* Was this the last file-direntry in the message? */
1546         if (j == document.termlist_end () ||
1547             strncmp ((*j).c_str (), prefix, strlen (prefix)))
1548         {
1549             db->delete_document (document.get_docid ());
1550             status = NOTMUCH_STATUS_SUCCESS;
1551         } else {
1552             db->replace_document (document.get_docid (), document);
1553             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1554         }
1555     }
1556
1557     talloc_free (local);
1558
1559     return status;
1560 }
1561
1562 notmuch_tags_t *
1563 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1564                        Xapian::TermIterator &end)
1565 {
1566     const char *prefix = _find_prefix ("tag");
1567     notmuch_tags_t *tags;
1568     std::string tag;
1569
1570     /* Currently this iteration is written with the assumption that
1571      * "tag" has a single-character prefix. */
1572     assert (strlen (prefix) == 1);
1573
1574     tags = _notmuch_tags_create (ctx);
1575     if (unlikely (tags == NULL))
1576         return NULL;
1577
1578     i.skip_to (prefix);
1579
1580     while (i != end) {
1581         tag = *i;
1582
1583         if (tag.empty () || tag[0] != *prefix)
1584             break;
1585
1586         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1587
1588         i++;
1589     }
1590
1591     _notmuch_tags_prepare_iterator (tags);
1592
1593     return tags;
1594 }
1595
1596 notmuch_tags_t *
1597 notmuch_database_get_all_tags (notmuch_database_t *db)
1598 {
1599     Xapian::TermIterator i, end;
1600     i = db->xapian_db->allterms_begin();
1601     end = db->xapian_db->allterms_end();
1602     return _notmuch_convert_tags(db, i, end);
1603 }