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