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