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