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