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