Work on ES Update
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.73 2002-09-17 12:27:12 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     zebra_mutex_cond_lock (&zs->session_lock);
393     while (zs->sessions)
394     {
395         zebra_close (zs->sessions);
396     }
397         
398     zebra_mutex_cond_unlock (&zs->session_lock);
399
400     zebra_mutex_cond_destroy (&zs->session_lock);
401
402     if (zs->passwd_db)
403         passwd_db_close (zs->passwd_db);
404
405     res_close (zs->global_res);
406     xfree (zs->configName);
407     xfree (zs->path_root);
408     xfree (zs);
409 }
410
411 void zebra_close (ZebraHandle zh)
412 {
413     ZebraService zs;
414     struct zebra_session **sp;
415
416     if (!zh)
417         return;
418
419     zs = zh->service;
420     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
421     if (!zh)
422         return ;
423     resultSetDestroy (zh, -1, 0, 0);
424
425
426     if (zh->reg)
427         zebra_register_close (zh->service, zh->reg);
428     zebra_close_res (zh);
429
430     xfree (zh->record_encoding);
431
432     if (zh->iconv_to_utf8 != 0)
433         yaz_iconv_close (zh->iconv_to_utf8);
434     if (zh->iconv_from_utf8 != 0)
435         yaz_iconv_close (zh->iconv_from_utf8);
436
437     xfree (zh->admin_databaseName);
438     zebra_mutex_cond_lock (&zs->session_lock);
439     zebra_lock_destroy (zh->lock_normal);
440     zebra_lock_destroy (zh->lock_shadow);
441     sp = &zs->sessions;
442     while (1)
443     {
444         assert (*sp);
445         if (*sp == zh)
446         {
447             *sp = (*sp)->next;
448             break;
449         }
450         sp = &(*sp)->next;
451     }
452 //    if (!zs->sessions && zs->stop_flag)
453 //      zebra_register_deactivate(zs);
454     zebra_mutex_cond_unlock (&zs->session_lock);
455     xfree (zh->reg_name);
456     xfree (zh);
457 }
458
459 struct map_baseinfo {
460     ZebraHandle zh;
461     NMEM mem;
462     int num_bases;
463     char **basenames;
464     int new_num_bases;
465     char **new_basenames;
466     int new_num_max;
467 };
468
469 static Res zebra_open_res (ZebraHandle zh)
470 {
471     Res res = 0;
472     char fname[512];
473     if (zh->path_reg)
474     {
475         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
476         res = res_open (fname, zh->service->global_res);
477         if (!res)
478             res = zh->service->global_res;
479     }
480     else if (*zh->reg_name == 0)
481     {
482         res = zh->service->global_res;
483     }
484     else
485     {
486         yaz_log (LOG_WARN, "no register root specified");
487         return 0;  /* no path for register - fail! */
488     }
489     return res;
490 }
491
492 static void zebra_close_res (ZebraHandle zh)
493 {
494     if (zh->res != zh->service->global_res)
495         res_close (zh->res);
496     zh->res = 0;
497 }
498
499 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
500 {
501     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
502         return 0;
503     if (!zh->res)
504     {
505         assert (zh->reg == 0);
506         assert (*zh->reg_name == 0);
507     }
508     else
509     {
510         if (zh->reg)
511         {
512             resultSetInvalidate (zh);
513             zebra_register_close (zh->service, zh->reg);
514             zh->reg = 0;
515         }
516         zebra_close_res(zh);
517     }
518     xfree (zh->reg_name);
519     zh->reg_name = xstrdup (new_reg);
520
521     xfree (zh->path_reg);
522     zh->path_reg = 0;
523     if (zh->service->path_root)
524     {
525         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
526                                 strlen(zh->reg_name) + 3);
527         strcpy (zh->path_reg, zh->service->path_root);
528         if (*zh->reg_name)
529         {
530             strcat (zh->path_reg, "/");
531             strcat (zh->path_reg, zh->reg_name);
532         }
533     }
534     zh->res = zebra_open_res (zh);
535     
536     if (zh->lock_normal)
537         zebra_lock_destroy (zh->lock_normal);
538     zh->lock_normal = 0;
539
540     if (zh->lock_shadow)
541         zebra_lock_destroy (zh->lock_shadow);
542     zh->lock_shadow = 0;
543
544     if (zh->res)
545     {
546         char fname[512];
547         const char *lock_area  =res_get (zh->res, "lockDir");
548         
549         if (!lock_area && zh->path_reg)
550             res_put (zh->res, "lockDir", zh->path_reg);
551         sprintf (fname, "norm.%s.LCK", zh->reg_name);
552         zh->lock_normal =
553             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
554         
555         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
556         zh->lock_shadow =
557             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
558
559     }
560     return 1;
561 }
562
563 void map_basenames_func (void *vp, const char *name, const char *value)
564 {
565     struct map_baseinfo *p = (struct map_baseinfo *) vp;
566     int i, no;
567     char fromdb[128], todb[8][128];
568     
569     no =
570         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
571                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
572                 todb[5], todb[6], todb[7]);
573     if (no < 2)
574         return ;
575     no--;
576     for (i = 0; i<p->num_bases; i++)
577         if (p->basenames[i] && !strcmp (p->basenames[i], fromdb))
578         {
579             p->basenames[i] = 0;
580             for (i = 0; i < no; i++)
581             {
582                 if (p->new_num_bases == p->new_num_max)
583                     return;
584                 p->new_basenames[(p->new_num_bases)++] = 
585                     nmem_strdup (p->mem, todb[i]);
586             }
587             return;
588         }
589 }
590
591 void map_basenames (ZebraHandle zh, ODR stream,
592                     int *num_bases, char ***basenames)
593 {
594     struct map_baseinfo info;
595     struct map_baseinfo *p = &info;
596     int i;
597
598     info.zh = zh;
599     info.num_bases = *num_bases;
600     info.basenames = *basenames;
601     info.new_num_max = 128;
602     info.new_num_bases = 0;
603     info.new_basenames = (char **)
604         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
605     info.mem = stream->mem;
606
607     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
608     
609     for (i = 0; i<p->num_bases; i++)
610         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
611         {
612             p->new_basenames[(p->new_num_bases)++] = 
613                 nmem_strdup (p->mem, p->basenames[i]);
614         }
615     *num_bases = info.new_num_bases;
616     *basenames = info.new_basenames;
617     for (i = 0; i<*num_bases; i++)
618         logf (LOG_LOG, "base %s", (*basenames)[i]);
619 }
620
621 int zebra_select_database (ZebraHandle zh, const char *basename)
622 {
623     return zebra_select_databases (zh, 1, &basename);
624 }
625
626 int zebra_select_databases (ZebraHandle zh, int num_bases,
627                             const char **basenames)
628 {
629     int i;
630     const char *cp;
631     int len = 0;
632     char *new_reg = 0;
633     
634     if (num_bases < 1)
635     {
636         zh->errCode = 23;
637         return -1;
638     }
639     for (i = 0; i < zh->num_basenames; i++)
640         xfree (zh->basenames[i]);
641     xfree (zh->basenames);
642     
643     zh->num_basenames = num_bases;
644     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
645     for (i = 0; i < zh->num_basenames; i++)
646         zh->basenames[i] = xstrdup (basenames[i]);
647
648     cp = strrchr(basenames[0], '/');
649     if (cp)
650     {
651         len = cp - basenames[0];
652         new_reg = xmalloc (len + 1);
653         memcpy (new_reg, basenames[0], len);
654         new_reg[len] = '\0';
655     }
656     else
657         new_reg = xstrdup ("");
658     for (i = 1; i<num_bases; i++)
659     {
660         const char *cp1;
661
662         cp1 = strrchr (basenames[i], '/');
663         if (cp)
664         {
665             if (!cp1)
666             {
667                 zh->errCode = 23;
668                 return -1;
669             }
670             if (len != cp1 - basenames[i] ||
671                 memcmp (basenames[i], new_reg, len))
672             {
673                 zh->errCode = 23;
674                 return -1;
675             }
676         }
677         else
678         {
679             if (cp1)
680             {
681                 zh->errCode = 23;
682                 return -1;
683             }
684         }
685     }
686     zebra_select_register (zh, new_reg);
687     xfree (new_reg);
688     if (!zh->res)
689     {
690         zh->errCode = 109;
691         return -1;
692     }
693     if (!zh->lock_normal || !zh->lock_shadow)
694     {
695         zh->errCode = 2;
696         return -1;
697     }
698     return 0;
699 }
700
701 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
702                        Z_RPNQuery *query, const char *setname, int *hits)
703 {
704     zh->hits = 0;
705     *hits = 0;
706
707     if (zebra_begin_read (zh))
708         return;
709     resultSetAddRPN (zh, decode, stream, query, 
710                      zh->num_basenames, zh->basenames, setname);
711
712     zebra_end_read (zh);
713
714     *hits = zh->hits;
715 }
716
717 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
718                              const char *setname, Z_RecordComposition *comp,
719                              oid_value input_format, int num_recs,
720                              ZebraRetrievalRecord *recs)
721 {
722     ZebraPosSet poset;
723     int i, *pos_array;
724
725     if (!zh->res)
726     {
727         zh->errCode = 30;
728         zh->errString = odr_strdup (stream, setname);
729         return;
730     }
731     
732     zh->errCode = 0;
733
734     if (zebra_begin_read (zh))
735         return;
736
737     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
738     for (i = 0; i<num_recs; i++)
739         pos_array[i] = recs[i].position;
740     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
741     if (!poset)
742     {
743         logf (LOG_DEBUG, "zebraPosSetCreate error");
744         zh->errCode = 30;
745         zh->errString = nmem_strdup (stream->mem, setname);
746     }
747     else
748     {
749         for (i = 0; i<num_recs; i++)
750         {
751             if (poset[i].term)
752             {
753                 recs[i].errCode = 0;
754                 recs[i].format = VAL_SUTRS;
755                 recs[i].len = strlen(poset[i].term);
756                 recs[i].buf = poset[i].term;
757                 recs[i].base = poset[i].db;
758             }
759             else if (poset[i].sysno)
760             {
761                 recs[i].errCode =
762                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
763                                         stream, input_format, comp,
764                                         &recs[i].format, &recs[i].buf,
765                                         &recs[i].len,
766                                         &recs[i].base);
767                 recs[i].errString = NULL;
768             }
769             else
770             {
771                 char num_str[20];
772
773                 sprintf (num_str, "%d", pos_array[i]);  
774                 zh->errCode = 13;
775                 zh->errString = odr_strdup (stream, num_str);
776                 break;
777             }
778         }
779         zebraPosSetDestroy (zh, poset, num_recs);
780     }
781     zebra_end_read (zh);
782     xfree (pos_array);
783 }
784
785 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
786                  oid_value attributeset,
787                  int *position, int *num_entries, ZebraScanEntry **entries,
788                  int *is_partial)
789 {
790     if (zebra_begin_read (zh))
791     {
792         *entries = 0;
793         *num_entries = 0;
794         return;
795     }
796     rpn_scan (zh, stream, zapt, attributeset,
797               zh->num_basenames, zh->basenames, position,
798               num_entries, entries, is_partial);
799     zebra_end_read (zh);
800 }
801
802 void zebra_sort (ZebraHandle zh, ODR stream,
803                  int num_input_setnames, const char **input_setnames,
804                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
805                  int *sort_status)
806 {
807     if (zebra_begin_read (zh))
808         return;
809     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
810                    output_setname, sort_sequence, sort_status);
811     zebra_end_read(zh);
812 }
813
814 int zebra_deleleResultSet(ZebraHandle zh, int function,
815                           int num_setnames, char **setnames,
816                           int *statuses)
817 {
818     int i, status;
819     if (zebra_begin_read(zh))
820         return Z_DeleteStatus_systemProblemAtTarget;
821     switch (function)
822     {
823     case Z_DeleteRequest_list:
824         resultSetDestroy (zh, num_setnames, setnames, statuses);
825         break;
826     case Z_DeleteRequest_all:
827         resultSetDestroy (zh, -1, 0, statuses);
828         break;
829     }
830     zebra_end_read (zh);
831     status = Z_DeleteStatus_success;
832     for (i = 0; i<num_setnames; i++)
833         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
834             status = statuses[i];
835     return status;
836 }
837
838 int zebra_errCode (ZebraHandle zh)
839 {
840     return zh->errCode;
841 }
842
843 const char *zebra_errString (ZebraHandle zh)
844 {
845     return diagbib1_str (zh->errCode);
846 }
847
848 char *zebra_errAdd (ZebraHandle zh)
849 {
850     return zh->errString;
851 }
852
853 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
854 {
855     ZebraService zs = zh->service;
856     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
857     {
858         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
859         return 0;
860     }
861
862     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
863     return 1;
864 }
865
866 void zebra_admin_import_begin (ZebraHandle zh, const char *database,
867                                const char *record_type)
868 {
869     if (zebra_select_database(zh, database))
870         return;
871     zebra_begin_trans (zh);
872     xfree (zh->admin_databaseName);
873     zh->admin_databaseName = xstrdup(database);
874 }
875
876 void zebra_admin_import_end (ZebraHandle zh)
877 {
878     zebra_end_trans (zh);
879 }
880
881 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
882 {
883     int sysno;
884     int i;
885     for (i = 0; i<segment->num_segmentRecords; i++)
886     {
887         Z_NamePlusRecord *npr = segment->segmentRecords[i];
888         const char *databaseName = npr->databaseName;
889
890         if (!databaseName)
891             databaseName = zh->admin_databaseName;
892         printf ("--------------%d--------------------\n", i);
893         if (npr->which == Z_NamePlusRecord_intermediateFragment)
894         {
895             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
896             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
897             {
898                 Odr_oct *oct = fragment->u.notExternallyTagged;
899                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
900                         oct->buf);
901                 
902                 sysno = 0;
903                 extract_rec_in_mem (zh, "grs.sgml",
904                                     oct->buf, oct->len,
905                                     databaseName,
906                                     0 /* delete_flag */,
907                                     0 /* test_mode */,
908                                     &sysno /* sysno */,
909                                     1 /* store_keys */,
910                                     1 /* store_data */,
911                                     0 /* match criteria */);
912             }
913         }
914     }
915 }
916
917 int zebra_admin_exchange_record (ZebraHandle zh,
918                                  const char *database,
919                                  const char *rec_buf,
920                                  size_t rec_len,
921                                  const char *recid_buf, size_t recid_len,
922                                  int action)
923 {
924     int sysno = 0;
925     char *rinfo = 0;
926     char recid_z[256];
927
928     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
929         return -1;
930     memcpy (recid_z, recid_buf, recid_len);
931     recid_z[recid_len] = 0;
932
933     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
934     if (rinfo)
935     {
936         if (action == 1)  /* fail if insert */
937             return -1;
938         memcpy (&sysno, rinfo+1, sizeof(sysno));
939     }
940     else
941     {
942         if (action == 2 || action == 3) /* fail if delete or update */
943             return -1;
944     }
945     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
946                         action == 3 ? 1 : 0 /* delete flag */,
947                         0, &sysno, 1, 1, 0);
948     if (action == 1)
949     {
950         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
951     }
952     else if (action == 3)
953     {
954         dict_delete (zh->reg->matchDict, recid_z);
955     }
956     return 0;
957 }
958
959 void zebra_admin_create (ZebraHandle zh, const char *database)
960 {
961     ZebraService zs;
962
963     if (zebra_select_database (zh, database))
964         return;
965     zebra_begin_trans (zh);
966
967     zs = zh->service;
968     /* announce database */
969     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
970                                   /* explainDatabase */))
971     {
972         zh->errCode = 224;
973         zh->errString = "database already exist";
974     }
975     zebra_end_trans (zh);
976 }
977
978 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
979                        const char *input_str, int input_len,
980                        char *output_str, int output_len)
981 {
982     WRBUF wrbuf;
983     if (!zh->reg->zebra_maps)
984         return -1;
985     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
986                           input_str, input_len);
987     if (!wrbuf)
988         return -2;
989     if (wrbuf_len(wrbuf) >= output_len)
990         return -3;
991     if (wrbuf_len(wrbuf))
992         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
993     output_str[wrbuf_len(wrbuf)] = '\0';
994     return wrbuf_len(wrbuf);
995 }
996
997
998 void zebra_set_state (ZebraHandle zh, int val, int seqno)
999 {
1000     char state_fname[256];
1001     char *fname;
1002     long p = getpid();
1003     FILE *f;
1004
1005     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1006     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1007     f = fopen (fname, "w");
1008
1009     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1010     fprintf (f, "%c %d %ld\n", val, seqno, p);
1011     fclose (f);
1012     xfree (fname);
1013 }
1014
1015 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1016 {
1017     char state_fname[256];
1018     char *fname;
1019     FILE *f;
1020
1021     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1022     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1023     f = fopen (fname, "r");
1024     *val = 'o';
1025     *seqno = 0;
1026
1027     if (f)
1028     {
1029         fscanf (f, "%c %d", val, seqno);
1030         fclose (f);
1031     }
1032     xfree (fname);
1033 }
1034
1035 int zebra_begin_read (ZebraHandle zh)
1036 {
1037     int dirty = 0;
1038     char val;
1039     int seqno;
1040
1041     assert (zh->res);
1042
1043     (zh->trans_no)++;
1044
1045     if (zh->trans_no != 1)
1046     {
1047         zebra_flush_reg (zh);
1048         return 0;
1049     }
1050 #if HAVE_SYS_TIMES_H
1051     times (&zh->tms1);
1052 #endif
1053     if (!zh->res)
1054     {
1055         (zh->trans_no)--;
1056         zh->errCode = 109;
1057         return -1;
1058     }
1059     if (!zh->lock_normal || !zh->lock_shadow)
1060     {
1061         (zh->trans_no)--;
1062         zh->errCode = 2;
1063         return -1;
1064     }
1065     zebra_get_state (zh, &val, &seqno);
1066     if (val == 'd')
1067         val = 'o';
1068
1069     if (!zh->reg)
1070         dirty = 1;
1071     else if (seqno != zh->reg->seqno)
1072     {
1073         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1074                  seqno, zh->reg->seqno);
1075         dirty = 1;
1076     }
1077     else if (zh->reg->last_val != val)
1078     {
1079         yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1080                  val, zh->reg->last_val);
1081         dirty = 1;
1082     }
1083     if (!dirty)
1084         return 0;
1085
1086     if (val == 'c')
1087         zebra_lock_r (zh->lock_shadow);
1088     else
1089         zebra_lock_r (zh->lock_normal);
1090     
1091     if (zh->reg)
1092         zebra_register_close (zh->service, zh->reg);
1093     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1094                                    0, val == 'c' ? 1 : 0,
1095                                    zh->res, zh->path_reg);
1096     if (!zh->reg)
1097     {
1098         zh->errCode = 109;
1099         return -1;
1100     }
1101     zh->reg->last_val = val;
1102     zh->reg->seqno = seqno;
1103
1104     return 0;
1105 }
1106
1107 void zebra_end_read (ZebraHandle zh)
1108 {
1109     (zh->trans_no)--;
1110
1111     if (zh->trans_no != 0)
1112         return;
1113
1114 #if HAVE_SYS_TIMES_H
1115     times (&zh->tms2);
1116     logf (LOG_LOG, "user/system: %ld/%ld",
1117                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1118                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1119
1120 #endif
1121
1122     zebra_unlock (zh->lock_normal);
1123     zebra_unlock (zh->lock_shadow);
1124 }
1125
1126 void zebra_begin_trans (ZebraHandle zh)
1127 {
1128     int pass;
1129     int seqno = 0;
1130     char val = '?';
1131     const char *rval = 0;
1132
1133     assert (zh->res);
1134
1135     (zh->trans_no++);
1136     if (zh->trans_no != 1)
1137     {
1138         return;
1139     }
1140     
1141     yaz_log (LOG_LOG, "zebra_begin_trans");
1142
1143     zh->records_inserted = 0;
1144     zh->records_updated = 0;
1145     zh->records_deleted = 0;
1146     zh->records_processed = 0;
1147
1148 #if HAVE_SYS_TIMES_H
1149     times (&zh->tms1);
1150 #endif
1151     
1152     /* lock */
1153     if (zh->shadow_enable)
1154         rval = res_get (zh->res, "shadow");
1155
1156     for (pass = 0; pass < 2; pass++)
1157     {
1158         if (rval)
1159         {
1160             zebra_lock_r (zh->lock_normal);
1161             zebra_lock_w (zh->lock_shadow);
1162         }
1163         else
1164         {
1165             zebra_lock_w (zh->lock_normal);
1166             zebra_lock_w (zh->lock_shadow);
1167         }
1168         
1169         zebra_get_state (zh, &val, &seqno);
1170         if (val == 'c')
1171         {
1172             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1173             zebra_unlock (zh->lock_shadow);
1174             zebra_unlock (zh->lock_normal);
1175             zebra_commit (zh);
1176             continue;
1177         }
1178         else if (val == 'd')
1179         {
1180             if (rval)
1181             {
1182                 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1183                                          zh->path_reg);
1184                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1185                 bf_commitClean (bfs, rval);
1186                 bfs_destroy (bfs);
1187             }
1188             else
1189             {
1190                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1191             }
1192         }
1193         break;
1194     }
1195     if (pass == 2)
1196     {
1197         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1198         abort();
1199         return;
1200     }
1201     zebra_set_state (zh, 'd', seqno);
1202
1203     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1204                                    1, rval ? 1 : 0, zh->res,
1205                                    zh->path_reg);
1206
1207     zh->reg->seqno = seqno;
1208 }
1209
1210 void zebra_end_trans (ZebraHandle zh)
1211 {
1212     char val;
1213     int seqno;
1214     const char *rval;
1215
1216     zh->trans_no--;
1217     if (zh->trans_no != 0)
1218         return;
1219
1220     yaz_log (LOG_LOG, "zebra_end_trans");
1221     rval = res_get (zh->res, "shadow");
1222
1223     zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1224
1225     zebra_flush_reg (zh);
1226
1227     zebra_register_close (zh->service, zh->reg);
1228     zh->reg = 0;
1229
1230     
1231     yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1232              zh->records_processed, zh->records_inserted,
1233              zh->records_updated, zh->records_deleted);
1234
1235     zebra_get_state (zh, &val, &seqno);
1236     if (val != 'd')
1237     {
1238         BFiles bfs = bfs_create (rval, zh->path_reg);
1239         yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1240         bf_commitClean (bfs, rval);
1241         bfs_destroy (bfs);
1242     }
1243     if (!rval)
1244         seqno++;
1245     zebra_set_state (zh, 'o', seqno);
1246
1247     zebra_unlock (zh->lock_shadow);
1248     zebra_unlock (zh->lock_normal);
1249
1250 #if HAVE_SYS_TIMES_H
1251     times (&zh->tms2);
1252     logf (LOG_LOG, "user/system: %ld/%ld",
1253                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1254                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1255
1256 #endif
1257 }
1258
1259 void zebra_repository_update (ZebraHandle zh)
1260 {
1261     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1262     repositoryUpdate (zh);    
1263 }
1264
1265 void zebra_repository_delete (ZebraHandle zh)
1266 {
1267     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1268     repositoryDelete (zh);
1269 }
1270
1271 void zebra_repository_show (ZebraHandle zh)
1272 {
1273     repositoryShow (zh);
1274 }
1275
1276 int zebra_commit (ZebraHandle zh)
1277 {
1278     int seqno;
1279     char val;
1280     const char *rval;
1281     BFiles bfs;
1282
1283     if (!zh->res)
1284     {
1285         zh->errCode = 109;
1286         return -1;
1287     }
1288     rval = res_get (zh->res, "shadow");    
1289     if (!rval)
1290     {
1291         logf (LOG_WARN, "Cannot perform commit");
1292         logf (LOG_WARN, "No shadow area defined");
1293         return 0;
1294     }
1295
1296     zebra_lock_w (zh->lock_normal);
1297     zebra_lock_r (zh->lock_shadow);
1298
1299     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1300
1301     zebra_get_state (zh, &val, &seqno);
1302
1303     if (rval && *rval)
1304         bf_cache (bfs, rval);
1305     if (bf_commitExists (bfs))
1306     {
1307         zebra_set_state (zh, 'c', seqno);
1308
1309         logf (LOG_LOG, "commit start");
1310         bf_commitExec (bfs);
1311 #ifndef WIN32
1312         sync ();
1313 #endif
1314         logf (LOG_LOG, "commit clean");
1315         bf_commitClean (bfs, rval);
1316         seqno++;
1317         zebra_set_state (zh, 'o', seqno);
1318     }
1319     else
1320     {
1321         logf (LOG_LOG, "nothing to commit");
1322     }
1323     bfs_destroy (bfs);
1324
1325     zebra_unlock (zh->lock_shadow);
1326     zebra_unlock (zh->lock_normal);
1327     return 0;
1328 }
1329
1330 int zebra_init (ZebraHandle zh)
1331 {
1332     const char *rval;
1333     BFiles bfs = 0;
1334
1335     if (!zh->res)
1336     {
1337         zh->errCode = 109;
1338         return -1;
1339     }
1340     rval = res_get (zh->res, "shadow");
1341
1342     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1343                       zh->path_reg);
1344     if (rval && *rval)
1345         bf_cache (bfs, rval);
1346     
1347     bf_reset (bfs);
1348     bfs_destroy (bfs);
1349     zebra_set_state (zh, 'o', 0);
1350     return 0;
1351 }
1352
1353 int zebra_compact (ZebraHandle zh)
1354 {
1355     BFiles bfs;
1356     if (!zh->res)
1357     {
1358         zh->errCode = 109;
1359         return -1;
1360     }
1361     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1362     inv_compact (bfs);
1363     bfs_destroy (bfs);
1364     return 0;
1365 }
1366
1367 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1368 {
1369     int sysno = 0;
1370     zebra_begin_trans (zh);
1371     extract_rec_in_mem (zh, "grs.sgml",
1372                         buf, len,
1373                         "Default",  /* database */
1374                         0 /* delete_flag */,
1375                         0 /* test_mode */,
1376                         &sysno /* sysno */,
1377                         1 /* store_keys */,
1378                         1 /* store_data */,
1379                         0 /* match criteria */);
1380     zebra_end_trans (zh);
1381     return sysno;
1382 }
1383
1384 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1385 {
1386     memcpy (&zh->rGroup, rg, sizeof(*rg));
1387 }
1388
1389 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1390 {
1391     *code = zh->errCode;
1392     *addinfo = zh->errString;
1393 }
1394
1395 void zebra_shadow_enable (ZebraHandle zh, int value)
1396 {
1397     zh->shadow_enable = value;
1398 }
1399
1400 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1401 {
1402     xfree (zh->record_encoding);
1403     zh->record_encoding = xstrdup (encoding);
1404     return 0;
1405 }