Added type signed/unsigned char type casts to make GCC 4 happy.
[idzebra-moved-to-github.git] / index / zserver.c
1 /* $Id: zserver.c,v 1.139 2005-08-22 09:04:18 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                                    0 /* term_ref_id */ );
219
220         sr->elements[i] = odr_malloc (r->stream, sizeof(**sr->elements));
221         sr->elements[i]->subqueryId = 0;
222         sr->elements[i]->fullQuery = odr_malloc (r->stream, 
223                                                  sizeof(bool_t));
224         *sr->elements[i]->fullQuery = 0;
225         sr->elements[i]->subqueryExpression = 
226             odr_malloc (r->stream, sizeof(Z_QueryExpression));
227         sr->elements[i]->subqueryExpression->which = 
228             Z_QueryExpression_term;
229         sr->elements[i]->subqueryExpression->u.term =
230             odr_malloc (r->stream, sizeof(Z_QueryExpressionTerm));
231         term = odr_malloc (r->stream, sizeof(Z_Term));
232         sr->elements[i]->subqueryExpression->u.term->queryTerm = term;
233         switch (type)
234         {
235         case Z_Term_characterString:
236             yaz_log (YLOG_DEBUG, "term as characterString");
237             term->which = Z_Term_characterString;
238             term->u.characterString = odr_strdup (r->stream, outbuf);
239             break;
240         case Z_Term_general:
241             yaz_log (YLOG_DEBUG, "term as general");
242             term->which = Z_Term_general;
243             term->u.general = odr_malloc (r->stream, sizeof(*term->u.general));
244             term->u.general->size = term->u.general->len = len;
245             term->u.general->buf = odr_malloc (r->stream, len);
246             memcpy (term->u.general->buf, outbuf, len);
247             break;
248         default:
249             term->which = Z_Term_general;
250             term->u.null = odr_nullval();
251         }
252         sr->elements[i]->subqueryExpression->u.term->termComment = 0;
253         sr->elements[i]->subqueryInterpretation = 0;
254         sr->elements[i]->subqueryRecommendation = 0;
255         if (count > 2000000000)
256             count = 2000000000;
257         sr->elements[i]->subqueryCount = odr_intdup (r->stream, (int) count);
258         sr->elements[i]->subqueryWeight = 0;
259         sr->elements[i]->resultsByDB = 0;
260     }
261 }
262
263 int bend_search (void *handle, bend_search_rr *r)
264 {
265     ZebraHandle zh = (ZebraHandle) handle;
266     zint zhits = 0;
267     ZEBRA_RES res;
268
269     res = zebra_select_databases (zh, r->num_bases,
270                                   (const char **) r->basenames);
271     if (res != ZEBRA_OK)
272     {
273         zebra_result (zh, &r->errcode, &r->errstring);
274         return 0;
275     }
276     yaz_log (YLOG_DEBUG, "ResultSet '%s'", r->setname);
277     switch (r->query->which)
278     {
279     case Z_Query_type_1: case Z_Query_type_101:
280         res = zebra_search_RPN(zh, r->stream, r->query->u.type_1,
281                                r->setname, &zhits);
282         if (res != ZEBRA_OK)
283             zebra_result(zh, &r->errcode, &r->errstring);
284         else
285         {
286             if (zhits >   2147483646)
287                 r->hits = 2147483647;
288             else
289             r->hits = (int) zhits;
290             search_terms (zh, r);
291         }
292         break;
293     case Z_Query_type_2:
294         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
295         r->errstring = "type-2";
296         break;
297     default:
298         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
299     }
300     return 0;
301 }
302
303
304 int bend_fetch (void *handle, bend_fetch_rr *r)
305 {
306     ZebraHandle zh = (ZebraHandle) handle;
307     ZebraRetrievalRecord retrievalRecord;
308     ZEBRA_RES res;
309
310     retrievalRecord.position = r->number;
311     
312     r->last_in_set = 0;
313     res = zebra_records_retrieve (zh, r->stream, r->setname, r->comp,
314                                   r->request_format, 1, &retrievalRecord);
315     if (res != ZEBRA_OK)
316     {
317         /* non-surrogate diagnostic */
318         zebra_result (zh, &r->errcode, &r->errstring);
319     }
320     else if (retrievalRecord.errCode)
321     {
322         /* surrogate diagnostic (diagnostic per record) */
323         r->surrogate_flag = 1;
324         r->errcode = retrievalRecord.errCode;
325         r->errstring = retrievalRecord.errString;
326         r->basename = retrievalRecord.base;
327     }
328     else
329     {
330         r->basename = retrievalRecord.base;
331         r->record = retrievalRecord.buf;
332         r->len = retrievalRecord.len;
333         r->output_format = retrievalRecord.format;
334     }
335     return 0;
336 }
337
338 static int bend_scan (void *handle, bend_scan_rr *r)
339 {
340     ZebraScanEntry *entries;
341     ZebraHandle zh = (ZebraHandle) handle;
342     int is_partial, i;
343     ZEBRA_RES res;
344
345     res = zebra_select_databases(zh, r->num_bases, 
346                                  (const char **) r->basenames);
347     if (res != ZEBRA_OK)
348     {
349         zebra_result (zh, &r->errcode, &r->errstring);
350         return 0;
351     }
352     if (r->step_size != 0 && *r->step_size != 0) {
353         r->errcode = YAZ_BIB1_ONLY_ZERO_STEP_SIZE_SUPPORTED_FOR_SCAN;
354         r->errstring = 0;
355         return 0;
356     }
357     r->entries = (struct scan_entry *)
358         odr_malloc (r->stream, sizeof(*r->entries) * r->num_entries);
359     res = zebra_scan(zh, r->stream, r->term,
360                      r->attributeset,
361                      &r->term_position,
362                      &r->num_entries, &entries, &is_partial, 
363                      0 /* setname */);
364     if (res == ZEBRA_OK)
365     {
366         if (is_partial)
367             r->status = BEND_SCAN_PARTIAL;
368         else
369             r->status = BEND_SCAN_SUCCESS;
370         for (i = 0; i < r->num_entries; i++)
371         {
372             r->entries[i].term = entries[i].term;
373             r->entries[i].occurrences = entries[i].occurrences;
374         }
375     }
376     else
377     {
378         r->status = BEND_SCAN_PARTIAL;
379         zebra_result(zh, &r->errcode, &r->errstring);
380     }
381     return 0;
382 }
383
384 void bend_close (void *handle)
385 {
386     zebra_close ((ZebraHandle) handle);
387     xmalloc_trav("bend_close");
388     nmem_print_list();
389 }
390
391 int bend_sort (void *handle, bend_sort_rr *rr)
392 {
393     ZebraHandle zh = (ZebraHandle) handle;
394
395     zebra_sort (zh, rr->stream,
396                 rr->num_input_setnames, (const char **) rr->input_setnames,
397                 rr->output_setname, rr->sort_sequence, &rr->sort_status);
398     zebra_result (zh, &rr->errcode, &rr->errstring);
399     return 0;
400 }
401
402 int bend_delete (void *handle, bend_delete_rr *rr)
403 {
404     ZebraHandle zh = (ZebraHandle) handle;
405
406     rr->delete_status = zebra_deleteResultSet(zh, rr->function,
407                                               rr->num_setnames, rr->setnames,
408                                               rr->statuses);
409     return 0;
410 }
411
412 static int es_admin_request (ZebraHandle zh, Z_AdminEsRequest *r)
413 {
414     if (r->toKeep->databaseName)
415     {
416         yaz_log(YLOG_LOG, "adm request database %s", r->toKeep->databaseName);
417     }
418     switch (r->toKeep->which)
419     {
420     case Z_ESAdminOriginPartToKeep_reIndex:
421         yaz_log(YLOG_LOG, "adm-reindex");
422         break;
423     case Z_ESAdminOriginPartToKeep_truncate:
424         yaz_log(YLOG_LOG, "adm-truncate");
425         break;
426     case Z_ESAdminOriginPartToKeep_drop:
427         yaz_log(YLOG_LOG, "adm-drop");
428         zebra_drop_database (zh, r->toKeep->databaseName);
429         break;
430     case Z_ESAdminOriginPartToKeep_create:
431         yaz_log(YLOG_LOG, "adm-create %s", r->toKeep->databaseName);
432         zebra_create_database (zh, r->toKeep->databaseName);
433         break;
434     case Z_ESAdminOriginPartToKeep_import:
435         yaz_log(YLOG_LOG, "adm-import");
436         zebra_admin_import_begin (zh, r->toKeep->databaseName,
437                         r->toKeep->u.import->recordType);
438         break;
439     case Z_ESAdminOriginPartToKeep_refresh:
440         yaz_log(YLOG_LOG, "adm-refresh");
441         break;
442     case Z_ESAdminOriginPartToKeep_commit:
443         yaz_log(YLOG_LOG, "adm-commit");
444         if (r->toKeep->databaseName)
445             zebra_select_database(zh, r->toKeep->databaseName);
446         zebra_commit(zh);
447         break;
448     case Z_ESAdminOriginPartToKeep_shutdown:
449         yaz_log(YLOG_LOG, "shutdown");
450         zebra_admin_shutdown(zh);
451         break;
452     case Z_ESAdminOriginPartToKeep_start:
453         yaz_log(YLOG_LOG, "start");
454         zebra_admin_start(zh);
455         break;
456     default:
457         yaz_log(YLOG_LOG, "unknown admin");
458     }
459     return 0;
460 }
461
462 static int es_admin (ZebraHandle zh, Z_Admin *r)
463 {
464     switch (r->which)
465     {
466     case Z_Admin_esRequest:
467         es_admin_request (zh, r->u.esRequest);
468         break;
469     case Z_Admin_taskPackage:
470         yaz_log (YLOG_LOG, "adm taskpackage (unhandled)");
471         break;
472     default:
473         break;
474     }
475     return 0;
476 }
477
478 int bend_segment (void *handle, bend_segment_rr *rr)
479 {
480     ZebraHandle zh = (ZebraHandle) handle;
481     Z_Segment *segment = rr->segment;
482
483     if (segment->num_segmentRecords)
484         zebra_admin_import_segment (zh, rr->segment);
485     else
486         zebra_admin_import_end (zh);
487     return 0;
488 }
489
490 int bend_esrequest (void *handle, bend_esrequest_rr *rr)
491 {
492     ZebraHandle zh = (ZebraHandle) handle;
493     
494     yaz_log(YLOG_LOG, "function: %d", *rr->esr->function);
495     if (rr->esr->packageName)
496         yaz_log(YLOG_LOG, "packagename: %s", rr->esr->packageName);
497     yaz_log(YLOG_LOG, "Waitaction: %d", *rr->esr->waitAction);
498
499     if (!rr->esr->taskSpecificParameters)
500     {
501         yaz_log (YLOG_WARN, "No task specific parameters");
502     }
503     else if (rr->esr->taskSpecificParameters->which == Z_External_ESAdmin)
504     {
505         es_admin (zh, rr->esr->taskSpecificParameters->u.adminService);
506
507         zebra_result (zh, &rr->errcode, &rr->errstring);
508     }
509     else if (rr->esr->taskSpecificParameters->which == Z_External_update)
510     {
511         Z_IUUpdate *up = rr->esr->taskSpecificParameters->u.update;
512         yaz_log (YLOG_LOG, "Received DB Update");
513         if (up->which == Z_IUUpdate_esRequest)
514         {
515             Z_IUUpdateEsRequest *esRequest = up->u.esRequest;
516             Z_IUOriginPartToKeep *toKeep = esRequest->toKeep;
517             Z_IUSuppliedRecords *notToKeep = esRequest->notToKeep;
518             
519             yaz_log (YLOG_LOG, "action");
520             if (toKeep->action)
521             {
522                 switch (*toKeep->action)
523                 {
524                 case Z_IUOriginPartToKeep_recordInsert:
525                     yaz_log (YLOG_LOG, "recordInsert");
526                     break;
527                 case Z_IUOriginPartToKeep_recordReplace:
528                     yaz_log (YLOG_LOG, "recordUpdate");
529                     break;
530                 case Z_IUOriginPartToKeep_recordDelete:
531                     yaz_log (YLOG_LOG, "recordDelete");
532                     break;
533                 case Z_IUOriginPartToKeep_elementUpdate:
534                     yaz_log (YLOG_LOG, "elementUpdate");
535                     break;
536                 case Z_IUOriginPartToKeep_specialUpdate:
537                     yaz_log (YLOG_LOG, "specialUpdate");
538                     break;
539                 case Z_ESAdminOriginPartToKeep_shutdown:
540                     yaz_log (YLOG_LOG, "shutDown");
541                     break;
542                 case Z_ESAdminOriginPartToKeep_start:
543                     yaz_log (YLOG_LOG, "start");
544                     break;
545                 default:
546                     yaz_log (YLOG_LOG, " unknown (%d)", *toKeep->action);
547                 }
548             }
549             if (toKeep->databaseName)
550             {
551                 yaz_log (YLOG_LOG, "database: %s", toKeep->databaseName);
552
553                 if (zebra_select_database(zh, toKeep->databaseName))
554                     return 0;
555             }
556             else
557             {
558                 yaz_log (YLOG_WARN, "no database supplied for ES Update");
559                 rr->errcode =
560                     YAZ_BIB1_ES_MISSING_MANDATORY_PARAMETER_FOR_SPECIFIED_FUNCTION_;
561                 rr->errstring = "database";
562                 return 0;
563             }
564             if (zebra_begin_trans(zh, 1) != ZEBRA_OK)
565             {
566                 zebra_result(zh, &rr->errcode, &rr->errstring);
567             }
568             else
569             {
570                 int i;
571                 for (i = 0; notToKeep && i < notToKeep->num; i++)
572                 {
573                     Z_External *rec = notToKeep->elements[i]->record;
574                     struct oident *oident = 0;
575                     Odr_oct *opaque_recid = 0;
576                     SYSNO sysno = 0;
577
578                     if (notToKeep->elements[i]->u.opaque)
579                     {
580                         switch(notToKeep->elements[i]->which)
581                         {
582                         case Z_IUSuppliedRecords_elem_opaque:
583                             opaque_recid = notToKeep->elements[i]->u.opaque;
584                             break; /* OK, recid already set */
585                         case Z_IUSuppliedRecords_elem_number:
586                             sysno = *notToKeep->elements[i]->u.number;
587                             break;
588                         }
589                     }
590                     if (rec->direct_reference)
591                     {
592                         oident = oid_getentbyoid(rec->direct_reference);
593                         if (oident)
594                             yaz_log (YLOG_LOG, "record %d type %s", i,
595                                      oident->desc);
596                     }
597                     switch (rec->which)
598                     {
599                     case Z_External_sutrs:
600                         if (rec->u.octet_aligned->len > 170)
601                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
602                                      rec->u.sutrs->len,
603                                      rec->u.sutrs->buf);
604                         else
605                             yaz_log (YLOG_LOG, "%d bytes:\n%s",
606                                      rec->u.sutrs->len,
607                                      rec->u.sutrs->buf);
608                         break;
609                     case Z_External_octet:
610                         if (rec->u.octet_aligned->len > 170)
611                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
612                                      rec->u.octet_aligned->len,
613                                      rec->u.octet_aligned->buf);
614                         else
615                             yaz_log (YLOG_LOG, "%d bytes\n%s",
616                                      rec->u.octet_aligned->len,
617                                      rec->u.octet_aligned->buf);
618                     }
619                     if (oident && oident->value != VAL_TEXT_XML)
620                     {
621                         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
622                         rr->errstring = "only XML update supported";
623                         break;
624                     }
625                     if (rec->which == Z_External_octet)
626                     {
627                         int action = 0;
628
629                         if (*toKeep->action ==
630                             Z_IUOriginPartToKeep_recordInsert)
631                             action = 1;
632                         if (*toKeep->action ==
633                             Z_IUOriginPartToKeep_recordReplace)
634                             action = 2;
635                         if (*toKeep->action ==
636                             Z_IUOriginPartToKeep_recordDelete)
637                             action = 3;
638                         if (*toKeep->action ==
639                             Z_IUOriginPartToKeep_specialUpdate)
640                             action = 4;
641
642                         if (!action)
643                         {
644                             rr->errcode =
645                                 YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
646                             rr->errstring = "unsupported ES Update action";
647                             break;
648                         }
649                         else if (opaque_recid)
650                         {
651                             int r = zebra_admin_exchange_record (
652                                 zh,
653                                 (const char *) rec->u.octet_aligned->buf,
654                                 rec->u.octet_aligned->len,
655                                 (const char *) opaque_recid->buf,
656                                 opaque_recid->len,
657                                 action);
658                             if (r)
659                             {
660                                 rr->errcode =
661                                     YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
662                                 rr->errstring = "record exchange failed";
663                                 break;
664                             }
665                         }
666                         else
667                         {
668                             ZEBRA_RES r = ZEBRA_FAIL;
669                             switch(action) {
670                             case 1:
671                                 r = zebra_insert_record(
672                                     zh,
673                                     0, /* recordType */
674                                     &sysno,
675                                     0, /* match */
676                                     0, /* fname */
677                                     (const char *) rec->u.octet_aligned->buf,
678                                     rec->u.octet_aligned->len,
679                                     0);
680                                 if (r == ZEBRA_FAIL)
681                                 {
682                                     rr->errcode =
683                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
684                                     rr->errstring = "insert_record failed";
685                                 }
686                                 break;
687                             case 2:
688                             case 4:
689                                 r = zebra_update_record(
690                                     zh,
691                                     0, /* recordType */
692                                     &sysno,
693                                     0, /* match */
694                                     0, /* fname */
695                                     (const char *) rec->u.octet_aligned->buf,
696                                     rec->u.octet_aligned->len,
697                                     1);
698                                 if (r == ZEBRA_FAIL)
699                                 {
700                                     rr->errcode =
701                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
702                                     rr->errstring = "update_record failed";
703                                 }
704                                 break;
705                             case 3:
706                                 r = zebra_delete_record(
707                                     zh,
708                                     0, /* recordType */
709                                     &sysno,
710                                     0, /* match */
711                                     0, /* fname */
712                                     (const char *) rec->u.octet_aligned->buf,
713                                     rec->u.octet_aligned->len,
714                                     0);
715                                 if (r == ZEBRA_FAIL)
716                                 {
717                                     rr->errcode =
718                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
719                                     rr->errstring = "delete_record failed";
720                                 }
721                                 break;
722                             }                           
723                         }
724                     }
725                 }
726                 zebra_end_trans (zh);
727             }
728         }
729     }
730     else
731     {
732         yaz_log (YLOG_WARN, "Unknown Extended Service(%d)",
733                  rr->esr->taskSpecificParameters->which);
734         rr->errcode = YAZ_BIB1_ES_EXTENDED_SERVICE_TYPE_UNSUPP;
735         
736     }
737     return 0;
738 }
739
740 static void bend_start (struct statserv_options_block *sob)
741 {
742     if (sob->handle)
743         zebra_stop((ZebraService) sob->handle);
744     sob->handle = zebra_start(sob->configname);
745     if (!sob->handle)
746     {
747         yaz_log (YLOG_FATAL, "Failed to read config `%s'", sob->configname);
748         exit (1);
749     }
750 #ifdef WIN32
751     
752 #else
753     if (!sob->inetd) 
754     {
755         char pidfname[4096];
756         struct flock area;
757         int fd;
758
759         zebra_pidfname(sob->handle, pidfname);
760
761         fd = open (pidfname, O_EXCL|O_WRONLY|O_CREAT, 0666);
762         if (fd == -1)
763         {
764             if (errno != EEXIST)
765             {
766                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
767                 exit(1);
768             }
769             fd = open(pidfname, O_RDWR, 0666);
770             if (fd == -1)
771             {
772                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
773                 exit(1);
774             }
775         }
776         area.l_type = F_WRLCK;
777         area.l_whence = SEEK_SET;
778         area.l_len = area.l_start = 0L;
779         if (fcntl (fd, F_SETLK, &area) == -1)
780         {
781             yaz_log(YLOG_ERRNO|YLOG_FATAL, "Zebra server already running");
782             exit(1);
783         }
784         else
785         {
786             char pidstr[30];
787         
788             sprintf (pidstr, "%ld", (long) getpid ());
789             write (fd, pidstr, strlen(pidstr));
790         }
791     }
792 #endif
793 }
794
795 static void bend_stop(struct statserv_options_block *sob)
796 {
797 #ifdef WIN32
798
799 #else
800     if (!sob->inetd && sob->handle) 
801     {
802         char pidfname[4096];
803         zebra_pidfname(sob->handle, pidfname);
804         unlink (pidfname);
805     }
806 #endif
807     if (sob->handle)
808     {
809         ZebraService service = sob->handle;
810         zebra_stop(service);
811     }
812 }
813
814 int main (int argc, char **argv)
815 {
816     struct statserv_options_block *sob;
817
818     sob = statserv_getcontrol ();
819     strcpy (sob->configname, "zebra.cfg");
820     sob->bend_start = bend_start;
821     sob->bend_stop = bend_stop;
822 #ifdef WIN32
823     strcpy (sob->service_display_name, "Zebra Server");
824 #endif
825     statserv_setcontrol (sob);
826
827     return statserv_main (argc, argv, bend_init, bend_close);
828 }