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