3 #include "chiark_tcl_cdb.h"
8 /*---------- Forward declarations ----------*/
12 /*---------- Useful routines ----------*/
14 static void maybe_close(int fd) {
19 rc= cht_posixerr(ip, errno, "failed to " m); goto x_rc; \
22 /*---------- Pathbuf ----------*/
24 typedef struct Pathbuf {
30 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
32 pb->buf= TALLOC(l + 4);
33 memcpy(pb->buf, pathb, l);
37 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
38 assert(strlen(suffix) <= MAX_SUFFIX);
39 strcpy(pb->sfx, suffix);
42 static void pathbuf_free(Pathbuf *pb) {
47 /*---------- Our hash table ----------*/
49 typedef struct HashTable {
51 Byte padding[128]; /* allow for expansion by Tcl, urgh */
55 typedef struct HashValue {
60 static HashValue *htv_prep(int len) {
62 hd= TALLOC((hd->data - (Byte*)hd) + len);
65 static Byte *htv_fillptr(HashValue *hd) {
68 static void htv_fill(HashValue *hd, const Byte *data) {
69 memcpy(hd->data, data, hd->len);
72 static void ht_setup(HashTable *ht) {
73 Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
75 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
79 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
80 if (!new) TFREE(Tcl_GetHashValue(he));
81 Tcl_SetHashValue(he, val_eat);
82 /* eats the value since the data structure owns the memory */
84 static void ht_maybeupdate(HashTable *ht, const char *key,
86 /* like ht_update except does not overwrite existing values */
90 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
91 if (!new) { TFREE(val_eat); return; }
92 Tcl_SetHashValue(he, val_eat);
95 static int ht_forall(HashTable *ht,
96 int (*fn)(const char *key, const HashValue *val,
97 struct ht_forall_ctx *ctx),
98 struct ht_forall_ctx *ctx) {
99 /* Returns first nonzero value returned by any call to fn, or 0. */
106 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
108 he= Tcl_NextHashEntry(&sp)) {
109 val= Tcl_GetHashValue(he);
110 if (!val->len) continue;
112 key= Tcl_GetHashKey(&ht->t, he);
114 r= fn(key, val, ctx);
120 static void ht_destroy(HashTable *ht) {
124 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
126 he= Tcl_NextHashEntry(&sp)) {
127 TFREE(Tcl_GetHashValue(he));
129 Tcl_DeleteHashTable(&ht->t);
132 /*---------- Rw data structure ----------*/
135 int ix, autocompact, maxage;
136 fixme implement maxage during compact;
138 struct cdb cdb; /* valid iff cdb_fd >= 0 */
139 off_t cdb_bytes; /* valid iff cdb_fd >= 0 */
142 Pathbuf pbsome, pbother;
146 static int rw_close(Tcl_Interp *ip, Rw *rw) {
150 ht_destroy(&rw->logincore);
151 maybe_close(rw->cdb_fd);
152 maybe_close(rw->lock_fd);
155 r= fclose(rw->logfile);
156 if (r && ip) { rc= cht_posixerr(ip, errno, "data loss! failed to"
157 " fclose logfile during untidy close"); }
160 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
165 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
166 const IdDataSpec cdbtcl_rwdatabases= {
167 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
170 /*---------- File handling ----------*/
172 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
173 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
174 * on error, and must be closed by the caller. */
179 um= umask(~(mode_t)0);
182 lockmode= 0666 & ~((um & 0444)>>1);
183 /* Remove r where umask would remove w;
184 * eg umask intending 0664 here gives 0660 */
186 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
188 return cht_posixerr(ip, errno, "could not open/create lockfile");
191 fl.l_whence= SEEK_SET;
196 r= fcntl(*lockfd_r, F_SETLK, &fl);
198 if (errno == EACCES || errno == EAGAIN)
199 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
200 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
205 /*---------- Log reading ----------*/
207 static int readlognum(FILE *f, int delim, int *num_r) {
209 char numbuf[20], *p, *ep;
214 c= getc(f); if (c==EOF) return -2;
215 if (c == delim) break;
216 if (!isdigit((unsigned char)c)) return -2;
218 if (p == numbuf+sizeof(numbuf)) return -2;
220 if (p == numbuf) return -2;
223 errno=0; ul= strtoul(numbuf, &ep, 10);
224 if (*ep || errno || ul >= INT_MAX/2) return -2;
229 static int readstorelogrecord(FILE *f, HashTable *ht,
230 void (*updatefn)(HashTable*, const char*,
235 * -2 corrupt or error
236 * -3 got newline indicating end
244 if (c==EOF) { if (feof(f)) return -1; return -2; }
245 if (c=='\n') return -3;
246 if (c!='+') return -2;
248 rc= readlognum(f, ',', &keylen); if (rc) return rc;
249 rc= readlognum(f, ':', &vallen); if (rc) return rc;
251 key= TALLOC(keylen+1);
252 val= htv_prep(vallen);
254 r= fread(key, 1,keylen, f);
255 if (r!=keylen) goto x2_free_keyval;
256 if (memchr(key,0,keylen)) goto x2_free_keyval;
259 c= getc(f); if (c!='-') goto x2_free_keyval;
260 c= getc(f); if (c!='>') goto x2_free_keyval;
262 r= fread(htv_fillptr(val), 1,vallen, f);
263 if (r!=vallen) goto x2_free_keyval;
265 updatefn(ht, key, val);
275 /*---------- Creating ----------*/
277 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
279 static const char *const toremoves[]= {
280 ".main", ".cdb", ".log", ".tmp", 0
284 int lock_fd=-1, fd=-1, rc, r;
285 const char *const *toremove;
287 pathbuf_init(&pb, pathb);
288 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
290 fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
291 if (fd <= 0) PE("create new database file");
293 for (toremove=toremoves; *toremove; toremove++) {
294 r= remove(*toremove);
295 if (r && errno != ENOENT)
296 PE("delete possible spurious file during creation");
303 maybe_close(lock_fd);
308 /*---------- Info callbacks ----------*/
310 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
311 const char *arg2fmt, const char *arg3, va_list al) {
315 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
316 const char *arg2fmt, const char *arg3, ...) {
320 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
325 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
326 const char *arg2fmt, ...) {
329 va_start(al, arg2fmt);
330 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
335 /*---------- Opening ----------*/
337 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
338 Tcl_Obj *on_info, int maxage, void **result) {
339 const Cdbwr_SubCommand *subcmd= cd;
340 int r, rc, mainfd=-1;
343 off_t logrecstart, logjunkpos;
345 rw= TALLOC(sizeof(*rw));
346 ht_setup(&rw->logincore);
347 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
349 pathbuf_init(&rw->pbsome, pathb);
350 pathbuf_init(&rw->pbother, pathb);
353 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
354 if (mainfd<0) PE("open exist3ing database file .main");
355 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
357 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
358 rw->mainsz= stab.st_size;
360 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
361 if (rw->cdb_fd >=0) {
362 r= cdb_init(&rw->cdb, rw->cdb_fd);
364 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
365 close(rw->cdb_fd); rw->cdb_fd= -1; goto x_rc;
367 } else if (errno == ENOENT) {
369 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
370 " .cdb must have been accidentally deleted!",
379 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
381 if (errno != ENOENT) PE("failed to open .log during open");
382 rw->logfile= fopen(rw->pbsome.buf, "w");
383 if (!rw->logfile) PE("create .log during (clean) open");
384 } else { /* rw->logfile */
385 r= fstat(fileno(rw->logfile), &stab);
386 if (r==-1) PE("fstat .log during open");
387 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
388 (unsigned long)stab.st_size);
392 logrecstart= ftello(rw->logfile);
393 if (logrecstart < 0) PE("ftello .log during (dirty) open");
394 r= readstorelogrecord(rw->logfile, &rw->logincore, ht_update);
395 if (ferror(rw->logfile)) {
396 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
401 } else if (r==-2 || r==-3) {
403 logjunkpos= ftello(rw->logfile);
404 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
406 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
407 (unsigned long)logjunkpos, (unsigned long)logrecstart);
409 if (!(subcmd->flags & RWSCF_OKJUNK)) {
410 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
411 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
413 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
414 " (dirty) open, at file position ", buf, (char*)0);
418 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
419 (unsigned long)logjunkpos);
422 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
423 if (r) PE("failed to fseeko .log before junk during dirty open");
425 r= ftruncate(fileno(rw->logfile), logrecstart);
426 if (r) PE("ftruncate .log to chop junk during dirty open");
432 /* now log is positioned for appending and everything is read */
444 /*---------- Compacting ----------*/
446 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsize) {
447 /* creates new .cdb and .main
449 * leaves .log with old data
450 * leaves cdb fd open onto old db
451 * leaves logincore full of crap
454 int cdbfd, cdbmaking;
458 struct ht_forall_ctx {
459 struct cdb_make cdbm;
468 r= fclose(rw->logfile);
469 if (r) { rc= cht_posixerr(ip, errno, "data loss! failed to fclose"
470 " logfile during compact"); goto x_rc; }
473 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
474 logsize, (unsigned long)rw->mainsz);
477 /* merge unsuperseded records from main into hash table */
479 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
480 if (!a.mainfile) PE("failed to open .main for reading during compact");
483 r= readstorelogrecord(a.mainfile, &rw->logincore, ht_maybeupdate);
484 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
485 " .main during compact"); goto x_rc;
489 } else if (r==-1 || r==-2) {
490 errpos= ftello(a.mainfile);
491 if (errpos<0) PE("ftello .main during report of syntax error");
492 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
493 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
494 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
496 Tcl_AppendResult(ip, "syntax error in .main during"
497 " compact, at file position ", buf, (char*)0);
509 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
510 if (cdbfd<0) PE("create .tmp for new cdb during compact");
512 r= cdb_make_start(&a.cdbm, cdbfd);
513 if (r) PE("cdb_make_start during compact");
516 r= ht_forall(&rw->logincore, addto_cdb, &addctx);
517 if (r) PE("cdb_make_add during compact");
519 r= cdb_make_finish(&a.cdbm, cdbfd);
520 if(r) PE("cdb_make_finish during compact");
523 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
524 r= close(cdbfd); if (r) PE("close new cdb during compact");
527 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
528 if (r) PE("install new .cdb during compact");
530 /* create new main */
532 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
533 if (!a.mainfile) PE("create .tmp for new main during compact");
536 r= ht_forall(&rw->logincore, addto_main, a.mainfile);
537 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
538 " during compact"); goto x_rc; }
540 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
541 r= fdatasync(fileno(a.mainfile));
542 if (r) PE("fdatasync new main during compact");
544 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
547 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
548 if (r) PE("install new .main during compact");
552 rc= infocb(ip, rw, "compact-end", "log=%luby main=%luby",
553 logsize, (unsigned long)rw->mainsz);
558 if (mainfile) fclose(mainfile);
559 if (cdbmaking) cdb_make_finish(&a.cdbm, cdbfd);
561 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
564 static void compact_forclose(Tcl_Interp *ip, Rw *rw) {
568 logsz= ftello(rw->logfile);
569 if (logsz < 0) PE("ftello logfile (during tidy close)");
571 rc= compact_core(ip, rw, logsz); if (rc) goto x_rc;
573 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
574 if (r) PE("remove .log (during tidy close)");
577 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
579 int rc, compact_rc, infocb_rc;
581 if (rw->autocompact) compact_rc= compact_forclose(ip, rw);
582 else compact_rc= TCL_OK;
585 infocb_rc= infocb_close(rw);
587 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
588 if (!rc) rc= compact_rc;
589 if (!rc) rc= infocb_rc;
594 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj **result);
595 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value *result);
596 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
597 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);
598 int cht_do_cdbwr_update_quick(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
599 int cht_do_cdbwr_update_quick_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);