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