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