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