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