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