]> git.notmuchmail.org Git - notmuch/blob - lib/open.cc
0dfd295f2e8b8da1166cd0e3184789ccef5d0510
[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 notmuch_status_t
236 _trial_open (const char *xapian_path, char **message_ptr)
237 {
238     try {
239         Xapian::Database db (xapian_path);
240     } catch (const Xapian::DatabaseOpeningError &error) {
241         IGNORE_RESULT (asprintf (message_ptr,
242                                  "Cannot open Xapian database at %s: %s\n",
243                                  xapian_path,
244                                  error.get_msg ().c_str ()));
245         return NOTMUCH_STATUS_PATH_ERROR;
246     } catch (const Xapian::Error &error) {
247         IGNORE_RESULT (asprintf (message_ptr,
248                                  "A Xapian exception occurred opening database: %s\n",
249                                  error.get_msg ().c_str ()));
250         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
251     }
252     return NOTMUCH_STATUS_SUCCESS;
253 }
254
255 static notmuch_status_t
256 _choose_xapian_path (void *ctx, const char *database_path, const char **xapian_path,
257                      char **message_ptr)
258 {
259     notmuch_status_t status;
260     const char *trial_path, *notmuch_path;
261
262     status = _db_dir_exists (database_path, message_ptr);
263     if (status)
264         goto DONE;
265
266     trial_path = talloc_asprintf (ctx, "%s/xapian", database_path);
267     status = _trial_open (trial_path, message_ptr);
268     if (status != NOTMUCH_STATUS_PATH_ERROR)
269         goto DONE;
270
271     notmuch_path = talloc_asprintf (ctx, "%s/.notmuch", database_path);
272     status = _db_dir_exists (notmuch_path, message_ptr);
273     if (status)
274         goto DONE;
275
276     trial_path = talloc_asprintf (ctx, "%s/xapian", notmuch_path);
277     status = _trial_open (trial_path, message_ptr);
278
279   DONE:
280     if (status == NOTMUCH_STATUS_SUCCESS)
281         *xapian_path = trial_path;
282     return status;
283 }
284
285 static void
286 _set_database_path (notmuch_database_t *notmuch,
287                     const char *database_path)
288 {
289     char *path = talloc_strdup (notmuch, database_path);
290
291     strip_trailing (path, '/');
292
293     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
294 }
295
296 static void
297 _init_libs ()
298 {
299
300     static int initialized = 0;
301
302     /* Initialize the GLib type system and threads */
303 #if ! GLIB_CHECK_VERSION (2, 35, 1)
304     g_type_init ();
305 #endif
306
307     /* Initialize gmime */
308     if (! initialized) {
309         g_mime_init ();
310         initialized = 1;
311     }
312 }
313
314 static notmuch_status_t
315 _finish_open (notmuch_database_t *notmuch,
316               const char *profile,
317               notmuch_database_mode_t mode,
318               GKeyFile *key_file,
319               char **message_ptr)
320 {
321     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
322     char *incompat_features;
323     char *message = NULL;
324     unsigned int version;
325     const char *database_path = notmuch_database_get_path (notmuch);
326
327     try {
328         std::string last_thread_id;
329         std::string last_mod;
330
331         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
332             notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
333                                                                         DB_ACTION);
334             notmuch->xapian_db = notmuch->writable_xapian_db;
335         } else {
336             notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path);
337         }
338
339         /* Check version.  As of database version 3, we represent
340          * changes in terms of features, so assume a version bump
341          * means a dramatically incompatible change. */
342         version = notmuch_database_get_version (notmuch);
343         if (version > NOTMUCH_DATABASE_VERSION) {
344             IGNORE_RESULT (asprintf (&message,
345                                      "Error: Notmuch database at %s\n"
346                                      "       has a newer database format version (%u) than supported by this\n"
347                                      "       version of notmuch (%u).\n",
348                                      database_path, version, NOTMUCH_DATABASE_VERSION));
349             notmuch_database_destroy (notmuch);
350             notmuch = NULL;
351             status = NOTMUCH_STATUS_FILE_ERROR;
352             goto DONE;
353         }
354
355         /* Check features. */
356         incompat_features = NULL;
357         notmuch->features = _notmuch_database_parse_features (
358             notmuch, notmuch->xapian_db->get_metadata ("features").c_str (),
359             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
360             &incompat_features);
361         if (incompat_features) {
362             IGNORE_RESULT (asprintf (&message,
363                                      "Error: Notmuch database at %s\n"
364                                      "       requires features (%s)\n"
365                                      "       not supported by this version of notmuch.\n",
366                                      database_path, incompat_features));
367             notmuch_database_destroy (notmuch);
368             notmuch = NULL;
369             status = NOTMUCH_STATUS_FILE_ERROR;
370             goto DONE;
371         }
372
373         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
374         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
375         if (last_thread_id.empty ()) {
376             notmuch->last_thread_id = 0;
377         } else {
378             const char *str;
379             char *end;
380
381             str = last_thread_id.c_str ();
382             notmuch->last_thread_id = strtoull (str, &end, 16);
383             if (*end != '\0')
384                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
385         }
386
387         /* Get current highest revision number. */
388         last_mod = notmuch->xapian_db->get_value_upper_bound (
389             NOTMUCH_VALUE_LAST_MOD);
390         if (last_mod.empty ())
391             notmuch->revision = 0;
392         else
393             notmuch->revision = Xapian::sortable_unserialise (last_mod);
394         notmuch->uuid = talloc_strdup (
395             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
396
397         notmuch->query_parser = new Xapian::QueryParser;
398         notmuch->term_gen = new Xapian::TermGenerator;
399         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
400         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
401         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP,
402                                                                      "date:");
403         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD,
404                                                                               "lastmod:");
405         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
406         notmuch->query_parser->set_database (*notmuch->xapian_db);
407         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
408         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
409         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
410         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
411         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
412
413         /* Configuration information is needed to set up query parser */
414         status = _notmuch_config_load_from_database (notmuch);
415         if (status)
416             goto DONE;
417
418         if (key_file)
419             status = _notmuch_config_load_from_file (notmuch, key_file);
420         if (status)
421             goto DONE;
422
423         status = _choose_hook_dir (notmuch, profile, &message);
424         if (status)
425             goto DONE;
426
427         status = _notmuch_config_load_defaults (notmuch);
428         if (status)
429             goto DONE;
430
431         status = _notmuch_database_setup_standard_query_fields (notmuch);
432         if (status)
433             goto DONE;
434
435         status = _notmuch_database_setup_user_query_fields (notmuch);
436         if (status)
437             goto DONE;
438
439     } catch (const Xapian::Error &error) {
440         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
441                                  error.get_msg ().c_str ()));
442         notmuch_database_destroy (notmuch);
443         notmuch = NULL;
444         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
445     }
446   DONE:
447     if (message_ptr)
448         *message_ptr = message;
449     return status;
450 }
451
452 notmuch_status_t
453 notmuch_database_open_with_config (const char *database_path,
454                                    notmuch_database_mode_t mode,
455                                    const char *config_path,
456                                    const char *profile,
457                                    notmuch_database_t **database,
458                                    char **status_string)
459 {
460     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
461     void *local = talloc_new (NULL);
462     notmuch_database_t *notmuch = NULL;
463     char *message = NULL;
464     GKeyFile *key_file = NULL;
465
466     _init_libs ();
467
468     notmuch = _alloc_notmuch ();
469     if (! notmuch) {
470         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
471         goto DONE;
472     }
473
474     if ((status = _choose_database_path (local, config_path, profile, &key_file, &database_path,
475                                          &message)))
476         goto DONE;
477
478     status = _db_dir_exists (database_path, &message);
479     if (status)
480         goto DONE;
481
482     _set_database_path (notmuch, database_path);
483
484     status = _choose_xapian_path (notmuch, database_path, &notmuch->xapian_path, &message);
485     if (status)
486         goto DONE;
487
488     status = _finish_open (notmuch, profile, mode, key_file, &message);
489
490   DONE:
491     talloc_free (local);
492
493     if (key_file)
494         g_key_file_free (key_file);
495
496     if (message) {
497         if (status_string)
498             *status_string = message;
499         else
500             free (message);
501     }
502
503     if (database)
504         *database = notmuch;
505     else
506         talloc_free (notmuch);
507
508     if (notmuch)
509         notmuch->open = true;
510
511     return status;
512 }
513
514 notmuch_status_t
515 notmuch_database_create (const char *path, notmuch_database_t **database)
516 {
517     char *status_string = NULL;
518     notmuch_status_t status;
519
520     status = notmuch_database_create_verbose (path, database,
521                                               &status_string);
522
523     if (status_string) {
524         fputs (status_string, stderr);
525         free (status_string);
526     }
527
528     return status;
529 }
530
531 notmuch_status_t
532 notmuch_database_create_verbose (const char *path,
533                                  notmuch_database_t **database,
534                                  char **status_string)
535 {
536     return notmuch_database_create_with_config (path, "", NULL, database, status_string);
537 }
538
539 notmuch_status_t
540 notmuch_database_create_with_config (const char *database_path,
541                                      const char *config_path,
542                                      const char *profile,
543                                      notmuch_database_t **database,
544                                      char **status_string)
545 {
546     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
547     notmuch_database_t *notmuch = NULL;
548     const char *notmuch_path = NULL;
549     char *message = NULL;
550     GKeyFile *key_file = NULL;
551     void *local = talloc_new (NULL);
552     int err;
553     bool split = false;
554
555     _init_libs ();
556
557     notmuch = _alloc_notmuch ();
558     if (! notmuch) {
559         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
560         goto DONE;
561     }
562
563     _init_libs ();
564
565     if ((status = _choose_database_path (local, config_path, profile,
566                                          &key_file, &database_path, &message)))
567         goto DONE;
568
569     status = _db_dir_exists (database_path, &message);
570     if (status)
571         goto DONE;
572
573     _set_database_path (notmuch, database_path);
574
575     if (key_file && ! split) {
576         char *mail_root = canonicalize_file_name (
577             g_key_file_get_value (key_file, "database", "mail_root", NULL));
578         char *db_path = canonicalize_file_name (database_path);
579
580         split = (mail_root && (0 != strcmp (mail_root, db_path)));
581
582         free (mail_root);
583         free (db_path);
584     }
585
586     if (split) {
587         notmuch_path = database_path;
588     } else {
589         if (! (notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch"))) {
590             status = NOTMUCH_STATUS_OUT_OF_MEMORY;
591             goto DONE;
592         }
593
594         err = mkdir (notmuch_path, 0755);
595         if (err) {
596             if (errno == EEXIST) {
597                 status = NOTMUCH_STATUS_DATABASE_EXISTS;
598                 talloc_free (notmuch);
599                 notmuch = NULL;
600             } else {
601                 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
602                                          notmuch_path, strerror (errno)));
603                 status = NOTMUCH_STATUS_FILE_ERROR;
604             }
605             goto DONE;
606         }
607     }
608
609     if (! (notmuch->xapian_path = talloc_asprintf (notmuch, "%s/%s", notmuch_path, "xapian"))) {
610         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
611         goto DONE;
612     }
613
614     status = _trial_open (notmuch->xapian_path, &message);
615     if (status == NOTMUCH_STATUS_SUCCESS) {
616         notmuch_database_destroy (notmuch);
617         notmuch = NULL;
618         status = NOTMUCH_STATUS_DATABASE_EXISTS;
619         goto DONE;
620     }
621
622     status = _finish_open (notmuch,
623                            profile,
624                            NOTMUCH_DATABASE_MODE_READ_WRITE,
625                            key_file,
626                            &message);
627     if (status)
628         goto DONE;
629
630     /* Upgrade doesn't add these feature to existing databases, but
631      * new databases have them. */
632     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
633     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
634     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
635
636     status = notmuch_database_upgrade (notmuch, NULL, NULL);
637     if (status) {
638         notmuch_database_close (notmuch);
639         notmuch = NULL;
640     }
641
642   DONE:
643     talloc_free (local);
644
645     if (key_file)
646         g_key_file_free (key_file);
647
648     if (message) {
649         if (status_string)
650             *status_string = message;
651         else
652             free (message);
653     }
654     if (database)
655         *database = notmuch;
656     else
657         talloc_free (notmuch);
658     return status;
659 }
660
661 notmuch_status_t
662 notmuch_database_reopen (notmuch_database_t *notmuch,
663                          notmuch_database_mode_t new_mode)
664 {
665     notmuch_database_mode_t cur_mode = _notmuch_database_mode (notmuch);
666
667     if (notmuch->xapian_db == NULL) {
668         _notmuch_database_log (notmuch, "Cannot reopen closed or nonexistent database\n");
669         return NOTMUCH_STATUS_ILLEGAL_ARGUMENT;
670     }
671
672     try {
673         if (cur_mode == new_mode &&
674             new_mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
675             notmuch->xapian_db->reopen ();
676         } else {
677             notmuch->xapian_db->close ();
678
679             delete notmuch->xapian_db;
680             notmuch->xapian_db = NULL;
681             /* no need to free the same object twice */
682             notmuch->writable_xapian_db = NULL;
683
684             if (new_mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
685                 notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
686                                                                             DB_ACTION);
687                 notmuch->xapian_db = notmuch->writable_xapian_db;
688             } else {
689                 notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path,
690                                                            DB_ACTION);
691             }
692         }
693     } catch (const Xapian::Error &error) {
694         if (! notmuch->exception_reported) {
695             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
696                                    error.get_msg ().c_str ());
697             notmuch->exception_reported = true;
698         }
699         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
700     }
701
702     notmuch->view++;
703     notmuch->open = true;
704     return NOTMUCH_STATUS_SUCCESS;
705 }