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 Tcl_HashEntry *he, struct ht_forall_ctx *ctx),
98 struct ht_forall_ctx *ctx) {
99 /* Returns first positive 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 ----------*/
137 struct cdb cdb; /* valid iff cdb_fd >= 0 */
138 off_t cdb_bytes; /* valid iff cdb_fd >= 0 */
141 Pathbuf pbsome, pbother;
143 ScriptToInvoke on_info, on_mintstamp;
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, "probable 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, Tcl_Obj *on_mintstamp,
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 scriptinv_init(&rw->on_info);
349 scriptinv_init(&rw->on_mintstamp);
350 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
352 pathbuf_init(&rw->pbsome, pathb);
353 pathbuf_init(&rw->pbother, pathb);
357 rc= scriptinv_set(&rw->on_mintstamp, ip, on_mintstamp, 0);
360 rw->on_mintstamp.llength= 0;
363 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
364 if (mainfd<0) PE("open exist3ing database file .main");
365 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
367 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
368 rw->mainsz= stab.st_size;
370 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
371 if (rw->cdb_fd >=0) {
372 r= cdb_init(&rw->cdb, rw->cdb_fd);
374 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
375 close(rw->cdb_fd); rw->cdb_fd= -1; goto x_rc;
377 } else if (errno == ENOENT) {
379 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
380 " .cdb must have been accidentally deleted!",
389 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
391 if (errno != ENOENT) PE("failed to open .log during open");
392 rw->logfile= fopen(rw->pbsome.buf, "w");
393 if (!rw->logfile) PE("create .log during (clean) open");
394 } else { /* rw->logfile */
395 r= fstat(fileno(rw->logfile), &stab);
396 if (r==-1) PE("fstat .log during open");
397 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
398 (unsigned long)stab.st_size);
402 logrecstart= ftello(rw->logfile);
403 if (logrecstart < 0) PE("ftello .log during (dirty) open");
404 r= readstorelogrecord(rw->logfile, &rw->logincore, ht_update);
405 if (ferror(rw->logfile)) {
406 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
411 } else if (r==-2 || r==-3) {
413 logjunkpos= ftello(rw->logfile);
414 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
416 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
417 (unsigned long)logjunkpos, (unsigned long)logrecstart);
419 if (!(subcmd->flags & RWSCF_OKJUNK)) {
420 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
421 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
423 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
424 " (dirty) open, at file position ", buf, (char*)0);
428 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
429 (unsigned long)logjunkpos);
432 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
433 if (r) PE("failed to fseeko .log before junk during dirty open");
435 r= ftruncate(fileno(rw->logfile), logrecstart);
436 if (r) PE("ftruncate .log to chop junk during dirty open");
442 /* now log is positioned for appending and everything is read */
454 /*---------- Compacting ----------*/
456 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsize) {
457 /* creates new .cdb and .main
459 * leaves .log with old data
460 * leaves cdb fd open onto old db
461 * leaves logincore full of crap
464 int cdbfd, cdbmaking;
468 struct ht_forall_ctx {
469 struct cdb_make cdbm;
478 r= fclose(rw->logfile);
479 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
480 " logfile during compact"); goto x_rc; }
483 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
484 logsize, (unsigned long)rw->mainsz);
487 if (rw->on_mintstamp.llength) {
488 rc= cht_scriptinv_invoke_fg(&rw->on_mintstamp, 0,0);
491 Tcl_GetObjResult(ip) fixme do something here
494 /* merge unsuperseded records from main into hash table */
496 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
497 if (!a.mainfile) PE("failed to open .main for reading during compact");
500 r= readstorelogrecord(a.mainfile, &rw->logincore, ht_maybeupdate);
501 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
502 " .main during compact"); goto x_rc;
506 } else if (r==-1 || r==-2) {
507 errpos= ftello(a.mainfile);
508 if (errpos<0) PE("ftello .main during report of syntax error");
509 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
510 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
511 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
513 Tcl_AppendResult(ip, "syntax error in .main during"
514 " compact, at file position ", buf, (char*)0);
526 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
527 if (cdbfd<0) PE("create .tmp for new cdb during compact");
529 r= cdb_make_start(&a.cdbm, cdbfd);
530 if (r) PE("cdb_make_start during compact");
533 r= ht_forall(&rw->logincore, addto_cdb, &addctx);
534 if (r) PE("cdb_make_add during compact");
536 r= cdb_make_finish(&a.cdbm, cdbfd);
537 if(r) PE("cdb_make_finish during compact");
540 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
541 r= close(cdbfd); if (r) PE("close new cdb during compact");
544 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
545 if (r) PE("install new .cdb during compact");
547 /* create new main */
549 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
550 if (!a.mainfile) PE("create .tmp for new main during compact");
553 r= ht_forall(&rw->logincore, addto_main, a.mainfile);
554 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
555 " during compact"); goto x_rc; }
557 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
558 r= fdatasync(fileno(a.mainfile));
559 if (r) PE("fdatasync new main during compact");
561 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
564 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
565 if (r) PE("install new .main during compact");
569 rc= infocb(ip, rw, "compact-end", "log=%luby main=%luby",
570 logsize, (unsigned long)rw->mainsz);
575 if (mainfile) fclose(mainfile);
576 if (cdbmaking) cdb_make_finish(&a.cdbm, cdbfd);
578 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
581 static void compact_forclose(Tcl_Interp *ip, Rw *rw) {
585 logsz= ftello(rw->logfile);
586 if (logsz < 0) PE("ftello logfile (during tidy close)");
588 rc= compact_core(ip, rw, logsz); if (rc) goto x_rc;
590 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
591 if (r) PE("remove .log (during tidy close)");
594 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
596 int rc, compact_rc, infocb_rc;
598 if (rw->autocompact) compact_rc= compact_forclose(ip, rw);
599 else compact_rc= TCL_OK;
602 infocb_rc= infocb_close(rw);
604 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
605 if (!rc) rc= compact_rc;
606 if (!rc) rc= infocb_rc;
611 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj **result);
612 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value *result);
613 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
614 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);
615 int cht_do_cdbwr_update_quick(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
616 int cht_do_cdbwr_update_quick_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);