updating dependency on libyaz3-dev
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /*
2  * $Id: SimpleServer.xs,v 1.63 2007-05-23 10:22:00 sondberg 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 #include <yaz/oid_db.h>
42 #ifdef WIN32
43 #else
44 #include <unistd.h>
45 #endif
46 #include <stdlib.h>
47 #include <ctype.h>
48 #define GRS_MAX_FIELDS 500 
49 #ifdef ASN_COMPILED
50 #include <yaz/ill.h>
51 #endif
52 #ifndef sv_undef                /* To fix the problem with Perl 5.6.0 */
53 #define sv_undef PL_sv_undef
54 #endif
55
56 YAZ_MUTEX simpleserver_mutex;
57
58 typedef struct {
59         SV *handle;
60
61         SV *init_ref;
62         SV *close_ref;
63         SV *sort_ref;
64         SV *search_ref;
65         SV *fetch_ref;
66         SV *present_ref;
67         SV *esrequest_ref;
68         SV *delete_ref;
69         SV *scan_ref;
70         SV *explain_ref;
71         NMEM nmem;
72         int stop_flag;  /* is used to stop server prematurely .. */
73 } Zfront_handle;
74
75 #define ENABLE_STOP_SERVER 0
76
77 SV *init_ref = NULL;
78 SV *close_ref = NULL;
79 SV *sort_ref = NULL;
80 SV *search_ref = NULL;
81 SV *fetch_ref = NULL;
82 SV *present_ref = NULL;
83 SV *esrequest_ref = NULL;
84 SV *delete_ref = NULL;
85 SV *scan_ref = NULL;
86 SV *explain_ref = NULL;
87 PerlInterpreter *root_perl_context;
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 = odr_intdup(o, type);
231                 t->tagValue = (Z_StringOrNumeric *)
232                         odr_malloc(o, sizeof(Z_StringOrNumeric));
233                 if ((ivalue = atoi(value)))
234                 {
235                         t->tagValue->which = Z_StringOrNumeric_numeric;
236                         t->tagValue->u.numeric = odr_intdup(o, ivalue);
237                 }
238                 else
239                 {
240                         t->tagValue->which = Z_StringOrNumeric_string;
241                         t->tagValue->u.string = odr_strdup(o, value);
242                 }
243                 t->tagOccurrence = 0;
244                 t->metaData = 0;
245                 t->appliedVariant = 0;
246                 t->content = c = (Z_ElementData *)odr_malloc(o, sizeof(Z_ElementData));
247                 if (*buf == '{')
248                 {
249                         c->which = Z_ElementData_subtree;
250                         c->u.subtree = read_grs1(str, o);
251                 }
252                 else
253                 {
254                         c->which = Z_ElementData_string;
255                         c->u.string = odr_strdup(o, buf);
256                 }
257                 r->num_elements++;
258         }
259 }
260
261
262
263 static void oid2str(Odr_oid *o, WRBUF buf)
264 {
265     for (; *o >= 0; o++) {
266         char ibuf[16];
267         sprintf(ibuf, "%d", *o);
268         wrbuf_puts(buf, ibuf);
269         if (o[1] > 0)
270             wrbuf_putc(buf, '.');
271     }
272 }
273
274 WRBUF oid2dotted(Odr_oid *oid)
275 {
276     WRBUF buf = wrbuf_alloc();
277     oid2str(oid, buf);
278     return buf;
279 }
280                 
281
282 WRBUF zquery2pquery(Z_Query *q)
283 {
284     WRBUF buf = wrbuf_alloc();
285
286     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
287         return 0;
288     yaz_rpnquery_to_wrbuf(buf, q->u.type_1);
289     return buf;
290 }
291
292
293 /* Lifted verbatim from Net::Z3950 yazwrap/util.c */
294 #include <stdarg.h>
295 void fatal(char *fmt, ...)
296 {
297     va_list ap;
298
299     fprintf(stderr, "FATAL (SimpleServer): ");
300     va_start(ap, fmt);
301     vfprintf(stderr, fmt, ap);
302     va_end(ap);
303     fprintf(stderr, "\n");
304     abort();
305 }
306
307
308 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
309 /*
310  * Creates a new Perl object of type `class'; the newly-created scalar
311  * that is a reference to the blessed thingy `referent' is returned.
312  */
313 static SV *newObject(char *class, SV *referent)
314 {
315     HV *stash;
316     SV *sv;
317
318     sv = newRV_noinc((SV*) referent);
319     stash = gv_stashpv(class, 0);
320     if (stash == 0)
321         fatal("attempt to create object of undefined class '%s'", class);
322     /*assert(stash != 0);*/
323     sv_bless(sv, stash);
324     return sv;
325 }
326
327
328 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
329 static void setMember(HV *hv, char *name, SV *val)
330 {
331     /* We don't increment `val's reference count -- I think this is
332      * right because it's created with a refcount of 1, and in fact
333      * the reference via this hash is the only reference to it in
334      * general.
335      */
336     if (!hv_store(hv, name, (U32) strlen(name), val, (U32) 0))
337         fatal("couldn't store member in hash");
338 }
339
340
341 /* Lifted verbatim from Net::Z3950 yazwrap/receive.c */
342 static SV *translateOID(Odr_oid *x)
343 {
344     /* Yaz represents an OID by an int array terminated by a negative
345      * value, typically -1; we represent it as a reference to a
346      * blessed scalar string of "."-separated elements.
347      */
348     char buf[1000];
349     int i;
350
351     *buf = '\0';
352     for (i = 0; x[i] >= 0; i++) {
353         sprintf(buf + strlen(buf), "%d", (int) x[i]);
354         if (x[i+1] >- 0)
355             strcat(buf, ".");
356     }
357
358     /*
359      * ### We'd like to return a blessed scalar (string) here, but of
360      *  course you can't do that in Perl: only references can be
361      *  blessed, so we'd have to return a _reference_ to a string, and
362      *  bless _that_.  Better to do without the blessing, I think.
363      */
364     if (1) {
365         return newSVpv(buf, 0);
366     } else {
367         return newObject("Net::Z3950::APDU::OID", newSVpv(buf, 0));
368     }
369 }
370
371
372 static SV *rpn2perl(Z_RPNStructure *s)
373 {
374     SV *sv;
375     HV *hv;
376     AV *av;
377
378     switch (s->which) {
379     case Z_RPNStructure_simple: {
380         Z_Operand *o = s->u.simple;
381         Z_AttributesPlusTerm *at;
382         if (o->which == Z_Operand_resultSetId) {
383             SV *sv2;
384             /* This code causes a SIGBUS on my machine, and I have no
385                idea why.  It seems as clear as day to me */
386             char *rsid = (char*) o->u.resultSetId;
387             printf("Encoding resultSetId '%s'\n", rsid);
388             sv = newObject("Net::Z3950::RPN::RSID", (SV*) (hv = newHV()));
389             printf("Made sv=0x%lx, hv=0x%lx\n",
390                    (unsigned long) sv ,(unsigned long) hv);
391             sv2 = newSVpv(rsid, strlen(rsid));
392             setMember(hv, "id", sv2);
393             printf("Set hv{id} to 0x%lx\n", (unsigned long) sv2);
394             return sv;
395         }
396         if (o->which != Z_Operand_APT)
397             fatal("can't handle RPN simples other than APT and RSID");
398         at = o->u.attributesPlusTerm;
399         if (at->term->which != Z_Term_general)
400             fatal("can't handle RPN terms other than general");
401
402         sv = newObject("Net::Z3950::RPN::Term", (SV*) (hv = newHV()));
403         if (at->attributes) {
404             int i;
405             SV *attrs = newObject("Net::Z3950::RPN::Attributes",
406                                   (SV*) (av = newAV()));
407             for (i = 0; i < at->attributes->num_attributes; i++) {
408                 Z_AttributeElement *elem = at->attributes->attributes[i];
409                 HV *hv2;
410                 SV *tmp = newObject("Net::Z3950::RPN::Attribute",
411                                     (SV*) (hv2 = newHV()));
412                 if (elem->attributeSet)
413                     setMember(hv2, "attributeSet",
414                               translateOID(elem->attributeSet));
415                 setMember(hv2, "attributeType",
416                           newSViv(*elem->attributeType));
417                 assert(elem->which == Z_AttributeValue_numeric);
418                 setMember(hv2, "attributeValue",
419                           newSViv(*elem->value.numeric));
420                 av_push(av, tmp);
421             }
422             setMember(hv, "attributes", attrs);
423         }
424         setMember(hv, "term", newSVpv((char*) at->term->u.general->buf,
425                                       at->term->u.general->len));
426         return sv;
427     }
428     case Z_RPNStructure_complex: {
429         SV *tmp;
430         Z_Complex *c = s->u.complex;
431         char *type = 0;         /* vacuous assignment satisfies gcc -Wall */
432         switch (c->roperator->which) {
433         case Z_Operator_and:     type = "Net::Z3950::RPN::And"; break;
434         case Z_Operator_or:      type = "Net::Z3950::RPN::Or"; break;
435         case Z_Operator_and_not: type = "Net::Z3950::RPN::AndNot"; break;
436         case Z_Operator_prox:    fatal("proximity not yet supported");
437         default: fatal("unknown RPN operator %d", (int) c->roperator->which);
438         }
439         sv = newObject(type, (SV*) (av = newAV()));
440         if ((tmp = rpn2perl(c->s1)) == 0)
441             return 0;
442         av_push(av, tmp);
443         if ((tmp = rpn2perl(c->s2)) == 0)
444             return 0;
445         av_push(av, tmp);
446         return sv;
447     }
448     default: fatal("unknown RPN node type %d", (int) s->which);
449     }
450
451     return 0;
452 }
453
454
455 /* Decode the Z_SortAttributes struct and store the whole thing into the
456  * hash by reference
457  */
458 int simpleserver_ExpandSortAttributes (HV *sort_spec, Z_SortAttributes *sattr)
459 {
460     WRBUF attrset_wr = wrbuf_alloc();
461     AV *list = newAV();
462     Z_AttributeList *attr_list = sattr->list;
463     int i;
464
465     oid2str(sattr->id, attrset_wr);
466     hv_store(sort_spec, "ATTRSET", 7,
467              newSVpv(attrset_wr->buf, attrset_wr->pos), 0);
468     wrbuf_destroy(attrset_wr);
469
470     hv_store(sort_spec, "SORT_ATTR", 9, newRV( sv_2mortal( (SV*) list ) ), 0);
471
472     for (i = 0; i < attr_list->num_attributes; i++) 
473     {
474         Z_AttributeElement *attr = *attr_list->attributes++; 
475         HV *attr_spec = newHV();
476                 
477         av_push(list, newRV( sv_2mortal( (SV*) attr_spec ) ));
478         hv_store(attr_spec, "ATTR_TYPE", 9, newSViv(*attr->attributeType), 0);
479
480         if (attr->which == Z_AttributeValue_numeric)
481         {
482             hv_store(attr_spec, "ATTR_VALUE", 10,
483                      newSViv(*attr->value.numeric), 0);
484         } else {
485             return 0;
486         }
487     }
488
489     return 1;
490 }
491
492
493 /* Decode the Z_SortKeySpec struct and store the whole thing in a perl hash */
494 int simpleserver_SortKeySpecToHash (HV *sort_spec, Z_SortKeySpec *spec)
495 {
496     Z_SortElement *element = spec->sortElement;
497
498     hv_store(sort_spec, "RELATION", 8, newSViv(*spec->sortRelation), 0);
499     hv_store(sort_spec, "CASE", 4, newSViv(*spec->caseSensitivity), 0);
500     hv_store(sort_spec, "MISSING", 7, newSViv(spec->which), 0);
501
502     if (element->which == Z_SortElement_generic)
503     {
504         Z_SortKey *key = element->u.generic;
505
506         if (key->which == Z_SortKey_sortField)
507         {
508             hv_store(sort_spec, "SORTFIELD", 9,
509                      newSVpv((char *) key->u.sortField, 0), 0);
510         }
511         else if (key->which == Z_SortKey_elementSpec)
512         {
513             Z_Specification *zspec = key->u.elementSpec;
514             
515             hv_store(sort_spec, "ELEMENTSPEC_TYPE", 16,
516                      newSViv(zspec->which), 0);
517
518             if (zspec->which == Z_Schema_oid)
519             {
520                 WRBUF elementSpec = wrbuf_alloc();
521
522                 oid2str(zspec->schema.oid, elementSpec);
523                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
524                          newSVpv(elementSpec->buf, elementSpec->pos), 0);
525                 wrbuf_destroy(elementSpec);
526             }
527             else if (zspec->which == Z_Schema_uri)
528             {
529                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
530                          newSVpv((char *) zspec->schema.uri, 0), 0);
531             }
532         }
533         else if (key->which == Z_SortKey_sortAttributes)
534         {
535             return simpleserver_ExpandSortAttributes(sort_spec,
536                                                      key->u.sortAttributes);
537         }
538         else
539         {
540             return 0;
541         }
542     }
543     else
544     {
545         return 0;
546     }
547
548     return 1;
549 }
550
551
552 static SV *zquery2perl(Z_Query *q)
553 {
554     SV *sv;
555     HV *hv;
556
557     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
558         return 0;
559     sv = newObject("Net::Z3950::APDU::Query", (SV*) (hv = newHV()));
560     if (q->u.type_1->attributeSetId)
561         setMember(hv, "attributeSet",
562                   translateOID(q->u.type_1->attributeSetId));
563     setMember(hv, "query", rpn2perl(q->u.type_1->RPNStructure));
564     return sv;
565 }
566
567
568 int bend_sort(void *handle, bend_sort_rr *rr)
569 {
570         HV *href;
571         AV *aref;
572         AV *sort_seq;
573         SV **temp;
574         SV *err_code;
575         SV *err_str;
576         SV *status;
577         SV *point;
578         STRLEN len;
579         char *ptr;
580         char *ODR_err_str;
581         char **input_setnames;
582         Zfront_handle *zhandle = (Zfront_handle *)handle;
583         Z_SortKeySpecList *sort_spec = rr->sort_sequence;
584         int i;
585         
586         dSP;
587         ENTER;
588         SAVETMPS;
589         
590         aref = newAV();
591         input_setnames = rr->input_setnames;
592         for (i = 0; i < rr->num_input_setnames; i++)
593         {
594             av_push(aref, newSVpv(*input_setnames++, 0));
595         }
596
597         sort_seq = newAV();
598         for (i = 0; i < sort_spec->num_specs; i++)
599         {
600             Z_SortKeySpec *spec = *sort_spec->specs++;
601             HV *sort_spec = newHV();
602
603             if ( simpleserver_SortKeySpecToHash(sort_spec, spec) )
604                 av_push(sort_seq, newRV( sv_2mortal( (SV*) sort_spec ) ));
605             else
606             {
607                 rr->errcode = 207;
608                 return 0;
609             }
610         }
611         
612         href = newHV();
613         hv_store(href, "INPUT", 5, newRV( (SV*) aref), 0);
614         hv_store(href, "OUTPUT", 6, newSVpv(rr->output_setname, 0), 0);
615         hv_store(href, "SEQUENCE", 8, newRV( (SV*) sort_seq), 0);
616         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
617         hv_store(href, "STATUS", 6, newSViv(0), 0);
618         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
619         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
620
621         PUSHMARK(sp);
622
623         XPUSHs(sv_2mortal(newRV( (SV*) href)));
624
625         PUTBACK;
626
627         perl_call_sv(sort_ref, G_SCALAR | G_DISCARD);
628
629         SPAGAIN;
630
631         temp = hv_fetch(href, "ERR_CODE", 8, 1);
632         err_code = newSVsv(*temp);
633
634         temp = hv_fetch(href, "ERR_STR", 7, 1);
635         err_str = newSVsv(*temp);
636
637         temp = hv_fetch(href, "STATUS", 6, 1);
638         status = newSVsv(*temp);
639
640         temp = hv_fetch(href, "HANDLE", 6, 1);
641         point = newSVsv(*temp);
642
643         hv_undef(href);
644         av_undef(aref);
645         av_undef(sort_seq);
646        
647         sv_free( (SV*) aref);
648         sv_free( (SV*) href);
649         sv_free( (SV*) sort_seq);
650
651         rr->errcode = SvIV(err_code);
652         rr->sort_status = SvIV(status);
653         
654         ptr = SvPV(err_str, len);
655         ODR_err_str = (char *)odr_malloc(rr->stream, len + 1);
656         strcpy(ODR_err_str, ptr);
657         rr->errstring = ODR_err_str;
658         zhandle->handle = point;
659
660         sv_free(err_code);
661         sv_free(err_str);
662         sv_free(status);
663         
664         PUTBACK;
665         FREETMPS;
666         LEAVE;
667
668         return 0;
669 }
670
671
672 int bend_search(void *handle, bend_search_rr *rr)
673 {
674         HV *href;
675         AV *aref;
676         SV **temp;
677         char *ODR_errstr;
678         STRLEN len;
679         int i;
680         char **basenames;
681         WRBUF query;
682         char *ptr;
683         SV *point;
684         Zfront_handle *zhandle = (Zfront_handle *)handle;
685         CV* handler_cv = 0;
686         SV *rpnSV;
687
688         dSP;
689         ENTER;
690         SAVETMPS;
691
692         aref = newAV();
693         basenames = rr->basenames;
694         for (i = 0; i < rr->num_bases; i++)
695         {
696                 av_push(aref, newSVpv(*basenames++, 0));
697         }
698 #if ENABLE_STOP_SERVER
699         if (rr->num_bases == 1 && !strcmp(rr->basenames[0], "XXstop"))
700         {
701                 zhandle->stop_flag = 1;
702         }
703 #endif
704         href = newHV();         
705         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
706         if (rr->srw_sortKeys && *rr->srw_sortKeys) 
707             hv_store(href, "SRW_SORTKEYS", 12, newSVpv(rr->srw_sortKeys, 0), 0);
708         hv_store(href, "REPL_SET", 8, newSViv(rr->replace_set), 0);
709         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
710         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
711         hv_store(href, "HITS", 4, newSViv(0), 0);
712         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
713         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
714         hv_store(href, "PID", 3, newSViv(getpid()), 0);
715         if ((rpnSV = zquery2perl(rr->query)) != 0) {
716             hv_store(href, "RPN", 3, rpnSV, 0);
717         }
718         query = zquery2pquery(rr->query);
719         if (query)
720         {
721                 hv_store(href, "QUERY", 5, newSVpv((char *)query->buf, query->pos), 0);
722         }
723         else if (rr->query->which == Z_Query_type_104 &&
724                  rr->query->u.type_104->which == Z_External_CQL) {
725             hv_store(href, "CQL", 3,
726                      newSVpv(rr->query->u.type_104->u.cql, 0), 0);
727         }
728         else
729         {       
730                 rr->errcode = 108;
731                 return 0;
732         }
733         PUSHMARK(sp);
734         
735         XPUSHs(sv_2mortal(newRV( (SV*) href)));
736         
737         PUTBACK;
738
739         handler_cv = simpleserver_sv2cv( search_ref );
740         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
741
742         SPAGAIN;
743
744         temp = hv_fetch(href, "HITS", 4, 1);
745         rr->hits = SvIV(*temp);
746
747         temp = hv_fetch(href, "ERR_CODE", 8, 1);
748         rr->errcode = SvIV(*temp);
749
750         temp = hv_fetch(href, "ERR_STR", 7, 1);
751         ptr = SvPV(*temp, len);
752         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
753         strcpy(ODR_errstr, ptr);
754         rr->errstring = ODR_errstr;
755
756         temp = hv_fetch(href, "HANDLE", 6, 1);
757         point = newSVsv(*temp);
758
759         hv_undef(href);
760         av_undef(aref);
761
762         zhandle->handle = point;
763         sv_free( (SV*) aref);
764         sv_free( (SV*) href);
765         if (query)
766             wrbuf_destroy(query);
767         PUTBACK;
768         FREETMPS;
769         LEAVE;
770         return 0;
771 }
772
773
774 int bend_fetch(void *handle, bend_fetch_rr *rr)
775 {
776         HV *href;
777         SV **temp;
778         SV *basename;
779         SV *record;
780         SV *last;
781         SV *err_code;
782         SV *err_string;
783         SV *sur_flag;
784         SV *point;
785         SV *rep_form;
786         SV *schema = 0;
787         char *ptr;
788         char *ODR_record;
789         char *ODR_basename;
790         char *ODR_errstr;
791         WRBUF oid_dotted;
792         Zfront_handle *zhandle = (Zfront_handle *)handle;
793         CV* handler_cv = 0;
794
795         Z_RecordComposition *composition;
796         Z_ElementSetNames *simple;
797         Z_CompSpec *complex;
798         STRLEN length;
799
800         dSP;
801         ENTER;
802         SAVETMPS;
803
804         rr->errcode = 0;
805         href = newHV();
806         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
807         if (rr->schema)
808                 hv_store(href, "SCHEMA", 6, newSVpv(rr->schema, 0), 0);
809         else
810                 hv_store(href, "SCHEMA", 6, newSVpv("", 0), 0);
811
812         temp = hv_store(href, "OFFSET", 6, newSViv(rr->number), 0);
813         if (rr->request_format != 0) {
814             oid_dotted = oid2dotted(rr->request_format);
815         } else {
816             /* Probably an SRU request: assume XML is required */
817             oid_dotted = wrbuf_alloc();
818             wrbuf_puts(oid_dotted, "1.2.840.10003.5.109.10");
819         }
820         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
821         hv_store(href, "REP_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
822         hv_store(href, "BASENAME", 8, newSVpv("", 0), 0);
823         hv_store(href, "RECORD", 6, newSVpv("", 0), 0);
824         hv_store(href, "LAST", 4, newSViv(0), 0);
825         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
826         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
827         hv_store(href, "SUR_FLAG", 8, newSViv(0), 0);
828         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
829         hv_store(href, "PID", 3, newSViv(getpid()), 0);
830         if (rr->comp)
831         {
832                 composition = rr->comp;
833                 if (composition->which == Z_RecordComp_simple)
834                 {
835                         simple = composition->u.simple;
836                         if (simple->which == Z_ElementSetNames_generic)
837                         {
838                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
839                         } 
840                         else
841                         {
842                                 rr->errcode = 26;
843                         }
844                 }
845                 else if (composition->which == Z_RecordComp_complex)
846                 {
847                         if (composition->u.complex->generic &&
848
849                                         composition->u.complex->generic &&
850                                         composition->u.complex->generic->elementSpec &&
851                                         composition->u.complex->generic->elementSpec->which ==
852                                         Z_ElementSpec_elementSetName)
853                         {
854                                 complex = composition->u.complex;
855                                 hv_store(href, "COMP", 4,
856                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
857                         }
858                         else
859                         {
860 #if 0   /* For now ignore this error, which is ubiquitous in SRU */
861                                 fprintf(stderr, "complex is weird\n");
862                                 rr->errcode = 26;
863                                 return 0;
864 #endif /*0*/
865                         }
866                 }
867                 else
868                 {
869                         rr->errcode = 26;
870                         return 0;
871                 }
872         }
873
874         PUSHMARK(sp);
875
876         XPUSHs(sv_2mortal(newRV( (SV*) href)));
877
878         PUTBACK;
879         
880         handler_cv = simpleserver_sv2cv( fetch_ref );
881         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
882
883         SPAGAIN;
884
885         temp = hv_fetch(href, "BASENAME", 8, 1);
886         basename = newSVsv(*temp);
887
888         temp = hv_fetch(href, "RECORD", 6, 1);
889         record = newSVsv(*temp);
890
891         temp = hv_fetch(href, "LAST", 4, 1);
892         last = newSVsv(*temp);
893
894         temp = hv_fetch(href, "ERR_CODE", 8, 1);
895         err_code = newSVsv(*temp);
896
897         temp = hv_fetch(href, "ERR_STR", 7, 1),
898         err_string = newSVsv(*temp);
899
900         temp = hv_fetch(href, "SUR_FLAG", 8, 1);
901         sur_flag = newSVsv(*temp);
902
903         temp = hv_fetch(href, "REP_FORM", 8, 1);
904         rep_form = newSVsv(*temp);
905
906         temp = hv_fetch(href, "SCHEMA", 6, 1);
907         if (temp != 0) {
908                 schema = newSVsv(*temp);
909                 ptr = SvPV(schema, length);
910                 if (length > 0) {
911                         rr->schema = (char *)odr_malloc(rr->stream, length + 1);
912                         strcpy(rr->schema, ptr);
913                 }
914         }
915
916         temp = hv_fetch(href, "HANDLE", 6, 1);
917         point = newSVsv(*temp);
918
919
920         hv_undef(href);
921         
922         ptr = SvPV(basename, length);
923         ODR_basename = (char *)odr_malloc(rr->stream, length + 1);
924         strcpy(ODR_basename, ptr);
925         rr->basename = ODR_basename;
926
927         ptr = SvPV(rep_form, length);
928
929         rr->output_format = yaz_string_to_oid_odr(yaz_oid_std(),
930                                         CLASS_RECSYN, ptr, rr->stream);
931         if (!rr->output_format)
932         {
933                 printf("Net::Z3950::SimpleServer: WARNING: Bad OID %s\n", ptr);
934                 rr->output_format =
935                         odr_oiddup(rr->stream, yaz_oid_recsyn_sutrs);
936         }
937         ptr = SvPV(record, length);
938         /* Treat GRS-1 records separately */
939         if (!oid_oidcmp(rr->output_format, 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);