Log permission for the active user
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.120.2.6 2005-05-12 10:01:54 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         if (!zh->lock_normal || !zh->lock_shadow)
633         {
634             if (zh->lock_normal)
635             {
636                 zebra_lock_destroy(zh->lock_normal);
637                 zh->lock_normal = 0;
638             }
639             if (zh->lock_shadow)
640             {
641                 zebra_lock_destroy(zh->lock_shadow);
642                 zh->lock_shadow = 0;
643             }
644             zebra_close_res(zh);
645             
646             return -1;
647         }
648     }
649     return 1;
650 }
651
652 void map_basenames_func (void *vp, const char *name, const char *value)
653 {
654     struct map_baseinfo *p = (struct map_baseinfo *) vp;
655     int i, no;
656     char fromdb[128], todb[8][128];
657     
658     no =
659         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
660                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
661                 todb[5], todb[6], todb[7]);
662     if (no < 2)
663         return ;
664     no--;
665     for (i = 0; i<p->num_bases; i++)
666         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
667         {
668             p->basenames[i] = 0;
669             for (i = 0; i < no; i++)
670             {
671                 if (p->new_num_bases == p->new_num_max)
672                     return;
673                 p->new_basenames[(p->new_num_bases)++] = 
674                     nmem_strdup (p->mem, todb[i]);
675             }
676             return;
677         }
678 }
679
680 void map_basenames (ZebraHandle zh, ODR stream,
681                     int *num_bases, char ***basenames)
682 {
683     struct map_baseinfo info;
684     struct map_baseinfo *p = &info;
685     int i;
686     ASSERTZH;
687     yaz_log(LOG_API,"map_basenames ");
688     zh->errCode=0;
689
690     info.zh = zh;
691     info.num_bases = *num_bases;
692     info.basenames = *basenames;
693     info.new_num_max = 128;
694     info.new_num_bases = 0;
695     info.new_basenames = (char **)
696         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
697     info.mem = stream->mem;
698
699     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
700     
701     for (i = 0; i<p->num_bases; i++)
702         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
703         {
704             p->new_basenames[(p->new_num_bases)++] = 
705                 nmem_strdup (p->mem, p->basenames[i]);
706         }
707     *num_bases = info.new_num_bases;
708     *basenames = info.new_basenames;
709     for (i = 0; i<*num_bases; i++)
710         logf (LOG_LOG, "base %s", (*basenames)[i]);
711 }
712
713 int zebra_select_default_database(ZebraHandle zh)
714 {
715     if (!zh->res)
716     {
717         /* no database has been selected - so we select based on
718            resource setting (including group)
719         */
720         const char *group = res_get(zh->service->global_res, "group");
721         const char *v = res_get_prefix(zh->service->global_res,
722                                        "database", group, "Default");
723         return zebra_select_database(zh, v);
724     }
725     return 0;
726 }
727
728 int zebra_select_database (ZebraHandle zh, const char *basename)
729 {
730     ASSERTZH;
731     yaz_log(LOG_API,"zebra_select_database %s",basename);
732     zh->errCode=0;
733     return zebra_select_databases (zh, 1, &basename);
734 }
735
736 int zebra_select_databases (ZebraHandle zh, int num_bases,
737                             const char **basenames)
738 {
739     int i;
740     const char *cp;
741     int len = 0;
742     char *new_reg = 0;
743     ASSERTZH;
744     yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
745                     num_bases,basenames[0]);
746     zh->errCode=0;
747     
748     if (num_bases < 1)
749     {
750         zh->errCode = 23;
751         return -1;
752     }
753     for (i = 0; i < zh->num_basenames; i++)
754         xfree (zh->basenames[i]);
755     xfree (zh->basenames);
756     
757     zh->num_basenames = num_bases;
758     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
759     for (i = 0; i < zh->num_basenames; i++)
760         zh->basenames[i] = xstrdup (basenames[i]);
761
762     cp = strrchr(basenames[0], '/');
763     if (cp)
764     {
765         len = cp - basenames[0];
766         new_reg = xmalloc (len + 1);
767         memcpy (new_reg, basenames[0], len);
768         new_reg[len] = '\0';
769     }
770     else
771         new_reg = xstrdup ("");
772     for (i = 1; i<num_bases; i++)
773     {
774         const char *cp1;
775
776         cp1 = strrchr (basenames[i], '/');
777         if (cp)
778         {
779             if (!cp1)
780             {
781                 zh->errCode = 23;
782                 return -1;
783             }
784             if (len != cp1 - basenames[i] ||
785                 memcmp (basenames[i], new_reg, len))
786             {
787                 zh->errCode = 23;
788                 return -1;
789             }
790         }
791         else
792         {
793             if (cp1)
794             {
795                 zh->errCode = 23;
796                 return -1;
797             }
798         }
799     }
800     zebra_select_register (zh, new_reg);
801     xfree (new_reg);
802     if (!zh->res)
803     {
804         zh->errCode = 109;
805         return -1;
806     }
807     if (!zh->lock_normal || !zh->lock_shadow)
808     {
809         zh->errCode = 2;
810         return -1;
811     }
812     return 0;
813 }
814
815 int zebra_search_RPN (ZebraHandle zh, ODR o,
816                        Z_RPNQuery *query, const char *setname, int *hits)
817 {
818     ASSERTZH;
819     yaz_log(LOG_API,"zebra_search_rpn");
820     zh->errCode=0;
821     zh->hits = 0;
822     *hits = 0;
823
824     if (zebra_begin_read (zh))
825         return 1;
826
827     zebra_livcode_transform(zh, query);
828
829     resultSetAddRPN (zh, odr_extract_mem(o), query, 
830                      zh->num_basenames, zh->basenames, setname);
831
832     zebra_end_read (zh);
833
834     *hits = zh->hits;
835     return 0;
836 }
837
838 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
839                              const char *setname, Z_RecordComposition *comp,
840                              oid_value input_format, int num_recs,
841                              ZebraRetrievalRecord *recs)
842 {
843     ZebraPosSet poset;
844     int i, *pos_array, ret = 0;
845     ASSERTZH;
846     yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
847     zh->errCode=0;
848
849     if (!zh->res)
850     {
851         zh->errCode = 30;
852         zh->errString = odr_strdup (stream, setname);
853         return -1;
854     }
855     
856     zh->errCode = 0;
857
858     if (zebra_begin_read (zh))
859         return -1;
860
861     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
862     for (i = 0; i<num_recs; i++)
863         pos_array[i] = recs[i].position;
864     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
865     if (!poset)
866     {
867         logf (LOG_DEBUG, "zebraPosSetCreate error");
868         zh->errCode = 30;
869         zh->errString = nmem_strdup (stream->mem, setname);
870         ret = -1;
871     }
872     else
873     {
874         for (i = 0; i<num_recs; i++)
875         {
876             if (poset[i].term)
877             {
878                 recs[i].errCode = 0;
879                 recs[i].format = VAL_SUTRS;
880                 recs[i].len = strlen(poset[i].term);
881                 recs[i].buf = poset[i].term;
882                 recs[i].base = poset[i].db;
883             }
884             else if (poset[i].sysno)
885             {
886                 recs[i].errCode =
887                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
888                                         stream, input_format, comp,
889                                         &recs[i].format, &recs[i].buf,
890                                         &recs[i].len,
891                                         &recs[i].base);
892                 recs[i].errString = NULL;
893             }
894             else
895             {
896                 char num_str[20];
897
898                 sprintf (num_str, "%d", pos_array[i]);  
899                 zh->errCode = 13;
900                 zh->errString = odr_strdup (stream, num_str);
901                 ret = -1;
902                 break;
903             }
904         }
905         zebraPosSetDestroy (zh, poset, num_recs);
906     }
907     zebra_end_read (zh);
908     xfree (pos_array);
909     return ret;
910 }
911
912 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
913                  oid_value attributeset,
914                  int *position, int *num_entries, ZebraScanEntry **entries,
915                  int *is_partial)
916 {
917     ASSERTZH;
918     yaz_log(LOG_API,"zebra_scan");
919     zh->errCode=0;
920     if (zebra_begin_read (zh))
921     {
922         *entries = 0;
923         *num_entries = 0;
924         return 1;
925     }
926     rpn_scan (zh, stream, zapt, attributeset,
927               zh->num_basenames, zh->basenames, position,
928               num_entries, entries, is_partial, 0, 0);
929     zebra_end_read (zh);
930     return 0;
931 }
932
933 int zebra_sort (ZebraHandle zh, ODR stream,
934                  int num_input_setnames, const char **input_setnames,
935                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
936                  int *sort_status)
937 {
938     ASSERTZH;
939     yaz_log(LOG_API,"zebra_sort");
940     zh->errCode=0;
941     if (zebra_begin_read (zh))
942         return 1;
943     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
944                    output_setname, sort_sequence, sort_status);
945     zebra_end_read(zh);
946     return 0;
947 }
948
949 int zebra_deleleResultSet(ZebraHandle zh, int function,
950                           int num_setnames, char **setnames,
951                           int *statuses)
952 {
953     int i, status;
954     ASSERTZH;
955     yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
956     zh->errCode=0;
957     if (zebra_begin_read(zh))
958         return Z_DeleteStatus_systemProblemAtTarget;
959     switch (function)
960     {
961     case Z_DeleteResultSetRequest_list:
962         resultSetDestroy (zh, num_setnames, setnames, statuses);
963         break;
964     case Z_DeleteResultSetRequest_all:
965         resultSetDestroy (zh, -1, 0, statuses);
966         break;
967     }
968     zebra_end_read (zh);
969     status = Z_DeleteStatus_success;
970     for (i = 0; i<num_setnames; i++)
971         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
972             status = statuses[i];
973     return status;
974 }
975
976 int zebra_errCode (ZebraHandle zh)
977 {
978     if (zh)
979     {
980         yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
981         return zh->errCode;
982     }
983     yaz_log(LOG_API,"zebra_errCode: o");
984     return 0; 
985 }
986
987 const char *zebra_errString (ZebraHandle zh)
988 {
989     const char *e="";
990     if (zh)
991         e= diagbib1_str (zh->errCode);
992     yaz_log(LOG_API,"zebra_errString: %s",e);
993     return e;
994 }
995
996 char *zebra_errAdd (ZebraHandle zh)
997 {
998     char *a="";
999     if (zh)
1000         a= zh->errString;
1001     yaz_log(LOG_API,"zebra_errAdd: %s",a);
1002     return a;
1003 }
1004
1005 void zebra_clearError(ZebraHandle zh)
1006 {
1007     if (zh)
1008     {
1009         zh->errCode=0;
1010         zh->errString="";
1011     }
1012 }
1013
1014 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1015 {
1016     const char *p;
1017     char u[40];
1018     ZebraService zs;
1019
1020     ASSERTZH;
1021     zh->errCode=0;
1022     zs= zh->service;
1023     
1024     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1025     p = res_get(zs->global_res, u);
1026     xfree (zh->user_perm);
1027     zh->user_perm = xstrdup(p ? p : "r");
1028
1029     yaz_log(LOG_LOG, "User perm for %s: %s", u, zh->user_perm);
1030
1031     /* users that don't require a password .. */
1032     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1033         return 0;
1034     
1035     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1036         return 0;
1037     return 1;
1038 }
1039
1040 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1041                                const char *record_type)
1042 {
1043     ASSERTZH;
1044     yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s", 
1045                      database, record_type);
1046     zh->errCode=0;
1047     if (zebra_select_database(zh, database))
1048         return 1;
1049     if (zebra_begin_trans (zh, 1))
1050         return 1;
1051     return 0;
1052 }
1053
1054 int zebra_admin_import_end (ZebraHandle zh)
1055 {
1056     ASSERTZH;
1057     yaz_log(LOG_API,"zebra_admin_import_end");
1058     zh->errCode=0;
1059     zebra_end_trans (zh);
1060     return 0;
1061 }
1062
1063 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1064 {
1065     int sysno;
1066     int i;
1067     ASSERTZH;
1068     yaz_log(LOG_API,"zebra_admin_import_segment");
1069     zh->errCode=0;
1070     for (i = 0; i<segment->num_segmentRecords; i++)
1071     {
1072         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1073
1074         printf ("--------------%d--------------------\n", i);
1075         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1076         {
1077             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1078             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1079             {
1080                 Odr_oct *oct = fragment->u.notExternallyTagged;
1081                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1082                         oct->buf);
1083                 
1084                 sysno = 0;
1085                 
1086                 zebra_update_record(zh, 
1087                                     0, /* record Type */
1088                                     &sysno,
1089                                     0, /* match */
1090                                     0, /* fname */
1091                                     oct->buf, oct->len,
1092                                     0);
1093             }
1094         }
1095     }
1096     return 0;
1097 }
1098
1099 int zebra_admin_exchange_record (ZebraHandle zh,
1100                                  const char *rec_buf,
1101                                  size_t rec_len,
1102                                  const char *recid_buf, size_t recid_len,
1103                                  int action)
1104     /* 1 = insert. Fail it already exists */
1105     /* 2 = replace. Fail it does not exist */
1106     /* 3 = delete. Fail if does not exist */
1107     /* 4 = update. Insert/replace */
1108 {
1109     int sysno = 0;
1110     char *rinfo = 0;
1111     char recid_z[256];
1112     ASSERTZH;
1113     yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1114     zh->errCode=0;
1115
1116     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1117         return -1;
1118     memcpy (recid_z, recid_buf, recid_len);
1119     recid_z[recid_len] = 0;
1120
1121     if (zebra_begin_trans(zh, 1))
1122         return -1;
1123
1124     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1125     if (rinfo)
1126     {
1127         if (action == 1)  /* fail if insert */
1128         {
1129              zebra_end_trans(zh);
1130              return -1;
1131         }
1132
1133         memcpy (&sysno, rinfo+1, sizeof(sysno));
1134     }
1135     else
1136     {
1137         if (action == 2 || action == 3) /* fail if delete or update */
1138         {
1139             zebra_end_trans(zh);
1140             return -1;
1141         }
1142         action = 1;  /* make it an insert (if it's an update).. */
1143     }
1144     buffer_extract_record (zh, rec_buf, rec_len,
1145                            action == 3 ? 1 : 0 /* delete flag */,
1146                            0, /* test mode */
1147                            0, /* recordType */
1148                            &sysno, 
1149                            0, /* match */
1150                            0, /* fname */
1151                            0, /* force update */
1152                            1  /* allow update */
1153         );
1154     if (action == 1)
1155     {
1156         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1157     }
1158     else if (action == 3)
1159     {
1160         dict_delete (zh->reg->matchDict, recid_z);
1161     }
1162     zebra_end_trans(zh);
1163     return 0;
1164 }
1165
1166 int delete_w_handle(const char *info, void *handle)
1167 {
1168     ZebraHandle zh = (ZebraHandle) handle;
1169     ISAMC_P pos;
1170
1171     if (*info == sizeof(pos))
1172     {
1173         memcpy (&pos, info+1, sizeof(pos));
1174         isamb_unlink(zh->reg->isamb, pos);
1175     }
1176     return 0;
1177 }
1178
1179 static int delete_SU_handle(void *handle, int ord)
1180 {
1181     ZebraHandle zh = (ZebraHandle) handle;
1182     char ord_buf[20];
1183     int ord_len;
1184
1185     ord_len = key_SU_encode (ord, ord_buf);
1186     ord_buf[ord_len] = '\0';
1187
1188     assert (zh->reg->isamb);
1189     dict_delete_subtree(zh->reg->dict, ord_buf,
1190                         zh, delete_w_handle);
1191     return 0;
1192 }
1193
1194 int zebra_drop_database  (ZebraHandle zh, const char *database)
1195 {
1196     int ret = 0;
1197     ASSERTZH;
1198     yaz_log(LOG_API,"zebra_drop_database");
1199     zh->errCode = 0;
1200
1201     if (zebra_select_database (zh, database))
1202         return -1;
1203     if (zebra_begin_trans (zh, 1))
1204         return -1;
1205     if (zh->reg->isamb)
1206     {
1207         zebraExplain_curDatabase (zh->reg->zei, database);
1208         
1209         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1210         zebraExplain_removeDatabase(zh->reg->zei, zh);
1211     }
1212     else
1213     {
1214         yaz_log(LOG_WARN, "drop database only supported for isam:b");
1215         ret = -1;
1216     }
1217     zebra_end_trans (zh);
1218     return ret;
1219 }
1220
1221 int zebra_create_database (ZebraHandle zh, const char *database)
1222 {
1223     ASSERTZH;
1224     yaz_log(LOG_API,"zebra_create_database");
1225     zh->errCode=0;
1226
1227     if (zebra_select_database (zh, database))
1228         return -1;
1229     if (zebra_begin_trans (zh, 1))
1230         return -1;
1231
1232     /* announce database */
1233     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1234                                   /* explainDatabase */))
1235     {
1236         zebra_end_trans (zh);
1237         zh->errCode = 224;
1238         zh->errString = "database already exist";
1239         return -1;
1240     }
1241     zebra_end_trans (zh);
1242     return 0;
1243 }
1244
1245 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1246                        const char *input_str, int input_len,
1247                        char *output_str, int output_len)
1248 {
1249     WRBUF wrbuf;
1250     ASSERTZH;
1251     yaz_log(LOG_API,"zebra_string_norm ");
1252     zh->errCode=0;
1253     if (!zh->reg->zebra_maps)
1254         return -1;
1255     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1256                           input_str, input_len);
1257     if (!wrbuf)
1258         return -2;
1259     if (wrbuf_len(wrbuf) >= output_len)
1260         return -3;
1261     if (wrbuf_len(wrbuf))
1262         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1263     output_str[wrbuf_len(wrbuf)] = '\0';
1264     return wrbuf_len(wrbuf);
1265 }
1266
1267
1268 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1269 {
1270     char state_fname[256];
1271     char *fname;
1272     long p = getpid();
1273     FILE *f;
1274     ASSERTZH;
1275     yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1276     zh->errCode=0;
1277
1278     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1279     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1280     f = fopen (fname, "w");
1281
1282     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1283     fprintf (f, "%c %d %ld\n", val, seqno, p);
1284     fclose (f);
1285     xfree (fname);
1286     return 0;
1287 }
1288
1289 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1290 {
1291     char state_fname[256];
1292     char *fname;
1293     FILE *f;
1294
1295     ASSERTZH;
1296     yaz_log(LOG_API,"zebra_get_state ");
1297     zh->errCode=0;
1298     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1299     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1300     f = fopen (fname, "r");
1301     *val = 'o';
1302     *seqno = 0;
1303
1304     if (f)
1305     {
1306         fscanf (f, "%c %d", val, seqno);
1307         fclose (f);
1308     }
1309     xfree (fname);
1310     return 0;
1311 }
1312
1313 int zebra_begin_read (ZebraHandle zh)
1314 {
1315     return zebra_begin_trans(zh, 0);
1316 }
1317
1318 int zebra_end_read (ZebraHandle zh)
1319 {
1320     return zebra_end_trans(zh);
1321 }
1322
1323 static void read_res_for_transaction(ZebraHandle zh)
1324 {
1325     const char *group = res_get(zh->res, "group");
1326     const char *v;
1327     
1328     zh->m_group = group;
1329     v = res_get_prefix(zh->res, "followLinks", group, "1");
1330     zh->m_follow_links = atoi(v);
1331
1332     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1333     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1334
1335     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1336     zh->m_store_keys = atoi(v);
1337
1338     v = res_get_prefix(zh->res, "storeData", group, "1");
1339     zh->m_store_data = atoi(v);
1340
1341     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1342     zh->m_explain_database = atoi(v);
1343
1344     v = res_get_prefix(zh->res, "openRW", group, "1");
1345     zh->m_flag_rw = atoi(v);
1346
1347     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1348     zh->m_file_verbose_limit = atoi(v);
1349 }
1350
1351 int zebra_begin_trans (ZebraHandle zh, int rw)
1352 {
1353     zebra_select_default_database(zh);
1354     if (!zh->res)
1355     {
1356         zh->errCode = 2;
1357         zh->errString = "zebra_begin_trans: no database selected";
1358         return -1;
1359     }
1360     ASSERTZHRES;
1361     yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1362
1363     if (zh->user_perm)
1364     {
1365         if (rw && !strchr(zh->user_perm, 'w'))
1366         {
1367             zh->errCode = 223;
1368             zh->errString = 0;
1369             return -1;
1370         }
1371     }
1372
1373     assert (zh->res);
1374     if (rw)
1375     {
1376         int pass;
1377         int seqno = 0;
1378         char val = '?';
1379         const char *rval = 0;
1380         
1381         (zh->trans_no++);
1382         if (zh->trans_w_no)
1383         {
1384             read_res_for_transaction(zh);
1385             return 0;
1386         }
1387         if (zh->trans_no != 1)
1388         {
1389             zh->errCode = 2;
1390             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1391             return -1;
1392         }
1393         if (zh->reg)
1394         {
1395             resultSetInvalidate (zh);
1396             zebra_register_close (zh->service, zh->reg);
1397         }
1398         zh->trans_w_no = zh->trans_no;
1399
1400         zh->errCode=0;
1401         
1402         zh->records_inserted = 0;
1403         zh->records_updated = 0;
1404         zh->records_deleted = 0;
1405         zh->records_processed = 0;
1406         
1407 #if HAVE_SYS_TIMES_H
1408         times (&zh->tms1);
1409 #endif
1410         /* lock */
1411         if (zh->shadow_enable)
1412             rval = res_get (zh->res, "shadow");
1413         
1414         for (pass = 0; pass < 2; pass++)
1415         {
1416             if (rval)
1417             {
1418                 zebra_lock_r (zh->lock_normal);
1419                 zebra_lock_w (zh->lock_shadow);
1420             }
1421             else
1422             {
1423                 zebra_lock_w (zh->lock_normal);
1424                 zebra_lock_w (zh->lock_shadow);
1425             }
1426             
1427             zebra_get_state (zh, &val, &seqno);
1428             if (val == 'c')
1429             {
1430                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1431                 zebra_unlock (zh->lock_shadow);
1432                 zebra_unlock (zh->lock_normal);
1433                 zebra_commit (zh);
1434                 continue;
1435             }
1436             else if (val == 'd')
1437             {
1438                 if (rval)
1439                 {
1440                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1441                                              zh->path_reg);
1442                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1443                     bf_commitClean (bfs, rval);
1444                     bfs_destroy (bfs);
1445             }
1446                 else
1447                 {
1448                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1449                 }
1450             }
1451             break;
1452         }
1453         if (pass == 2)
1454         {
1455             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1456             abort();
1457             return -1;
1458         }
1459         zebra_set_state (zh, 'd', seqno);
1460         
1461         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1462                                        1, rval ? 1 : 0, zh->res,
1463                                        zh->path_reg);
1464         if (zh->reg)
1465             zh->reg->seqno = seqno;
1466         else
1467         {
1468             zebra_set_state (zh, 'o', seqno);
1469             
1470             zebra_unlock (zh->lock_shadow);
1471             zebra_unlock (zh->lock_normal);
1472
1473             zh->trans_no--;
1474             zh->trans_w_no = 0;
1475
1476             zh->errCode = 2;
1477             zh->errString = "zebra_begin_trans: cannot open register";
1478             yaz_log(LOG_FATAL, zh->errString);
1479             return -1;
1480         }
1481     }
1482     else
1483     {
1484         int dirty = 0;
1485         char val;
1486         int seqno;
1487         
1488         (zh->trans_no)++;
1489         
1490         if (zh->trans_no != 1)
1491         {
1492             zebra_flush_reg (zh);
1493             return 0;
1494         }
1495         zh->errCode=0;
1496 #if HAVE_SYS_TIMES_H
1497         times (&zh->tms1);
1498 #endif
1499         if (!zh->res)
1500         {
1501             (zh->trans_no)--;
1502             zh->errCode = 109;
1503             return -1;
1504         }
1505         if (!zh->lock_normal || !zh->lock_shadow)
1506         {
1507             (zh->trans_no)--;
1508             zh->errCode = 2;
1509             return -1;
1510         }
1511         zebra_get_state (zh, &val, &seqno);
1512         if (val == 'd')
1513             val = 'o';
1514         
1515         if (!zh->reg)
1516             dirty = 1;
1517         else if (seqno != zh->reg->seqno)
1518         {
1519             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1520                      seqno, zh->reg->seqno);
1521             dirty = 1;
1522         }
1523         else if (zh->reg->last_val != val)
1524         {
1525             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1526                      val, zh->reg->last_val);
1527             dirty = 1;
1528         }
1529         if (!dirty)
1530             return 0;
1531         
1532         if (val == 'c')
1533             zebra_lock_r (zh->lock_shadow);
1534         else
1535             zebra_lock_r (zh->lock_normal);
1536         
1537         if (zh->reg)
1538         {
1539             resultSetInvalidate (zh);
1540             zebra_register_close (zh->service, zh->reg);
1541         }
1542         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1543                                        0, val == 'c' ? 1 : 0,
1544                                        zh->res, zh->path_reg);
1545         if (!zh->reg)
1546         {
1547             zebra_unlock (zh->lock_normal);
1548             zebra_unlock (zh->lock_shadow);
1549             zh->trans_no--;
1550             zh->errCode = 109;
1551             return -1;
1552         }
1553         zh->reg->last_val = val;
1554         zh->reg->seqno = seqno;
1555     }
1556     read_res_for_transaction(zh);
1557     return 0;
1558 }
1559
1560 int zebra_end_trans (ZebraHandle zh)
1561 {
1562     ZebraTransactionStatus dummy;
1563     yaz_log(LOG_API,"zebra_end_trans");
1564     return zebra_end_transaction(zh, &dummy);
1565 }
1566
1567 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1568 {
1569     char val;
1570     int seqno;
1571     const char *rval;
1572
1573     ASSERTZH;
1574     yaz_log(LOG_API,"zebra_end_transaction");
1575
1576     status->processed = 0;
1577     status->inserted  = 0;
1578     status->updated   = 0;
1579     status->deleted   = 0;
1580     status->utime     = 0;
1581     status->stime     = 0;
1582
1583     if (!zh->res || !zh->reg)
1584     {
1585         zh->errCode = 2;
1586         zh->errString = "zebra_end_trans: no open transaction";
1587         return -1;
1588     }
1589     if (zh->trans_no != zh->trans_w_no)
1590     {
1591         zh->trans_no--;
1592         if (zh->trans_no != 0)
1593             return 0;
1594
1595         /* release read lock */
1596
1597         zebra_unlock (zh->lock_normal);
1598         zebra_unlock (zh->lock_shadow);
1599     }
1600     else
1601     {   /* release write lock */
1602         zh->trans_no--;
1603         zh->trans_w_no = 0;
1604         
1605         yaz_log (LOG_LOG, "zebra_end_trans");
1606         rval = res_get (zh->res, "shadow");
1607         
1608         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1609         
1610         zebra_flush_reg (zh);
1611         
1612         resultSetInvalidate (zh);
1613
1614         zebra_register_close (zh->service, zh->reg);
1615         zh->reg = 0;
1616         
1617         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1618                  zh->records_processed, zh->records_inserted,
1619                  zh->records_updated, zh->records_deleted);
1620         
1621         status->processed = zh->records_processed;
1622         status->inserted = zh->records_inserted;
1623         status->updated = zh->records_updated;
1624         status->deleted = zh->records_deleted;
1625         
1626         zebra_get_state (zh, &val, &seqno);
1627         if (val != 'd')
1628         {
1629             BFiles bfs = bfs_create (rval, zh->path_reg);
1630             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1631             bf_commitClean (bfs, rval);
1632             bfs_destroy (bfs);
1633         }
1634         if (!rval)
1635             seqno++;
1636         zebra_set_state (zh, 'o', seqno);
1637         
1638         zebra_unlock (zh->lock_shadow);
1639         zebra_unlock (zh->lock_normal);
1640         
1641     }
1642 #if HAVE_SYS_TIMES_H
1643     times (&zh->tms2);
1644     logf (LOG_LOG, "user/system: %ld/%ld",
1645           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1646           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1647     
1648     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1649     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1650 #endif
1651     return 0;
1652 }
1653
1654 int zebra_repository_update (ZebraHandle zh, const char *path)
1655 {
1656     ASSERTZH;
1657     zh->errCode=0;
1658     logf (LOG_LOG|LOG_API, "updating %s", path);
1659     repositoryUpdate (zh, path);
1660     return zh->errCode;
1661 }
1662
1663 int zebra_repository_delete (ZebraHandle zh, const char *path)
1664 {
1665     ASSERTZH;
1666     zh->errCode=0;
1667     logf (LOG_LOG|LOG_API, "deleting %s", path);
1668     repositoryDelete (zh, path);
1669     return zh->errCode;
1670 }
1671
1672 int zebra_repository_show (ZebraHandle zh, const char *path)
1673 {
1674     ASSERTZH;
1675     yaz_log(LOG_API,"zebra_repository_show");
1676     zh->errCode=0;
1677     repositoryShow (zh, path);
1678     return zh->errCode;
1679 }
1680
1681 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1682 {
1683     int seqno;
1684     char val;
1685     const char *rval;
1686     BFiles bfs;
1687     ASSERTZH;
1688     zh->errCode=0;
1689
1690     zebra_select_default_database(zh);
1691     if (!zh->res)
1692     {
1693         zh->errCode = 109;
1694         return -1;
1695     }
1696     rval = res_get (zh->res, "shadow");    
1697     if (!rval)
1698     {
1699         logf (LOG_WARN, "Cannot perform commit");
1700         logf (LOG_WARN, "No shadow area defined");
1701         return 0;
1702     }
1703
1704     zebra_lock_w (zh->lock_normal);
1705     zebra_lock_r (zh->lock_shadow);
1706
1707     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1708
1709     zebra_get_state (zh, &val, &seqno);
1710
1711     if (rval && *rval)
1712         bf_cache (bfs, rval);
1713     if (bf_commitExists (bfs))
1714     {
1715         if (clean_only)
1716             zebra_set_state (zh, 'd', seqno);
1717         else
1718         {
1719             zebra_set_state (zh, 'c', seqno);
1720             
1721             logf (LOG_LOG, "commit start");
1722             bf_commitExec (bfs);
1723 #ifndef WIN32
1724             sync ();
1725 #endif
1726         }
1727         logf (LOG_LOG, "commit clean");
1728         bf_commitClean (bfs, rval);
1729         seqno++;
1730         zebra_set_state (zh, 'o', seqno);
1731     }
1732     else
1733     {
1734         logf (LOG_LOG, "nothing to commit");
1735     }
1736     bfs_destroy (bfs);
1737
1738     zebra_unlock (zh->lock_shadow);
1739     zebra_unlock (zh->lock_normal);
1740     return 0;
1741 }
1742
1743 int zebra_clean (ZebraHandle zh)
1744 {
1745     yaz_log(LOG_API,"zebra_clean");
1746     return zebra_commit_ex(zh, 1);
1747 }
1748
1749 int zebra_commit (ZebraHandle zh)
1750 {
1751     yaz_log(LOG_API,"zebra_commit");
1752     return zebra_commit_ex(zh, 0);
1753 }
1754
1755 int zebra_init (ZebraHandle zh)
1756 {
1757     const char *rval;
1758     BFiles bfs = 0;
1759     ASSERTZH;
1760     yaz_log(LOG_API,"zebra_init");
1761     zh->errCode=0;
1762
1763     zebra_select_default_database(zh);
1764     if (!zh->res)
1765     {
1766         zh->errCode = 109;
1767         return -1;
1768     }
1769     rval = res_get (zh->res, "shadow");
1770
1771     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1772     if (!bfs)
1773         return -1;
1774     if (rval && *rval)
1775         bf_cache (bfs, rval);
1776     
1777     bf_reset (bfs);
1778     bfs_destroy (bfs);
1779     zebra_set_state (zh, 'o', 0);
1780     return 0;
1781 }
1782
1783 int zebra_compact (ZebraHandle zh)
1784 {
1785     BFiles bfs;
1786     ASSERTZH;
1787     yaz_log(LOG_API,"zebra_compact");
1788     zh->errCode=0;
1789     if (!zh->res)
1790     {
1791         zh->errCode = 109;
1792         return -1;
1793     }
1794     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1795     inv_compact (bfs);
1796     bfs_destroy (bfs);
1797     return 0;
1798 }
1799
1800 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1801 {
1802     ASSERTZH;
1803     yaz_log(LOG_API,"zebra_result");
1804     *code = zh->errCode;
1805     *addinfo = zh->errString;
1806     return 0;
1807 }
1808
1809 int zebra_shadow_enable (ZebraHandle zh, int value)
1810 {
1811     ASSERTZH;
1812     yaz_log(LOG_API,"zebra_shadow_enable");
1813     zh->errCode=0;
1814     zh->shadow_enable = value;
1815     return 0;
1816 }
1817
1818 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1819 {
1820     ASSERTZH;
1821     yaz_log(LOG_API,"zebra_record_encoding");
1822     zh->errCode=0;
1823     xfree (zh->record_encoding);
1824
1825     /*
1826      * Fixme!
1827      * Something about charset aliases. Oleg???
1828      */
1829
1830     if (zh->iconv_to_utf8 != 0)
1831         yaz_iconv_close(zh->iconv_to_utf8);
1832     if (zh->iconv_from_utf8 != 0)
1833         yaz_iconv_close(zh->iconv_from_utf8);
1834     
1835     zh->record_encoding = xstrdup (encoding);
1836     
1837     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1838     
1839     zh->iconv_to_utf8 =
1840         yaz_iconv_open ("UTF-8", encoding);
1841     if (zh->iconv_to_utf8 == 0)
1842         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1843     zh->iconv_from_utf8 =
1844         yaz_iconv_open (encoding, "UTF-8");
1845     if (zh->iconv_to_utf8 == 0)
1846         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1847
1848     return 0;
1849 }
1850
1851 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1852 {
1853     ASSERTZH;
1854     yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1855     zh->errCode=0;
1856     res_set(zh->res, name, value);
1857     return 0;
1858 }
1859
1860 const char *zebra_get_resource(ZebraHandle zh,
1861                                const char *name, const char *defaultvalue)
1862 {
1863     const char *v;
1864     ASSERTZH;
1865     v= res_get_def( zh->res, name, (char *)defaultvalue);
1866     zh->errCode=0;
1867     yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1868     return v;
1869 }
1870
1871 /* moved from zebra_api_ext.c by pop */
1872 /* FIXME: Should this really be public??? -Heikki */
1873
1874 int zebra_trans_no (ZebraHandle zh)
1875 {
1876     ASSERTZH;
1877     yaz_log(LOG_API,"zebra_trans_no");
1878     return zh->trans_no;
1879 }
1880
1881 int zebra_get_shadow_enable (ZebraHandle zh)
1882 {
1883     yaz_log(LOG_API,"zebra_get_shadow_enable");
1884     return (zh->shadow_enable);
1885 }
1886
1887 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1888 {
1889     yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1890     zh->shadow_enable = value;
1891     return 0;
1892 }
1893
1894 /* almost the same as zebra_records_retrieve ... but how did it work? 
1895    I mean for multiple records ??? CHECK ??? */
1896 void api_records_retrieve (ZebraHandle zh, ODR stream,
1897                            const char *setname, Z_RecordComposition *comp,
1898                            oid_value input_format, int num_recs,
1899                            ZebraRetrievalRecord *recs)
1900 {
1901     ZebraPosSet poset;
1902     int i, *pos_array;
1903     yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1904
1905     if (!zh->res)
1906     {
1907         zh->errCode = 30;
1908         zh->errString = odr_strdup (stream, setname);
1909         return;
1910     }
1911     
1912     zh->errCode = 0; 
1913
1914     if (zebra_begin_read (zh))
1915         return;
1916
1917     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1918     for (i = 0; i<num_recs; i++)
1919         pos_array[i] = recs[i].position;
1920     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1921     if (!poset)
1922     {
1923         logf (LOG_DEBUG, "zebraPosSetCreate error");
1924         zh->errCode = 30;
1925         zh->errString = nmem_strdup (stream->mem, setname);
1926     }
1927     else
1928     {
1929         for (i = 0; i<num_recs; i++)
1930         {
1931             if (poset[i].term)
1932             {
1933                 recs[i].errCode = 0;
1934                 recs[i].format = VAL_SUTRS;
1935                 recs[i].len = strlen(poset[i].term);
1936                 recs[i].buf = poset[i].term;
1937                 recs[i].base = poset[i].db;
1938                 recs[i].sysno = 0;
1939             
1940             }
1941             else if (poset[i].sysno)
1942             {
1943               /* changed here ??? CHECK ??? */
1944               char *b;
1945                 recs[i].errCode =
1946                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1947                                         stream, input_format, comp,
1948                                         &recs[i].format, 
1949                                         &b,
1950                                         &recs[i].len,
1951                                         &recs[i].base);
1952                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1953                 memcpy(recs[i].buf, b, recs[i].len);
1954                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1955                 recs[i].sysno = poset[i].sysno;
1956                 recs[i].score = poset[i].score;
1957             }
1958             else
1959             {
1960                 char num_str[20];
1961
1962                 sprintf (num_str, "%d", pos_array[i]);  
1963                 zh->errCode = 13;
1964                 zh->errString = odr_strdup (stream, num_str);
1965                 break;
1966             }
1967
1968         }
1969         zebraPosSetDestroy (zh, poset, num_recs);
1970     }
1971     zebra_end_read (zh);
1972     xfree (pos_array);
1973 }
1974
1975
1976 /* ---------------------------------------------------------------------------
1977   Record insert(=update), delete 
1978
1979   If sysno is provided, then it's used to identify the record.
1980   If not, and match_criteria is provided, then sysno is guessed
1981   If not, and a record is provided, then sysno is got from there
1982 NOTE: Now returns 0 at success and updates sysno, which is an int*
1983   20-jun-2003 Heikki
1984 */
1985
1986 int zebra_add_record(ZebraHandle zh,
1987                      const char *buf, int buf_size)
1988 {
1989     int sysno = 0;
1990     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1991 }
1992
1993 int zebra_insert_record (ZebraHandle zh, 
1994                          const char *recordType,
1995                          int *sysno, const char *match, const char *fname,
1996                          const char *buf, int buf_size, int force_update)
1997 {
1998     int res;
1999     yaz_log(LOG_API,"zebra_insert_record sysno=%d", *sysno);
2000
2001     if (buf_size < 1) buf_size = strlen(buf);
2002
2003     if (zebra_begin_trans(zh, 1))
2004         return 1;
2005     res = buffer_extract_record (zh, buf, buf_size, 
2006                                  0, /* delete_flag  */
2007                                  0, /* test_mode */
2008                                  recordType,
2009                                  sysno,   
2010                                  match, fname,
2011                                  0, 
2012                                  0); /* allow_update */
2013     zebra_end_trans(zh); 
2014     return res; 
2015 }
2016
2017 int zebra_update_record (ZebraHandle zh, 
2018                          const char *recordType,
2019                          int* sysno, const char *match, const char *fname,
2020                          const char *buf, int buf_size,
2021                          int force_update)
2022 {
2023     int res;
2024
2025     yaz_log(LOG_API,"zebra_update_record sysno=%d", *sysno);
2026
2027     if (buf_size < 1) buf_size = strlen(buf);
2028
2029     if (zebra_begin_trans(zh, 1))
2030         return 1;
2031     res = buffer_extract_record (zh, buf, buf_size, 
2032                                  0, /* delete_flag */
2033                                  0, /* test_mode */
2034                                  recordType,
2035                                  sysno,   
2036                                  match, fname,
2037                                  force_update, 
2038                                  1); /* allow_update */
2039     yaz_log(LOG_LOG, "zebra_update_record returned res=%d", res);
2040     zebra_end_trans(zh); 
2041     return res; 
2042 }
2043
2044 int zebra_delete_record (ZebraHandle zh, 
2045                          const char *recordType,
2046                          int *sysno, const char *match, const char *fname,
2047                          const char *buf, int buf_size,
2048                          int force_update) 
2049 {
2050     int res;
2051     yaz_log(LOG_API,"zebra_delete_record sysno=%d", *sysno);
2052
2053     if (buf_size < 1) buf_size = strlen(buf);
2054
2055     if (zebra_begin_trans(zh, 1))
2056         return 1;
2057     res = buffer_extract_record (zh, buf, buf_size,
2058                                  1, /* delete_flag */
2059                                  0, /* test_mode */
2060                                  recordType,
2061                                  sysno,
2062                                  match,fname,
2063                                  force_update,
2064                                  1); /* allow_update */
2065     zebra_end_trans(zh);
2066     return res;   
2067 }
2068
2069 /* ---------------------------------------------------------------------------
2070   Searching 
2071 */
2072
2073 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2074                       const char *setname, int *numhits)
2075 {
2076     int hits = 0;
2077     int res=-1;
2078     Z_RPNQuery *query;
2079     ODR odr = odr_createmem(ODR_ENCODE);
2080
2081     yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2082     
2083     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2084     
2085     if (!query)
2086         yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2087     else
2088         res=zebra_search_RPN (zh, odr, query, setname, &hits);
2089     
2090     odr_destroy(odr);
2091
2092     yaz_log(LOG_API,"Hits: %d",hits);
2093
2094     if (numhits)
2095         *numhits=hits;
2096
2097     return res;
2098 }
2099
2100 /* ---------------------------------------------------------------------------
2101   Sort - a simplified interface, with optional read locks.
2102   FIXME - This is a horrible name, will conflict with half the applications
2103 */
2104 int zebra_sort_by_specstr (ZebraHandle zh, 
2105                            ODR stream,
2106                            const char *sort_spec,
2107                            const char *output_setname,
2108                            const char **input_setnames) 
2109 {
2110     int num_input_setnames = 0;
2111     int sort_status = 0;
2112     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2113     yaz_log(LOG_API,"sort (FIXME) ");
2114     if (!sort_sequence)
2115     {
2116         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2117         zh->errCode = 207;
2118         return -1;
2119     }
2120     
2121     /* we can do this, since the perl typemap code for char** will 
2122        put a NULL at the end of list */
2123     while (input_setnames[num_input_setnames]) num_input_setnames++;
2124
2125     if (zebra_begin_read (zh))
2126         return -1;
2127     
2128     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2129                    output_setname, sort_sequence, &sort_status);
2130     
2131     zebra_end_read(zh);
2132     return sort_status;
2133 }
2134