Update for YAZ 3s libyaz_server.la
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /*
2  * $Id: SimpleServer.xs,v 1.60 2007-04-17 20:26:58 adam Exp $ 
3  * ----------------------------------------------------------------------
4  * 
5  * Copyright (c) 2000-2004, Index Data.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and
8  * its documentation, in whole or in part, for any purpose, is hereby granted,
9  * provided that:
10  *
11  * 1. This copyright and permission notice appear in all copies of the
12  * software and its documentation. Notices of copyright or attribution
13  * which appear at the beginning of any file must remain unchanged.
14  *
15  * 2. The name of Index Data or the individual authors may not be used to
16  * endorse or promote products derived from this software without specific
17  * prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,
20  * EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
21  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
22  * IN NO EVENT SHALL INDEX DATA BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
23  * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES
24  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR
25  * NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
26  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
27  * OF THIS SOFTWARE.
28  */
29
30 #include "EXTERN.h"
31 #include "perl.h"
32 #include "proto.h"
33 #include "embed.h"
34 #include "XSUB.h"
35 #include <yaz/backend.h>
36 #include <yaz/log.h>
37 #include <yaz/wrbuf.h>
38 #include <yaz/querytowrbuf.h>
39 #include <stdio.h>
40 #include <yaz/mutex.h>
41 #ifdef WIN32
42 #else
43 #include <unistd.h>
44 #endif
45 #include <stdlib.h>
46 #include <ctype.h>
47 #define GRS_MAX_FIELDS 500 
48 #ifdef ASN_COMPILED
49 #include <yaz/ill.h>
50 #endif
51 #ifndef sv_undef                /* To fix the problem with Perl 5.6.0 */
52 #define sv_undef PL_sv_undef
53 #endif
54
55 YAZ_MUTEX simpleserver_mutex;
56
57 typedef struct {
58         SV *handle;
59
60         SV *init_ref;
61         SV *close_ref;
62         SV *sort_ref;
63         SV *search_ref;
64         SV *fetch_ref;
65         SV *present_ref;
66         SV *esrequest_ref;
67         SV *delete_ref;
68         SV *scan_ref;
69         SV *explain_ref;
70         NMEM nmem;
71         int stop_flag;  /* is used to stop server prematurely .. */
72 } Zfront_handle;
73
74 #define ENABLE_STOP_SERVER 0
75
76 SV *init_ref = NULL;
77 SV *close_ref = NULL;
78 SV *sort_ref = NULL;
79 SV *search_ref = NULL;
80 SV *fetch_ref = NULL;
81 SV *present_ref = NULL;
82 SV *esrequest_ref = NULL;
83 SV *delete_ref = NULL;
84 SV *scan_ref = NULL;
85 SV *explain_ref = NULL;
86 PerlInterpreter *root_perl_context;
87 int MAX_OID = 15;
88
89 #define GRS_BUF_SIZE 8192
90
91 CV * simpleserver_sv2cv(SV *handler) {
92     STRLEN len;
93     char *buf;
94    
95     if (SvPOK(handler)) {
96         CV *ret;
97         buf = SvPV( handler, len);
98         if ( !( ret = perl_get_cv(buf, FALSE ) ) ) {
99             fprintf( stderr, "simpleserver_sv2cv: No such handler '%s'\n\n", buf );
100             exit(1);
101         }
102         
103         return ret;
104     } else {
105         return (CV *) handler;
106     }
107 }
108
109 /* debugging routine to check for destruction of Perl interpreters */
110 #ifdef USE_ITHREADS
111 void tst_clones(void)
112 {
113     int i; 
114     PerlInterpreter *parent = PERL_GET_CONTEXT;
115     for (i = 0; i<5000; i++)
116     {
117         PerlInterpreter *perl_interp;
118
119         PERL_SET_CONTEXT(parent);
120         PL_perl_destruct_level = 2;
121         perl_interp = perl_clone(parent, CLONEf_CLONE_HOST);
122         PL_perl_destruct_level = 2;
123         PERL_SET_CONTEXT(perl_interp);
124         perl_destruct(perl_interp);
125         perl_free(perl_interp);
126     }
127     exit (0);
128 }
129 #endif
130
131 int simpleserver_clone(void) {
132 #ifdef USE_ITHREADS
133      yaz_mutex_enter(simpleserver_mutex);
134      if (1)
135      {
136          PerlInterpreter *current = PERL_GET_CONTEXT;
137
138          /* if current is unset, then we're in a new thread with
139           * no Perl interpreter for it. So we must create one .
140           * This will only happen when threaded is used..
141           */
142          if (!current) {
143              PerlInterpreter *perl_interp;
144              PERL_SET_CONTEXT( root_perl_context );
145              perl_interp = perl_clone(root_perl_context, CLONEf_CLONE_HOST);
146              PERL_SET_CONTEXT( perl_interp );
147          }
148      }
149      yaz_mutex_leave(simpleserver_mutex);
150 #endif
151      return 0;
152 }
153
154
155 void simpleserver_free(void) {
156     yaz_mutex_enter(simpleserver_mutex);
157     if (1)
158     {
159         PerlInterpreter *current_interp = PERL_GET_CONTEXT;
160
161         /* If current Perl Interp is different from root interp, then
162          * we're in threaded mode and we must destroy.. 
163          */
164         if (current_interp != root_perl_context) {
165             PL_perl_destruct_level = 2;
166             PERL_SET_CONTEXT(current_interp);
167             perl_destruct(current_interp);
168             perl_free(current_interp);
169         }
170     }
171     yaz_mutex_leave(simpleserver_mutex);
172 }
173
174
175 Z_GenericRecord *read_grs1(char *str, ODR o)
176 {
177         int type, ivalue;
178         char line[GRS_BUF_SIZE+1], *buf, *ptr, *original;
179         char value[GRS_BUF_SIZE+1];
180         Z_GenericRecord *r = 0;
181
182         original = str;
183         r = (Z_GenericRecord *)odr_malloc(o, sizeof(*r));
184         r->elements = (Z_TaggedElement **) odr_malloc(o, sizeof(Z_TaggedElement*) * GRS_MAX_FIELDS);
185         r->num_elements = 0;
186         
187         for (;;)
188         {
189                 Z_TaggedElement *t;
190                 Z_ElementData *c;
191                 int len;
192         
193                 ptr = strchr(str, '\n');
194                 if (!ptr) {
195                         return r;
196                 }
197                 len = ptr - str;
198                 if (len > GRS_BUF_SIZE) {
199                     yaz_log(YLOG_WARN, "GRS string too long - truncating (%d > %d)", len, GRS_BUF_SIZE);
200                     len = GRS_BUF_SIZE;
201                 }
202                 strncpy(line, str, len);
203                 line[len] = 0;
204                 buf = line;
205                 str = ptr + 1;
206                 while (*buf && isspace(*buf))
207                         buf++;
208                 if (*buf == '}') {
209                         memmove(original, str, strlen(str));
210                         return r;
211                 }
212                 if (sscanf(buf, "(%d,%[^)])", &type, value) != 2)
213                 {
214                         yaz_log(YLOG_WARN, "Bad data in '%s'", buf);
215                         return r;
216                 }
217                 if (!type && *value == '0')
218                         return r;
219                 if (!(buf = strchr(buf, ')')))
220                         return r;
221                 buf++;
222                 while (*buf && isspace(*buf))
223                         buf++;
224                 if (r->num_elements >= GRS_MAX_FIELDS)
225                 {
226                         yaz_log(YLOG_WARN, "Max number of GRS-1 elements exceeded [GRS_MAX_FIELDS=%d]", GRS_MAX_FIELDS);
227                         exit(0);
228                 }
229                 r->elements[r->num_elements] = t = (Z_TaggedElement *) odr_malloc(o, sizeof(Z_TaggedElement));
230                 t->tagType = (int *)odr_malloc(o, sizeof(int));
231                 *t->tagType = type;
232                 t->tagValue = (Z_StringOrNumeric *)
233                         odr_malloc(o, sizeof(Z_StringOrNumeric));
234                 if ((ivalue = atoi(value)))
235                 {
236                         t->tagValue->which = Z_StringOrNumeric_numeric;
237                         t->tagValue->u.numeric = (int *)odr_malloc(o, sizeof(int));
238                         *t->tagValue->u.numeric = ivalue;
239                 }
240                 else
241                 {
242                         t->tagValue->which = Z_StringOrNumeric_string;
243                         t->tagValue->u.string = (char *)odr_malloc(o, strlen(value)+1);
244                         strcpy(t->tagValue->u.string, value);
245                 }
246                 t->tagOccurrence = 0;
247                 t->metaData = 0;
248                 t->appliedVariant = 0;
249                 t->content = c = (Z_ElementData *)odr_malloc(o, sizeof(Z_ElementData));
250                 if (*buf == '{')
251                 {
252                         c->which = Z_ElementData_subtree;
253                         c->u.subtree = read_grs1(str, o);
254                 }
255                 else
256                 {
257                         c->which = Z_ElementData_string;
258                         c->u.string = odr_strdup(o, buf);
259                 }
260                 r->num_elements++;
261         }
262 }
263
264
265
266 static void oid2str(Odr_oid *o, WRBUF buf)
267 {
268     for (; *o >= 0; o++) {
269         char ibuf[16];
270         sprintf(ibuf, "%d", *o);
271         wrbuf_puts(buf, ibuf);
272         if (o[1] > 0)
273             wrbuf_putc(buf, '.');
274     }
275 }
276
277 WRBUF oid2dotted(int *oid)
278 {
279     WRBUF buf = wrbuf_alloc();
280     oid2str(oid, buf);
281     return buf;
282 }
283                 
284
285 WRBUF zquery2pquery(Z_Query *q)
286 {
287     WRBUF buf = wrbuf_alloc();
288
289     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
290         return 0;
291     yaz_rpnquery_to_wrbuf(buf, q->u.type_1);
292     return buf;
293 }
294
295
296 /* Lifted verbatim from Net::Z3950 yazwrap/util.c */
297 #include <stdarg.h>
298 void fatal(char *fmt, ...)
299 {
300     va_list ap;
301
302     fprintf(stderr, "FATAL (SimpleServer): ");
303     va_start(ap, fmt);
304     vfprintf(stderr, fmt, ap);
305     va_end(ap);
306     fprintf(stderr, "\n");
307     abort();
308 }
309
310
311 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
312 /*
313  * Creates a new Perl object of type `class'; the newly-created scalar
314  * that is a reference to the blessed thingy `referent' is returned.
315  */
316 static SV *newObject(char *class, SV *referent)
317 {
318     HV *stash;
319     SV *sv;
320
321     sv = newRV_noinc((SV*) referent);
322     stash = gv_stashpv(class, 0);
323     if (stash == 0)
324         fatal("attempt to create object of undefined class '%s'", class);
325     /*assert(stash != 0);*/
326     sv_bless(sv, stash);
327     return sv;
328 }
329
330
331 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
332 static void setMember(HV *hv, char *name, SV *val)
333 {
334     /* We don't increment `val's reference count -- I think this is
335      * right because it's created with a refcount of 1, and in fact
336      * the reference via this hash is the only reference to it in
337      * general.
338      */
339     if (!hv_store(hv, name, (U32) strlen(name), val, (U32) 0))
340         fatal("couldn't store member in hash");
341 }
342
343
344 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
345 static SV *translateOID(Odr_oid *x)
346 {
347     /* Yaz represents an OID by an int array terminated by a negative
348      * value, typically -1; we represent it as a reference to a
349      * blessed scalar string of "."-separated elements.
350      */
351     char buf[1000];
352     int i;
353
354     *buf = '\0';
355     for (i = 0; x[i] >= 0; i++) {
356         sprintf(buf + strlen(buf), "%d", (int) x[i]);
357         if (x[i+1] >- 0)
358             strcat(buf, ".");
359     }
360
361     /*
362      * ### We'd like to return a blessed scalar (string) here, but of
363      *  course you can't do that in Perl: only references can be
364      *  blessed, so we'd have to return a _reference_ to a string, and
365      *  bless _that_.  Better to do without the blessing, I think.
366      */
367     if (1) {
368         return newSVpv(buf, 0);
369     } else {
370         return newObject("Net::Z3950::APDU::OID", newSVpv(buf, 0));
371     }
372 }
373
374
375 static SV *rpn2perl(Z_RPNStructure *s)
376 {
377     SV *sv;
378     HV *hv;
379     AV *av;
380
381     switch (s->which) {
382     case Z_RPNStructure_simple: {
383         Z_Operand *o = s->u.simple;
384         Z_AttributesPlusTerm *at;
385         if (o->which == Z_Operand_resultSetId) {
386             SV *sv2;
387             /* This code causes a SIGBUS on my machine, and I have no
388                idea why.  It seems as clear as day to me */
389             char *rsid = (char*) o->u.resultSetId;
390             printf("Encoding resultSetId '%s'\n", rsid);
391             sv = newObject("Net::Z3950::RPN::RSID", (SV*) (hv = newHV()));
392             printf("Made sv=0x%lx, hv=0x%lx\n",
393                    (unsigned long) sv ,(unsigned long) hv);
394             sv2 = newSVpv(rsid, strlen(rsid));
395             setMember(hv, "id", sv2);
396             printf("Set hv{id} to 0x%lx\n", (unsigned long) sv2);
397             return sv;
398         }
399         if (o->which != Z_Operand_APT)
400             fatal("can't handle RPN simples other than APT and RSID");
401         at = o->u.attributesPlusTerm;
402         if (at->term->which != Z_Term_general)
403             fatal("can't handle RPN terms other than general");
404
405         sv = newObject("Net::Z3950::RPN::Term", (SV*) (hv = newHV()));
406         if (at->attributes) {
407             int i;
408             SV *attrs = newObject("Net::Z3950::RPN::Attributes",
409                                   (SV*) (av = newAV()));
410             for (i = 0; i < at->attributes->num_attributes; i++) {
411                 Z_AttributeElement *elem = at->attributes->attributes[i];
412                 HV *hv2;
413                 SV *tmp = newObject("Net::Z3950::RPN::Attribute",
414                                     (SV*) (hv2 = newHV()));
415                 if (elem->attributeSet)
416                     setMember(hv2, "attributeSet",
417                               translateOID(elem->attributeSet));
418                 setMember(hv2, "attributeType",
419                           newSViv(*elem->attributeType));
420                 assert(elem->which == Z_AttributeValue_numeric);
421                 setMember(hv2, "attributeValue",
422                           newSViv(*elem->value.numeric));
423                 av_push(av, tmp);
424             }
425             setMember(hv, "attributes", attrs);
426         }
427         setMember(hv, "term", newSVpv((char*) at->term->u.general->buf,
428                                       at->term->u.general->len));
429         return sv;
430     }
431     case Z_RPNStructure_complex: {
432         SV *tmp;
433         Z_Complex *c = s->u.complex;
434         char *type = 0;         /* vacuous assignment satisfies gcc -Wall */
435         switch (c->roperator->which) {
436         case Z_Operator_and:     type = "Net::Z3950::RPN::And"; break;
437         case Z_Operator_or:      type = "Net::Z3950::RPN::Or"; break;
438         case Z_Operator_and_not: type = "Net::Z3950::RPN::AndNot"; break;
439         case Z_Operator_prox:    fatal("proximity not yet supported");
440         default: fatal("unknown RPN operator %d", (int) c->roperator->which);
441         }
442         sv = newObject(type, (SV*) (av = newAV()));
443         if ((tmp = rpn2perl(c->s1)) == 0)
444             return 0;
445         av_push(av, tmp);
446         if ((tmp = rpn2perl(c->s2)) == 0)
447             return 0;
448         av_push(av, tmp);
449         return sv;
450     }
451     default: fatal("unknown RPN node type %d", (int) s->which);
452     }
453
454     return 0;
455 }
456
457
458 /* Decode the Z_SortAttributes struct and store the whole thing into the
459  * hash by reference
460  */
461 int simpleserver_ExpandSortAttributes (HV *sort_spec, Z_SortAttributes *sattr)
462 {
463     WRBUF attrset_wr = wrbuf_alloc();
464     AV *list = newAV();
465     Z_AttributeList *attr_list = sattr->list;
466     int i;
467
468     oid2str(sattr->id, attrset_wr);
469     hv_store(sort_spec, "ATTRSET", 7,
470              newSVpv(attrset_wr->buf, attrset_wr->pos), 0);
471     wrbuf_destroy(attrset_wr);
472
473     hv_store(sort_spec, "SORT_ATTR", 9, newRV( sv_2mortal( (SV*) list ) ), 0);
474
475     for (i = 0; i < attr_list->num_attributes; i++) 
476     {
477         Z_AttributeElement *attr = *attr_list->attributes++; 
478         HV *attr_spec = newHV();
479                 
480         av_push(list, newRV( sv_2mortal( (SV*) attr_spec ) ));
481         hv_store(attr_spec, "ATTR_TYPE", 9, newSViv(*attr->attributeType), 0);
482
483         if (attr->which == Z_AttributeValue_numeric)
484         {
485             hv_store(attr_spec, "ATTR_VALUE", 10,
486                      newSViv(*attr->value.numeric), 0);
487         } else {
488             return 0;
489         }
490     }
491
492     return 1;
493 }
494
495
496 /* Decode the Z_SortKeySpec struct and store the whole thing in a perl hash */
497 int simpleserver_SortKeySpecToHash (HV *sort_spec, Z_SortKeySpec *spec)
498 {
499     Z_SortElement *element = spec->sortElement;
500
501     hv_store(sort_spec, "RELATION", 8, newSViv(*spec->sortRelation), 0);
502     hv_store(sort_spec, "CASE", 4, newSViv(*spec->caseSensitivity), 0);
503     hv_store(sort_spec, "MISSING", 7, newSViv(spec->which), 0);
504
505     if (element->which == Z_SortElement_generic)
506     {
507         Z_SortKey *key = element->u.generic;
508
509         if (key->which == Z_SortKey_sortField)
510         {
511             hv_store(sort_spec, "SORTFIELD", 9,
512                      newSVpv((char *) key->u.sortField, 0), 0);
513         }
514         else if (key->which == Z_SortKey_elementSpec)
515         {
516             Z_Specification *zspec = key->u.elementSpec;
517             
518             hv_store(sort_spec, "ELEMENTSPEC_TYPE", 16,
519                      newSViv(zspec->which), 0);
520
521             if (zspec->which == Z_Schema_oid)
522             {
523                 WRBUF elementSpec = wrbuf_alloc();
524
525                 oid2str(zspec->schema.oid, elementSpec);
526                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
527                          newSVpv(elementSpec->buf, elementSpec->pos), 0);
528                 wrbuf_destroy(elementSpec);
529             }
530             else if (zspec->which == Z_Schema_uri)
531             {
532                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
533                          newSVpv((char *) zspec->schema.uri, 0), 0);
534             }
535         }
536         else if (key->which == Z_SortKey_sortAttributes)
537         {
538             return simpleserver_ExpandSortAttributes(sort_spec,
539                                                      key->u.sortAttributes);
540         }
541         else
542         {
543             return 0;
544         }
545     }
546     else
547     {
548         return 0;
549     }
550
551     return 1;
552 }
553
554
555 static SV *zquery2perl(Z_Query *q)
556 {
557     SV *sv;
558     HV *hv;
559
560     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
561         return 0;
562     sv = newObject("Net::Z3950::APDU::Query", (SV*) (hv = newHV()));
563     if (q->u.type_1->attributeSetId)
564         setMember(hv, "attributeSet",
565                   translateOID(q->u.type_1->attributeSetId));
566     setMember(hv, "query", rpn2perl(q->u.type_1->RPNStructure));
567     return sv;
568 }
569
570
571 int bend_sort(void *handle, bend_sort_rr *rr)
572 {
573         HV *href;
574         AV *aref;
575         AV *sort_seq;
576         SV **temp;
577         SV *err_code;
578         SV *err_str;
579         SV *status;
580         SV *point;
581         STRLEN len;
582         char *ptr;
583         char *ODR_err_str;
584         char **input_setnames;
585         Zfront_handle *zhandle = (Zfront_handle *)handle;
586         Z_SortKeySpecList *sort_spec = rr->sort_sequence;
587         int i;
588         
589         dSP;
590         ENTER;
591         SAVETMPS;
592         
593         aref = newAV();
594         input_setnames = rr->input_setnames;
595         for (i = 0; i < rr->num_input_setnames; i++)
596         {
597             av_push(aref, newSVpv(*input_setnames++, 0));
598         }
599
600         sort_seq = newAV();
601         for (i = 0; i < sort_spec->num_specs; i++)
602         {
603             Z_SortKeySpec *spec = *sort_spec->specs++;
604             HV *sort_spec = newHV();
605
606             if ( simpleserver_SortKeySpecToHash(sort_spec, spec) )
607                 av_push(sort_seq, newRV( sv_2mortal( (SV*) sort_spec ) ));
608             else
609             {
610                 rr->errcode = 207;
611                 return 0;
612             }
613         }
614         
615         href = newHV();
616         hv_store(href, "INPUT", 5, newRV( (SV*) aref), 0);
617         hv_store(href, "OUTPUT", 6, newSVpv(rr->output_setname, 0), 0);
618         hv_store(href, "SEQUENCE", 8, newRV( (SV*) sort_seq), 0);
619         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
620         hv_store(href, "STATUS", 6, newSViv(0), 0);
621         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
622         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
623
624         PUSHMARK(sp);
625
626         XPUSHs(sv_2mortal(newRV( (SV*) href)));
627
628         PUTBACK;
629
630         perl_call_sv(sort_ref, G_SCALAR | G_DISCARD);
631
632         SPAGAIN;
633
634         temp = hv_fetch(href, "ERR_CODE", 8, 1);
635         err_code = newSVsv(*temp);
636
637         temp = hv_fetch(href, "ERR_STR", 7, 1);
638         err_str = newSVsv(*temp);
639
640         temp = hv_fetch(href, "STATUS", 6, 1);
641         status = newSVsv(*temp);
642
643         temp = hv_fetch(href, "HANDLE", 6, 1);
644         point = newSVsv(*temp);
645
646         hv_undef(href);
647         av_undef(aref);
648         av_undef(sort_seq);
649        
650         sv_free( (SV*) aref);
651         sv_free( (SV*) href);
652         sv_free( (SV*) sort_seq);
653
654         rr->errcode = SvIV(err_code);
655         rr->sort_status = SvIV(status);
656         
657         ptr = SvPV(err_str, len);
658         ODR_err_str = (char *)odr_malloc(rr->stream, len + 1);
659         strcpy(ODR_err_str, ptr);
660         rr->errstring = ODR_err_str;
661         zhandle->handle = point;
662
663         sv_free(err_code);
664         sv_free(err_str);
665         sv_free(status);
666         
667         PUTBACK;
668         FREETMPS;
669         LEAVE;
670
671         return 0;
672 }
673
674
675 int bend_search(void *handle, bend_search_rr *rr)
676 {
677         HV *href;
678         AV *aref;
679         SV **temp;
680         char *ODR_errstr;
681         STRLEN len;
682         int i;
683         char **basenames;
684         WRBUF query;
685         char *ptr;
686         SV *point;
687         Zfront_handle *zhandle = (Zfront_handle *)handle;
688         CV* handler_cv = 0;
689         SV *rpnSV;
690
691         dSP;
692         ENTER;
693         SAVETMPS;
694
695         aref = newAV();
696         basenames = rr->basenames;
697         for (i = 0; i < rr->num_bases; i++)
698         {
699                 av_push(aref, newSVpv(*basenames++, 0));
700         }
701 #if ENABLE_STOP_SERVER
702         if (rr->num_bases == 1 && !strcmp(rr->basenames[0], "XXstop"))
703         {
704                 zhandle->stop_flag = 1;
705         }
706 #endif
707         href = newHV();         
708         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
709         if (rr->srw_sortKeys && *rr->srw_sortKeys) 
710             hv_store(href, "SRW_SORTKEYS", 12, newSVpv(rr->srw_sortKeys, 0), 0);
711         hv_store(href, "REPL_SET", 8, newSViv(rr->replace_set), 0);
712         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
713         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
714         hv_store(href, "HITS", 4, newSViv(0), 0);
715         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
716         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
717         hv_store(href, "PID", 3, newSViv(getpid()), 0);
718         if ((rpnSV = zquery2perl(rr->query)) != 0) {
719             hv_store(href, "RPN", 3, rpnSV, 0);
720         }
721         query = zquery2pquery(rr->query);
722         if (query)
723         {
724                 hv_store(href, "QUERY", 5, newSVpv((char *)query->buf, query->pos), 0);
725         }
726         else if (rr->query->which == Z_Query_type_104 &&
727                  rr->query->u.type_104->which == Z_External_CQL) {
728             hv_store(href, "CQL", 3,
729                      newSVpv(rr->query->u.type_104->u.cql, 0), 0);
730         }
731         else
732         {       
733                 rr->errcode = 108;
734                 return 0;
735         }
736         PUSHMARK(sp);
737         
738         XPUSHs(sv_2mortal(newRV( (SV*) href)));
739         
740         PUTBACK;
741
742         handler_cv = simpleserver_sv2cv( search_ref );
743         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
744
745         SPAGAIN;
746
747         temp = hv_fetch(href, "HITS", 4, 1);
748         rr->hits = SvIV(*temp);
749
750         temp = hv_fetch(href, "ERR_CODE", 8, 1);
751         rr->errcode = SvIV(*temp);
752
753         temp = hv_fetch(href, "ERR_STR", 7, 1);
754         ptr = SvPV(*temp, len);
755         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
756         strcpy(ODR_errstr, ptr);
757         rr->errstring = ODR_errstr;
758
759         temp = hv_fetch(href, "HANDLE", 6, 1);
760         point = newSVsv(*temp);
761
762         hv_undef(href);
763         av_undef(aref);
764
765         zhandle->handle = point;
766         sv_free( (SV*) aref);
767         sv_free( (SV*) href);
768         if (query)
769             wrbuf_destroy(query);
770         PUTBACK;
771         FREETMPS;
772         LEAVE;
773         return 0;
774 }
775
776
777 int bend_fetch(void *handle, bend_fetch_rr *rr)
778 {
779         HV *href;
780         SV **temp;
781         SV *basename;
782         SV *record;
783         SV *last;
784         SV *err_code;
785         SV *err_string;
786         SV *sur_flag;
787         SV *point;
788         SV *rep_form;
789         SV *schema = 0;
790         char *ptr;
791         char *ODR_record;
792         char *ODR_basename;
793         char *ODR_errstr;
794         int *ODR_oid_buf;
795         WRBUF oid_dotted;
796         Zfront_handle *zhandle = (Zfront_handle *)handle;
797         CV* handler_cv = 0;
798
799         Z_RecordComposition *composition;
800         Z_ElementSetNames *simple;
801         Z_CompSpec *complex;
802         STRLEN length;
803
804         dSP;
805         ENTER;
806         SAVETMPS;
807
808         rr->errcode = 0;
809         href = newHV();
810         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
811         if (rr->schema)
812                 hv_store(href, "SCHEMA", 6, newSVpv(rr->schema, 0), 0);
813         temp = hv_store(href, "OFFSET", 6, newSViv(rr->number), 0);
814         if (rr->request_format != 0) {
815             oid_dotted = oid2dotted(rr->request_format);
816         } else {
817             /* Probably an SRU request: assume XML is required */
818             oid_dotted = wrbuf_alloc();
819             wrbuf_puts(oid_dotted, "1.2.840.10003.5.109.10");
820         }
821         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
822         hv_store(href, "REP_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
823         hv_store(href, "BASENAME", 8, newSVpv("", 0), 0);
824         hv_store(href, "RECORD", 6, newSVpv("", 0), 0);
825         hv_store(href, "LAST", 4, newSViv(0), 0);
826         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
827         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
828         hv_store(href, "SUR_FLAG", 8, newSViv(0), 0);
829         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
830         hv_store(href, "PID", 3, newSViv(getpid()), 0);
831         if (rr->comp)
832         {
833                 composition = rr->comp;
834                 if (composition->which == Z_RecordComp_simple)
835                 {
836                         simple = composition->u.simple;
837                         if (simple->which == Z_ElementSetNames_generic)
838                         {
839                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
840                         } 
841                         else
842                         {
843                                 rr->errcode = 26;
844                         }
845                 }
846                 else if (composition->which == Z_RecordComp_complex)
847                 {
848                         if (composition->u.complex->generic &&
849
850                                         composition->u.complex->generic &&
851                                         composition->u.complex->generic->elementSpec &&
852                                         composition->u.complex->generic->elementSpec->which ==
853                                         Z_ElementSpec_elementSetName)
854                         {
855                                 complex = composition->u.complex;
856                                 hv_store(href, "COMP", 4,
857                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
858                         }
859                         else
860                         {
861 #if 0   /* For now ignore this error, which is ubiquitous in SRU */
862                                 fprintf(stderr, "complex is weird\n");
863                                 rr->errcode = 26;
864                                 return 0;
865 #endif /*0*/
866                         }
867                 }
868                 else
869                 {
870                         rr->errcode = 26;
871                         return 0;
872                 }
873         }
874
875         PUSHMARK(sp);
876
877         XPUSHs(sv_2mortal(newRV( (SV*) href)));
878
879         PUTBACK;
880         
881         handler_cv = simpleserver_sv2cv( fetch_ref );
882         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
883
884         SPAGAIN;
885
886         temp = hv_fetch(href, "BASENAME", 8, 1);
887         basename = newSVsv(*temp);
888
889         temp = hv_fetch(href, "RECORD", 6, 1);
890         record = newSVsv(*temp);
891
892         temp = hv_fetch(href, "LAST", 4, 1);
893         last = newSVsv(*temp);
894
895         temp = hv_fetch(href, "ERR_CODE", 8, 1);
896         err_code = newSVsv(*temp);
897
898         temp = hv_fetch(href, "ERR_STR", 7, 1),
899         err_string = newSVsv(*temp);
900
901         temp = hv_fetch(href, "SUR_FLAG", 8, 1);
902         sur_flag = newSVsv(*temp);
903
904         temp = hv_fetch(href, "REP_FORM", 8, 1);
905         rep_form = newSVsv(*temp);
906
907         temp = hv_fetch(href, "SCHEMA", 6, 1);
908         if (temp != 0) {
909                 schema = newSVsv(*temp);
910                 ptr = SvPV(schema, length);
911                 if (length > 0) {
912                         rr->schema = (char *)odr_malloc(rr->stream, length + 1);
913                         strcpy(rr->schema, ptr);
914                 }
915         }
916
917         temp = hv_fetch(href, "HANDLE", 6, 1);
918         point = newSVsv(*temp);
919
920
921         hv_undef(href);
922         
923         ptr = SvPV(basename, length);
924         ODR_basename = (char *)odr_malloc(rr->stream, length + 1);
925         strcpy(ODR_basename, ptr);
926         rr->basename = ODR_basename;
927
928         ptr = SvPV(rep_form, length);
929
930         ODR_oid_buf = (int *)odr_malloc(rr->stream, (MAX_OID + 1) * sizeof(int));
931         if (oid_dotstring_to_oid(ptr, ODR_oid_buf))
932         {
933                 printf("Net::Z3950::SimpleServer: WARNING: OID structure too long, max length is %d\n", MAX_OID);
934         }
935         rr->output_format = ODR_oid_buf;        
936         
937         ptr = SvPV(record, length);
938         /* Treat GRS-1 records separately */
939         if (!oid_oidcmp(ODR_oid_buf, yaz_oid_recsyn_grs_1))
940         {
941                 rr->record = (char *) read_grs1(ptr, rr->stream);
942                 rr->len = -1;
943         }
944         else
945         {
946                 ODR_record = (char *)odr_malloc(rr->stream, length + 1);
947                 strcpy(ODR_record, ptr);
948                 rr->record = ODR_record;
949                 rr->len = length;
950         }
951         zhandle->handle = point;
952         handle = zhandle;
953         rr->last_in_set = SvIV(last);
954         
955         if (!(rr->errcode))
956         {
957                 rr->errcode = SvIV(err_code);
958                 ptr = SvPV(err_string, length);
959                 ODR_errstr = (char *)odr_malloc(rr->stream, length + 1);
960                 strcpy(ODR_errstr, ptr);
961                 rr->errstring = ODR_errstr;
962         }
963         rr->surrogate_flag = SvIV(sur_flag);
964
965         wrbuf_destroy(oid_dotted);
966         sv_free((SV*) href);
967         sv_free(basename);
968         sv_free(record);
969         sv_free(last);
970         sv_free(err_string);
971         sv_free(err_code),
972         sv_free(sur_flag);
973         sv_free(rep_form);
974
975         if (schema)
976                 sv_free(schema);
977
978         PUTBACK;
979         FREETMPS;
980         LEAVE;
981         
982         return 0;
983 }
984
985
986 int bend_present(void *handle, bend_present_rr *rr)
987 {
988         HV *href;
989         SV **temp;
990         SV *err_code;
991         SV *err_string;
992         SV *hits;
993         SV *point;
994         STRLEN len;
995         Z_RecordComposition *composition;
996         Z_ElementSetNames *simple;
997         Z_CompSpec *complex;
998         char *ODR_errstr;
999         char *ptr;
1000         Zfront_handle *zhandle = (Zfront_handle *)handle;
1001         CV* handler_cv = 0;
1002
1003 /*      WRBUF oid_dotted; */
1004
1005         dSP;
1006         ENTER;
1007         SAVETMPS;
1008
1009         href = newHV();
1010         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1011         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1012         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1013         hv_store(href, "START", 5, newSViv(rr->start), 0);
1014         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
1015         hv_store(href, "NUMBER", 6, newSViv(rr->number), 0);
1016         /*oid_dotted = oid2dotted(rr->request_format_raw);
1017         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);*/
1018         hv_store(href, "HITS", 4, newSViv(0), 0);
1019         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1020         if (rr->comp)
1021         {
1022                 composition = rr->comp;
1023                 if (composition->which == Z_RecordComp_simple)
1024                 {
1025                         simple = composition->u.simple;
1026                         if (simple->which == Z_ElementSetNames_generic)
1027                         {
1028                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
1029                         } 
1030                         else
1031                         {
1032                                 rr->errcode = 26;
1033                                 return 0;
1034                         }
1035                 }
1036                 else if (composition->which == Z_RecordComp_complex)
1037                 {
1038                         if (composition->u.complex->generic &&
1039
1040                                         composition->u.complex->generic &&
1041                                         composition->u.complex->generic->elementSpec &&
1042                                         composition->u.complex->generic->elementSpec->which ==
1043                                         Z_ElementSpec_elementSetName)
1044                         {
1045                                 complex = composition->u.complex;
1046                                 hv_store(href, "COMP", 4,
1047                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
1048                         }
1049                         else
1050                         {
1051                                 rr->errcode = 26;
1052                                 return 0;
1053                         }
1054                 }
1055                 else
1056                 {
1057                         rr->errcode = 26;
1058                         return 0;
1059                 }
1060         }
1061
1062         PUSHMARK(sp);
1063         
1064         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1065         
1066         PUTBACK;
1067         
1068         handler_cv = simpleserver_sv2cv( present_ref );
1069         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1070         
1071         SPAGAIN;
1072
1073         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1074         err_code = newSVsv(*temp);
1075
1076         temp = hv_fetch(href, "ERR_STR", 7, 1);
1077         err_string = newSVsv(*temp);
1078
1079         temp = hv_fetch(href, "HITS", 4, 1);
1080         hits = newSVsv(*temp);
1081
1082         temp = hv_fetch(href, "HANDLE", 6, 1);
1083         point = newSVsv(*temp);
1084
1085         PUTBACK;
1086         FREETMPS;
1087         LEAVE;
1088         
1089         hv_undef(href);
1090         rr->errcode = SvIV(err_code);
1091         rr->hits = SvIV(hits);
1092
1093         ptr = SvPV(err_string, len);
1094         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1095         strcpy(ODR_errstr, ptr);
1096         rr->errstring = ODR_errstr;
1097 /*      wrbuf_free(oid_dotted, 1);*/
1098         zhandle->handle = point;
1099         handle = zhandle;
1100         sv_free(err_code);
1101         sv_free(err_string);
1102         sv_free(hits);
1103         sv_free( (SV*) href);
1104
1105         return 0;
1106 }
1107
1108
1109 int bend_esrequest(void *handle, bend_esrequest_rr *rr)
1110 {
1111         perl_call_sv(esrequest_ref, G_VOID | G_DISCARD | G_NOARGS);
1112         return 0;
1113 }
1114
1115
1116 int bend_delete(void *handle, bend_delete_rr *rr)
1117 {
1118         perl_call_sv(delete_ref, G_VOID | G_DISCARD | G_NOARGS);
1119         return 0;
1120 }
1121
1122
1123 int bend_scan(void *handle, bend_scan_rr *rr)
1124 {
1125         HV *href;
1126         AV *aref;
1127         AV *list;
1128         AV *entries;
1129         HV *scan_item;
1130         struct scan_entry *scan_list;
1131         struct scan_entry *buffer;
1132         int *step_size = rr->step_size;
1133         int i;
1134         char **basenames;
1135         SV **temp;
1136         SV *err_code = sv_newmortal();
1137         SV *err_str = sv_newmortal();
1138         SV *point = sv_newmortal();
1139         SV *status = sv_newmortal();
1140         SV *number = sv_newmortal();
1141         char *ptr;
1142         char *ODR_errstr;
1143         STRLEN len;
1144         int term_len;
1145         SV *entries_ref;
1146         Zfront_handle *zhandle = (Zfront_handle *)handle;
1147         CV* handler_cv = 0;
1148
1149         dSP;
1150         ENTER;
1151         SAVETMPS;
1152         href = newHV();
1153         list = newAV();
1154         if (rr->term->term->which == Z_Term_general)
1155         {
1156                 term_len = rr->term->term->u.general->len;
1157                 hv_store(href, "TERM", 4, newSVpv((char*) rr->term->term->u.general->buf, term_len), 0);
1158         } else {
1159                 rr->errcode = 229;      /* Unsupported term type */
1160                 return 0;
1161         }
1162         hv_store(href, "STEP", 4, newSViv(*step_size), 0);
1163         hv_store(href, "NUMBER", 6, newSViv(rr->num_entries), 0);
1164         hv_store(href, "POS", 3, newSViv(rr->term_position), 0);
1165         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1166         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1167         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1168         hv_store(href, "STATUS", 6, newSViv(BEND_SCAN_SUCCESS), 0);
1169         hv_store(href, "ENTRIES", 7, newRV((SV *) list), 0);
1170         aref = newAV();
1171         basenames = rr->basenames;
1172         for (i = 0; i < rr->num_bases; i++)
1173         {
1174                 av_push(aref, newSVpv(*basenames++, 0));
1175         }
1176         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
1177
1178         PUSHMARK(sp);
1179
1180         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1181
1182         PUTBACK;
1183
1184         handler_cv = simpleserver_sv2cv( scan_ref );
1185         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1186
1187         SPAGAIN;
1188
1189         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1190         err_code = newSVsv(*temp);
1191
1192         temp = hv_fetch(href, "ERR_STR", 7, 1);
1193         err_str = newSVsv(*temp);
1194
1195         temp = hv_fetch(href, "HANDLE", 6, 1);
1196         point = newSVsv(*temp);
1197
1198         temp = hv_fetch(href, "STATUS", 6, 1);
1199         status = newSVsv(*temp);
1200         
1201         temp = hv_fetch(href, "NUMBER", 6, 1);
1202         number = newSVsv(*temp);
1203
1204         temp = hv_fetch(href, "ENTRIES", 7, 1);
1205         entries_ref = newSVsv(*temp);
1206
1207         PUTBACK;
1208         FREETMPS;
1209         LEAVE;
1210
1211         ptr = SvPV(err_str, len);
1212         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1213         strcpy(ODR_errstr, ptr);
1214         rr->errstring = ODR_errstr;
1215         rr->errcode = SvIV(err_code);
1216         rr->num_entries = SvIV(number);
1217         rr->status = SvIV(status);
1218         scan_list = (struct scan_entry *) odr_malloc (rr->stream, rr->num_entries * sizeof(*scan_list));
1219         buffer = scan_list;
1220         entries = (AV *)SvRV(entries_ref);
1221         for (i = 0; i < rr->num_entries; i++)
1222         {
1223                 scan_item = (HV *)SvRV(sv_2mortal(av_shift(entries)));
1224                 temp = hv_fetch(scan_item, "TERM", 4, 1);
1225                 ptr = SvPV(*temp, len);
1226                 buffer->term = (char *) odr_malloc (rr->stream, len + 1); 
1227                 strcpy(buffer->term, ptr);
1228                 temp = hv_fetch(scan_item, "OCCURRENCE", 10, 1); 
1229                 buffer->occurrences = SvIV(*temp);
1230                 buffer++;
1231                 hv_undef(scan_item);
1232         }
1233         rr->entries = scan_list;
1234         zhandle->handle = point;
1235         handle = zhandle;
1236         sv_free(err_code);
1237         sv_free(err_str);
1238         sv_free(status);
1239         sv_free(number);
1240         hv_undef(href);
1241         sv_free((SV *)href);
1242         av_undef(aref);
1243         sv_free((SV *)aref);
1244         av_undef(list);
1245         sv_free((SV *)list);
1246         av_undef(entries);
1247         /*sv_free((SV *)entries);*/
1248         sv_free(entries_ref);
1249
1250         return 0;
1251 }
1252
1253 int bend_explain(void *handle, bend_explain_rr *q)
1254 {
1255         HV *href;
1256         CV *handler_cv = 0;
1257         SV **temp;
1258         char *explain;
1259         SV *explainsv;
1260         STRLEN len;
1261         Zfront_handle *zhandle = (Zfront_handle *)handle;
1262
1263         dSP;
1264         ENTER;
1265         SAVETMPS;
1266
1267         href = newHV();
1268         hv_store(href, "EXPLAIN", 7, newSVpv("", 0), 0);
1269         hv_store(href, "DATABASE", 8, newSVpv(q->database, 0), 0);
1270         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1271
1272         PUSHMARK(sp);
1273         XPUSHs(sv_2mortal(newRV((SV*) href)));
1274         PUTBACK;
1275
1276         handler_cv = simpleserver_sv2cv(explain_ref);
1277         perl_call_sv((SV*) handler_cv, G_SCALAR | G_DISCARD);
1278
1279         SPAGAIN;
1280
1281         temp = hv_fetch(href, "EXPLAIN", 7, 1);
1282         explainsv = newSVsv(*temp);
1283
1284         PUTBACK;
1285         FREETMPS;
1286         LEAVE;
1287
1288         explain = SvPV(explainsv, len);
1289         q->explain_buf = (char*) odr_malloc(q->stream, len + 1);
1290         strcpy(q->explain_buf, explain);
1291
1292         return 0;
1293 }
1294
1295 bend_initresult *bend_init(bend_initrequest *q)
1296 {
1297         int dummy = simpleserver_clone();
1298         bend_initresult *r = (bend_initresult *)
1299                 odr_malloc (q->stream, sizeof(*r));
1300         char *ptr;
1301         CV* handler_cv = 0;
1302         dSP;
1303         STRLEN len;
1304         NMEM nmem = nmem_create();
1305         Zfront_handle *zhandle =  (Zfront_handle *) nmem_malloc (nmem,
1306                         sizeof(*zhandle));
1307         SV *handle;
1308         HV *href;
1309         SV **temp;
1310
1311         ENTER;
1312         SAVETMPS;
1313
1314         zhandle->nmem = nmem;
1315         zhandle->stop_flag = 0;
1316
1317         if (sort_ref)
1318         {
1319             q->bend_sort = bend_sort;
1320         }
1321         if (search_ref)
1322         {
1323                 q->bend_search = bend_search;
1324         }
1325         if (present_ref)
1326         {
1327                 q->bend_present = bend_present;
1328         }
1329         /*q->bend_esrequest = bend_esrequest;*/
1330         /*q->bend_delete = bend_delete;*/
1331         if (fetch_ref)
1332         {
1333                 q->bend_fetch = bend_fetch;
1334         }
1335         if (scan_ref)
1336         {
1337                 q->bend_scan = bend_scan;
1338         }
1339         if (explain_ref)
1340         {
1341                 q->bend_explain = bend_explain;
1342         }
1343
1344         href = newHV(); 
1345         hv_store(href, "IMP_ID", 6, newSVpv("", 0), 0);
1346         hv_store(href, "IMP_NAME", 8, newSVpv("", 0), 0);
1347         hv_store(href, "IMP_VER", 7, newSVpv("", 0), 0);
1348         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1349         hv_store(href, "ERR_STR", 7, newSViv(0), 0);
1350         hv_store(href, "PEER_NAME", 9, newSVpv(q->peer_name, 0), 0);
1351         hv_store(href, "HANDLE", 6, newSVsv(&sv_undef), 0);
1352         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1353         if (q->auth) {
1354             char *user = NULL;
1355             char *passwd = NULL;
1356             if (q->auth->which == Z_IdAuthentication_open) {
1357                 char *cp;
1358                 user = nmem_strdup (odr_getmem (q->stream), q->auth->u.open);
1359                 cp = strchr (user, '/');
1360                 if (cp) {
1361                     /* password after / given */
1362                     *cp = '\0';
1363                     passwd = cp+1;
1364                 }
1365             } else if (q->auth->which == Z_IdAuthentication_idPass) {
1366                 user = q->auth->u.idPass->userId;
1367                 passwd = q->auth->u.idPass->password;
1368             }
1369             /* ### some code paths have user/password unassigned here */
1370             if (user)
1371                 hv_store(href, "USER", 4, newSVpv(user, 0), 0);
1372             if (passwd)
1373                 hv_store(href, "PASS", 4, newSVpv(passwd, 0), 0);
1374         }
1375
1376         PUSHMARK(sp);   
1377
1378         XPUSHs(sv_2mortal(newRV((SV*) href)));
1379
1380         PUTBACK;
1381
1382         if (init_ref != NULL)
1383         {
1384              handler_cv = simpleserver_sv2cv( init_ref );
1385              perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1386         }
1387
1388         SPAGAIN;
1389
1390         temp = hv_fetch(href, "IMP_ID", 6, 1);
1391         ptr = SvPV(*temp, len);
1392         q->implementation_id = nmem_strdup(nmem, ptr);
1393
1394         temp = hv_fetch(href, "IMP_NAME", 8, 1);
1395         ptr = SvPV(*temp, len);
1396         q->implementation_name = nmem_strdup(nmem, ptr);
1397
1398         temp = hv_fetch(href, "IMP_VER", 7, 1);
1399         ptr = SvPV(*temp, len);
1400         q->implementation_version = nmem_strdup(nmem, ptr);
1401
1402         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1403         r->errcode = SvIV(*temp);
1404
1405         temp = hv_fetch(href, "ERR_STR", 7, 1);
1406         ptr = SvPV(*temp, len);
1407         r->errstring = (char *)odr_malloc(q->stream, len + 1);
1408         strcpy(r->errstring, ptr);
1409
1410         temp = hv_fetch(href, "HANDLE", 6, 1);
1411         handle= newSVsv(*temp);
1412         zhandle->handle = handle;
1413
1414         r->handle = zhandle;
1415
1416         hv_undef(href);
1417         sv_free((SV*) href);
1418
1419         PUTBACK;
1420         FREETMPS;
1421         LEAVE;
1422         
1423         return r;       
1424 }
1425
1426 void bend_close(void *handle)
1427 {
1428         HV *href;
1429         Zfront_handle *zhandle = (Zfront_handle *)handle;
1430         CV* handler_cv = 0;
1431         int stop_flag = 0;
1432         dSP;
1433         ENTER;
1434         SAVETMPS;
1435
1436         if (close_ref)
1437         {
1438                 href = newHV();
1439                 hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1440
1441                 PUSHMARK(sp);
1442
1443                 XPUSHs(sv_2mortal(newRV((SV *)href)));
1444
1445                 PUTBACK;
1446         
1447                 handler_cv = simpleserver_sv2cv( close_ref );
1448                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1449         
1450                 SPAGAIN;
1451
1452                 sv_free((SV*) href);
1453         }
1454         else
1455                 sv_free(zhandle->handle);
1456         PUTBACK;
1457         FREETMPS;
1458         LEAVE;
1459         stop_flag = zhandle->stop_flag;
1460         nmem_destroy(zhandle->nmem);
1461         simpleserver_free();
1462
1463         if (stop_flag)
1464                 exit(0);
1465         return;
1466 }
1467
1468
1469 MODULE = Net::Z3950::SimpleServer       PACKAGE = Net::Z3950::SimpleServer
1470
1471 PROTOTYPES: DISABLE
1472
1473
1474 void
1475 set_init_handler(arg)
1476                 SV *arg
1477         CODE:
1478                 init_ref = newSVsv(arg);
1479                 
1480
1481 void
1482 set_close_handler(arg)
1483                 SV *arg
1484         CODE:
1485                 close_ref = newSVsv(arg);
1486
1487
1488 void
1489 set_sort_handler(arg)
1490                 SV *arg
1491         CODE:
1492                 sort_ref = newSVsv(arg);
1493
1494 void
1495 set_search_handler(arg)
1496                 SV *arg
1497         CODE:
1498                 search_ref = newSVsv(arg);
1499
1500
1501 void
1502 set_fetch_handler(arg)
1503                 SV *arg
1504         CODE:
1505                 fetch_ref = newSVsv(arg);
1506
1507
1508 void
1509 set_present_handler(arg)
1510                 SV *arg
1511         CODE:
1512                 present_ref = newSVsv(arg);
1513
1514
1515 void
1516 set_esrequest_handler(arg)
1517                 SV *arg
1518         CODE:
1519                 esrequest_ref = newSVsv(arg);
1520
1521
1522 void
1523 set_delete_handler(arg)
1524                 SV *arg
1525         CODE:
1526                 delete_ref = newSVsv(arg);
1527
1528
1529 void
1530 set_scan_handler(arg)
1531                 SV *arg
1532         CODE:
1533                 scan_ref = newSVsv(arg);
1534
1535 void
1536 set_explain_handler(arg)
1537                 SV *arg
1538         CODE:
1539                 explain_ref = newSVsv(arg);
1540
1541 int
1542 start_server(...)
1543         PREINIT:
1544                 char **argv;
1545                 char **argv_buf;
1546                 char *ptr;
1547                 int i;
1548                 STRLEN len;
1549         CODE:
1550                 argv_buf = (char **)xmalloc((items + 1) * sizeof(char *));
1551                 argv = argv_buf;
1552                 for (i = 0; i < items; i++)
1553                 {
1554                         ptr = SvPV(ST(i), len);
1555                         *argv_buf = (char *)xmalloc(len + 1);
1556                         strcpy(*argv_buf++, ptr); 
1557                 }
1558                 *argv_buf = NULL;
1559                 root_perl_context = PERL_GET_CONTEXT;
1560                 yaz_mutex_create(&simpleserver_mutex);
1561 #if 0
1562                 /* only for debugging perl_clone .. */
1563                 tst_clones();
1564 #endif
1565                 
1566                 RETVAL = statserv_main(items, argv, bend_init, bend_close);
1567         OUTPUT:
1568                 RETVAL
1569
1570
1571 int
1572 ScanSuccess()
1573         CODE:
1574                 RETVAL = BEND_SCAN_SUCCESS;
1575         OUTPUT:
1576                 RETVAL
1577
1578 int
1579 ScanPartial()
1580         CODE:
1581                 RETVAL = BEND_SCAN_PARTIAL;
1582         OUTPUT:
1583                 RETVAL
1584
1585  
1586 void
1587 yazlog(arg)
1588                 SV *arg
1589         CODE:
1590                 STRLEN len;
1591                 char *ptr;
1592                 ptr = SvPV(arg, len);
1593                 yaz_log(YLOG_LOG, "%.*s", len, ptr);