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