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