chiark / gitweb /
cf9a65e11dfe0319068000d145c0f7f5bb501064
[chiark-tcl.git] / cdb / writeable.c
1 /**/
2
3 #include "chiark_tcl_cdb.h"
4
5 #define ftello ftell
6 #define fseeko fseek
7
8 /*---------- Forward declarations ----------*/
9
10 struct ht_forall_ctx;
11
12 /*---------- Useful routines ----------*/
13
14 static void maybe_close(int fd) {
15   if (fd>=0) close(fd);
16 }
17
18 /*==================== Subsystems and subtypes ====================*/
19
20 /*---------- Pathbuf ----------*/
21
22 typedef struct Pathbuf {
23   char *buf, *sfx;
24 } Pathbuf;
25
26 #define MAX_SUFFIX 5
27
28 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
29   int l= strlen(pathb);
30   pb->buf= TALLOC(l + MAX_SUFFIX + 1);
31   memcpy(pb->buf, pathb, l);
32   pb->sfx= pb->buf + l;
33 }
34 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
35   assert(strlen(suffix) <= MAX_SUFFIX);
36   strcpy(pb->sfx, suffix);
37   return pb->buf;
38 }
39 static void pathbuf_free(Pathbuf *pb) {
40   TFREE(pb->buf);
41   pb->buf= 0;
42 }
43
44 /*---------- Our hash table ----------*/
45
46 typedef struct HashTable {
47   Tcl_HashTable t;
48   Byte padding[128]; /* allow for expansion by Tcl, urgh */
49   Byte confound[16];
50 } HashTable;
51
52 typedef struct HashValue {
53   int len;
54   Byte data[1];
55 } HashValue;
56
57 static HashValue *htv_prep(int len) {
58   HashValue *hd;
59   hd= TALLOC((hd->data - (Byte*)hd) + len);
60   hd->len= len;
61   return hd;
62 }  
63 static Byte *htv_fillptr(HashValue *hd) {
64   return hd->data;
65 }
66
67 static void ht_setup(HashTable *ht) {
68   Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
69 }
70 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
71   Tcl_HashEntry *he;
72   int new;
73
74   he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
75   if (!new) TFREE(Tcl_GetHashValue(he));
76   Tcl_SetHashValue(he, val_eat);
77     /* eats the value since the data structure owns the memory */
78 }
79 static void ht_maybeupdate(HashTable *ht, const char *key,
80                            HashValue *val_eat) {
81   /* like ht_update except does not overwrite existing values */
82   Tcl_HashEntry *he;
83   int new;
84
85   he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
86   if (!new) { TFREE(val_eat); return; }
87   Tcl_SetHashValue(he, val_eat);
88 }
89
90 static const HashValue *ht_lookup(HashTable *ht, const char *key) {
91   Tcl_HashEntry *he;
92   
93   he= Tcl_FindHashEntry(&ht->t, key);
94   if (!he) return 0;
95   
96   return Tcl_GetHashValue(he);
97 }
98
99 static int ht_forall(HashTable *ht,
100                      int (*fn)(const char *key, HashValue *val,
101                                struct ht_forall_ctx *ctx),
102                      struct ht_forall_ctx *ctx) {
103   /* Returns first positive value returned by any call to fn, or 0. */
104   Tcl_HashSearch sp;
105   Tcl_HashEntry *he;
106   const char *key;
107   HashValue *val;
108   int r;
109   
110   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
111        he;
112        he= Tcl_NextHashEntry(&sp)) {
113     val= Tcl_GetHashValue(he);
114     if (!val->len) continue;
115
116     key= Tcl_GetHashKey(&ht->t, he);
117     
118     r= fn(key, val, ctx);
119     if (r) return r;
120   }
121   return 0;
122 }
123
124 static void ht_destroy(HashTable *ht) {
125   Tcl_HashSearch sp;
126   Tcl_HashEntry *he;
127   
128   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
129        he;
130        he= Tcl_NextHashEntry(&sp)) {
131     /* ht_forall skips empty (deleted) entries so is no good for this */
132     TFREE(Tcl_GetHashValue(he));
133   }
134   Tcl_DeleteHashTable(&ht->t);
135 }
136
137 /*==================== Existential ====================*/
138
139 /*---------- Rw data structure ----------*/
140
141 typedef struct Rw {
142   int ix, autocompact;
143   int cdb_fd, lock_fd;
144   struct cdb cdb; /* valid iff cdb_fd >= 0 */
145   FILE *logfile;
146   HashTable logincore;
147   Pathbuf pbsome, pbother;
148   off_t mainsz;
149   ScriptToInvoke on_info, on_lexminval;
150 } Rw;
151
152 static int rw_close(Tcl_Interp *ip, Rw *rw) {
153   int rc, r;
154
155   rc= TCL_OK;
156   ht_destroy(&rw->logincore);
157   if (rw->cdb_fd >= 0) cdb_free(&rw->cdb);
158   maybe_close(rw->cdb_fd);
159   maybe_close(rw->lock_fd);
160
161   if (rw->logfile) {
162     r= fclose(rw->logfile);
163     if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
164                                     " fclose logfile during untidy close"); }
165   }
166
167   pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
168   TFREE(rw);
169   return rc;
170 }
171
172 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
173 const IdDataSpec cdbtcl_rwdatabases= {
174   "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
175 };
176
177 /*---------- File handling ----------*/
178
179 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
180   /* *lockfd_r must be -1 on entry.  If may be set to >=0 even
181    * on error, and must be closed by the caller. */
182   mode_t um, lockmode;
183   struct flock fl;
184   int r;
185
186   um= umask(~(mode_t)0);
187   umask(um);
188
189   lockmode= 0666 & ~((um & 0444)>>1);
190   /* Remove r where umask would remove w;
191    * eg umask intending 0664 here gives 0660 */
192   
193   *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDWR|O_CREAT, lockmode);
194   if (*lockfd_r < 0)
195     return cht_posixerr(ip, errno, "could not open/create lockfile");
196
197   fl.l_type= F_WRLCK;
198   fl.l_whence= SEEK_SET;
199   fl.l_start= 0;
200   fl.l_len= 0;
201   fl.l_pid= getpid();
202
203   r= fcntl(*lockfd_r, F_SETLK, &fl);
204   if (r == -1) {
205     if (errno == EACCES || errno == EAGAIN)
206       return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
207     else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
208                              " acquiring lock");
209   }
210
211   return TCL_OK;
212 }
213
214 /*---------- Log reading and writing ----------*/
215
216 static int readlognum(FILE *f, int delim, int *num_r) {
217   int c;
218   char numbuf[20], *p, *ep;
219   unsigned long ul;
220
221   p= numbuf;
222   for (;;) {
223     c= getc(f);  if (c==EOF) return -2;
224     if (c == delim) break;
225     if (!isdigit((unsigned char)c)) return -2;
226     *p++= c;
227     if (p == numbuf+sizeof(numbuf)) return -2;
228   }
229   if (p == numbuf) return -2;
230   *p= 0;
231
232   errno=0; ul= strtoul(numbuf, &ep, 10);
233   if (*ep || errno || ul >= INT_MAX/2) return -2;
234   *num_r= ul;
235   return 0;
236 }
237
238 static int readstorelogrecord(FILE *f, HashTable *ht,
239                               int (*omitfn)(const HashValue*,
240                                             struct ht_forall_ctx *ctx),
241                               struct ht_forall_ctx *ctx,
242                               void (*updatefn)(HashTable*, const char*,
243                                                HashValue*)) {
244   /* returns:
245    *      0     for OK
246    *     -1     eof
247    *     -2     corrupt or error
248    *     -3     got newline indicating end
249    *     >0     value from omitfn
250    */
251   int keylen, vallen;
252   char *key;
253   HashValue *val;
254   int c, rc, r;
255
256   c= getc(f);
257   if (c==EOF) { if (feof(f)) return -1; return -2; }
258   if (c=='\n') return -3;
259   if (c!='+') return -2;
260
261   rc= readlognum(f, ',', &keylen);  if (rc) return rc;
262   rc= readlognum(f, ':', &vallen);  if (rc) return rc;
263
264   key= TALLOC(keylen+1);
265   val= htv_prep(vallen);
266
267   r= fread(key, 1,keylen, f);
268   if (r!=keylen) goto x2_free_keyval;
269   if (memchr(key,0,keylen)) goto x2_free_keyval;
270   key[keylen]= 0;
271
272   c= getc(f);  if (c!='-') goto x2_free_keyval;
273   c= getc(f);  if (c!='>') goto x2_free_keyval;
274   
275   r= fread(htv_fillptr(val), 1,vallen, f);
276   if (r!=vallen) goto x2_free_keyval;
277
278   rc= omitfn ? omitfn(val, ctx) : TCL_OK;
279   if (rc) { assert(rc>0); TFREE(val); }
280   else updatefn(ht, key, val);
281   
282   TFREE(key);
283   return rc;
284
285  x2_free_keyval:
286   TFREE(val);
287   TFREE(key);
288   return -2;
289 }
290
291 static int writerecord(FILE *f, const char *key, const HashValue *val) {
292   int r;
293
294   r= fprintf(f, "+%d,%d:%s->", strlen(key), val->len, key);
295   if (r<0) return -1;
296   
297   r= fwrite(val->data, 1, val->len, f);
298   if (r != val->len) return -1;
299
300   return 0;
301 }
302
303 /*---------- Creating ----------*/
304
305 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
306                               const char *pathb) {
307   static const char *const toremoves[]= {
308     ".main", ".cdb", ".log", ".tmp", 0
309   };
310
311   Pathbuf pb;
312   int lock_fd=-1, fd=-1, rc, r;
313   const char *const *toremove;
314
315   pathbuf_init(&pb, pathb);
316   rc= acquire_lock(ip, &pb, &lock_fd);  if (rc) goto x_rc;
317   
318   fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
319   if (fd <= 0) PE("create new database file");
320
321   for (toremove=toremoves; *toremove; toremove++) {
322     r= remove(*toremove);
323     if (r && errno != ENOENT)
324       PE("delete possible spurious file during creation");
325   }
326   
327   rc= TCL_OK;
328
329  x_rc:
330   maybe_close(fd);
331   maybe_close(lock_fd);
332   pathbuf_free(&pb);
333   return rc;
334 }
335
336 /*---------- Info callbacks ----------*/
337
338 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
339                     const char *arg2fmt, const char *arg3, va_list al) {
340   Tcl_Obj *aa[3];
341   int na;
342   char buf[200];
343   vsnprintf(buf, sizeof(buf), arg2fmt, al);
344
345   na= 0;
346   aa[na++]= cht_ret_string(ip, arg1);
347   aa[na++]= cht_ret_string(ip, buf);
348   if (arg3) aa[na++]= cht_ret_string(ip, arg3);
349   
350   return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
351 }
352   
353 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
354                    const char *arg2fmt, const char *arg3, ...) {
355   int rc;
356   va_list al;
357   va_start(al, arg3);
358   rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
359   va_end(al);
360   return rc;
361 }
362   
363 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
364                   const char *arg2fmt, ...) {
365   int rc;
366   va_list al;
367   va_start(al, arg2fmt);
368   rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
369   va_end(al);
370   return rc;
371 }
372   
373 /*---------- Opening ----------*/
374
375 static int cdbinit(Tcl_Interp *ip, Rw *rw) {
376   /* On entry, cdb_fd >=0 but cdb is _undefined_/
377    * On exit, either cdb_fd<0 or cdb is initialised */
378   int r, rc;
379   
380   r= cdb_init(&rw->cdb, rw->cdb_fd);
381   if (r) {
382     rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
383     close(rw->cdb_fd);  rw->cdb_fd= -1;  return rc;
384   }
385   return TCL_OK;
386 }
387
388 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
389                       Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
390                       void **result) {
391   const Cdbwr_SubCommand *subcmd= cd;
392   int r, rc, mainfd=-1;
393   Rw *rw;
394   struct stat stab;
395   off_t logrecstart, logjunkpos;
396
397   rw= TALLOC(sizeof(*rw));
398   ht_setup(&rw->logincore);
399   cht_scriptinv_init(&rw->on_info);
400   cht_scriptinv_init(&rw->on_lexminval);
401   rw->cdb_fd= rw->lock_fd= -1;  rw->logfile= 0;
402   pathbuf_init(&rw->pbsome, pathb);
403   pathbuf_init(&rw->pbother, pathb);
404   rw->autocompact= 1;
405
406   if (on_lexminval) {
407     rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
408     if (rc) goto x_rc;
409   } else {
410     rw->on_lexminval.llength= 0;
411   }
412
413   mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
414   if (mainfd<0) PE("open existing database file .main");
415   rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd);  if (rc) goto x_rc;
416
417   r= fstat(mainfd, &stab);  if (r) PE("fstat .main");
418   rw->mainsz= stab.st_size;
419
420   rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
421   if (rw->cdb_fd >=0) {
422     rc= cdbinit(ip, rw);  if (rc) goto x_rc;
423   } else if (errno == ENOENT) {
424     if (rw->mainsz) {
425       rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
426                         " .cdb must have been accidentally deleted!",
427                         "CDB CDBMISSING");
428       goto x_rc;
429     }
430     /* fine */
431   } else {
432     PE("open .cdb");
433   }
434
435   rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
436   if (!rw->logfile) {
437     if (errno != ENOENT) PE("failed to open .log during open");
438     rw->logfile= fopen(rw->pbsome.buf, "w");
439     if (!rw->logfile) PE("create .log during (clean) open");
440   } else { /* rw->logfile */
441     r= fstat(fileno(rw->logfile), &stab);
442     if (r==-1) PE("fstat .log during open");
443     rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
444                (unsigned long)stab.st_size);
445     if (rc) goto x_rc;
446
447     for (;;) {
448       logrecstart= ftello(rw->logfile);
449       if (logrecstart < 0) PE("ftello .log during (dirty) open");
450       r= readstorelogrecord(rw->logfile, &rw->logincore, 0,0, ht_update);
451       if (ferror(rw->logfile)) {
452         rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
453         goto x_rc;
454       }
455       if (r==-1) {
456         break;
457       } else if (r==-2 || r==-3) {
458         char buf[100];
459         logjunkpos= ftello(rw->logfile);
460         if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
461
462         snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
463                  (unsigned long)logjunkpos, (unsigned long)logrecstart);
464
465         if (!(subcmd->flags & RWSCF_OKJUNK)) {
466           Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
467           snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
468           Tcl_ResetResult(ip);
469           Tcl_AppendResult(ip, "syntax error (junk) in .log during"
470                            " (dirty) open, at file position ", buf, (char*)0);
471           rc= TCL_ERROR;
472           goto x_rc;
473         }
474         rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
475                     (unsigned long)logjunkpos);
476         if (rc) goto x_rc;
477
478         r= fseeko(rw->logfile, logrecstart, SEEK_SET);
479         if (r) PE("failed to fseeko .log before junk during dirty open");
480
481         r= ftruncate(fileno(rw->logfile), logrecstart);
482         if (r) PE("ftruncate .log to chop junk during dirty open");
483       } else {
484         assert(!r);
485       }
486     }
487   }
488   /* now log is positioned for appending and everything is read */
489
490   *result= rw;
491   maybe_close(mainfd);
492   return TCL_OK;
493
494  x_rc:
495   rw_close(0,rw);
496   maybe_close(mainfd);
497   return rc;
498 }
499
500 int cht_do_cdbwr_open_okjunk(ClientData cd, Tcl_Interp *ip, const char *pathb,
501                       Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
502                       void **result) {
503   return cht_do_cdbwr_open(cd,ip,pathb,on_info,on_lexminval,result);
504 }
505
506 /*==================== COMPACTION ====================*/
507
508 struct ht_forall_ctx {
509   struct cdb_make cdbm;
510   FILE *mainfile;
511   int lexminvall;
512   long *reccount;
513   const char *lexminval;
514 };
515
516 /*---------- helper functions ----------*/
517
518 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
519   int r, l;
520   if (!val->len) return 0;
521   l= val->len < a->lexminvall ? val->len : a->lexminvall;
522   r= memcmp(val->data, a->lexminval, l);
523   if (r>0) return 0;
524   if (r<0) return 1;
525   return val->len < a->lexminvall;
526 }
527
528 static int delete_ifexpired(const char *key, HashValue *val,
529                             struct ht_forall_ctx *a) {
530   if (!expiredp(val, a)) return 0;
531   val->len= 0;
532   /* we don't actually need to realloc it to free the memory because
533    * this will shortly all be deleted as part of the compaction */
534   return 0;
535 }
536
537 static int addto_cdb(const char *key, HashValue *val,
538                      struct ht_forall_ctx *a) {
539   return cdb_make_add(&a->cdbm, key, strlen(key), val->data, val->len);
540 }
541
542 static int addto_main(const char *key, HashValue *val,
543                       struct ht_forall_ctx *a) {
544   (*a->reccount)++;
545   return writerecord(a->mainfile, key, val);
546 }
547
548 /*---------- compact main entrypoint ----------*/
549
550 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsz,
551                         long *reccount_r) {
552   /* creates new .cdb and .main
553    * closes logfile
554    * leaves .log with old data
555    * leaves cdb fd open onto old db
556    * leaves logincore full of crap
557    */
558   int r, rc;
559   int cdbfd, cdbmaking;
560   off_t errpos, newmainsz;
561   char buf[100];
562   Tcl_Obj *res;
563   struct ht_forall_ctx a;
564
565   a.mainfile= 0;
566   cdbfd= -1;
567   cdbmaking= 0;
568   *reccount_r= 0;
569   a.reccount= reccount_r;
570
571   r= fclose(rw->logfile);
572   if (r) { rc= cht_posixerr(ip, errno, "probable data loss!  failed to fclose"
573                             " logfile during compact");  goto x_rc; }
574   rw->logfile= 0;
575   
576   rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
577              logsz, (unsigned long)rw->mainsz);
578   if (rc) goto x_rc;
579
580   if (rw->on_lexminval.llength) {
581     rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
582     if (rc) goto x_rc;
583
584     res= Tcl_GetObjResult(ip);  assert(res);
585     a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
586     assert(a.lexminval);
587
588     /* we rely not calling Tcl_Eval during the actual compaction;
589      * if we did Tcl_Eval then the interp result would be trashed.
590      */
591     rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
592
593   } else {
594     a.lexminval= "";
595   }
596
597   /* merge unsuperseded records from main into hash table */
598
599   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
600   if (!a.mainfile) PE("failed to open .main for reading during compact");
601
602   for (;;) {
603     r= readstorelogrecord(a.mainfile, &rw->logincore,
604                           expiredp, &a,
605                           ht_maybeupdate);
606     if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
607                          " .main during compact"); goto x_rc;
608     }
609     if (r==-3) {
610       break;
611     } else if (r==-1 || r==-2) {
612       errpos= ftello(a.mainfile);
613       if (errpos<0) PE("ftello .main during report of syntax error");
614       snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
615       Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
616       snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
617       Tcl_ResetResult(ip);
618       Tcl_AppendResult(ip, "syntax error in .main during"
619                        " compact, at file position ", buf, (char*)0);
620       rc= TCL_ERROR;
621       goto x_rc;
622     } else {
623       assert(!rc);
624     }
625   }
626   fclose(a.mainfile);
627   a.mainfile= 0;
628
629   /* create new cdb */
630
631   cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
632   if (cdbfd<0) PE("create .tmp for new cdb during compact");
633
634   r= cdb_make_start(&a.cdbm, cdbfd);
635   if (r) PE("cdb_make_start during compact");
636   cdbmaking= 1;
637
638   r= ht_forall(&rw->logincore, addto_cdb, &a);
639   if (r) PE("cdb_make_add during compact");
640
641   r= cdb_make_finish(&a.cdbm);
642   if(r) PE("cdb_make_finish during compact");
643   cdbmaking= 0;
644
645   r= fdatasync(cdbfd);  if (r) PE("fdatasync new cdb during compact");
646   r= close(cdbfd);  if (r) PE("close new cdb during compact");
647   cdbfd= -1;
648
649   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
650   if (r) PE("install new .cdb during compact");
651
652   /* create new main */
653
654   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
655   if (!a.mainfile) PE("create .tmp for new main during compact");
656
657   r= ht_forall(&rw->logincore, addto_main, &a);
658   if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
659                             " during compact");  goto x_rc; }
660   
661   r= fflush(a.mainfile);  if (r) PE("fflush new main during compact");
662   r= fdatasync(fileno(a.mainfile));
663   if (r) PE("fdatasync new main during compact");
664
665   newmainsz= ftello(a.mainfile);
666   if (newmainsz<0) PE("ftello new main during compact");
667   
668   r= fclose(a.mainfile);  if (r) PE("fclose new main during compact");
669   a.mainfile= 0;
670
671   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
672   if (r) PE("install new .main during compact");
673
674   rw->mainsz= newmainsz;
675
676   /* done! */
677   
678   rc= infocb(ip, rw, "compact-end", "main=%luby nrecs=%l",
679              (unsigned long)rw->mainsz, *a.reccount);
680   if (rc) goto x_rc;
681
682   return rc;
683
684 x_rc:
685   if (a.mainfile) fclose(a.mainfile);
686   if (cdbmaking) cdb_make_finish(&a.cdbm);
687   maybe_close(cdbfd);
688   remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
689   return rc;
690 }
691
692 /*---------- Closing ----------*/
693
694 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
695   off_t logsz;
696   int r, rc;
697
698   logsz= ftello(rw->logfile);
699   if (logsz < 0) PE("ftello logfile (during tidy close)");
700
701   rc= compact_core(ip, rw, logsz, reccount_r);  if (rc) goto x_rc;
702
703   r= remove(pathbuf_sfx(&rw->pbsome,".log"));
704   if (r) PE("remove .log (during tidy close)");
705
706   return TCL_OK;
707
708 x_rc: return rc;
709 }
710   
711 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
712   Rw *rw= rw_v;
713   int rc, rc_close;
714   long reccount= -1;
715   off_t logsz;
716
717   if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
718   else rc= TCL_OK;
719
720   if (!rc) {
721     if (!rw->logfile) {
722       logsz= ftello(rw->logfile);
723       if (logsz < 0)
724         rc= cht_posixerr(ip, errno, "ftell logfile during close info");
725       else
726         rc= infocb(ip, rw, "close", "main=%luby log=%luby",
727                    rw->mainsz, logsz);
728     } else if (reccount>=0) {
729       rc= infocb(ip, rw, "close", "main=%luby nrecs=%l", rw->mainsz, reccount);
730     } else {
731       rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
732     }
733   }
734   rc_close= rw_close(ip,rw);
735   if (rc_close) rc= rc_close;
736   
737   cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
738   return rc;
739 }
740
741 /*---------- Other compaction-related entrypoints ----------*/
742
743 static int compact_keepopen(Tcl_Interp *ip, Rw *rw, int force) {
744   off_t logsz;
745   long reccount;
746   int rc, r;
747
748   logsz= ftello(rw->logfile);
749   if (logsz < 0) return cht_posixerr(ip, errno, "ftell .log"
750                                        " during compact check or force");
751
752   if (!force && logsz < rw->mainsz / 10 + 1000) return TCL_OK;
753
754   rc= compact_core(ip, rw, logsz, &reccount);  if (rc) goto x_rc;
755
756   maybe_close(rw->cdb_fd);
757   rw->cdb_fd= -1;
758   ht_destroy(&rw->logincore);
759   ht_setup(&rw->logincore);
760
761   rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
762   if (rw->cdb_fd < 0) PE("reopen .cdb after compact");
763
764   rc= cdbinit(ip, rw);  if (rc) goto x_rc;
765
766   rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "w");
767   if (!rw->logfile) PE("reopen .log after compact");
768
769   r= fsync(fileno(rw->logfile));  if (r) PE("fsync .log after compact reopen");
770
771   return TCL_OK;
772
773 x_rc:
774   /* doom! all updates fail after this (because rw->logfile is 0), and
775    * we may be using a lot more RAM than would be ideal.  Program will
776    * have to reopen if it really wants sanity. */
777   return rc;
778 }
779
780 int cht_do_cdbwr_compact_force(ClientData cd, Tcl_Interp *ip, void *rw_v) {
781   return compact_keepopen(ip, rw_v, 1);
782 }
783 int cht_do_cdbwr_compact_check(ClientData cd, Tcl_Interp *ip, void *rw_v) {
784   return compact_keepopen(ip, rw_v, 0);
785 }
786
787 int cht_do_cdbwr_compact_explicit(ClientData cd, Tcl_Interp *ip, void *rw_v) {
788   Rw *rw= rw_v;
789   rw->autocompact= 0;
790   return TCL_OK;
791 }
792 int cht_do_cdbwr_compact_auto(ClientData cd, Tcl_Interp *ip, void *rw_v) {
793   Rw *rw= rw_v;
794   rw->autocompact= 1;
795   return TCL_OK;
796 }
797
798 /*---------- Updateing ----------*/
799
800 static int update(Tcl_Interp *ip, Rw *rw, const char *key,
801                   const Byte *data, int dlen) {
802   HashValue *val;
803   int rc, r;
804
805   if (!rw->logfile) return cht_staticerr
806     (ip, "previous compact failed; cdbwr must be closed and reopened "
807      "before any further updates", "CDB BROKEN");
808   
809   val= htv_prep(dlen);  assert(val);
810   memcpy(htv_fillptr(val), data, dlen);
811
812   r= writerecord(rw->logfile, key, val);
813   if (!r) r= fflush(rw->logfile);
814   if (r) PE("write update to logfile");
815
816   ht_update(&rw->logincore, key, val);
817   return compact_keepopen(ip, rw, 0);
818
819  x_rc:
820   TFREE(val);
821   return rc;
822 }  
823
824 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip,
825                         void *rw_v, const char *key, Tcl_Obj *value) {
826   int dlen;
827   const char *data;
828   data= Tcl_GetStringFromObj(value, &dlen);  assert(data);
829   return update(ip, rw_v, key, data, dlen);
830 }
831
832 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip,
833                            void *rw_v, const char *key, HBytes_Value value) {
834   return update(ip, rw_v, key, cht_hb_data(&value), cht_hb_len(&value));
835 }
836
837 int cht_do_cdbwr_delete(ClientData cd, Tcl_Interp *ip, void *rw_v,
838                         const char *key) {
839   return update(ip, rw_v, key, 0, 0);
840 }
841
842 /*---------- Lookups ----------*/
843
844 static int lookup_rw(Tcl_Interp *ip, void *rw_v, const char *key,
845                     const Byte **data_r, int *len_r /* -1 => notfound */) {
846   Rw *rw= rw_v;
847   const HashValue *val;
848
849   val= ht_lookup(&rw->logincore, key);
850   if (val) {
851     if (val->len) { *data_r= val->data; *len_r= val->len; return TCL_OK; }
852     else { *data_r= 0; *len_r= -1; return TCL_OK; }
853   }
854
855   return cht_cdb_lookup_cdb(ip, &rw->cdb, key, strlen(key), data_r, len_r);
856
857
858 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *rw_v,
859                         const char *key, Tcl_Obj *def,
860                         Tcl_Obj **result) {
861   const Byte *data;
862   int dlen, r;
863   
864   r= lookup_rw(ip, rw_v, key, &data, &dlen);  if (r) return r;
865   return cht_cdb_donesomelookup(ip, rw_v, def, result, data, dlen,
866                                 cht_cdb_storeanswer_string);
867 }
868   
869 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *rw_v,
870                            const char *key, Tcl_Obj *def,
871                            Tcl_Obj **result) {
872   const Byte *data;
873   int dlen, r;
874   
875   r= lookup_rw(ip, rw_v, key, &data, &dlen);  if (r) return r;
876   return cht_cdb_donesomelookup(ip, rw_v, def, result, data, dlen,
877                                 cht_cdb_storeanswer_hb);
878 }
879
880 int cht_do_cdbtoplevel_cdb_wr(ClientData cd, Tcl_Interp *ip,
881                               const Cdbwr_SubCommand* subcmd,
882                               int objc, Tcl_Obj *const *objv) {
883   return subcmd->func((void*)subcmd,ip,objc,objv);
884 }