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