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