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