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