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