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