reset error for retrieve. Remove sleep call
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /*
2  * Copyright (C) 1995-2002, Index Data
3  * All rights reserved.
4  *
5  * $Id: zebraapi.c,v 1.61 2002-07-03 14:10:12 adam Exp $
6  */
7
8 #include <assert.h>
9 #include <stdio.h>
10 #ifdef WIN32
11 #include <io.h>
12 #include <process.h>
13 #include <direct.h>
14 #else
15 #include <unistd.h>
16 #endif
17
18 #include <yaz/diagbib1.h>
19 #include "index.h"
20 #include <charmap.h>
21
22 static Res zebra_open_res (ZebraHandle zh);
23 static void zebra_close_res (ZebraHandle zh);
24
25 static void zebra_chdir (ZebraService zh)
26 {
27     const char *dir = res_get (zh->global_res, "chdir");
28     if (!dir)
29         return;
30     logf (LOG_DEBUG, "chdir %s", dir);
31 #ifdef WIN32
32     _chdir(dir);
33 #else
34     chdir (dir);
35 #endif
36 }
37
38 static void zebra_flush_reg (ZebraHandle zh)
39 {
40     zebraExplain_flush (zh->reg->zei, zh);
41     
42     extract_flushWriteKeys (zh);
43     zebra_index_merge (zh);
44 }
45
46 static struct zebra_register *zebra_register_open (ZebraService zs, 
47                                                    const char *name,
48                                                    int rw, int useshadow,
49                                                    Res res,
50                                                    const char *reg_path);
51 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
52
53 ZebraHandle zebra_open (ZebraService zs)
54 {
55     ZebraHandle zh;
56
57     if (!zs)
58         return 0;
59
60     zh = (ZebraHandle) xmalloc (sizeof(*zh));
61     yaz_log (LOG_LOG, "zebra_open zs=%p returns %p", zs, zh);
62
63     zh->service = zs;
64     zh->reg = 0;          /* no register attached yet */
65     zh->sets = 0;
66     zh->destroyed = 0;
67     zh->errCode = 0;
68     zh->errString = 0;
69     zh->res = 0;
70
71     zh->reg_name = xstrdup ("");
72     zh->path_reg = 0;
73     zh->num_basenames = 0;
74     zh->basenames = 0;
75
76     zh->trans_no = 0;
77
78     zh->lock_normal = 0;
79     zh->lock_shadow = 0;
80
81     zh->admin_databaseName = 0;
82
83     zh->shadow_enable = 1;
84
85     zebra_mutex_cond_lock (&zs->session_lock);
86
87     zh->next = zs->sessions;
88     zs->sessions = zh;
89
90     zebra_mutex_cond_unlock (&zs->session_lock);
91
92     return zh;
93 }
94
95 ZebraService zebra_start (const char *configName)
96 {
97     Res res;
98
99     yaz_log (LOG_LOG, "zebra_start %s", configName);
100
101     if (!(res = res_open (configName, 0)))
102         yaz_log (LOG_WARN, "Cannot read resources `%s'", configName);
103     else
104     {
105         ZebraService zh = xmalloc (sizeof(*zh));
106
107         yaz_log (LOG_LOG, "Read resources `%s'", configName);
108         
109         zh->global_res = res;
110         zh->configName = xstrdup(configName);
111         zh->sessions = 0;
112         
113         zebra_chdir (zh);
114         
115         zebra_mutex_cond_init (&zh->session_lock);
116         if (!res_get (zh->global_res, "passwd"))
117             zh->passwd_db = NULL;
118         else
119         {
120             zh->passwd_db = passwd_db_open ();
121             if (!zh->passwd_db)
122                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
123             else
124                 passwd_db_file (zh->passwd_db,
125                                 res_get (zh->global_res, "passwd"));
126         }
127         zh->path_root = res_get (zh->global_res, "root");
128         return zh;
129     }
130     return 0;
131 }
132
133 static
134 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
135                                             int rw, int useshadow, Res res,
136                                             const char *reg_path)
137 {
138     struct zebra_register *reg;
139     int record_compression = REC_COMPRESS_NONE;
140     char *recordCompression = 0;
141
142     reg = xmalloc (sizeof(*reg));
143
144     assert (name);
145     reg->name = xstrdup (name);
146
147     reg->seqno = 0;
148     reg->last_val = 0;
149
150     assert (res);
151
152     yaz_log (LOG_LOG, "zebra_register_open rw = %d useshadow=%d p=%p",
153              rw, useshadow, reg);
154
155     reg->dh = data1_create ();
156     if (!reg->dh)
157         return 0;
158     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
159     if (!reg->bfs)
160     {
161         data1_destroy(reg->dh);
162         return 0;
163     }
164     if (useshadow)
165         bf_cache (reg->bfs, res_get (res, "shadow"));
166     data1_set_tabpath (reg->dh, res_get(res, "profilePath"));
167     data1_set_tabroot (reg->dh, reg_path);
168     reg->recTypes = recTypes_init (reg->dh);
169     recTypes_default_handlers (reg->recTypes);
170
171     reg->zebra_maps = zebra_maps_open (res, reg_path);
172     reg->rank_classes = NULL;
173
174     reg->key_buf = 0;
175
176     reg->keys.buf_max = 0;
177     reg->keys.buf = 0;
178
179     reg->records = 0;
180     reg->dict = 0;
181     reg->sortIdx = 0;
182     reg->isams = 0;
183     reg->matchDict = 0;
184     reg->isam = 0;
185     reg->isamc = 0;
186     reg->isamd = 0;
187     reg->isamb = 0;
188     reg->zei = 0;
189     reg->matchDict = 0;
190     
191     zebraRankInstall (reg, rank1_class);
192
193     recordCompression = res_get_def (res, "recordCompression", "none");
194     if (!strcmp (recordCompression, "none"))
195         record_compression = REC_COMPRESS_NONE;
196     if (!strcmp (recordCompression, "bzip2"))
197         record_compression = REC_COMPRESS_BZIP2;
198
199     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
200     {
201         logf (LOG_WARN, "rec_open");
202         return 0;
203     }
204     if (rw)
205     {
206         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
207     }
208     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
209     {
210         logf (LOG_WARN, "dict_open");
211         return 0;
212     }
213     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
214     {
215         logf (LOG_WARN, "sortIdx_open");
216         return 0;
217     }
218     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
219     {
220         struct ISAMS_M_s isams_m;
221         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
222                                       key_isams_m(res, &isams_m))))
223         {
224             logf (LOG_WARN, "isams_open");
225             return 0;
226         }
227     }
228     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
229     {
230         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
231                                   sizeof (struct it_key), res)))
232         {
233             logf (LOG_WARN, "is_open");
234             return 0;
235         }
236     }
237     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
238     {
239         struct ISAMC_M_s isamc_m;
240         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
241                                     rw, key_isamc_m(res, &isamc_m))))
242         {
243             logf (LOG_WARN, "isc_open");
244             return 0;
245         }
246     }
247     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
248     {
249         struct ISAMD_M_s isamd_m;
250         
251         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
252                                       rw, key_isamd_m(res, &isamd_m))))
253         {
254             logf (LOG_WARN, "isamd_open");
255             return 0;
256         }
257     }
258     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
259     {
260         struct ISAMC_M_s isamc_m;
261         
262         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
263                                        rw, key_isamc_m(res, &isamc_m))))
264         {
265             logf (LOG_WARN, "isamb_open");
266             return 0;
267         }
268     }
269     reg->zei = zebraExplain_open (reg->records, reg->dh,
270                                   res, rw, reg,
271                                   explain_extract);
272     if (!reg->zei)
273     {
274         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
275         return 0;
276     }
277     reg->active = 2;
278     yaz_log (LOG_LOG, "zebra_register_open ok p=%p", reg);
279     return reg;
280 }
281
282 void zebra_admin_shutdown (ZebraHandle zh)
283 {
284     zebra_mutex_cond_lock (&zh->service->session_lock);
285     zh->service->stop_flag = 1;
286     zebra_mutex_cond_unlock (&zh->service->session_lock);
287 }
288
289 void zebra_admin_start (ZebraHandle zh)
290 {
291     ZebraService zs = zh->service;
292     zh->errCode = 0;
293     zebra_mutex_cond_lock (&zs->session_lock);
294     zebra_mutex_cond_unlock (&zs->session_lock);
295 }
296
297 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
298 {
299     yaz_log(LOG_LOG, "zebra_register_close p=%p", reg);
300     reg->stop_flag = 0;
301     zebra_chdir (zs);
302     if (reg->records)
303     {
304         zebraExplain_close (reg->zei);
305         dict_close (reg->dict);
306         if (reg->matchDict)
307             dict_close (reg->matchDict);
308         sortIdx_close (reg->sortIdx);
309         if (reg->isams)
310             isams_close (reg->isams);
311         if (reg->isam)
312             is_close (reg->isam);
313         if (reg->isamc)
314             isc_close (reg->isamc);
315         if (reg->isamd)
316             isamd_close (reg->isamd);
317         if (reg->isamb)
318             isamb_close (reg->isamb);
319         rec_close (&reg->records);
320     }
321
322     recTypes_destroy (reg->recTypes);
323     zebra_maps_close (reg->zebra_maps);
324     zebraRankDestroy (reg);
325     bfs_destroy (reg->bfs);
326     data1_destroy (reg->dh);
327
328     xfree (reg->key_buf);
329     xfree (reg->name);
330     xfree (reg);
331     yaz_log (LOG_LOG, "zebra_register_close 2");
332 }
333
334 void zebra_stop(ZebraService zs)
335 {
336     if (!zs)
337         return ;
338     yaz_log (LOG_LOG, "zebra_stop");
339
340     zebra_mutex_cond_lock (&zs->session_lock);
341     while (zs->sessions)
342     {
343         zebra_close (zs->sessions);
344     }
345         
346     zebra_mutex_cond_unlock (&zs->session_lock);
347
348     zebra_mutex_cond_destroy (&zs->session_lock);
349
350     if (zs->passwd_db)
351         passwd_db_close (zs->passwd_db);
352
353     res_close (zs->global_res);
354     xfree (zs->configName);
355     xfree (zs->path_root);
356     xfree (zs);
357 }
358
359 void zebra_close (ZebraHandle zh)
360 {
361     ZebraService zs;
362     struct zebra_session **sp;
363
364     if (!zh)
365         return;
366
367     zs = zh->service;
368     yaz_log (LOG_LOG, "zebra_close zh=%p", zh);
369     if (!zh)
370         return ;
371     resultSetDestroy (zh, -1, 0, 0);
372
373
374     if (zh->reg)
375         zebra_register_close (zh->service, zh->reg);
376     zebra_close_res (zh);
377
378     xfree (zh->admin_databaseName);
379     zebra_mutex_cond_lock (&zs->session_lock);
380     zebra_lock_destroy (zh->lock_normal);
381     zebra_lock_destroy (zh->lock_shadow);
382     sp = &zs->sessions;
383     while (1)
384     {
385         assert (*sp);
386         if (*sp == zh)
387         {
388             *sp = (*sp)->next;
389             break;
390         }
391         sp = &(*sp)->next;
392     }
393 //    if (!zs->sessions && zs->stop_flag)
394 //      zebra_register_deactivate(zs);
395     zebra_mutex_cond_unlock (&zs->session_lock);
396     xfree (zh->reg_name);
397     xfree (zh);
398 }
399
400 struct map_baseinfo {
401     ZebraHandle zh;
402     NMEM mem;
403     int num_bases;
404     char **basenames;
405     int new_num_bases;
406     char **new_basenames;
407     int new_num_max;
408 };
409
410 static Res zebra_open_res (ZebraHandle zh)
411 {
412     Res res = 0;
413     char fname[512];
414     if (zh->path_reg)
415     {
416         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
417         res = res_open (fname, zh->service->global_res);
418         if (!res)
419             res = zh->service->global_res;
420     }
421     else if (*zh->reg_name == 0)
422     {
423         res = zh->service->global_res;
424     }
425     else
426     {
427         yaz_log (LOG_WARN, "no register root specified");
428         return 0;  /* no path for register - fail! */
429     }
430     return res;
431 }
432
433 static void zebra_close_res (ZebraHandle zh)
434 {
435     if (zh->res != zh->service->global_res)
436         res_close (zh->res);
437     zh->res = 0;
438 }
439
440 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
441 {
442     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
443         return 0;
444     if (!zh->res)
445     {
446         assert (zh->reg == 0);
447         assert (*zh->reg_name == 0);
448     }
449     else
450     {
451         if (zh->reg)
452         {
453             resultSetInvalidate (zh);
454             zebra_register_close (zh->service, zh->reg);
455             zh->reg = 0;
456         }
457         zebra_close_res(zh);
458     }
459     xfree (zh->reg_name);
460     zh->reg_name = xstrdup (new_reg);
461
462     xfree (zh->path_reg);
463     zh->path_reg = 0;
464     if (zh->service->path_root)
465     {
466         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
467                                 strlen(zh->reg_name) + 3);
468         strcpy (zh->path_reg, zh->service->path_root);
469         if (*zh->reg_name)
470         {
471             strcat (zh->path_reg, "/");
472             strcat (zh->path_reg, zh->reg_name);
473         }
474     }
475     zh->res = zebra_open_res (zh);
476     
477     if (zh->lock_normal)
478         zebra_lock_destroy (zh->lock_normal);
479     zh->lock_normal = 0;
480
481     if (zh->lock_shadow)
482         zebra_lock_destroy (zh->lock_shadow);
483     zh->lock_shadow = 0;
484
485     if (zh->res)
486     {
487         char fname[512];
488         const char *lock_area  =res_get (zh->res, "lockDir");
489         
490         if (!lock_area && zh->path_reg)
491             res_put (zh->res, "lockDir", zh->path_reg);
492         sprintf (fname, "norm.%s.LCK", zh->reg_name);
493         zh->lock_normal =
494             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
495         
496         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
497         zh->lock_shadow =
498             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
499
500     }
501     return 1;
502 }
503
504 void map_basenames_func (void *vp, const char *name, const char *value)
505 {
506     struct map_baseinfo *p = (struct map_baseinfo *) vp;
507     int i, no;
508     char fromdb[128], todb[8][128];
509     
510     no =
511         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
512                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
513                 todb[5], todb[6], todb[7]);
514     if (no < 2)
515         return ;
516     no--;
517     for (i = 0; i<p->num_bases; i++)
518         if (p->basenames[i] && !strcmp (p->basenames[i], fromdb))
519         {
520             p->basenames[i] = 0;
521             for (i = 0; i < no; i++)
522             {
523                 if (p->new_num_bases == p->new_num_max)
524                     return;
525                 p->new_basenames[(p->new_num_bases)++] = 
526                     nmem_strdup (p->mem, todb[i]);
527             }
528             return;
529         }
530 }
531
532 void map_basenames (ZebraHandle zh, ODR stream,
533                     int *num_bases, char ***basenames)
534 {
535     struct map_baseinfo info;
536     struct map_baseinfo *p = &info;
537     int i;
538
539     info.zh = zh;
540     info.num_bases = *num_bases;
541     info.basenames = *basenames;
542     info.new_num_max = 128;
543     info.new_num_bases = 0;
544     info.new_basenames = (char **)
545         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
546     info.mem = stream->mem;
547
548     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
549     
550     for (i = 0; i<p->num_bases; i++)
551         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
552         {
553             p->new_basenames[(p->new_num_bases)++] = 
554                 nmem_strdup (p->mem, p->basenames[i]);
555         }
556     *num_bases = info.new_num_bases;
557     *basenames = info.new_basenames;
558     for (i = 0; i<*num_bases; i++)
559         logf (LOG_LOG, "base %s", (*basenames)[i]);
560 }
561
562 int zebra_select_database (ZebraHandle zh, const char *basename)
563 {
564     return zebra_select_databases (zh, 1, &basename);
565 }
566
567 int zebra_select_databases (ZebraHandle zh, int num_bases,
568                             const char **basenames)
569 {
570     int i;
571     const char *cp;
572     int len = 0;
573     char *new_reg = 0;
574     
575     if (num_bases < 1)
576     {
577         zh->errCode = 23;
578         return -1;
579     }
580     for (i = 0; i < zh->num_basenames; i++)
581         xfree (zh->basenames[i]);
582     xfree (zh->basenames);
583     
584     zh->num_basenames = num_bases;
585     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
586     for (i = 0; i < zh->num_basenames; i++)
587         zh->basenames[i] = xstrdup (basenames[i]);
588
589     cp = strrchr(basenames[0], '/');
590     if (cp)
591     {
592         len = cp - basenames[0];
593         new_reg = xmalloc (len + 1);
594         memcpy (new_reg, basenames[0], len);
595         new_reg[len] = '\0';
596     }
597     else
598         new_reg = xstrdup ("");
599     for (i = 1; i<num_bases; i++)
600     {
601         const char *cp1;
602
603         cp1 = strrchr (basenames[i], '/');
604         if (cp)
605         {
606             if (!cp1)
607             {
608                 zh->errCode = 23;
609                 return -1;
610             }
611             if (len != cp1 - basenames[i] ||
612                 memcmp (basenames[i], new_reg, len))
613             {
614                 zh->errCode = 23;
615                 return -1;
616             }
617         }
618         else
619         {
620             if (cp1)
621             {
622                 zh->errCode = 23;
623                 return -1;
624             }
625         }
626     }
627     zebra_select_register (zh, new_reg);
628     xfree (new_reg);
629     if (!zh->res)
630     {
631         zh->errCode = 109;
632         return -1;
633     }
634     return 0;
635 }
636
637 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
638                        Z_RPNQuery *query, const char *setname, int *hits)
639 {
640     zh->hits = 0;
641     *hits = 0;
642
643     if (zebra_begin_read (zh))
644         return;
645     resultSetAddRPN (zh, decode, stream, query, 
646                      zh->num_basenames, zh->basenames, setname);
647
648     zebra_end_read (zh);
649
650     *hits = zh->hits;
651 }
652
653 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
654                              const char *setname, Z_RecordComposition *comp,
655                              oid_value input_format, int num_recs,
656                              ZebraRetrievalRecord *recs)
657 {
658     ZebraPosSet poset;
659     int i, *pos_array;
660
661     if (!zh->res)
662     {
663         zh->errCode = 30;
664         zh->errString = odr_strdup (stream, setname);
665         return;
666     }
667     
668     zh->errCode = 0;
669
670     if (zebra_begin_read (zh))
671         return;
672
673     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
674     for (i = 0; i<num_recs; i++)
675         pos_array[i] = recs[i].position;
676     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
677     if (!poset)
678     {
679         logf (LOG_DEBUG, "zebraPosSetCreate error");
680         zh->errCode = 30;
681         zh->errString = nmem_strdup (stream->mem, setname);
682     }
683     else
684     {
685         for (i = 0; i<num_recs; i++)
686         {
687             if (poset[i].term)
688             {
689                 recs[i].errCode = 0;
690                 recs[i].format = VAL_SUTRS;
691                 recs[i].len = strlen(poset[i].term);
692                 recs[i].buf = poset[i].term;
693                 recs[i].base = poset[i].db;
694             }
695             else if (poset[i].sysno)
696             {
697                 recs[i].errCode =
698                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
699                                         stream, input_format, comp,
700                                         &recs[i].format, &recs[i].buf,
701                                         &recs[i].len,
702                                         &recs[i].base);
703                 recs[i].errString = NULL;
704             }
705             else
706             {
707                 char num_str[20];
708
709                 sprintf (num_str, "%d", pos_array[i]);  
710                 zh->errCode = 13;
711                 zh->errString = odr_strdup (stream, num_str);
712                 break;
713             }
714         }
715         zebraPosSetDestroy (zh, poset, num_recs);
716     }
717     zebra_end_read (zh);
718     xfree (pos_array);
719 }
720
721 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
722                  oid_value attributeset,
723                  int *position, int *num_entries, ZebraScanEntry **entries,
724                  int *is_partial)
725 {
726     if (zebra_begin_read (zh))
727     {
728         *entries = 0;
729         *num_entries = 0;
730         return;
731     }
732     rpn_scan (zh, stream, zapt, attributeset,
733               zh->num_basenames, zh->basenames, position,
734               num_entries, entries, is_partial);
735     zebra_end_read (zh);
736 }
737
738 void zebra_sort (ZebraHandle zh, ODR stream,
739                  int num_input_setnames, const char **input_setnames,
740                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
741                  int *sort_status)
742 {
743     if (zebra_begin_read (zh))
744         return;
745     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
746                    output_setname, sort_sequence, sort_status);
747     zebra_end_read(zh);
748 }
749
750 int zebra_deleleResultSet(ZebraHandle zh, int function,
751                           int num_setnames, char **setnames,
752                           int *statuses)
753 {
754     int i, status;
755     if (zebra_begin_read(zh))
756         return Z_DeleteStatus_systemProblemAtTarget;
757     switch (function)
758     {
759     case Z_DeleteRequest_list:
760         resultSetDestroy (zh, num_setnames, setnames, statuses);
761         break;
762     case Z_DeleteRequest_all:
763         resultSetDestroy (zh, -1, 0, statuses);
764         break;
765     }
766     zebra_end_read (zh);
767     status = Z_DeleteStatus_success;
768     for (i = 0; i<num_setnames; i++)
769         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
770             status = statuses[i];
771     return status;
772 }
773
774 int zebra_errCode (ZebraHandle zh)
775 {
776     return zh->errCode;
777 }
778
779 const char *zebra_errString (ZebraHandle zh)
780 {
781     return diagbib1_str (zh->errCode);
782 }
783
784 char *zebra_errAdd (ZebraHandle zh)
785 {
786     return zh->errString;
787 }
788
789 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
790 {
791     ZebraService zs = zh->service;
792     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
793     {
794         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
795         return 0;
796     }
797
798     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
799     return 1;
800 }
801
802 void zebra_admin_import_begin (ZebraHandle zh, const char *database)
803 {
804     zebra_begin_trans (zh);
805     xfree (zh->admin_databaseName);
806     zh->admin_databaseName = xstrdup(database);
807 }
808
809 void zebra_admin_import_end (ZebraHandle zh)
810 {
811     zebra_end_trans (zh);
812 }
813
814 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
815 {
816     int sysno;
817     int i;
818     for (i = 0; i<segment->num_segmentRecords; i++)
819     {
820         Z_NamePlusRecord *npr = segment->segmentRecords[i];
821         const char *databaseName = npr->databaseName;
822
823         if (!databaseName)
824             databaseName = zh->admin_databaseName;
825         printf ("--------------%d--------------------\n", i);
826         if (npr->which == Z_NamePlusRecord_intermediateFragment)
827         {
828             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
829             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
830             {
831                 Odr_oct *oct = fragment->u.notExternallyTagged;
832                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
833                         oct->buf);
834                 
835                 sysno = 0;
836                 extract_rec_in_mem (zh, "grs.sgml",
837                                     oct->buf, oct->len,
838                                     databaseName,
839                                     0 /* delete_flag */,
840                                     0 /* test_mode */,
841                                     &sysno /* sysno */,
842                                     1 /* store_keys */,
843                                     1 /* store_data */,
844                                     0 /* match criteria */);
845             }
846         }
847     }
848 }
849
850 void zebra_admin_create (ZebraHandle zh, const char *database)
851 {
852     ZebraService zs;
853
854     zebra_begin_trans (zh);
855
856     zs = zh->service;
857     /* announce database */
858     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
859                                   /* explainDatabase */))
860     {
861         zh->errCode = 224;
862         zh->errString = "Database already exist";
863     }
864     zebra_end_trans (zh);
865 }
866
867 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
868                        const char *input_str, int input_len,
869                        char *output_str, int output_len)
870 {
871     WRBUF wrbuf;
872     if (!zh->reg->zebra_maps)
873         return -1;
874     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
875                           input_str, input_len);
876     if (!wrbuf)
877         return -2;
878     if (wrbuf_len(wrbuf) >= output_len)
879         return -3;
880     if (wrbuf_len(wrbuf))
881         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
882     output_str[wrbuf_len(wrbuf)] = '\0';
883     return wrbuf_len(wrbuf);
884 }
885
886
887 void zebra_set_state (ZebraHandle zh, int val, int seqno)
888 {
889     char state_fname[256];
890     char *fname;
891     long p = getpid();
892     FILE *f;
893
894     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
895     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
896     f = fopen (fname, "w");
897
898     yaz_log (LOG_LOG, "%c %d %ld", val, seqno, p);
899     fprintf (f, "%c %d %ld\n", val, seqno, p);
900     fclose (f);
901     xfree (fname);
902 }
903
904 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
905 {
906     char state_fname[256];
907     char *fname;
908     FILE *f;
909
910     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
911     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
912     f = fopen (fname, "r");
913     *val = 'o';
914     *seqno = 0;
915
916     if (f)
917     {
918         fscanf (f, "%c %d", val, seqno);
919         fclose (f);
920     }
921     xfree (fname);
922 }
923
924 int zebra_begin_read (ZebraHandle zh)
925 {
926     int dirty = 0;
927     char val;
928     int seqno;
929
930     assert (zh->res);
931
932     (zh->trans_no)++;
933
934     if (zh->trans_no != 1)
935     {
936         zebra_flush_reg (zh);
937         return 0;
938     }
939 #if HAVE_SYS_TIMES_H
940     times (&zh->tms1);
941 #endif
942     if (!zh->res)
943     {
944         (zh->trans_no)--;
945         zh->errCode = 109;
946         return -1;
947     }
948     zebra_get_state (zh, &val, &seqno);
949     if (val == 'd')
950         val = 'o';
951
952     if (!zh->reg)
953         dirty = 1;
954     else if (seqno != zh->reg->seqno)
955     {
956         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
957                  seqno, zh->reg->seqno);
958         dirty = 1;
959     }
960     else if (zh->reg->last_val != val)
961     {
962         yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
963                  val, zh->reg->last_val);
964         dirty = 1;
965     }
966     if (!dirty)
967         return 0;
968
969     if (val == 'c')
970         zebra_lock_r (zh->lock_shadow);
971     else
972         zebra_lock_r (zh->lock_normal);
973     
974     if (zh->reg)
975         zebra_register_close (zh->service, zh->reg);
976     zh->reg = zebra_register_open (zh->service, zh->reg_name,
977                                    0, val == 'c' ? 1 : 0,
978                                    zh->res, zh->path_reg);
979     if (!zh->reg)
980     {
981         zh->errCode = 109;
982         return -1;
983     }
984     zh->reg->last_val = val;
985     zh->reg->seqno = seqno;
986
987     return 0;
988 }
989
990 void zebra_end_read (ZebraHandle zh)
991 {
992     (zh->trans_no)--;
993
994     if (zh->trans_no != 0)
995         return;
996
997 #if HAVE_SYS_TIMES_H
998     times (&zh->tms2);
999     logf (LOG_LOG, "user/system: %ld/%ld",
1000                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1001                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1002
1003 #endif
1004
1005     zebra_unlock (zh->lock_normal);
1006     zebra_unlock (zh->lock_shadow);
1007 }
1008
1009 void zebra_begin_trans (ZebraHandle zh)
1010 {
1011     int pass;
1012     int seqno = 0;
1013     char val = '?';
1014     const char *rval = 0;
1015
1016     assert (zh->res);
1017
1018     (zh->trans_no++);
1019     if (zh->trans_no != 1)
1020     {
1021         return;
1022     }
1023     
1024     yaz_log (LOG_LOG, "zebra_begin_trans");
1025
1026     zh->records_inserted = 0;
1027     zh->records_updated = 0;
1028     zh->records_deleted = 0;
1029     zh->records_processed = 0;
1030
1031 #if HAVE_SYS_TIMES_H
1032     times (&zh->tms1);
1033 #endif
1034     
1035     /* lock */
1036     if (zh->shadow_enable)
1037         rval = res_get (zh->res, "shadow");
1038
1039     for (pass = 0; pass < 2; pass++)
1040     {
1041         if (rval)
1042         {
1043             zebra_lock_r (zh->lock_normal);
1044             zebra_lock_w (zh->lock_shadow);
1045         }
1046         else
1047         {
1048             zebra_lock_w (zh->lock_normal);
1049             zebra_lock_w (zh->lock_shadow);
1050         }
1051         
1052         zebra_get_state (zh, &val, &seqno);
1053         if (val == 'c')
1054         {
1055             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1056             zebra_unlock (zh->lock_shadow);
1057             zebra_unlock (zh->lock_normal);
1058             zebra_commit (zh);
1059             continue;
1060         }
1061         else if (val == 'd')
1062         {
1063             if (rval)
1064             {
1065                 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1066                                          zh->path_reg);
1067                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1068                 bf_commitClean (bfs, rval);
1069                 bfs_destroy (bfs);
1070             }
1071             else
1072             {
1073                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1074             }
1075         }
1076         break;
1077     }
1078     if (pass == 2)
1079     {
1080         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1081         abort();
1082         return;
1083     }
1084     zebra_set_state (zh, 'd', seqno);
1085
1086     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1087                                    1, rval ? 1 : 0, zh->res,
1088                                    zh->path_reg);
1089
1090     zh->reg->seqno = seqno;
1091 }
1092
1093 void zebra_end_trans (ZebraHandle zh)
1094 {
1095     char val;
1096     int seqno;
1097     const char *rval;
1098
1099     zh->trans_no--;
1100     if (zh->trans_no != 0)
1101         return;
1102
1103     yaz_log (LOG_LOG, "zebra_end_trans");
1104     rval = res_get (zh->res, "shadow");
1105
1106     zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1107
1108     zebra_flush_reg (zh);
1109
1110     zebra_register_close (zh->service, zh->reg);
1111     zh->reg = 0;
1112
1113     
1114     yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1115              zh->records_processed, zh->records_inserted,
1116              zh->records_updated, zh->records_deleted);
1117
1118     zebra_get_state (zh, &val, &seqno);
1119     if (val != 'd')
1120     {
1121         BFiles bfs = bfs_create (rval, zh->path_reg);
1122         yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1123         bf_commitClean (bfs, rval);
1124         bfs_destroy (bfs);
1125     }
1126     if (!rval)
1127         seqno++;
1128     zebra_set_state (zh, 'o', seqno);
1129
1130     zebra_unlock (zh->lock_shadow);
1131     zebra_unlock (zh->lock_normal);
1132
1133 #if HAVE_SYS_TIMES_H
1134     times (&zh->tms2);
1135     logf (LOG_LOG, "user/system: %ld/%ld",
1136                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1137                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1138
1139 #endif
1140 }
1141
1142 void zebra_repository_update (ZebraHandle zh)
1143 {
1144     zebra_begin_trans (zh);
1145     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1146     repositoryUpdate (zh);    
1147     zebra_end_trans (zh);
1148 }
1149
1150 void zebra_repository_delete (ZebraHandle zh)
1151 {
1152     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1153     repositoryDelete (zh);
1154 }
1155
1156 void zebra_repository_show (ZebraHandle zh)
1157 {
1158     repositoryShow (zh);
1159 }
1160
1161 int zebra_commit (ZebraHandle zh)
1162 {
1163     int seqno;
1164     char val;
1165     const char *rval;
1166     BFiles bfs;
1167
1168     if (!zh->res)
1169     {
1170         zh->errCode = 109;
1171         return -1;
1172     }
1173     rval = res_get (zh->res, "shadow");    
1174     if (!rval)
1175     {
1176         logf (LOG_WARN, "Cannot perform commit");
1177         logf (LOG_WARN, "No shadow area defined");
1178         return 0;
1179     }
1180
1181     zebra_lock_w (zh->lock_normal);
1182     zebra_lock_r (zh->lock_shadow);
1183
1184     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1185
1186     zebra_get_state (zh, &val, &seqno);
1187
1188     if (rval && *rval)
1189         bf_cache (bfs, rval);
1190     if (bf_commitExists (bfs))
1191     {
1192         zebra_set_state (zh, 'c', seqno);
1193
1194         logf (LOG_LOG, "commit start");
1195         bf_commitExec (bfs);
1196 #ifndef WIN32
1197         sync ();
1198 #endif
1199         logf (LOG_LOG, "commit clean");
1200         bf_commitClean (bfs, rval);
1201         seqno++;
1202         zebra_set_state (zh, 'o', seqno);
1203     }
1204     else
1205     {
1206         logf (LOG_LOG, "nothing to commit");
1207     }
1208     bfs_destroy (bfs);
1209
1210     zebra_unlock (zh->lock_shadow);
1211     zebra_unlock (zh->lock_normal);
1212     return 0;
1213 }
1214
1215 int zebra_init (ZebraHandle zh)
1216 {
1217     const char *rval;
1218     BFiles bfs = 0;
1219
1220     if (!zh->res)
1221     {
1222         zh->errCode = 109;
1223         return -1;
1224     }
1225     rval = res_get (zh->res, "shadow");
1226
1227     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1228                       zh->path_reg);
1229     if (rval && *rval)
1230         bf_cache (bfs, rval);
1231     
1232     bf_reset (bfs);
1233     bfs_destroy (bfs);
1234     zebra_set_state (zh, 'o', 0);
1235     return 0;
1236 }
1237
1238 int zebra_compact (ZebraHandle zh)
1239 {
1240     BFiles bfs;
1241     if (!zh->res)
1242     {
1243         zh->errCode = 109;
1244         return -1;
1245     }
1246     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1247     inv_compact (bfs);
1248     bfs_destroy (bfs);
1249     return 0;
1250 }
1251
1252 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1253 {
1254     int sysno = 0;
1255     zebra_begin_trans (zh);
1256     extract_rec_in_mem (zh, "grs.sgml",
1257                         buf, len,
1258                         "Default",  /* database */
1259                         0 /* delete_flag */,
1260                         0 /* test_mode */,
1261                         &sysno /* sysno */,
1262                         1 /* store_keys */,
1263                         1 /* store_data */,
1264                         0 /* match criteria */);
1265     zebra_end_trans (zh);
1266     return sysno;
1267 }
1268
1269 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1270 {
1271     memcpy (&zh->rGroup, rg, sizeof(*rg));
1272 }
1273
1274 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1275 {
1276     *code = zh->errCode;
1277     *addinfo = zh->errString;
1278 }
1279
1280 void zebra_shadow_enable (ZebraHandle zh, int value)
1281 {
1282     zh->shadow_enable = value;
1283 }
1284