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