For estimated hit counts, Zebra returns resultSetStatus=estimtate as
[idzebra-moved-to-github.git] / index / zebrasrv.c
1 /* $Id: zebrasrv.c,v 1.6 2007-01-16 15:01:15 adam Exp $
2    Copyright (C) 1995-2007
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 this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
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 <yaz/backend.h>
45 #include <yaz/charneg.h>
46 #include <idzebra/api.h>
47
48 static int bend_sort (void *handle, bend_sort_rr *rr);
49 static int bend_delete (void *handle, bend_delete_rr *rr);
50 static int bend_esrequest (void *handle, bend_esrequest_rr *rr);
51 static int bend_segment (void *handle, bend_segment_rr *rr);
52 static int bend_search (void *handle, bend_search_rr *r);
53 static int bend_fetch (void *handle, bend_fetch_rr *r);
54 static int bend_scan (void *handle, bend_scan_rr *r);
55
56 bend_initresult *bend_init (bend_initrequest *q)
57 {
58     bend_initresult *r = (bend_initresult *)
59         odr_malloc (q->stream, sizeof(*r));
60     ZebraHandle zh;
61     struct statserv_options_block *sob;
62     char *user = NULL;
63     char *passwd = NULL;
64
65     r->errcode = 0;
66     r->errstring = 0;
67     q->bend_sort = bend_sort;
68     q->bend_delete = bend_delete;
69     q->bend_esrequest = bend_esrequest;
70     q->bend_segment = bend_segment;
71     q->bend_search = bend_search;
72     q->bend_fetch = bend_fetch;
73     q->bend_scan = bend_scan;
74
75     q->implementation_name = "Zebra Information Server";
76     q->implementation_version = "Zebra " ZEBRAVER;
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     if (q->auth)
89     {
90         if (q->auth->which == Z_IdAuthentication_open)
91         {
92             char *openpass = xstrdup (q->auth->u.open);
93             char *cp = strchr (openpass, '/');
94             if (cp)
95             {
96                 *cp = '\0';
97                 user = nmem_strdup (odr_getmem (q->stream), openpass);
98                 passwd = nmem_strdup (odr_getmem (q->stream), cp+1);
99             }
100             xfree (openpass);
101         }
102         else if (q->auth->which == Z_IdAuthentication_idPass)
103         {
104             Z_IdPass *idPass = q->auth->u.idPass;
105
106             user = idPass->userId;
107             passwd = idPass->password;
108         }
109     }
110     if (zebra_auth(zh, user, passwd) != ZEBRA_OK)
111     {
112         r->errcode = YAZ_BIB1_INIT_AC_BAD_USERID_AND_OR_PASSWORD;
113         r->errstring = user;
114         return r;
115     }
116     if (q->charneg_request) /* characater set and langauge negotiation? */
117     {
118         char **charsets = 0;
119         int num_charsets;
120         char **langs = 0;
121         int num_langs = 0;
122         int selected = 0;
123         int i;
124         NMEM nmem = nmem_create();
125
126         yaz_log (YLOG_LOG, "character set and language negotiation");
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 =
201         yaz_oidval_to_z3950oid (r->stream, CLASS_USERINFO, VAL_SEARCHRES1);
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_intdup(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         if (count > 2147483646)
257             count = 2147483647;
258         se->subqueryCount = odr_intdup(r->stream, CAST_ZINT_TO_INT(count));
259         se->subqueryWeight = 0;
260         se->resultsByDB = 0;
261     }
262 }
263
264 int bend_search(void *handle, bend_search_rr *r)
265 {
266     ZebraHandle zh = (ZebraHandle) handle;
267     zint zhits = 0;
268     ZEBRA_RES res;
269
270     res = zebra_select_databases (zh, r->num_bases,
271                                   (const char **) r->basenames);
272     if (res != ZEBRA_OK)
273     {
274         zebra_result (zh, &r->errcode, &r->errstring);
275         return 0;
276     }
277     yaz_log (YLOG_DEBUG, "ResultSet '%s'", r->setname);
278     switch (r->query->which)
279     {
280     case Z_Query_type_1: case Z_Query_type_101:
281         res = zebra_search_RPN_x(zh, r->stream, r->query->u.type_1,
282                                  r->setname, &zhits,
283                                  &r->estimated_hit_count,
284                                  &r->partial_resultset);
285         if (res != ZEBRA_OK)
286             zebra_result(zh, &r->errcode, &r->errstring);
287         else
288         {
289             if (zhits > 2147483646)
290                 zhits = 2147483647;
291             r->hits = CAST_ZINT_TO_INT(zhits);
292             search_terms (zh, r);
293         }
294         break;
295     case Z_Query_type_2:
296         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
297         r->errstring = "type-2";
298         break;
299     default:
300         r->errcode = YAZ_BIB1_QUERY_TYPE_UNSUPP;
301     }
302     return 0;
303 }
304
305
306 int bend_fetch (void *handle, bend_fetch_rr *r)
307 {
308     ZebraHandle zh = (ZebraHandle) handle;
309     ZebraRetrievalRecord retrievalRecord;
310     ZEBRA_RES res;
311
312     retrievalRecord.position = r->number;
313     
314     r->last_in_set = 0;
315     res = zebra_records_retrieve (zh, r->stream, r->setname, r->comp,
316                                   r->request_format, 1, &retrievalRecord);
317     if (res != ZEBRA_OK)
318     {
319         /* non-surrogate diagnostic */
320         zebra_result (zh, &r->errcode, &r->errstring);
321     }
322     else if (retrievalRecord.errCode)
323     {
324         /* surrogate diagnostic (diagnostic per record) */
325         r->surrogate_flag = 1;
326         r->errcode = retrievalRecord.errCode;
327         r->errstring = retrievalRecord.errString;
328         r->basename = retrievalRecord.base;
329     }
330     else
331     {
332         r->basename = retrievalRecord.base;
333         r->record = retrievalRecord.buf;
334         r->len = retrievalRecord.len;
335         r->output_format = retrievalRecord.format;
336     }
337     return 0;
338 }
339
340 static int bend_scan (void *handle, bend_scan_rr *r)
341 {
342     ZebraScanEntry *entries;
343     ZebraHandle zh = (ZebraHandle) handle;
344     int is_partial, i;
345     ZEBRA_RES res;
346
347     res = zebra_select_databases(zh, r->num_bases, 
348                                  (const char **) r->basenames);
349     if (res != ZEBRA_OK)
350     {
351         zebra_result (zh, &r->errcode, &r->errstring);
352         return 0;
353     }
354     if (r->step_size != 0 && *r->step_size != 0) {
355         r->errcode = YAZ_BIB1_ONLY_ZERO_STEP_SIZE_SUPPORTED_FOR_SCAN;
356         r->errstring = 0;
357         return 0;
358     }
359     r->entries = (struct scan_entry *)
360         odr_malloc (r->stream, sizeof(*r->entries) * r->num_entries);
361     res = zebra_scan(zh, r->stream, r->term,
362                      r->attributeset,
363                      &r->term_position,
364                      &r->num_entries, &entries, &is_partial, 
365                      0 /* setname */);
366     if (res == ZEBRA_OK)
367     {
368         if (is_partial)
369             r->status = BEND_SCAN_PARTIAL;
370         else
371             r->status = BEND_SCAN_SUCCESS;
372         for (i = 0; i < r->num_entries; i++)
373         {
374             r->entries[i].term = entries[i].term;
375             r->entries[i].occurrences =
376                 CAST_ZINT_TO_INT(entries[i].occurrences);
377         }
378     }
379     else
380     {
381         r->status = BEND_SCAN_PARTIAL;
382         zebra_result(zh, &r->errcode, &r->errstring);
383     }
384     return 0;
385 }
386
387 void bend_close (void *handle)
388 {
389     zebra_close ((ZebraHandle) handle);
390     xmalloc_trav("bend_close");
391     nmem_print_list();
392 }
393
394 int bend_sort (void *handle, bend_sort_rr *rr)
395 {
396     ZebraHandle zh = (ZebraHandle) handle;
397
398     if (zebra_sort (zh, rr->stream,
399                     rr->num_input_setnames, (const char **) rr->input_setnames,
400                     rr->output_setname, rr->sort_sequence, &rr->sort_status)
401         != ZEBRA_OK)
402         zebra_result (zh, &rr->errcode, &rr->errstring);
403     return 0;
404 }
405
406 int bend_delete (void *handle, bend_delete_rr *rr)
407 {
408     ZebraHandle zh = (ZebraHandle) handle;
409
410     rr->delete_status = zebra_deleteResultSet(zh, rr->function,
411                                               rr->num_setnames, rr->setnames,
412                                               rr->statuses);
413     return 0;
414 }
415
416 static void es_admin_request (bend_esrequest_rr *rr, ZebraHandle zh, Z_AdminEsRequest *r)
417 {
418     ZEBRA_RES res = ZEBRA_OK;
419     if (r->toKeep->databaseName)
420     {
421         yaz_log(YLOG_LOG, "adm request database %s", r->toKeep->databaseName);
422     }
423     switch (r->toKeep->which)
424     {
425     case Z_ESAdminOriginPartToKeep_reIndex:
426         yaz_log(YLOG_LOG, "adm-reindex");
427         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
428         rr->errstring = "adm-reindex not implemented yet";
429         break;
430     case Z_ESAdminOriginPartToKeep_truncate:
431         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
432         rr->errstring = "adm-reindex not implemented yet";
433         yaz_log(YLOG_LOG, "adm-truncate");
434         break;
435     case Z_ESAdminOriginPartToKeep_drop:
436         yaz_log(YLOG_LOG, "adm-drop");
437         res = zebra_drop_database (zh, r->toKeep->databaseName);
438         break;
439     case Z_ESAdminOriginPartToKeep_create:
440         yaz_log(YLOG_LOG, "adm-create %s", r->toKeep->databaseName);
441         res = zebra_create_database (zh, r->toKeep->databaseName);
442         break;
443     case Z_ESAdminOriginPartToKeep_import:
444         yaz_log(YLOG_LOG, "adm-import");
445         res = zebra_admin_import_begin (zh, r->toKeep->databaseName,
446                                         r->toKeep->u.import->recordType);
447         break;
448     case Z_ESAdminOriginPartToKeep_refresh:
449         yaz_log(YLOG_LOG, "adm-refresh");
450         break;
451     case Z_ESAdminOriginPartToKeep_commit:
452         yaz_log(YLOG_LOG, "adm-commit");
453         if (r->toKeep->databaseName)
454         {
455             if (zebra_select_database(zh, r->toKeep->databaseName) !=
456                 ZEBRA_OK)
457                 yaz_log(YLOG_WARN, "zebra_select_database failed in "
458                         "adm-commit");
459         }
460         zebra_commit(zh);
461         break;
462     case Z_ESAdminOriginPartToKeep_shutdown:
463         yaz_log(YLOG_LOG, "shutdown");
464         res = zebra_admin_shutdown(zh);
465         break;
466     case Z_ESAdminOriginPartToKeep_start:
467         yaz_log(YLOG_LOG, "start");
468         zebra_admin_start(zh);
469         break;
470     default:
471         yaz_log(YLOG_LOG, "unknown admin");
472         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
473         rr->errstring = "adm-reindex not implemented yet";
474     }
475     if (res != ZEBRA_OK)
476         zebra_result(zh, &rr->errcode, &rr->errstring);
477 }
478
479 static void es_admin (bend_esrequest_rr *rr, ZebraHandle zh, Z_Admin *r)
480 {
481     switch (r->which)
482     {
483     case Z_Admin_esRequest:
484         es_admin_request (rr, zh, r->u.esRequest);
485         return;
486     default:
487         break;
488     }
489         yaz_log (YLOG_WARN, "adm taskpackage (unhandled)");
490     rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
491     rr->errstring = "adm-task package (unhandled)";
492 }
493
494 int bend_segment (void *handle, bend_segment_rr *rr)
495 {
496     ZebraHandle zh = (ZebraHandle) handle;
497     Z_Segment *segment = rr->segment;
498
499     if (segment->num_segmentRecords)
500         zebra_admin_import_segment (zh, rr->segment);
501     else
502         zebra_admin_import_end (zh);
503     return 0;
504 }
505
506 int bend_esrequest (void *handle, bend_esrequest_rr *rr)
507 {
508     ZebraHandle zh = (ZebraHandle) handle;
509     
510     yaz_log(YLOG_LOG, "function: %d", *rr->esr->function);
511     if (rr->esr->packageName)
512         yaz_log(YLOG_LOG, "packagename: %s", rr->esr->packageName);
513     yaz_log(YLOG_LOG, "Waitaction: %d", *rr->esr->waitAction);
514
515     if (!rr->esr->taskSpecificParameters)
516     {
517         yaz_log (YLOG_WARN, "No task specific parameters");
518     }
519     else if (rr->esr->taskSpecificParameters->which == Z_External_ESAdmin)
520     {
521         es_admin(rr, zh, rr->esr->taskSpecificParameters->u.adminService);
522     }
523     else if (rr->esr->taskSpecificParameters->which == Z_External_update)
524     {
525         Z_IUUpdate *up = rr->esr->taskSpecificParameters->u.update;
526         yaz_log (YLOG_LOG, "Received DB Update");
527         if (up->which == Z_IUUpdate_esRequest)
528         {
529             Z_IUUpdateEsRequest *esRequest = up->u.esRequest;
530             Z_IUOriginPartToKeep *toKeep = esRequest->toKeep;
531             Z_IUSuppliedRecords *notToKeep = esRequest->notToKeep;
532             
533             yaz_log (YLOG_LOG, "action");
534             if (toKeep->action)
535             {
536                 switch (*toKeep->action)
537                 {
538                 case Z_IUOriginPartToKeep_recordInsert:
539                     yaz_log (YLOG_LOG, "recordInsert");
540                     break;
541                 case Z_IUOriginPartToKeep_recordReplace:
542                     yaz_log (YLOG_LOG, "recordUpdate");
543                     break;
544                 case Z_IUOriginPartToKeep_recordDelete:
545                     yaz_log (YLOG_LOG, "recordDelete");
546                     break;
547                 case Z_IUOriginPartToKeep_elementUpdate:
548                     yaz_log (YLOG_LOG, "elementUpdate");
549                     break;
550                 case Z_IUOriginPartToKeep_specialUpdate:
551                     yaz_log (YLOG_LOG, "specialUpdate");
552                     break;
553                 case Z_ESAdminOriginPartToKeep_shutdown:
554                     yaz_log (YLOG_LOG, "shutDown");
555                     break;
556                 case Z_ESAdminOriginPartToKeep_start:
557                     yaz_log (YLOG_LOG, "start");
558                     break;
559                 default:
560                     yaz_log (YLOG_LOG, " unknown (%d)", *toKeep->action);
561                 }
562             }
563             if (toKeep->databaseName)
564             {
565                 yaz_log (YLOG_LOG, "database: %s", toKeep->databaseName);
566
567                 if (zebra_select_database(zh, toKeep->databaseName))
568                     return 0;
569             }
570             else
571             {
572                 yaz_log (YLOG_WARN, "no database supplied for ES Update");
573                 rr->errcode =
574                     YAZ_BIB1_ES_MISSING_MANDATORY_PARAMETER_FOR_SPECIFIED_FUNCTION_;
575                 rr->errstring = "database";
576                 return 0;
577             }
578             if (zebra_begin_trans(zh, 1) != ZEBRA_OK)
579             {
580                 zebra_result(zh, &rr->errcode, &rr->errstring);
581             }
582             else
583             {
584                 int i;
585                 for (i = 0; notToKeep && i < notToKeep->num; i++)
586                 {
587                     Z_External *rec = notToKeep->elements[i]->record;
588                     struct oident *oident = 0;
589                     Odr_oct *opaque_recid = 0;
590                     zint *sysno = 0;
591                     zint sysno_tmp;
592
593                     if (notToKeep->elements[i]->u.opaque)
594                     {
595                         switch(notToKeep->elements[i]->which)
596                         {
597                         case Z_IUSuppliedRecords_elem_opaque:
598                             opaque_recid = notToKeep->elements[i]->u.opaque;
599                             break; /* OK, recid already set */
600                         case Z_IUSuppliedRecords_elem_number:
601                             sysno_tmp = *notToKeep->elements[i]->u.number;
602                             sysno = &sysno_tmp;
603                             break;
604                         }
605                     }
606                     if (rec->direct_reference)
607                     {
608                         oident = oid_getentbyoid(rec->direct_reference);
609                         if (oident)
610                             yaz_log (YLOG_LOG, "record %d type %s", i,
611                                      oident->desc);
612                     }
613                     switch (rec->which)
614                     {
615                     case Z_External_sutrs:
616                         if (rec->u.octet_aligned->len > 170)
617                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
618                                      rec->u.sutrs->len,
619                                      rec->u.sutrs->buf);
620                         else
621                             yaz_log (YLOG_LOG, "%d bytes:\n%s",
622                                      rec->u.sutrs->len,
623                                      rec->u.sutrs->buf);
624                         break;
625                     case Z_External_octet:
626                         if (rec->u.octet_aligned->len > 170)
627                             yaz_log (YLOG_LOG, "%d bytes:\n%.168s ...",
628                                      rec->u.octet_aligned->len,
629                                      rec->u.octet_aligned->buf);
630                         else
631                             yaz_log (YLOG_LOG, "%d bytes\n%s",
632                                      rec->u.octet_aligned->len,
633                                      rec->u.octet_aligned->buf);
634                     }
635                     if (oident && oident->value != VAL_TEXT_XML 
636                         && oident->value != VAL_SUTRS)
637                     {
638                         rr->errcode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
639                         rr->errstring = "only XML update supported";
640                         break;
641                     }
642                     if (rec->which == Z_External_octet)
643                     {
644                         int action = 0;
645
646                         if (*toKeep->action ==
647                             Z_IUOriginPartToKeep_recordInsert)
648                             action = 1;
649                         if (*toKeep->action ==
650                             Z_IUOriginPartToKeep_recordReplace)
651                             action = 2;
652                         if (*toKeep->action ==
653                             Z_IUOriginPartToKeep_recordDelete)
654                             action = 3;
655                         if (*toKeep->action ==
656                             Z_IUOriginPartToKeep_specialUpdate)
657                             action = 4;
658
659                         if (!action)
660                         {
661                             rr->errcode =
662                                 YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
663                             rr->errstring = "unsupported ES Update action";
664                             break;
665                         }
666                         else if (opaque_recid)
667                         {
668                             int r = zebra_admin_exchange_record (
669                                 zh,
670                                 (const char *) rec->u.octet_aligned->buf,
671                                 rec->u.octet_aligned->len,
672                                 (const char *) opaque_recid->buf,
673                                 opaque_recid->len,
674                                 action);
675                             if (r)
676                             {
677                                 zebra_result(zh, &rr->errcode,
678                                              &rr->errstring);
679                                 break;
680                             }
681                         }
682                         else
683                         {
684                             ZEBRA_RES r = ZEBRA_FAIL;
685                             switch(action) {
686                             case 1:
687                                 r = zebra_insert_record(
688                                     zh,
689                                     0, /* recordType */
690                                     sysno,
691                                     0, /* match */
692                                     0, /* fname */
693                                     (const char *) rec->u.octet_aligned->buf,
694                                     rec->u.octet_aligned->len,
695                                     0);
696                                 if (r == ZEBRA_FAIL)
697                                 {
698                                     rr->errcode =
699                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
700                                     rr->errstring = "insert_record failed";
701                                 }
702                                 break;
703                             case 2:
704                             case 4:
705                                 r = zebra_update_record(
706                                     zh,
707                                     0, /* recordType */
708                                     sysno,
709                                     0, /* match */
710                                     0, /* fname */
711                                     (const char *) rec->u.octet_aligned->buf,
712                                     rec->u.octet_aligned->len,
713                                     1);
714                                 if (r == ZEBRA_FAIL)
715                                 {
716                                     rr->errcode =
717                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
718                                     rr->errstring = "update_record failed";
719                                 }
720                                 break;
721                             case 3:
722                                 r = zebra_delete_record(
723                                     zh,
724                                     0, /* recordType */
725                                     sysno,
726                                     0, /* match */
727                                     0, /* fname */
728                                     (const char *) rec->u.octet_aligned->buf,
729                                     rec->u.octet_aligned->len,
730                                     0);
731                                 if (r == ZEBRA_FAIL)
732                                 {
733                                     rr->errcode =
734                                         YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
735                                     rr->errstring = "delete_record failed";
736                                 }
737                                 break;
738                             }                           
739                         }
740                     }
741                 }
742                 if (zebra_end_trans (zh) != ZEBRA_OK)
743                 {
744                     yaz_log(YLOG_WARN, "zebra_end_trans failed for"
745                             " extended service operation");
746                 }
747             }
748         }
749     }
750     else
751     {
752         yaz_log (YLOG_WARN, "Unknown Extended Service(%d)",
753                  rr->esr->taskSpecificParameters->which);
754         rr->errcode = YAZ_BIB1_ES_EXTENDED_SERVICE_TYPE_UNSUPP;
755         
756     }
757     return 0;
758 }
759
760 static void bend_start (struct statserv_options_block *sob)
761 {
762     Res default_res = res_open(0, 0);
763
764     if (sob->handle)
765         zebra_stop((ZebraService) sob->handle);
766     res_set(default_res, "profilePath", DEFAULT_PROFILE_PATH);
767     res_set(default_res, "modulePath", DEFAULT_MODULE_PATH);
768     sob->handle = zebra_start(sob->configname);
769     res_close(default_res);
770     if (!sob->handle)
771     {
772         yaz_log (YLOG_FATAL, "Failed to read config `%s'", sob->configname);
773         exit (1);
774     }
775 #ifdef WIN32
776     
777 #else
778     if (!sob->inetd) 
779     {
780         char pidfname[4096];
781         struct flock area;
782         int fd;
783
784         zebra_pidfname(sob->handle, pidfname);
785
786         fd = open (pidfname, O_EXCL|O_WRONLY|O_CREAT, 0666);
787         if (fd == -1)
788         {
789             if (errno != EEXIST)
790             {
791                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
792                 exit(1);
793             }
794             fd = open(pidfname, O_RDWR, 0666);
795             if (fd == -1)
796             {
797                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "lock file %s", pidfname);
798                 exit(1);
799             }
800         }
801         area.l_type = F_WRLCK;
802         area.l_whence = SEEK_SET;
803         area.l_len = area.l_start = 0L;
804         if (fcntl (fd, F_SETLK, &area) == -1)
805         {
806             yaz_log(YLOG_ERRNO|YLOG_FATAL, "Zebra server already running");
807             exit(1);
808         }
809         else
810         {
811             char pidstr[30];
812         
813             sprintf (pidstr, "%ld", (long) getpid ());
814             write (fd, pidstr, strlen(pidstr));
815         }
816     }
817 #endif
818 }
819
820 static void bend_stop(struct statserv_options_block *sob)
821 {
822 #ifdef WIN32
823
824 #else
825     if (!sob->inetd && sob->handle) 
826     {
827         char pidfname[4096];
828         zebra_pidfname(sob->handle, pidfname);
829         unlink (pidfname);
830     }
831 #endif
832     if (sob->handle)
833     {
834         ZebraService service = sob->handle;
835         zebra_stop(service);
836     }
837 }
838
839 int main (int argc, char **argv)
840 {
841     struct statserv_options_block *sob;
842
843     sob = statserv_getcontrol ();
844     strcpy (sob->configname, "zebra.cfg");
845     sob->bend_start = bend_start;
846     sob->bend_stop = bend_stop;
847 #ifdef WIN32
848     strcpy (sob->service_display_name, "Zebra Server");
849 #endif
850     statserv_setcontrol (sob);
851
852     return statserv_main (argc, argv, bend_init, bend_close);
853 }
854 /*
855  * Local variables:
856  * c-basic-offset: 4
857  * indent-tabs-mode: nil
858  * End:
859  * vim: shiftwidth=4 tabstop=8 expandtab
860  */
861