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