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 positive value returned by any call to fn, or 0.
100 * If fn returns -1, key is deleted. */
107 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
109 he= Tcl_NextHashEntry(&sp)) {
110 val= Tcl_GetHashValue(he);
111 if (!val->len) continue;
113 key= Tcl_GetHashKey(&ht->t, he);
115 r= fn(key, val, ctx);
121 static void ht_destroy(HashTable *ht) {
125 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
127 he= Tcl_NextHashEntry(&sp)) {
128 TFREE(Tcl_GetHashValue(he));
130 Tcl_DeleteHashTable(&ht->t);
133 /*---------- Rw data structure ----------*/
136 int ix, autocompact, maxage;
137 fixme implement maxage during compact;
139 struct cdb cdb; /* valid iff cdb_fd >= 0 */
140 off_t cdb_bytes; /* valid iff cdb_fd >= 0 */
143 Pathbuf pbsome, pbother;
147 static int rw_close(Tcl_Interp *ip, Rw *rw) {
151 ht_destroy(&rw->logincore);
152 maybe_close(rw->cdb_fd);
153 maybe_close(rw->lock_fd);
156 r= fclose(rw->logfile);
157 if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
158 " fclose logfile during untidy close"); }
161 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
166 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
167 const IdDataSpec cdbtcl_rwdatabases= {
168 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
171 /*---------- File handling ----------*/
173 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
174 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
175 * on error, and must be closed by the caller. */
180 um= umask(~(mode_t)0);
183 lockmode= 0666 & ~((um & 0444)>>1);
184 /* Remove r where umask would remove w;
185 * eg umask intending 0664 here gives 0660 */
187 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
189 return cht_posixerr(ip, errno, "could not open/create lockfile");
192 fl.l_whence= SEEK_SET;
197 r= fcntl(*lockfd_r, F_SETLK, &fl);
199 if (errno == EACCES || errno == EAGAIN)
200 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
201 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
206 /*---------- Log reading ----------*/
208 static int readlognum(FILE *f, int delim, int *num_r) {
210 char numbuf[20], *p, *ep;
215 c= getc(f); if (c==EOF) return -2;
216 if (c == delim) break;
217 if (!isdigit((unsigned char)c)) return -2;
219 if (p == numbuf+sizeof(numbuf)) return -2;
221 if (p == numbuf) return -2;
224 errno=0; ul= strtoul(numbuf, &ep, 10);
225 if (*ep || errno || ul >= INT_MAX/2) return -2;
230 static int readstorelogrecord(FILE *f, HashTable *ht,
231 void (*updatefn)(HashTable*, const char*,
236 * -2 corrupt or error
237 * -3 got newline indicating end
245 if (c==EOF) { if (feof(f)) return -1; return -2; }
246 if (c=='\n') return -3;
247 if (c!='+') return -2;
249 rc= readlognum(f, ',', &keylen); if (rc) return rc;
250 rc= readlognum(f, ':', &vallen); if (rc) return rc;
252 key= TALLOC(keylen+1);
253 val= htv_prep(vallen);
255 r= fread(key, 1,keylen, f);
256 if (r!=keylen) goto x2_free_keyval;
257 if (memchr(key,0,keylen)) goto x2_free_keyval;
260 c= getc(f); if (c!='-') goto x2_free_keyval;
261 c= getc(f); if (c!='>') goto x2_free_keyval;
263 r= fread(htv_fillptr(val), 1,vallen, f);
264 if (r!=vallen) goto x2_free_keyval;
266 updatefn(ht, key, val);
276 /*---------- Creating ----------*/
278 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
280 static const char *const toremoves[]= {
281 ".main", ".cdb", ".log", ".tmp", 0
285 int lock_fd=-1, fd=-1, rc, r;
286 const char *const *toremove;
288 pathbuf_init(&pb, pathb);
289 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
291 fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
292 if (fd <= 0) PE("create new database file");
294 for (toremove=toremoves; *toremove; toremove++) {
295 r= remove(*toremove);
296 if (r && errno != ENOENT)
297 PE("delete possible spurious file during creation");
304 maybe_close(lock_fd);
309 /*---------- Info callbacks ----------*/
311 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
312 const char *arg2fmt, const char *arg3, va_list al) {
316 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
317 const char *arg2fmt, const char *arg3, ...) {
321 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
326 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
327 const char *arg2fmt, ...) {
330 va_start(al, arg2fmt);
331 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
336 /*---------- Opening ----------*/
338 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
339 Tcl_Obj *on_info, int maxage, void **result) {
340 const Cdbwr_SubCommand *subcmd= cd;
341 int r, rc, mainfd=-1;
344 off_t logrecstart, logjunkpos;
346 rw= TALLOC(sizeof(*rw));
347 ht_setup(&rw->logincore);
348 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
350 pathbuf_init(&rw->pbsome, pathb);
351 pathbuf_init(&rw->pbother, pathb);
354 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
355 if (mainfd<0) PE("open exist3ing database file .main");
356 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
358 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
359 rw->mainsz= stab.st_size;
361 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
362 if (rw->cdb_fd >=0) {
363 r= cdb_init(&rw->cdb, rw->cdb_fd);
365 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
366 close(rw->cdb_fd); rw->cdb_fd= -1; goto x_rc;
368 } else if (errno == ENOENT) {
370 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
371 " .cdb must have been accidentally deleted!",
380 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
382 if (errno != ENOENT) PE("failed to open .log during open");
383 rw->logfile= fopen(rw->pbsome.buf, "w");
384 if (!rw->logfile) PE("create .log during (clean) open");
385 } else { /* rw->logfile */
386 r= fstat(fileno(rw->logfile), &stab);
387 if (r==-1) PE("fstat .log during open");
388 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
389 (unsigned long)stab.st_size);
393 logrecstart= ftello(rw->logfile);
394 if (logrecstart < 0) PE("ftello .log during (dirty) open");
395 r= readstorelogrecord(rw->logfile, &rw->logincore, ht_update);
396 if (ferror(rw->logfile)) {
397 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
402 } else if (r==-2 || r==-3) {
404 logjunkpos= ftello(rw->logfile);
405 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
407 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
408 (unsigned long)logjunkpos, (unsigned long)logrecstart);
410 if (!(subcmd->flags & RWSCF_OKJUNK)) {
411 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
412 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
414 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
415 " (dirty) open, at file position ", buf, (char*)0);
419 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
420 (unsigned long)logjunkpos);
423 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
424 if (r) PE("failed to fseeko .log before junk during dirty open");
426 r= ftruncate(fileno(rw->logfile), logrecstart);
427 if (r) PE("ftruncate .log to chop junk during dirty open");
433 /* now log is positioned for appending and everything is read */
445 /*---------- Compacting ----------*/
447 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsize) {
448 /* creates new .cdb and .main
450 * leaves .log with old data
451 * leaves cdb fd open onto old db
452 * leaves logincore full of crap
455 int cdbfd, cdbmaking;
459 struct ht_forall_ctx {
460 struct cdb_make cdbm;
469 r= fclose(rw->logfile);
470 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
471 " logfile during compact"); goto x_rc; }
474 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
475 logsize, (unsigned long)rw->mainsz);
478 /* merge unsuperseded records from main into hash table */
480 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
481 if (!a.mainfile) PE("failed to open .main for reading during compact");
484 r= readstorelogrecord(a.mainfile, &rw->logincore, ht_maybeupdate);
485 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
486 " .main during compact"); goto x_rc;
490 } else if (r==-1 || r==-2) {
491 errpos= ftello(a.mainfile);
492 if (errpos<0) PE("ftello .main during report of syntax error");
493 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
494 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
495 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
497 Tcl_AppendResult(ip, "syntax error in .main during"
498 " compact, at file position ", buf, (char*)0);
510 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
511 if (cdbfd<0) PE("create .tmp for new cdb during compact");
513 r= cdb_make_start(&a.cdbm, cdbfd);
514 if (r) PE("cdb_make_start during compact");
517 r= ht_forall(&rw->logincore, addto_cdb, &addctx);
518 if (r) PE("cdb_make_add during compact");
520 r= cdb_make_finish(&a.cdbm, cdbfd);
521 if(r) PE("cdb_make_finish during compact");
524 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
525 r= close(cdbfd); if (r) PE("close new cdb during compact");
528 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
529 if (r) PE("install new .cdb during compact");
531 /* create new main */
533 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
534 if (!a.mainfile) PE("create .tmp for new main during compact");
537 r= ht_forall(&rw->logincore, addto_main, a.mainfile);
538 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
539 " during compact"); goto x_rc; }
541 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
542 r= fdatasync(fileno(a.mainfile));
543 if (r) PE("fdatasync new main during compact");
545 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
548 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
549 if (r) PE("install new .main during compact");
553 rc= infocb(ip, rw, "compact-end", "log=%luby main=%luby",
554 logsize, (unsigned long)rw->mainsz);
559 if (mainfile) fclose(mainfile);
560 if (cdbmaking) cdb_make_finish(&a.cdbm, cdbfd);
562 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
565 static void compact_forclose(Tcl_Interp *ip, Rw *rw) {
569 logsz= ftello(rw->logfile);
570 if (logsz < 0) PE("ftello logfile (during tidy close)");
572 rc= compact_core(ip, rw, logsz); if (rc) goto x_rc;
574 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
575 if (r) PE("remove .log (during tidy close)");
578 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
580 int rc, compact_rc, infocb_rc;
582 if (rw->autocompact) compact_rc= compact_forclose(ip, rw);
583 else compact_rc= TCL_OK;
586 infocb_rc= infocb_close(rw);
588 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
589 if (!rc) rc= compact_rc;
590 if (!rc) rc= infocb_rc;
595 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj **result);
596 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value *result);
597 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
598 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);
599 int cht_do_cdbwr_update_quick(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
600 int cht_do_cdbwr_update_quick_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);