da613c2f812e954efa29b6837559c127582d5b07
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /*
2  * $Id: SimpleServer.xs,v 1.69 2007-08-17 12:31: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
405     switch (s->which) {
406     case Z_RPNStructure_simple: {
407         Z_Operand *o = s->u.simple;
408         Z_AttributesPlusTerm *at;
409         if (o->which == Z_Operand_resultSetId) {
410             SV *sv2;
411             /* This code causes a SIGBUS on my machine, and I have no
412                idea why.  It seems as clear as day to me */
413             char *rsid = (char*) o->u.resultSetId;
414             printf("Encoding resultSetId '%s'\n", rsid);
415             sv = newObject("Net::Z3950::RPN::RSID", (SV*) (hv = newHV()));
416             printf("Made sv=0x%lx, hv=0x%lx\n",
417                    (unsigned long) sv ,(unsigned long) hv);
418             sv2 = newSVpv(rsid, strlen(rsid));
419             setMember(hv, "id", sv2);
420             printf("Set hv{id} to 0x%lx\n", (unsigned long) sv2);
421             return sv;
422         }
423         if (o->which != Z_Operand_APT)
424             fatal("can't handle RPN simples other than APT and RSID");
425         at = o->u.attributesPlusTerm;
426         if (at->term->which != Z_Term_general)
427             fatal("can't handle RPN terms other than general");
428
429         sv = newObject("Net::Z3950::RPN::Term", (SV*) (hv = newHV()));
430         if (at->attributes) {
431             int i;
432             SV *attrs = newObject("Net::Z3950::RPN::Attributes",
433                                   (SV*) (av = newAV()));
434             for (i = 0; i < at->attributes->num_attributes; i++) {
435                 Z_AttributeElement *elem = at->attributes->attributes[i];
436                 HV *hv2;
437                 SV *tmp = newObject("Net::Z3950::RPN::Attribute",
438                                     (SV*) (hv2 = newHV()));
439                 if (elem->attributeSet)
440                     setMember(hv2, "attributeSet",
441                               translateOID(elem->attributeSet));
442                 setMember(hv2, "attributeType",
443                           newSViv(*elem->attributeType));
444                 if (elem->which == Z_AttributeValue_numeric) {
445                     setMember(hv2, "attributeValue",
446                               newSViv(*elem->value.numeric));
447                 } else {
448                     assert(elem->which == Z_AttributeValue_complex);
449                     Z_ComplexAttribute *complex = elem->value.complex;
450                     Z_StringOrNumeric *son;
451                     /* We ignore semantic actions and multiple values */
452                     assert(complex->num_list > 0);
453                     son = complex->list[0];
454                     if (son->which == Z_StringOrNumeric_numeric) {
455                         setMember(hv2, "attributeValue",
456                                   newSViv(*son->u.numeric));
457                     } else { /*Z_StringOrNumeric_string*/
458                         setMember(hv2, "attributeValue",
459                                   newSVpv(son->u.string, 0));
460                     }
461                 }
462                 av_push(av, tmp);
463             }
464             setMember(hv, "attributes", attrs);
465         }
466         setMember(hv, "term", newSVpv((char*) at->term->u.general->buf,
467                                       at->term->u.general->len));
468         return sv;
469     }
470     case Z_RPNStructure_complex: {
471         SV *tmp;
472         Z_Complex *c = s->u.complex;
473         char *type = 0;         /* vacuous assignment satisfies gcc -Wall */
474         switch (c->roperator->which) {
475         case Z_Operator_and:     type = "Net::Z3950::RPN::And"; break;
476         case Z_Operator_or:      type = "Net::Z3950::RPN::Or"; break;
477         case Z_Operator_and_not: type = "Net::Z3950::RPN::AndNot"; break;
478         case Z_Operator_prox:    fatal("proximity not yet supported");
479         default: fatal("unknown RPN operator %d", (int) c->roperator->which);
480         }
481         sv = newObject(type, (SV*) (av = newAV()));
482         if ((tmp = rpn2perl(c->s1)) == 0)
483             return 0;
484         av_push(av, tmp);
485         if ((tmp = rpn2perl(c->s2)) == 0)
486             return 0;
487         av_push(av, tmp);
488         return sv;
489     }
490     default: fatal("unknown RPN node type %d", (int) s->which);
491     }
492
493     return 0;
494 }
495
496
497 /* Decode the Z_SortAttributes struct and store the whole thing into the
498  * hash by reference
499  */
500 int simpleserver_ExpandSortAttributes (HV *sort_spec, Z_SortAttributes *sattr)
501 {
502     WRBUF attrset_wr = wrbuf_alloc();
503     AV *list = newAV();
504     Z_AttributeList *attr_list = sattr->list;
505     int i;
506
507     oid2str(sattr->id, attrset_wr);
508     hv_store(sort_spec, "ATTRSET", 7,
509              newSVpv(attrset_wr->buf, attrset_wr->pos), 0);
510     wrbuf_destroy(attrset_wr);
511
512     hv_store(sort_spec, "SORT_ATTR", 9, newRV( sv_2mortal( (SV*) list ) ), 0);
513
514     for (i = 0; i < attr_list->num_attributes; i++) 
515     {
516         Z_AttributeElement *attr = *attr_list->attributes++; 
517         HV *attr_spec = newHV();
518                 
519         av_push(list, newRV( sv_2mortal( (SV*) attr_spec ) ));
520         hv_store(attr_spec, "ATTR_TYPE", 9, newSViv(*attr->attributeType), 0);
521
522         if (attr->which == Z_AttributeValue_numeric)
523         {
524             hv_store(attr_spec, "ATTR_VALUE", 10,
525                      newSViv(*attr->value.numeric), 0);
526         } else {
527             return 0;
528         }
529     }
530
531     return 1;
532 }
533
534
535 /* Decode the Z_SortKeySpec struct and store the whole thing in a perl hash */
536 int simpleserver_SortKeySpecToHash (HV *sort_spec, Z_SortKeySpec *spec)
537 {
538     Z_SortElement *element = spec->sortElement;
539
540     hv_store(sort_spec, "RELATION", 8, newSViv(*spec->sortRelation), 0);
541     hv_store(sort_spec, "CASE", 4, newSViv(*spec->caseSensitivity), 0);
542     hv_store(sort_spec, "MISSING", 7, newSViv(spec->which), 0);
543
544     if (element->which == Z_SortElement_generic)
545     {
546         Z_SortKey *key = element->u.generic;
547
548         if (key->which == Z_SortKey_sortField)
549         {
550             hv_store(sort_spec, "SORTFIELD", 9,
551                      newSVpv((char *) key->u.sortField, 0), 0);
552         }
553         else if (key->which == Z_SortKey_elementSpec)
554         {
555             Z_Specification *zspec = key->u.elementSpec;
556             
557             hv_store(sort_spec, "ELEMENTSPEC_TYPE", 16,
558                      newSViv(zspec->which), 0);
559
560             if (zspec->which == Z_Schema_oid)
561             {
562                 WRBUF elementSpec = wrbuf_alloc();
563
564                 oid2str(zspec->schema.oid, elementSpec);
565                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
566                          newSVpv(elementSpec->buf, elementSpec->pos), 0);
567                 wrbuf_destroy(elementSpec);
568             }
569             else if (zspec->which == Z_Schema_uri)
570             {
571                 hv_store(sort_spec, "ELEMENTSPEC_VALUE", 17,
572                          newSVpv((char *) zspec->schema.uri, 0), 0);
573             }
574         }
575         else if (key->which == Z_SortKey_sortAttributes)
576         {
577             return simpleserver_ExpandSortAttributes(sort_spec,
578                                                      key->u.sortAttributes);
579         }
580         else
581         {
582             return 0;
583         }
584     }
585     else
586     {
587         return 0;
588     }
589
590     return 1;
591 }
592
593
594 static SV *zquery2perl(Z_Query *q)
595 {
596     SV *sv;
597     HV *hv;
598
599     if (q->which != Z_Query_type_1 && q->which != Z_Query_type_101) 
600         return 0;
601     sv = newObject("Net::Z3950::APDU::Query", (SV*) (hv = newHV()));
602     if (q->u.type_1->attributeSetId)
603         setMember(hv, "attributeSet",
604                   translateOID(q->u.type_1->attributeSetId));
605     setMember(hv, "query", rpn2perl(q->u.type_1->RPNStructure));
606     return sv;
607 }
608
609
610 int bend_sort(void *handle, bend_sort_rr *rr)
611 {
612         HV *href;
613         AV *aref;
614         AV *sort_seq;
615         SV **temp;
616         SV *err_code;
617         SV *err_str;
618         SV *status;
619         SV *point;
620         STRLEN len;
621         char *ptr;
622         char *ODR_err_str;
623         char **input_setnames;
624         Zfront_handle *zhandle = (Zfront_handle *)handle;
625         Z_SortKeySpecList *sort_spec = rr->sort_sequence;
626         int i;
627         
628         dSP;
629         ENTER;
630         SAVETMPS;
631         
632         aref = newAV();
633         input_setnames = rr->input_setnames;
634         for (i = 0; i < rr->num_input_setnames; i++)
635         {
636             av_push(aref, newSVpv(*input_setnames++, 0));
637         }
638
639         sort_seq = newAV();
640         for (i = 0; i < sort_spec->num_specs; i++)
641         {
642             Z_SortKeySpec *spec = *sort_spec->specs++;
643             HV *sort_spec = newHV();
644
645             if ( simpleserver_SortKeySpecToHash(sort_spec, spec) )
646                 av_push(sort_seq, newRV( sv_2mortal( (SV*) sort_spec ) ));
647             else
648             {
649                 rr->errcode = 207;
650                 return 0;
651             }
652         }
653         
654         href = newHV();
655         hv_store(href, "INPUT", 5, newRV( (SV*) aref), 0);
656         hv_store(href, "OUTPUT", 6, newSVpv(rr->output_setname, 0), 0);
657         hv_store(href, "SEQUENCE", 8, newRV( (SV*) sort_seq), 0);
658         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
659         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
660         hv_store(href, "STATUS", 6, newSViv(0), 0);
661         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
662         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
663
664         PUSHMARK(sp);
665
666         XPUSHs(sv_2mortal(newRV( (SV*) href)));
667
668         PUTBACK;
669
670         perl_call_sv(sort_ref, G_SCALAR | G_DISCARD);
671
672         SPAGAIN;
673
674         temp = hv_fetch(href, "ERR_CODE", 8, 1);
675         err_code = newSVsv(*temp);
676
677         temp = hv_fetch(href, "ERR_STR", 7, 1);
678         err_str = newSVsv(*temp);
679
680         temp = hv_fetch(href, "STATUS", 6, 1);
681         status = newSVsv(*temp);
682
683         temp = hv_fetch(href, "HANDLE", 6, 1);
684         point = newSVsv(*temp);
685
686         hv_undef(href);
687         av_undef(aref);
688         av_undef(sort_seq);
689        
690         sv_free( (SV*) aref);
691         sv_free( (SV*) href);
692         sv_free( (SV*) sort_seq);
693
694         rr->errcode = SvIV(err_code);
695         rr->sort_status = SvIV(status);
696         
697         ptr = SvPV(err_str, len);
698         ODR_err_str = (char *)odr_malloc(rr->stream, len + 1);
699         strcpy(ODR_err_str, ptr);
700         rr->errstring = ODR_err_str;
701         zhandle->handle = point;
702
703         sv_free(err_code);
704         sv_free(err_str);
705         sv_free(status);
706         
707         PUTBACK;
708         FREETMPS;
709         LEAVE;
710
711         return 0;
712 }
713
714
715 int bend_search(void *handle, bend_search_rr *rr)
716 {
717         HV *href;
718         AV *aref;
719         SV **temp;
720         int i;
721         char **basenames;
722         WRBUF query;
723         SV *point;
724         Zfront_handle *zhandle = (Zfront_handle *)handle;
725         CV* handler_cv = 0;
726         SV *rpnSV;
727
728         dSP;
729         ENTER;
730         SAVETMPS;
731
732         aref = newAV();
733         basenames = rr->basenames;
734         for (i = 0; i < rr->num_bases; i++)
735         {
736                 av_push(aref, newSVpv(*basenames++, 0));
737         }
738 #if ENABLE_STOP_SERVER
739         if (rr->num_bases == 1 && !strcmp(rr->basenames[0], "XXstop"))
740         {
741                 zhandle->stop_flag = 1;
742         }
743 #endif
744         href = newHV();         
745         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
746         if (rr->srw_sortKeys && *rr->srw_sortKeys) 
747             hv_store(href, "SRW_SORTKEYS", 12, newSVpv(rr->srw_sortKeys, 0), 0);
748         hv_store(href, "REPL_SET", 8, newSViv(rr->replace_set), 0);
749         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
750         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
751         hv_store(href, "HITS", 4, newSViv(0), 0);
752         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
753         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
754         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
755         hv_store(href, "PID", 3, newSViv(getpid()), 0);
756         if ((rpnSV = zquery2perl(rr->query)) != 0) {
757             hv_store(href, "RPN", 3, rpnSV, 0);
758         }
759         query = zquery2pquery(rr->query);
760         if (query)
761         {
762                 hv_store(href, "QUERY", 5, newSVpv((char *)query->buf, query->pos), 0);
763         }
764         else if (rr->query->which == Z_Query_type_104 &&
765                  rr->query->u.type_104->which == Z_External_CQL) {
766             hv_store(href, "CQL", 3,
767                      newSVpv(rr->query->u.type_104->u.cql, 0), 0);
768         }
769         else
770         {       
771                 rr->errcode = 108;
772                 return 0;
773         }
774         PUSHMARK(sp);
775         
776         XPUSHs(sv_2mortal(newRV( (SV*) href)));
777         
778         PUTBACK;
779
780         handler_cv = simpleserver_sv2cv( search_ref );
781         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
782
783         SPAGAIN;
784
785         temp = hv_fetch(href, "HITS", 4, 1);
786         rr->hits = SvIV(*temp);
787
788         temp = hv_fetch(href, "ERR_CODE", 8, 1);
789         rr->errcode = SvIV(*temp);
790
791         temp = hv_fetch(href, "ERR_STR", 7, 1);
792         rr->errstring = string_or_undef(temp, rr->stream);
793
794         temp = hv_fetch(href, "HANDLE", 6, 1);
795         point = newSVsv(*temp);
796
797         hv_undef(href);
798         av_undef(aref);
799
800         zhandle->handle = point;
801         sv_free( (SV*) aref);
802         sv_free( (SV*) href);
803         if (query)
804             wrbuf_destroy(query);
805         PUTBACK;
806         FREETMPS;
807         LEAVE;
808         return 0;
809 }
810
811
812 int bend_fetch(void *handle, bend_fetch_rr *rr)
813 {
814         HV *href;
815         SV **temp;
816         SV *basename;
817         SV *record;
818         SV *last;
819         SV *err_code;
820         SV *err_string;
821         SV *sur_flag;
822         SV *point;
823         SV *rep_form;
824         SV *schema = 0;
825         char *ptr;
826         char *ODR_record;
827         char *ODR_basename;
828         char *ODR_errstr;
829         WRBUF oid_dotted;
830         Zfront_handle *zhandle = (Zfront_handle *)handle;
831         CV* handler_cv = 0;
832
833         Z_RecordComposition *composition;
834         Z_ElementSetNames *simple;
835         Z_CompSpec *complex;
836         STRLEN length;
837
838         dSP;
839         ENTER;
840         SAVETMPS;
841
842         rr->errcode = 0;
843         href = newHV();
844         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
845         if (rr->schema)
846                 hv_store(href, "SCHEMA", 6, newSVpv(rr->schema, 0), 0);
847         else
848                 hv_store(href, "SCHEMA", 6, newSVpv("", 0), 0);
849
850         temp = hv_store(href, "OFFSET", 6, newSViv(rr->number), 0);
851         if (rr->request_format != 0) {
852             oid_dotted = oid2dotted(rr->request_format);
853         } else {
854             /* Probably an SRU request: assume XML is required */
855             oid_dotted = wrbuf_alloc();
856             wrbuf_puts(oid_dotted, "1.2.840.10003.5.109.10");
857         }
858         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
859         hv_store(href, "REP_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);
860         hv_store(href, "BASENAME", 8, newSVpv("", 0), 0);
861         hv_store(href, "RECORD", 6, newSVpv("", 0), 0);
862         hv_store(href, "LAST", 4, newSViv(0), 0);
863         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
864         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
865         hv_store(href, "SUR_FLAG", 8, newSViv(0), 0);
866         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
867         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
868         hv_store(href, "PID", 3, newSViv(getpid()), 0);
869         if (rr->comp)
870         {
871                 composition = rr->comp;
872                 if (composition->which == Z_RecordComp_simple)
873                 {
874                         simple = composition->u.simple;
875                         if (simple->which == Z_ElementSetNames_generic)
876                         {
877                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
878                         } 
879                         else
880                         {
881                                 rr->errcode = 26;
882                         }
883                 }
884                 else if (composition->which == Z_RecordComp_complex)
885                 {
886                         if (composition->u.complex->generic &&
887
888                                         composition->u.complex->generic &&
889                                         composition->u.complex->generic->elementSpec &&
890                                         composition->u.complex->generic->elementSpec->which ==
891                                         Z_ElementSpec_elementSetName)
892                         {
893                                 complex = composition->u.complex;
894                                 hv_store(href, "COMP", 4,
895                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
896                         }
897                         else
898                         {
899 #if 0   /* For now ignore this error, which is ubiquitous in SRU */
900                                 fprintf(stderr, "complex is weird\n");
901                                 rr->errcode = 26;
902                                 return 0;
903 #endif /*0*/
904                         }
905                 }
906                 else
907                 {
908                         rr->errcode = 26;
909                         return 0;
910                 }
911         }
912
913         PUSHMARK(sp);
914
915         XPUSHs(sv_2mortal(newRV( (SV*) href)));
916
917         PUTBACK;
918         
919         handler_cv = simpleserver_sv2cv( fetch_ref );
920         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
921
922         SPAGAIN;
923
924         temp = hv_fetch(href, "BASENAME", 8, 1);
925         basename = newSVsv(*temp);
926
927         temp = hv_fetch(href, "RECORD", 6, 1);
928         record = newSVsv(*temp);
929
930         temp = hv_fetch(href, "LAST", 4, 1);
931         last = newSVsv(*temp);
932
933         temp = hv_fetch(href, "ERR_CODE", 8, 1);
934         err_code = newSVsv(*temp);
935
936         temp = hv_fetch(href, "ERR_STR", 7, 1),
937         err_string = newSVsv(*temp);
938
939         temp = hv_fetch(href, "SUR_FLAG", 8, 1);
940         sur_flag = newSVsv(*temp);
941
942         temp = hv_fetch(href, "REP_FORM", 8, 1);
943         rep_form = newSVsv(*temp);
944
945         temp = hv_fetch(href, "SCHEMA", 6, 1);
946         if (temp != 0) {
947                 schema = newSVsv(*temp);
948                 ptr = SvPV(schema, length);
949                 if (length > 0) {
950                         rr->schema = (char *)odr_malloc(rr->stream, length + 1);
951                         strcpy(rr->schema, ptr);
952                 }
953         }
954
955         temp = hv_fetch(href, "HANDLE", 6, 1);
956         point = newSVsv(*temp);
957
958
959         hv_undef(href);
960         
961         ptr = SvPV(basename, length);
962         ODR_basename = (char *)odr_malloc(rr->stream, length + 1);
963         strcpy(ODR_basename, ptr);
964         rr->basename = ODR_basename;
965
966         ptr = SvPV(rep_form, length);
967
968         rr->output_format = yaz_string_to_oid_odr(yaz_oid_std(),
969                                         CLASS_RECSYN, ptr, rr->stream);
970         if (!rr->output_format)
971         {
972                 printf("Net::Z3950::SimpleServer: WARNING: Bad OID %s\n", ptr);
973                 rr->output_format =
974                         odr_oiddup(rr->stream, yaz_oid_recsyn_sutrs);
975         }
976         ptr = SvPV(record, length);
977         /* Treat GRS-1 records separately */
978         if (!oid_oidcmp(rr->output_format, yaz_oid_recsyn_grs_1))
979         {
980                 rr->record = (char *) read_grs1(ptr, rr->stream);
981                 rr->len = -1;
982         }
983         else
984         {
985                 ODR_record = (char *)odr_malloc(rr->stream, length + 1);
986                 strcpy(ODR_record, ptr);
987                 rr->record = ODR_record;
988                 rr->len = length;
989         }
990         zhandle->handle = point;
991         handle = zhandle;
992         rr->last_in_set = SvIV(last);
993         
994         if (!(rr->errcode))
995         {
996                 rr->errcode = SvIV(err_code);
997                 ptr = SvPV(err_string, length);
998                 ODR_errstr = (char *)odr_malloc(rr->stream, length + 1);
999                 strcpy(ODR_errstr, ptr);
1000                 rr->errstring = ODR_errstr;
1001         }
1002         rr->surrogate_flag = SvIV(sur_flag);
1003
1004         wrbuf_destroy(oid_dotted);
1005         sv_free((SV*) href);
1006         sv_free(basename);
1007         sv_free(record);
1008         sv_free(last);
1009         sv_free(err_string);
1010         sv_free(err_code),
1011         sv_free(sur_flag);
1012         sv_free(rep_form);
1013
1014         if (schema)
1015                 sv_free(schema);
1016
1017         PUTBACK;
1018         FREETMPS;
1019         LEAVE;
1020         
1021         return 0;
1022 }
1023
1024
1025 int bend_present(void *handle, bend_present_rr *rr)
1026 {
1027         HV *href;
1028         SV **temp;
1029         SV *err_code;
1030         SV *err_string;
1031         SV *hits;
1032         SV *point;
1033         STRLEN len;
1034         Z_RecordComposition *composition;
1035         Z_ElementSetNames *simple;
1036         Z_CompSpec *complex;
1037         char *ODR_errstr;
1038         char *ptr;
1039         Zfront_handle *zhandle = (Zfront_handle *)handle;
1040         CV* handler_cv = 0;
1041
1042 /*      WRBUF oid_dotted; */
1043
1044         dSP;
1045         ENTER;
1046         SAVETMPS;
1047
1048         href = newHV();
1049         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1050         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1051         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1052         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1053         hv_store(href, "START", 5, newSViv(rr->start), 0);
1054         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
1055         hv_store(href, "NUMBER", 6, newSViv(rr->number), 0);
1056         /*oid_dotted = oid2dotted(rr->request_format_raw);
1057         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);*/
1058         hv_store(href, "HITS", 4, newSViv(0), 0);
1059         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1060         if (rr->comp)
1061         {
1062                 composition = rr->comp;
1063                 if (composition->which == Z_RecordComp_simple)
1064                 {
1065                         simple = composition->u.simple;
1066                         if (simple->which == Z_ElementSetNames_generic)
1067                         {
1068                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
1069                         } 
1070                         else
1071                         {
1072                                 rr->errcode = 26;
1073                                 return 0;
1074                         }
1075                 }
1076                 else if (composition->which == Z_RecordComp_complex)
1077                 {
1078                         if (composition->u.complex->generic &&
1079
1080                                         composition->u.complex->generic &&
1081                                         composition->u.complex->generic->elementSpec &&
1082                                         composition->u.complex->generic->elementSpec->which ==
1083                                         Z_ElementSpec_elementSetName)
1084                         {
1085                                 complex = composition->u.complex;
1086                                 hv_store(href, "COMP", 4,
1087                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
1088                         }
1089                         else
1090                         {
1091                                 rr->errcode = 26;
1092                                 return 0;
1093                         }
1094                 }
1095                 else
1096                 {
1097                         rr->errcode = 26;
1098                         return 0;
1099                 }
1100         }
1101
1102         PUSHMARK(sp);
1103         
1104         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1105         
1106         PUTBACK;
1107         
1108         handler_cv = simpleserver_sv2cv( present_ref );
1109         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1110         
1111         SPAGAIN;
1112
1113         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1114         err_code = newSVsv(*temp);
1115
1116         temp = hv_fetch(href, "ERR_STR", 7, 1);
1117         err_string = newSVsv(*temp);
1118
1119         temp = hv_fetch(href, "HITS", 4, 1);
1120         hits = newSVsv(*temp);
1121
1122         temp = hv_fetch(href, "HANDLE", 6, 1);
1123         point = newSVsv(*temp);
1124
1125         PUTBACK;
1126         FREETMPS;
1127         LEAVE;
1128         
1129         hv_undef(href);
1130         rr->errcode = SvIV(err_code);
1131         rr->hits = SvIV(hits);
1132
1133         ptr = SvPV(err_string, len);
1134         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1135         strcpy(ODR_errstr, ptr);
1136         rr->errstring = ODR_errstr;
1137 /*      wrbuf_free(oid_dotted, 1);*/
1138         zhandle->handle = point;
1139         handle = zhandle;
1140         sv_free(err_code);
1141         sv_free(err_string);
1142         sv_free(hits);
1143         sv_free( (SV*) href);
1144
1145         return 0;
1146 }
1147
1148
1149 int bend_esrequest(void *handle, bend_esrequest_rr *rr)
1150 {
1151         perl_call_sv(esrequest_ref, G_VOID | G_DISCARD | G_NOARGS);
1152         return 0;
1153 }
1154
1155
1156 int bend_delete(void *handle, bend_delete_rr *rr)
1157 {
1158         perl_call_sv(delete_ref, G_VOID | G_DISCARD | G_NOARGS);
1159         return 0;
1160 }
1161
1162
1163 int bend_scan(void *handle, bend_scan_rr *rr)
1164 {
1165         HV *href;
1166         AV *aref;
1167         AV *list;
1168         AV *entries;
1169         HV *scan_item;
1170         struct scan_entry *scan_list;
1171         struct scan_entry *buffer;
1172         int *step_size = rr->step_size;
1173         int i;
1174         char **basenames;
1175         SV **temp;
1176         SV *err_code = sv_newmortal();
1177         SV *err_str = sv_newmortal();
1178         SV *point = sv_newmortal();
1179         SV *status = sv_newmortal();
1180         SV *number = sv_newmortal();
1181         char *ptr;
1182         char *ODR_errstr;
1183         STRLEN len;
1184         int term_len;
1185         SV *entries_ref;
1186         Zfront_handle *zhandle = (Zfront_handle *)handle;
1187         CV* handler_cv = 0;
1188
1189         dSP;
1190         ENTER;
1191         SAVETMPS;
1192         href = newHV();
1193         list = newAV();
1194         if (rr->term->term->which == Z_Term_general)
1195         {
1196                 term_len = rr->term->term->u.general->len;
1197                 hv_store(href, "TERM", 4, newSVpv((char*) rr->term->term->u.general->buf, term_len), 0);
1198         } else {
1199                 rr->errcode = 229;      /* Unsupported term type */
1200                 return 0;
1201         }
1202         hv_store(href, "STEP", 4, newSViv(*step_size), 0);
1203         hv_store(href, "NUMBER", 6, newSViv(rr->num_entries), 0);
1204         hv_store(href, "POS", 3, newSViv(rr->term_position), 0);
1205         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1206         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1207         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1208         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1209         hv_store(href, "STATUS", 6, newSViv(BEND_SCAN_SUCCESS), 0);
1210         hv_store(href, "ENTRIES", 7, newRV((SV *) list), 0);
1211         aref = newAV();
1212         basenames = rr->basenames;
1213         for (i = 0; i < rr->num_bases; i++)
1214         {
1215                 av_push(aref, newSVpv(*basenames++, 0));
1216         }
1217         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
1218
1219         PUSHMARK(sp);
1220
1221         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1222
1223         PUTBACK;
1224
1225         handler_cv = simpleserver_sv2cv( scan_ref );
1226         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1227
1228         SPAGAIN;
1229
1230         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1231         err_code = newSVsv(*temp);
1232
1233         temp = hv_fetch(href, "ERR_STR", 7, 1);
1234         err_str = newSVsv(*temp);
1235
1236         temp = hv_fetch(href, "HANDLE", 6, 1);
1237         point = newSVsv(*temp);
1238
1239         temp = hv_fetch(href, "STATUS", 6, 1);
1240         status = newSVsv(*temp);
1241         
1242         temp = hv_fetch(href, "NUMBER", 6, 1);
1243         number = newSVsv(*temp);
1244
1245         temp = hv_fetch(href, "ENTRIES", 7, 1);
1246         entries_ref = newSVsv(*temp);
1247
1248         PUTBACK;
1249         FREETMPS;
1250         LEAVE;
1251
1252         ptr = SvPV(err_str, len);
1253         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1254         strcpy(ODR_errstr, ptr);
1255         rr->errstring = ODR_errstr;
1256         rr->errcode = SvIV(err_code);
1257         rr->num_entries = SvIV(number);
1258         rr->status = SvIV(status);
1259         scan_list = (struct scan_entry *) odr_malloc (rr->stream, rr->num_entries * sizeof(*scan_list));
1260         buffer = scan_list;
1261         entries = (AV *)SvRV(entries_ref);
1262         if (rr->errcode == 0) for (i = 0; i < rr->num_entries; i++)
1263         {
1264                 scan_item = (HV *)SvRV(sv_2mortal(av_shift(entries)));
1265                 temp = hv_fetch(scan_item, "TERM", 4, 1);
1266                 ptr = SvPV(*temp, len);
1267                 buffer->term = (char *) odr_malloc (rr->stream, len + 1); 
1268                 strcpy(buffer->term, ptr);
1269                 temp = hv_fetch(scan_item, "OCCURRENCE", 10, 1); 
1270                 buffer->occurrences = SvIV(*temp);
1271                 buffer++;
1272                 hv_undef(scan_item);
1273         }
1274         rr->entries = scan_list;
1275         zhandle->handle = point;
1276         handle = zhandle;
1277         sv_free(err_code);
1278         sv_free(err_str);
1279         sv_free(status);
1280         sv_free(number);
1281         hv_undef(href);
1282         sv_free((SV *)href);
1283         av_undef(aref);
1284         sv_free((SV *)aref);
1285         av_undef(list);
1286         sv_free((SV *)list);
1287         av_undef(entries);
1288         /*sv_free((SV *)entries);*/
1289         sv_free(entries_ref);
1290
1291         return 0;
1292 }
1293
1294 int bend_explain(void *handle, bend_explain_rr *q)
1295 {
1296         HV *href;
1297         CV *handler_cv = 0;
1298         SV **temp;
1299         char *explain;
1300         SV *explainsv;
1301         STRLEN len;
1302         Zfront_handle *zhandle = (Zfront_handle *)handle;
1303
1304         dSP;
1305         ENTER;
1306         SAVETMPS;
1307
1308         href = newHV();
1309         hv_store(href, "EXPLAIN", 7, newSVpv("", 0), 0);
1310         hv_store(href, "DATABASE", 8, newSVpv(q->database, 0), 0);
1311         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1312         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1313
1314         PUSHMARK(sp);
1315         XPUSHs(sv_2mortal(newRV((SV*) href)));
1316         PUTBACK;
1317
1318         handler_cv = simpleserver_sv2cv(explain_ref);
1319         perl_call_sv((SV*) handler_cv, G_SCALAR | G_DISCARD);
1320
1321         SPAGAIN;
1322
1323         temp = hv_fetch(href, "EXPLAIN", 7, 1);
1324         explainsv = newSVsv(*temp);
1325
1326         PUTBACK;
1327         FREETMPS;
1328         LEAVE;
1329
1330         explain = SvPV(explainsv, len);
1331         q->explain_buf = (char*) odr_malloc(q->stream, len + 1);
1332         strcpy(q->explain_buf, explain);
1333
1334         return 0;
1335 }
1336
1337 bend_initresult *bend_init(bend_initrequest *q)
1338 {
1339         int dummy = simpleserver_clone();
1340         bend_initresult *r = (bend_initresult *)
1341                 odr_malloc (q->stream, sizeof(*r));
1342         char *ptr;
1343         CV* handler_cv = 0;
1344         dSP;
1345         STRLEN len;
1346         NMEM nmem = nmem_create();
1347         Zfront_handle *zhandle =  (Zfront_handle *) nmem_malloc (nmem,
1348                         sizeof(*zhandle));
1349         SV *handle;
1350         HV *href;
1351         SV **temp;
1352
1353         ENTER;
1354         SAVETMPS;
1355
1356         zhandle->ghandle = _global_ghandle;
1357         zhandle->nmem = nmem;
1358         zhandle->stop_flag = 0;
1359
1360         if (sort_ref)
1361         {
1362             q->bend_sort = bend_sort;
1363         }
1364         if (search_ref)
1365         {
1366                 q->bend_search = bend_search;
1367         }
1368         if (present_ref)
1369         {
1370                 q->bend_present = bend_present;
1371         }
1372         /*q->bend_esrequest = bend_esrequest;*/
1373         /*q->bend_delete = bend_delete;*/
1374         if (fetch_ref)
1375         {
1376                 q->bend_fetch = bend_fetch;
1377         }
1378         if (scan_ref)
1379         {
1380                 q->bend_scan = bend_scan;
1381         }
1382         if (explain_ref)
1383         {
1384                 q->bend_explain = bend_explain;
1385         }
1386
1387         href = newHV(); 
1388         hv_store(href, "IMP_ID", 6, newSVpv("", 0), 0);
1389         hv_store(href, "IMP_NAME", 8, newSVpv("", 0), 0);
1390         hv_store(href, "IMP_VER", 7, newSVpv("", 0), 0);
1391         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1392         hv_store(href, "ERR_STR", 7, newSViv(0), 0);
1393         hv_store(href, "PEER_NAME", 9, newSVpv(q->peer_name, 0), 0);
1394         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1395         hv_store(href, "HANDLE", 6, newSVsv(&sv_undef), 0);
1396         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1397         if (q->auth) {
1398             char *user = NULL;
1399             char *passwd = NULL;
1400             if (q->auth->which == Z_IdAuthentication_open) {
1401                 char *cp;
1402                 user = nmem_strdup (odr_getmem (q->stream), q->auth->u.open);
1403                 cp = strchr (user, '/');
1404                 if (cp) {
1405                     /* password after / given */
1406                     *cp = '\0';
1407                     passwd = cp+1;
1408                 }
1409             } else if (q->auth->which == Z_IdAuthentication_idPass) {
1410                 user = q->auth->u.idPass->userId;
1411                 passwd = q->auth->u.idPass->password;
1412             }
1413             /* ### some code paths have user/password unassigned here */
1414             if (user)
1415                 hv_store(href, "USER", 4, newSVpv(user, 0), 0);
1416             if (passwd)
1417                 hv_store(href, "PASS", 4, newSVpv(passwd, 0), 0);
1418         }
1419
1420         PUSHMARK(sp);   
1421
1422         XPUSHs(sv_2mortal(newRV((SV*) href)));
1423
1424         PUTBACK;
1425
1426         if (init_ref != NULL)
1427         {
1428              handler_cv = simpleserver_sv2cv( init_ref );
1429              perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1430         }
1431
1432         SPAGAIN;
1433
1434         temp = hv_fetch(href, "IMP_ID", 6, 1);
1435         ptr = SvPV(*temp, len);
1436         q->implementation_id = nmem_strdup(nmem, ptr);
1437
1438         temp = hv_fetch(href, "IMP_NAME", 8, 1);
1439         ptr = SvPV(*temp, len);
1440         q->implementation_name = nmem_strdup(nmem, ptr);
1441
1442         temp = hv_fetch(href, "IMP_VER", 7, 1);
1443         ptr = SvPV(*temp, len);
1444         q->implementation_version = nmem_strdup(nmem, ptr);
1445
1446         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1447         r->errcode = SvIV(*temp);
1448
1449         temp = hv_fetch(href, "ERR_STR", 7, 1);
1450         ptr = SvPV(*temp, len);
1451         r->errstring = (char *)odr_malloc(q->stream, len + 1);
1452         strcpy(r->errstring, ptr);
1453
1454         temp = hv_fetch(href, "HANDLE", 6, 1);
1455         handle= newSVsv(*temp);
1456         zhandle->handle = handle;
1457
1458         r->handle = zhandle;
1459
1460         hv_undef(href);
1461         sv_free((SV*) href);
1462
1463         PUTBACK;
1464         FREETMPS;
1465         LEAVE;
1466         
1467         return r;       
1468 }
1469
1470 void bend_close(void *handle)
1471 {
1472         HV *href;
1473         Zfront_handle *zhandle = (Zfront_handle *)handle;
1474         CV* handler_cv = 0;
1475         int stop_flag = 0;
1476         dSP;
1477         ENTER;
1478         SAVETMPS;
1479
1480         if (close_ref)
1481         {
1482                 href = newHV();
1483                 hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1484                 hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1485
1486                 PUSHMARK(sp);
1487
1488                 XPUSHs(sv_2mortal(newRV((SV *)href)));
1489
1490                 PUTBACK;
1491         
1492                 handler_cv = simpleserver_sv2cv( close_ref );
1493                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1494         
1495                 SPAGAIN;
1496
1497                 sv_free((SV*) href);
1498         }
1499         else
1500                 sv_free(zhandle->handle);
1501         PUTBACK;
1502         FREETMPS;
1503         LEAVE;
1504         stop_flag = zhandle->stop_flag;
1505         nmem_destroy(zhandle->nmem);
1506         simpleserver_free();
1507
1508         if (stop_flag)
1509                 exit(0);
1510         return;
1511 }
1512
1513
1514 MODULE = Net::Z3950::SimpleServer       PACKAGE = Net::Z3950::SimpleServer
1515
1516 PROTOTYPES: DISABLE
1517
1518
1519 void
1520 set_ghandle(arg)
1521                 SV *arg
1522         CODE:
1523                 _global_ghandle = newSVsv(arg);
1524                 
1525
1526 void
1527 set_init_handler(arg)
1528                 SV *arg
1529         CODE:
1530                 init_ref = newSVsv(arg);
1531                 
1532
1533 void
1534 set_close_handler(arg)
1535                 SV *arg
1536         CODE:
1537                 close_ref = newSVsv(arg);
1538
1539
1540 void
1541 set_sort_handler(arg)
1542                 SV *arg
1543         CODE:
1544                 sort_ref = newSVsv(arg);
1545
1546 void
1547 set_search_handler(arg)
1548                 SV *arg
1549         CODE:
1550                 search_ref = newSVsv(arg);
1551
1552
1553 void
1554 set_fetch_handler(arg)
1555                 SV *arg
1556         CODE:
1557                 fetch_ref = newSVsv(arg);
1558
1559
1560 void
1561 set_present_handler(arg)
1562                 SV *arg
1563         CODE:
1564                 present_ref = newSVsv(arg);
1565
1566
1567 void
1568 set_esrequest_handler(arg)
1569                 SV *arg
1570         CODE:
1571                 esrequest_ref = newSVsv(arg);
1572
1573
1574 void
1575 set_delete_handler(arg)
1576                 SV *arg
1577         CODE:
1578                 delete_ref = newSVsv(arg);
1579
1580
1581 void
1582 set_scan_handler(arg)
1583                 SV *arg
1584         CODE:
1585                 scan_ref = newSVsv(arg);
1586
1587 void
1588 set_explain_handler(arg)
1589                 SV *arg
1590         CODE:
1591                 explain_ref = newSVsv(arg);
1592
1593 int
1594 start_server(...)
1595         PREINIT:
1596                 char **argv;
1597                 char **argv_buf;
1598                 char *ptr;
1599                 int i;
1600                 STRLEN len;
1601         CODE:
1602                 argv_buf = (char **)xmalloc((items + 1) * sizeof(char *));
1603                 argv = argv_buf;
1604                 for (i = 0; i < items; i++)
1605                 {
1606                         ptr = SvPV(ST(i), len);
1607                         *argv_buf = (char *)xmalloc(len + 1);
1608                         strcpy(*argv_buf++, ptr); 
1609                 }
1610                 *argv_buf = NULL;
1611                 root_perl_context = PERL_GET_CONTEXT;
1612                 yaz_mutex_create(&simpleserver_mutex);
1613 #if 0
1614                 /* only for debugging perl_clone .. */
1615                 tst_clones();
1616 #endif
1617                 
1618                 RETVAL = statserv_main(items, argv, bend_init, bend_close);
1619         OUTPUT:
1620                 RETVAL
1621
1622
1623 int
1624 ScanSuccess()
1625         CODE:
1626                 RETVAL = BEND_SCAN_SUCCESS;
1627         OUTPUT:
1628                 RETVAL
1629
1630 int
1631 ScanPartial()
1632         CODE:
1633                 RETVAL = BEND_SCAN_PARTIAL;
1634         OUTPUT:
1635                 RETVAL
1636
1637  
1638 void
1639 yazlog(arg)
1640                 SV *arg
1641         CODE:
1642                 STRLEN len;
1643                 char *ptr;
1644                 ptr = SvPV(arg, len);
1645                 yaz_log(YLOG_LOG, "%.*s", len, ptr);
1646
1647 int
1648 yaz_diag_srw_to_bib1(srw_code)
1649         int srw_code
1650
1651 int
1652 yaz_diag_bib1_to_srw(bib1_code)
1653         int bib1_code
1654