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