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