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