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