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