]> git.notmuchmail.org Git - notmuch/blob - lib/open.cc
lib/config: add configuration variable for backup directory
[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
7 #if HAVE_XAPIAN_DB_RETRY_LOCK
8 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
9 #else
10 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
11 #endif
12
13 notmuch_status_t
14 notmuch_database_open (const char *path,
15                        notmuch_database_mode_t mode,
16                        notmuch_database_t **database)
17 {
18     char *status_string = NULL;
19     notmuch_status_t status;
20
21     status = notmuch_database_open_verbose (path, mode, database,
22                                             &status_string);
23
24     if (status_string) {
25         fputs (status_string, stderr);
26         free (status_string);
27     }
28
29     return status;
30 }
31
32 notmuch_status_t
33 notmuch_database_open_verbose (const char *path,
34                                notmuch_database_mode_t mode,
35                                notmuch_database_t **database,
36                                char **status_string)
37 {
38     return notmuch_database_open_with_config (path, mode, "", NULL,
39                                               database, status_string);
40 }
41
42 static const char *
43 _xdg_dir (void *ctx,
44           const char *xdg_root_variable,
45           const char *xdg_prefix,
46           const char *profile_name)
47 {
48     const char *xdg_root = getenv (xdg_root_variable);
49
50     if (! xdg_root) {
51         const char *home = getenv ("HOME");
52
53         if (! home) return NULL;
54
55         xdg_root = talloc_asprintf (ctx,
56                                     "%s/%s",
57                                     home,
58                                     xdg_prefix);
59     }
60
61     if (! profile_name)
62         profile_name = getenv ("NOTMUCH_PROFILE");
63
64     if (! profile_name)
65         profile_name = "default";
66
67     return talloc_asprintf (ctx,
68                             "%s/notmuch/%s",
69                             xdg_root,
70                             profile_name);
71 }
72
73 static notmuch_status_t
74 _choose_dir (notmuch_database_t *notmuch,
75              const char *profile,
76              notmuch_config_key_t key,
77              const char *xdg_var,
78              const char *xdg_subdir,
79              const char *subdir,
80              char **message = NULL)
81 {
82     const char *parent;
83     const char *dir;
84     struct stat st;
85     int err;
86
87     dir = notmuch_config_get (notmuch, key);
88
89     if (dir)
90         return NOTMUCH_STATUS_SUCCESS;
91
92     parent = _xdg_dir (notmuch, xdg_var, xdg_subdir, profile);
93     if (! parent)
94         return NOTMUCH_STATUS_PATH_ERROR;
95
96     dir = talloc_asprintf (notmuch, "%s/%s", parent, subdir);
97
98     err = stat (dir, &st);
99     if (err) {
100         if (errno == ENOENT) {
101             char *notmuch_path = dirname (talloc_strdup (notmuch, notmuch->xapian_path));
102             dir = talloc_asprintf (notmuch, "%s/%s", notmuch_path, subdir);
103         } else {
104             IGNORE_RESULT (asprintf (message, "Error: Cannot stat %s: %s.\n",
105                                      dir, strerror (errno)));
106             return NOTMUCH_STATUS_FILE_ERROR;
107         }
108     }
109
110     _notmuch_config_cache (notmuch, key, dir);
111
112     return NOTMUCH_STATUS_SUCCESS;
113 }
114
115 static notmuch_status_t
116 _load_key_file (const char *path,
117                 const char *profile,
118                 GKeyFile **key_file)
119 {
120     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
121     void *local = talloc_new (NULL);
122
123     if (path && EMPTY_STRING (path))
124         goto DONE;
125
126     if (! path)
127         path = getenv ("NOTMUCH_CONFIG");
128
129     if (! path) {
130         const char *dir = _xdg_dir (local, "XDG_CONFIG_HOME", ".config", profile);
131
132         if (dir) {
133             path = talloc_asprintf (local, "%s/config", dir);
134             if (access (path, R_OK) != 0)
135                 path = NULL;
136         }
137     }
138
139     if (! path) {
140         const char *home = getenv ("HOME");
141
142         path = talloc_asprintf (local, "%s/.notmuch-config", home);
143
144         if (! profile)
145             profile = getenv ("NOTMUCH_PROFILE");
146
147         if (profile)
148             path = talloc_asprintf (local, "%s.%s", path, profile);
149     }
150
151     *key_file = g_key_file_new ();
152     if (! g_key_file_load_from_file (*key_file, path, G_KEY_FILE_NONE, NULL)) {
153         status = NOTMUCH_STATUS_NO_CONFIG;
154     }
155
156   DONE:
157     talloc_free (local);
158     return status;
159 }
160
161 static notmuch_status_t
162 _db_dir_exists (const char *database_path, char **message)
163 {
164     struct stat st;
165     int err;
166
167     err = stat (database_path, &st);
168     if (err) {
169         IGNORE_RESULT (asprintf (message, "Error: Cannot open database at %s: %s.\n",
170                                  database_path, strerror (errno)));
171         return NOTMUCH_STATUS_FILE_ERROR;
172     }
173
174     if (! S_ISDIR (st.st_mode)) {
175         IGNORE_RESULT (asprintf (message, "Error: Cannot open database at %s: "
176                                  "Not a directory.\n",
177                                  database_path));
178         return NOTMUCH_STATUS_FILE_ERROR;
179     }
180
181     return NOTMUCH_STATUS_SUCCESS;
182 }
183
184 static notmuch_status_t
185 _choose_database_path (void *ctx,
186                        const char *config_path,
187                        const char *profile,
188                        GKeyFile **key_file,
189                        const char **database_path,
190                        bool *split,
191                        char **message)
192 {
193     notmuch_status_t status;
194
195     status = _load_key_file (config_path, profile, key_file);
196     if (status) {
197         *message = strdup ("Error: cannot load config file.\n");
198         return status;
199     }
200
201     if (! *database_path) {
202         *database_path = getenv ("NOTMUCH_DATABASE");
203     }
204
205     if (! *database_path && *key_file) {
206         char *path = g_key_file_get_value (*key_file, "database", "path", NULL);
207         if (path) {
208             *database_path = talloc_strdup (ctx, path);
209             g_free (path);
210         }
211     }
212
213     if (! *database_path) {
214         *database_path = _xdg_dir (ctx, "XDG_DATA_HOME", ".local/share", profile);
215         *split = true;
216     }
217
218     if (*database_path == NULL) {
219         *message = strdup ("Error: Cannot open a database for a NULL path.\n");
220         return NOTMUCH_STATUS_NULL_POINTER;
221     }
222
223     if (*database_path[0] != '/') {
224         *message = strdup ("Error: Database path must be absolute.\n");
225         return NOTMUCH_STATUS_PATH_ERROR;
226     }
227     return NOTMUCH_STATUS_SUCCESS;
228 }
229
230 notmuch_database_t *
231 _alloc_notmuch ()
232 {
233     notmuch_database_t *notmuch;
234
235     notmuch = talloc_zero (NULL, notmuch_database_t);
236     if (! notmuch)
237         return NULL;
238
239     notmuch->exception_reported = false;
240     notmuch->status_string = NULL;
241     notmuch->writable_xapian_db = NULL;
242     notmuch->atomic_nesting = 0;
243     notmuch->view = 1;
244     return notmuch;
245 }
246
247 static notmuch_status_t
248 _trial_open (const char *xapian_path, char **message_ptr)
249 {
250     try {
251         Xapian::Database db (xapian_path);
252     } catch (const Xapian::DatabaseOpeningError &error) {
253         IGNORE_RESULT (asprintf (message_ptr,
254                                  "Cannot open Xapian database at %s: %s\n",
255                                  xapian_path,
256                                  error.get_msg ().c_str ()));
257         return NOTMUCH_STATUS_PATH_ERROR;
258     } catch (const Xapian::Error &error) {
259         IGNORE_RESULT (asprintf (message_ptr,
260                                  "A Xapian exception occurred opening database: %s\n",
261                                  error.get_msg ().c_str ()));
262         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
263     }
264     return NOTMUCH_STATUS_SUCCESS;
265 }
266
267 notmuch_status_t
268 _notmuch_choose_xapian_path (void *ctx, const char *database_path,
269                              const char **xapian_path, char **message_ptr)
270 {
271     notmuch_status_t status;
272     const char *trial_path, *notmuch_path;
273
274     status = _db_dir_exists (database_path, message_ptr);
275     if (status)
276         goto DONE;
277
278     trial_path = talloc_asprintf (ctx, "%s/xapian", database_path);
279     status = _trial_open (trial_path, message_ptr);
280     if (status != NOTMUCH_STATUS_PATH_ERROR)
281         goto DONE;
282
283     notmuch_path = talloc_asprintf (ctx, "%s/.notmuch", database_path);
284     status = _db_dir_exists (notmuch_path, message_ptr);
285     if (status)
286         goto DONE;
287
288     trial_path = talloc_asprintf (ctx, "%s/xapian", notmuch_path);
289     status = _trial_open (trial_path, message_ptr);
290
291   DONE:
292     if (status == NOTMUCH_STATUS_SUCCESS)
293         *xapian_path = trial_path;
294     return status;
295 }
296
297 static void
298 _set_database_path (notmuch_database_t *notmuch,
299                     const char *database_path)
300 {
301     char *path = talloc_strdup (notmuch, database_path);
302
303     strip_trailing (path, '/');
304
305     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
306 }
307
308 static void
309 _init_libs ()
310 {
311
312     static int initialized = 0;
313
314     /* Initialize the GLib type system and threads */
315 #if ! GLIB_CHECK_VERSION (2, 35, 1)
316     g_type_init ();
317 #endif
318
319     /* Initialize gmime */
320     if (! initialized) {
321         g_mime_init ();
322         initialized = 1;
323     }
324 }
325
326 static notmuch_status_t
327 _finish_open (notmuch_database_t *notmuch,
328               const char *profile,
329               notmuch_database_mode_t mode,
330               GKeyFile *key_file,
331               char **message_ptr)
332 {
333     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
334     char *incompat_features;
335     char *message = NULL;
336     unsigned int version;
337     const char *database_path = notmuch_database_get_path (notmuch);
338
339     try {
340         std::string last_thread_id;
341         std::string last_mod;
342
343         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
344             notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
345                                                                         DB_ACTION);
346             notmuch->xapian_db = notmuch->writable_xapian_db;
347         } else {
348             notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path);
349         }
350
351         /* Check version.  As of database version 3, we represent
352          * changes in terms of features, so assume a version bump
353          * means a dramatically incompatible change. */
354         version = notmuch_database_get_version (notmuch);
355         if (version > NOTMUCH_DATABASE_VERSION) {
356             IGNORE_RESULT (asprintf (&message,
357                                      "Error: Notmuch database at %s\n"
358                                      "       has a newer database format version (%u) than supported by this\n"
359                                      "       version of notmuch (%u).\n",
360                                      database_path, version, NOTMUCH_DATABASE_VERSION));
361             notmuch_database_destroy (notmuch);
362             notmuch = NULL;
363             status = NOTMUCH_STATUS_FILE_ERROR;
364             goto DONE;
365         }
366
367         /* Check features. */
368         incompat_features = NULL;
369         notmuch->features = _notmuch_database_parse_features (
370             notmuch, notmuch->xapian_db->get_metadata ("features").c_str (),
371             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
372             &incompat_features);
373         if (incompat_features) {
374             IGNORE_RESULT (asprintf (&message,
375                                      "Error: Notmuch database at %s\n"
376                                      "       requires features (%s)\n"
377                                      "       not supported by this version of notmuch.\n",
378                                      database_path, incompat_features));
379             notmuch_database_destroy (notmuch);
380             notmuch = NULL;
381             status = NOTMUCH_STATUS_FILE_ERROR;
382             goto DONE;
383         }
384
385         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
386         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
387         if (last_thread_id.empty ()) {
388             notmuch->last_thread_id = 0;
389         } else {
390             const char *str;
391             char *end;
392
393             str = last_thread_id.c_str ();
394             notmuch->last_thread_id = strtoull (str, &end, 16);
395             if (*end != '\0')
396                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
397         }
398
399         /* Get current highest revision number. */
400         last_mod = notmuch->xapian_db->get_value_upper_bound (
401             NOTMUCH_VALUE_LAST_MOD);
402         if (last_mod.empty ())
403             notmuch->revision = 0;
404         else
405             notmuch->revision = Xapian::sortable_unserialise (last_mod);
406         notmuch->uuid = talloc_strdup (
407             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
408
409         notmuch->query_parser = new Xapian::QueryParser;
410         notmuch->term_gen = new Xapian::TermGenerator;
411         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
412         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
413         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP,
414                                                                      "date:");
415         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD,
416                                                                               "lastmod:");
417         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
418         notmuch->query_parser->set_database (*notmuch->xapian_db);
419         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
420         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
421         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
422         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
423         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
424
425         /* Configuration information is needed to set up query parser */
426         status = _notmuch_config_load_from_database (notmuch);
427         if (status)
428             goto DONE;
429
430         if (key_file)
431             status = _notmuch_config_load_from_file (notmuch, key_file);
432         if (status)
433             goto DONE;
434
435         status = _choose_dir (notmuch, profile,
436                               NOTMUCH_CONFIG_HOOK_DIR,
437                               "XDG_CONFIG_HOME",
438                               ".config",
439                               "hooks",
440                               &message);
441         if (status)
442             goto DONE;
443
444         status = _choose_dir (notmuch, profile,
445                               NOTMUCH_CONFIG_BACKUP_DIR,
446                               "XDG_DATA_HOME",
447                               ".local/share",
448                               "backups",
449                               &message);
450         if (status)
451             goto DONE;
452         status = _notmuch_config_load_defaults (notmuch);
453         if (status)
454             goto DONE;
455
456         status = _notmuch_database_setup_standard_query_fields (notmuch);
457         if (status)
458             goto DONE;
459
460         status = _notmuch_database_setup_user_query_fields (notmuch);
461         if (status)
462             goto DONE;
463
464     } catch (const Xapian::Error &error) {
465         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
466                                  error.get_msg ().c_str ()));
467         notmuch_database_destroy (notmuch);
468         notmuch = NULL;
469         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
470     }
471   DONE:
472     if (message_ptr)
473         *message_ptr = message;
474     return status;
475 }
476
477 notmuch_status_t
478 notmuch_database_open_with_config (const char *database_path,
479                                    notmuch_database_mode_t mode,
480                                    const char *config_path,
481                                    const char *profile,
482                                    notmuch_database_t **database,
483                                    char **status_string)
484 {
485     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
486     void *local = talloc_new (NULL);
487     notmuch_database_t *notmuch = NULL;
488     char *message = NULL;
489     GKeyFile *key_file = NULL;
490     bool split = false;
491
492     _init_libs ();
493
494     notmuch = _alloc_notmuch ();
495     if (! notmuch) {
496         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
497         goto DONE;
498     }
499
500     if ((status = _choose_database_path (local, config_path, profile,
501                                          &key_file, &database_path, &split,
502                                          &message)))
503         goto DONE;
504
505     status = _db_dir_exists (database_path, &message);
506     if (status)
507         goto DONE;
508
509     _set_database_path (notmuch, database_path);
510
511     status = _notmuch_choose_xapian_path (notmuch, database_path,
512                                           &notmuch->xapian_path, &message);
513     if (status)
514         goto DONE;
515
516     status = _finish_open (notmuch, profile, mode, key_file, &message);
517
518   DONE:
519     talloc_free (local);
520
521     if (key_file)
522         g_key_file_free (key_file);
523
524     if (message) {
525         if (status_string)
526             *status_string = message;
527         else
528             free (message);
529     }
530
531     if (database)
532         *database = notmuch;
533     else
534         talloc_free (notmuch);
535
536     if (notmuch)
537         notmuch->open = true;
538
539     return status;
540 }
541
542 notmuch_status_t
543 notmuch_database_create (const char *path, notmuch_database_t **database)
544 {
545     char *status_string = NULL;
546     notmuch_status_t status;
547
548     status = notmuch_database_create_verbose (path, database,
549                                               &status_string);
550
551     if (status_string) {
552         fputs (status_string, stderr);
553         free (status_string);
554     }
555
556     return status;
557 }
558
559 notmuch_status_t
560 notmuch_database_create_verbose (const char *path,
561                                  notmuch_database_t **database,
562                                  char **status_string)
563 {
564     return notmuch_database_create_with_config (path, "", NULL, database, status_string);
565 }
566
567 notmuch_status_t
568 notmuch_database_create_with_config (const char *database_path,
569                                      const char *config_path,
570                                      const char *profile,
571                                      notmuch_database_t **database,
572                                      char **status_string)
573 {
574     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
575     notmuch_database_t *notmuch = NULL;
576     const char *notmuch_path = NULL;
577     char *message = NULL;
578     GKeyFile *key_file = NULL;
579     void *local = talloc_new (NULL);
580     int err;
581     bool split = false;
582
583     _init_libs ();
584
585     notmuch = _alloc_notmuch ();
586     if (! notmuch) {
587         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
588         goto DONE;
589     }
590
591     _init_libs ();
592
593     if ((status = _choose_database_path (local, config_path, profile,
594                                          &key_file, &database_path, &split,
595                                          &message)))
596         goto DONE;
597
598     status = _db_dir_exists (database_path, &message);
599     if (status)
600         goto DONE;
601
602     _set_database_path (notmuch, database_path);
603
604     if (key_file && ! split) {
605         char *mail_root = canonicalize_file_name (
606             g_key_file_get_value (key_file, "database", "mail_root", NULL));
607         char *db_path = canonicalize_file_name (database_path);
608
609         split = (mail_root && (0 != strcmp (mail_root, db_path)));
610
611         free (mail_root);
612         free (db_path);
613     }
614
615     if (split) {
616         notmuch_path = database_path;
617     } else {
618         if (! (notmuch_path = talloc_asprintf (local, "%s/%s", database_path, ".notmuch"))) {
619             status = NOTMUCH_STATUS_OUT_OF_MEMORY;
620             goto DONE;
621         }
622
623         err = mkdir (notmuch_path, 0755);
624         if (err) {
625             if (errno == EEXIST) {
626                 status = NOTMUCH_STATUS_DATABASE_EXISTS;
627                 talloc_free (notmuch);
628                 notmuch = NULL;
629             } else {
630                 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
631                                          notmuch_path, strerror (errno)));
632                 status = NOTMUCH_STATUS_FILE_ERROR;
633             }
634             goto DONE;
635         }
636     }
637
638     if (! (notmuch->xapian_path = talloc_asprintf (notmuch, "%s/%s", notmuch_path, "xapian"))) {
639         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
640         goto DONE;
641     }
642
643     status = _trial_open (notmuch->xapian_path, &message);
644     if (status == NOTMUCH_STATUS_SUCCESS) {
645         notmuch_database_destroy (notmuch);
646         notmuch = NULL;
647         status = NOTMUCH_STATUS_DATABASE_EXISTS;
648         goto DONE;
649     }
650
651     status = _finish_open (notmuch,
652                            profile,
653                            NOTMUCH_DATABASE_MODE_READ_WRITE,
654                            key_file,
655                            &message);
656     if (status)
657         goto DONE;
658
659     /* Upgrade doesn't add these feature to existing databases, but
660      * new databases have them. */
661     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
662     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
663     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
664
665     status = notmuch_database_upgrade (notmuch, NULL, NULL);
666     if (status) {
667         notmuch_database_close (notmuch);
668         notmuch = NULL;
669     }
670
671   DONE:
672     talloc_free (local);
673
674     if (key_file)
675         g_key_file_free (key_file);
676
677     if (message) {
678         if (status_string)
679             *status_string = message;
680         else
681             free (message);
682     }
683     if (database)
684         *database = notmuch;
685     else
686         talloc_free (notmuch);
687     return status;
688 }
689
690 notmuch_status_t
691 notmuch_database_reopen (notmuch_database_t *notmuch,
692                          notmuch_database_mode_t new_mode)
693 {
694     notmuch_database_mode_t cur_mode = _notmuch_database_mode (notmuch);
695
696     if (notmuch->xapian_db == NULL) {
697         _notmuch_database_log (notmuch, "Cannot reopen closed or nonexistent database\n");
698         return NOTMUCH_STATUS_ILLEGAL_ARGUMENT;
699     }
700
701     try {
702         if (cur_mode == new_mode &&
703             new_mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
704             notmuch->xapian_db->reopen ();
705         } else {
706             notmuch->xapian_db->close ();
707
708             delete notmuch->xapian_db;
709             notmuch->xapian_db = NULL;
710             /* no need to free the same object twice */
711             notmuch->writable_xapian_db = NULL;
712
713             if (new_mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
714                 notmuch->writable_xapian_db = new Xapian::WritableDatabase (notmuch->xapian_path,
715                                                                             DB_ACTION);
716                 notmuch->xapian_db = notmuch->writable_xapian_db;
717             } else {
718                 notmuch->xapian_db = new Xapian::Database (notmuch->xapian_path,
719                                                            DB_ACTION);
720             }
721         }
722     } catch (const Xapian::Error &error) {
723         if (! notmuch->exception_reported) {
724             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
725                                    error.get_msg ().c_str ());
726             notmuch->exception_reported = true;
727         }
728         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
729     }
730
731     notmuch->view++;
732     notmuch->open = true;
733     return NOTMUCH_STATUS_SUCCESS;
734 }