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