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