Merge branch 'master' of ssh://git.indexdata.com/home/git/pub/simpleserver
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /* This file is part of simpleserver.
2  * Copyright (C) 2000-2011 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 #if 0
63 /* ### These callback-reference elements are never used! */
64         SV *init_ref;
65         SV *close_ref;
66         SV *sort_ref;
67         SV *search_ref;
68         SV *fetch_ref;
69         SV *present_ref;
70         SV *esrequest_ref;
71         SV *delete_ref;
72         SV *scan_ref;
73         SV *explain_ref;
74 #endif /*0*/
75         NMEM nmem;
76         int stop_flag;  /* is used to stop server prematurely .. */
77 } Zfront_handle;
78
79 #define ENABLE_STOP_SERVER 0
80
81 SV *_global_ghandle = NULL; /* To be copied into zhandle then ignored */
82 SV *init_ref = NULL;
83 SV *close_ref = NULL;
84 SV *sort_ref = NULL;
85 SV *search_ref = NULL;
86 SV *fetch_ref = NULL;
87 SV *present_ref = NULL;
88 SV *esrequest_ref = NULL;
89 SV *delete_ref = NULL;
90 SV *scan_ref = NULL;
91 SV *explain_ref = NULL;
92 PerlInterpreter *root_perl_context;
93
94 #define GRS_BUF_SIZE 8192
95
96
97 /*
98  * Inspects the SV indicated by svp, and returns a null pointer if
99  * it's an undefined value, or a string allocation from `stream'
100  * otherwise.  Using this when filling in addinfo avoids those
101  * irritating "Use of uninitialized value in subroutine entry"
102  * warnings from Perl.
103  */
104 char *string_or_undef(SV **svp, ODR stream) {
105         STRLEN len;
106         char *ptr, *buf;
107
108         if (!SvOK(*svp))
109                 return 0;
110
111         ptr = SvPV(*svp, len);
112         buf = (char*) odr_malloc(stream, len+1);
113         strcpy(buf, ptr);
114         return buf;
115 }
116
117
118 CV * simpleserver_sv2cv(SV *handler) {
119     STRLEN len;
120     char *buf;
121    
122     if (SvPOK(handler)) {
123         CV *ret;
124         buf = SvPV( handler, len);
125         if ( !( ret = perl_get_cv(buf, FALSE ) ) ) {
126             fprintf( stderr, "simpleserver_sv2cv: No such handler '%s'\n\n", buf );
127             exit(1);
128         }
129         
130         return ret;
131     } else {
132         return (CV *) handler;
133     }
134 }
135
136 /* debugging routine to check for destruction of Perl interpreters */
137 #ifdef USE_ITHREADS
138 void tst_clones(void)
139 {
140     int i; 
141     PerlInterpreter *parent = PERL_GET_CONTEXT;
142     for (i = 0; i<5000; i++)
143     {
144         PerlInterpreter *perl_interp;
145
146         PERL_SET_CONTEXT(parent);
147         PL_perl_destruct_level = 2;
148         perl_interp = perl_clone(parent, CLONEf_CLONE_HOST);
149         PL_perl_destruct_level = 2;
150         PERL_SET_CONTEXT(perl_interp);
151         perl_destruct(perl_interp);
152         perl_free(perl_interp);
153     }
154     exit (0);
155 }
156 #endif
157
158 int simpleserver_clone(void) {
159 #ifdef USE_ITHREADS
160      yaz_mutex_enter(simpleserver_mutex);
161      if (1)
162      {
163          PerlInterpreter *current = PERL_GET_CONTEXT;
164
165          /* if current is unset, then we're in a new thread with
166           * no Perl interpreter for it. So we must create one .
167           * This will only happen when threaded is used..
168           */
169          if (!current) {
170              PerlInterpreter *perl_interp;
171              PERL_SET_CONTEXT( root_perl_context );
172              perl_interp = perl_clone(root_perl_context, CLONEf_CLONE_HOST);
173              PERL_SET_CONTEXT( perl_interp );
174          }
175      }
176      yaz_mutex_leave(simpleserver_mutex);
177 #endif
178      return 0;
179 }
180
181
182 void simpleserver_free(void) {
183     yaz_mutex_enter(simpleserver_mutex);
184     if (1)
185     {
186         PerlInterpreter *current_interp = PERL_GET_CONTEXT;
187
188         /* If current Perl Interp is different from root interp, then
189          * we're in threaded mode and we must destroy.. 
190          */
191         if (current_interp != root_perl_context) {
192             PL_perl_destruct_level = 2;
193             PERL_SET_CONTEXT(current_interp);
194             perl_destruct(current_interp);
195             perl_free(current_interp);
196         }
197     }
198     yaz_mutex_leave(simpleserver_mutex);
199 }
200
201
202 Z_GenericRecord *read_grs1(char *str, ODR o)
203 {
204         int type, ivalue;
205         char line[GRS_BUF_SIZE+1], *buf, *ptr, *original;
206         char value[GRS_BUF_SIZE+1];
207         Z_GenericRecord *r = 0;
208
209         original = str;
210         r = (Z_GenericRecord *)odr_malloc(o, sizeof(*r));
211         r->elements = (Z_TaggedElement **) odr_malloc(o, sizeof(Z_TaggedElement*) * GRS_MAX_FIELDS);
212         r->num_elements = 0;
213         
214         for (;;)
215         {
216                 Z_TaggedElement *t;
217                 Z_ElementData *c;
218                 int len;
219         
220                 ptr = strchr(str, '\n');
221                 if (!ptr) {
222                         return r;
223                 }
224                 len = ptr - str;
225                 if (len > GRS_BUF_SIZE) {
226                     yaz_log(YLOG_WARN, "GRS string too long - truncating (%d > %d)", len, GRS_BUF_SIZE);
227                     len = GRS_BUF_SIZE;
228                 }
229                 strncpy(line, str, len);
230                 line[len] = 0;
231                 buf = line;
232                 str = ptr + 1;
233                 while (*buf && isspace(*buf))
234                         buf++;
235                 if (*buf == '}') {
236                         memmove(original, str, strlen(str));
237                         return r;
238                 }
239                 if (sscanf(buf, "(%d,%[^)])", &type, value) != 2)
240                 {
241                         yaz_log(YLOG_WARN, "Bad data in '%s'", buf);
242                         return r;
243                 }
244                 if (!type && *value == '0')
245                         return r;
246                 if (!(buf = strchr(buf, ')')))
247                         return r;
248                 buf++;
249                 while (*buf && isspace(*buf))
250                         buf++;
251                 if (r->num_elements >= GRS_MAX_FIELDS)
252                 {
253                         yaz_log(YLOG_WARN, "Max number of GRS-1 elements exceeded [GRS_MAX_FIELDS=%d]", GRS_MAX_FIELDS);
254                         exit(0);
255                 }
256                 r->elements[r->num_elements] = t = (Z_TaggedElement *) odr_malloc(o, sizeof(Z_TaggedElement));
257                 t->tagType = odr_intdup(o, type);
258                 t->tagValue = (Z_StringOrNumeric *)
259                         odr_malloc(o, sizeof(Z_StringOrNumeric));
260                 if ((ivalue = atoi(value)))
261                 {
262                         t->tagValue->which = Z_StringOrNumeric_numeric;
263                         t->tagValue->u.numeric = odr_intdup(o, ivalue);
264                 }
265                 else
266                 {
267                         t->tagValue->which = Z_StringOrNumeric_string;
268                         t->tagValue->u.string = odr_strdup(o, value);
269                 }
270                 t->tagOccurrence = 0;
271                 t->metaData = 0;
272                 t->appliedVariant = 0;
273                 t->content = c = (Z_ElementData *)odr_malloc(o, sizeof(Z_ElementData));
274                 if (*buf == '{')
275                 {
276                         c->which = Z_ElementData_subtree;
277                         c->u.subtree = read_grs1(str, o);
278                 }
279                 else
280                 {
281                         c->which = Z_ElementData_string;
282                         c->u.string = odr_strdup(o, buf);
283                 }
284                 r->num_elements++;
285         }
286 }
287
288
289
290 static void oid2str(Odr_oid *o, WRBUF buf)
291 {
292     for (; *o >= 0; o++) {
293         char ibuf[16];
294         sprintf(ibuf, "%d", *o);
295         wrbuf_puts(buf, ibuf);
296         if (o[1] > 0)
297             wrbuf_putc(buf, '.');
298     }
299 }
300
301 WRBUF oid2dotted(Odr_oid *oid)
302 {
303     WRBUF buf = wrbuf_alloc();
304     oid2str(oid, buf);
305     return buf;
306 }
307                 
308
309 WRBUF zquery2pquery(Z_Query *q)
310 {
311     WRBUF buf = wrbuf_alloc();
312
313     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
314         return 0;
315     yaz_rpnquery_to_wrbuf(buf, q->u.type_1);
316     return buf;
317 }
318
319
320 /* Lifted verbatim from Net::Z3950 yazwrap/util.c */
321 #include <stdarg.h>
322 void fatal(char *fmt, ...)
323 {
324     va_list ap;
325
326     fprintf(stderr, "FATAL (SimpleServer): ");
327     va_start(ap, fmt);
328     vfprintf(stderr, fmt, ap);
329     va_end(ap);
330     fprintf(stderr, "\n");
331     abort();
332 }
333
334
335 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
336 /*
337  * Creates a new Perl object of type `class'; the newly-created scalar
338  * that is a reference to the blessed thingy `referent' is returned.
339  */
340 static SV *newObject(char *class, SV *referent)
341 {
342     HV *stash;
343     SV *sv;
344
345     sv = newRV_noinc((SV*) referent);
346     stash = gv_stashpv(class, 0);
347     if (stash == 0)
348         fatal("attempt to create object of undefined class '%s'", class);
349     /*assert(stash != 0);*/
350     sv_bless(sv, stash);
351     return sv;
352 }
353
354
355 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
356 static void setMember(HV *hv, char *name, SV *val)
357 {
358     /* We don't increment `val's reference count -- I think this is
359      * right because it's created with a refcount of 1, and in fact
360      * the reference via this hash is the only reference to it in
361      * general.
362      */
363     if (!hv_store(hv, name, (U32) strlen(name), val, (U32) 0))
364         fatal("couldn't store member in hash");
365 }
366
367
368 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
369 static SV *translateOID(Odr_oid *x)
370 {
371     /* Yaz represents an OID by an int array terminated by a negative
372      * value, typically -1; we represent it as a reference to a
373      * blessed scalar string of "."-separated elements.
374      */
375     char buf[1000];
376     int i;
377
378     *buf = '\0';
379     for (i = 0; x[i] >= 0; i++) {
380         sprintf(buf + strlen(buf), "%d", (int) x[i]);
381         if (x[i+1] >- 0)
382             strcat(buf, ".");
383     }
384
385     /*
386      * ### We'd like to return a blessed scalar (string) here, but of
387      *  course you can't do that in Perl: only references can be
388      *  blessed, so we'd have to return a _reference_ to a string, and
389      *  bless _that_.  Better to do without the blessing, I think.
390      */
391     if (1) {
392         return newSVpv(buf, 0);
393     } else {
394         return newObject("Net::Z3950::APDU::OID", newSVpv(buf, 0));
395     }
396 }
397
398 static SV *attributes2perl(Z_AttributeList *list)
399 {
400     AV *av;
401         int i;
402         SV *attrs = newObject("Net::Z3950::RPN::Attributes",
403                               (SV*) (av = newAV()));
404         for (i = 0; i < list->num_attributes; i++) {
405             Z_AttributeElement *elem = list->attributes[i];
406             HV *hv2;
407             SV *tmp = newObject("Net::Z3950::RPN::Attribute",
408                                 (SV*) (hv2 = newHV()));
409             if (elem->attributeSet)
410                 setMember(hv2, "attributeSet",
411                           translateOID(elem->attributeSet));
412             setMember(hv2, "attributeType",
413                       newSViv(*elem->attributeType));
414             if (elem->which == Z_AttributeValue_numeric) {
415                 setMember(hv2, "attributeValue",
416                           newSViv(*elem->value.numeric));
417             } else {
418                 Z_ComplexAttribute *c;
419                 Z_StringOrNumeric *son;
420                 assert(elem->which == Z_AttributeValue_complex);
421                 c = elem->value.complex;
422                 /* We ignore semantic actions and multiple values */
423                 assert(c->num_list > 0);
424                 son = c->list[0];
425                 if (son->which == Z_StringOrNumeric_numeric) {
426                     setMember(hv2, "attributeValue",
427                               newSViv(*son->u.numeric));
428                 } else { /*Z_StringOrNumeric_string*/
429                     setMember(hv2, "attributeValue",
430                               newSVpv(son->u.string, 0));
431                 }
432             }
433             av_push(av, tmp);
434         }
435         return attrs;
436 }
437
438 static SV *f_Term_to_SV(Z_Term *term, Z_AttributeList *attributes)
439 {
440         HV *hv;
441         SV *sv = newObject("Net::Z3950::RPN::Term", (SV*) (hv = newHV()));
442
443         if (term->which != Z_Term_general)
444                 fatal("can't handle RPN terms other than general");
445
446         setMember(hv, "term", newSVpv((char*) term->u.general->buf,
447                                   term->u.general->len));
448
449         if (attributes) {
450                 setMember(hv, "attributes", attributes2perl(attributes));
451         }
452         return sv;
453 }
454
455 static SV *rpn2perl(Z_RPNStructure *s)
456 {
457     SV *sv;
458     HV *hv;
459     AV *av;
460     Z_Operand *o;
461
462     switch (s->which) {
463     case Z_RPNStructure_simple:
464         o = s->u.simple;
465         switch (o->which) {
466         case Z_Operand_resultSetId: {
467             /* This code causes a SIGBUS on my machine, and I have no
468                idea why.  It seems as clear as day to me */
469             SV *sv2;
470             char *rsid = (char*) o->u.resultSetId;
471             /*printf("Encoding resultSetId '%s'\n", rsid);*/
472             sv = newObject("Net::Z3950::RPN::RSID", (SV*) (hv = newHV()));
473             /*printf("Made sv=0x%lx, hv=0x%lx\n", (unsigned long) sv ,(unsigned long) hv);*/
474             sv2 = newSVpv(rsid, strlen(rsid));
475             setMember(hv, "id", sv2);
476             /*printf("Set hv{id} to 0x%lx\n", (unsigned long) sv2);*/
477             return sv;
478         }
479
480         case  Z_Operand_APT:
481             return f_Term_to_SV(o->u.attributesPlusTerm->term,
482                         o->u.attributesPlusTerm->attributes);   
483         default:
484             fatal("unknown RPN simple type %d", (int) o->which);
485         }
486
487     case Z_RPNStructure_complex: {
488         SV *tmp;
489         Z_Complex *c = s->u.complex;
490         char *type = 0;         /* vacuous assignment satisfies gcc -Wall */
491         switch (c->roperator->which) {
492         case Z_Operator_and:     type = "Net::Z3950::RPN::And";    break;
493         case Z_Operator_or:      type = "Net::Z3950::RPN::Or";     break;
494         case Z_Operator_and_not: type = "Net::Z3950::RPN::AndNot"; break;
495         case Z_Operator_prox:    fatal("proximity not yet supported");
496         default: fatal("unknown RPN operator %d", (int) c->roperator->which);
497         }
498         sv = newObject(type, (SV*) (av = newAV()));
499         if ((tmp = rpn2perl(c->s1)) == 0)
500             return 0;
501         av_push(av, tmp);
502         if ((tmp = rpn2perl(c->s2)) == 0)
503             return 0;
504         av_push(av, tmp);
505         return sv;
506     }
507
508     default:
509         fatal("unknown RPN node type %d", (int) s->which);
510     }
511     
512     return 0;
513 }
514
515
516 /* Decode the Z_SortAttributes struct and store the whole thing into the
517  * hash by reference
518  */
519 int simpleserver_ExpandSortAttributes (HV *sort_spec, Z_SortAttributes *sattr)
520 {
521     WRBUF attrset_wr = wrbuf_alloc();
522     AV *list = newAV();
523     Z_AttributeList *attr_list = sattr->list;
524     int i;
525
526     oid2str(sattr->id, attrset_wr);
527     hv_store(sort_spec, "ATTRSET", 7,
528              newSVpv(attrset_wr->buf, attrset_wr->pos), 0);
529     wrbuf_destroy(attrset_wr);
530
531     hv_store(sort_spec, "SORT_ATTR", 9, newRV( sv_2mortal( (SV*) list ) ), 0);
532
533     for (i = 0; i < attr_list->num_attributes; i++) 
534     {
535         Z_AttributeElement *attr = *attr_list->attributes++; 
536         HV *attr_spec = newHV();
537                 
538         av_push(list, newRV( sv_2mortal( (SV*) attr_spec ) ));
539         hv_store(attr_spec, "ATTR_TYPE", 9, newSViv(*attr->attributeType), 0);
540
541         if (attr->which == Z_AttributeValue_numeric)
542         {
543             hv_store(attr_spec, "ATTR_VALUE", 10,
544                      newSViv(*attr->value.numeric), 0);
545         } else {
546             return 0;
547         }
548     }
549
550     return 1;
551 }
552
553
554 /* Decode the Z_SortKeySpec struct and store the whole thing in a perl hash */
555 int simpleserver_SortKeySpecToHash (HV *sort_spec, Z_SortKeySpec *spec)
556 {
557     Z_SortElement *element = spec->sortElement;
558
559     hv_store(sort_spec, "RELATION", 8, newSViv(*spec->sortRelation), 0);
560     hv_store(sort_spec, "CASE", 4, newSViv(*spec->caseSensitivity), 0);
561     hv_store(sort_spec, "MISSING", 7, newSViv(spec->which), 0);
562
563     if (element->which == Z_SortElement_generic)
564     {
565         Z_SortKey *key = element->u.generic;
566
567         if (key->which == Z_SortKey_sortField)
568         {
569             hv_store(sort_spec, "SORTFIELD", 9,
570                      newSVpv((char *) key->u.sortField, 0), 0);
571         }
572         else if (key->which == Z_SortKey_elementSpec)
573         {
574             Z_Specification *zspec = key->u.elementSpec;
575             
576             hv_store(sort_spec, "ELEMENTSPEC_TYPE", 16,
577                      newSViv(zspec->which), 0);
578
579             if (zspec->which == Z_Schema_oid)
580             {
581                 WRBUF elementSpec = wrbuf_alloc();
582
583                 oid2str(zspec->schema.oid, elementSpec);
584                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
585                          newSVpv(elementSpec->buf, elementSpec->pos), 0);
586                 wrbuf_destroy(elementSpec);
587             }
588             else if (zspec->which == Z_Schema_uri)
589             {
590                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
591                          newSVpv((char *) zspec->schema.uri, 0), 0);
592             }
593         }
594         else if (key->which == Z_SortKey_sortAttributes)
595         {
596             return simpleserver_ExpandSortAttributes(sort_spec,
597                                                      key->u.sortAttributes);
598         }
599         else
600         {
601             return 0;
602         }
603     }
604     else
605     {
606         return 0;
607     }
608
609     return 1;
610 }
611
612
613 static SV *zquery2perl(Z_Query *q)
614 {
615     SV *sv;
616     HV *hv;
617
618     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
619         return 0;
620     sv = newObject("Net::Z3950::APDU::Query", (SV*) (hv = newHV()));
621     if (q->u.type_1->attributeSetId)
622         setMember(hv, "attributeSet",
623                   translateOID(q->u.type_1->attributeSetId));
624     setMember(hv, "query", rpn2perl(q->u.type_1->RPNStructure));
625     return sv;
626 }
627
628
629 int bend_sort(void *handle, bend_sort_rr *rr)
630 {
631         HV *href;
632         AV *aref;
633         AV *sort_seq;
634         SV **temp;
635         SV *err_code;
636         SV *err_str;
637         SV *status;
638         SV *point;
639         STRLEN len;
640         char *ptr;
641         char *ODR_err_str;
642         char **input_setnames;
643         Zfront_handle *zhandle = (Zfront_handle *)handle;
644         Z_SortKeySpecList *sort_spec = rr->sort_sequence;
645         int i;
646         
647         dSP;
648         ENTER;
649         SAVETMPS;
650         
651         aref = newAV();
652         input_setnames = rr->input_setnames;
653         for (i = 0; i < rr->num_input_setnames; i++)
654         {
655             av_push(aref, newSVpv(*input_setnames++, 0));
656         }
657
658         sort_seq = newAV();
659         for (i = 0; i < sort_spec->num_specs; i++)
660         {
661             Z_SortKeySpec *spec = *sort_spec->specs++;
662             HV *sort_spec = newHV();
663
664             if ( simpleserver_SortKeySpecToHash(sort_spec, spec) )
665                 av_push(sort_seq, newRV( sv_2mortal( (SV*) sort_spec ) ));
666             else
667             {
668                 rr->errcode = 207;
669                 return 0;
670             }
671         }
672         
673         href = newHV();
674         hv_store(href, "INPUT", 5, newRV( (SV*) aref), 0);
675         hv_store(href, "OUTPUT", 6, newSVpv(rr->output_setname, 0), 0);
676         hv_store(href, "SEQUENCE", 8, newRV( (SV*) sort_seq), 0);
677         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
678         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
679         hv_store(href, "STATUS", 6, newSViv(0), 0);
680         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
681         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
682
683         PUSHMARK(sp);
684
685         XPUSHs(sv_2mortal(newRV( (SV*) href)));
686
687         PUTBACK;
688
689         perl_call_sv(sort_ref, G_SCALAR | G_DISCARD);
690
691         SPAGAIN;
692
693         temp = hv_fetch(href, "ERR_CODE", 8, 1);
694         err_code = newSVsv(*temp);
695
696         temp = hv_fetch(href, "ERR_STR", 7, 1);
697         err_str = newSVsv(*temp);
698
699         temp = hv_fetch(href, "STATUS", 6, 1);
700         status = newSVsv(*temp);
701
702         temp = hv_fetch(href, "HANDLE", 6, 1);
703         point = newSVsv(*temp);
704
705         hv_undef(href);
706         av_undef(aref);
707         av_undef(sort_seq);
708        
709         sv_free( (SV*) aref);
710         sv_free( (SV*) href);
711         sv_free( (SV*) sort_seq);
712
713         rr->errcode = SvIV(err_code);
714         rr->sort_status = SvIV(status);
715         
716         ptr = SvPV(err_str, len);
717         ODR_err_str = (char *)odr_malloc(rr->stream, len + 1);
718         strcpy(ODR_err_str, ptr);
719         rr->errstring = ODR_err_str;
720         zhandle->handle = point;
721
722         sv_free(err_code);
723         sv_free(err_str);
724         sv_free(status);
725         
726         PUTBACK;
727         FREETMPS;
728         LEAVE;
729
730         return 0;
731 }
732
733 static SV *f_FacetField_to_SV(Z_FacetField *facet_field)
734 {
735         HV *hv;
736         AV *av;
737         SV *terms;
738         int i;
739         SV *sv = newObject("Net::Z3950::FacetField", (SV *) (hv = newHV()));
740         if (facet_field->attributes) {
741                 setMember(hv, "attributes",
742                      attributes2perl(facet_field->attributes));
743         }            
744         terms = newObject("Net::Z3950::FacetTerms", (SV *) (av = newAV()));
745
746         for (i = 0; i < facet_field->num_terms; i++) {
747             SV *sv_count = newSViv(*facet_field->terms[i]->count);
748             SV *sv_term = f_Term_to_SV(facet_field->terms[i]->term, 0);
749             SV *tmp = newObject("Net::Z3950::FacetTerm", (SV *) (hv = newHV()));
750             
751             setMember(hv, "count", sv_count);
752             setMember(hv, "term", sv_term);
753             
754             av_push(av, tmp);
755         }
756         setMember(hv, "terms", terms);
757         return sv;
758 }
759
760 static SV *f_FacetList_to_SV(Z_FacetList *facet_list)
761 {
762         SV *sv = 0;
763         if (facet_list) {
764                 AV *av;
765                 int i;
766                 sv = newObject("Net::Z3950::FacetList", (SV *) (av = newAV()));
767         
768                 for (i = 0; i < facet_list->num; i++) {
769                        SV *sv = f_FacetField_to_SV(facet_list->elements[i]);
770                        av_push(av, sv);
771                 }
772         }
773         return sv;
774 }
775
776
777 static void f_SV_to_FacetField(HV *facet_field_hv, Z_FacetField **fl, ODR odr)
778 {
779         int i;
780         int num_terms, num_attributes;
781         SV **temp;
782         Z_AttributeList *attributes = odr_malloc(odr, sizeof(*attributes));
783
784         AV *sv_terms, *sv_attributes;
785         printf("facet_field=%p\n", facet_field_hv);
786
787         temp = hv_fetch(facet_field_hv, "attributes", 10, 1);
788         sv_attributes = (AV *) SvRV(*temp);
789         num_attributes = av_len(sv_attributes) + 1;
790         printf(" attributes length=%d\n", num_attributes);
791         attributes->num_attributes = num_attributes;
792         attributes->attributes = (Z_AttributeElement **)
793              odr_malloc(odr, sizeof(*attributes->attributes) * num_attributes);
794
795         for (i = 0; i < num_attributes; i++) {
796             HV *hv_elem = (HV*) SvRV(sv_2mortal(av_shift(sv_attributes)));
797             Z_AttributeElement *elem;
798             elem = (Z_AttributeElement *) odr_malloc(odr, sizeof(*elem));
799             attributes->attributes[i] = elem;
800
801             elem->attributeSet = 0;
802
803             temp = hv_fetch(hv_elem, "attributeType", 13, 1);
804             elem->attributeType = odr_intdup(odr, SvIV(*temp));
805
806             temp = hv_fetch(hv_elem, "attributeValue", 14, 1);
807
808             if (SvIOK(*temp)) {
809                     elem->which = Z_AttributeValue_numeric;
810                     elem->value.numeric = odr_intdup(odr, SvIV(*temp));
811             } else {
812                     STRLEN s_len;
813                     char *s_buf = SvPV(*temp, s_len);
814                     Z_ComplexAttribute *c = odr_malloc(odr, sizeof *c);
815                     elem->which = Z_AttributeValue_complex;
816                     elem->value.complex = c;
817
818                     c->num_list = 1;
819                     c->list = (Z_StringOrNumeric **) odr_malloc(odr,
820                           sizeof(*c->list));
821                     c->list[0] = (Z_StringOrNumeric *) odr_malloc(odr,
822                           sizeof(**c->list));
823                     c->list[0]->which = Z_StringOrNumeric_string;
824                     c->list[0]->u.string = odr_malloc(odr, s_len + 1);
825                     memcpy(c->list[0]->u.string, s_buf, s_len);
826                     c->list[0]->u.string[s_len] = '\0';
827                     c->num_semanticAction = 0;
828                     c->semanticAction = 0;
829             }
830             hv_undef(hv_elem);
831         }
832
833         temp = hv_fetch(facet_field_hv, "terms", 5, 1);
834         sv_terms = (AV *) SvRV(*temp);
835         num_terms = av_len(sv_terms) + 1;
836         printf(" terms length=%d\n", num_terms);
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
851
852             temp = hv_fetch(hv_elem, "term", 4, 1);
853
854             s_buf = SvPV(*temp, s_len);
855             facet_term->term = z_Term_create(odr, Z_Term_general, s_buf, s_len);
856             hv_under(hv_elem);
857         }
858
859 }
860
861 static void f_SV_to_FacetList(SV *sv, Z_OtherInformation **oip, ODR odr)
862 {
863     AV *entries = (AV *) SvRV(sv);
864     int num_facets;
865     if (SvTYPE(entries) == SVt_PVAV && (num_facets = av_len(entries) + 1) > 0)
866     {
867             int i;
868             Z_FacetList *facet_list = facet_list_create(odr, num_facets);
869             for (; 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
873                 hv_undef(facet_field);
874             }
875             Z_OtherInformation *oi = odr_malloc(odr, sizeof(*oi));
876             Z_OtherInformationUnit *oiu = odr_malloc(odr, sizeof(*oiu));
877             oi->num_elements = 1;
878             oi->list = odr_malloc(odr, oi->num_elements * sizeof(*oi->list));
879             oiu->category = 0;
880             oiu->which = Z_OtherInfo_externallyDefinedInfo;
881             oiu->information.externallyDefinedInfo = odr_malloc(odr, sizeof(*oiu->information.externallyDefinedInfo));
882             oiu->information.externallyDefinedInfo->direct_reference = odr_oiddup(odr, yaz_oid_userinfo_facet_1);
883             oiu->information.externallyDefinedInfo->descriptor = 0;
884             oiu->information.externallyDefinedInfo->indirect_reference = 0;
885             oiu->information.externallyDefinedInfo->which = Z_External_userFacets;
886             oiu->information.externallyDefinedInfo->u.facetList = facet_list;
887             oi->list[0] = oiu;
888             *oip = oi;
889      }
890 }
891
892 int bend_search(void *handle, bend_search_rr *rr)
893 {
894         HV *href;
895         AV *aref;
896         SV **temp;
897         int i;
898         char **basenames;
899         WRBUF query;
900         SV *point;
901         Zfront_handle *zhandle = (Zfront_handle *)handle;
902         CV* handler_cv = 0;
903         SV *rpnSV;
904         SV *facetSV;
905
906         dSP;
907         ENTER;
908         SAVETMPS;
909
910         aref = newAV();
911         basenames = rr->basenames;
912         for (i = 0; i < rr->num_bases; i++)
913         {
914                 av_push(aref, newSVpv(*basenames++, 0));
915         }
916 #if ENABLE_STOP_SERVER
917         if (rr->num_bases == 1 && !strcmp(rr->basenames[0], "XXstop"))
918         {
919                 zhandle->stop_flag = 1;
920         }
921 #endif
922         href = newHV();         
923         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
924         if (rr->srw_sortKeys && *rr->srw_sortKeys) 
925             hv_store(href, "SRW_SORTKEYS", 12, newSVpv(rr->srw_sortKeys, 0), 0);
926         hv_store(href, "REPL_SET", 8, newSViv(rr->replace_set), 0);
927         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
928         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
929         hv_store(href, "HITS", 4, newSViv(0), 0);
930         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
931         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
932         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
933         hv_store(href, "PID", 3, newSViv(getpid()), 0);
934         if ((rpnSV = zquery2perl(rr->query)) != 0) {
935             hv_store(href, "RPN", 3, rpnSV, 0);
936         }
937         facetSV = f_FacetList_to_SV(yaz_oi_get_facetlist(&rr->search_input));
938         if (facetSV) {
939             hv_store(href, "INPUTFACETS", 11, facetSV, 0);
940         }
941
942         query = zquery2pquery(rr->query);
943         if (query)
944         {
945                 hv_store(href, "QUERY", 5, newSVpv((char *)query->buf, query->pos), 0);
946         }
947         else if (rr->query->which == Z_Query_type_104 &&
948                  rr->query->u.type_104->which == Z_External_CQL) {
949             hv_store(href, "CQL", 3,
950                      newSVpv(rr->query->u.type_104->u.cql, 0), 0);
951         }
952         else
953         {       
954                 rr->errcode = 108;
955                 return 0;
956         }
957         PUSHMARK(sp);
958         
959         XPUSHs(sv_2mortal(newRV( (SV*) href)));
960         
961         PUTBACK;
962
963         handler_cv = simpleserver_sv2cv( search_ref );
964         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
965
966         SPAGAIN;
967
968         temp = hv_fetch(href, "HITS", 4, 1);
969         rr->hits = SvIV(*temp);
970
971         temp = hv_fetch(href, "ERR_CODE", 8, 1);
972         rr->errcode = SvIV(*temp);
973
974         temp = hv_fetch(href, "ERR_STR", 7, 1);
975         rr->errstring = string_or_undef(temp, rr->stream);
976
977         temp = hv_fetch(href, "HANDLE", 6, 1);
978         point = newSVsv(*temp);
979
980         temp = hv_fetch(href, "OUTPUTFACETS", 12, 1);
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
1791 MODULE = Net::Z3950::SimpleServer       PACKAGE = Net::Z3950::SimpleServer
1792
1793 PROTOTYPES: DISABLE
1794
1795
1796 void
1797 set_ghandle(arg)
1798                 SV *arg
1799         CODE:
1800                 _global_ghandle = newSVsv(arg);
1801                 
1802
1803 void
1804 set_init_handler(arg)
1805                 SV *arg
1806         CODE:
1807                 init_ref = newSVsv(arg);
1808                 
1809
1810 void
1811 set_close_handler(arg)
1812                 SV *arg
1813         CODE:
1814                 close_ref = newSVsv(arg);
1815
1816
1817 void
1818 set_sort_handler(arg)
1819                 SV *arg
1820         CODE:
1821                 sort_ref = newSVsv(arg);
1822
1823 void
1824 set_search_handler(arg)
1825                 SV *arg
1826         CODE:
1827                 search_ref = newSVsv(arg);
1828
1829
1830 void
1831 set_fetch_handler(arg)
1832                 SV *arg
1833         CODE:
1834                 fetch_ref = newSVsv(arg);
1835
1836
1837 void
1838 set_present_handler(arg)
1839                 SV *arg
1840         CODE:
1841                 present_ref = newSVsv(arg);
1842
1843
1844 void
1845 set_esrequest_handler(arg)
1846                 SV *arg
1847         CODE:
1848                 esrequest_ref = newSVsv(arg);
1849
1850
1851 void
1852 set_delete_handler(arg)
1853                 SV *arg
1854         CODE:
1855                 delete_ref = newSVsv(arg);
1856
1857
1858 void
1859 set_scan_handler(arg)
1860                 SV *arg
1861         CODE:
1862                 scan_ref = newSVsv(arg);
1863
1864 void
1865 set_explain_handler(arg)
1866                 SV *arg
1867         CODE:
1868                 explain_ref = newSVsv(arg);
1869
1870 int
1871 start_server(...)
1872         PREINIT:
1873                 char **argv;
1874                 char **argv_buf;
1875                 char *ptr;
1876                 int i;
1877                 STRLEN len;
1878         CODE:
1879                 argv_buf = (char **)xmalloc((items + 1) * sizeof(char *));
1880                 argv = argv_buf;
1881                 for (i = 0; i < items; i++)
1882                 {
1883                         ptr = SvPV(ST(i), len);
1884                         *argv_buf = (char *)xmalloc(len + 1);
1885                         strcpy(*argv_buf++, ptr); 
1886                 }
1887                 *argv_buf = NULL;
1888                 root_perl_context = PERL_GET_CONTEXT;
1889                 yaz_mutex_create(&simpleserver_mutex);
1890 #if 0
1891                 /* only for debugging perl_clone .. */
1892                 tst_clones();
1893 #endif
1894                 
1895                 RETVAL = statserv_main(items, argv, bend_init, bend_close);
1896         OUTPUT:
1897                 RETVAL
1898
1899
1900 int
1901 ScanSuccess()
1902         CODE:
1903                 RETVAL = BEND_SCAN_SUCCESS;
1904         OUTPUT:
1905                 RETVAL
1906
1907 int
1908 ScanPartial()
1909         CODE:
1910                 RETVAL = BEND_SCAN_PARTIAL;
1911         OUTPUT:
1912                 RETVAL
1913
1914  
1915 void
1916 yazlog(arg)
1917                 SV *arg
1918         CODE:
1919                 STRLEN len;
1920                 char *ptr;
1921                 ptr = SvPV(arg, len);
1922                 yaz_log(YLOG_LOG, "%.*s", (int) len, ptr);
1923
1924 int
1925 yaz_diag_srw_to_bib1(srw_code)
1926         int srw_code
1927
1928 int
1929 yaz_diag_bib1_to_srw(bib1_code)
1930         int bib1_code
1931