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