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