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