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