]> git.notmuchmail.org Git - notmuch/blob - lib/open.cc
lib/open: support NOTMUCH_DATABASE environment variable
[notmuch] / lib / open.cc
1 #include <unistd.h>
2 #include "database-private.h"
3 #include "parse-time-vrp.h"
4
5 #if HAVE_XAPIAN_DB_RETRY_LOCK
6 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
7 #else
8 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
9 #endif
10
11 notmuch_status_t
12 notmuch_database_open (const char *path,
13                        notmuch_database_mode_t mode,
14                        notmuch_database_t **database)
15 {
16     char *status_string = NULL;
17     notmuch_status_t status;
18
19     status = notmuch_database_open_verbose (path, mode, database,
20                                             &status_string);
21
22     if (status_string) {
23         fputs (status_string, stderr);
24         free (status_string);
25     }
26
27     return status;
28 }
29
30 notmuch_status_t
31 notmuch_database_open_verbose (const char *path,
32                                notmuch_database_mode_t mode,
33                                notmuch_database_t **database,
34                                char **status_string)
35 {
36     return notmuch_database_open_with_config (path, mode, "", NULL,
37                                               database, status_string);
38 }
39
40 static const char *
41 _xdg_dir (void *ctx,
42           const char *xdg_root_variable,
43           const char *xdg_prefix,
44           const char *profile_name)
45 {
46     const char *xdg_root = getenv (xdg_root_variable);
47
48     if (! xdg_root) {
49         const char *home = getenv ("HOME");
50
51         if (! home) return NULL;
52
53         xdg_root = talloc_asprintf (ctx,
54                                     "%s/%s",
55                                     home,
56                                     xdg_prefix);
57     }
58
59     if (! profile_name)
60         profile_name = getenv ("NOTMUCH_PROFILE");
61
62     if (! profile_name)
63         profile_name = "default";
64
65     return talloc_asprintf (ctx,
66                             "%s/notmuch/%s",
67                             xdg_root,
68                             profile_name);
69 }
70
71 static notmuch_status_t
72 _choose_hook_dir (notmuch_database_t *notmuch,
73                   const char *profile,
74                   char **message)
75 {
76     const char *config;
77     const char *hook_dir;
78     struct stat st;
79     int err;
80
81     hook_dir = notmuch_config_get (notmuch, NOTMUCH_CONFIG_HOOK_DIR);
82
83     if (hook_dir)
84         return NOTMUCH_STATUS_SUCCESS;
85
86     config = _xdg_dir (notmuch, "XDG_CONFIG_HOME", ".config", profile);
87     if (! config)
88         return NOTMUCH_STATUS_PATH_ERROR;
89
90     hook_dir = talloc_asprintf (notmuch, "%s/hooks", config);
91
92     err = stat (hook_dir, &st);
93     if (err) {
94         if (errno == ENOENT) {
95             const char *database_path = notmuch_database_get_path (notmuch);
96             hook_dir = talloc_asprintf (notmuch, "%s/.notmuch/hooks", database_path);
97         } else {
98             IGNORE_RESULT (asprintf (message, "Error: Cannot stat %s: %s.\n",
99                                      hook_dir, strerror (errno)));
100             return NOTMUCH_STATUS_FILE_ERROR;
101         }
102     }
103
104     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_HOOK_DIR, hook_dir);
105
106     return NOTMUCH_STATUS_SUCCESS;
107 }
108
109 static notmuch_status_t
110 _load_key_file (const char *path,
111                 const char *profile,
112                 GKeyFile **key_file)
113 {
114     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
115     void *local = talloc_new (NULL);
116
117     if (path && EMPTY_STRING (path))
118         goto DONE;
119
120     if (! path)
121         path = getenv ("NOTMUCH_CONFIG");
122
123     if (! path) {
124         const char *dir = _xdg_dir (local, "XDG_CONFIG_HOME", ".config", profile);
125
126         if (dir) {
127             path = talloc_asprintf (local, "%s/config", dir);
128             if (access (path, R_OK) != 0)
129                 path = NULL;
130         }
131     }
132
133     if (! path) {
134         const char *home = getenv ("HOME");
135
136         path = talloc_asprintf (local, "%s/.notmuch-config", home);
137
138         if (! profile)
139             profile = getenv ("NOTMUCH_PROFILE");
140
141         if (profile)
142             path = talloc_asprintf (local, "%s.%s", path, profile);
143     }
144
145     *key_file = g_key_file_new ();
146     if (! g_key_file_load_from_file (*key_file, path, G_KEY_FILE_NONE, NULL)) {
147         status = NOTMUCH_STATUS_NO_CONFIG;
148     }
149
150   DONE:
151     talloc_free (local);
152     return status;
153 }
154
155 static notmuch_status_t
156 _choose_database_path (void *ctx,
157                        const char *config_path,
158                        const char *profile,
159                        GKeyFile **key_file,
160                        const char **database_path,
161                        char **message)
162 {
163     notmuch_status_t status;
164
165     status = _load_key_file (config_path, profile, key_file);
166     if (status) {
167         *message = strdup ("Error: cannot load config file.\n");
168         return status;
169     }
170
171     if (! *database_path) {
172         *database_path = getenv ("NOTMUCH_DATABASE");
173     }
174
175     if (! *database_path && *key_file) {
176         char *path = g_key_file_get_value (*key_file, "database", "path", NULL);
177         if (path) {
178             *database_path = talloc_strdup (ctx, path);
179             g_free (path);
180         }
181     }
182
183     if (*database_path == NULL) {
184         *message = strdup ("Error: Cannot open a database for a NULL path.\n");
185         return NOTMUCH_STATUS_NULL_POINTER;
186     }
187
188     if (*database_path[0] != '/') {
189         *message = strdup ("Error: Database path must be absolute.\n");
190         return NOTMUCH_STATUS_PATH_ERROR;
191     }
192     return NOTMUCH_STATUS_SUCCESS;
193 }
194
195 notmuch_status_t
196 notmuch_database_open_with_config (const char *database_path,
197                                    notmuch_database_mode_t mode,
198                                    const char *config_path,
199                                    const char *profile,
200                                    notmuch_database_t **database,
201                                    char **status_string)
202 {
203     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
204     void *local = talloc_new (NULL);
205     notmuch_database_t *notmuch = NULL;
206     char *notmuch_path, *incompat_features;
207     char *message = NULL;
208     struct stat st;
209     int err;
210     unsigned int version;
211     GKeyFile *key_file = NULL;
212     static int initialized = 0;
213
214     if ((status = _choose_database_path (local, config_path, profile, &key_file, &database_path,
215                                          &message)))
216         goto DONE;
217
218     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch"))) {
219         message = strdup ("Out of memory\n");
220         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
221         goto DONE;
222     }
223
224     err = stat (notmuch_path, &st);
225     if (err) {
226         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
227                                  notmuch_path, strerror (errno)));
228         status = NOTMUCH_STATUS_FILE_ERROR;
229         goto DONE;
230     }
231
232     /* Initialize the GLib type system and threads */
233 #if ! GLIB_CHECK_VERSION (2, 35, 1)
234     g_type_init ();
235 #endif
236
237     /* Initialize gmime */
238     if (! initialized) {
239         g_mime_init ();
240         initialized = 1;
241     }
242
243     notmuch = talloc_zero (NULL, notmuch_database_t);
244     notmuch->exception_reported = false;
245     notmuch->status_string = NULL;
246     notmuch->path = talloc_strdup (notmuch, database_path);
247
248     strip_trailing (notmuch->path, '/');
249
250     notmuch->writable_xapian_db = NULL;
251     notmuch->atomic_nesting = 0;
252     notmuch->view = 1;
253
254     if (! (notmuch->xapian_path = talloc_asprintf (notmuch, "%s/%s", notmuch_path, "xapian"))) {
255         message = strdup ("Out of memory\n");
256         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
257         goto DONE;
258     }
259
260     try {
261         std::string last_thread_id;
262         std::string last_mod;
263
264         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
265             notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
266                                                                         DB_ACTION);
267             notmuch->xapian_db = notmuch->writable_xapian_db;
268         } else {
269             notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path);
270         }
271
272         /* Check version.  As of database version 3, we represent
273          * changes in terms of features, so assume a version bump
274          * means a dramatically incompatible change. */
275         version = notmuch_database_get_version (notmuch);
276         if (version > NOTMUCH_DATABASE_VERSION) {
277             IGNORE_RESULT (asprintf (&message,
278                                      "Error: Notmuch database at %s\n"
279                                      "       has a newer database format version (%u) than supported by this\n"
280                                      "       version of notmuch (%u).\n",
281                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
282             notmuch_database_destroy (notmuch);
283             notmuch = NULL;
284             status = NOTMUCH_STATUS_FILE_ERROR;
285             goto DONE;
286         }
287
288         /* Check features. */
289         incompat_features = NULL;
290         notmuch->features = _notmuch_database_parse_features (
291             local, notmuch->xapian_db->get_metadata ("features").c_str (),
292             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
293             &incompat_features);
294         if (incompat_features) {
295             IGNORE_RESULT (asprintf (&message,
296                                      "Error: Notmuch database at %s\n"
297                                      "       requires features (%s)\n"
298                                      "       not supported by this version of notmuch.\n",
299                                      notmuch_path, incompat_features));
300             notmuch_database_destroy (notmuch);
301             notmuch = NULL;
302             status = NOTMUCH_STATUS_FILE_ERROR;
303             goto DONE;
304         }
305
306         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
307         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
308         if (last_thread_id.empty ()) {
309             notmuch->last_thread_id = 0;
310         } else {
311             const char *str;
312             char *end;
313
314             str = last_thread_id.c_str ();
315             notmuch->last_thread_id = strtoull (str, &end, 16);
316             if (*end != '\0')
317                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
318         }
319
320         /* Get current highest revision number. */
321         last_mod = notmuch->xapian_db->get_value_upper_bound (
322             NOTMUCH_VALUE_LAST_MOD);
323         if (last_mod.empty ())
324             notmuch->revision = 0;
325         else
326             notmuch->revision = Xapian::sortable_unserialise (last_mod);
327         notmuch->uuid = talloc_strdup (
328             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
329
330         notmuch->query_parser = new Xapian::QueryParser;
331         notmuch->term_gen = new Xapian::TermGenerator;
332         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
333         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
334         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP,
335                                                                      "date:");
336         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD,
337                                                                               "lastmod:");
338         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
339         notmuch->query_parser->set_database (*notmuch->xapian_db);
340         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
341         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
342         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
343         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
344         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
345
346         /* Configuration information is needed to set up query parser */
347         status = _notmuch_config_load_from_database (notmuch);
348         if (status)
349             goto DONE;
350
351         if (key_file)
352             status = _notmuch_config_load_from_file (notmuch, key_file);
353         if (status)
354             goto DONE;
355
356         status = _choose_hook_dir (notmuch, profile, &message);
357         if (status)
358             goto DONE;
359
360         status = _notmuch_config_load_defaults (notmuch);
361         if (status)
362             goto DONE;
363
364         status = _notmuch_database_setup_standard_query_fields (notmuch);
365         if (status)
366             goto DONE;
367
368         status = _notmuch_database_setup_user_query_fields (notmuch);
369         if (status)
370             goto DONE;
371
372     } catch (const Xapian::Error &error) {
373         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
374                                  error.get_msg ().c_str ()));
375         notmuch_database_destroy (notmuch);
376         notmuch = NULL;
377         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
378     }
379
380   DONE:
381     talloc_free (local);
382
383     if (key_file)
384         g_key_file_free (key_file);
385
386     if (message) {
387         if (status_string)
388             *status_string = message;
389         else
390             free (message);
391     }
392
393     if (database)
394         *database = notmuch;
395     else
396         talloc_free (notmuch);
397
398     if (notmuch)
399         notmuch->open = true;
400
401     return status;
402 }
403
404 notmuch_status_t
405 notmuch_database_create (const char *path, notmuch_database_t **database)
406 {
407     char *status_string = NULL;
408     notmuch_status_t status;
409
410     status = notmuch_database_create_verbose (path, database,
411                                               &status_string);
412
413     if (status_string) {
414         fputs (status_string, stderr);
415         free (status_string);
416     }
417
418     return status;
419 }
420
421 notmuch_status_t
422 notmuch_database_create_verbose (const char *path,
423                                  notmuch_database_t **database,
424                                  char **status_string)
425 {
426     return notmuch_database_create_with_config (path, "", NULL, database, status_string);
427 }
428
429 notmuch_status_t
430 notmuch_database_create_with_config (const char *database_path,
431                                      const char *config_path,
432                                      const char *profile,
433                                      notmuch_database_t **database,
434                                      char **status_string)
435 {
436     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
437     notmuch_database_t *notmuch = NULL;
438     char *notmuch_path = NULL;
439     char *message = NULL;
440     GKeyFile *key_file = NULL;
441     struct stat st;
442     int err;
443     void *local = talloc_new (NULL);
444
445     if ((status = _choose_database_path (local, config_path, profile, &key_file, &database_path,
446                                          &message)))
447         goto DONE;
448
449     err = stat (database_path, &st);
450     if (err) {
451         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
452                                  database_path, strerror (errno)));
453         status = NOTMUCH_STATUS_FILE_ERROR;
454         goto DONE;
455     }
456
457     if (! S_ISDIR (st.st_mode)) {
458         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
459                                  "Not a directory.\n",
460                                  database_path));
461         status = NOTMUCH_STATUS_FILE_ERROR;
462         goto DONE;
463     }
464
465     notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch");
466
467     err = mkdir (notmuch_path, 0755);
468     if (err) {
469         if (errno == EEXIST) {
470             status = NOTMUCH_STATUS_DATABASE_EXISTS;
471         } else {
472             IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
473                                      notmuch_path, strerror (errno)));
474             status = NOTMUCH_STATUS_FILE_ERROR;
475         }
476         goto DONE;
477     }
478
479     /* XXX this reads the config file twice, which is a bit wasteful */
480     status = notmuch_database_open_with_config (database_path,
481                                                 NOTMUCH_DATABASE_MODE_READ_WRITE,
482                                                 config_path,
483                                                 profile,
484                                                 &notmuch, &message);
485     if (status)
486         goto DONE;
487
488     /* Upgrade doesn't add these feature to existing databases, but
489      * new databases have them. */
490     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
491     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
492     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
493
494     status = notmuch_database_upgrade (notmuch, NULL, NULL);
495     if (status) {
496         notmuch_database_close (notmuch);
497         notmuch = NULL;
498     }
499
500   DONE:
501     talloc_free (local);
502
503     if (key_file)
504         g_key_file_free (key_file);
505
506     if (message) {
507         if (status_string)
508             *status_string = message;
509         else
510             free (message);
511     }
512     if (database)
513         *database = notmuch;
514     else
515         talloc_free (notmuch);
516     return status;
517 }
518
519 notmuch_status_t
520 notmuch_database_reopen (notmuch_database_t *notmuch,
521                          notmuch_database_mode_t new_mode)
522 {
523     notmuch_database_mode_t cur_mode = _notmuch_database_mode (notmuch);
524
525     if (notmuch->xapian_db == NULL) {
526         _notmuch_database_log (notmuch, "Cannot reopen closed or nonexistent database\n");
527         return NOTMUCH_STATUS_ILLEGAL_ARGUMENT;
528     }
529
530     try {
531         if (cur_mode == new_mode &&
532             new_mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
533             notmuch->xapian_db->reopen ();
534         } else {
535             notmuch->xapian_db->close ();
536
537             delete notmuch->xapian_db;
538             notmuch->xapian_db = NULL;
539             /* no need to free the same object twice */
540             notmuch->writable_xapian_db = NULL;
541
542             if (new_mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
543                 notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
544                                                                             DB_ACTION);
545                 notmuch->xapian_db = notmuch->writable_xapian_db;
546             } else {
547                 notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path,
548                                                            DB_ACTION);
549             }
550         }
551     } catch (const Xapian::Error &error) {
552         if (! notmuch->exception_reported) {
553             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
554                                    error.get_msg ().c_str ());
555             notmuch->exception_reported = true;
556         }
557         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
558     }
559
560     notmuch->view++;
561     notmuch->open = true;
562     return NOTMUCH_STATUS_SUCCESS;
563 }