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