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