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