chiark / gitweb /
create users.db (but don't do anythin with it). tighter db permissions
[disorder] / server / dump.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 #include <config.h>
22 #include "types.h"
23
24 #include <getopt.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <pcre.h>
30 #include <unistd.h>
31 #include <db.h>
32 #include <fcntl.h>
33
34 #include "configuration.h"
35 #include "syscalls.h"
36 #include "log.h"
37 #include "client.h"
38 #include "sink.h"
39 #include "mem.h"
40 #include "defs.h"
41 #include "printf.h"
42 #include "kvp.h"
43 #include "vector.h"
44 #include "inputline.h"
45 #include "trackdb.h"
46 #include "trackdb-int.h"
47 #include "charset.h"
48
49 static const struct option options[] = {
50   { "help", no_argument, 0, 'h' },
51   { "version", no_argument, 0, 'V' },
52   { "config", required_argument, 0, 'c' },
53   { "dump", no_argument, 0, 'd' },
54   { "undump", no_argument, 0, 'u' },
55   { "debug", no_argument, 0, 'D' },
56   { "recover", no_argument, 0, 'r' },
57   { "recover-fatal", no_argument, 0, 'R' },
58   { "trackdb", no_argument, 0, 't' },
59   { "searchdb", no_argument, 0, 's' },
60   { "recompute-aliases", no_argument, 0, 'a' },
61   { "remove-pathless", no_argument, 0, 'P' },
62   { 0, 0, 0, 0 }
63 };
64
65 /* display usage message and terminate */
66 static void help(void) {
67   xprintf("Usage:\n"
68           "  disorder-dump [OPTIONS] --dump|--undump PATH\n"
69           "  disorder-dump [OPTIONS] --recompute-aliases\n"
70           "Options:\n"
71           "  --help, -h               Display usage message\n"
72           "  --version, -V            Display version number\n"
73           "  --config PATH, -c PATH   Set configuration file\n"
74           "  --dump, -d               Dump state to PATH\n"
75           "  --undump, -u             Restore state from PATH\n"
76           "  --recover, -r            Run database recovery\n"
77           "  --recompute-aliases, -a  Recompute aliases\n"
78           "  --remove-pathless, -P    Remove pathless tracks\n"
79           "  --debug                  Debug mode\n");
80   xfclose(stdout);
81   exit(0);
82 }
83
84 /* display version number and terminate */
85 static void version(void) {
86   xprintf("%s", disorder_version_string);
87   xfclose(stdout);
88   exit(0);
89 }
90
91 /* dump prefs to FP, return nonzero on error */
92 static void do_dump(FILE *fp, const char *tag,
93                     int tracksdb, int searchdb) {
94   DBC *cursor = 0;
95   DB_TXN *tid;
96   struct sink *s = sink_stdio(tag, fp);
97   int err;
98   DBT k, d;
99
100   for(;;) {
101     tid = trackdb_begin_transaction();
102     if(fseek(fp, 0, SEEK_SET) < 0)
103       fatal(errno, "error calling fseek");
104     if(fflush(fp) < 0)
105       fatal(errno, "error calling fflush");
106     if(ftruncate(fileno(fp), 0) < 0)
107       fatal(errno, "error calling ftruncate");
108     if(fprintf(fp, "V%c\n", (tracksdb || searchdb) ? '1' : '0') < 0)
109       fatal(errno, "error writing to %s", tag);
110     /* dump the preferences */
111     cursor = trackdb_opencursor(trackdb_prefsdb, tid);
112     err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
113                         DB_FIRST);
114     while(err == 0) {
115       if(fputc('P', fp) < 0
116          || urlencode(s, k.data, k.size)
117          || fputc('\n', fp) < 0
118          || urlencode(s, d.data, d.size)
119          || fputc('\n', fp) < 0)
120         fatal(errno, "error writing to %s", tag);
121       err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
122                           DB_NEXT);
123     }
124     if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }
125     cursor = 0;
126
127     /* dump the global preferences */
128     cursor = trackdb_opencursor(trackdb_globaldb, tid);
129     err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
130                         DB_FIRST);
131     while(err == 0) {
132       if(fputc('G', fp) < 0
133          || urlencode(s, k.data, k.size)
134          || fputc('\n', fp) < 0
135          || urlencode(s, d.data, d.size)
136          || fputc('\n', fp) < 0)
137         fatal(errno, "error writing to %s", tag);
138       err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
139                           DB_NEXT);
140     }
141     if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }
142     cursor = 0;
143     
144     /* dump the users */
145     cursor = trackdb_opencursor(trackdb_usersdb, tid);
146     err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
147                         DB_FIRST);
148     while(err == 0) {
149       if(fputc('U', fp) < 0
150          || urlencode(s, k.data, k.size)
151          || fputc('\n', fp) < 0
152          || urlencode(s, d.data, d.size)
153          || fputc('\n', fp) < 0)
154         fatal(errno, "error writing to %s", tag);
155       err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
156                           DB_NEXT);
157     }
158     if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }
159     cursor = 0;
160     
161     if(tracksdb) {
162       cursor = trackdb_opencursor(trackdb_tracksdb, tid);
163       err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
164                           DB_FIRST);
165       while(err == 0) {
166         if(fputc('T', fp) < 0
167            || urlencode(s, k.data, k.size)
168            || fputc('\n', fp) < 0
169            || urlencode(s, d.data, d.size)
170            || fputc('\n', fp) < 0)
171           fatal(errno, "error writing to %s", tag);
172         err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
173                             DB_NEXT);
174       }
175       if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }
176       cursor = 0;
177     }
178
179     if(searchdb) {
180       cursor = trackdb_opencursor(trackdb_searchdb, tid);
181       err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
182                           DB_FIRST);
183       while(err == 0) {
184         if(fputc('S', fp) < 0
185            || urlencode(s, k.data, k.size)
186            || fputc('\n', fp) < 0
187            || urlencode(s, d.data, d.size)
188            || fputc('\n', fp) < 0)
189           fatal(errno, "error writing to %s", tag);
190         err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
191                             DB_NEXT);
192       }
193       if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }      cursor = 0;
194     }
195
196     if(fputs("E\n", fp) < 0) fatal(errno, "error writing to %s", tag);
197     if(err == DB_LOCK_DEADLOCK) {
198       error(0, "c->c_get: %s", db_strerror(err));
199       goto fail;
200     }
201     if(err && err != DB_NOTFOUND)
202       fatal(0, "cursor->c_get: %s", db_strerror(err));
203     if(trackdb_closecursor(cursor)) { cursor = 0; goto fail; }
204     break;
205 fail:
206     trackdb_closecursor(cursor);
207     cursor = 0;
208     info("aborting transaction and retrying dump");
209     trackdb_abort_transaction(tid);
210   }
211   trackdb_commit_transaction(tid);
212   if(fflush(fp) < 0) fatal(errno, "error writing to %s", tag);
213   /* caller might not be paranoid so we are paranoid on their behalf */
214   if(fsync(fileno(fp)) < 0) fatal(errno, "error syncing %s", tag);
215 }
216
217 /* delete all aliases prefs, return 0 or DB_LOCK_DEADLOCK */
218 static int remove_aliases(DB_TXN *tid, int remove_pathless) {
219   DBC *cursor;
220   int err;
221   DBT k, d;
222   struct kvp *data;
223   int alias, pathless;
224
225   info("removing aliases");
226   cursor = trackdb_opencursor(trackdb_tracksdb, tid);
227   if((err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
228                           DB_FIRST)) == DB_LOCK_DEADLOCK) {
229     error(0, "cursor->c_get: %s", db_strerror(err));
230     goto done;
231   }
232   while(err == 0) {
233     data = kvp_urldecode(d.data, d.size);
234     alias = !!kvp_get(data, "_alias_for");
235     pathless = !kvp_get(data, "_path");
236     if(pathless && !remove_pathless)
237       info("no _path for %s", utf82mb(xstrndup(k.data, k.size)));
238     if(alias || (remove_pathless && pathless)) {
239       switch(err = cursor->c_del(cursor, 0)) {
240       case 0: break;
241       case DB_LOCK_DEADLOCK:
242         error(0, "cursor->c_get: %s", db_strerror(err));
243         goto done;
244       default:
245         fatal(0, "cursor->c_del: %s", db_strerror(err));
246       }
247     }
248     err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d), DB_NEXT);
249   }
250   if(err == DB_LOCK_DEADLOCK) {
251     error(0, "cursor operation: %s", db_strerror(err));
252     goto done;
253   }
254   if(err != DB_NOTFOUND) fatal(0, "cursor->c_get: %s", db_strerror(err));
255   err = 0;
256 done:
257   if(trackdb_closecursor(cursor) && !err) err = DB_LOCK_DEADLOCK;
258   return err;
259 }
260
261 /* truncate (i.e. empty) a database, return 0 or DB_LOCK_DEADLOCK */
262 static int truncdb(DB_TXN *tid, DB *db) {
263   int err;
264   u_int32_t count;
265
266   switch(err = db->truncate(db, tid, &count, 0)) {
267   case 0: break;
268   case DB_LOCK_DEADLOCK:
269     error(0, "db->truncate: %s", db_strerror(err));
270     break;
271   default:
272     fatal(0, "db->truncate: %s", db_strerror(err));
273   }
274   return err;
275 }
276
277 /* read a DBT from FP, return 0 on success or -1 on input error */
278 static int undump_dbt(FILE *fp, const char *tag, DBT *dbt) {
279   char *s;
280   struct dynstr d;
281
282   if(inputline(tag, fp, &s, '\n')) return -1;
283   dynstr_init(&d);
284   if(urldecode(sink_dynstr(&d), s, strlen(s)))
285     fatal(0, "invalid URL-encoded data in %s", tag);
286   dbt->data = d.vec;
287   dbt->size = d.nvec;
288   return 0;
289 }
290
291 /* undump from FP, return 0 or DB_LOCK_DEADLOCK */
292 static int undump_from_fp(DB_TXN *tid, FILE *fp, const char *tag) {
293   int err, c;
294   DBT k, d;
295   const char *which_name;
296   DB *which_db;
297
298   info("undumping");
299   if(fseek(fp, 0, SEEK_SET) < 0)
300     fatal(errno, "error calling fseek on %s", tag);
301   if((err = truncdb(tid, trackdb_prefsdb))) return err;
302   if((err = truncdb(tid, trackdb_globaldb))) return err;
303   if((err = truncdb(tid, trackdb_searchdb))) return err;
304   if((err = truncdb(tid, trackdb_tagsdb))) return err;
305   if((err = truncdb(tid, trackdb_usersdb))) return err;
306   c = getc(fp);
307   while(!ferror(fp) && !feof(fp)) {
308     switch(c) {
309     case 'V':
310       c = getc(fp);
311       if(c != '0')
312         fatal(0, "unknown version '%c'", c);
313       break;
314     case 'E':
315       return 0;
316     case 'P':
317     case 'G':
318     case 'U':
319       switch(c) {
320       case 'P':
321         which_db = trackdb_prefsdb;
322         which_name = "prefs.db";
323         break;
324       case 'G':
325         which_db = trackdb_globaldb;
326         which_name = "global.db";
327         break;
328       case 'U':
329         which_db = trackdb_usersdb;
330         which_name = "users.db";
331         break;
332       default:
333         abort();
334       }
335       if(undump_dbt(fp, tag, prepare_data(&k))
336          || undump_dbt(fp, tag, prepare_data(&d)))
337         break;
338       switch(err = trackdb_prefsdb->put(which_db, tid, &k, &d, 0)) {
339       case 0:
340         break;
341       case DB_LOCK_DEADLOCK:
342         error(0, "error updating %s: %s", which_name, db_strerror(err));
343         return err;
344       default:
345         fatal(0, "error updating %s: %s", which_name, db_strerror(err));
346       }
347       break;
348     case 'T':
349     case 'S':
350       if(undump_dbt(fp, tag, prepare_data(&k))
351          || undump_dbt(fp, tag, prepare_data(&d)))
352         break;
353       /* We don't restore the tracks.db or search.db entries, instead
354        * we recompute them */
355       break;
356     case '\n':
357       break;
358     }
359     c = getc(fp);
360   }
361   if(ferror(fp))
362     fatal(errno, "error reading %s", tag);
363   else
364     fatal(0, "unexpected EOF reading %s", tag);
365   return 0;
366 }
367
368 /* recompute aliases and search database from prefs, return 0 or
369  * DB_LOCK_DEADLOCK */
370 static int recompute_aliases(DB_TXN *tid) {
371   DBC *cursor;
372   DBT k, d;
373   int err;
374   struct kvp *data;
375   const char *path, *track;
376
377   info("recomputing aliases");
378   cursor = trackdb_opencursor(trackdb_tracksdb, tid);
379   if((err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
380                           DB_FIRST)) == DB_LOCK_DEADLOCK) goto done;
381   while(err == 0) {
382     data = kvp_urldecode(d.data, d.size);
383     track = xstrndup(k.data, k.size);
384     if(!kvp_get(data, "_alias_for")) {
385       if(!(path = kvp_get(data, "_path")))
386         error(0, "%s is not an alias but has no path", utf82mb(track));
387       else
388         if((err = trackdb_notice_tid(track, path, tid)) == DB_LOCK_DEADLOCK)
389           goto done;
390     }
391     err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
392                         DB_NEXT);
393   }
394   switch(err) {
395   case 0:
396     break;
397   case DB_NOTFOUND:
398     err = 0;
399     break;
400   case DB_LOCK_DEADLOCK:
401     break;
402   default:
403     fatal(0, "cursor->c_get: %s", db_strerror(err));
404   }
405 done:
406   if(trackdb_closecursor(cursor) && !err) err = DB_LOCK_DEADLOCK;
407   return err;
408 }
409
410 /* restore prefs from FP */
411 static void do_undump(FILE *fp, const char *tag, int remove_pathless) {
412   DB_TXN *tid;
413
414   for(;;) {
415     tid = trackdb_begin_transaction();
416     if(remove_aliases(tid, remove_pathless)
417        || undump_from_fp(tid, fp, tag)
418        || recompute_aliases(tid)) goto fail;
419     break;
420 fail:
421     info("aborting transaction and retrying undump");
422     trackdb_abort_transaction(tid);
423   }
424   info("committing undump");
425   trackdb_commit_transaction(tid);
426 }
427
428 /* just recompute alisaes */
429 static void do_recompute(int remove_pathless) {
430   DB_TXN *tid;
431
432   for(;;) {
433     tid = trackdb_begin_transaction();
434     if(remove_aliases(tid, remove_pathless)
435        || recompute_aliases(tid)) goto fail;
436     break;
437 fail:
438     info("aborting transaction and retrying recomputation");
439     trackdb_abort_transaction(tid);
440   }
441   info("committing recomputed aliases");
442   trackdb_commit_transaction(tid);
443 }
444
445 int main(int argc, char **argv) {
446   int n, dump = 0, undump = 0, recover = TRACKDB_NO_RECOVER, recompute = 0;
447   int tracksdb = 0, searchdb = 0, remove_pathless = 0, fd;
448   const char *path;
449   char *tmp;
450   FILE *fp;
451
452   mem_init();
453   while((n = getopt_long(argc, argv, "hVc:dDutsrRaP", options, 0)) >= 0) {
454     switch(n) {
455     case 'h': help();
456     case 'V': version();
457     case 'c': configfile = optarg; break;
458     case 'd': dump = 1; break;
459     case 'u': undump = 1; break;
460     case 'D': debugging = 1; break;
461     case 't': tracksdb = 1; break;
462     case 's': searchdb = 1; break;
463     case 'r': recover = TRACKDB_NORMAL_RECOVER;
464     case 'R': recover = TRACKDB_FATAL_RECOVER;
465     case 'a': recompute = 1; break;
466     case 'P': remove_pathless = 1; break;
467     default: fatal(0, "invalid option");
468     }
469   }
470   if(dump + undump + recompute != 1)
471     fatal(0, "choose exactly one of --dump, --undump or --recompute-aliases");
472   if((undump || recompute) && (tracksdb || searchdb))
473     fatal(0, "--trackdb and --searchdb with --undump or --recompute-aliases");
474   if(recompute) {
475     if(optind != argc)
476       fatal(0, "--recompute-aliases does not take a filename");
477     path = 0;
478   } else {
479     if(optind >= argc)
480       fatal(0, "missing dump file name");
481     if(optind + 1 < argc)
482       fatal(0, "specify only a dump file name");
483     path = argv[optind];
484   }
485   if(config_read(0)) fatal(0, "cannot read configuration");
486   trackdb_init(recover|TRACKDB_MAY_CREATE);
487   trackdb_open(TRACKDB_NO_UPGRADE);
488   if(dump) {
489     /* We write to a temporary file and rename into place.  We make
490      * sure the permissions are tight from the start. */
491     byte_xasprintf(&tmp, "%s.%lx.tmp", path, (unsigned long)getpid());
492     if((fd = open(tmp, O_CREAT|O_TRUNC|O_WRONLY, 0600)) < 0)
493       fatal(errno, "error opening %s", tmp);
494     if(!(fp = fdopen(fd, "w")))
495       fatal(errno, "fdopen on %s", tmp);
496     do_dump(fp, tmp, tracksdb, searchdb);
497     if(fclose(fp) < 0) fatal(errno, "error closing %s", tmp);
498     if(rename(tmp, path) < 0)
499       fatal(errno, "error renaming %s to %s", tmp, path);
500   } else if(undump) {
501     /* the databases or logfiles might end up with wrong permissions
502      * if new ones are created */
503     if(getuid() == 0) info("you might need to chown database files");
504     if(!(fp = fopen(path, "r"))) fatal(errno, "error opening %s", path);
505     do_undump(fp, path, remove_pathless);
506     xfclose(fp);
507   } else if(recompute) {
508     do_recompute(remove_pathless);
509   }
510   trackdb_close();
511   trackdb_deinit();
512   return 0;
513 }
514
515 /*
516 Local Variables:
517 c-basic-offset:2
518 comment-column:40
519 End:
520 */