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