]> git.notmuchmail.org Git - notmuch/blob - lib/open.cc
lib: add field processor for lastmod: prefix
[notmuch] / lib / open.cc
1 #include <unistd.h>
2 #include <libgen.h>
3
4 #include "database-private.h"
5 #include "parse-time-vrp.h"
6 #include "lastmod-fp.h"
7 #include "path-util.h"
8
9 #if HAVE_XAPIAN_DB_RETRY_LOCK
10 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
11 #else
12 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
13 #endif
14
15 notmuch_status_t
16 notmuch_database_open (const char *path,
17                        notmuch_database_mode_t mode,
18                        notmuch_database_t **database)
19 {
20     char *status_string = NULL;
21     notmuch_status_t status;
22
23     status = notmuch_database_open_with_config (path, mode, "", NULL,
24                                                 database, &status_string);
25     if (status_string) {
26         fputs (status_string, stderr);
27         free (status_string);
28     }
29
30     return status;
31 }
32
33 notmuch_status_t
34 notmuch_database_open_verbose (const char *path,
35                                notmuch_database_mode_t mode,
36                                notmuch_database_t **database,
37                                char **status_string)
38 {
39     return notmuch_database_open_with_config (path, mode, "", NULL,
40                                               database, status_string);
41 }
42
43 static const char *
44 _xdg_dir (void *ctx,
45           const char *xdg_root_variable,
46           const char *xdg_prefix,
47           const char *profile_name)
48 {
49     const char *xdg_root = getenv (xdg_root_variable);
50
51     if (! xdg_root) {
52         const char *home = getenv ("HOME");
53
54         if (! home) return NULL;
55
56         xdg_root = talloc_asprintf (ctx,
57                                     "%s/%s",
58                                     home,
59                                     xdg_prefix);
60     }
61
62     if (! profile_name)
63         profile_name = getenv ("NOTMUCH_PROFILE");
64
65     if (! profile_name)
66         profile_name = "default";
67
68     return talloc_asprintf (ctx,
69                             "%s/notmuch/%s",
70                             xdg_root,
71                             profile_name);
72 }
73
74 static notmuch_status_t
75 _choose_dir (notmuch_database_t *notmuch,
76              const char *profile,
77              notmuch_config_key_t key,
78              const char *xdg_var,
79              const char *xdg_subdir,
80              const char *subdir,
81              char **message = NULL)
82 {
83     const char *parent;
84     const char *dir;
85     struct stat st;
86     int err;
87
88     dir = notmuch_config_get (notmuch, key);
89
90     if (dir)
91         return NOTMUCH_STATUS_SUCCESS;
92
93     parent = _xdg_dir (notmuch, xdg_var, xdg_subdir, profile);
94     if (! parent)
95         return NOTMUCH_STATUS_PATH_ERROR;
96
97     dir = talloc_asprintf (notmuch, "%s/%s", parent, subdir);
98
99     err = stat (dir, &st);
100     if (err) {
101         if (errno == ENOENT) {
102             char *notmuch_path = dirname (talloc_strdup (notmuch, notmuch->xapian_path));
103             dir = talloc_asprintf (notmuch, "%s/%s", notmuch_path, subdir);
104         } else {
105             IGNORE_RESULT (asprintf (message, "Error: Cannot stat %s: %s.\n",
106                                      dir, strerror (errno)));
107             return NOTMUCH_STATUS_FILE_ERROR;
108         }
109     }
110
111     _notmuch_config_cache (notmuch, key, dir);
112
113     return NOTMUCH_STATUS_SUCCESS;
114 }
115
116 static notmuch_status_t
117 _load_key_file (notmuch_database_t *notmuch,
118                 const char *path,
119                 const char *profile,
120                 GKeyFile **key_file)
121 {
122     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
123
124     if (path && EMPTY_STRING (path))
125         goto DONE;
126
127     if (! path)
128         path = getenv ("NOTMUCH_CONFIG");
129
130     if (path)
131         path = talloc_strdup (notmuch, path);
132     else {
133         const char *dir = _xdg_dir (notmuch, "XDG_CONFIG_HOME", ".config", profile);
134
135         if (dir) {
136             path = talloc_asprintf (notmuch, "%s/config", dir);
137             if (access (path, R_OK) != 0)
138                 path = NULL;
139         }
140     }
141
142     if (! path) {
143         const char *home = getenv ("HOME");
144
145         path = talloc_asprintf (notmuch, "%s/.notmuch-config", home);
146
147         if (! profile)
148             profile = getenv ("NOTMUCH_PROFILE");
149
150         if (profile)
151             path = talloc_asprintf (notmuch, "%s.%s", path, profile);
152     }
153
154     *key_file = g_key_file_new ();
155     if (! g_key_file_load_from_file (*key_file, path, G_KEY_FILE_NONE, NULL)) {
156         status = NOTMUCH_STATUS_NO_CONFIG;
157     }
158
159   DONE:
160     if (path)
161         notmuch->config_path = path;
162
163     return status;
164 }
165
166 static notmuch_status_t
167 _db_dir_exists (const char *database_path, char **message)
168 {
169     struct stat st;
170     int err;
171
172     err = stat (database_path, &st);
173     if (err) {
174         IGNORE_RESULT (asprintf (message, "Error: Cannot open database at %s: %s.\n",
175                                  database_path, strerror (errno)));
176         return NOTMUCH_STATUS_FILE_ERROR;
177     }
178
179     if (! S_ISDIR (st.st_mode)) {
180         IGNORE_RESULT (asprintf (message, "Error: Cannot open database at %s: "
181                                  "Not a directory.\n",
182                                  database_path));
183         return NOTMUCH_STATUS_FILE_ERROR;
184     }
185
186     return NOTMUCH_STATUS_SUCCESS;
187 }
188
189 static notmuch_status_t
190 _choose_database_path (notmuch_database_t *notmuch,
191                        const char *profile,
192                        GKeyFile *key_file,
193                        const char **database_path,
194                        char **message)
195 {
196     notmuch_status_t status;
197
198     if (! *database_path) {
199         *database_path = getenv ("NOTMUCH_DATABASE");
200     }
201
202     if (! *database_path && key_file) {
203         char *path = g_key_file_get_string (key_file, "database", "path", NULL);
204         if (path) {
205             if (path[0] == '/')
206                 *database_path = talloc_strdup (notmuch, path);
207             else
208                 *database_path = talloc_asprintf (notmuch, "%s/%s", getenv ("HOME"), path);
209             g_free (path);
210         }
211     }
212     if (! *database_path) {
213         *database_path = _xdg_dir (notmuch, "XDG_DATA_HOME", ".local/share", profile);
214         status = _db_dir_exists (*database_path, message);
215         if (status) {
216             *database_path = NULL;
217         } else {
218             notmuch->params |= NOTMUCH_PARAM_SPLIT;
219         }
220     }
221
222     if (! *database_path) {
223         *database_path = getenv ("MAILDIR");
224     }
225
226     if (! *database_path) {
227         *database_path = talloc_asprintf (notmuch, "%s/mail", getenv ("HOME"));
228         status = _db_dir_exists (*database_path, message);
229         if (status) {
230             *database_path = NULL;
231         }
232     }
233
234     if (*database_path == NULL) {
235         *message = strdup ("Error: could not locate database.\n");
236         return NOTMUCH_STATUS_NO_DATABASE;
237     }
238
239     if (*database_path[0] != '/') {
240         *message = strdup ("Error: Database path must be absolute.\n");
241         return NOTMUCH_STATUS_PATH_ERROR;
242     }
243
244     status = _db_dir_exists (*database_path, message);
245     if (status) {
246         IGNORE_RESULT (asprintf (message,
247                                  "Error: database path '%s' does not exist or is not a directory.\n",
248                                  *database_path));
249         return NOTMUCH_STATUS_NO_DATABASE;
250     }
251
252     return NOTMUCH_STATUS_SUCCESS;
253 }
254
255 static notmuch_status_t
256 _mkdir (const char *path, char **message)
257 {
258     if (g_mkdir_with_parents (path, 0755)) {
259         IGNORE_RESULT (asprintf (message, "Error: Cannot create directory %s: %s.\n",
260                                  path, strerror (errno)));
261         return NOTMUCH_STATUS_FILE_ERROR;
262     }
263     return NOTMUCH_STATUS_SUCCESS;
264 }
265
266 static notmuch_status_t
267 _create_database_path (notmuch_database_t *notmuch,
268                        const char *profile,
269                        GKeyFile *key_file,
270                        const char **database_path,
271                        char **message)
272 {
273     notmuch_status_t status;
274
275     if (! *database_path) {
276         *database_path = getenv ("NOTMUCH_DATABASE");
277     }
278
279     if (! *database_path && key_file) {
280         char *path = g_key_file_get_string (key_file, "database", "path", NULL);
281         if (path) {
282             if (path[0] == '/')
283                 *database_path = talloc_strdup (notmuch, path);
284             else
285                 *database_path = talloc_asprintf (notmuch, "%s/%s", getenv ("HOME"), path);
286             g_free (path);
287         }
288     }
289
290     if (! *database_path) {
291         *database_path = _xdg_dir (notmuch, "XDG_DATA_HOME", ".local/share", profile);
292         notmuch->params |= NOTMUCH_PARAM_SPLIT;
293     }
294
295     if (*database_path[0] != '/') {
296         *message = strdup ("Error: Database path must be absolute.\n");
297         return NOTMUCH_STATUS_PATH_ERROR;
298     }
299
300     if ((status = _mkdir (*database_path, message)))
301         return status;
302
303     return NOTMUCH_STATUS_SUCCESS;
304 }
305
306 static notmuch_database_t *
307 _alloc_notmuch (const char *database_path, const char *config_path, const char *profile)
308 {
309     notmuch_database_t *notmuch;
310
311     notmuch = talloc_zero (NULL, notmuch_database_t);
312     if (! notmuch)
313         return NULL;
314
315     notmuch->exception_reported = false;
316     notmuch->status_string = NULL;
317     notmuch->writable_xapian_db = NULL;
318     notmuch->config_path = NULL;
319     notmuch->atomic_nesting = 0;
320     notmuch->transaction_count = 0;
321     notmuch->transaction_threshold = 0;
322     notmuch->view = 1;
323
324     notmuch->params = NOTMUCH_PARAM_NONE;
325     if (database_path)
326         notmuch->params |= NOTMUCH_PARAM_DATABASE;
327     if (config_path)
328         notmuch->params |= NOTMUCH_PARAM_CONFIG;
329     if (profile)
330         notmuch->params |= NOTMUCH_PARAM_PROFILE;
331
332     return notmuch;
333 }
334
335 static notmuch_status_t
336 _trial_open (const char *xapian_path, char **message_ptr)
337 {
338     try {
339         Xapian::Database db (xapian_path);
340     } catch (const Xapian::DatabaseOpeningError &error) {
341         IGNORE_RESULT (asprintf (message_ptr,
342                                  "Cannot open Xapian database at %s: %s\n",
343                                  xapian_path,
344                                  error.get_msg ().c_str ()));
345         return NOTMUCH_STATUS_PATH_ERROR;
346     } catch (const Xapian::Error &error) {
347         IGNORE_RESULT (asprintf (message_ptr,
348                                  "A Xapian exception occurred opening database: %s\n",
349                                  error.get_msg ().c_str ()));
350         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
351     }
352     return NOTMUCH_STATUS_SUCCESS;
353 }
354
355 notmuch_status_t
356 _notmuch_choose_xapian_path (void *ctx, const char *database_path,
357                              const char **xapian_path, char **message_ptr)
358 {
359     notmuch_status_t status;
360     const char *trial_path, *notmuch_path;
361
362     status = _db_dir_exists (database_path, message_ptr);
363     if (status)
364         goto DONE;
365
366     trial_path = talloc_asprintf (ctx, "%s/xapian", database_path);
367     status = _trial_open (trial_path, message_ptr);
368     if (status != NOTMUCH_STATUS_PATH_ERROR)
369         goto DONE;
370
371     if (*message_ptr)
372         free (*message_ptr);
373
374     notmuch_path = talloc_asprintf (ctx, "%s/.notmuch", database_path);
375     status = _db_dir_exists (notmuch_path, message_ptr);
376     if (status)
377         goto DONE;
378
379     trial_path = talloc_asprintf (ctx, "%s/xapian", notmuch_path);
380     status = _trial_open (trial_path, message_ptr);
381
382   DONE:
383     if (status == NOTMUCH_STATUS_SUCCESS)
384         *xapian_path = trial_path;
385     return status;
386 }
387
388 static void
389 _set_database_path (notmuch_database_t *notmuch,
390                     const char *database_path)
391 {
392     char *path = talloc_strdup (notmuch, database_path);
393
394     strip_trailing (path, '/');
395
396     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
397 }
398
399 static void
400 _load_database_state (notmuch_database_t *notmuch)
401 {
402     std::string last_thread_id;
403     std::string last_mod;
404
405     notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
406     last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
407     if (last_thread_id.empty ()) {
408         notmuch->last_thread_id = 0;
409     } else {
410         const char *str;
411         char *end;
412
413         str = last_thread_id.c_str ();
414         notmuch->last_thread_id = strtoull (str, &end, 16);
415         if (*end != '\0')
416             INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
417     }
418
419     /* Get current highest revision number. */
420     last_mod = notmuch->xapian_db->get_value_upper_bound (
421         NOTMUCH_VALUE_LAST_MOD);
422     if (last_mod.empty ())
423         notmuch->revision = 0;
424     else
425         notmuch->revision = Xapian::sortable_unserialise (last_mod);
426     notmuch->uuid = talloc_strdup (
427         notmuch, notmuch->xapian_db->get_uuid ().c_str ());
428 }
429
430 static notmuch_status_t
431 _finish_open (notmuch_database_t *notmuch,
432               const char *profile,
433               notmuch_database_mode_t mode,
434               GKeyFile *key_file,
435               char **message_ptr)
436 {
437     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
438     char *incompat_features;
439     char *message = NULL;
440     const char *autocommit_str;
441     char *autocommit_end;
442     unsigned int version;
443     const char *database_path = notmuch_database_get_path (notmuch);
444
445     try {
446
447         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
448             notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
449                                                                         DB_ACTION);
450             notmuch->xapian_db = notmuch->writable_xapian_db;
451         } else {
452             notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path);
453         }
454
455         /* Check version.  As of database version 3, we represent
456          * changes in terms of features, so assume a version bump
457          * means a dramatically incompatible change. */
458         version = notmuch_database_get_version (notmuch);
459         if (version > NOTMUCH_DATABASE_VERSION) {
460             IGNORE_RESULT (asprintf (&message,
461                                      "Error: Notmuch database at %s\n"
462                                      "       has a newer database format version (%u) than supported by this\n"
463                                      "       version of notmuch (%u).\n",
464                                      database_path, version, NOTMUCH_DATABASE_VERSION));
465             status = NOTMUCH_STATUS_FILE_ERROR;
466             goto DONE;
467         }
468
469         /* Check features. */
470         incompat_features = NULL;
471         notmuch->features = _notmuch_database_parse_features (
472             notmuch, notmuch->xapian_db->get_metadata ("features").c_str (),
473             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
474             &incompat_features);
475         if (incompat_features) {
476             IGNORE_RESULT (asprintf (&message,
477                                      "Error: Notmuch database at %s\n"
478                                      "       requires features (%s)\n"
479                                      "       not supported by this version of notmuch.\n",
480                                      database_path, incompat_features));
481             status = NOTMUCH_STATUS_FILE_ERROR;
482             goto DONE;
483         }
484
485         _load_database_state (notmuch);
486
487         notmuch->query_parser = new Xapian::QueryParser;
488         notmuch->term_gen = new Xapian::TermGenerator;
489         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
490         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
491         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP,
492                                                                      "date:");
493         notmuch->last_mod_range_processor = new LastModRangeProcessor (notmuch, "lastmod:");
494         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
495         notmuch->query_parser->set_database (*notmuch->xapian_db);
496         notmuch->stemmer = new Xapian::Stem ("english");
497         notmuch->query_parser->set_stemmer (*notmuch->stemmer);
498         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
499         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
500         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
501         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
502
503         /* Configuration information is needed to set up query parser */
504         status = _notmuch_config_load_from_database (notmuch);
505         if (status)
506             goto DONE;
507
508         if (key_file)
509             status = _notmuch_config_load_from_file (notmuch, key_file);
510         if (status)
511             goto DONE;
512
513         status = _choose_dir (notmuch, profile,
514                               NOTMUCH_CONFIG_HOOK_DIR,
515                               "XDG_CONFIG_HOME",
516                               ".config",
517                               "hooks",
518                               &message);
519         if (status)
520             goto DONE;
521
522         status = _choose_dir (notmuch, profile,
523                               NOTMUCH_CONFIG_BACKUP_DIR,
524                               "XDG_DATA_HOME",
525                               ".local/share",
526                               "backups",
527                               &message);
528         if (status)
529             goto DONE;
530         status = _notmuch_config_load_defaults (notmuch);
531         if (status)
532             goto DONE;
533
534         autocommit_str = notmuch_config_get (notmuch, NOTMUCH_CONFIG_AUTOCOMMIT);
535         if (unlikely (! autocommit_str)) {
536             INTERNAL_ERROR ("missing configuration for autocommit");
537         }
538         notmuch->transaction_threshold = strtoul (autocommit_str, &autocommit_end, 10);
539         if (*autocommit_end != '\0')
540             INTERNAL_ERROR ("Malformed database database.autocommit value: %s", autocommit_str);
541
542         status = _notmuch_database_setup_standard_query_fields (notmuch);
543         if (status)
544             goto DONE;
545
546         status = _notmuch_database_setup_user_query_fields (notmuch);
547         if (status)
548             goto DONE;
549
550     } catch (const Xapian::Error &error) {
551         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
552                                  error.get_msg ().c_str ()));
553         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
554     }
555   DONE:
556     if (message_ptr)
557         *message_ptr = message;
558     return status;
559 }
560
561 notmuch_status_t
562 notmuch_database_open_with_config (const char *database_path,
563                                    notmuch_database_mode_t mode,
564                                    const char *config_path,
565                                    const char *profile,
566                                    notmuch_database_t **database,
567                                    char **status_string)
568 {
569     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
570     notmuch_database_t *notmuch = NULL;
571     char *message = NULL;
572     GKeyFile *key_file = NULL;
573
574     _notmuch_init ();
575
576     notmuch = _alloc_notmuch (database_path, config_path, profile);
577     if (! notmuch) {
578         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
579         goto DONE;
580     }
581
582     status = _load_key_file (notmuch, config_path, profile, &key_file);
583     if (status) {
584         message = strdup ("Error: cannot load config file.\n");
585         goto DONE;
586     }
587
588     if ((status = _choose_database_path (notmuch, profile, key_file,
589                                          &database_path,
590                                          &message)))
591         goto DONE;
592
593     status = _db_dir_exists (database_path, &message);
594     if (status)
595         goto DONE;
596
597     _set_database_path (notmuch, database_path);
598
599     status = _notmuch_choose_xapian_path (notmuch, database_path,
600                                           &notmuch->xapian_path, &message);
601     if (status)
602         goto DONE;
603
604     status = _finish_open (notmuch, profile, mode, key_file, &message);
605
606   DONE:
607     if (key_file)
608         g_key_file_free (key_file);
609
610     if (message) {
611         if (status_string)
612             *status_string = message;
613         else
614             free (message);
615     }
616
617     if (status && notmuch) {
618         notmuch_database_destroy (notmuch);
619         notmuch = NULL;
620     }
621
622     if (database)
623         *database = notmuch;
624
625     if (notmuch)
626         notmuch->open = true;
627
628     return status;
629 }
630
631 notmuch_status_t
632 notmuch_database_create (const char *path, notmuch_database_t **database)
633 {
634     char *status_string = NULL;
635     notmuch_status_t status;
636
637     status = notmuch_database_create_verbose (path, database,
638                                               &status_string);
639
640     if (status_string) {
641         fputs (status_string, stderr);
642         free (status_string);
643     }
644
645     return status;
646 }
647
648 notmuch_status_t
649 notmuch_database_create_verbose (const char *path,
650                                  notmuch_database_t **database,
651                                  char **status_string)
652 {
653     return notmuch_database_create_with_config (path, "", NULL, database, status_string);
654 }
655
656 notmuch_status_t
657 notmuch_database_create_with_config (const char *database_path,
658                                      const char *config_path,
659                                      const char *profile,
660                                      notmuch_database_t **database,
661                                      char **status_string)
662 {
663     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
664     notmuch_database_t *notmuch = NULL;
665     const char *notmuch_path = NULL;
666     char *message = NULL;
667     GKeyFile *key_file = NULL;
668
669     _notmuch_init ();
670
671     notmuch = _alloc_notmuch (database_path, config_path, profile);
672     if (! notmuch) {
673         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
674         goto DONE;
675     }
676
677     status = _load_key_file (notmuch, config_path, profile, &key_file);
678     if (status) {
679         message = strdup ("Error: cannot load config file.\n");
680         goto DONE;
681     }
682
683     status = _choose_database_path (notmuch, profile, key_file,
684                                     &database_path, &message);
685     switch (status) {
686     case NOTMUCH_STATUS_SUCCESS:
687         break;
688     case NOTMUCH_STATUS_NO_DATABASE:
689         if ((status = _create_database_path (notmuch, profile, key_file,
690                                              &database_path, &message)))
691             goto DONE;
692         break;
693     default:
694         goto DONE;
695     }
696
697     _set_database_path (notmuch, database_path);
698
699     if (key_file && ! (notmuch->params & NOTMUCH_PARAM_SPLIT)) {
700         char *mail_root = notmuch_canonicalize_file_name (
701             g_key_file_get_string (key_file, "database", "mail_root", NULL));
702         char *db_path = notmuch_canonicalize_file_name (database_path);
703
704         if (mail_root && (0 != strcmp (mail_root, db_path)))
705             notmuch->params |= NOTMUCH_PARAM_SPLIT;
706
707         free (mail_root);
708         free (db_path);
709     }
710
711     if (notmuch->params & NOTMUCH_PARAM_SPLIT) {
712         notmuch_path = database_path;
713     } else {
714         if (! (notmuch_path = talloc_asprintf (notmuch, "%s/%s", database_path, ".notmuch"))) {
715             status = NOTMUCH_STATUS_OUT_OF_MEMORY;
716             goto DONE;
717         }
718
719         status = _mkdir (notmuch_path, &message);
720         if (status)
721             goto DONE;
722     }
723
724     if (! (notmuch->xapian_path = talloc_asprintf (notmuch, "%s/%s", notmuch_path, "xapian"))) {
725         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
726         goto DONE;
727     }
728
729     status = _trial_open (notmuch->xapian_path, &message);
730     if (status == NOTMUCH_STATUS_SUCCESS) {
731         notmuch_database_destroy (notmuch);
732         notmuch = NULL;
733         status = NOTMUCH_STATUS_DATABASE_EXISTS;
734         goto DONE;
735     }
736
737     if (message)
738         free (message);
739
740     status = _finish_open (notmuch,
741                            profile,
742                            NOTMUCH_DATABASE_MODE_READ_WRITE,
743                            key_file,
744                            &message);
745     if (status)
746         goto DONE;
747
748     /* Upgrade doesn't add these feature to existing databases, but
749      * new databases have them. */
750     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
751     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
752     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
753
754     status = notmuch_database_upgrade (notmuch, NULL, NULL);
755     if (status) {
756         notmuch_database_close (notmuch);
757         notmuch = NULL;
758     }
759
760   DONE:
761     if (key_file)
762         g_key_file_free (key_file);
763
764     if (message) {
765         if (status_string)
766             *status_string = message;
767         else
768             free (message);
769     }
770     if (status && notmuch) {
771         notmuch_database_destroy (notmuch);
772         notmuch = NULL;
773     }
774
775     if (database)
776         *database = notmuch;
777
778     if (notmuch)
779         notmuch->open = true;
780     return status;
781 }
782
783 notmuch_status_t
784 notmuch_database_reopen (notmuch_database_t *notmuch,
785                          notmuch_database_mode_t new_mode)
786 {
787     notmuch_database_mode_t cur_mode = _notmuch_database_mode (notmuch);
788
789     if (notmuch->xapian_db == NULL) {
790         _notmuch_database_log (notmuch, "Cannot reopen closed or nonexistent database\n");
791         return NOTMUCH_STATUS_ILLEGAL_ARGUMENT;
792     }
793
794     try {
795         if (cur_mode == new_mode &&
796             new_mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
797             notmuch->xapian_db->reopen ();
798         } else {
799             notmuch->xapian_db->close ();
800
801             delete notmuch->xapian_db;
802             notmuch->xapian_db = NULL;
803             /* no need to free the same object twice */
804             notmuch->writable_xapian_db = NULL;
805
806             if (new_mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
807                 notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
808                                                                             DB_ACTION);
809                 notmuch->xapian_db = notmuch->writable_xapian_db;
810             } else {
811                 notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path,
812                                                            DB_ACTION);
813             }
814         }
815
816         _load_database_state (notmuch);
817     } catch (const Xapian::Error &error) {
818         if (! notmuch->exception_reported) {
819             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
820                                    error.get_msg ().c_str ());
821             notmuch->exception_reported = true;
822         }
823         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
824     }
825
826     notmuch->view++;
827     notmuch->open = true;
828     return NOTMUCH_STATUS_SUCCESS;
829 }
830
831 static notmuch_status_t
832 _maybe_load_config_from_database (notmuch_database_t *notmuch,
833                                   GKeyFile *key_file,
834                                   const char *database_path,
835                                   const char *profile)
836 {
837     char *message; /* ignored */
838
839     if (_db_dir_exists (database_path, &message))
840         return NOTMUCH_STATUS_NO_DATABASE;
841
842     _set_database_path (notmuch, database_path);
843
844     if (_notmuch_choose_xapian_path (notmuch, database_path, &notmuch->xapian_path, &message))
845         return NOTMUCH_STATUS_NO_DATABASE;
846
847     (void) _finish_open (notmuch, profile, NOTMUCH_DATABASE_MODE_READ_ONLY, key_file, &message);
848
849     return NOTMUCH_STATUS_SUCCESS;
850 }
851
852 notmuch_status_t
853 notmuch_database_load_config (const char *database_path,
854                               const char *config_path,
855                               const char *profile,
856                               notmuch_database_t **database,
857                               char **status_string)
858 {
859     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS, warning = NOTMUCH_STATUS_SUCCESS;
860     notmuch_database_t *notmuch = NULL;
861     char *message = NULL;
862     GKeyFile *key_file = NULL;
863
864     _notmuch_init ();
865
866     notmuch = _alloc_notmuch (database_path, config_path, profile);
867     if (! notmuch) {
868         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
869         goto DONE;
870     }
871
872     status = _load_key_file (notmuch, config_path, profile, &key_file);
873     switch (status) {
874     case NOTMUCH_STATUS_SUCCESS:
875         break;
876     case NOTMUCH_STATUS_NO_CONFIG:
877         warning = status;
878         break;
879     default:
880         message = strdup ("Error: cannot load config file.\n");
881         goto DONE;
882     }
883
884     status = _choose_database_path (notmuch, profile, key_file,
885                                     &database_path, &message);
886     switch (status) {
887     case NOTMUCH_STATUS_NO_DATABASE:
888     case NOTMUCH_STATUS_SUCCESS:
889         if (! warning)
890             warning = status;
891         break;
892     default:
893         goto DONE;
894     }
895
896
897     if (database_path) {
898         status = _maybe_load_config_from_database (notmuch, key_file, database_path, profile);
899         switch (status) {
900         case NOTMUCH_STATUS_NO_DATABASE:
901         case NOTMUCH_STATUS_SUCCESS:
902             if (! warning)
903                 warning = status;
904             break;
905         default:
906             goto DONE;
907         }
908     }
909
910     if (key_file) {
911         status = _notmuch_config_load_from_file (notmuch, key_file);
912         if (status)
913             goto DONE;
914     }
915     status = _notmuch_config_load_defaults (notmuch);
916     if (status)
917         goto DONE;
918
919   DONE:
920     if (status_string)
921         *status_string = message;
922
923     if (status &&
924         status != NOTMUCH_STATUS_NO_DATABASE
925         && status != NOTMUCH_STATUS_NO_CONFIG) {
926         notmuch_database_destroy (notmuch);
927         notmuch = NULL;
928     }
929
930     if (database)
931         *database = notmuch;
932
933     if (status)
934         return status;
935     else
936         return warning;
937 }