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