Asserts in zebraapi, clearing the errCode
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.83 2003-02-12 15:45:59 heikki Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002
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 "index.h"
37 #include <charmap.h>
38
39 /* simple asserts to validate the most essential input args */
40 #define ASSERTZH assert(zh && zh->service)
41 #define ASSERTZHRES assert(zh && zh->service && zh->res)
42 #define ASSERTZS assert(zs)
43
44 static Res zebra_open_res (ZebraHandle zh);
45 static void zebra_close_res (ZebraHandle zh);
46
47
48 static void zebra_chdir (ZebraService zs)
49 {
50     const char *dir ;
51     ASSERTZS;
52     dir = res_get (zs->global_res, "chdir");
53     if (!dir)
54         return;
55     logf (LOG_DEBUG, "chdir %s", dir);
56 #ifdef WIN32
57     _chdir(dir);
58 #else
59     chdir (dir);
60 #endif
61 }
62
63 static void zebra_flush_reg (ZebraHandle zh)
64 {
65     ASSERTZH;
66     zh->errCode=0;
67     zebraExplain_flush (zh->reg->zei, zh);
68     
69     extract_flushWriteKeys (zh);
70     zebra_index_merge (zh);
71 }
72
73 static struct zebra_register *zebra_register_open (ZebraService zs, 
74                                                    const char *name,
75                                                    int rw, int useshadow,
76                                                    Res res,
77                                                    const char *reg_path);
78 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
79
80 ZebraHandle zebra_open (ZebraService zs)
81 {
82     ZebraHandle zh;
83     const char *default_encoding;
84     ASSERTZS;
85
86     if (!zs)
87         return 0;
88
89     zh = (ZebraHandle) xmalloc (sizeof(*zh));
90     yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
91
92     zh->service = zs;
93     zh->reg = 0;          /* no register attached yet */
94     zh->sets = 0;
95     zh->destroyed = 0;
96     zh->errCode = 0;
97     zh->errString = 0;
98     zh->res = 0; 
99
100     zh->reg_name = xstrdup ("");
101     zh->path_reg = 0;
102     zh->num_basenames = 0;
103     zh->basenames = 0;
104
105     zh->trans_no = 0;
106
107     zh->lock_normal = 0;
108     zh->lock_shadow = 0;
109
110     zh->admin_databaseName = 0;
111
112     zh->shadow_enable = 1;
113
114     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
115     zh->record_encoding = xstrdup (default_encoding);
116
117     zh->iconv_to_utf8 =
118         yaz_iconv_open ("UTF-8", default_encoding);
119     if (zh->iconv_to_utf8 == 0)
120         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
121            default_encoding);
122     zh->iconv_from_utf8 =
123         yaz_iconv_open (default_encoding, "UTF-8");
124     if (zh->iconv_to_utf8 == 0)
125         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
126            default_encoding);
127
128     zebra_mutex_cond_lock (&zs->session_lock);
129
130     zh->next = zs->sessions;
131     zs->sessions = zh;
132
133     zebra_mutex_cond_unlock (&zs->session_lock);
134
135     return zh;
136 }
137
138 ZebraService zebra_start (const char *configName)
139 {
140     Res res;
141
142     yaz_log (LOG_LOG, "zebra_start %s", configName);
143
144     if ((res = res_open (configName, 0)))
145     {
146         ZebraService zh = xmalloc (sizeof(*zh));
147
148         yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
149         
150         zh->global_res = res;
151         zh->configName = xstrdup(configName);
152         zh->sessions = 0;
153         
154         zebra_chdir (zh);
155         
156         zebra_mutex_cond_init (&zh->session_lock);
157         if (!res_get (zh->global_res, "passwd"))
158             zh->passwd_db = NULL;
159         else
160         {
161             zh->passwd_db = passwd_db_open ();
162             if (!zh->passwd_db)
163                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
164             else
165                 passwd_db_file (zh->passwd_db,
166                                 res_get (zh->global_res, "passwd"));
167         }
168         zh->path_root = res_get (zh->global_res, "root");
169         return zh;
170     }
171     return 0;
172 }
173
174 static
175 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
176                                             int rw, int useshadow, Res res,
177                                             const char *reg_path)
178 {
179     struct zebra_register *reg;
180     int record_compression = REC_COMPRESS_NONE;
181     char *recordCompression = 0;
182
183     ASSERTZS;
184     
185     reg = xmalloc (sizeof(*reg));
186
187     assert (name);
188     reg->name = xstrdup (name);
189
190     reg->seqno = 0;
191     reg->last_val = 0;
192
193     assert (res);
194
195     yaz_log (LOG_DEBUG, "zebra_register_open rw = %d useshadow=%d p=%p",
196              rw, useshadow, reg);
197
198     reg->dh = data1_createx (DATA1_FLAG_XML);
199     if (!reg->dh)
200         return 0;
201     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
202     if (!reg->bfs)
203     {
204         data1_destroy(reg->dh);
205         return 0;
206     }
207     if (useshadow)
208         bf_cache (reg->bfs, res_get (res, "shadow"));
209     data1_set_tabpath (reg->dh, res_get_def(res, "profilePath",
210                                             DEFAULT_PROFILE_PATH));
211     data1_set_tabroot (reg->dh, reg_path);
212     reg->recTypes = recTypes_init (reg->dh);
213     recTypes_default_handlers (reg->recTypes);
214
215     reg->zebra_maps = zebra_maps_open (res, reg_path);
216     reg->rank_classes = NULL;
217
218     reg->key_buf = 0;
219
220     reg->keys.buf_max = 0;
221     reg->keys.buf = 0;
222
223     reg->records = 0;
224     reg->dict = 0;
225     reg->sortIdx = 0;
226     reg->isams = 0;
227     reg->matchDict = 0;
228     reg->isam = 0;
229     reg->isamc = 0;
230     reg->isamd = 0;
231     reg->isamb = 0;
232     reg->zei = 0;
233     reg->matchDict = 0;
234     reg->key_file_no = 0;
235     
236     zebraRankInstall (reg, rank1_class);
237
238     recordCompression = res_get_def (res, "recordCompression", "none");
239     if (!strcmp (recordCompression, "none"))
240         record_compression = REC_COMPRESS_NONE;
241     if (!strcmp (recordCompression, "bzip2"))
242         record_compression = REC_COMPRESS_BZIP2;
243
244     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
245     {
246         logf (LOG_WARN, "rec_open");
247         return 0;
248     }
249     if (rw)
250     {
251         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
252     }
253     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
254     {
255         logf (LOG_WARN, "dict_open");
256         return 0;
257     }
258     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
259     {
260         logf (LOG_WARN, "sortIdx_open");
261         return 0;
262     }
263     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
264     {
265         struct ISAMS_M_s isams_m;
266         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
267                                       key_isams_m(res, &isams_m))))
268         {
269             logf (LOG_WARN, "isams_open");
270             return 0;
271         }
272     }
273     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
274     {
275         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
276                                   sizeof (struct it_key), res)))
277         {
278             logf (LOG_WARN, "is_open");
279             return 0;
280         }
281     }
282     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
283     {
284         struct ISAMC_M_s isamc_m;
285         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
286                                     rw, key_isamc_m(res, &isamc_m))))
287         {
288             logf (LOG_WARN, "isc_open");
289             return 0;
290         }
291     }
292     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
293     {
294         struct ISAMD_M_s isamd_m;
295         
296         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
297                                       rw, key_isamd_m(res, &isamd_m))))
298         {
299             logf (LOG_WARN, "isamd_open");
300             return 0;
301         }
302     }
303     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
304     {
305         struct ISAMC_M_s isamc_m;
306         
307         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
308                                        rw, key_isamc_m(res, &isamc_m), 0)))
309         {
310             logf (LOG_WARN, "isamb_open");
311             return 0;
312         }
313     }
314     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
315     {
316         struct ISAMC_M_s isamc_m;
317         
318         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
319                                        rw, key_isamc_m(res, &isamc_m), 1)))
320         {
321             logf (LOG_WARN, "isamb_open");
322             return 0;
323         }
324     }
325     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
326     {
327         struct ISAMC_M_s isamc_m;
328         
329         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
330                                        rw, key_isamc_m(res, &isamc_m), -1)))
331         {
332             logf (LOG_WARN, "isamb_open");
333             return 0;
334         }
335     }
336     reg->zei = zebraExplain_open (reg->records, reg->dh,
337                                   res, rw, reg,
338                                   explain_extract);
339     if (!reg->zei)
340     {
341         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
342         return 0;
343     }
344     reg->active = 2;
345     yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
346     return reg;
347 }
348
349 void zebra_admin_shutdown (ZebraHandle zh)
350 {
351     ASSERTZH;
352     zh->errCode=0;
353
354     zebra_mutex_cond_lock (&zh->service->session_lock);
355     zh->service->stop_flag = 1;
356     zebra_mutex_cond_unlock (&zh->service->session_lock);
357 }
358
359 void zebra_admin_start (ZebraHandle zh)
360 {
361     ZebraService zs;
362     ASSERTZH;
363     zh->errCode=0;
364     zs = zh->service;
365     zebra_mutex_cond_lock (&zs->session_lock);
366     zebra_mutex_cond_unlock (&zs->session_lock);
367 }
368
369 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
370 {
371     ASSERTZS;
372     yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
373     reg->stop_flag = 0;
374     zebra_chdir (zs);
375     if (reg->records)
376     {
377         zebraExplain_close (reg->zei);
378         dict_close (reg->dict);
379         if (reg->matchDict)
380             dict_close (reg->matchDict);
381         sortIdx_close (reg->sortIdx);
382         if (reg->isams)
383             isams_close (reg->isams);
384         if (reg->isam)
385             is_close (reg->isam);
386         if (reg->isamc)
387             isc_close (reg->isamc);
388         if (reg->isamd)
389             isamd_close (reg->isamd);
390         if (reg->isamb)
391             isamb_close (reg->isamb);
392         rec_close (&reg->records);
393     }
394
395     recTypes_destroy (reg->recTypes);
396     zebra_maps_close (reg->zebra_maps);
397     zebraRankDestroy (reg);
398     bfs_destroy (reg->bfs);
399     data1_destroy (reg->dh);
400
401     xfree (reg->key_buf);
402     xfree (reg->name);
403     xfree (reg);
404     yaz_log(LOG_DEBUG, "zebra_register_close 2");
405 }
406
407 void zebra_stop(ZebraService zs)
408 {
409     if (!zs)
410         return ;
411     yaz_log (LOG_LOG, "zebra_stop");
412
413     while (zs->sessions)
414     {
415         zebra_close (zs->sessions);
416     }
417         
418     zebra_mutex_cond_destroy (&zs->session_lock);
419
420     if (zs->passwd_db)
421         passwd_db_close (zs->passwd_db);
422
423     res_close (zs->global_res);
424     xfree (zs->configName);
425     xfree (zs->path_root);
426     xfree (zs);
427 }
428
429 void zebra_close (ZebraHandle zh)
430 {
431     ZebraService zs;
432     struct zebra_session **sp;
433
434     if (!zh)
435         return;
436     ASSERTZH;
437     zh->errCode=0;
438     
439     zs = zh->service;
440     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
441     if (!zh)
442         return ;
443     resultSetDestroy (zh, -1, 0, 0);
444
445
446     if (zh->reg)
447         zebra_register_close (zh->service, zh->reg);
448     zebra_close_res (zh);
449
450     xfree (zh->record_encoding);
451
452     if (zh->iconv_to_utf8 != 0)
453         yaz_iconv_close (zh->iconv_to_utf8);
454     if (zh->iconv_from_utf8 != 0)
455         yaz_iconv_close (zh->iconv_from_utf8);
456
457     xfree (zh->admin_databaseName);
458     zebra_mutex_cond_lock (&zs->session_lock);
459     zebra_lock_destroy (zh->lock_normal);
460     zebra_lock_destroy (zh->lock_shadow);
461     sp = &zs->sessions;
462     while (1)
463     {
464         assert (*sp);
465         if (*sp == zh)
466         {
467             *sp = (*sp)->next;
468             break;
469         }
470         sp = &(*sp)->next;
471     }
472     zebra_mutex_cond_unlock (&zs->session_lock);
473     xfree (zh->reg_name);
474     zh->service=0; /* more likely to trigger an assert */
475     xfree (zh);
476 }
477
478 struct map_baseinfo {
479     ZebraHandle zh;
480     NMEM mem;
481     int num_bases;
482     char **basenames;
483     int new_num_bases;
484     char **new_basenames;
485     int new_num_max;
486 };
487
488 static Res zebra_open_res (ZebraHandle zh)
489 {
490     Res res = 0;
491     char fname[512];
492     ASSERTZH;
493     zh->errCode=0;
494
495     if (zh->path_reg)
496     {
497         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
498         res = res_open (fname, zh->service->global_res);
499         if (!res)
500             res = zh->service->global_res;
501     }
502     else if (*zh->reg_name == 0)
503     {
504         res = zh->service->global_res;
505     }
506     else
507     {
508         yaz_log (LOG_WARN, "no register root specified");
509         return 0;  /* no path for register - fail! */
510     }
511     return res;
512 }
513
514 static void zebra_close_res (ZebraHandle zh)
515 {
516     ASSERTZH;
517     zh->errCode=0;
518     if (zh->res != zh->service->global_res)
519         res_close (zh->res);
520     zh->res = 0;
521 }
522
523 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
524 {
525     ASSERTZH;
526     zh->errCode=0;
527     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
528         return 0;
529     if (!zh->res)
530     {
531         assert (zh->reg == 0);
532         assert (*zh->reg_name == 0);
533     }
534     else
535     {
536         if (zh->reg)
537         {
538             resultSetInvalidate (zh);
539             zebra_register_close (zh->service, zh->reg);
540             zh->reg = 0;
541         }
542         zebra_close_res(zh);
543     }
544     xfree (zh->reg_name);
545     zh->reg_name = xstrdup (new_reg);
546
547     xfree (zh->path_reg);
548     zh->path_reg = 0;
549     if (zh->service->path_root)
550     {
551         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
552                                 strlen(zh->reg_name) + 3);
553         strcpy (zh->path_reg, zh->service->path_root);
554         if (*zh->reg_name)
555         {
556             strcat (zh->path_reg, "/");
557             strcat (zh->path_reg, zh->reg_name);
558         }
559     }
560     zh->res = zebra_open_res (zh);
561     
562     if (zh->lock_normal)
563         zebra_lock_destroy (zh->lock_normal);
564     zh->lock_normal = 0;
565
566     if (zh->lock_shadow)
567         zebra_lock_destroy (zh->lock_shadow);
568     zh->lock_shadow = 0;
569
570     if (zh->res)
571     {
572         char fname[512];
573         const char *lock_area  =res_get (zh->res, "lockDir");
574         
575         if (!lock_area && zh->path_reg)
576             res_put (zh->res, "lockDir", zh->path_reg);
577         sprintf (fname, "norm.%s.LCK", zh->reg_name);
578         zh->lock_normal =
579             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
580         
581         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
582         zh->lock_shadow =
583             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
584
585     }
586     return 1;
587 }
588
589 void map_basenames_func (void *vp, const char *name, const char *value)
590 {
591     struct map_baseinfo *p = (struct map_baseinfo *) vp;
592     int i, no;
593     char fromdb[128], todb[8][128];
594     
595     no =
596         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
597                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
598                 todb[5], todb[6], todb[7]);
599     if (no < 2)
600         return ;
601     no--;
602     for (i = 0; i<p->num_bases; i++)
603         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
604         {
605             p->basenames[i] = 0;
606             for (i = 0; i < no; i++)
607             {
608                 if (p->new_num_bases == p->new_num_max)
609                     return;
610                 p->new_basenames[(p->new_num_bases)++] = 
611                     nmem_strdup (p->mem, todb[i]);
612             }
613             return;
614         }
615 }
616
617 void map_basenames (ZebraHandle zh, ODR stream,
618                     int *num_bases, char ***basenames)
619 {
620     struct map_baseinfo info;
621     struct map_baseinfo *p = &info;
622     int i;
623     ASSERTZH;
624     zh->errCode=0;
625
626     info.zh = zh;
627     info.num_bases = *num_bases;
628     info.basenames = *basenames;
629     info.new_num_max = 128;
630     info.new_num_bases = 0;
631     info.new_basenames = (char **)
632         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
633     info.mem = stream->mem;
634
635     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
636     
637     for (i = 0; i<p->num_bases; i++)
638         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
639         {
640             p->new_basenames[(p->new_num_bases)++] = 
641                 nmem_strdup (p->mem, p->basenames[i]);
642         }
643     *num_bases = info.new_num_bases;
644     *basenames = info.new_basenames;
645     for (i = 0; i<*num_bases; i++)
646         logf (LOG_LOG, "base %s", (*basenames)[i]);
647 }
648
649 int zebra_select_database (ZebraHandle zh, const char *basename)
650 {
651     ASSERTZH;
652     zh->errCode=0;
653     return zebra_select_databases (zh, 1, &basename);
654 }
655
656 int zebra_select_databases (ZebraHandle zh, int num_bases,
657                             const char **basenames)
658 {
659     int i;
660     const char *cp;
661     int len = 0;
662     char *new_reg = 0;
663     ASSERTZH;
664     zh->errCode=0;
665     
666     if (num_bases < 1)
667     {
668         zh->errCode = 23;
669         return -1;
670     }
671     for (i = 0; i < zh->num_basenames; i++)
672         xfree (zh->basenames[i]);
673     xfree (zh->basenames);
674     
675     zh->num_basenames = num_bases;
676     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
677     for (i = 0; i < zh->num_basenames; i++)
678         zh->basenames[i] = xstrdup (basenames[i]);
679
680     cp = strrchr(basenames[0], '/');
681     if (cp)
682     {
683         len = cp - basenames[0];
684         new_reg = xmalloc (len + 1);
685         memcpy (new_reg, basenames[0], len);
686         new_reg[len] = '\0';
687     }
688     else
689         new_reg = xstrdup ("");
690     for (i = 1; i<num_bases; i++)
691     {
692         const char *cp1;
693
694         cp1 = strrchr (basenames[i], '/');
695         if (cp)
696         {
697             if (!cp1)
698             {
699                 zh->errCode = 23;
700                 return -1;
701             }
702             if (len != cp1 - basenames[i] ||
703                 memcmp (basenames[i], new_reg, len))
704             {
705                 zh->errCode = 23;
706                 return -1;
707             }
708         }
709         else
710         {
711             if (cp1)
712             {
713                 zh->errCode = 23;
714                 return -1;
715             }
716         }
717     }
718     zebra_select_register (zh, new_reg);
719     xfree (new_reg);
720     if (!zh->res)
721     {
722         zh->errCode = 109;
723         return -1;
724     }
725     if (!zh->lock_normal || !zh->lock_shadow)
726     {
727         zh->errCode = 2;
728         return -1;
729     }
730     return 0;
731 }
732
733 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
734                        Z_RPNQuery *query, const char *setname, int *hits)
735 {
736     ASSERTZH;
737     zh->errCode=0;
738     zh->hits = 0;
739     *hits = 0;
740
741     if (zebra_begin_read (zh))
742         return;
743     resultSetAddRPN (zh, decode, stream, query, 
744                      zh->num_basenames, zh->basenames, setname);
745
746     zebra_end_read (zh);
747
748     *hits = zh->hits;
749 }
750
751 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
752                              const char *setname, Z_RecordComposition *comp,
753                              oid_value input_format, int num_recs,
754                              ZebraRetrievalRecord *recs)
755 {
756     ZebraPosSet poset;
757     int i, *pos_array;
758     ASSERTZH;
759     zh->errCode=0;
760
761     if (!zh->res)
762     {
763         zh->errCode = 30;
764         zh->errString = odr_strdup (stream, setname);
765         return;
766     }
767     
768     zh->errCode = 0;
769
770     if (zebra_begin_read (zh))
771         return;
772
773     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
774     for (i = 0; i<num_recs; i++)
775         pos_array[i] = recs[i].position;
776     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
777     if (!poset)
778     {
779         logf (LOG_DEBUG, "zebraPosSetCreate error");
780         zh->errCode = 30;
781         zh->errString = nmem_strdup (stream->mem, setname);
782     }
783     else
784     {
785         for (i = 0; i<num_recs; i++)
786         {
787             if (poset[i].term)
788             {
789                 recs[i].errCode = 0;
790                 recs[i].format = VAL_SUTRS;
791                 recs[i].len = strlen(poset[i].term);
792                 recs[i].buf = poset[i].term;
793                 recs[i].base = poset[i].db;
794             }
795             else if (poset[i].sysno)
796             {
797                 recs[i].errCode =
798                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
799                                         stream, input_format, comp,
800                                         &recs[i].format, &recs[i].buf,
801                                         &recs[i].len,
802                                         &recs[i].base);
803                 recs[i].errString = NULL;
804             }
805             else
806             {
807                 char num_str[20];
808
809                 sprintf (num_str, "%d", pos_array[i]);  
810                 zh->errCode = 13;
811                 zh->errString = odr_strdup (stream, num_str);
812                 break;
813             }
814         }
815         zebraPosSetDestroy (zh, poset, num_recs);
816     }
817     zebra_end_read (zh);
818     xfree (pos_array);
819 }
820
821 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
822                  oid_value attributeset,
823                  int *position, int *num_entries, ZebraScanEntry **entries,
824                  int *is_partial)
825 {
826     ASSERTZH;
827     zh->errCode=0;
828     if (zebra_begin_read (zh))
829     {
830         *entries = 0;
831         *num_entries = 0;
832         return;
833     }
834     rpn_scan (zh, stream, zapt, attributeset,
835               zh->num_basenames, zh->basenames, position,
836               num_entries, entries, is_partial);
837     zebra_end_read (zh);
838 }
839
840 void zebra_sort (ZebraHandle zh, ODR stream,
841                  int num_input_setnames, const char **input_setnames,
842                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
843                  int *sort_status)
844 {
845     ASSERTZH;
846     zh->errCode=0;
847     if (zebra_begin_read (zh))
848         return;
849     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
850                    output_setname, sort_sequence, sort_status);
851     zebra_end_read(zh);
852 }
853
854 int zebra_deleleResultSet(ZebraHandle zh, int function,
855                           int num_setnames, char **setnames,
856                           int *statuses)
857 {
858     int i, status;
859     ASSERTZH;
860     zh->errCode=0;
861     if (zebra_begin_read(zh))
862         return Z_DeleteStatus_systemProblemAtTarget;
863     switch (function)
864     {
865     case Z_DeleteRequest_list:
866         resultSetDestroy (zh, num_setnames, setnames, statuses);
867         break;
868     case Z_DeleteRequest_all:
869         resultSetDestroy (zh, -1, 0, statuses);
870         break;
871     }
872     zebra_end_read (zh);
873     status = Z_DeleteStatus_success;
874     for (i = 0; i<num_setnames; i++)
875         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
876             status = statuses[i];
877     return status;
878 }
879
880 int zebra_errCode (ZebraHandle zh)
881 {
882     if (zh)
883         return zh->errCode;
884     return 0; 
885 }
886
887 const char *zebra_errString (ZebraHandle zh)
888 {
889     if (zh)
890         return diagbib1_str (zh->errCode);
891     return "";
892 }
893
894 char *zebra_errAdd (ZebraHandle zh)
895 {
896     if (zh)
897         return zh->errString;
898     return "";
899 }
900
901 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
902 {
903     ZebraService zs;
904     ASSERTZH;
905     zh->errCode=0;
906     zs= zh->service;
907     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
908     {
909         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
910         return 0;
911     }
912
913     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
914     return 1;
915 }
916
917 void zebra_admin_import_begin (ZebraHandle zh, const char *database,
918                                const char *record_type)
919 {
920     ASSERTZH;
921     zh->errCode=0;
922     if (zebra_select_database(zh, database))
923         return;
924     zebra_begin_trans (zh);
925     xfree (zh->admin_databaseName);
926     zh->admin_databaseName = xstrdup(database);
927 }
928
929 void zebra_admin_import_end (ZebraHandle zh)
930 {
931     ASSERTZH;
932     zh->errCode=0;
933     zebra_end_trans (zh);
934 }
935
936 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
937 {
938     int sysno;
939     int i;
940     ASSERTZH;
941     zh->errCode=0;
942     for (i = 0; i<segment->num_segmentRecords; i++)
943     {
944         Z_NamePlusRecord *npr = segment->segmentRecords[i];
945         const char *databaseName = npr->databaseName;
946
947         if (!databaseName)
948             databaseName = zh->admin_databaseName;
949         printf ("--------------%d--------------------\n", i);
950         if (npr->which == Z_NamePlusRecord_intermediateFragment)
951         {
952             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
953             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
954             {
955                 Odr_oct *oct = fragment->u.notExternallyTagged;
956                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
957                         oct->buf);
958                 
959                 sysno = 0;
960                 extract_rec_in_mem (zh, "grs.sgml",
961                                     oct->buf, oct->len,
962                                     databaseName,
963                                     0 /* delete_flag */,
964                                     0 /* test_mode */,
965                                     &sysno /* sysno */,
966                                     1 /* store_keys */,
967                                     1 /* store_data */,
968                                     0 /* match criteria */);
969             }
970         }
971     }
972 }
973
974 int zebra_admin_exchange_record (ZebraHandle zh,
975                                  const char *database,
976                                  const char *rec_buf,
977                                  size_t rec_len,
978                                  const char *recid_buf, size_t recid_len,
979                                  int action)
980 {
981     int sysno = 0;
982     char *rinfo = 0;
983     char recid_z[256];
984     ASSERTZH;
985     zh->errCode=0;
986
987     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
988         return -1;
989     memcpy (recid_z, recid_buf, recid_len);
990     recid_z[recid_len] = 0;
991
992     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
993     if (rinfo)
994     {
995         if (action == 1)  /* fail if insert */
996             return -1;
997         memcpy (&sysno, rinfo+1, sizeof(sysno));
998     }
999     else
1000     {
1001         if (action == 2 || action == 3) /* fail if delete or update */
1002             return -1;
1003     }
1004     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
1005                         action == 3 ? 1 : 0 /* delete flag */,
1006                         0, &sysno, 1, 1, 0);
1007     if (action == 1)
1008     {
1009         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1010     }
1011     else if (action == 3)
1012     {
1013         dict_delete (zh->reg->matchDict, recid_z);
1014     }
1015     return 0;
1016 }
1017
1018 void zebra_admin_create (ZebraHandle zh, const char *database)
1019 {
1020     ZebraService zs;
1021     ASSERTZH;
1022     zh->errCode=0;
1023
1024     if (zebra_select_database (zh, database))
1025         return;
1026     zebra_begin_trans (zh);
1027
1028     zs = zh->service;
1029     /* announce database */
1030     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1031                                   /* explainDatabase */))
1032     {
1033         zh->errCode = 224;
1034         zh->errString = "database already exist";
1035     }
1036     zebra_end_trans (zh);
1037 }
1038
1039 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1040                        const char *input_str, int input_len,
1041                        char *output_str, int output_len)
1042 {
1043     WRBUF wrbuf;
1044     ASSERTZH;
1045     zh->errCode=0;
1046     if (!zh->reg->zebra_maps)
1047         return -1;
1048     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1049                           input_str, input_len);
1050     if (!wrbuf)
1051         return -2;
1052     if (wrbuf_len(wrbuf) >= output_len)
1053         return -3;
1054     if (wrbuf_len(wrbuf))
1055         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1056     output_str[wrbuf_len(wrbuf)] = '\0';
1057     return wrbuf_len(wrbuf);
1058 }
1059
1060
1061 void zebra_set_state (ZebraHandle zh, int val, int seqno)
1062 {
1063     char state_fname[256];
1064     char *fname;
1065     long p = getpid();
1066     FILE *f;
1067     ASSERTZH;
1068     zh->errCode=0;
1069
1070     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1071     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1072     f = fopen (fname, "w");
1073
1074     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1075     fprintf (f, "%c %d %ld\n", val, seqno, p);
1076     fclose (f);
1077     xfree (fname);
1078 }
1079
1080 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1081 {
1082     char state_fname[256];
1083     char *fname;
1084     FILE *f;
1085
1086     ASSERTZH;
1087     zh->errCode=0;
1088     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1089     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1090     f = fopen (fname, "r");
1091     *val = 'o';
1092     *seqno = 0;
1093
1094     if (f)
1095     {
1096         fscanf (f, "%c %d", val, seqno);
1097         fclose (f);
1098     }
1099     xfree (fname);
1100 }
1101
1102 int zebra_begin_read (ZebraHandle zh)
1103 {
1104     int dirty = 0;
1105     char val;
1106     int seqno;
1107     ASSERTZH;
1108
1109     assert (zh->res);
1110
1111     (zh->trans_no)++;
1112
1113     if (zh->trans_no != 1)
1114     {
1115         zebra_flush_reg (zh);
1116         return 0;
1117     }
1118     zh->errCode=0;
1119 #if HAVE_SYS_TIMES_H
1120     times (&zh->tms1);
1121 #endif
1122     if (!zh->res)
1123     {
1124         (zh->trans_no)--;
1125         zh->errCode = 109;
1126         return -1;
1127     }
1128     if (!zh->lock_normal || !zh->lock_shadow)
1129     {
1130         (zh->trans_no)--;
1131         zh->errCode = 2;
1132         return -1;
1133     }
1134     zebra_get_state (zh, &val, &seqno);
1135     if (val == 'd')
1136         val = 'o';
1137
1138     if (!zh->reg)
1139         dirty = 1;
1140     else if (seqno != zh->reg->seqno)
1141     {
1142         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1143                  seqno, zh->reg->seqno);
1144         dirty = 1;
1145     }
1146     else if (zh->reg->last_val != val)
1147     {
1148         yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1149                  val, zh->reg->last_val);
1150         dirty = 1;
1151     }
1152     if (!dirty)
1153         return 0;
1154
1155     if (val == 'c')
1156         zebra_lock_r (zh->lock_shadow);
1157     else
1158         zebra_lock_r (zh->lock_normal);
1159     
1160     if (zh->reg)
1161         zebra_register_close (zh->service, zh->reg);
1162     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1163                                    0, val == 'c' ? 1 : 0,
1164                                    zh->res, zh->path_reg);
1165     if (!zh->reg)
1166     {
1167         zh->errCode = 109;
1168         return -1;
1169     }
1170     zh->reg->last_val = val;
1171     zh->reg->seqno = seqno;
1172
1173     return 0;
1174 }
1175
1176 void zebra_end_read (ZebraHandle zh)
1177 {
1178     ASSERTZH;
1179     (zh->trans_no)--;
1180
1181     if (zh->trans_no != 0)
1182         return;
1183     zh->errCode=0;
1184
1185 #if HAVE_SYS_TIMES_H
1186     times (&zh->tms2);
1187     logf (LOG_LOG, "user/system: %ld/%ld",
1188                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1189                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1190
1191 #endif
1192
1193     zebra_unlock (zh->lock_normal);
1194     zebra_unlock (zh->lock_shadow);
1195 }
1196
1197 void zebra_begin_trans (ZebraHandle zh)
1198 {
1199     int pass;
1200     int seqno = 0;
1201     char val = '?';
1202     const char *rval = 0;
1203     ASSERTZHRES;
1204
1205     assert (zh->res);
1206
1207     (zh->trans_no++);
1208     if (zh->trans_no != 1)
1209     {
1210         return;
1211     }
1212     zh->errCode=0;
1213     
1214     yaz_log (LOG_LOG, "zebra_begin_trans");
1215
1216     zh->records_inserted = 0;
1217     zh->records_updated = 0;
1218     zh->records_deleted = 0;
1219     zh->records_processed = 0;
1220
1221 #if HAVE_SYS_TIMES_H
1222     times (&zh->tms1);
1223 #endif
1224     
1225     /* lock */
1226     if (zh->shadow_enable)
1227         rval = res_get (zh->res, "shadow");
1228
1229     for (pass = 0; pass < 2; pass++)
1230     {
1231         if (rval)
1232         {
1233             zebra_lock_r (zh->lock_normal);
1234             zebra_lock_w (zh->lock_shadow);
1235         }
1236         else
1237         {
1238             zebra_lock_w (zh->lock_normal);
1239             zebra_lock_w (zh->lock_shadow);
1240         }
1241         
1242         zebra_get_state (zh, &val, &seqno);
1243         if (val == 'c')
1244         {
1245             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1246             zebra_unlock (zh->lock_shadow);
1247             zebra_unlock (zh->lock_normal);
1248             zebra_commit (zh);
1249             continue;
1250         }
1251         else if (val == 'd')
1252         {
1253             if (rval)
1254             {
1255                 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1256                                          zh->path_reg);
1257                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1258                 bf_commitClean (bfs, rval);
1259                 bfs_destroy (bfs);
1260             }
1261             else
1262             {
1263                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1264             }
1265         }
1266         break;
1267     }
1268     if (pass == 2)
1269     {
1270         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1271         abort();
1272         return;
1273     }
1274     zebra_set_state (zh, 'd', seqno);
1275
1276     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1277                                    1, rval ? 1 : 0, zh->res,
1278                                    zh->path_reg);
1279
1280     zh->reg->seqno = seqno;
1281 }
1282
1283 void zebra_end_trans (ZebraHandle zh)
1284 {
1285     char val;
1286     int seqno;
1287     const char *rval;
1288     ASSERTZH;
1289
1290     zh->trans_no--;
1291     if (zh->trans_no != 0)
1292         return;
1293     zh->errCode=0;
1294
1295     yaz_log (LOG_LOG, "zebra_end_trans");
1296     rval = res_get (zh->res, "shadow");
1297
1298     zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1299
1300     zebra_flush_reg (zh);
1301
1302     zebra_register_close (zh->service, zh->reg);
1303     zh->reg = 0;
1304
1305     yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1306              zh->records_processed, zh->records_inserted,
1307              zh->records_updated, zh->records_deleted);
1308
1309     zebra_get_state (zh, &val, &seqno);
1310     if (val != 'd')
1311     {
1312         BFiles bfs = bfs_create (rval, zh->path_reg);
1313         yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1314         bf_commitClean (bfs, rval);
1315         bfs_destroy (bfs);
1316     }
1317     if (!rval)
1318         seqno++;
1319     zebra_set_state (zh, 'o', seqno);
1320
1321     zebra_unlock (zh->lock_shadow);
1322     zebra_unlock (zh->lock_normal);
1323
1324 #if HAVE_SYS_TIMES_H
1325     times (&zh->tms2);
1326     logf (LOG_LOG, "user/system: %ld/%ld",
1327                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1328                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1329
1330 #endif
1331 }
1332
1333 void zebra_repository_update (ZebraHandle zh)
1334 {
1335     ASSERTZH;
1336     zh->errCode=0;
1337     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1338     repositoryUpdate (zh);    
1339 }
1340
1341 void zebra_repository_delete (ZebraHandle zh)
1342 {
1343     ASSERTZH;
1344     zh->errCode=0;
1345     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1346     repositoryDelete (zh);
1347 }
1348
1349 void zebra_repository_show (ZebraHandle zh)
1350 {
1351     ASSERTZH;
1352     zh->errCode=0;
1353     repositoryShow (zh);
1354 }
1355
1356 int zebra_commit (ZebraHandle zh)
1357 {
1358     int seqno;
1359     char val;
1360     const char *rval;
1361     BFiles bfs;
1362     ASSERTZH;
1363     zh->errCode=0;
1364
1365     if (!zh->res)
1366     {
1367         zh->errCode = 109;
1368         return -1;
1369     }
1370     rval = res_get (zh->res, "shadow");    
1371     if (!rval)
1372     {
1373         logf (LOG_WARN, "Cannot perform commit");
1374         logf (LOG_WARN, "No shadow area defined");
1375         return 0;
1376     }
1377
1378     zebra_lock_w (zh->lock_normal);
1379     zebra_lock_r (zh->lock_shadow);
1380
1381     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1382
1383     zebra_get_state (zh, &val, &seqno);
1384
1385     if (rval && *rval)
1386         bf_cache (bfs, rval);
1387     if (bf_commitExists (bfs))
1388     {
1389         zebra_set_state (zh, 'c', seqno);
1390
1391         logf (LOG_LOG, "commit start");
1392         bf_commitExec (bfs);
1393 #ifndef WIN32
1394         sync ();
1395 #endif
1396         logf (LOG_LOG, "commit clean");
1397         bf_commitClean (bfs, rval);
1398         seqno++;
1399         zebra_set_state (zh, 'o', seqno);
1400     }
1401     else
1402     {
1403         logf (LOG_LOG, "nothing to commit");
1404     }
1405     bfs_destroy (bfs);
1406
1407     zebra_unlock (zh->lock_shadow);
1408     zebra_unlock (zh->lock_normal);
1409     return 0;
1410 }
1411
1412 int zebra_init (ZebraHandle zh)
1413 {
1414     const char *rval;
1415     BFiles bfs = 0;
1416     ASSERTZH;
1417     zh->errCode=0;
1418
1419     if (!zh->res)
1420     {
1421         zh->errCode = 109;
1422         return -1;
1423     }
1424     rval = res_get (zh->res, "shadow");
1425
1426     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1427                       zh->path_reg);
1428     if (rval && *rval)
1429         bf_cache (bfs, rval);
1430     
1431     bf_reset (bfs);
1432     bfs_destroy (bfs);
1433     zebra_set_state (zh, 'o', 0);
1434     return 0;
1435 }
1436
1437 int zebra_compact (ZebraHandle zh)
1438 {
1439     BFiles bfs;
1440     ASSERTZH;
1441     zh->errCode=0;
1442     if (!zh->res)
1443     {
1444         zh->errCode = 109;
1445         return -1;
1446     }
1447     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1448     inv_compact (bfs);
1449     bfs_destroy (bfs);
1450     return 0;
1451 }
1452
1453 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1454 {
1455     int sysno = 0;
1456     int olderr;
1457     ASSERTZH;
1458     zh->errCode=0;
1459     zebra_begin_trans (zh);
1460     if (zh->errCode)
1461       return 0; /* bad sysno */
1462     extract_rec_in_mem (zh, "grs.sgml",
1463                         buf, len,
1464                         "Default",  /* database */
1465                         0 /* delete_flag */,
1466                         0 /* test_mode */,
1467                         &sysno /* sysno */,
1468                         1 /* store_keys */,
1469                         1 /* store_data */,
1470                         0 /* match criteria */);
1471     olderr=zh->errCode;
1472     zebra_end_trans (zh);
1473     if (olderr)
1474       zh->errCode=olderr; 
1475     return sysno;
1476 }
1477
1478 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1479 {
1480     ASSERTZH;
1481     zh->errCode=0;
1482     memcpy (&zh->rGroup, rg, sizeof(*rg));
1483 }
1484
1485 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1486 {
1487     ASSERTZH;
1488     *code = zh->errCode;
1489     *addinfo = zh->errString;
1490 }
1491
1492 void zebra_shadow_enable (ZebraHandle zh, int value)
1493 {
1494     ASSERTZH;
1495     zh->errCode=0;
1496     zh->shadow_enable = value;
1497 }
1498
1499 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1500 {
1501     ASSERTZH;
1502     zh->errCode=0;
1503     xfree (zh->record_encoding);
1504
1505     /*
1506      * Fixme!
1507      */
1508
1509     if (zh->iconv_to_utf8 != 0)
1510         yaz_iconv_close(zh->iconv_to_utf8);
1511     if (zh->iconv_from_utf8 != 0)
1512         yaz_iconv_close(zh->iconv_from_utf8);
1513     
1514     zh->record_encoding = xstrdup (encoding);
1515     
1516     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1517     
1518     zh->iconv_to_utf8 =
1519         yaz_iconv_open ("UTF-8", encoding);
1520     if (zh->iconv_to_utf8 == 0)
1521         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1522     zh->iconv_from_utf8 =
1523         yaz_iconv_open (encoding, "UTF-8");
1524     if (zh->iconv_to_utf8 == 0)
1525         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1526
1527     return 0;
1528 }
1529
1530 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1531 {
1532     ASSERTZH;
1533     zh->errCode=0;
1534     res_put(zh->res, name, value);
1535 }
1536
1537 const char *zebra_get_resource(ZebraHandle zh,
1538                                 const char *name, const char *defaultvalue)
1539 {
1540     ASSERTZH;
1541     zh->errCode=0;
1542     return res_get_def( zh->res, name, (char *)defaultvalue);
1543 }