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