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