e2ec1b34b3c00f844ba2c24434cb3bb81b27e6a7
[idzebra-moved-to-github.git] / index / zserver.c
1 /* $Id: zserver.c,v 1.135 2005-06-13 10:29:20 adam Exp $
2    Copyright (C) 1995-2005
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 #include <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <fcntl.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #include <sys/locking.h>
31 #else
32 #include <unistd.h>
33 #endif
34
35 #include <errno.h>
36 #include <yaz/log.h>
37 #include <yaz/ill.h>
38 #include <yaz/yaz-util.h>
39 #include <yaz/diagbib1.h>
40
41 #include <sys/types.h>
42
43 #include "zserver.h"
44
45 static int bend_sort (void *handle, bend_sort_rr *rr);
46 static int bend_delete (void *handle, bend_delete_rr *rr);
47 static int bend_esrequest (void *handle, bend_esrequest_rr *rr);
48 static int bend_segment (void *handle, bend_segment_rr *rr);
49 static int bend_search (void *handle, bend_search_rr *r);
50 static int bend_fetch (void *handle, bend_fetch_rr *r);
51 static int bend_scan (void *handle, bend_scan_rr *r);
52
53 bend_initresult *bend_init (bend_initrequest *q)
54 {
55     bend_initresult *r = (bend_initresult *)
56         odr_malloc (q->stream, sizeof(*r));
57     ZebraHandle zh;
58     struct statserv_options_block *sob;
59     char *user = NULL;
60     char *passwd = NULL;
61
62     r->errcode = 0;
63     r->errstring = 0;
64     q->bend_sort = bend_sort;
65     q->bend_delete = bend_delete;
66     q->bend_esrequest = bend_esrequest;
67     q->bend_segment = bend_segment;
68     q->bend_search = bend_search;
69     q->bend_fetch = bend_fetch;
70     q->bend_scan = bend_scan;
71
72     q->implementation_name = "Zebra Information Server";
73     q->implementation_version = "Zebra " ZEBRAVER;
74
75     yaz_log (YLOG_DEBUG, "bend_init");
76
77     sob = statserv_getcontrol ();
78     if (!(zh = zebra_open (sob->handle)))
79     {
80         yaz_log (YLOG_WARN, "Failed to read config `%s'", sob->configname);
81         r->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
82         return r;
83     }
84     r->handle = zh;
85     if (q->auth)
86     {
87         if (q->auth->which == Z_IdAuthentication_open)
88         {
89             char *openpass = xstrdup (q->auth->u.open);
90             char *cp = strchr (openpass, '/');
91             if (cp)
92             {
93                 *cp = '\0';
94                 user = nmem_strdup (odr_getmem (q->stream), openpass);
95                 passwd = nmem_strdup (odr_getmem (q->stream), cp+1);
96             }
97             xfree (openpass);
98         }
99         else if (q->auth->which == Z_IdAuthentication_idPass)
100         {
101             Z_IdPass *idPass = q->auth->u.idPass;
102
103             user = idPass->userId;
104             passwd = idPass->password;
105         }
106     }
107     if (zebra_auth(zh, user, passwd) != ZEBRA_OK)
108     {
109         r->errcode = YAZ_BIB1_INIT_AC_BAD_USERID_AND_OR_PASSWORD;
110         r->errstring = user;
111         return r;
112     }
113     if (q->charneg_request) /* characater set and langauge negotiation? */
114     {
115         char **charsets = 0;
116         int num_charsets;
117         char **langs = 0;
118         int num_langs = 0;
119         int selected = 0;
120         int i;
121         NMEM nmem = nmem_create();
122
123         yaz_log (YLOG_LOG, "character set and language negotiation");
124
125         yaz_get_proposal_charneg (nmem, q->charneg_request,
126                                   &charsets, &num_charsets,
127                                   &langs, &num_langs, &selected);
128         
129         for (i = 0; i < num_charsets; i++)
130         {
131             const char *right_name = "";
132             /*
133              * FIXME! It is like rudiment :-))
134              * We have to support this short names of character sets,
135              * because a lot servers in Russia to use own in during
136              * character set and language negotiation still.
137              */
138             
139             if (!yaz_matchstr(charsets[i], "win")) {
140                 right_name = "WINDOWS-1251";
141             } else if (!yaz_matchstr(charsets[i], "koi")) {
142                 right_name = "KOI8-R";
143             } else if (!yaz_matchstr(charsets[i], "iso")) {
144                 right_name = "ISO-8859-5";
145             } else if (!yaz_matchstr(charsets[i], "dos")) {
146                 right_name = "CP866";
147             } else if (!yaz_matchstr(charsets[i], "uni")) {
148                 right_name = "UTF-8";
149             } else {
150                 right_name = charsets[i];
151             }
152             if (odr_set_charset (q->decode, "UTF-8", right_name) == 0)
153             {
154                 yaz_log (YLOG_LOG, "charset %d %s (proper name %s): OK", i,
155                          charsets[i], right_name);
156                 odr_set_charset (q->stream, right_name, "UTF-8");
157                 if (selected)
158                     zebra_record_encoding(zh, right_name);
159                 zebra_octet_term_encoding(zh, right_name);
160                 q->charneg_response =
161                     yaz_set_response_charneg (q->stream, charsets[i],
162                                               0, selected);
163                 break;
164             } else {
165                 yaz_log (YLOG_LOG, "charset %d %s (proper name %s): unsupported", i,
166                          charsets[i], right_name);
167             }
168         }
169         nmem_destroy(nmem);
170     }
171     return r;
172 }
173
174 static void search_terms(ZebraHandle zh, bend_search_rr *r)
175 {
176     int no_terms;
177     int i;
178     int type = Z_Term_general;
179     struct Z_External *ext;
180     Z_SearchInfoReport *sr;
181
182     zebra_result_set_term_no(zh, r->setname, &no_terms);
183     if (!no_terms)
184         return;
185
186     r->search_info = odr_malloc (r->stream, sizeof(*r->search_info));
187
188     r->search_info->num_elements = 1;
189     r->search_info->list =
190         odr_malloc (r->stream, sizeof(*r->search_info->list));
191     r->search_info->list[0] =
192         odr_malloc (r->stream, sizeof(**r->search_info->list));
193     r->search_info->list[0]->category = 0;
194     r->search_info->list[0]->which = Z_OtherInfo_externallyDefinedInfo;
195     ext = odr_malloc (r->stream, sizeof(*ext));
196     r->search_info->list[0]->information.externallyDefinedInfo = ext;
197     ext->direct_reference =
198         yaz_oidval_to_z3950oid (r->stream, CLASS_USERINFO, VAL_SEARCHRES1);
199     ext->indirect_reference = 0;
200     ext->descriptor = 0;
201     ext->which = Z_External_searchResult1;
202     sr = odr_malloc (r->stream, sizeof(Z_SearchInfoReport));
203     ext->u.searchResult1 = sr;
204     sr->num = no_terms;
205     sr->elements = odr_malloc (r->stream, sr->num *
206                                sizeof(*sr->elements));
207     for (i = 0; i<no_terms; i++)
208     {
209         Z_Term *term;
210         zint count;
211         int approx;
212         char outbuf[1024];
213         size_t len = sizeof(outbuf);
214
215         zebra_result_set_term_info(zh, r->setname, i,
216                                    &count, &approx, outbuf, &len);
217
218         sr->elements[i] = odr_malloc (r->stream, sizeof(**sr->elements));
219         sr->elements[i]->subqueryId = 0;
220         sr->elements[i]->fullQuery = odr_malloc (r->stream, 
221                                                  sizeof(bool_t));
222         *sr->elements[i]->fullQuery = 0;
223         sr->elements[i]->subqueryExpression = 
224             odr_malloc (r->stream, sizeof(Z_QueryExpression));
225         sr->elements[i]->subqueryExpression->which = 
226             Z_QueryExpression_term;
227         sr->elements[i]->subqueryExpression->u.term =
228             odr_malloc (r->stream, sizeof(Z_QueryExpressionTerm));
229         term = odr_malloc (r->stream, sizeof(Z_Term));
230         sr->elements[i]->subqueryExpression->u.term->queryTerm = term;
231         switch (type)
232         {
233         case Z_Term_characterString:
234             yaz_log (YLOG_DEBUG, "term as characterString");
235             term->which = Z_Term_characterString;
236             term->u.characterString = odr_strdup (r->stream, outbuf);
237             break;
238         case Z_Term_general:
239             yaz_log (YLOG_DEBUG, "term as general");
240             term->which = Z_Term_general;
241             term->u.general = odr_malloc (r->stream, sizeof(*term->u.general));
242             term->u.general->size = term->u.general->len = len;
243             term->u.general->buf = odr_malloc (r->stream, len);
244             memcpy (term->u.general->buf, outbuf, len);
245             break;
246         default:
247             term->which = Z_Term_general;
248             term->u.null = odr_nullval();
249         }
250         sr->elements[i]->subqueryExpression->u.term->termComment = 0;
251         sr->elements[i]->subqueryInterpretation = 0;
252         sr->elements[i]->subqueryRecommendation = 0;
253         if (count > 2000000000)
254             count = 2000000000;
255         sr->elements[i]->subqueryCount = odr_intdup (r->stream, (int) count);
256         sr->elements[i]->subqueryWeight = 0;
257         sr->elements[i]->resultsByDB = 0;
258     }
259 }
260
261 int bend_search (void *handle, bend_search_rr *r)
262 {
263     ZebraHandle zh = (ZebraHandle) handle;
264     zint zhits = 0;
265     ZEBRA_RES res;
266
267     res = zebra_select_databases (zh, r->num_bases,
268                                   (const char **) r->basenames);
269     if (res != ZEBRA_OK)
270     {
271         zebra_result (zh, &r->errcode, &r->errstring);
272         return 0;
273     }
274     yaz_log (YLOG_DEBUG, "ResultSet '%s'", r->setname);
275     switch (r->query->which)
276     {
277     case Z_Query_type_1: case Z_Query_type_101:
278         res = zebra_search_RPN(zh, r->stream, r->query->u.type_1,
279                                r->setname, &zhits);
280         if (res != ZEBRA_OK)
281             zebra_result(zh, &r->errcode, &r->errstring);
282         else
283         {
284             if (zhits >   2147483646)
285                 r->hits = 2147483647;
286             else
287             r->hits = (int) zhits;
288             search_terms (zh, r);
289         }
290         break;
291     case Z_Query_type_2:
292         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
293         r->errstring = "type-2";
294         break;
295     default:
296         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
297     }
298     return 0;
299 }
300
301
302 int bend_fetch (void *handle, bend_fetch_rr *r)
303 {
304     ZebraHandle zh = (ZebraHandle) handle;
305     ZebraRetrievalRecord retrievalRecord;
306     ZEBRA_RES res;
307
308     retrievalRecord.position = r->number;
309     
310     r->last_in_set = 0;
311     res = zebra_records_retrieve (zh, r->stream, r->setname, r->comp,
312                                   r->request_format, 1, &retrievalRecord);
313     if (res != ZEBRA_OK)
314     {
315         /* non-surrogate diagnostic */
316         zebra_result (zh, &r->errcode, &r->errstring);
317     }
318     else if (retrievalRecord.errCode)
319     {
320         /* surrogate diagnostic (diagnostic per record) */
321         r->surrogate_flag = 1;
322         r->errcode = retrievalRecord.errCode;
323         r->errstring = retrievalRecord.errString;
324         r->basename = retrievalRecord.base;
325     }
326     else
327     {
328         r->basename = retrievalRecord.base;
329         r->record = retrievalRecord.buf;
330         r->len = retrievalRecord.len;
331         r->output_format = retrievalRecord.format;
332     }
333     return 0;
334 }
335
336 static int bend_scan (void *handle, bend_scan_rr *r)
337 {
338     ZebraScanEntry *entries;
339     ZebraHandle zh = (ZebraHandle) handle;
340     int is_partial, i;
341     ZEBRA_RES res;
342
343     res = zebra_select_databases(zh, r->num_bases, 
344                                  (const char **) r->basenames);
345     if (res != ZEBRA_OK)
346     {
347         zebra_result (zh, &r->errcode, &r->errstring);
348         return 0;
349     }
350     if (r->step_size != 0 && *r->step_size != 0) {
351         r->errcode = YAZ_BIB1_ONLY_ZERO_STEP_SIZE_SUPPORTED_FOR_SCAN;
352         r->errstring = 0;
353         return 0;
354     }
355     r->entries = (struct scan_entry *)
356         odr_malloc (r->stream, sizeof(*r->entries) * r->num_entries);
357     res = zebra_scan(zh, r->stream, r->term,
358                      r->attributeset,
359                      &r->term_position,
360                      &r->num_entries, &entries, &is_partial);
361     if (res == ZEBRA_OK)
362     {
363         if (is_partial)
364             r->status = BEND_SCAN_PARTIAL;
365         else
366             r->status = BEND_SCAN_SUCCESS;
367         for (i = 0; i < r->num_entries; i++)
368         {
369             r->entries[i].term = entries[i].term;
370             r->entries[i].occurrences = entries[i].occurrences;
371         }
372     }
373     else
374     {
375         r->status = BEND_SCAN_PARTIAL;
376         zebra_result(zh, &r->errcode, &r->errstring);
377     }
378     return 0;
379 }
380
381 void bend_close (void *handle)
382 {
383     zebra_close ((ZebraHandle) handle);
384     xmalloc_trav("bend_close");
385     nmem_print_list();
386 }
387
388 int bend_sort (void *handle, bend_sort_rr *rr)
389 {
390     ZebraHandle zh = (ZebraHandle) handle;
391
392     zebra_sort (zh, rr->stream,
393                 rr->num_input_setnames, (const char **) rr->input_setnames,
394                 rr->output_setname, rr->sort_sequence, &rr->sort_status);
395     zebra_result (zh, &rr->errcode, &rr->errstring);
396     return 0;
397 }
398
399 int bend_delete (void *handle, bend_delete_rr *rr)
400 {
401     ZebraHandle zh = (ZebraHandle) handle;
402
403     rr->delete_status = zebra_deleteResultSet(zh, rr->function,
404                                               rr->num_setnames, rr->setnames,
405                                               rr->statuses);
406     return 0;
407 }
408
409 static int es_admin_request (ZebraHandle zh, Z_AdminEsRequest *r)
410 {
411     if (r->toKeep->databaseName)
412     {
413         yaz_log(YLOG_LOG, "adm request database %s", r->toKeep->databaseName);
414     }
415     switch (r->toKeep->which)
416     {
417     case Z_ESAdminOriginPartToKeep_reIndex:
418         yaz_log(YLOG_LOG, "adm-reindex");
419         break;
420     case Z_ESAdminOriginPartToKeep_truncate:
421         yaz_log(YLOG_LOG, "adm-truncate");
422         break;
423     case Z_ESAdminOriginPartToKeep_drop:
424         yaz_log(YLOG_LOG, "adm-drop");
425         zebra_drop_database (zh, r->toKeep->databaseName);
426         break;
427     case Z_ESAdminOriginPartToKeep_create:
428         yaz_log(YLOG_LOG, "adm-create %s", r->toKeep->databaseName);
429         zebra_create_database (zh, r->toKeep->databaseName);
430         break;
431     case Z_ESAdminOriginPartToKeep_import:
432         yaz_log(YLOG_LOG, "adm-import");
433         zebra_admin_import_begin (zh, r->toKeep->databaseName,
434                         r->toKeep->u.import->recordType);
435         break;
436     case Z_ESAdminOriginPartToKeep_refresh:
437         yaz_log(YLOG_LOG, "adm-refresh");
438         break;
439     case Z_ESAdminOriginPartToKeep_commit:
440         yaz_log(YLOG_LOG, "adm-commit");
441         if (r->toKeep->databaseName)
442             zebra_select_database(zh, r->toKeep->databaseName);
443         zebra_commit(zh);
444         break;
445     case Z_ESAdminOriginPartToKeep_shutdown:
446         yaz_log(YLOG_LOG, "shutdown");
447         zebra_admin_shutdown(zh);
448         break;
449     case Z_ESAdminOriginPartToKeep_start:
450         yaz_log(YLOG_LOG, "start");
451         zebra_admin_start(zh);
452         break;
453     default:
454         yaz_log(YLOG_LOG, "unknown admin");
455     }
456     return 0;
457 }
458
459 static int es_admin (ZebraHandle zh, Z_Admin *r)
460 {
461     switch (r->which)
462     {
463     case Z_Admin_esRequest:
464         es_admin_request (zh, r->u.esRequest);
465         break;
466     case Z_Admin_taskPackage:
467         yaz_log (YLOG_LOG, "adm taskpackage (unhandled)");
468         break;
469     default:
470         break;
471     }
472     return 0;
473 }
474
475 int bend_segment (void *handle, bend_segment_rr *rr)
476 {
477     ZebraHandle zh = (ZebraHandle) handle;
478     Z_Segment *segment = rr->segment;
479
480     if (segment->num_segmentRecords)
481         zebra_admin_import_segment (zh, rr->segment);
482     else
483         zebra_admin_import_end (zh);
484     return 0;
485 }
486
487 int bend_esrequest (void *handle, bend_esrequest_rr *rr)
488 {
489     ZebraHandle zh = (ZebraHandle) handle;
490     
491     yaz_log(YLOG_LOG, "function: %d", *rr->esr->function);
492     if (rr->esr->packageName)
493         yaz_log(YLOG_LOG, "packagename: %s", rr->esr->packageName);
494     yaz_log(YLOG_LOG, "Waitaction: %d", *rr->esr->waitAction);
495
496     if (!rr->esr->taskSpecificParameters)
497     {
498         yaz_log (YLOG_WARN, "No task specific parameters");
499     }
500     else if (rr->esr->taskSpecificParameters->which == Z_External_ESAdmin)
501     {
502         es_admin (zh, rr->esr->taskSpecificParameters->u.adminService);
503
504         zebra_result (zh, &rr->errcode, &rr->errstring);
505     }
506     else if (rr->esr->taskSpecificParameters->which == Z_External_update)
507     {
508         Z_IUUpdate *up = rr->esr->taskSpecificParameters->u.update;
509         yaz_log (YLOG_LOG, "Received DB Update");
510         if (up->which == Z_IUUpdate_esRequest)
511         {
512             Z_IUUpdateEsRequest *esRequest = up->u.esRequest;
513             Z_IUOriginPartToKeep *toKeep = esRequest->toKeep;
514             Z_IUSuppliedRecords *notToKeep = esRequest->notToKeep;
515             
516             yaz_log (YLOG_LOG, "action");
517             if (toKeep->action)
518             {
519                 switch (*toKeep->action)
520                 {
521                 case Z_IUOriginPartToKeep_recordInsert:
522                     yaz_log (YLOG_LOG, "recordInsert");
523                     break;
524                 case Z_IUOriginPartToKeep_recordReplace:
525                     yaz_log (YLOG_LOG, "recordUpdate");
526                     break;
527                 case Z_IUOriginPartToKeep_recordDelete:
528                     yaz_log (YLOG_LOG, "recordDelete");
529                     break;
530                 case Z_IUOriginPartToKeep_elementUpdate:
531                     yaz_log (YLOG_LOG, "elementUpdate");
532                     break;
533                 case Z_IUOriginPartToKeep_specialUpdate:
534                     yaz_log (YLOG_LOG, "specialUpdate");
535                     break;
536                 case Z_ESAdminOriginPartToKeep_shutdown:
537                     yaz_log (YLOG_LOG, "shutDown");
538                     break;
539                 case Z_ESAdminOriginPartToKeep_start:
540                     yaz_log (YLOG_LOG, "start");
541                     break;
542                 default:
543                     yaz_log (YLOG_LOG, " unknown (%d)", *toKeep->action);
544                 }
545             }
546             if (toKeep->databaseName)
547             {
548                 yaz_log (YLOG_LOG, "database: %s", toKeep->databaseName);
549
550                 if (zebra_select_database(zh, toKeep->databaseName))
551                     return 0;
552             }
553             else
554             {
555                 yaz_log (YLOG_WARN, "no database supplied for ES Update");
556                 rr->errcode =
557                     YAZ_BIB1_ES_MISSING_MANDATORY_PARAMETER_FOR_SPECIFIED_FUNCTION_;
558                 rr->errstring = "database";
559                 return 0;
560             }
561             if (zebra_begin_trans(zh, 1) != ZEBRA_OK)
562             {
563                 zebra_result(zh, &rr->errcode, &rr->errstring);
564             }
565             else
566             {
567                 int i;
568                 for (i = 0; notToKeep && i < notToKeep->num; i++)
569                 {
570                     Z_External *rec = notToKeep->elements[i]->record;
571                     struct oident *oident = 0;
572                     Odr_oct *opaque_recid = 0;
573                     SYSNO sysno = 0;
574
575                     if (notToKeep->elements[i]->u.opaque)
576                     {
577                         switch(notToKeep->elements[i]->which)
578                         {
579                         case Z_IUSuppliedRecords_elem_opaque:
580                             opaque_recid = notToKeep->elements[i]->u.opaque;
581                             break; /* OK, recid already set */
582                         case Z_IUSuppliedRecords_elem_number:
583                             sysno = *notToKeep->elements[i]->u.number;
584                             break;
585                         }
586                     }
587                     if (rec->direct_reference)
588                     {
589                         oident = oid_getentbyoid(rec->direct_reference);
590                         if (oident)
591                             yaz_log (YLOG_LOG, "record %d type %s", i,
592                                      oident->desc);
593                     }
594                     switch (rec->which)
595                     {
596                     case Z_External_sutrs:
597                         if (rec->u.octet_aligned->len > 170)
598                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
599                                      rec->u.sutrs->len,
600                                      rec->u.sutrs->buf);
601                         else
602                             yaz_log (YLOG_LOG, "%d bytes:\n%s",
603                                      rec->u.sutrs->len,
604                                      rec->u.sutrs->buf);
605                         break;
606                     case Z_External_octet:
607                         if (rec->u.octet_aligned->len > 170)
608                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
609                                      rec->u.octet_aligned->len,
610                                      rec->u.octet_aligned->buf);
611                         else
612                             yaz_log (YLOG_LOG, "%d bytes\n%s",
613                                      rec->u.octet_aligned->len,
614                                      rec->u.octet_aligned->buf);
615                     }
616                     if (oident && oident->value != VAL_TEXT_XML)
617                     {
618                         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
619                         rr->errstring = "only XML update supported";
620                         break;
621                     }
622                     if (rec->which == Z_External_octet)
623                     {
624                         int action = 0;
625
626                         if (*toKeep->action ==
627                             Z_IUOriginPartToKeep_recordInsert)
628                             action = 1;
629                         if (*toKeep->action ==
630                             Z_IUOriginPartToKeep_recordReplace)
631                             action = 2;
632                         if (*toKeep->action ==
633                             Z_IUOriginPartToKeep_recordDelete)
634                             action = 3;
635                         if (*toKeep->action ==
636                             Z_IUOriginPartToKeep_specialUpdate)
637                             action = 4;
638
639                         if (!action)
640                         {
641                             rr->errcode =
642                                 YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
643                             rr->errstring = "unsupported ES Update action";
644                             break;
645                         }
646                         else if (opaque_recid)
647                         {
648                             int r = zebra_admin_exchange_record (
649                                 zh,
650                                 rec->u.octet_aligned->buf,
651                                 rec->u.octet_aligned->len,
652                                 opaque_recid->buf, opaque_recid->len,
653                                 action);
654                             if (r)
655                             {
656                                 rr->errcode =
657                                     YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
658                                 rr->errstring = "record exchange failed";
659                                 break;
660                             }
661                         }
662                         else
663                         {
664                             ZEBRA_RES r = ZEBRA_FAIL;
665                             switch(action) {
666                             case 1:
667                                 r = zebra_insert_record(
668                                     zh,
669                                     0, /* recordType */
670                                     &sysno,
671                                     0, /* match */
672                                     0, /* fname */
673                                     rec->u.octet_aligned->buf,
674                                     rec->u.octet_aligned->len,
675                                     0);
676                                 if (r == ZEBRA_FAIL)
677                                 {
678                                     rr->errcode =
679                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
680                                     rr->errstring = "insert_record failed";
681                                 }
682                                 break;
683                             case 2:
684                             case 4:
685                                 r = zebra_update_record(
686                                     zh,
687                                     0, /* recordType */
688                                     &sysno,
689                                     0, /* match */
690                                     0, /* fname */
691                                     rec->u.octet_aligned->buf,
692                                     rec->u.octet_aligned->len,
693                                     1);
694                                 if (r == ZEBRA_FAIL)
695                                 {
696                                     rr->errcode =
697                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
698                                     rr->errstring = "update_record failed";
699                                 }
700                                 break;
701                             case 3:
702                                 r = zebra_delete_record(
703                                     zh,
704                                     0, /* recordType */
705                                     &sysno,
706                                     0, /* match */
707                                     0, /* fname */
708                                     rec->u.octet_aligned->buf,
709                                     rec->u.octet_aligned->len,
710                                     0);
711                                 if (r == ZEBRA_FAIL)
712                                 {
713                                     rr->errcode =
714                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
715                                     rr->errstring = "delete_record failed";
716                                 }
717                                 break;
718                             }                           
719                         }
720                     }
721                 }
722                 zebra_end_trans (zh);
723             }
724         }
725     }
726     else
727     {
728         yaz_log (YLOG_WARN, "Unknown Extended Service(%d)",
729                  rr->esr->taskSpecificParameters->which);
730         rr->errcode = YAZ_BIB1_ES_EXTENDED_SERVICE_TYPE_UNSUPP;
731         
732     }
733     return 0;
734 }
735
736 static void bend_start (struct statserv_options_block *sob)
737 {
738     if (sob->handle)
739         zebra_stop((ZebraService) sob->handle);
740     sob->handle = zebra_start(sob->configname);
741     if (!sob->handle)
742     {
743         yaz_log (YLOG_FATAL, "Failed to read config `%s'", sob->configname);
744         exit (1);
745     }
746 #ifdef WIN32
747     
748 #else
749     if (!sob->inetd) 
750     {
751         char pidfname[4096];
752         struct flock area;
753         int fd;
754
755         zebra_pidfname(sob->handle, pidfname);
756
757         fd = open (pidfname, O_EXCL|O_WRONLY|O_CREAT, 0666);
758         if (fd == -1)
759         {
760             if (errno != EEXIST)
761             {
762                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
763                 exit(1);
764             }
765             fd = open(pidfname, O_RDWR, 0666);
766             if (fd == -1)
767             {
768                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
769                 exit(1);
770             }
771         }
772         area.l_type = F_WRLCK;
773         area.l_whence = SEEK_SET;
774         area.l_len = area.l_start = 0L;
775         if (fcntl (fd, F_SETLK, &area) == -1)
776         {
777             yaz_log(YLOG_ERRNO|YLOG_FATAL, "Zebra server already running");
778             exit(1);
779         }
780         else
781         {
782             char pidstr[30];
783         
784             sprintf (pidstr, "%ld", (long) getpid ());
785             write (fd, pidstr, strlen(pidstr));
786         }
787     }
788 #endif
789 }
790
791 static void bend_stop(struct statserv_options_block *sob)
792 {
793 #ifdef WIN32
794
795 #else
796     if (!sob->inetd && sob->handle) 
797     {
798         char pidfname[4096];
799         zebra_pidfname(sob->handle, pidfname);
800         unlink (pidfname);
801     }
802 #endif
803     if (sob->handle)
804     {
805         ZebraService service = sob->handle;
806         zebra_stop(service);
807     }
808 }
809
810 int main (int argc, char **argv)
811 {
812     struct statserv_options_block *sob;
813
814     sob = statserv_getcontrol ();
815     strcpy (sob->configname, "zebra.cfg");
816     sob->bend_start = bend_start;
817     sob->bend_stop = bend_stop;
818 #ifdef WIN32
819     strcpy (sob->service_display_name, "Zebra Server");
820 #endif
821     statserv_setcontrol (sob);
822
823     return statserv_main (argc, argv, bend_init, bend_close);
824 }