]> git.notmuchmail.org Git - notmuch/blob - lib/open.cc
lib/open: allocate notmuch_t struct early
[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_database_t *
196 _alloc_notmuch ()
197 {
198     notmuch_database_t *notmuch;
199
200     notmuch = talloc_zero (NULL, notmuch_database_t);
201     if (! notmuch)
202         return NULL;
203
204     notmuch->exception_reported = false;
205     notmuch->status_string = NULL;
206     notmuch->writable_xapian_db = NULL;
207     notmuch->atomic_nesting = 0;
208     notmuch->view = 1;
209     return notmuch;
210 }
211
212 notmuch_status_t
213 notmuch_database_open_with_config (const char *database_path,
214                                    notmuch_database_mode_t mode,
215                                    const char *config_path,
216                                    const char *profile,
217                                    notmuch_database_t **database,
218                                    char **status_string)
219 {
220     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
221     void *local = talloc_new (NULL);
222     notmuch_database_t *notmuch = NULL;
223     char *notmuch_path, *incompat_features;
224     char *message = NULL;
225     struct stat st;
226     int err;
227     unsigned int version;
228     GKeyFile *key_file = NULL;
229     static int initialized = 0;
230
231     notmuch = _alloc_notmuch ();
232     if (! notmuch) {
233         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
234         goto DONE;
235     }
236
237     if ((status = _choose_database_path (local, config_path, profile,
238                                          &key_file, &database_path, &message)))
239         goto DONE;
240
241     notmuch->path = talloc_strdup (notmuch, database_path);
242     strip_trailing (notmuch->path, '/');
243
244     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch"))) {
245         message = strdup ("Out of memory\n");
246         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
247         goto DONE;
248     }
249
250     err = stat (notmuch_path, &st);
251     if (err) {
252         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
253                                  notmuch_path, strerror (errno)));
254         status = NOTMUCH_STATUS_FILE_ERROR;
255         goto DONE;
256     }
257
258     if (! (notmuch->xapian_path = talloc_asprintf (notmuch, "%s/%s", notmuch_path, "xapian"))) {
259         message = strdup ("Out of memory\n");
260         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
261         goto DONE;
262     }
263
264     /* Initialize the GLib type system and threads */
265 #if ! GLIB_CHECK_VERSION (2, 35, 1)
266     g_type_init ();
267 #endif
268
269     /* Initialize gmime */
270     if (! initialized) {
271         g_mime_init ();
272         initialized = 1;
273     }
274
275     try {
276         std::string last_thread_id;
277         std::string last_mod;
278
279         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
280             notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
281                                                                         DB_ACTION);
282             notmuch->xapian_db = notmuch->writable_xapian_db;
283         } else {
284             notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path);
285         }
286
287         /* Check version.  As of database version 3, we represent
288          * changes in terms of features, so assume a version bump
289          * means a dramatically incompatible change. */
290         version = notmuch_database_get_version (notmuch);
291         if (version > NOTMUCH_DATABASE_VERSION) {
292             IGNORE_RESULT (asprintf (&message,
293                                      "Error: Notmuch database at %s\n"
294                                      "       has a newer database format version (%u) than supported by this\n"
295                                      "       version of notmuch (%u).\n",
296                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
297             notmuch_database_destroy (notmuch);
298             notmuch = NULL;
299             status = NOTMUCH_STATUS_FILE_ERROR;
300             goto DONE;
301         }
302
303         /* Check features. */
304         incompat_features = NULL;
305         notmuch->features = _notmuch_database_parse_features (
306             local, notmuch->xapian_db->get_metadata ("features").c_str (),
307             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
308             &incompat_features);
309         if (incompat_features) {
310             IGNORE_RESULT (asprintf (&message,
311                                      "Error: Notmuch database at %s\n"
312                                      "       requires features (%s)\n"
313                                      "       not supported by this version of notmuch.\n",
314                                      notmuch_path, incompat_features));
315             notmuch_database_destroy (notmuch);
316             notmuch = NULL;
317             status = NOTMUCH_STATUS_FILE_ERROR;
318             goto DONE;
319         }
320
321         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
322         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
323         if (last_thread_id.empty ()) {
324             notmuch->last_thread_id = 0;
325         } else {
326             const char *str;
327             char *end;
328
329             str = last_thread_id.c_str ();
330             notmuch->last_thread_id = strtoull (str, &end, 16);
331             if (*end != '\0')
332                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
333         }
334
335         /* Get current highest revision number. */
336         last_mod = notmuch->xapian_db->get_value_upper_bound (
337             NOTMUCH_VALUE_LAST_MOD);
338         if (last_mod.empty ())
339             notmuch->revision = 0;
340         else
341             notmuch->revision = Xapian::sortable_unserialise (last_mod);
342         notmuch->uuid = talloc_strdup (
343             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
344
345         notmuch->query_parser = new Xapian::QueryParser;
346         notmuch->term_gen = new Xapian::TermGenerator;
347         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
348         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
349         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP,
350                                                                      "date:");
351         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD,
352                                                                               "lastmod:");
353         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
354         notmuch->query_parser->set_database (*notmuch->xapian_db);
355         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
356         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
357         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
358         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
359         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
360
361         /* Configuration information is needed to set up query parser */
362         status = _notmuch_config_load_from_database (notmuch);
363         if (status)
364             goto DONE;
365
366         if (key_file)
367             status = _notmuch_config_load_from_file (notmuch, key_file);
368         if (status)
369             goto DONE;
370
371         status = _choose_hook_dir (notmuch, profile, &message);
372         if (status)
373             goto DONE;
374
375         status = _notmuch_config_load_defaults (notmuch);
376         if (status)
377             goto DONE;
378
379         status = _notmuch_database_setup_standard_query_fields (notmuch);
380         if (status)
381             goto DONE;
382
383         status = _notmuch_database_setup_user_query_fields (notmuch);
384         if (status)
385             goto DONE;
386
387     } catch (const Xapian::Error &error) {
388         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
389                                  error.get_msg ().c_str ()));
390         notmuch_database_destroy (notmuch);
391         notmuch = NULL;
392         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
393     }
394
395   DONE:
396     talloc_free (local);
397
398     if (key_file)
399         g_key_file_free (key_file);
400
401     if (message) {
402         if (status_string)
403             *status_string = message;
404         else
405             free (message);
406     }
407
408     if (database)
409         *database = notmuch;
410     else
411         talloc_free (notmuch);
412
413     if (notmuch)
414         notmuch->open = true;
415
416     return status;
417 }
418
419 notmuch_status_t
420 notmuch_database_create (const char *path, notmuch_database_t **database)
421 {
422     char *status_string = NULL;
423     notmuch_status_t status;
424
425     status = notmuch_database_create_verbose (path, database,
426                                               &status_string);
427
428     if (status_string) {
429         fputs (status_string, stderr);
430         free (status_string);
431     }
432
433     return status;
434 }
435
436 notmuch_status_t
437 notmuch_database_create_verbose (const char *path,
438                                  notmuch_database_t **database,
439                                  char **status_string)
440 {
441     return notmuch_database_create_with_config (path, "", NULL, database, status_string);
442 }
443
444 notmuch_status_t
445 notmuch_database_create_with_config (const char *database_path,
446                                      const char *config_path,
447                                      const char *profile,
448                                      notmuch_database_t **database,
449                                      char **status_string)
450 {
451     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
452     notmuch_database_t *notmuch = NULL;
453     char *notmuch_path = NULL;
454     char *message = NULL;
455     GKeyFile *key_file = NULL;
456     struct stat st;
457     int err;
458     void *local = talloc_new (NULL);
459
460     if ((status = _choose_database_path (local, config_path, profile,
461                                          &key_file, &database_path, &message)))
462         goto DONE;
463
464     err = stat (database_path, &st);
465     if (err) {
466         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
467                                  database_path, strerror (errno)));
468         status = NOTMUCH_STATUS_FILE_ERROR;
469         goto DONE;
470     }
471
472     if (! S_ISDIR (st.st_mode)) {
473         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
474                                  "Not a directory.\n",
475                                  database_path));
476         status = NOTMUCH_STATUS_FILE_ERROR;
477         goto DONE;
478     }
479
480     notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch");
481
482     err = mkdir (notmuch_path, 0755);
483     if (err) {
484         if (errno == EEXIST) {
485             status = NOTMUCH_STATUS_DATABASE_EXISTS;
486         } else {
487             IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
488                                      notmuch_path, strerror (errno)));
489             status = NOTMUCH_STATUS_FILE_ERROR;
490         }
491         goto DONE;
492     }
493
494     /* XXX this reads the config file twice, which is a bit wasteful */
495     status = notmuch_database_open_with_config (database_path,
496                                                 NOTMUCH_DATABASE_MODE_READ_WRITE,
497                                                 config_path,
498                                                 profile,
499                                                 &notmuch, &message);
500     if (status)
501         goto DONE;
502
503     /* Upgrade doesn't add these feature to existing databases, but
504      * new databases have them. */
505     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
506     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
507     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
508
509     status = notmuch_database_upgrade (notmuch, NULL, NULL);
510     if (status) {
511         notmuch_database_close (notmuch);
512         notmuch = NULL;
513     }
514
515   DONE:
516     talloc_free (local);
517
518     if (key_file)
519         g_key_file_free (key_file);
520
521     if (message) {
522         if (status_string)
523             *status_string = message;
524         else
525             free (message);
526     }
527     if (database)
528         *database = notmuch;
529     else
530         talloc_free (notmuch);
531     return status;
532 }
533
534 notmuch_status_t
535 notmuch_database_reopen (notmuch_database_t *notmuch,
536                          notmuch_database_mode_t new_mode)
537 {
538     notmuch_database_mode_t cur_mode = _notmuch_database_mode (notmuch);
539
540     if (notmuch->xapian_db == NULL) {
541         _notmuch_database_log (notmuch, "Cannot reopen closed or nonexistent database\n");
542         return NOTMUCH_STATUS_ILLEGAL_ARGUMENT;
543     }
544
545     try {
546         if (cur_mode == new_mode &&
547             new_mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
548             notmuch->xapian_db->reopen ();
549         } else {
550             notmuch->xapian_db->close ();
551
552             delete notmuch->xapian_db;
553             notmuch->xapian_db = NULL;
554             /* no need to free the same object twice */
555             notmuch->writable_xapian_db = NULL;
556
557             if (new_mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
558                 notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
559                                                                             DB_ACTION);
560                 notmuch->xapian_db = notmuch->writable_xapian_db;
561             } else {
562                 notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path,
563                                                            DB_ACTION);
564             }
565         }
566     } catch (const Xapian::Error &error) {
567         if (! notmuch->exception_reported) {
568             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
569                                    error.get_msg ().c_str ());
570             notmuch->exception_reported = true;
571         }
572         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
573     }
574
575     notmuch->view++;
576     notmuch->open = true;
577     return NOTMUCH_STATUS_SUCCESS;
578 }