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