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