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