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