06dc3b1635589115b9c9db91f2c849805d8d686e
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /* This file is part of simpleserver.
2  * Copyright (C) 2000-2013 Index Data.
3  * All rights reserved.
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  *     * Redistributions of source code must retain the above copyright
8  *       notice, this list of conditions and the following disclaimer.
9  *     * Redistributions in binary form must reproduce the above copyright
10  *       notice, this list of conditions and the following disclaimer in the
11  *       documentation and/or other materials provided with the distribution.
12  *     * Neither the name of Index Data nor the names of its contributors
13  *       may be used to endorse or promote products derived from this
14  *       software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "EXTERN.h"
29 #include "perl.h"
30 #include "proto.h"
31 #include "embed.h"
32 #include "XSUB.h"
33 #include <assert.h>
34 #include <yaz/backend.h>
35 #include <yaz/facet.h>
36 #include <yaz/log.h>
37 #include <yaz/wrbuf.h>
38 #include <yaz/pquery.h>
39 #include <yaz/querytowrbuf.h>
40 #include <stdio.h>
41 #include <yaz/mutex.h>
42 #include <yaz/oid_db.h>
43 #ifdef WIN32
44 #else
45 #include <unistd.h>
46 #endif
47 #include <stdlib.h>
48 #include <ctype.h>
49 #define GRS_MAX_FIELDS 500
50 #ifdef ASN_COMPILED
51 #include <yaz/ill.h>
52 #endif
53 #ifndef sv_undef                /* To fix the problem with Perl 5.6.0 */
54 #define sv_undef PL_sv_undef
55 #endif
56
57 YAZ_MUTEX simpleserver_mutex;
58
59 typedef struct {
60         SV *ghandle;    /* Global handle specified at creation */
61         SV *handle;     /* Per-connection handle set at Init */
62         NMEM nmem;
63         int stop_flag;  /* is used to stop server prematurely .. */
64 } Zfront_handle;
65
66 #define ENABLE_STOP_SERVER 0
67
68 SV *_global_ghandle = NULL; /* To be copied into zhandle then ignored */
69 SV *init_ref = NULL;
70 SV *close_ref = NULL;
71 SV *sort_ref = NULL;
72 SV *search_ref = NULL;
73 SV *fetch_ref = NULL;
74 SV *present_ref = NULL;
75 SV *esrequest_ref = NULL;
76 SV *delete_ref = NULL;
77 SV *scan_ref = NULL;
78 SV *explain_ref = NULL;
79 SV *start_ref = NULL;
80 PerlInterpreter *root_perl_context;
81
82 #define GRS_BUF_SIZE 8192
83
84
85 /*
86  * Inspects the SV indicated by svp, and returns a null pointer if
87  * it's an undefined value, or a string allocation from `stream'
88  * otherwise.  Using this when filling in addinfo avoids those
89  * irritating "Use of uninitialized value in subroutine entry"
90  * warnings from Perl.
91  */
92 char *string_or_undef(SV **svp, ODR stream) {
93         STRLEN len;
94         char *ptr, *buf;
95
96         if (!SvOK(*svp))
97                 return 0;
98
99         ptr = SvPV(*svp, len);
100         buf = (char*) odr_malloc(stream, len+1);
101         strcpy(buf, ptr);
102         return buf;
103 }
104
105
106 CV * simpleserver_sv2cv(SV *handler) {
107     STRLEN len;
108     char *buf;
109
110     if (SvPOK(handler)) {
111         CV *ret;
112         buf = SvPV( handler, len);
113         if ( !( ret = perl_get_cv(buf, FALSE ) ) ) {
114             fprintf( stderr, "simpleserver_sv2cv: No such handler '%s'\n\n", buf );
115             exit(1);
116         }
117
118         return ret;
119     } else {
120         return (CV *) handler;
121     }
122 }
123
124 /* debugging routine to check for destruction of Perl interpreters */
125 #ifdef USE_ITHREADS
126 void tst_clones(void)
127 {
128     int i;
129     PerlInterpreter *parent = PERL_GET_CONTEXT;
130     for (i = 0; i<5000; i++)
131     {
132         PerlInterpreter *perl_interp;
133
134         PERL_SET_CONTEXT(parent);
135         PL_perl_destruct_level = 2;
136         perl_interp = perl_clone(parent, CLONEf_CLONE_HOST);
137         PL_perl_destruct_level = 2;
138         PERL_SET_CONTEXT(perl_interp);
139         perl_destruct(perl_interp);
140         perl_free(perl_interp);
141     }
142     exit (0);
143 }
144 #endif
145
146 int simpleserver_clone(void) {
147 #ifdef USE_ITHREADS
148      yaz_mutex_enter(simpleserver_mutex);
149      if (1)
150      {
151          PerlInterpreter *current = PERL_GET_CONTEXT;
152
153          /* if current is unset, then we're in a new thread with
154           * no Perl interpreter for it. So we must create one .
155           * This will only happen when threaded is used..
156           */
157          if (!current) {
158              PerlInterpreter *perl_interp;
159              PERL_SET_CONTEXT( root_perl_context );
160              perl_interp = perl_clone(root_perl_context, CLONEf_CLONE_HOST);
161              PERL_SET_CONTEXT( perl_interp );
162          }
163      }
164      yaz_mutex_leave(simpleserver_mutex);
165 #endif
166      return 0;
167 }
168
169
170 void simpleserver_free(void) {
171     yaz_mutex_enter(simpleserver_mutex);
172     if (1)
173     {
174         PerlInterpreter *current_interp = PERL_GET_CONTEXT;
175
176         /* If current Perl Interp is different from root interp, then
177          * we're in threaded mode and we must destroy..
178          */
179         if (current_interp != root_perl_context) {
180             PL_perl_destruct_level = 2;
181             PERL_SET_CONTEXT(current_interp);
182             perl_destruct(current_interp);
183             perl_free(current_interp);
184         }
185     }
186     yaz_mutex_leave(simpleserver_mutex);
187 }
188
189
190 Z_GenericRecord *read_grs1(char *str, ODR o)
191 {
192         int type, ivalue;
193         char line[GRS_BUF_SIZE+1], *buf, *ptr, *original;
194         char value[GRS_BUF_SIZE+1];
195         Z_GenericRecord *r = 0;
196
197         original = str;
198         r = (Z_GenericRecord *)odr_malloc(o, sizeof(*r));
199         r->elements = (Z_TaggedElement **) odr_malloc(o, sizeof(Z_TaggedElement*) * GRS_MAX_FIELDS);
200         r->num_elements = 0;
201
202         for (;;)
203         {
204                 Z_TaggedElement *t;
205                 Z_ElementData *c;
206                 int len;
207
208                 ptr = strchr(str, '\n');
209                 if (!ptr) {
210                         return r;
211                 }
212                 len = ptr - str;
213                 if (len > GRS_BUF_SIZE) {
214                     yaz_log(YLOG_WARN, "GRS string too long - truncating (%d > %d)", len, GRS_BUF_SIZE);
215                     len = GRS_BUF_SIZE;
216                 }
217                 strncpy(line, str, len);
218                 line[len] = 0;
219                 buf = line;
220                 str = ptr + 1;
221                 while (*buf && isspace(*buf))
222                         buf++;
223                 if (*buf == '}') {
224                         memmove(original, str, strlen(str));
225                         return r;
226                 }
227                 if (sscanf(buf, "(%d,%[^)])", &type, value) != 2)
228                 {
229                         yaz_log(YLOG_WARN, "Bad data in '%s'", buf);
230                         return r;
231                 }
232                 if (!type && *value == '0')
233                         return r;
234                 if (!(buf = strchr(buf, ')')))
235                         return r;
236                 buf++;
237                 while (*buf && isspace(*buf))
238                         buf++;
239                 if (r->num_elements >= GRS_MAX_FIELDS)
240                 {
241                         yaz_log(YLOG_WARN, "Max number of GRS-1 elements exceeded [GRS_MAX_FIELDS=%d]", GRS_MAX_FIELDS);
242                         exit(0);
243                 }
244                 r->elements[r->num_elements] = t = (Z_TaggedElement *) odr_malloc(o, sizeof(Z_TaggedElement));
245                 t->tagType = odr_intdup(o, type);
246                 t->tagValue = (Z_StringOrNumeric *)
247                         odr_malloc(o, sizeof(Z_StringOrNumeric));
248                 if ((ivalue = atoi(value)))
249                 {
250                         t->tagValue->which = Z_StringOrNumeric_numeric;
251                         t->tagValue->u.numeric = odr_intdup(o, ivalue);
252                 }
253                 else
254                 {
255                         t->tagValue->which = Z_StringOrNumeric_string;
256                         t->tagValue->u.string = odr_strdup(o, value);
257                 }
258                 t->tagOccurrence = 0;
259                 t->metaData = 0;
260                 t->appliedVariant = 0;
261                 t->content = c = (Z_ElementData *)odr_malloc(o, sizeof(Z_ElementData));
262                 if (*buf == '{')
263                 {
264                         c->which = Z_ElementData_subtree;
265                         c->u.subtree = read_grs1(str, o);
266                 }
267                 else
268                 {
269                         c->which = Z_ElementData_string;
270                         c->u.string = odr_strdup(o, buf);
271                 }
272                 r->num_elements++;
273         }
274 }
275
276
277
278 static void oid2str(Odr_oid *o, WRBUF buf)
279 {
280     for (; *o >= 0; o++) {
281         char ibuf[16];
282         sprintf(ibuf, "%d", *o);
283         wrbuf_puts(buf, ibuf);
284         if (o[1] > 0)
285             wrbuf_putc(buf, '.');
286     }
287 }
288
289 WRBUF oid2dotted(Odr_oid *oid)
290 {
291     WRBUF buf = wrbuf_alloc();
292     oid2str(oid, buf);
293     return buf;
294 }
295
296
297 WRBUF zquery2pquery(Z_Query *q)
298 {
299     WRBUF buf = wrbuf_alloc();
300
301     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101)
302         return 0;
303     yaz_rpnquery_to_wrbuf(buf, q->u.type_1);
304     return buf;
305 }
306
307
308 /* Lifted verbatim from Net::Z3950 yazwrap/util.c */
309 #include <stdarg.h>
310 void fatal(char *fmt, ...)
311 {
312     va_list ap;
313
314     fprintf(stderr, "FATAL (SimpleServer): ");
315     va_start(ap, fmt);
316     vfprintf(stderr, fmt, ap);
317     va_end(ap);
318     fprintf(stderr, "\n");
319     abort();
320 }
321
322
323 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
324 /*
325  * Creates a new Perl object of type `class'; the newly-created scalar
326  * that is a reference to the blessed thingy `referent' is returned.
327  */
328 static SV *newObject(char *class, SV *referent)
329 {
330     HV *stash;
331     SV *sv;
332
333     sv = newRV_noinc((SV*) referent);
334     stash = gv_stashpv(class, 0);
335     if (stash == 0)
336         fatal("attempt to create object of undefined class '%s'", class);
337     /*assert(stash != 0);*/
338     sv_bless(sv, stash);
339     return sv;
340 }
341
342
343 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
344 static void setMember(HV *hv, char *name, SV *val)
345 {
346     /* We don't increment `val's reference count -- I think this is
347      * right because it's created with a refcount of 1, and in fact
348      * the reference via this hash is the only reference to it in
349      * general.
350      */
351     if (!hv_store(hv, name, (U32) strlen(name), val, (U32) 0))
352         fatal("couldn't store member in hash");
353 }
354
355
356 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
357 static SV *translateOID(Odr_oid *x)
358 {
359     /* Yaz represents an OID by an int array terminated by a negative
360      * value, typically -1; we represent it as a reference to a
361      * blessed scalar string of "."-separated elements.
362      */
363     char buf[1000];
364     int i;
365
366     *buf = '\0';
367     for (i = 0; x[i] >= 0; i++) {
368         sprintf(buf + strlen(buf), "%d", (int) x[i]);
369         if (x[i+1] >- 0)
370             strcat(buf, ".");
371     }
372
373     /*
374      * ### We'd like to return a blessed scalar (string) here, but of
375      *  course you can't do that in Perl: only references can be
376      *  blessed, so we'd have to return a _reference_ to a string, and
377      *  bless _that_.  Better to do without the blessing, I think.
378      */
379     if (1) {
380         return newSVpv(buf, 0);
381     } else {
382         return newObject("Net::Z3950::APDU::OID", newSVpv(buf, 0));
383     }
384 }
385
386 static SV *attributes2perl(Z_AttributeList *list)
387 {
388     AV *av;
389         int i;
390         SV *attrs = newObject("Net::Z3950::RPN::Attributes",
391                               (SV*) (av = newAV()));
392         for (i = 0; i < list->num_attributes; i++) {
393             Z_AttributeElement *elem = list->attributes[i];
394             HV *hv2;
395             SV *tmp = newObject("Net::Z3950::RPN::Attribute",
396                                 (SV*) (hv2 = newHV()));
397             if (elem->attributeSet)
398                 setMember(hv2, "attributeSet",
399                           translateOID(elem->attributeSet));
400             setMember(hv2, "attributeType",
401                       newSViv(*elem->attributeType));
402             if (elem->which == Z_AttributeValue_numeric) {
403                 setMember(hv2, "attributeValue",
404                           newSViv(*elem->value.numeric));
405             } else {
406                 Z_ComplexAttribute *c;
407                 Z_StringOrNumeric *son;
408                 assert(elem->which == Z_AttributeValue_complex);
409                 c = elem->value.complex;
410                 /* We ignore semantic actions and multiple values */
411                 assert(c->num_list > 0);
412                 son = c->list[0];
413                 if (son->which == Z_StringOrNumeric_numeric) {
414                     setMember(hv2, "attributeValue",
415                               newSViv(*son->u.numeric));
416                 } else { /*Z_StringOrNumeric_string*/
417                     setMember(hv2, "attributeValue",
418                               newSVpv(son->u.string, 0));
419                 }
420             }
421             av_push(av, tmp);
422         }
423         return attrs;
424 }
425
426 static SV *f_Term_to_SV(Z_Term *term, Z_AttributeList *attributes)
427 {
428         HV *hv;
429         SV *sv = newObject("Net::Z3950::RPN::Term", (SV*) (hv = newHV()));
430
431         if (term->which != Z_Term_general)
432                 fatal("can't handle RPN terms other than general");
433
434         setMember(hv, "term", newSVpv((char*) term->u.general->buf,
435                                   term->u.general->len));
436
437         if (attributes) {
438                 setMember(hv, "attributes", attributes2perl(attributes));
439         }
440         return sv;
441 }
442
443 static SV *rpn2perl(Z_RPNStructure *s)
444 {
445     SV *sv;
446     HV *hv;
447     AV *av;
448     Z_Operand *o;
449
450     switch (s->which) {
451     case Z_RPNStructure_simple:
452         o = s->u.simple;
453         switch (o->which) {
454         case Z_Operand_resultSetId: {
455             /* This code causes a SIGBUS on my machine, and I have no
456                idea why.  It seems as clear as day to me */
457             SV *sv2;
458             char *rsid = (char*) o->u.resultSetId;
459             /*printf("Encoding resultSetId '%s'\n", rsid);*/
460             sv = newObject("Net::Z3950::RPN::RSID", (SV*) (hv = newHV()));
461             /*printf("Made sv=0x%lx, hv=0x%lx\n", (unsigned long) sv ,(unsigned long) hv);*/
462             sv2 = newSVpv(rsid, strlen(rsid));
463             setMember(hv, "id", sv2);
464             /*printf("Set hv{id} to 0x%lx\n", (unsigned long) sv2);*/
465             return sv;
466         }
467
468         case  Z_Operand_APT:
469             return f_Term_to_SV(o->u.attributesPlusTerm->term,
470                         o->u.attributesPlusTerm->attributes);
471         default:
472             fatal("unknown RPN simple type %d", (int) o->which);
473         }
474
475     case Z_RPNStructure_complex: {
476         SV *tmp;
477         Z_Complex *c = s->u.complex;
478         char *type = 0;         /* vacuous assignment satisfies gcc -Wall */
479         switch (c->roperator->which) {
480         case Z_Operator_and:     type = "Net::Z3950::RPN::And";    break;
481         case Z_Operator_or:      type = "Net::Z3950::RPN::Or";     break;
482         case Z_Operator_and_not: type = "Net::Z3950::RPN::AndNot"; break;
483         case Z_Operator_prox:    fatal("proximity not yet supported");
484         default: fatal("unknown RPN operator %d", (int) c->roperator->which);
485         }
486         sv = newObject(type, (SV*) (av = newAV()));
487         if ((tmp = rpn2perl(c->s1)) == 0)
488             return 0;
489         av_push(av, tmp);
490         if ((tmp = rpn2perl(c->s2)) == 0)
491             return 0;
492         av_push(av, tmp);
493         return sv;
494     }
495
496     default:
497         fatal("unknown RPN node type %d", (int) s->which);
498     }
499
500     return 0;
501 }
502
503
504 /* Decode the Z_SortAttributes struct and store the whole thing into the
505  * hash by reference
506  */
507 int simpleserver_ExpandSortAttributes (HV *sort_spec, Z_SortAttributes *sattr)
508 {
509     WRBUF attrset_wr = wrbuf_alloc();
510     AV *list = newAV();
511     Z_AttributeList *attr_list = sattr->list;
512     int i;
513
514     oid2str(sattr->id, attrset_wr);
515     hv_store(sort_spec, "ATTRSET", 7,
516              newSVpv(attrset_wr->buf, attrset_wr->pos), 0);
517     wrbuf_destroy(attrset_wr);
518
519     hv_store(sort_spec, "SORT_ATTR", 9, newRV( sv_2mortal( (SV*) list ) ), 0);
520
521     for (i = 0; i < attr_list->num_attributes; i++)
522     {
523         Z_AttributeElement *attr = *attr_list->attributes++;
524         HV *attr_spec = newHV();
525
526         av_push(list, newRV( sv_2mortal( (SV*) attr_spec ) ));
527         hv_store(attr_spec, "ATTR_TYPE", 9, newSViv(*attr->attributeType), 0);
528
529         if (attr->which == Z_AttributeValue_numeric)
530         {
531             hv_store(attr_spec, "ATTR_VALUE", 10,
532                      newSViv(*attr->value.numeric), 0);
533         } else {
534             return 0;
535         }
536     }
537
538     return 1;
539 }
540
541
542 /* Decode the Z_SortKeySpec struct and store the whole thing in a perl hash */
543 int simpleserver_SortKeySpecToHash (HV *sort_spec, Z_SortKeySpec *spec)
544 {
545     Z_SortElement *element = spec->sortElement;
546
547     hv_store(sort_spec, "RELATION", 8, newSViv(*spec->sortRelation), 0);
548     hv_store(sort_spec, "CASE", 4, newSViv(*spec->caseSensitivity), 0);
549     hv_store(sort_spec, "MISSING", 7, newSViv(spec->which), 0);
550
551     if (element->which == Z_SortElement_generic)
552     {
553         Z_SortKey *key = element->u.generic;
554
555         if (key->which == Z_SortKey_sortField)
556         {
557             hv_store(sort_spec, "SORTFIELD", 9,
558                      newSVpv((char *) key->u.sortField, 0), 0);
559         }
560         else if (key->which == Z_SortKey_elementSpec)
561         {
562             Z_Specification *zspec = key->u.elementSpec;
563
564             hv_store(sort_spec, "ELEMENTSPEC_TYPE", 16,
565                      newSViv(zspec->which), 0);
566
567             if (zspec->which == Z_Schema_oid)
568             {
569                 WRBUF elementSpec = wrbuf_alloc();
570
571                 oid2str(zspec->schema.oid, elementSpec);
572                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
573                          newSVpv(elementSpec->buf, elementSpec->pos), 0);
574                 wrbuf_destroy(elementSpec);
575             }
576             else if (zspec->which == Z_Schema_uri)
577             {
578                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
579                          newSVpv((char *) zspec->schema.uri, 0), 0);
580             }
581         }
582         else if (key->which == Z_SortKey_sortAttributes)
583         {
584             return simpleserver_ExpandSortAttributes(sort_spec,
585                                                      key->u.sortAttributes);
586         }
587         else
588         {
589             return 0;
590         }
591     }
592     else
593     {
594         return 0;
595     }
596
597     return 1;
598 }
599
600
601 static SV *zquery2perl(Z_Query *q)
602 {
603     SV *sv;
604     HV *hv;
605
606     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101)
607         return 0;
608     sv = newObject("Net::Z3950::APDU::Query", (SV*) (hv = newHV()));
609     if (q->u.type_1->attributeSetId)
610         setMember(hv, "attributeSet",
611                   translateOID(q->u.type_1->attributeSetId));
612     setMember(hv, "query", rpn2perl(q->u.type_1->RPNStructure));
613     return sv;
614 }
615
616
617 int bend_sort(void *handle, bend_sort_rr *rr)
618 {
619         HV *href;
620         AV *aref;
621         AV *sort_seq;
622         SV **temp;
623         SV *err_code;
624         SV *err_str;
625         SV *status;
626         SV *point;
627         STRLEN len;
628         char *ptr;
629         char *ODR_err_str;
630         char **input_setnames;
631         Zfront_handle *zhandle = (Zfront_handle *)handle;
632         Z_SortKeySpecList *sort_spec = rr->sort_sequence;
633         int i;
634
635         dSP;
636         ENTER;
637         SAVETMPS;
638
639         aref = newAV();
640         input_setnames = rr->input_setnames;
641         for (i = 0; i < rr->num_input_setnames; i++)
642         {
643             av_push(aref, newSVpv(*input_setnames++, 0));
644         }
645
646         sort_seq = newAV();
647         for (i = 0; i < sort_spec->num_specs; i++)
648         {
649             Z_SortKeySpec *spec = *sort_spec->specs++;
650             HV *sort_spec = newHV();
651
652             if ( simpleserver_SortKeySpecToHash(sort_spec, spec) )
653                 av_push(sort_seq, newRV( sv_2mortal( (SV*) sort_spec ) ));
654             else
655             {
656                 rr->errcode = 207;
657                 return 0;
658             }
659         }
660
661         href = newHV();
662         hv_store(href, "INPUT", 5, newRV( (SV*) aref), 0);
663         hv_store(href, "OUTPUT", 6, newSVpv(rr->output_setname, 0), 0);
664         hv_store(href, "SEQUENCE", 8, newRV( (SV*) sort_seq), 0);
665         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
666         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
667         hv_store(href, "STATUS", 6, newSViv(0), 0);
668         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
669         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
670
671         PUSHMARK(sp);
672
673         XPUSHs(sv_2mortal(newRV( (SV*) href)));
674
675         PUTBACK;
676
677         perl_call_sv(sort_ref, G_SCALAR | G_DISCARD);
678
679         SPAGAIN;
680
681         temp = hv_fetch(href, "ERR_CODE", 8, 1);
682         err_code = newSVsv(*temp);
683
684         temp = hv_fetch(href, "ERR_STR", 7, 1);
685         err_str = newSVsv(*temp);
686
687         temp = hv_fetch(href, "STATUS", 6, 1);
688         status = newSVsv(*temp);
689
690         temp = hv_fetch(href, "HANDLE", 6, 1);
691         point = newSVsv(*temp);
692
693         hv_undef(href);
694         av_undef(aref);
695         av_undef(sort_seq);
696
697         sv_free( (SV*) aref);
698         sv_free( (SV*) href);
699         sv_free( (SV*) sort_seq);
700
701         rr->errcode = SvIV(err_code);
702         rr->sort_status = SvIV(status);
703
704         ptr = SvPV(err_str, len);
705         ODR_err_str = (char *)odr_malloc(rr->stream, len + 1);
706         strcpy(ODR_err_str, ptr);
707         rr->errstring = ODR_err_str;
708         zhandle->handle = point;
709
710         sv_free(err_code);
711         sv_free(err_str);
712         sv_free(status);
713
714         PUTBACK;
715         FREETMPS;
716         LEAVE;
717
718         return 0;
719 }
720
721 static SV *f_FacetField_to_SV(Z_FacetField *facet_field)
722 {
723         HV *hv;
724         AV *av;
725         SV *terms;
726         int i;
727         SV *sv = newObject("Net::Z3950::FacetField", (SV *) (hv = newHV()));
728         if (facet_field->attributes) {
729                 setMember(hv, "attributes",
730                      attributes2perl(facet_field->attributes));
731         }
732         terms = newObject("Net::Z3950::FacetTerms", (SV *) (av = newAV()));
733
734         for (i = 0; i < facet_field->num_terms; i++) {
735             Z_Term *z_term = facet_field->terms[i]->term;
736             HV *hv;
737             SV *sv_count = newSViv(*facet_field->terms[i]->count);
738             SV *sv_term;
739             SV *tmp;
740             if (z_term->which == Z_Term_general) {
741                 sv_term = newSVpv((char*) z_term->u.general->buf,
742                                    z_term->u.general->len);
743             } else if (z_term->which == Z_Term_characterString) {
744                 sv_term = newSVpv(z_term->u.characterString,
745                                   strlen(z_term->u.characterString));
746             }
747             tmp = newObject("Net::Z3950::FacetTerm", (SV *) (hv = newHV()));
748
749             setMember(hv, "count", sv_count);
750             setMember(hv, "term", sv_term);
751
752             av_push(av, tmp);
753         }
754         setMember(hv, "terms", terms);
755         return sv;
756 }
757
758 static SV *f_FacetList_to_SV(Z_FacetList *facet_list)
759 {
760         SV *sv = 0;
761         if (facet_list) {
762                 AV *av;
763                 int i;
764                 sv = newObject("Net::Z3950::FacetList", (SV *) (av = newAV()));
765
766                 for (i = 0; i < facet_list->num; i++) {
767                        SV *sv = f_FacetField_to_SV(facet_list->elements[i]);
768                        av_push(av, sv);
769                 }
770         }
771         return sv;
772 }
773
774
775 static void f_SV_to_FacetField(HV *facet_field_hv, Z_FacetField **fl, ODR odr)
776 {
777         int i;
778         int num_terms, num_attributes;
779         SV **temp;
780         Z_AttributeList *attributes = odr_malloc(odr, sizeof(*attributes));
781
782         AV *sv_terms, *sv_attributes;
783
784         temp = hv_fetch(facet_field_hv, "attributes", 10, 1);
785         sv_attributes = (AV *) SvRV(*temp);
786         num_attributes = av_len(sv_attributes) + 1;
787         attributes->num_attributes = num_attributes;
788         attributes->attributes = (Z_AttributeElement **)
789              odr_malloc(odr, sizeof(*attributes->attributes) * num_attributes);
790
791         for (i = 0; i < num_attributes; i++) {
792             HV *hv_elem = (HV*) SvRV(sv_2mortal(av_shift(sv_attributes)));
793             Z_AttributeElement *elem;
794             elem = (Z_AttributeElement *) odr_malloc(odr, sizeof(*elem));
795             attributes->attributes[i] = elem;
796
797             elem->attributeSet = 0;
798
799             temp = hv_fetch(hv_elem, "attributeType", 13, 1);
800             elem->attributeType = odr_intdup(odr, SvIV(*temp));
801
802             temp = hv_fetch(hv_elem, "attributeValue", 14, 1);
803
804             if (SvIOK(*temp)) {
805                     elem->which = Z_AttributeValue_numeric;
806                     elem->value.numeric = odr_intdup(odr, SvIV(*temp));
807             } else {
808                     STRLEN s_len;
809                     char *s_buf = SvPV(*temp, s_len);
810                     Z_ComplexAttribute *c = odr_malloc(odr, sizeof *c);
811                     elem->which = Z_AttributeValue_complex;
812                     elem->value.complex = c;
813
814                     c->num_list = 1;
815                     c->list = (Z_StringOrNumeric **) odr_malloc(odr,
816                           sizeof(*c->list));
817                     c->list[0] = (Z_StringOrNumeric *) odr_malloc(odr,
818                           sizeof(**c->list));
819                     c->list[0]->which = Z_StringOrNumeric_string;
820                     c->list[0]->u.string = odr_malloc(odr, s_len + 1);
821                     memcpy(c->list[0]->u.string, s_buf, s_len);
822                     c->list[0]->u.string[s_len] = '\0';
823                     c->num_semanticAction = 0;
824                     c->semanticAction = 0;
825             }
826             hv_undef(hv_elem);
827         }
828
829         temp = hv_fetch(facet_field_hv, "terms", 5, 1);
830
831         sv_terms = (AV *) SvRV(*temp);
832         if (SvTYPE(sv_terms) == SVt_PVAV) {
833             num_terms = av_len(sv_terms) + 1;
834         } else {
835             num_terms = 0;
836         }
837         *fl = facet_field_create(odr, attributes, num_terms);
838         for (i = 0; i < num_terms; i++) {
839             STRLEN s_len;
840             char *s_buf;
841             HV *hv_elem = (HV*) SvRV(sv_2mortal(av_shift(sv_terms)));
842
843             Z_FacetTerm *facet_term =
844              (Z_FacetTerm *) odr_malloc(odr, sizeof(*facet_term));
845             (*fl)->terms[i] = facet_term;
846
847             temp = hv_fetch(hv_elem, "count", 5, 1);
848             facet_term->count = odr_intdup(odr, SvIV(*temp));
849
850             temp = hv_fetch(hv_elem, "term", 4, 1);
851
852             s_buf = SvPV(*temp, s_len);
853             facet_term->term = z_Term_create(odr, Z_Term_general, s_buf, s_len);
854             hv_undef(hv_elem);
855         }
856 }
857
858 static void f_SV_to_FacetList(SV *sv, Z_OtherInformation **oip, ODR odr)
859 {
860         AV *entries = (AV *) SvRV(sv);
861         int num_facets;
862         if (entries && SvTYPE(entries) == SVt_PVAV &&
863                 (num_facets = av_len(entries) + 1) > 0)
864         {
865             Z_OtherInformation *oi;
866             Z_OtherInformationUnit *oiu;
867             Z_FacetList *facet_list = facet_list_create(odr, num_facets);
868             int i;
869             for (i = 0; i < num_facets; i++) {
870                 HV *facet_field = (HV*) SvRV(sv_2mortal(av_shift(entries)));
871                 f_SV_to_FacetField(facet_field, &facet_list->elements[i], odr);
872                 hv_undef(facet_field);
873             }
874             oi = odr_malloc(odr, sizeof(*oi));
875             oiu = odr_malloc(odr, sizeof(*oiu));
876             oi->num_elements = 1;
877             oi->list = odr_malloc(odr, oi->num_elements * sizeof(*oi->list));
878             oiu->category = 0;
879             oiu->which = Z_OtherInfo_externallyDefinedInfo;
880             oiu->information.externallyDefinedInfo = odr_malloc(odr, sizeof(*oiu->information.externallyDefinedInfo));
881             oiu->information.externallyDefinedInfo->direct_reference = odr_oiddup(odr, yaz_oid_userinfo_facet_1);
882             oiu->information.externallyDefinedInfo->descriptor = 0;
883             oiu->information.externallyDefinedInfo->indirect_reference = 0;
884             oiu->information.externallyDefinedInfo->which = Z_External_userFacets;
885             oiu->information.externallyDefinedInfo->u.facetList = facet_list;
886             oi->list[0] = oiu;
887             *oip = oi;
888         }
889 }
890
891 int bend_search(void *handle, bend_search_rr *rr)
892 {
893         HV *href;
894         AV *aref;
895         SV **temp;
896         int i;
897         char **basenames;
898         WRBUF query;
899         SV *point;
900         Zfront_handle *zhandle = (Zfront_handle *)handle;
901         CV* handler_cv = 0;
902         SV *rpnSV;
903         SV *facetSV;
904
905         dSP;
906         ENTER;
907         SAVETMPS;
908
909         aref = newAV();
910         basenames = rr->basenames;
911         for (i = 0; i < rr->num_bases; i++)
912         {
913                 av_push(aref, newSVpv(*basenames++, 0));
914         }
915 #if ENABLE_STOP_SERVER
916         if (rr->num_bases == 1 && !strcmp(rr->basenames[0], "XXstop"))
917         {
918                 zhandle->stop_flag = 1;
919         }
920 #endif
921         href = newHV();
922         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
923         if (rr->srw_sortKeys && *rr->srw_sortKeys)
924             hv_store(href, "SRW_SORTKEYS", 12, newSVpv(rr->srw_sortKeys, 0), 0);
925         hv_store(href, "REPL_SET", 8, newSViv(rr->replace_set), 0);
926         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
927         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
928         hv_store(href, "HITS", 4, newSViv(0), 0);
929         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
930         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
931         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
932         hv_store(href, "PID", 3, newSViv(getpid()), 0);
933         if ((rpnSV = zquery2perl(rr->query)) != 0) {
934             hv_store(href, "RPN", 3, rpnSV, 0);
935         }
936         facetSV = f_FacetList_to_SV(yaz_oi_get_facetlist(&rr->search_input));
937         if (facetSV) {
938             hv_store(href, "INPUTFACETS", 11, facetSV, 0);
939         }
940
941         query = zquery2pquery(rr->query);
942         if (query)
943         {
944                 hv_store(href, "QUERY", 5, newSVpv((char *)query->buf, query->pos), 0);
945         }
946         else if (rr->query->which == Z_Query_type_104 &&
947                  rr->query->u.type_104->which == Z_External_CQL) {
948             hv_store(href, "CQL", 3,
949                      newSVpv(rr->query->u.type_104->u.cql, 0), 0);
950         }
951         else
952         {
953                 rr->errcode = 108;
954                 return 0;
955         }
956         PUSHMARK(sp);
957
958         XPUSHs(sv_2mortal(newRV( (SV*) href)));
959
960         PUTBACK;
961
962         handler_cv = simpleserver_sv2cv( search_ref );
963         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
964
965         SPAGAIN;
966
967         temp = hv_fetch(href, "HITS", 4, 1);
968         rr->hits = SvIV(*temp);
969
970         temp = hv_fetch(href, "ERR_CODE", 8, 1);
971         rr->errcode = SvIV(*temp);
972
973         temp = hv_fetch(href, "ERR_STR", 7, 1);
974         rr->errstring = string_or_undef(temp, rr->stream);
975
976         temp = hv_fetch(href, "HANDLE", 6, 1);
977         point = newSVsv(*temp);
978
979         temp = hv_fetch(href, "OUTPUTFACETS", 12, 1);
980         if (SvTYPE(*temp) != SVt_NULL)
981             f_SV_to_FacetList(*temp, &rr->search_info, rr->stream);
982
983         hv_undef(href);
984         av_undef(aref);
985
986         zhandle->handle = point;
987         sv_free( (SV*) aref);
988         sv_free( (SV*) href);
989         if (query)
990             wrbuf_destroy(query);
991         PUTBACK;
992         FREETMPS;
993         LEAVE;
994         return 0;
995 }
996
997
998 /* ### I am not 100% about the memory management in this handler */
999 int bend_delete(void *handle, bend_delete_rr *rr)
1000 {
1001         Zfront_handle *zhandle = (Zfront_handle *)handle;
1002         HV *href;
1003         CV* handler_cv;
1004         int i;
1005         SV **temp;
1006         SV *point;
1007
1008         dSP;
1009         ENTER;
1010         SAVETMPS;
1011
1012         href = newHV();
1013         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1014         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1015         hv_store(href, "STATUS", 6, newSViv(0), 0);
1016
1017         PUSHMARK(sp);
1018         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1019         PUTBACK;
1020
1021         handler_cv = simpleserver_sv2cv(delete_ref);
1022
1023         if (rr->function == 1) {
1024             /* Delete all result sets in the session */
1025             perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1026             temp = hv_fetch(href, "STATUS", 6, 1);
1027             rr->delete_status = SvIV(*temp);
1028         } else {
1029             rr->delete_status = 0;
1030             /*
1031              * For some reason, deleting two or more result-sets in
1032              * one operation goes horribly wrong, and ### I don't have
1033              * time to debug it right now.
1034              */
1035             if (rr->num_setnames > 1) {
1036                 rr->delete_status = 3; /* "System problem at target" */
1037                 /* There's no way to sent delete-msg using the GFS */
1038                 return 0;
1039             }
1040
1041             for (i = 0; i < rr->num_setnames; i++) {
1042                 hv_store(href, "SETNAME", 7, newSVpv(rr->setnames[i], 0), 0);
1043                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1044                 temp = hv_fetch(href, "STATUS", 6, 1);
1045                 rr->statuses[i] = SvIV(*temp);
1046                 if (rr->statuses[i] != 0)
1047                     rr->delete_status = rr->statuses[i];
1048             }
1049         }
1050
1051         SPAGAIN;
1052
1053         temp = hv_fetch(href, "HANDLE", 6, 1);
1054         point = newSVsv(*temp);
1055
1056         hv_undef(href);
1057
1058         zhandle->handle = point;
1059
1060         sv_free( (SV*) href);
1061
1062         PUTBACK;
1063         FREETMPS;
1064         LEAVE;
1065
1066         return 0;
1067 }
1068
1069
1070 int bend_fetch(void *handle, bend_fetch_rr *rr)
1071 {
1072         HV *href;
1073         SV **temp;
1074         SV *basename;
1075         SV *record;
1076         SV *last;
1077         SV *err_code;
1078         SV *err_string;
1079         SV *sur_flag;
1080         SV *point;
1081         SV *rep_form;
1082         SV *schema = 0;
1083         char *ptr;
1084         char *ODR_record;
1085         char *ODR_basename;
1086         char *ODR_errstr;
1087         WRBUF oid_dotted;
1088         Zfront_handle *zhandle = (Zfront_handle *)handle;
1089         CV* handler_cv = 0;
1090
1091         Z_RecordComposition *composition;
1092         Z_ElementSetNames *simple;
1093         Z_CompSpec *complex;
1094         STRLEN length;
1095
1096         dSP;
1097         ENTER;
1098         SAVETMPS;
1099
1100         rr->errcode = 0;
1101         href = newHV();
1102         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
1103         if (rr->schema)
1104                 hv_store(href, "SCHEMA", 6, newSVpv(rr->schema, 0), 0);
1105         else
1106                 hv_store(href, "SCHEMA", 6, newSVpv("", 0), 0);
1107
1108         temp = hv_store(href, "OFFSET", 6, newSViv(rr->number), 0);
1109         if (rr->request_format != 0) {
1110             oid_dotted = oid2dotted(rr->request_format);
1111         } else {
1112             /* Probably an SRU request: assume XML is required */
1113             oid_dotted = wrbuf_alloc();
1114             wrbuf_puts(oid_dotted, "1.2.840.10003.5.109.10");
1115         }
1116         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
1117         hv_store(href, "REP_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
1118         hv_store(href, "BASENAME", 8, newSVpv("", 0), 0);
1119         hv_store(href, "RECORD", 6, newSVpv("", 0), 0);
1120         hv_store(href, "LAST", 4, newSViv(0), 0);
1121         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1122         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1123         hv_store(href, "SUR_FLAG", 8, newSViv(0), 0);
1124         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1125         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1126         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1127         if (rr->comp)
1128         {
1129                 composition = rr->comp;
1130                 if (composition->which == Z_RecordComp_simple)
1131                 {
1132                         simple = composition->u.simple;
1133                         if (simple->which == Z_ElementSetNames_generic)
1134                         {
1135                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
1136                         }
1137                         else
1138                         {
1139                                 rr->errcode = 26;
1140                                 rr->errstring = odr_strdup(rr->stream, "non-generic 'simple' composition");
1141                                 return 0;
1142                         }
1143                 }
1144                 else if (composition->which == Z_RecordComp_complex)
1145                 {
1146                         if (composition->u.complex->generic &&
1147
1148                                         composition->u.complex->generic &&
1149                                         composition->u.complex->generic->elementSpec &&
1150                                         composition->u.complex->generic->elementSpec->which ==
1151                                         Z_ElementSpec_elementSetName)
1152                         {
1153                                 complex = composition->u.complex;
1154                                 hv_store(href, "COMP", 4,
1155                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
1156                         }
1157                         else
1158                         {
1159 #if 0   /* For now ignore this error, which is ubiquitous in SRU */
1160                                 rr->errcode = 26;
1161                                 rr->errstring = odr_strdup(rr->stream, "'complex' composition is not generic ESN");
1162                                 return 0;
1163 #endif /*0*/
1164                         }
1165                 }
1166                 else
1167                 {
1168                         rr->errcode = 26;
1169                         rr->errstring = odr_strdup(rr->stream, "composition neither simple nor complex");
1170                         return 0;
1171                 }
1172         }
1173
1174         PUSHMARK(sp);
1175
1176         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1177
1178         PUTBACK;
1179
1180         handler_cv = simpleserver_sv2cv( fetch_ref );
1181         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1182
1183         SPAGAIN;
1184
1185         temp = hv_fetch(href, "BASENAME", 8, 1);
1186         basename = newSVsv(*temp);
1187
1188         temp = hv_fetch(href, "RECORD", 6, 1);
1189         record = newSVsv(*temp);
1190
1191         temp = hv_fetch(href, "LAST", 4, 1);
1192         last = newSVsv(*temp);
1193
1194         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1195         err_code = newSVsv(*temp);
1196
1197         temp = hv_fetch(href, "ERR_STR", 7, 1),
1198         err_string = newSVsv(*temp);
1199
1200         temp = hv_fetch(href, "SUR_FLAG", 8, 1);
1201         sur_flag = newSVsv(*temp);
1202
1203         temp = hv_fetch(href, "REP_FORM", 8, 1);
1204         rep_form = newSVsv(*temp);
1205
1206         temp = hv_fetch(href, "SCHEMA", 6, 1);
1207         if (temp != 0) {
1208                 schema = newSVsv(*temp);
1209                 ptr = SvPV(schema, length);
1210                 if (length > 0) {
1211                         rr->schema = (char *)odr_malloc(rr->stream, length + 1);
1212                         strcpy(rr->schema, ptr);
1213                 }
1214         }
1215
1216         temp = hv_fetch(href, "HANDLE", 6, 1);
1217         point = newSVsv(*temp);
1218
1219
1220         hv_undef(href);
1221
1222         ptr = SvPV(basename, length);
1223         ODR_basename = (char *)odr_malloc(rr->stream, length + 1);
1224         strcpy(ODR_basename, ptr);
1225         rr->basename = ODR_basename;
1226
1227         ptr = SvPV(rep_form, length);
1228
1229         rr->output_format = yaz_string_to_oid_odr(yaz_oid_std(),
1230                                         CLASS_RECSYN, ptr, rr->stream);
1231         if (!rr->output_format)
1232         {
1233                 printf("Net::Z3950::SimpleServer: WARNING: Bad OID %s\n", ptr);
1234                 rr->output_format =
1235                         odr_oiddup(rr->stream, yaz_oid_recsyn_sutrs);
1236         }
1237         ptr = SvPV(record, length);
1238         /* Treat GRS-1 records separately */
1239         if (!oid_oidcmp(rr->output_format, yaz_oid_recsyn_grs_1))
1240         {
1241                 rr->record = (char *) read_grs1(ptr, rr->stream);
1242                 rr->len = -1;
1243         }
1244         else
1245         {
1246                 ODR_record = (char *)odr_malloc(rr->stream, length + 1);
1247                 strcpy(ODR_record, ptr);
1248                 rr->record = ODR_record;
1249                 rr->len = length;
1250         }
1251         zhandle->handle = point;
1252         handle = zhandle;
1253         rr->last_in_set = SvIV(last);
1254
1255         if (!(rr->errcode))
1256         {
1257                 rr->errcode = SvIV(err_code);
1258                 ptr = SvPV(err_string, length);
1259                 ODR_errstr = (char *)odr_malloc(rr->stream, length + 1);
1260                 strcpy(ODR_errstr, ptr);
1261                 rr->errstring = ODR_errstr;
1262         }
1263         rr->surrogate_flag = SvIV(sur_flag);
1264
1265         wrbuf_destroy(oid_dotted);
1266         sv_free((SV*) href);
1267         sv_free(basename);
1268         sv_free(record);
1269         sv_free(last);
1270         sv_free(err_string);
1271         sv_free(err_code),
1272         sv_free(sur_flag);
1273         sv_free(rep_form);
1274
1275         if (schema)
1276                 sv_free(schema);
1277
1278         PUTBACK;
1279         FREETMPS;
1280         LEAVE;
1281
1282         return 0;
1283 }
1284
1285
1286 int bend_present(void *handle, bend_present_rr *rr)
1287 {
1288         HV *href;
1289         SV **temp;
1290         SV *err_code;
1291         SV *err_string;
1292         SV *point;
1293         STRLEN len;
1294         Z_RecordComposition *composition;
1295         Z_ElementSetNames *simple;
1296         Z_CompSpec *complex;
1297         char *ODR_errstr;
1298         char *ptr;
1299         Zfront_handle *zhandle = (Zfront_handle *)handle;
1300         CV* handler_cv = 0;
1301
1302 /*      WRBUF oid_dotted; */
1303
1304         dSP;
1305         ENTER;
1306         SAVETMPS;
1307
1308         href = newHV();
1309         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1310         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1311         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1312         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1313         hv_store(href, "START", 5, newSViv(rr->start), 0);
1314         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
1315         hv_store(href, "NUMBER", 6, newSViv(rr->number), 0);
1316         /*oid_dotted = oid2dotted(rr->request_format_raw);
1317         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);*/
1318         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1319         if (rr->comp)
1320         {
1321                 composition = rr->comp;
1322                 if (composition->which == Z_RecordComp_simple)
1323                 {
1324                         simple = composition->u.simple;
1325                         if (simple->which == Z_ElementSetNames_generic)
1326                         {
1327                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
1328                         }
1329                         else
1330                         {
1331                                 rr->errcode = 26;
1332                                 rr->errstring = odr_strdup(rr->stream, "non-generic 'simple' composition");
1333                                 return 0;
1334                         }
1335                 }
1336                 else if (composition->which == Z_RecordComp_complex)
1337                 {
1338                         if (composition->u.complex->generic &&
1339
1340                                         composition->u.complex->generic &&
1341                                         composition->u.complex->generic->elementSpec &&
1342                                         composition->u.complex->generic->elementSpec->which ==
1343                                         Z_ElementSpec_elementSetName)
1344                         {
1345                                 complex = composition->u.complex;
1346                                 hv_store(href, "COMP", 4,
1347                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
1348                         }
1349                         else
1350                         {
1351                                 rr->errcode = 26;
1352                                 rr->errstring = odr_strdup(rr->stream, "'complex' composition is not generic ESN");
1353                                 return 0;
1354                         }
1355                 }
1356                 else
1357                 {
1358                         rr->errcode = 26;
1359                         rr->errstring = odr_strdup(rr->stream, "composition neither simple nor complex");
1360                         return 0;
1361                 }
1362         }
1363
1364         PUSHMARK(sp);
1365
1366         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1367
1368         PUTBACK;
1369
1370         handler_cv = simpleserver_sv2cv( present_ref );
1371         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1372
1373         SPAGAIN;
1374
1375         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1376         err_code = newSVsv(*temp);
1377
1378         temp = hv_fetch(href, "ERR_STR", 7, 1);
1379         err_string = newSVsv(*temp);
1380
1381         temp = hv_fetch(href, "HANDLE", 6, 1);
1382         point = newSVsv(*temp);
1383
1384         PUTBACK;
1385         FREETMPS;
1386         LEAVE;
1387
1388         hv_undef(href);
1389         rr->errcode = SvIV(err_code);
1390
1391         ptr = SvPV(err_string, len);
1392         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1393         strcpy(ODR_errstr, ptr);
1394         rr->errstring = ODR_errstr;
1395 /*      wrbuf_free(oid_dotted, 1);*/
1396         zhandle->handle = point;
1397         handle = zhandle;
1398         sv_free(err_code);
1399         sv_free(err_string);
1400         sv_free( (SV*) href);
1401
1402         return 0;
1403 }
1404
1405
1406 int bend_esrequest(void *handle, bend_esrequest_rr *rr)
1407 {
1408         perl_call_sv(esrequest_ref, G_VOID | G_DISCARD | G_NOARGS);
1409         return 0;
1410 }
1411
1412
1413 int bend_scan(void *handle, bend_scan_rr *rr)
1414 {
1415         HV *href;
1416         AV *aref;
1417         AV *list;
1418         AV *entries;
1419         HV *scan_item;
1420         struct scan_entry *scan_list;
1421         struct scan_entry *buffer;
1422         int *step_size = rr->step_size;
1423         int i;
1424         char **basenames;
1425         SV **temp;
1426         SV *err_code = sv_newmortal();
1427         SV *err_str = sv_newmortal();
1428         SV *point = sv_newmortal();
1429         SV *status = sv_newmortal();
1430         SV *number = sv_newmortal();
1431         char *ptr;
1432         char *ODR_errstr;
1433         STRLEN len;
1434         int term_len;
1435         SV *entries_ref;
1436         Zfront_handle *zhandle = (Zfront_handle *)handle;
1437         CV* handler_cv = 0;
1438         SV *rpnSV;
1439
1440         dSP;
1441         ENTER;
1442         SAVETMPS;
1443         href = newHV();
1444         list = newAV();
1445
1446         /* RPN is better than TERM since it includes attributes */
1447         if ((rpnSV = f_Term_to_SV(rr->term->term, rr->term->attributes)) != 0) {
1448             setMember(href, "RPN", rpnSV);
1449         }
1450
1451         if (rr->term->term->which == Z_Term_general)
1452         {
1453                 term_len = rr->term->term->u.general->len;
1454                 hv_store(href, "TERM", 4, newSVpv((char*) rr->term->term->u.general->buf, term_len), 0);
1455         } else {
1456                 rr->errcode = 229;      /* Unsupported term type */
1457                 return 0;
1458         }
1459         hv_store(href, "STEP", 4, newSViv(*step_size), 0);
1460         hv_store(href, "NUMBER", 6, newSViv(rr->num_entries), 0);
1461         hv_store(href, "POS", 3, newSViv(rr->term_position), 0);
1462         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1463         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1464         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1465         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1466         hv_store(href, "STATUS", 6, newSViv(BEND_SCAN_SUCCESS), 0);
1467         hv_store(href, "ENTRIES", 7, newRV((SV *) list), 0);
1468         aref = newAV();
1469         basenames = rr->basenames;
1470         for (i = 0; i < rr->num_bases; i++)
1471         {
1472                 av_push(aref, newSVpv(*basenames++, 0));
1473         }
1474         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
1475
1476         PUSHMARK(sp);
1477
1478         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1479
1480         PUTBACK;
1481
1482         handler_cv = simpleserver_sv2cv( scan_ref );
1483         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1484
1485         SPAGAIN;
1486
1487         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1488         err_code = newSVsv(*temp);
1489
1490         temp = hv_fetch(href, "ERR_STR", 7, 1);
1491         err_str = newSVsv(*temp);
1492
1493         temp = hv_fetch(href, "HANDLE", 6, 1);
1494         point = newSVsv(*temp);
1495
1496         temp = hv_fetch(href, "STATUS", 6, 1);
1497         status = newSVsv(*temp);
1498
1499         temp = hv_fetch(href, "NUMBER", 6, 1);
1500         number = newSVsv(*temp);
1501
1502         temp = hv_fetch(href, "ENTRIES", 7, 1);
1503         entries_ref = newSVsv(*temp);
1504
1505         PUTBACK;
1506         FREETMPS;
1507         LEAVE;
1508
1509         ptr = SvPV(err_str, len);
1510         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1511         strcpy(ODR_errstr, ptr);
1512         rr->errstring = ODR_errstr;
1513         rr->errcode = SvIV(err_code);
1514         rr->num_entries = SvIV(number);
1515         rr->status = SvIV(status);
1516         scan_list = (struct scan_entry *) odr_malloc (rr->stream, rr->num_entries * sizeof(*scan_list));
1517         buffer = scan_list;
1518         entries = (AV *)SvRV(entries_ref);
1519         if (rr->errcode == 0) for (i = 0; i < rr->num_entries; i++)
1520         {
1521                 scan_item = (HV *)SvRV(sv_2mortal(av_shift(entries)));
1522                 temp = hv_fetch(scan_item, "TERM", 4, 1);
1523                 ptr = SvPV(*temp, len);
1524                 buffer->term = (char *) odr_malloc (rr->stream, len + 1);
1525                 strcpy(buffer->term, ptr);
1526                 temp = hv_fetch(scan_item, "OCCURRENCE", 10, 1);
1527                 buffer->occurrences = SvIV(*temp);
1528                 buffer++;
1529                 hv_undef(scan_item);
1530         }
1531         rr->entries = scan_list;
1532         zhandle->handle = point;
1533         handle = zhandle;
1534         sv_free(err_code);
1535         sv_free(err_str);
1536         sv_free(status);
1537         sv_free(number);
1538         hv_undef(href);
1539         sv_free((SV *)href);
1540         av_undef(aref);
1541         sv_free((SV *)aref);
1542         av_undef(list);
1543         sv_free((SV *)list);
1544         av_undef(entries);
1545         /*sv_free((SV *)entries);*/
1546         sv_free(entries_ref);
1547
1548         return 0;
1549 }
1550
1551 int bend_explain(void *handle, bend_explain_rr *q)
1552 {
1553         HV *href;
1554         CV *handler_cv = 0;
1555         SV **temp;
1556         char *explain;
1557         SV *explainsv;
1558         STRLEN len;
1559         Zfront_handle *zhandle = (Zfront_handle *)handle;
1560
1561         dSP;
1562         ENTER;
1563         SAVETMPS;
1564
1565         href = newHV();
1566         hv_store(href, "EXPLAIN", 7, newSVpv("", 0), 0);
1567         hv_store(href, "DATABASE", 8, newSVpv(q->database, 0), 0);
1568         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1569         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1570
1571         PUSHMARK(sp);
1572         XPUSHs(sv_2mortal(newRV((SV*) href)));
1573         PUTBACK;
1574
1575         handler_cv = simpleserver_sv2cv(explain_ref);
1576         perl_call_sv((SV*) handler_cv, G_SCALAR | G_DISCARD);
1577
1578         SPAGAIN;
1579
1580         temp = hv_fetch(href, "EXPLAIN", 7, 1);
1581         explainsv = newSVsv(*temp);
1582
1583         PUTBACK;
1584         FREETMPS;
1585         LEAVE;
1586
1587         explain = SvPV(explainsv, len);
1588         q->explain_buf = (char*) odr_malloc(q->stream, len + 1);
1589         strcpy(q->explain_buf, explain);
1590
1591         return 0;
1592 }
1593
1594
1595 /*
1596  * You'll laugh when I tell you this ...  Astonishingly, it turns out
1597  * that ActivePerl (which is widely used on Windows) has, in the
1598  * header file Perl\lib\CORE\XSUB.h, the following heinous crime:
1599  *          #    define open            PerlLIO_open
1600  * This of course screws up the use of the "open" member of the
1601  * Z_IdAuthentication structure below, so we have to undo this
1602  * brain-damage.
1603  */
1604 #ifdef open
1605 #undef open
1606 #endif
1607
1608
1609 bend_initresult *bend_init(bend_initrequest *q)
1610 {
1611         int dummy = simpleserver_clone();
1612         bend_initresult *r = (bend_initresult *)
1613                 odr_malloc (q->stream, sizeof(*r));
1614         char *ptr;
1615         CV* handler_cv = 0;
1616         dSP;
1617         STRLEN len;
1618         NMEM nmem = nmem_create();
1619         Zfront_handle *zhandle =  (Zfront_handle *) nmem_malloc (nmem,
1620                         sizeof(*zhandle));
1621         SV *handle;
1622         HV *href;
1623         SV **temp;
1624
1625         ENTER;
1626         SAVETMPS;
1627
1628         zhandle->ghandle = _global_ghandle;
1629         zhandle->nmem = nmem;
1630         zhandle->stop_flag = 0;
1631
1632         if (sort_ref)
1633         {
1634             q->bend_sort = bend_sort;
1635         }
1636         if (search_ref)
1637         {
1638                 q->bend_search = bend_search;
1639         }
1640         if (present_ref)
1641         {
1642                 q->bend_present = bend_present;
1643         }
1644         /*q->bend_esrequest = bend_esrequest;*/
1645         if (delete_ref) {
1646                 q->bend_delete = bend_delete;
1647         }
1648         if (fetch_ref)
1649         {
1650                 q->bend_fetch = bend_fetch;
1651         }
1652         if (scan_ref)
1653         {
1654                 q->bend_scan = bend_scan;
1655         }
1656         if (explain_ref)
1657         {
1658                 q->bend_explain = bend_explain;
1659         }
1660
1661         href = newHV();
1662
1663         /* ### These should be given initial values from the client */
1664         hv_store(href, "IMP_ID", 6, newSVpv("", 0), 0);
1665         hv_store(href, "IMP_NAME", 8, newSVpv("", 0), 0);
1666         hv_store(href, "IMP_VER", 7, newSVpv("", 0), 0);
1667
1668         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1669         hv_store(href, "ERR_STR", 7, newSViv(0), 0);
1670         hv_store(href, "PEER_NAME", 9, newSVpv(q->peer_name, 0), 0);
1671         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1672         hv_store(href, "HANDLE", 6, newSVsv(&sv_undef), 0);
1673         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1674         if (q->auth) {
1675             char *user = NULL;
1676             char *passwd = NULL;
1677             if (q->auth->which == Z_IdAuthentication_open) {
1678                 char *cp;
1679                 user = nmem_strdup (odr_getmem (q->stream), q->auth->u.open);
1680                 cp = strchr (user, '/');
1681                 if (cp) {
1682                     /* password after / given */
1683                     *cp = '\0';
1684                     passwd = cp+1;
1685                 }
1686             } else if (q->auth->which == Z_IdAuthentication_idPass) {
1687                 user = q->auth->u.idPass->userId;
1688                 passwd = q->auth->u.idPass->password;
1689             }
1690             /* ### some code paths have user/password unassigned here */
1691             if (user)
1692                 hv_store(href, "USER", 4, newSVpv(user, 0), 0);
1693             if (passwd)
1694                 hv_store(href, "PASS", 4, newSVpv(passwd, 0), 0);
1695         }
1696
1697         PUSHMARK(sp);
1698
1699         XPUSHs(sv_2mortal(newRV((SV*) href)));
1700
1701         PUTBACK;
1702
1703         if (init_ref != NULL)
1704         {
1705              handler_cv = simpleserver_sv2cv( init_ref );
1706              perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1707         }
1708
1709         SPAGAIN;
1710
1711         temp = hv_fetch(href, "IMP_ID", 6, 1);
1712         ptr = SvPV(*temp, len);
1713         q->implementation_id = nmem_strdup(nmem, ptr);
1714
1715         temp = hv_fetch(href, "IMP_NAME", 8, 1);
1716         ptr = SvPV(*temp, len);
1717         q->implementation_name = nmem_strdup(nmem, ptr);
1718
1719         temp = hv_fetch(href, "IMP_VER", 7, 1);
1720         ptr = SvPV(*temp, len);
1721         q->implementation_version = nmem_strdup(nmem, ptr);
1722
1723         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1724         r->errcode = SvIV(*temp);
1725
1726         temp = hv_fetch(href, "ERR_STR", 7, 1);
1727         ptr = SvPV(*temp, len);
1728         r->errstring = (char *)odr_malloc(q->stream, len + 1);
1729         strcpy(r->errstring, ptr);
1730
1731         temp = hv_fetch(href, "HANDLE", 6, 1);
1732         handle= newSVsv(*temp);
1733         zhandle->handle = handle;
1734
1735         r->handle = zhandle;
1736
1737         hv_undef(href);
1738         sv_free((SV*) href);
1739
1740         PUTBACK;
1741         FREETMPS;
1742         LEAVE;
1743
1744         return r;
1745 }
1746
1747 void bend_close(void *handle)
1748 {
1749         HV *href;
1750         Zfront_handle *zhandle = (Zfront_handle *)handle;
1751         CV* handler_cv = 0;
1752         int stop_flag = 0;
1753         dSP;
1754         ENTER;
1755         SAVETMPS;
1756
1757         if (close_ref)
1758         {
1759                 href = newHV();
1760                 hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1761                 hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1762
1763                 PUSHMARK(sp);
1764
1765                 XPUSHs(sv_2mortal(newRV((SV *)href)));
1766
1767                 PUTBACK;
1768
1769                 handler_cv = simpleserver_sv2cv( close_ref );
1770                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1771
1772                 SPAGAIN;
1773
1774                 sv_free((SV*) href);
1775         }
1776         else
1777                 sv_free(zhandle->handle);
1778         PUTBACK;
1779         FREETMPS;
1780         LEAVE;
1781         stop_flag = zhandle->stop_flag;
1782         nmem_destroy(zhandle->nmem);
1783         simpleserver_free();
1784
1785         if (stop_flag)
1786                 exit(0);
1787         return;
1788 }
1789
1790 static void start_stop(struct statserv_options_block *sob, SV *handler_ref)
1791 {
1792         HV *href;
1793         dSP;
1794         ENTER;
1795         SAVETMPS;
1796
1797         href = newHV();
1798         hv_store(href, "CONFIG", 6, newSVpv(sob->configname, 0), 0);
1799
1800         PUSHMARK(sp);
1801
1802         XPUSHs(sv_2mortal(newRV((SV*) href)));
1803
1804         PUTBACK;
1805
1806         if (handler_ref != NULL)
1807         {
1808                 CV* handler_cv = simpleserver_sv2cv( handler_ref );
1809                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1810         }
1811
1812         SPAGAIN;
1813
1814         PUTBACK;
1815         FREETMPS;
1816         LEAVE;
1817
1818
1819 }
1820
1821 void bend_start(struct statserv_options_block *sob)
1822 {
1823         start_stop(sob, start_ref);
1824 }
1825
1826 MODULE = Net::Z3950::SimpleServer       PACKAGE = Net::Z3950::SimpleServer
1827
1828 PROTOTYPES: DISABLE
1829
1830
1831 void
1832 set_ghandle(arg)
1833                 SV *arg
1834         CODE:
1835                 _global_ghandle = newSVsv(arg);
1836
1837
1838 void
1839 set_init_handler(arg)
1840                 SV *arg
1841         CODE:
1842                 init_ref = newSVsv(arg);
1843
1844
1845 void
1846 set_close_handler(arg)
1847                 SV *arg
1848         CODE:
1849                 close_ref = newSVsv(arg);
1850
1851
1852 void
1853 set_sort_handler(arg)
1854                 SV *arg
1855         CODE:
1856                 sort_ref = newSVsv(arg);
1857
1858 void
1859 set_search_handler(arg)
1860                 SV *arg
1861         CODE:
1862                 search_ref = newSVsv(arg);
1863
1864
1865 void
1866 set_fetch_handler(arg)
1867                 SV *arg
1868         CODE:
1869                 fetch_ref = newSVsv(arg);
1870
1871
1872 void
1873 set_present_handler(arg)
1874                 SV *arg
1875         CODE:
1876                 present_ref = newSVsv(arg);
1877
1878
1879 void
1880 set_esrequest_handler(arg)
1881                 SV *arg
1882         CODE:
1883                 esrequest_ref = newSVsv(arg);
1884
1885
1886 void
1887 set_delete_handler(arg)
1888                 SV *arg
1889         CODE:
1890                 delete_ref = newSVsv(arg);
1891
1892
1893 void
1894 set_scan_handler(arg)
1895                 SV *arg
1896         CODE:
1897                 scan_ref = newSVsv(arg);
1898
1899 void
1900 set_explain_handler(arg)
1901                 SV *arg
1902         CODE:
1903                 explain_ref = newSVsv(arg);
1904
1905 void
1906 set_start_handler(arg)
1907                 SV *arg
1908         CODE:
1909                 start_ref = newSVsv(arg);
1910
1911 int
1912 start_server(...)
1913         PREINIT:
1914                 char **argv;
1915                 char **argv_buf;
1916                 char *ptr;
1917                 int i;
1918                 STRLEN len;
1919                 struct statserv_options_block *sob;
1920         CODE:
1921                 argv_buf = (char **)xmalloc((items + 1) * sizeof(char *));
1922                 argv = argv_buf;
1923                 for (i = 0; i < items; i++)
1924                 {
1925                         ptr = SvPV(ST(i), len);
1926                         *argv_buf = (char *)xmalloc(len + 1);
1927                         strcpy(*argv_buf++, ptr);
1928                 }
1929                 *argv_buf = NULL;
1930
1931                 sob = statserv_getcontrol();
1932                 sob->bend_start = bend_start;
1933                 statserv_setcontrol(sob);
1934
1935                 root_perl_context = PERL_GET_CONTEXT;
1936                 yaz_mutex_create(&simpleserver_mutex);
1937 #if 0
1938                 /* only for debugging perl_clone .. */
1939                 tst_clones();
1940 #endif
1941
1942                 RETVAL = statserv_main(items, argv, bend_init, bend_close);
1943         OUTPUT:
1944                 RETVAL
1945
1946
1947 int
1948 ScanSuccess()
1949         CODE:
1950                 RETVAL = BEND_SCAN_SUCCESS;
1951         OUTPUT:
1952                 RETVAL
1953
1954 int
1955 ScanPartial()
1956         CODE:
1957                 RETVAL = BEND_SCAN_PARTIAL;
1958         OUTPUT:
1959                 RETVAL
1960
1961
1962 void
1963 yazlog(arg)
1964                 SV *arg
1965         CODE:
1966                 STRLEN len;
1967                 char *ptr;
1968                 ptr = SvPV(arg, len);
1969                 yaz_log(YLOG_LOG, "%.*s", (int) len, ptr);
1970
1971 int
1972 yaz_diag_srw_to_bib1(srw_code)
1973         int srw_code
1974
1975 int
1976 yaz_diag_bib1_to_srw(bib1_code)
1977         int bib1_code
1978