Document the SORT API.
[simpleserver-moved-to-github.git] / SimpleServer.xs
1 /*
2  * $Id: SimpleServer.xs,v 1.76 2007-08-20 21:27:50 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                         }
970                 }
971                 else if (composition->which == Z_RecordComp_complex)
972                 {
973                         if (composition->u.complex->generic &&
974
975                                         composition->u.complex->generic &&
976                                         composition->u.complex->generic->elementSpec &&
977                                         composition->u.complex->generic->elementSpec->which ==
978                                         Z_ElementSpec_elementSetName)
979                         {
980                                 complex = composition->u.complex;
981                                 hv_store(href, "COMP", 4,
982                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
983                         }
984                         else
985                         {
986 #if 0   /* For now ignore this error, which is ubiquitous in SRU */
987                                 fprintf(stderr, "complex is weird\n");
988                                 rr->errcode = 26;
989                                 return 0;
990 #endif /*0*/
991                         }
992                 }
993                 else
994                 {
995                         rr->errcode = 26;
996                         return 0;
997                 }
998         }
999
1000         PUSHMARK(sp);
1001
1002         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1003
1004         PUTBACK;
1005         
1006         handler_cv = simpleserver_sv2cv( fetch_ref );
1007         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1008
1009         SPAGAIN;
1010
1011         temp = hv_fetch(href, "BASENAME", 8, 1);
1012         basename = newSVsv(*temp);
1013
1014         temp = hv_fetch(href, "RECORD", 6, 1);
1015         record = newSVsv(*temp);
1016
1017         temp = hv_fetch(href, "LAST", 4, 1);
1018         last = newSVsv(*temp);
1019
1020         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1021         err_code = newSVsv(*temp);
1022
1023         temp = hv_fetch(href, "ERR_STR", 7, 1),
1024         err_string = newSVsv(*temp);
1025
1026         temp = hv_fetch(href, "SUR_FLAG", 8, 1);
1027         sur_flag = newSVsv(*temp);
1028
1029         temp = hv_fetch(href, "REP_FORM", 8, 1);
1030         rep_form = newSVsv(*temp);
1031
1032         temp = hv_fetch(href, "SCHEMA", 6, 1);
1033         if (temp != 0) {
1034                 schema = newSVsv(*temp);
1035                 ptr = SvPV(schema, length);
1036                 if (length > 0) {
1037                         rr->schema = (char *)odr_malloc(rr->stream, length + 1);
1038                         strcpy(rr->schema, ptr);
1039                 }
1040         }
1041
1042         temp = hv_fetch(href, "HANDLE", 6, 1);
1043         point = newSVsv(*temp);
1044
1045
1046         hv_undef(href);
1047         
1048         ptr = SvPV(basename, length);
1049         ODR_basename = (char *)odr_malloc(rr->stream, length + 1);
1050         strcpy(ODR_basename, ptr);
1051         rr->basename = ODR_basename;
1052
1053         ptr = SvPV(rep_form, length);
1054
1055         rr->output_format = yaz_string_to_oid_odr(yaz_oid_std(),
1056                                         CLASS_RECSYN, ptr, rr->stream);
1057         if (!rr->output_format)
1058         {
1059                 printf("Net::Z3950::SimpleServer: WARNING: Bad OID %s\n", ptr);
1060                 rr->output_format =
1061                         odr_oiddup(rr->stream, yaz_oid_recsyn_sutrs);
1062         }
1063         ptr = SvPV(record, length);
1064         /* Treat GRS-1 records separately */
1065         if (!oid_oidcmp(rr->output_format, yaz_oid_recsyn_grs_1))
1066         {
1067                 rr->record = (char *) read_grs1(ptr, rr->stream);
1068                 rr->len = -1;
1069         }
1070         else
1071         {
1072                 ODR_record = (char *)odr_malloc(rr->stream, length + 1);
1073                 strcpy(ODR_record, ptr);
1074                 rr->record = ODR_record;
1075                 rr->len = length;
1076         }
1077         zhandle->handle = point;
1078         handle = zhandle;
1079         rr->last_in_set = SvIV(last);
1080         
1081         if (!(rr->errcode))
1082         {
1083                 rr->errcode = SvIV(err_code);
1084                 ptr = SvPV(err_string, length);
1085                 ODR_errstr = (char *)odr_malloc(rr->stream, length + 1);
1086                 strcpy(ODR_errstr, ptr);
1087                 rr->errstring = ODR_errstr;
1088         }
1089         rr->surrogate_flag = SvIV(sur_flag);
1090
1091         wrbuf_destroy(oid_dotted);
1092         sv_free((SV*) href);
1093         sv_free(basename);
1094         sv_free(record);
1095         sv_free(last);
1096         sv_free(err_string);
1097         sv_free(err_code),
1098         sv_free(sur_flag);
1099         sv_free(rep_form);
1100
1101         if (schema)
1102                 sv_free(schema);
1103
1104         PUTBACK;
1105         FREETMPS;
1106         LEAVE;
1107         
1108         return 0;
1109 }
1110
1111
1112 int bend_present(void *handle, bend_present_rr *rr)
1113 {
1114         HV *href;
1115         SV **temp;
1116         SV *err_code;
1117         SV *err_string;
1118         SV *hits;
1119         SV *point;
1120         STRLEN len;
1121         Z_RecordComposition *composition;
1122         Z_ElementSetNames *simple;
1123         Z_CompSpec *complex;
1124         char *ODR_errstr;
1125         char *ptr;
1126         Zfront_handle *zhandle = (Zfront_handle *)handle;
1127         CV* handler_cv = 0;
1128
1129 /*      WRBUF oid_dotted; */
1130
1131         dSP;
1132         ENTER;
1133         SAVETMPS;
1134
1135         href = newHV();
1136         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1137         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1138         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1139         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1140         hv_store(href, "START", 5, newSViv(rr->start), 0);
1141         hv_store(href, "SETNAME", 7, newSVpv(rr->setname, 0), 0);
1142         hv_store(href, "NUMBER", 6, newSViv(rr->number), 0);
1143         /*oid_dotted = oid2dotted(rr->request_format_raw);
1144         hv_store(href, "REQ_FORM", 8, newSVpv((char *)oid_dotted->buf, oid_dotted->pos), 0);*/
1145         hv_store(href, "HITS", 4, newSViv(0), 0);
1146         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1147         if (rr->comp)
1148         {
1149                 composition = rr->comp;
1150                 if (composition->which == Z_RecordComp_simple)
1151                 {
1152                         simple = composition->u.simple;
1153                         if (simple->which == Z_ElementSetNames_generic)
1154                         {
1155                                 hv_store(href, "COMP", 4, newSVpv(simple->u.generic, 0), 0);
1156                         } 
1157                         else
1158                         {
1159                                 rr->errcode = 26;
1160                                 return 0;
1161                         }
1162                 }
1163                 else if (composition->which == Z_RecordComp_complex)
1164                 {
1165                         if (composition->u.complex->generic &&
1166
1167                                         composition->u.complex->generic &&
1168                                         composition->u.complex->generic->elementSpec &&
1169                                         composition->u.complex->generic->elementSpec->which ==
1170                                         Z_ElementSpec_elementSetName)
1171                         {
1172                                 complex = composition->u.complex;
1173                                 hv_store(href, "COMP", 4,
1174                                         newSVpv(complex->generic->elementSpec->u.elementSetName, 0), 0);
1175                         }
1176                         else
1177                         {
1178                                 rr->errcode = 26;
1179                                 return 0;
1180                         }
1181                 }
1182                 else
1183                 {
1184                         rr->errcode = 26;
1185                         return 0;
1186                 }
1187         }
1188
1189         PUSHMARK(sp);
1190         
1191         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1192         
1193         PUTBACK;
1194         
1195         handler_cv = simpleserver_sv2cv( present_ref );
1196         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1197         
1198         SPAGAIN;
1199
1200         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1201         err_code = newSVsv(*temp);
1202
1203         temp = hv_fetch(href, "ERR_STR", 7, 1);
1204         err_string = newSVsv(*temp);
1205
1206         temp = hv_fetch(href, "HITS", 4, 1);
1207         hits = newSVsv(*temp);
1208
1209         temp = hv_fetch(href, "HANDLE", 6, 1);
1210         point = newSVsv(*temp);
1211
1212         PUTBACK;
1213         FREETMPS;
1214         LEAVE;
1215         
1216         hv_undef(href);
1217         rr->errcode = SvIV(err_code);
1218         rr->hits = SvIV(hits);
1219
1220         ptr = SvPV(err_string, len);
1221         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1222         strcpy(ODR_errstr, ptr);
1223         rr->errstring = ODR_errstr;
1224 /*      wrbuf_free(oid_dotted, 1);*/
1225         zhandle->handle = point;
1226         handle = zhandle;
1227         sv_free(err_code);
1228         sv_free(err_string);
1229         sv_free(hits);
1230         sv_free( (SV*) href);
1231
1232         return 0;
1233 }
1234
1235
1236 int bend_esrequest(void *handle, bend_esrequest_rr *rr)
1237 {
1238         perl_call_sv(esrequest_ref, G_VOID | G_DISCARD | G_NOARGS);
1239         return 0;
1240 }
1241
1242
1243 int bend_scan(void *handle, bend_scan_rr *rr)
1244 {
1245         HV *href;
1246         AV *aref;
1247         AV *list;
1248         AV *entries;
1249         HV *scan_item;
1250         struct scan_entry *scan_list;
1251         struct scan_entry *buffer;
1252         int *step_size = rr->step_size;
1253         int i;
1254         char **basenames;
1255         SV **temp;
1256         SV *err_code = sv_newmortal();
1257         SV *err_str = sv_newmortal();
1258         SV *point = sv_newmortal();
1259         SV *status = sv_newmortal();
1260         SV *number = sv_newmortal();
1261         char *ptr;
1262         char *ODR_errstr;
1263         STRLEN len;
1264         int term_len;
1265         SV *entries_ref;
1266         Zfront_handle *zhandle = (Zfront_handle *)handle;
1267         CV* handler_cv = 0;
1268         SV *rpnSV;
1269
1270         dSP;
1271         ENTER;
1272         SAVETMPS;
1273         href = newHV();
1274         list = newAV();
1275
1276         /* RPN is better than TERM since it includes attributes */
1277         if ((rpnSV = apt2perl(rr->term)) != 0) {
1278             setMember(href, "RPN", rpnSV);
1279         }
1280
1281         if (rr->term->term->which == Z_Term_general)
1282         {
1283                 term_len = rr->term->term->u.general->len;
1284                 hv_store(href, "TERM", 4, newSVpv((char*) rr->term->term->u.general->buf, term_len), 0);
1285         } else {
1286                 rr->errcode = 229;      /* Unsupported term type */
1287                 return 0;
1288         }
1289         hv_store(href, "STEP", 4, newSViv(*step_size), 0);
1290         hv_store(href, "NUMBER", 6, newSViv(rr->num_entries), 0);
1291         hv_store(href, "POS", 3, newSViv(rr->term_position), 0);
1292         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1293         hv_store(href, "ERR_STR", 7, newSVpv("", 0), 0);
1294         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1295         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1296         hv_store(href, "STATUS", 6, newSViv(BEND_SCAN_SUCCESS), 0);
1297         hv_store(href, "ENTRIES", 7, newRV((SV *) list), 0);
1298         aref = newAV();
1299         basenames = rr->basenames;
1300         for (i = 0; i < rr->num_bases; i++)
1301         {
1302                 av_push(aref, newSVpv(*basenames++, 0));
1303         }
1304         hv_store(href, "DATABASES", 9, newRV( (SV*) aref), 0);
1305
1306         PUSHMARK(sp);
1307
1308         XPUSHs(sv_2mortal(newRV( (SV*) href)));
1309
1310         PUTBACK;
1311
1312         handler_cv = simpleserver_sv2cv( scan_ref );
1313         perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1314
1315         SPAGAIN;
1316
1317         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1318         err_code = newSVsv(*temp);
1319
1320         temp = hv_fetch(href, "ERR_STR", 7, 1);
1321         err_str = newSVsv(*temp);
1322
1323         temp = hv_fetch(href, "HANDLE", 6, 1);
1324         point = newSVsv(*temp);
1325
1326         temp = hv_fetch(href, "STATUS", 6, 1);
1327         status = newSVsv(*temp);
1328         
1329         temp = hv_fetch(href, "NUMBER", 6, 1);
1330         number = newSVsv(*temp);
1331
1332         temp = hv_fetch(href, "ENTRIES", 7, 1);
1333         entries_ref = newSVsv(*temp);
1334
1335         PUTBACK;
1336         FREETMPS;
1337         LEAVE;
1338
1339         ptr = SvPV(err_str, len);
1340         ODR_errstr = (char *)odr_malloc(rr->stream, len + 1);
1341         strcpy(ODR_errstr, ptr);
1342         rr->errstring = ODR_errstr;
1343         rr->errcode = SvIV(err_code);
1344         rr->num_entries = SvIV(number);
1345         rr->status = SvIV(status);
1346         scan_list = (struct scan_entry *) odr_malloc (rr->stream, rr->num_entries * sizeof(*scan_list));
1347         buffer = scan_list;
1348         entries = (AV *)SvRV(entries_ref);
1349         if (rr->errcode == 0) for (i = 0; i < rr->num_entries; i++)
1350         {
1351                 scan_item = (HV *)SvRV(sv_2mortal(av_shift(entries)));
1352                 temp = hv_fetch(scan_item, "TERM", 4, 1);
1353                 ptr = SvPV(*temp, len);
1354                 buffer->term = (char *) odr_malloc (rr->stream, len + 1); 
1355                 strcpy(buffer->term, ptr);
1356                 temp = hv_fetch(scan_item, "OCCURRENCE", 10, 1); 
1357                 buffer->occurrences = SvIV(*temp);
1358                 buffer++;
1359                 hv_undef(scan_item);
1360         }
1361         rr->entries = scan_list;
1362         zhandle->handle = point;
1363         handle = zhandle;
1364         sv_free(err_code);
1365         sv_free(err_str);
1366         sv_free(status);
1367         sv_free(number);
1368         hv_undef(href);
1369         sv_free((SV *)href);
1370         av_undef(aref);
1371         sv_free((SV *)aref);
1372         av_undef(list);
1373         sv_free((SV *)list);
1374         av_undef(entries);
1375         /*sv_free((SV *)entries);*/
1376         sv_free(entries_ref);
1377
1378         return 0;
1379 }
1380
1381 int bend_explain(void *handle, bend_explain_rr *q)
1382 {
1383         HV *href;
1384         CV *handler_cv = 0;
1385         SV **temp;
1386         char *explain;
1387         SV *explainsv;
1388         STRLEN len;
1389         Zfront_handle *zhandle = (Zfront_handle *)handle;
1390
1391         dSP;
1392         ENTER;
1393         SAVETMPS;
1394
1395         href = newHV();
1396         hv_store(href, "EXPLAIN", 7, newSVpv("", 0), 0);
1397         hv_store(href, "DATABASE", 8, newSVpv(q->database, 0), 0);
1398         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1399         hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1400
1401         PUSHMARK(sp);
1402         XPUSHs(sv_2mortal(newRV((SV*) href)));
1403         PUTBACK;
1404
1405         handler_cv = simpleserver_sv2cv(explain_ref);
1406         perl_call_sv((SV*) handler_cv, G_SCALAR | G_DISCARD);
1407
1408         SPAGAIN;
1409
1410         temp = hv_fetch(href, "EXPLAIN", 7, 1);
1411         explainsv = newSVsv(*temp);
1412
1413         PUTBACK;
1414         FREETMPS;
1415         LEAVE;
1416
1417         explain = SvPV(explainsv, len);
1418         q->explain_buf = (char*) odr_malloc(q->stream, len + 1);
1419         strcpy(q->explain_buf, explain);
1420
1421         return 0;
1422 }
1423
1424 bend_initresult *bend_init(bend_initrequest *q)
1425 {
1426         int dummy = simpleserver_clone();
1427         bend_initresult *r = (bend_initresult *)
1428                 odr_malloc (q->stream, sizeof(*r));
1429         char *ptr;
1430         CV* handler_cv = 0;
1431         dSP;
1432         STRLEN len;
1433         NMEM nmem = nmem_create();
1434         Zfront_handle *zhandle =  (Zfront_handle *) nmem_malloc (nmem,
1435                         sizeof(*zhandle));
1436         SV *handle;
1437         HV *href;
1438         SV **temp;
1439
1440         ENTER;
1441         SAVETMPS;
1442
1443         zhandle->ghandle = _global_ghandle;
1444         zhandle->nmem = nmem;
1445         zhandle->stop_flag = 0;
1446
1447         if (sort_ref)
1448         {
1449             q->bend_sort = bend_sort;
1450         }
1451         if (search_ref)
1452         {
1453                 q->bend_search = bend_search;
1454         }
1455         if (present_ref)
1456         {
1457                 q->bend_present = bend_present;
1458         }
1459         /*q->bend_esrequest = bend_esrequest;*/
1460         if (delete_ref) {
1461                 q->bend_delete = bend_delete;
1462         }
1463         if (fetch_ref)
1464         {
1465                 q->bend_fetch = bend_fetch;
1466         }
1467         if (scan_ref)
1468         {
1469                 q->bend_scan = bend_scan;
1470         }
1471         if (explain_ref)
1472         {
1473                 q->bend_explain = bend_explain;
1474         }
1475
1476         href = newHV(); 
1477         hv_store(href, "IMP_ID", 6, newSVpv("", 0), 0);
1478         hv_store(href, "IMP_NAME", 8, newSVpv("", 0), 0);
1479         hv_store(href, "IMP_VER", 7, newSVpv("", 0), 0);
1480         hv_store(href, "ERR_CODE", 8, newSViv(0), 0);
1481         hv_store(href, "ERR_STR", 7, newSViv(0), 0);
1482         hv_store(href, "PEER_NAME", 9, newSVpv(q->peer_name, 0), 0);
1483         hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1484         hv_store(href, "HANDLE", 6, newSVsv(&sv_undef), 0);
1485         hv_store(href, "PID", 3, newSViv(getpid()), 0);
1486         if (q->auth) {
1487             char *user = NULL;
1488             char *passwd = NULL;
1489             if (q->auth->which == Z_IdAuthentication_open) {
1490                 char *cp;
1491                 user = nmem_strdup (odr_getmem (q->stream), q->auth->u.open);
1492                 cp = strchr (user, '/');
1493                 if (cp) {
1494                     /* password after / given */
1495                     *cp = '\0';
1496                     passwd = cp+1;
1497                 }
1498             } else if (q->auth->which == Z_IdAuthentication_idPass) {
1499                 user = q->auth->u.idPass->userId;
1500                 passwd = q->auth->u.idPass->password;
1501             }
1502             /* ### some code paths have user/password unassigned here */
1503             if (user)
1504                 hv_store(href, "USER", 4, newSVpv(user, 0), 0);
1505             if (passwd)
1506                 hv_store(href, "PASS", 4, newSVpv(passwd, 0), 0);
1507         }
1508
1509         PUSHMARK(sp);   
1510
1511         XPUSHs(sv_2mortal(newRV((SV*) href)));
1512
1513         PUTBACK;
1514
1515         if (init_ref != NULL)
1516         {
1517              handler_cv = simpleserver_sv2cv( init_ref );
1518              perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1519         }
1520
1521         SPAGAIN;
1522
1523         temp = hv_fetch(href, "IMP_ID", 6, 1);
1524         ptr = SvPV(*temp, len);
1525         q->implementation_id = nmem_strdup(nmem, ptr);
1526
1527         temp = hv_fetch(href, "IMP_NAME", 8, 1);
1528         ptr = SvPV(*temp, len);
1529         q->implementation_name = nmem_strdup(nmem, ptr);
1530
1531         temp = hv_fetch(href, "IMP_VER", 7, 1);
1532         ptr = SvPV(*temp, len);
1533         q->implementation_version = nmem_strdup(nmem, ptr);
1534
1535         temp = hv_fetch(href, "ERR_CODE", 8, 1);
1536         r->errcode = SvIV(*temp);
1537
1538         temp = hv_fetch(href, "ERR_STR", 7, 1);
1539         ptr = SvPV(*temp, len);
1540         r->errstring = (char *)odr_malloc(q->stream, len + 1);
1541         strcpy(r->errstring, ptr);
1542
1543         temp = hv_fetch(href, "HANDLE", 6, 1);
1544         handle= newSVsv(*temp);
1545         zhandle->handle = handle;
1546
1547         r->handle = zhandle;
1548
1549         hv_undef(href);
1550         sv_free((SV*) href);
1551
1552         PUTBACK;
1553         FREETMPS;
1554         LEAVE;
1555         
1556         return r;       
1557 }
1558
1559 void bend_close(void *handle)
1560 {
1561         HV *href;
1562         Zfront_handle *zhandle = (Zfront_handle *)handle;
1563         CV* handler_cv = 0;
1564         int stop_flag = 0;
1565         dSP;
1566         ENTER;
1567         SAVETMPS;
1568
1569         if (close_ref)
1570         {
1571                 href = newHV();
1572                 hv_store(href, "GHANDLE", 7, newSVsv(zhandle->ghandle), 0);
1573                 hv_store(href, "HANDLE", 6, zhandle->handle, 0);
1574
1575                 PUSHMARK(sp);
1576
1577                 XPUSHs(sv_2mortal(newRV((SV *)href)));
1578
1579                 PUTBACK;
1580         
1581                 handler_cv = simpleserver_sv2cv( close_ref );
1582                 perl_call_sv( (SV *) handler_cv, G_SCALAR | G_DISCARD);
1583         
1584                 SPAGAIN;
1585
1586                 sv_free((SV*) href);
1587         }
1588         else
1589                 sv_free(zhandle->handle);
1590         PUTBACK;
1591         FREETMPS;
1592         LEAVE;
1593         stop_flag = zhandle->stop_flag;
1594         nmem_destroy(zhandle->nmem);
1595         simpleserver_free();
1596
1597         if (stop_flag)
1598                 exit(0);
1599         return;
1600 }
1601
1602
1603 MODULE = Net::Z3950::SimpleServer       PACKAGE = Net::Z3950::SimpleServer
1604
1605 PROTOTYPES: DISABLE
1606
1607
1608 void
1609 set_ghandle(arg)
1610                 SV *arg
1611         CODE:
1612                 _global_ghandle = newSVsv(arg);
1613                 
1614
1615 void
1616 set_init_handler(arg)
1617                 SV *arg
1618         CODE:
1619                 init_ref = newSVsv(arg);
1620                 
1621
1622 void
1623 set_close_handler(arg)
1624                 SV *arg
1625         CODE:
1626                 close_ref = newSVsv(arg);
1627
1628
1629 void
1630 set_sort_handler(arg)
1631                 SV *arg
1632         CODE:
1633                 sort_ref = newSVsv(arg);
1634
1635 void
1636 set_search_handler(arg)
1637                 SV *arg
1638         CODE:
1639                 search_ref = newSVsv(arg);
1640
1641
1642 void
1643 set_fetch_handler(arg)
1644                 SV *arg
1645         CODE:
1646                 fetch_ref = newSVsv(arg);
1647
1648
1649 void
1650 set_present_handler(arg)
1651                 SV *arg
1652         CODE:
1653                 present_ref = newSVsv(arg);
1654
1655
1656 void
1657 set_esrequest_handler(arg)
1658                 SV *arg
1659         CODE:
1660                 esrequest_ref = newSVsv(arg);
1661
1662
1663 void
1664 set_delete_handler(arg)
1665                 SV *arg
1666         CODE:
1667                 delete_ref = newSVsv(arg);
1668
1669
1670 void
1671 set_scan_handler(arg)
1672                 SV *arg
1673         CODE:
1674                 scan_ref = newSVsv(arg);
1675
1676 void
1677 set_explain_handler(arg)
1678                 SV *arg
1679         CODE:
1680                 explain_ref = newSVsv(arg);
1681
1682 int
1683 start_server(...)
1684         PREINIT:
1685                 char **argv;
1686                 char **argv_buf;
1687                 char *ptr;
1688                 int i;
1689                 STRLEN len;
1690         CODE:
1691                 argv_buf = (char **)xmalloc((items + 1) * sizeof(char *));
1692                 argv = argv_buf;
1693                 for (i = 0; i < items; i++)
1694                 {
1695                         ptr = SvPV(ST(i), len);
1696                         *argv_buf = (char *)xmalloc(len + 1);
1697                         strcpy(*argv_buf++, ptr); 
1698                 }
1699                 *argv_buf = NULL;
1700                 root_perl_context = PERL_GET_CONTEXT;
1701                 yaz_mutex_create(&simpleserver_mutex);
1702 #if 0
1703                 /* only for debugging perl_clone .. */
1704                 tst_clones();
1705 #endif
1706                 
1707                 RETVAL = statserv_main(items, argv, bend_init, bend_close);
1708         OUTPUT:
1709                 RETVAL
1710
1711
1712 int
1713 ScanSuccess()
1714         CODE:
1715                 RETVAL = BEND_SCAN_SUCCESS;
1716         OUTPUT:
1717                 RETVAL
1718
1719 int
1720 ScanPartial()
1721         CODE:
1722                 RETVAL = BEND_SCAN_PARTIAL;
1723         OUTPUT:
1724                 RETVAL
1725
1726  
1727 void
1728 yazlog(arg)
1729                 SV *arg
1730         CODE:
1731                 STRLEN len;
1732                 char *ptr;
1733                 ptr = SvPV(arg, len);
1734                 yaz_log(YLOG_LOG, "%.*s", len, ptr);
1735
1736 int
1737 yaz_diag_srw_to_bib1(srw_code)
1738         int srw_code
1739
1740 int
1741 yaz_diag_bib1_to_srw(bib1_code)
1742         int bib1_code
1743