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