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