Minor leak fixes - in case if zebra_register_open fail.
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.205 2006-03-25 15:33:29 adam Exp $
2    Copyright (C) 1995-2005
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 #include <assert.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #ifdef WIN32
27 #include <io.h>
28 #include <process.h>
29 #include <direct.h>
30 #endif
31 #if HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include <yaz/diagbib1.h>
36 #include <yaz/pquery.h>
37 #include <yaz/sortspec.h>
38 #include "index.h"
39 #include "orddict.h"
40 #include <charmap.h>
41 #include <idzebra/api.h>
42
43 #define DEFAULT_APPROX_LIMIT 2000000000
44
45 /* simple asserts to validate the most essential input args */
46 #define ASSERTZH assert(zh && zh->service)
47 #define ASSERTZHRES assert(zh && zh->service && zh->res)
48 #define ASSERTZS assert(zs)
49
50 static int log_level = 0;
51 static int log_level_initialized = 0;
52
53 static void zebra_open_res(ZebraHandle zh);
54 static void zebra_close_res(ZebraHandle zh);
55
56 static void zebra_chdir (ZebraService zs)
57 {
58     const char *dir ;
59     ASSERTZS;
60     yaz_log(log_level, "zebra_chdir");
61     dir = res_get (zs->global_res, "chdir");
62     if (!dir)
63         return;
64     yaz_log (YLOG_DEBUG, "chdir %s", dir);
65 #ifdef WIN32
66     _chdir(dir);
67 #else
68     chdir (dir);
69 #endif
70 }
71
72 static void zebra_flush_reg (ZebraHandle zh)
73 {
74     ASSERTZH;
75     yaz_log(log_level, "zebra_flush_reg");
76     zebraExplain_flush (zh->reg->zei, zh);
77     
78     extract_flushWriteKeys (zh, 1 /* final */);
79     zebra_index_merge (zh );
80 }
81
82 static struct zebra_register *zebra_register_open(ZebraService zs, 
83                                                   const char *name,
84                                                   int rw, int useshadow,
85                                                   Res res,
86                                                   const char *reg_path);
87 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
88
89 ZebraHandle zebra_open(ZebraService zs, Res res)
90 {
91     ZebraHandle zh;
92     const char *default_encoding;
93     if (!log_level_initialized)
94     {
95         log_level = yaz_log_module_level("zebraapi");
96         log_level_initialized = 1;
97     }
98
99     yaz_log(log_level, "zebra_open");
100
101     if (!zs)
102         return 0;
103
104     zh = (ZebraHandle) xmalloc(sizeof(*zh));
105     yaz_log (YLOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
106
107     zh->service = zs;
108     zh->reg = 0;          /* no register attached yet */
109     zh->sets = 0;
110     zh->destroyed = 0;
111     zh->errCode = 0;
112     zh->errString = 0;
113     zh->res = 0; 
114     zh->session_res = res_open(zs->global_res, res);
115     zh->user_perm = 0;
116     zh->dbaccesslist = 0;
117
118     zh->reg_name = xstrdup ("");
119     zh->path_reg = 0;
120     zh->num_basenames = 0;
121     zh->basenames = 0;
122
123     zh->approx_limit = DEFAULT_APPROX_LIMIT;
124     zh->trans_no = 0;
125     zh->trans_w_no = 0;
126
127     zh->lock_normal = 0;
128     zh->lock_shadow = 0;
129
130     zh->shadow_enable = 1;
131     zh->m_staticrank = 0;
132
133     default_encoding = res_get_def(zh->session_res, "encoding", "ISO-8859-1");
134
135     zh->iconv_to_utf8 =
136         yaz_iconv_open ("UTF-8", default_encoding);
137     if (zh->iconv_to_utf8 == 0)
138         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported",
139            default_encoding);
140     zh->iconv_from_utf8 =
141         yaz_iconv_open (default_encoding, "UTF-8");
142     if (zh->iconv_to_utf8 == 0)
143         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported",
144            default_encoding);
145
146     zh->record_encoding = 0;
147
148     zebra_mutex_cond_lock (&zs->session_lock);
149
150     zh->next = zs->sessions;
151     zs->sessions = zh;
152
153     zebra_mutex_cond_unlock (&zs->session_lock);
154
155     zh->store_data_buf = 0;
156
157     zh->m_limit = zebra_limit_create(1, 0);
158
159     zh->nmem_error = nmem_create();
160
161     return zh;
162 }
163
164 ZebraService zebra_start (const char *configName)
165 {
166     return zebra_start_res(configName, 0, 0);
167 }
168
169 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
170 {
171     Res res;
172
173     if (!log_level_initialized)
174     {
175         log_level = yaz_log_module_level("zebraapi");
176         log_level_initialized = 1;
177     }
178     
179     yaz_log(YLOG_LOG, "zebra_start %s %s", ZEBRAVER,
180             configName ? configName : "");
181
182     if ((res = res_open(def_res, over_res)))
183     {
184         const char *passwd_plain = 0;
185         const char *passwd_encrypt = 0;
186         const char *dbaccess = 0;
187         ZebraService zh = 0;
188
189         if (configName)
190         {
191             ZEBRA_RES ret = res_read_file(res, configName);
192             if (ret != ZEBRA_OK)
193             {
194                 res_close(res);
195                 return 0;
196             }
197         }
198         zh = xmalloc(sizeof(*zh));
199         zh->global_res = res;
200         zh->sessions = 0;
201         
202         zebra_chdir (zh);
203         
204         zebra_mutex_cond_init (&zh->session_lock);
205         passwd_plain = res_get (zh->global_res, "passwd");
206         passwd_encrypt = res_get (zh->global_res, "passwd.c");
207         dbaccess = res_get (zh->global_res, "dbaccess");
208
209         if (!passwd_plain && !passwd_encrypt)
210             zh->passwd_db = NULL;
211         else 
212         {
213             zh->passwd_db = passwd_db_open();
214             if (!zh->passwd_db)
215                 yaz_log (YLOG_WARN|YLOG_ERRNO, "passwd_db_open failed");
216             else
217             {
218                 if (passwd_plain)
219                     passwd_db_file_plain(zh->passwd_db, passwd_plain);
220                 if (passwd_encrypt)
221                     passwd_db_file_crypt(zh->passwd_db, passwd_encrypt);
222             }
223         }
224
225         if (!dbaccess)
226             zh->dbaccess = NULL;
227         else {
228             zh->dbaccess = res_open(NULL, NULL);
229             if (res_read_file(zh->dbaccess, dbaccess) != ZEBRA_OK) {
230                 yaz_log(YLOG_FATAL, "Failed to read %s", dbaccess);
231                 return NULL;
232             }
233         }
234
235         zh->path_root = res_get (zh->global_res, "root");
236         zh->nmem = nmem_create();
237         zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
238         return zh;
239     }
240     return 0;
241 }
242
243 void zebra_filter_info(ZebraService zs, void *cd,
244                         void (*cb)(void *cd, const char *name))
245 {
246     ASSERTZS;
247     assert(cb);
248     recTypeClass_info(zs->record_classes, cd, cb);
249 }
250
251 void zebra_pidfname(ZebraService zs, char *path)
252 {
253     ASSERTZS;
254     zebra_lock_prefix (zs->global_res, path);
255     strcat(path, "zebrasrv.pid");
256 }
257
258 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
259                     int compact_flag, Res res)
260 {
261     int page_size = 4096;
262     char resource_str[200];
263     sprintf (resource_str, "dict.%.100s.pagesize", name);
264     assert(bfs);
265     assert(name);
266
267     if (res_get_int(res, resource_str, &page_size) == ZEBRA_OK)
268         yaz_log(YLOG_LOG, "Using custom dictionary page size %d for %s",
269                 page_size, name);
270     return dict_open(bfs, name, cache, rw, compact_flag, page_size);
271 }
272
273 static
274 struct zebra_register *zebra_register_open(ZebraService zs, const char *name,
275                                            int rw, int useshadow, Res res,
276                                            const char *reg_path)
277 {
278     struct zebra_register *reg;
279     int record_compression = REC_COMPRESS_NONE;
280     const char *recordCompression = 0;
281     const char *profilePath;
282     char cwd[1024];
283
284     ASSERTZS;
285     
286     reg = xmalloc(sizeof(*reg));
287
288     assert (name);
289     reg->name = xstrdup (name);
290
291     reg->seqno = 0;
292     reg->last_val = 0;
293
294     assert (res);
295
296     yaz_log (YLOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
297              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
298     
299     reg->dh = data1_createx (DATA1_FLAG_XML);
300     if (!reg->dh)
301     {
302         xfree(reg->name);
303         xfree(reg);
304         return 0;
305     }
306     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
307     if (!reg->bfs)
308     {
309         data1_destroy(reg->dh);
310         xfree(reg->name);
311         xfree(reg);
312         return 0;
313     }
314     if (useshadow)
315     {
316         if (bf_cache (reg->bfs, res_get (res, "shadow")) == ZEBRA_FAIL)
317         {
318             bfs_destroy(reg->bfs);
319             data1_destroy(reg->dh);
320             xfree(reg->name);
321             xfree(reg);
322             return 0;
323         }
324     }
325
326     getcwd(cwd, sizeof(cwd)-1);
327     profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
328     yaz_log(YLOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
329
330     data1_set_tabpath (reg->dh, profilePath);
331     data1_set_tabroot (reg->dh, reg_path);
332     reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
333
334     if ((reg->zebra_maps = zebra_maps_open (res, reg_path)) == 0)
335     {
336         recTypes_destroy(reg->recTypes);
337         bfs_destroy(reg->bfs);
338         data1_destroy(reg->dh);
339         xfree(reg->name);
340         xfree(reg);
341         return 0;
342     }
343
344     reg->rank_classes = NULL;
345
346     reg->key_buf = 0;
347
348     reg->keys = zebra_rec_keys_open();
349
350 #if NATTR
351     reg->sortKeys = zebra_rec_keys_open();
352 #else
353     reg->sortKeys.buf = 0;
354     reg->sortKeys.buf_max = 0;
355 #endif
356
357     reg->records = 0;
358     reg->dict = 0;
359     reg->sortIdx = 0;
360     reg->isams = 0;
361     reg->matchDict = 0;
362     reg->isamc = 0;
363     reg->isamb = 0;
364     reg->zei = 0;
365     reg->key_file_no = 0;
366     reg->ptr_i = 0;
367     
368     zebraRankInstall (reg, rank_1_class);
369     zebraRankInstall (reg, rank_zv_class);
370     zebraRankInstall (reg, rank_static_class);
371
372     recordCompression = res_get_def (res, "recordCompression", "none");
373     if (!strcmp (recordCompression, "none"))
374         record_compression = REC_COMPRESS_NONE;
375     if (!strcmp (recordCompression, "bzip2"))
376         record_compression = REC_COMPRESS_BZIP2;
377
378     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
379     {
380         yaz_log (YLOG_WARN, "rec_open failed");
381         return 0;
382     }
383     if (rw)
384     {
385         reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
386     }
387     if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
388     {
389         yaz_log (YLOG_WARN, "dict_open failed");
390         return 0;
391     }
392     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
393     {
394         yaz_log (YLOG_WARN, "sortIdx_open failed");
395         return 0;
396     }
397     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
398     {
399         struct ISAMS_M_s isams_m;
400         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
401                                       key_isams_m(res, &isams_m))))
402         {
403             yaz_log (YLOG_WARN, "isams_open failed");
404             return 0;
405         }
406     }
407     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
408     {
409         struct ISAMC_M_s isamc_m;
410         if (!(reg->isamc = isamc_open (reg->bfs, FNAME_ISAMC,
411                                     rw, key_isamc_m(res, &isamc_m))))
412         {
413             yaz_log (YLOG_WARN, "isamc_open failed");
414             return 0;
415         }
416     }
417     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
418     {
419         struct ISAMC_M_s isamc_m;
420         
421         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
422                                        rw, key_isamc_m(res, &isamc_m), 0)))
423         {
424             yaz_log (YLOG_WARN, "isamb_open failed");
425             return 0;
426         }
427     }
428     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
429     {
430         struct ISAMC_M_s isamc_m;
431         
432         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
433                                        rw, key_isamc_m(res, &isamc_m), 1)))
434         {
435             yaz_log (YLOG_WARN, "isamb_open failed");
436             return 0;
437         }
438     }
439     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
440     {
441         struct ISAMC_M_s isamc_m;
442         
443         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
444                                        rw, key_isamc_m(res, &isamc_m), -1)))
445         {
446             yaz_log (YLOG_WARN, "isamb_open failed");
447             return 0;
448         }
449     }
450     reg->zei = zebraExplain_open (reg->records, reg->dh,
451                                   res, rw, reg,
452                                   explain_extract);
453     if (!reg->zei)
454     {
455         yaz_log (YLOG_WARN, "Cannot obtain EXPLAIN information");
456         return 0;
457     }
458
459     reg->active = 2;
460     yaz_log (YLOG_DEBUG, "zebra_register_open ok p=%p", reg);
461     return reg;
462 }
463
464 ZEBRA_RES zebra_admin_shutdown (ZebraHandle zh)
465 {
466     ASSERTZH;
467     yaz_log(log_level, "zebra_admin_shutdown");
468
469     zebra_mutex_cond_lock (&zh->service->session_lock);
470     zh->service->stop_flag = 1;
471     zebra_mutex_cond_unlock (&zh->service->session_lock);
472     return ZEBRA_OK;
473 }
474
475 ZEBRA_RES zebra_admin_start (ZebraHandle zh)
476 {
477     ZebraService zs;
478     ASSERTZH;
479     yaz_log(log_level, "zebra_admin_start");
480     zs = zh->service;
481     zebra_mutex_cond_lock (&zs->session_lock);
482     zebra_mutex_cond_unlock (&zs->session_lock);
483     return ZEBRA_OK;
484 }
485
486 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
487 {
488     ASSERTZS;
489     assert(reg);
490     yaz_log(YLOG_DEBUG, "zebra_register_close p=%p", reg);
491     reg->stop_flag = 0;
492     zebra_chdir (zs);
493     if (reg->records)
494     {
495         zebraExplain_close (reg->zei);
496         dict_close (reg->dict);
497         if (reg->matchDict)
498             dict_close (reg->matchDict);
499         sortIdx_close (reg->sortIdx);
500         if (reg->isams)
501             isams_close (reg->isams);
502         if (reg->isamc)
503             isamc_close (reg->isamc);
504         if (reg->isamb)
505             isamb_close (reg->isamb);
506         rec_close (&reg->records);
507     }
508
509     recTypes_destroy (reg->recTypes);
510     zebra_maps_close (reg->zebra_maps);
511     zebraRankDestroy (reg);
512     bfs_destroy (reg->bfs);
513     data1_destroy (reg->dh);
514
515     zebra_rec_keys_close(reg->keys);
516 #if NATTR
517     zebra_rec_keys_close(reg->sortKeys);
518 #else
519     xfree(reg->sortKeys.buf);
520 #endif
521
522     xfree(reg->key_buf);
523     xfree(reg->name);
524     xfree(reg);
525 }
526
527 ZEBRA_RES zebra_stop(ZebraService zs)
528 {
529     if (!zs)
530         return ZEBRA_OK;
531     yaz_log (log_level, "zebra_stop");
532
533     while (zs->sessions)
534     {
535         zebra_close (zs->sessions);
536     }
537         
538     zebra_mutex_cond_destroy (&zs->session_lock);
539
540     if (zs->passwd_db)
541         passwd_db_close (zs->passwd_db);
542
543     recTypeClass_destroy(zs->record_classes);
544     nmem_destroy(zs->nmem);
545     res_close (zs->global_res);
546     xfree(zs);
547     return ZEBRA_OK;
548 }
549
550 ZEBRA_RES zebra_close (ZebraHandle zh)
551 {
552     ZebraService zs;
553     struct zebra_session **sp;
554     int i;
555
556     yaz_log(log_level, "zebra_close");
557     if (!zh)
558         return ZEBRA_OK;
559     ASSERTZH;
560     zh->errCode = 0;
561     
562     zs = zh->service;
563     yaz_log (YLOG_DEBUG, "zebra_close zh=%p", zh);
564     resultSetDestroy (zh, -1, 0, 0);
565
566     if (zh->reg)
567         zebra_register_close (zh->service, zh->reg);
568     zebra_close_res (zh);
569     res_close(zh->session_res);
570
571     xfree(zh->record_encoding);
572
573     xfree(zh->dbaccesslist);
574
575     for (i = 0; i < zh->num_basenames; i++)
576         xfree(zh->basenames[i]);
577     xfree(zh->basenames);
578
579     if (zh->iconv_to_utf8 != 0)
580         yaz_iconv_close (zh->iconv_to_utf8);
581     if (zh->iconv_from_utf8 != 0)
582         yaz_iconv_close (zh->iconv_from_utf8);
583
584     zebra_mutex_cond_lock (&zs->session_lock);
585     zebra_lock_destroy (zh->lock_normal);
586     zebra_lock_destroy (zh->lock_shadow);
587     sp = &zs->sessions;
588     while (1)
589     {
590         assert (*sp);
591         if (*sp == zh)
592         {
593             *sp = (*sp)->next;
594             break;
595         }
596         sp = &(*sp)->next;
597     }
598     zebra_mutex_cond_unlock (&zs->session_lock);
599     xfree(zh->reg_name);
600     xfree(zh->user_perm);
601     zh->service = 0; /* more likely to trigger an assert */
602
603     zebra_limit_destroy(zh->m_limit);
604
605     nmem_destroy(zh->nmem_error);
606
607     xfree(zh->path_reg);
608     xfree(zh);
609     return ZEBRA_OK;
610 }
611
612 struct map_baseinfo {
613     ZebraHandle zh;
614     NMEM mem;
615     int num_bases;
616     char **basenames;
617     int new_num_bases;
618     char **new_basenames;
619     int new_num_max;
620 };
621
622 static void zebra_open_res(ZebraHandle zh)
623 {
624     char fname[512];
625     ASSERTZH;
626     zh->errCode = 0;
627
628     if (zh->path_reg)
629     {
630         sprintf(fname, "%.200s/zebra.cfg", zh->path_reg);
631         zh->res = res_open(zh->session_res, 0);
632         res_read_file(zh->res, fname);
633     }
634     else if (*zh->reg_name == 0)
635     {
636         zh->res = res_open(zh->session_res, 0);
637     }
638     else
639     {
640         yaz_log (YLOG_WARN, "no register root specified");
641         zh->res = 0;  /* no path for register - fail! */
642     }
643 }
644
645 static void zebra_close_res (ZebraHandle zh)
646 {
647     ASSERTZH;
648     zh->errCode = 0;
649     res_close (zh->res);
650     zh->res = 0;
651 }
652
653 static void zebra_select_register (ZebraHandle zh, const char *new_reg)
654 {
655     ASSERTZH;
656     zh->errCode = 0;
657     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
658         return;
659     if (!zh->res)
660     {
661         assert (zh->reg == 0);
662         assert (*zh->reg_name == 0);
663     }
664     else
665     {
666         if (zh->reg)
667         {
668             resultSetInvalidate (zh);
669             zebra_register_close (zh->service, zh->reg);
670             zh->reg = 0;
671         }
672         zebra_close_res(zh);
673     }
674     xfree(zh->reg_name);
675     zh->reg_name = xstrdup (new_reg);
676
677     xfree(zh->path_reg);
678     zh->path_reg = 0;
679     if (zh->service->path_root)
680     {
681         zh->path_reg = xmalloc(strlen(zh->service->path_root) + 
682                                 strlen(zh->reg_name) + 3);
683         strcpy (zh->path_reg, zh->service->path_root);
684         if (*zh->reg_name)
685         {
686             strcat (zh->path_reg, "/");
687             strcat (zh->path_reg, zh->reg_name);
688         }
689     }
690     zebra_open_res(zh);
691     
692     if (zh->lock_normal)
693         zebra_lock_destroy (zh->lock_normal);
694     zh->lock_normal = 0;
695
696     if (zh->lock_shadow)
697         zebra_lock_destroy (zh->lock_shadow);
698     zh->lock_shadow = 0;
699
700     if (zh->res)
701     {
702         char fname[512];
703         const char *lock_area = res_get (zh->res, "lockDir");
704         
705         if (!lock_area && zh->path_reg)
706             res_set (zh->res, "lockDir", zh->path_reg);
707         sprintf (fname, "norm.%s.LCK", zh->reg_name);
708         zh->lock_normal =
709             zebra_lock_create (res_get(zh->res, "lockDir"), fname);
710         
711         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
712         zh->lock_shadow =
713             zebra_lock_create (res_get(zh->res, "lockDir"), fname);
714
715         if (!zh->lock_normal || !zh->lock_shadow)
716         {
717             if (zh->lock_normal)
718             {
719                 zebra_lock_destroy(zh->lock_normal);
720                 zh->lock_normal = 0;
721             }
722             if (zh->lock_shadow)
723             {
724                 zebra_lock_destroy(zh->lock_shadow);
725                 zh->lock_shadow = 0;
726             }
727             zebra_close_res(zh);
728         }
729     }
730     if (zh->res)
731     {
732         int approx = 0;
733         if (res_get_int(zh->res, "estimatehits", &approx) == ZEBRA_OK)
734             zebra_set_approx_limit(zh, approx);
735     }
736     if (zh->res)
737     {
738         if (res_get_int(zh->res, "staticrank", &zh->m_staticrank) == ZEBRA_OK)
739             yaz_log(YLOG_LOG, "static rank set and is %d", zh->m_staticrank);
740         else
741             yaz_log(YLOG_LOG, "static rank unset");
742     }
743 }
744
745 void map_basenames_func (void *vp, const char *name, const char *value)
746 {
747     struct map_baseinfo *p = (struct map_baseinfo *) vp;
748     int i, no;
749     char fromdb[128], todb[8][128];
750
751     assert(value);
752     assert(name);
753     assert(vp);
754     
755     no =
756         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
757                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
758                 todb[5], todb[6], todb[7]);
759     if (no < 2)
760         return ;
761     no--;
762     for (i = 0; i<p->num_bases; i++)
763         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
764         {
765             p->basenames[i] = 0;
766             for (i = 0; i < no; i++)
767             {
768                 if (p->new_num_bases == p->new_num_max)
769                     return;
770                 p->new_basenames[(p->new_num_bases)++] = 
771                     nmem_strdup (p->mem, todb[i]);
772             }
773             return;
774         }
775 }
776
777 int zebra_select_default_database(ZebraHandle zh)
778 {
779     if (!zh->res)
780     {
781         /* no database has been selected - so we select based on
782            resource setting (including group)
783         */
784         const char *group = res_get(zh->session_res, "group");
785         const char *v = res_get_prefix(zh->session_res,
786                                        "database", group, "Default");
787         return zebra_select_database(zh, v);
788     }
789     return 0;
790 }
791
792 void map_basenames (ZebraHandle zh, ODR stream,
793                     int *num_bases, char ***basenames)
794 {
795     struct map_baseinfo info;
796     struct map_baseinfo *p = &info;
797     int i;
798     ASSERTZH;
799     yaz_log(log_level, "map_basenames ");
800     assert(stream);
801
802     info.zh = zh;
803
804     info.num_bases = *num_bases;
805     info.basenames = *basenames;
806     info.new_num_max = 128;
807     info.new_num_bases = 0;
808     info.new_basenames = (char **)
809         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
810     info.mem = stream->mem;
811
812     res_trav (zh->session_res, "mapdb", &info, map_basenames_func);
813     
814     for (i = 0; i<p->num_bases; i++)
815         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
816         {
817             p->new_basenames[(p->new_num_bases)++] = 
818                 nmem_strdup (p->mem, p->basenames[i]);
819         }
820     *num_bases = info.new_num_bases;
821     *basenames = info.new_basenames;
822     for (i = 0; i<*num_bases; i++)
823         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
824 }
825
826 ZEBRA_RES zebra_select_database (ZebraHandle zh, const char *basename)
827 {
828     ASSERTZH;
829     yaz_log(log_level, "zebra_select_database %s",basename);
830     assert(basename);
831     return zebra_select_databases (zh, 1, &basename);
832 }
833
834 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
835                                   const char **basenames)
836 {
837     int i;
838     const char *cp;
839     int len = 0;
840     char *new_reg = 0;
841     ASSERTZH;
842     assert(basenames);
843
844     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
845                     num_bases,basenames[0]);
846     zh->errCode = 0;
847     
848     if (num_bases < 1)
849     {
850         zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
851         return ZEBRA_FAIL;
852     }
853
854     /* Check if the user has access to all databases (Seb) */
855     /* You could argue that this should happen later, after we have
856      * determined that the database(s) exist. */
857     if (zh->dbaccesslist) {
858         for (i = 0; i < num_bases; i++) {
859             const char *db = basenames[i];
860             char *p, *pp;
861             for (p = zh->dbaccesslist; p && *p; p = pp) {
862                 int len;
863                 if ((pp = strchr(p, '+'))) {
864                     len = pp - p;
865                     pp++;
866                 }
867                 else
868                     len = strlen(p);
869                 if (len == strlen(db) && !strncmp(db, p, len))
870                     break;
871             }
872             if (!p) {
873                 zh->errCode = YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED;
874                 return ZEBRA_FAIL;
875             }
876         }
877     }
878
879     for (i = 0; i < zh->num_basenames; i++)
880         xfree(zh->basenames[i]);
881     xfree(zh->basenames);
882     
883     zh->num_basenames = num_bases;
884     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
885     for (i = 0; i < zh->num_basenames; i++)
886         zh->basenames[i] = xstrdup (basenames[i]);
887
888     cp = strrchr(basenames[0], '/');
889     if (cp)
890     {
891         len = cp - basenames[0];
892         new_reg = xmalloc(len + 1);
893         memcpy (new_reg, basenames[0], len);
894         new_reg[len] = '\0';
895     }
896     else
897         new_reg = xstrdup ("");
898     for (i = 1; i<num_bases; i++)
899     {
900         const char *cp1;
901
902         cp1 = strrchr (basenames[i], '/');
903         if (cp)
904         {
905             if (!cp1)
906             {
907                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
908                 return -1;
909             }
910             if (len != cp1 - basenames[i] ||
911                 memcmp (basenames[i], new_reg, len))
912             {
913                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
914                 return -1;
915             }
916         }
917         else
918         {
919             if (cp1)
920             {
921                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
922                 return ZEBRA_FAIL;
923             }
924         }
925     }
926     zebra_select_register (zh, new_reg);
927     xfree(new_reg);
928     if (!zh->res)
929     {
930         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
931         return ZEBRA_FAIL;
932     }
933     if (!zh->lock_normal || !zh->lock_shadow)
934     {
935         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
936         return ZEBRA_FAIL;
937     }
938     return ZEBRA_OK;
939 }
940
941 ZEBRA_RES zebra_set_approx_limit(ZebraHandle zh, zint approx_limit)
942 {
943     if (approx_limit == 0)
944         approx_limit = DEFAULT_APPROX_LIMIT;
945     zh->approx_limit = approx_limit;
946     return ZEBRA_OK;
947 }
948
949 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
950                            const char *setname, zint *hits)
951 {
952     ZEBRA_RES r;
953     ASSERTZH;
954     assert(o);
955     assert(query);
956     assert(hits);
957     assert(setname);
958     yaz_log(log_level, "zebra_search_rpn");
959     zh->hits = 0;
960     *hits = 0;
961
962     if (zebra_begin_read(zh) == ZEBRA_FAIL)
963         return ZEBRA_FAIL;
964
965     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
966                         zh->num_basenames, zh->basenames, setname);
967     zebra_end_read(zh);
968     *hits = zh->hits;
969     return r;
970 }
971
972 ZEBRA_RES zebra_records_retrieve(ZebraHandle zh, ODR stream,
973                                  const char *setname,
974                                  Z_RecordComposition *comp,
975                                  oid_value input_format, int num_recs,
976                                  ZebraRetrievalRecord *recs)
977 {
978     ZebraMetaRecord *poset;
979     int i;
980     ZEBRA_RES ret = ZEBRA_OK;
981     zint *pos_array;
982     ASSERTZH;
983     assert(stream);
984     assert(setname);
985     assert(recs);
986     assert(num_recs>0);
987
988     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
989
990     if (!zh->res)
991     {
992         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
993                        setname);
994         return ZEBRA_FAIL;
995     }
996     
997     if (zebra_begin_read (zh) == ZEBRA_FAIL)
998         return ZEBRA_FAIL;
999
1000     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
1001     for (i = 0; i<num_recs; i++)
1002         pos_array[i] = recs[i].position;
1003     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
1004     if (!poset)
1005     {
1006         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
1007         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1008                        setname);
1009         ret = ZEBRA_FAIL;
1010     }
1011     else
1012     {
1013         for (i = 0; i<num_recs; i++)
1014         {
1015             if (poset[i].term)
1016             {
1017                 recs[i].errCode = 0;
1018                 recs[i].format = VAL_SUTRS;
1019                 recs[i].len = strlen(poset[i].term);
1020                 recs[i].buf = poset[i].term;
1021                 recs[i].base = poset[i].db;
1022             }
1023             else if (poset[i].sysno)
1024             {
1025                 char *buf;
1026                 int len;
1027                 zebra_snippets *hit_snippet = zebra_snippets_create();
1028
1029                 zebra_snippets_hit_vector(zh, setname, poset[i].sysno, 
1030                                           hit_snippet);
1031
1032                 recs[i].errCode =
1033                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
1034                                        hit_snippet,
1035                                        stream, input_format, comp,
1036                                        &recs[i].format, &buf, &len,
1037                                        &recs[i].base, &recs[i].errString);
1038                 
1039                 recs[i].len = len;
1040                 if (len > 0)
1041                 {
1042                     recs[i].buf = (char*) odr_malloc(stream, len);
1043                     memcpy(recs[i].buf, buf, len);
1044                 }
1045                 else
1046                     recs[i].buf = buf;
1047                 recs[i].score = poset[i].score;
1048                 recs[i].sysno = poset[i].sysno;
1049                 zebra_snippets_destroy(hit_snippet);
1050             }
1051             else
1052             {
1053                 /* only need to set it once */
1054                 if (pos_array[i] < zh->approx_limit && ret == ZEBRA_OK)
1055                 {
1056                     zebra_setError_zint(zh,
1057                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1058                                         pos_array[i]);
1059                     ret = ZEBRA_FAIL;
1060                     break;
1061                 }
1062                 recs[i].buf = 0;  /* no record and no error issued */
1063                 recs[i].len = 0;
1064                 recs[i].errCode = 0;
1065                 recs[i].format = VAL_NONE;
1066                 recs[i].sysno = 0;
1067             }
1068         }
1069         zebra_meta_records_destroy(zh, poset, num_recs);
1070     }
1071     zebra_end_read (zh);
1072     xfree(pos_array);
1073     return ret;
1074 }
1075
1076 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
1077                          int *position,
1078                          int *num_entries, ZebraScanEntry **entries,
1079                          int *is_partial,
1080                          const char *setname)
1081 {
1082     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1083     Z_AttributesPlusTerm *zapt;
1084     int *attributeSet;
1085     ZEBRA_RES res;
1086     
1087     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
1088     {
1089         res = ZEBRA_FAIL;
1090         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
1091     }
1092     else
1093         res = zebra_scan(zh, stream, zapt, VAL_BIB1,
1094                          position, num_entries, entries, is_partial,
1095                          setname);
1096     yaz_pqf_destroy (pqf_parser);
1097     return res;
1098 }
1099
1100 ZEBRA_RES zebra_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
1101                      oid_value attributeset,
1102                      int *position,
1103                      int *num_entries, ZebraScanEntry **entries,
1104                      int *is_partial,
1105                      const char *setname)
1106 {
1107     ZEBRA_RES res;
1108     RSET limit_rset = 0;
1109     ASSERTZH;
1110     assert(stream);
1111     assert(zapt);
1112     assert(position);
1113     assert(num_entries);
1114     assert(is_partial);
1115     assert(entries);
1116     yaz_log(log_level, "zebra_scan");
1117
1118     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1119     {
1120         *entries = 0;
1121         *num_entries = 0;
1122         return ZEBRA_FAIL;
1123     }
1124     if (setname)
1125     {
1126         limit_rset = resultSetRef(zh, setname);
1127         if (!limit_rset)
1128         {
1129             zebra_setError(zh, 
1130                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1131                            setname);
1132             zebra_end_read (zh);
1133             return ZEBRA_FAIL;
1134         }
1135     }
1136     res = rpn_scan (zh, stream, zapt, attributeset,
1137                     zh->num_basenames, zh->basenames, position,
1138                     num_entries, entries, is_partial, limit_rset, 0);
1139     zebra_end_read (zh);
1140     return res;
1141 }
1142
1143 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1144                       int num_input_setnames, const char **input_setnames,
1145                       const char *output_setname,
1146                       Z_SortKeySpecList *sort_sequence,
1147                       int *sort_status)
1148 {
1149     ZEBRA_RES res;
1150     ASSERTZH;
1151     assert(stream);
1152     assert(num_input_setnames>0);
1153     assert(input_setnames);
1154     assert(sort_sequence);
1155     assert(sort_status);
1156     yaz_log(log_level, "zebra_sort");
1157
1158     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1159         return ZEBRA_FAIL;
1160     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1161                         output_setname, sort_sequence, sort_status);
1162     zebra_end_read(zh);
1163     return res;
1164 }
1165
1166 int zebra_deleteResultSet(ZebraHandle zh, int function,
1167                           int num_setnames, char **setnames,
1168                           int *statuses)
1169 {
1170     int i, status;
1171     ASSERTZH;
1172     assert(statuses);
1173     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1174
1175     if (zebra_begin_read(zh))
1176         return Z_DeleteStatus_systemProblemAtTarget;
1177     switch (function)
1178     {
1179     case Z_DeleteResultSetRequest_list:
1180         assert(num_setnames>0);
1181         assert(setnames);
1182         resultSetDestroy (zh, num_setnames, setnames, statuses);
1183         break;
1184     case Z_DeleteResultSetRequest_all:
1185         resultSetDestroy (zh, -1, 0, statuses);
1186         break;
1187     }
1188     zebra_end_read (zh);
1189     status = Z_DeleteStatus_success;
1190     for (i = 0; i<num_setnames; i++)
1191         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1192             status = statuses[i];
1193     return status;
1194 }
1195
1196 int zebra_errCode (ZebraHandle zh)
1197 {
1198     if (zh)
1199     {
1200         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1201         return zh->errCode;
1202     }
1203     yaz_log(log_level, "zebra_errCode: o");
1204     return 0; 
1205 }
1206
1207 const char *zebra_errString (ZebraHandle zh)
1208 {
1209     const char *e = 0;
1210     if (zh)
1211         e= diagbib1_str (zh->errCode);
1212     yaz_log(log_level, "zebra_errString: %s",e);
1213     return e;
1214 }
1215
1216 char *zebra_errAdd (ZebraHandle zh)
1217 {
1218     char *a = 0;
1219     if (zh)
1220         a= zh->errString;
1221     yaz_log(log_level, "zebra_errAdd: %s",a);
1222     return a;
1223 }
1224
1225 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1226 {
1227     const char *p;
1228     const char *astring;
1229     char u[40];
1230     ZebraService zs;
1231
1232     ASSERTZH;
1233
1234     zs= zh->service;
1235     
1236     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1237     p = res_get(zs->global_res, u);
1238     xfree(zh->user_perm);
1239     zh->user_perm = xstrdup(p ? p : "r");
1240
1241     /* Determine database access list */
1242     astring = res_get(zs->dbaccess, user ? user : "anonymous");
1243     if (astring)
1244         zh->dbaccesslist = xstrdup(astring);
1245     else
1246         zh->dbaccesslist = 0;
1247
1248     /* users that don't require a password .. */
1249     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1250         return ZEBRA_OK;
1251     
1252     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1253         return ZEBRA_OK;
1254     return ZEBRA_FAIL;
1255 }
1256
1257 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1258                                const char *record_type)
1259 {
1260     ASSERTZH;
1261     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1262                      database, record_type);
1263     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1264         return ZEBRA_FAIL;
1265     return zebra_begin_trans(zh, 1);
1266 }
1267
1268 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1269 {
1270     ASSERTZH;
1271     yaz_log(log_level, "zebra_admin_import_end");
1272     return zebra_end_trans(zh);
1273 }
1274
1275 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1276 {
1277     ZEBRA_RES res = ZEBRA_OK;
1278     SYSNO sysno;
1279     int i;
1280     ASSERTZH;
1281     yaz_log(log_level, "zebra_admin_import_segment");
1282
1283     for (i = 0; i<segment->num_segmentRecords; i++)
1284     {
1285         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1286
1287         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1288         {
1289             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1290             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1291             {
1292                 Odr_oct *oct = fragment->u.notExternallyTagged;
1293                 sysno = 0;
1294                 
1295                 if (zebra_update_record(zh, 
1296                                         0, /* record Type */
1297                                         &sysno,
1298                                         0, /* match */
1299                                         0, /* fname */
1300                                         (const char *) oct->buf, oct->len,
1301                                         0) == ZEBRA_FAIL)
1302                     res = ZEBRA_FAIL;
1303             }
1304         }
1305     }
1306     return res;
1307 }
1308
1309 ZEBRA_RES zebra_admin_exchange_record(ZebraHandle zh,
1310                                       const char *rec_buf,
1311                                       size_t rec_len,
1312                                       const char *recid_buf, size_t recid_len,
1313                                       int action)
1314     /* 1 = insert. Fail it already exists */
1315     /* 2 = replace. Fail it does not exist */
1316     /* 3 = delete. Fail if does not exist */
1317     /* 4 = update. Insert/replace */
1318 {
1319     ZEBRA_RES res;
1320     SYSNO sysno = 0;
1321     char *rinfo = 0;
1322     char recid_z[256];
1323     int db_ord;
1324     ASSERTZH;
1325     assert(action>0 && action <=4);
1326     assert(rec_buf);
1327
1328     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1329
1330     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1331     {
1332         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1333                        "no record ID or empty record ID");
1334         return ZEBRA_FAIL;
1335     }
1336
1337     memcpy (recid_z, recid_buf, recid_len);
1338     recid_z[recid_len] = 0;
1339
1340     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
1341         return ZEBRA_FAIL;
1342
1343     db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1344     rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord, recid_z);
1345     if (rinfo)
1346     {
1347         if (action == 1)  /* fail if insert */
1348         {
1349             zebra_end_trans(zh);
1350             zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1351                            "Cannot insert record: already exist");
1352             return ZEBRA_FAIL;
1353         }
1354
1355         memcpy (&sysno, rinfo+1, sizeof(sysno));
1356     }
1357     else
1358     {
1359         if (action == 2 || action == 3) /* fail if delete or update */
1360         {
1361             zebra_end_trans(zh);
1362             zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1363                            "Cannot delete/update record: does not exist");
1364             return ZEBRA_FAIL;
1365         }
1366         action = 1;  /* make it an insert (if it's an update).. */
1367     }
1368     res = buffer_extract_record (zh, rec_buf, rec_len,
1369                                  action == 3 ? 1 : 0 /* delete flag */,
1370                                  0, /* test mode */
1371                                  0, /* recordType */
1372                                  &sysno, 
1373                                  0, /* match */
1374                                  0, /* fname */
1375                                  0, /* force update */
1376                                  1  /* allow update */
1377         );
1378     if (res == ZEBRA_FAIL)
1379     {
1380         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1381                        "Unable to parse record");
1382     }
1383     if (action == 1)
1384     {
1385         dict_insert_ord(zh->reg->matchDict, db_ord, recid_z,
1386                         sizeof(sysno), &sysno);
1387     }
1388     else if (action == 3)
1389     {
1390         dict_delete_ord(zh->reg->matchDict, db_ord, recid_z);
1391     }
1392     zebra_end_trans(zh);
1393     return res;
1394 }
1395
1396 int delete_w_handle(const char *info, void *handle)
1397 {
1398     ZebraHandle zh = (ZebraHandle) handle;
1399     ISAM_P pos;
1400     ASSERTZH;
1401
1402     if (*info == sizeof(pos))
1403     {
1404         memcpy (&pos, info+1, sizeof(pos));
1405         isamb_unlink(zh->reg->isamb, pos);
1406     }
1407     return 0;
1408 }
1409
1410 static int delete_SU_handle(void *handle, int ord)
1411 {
1412     ZebraHandle zh = (ZebraHandle) handle;
1413     char ord_buf[20];
1414     int ord_len;
1415
1416     ord_len = key_SU_encode (ord, ord_buf);
1417     ord_buf[ord_len] = '\0';
1418
1419     assert (zh->reg->isamb);
1420     dict_delete_subtree(zh->reg->dict, ord_buf,
1421                         zh, delete_w_handle);
1422     return 0;
1423 }
1424
1425 ZEBRA_RES zebra_drop_database(ZebraHandle zh, const char *db)
1426 {
1427     ZEBRA_RES ret = ZEBRA_OK;
1428     ASSERTZH;
1429     yaz_log(log_level, "zebra_drop_database %s", db);
1430
1431     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1432         return ZEBRA_FAIL;
1433     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1434         return ZEBRA_FAIL;
1435     if (zh->reg->isamb)
1436     {
1437         int db_ord;
1438         zebraExplain_curDatabase (zh->reg->zei, db);
1439         db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1440         dict_delete_subtree_ord(zh->reg->matchDict, db_ord,
1441                                 0 /* handle */, 0 /* func */);
1442         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1443         zebraExplain_removeDatabase(zh->reg->zei, zh);
1444     }
1445     else
1446     {
1447         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1448         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1449                        "drop database only supported for isam:b");
1450         ret = ZEBRA_FAIL;
1451     }
1452     zebra_end_trans (zh);
1453     return ret;
1454 }
1455
1456 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *db)
1457 {
1458     ASSERTZH;
1459     yaz_log(log_level, "zebra_create_database %s", db);
1460     assert(db);
1461
1462     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1463         return ZEBRA_FAIL;
1464     if (zebra_begin_trans (zh, 1))
1465         return ZEBRA_FAIL;
1466
1467     /* announce database */
1468     if (zebraExplain_newDatabase (zh->reg->zei, db, 0 
1469                                   /* explainDatabase */))
1470     {
1471         zebra_end_trans (zh);
1472         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, db);
1473         return ZEBRA_FAIL;
1474     }
1475     return zebra_end_trans (zh);
1476 }
1477
1478 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1479                        const char *input_str, int input_len,
1480                        char *output_str, int output_len)
1481 {
1482     WRBUF wrbuf;
1483     ASSERTZH;
1484     assert(input_str);
1485     assert(output_str);
1486     yaz_log(log_level, "zebra_string_norm ");
1487
1488     if (!zh->reg->zebra_maps)
1489         return -1;
1490     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1491                           input_str, input_len);
1492     if (!wrbuf)
1493         return -2;
1494     if (wrbuf_len(wrbuf) >= output_len)
1495         return -3;
1496     if (wrbuf_len(wrbuf))
1497         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1498     output_str[wrbuf_len(wrbuf)] = '\0';
1499     return wrbuf_len(wrbuf);
1500 }
1501
1502 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1503 {
1504     char state_fname[256];
1505     char *fname;
1506     long p = getpid();
1507     FILE *f;
1508     ASSERTZH;
1509     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1510
1511     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1512     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1513     f = fopen (fname, "w");
1514
1515     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1516     fprintf (f, "%c %d %ld\n", val, seqno, p);
1517     fclose (f);
1518     xfree(fname);
1519 }
1520
1521 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1522 {
1523     char state_fname[256];
1524     char *fname;
1525     FILE *f;
1526
1527     ASSERTZH;
1528     yaz_log(log_level, "zebra_get_state ");
1529
1530     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1531     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1532     f = fopen (fname, "r");
1533     *val = 'o';
1534     *seqno = 0;
1535
1536     if (f)
1537     {
1538         fscanf (f, "%c %d", val, seqno);
1539         fclose (f);
1540     }
1541     xfree(fname);
1542 }
1543
1544 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1545 {
1546     return zebra_begin_trans(zh, 0);
1547 }
1548
1549 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1550 {
1551     return zebra_end_trans(zh);
1552 }
1553
1554 static void read_res_for_transaction(ZebraHandle zh)
1555 {
1556     const char *group = res_get(zh->res, "group");
1557     const char *v;
1558     /* FIXME - do we still use groups ?? */
1559     
1560     zh->m_group = group;
1561     v = res_get_prefix(zh->res, "followLinks", group, "1");
1562     zh->m_follow_links = atoi(v);
1563
1564     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1565     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1566
1567     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1568     zh->m_store_keys = atoi(v);
1569
1570     v = res_get_prefix(zh->res, "storeData", group, "1");
1571     zh->m_store_data = atoi(v);
1572
1573     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1574     zh->m_explain_database = atoi(v);
1575
1576     v = res_get_prefix(zh->res, "openRW", group, "1");
1577     zh->m_flag_rw = atoi(v);
1578
1579     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1580     zh->m_file_verbose_limit = atoi(v);
1581 }
1582
1583 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1584 {
1585     ASSERTZH;
1586     zebra_select_default_database(zh);
1587     if (!zh->res)
1588     {
1589         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1590                        "zebra_begin_trans: no database selected");
1591         return ZEBRA_FAIL;
1592     }
1593     ASSERTZHRES;
1594     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1595
1596     if (zh->user_perm)
1597     {
1598         if (rw && !strchr(zh->user_perm, 'w'))
1599         {
1600             zebra_setError(
1601                 zh,
1602                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1603                 0);
1604             return ZEBRA_FAIL;
1605         }
1606     }
1607
1608     assert (zh->res);
1609     if (rw)
1610     {
1611         int pass;
1612         int seqno = 0;
1613         char val = '?';
1614         const char *rval = 0;
1615         
1616         (zh->trans_no++);
1617         if (zh->trans_w_no)
1618         {
1619             read_res_for_transaction(zh);
1620             return 0;
1621         }
1622         if (zh->trans_no != 1)
1623         {
1624             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1625                            "zebra_begin_trans: no write trans within read");
1626             return ZEBRA_FAIL;
1627         }
1628         if (zh->reg)
1629         {
1630             resultSetInvalidate (zh);
1631             zebra_register_close (zh->service, zh->reg);
1632         }
1633         zh->trans_w_no = zh->trans_no;
1634
1635         zh->records_inserted = 0;
1636         zh->records_updated = 0;
1637         zh->records_deleted = 0;
1638         zh->records_processed = 0;
1639         
1640 #if HAVE_SYS_TIMES_H
1641         times (&zh->tms1);
1642 #endif
1643         /* lock */
1644         if (zh->shadow_enable)
1645             rval = res_get (zh->res, "shadow");
1646         
1647         for (pass = 0; pass < 2; pass++)
1648         {
1649             if (rval)
1650             {
1651                 zebra_lock_r (zh->lock_normal);
1652                 zebra_lock_w (zh->lock_shadow);
1653             }
1654             else
1655             {
1656                 zebra_lock_w (zh->lock_normal);
1657                 zebra_lock_w (zh->lock_shadow);
1658             }
1659             
1660             zebra_get_state (zh, &val, &seqno);
1661             if (val == 'c')
1662             {
1663                 yaz_log (YLOG_WARN, "previous transaction didn't finish commit");
1664                 zebra_unlock (zh->lock_shadow);
1665                 zebra_unlock (zh->lock_normal);
1666                 zebra_commit (zh);
1667                 continue;
1668             }
1669             else if (val == 'd')
1670             {
1671                 if (rval)
1672                 {
1673                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1674                                              zh->path_reg);
1675                     yaz_log (YLOG_WARN, "previous transaction didn't reach commit");
1676                     bf_commitClean (bfs, rval);
1677                     bfs_destroy (bfs);
1678                 }
1679                 else
1680                 {
1681                     yaz_log (YLOG_WARN, "your previous transaction didn't finish");
1682                 }
1683             }
1684             break;
1685         }
1686         if (pass == 2)
1687         {
1688             yaz_log (YLOG_FATAL, "zebra_begin_trans couldn't finish commit");
1689             abort();
1690             return ZEBRA_FAIL;
1691         }
1692         zebra_set_state (zh, 'd', seqno);
1693         
1694         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1695                                       1, rval ? 1 : 0, zh->res,
1696                                       zh->path_reg);
1697         if (zh->reg)
1698             zh->reg->seqno = seqno;
1699         else
1700         {
1701             zebra_set_state (zh, 'o', seqno);
1702             
1703             zebra_unlock (zh->lock_shadow);
1704             zebra_unlock (zh->lock_normal);
1705
1706             zh->trans_no--;
1707             zh->trans_w_no = 0;
1708
1709             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1710                            "zebra_begin_trans: cannot open register");
1711             yaz_log(YLOG_FATAL, "%s", zh->errString);
1712             return ZEBRA_FAIL;
1713         }
1714         zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]);
1715     }
1716     else
1717     {
1718         int dirty = 0;
1719         char val;
1720         int seqno;
1721         
1722         (zh->trans_no)++;
1723         
1724         if (zh->trans_no != 1)
1725         {
1726             zebra_flush_reg (zh);
1727             return ZEBRA_OK;
1728         }
1729 #if HAVE_SYS_TIMES_H
1730         times (&zh->tms1);
1731 #endif
1732         if (!zh->res)
1733         {
1734             (zh->trans_no)--;
1735             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1736             return ZEBRA_FAIL;
1737         }
1738         if (!zh->lock_normal || !zh->lock_shadow)
1739         {
1740             (zh->trans_no)--;
1741             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1742             return ZEBRA_FAIL;
1743         }
1744         zebra_get_state (zh, &val, &seqno);
1745         if (val == 'd')
1746             val = 'o';
1747         
1748         if (!zh->reg)
1749             dirty = 1;
1750         else if (seqno != zh->reg->seqno)
1751         {
1752             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1753                      seqno, zh->reg->seqno);
1754             dirty = 1;
1755         }
1756         else if (zh->reg->last_val != val)
1757         {
1758             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1759                      val, zh->reg->last_val);
1760             dirty = 1;
1761         }
1762         if (!dirty)
1763             return ZEBRA_OK;
1764         
1765         if (val == 'c')
1766             zebra_lock_r (zh->lock_shadow);
1767         else
1768             zebra_lock_r (zh->lock_normal);
1769         
1770         if (zh->reg)
1771         {
1772             resultSetInvalidate (zh);
1773             zebra_register_close (zh->service, zh->reg);
1774         }
1775         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1776                                       0, val == 'c' ? 1 : 0,
1777                                       zh->res, zh->path_reg);
1778         if (!zh->reg)
1779         {
1780             zebra_unlock (zh->lock_normal);
1781             zebra_unlock (zh->lock_shadow);
1782             zh->trans_no--;
1783             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1784             return ZEBRA_FAIL;
1785         }
1786         zh->reg->last_val = val;
1787         zh->reg->seqno = seqno;
1788     }
1789     read_res_for_transaction(zh);
1790     return ZEBRA_OK;
1791 }
1792
1793 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1794 {
1795     ZebraTransactionStatus dummy;
1796     ASSERTZH;
1797     yaz_log(log_level, "zebra_end_trans");
1798     return zebra_end_transaction(zh, &dummy);
1799 }
1800
1801 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1802 {
1803     char val;
1804     int seqno;
1805     const char *rval;
1806
1807     ASSERTZH;
1808     assert(status);
1809     yaz_log(log_level, "zebra_end_transaction");
1810
1811     status->processed = 0;
1812     status->inserted  = 0;
1813     status->updated   = 0;
1814     status->deleted   = 0;
1815     status->utime     = 0;
1816     status->stime     = 0;
1817
1818     if (!zh->res || !zh->reg)
1819     {
1820         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1821                        "zebra_end_trans: no open transaction");
1822         return ZEBRA_FAIL;
1823     }
1824     if (zh->trans_no != zh->trans_w_no)
1825     {
1826         zh->trans_no--;
1827         if (zh->trans_no != 0)
1828             return ZEBRA_OK;
1829
1830         /* release read lock */
1831
1832         zebra_unlock (zh->lock_normal);
1833         zebra_unlock (zh->lock_shadow);
1834     }
1835     else
1836     {   /* release write lock */
1837         zh->trans_no--;
1838         zh->trans_w_no = 0;
1839         
1840         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1841         rval = res_get (zh->res, "shadow");
1842         
1843         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1844         
1845         zebra_flush_reg (zh);
1846         
1847         resultSetInvalidate (zh);
1848
1849         zebra_register_close (zh->service, zh->reg);
1850         zh->reg = 0;
1851         
1852         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1853                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1854                  zh->records_processed, zh->records_inserted,
1855                  zh->records_updated, zh->records_deleted);
1856         
1857         status->processed = (int) zh->records_processed;
1858         status->inserted = (int) zh->records_inserted;
1859         status->updated = (int) zh->records_updated;
1860         status->deleted = (int) zh->records_deleted;
1861         
1862         zebra_get_state (zh, &val, &seqno);
1863         if (val != 'd')
1864         {
1865             BFiles bfs = bfs_create (rval, zh->path_reg);
1866             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1867             bf_commitClean (bfs, rval);
1868             bfs_destroy (bfs);
1869         }
1870         if (!rval)
1871             seqno++;
1872         zebra_set_state (zh, 'o', seqno);
1873         
1874         zebra_unlock (zh->lock_shadow);
1875         zebra_unlock (zh->lock_normal);
1876         
1877     }
1878 #if HAVE_SYS_TIMES_H
1879     times (&zh->tms2);
1880     yaz_log (log_level, "user/system: %ld/%ld",
1881           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1882           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1883     
1884     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1885     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1886 #endif
1887     return ZEBRA_OK;
1888 }
1889
1890 int zebra_repository_update (ZebraHandle zh, const char *path)
1891 {
1892     ASSERTZH;
1893     assert(path);
1894     yaz_log (log_level, "updating %s", path);
1895     repositoryUpdate (zh, path);
1896     return 0;
1897 }
1898
1899 int zebra_repository_delete (ZebraHandle zh, const char *path)
1900 {
1901     ASSERTZH;
1902     assert(path);
1903     yaz_log (log_level, "deleting %s", path);
1904     repositoryDelete (zh, path);
1905     return 0;
1906 }
1907
1908 int zebra_repository_show (ZebraHandle zh, const char *path)
1909 {
1910     ASSERTZH;
1911     assert(path);
1912     yaz_log(log_level, "zebra_repository_show");
1913     repositoryShow (zh, path);
1914     return 0;
1915 }
1916
1917 static ZEBRA_RES zebra_commit_ex(ZebraHandle zh, int clean_only)
1918 {
1919     int seqno;
1920     char val;
1921     const char *rval;
1922     BFiles bfs;
1923     ASSERTZH;
1924
1925     zebra_select_default_database(zh);
1926     if (!zh->res)
1927     {
1928         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1929         return ZEBRA_FAIL;
1930     }
1931     rval = res_get (zh->res, "shadow");    
1932     if (!rval)
1933     {
1934         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1935         return ZEBRA_OK;
1936     }
1937
1938     zebra_lock_w (zh->lock_normal);
1939     zebra_lock_r (zh->lock_shadow);
1940
1941     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1942
1943     zebra_get_state (zh, &val, &seqno);
1944
1945     if (rval && *rval)
1946         bf_cache (bfs, rval);
1947     if (bf_commitExists (bfs))
1948     {
1949         if (clean_only)
1950             zebra_set_state (zh, 'd', seqno);
1951         else
1952         {
1953             zebra_set_state (zh, 'c', seqno);
1954             
1955             yaz_log (YLOG_DEBUG, "commit start");
1956             bf_commitExec (bfs);
1957 #ifndef WIN32
1958             sync ();
1959 #endif
1960         }
1961         yaz_log (YLOG_DEBUG, "commit clean");
1962         bf_commitClean (bfs, rval);
1963         seqno++;
1964         zebra_set_state (zh, 'o', seqno);
1965     }
1966     else
1967     {
1968         yaz_log (log_level, "nothing to commit");
1969     }
1970     bfs_destroy (bfs);
1971
1972     zebra_unlock (zh->lock_shadow);
1973     zebra_unlock (zh->lock_normal);
1974     return ZEBRA_OK;
1975 }
1976
1977 ZEBRA_RES zebra_clean(ZebraHandle zh)
1978 {
1979     ASSERTZH;
1980     yaz_log(log_level, "zebra_clean");
1981     return zebra_commit_ex(zh, 1);
1982 }
1983
1984 ZEBRA_RES zebra_commit(ZebraHandle zh)
1985 {
1986     ASSERTZH;
1987     yaz_log(log_level, "zebra_commit");
1988     return zebra_commit_ex(zh, 0);
1989 }
1990
1991 ZEBRA_RES zebra_init(ZebraHandle zh)
1992 {
1993     const char *rval;
1994     BFiles bfs = 0;
1995     ASSERTZH;
1996     yaz_log(log_level, "zebra_init");
1997
1998     zebra_select_default_database(zh);
1999     if (!zh->res)
2000     {
2001         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
2002                        "cannot select default database");
2003         return ZEBRA_FAIL;
2004     }
2005     rval = res_get (zh->res, "shadow");
2006
2007     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2008     if (!bfs)
2009     {
2010         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "bfs_create");
2011         return ZEBRA_FAIL;
2012     }
2013     if (rval && *rval)
2014         bf_cache (bfs, rval);
2015     
2016     bf_reset (bfs);
2017     bfs_destroy (bfs);
2018     zebra_set_state (zh, 'o', 0);
2019     return ZEBRA_OK;
2020 }
2021
2022 ZEBRA_RES zebra_compact(ZebraHandle zh)
2023 {
2024     BFiles bfs;
2025     ASSERTZH;
2026     yaz_log(log_level, "zebra_compact");
2027     if (!zh->res)
2028     {
2029         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
2030         return ZEBRA_FAIL;
2031     }
2032     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2033     inv_compact (bfs);
2034     bfs_destroy (bfs);
2035     return ZEBRA_OK;
2036 }
2037
2038 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
2039 {
2040     ASSERTZH;
2041     yaz_log(log_level, "zebra_result");
2042     *code = zh->errCode;
2043     *addinfo = zh->errString;
2044 }
2045
2046 void zebra_shadow_enable(ZebraHandle zh, int value)
2047 {
2048     ASSERTZH;
2049     yaz_log(log_level, "zebra_shadow_enable");
2050     zh->shadow_enable = value;
2051 }
2052
2053 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
2054 {
2055     ASSERTZH;
2056     assert(encoding);
2057     yaz_log(log_level, "zebra_octet_term_encoding %s", encoding);
2058
2059     if (zh->iconv_to_utf8 != 0)
2060         yaz_iconv_close(zh->iconv_to_utf8);
2061     if (zh->iconv_from_utf8 != 0)
2062         yaz_iconv_close(zh->iconv_from_utf8);
2063     
2064     zh->iconv_to_utf8 =
2065         yaz_iconv_open ("UTF-8", encoding);
2066     if (zh->iconv_to_utf8 == 0)
2067         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
2068     zh->iconv_from_utf8 =
2069         yaz_iconv_open (encoding, "UTF-8");
2070     if (zh->iconv_to_utf8 == 0)
2071         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
2072
2073     return ZEBRA_OK;
2074 }
2075
2076 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
2077 {
2078     ASSERTZH;
2079     yaz_log(log_level, "zebra_record_encoding");
2080     xfree(zh->record_encoding);
2081     zh->record_encoding = 0;
2082     if (encoding)
2083         zh->record_encoding = xstrdup (encoding);
2084     return ZEBRA_OK;
2085 }
2086
2087 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
2088 {
2089     ASSERTZH;
2090     assert(name);
2091     assert(value);
2092     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
2093     res_set(zh->res, name, value);
2094 }
2095
2096 const char *zebra_get_resource(ZebraHandle zh,
2097                                const char *name, const char *defaultvalue)
2098 {
2099     const char *v;
2100     ASSERTZH;
2101     assert(name);
2102     v = res_get_def (zh->res, name, (char *)defaultvalue);
2103     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
2104     return v;
2105 }
2106
2107 /* moved from zebra_api_ext.c by pop */
2108 /* FIXME: Should this really be public??? -Heikki */
2109
2110 int zebra_trans_no (ZebraHandle zh)
2111 {
2112     ASSERTZH;
2113     yaz_log(log_level, "zebra_trans_no");
2114     return zh->trans_no;
2115 }
2116
2117 int zebra_get_shadow_enable (ZebraHandle zh)
2118 {
2119     ASSERTZH;
2120     yaz_log(log_level, "zebra_get_shadow_enable");
2121     return zh->shadow_enable;
2122 }
2123
2124 void zebra_set_shadow_enable (ZebraHandle zh, int value)
2125 {
2126     ASSERTZH;
2127     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
2128     zh->shadow_enable = value;
2129 }
2130
2131 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
2132    so that it's identicical to the original api_records_retrieve */
2133 void api_records_retrieve (ZebraHandle zh, ODR stream,
2134                            const char *setname, Z_RecordComposition *comp,
2135                            oid_value input_format, int num_recs,
2136                            ZebraRetrievalRecord *recs)
2137 {
2138     zebra_records_retrieve(zh, stream, setname, comp, input_format,
2139                            num_recs, recs);
2140 }
2141
2142 /* ---------------------------------------------------------------------------
2143   Record insert(=update), delete 
2144
2145   If sysno is provided, then it's used to identify the record.
2146   If not, and match_criteria is provided, then sysno is guessed
2147   If not, and a record is provided, then sysno is got from there
2148 NOTE: Now returns 0 at success and updates sysno, which is an int*
2149   20-jun-2003 Heikki
2150 */
2151
2152 int zebra_add_record(ZebraHandle zh,
2153                      const char *buf, int buf_size)
2154 {
2155     return zebra_update_record(zh, 0, 0 /* sysno */, 0, 0, buf, buf_size, 0);
2156 }
2157
2158 ZEBRA_RES zebra_insert_record (ZebraHandle zh, 
2159                                const char *recordType,
2160                                SYSNO *sysno, const char *match,
2161                                const char *fname,
2162                                const char *buf, int buf_size, int force_update)
2163 {
2164     ZEBRA_RES res;
2165     ASSERTZH;
2166     assert(sysno);
2167     assert(buf);
2168     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2169
2170     if (buf_size < 1)
2171         buf_size = strlen(buf);
2172
2173     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2174         return ZEBRA_FAIL;
2175     res = buffer_extract_record (zh, buf, buf_size, 
2176                                  0, /* delete_flag  */
2177                                  0, /* test_mode */
2178                                  recordType,
2179                                  sysno,   
2180                                  match, fname,
2181                                  0, 
2182                                  0); /* allow_update */
2183     zebra_end_trans(zh); 
2184     return res; 
2185 }
2186
2187 ZEBRA_RES zebra_update_record (ZebraHandle zh, 
2188                                const char *recordType,
2189                                SYSNO* sysno, const char *match,
2190                                const char *fname,
2191                                const char *buf, int buf_size,
2192                                int force_update)
2193 {
2194     ZEBRA_RES res;
2195     ASSERTZH;
2196     assert(buf);
2197
2198     yaz_log(log_level, "zebra_update_record");
2199     if (sysno)
2200         yaz_log(log_level, " sysno=" ZINT_FORMAT, *sysno);
2201
2202     if (buf_size < 1) buf_size = strlen(buf);
2203
2204     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2205         return ZEBRA_FAIL;
2206     res = buffer_extract_record (zh, buf, buf_size, 
2207                                  0, /* delete_flag */
2208                                  0, /* test_mode */
2209                                  recordType,
2210                                  sysno,   
2211                                  match, fname,
2212                                  force_update, 
2213                                  1); /* allow_update */
2214     zebra_end_trans(zh); 
2215     return res; 
2216 }
2217
2218 ZEBRA_RES zebra_delete_record (ZebraHandle zh, 
2219                                const char *recordType,
2220                                SYSNO *sysno, const char *match,
2221                                const char *fname,
2222                                const char *buf, int buf_size,
2223                                int force_update) 
2224 {
2225     ZEBRA_RES res;
2226     ASSERTZH;
2227     assert(sysno);
2228     assert(buf);
2229     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2230
2231     if (buf_size < 1) buf_size = strlen(buf);
2232
2233     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2234         return ZEBRA_FAIL;
2235     res = buffer_extract_record (zh, buf, buf_size,
2236                                  1, /* delete_flag */
2237                                  0, /* test_mode */
2238                                  recordType,
2239                                  sysno,
2240                                  match,fname,
2241                                  force_update,
2242                                  1); /* allow_update */
2243     zebra_end_trans(zh);
2244     return res;
2245 }
2246
2247 /* ---------------------------------------------------------------------------
2248   Searching 
2249 */
2250
2251 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2252                            const char *setname, zint *hits)
2253 {
2254     zint lhits = 0;
2255     ZEBRA_RES res = ZEBRA_OK;
2256     Z_RPNQuery *query;
2257     ODR odr = odr_createmem(ODR_ENCODE);
2258     ASSERTZH;
2259     assert(pqf_query);
2260     assert(setname);
2261
2262     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2263     
2264     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2265     
2266     if (!query)
2267     {
2268         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2269         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2270         res = ZEBRA_FAIL;
2271     }
2272     else
2273         res = zebra_search_RPN(zh, odr, query, setname, &lhits);
2274     
2275     odr_destroy(odr);
2276
2277     yaz_log(log_level, "Hits: " ZINT_FORMAT, lhits);
2278
2279     if (hits)
2280         *hits = lhits;
2281
2282     return res;
2283 }
2284
2285 /* ---------------------------------------------------------------------------
2286   Sort - a simplified interface, with optional read locks.
2287 */
2288 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2289                            const char *sort_spec,
2290                            const char *output_setname,
2291                            const char **input_setnames) 
2292 {
2293     int num_input_setnames = 0;
2294     int sort_status = 0;
2295     Z_SortKeySpecList *sort_sequence;
2296     ASSERTZH;
2297     assert(stream);
2298     assert(sort_spec);
2299     assert(output_setname);
2300     assert(input_setnames);
2301     sort_sequence = yaz_sort_spec (stream, sort_spec);
2302     yaz_log(log_level, "sort (FIXME) ");
2303     if (!sort_sequence)
2304     {
2305         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2306         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2307         return -1;
2308     }
2309     
2310     /* we can do this, since the perl typemap code for char** will 
2311        put a NULL at the end of list */
2312     while (input_setnames[num_input_setnames]) num_input_setnames++;
2313
2314     if (zebra_begin_read (zh))
2315         return -1;
2316     
2317     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2318                    output_setname, sort_sequence, &sort_status);
2319     
2320     zebra_end_read(zh);
2321     return sort_status;
2322 }
2323
2324 /* ---------------------------------------------------------------------------
2325   Get BFS for Zebra system (to make alternative storage methods)
2326 */
2327 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2328 {
2329     if (zh && zh->reg)
2330         return zh->reg->bfs;
2331     return 0;
2332 }
2333
2334
2335 /* ---------------------------------------------------------------------------
2336   Set limit for search/scan
2337 */
2338 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int complement_flag, zint *ids)
2339 {
2340     ASSERTZH;
2341     zebra_limit_destroy(zh->m_limit);
2342     zh->m_limit = zebra_limit_create(complement_flag, ids);
2343     return ZEBRA_OK;
2344 }
2345
2346 /*
2347   Set Error code + addinfo
2348 */
2349 void zebra_setError(ZebraHandle zh, int code, const char *addinfo)
2350 {
2351     zh->errCode = code;
2352     nmem_reset(zh->nmem_error);
2353     zh->errString = addinfo ? nmem_strdup(zh->nmem_error, addinfo) : 0;
2354 }
2355
2356 void zebra_setError_zint(ZebraHandle zh, int code, zint i)
2357 {
2358     char vstr[60];
2359     sprintf(vstr, ZINT_FORMAT, i);
2360
2361     zh->errCode = code;
2362     nmem_reset(zh->nmem_error);
2363     zh->errString = nmem_strdup(zh->nmem_error, vstr);
2364 }
2365
2366 void zebra_lock_prefix (Res res, char *path)
2367 {
2368     const char *lock_dir = res_get_def (res, "lockDir", "");
2369
2370     strcpy (path, lock_dir);
2371     if (*path && path[strlen(path)-1] != '/')
2372         strcat (path, "/");
2373 }
2374