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