]> git.notmuchmail.org Git - notmuch/blob - database.cc
Unbreak the "notmuch setup" command.
[notmuch] / 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 timestamps.
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:
46  *
47  *    Single terms of given prefix:
48  *
49  *      type:   mail
50  *
51  *      id:     Unique ID of mail, (from Message-ID header or generated
52  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
53  *
54  *      thread: The ID of the thread to which the mail belongs
55  *
56  *    Multiple terms of given prefix:
57  *
58  *      ref:    All unresolved message IDs from In-Reply-To and
59  *              References headers in the message. (Once a referenced
60  *              message is added to the database and the thread IDs
61  *              are linked the corresponding "ref" term is dropped
62  *              from the message document.)
63  *
64  *      tag:    Any tags associated with this message by the user.
65  *
66  *    A mail document also has two values:
67  *
68  *      TIMESTAMP:      The time_t value corresponding to the message's
69  *                      Date header.
70  *
71  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
72  *
73  * Timestamp document
74  * ------------------
75  * A timestamp document is used by a client of the notmuch library to
76  * maintain data necessary to allow for efficient polling of mail
77  * directories. The notmuch library does no interpretation of
78  * timestamps, but merely allows the user to store and retrieve
79  * timestamps as name/value pairs.
80  *
81  * The timestamp document is indexed with a single prefixed term:
82  *
83  *      timestamp:      The user's key value (likely a directory name)
84  *
85  * and has a single value:
86  *
87  *      TIMETAMPS:      The time_t value from the user.
88  */
89
90 /* With these prefix values we follow the conventions published here:
91  *
92  * http://xapian.org/docs/omega/termprefixes.html
93  *
94  * as much as makes sense. Note that I took some liberty in matching
95  * the reserved prefix values to notmuch concepts, (for example, 'G'
96  * is documented as "newsGroup (or similar entity - e.g. a web forum
97  * name)", for which I think the thread is the closest analogue in
98  * notmuch. This in spite of the fact that we will eventually be
99  * storing mailing-list messages where 'G' for "mailing list name"
100  * might be even a closer analogue. I'm treating the single-character
101  * prefixes preferentially for core notmuch concepts (which will be
102  * nearly universal to all mail messages).
103  */
104
105 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
106     { "type", "T" },
107     { "thread", "G" },
108     { "ref", "XREFERENCE" },
109     { "timestamp", "XTIMESTAMP" },
110 };
111
112 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
113     { "tag", "K" },
114     { "id", "Q" }
115 };
116
117 int
118 _internal_error (const char *format, ...)
119 {
120     va_list va_args;
121
122     va_start (va_args, format);
123
124     vfprintf (stderr, format, va_args);
125
126     exit (1);
127
128     return 1;
129 }
130
131 const char *
132 _find_prefix (const char *name)
133 {
134     unsigned int i;
135
136     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
137         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
138             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
139
140     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
141         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
142             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
143
144     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
145
146     return "";
147 }
148
149 const char *
150 notmuch_status_to_string (notmuch_status_t status)
151 {
152     switch (status) {
153     case NOTMUCH_STATUS_SUCCESS:
154         return "No error occurred";
155     case NOTMUCH_STATUS_OUT_OF_MEMORY:
156         return "Out of memory";
157     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
158         return "A Xapian exception occurred";
159     case NOTMUCH_STATUS_FILE_ERROR:
160         return "Something went wrong trying to read or write a file";
161     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
162         return "File is not an email";
163     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
164         return "Message ID is identical to a message in database";
165     case NOTMUCH_STATUS_NULL_POINTER:
166         return "Erroneous NULL pointer";
167     case NOTMUCH_STATUS_TAG_TOO_LONG:
168         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
169     default:
170     case NOTMUCH_STATUS_LAST_STATUS:
171         return "Unknown error status value";
172     }
173 }
174
175 static void
176 find_doc_ids (notmuch_database_t *notmuch,
177               const char *prefix_name,
178               const char *value,
179               Xapian::PostingIterator *begin,
180               Xapian::PostingIterator *end)
181 {
182     Xapian::PostingIterator i;
183     char *term;
184
185     term = talloc_asprintf (notmuch, "%s%s",
186                             _find_prefix (prefix_name), value);
187
188     *begin = notmuch->xapian_db->postlist_begin (term);
189
190     *end = notmuch->xapian_db->postlist_end (term);
191
192     talloc_free (term);
193 }
194
195 static notmuch_private_status_t
196 find_unique_doc_id (notmuch_database_t *notmuch,
197                     const char *prefix_name,
198                     const char *value,
199                     unsigned int *doc_id)
200 {
201     Xapian::PostingIterator i, end;
202
203     find_doc_ids (notmuch, prefix_name, value, &i, &end);
204
205     if (i == end) {
206         *doc_id = 0;
207         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
208     } else {
209         *doc_id = *i;
210         return NOTMUCH_PRIVATE_STATUS_SUCCESS;
211     }
212 }
213
214 static Xapian::Document
215 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
216 {
217     return notmuch->xapian_db->get_document (doc_id);
218 }
219
220 static notmuch_private_status_t
221 find_unique_document (notmuch_database_t *notmuch,
222                       const char *prefix_name,
223                       const char *value,
224                       Xapian::Document *document,
225                       unsigned int *doc_id)
226 {
227     notmuch_private_status_t status;
228
229     status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
230
231     if (status) {
232         *document = Xapian::Document ();
233         return status;
234     }
235
236     *document = find_document_for_doc_id (notmuch, *doc_id);
237     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
238 }
239
240 notmuch_message_t *
241 notmuch_database_find_message (notmuch_database_t *notmuch,
242                                const char *message_id)
243 {
244     notmuch_private_status_t status;
245     unsigned int doc_id;
246
247     status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
248
249     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
250         return NULL;
251
252     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
253 }
254
255 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
256  * a (potentially nested) parenthesized sequence with '\' used to
257  * escape any character (including parentheses).
258  *
259  * If the sequence to be skipped continues to the end of the string,
260  * then 'str' will be left pointing at the final terminating '\0'
261  * character.
262  */
263 static void
264 skip_space_and_comments (const char **str)
265 {
266     const char *s;
267
268     s = *str;
269     while (*s && (isspace (*s) || *s == '(')) {
270         while (*s && isspace (*s))
271             s++;
272         if (*s == '(') {
273             int nesting = 1;
274             s++;
275             while (*s && nesting) {
276                 if (*s == '(')
277                     nesting++;
278                 else if (*s == ')')
279                     nesting--;
280                 else if (*s == '\\')
281                     if (*(s+1))
282                         s++;
283                 s++;
284             }
285         }
286     }
287
288     *str = s;
289 }
290
291 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
292  * comments, and the '<' and '>' delimeters.
293  *
294  * If not NULL, then *next will be made to point to the first character
295  * not parsed, (possibly pointing to the final '\0' terminator.
296  *
297  * Returns a newly talloc'ed string belonging to 'ctx'.
298  *
299  * Returns NULL if there is any error parsing the message-id. */
300 static char *
301 parse_message_id (void *ctx, const char *message_id, const char **next)
302 {
303     const char *s, *end;
304     char *result;
305
306     if (message_id == NULL)
307         return NULL;
308
309     s = message_id;
310
311     skip_space_and_comments (&s);
312
313     /* Skip any unstructured text as well. */
314     while (*s && *s != '<')
315         s++;
316
317     if (*s == '<') {
318         s++;
319     } else {
320         if (next)
321             *next = s;
322         return NULL;
323     }
324
325     skip_space_and_comments (&s);
326
327     end = s;
328     while (*end && *end != '>')
329         end++;
330     if (next) {
331         if (*end)
332             *next = end + 1;
333         else
334             *next = end;
335     }
336
337     if (end > s && *end == '>')
338         end--;
339     if (end <= s)
340         return NULL;
341
342     result = talloc_strndup (ctx, s, end - s + 1);
343
344     /* Finally, collapse any whitespace that is within the message-id
345      * itself. */
346     {
347         char *r;
348         int len;
349
350         for (r = result, len = strlen (r); *r; r++, len--)
351             if (*r == ' ' || *r == '\t')
352                 memmove (r, r+1, len);
353     }
354
355     return result;
356 }
357
358 /* Parse a References header value, putting a (talloc'ed under 'ctx')
359  * copy of each referenced message-id into 'hash'. */
360 static void
361 parse_references (void *ctx,
362                   GHashTable *hash,
363                   const char *refs)
364 {
365     char *ref;
366
367     if (refs == NULL)
368         return;
369
370     while (*refs) {
371         ref = parse_message_id (ctx, refs, &refs);
372
373         if (ref)
374             g_hash_table_insert (hash, ref, NULL);
375     }
376 }
377
378 char *
379 notmuch_database_default_path (void)
380 {
381     char *path;
382
383     if (getenv ("NOTMUCH_BASE"))
384         return strdup (getenv ("NOTMUCH_BASE"));
385
386     if (asprintf (&path, "%s/mail", getenv ("HOME")) == -1) {
387         fprintf (stderr, "Out of memory.\n");
388         return xstrdup("");
389     }
390
391     return path;
392 }
393
394 notmuch_database_t *
395 notmuch_database_create (const char *path)
396 {
397     notmuch_database_t *notmuch = NULL;
398     char *notmuch_path = NULL;
399     struct stat st;
400     int err;
401     char *local_path = NULL;
402
403     if (path == NULL)
404         path = local_path = notmuch_database_default_path ();
405
406     err = stat (path, &st);
407     if (err) {
408         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
409                  path, strerror (errno));
410         goto DONE;
411     }
412
413     if (! S_ISDIR (st.st_mode)) {
414         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
415                  path);
416         goto DONE;
417     }
418
419     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
420
421     err = mkdir (notmuch_path, 0755);
422
423     if (err) {
424         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
425                  notmuch_path, strerror (errno));
426         goto DONE;
427     }
428
429     notmuch = notmuch_database_open (path);
430
431   DONE:
432     if (notmuch_path)
433         talloc_free (notmuch_path);
434     if (local_path)
435         free (local_path);
436
437     return notmuch;
438 }
439
440 notmuch_database_t *
441 notmuch_database_open (const char *path)
442 {
443     notmuch_database_t *notmuch = NULL;
444     char *notmuch_path = NULL, *xapian_path = NULL;
445     struct stat st;
446     int err;
447     char *local_path = NULL;
448     unsigned int i;
449
450     if (path == NULL)
451         path = local_path = notmuch_database_default_path ();
452
453     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
454         notmuch_path = NULL;
455         fprintf (stderr, "Out of memory\n");
456         goto DONE;
457     }
458
459     err = stat (notmuch_path, &st);
460     if (err) {
461         fprintf (stderr, "Error opening database at %s: %s\n",
462                  notmuch_path, strerror (errno));
463         goto DONE;
464     }
465
466     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
467         xapian_path = NULL;
468         fprintf (stderr, "Out of memory\n");
469         goto DONE;
470     }
471
472     notmuch = talloc (NULL, notmuch_database_t);
473     notmuch->path = talloc_strdup (notmuch, path);
474
475     try {
476         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
477                                                            Xapian::DB_CREATE_OR_OPEN);
478         notmuch->query_parser = new Xapian::QueryParser;
479         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
480         notmuch->query_parser->set_database (*notmuch->xapian_db);
481
482         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
483             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
484             notmuch->query_parser->add_boolean_prefix (prefix->name,
485                                                        prefix->prefix);
486         }
487     } catch (const Xapian::Error &error) {
488         fprintf (stderr, "A Xapian exception occurred: %s\n",
489                  error.get_msg().c_str());
490     }
491     
492   DONE:
493     if (local_path)
494         free (local_path);
495     if (notmuch_path)
496         free (notmuch_path);
497     if (xapian_path)
498         free (xapian_path);
499
500     return notmuch;
501 }
502
503 void
504 notmuch_database_close (notmuch_database_t *notmuch)
505 {
506     delete notmuch->query_parser;
507     delete notmuch->xapian_db;
508     talloc_free (notmuch);
509 }
510
511 const char *
512 notmuch_database_get_path (notmuch_database_t *notmuch)
513 {
514     return notmuch->path;
515 }
516
517 static notmuch_private_status_t
518 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
519                          Xapian::Document *doc, unsigned int *doc_id)
520 {
521     return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
522 }
523
524 /* We allow the user to use arbitrarily long keys for timestamps,
525  * (they're for filesystem paths after all, which have no limit we
526  * know about). But we have a term-length limit. So if we exceed that,
527  * we'll use the SHA-1 of the user's key as the actual key for
528  * constructing a database term.
529  *
530  * Caution: This function returns a newly allocated string which the
531  * caller should free() when finished.
532  */
533 static char *
534 timestamp_db_key (const char *key)
535 {
536     int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
537
538     if (term_len > NOTMUCH_TERM_MAX)
539         return notmuch_sha1_of_string (key);
540     else
541         return strdup (key);
542 }
543
544 notmuch_status_t
545 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
546                                 const char *key, time_t timestamp)
547 {
548     Xapian::Document doc;
549     unsigned int doc_id;
550     notmuch_private_status_t status;
551     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
552     char *db_key = NULL;
553
554     db_key = timestamp_db_key (key);
555
556     try {
557         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
558
559         doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
560                        Xapian::sortable_serialise (timestamp));
561
562         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
563             char *term = talloc_asprintf (NULL, "%s%s",
564                                           _find_prefix ("timestamp"), db_key);
565             doc.add_term (term);
566             talloc_free (term);
567
568             notmuch->xapian_db->add_document (doc);
569         } else {
570             notmuch->xapian_db->replace_document (doc_id, doc);
571         }
572
573     } catch (Xapian::Error &error) {
574         fprintf (stderr, "A Xapian exception occurred: %s.\n",
575                  error.get_msg().c_str());
576         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
577     }
578
579     if (db_key)
580         free (db_key);
581
582     return ret;
583 }
584
585 time_t
586 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
587 {
588     Xapian::Document doc;
589     unsigned int doc_id;
590     notmuch_private_status_t status;
591     char *db_key = NULL;
592     time_t ret = 0;
593
594     db_key = timestamp_db_key (key);
595
596     try {
597         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
598
599         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
600             goto DONE;
601
602         ret =  Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
603     } catch (Xapian::Error &error) {
604         goto DONE;
605     }
606
607   DONE:
608     if (db_key)
609         free (db_key);
610
611     return ret;
612 }
613
614 /* Find the thread ID to which the message with 'message_id' belongs.
615  *
616  * Returns NULL if no message with message ID 'message_id' is in the
617  * database.
618  *
619  * Otherwise, returns a newly talloced string belonging to 'ctx'.
620  */
621 static const char *
622 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
623                                   void *ctx,
624                                   const char *message_id)
625 {
626     notmuch_message_t *message;
627     const char *ret = NULL;
628
629     message = notmuch_database_find_message (notmuch, message_id);
630     if (message == NULL)
631         goto DONE;
632
633     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
634
635   DONE:
636     if (message)
637         notmuch_message_destroy (message);
638
639     return ret;
640 }
641
642 static notmuch_status_t
643 _merge_threads (notmuch_database_t *notmuch,
644                 const char *winner_thread_id,
645                 const char *loser_thread_id)
646 {
647     Xapian::PostingIterator loser, loser_end;
648     notmuch_message_t *message = NULL;
649     notmuch_private_status_t private_status;
650     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
651
652     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
653
654     for ( ; loser != loser_end; loser++) {
655         message = _notmuch_message_create (notmuch, notmuch,
656                                            *loser, &private_status);
657         if (message == NULL) {
658             ret = COERCE_STATUS (private_status,
659                                  "Cannot find document for doc_id from query");
660             goto DONE;
661         }
662
663         _notmuch_message_remove_term (message, "thread", loser_thread_id);
664         _notmuch_message_add_term (message, "thread", winner_thread_id);
665         _notmuch_message_sync (message);
666
667         notmuch_message_destroy (message);
668         message = NULL;
669     }
670
671   DONE:
672     if (message)
673         notmuch_message_destroy (message);
674
675     return ret;
676 }
677
678 static void
679 _my_talloc_free_for_g_hash (void *ptr)
680 {
681     talloc_free (ptr);
682 }
683
684 static notmuch_status_t
685 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
686                                            notmuch_message_t *message,
687                                            notmuch_message_file_t *message_file,
688                                            const char **thread_id)
689 {
690     GHashTable *parents = NULL;
691     const char *refs, *in_reply_to;
692     GList *l, *keys = NULL;
693     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
694
695     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
696                                      _my_talloc_free_for_g_hash, NULL);
697
698     refs = notmuch_message_file_get_header (message_file, "references");
699     parse_references (message, parents, refs);
700
701     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
702     parse_references (message, parents, in_reply_to);
703
704     keys = g_hash_table_get_keys (parents);
705     for (l = keys; l; l = l->next) {
706         char *parent_message_id;
707         const char *parent_thread_id;
708
709         parent_message_id = (char *) l->data;
710         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
711                                                              message,
712                                                              parent_message_id);
713
714         if (parent_thread_id == NULL) {
715             _notmuch_message_add_term (message, "ref", parent_message_id);
716         } else {
717             if (*thread_id == NULL) {
718                 *thread_id = talloc_strdup (message, parent_thread_id);
719                 _notmuch_message_add_term (message, "thread", *thread_id);
720             } else if (strcmp (*thread_id, parent_thread_id)) {
721                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
722                 if (ret)
723                     goto DONE;
724             }
725         }
726     }
727
728   DONE:
729     if (keys)
730         g_list_free (keys);
731     if (parents)
732         g_hash_table_unref (parents);
733
734     return ret;
735 }
736
737 static notmuch_status_t
738 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
739                                             notmuch_message_t *message,
740                                             const char **thread_id)
741 {
742     const char *message_id = notmuch_message_get_message_id (message);
743     Xapian::PostingIterator child, children_end;
744     notmuch_message_t *child_message = NULL;
745     const char *child_thread_id;
746     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
747     notmuch_private_status_t private_status;
748
749     find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
750
751     for ( ; child != children_end; child++) {
752
753         child_message = _notmuch_message_create (message, notmuch,
754                                                  *child, &private_status);
755         if (child_message == NULL) {
756             ret = COERCE_STATUS (private_status,
757                                  "Cannot find document for doc_id from query");
758             goto DONE;
759         }
760
761         child_thread_id = notmuch_message_get_thread_id (child_message);
762         if (*thread_id == NULL) {
763             *thread_id = talloc_strdup (message, child_thread_id);
764             _notmuch_message_add_term (message, "thread", *thread_id);
765         } else if (strcmp (*thread_id, child_thread_id)) {
766             _notmuch_message_remove_term (child_message, "ref",
767                                           message_id);
768             _notmuch_message_sync (child_message);
769             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
770             if (ret)
771                 goto DONE;
772         }
773
774         notmuch_message_destroy (child_message);
775         child_message = NULL;
776     }
777
778   DONE:
779     if (child_message)
780         notmuch_message_destroy (child_message);
781
782     return ret;
783 }
784
785 /* Given a (mostly empty) 'message' and its corresponding
786  * 'message_file' link it to existing threads in the database.
787  *
788  * We first looke at 'message_file' and its link-relevant headers
789  * (References and In-Reply-To) for message IDs. We also look in the
790  * database for existing message that reference 'message'.p
791  *
792  * The end result is to call _notmuch_message_add_thread_id with one
793  * or more thread IDs to which this message belongs, (including
794  * generating a new thread ID if necessary if the message doesn't
795  * connect to any existing threads).
796  */
797 static notmuch_status_t
798 _notmuch_database_link_message (notmuch_database_t *notmuch,
799                                 notmuch_message_t *message,
800                                 notmuch_message_file_t *message_file)
801 {
802     notmuch_status_t status;
803     const char *thread_id = NULL;
804
805     status = _notmuch_database_link_message_to_parents (notmuch, message,
806                                                         message_file,
807                                                         &thread_id);
808     if (status)
809         return status;
810
811     status = _notmuch_database_link_message_to_children (notmuch, message,
812                                                          &thread_id);
813     if (status)
814         return status;
815
816     if (thread_id == NULL)
817         _notmuch_message_ensure_thread_id (message);
818
819     return NOTMUCH_STATUS_SUCCESS;
820 }
821
822 notmuch_status_t
823 notmuch_database_add_message (notmuch_database_t *notmuch,
824                               const char *filename,
825                               notmuch_message_t **message_ret)
826 {
827     notmuch_message_file_t *message_file;
828     notmuch_message_t *message;
829     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
830
831     const char *date, *header;
832     const char *from, *to, *subject, *old_filename;
833     char *message_id;
834
835     message_file = notmuch_message_file_open (filename);
836     if (message_file == NULL) {
837         ret = NOTMUCH_STATUS_FILE_ERROR;
838         goto DONE;
839     }
840
841     notmuch_message_file_restrict_headers (message_file,
842                                            "date",
843                                            "from",
844                                            "in-reply-to",
845                                            "message-id",
846                                            "references",
847                                            "subject",
848                                            "to",
849                                            (char *) NULL);
850
851     try {
852         /* The first order of business is to find/create a message ID. */
853
854         header = notmuch_message_file_get_header (message_file, "message-id");
855         if (header) {
856             message_id = parse_message_id (message_file, header, NULL);
857             /* So the header value isn't RFC-compliant, but it's
858              * better than no message-id at all. */
859             if (message_id == NULL)
860                 message_id = talloc_strdup (message_file, header);
861         } else {
862             /* No message-id at all, let's generate one by taking a
863              * hash over the file's contents. */
864             char *sha1 = notmuch_sha1_of_file (filename);
865
866             /* If that failed too, something is really wrong. Give up. */
867             if (sha1 == NULL) {
868                 ret = NOTMUCH_STATUS_FILE_ERROR;
869                 goto DONE;
870             }
871
872             message_id = talloc_asprintf (message_file,
873                                           "notmuch-sha1-%s", sha1);
874             free (sha1);
875         }
876
877         /* Now that we have a message ID, we get a message object,
878          * (which may or may not reference an existing document in the
879          * database). */
880
881         /* Use NULL for owner since we want to free this locally. */
882         message = _notmuch_message_create_for_message_id (NULL,
883                                                           notmuch,
884                                                           message_id,
885                                                           &ret);
886
887         talloc_free (message_id);
888
889         if (message == NULL)
890             goto DONE;
891
892         /* Has a message previously been added with the same ID? */
893         old_filename = notmuch_message_get_filename (message);
894         if (old_filename && strlen (old_filename)) {
895             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
896             goto DONE;
897         } else {
898             _notmuch_message_set_filename (message, filename);
899             _notmuch_message_add_term (message, "type", "mail");
900         }
901
902         ret = _notmuch_database_link_message (notmuch, message, message_file);
903         if (ret)
904             goto DONE;
905
906         date = notmuch_message_file_get_header (message_file, "date");
907         _notmuch_message_set_date (message, date);
908
909         from = notmuch_message_file_get_header (message_file, "from");
910         subject = notmuch_message_file_get_header (message_file, "subject");
911         to = notmuch_message_file_get_header (message_file, "to");
912
913         if (from == NULL &&
914             subject == NULL &&
915             to == NULL)
916         {
917             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
918             goto DONE;
919         } else {
920             _notmuch_message_sync (message);
921         }
922     } catch (const Xapian::Error &error) {
923         fprintf (stderr, "A Xapian exception occurred: %s.\n",
924                  error.get_msg().c_str());
925         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
926         goto DONE;
927     }
928
929   DONE:
930     if (message) {
931         if (message_ret)
932             *message_ret = message;
933         else
934             notmuch_message_destroy (message);
935     }
936
937     if (message_file)
938         notmuch_message_file_close (message_file);
939
940     return ret;
941 }