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