2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.42 1995-08-15 11:16:50 quinn
8 * CV:e ----------------------------------------------------------------------
9 * CV:e ----------------------------------------------------------------------
11 * Revision 1.41 1995/08/02 10:23:06 quinn
14 * Revision 1.40 1995/07/31 14:34:26 quinn
15 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
17 * Revision 1.39 1995/06/27 13:21:00 quinn
20 * Revision 1.38 1995/06/19 12:39:11 quinn
21 * Fixed bug in timeout code. Added BER dumper.
23 * Revision 1.37 1995/06/16 13:16:14 quinn
24 * Fixed Defaultdiagformat.
26 * Revision 1.36 1995/06/16 10:31:36 quinn
27 * Added session timeout.
29 * Revision 1.35 1995/06/15 07:45:14 quinn
32 * Revision 1.34 1995/06/14 15:26:46 quinn
33 * *** empty log message ***
35 * Revision 1.33 1995/06/06 14:57:05 quinn
38 * Revision 1.32 1995/06/06 08:41:44 quinn
41 * Revision 1.31 1995/06/06 08:15:37 quinn
44 * Revision 1.30 1995/06/05 10:53:32 quinn
45 * Added a better SCAN.
47 * Revision 1.29 1995/06/01 11:25:03 quinn
50 * Revision 1.28 1995/06/01 11:21:01 quinn
51 * Attempting to fix a bug in pack-records. replaced break with continue
52 * for large records, according to standard.
54 * Revision 1.27 1995/05/29 08:12:06 quinn
57 * Revision 1.26 1995/05/18 13:02:12 quinn
60 * Revision 1.25 1995/05/17 08:42:26 quinn
61 * Transfer auth info to backend. Allow backend to reject init gracefully.
63 * Revision 1.24 1995/05/16 08:51:04 quinn
64 * License, documentation, and memory fixes
66 * Revision 1.23 1995/05/15 13:25:10 quinn
69 * Revision 1.22 1995/05/15 11:56:39 quinn
70 * Asynchronous facilities. Restructuring of seshigh code.
72 * Revision 1.21 1995/05/02 08:53:19 quinn
73 * Trying in vain to fix comm with ISODE
75 * Revision 1.20 1995/04/20 15:13:00 quinn
78 * Revision 1.19 1995/04/18 08:15:34 quinn
79 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
80 * neater. We'll make the same change for decoding one day.
82 * Revision 1.18 1995/04/17 11:28:25 quinn
85 * Revision 1.17 1995/04/10 10:23:36 quinn
86 * Some work to add scan and other things.
88 * Revision 1.16 1995/03/31 09:18:55 quinn
91 * Revision 1.15 1995/03/30 14:03:23 quinn
92 * Added RFC1006 as separate library
94 * Revision 1.14 1995/03/30 12:18:17 quinn
97 * Revision 1.13 1995/03/30 09:09:24 quinn
98 * Added state-handle and some support for asynchronous activities.
100 * Revision 1.12 1995/03/29 15:40:16 quinn
101 * Ongoing work. Statserv is now dynamic by default
103 * Revision 1.11 1995/03/28 09:16:21 quinn
104 * Added record packing to the search request
106 * Revision 1.10 1995/03/27 08:34:24 quinn
107 * Added dynamic server functionality.
108 * Released bindings to session.c (is now redundant)
110 * Revision 1.9 1995/03/22 15:01:26 quinn
111 * Adjusting record packing.
113 * Revision 1.8 1995/03/22 10:13:21 quinn
114 * Working on record packer
116 * Revision 1.7 1995/03/21 15:53:31 quinn
119 * Revision 1.6 1995/03/21 12:30:09 quinn
120 * Beginning to add support for record packing.
122 * Revision 1.5 1995/03/17 10:44:13 quinn
123 * Added catch of null-string in makediagrec
125 * Revision 1.4 1995/03/17 10:18:08 quinn
126 * Added memory management.
128 * Revision 1.3 1995/03/16 17:42:39 quinn
131 * Revision 1.2 1995/03/16 13:29:01 quinn
132 * Partitioned server.
134 * Revision 1.1 1995/03/15 16:02:10 quinn
135 * Modded session.c to seshigh.c
140 * Frontend server logic.
142 * This code receives incoming APDUs, and handles client requests by means
143 * of the backend API.
145 * Some of the code is getting quite involved, compared to simpler servers -
146 * primarily because it is asynchronous both in the communication with
147 * the user and the backend. We think the complexity will pay off in
148 * the form of greater flexibility when more asynchronous facilities
151 * Memory management has become somewhat involved. In the simple case, where
152 * only one PDU is pending at a time, it will simply reuse the same memory,
153 * once it has found its working size. When we enable multiple concurrent
154 * operations, perhaps even with multiple parallel calls to the backend, it
155 * will maintain a pool of buffers for encoding and decoding, trying to
156 * minimize memory allocation/deallocation during normal operation.
158 * TODOs include (and will be done in order of public interest):
160 * Support for EXPLAIN - provide simple meta-database system.
161 * Support for access control.
162 * Support for resource control.
163 * Support for extended services - primarily Item Order.
164 * Rest of Z39.50-1994
174 #include <comstack.h>
180 #include <statserv.h>
184 static int process_request(association *assoc);
185 void backend_response(IOCHAN i, int event);
186 static int process_response(association *assoc, request *req, Z_APDU *res);
187 static Z_APDU *process_initRequest(association *assoc, request *reqb);
188 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
190 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
191 bend_searchresult *bsrt, int *fd);
192 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
194 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
196 static FILE *apduf = 0; /* for use in static mode */
197 static statserv_options_block *control_block = 0;
200 * Create and initialize a new association-handle.
201 * channel : iochannel for the current line.
202 * link : communications channel.
203 * Returns: 0 or a new association handle.
205 association *create_association(IOCHAN channel, COMSTACK link)
210 control_block = statserv_getcontrol();
211 if (!(new = malloc(sizeof(*new))))
213 new->client_chan = channel;
214 new->client_link = link;
215 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
216 !(new->encode = odr_createmem(ODR_ENCODE)))
218 if (*control_block->apdufile)
223 strcpy(filename, control_block->apdufile);
224 if (!(new->print = odr_createmem(ODR_PRINT)))
226 if (*control_block->apdufile != '-')
228 strcpy(filename, control_block->apdufile);
229 if (!control_block->dynamic)
233 if (!(apduf = fopen(filename, "w")))
235 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
238 setvbuf(apduf, 0, _IONBF, 0);
244 sprintf(filename + strlen(filename), ".%d", getpid());
245 if (!(f = fopen(filename, "w")))
247 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
250 setvbuf(f, 0, _IONBF, 0);
252 odr_setprint(new->print, f);
257 new->input_buffer = 0;
258 new->input_buffer_len = 0;
261 request_initq(&new->incoming);
262 request_initq(&new->outgoing);
263 new->proto = cs_getproto(link);
268 * Free association and release resources.
270 void destroy_association(association *h)
272 odr_destroy(h->decode);
273 odr_destroy(h->encode);
275 odr_destroy(h->print);
277 free(h->input_buffer);
279 bend_close(h->backend);
280 while (request_deq(&h->incoming));
281 while (request_deq(&h->outgoing));
286 * This is where PDUs from the client are read and the further
287 * processing is initiated. Flow of control moves down through the
288 * various process_* functions below, until the encoded result comes back up
289 * to the output handler in here.
291 * h : the I/O channel that has an outstanding event.
292 * event : the current outstanding event.
294 void ir_session(IOCHAN h, int event)
297 association *assoc = iochan_getdata(h);
298 COMSTACK conn = assoc->client_link;
301 assert(h && conn && assoc);
302 if (event == EVENT_TIMEOUT)
304 logf(LOG_LOG, "Timeout - closing connection.");
306 destroy_association(assoc);
310 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
312 if (event & EVENT_INPUT)
314 logf(LOG_DEBUG, "ir_session (input)");
315 assert(assoc && conn);
316 /* We aren't speaking to this fellow */
319 logf(LOG_LOG, "Closed connection after reject");
321 destroy_association(assoc);
325 if ((res = cs_get(conn, &assoc->input_buffer,
326 &assoc->input_buffer_len)) <= 0)
328 logf(LOG_LOG, "Connection closed by client");
330 destroy_association(assoc);
334 else if (res == 1) /* incomplete read - wait for more */
336 if (cs_more(conn)) /* more stuff - call us again later, please */
337 iochan_setevent(h, EVENT_INPUT);
339 /* we got a complete PDU. Let's decode it */
340 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
341 req = request_get(); /* get a new request structure */
342 odr_reset(assoc->decode);
343 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
344 if (!z_APDU(assoc->decode, &req->request, 0))
346 logf(LOG_LOG, "ODR error on incoming PDU: %s",
347 odr_errlist[odr_geterror(assoc->decode)]);
348 logf(LOG_LOG, "PDU dump:");
349 odr_dumpBER(log_file(), assoc->input_buffer, res);
351 destroy_association(assoc);
355 req->request_mem = odr_extract_mem(assoc->decode);
356 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
358 logf(LOG_WARN, "ODR print error: %s",
359 odr_errlist[odr_geterror(assoc->print)]);
360 odr_reset(assoc->print);
362 request_enq(&assoc->incoming, req);
365 /* can we do something yet? */
366 req = request_head(&assoc->incoming);
367 if (req->state == REQUEST_IDLE)
368 if (process_request(assoc) < 0)
371 destroy_association(assoc);
375 if (event & EVENT_OUTPUT)
377 request *req = request_head(&assoc->outgoing);
379 logf(LOG_DEBUG, "ir_session (output)");
380 req->state = REQUEST_PENDING;
381 switch (res = cs_put(conn, req->response, req->len_response))
384 logf(LOG_LOG, "Connection closed by client");
386 destroy_association(assoc);
389 case 0: /* all sent - release the request structure */
390 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
391 odr_release_mem(req->request_mem);
392 request_deq(&assoc->outgoing);
393 request_release(req);
394 if (!request_head(&assoc->outgoing))
395 iochan_clearflag(h, EVENT_OUTPUT);
397 /* value of 1 -- partial send -- is simply ignored */
400 if (event & EVENT_EXCEPT)
402 logf(LOG_DEBUG, "ir_session (exception)");
404 destroy_association(assoc);
410 * Initiate request processing.
412 static int process_request(association *assoc)
414 request *req = request_head(&assoc->incoming);
418 logf(LOG_DEBUG, "process_request");
419 assert(req && req->state == REQUEST_IDLE);
420 switch (req->request->which)
422 case Z_APDU_initRequest:
423 res = process_initRequest(assoc, req); break;
424 case Z_APDU_searchRequest:
425 res = process_searchRequest(assoc, req, &fd); break;
426 case Z_APDU_presentRequest:
427 res = process_presentRequest(assoc, req, &fd); break;
428 case Z_APDU_scanRequest:
429 res = process_scanRequest(assoc, req, &fd); break;
431 logf(LOG_WARN, "Bad APDU received");
436 logf(LOG_DEBUG, " result immediately available");
437 return process_response(assoc, req, res);
441 logf(LOG_WARN, " bad result");
444 else /* no result yet - one will be provided later */
448 /* Set up an I/O handler for the fd supplied by the backend */
450 logf(LOG_DEBUG, " establishing handler for result");
451 req->state = REQUEST_PENDING;
452 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
454 iochan_setdata(chan, assoc);
460 * Handle message from the backend.
462 void backend_response(IOCHAN i, int event)
464 association *assoc = iochan_getdata(i);
465 request *req = request_head(&assoc->incoming);
469 logf(LOG_DEBUG, "backend_response");
470 assert(assoc && req && req->state != REQUEST_IDLE);
471 /* determine what it is we're waiting for */
472 switch (req->request->which)
474 case Z_APDU_searchRequest:
475 res = response_searchRequest(assoc, req, 0, &fd); break;
477 case Z_APDU_presentRequest:
478 res = response_presentRequest(assoc, req, 0, &fd); break;
479 case Z_APDU_scanRequest:
480 res = response_scanRequest(assoc, req, 0, &fd); break;
483 logf(LOG_WARN, "Serious programmer's lapse or bug");
486 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
488 logf(LOG_LOG, "Fatal error when talking to backend");
489 cs_close(assoc->client_link);
490 destroy_association(assoc);
491 iochan_destroy(assoc->client_chan);
495 else if (!res) /* no result yet - try again later */
497 logf(LOG_DEBUG, " no result yet");
498 iochan_setfd(i, fd); /* in case fd has changed */
503 * Encode response, and transfer the request structure to the outgoing queue.
505 static int process_response(association *assoc, request *req, Z_APDU *res)
507 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
508 if (!z_APDU(assoc->encode, &res, 0))
510 logf(LOG_WARN, "ODR error when encoding response: %s",
511 odr_errlist[odr_geterror(assoc->decode)]);
514 req->response = odr_getbuf(assoc->encode, &req->len_response,
515 &req->size_response);
516 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
517 odr_reset(assoc->encode);
518 if (assoc->print && !z_APDU(assoc->print, &res, 0))
520 logf(LOG_WARN, "ODR print error: %s",
521 odr_errlist[odr_geterror(assoc->print)]);
522 odr_reset(assoc->print);
524 /* change this when we make the backend reentrant */
525 assert(req == request_head(&assoc->incoming));
526 req->state = REQUEST_IDLE;
527 request_deq(&assoc->incoming);
528 request_enq(&assoc->outgoing, req);
529 /* turn the work over to the ir_session handler */
530 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
531 /* Is there more work to be done? give that to the input handler too */
532 if (request_head(&assoc->incoming))
533 iochan_setevent(assoc->client_chan, EVENT_WORK);
538 * Handle init request.
539 * At the moment, we don't check the protocol version or the options
540 * anywhere else in the code - we just try not to do anything that would
541 * break a naive client. We'll toss 'em into the association block when
542 * we need them there.
544 static Z_APDU *process_initRequest(association *assoc, request *reqb)
546 Z_InitRequest *req = reqb->request->u.initRequest;
547 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
548 Z_InitResponse *resp = apdu->u.initResponse;
549 bend_initrequest binitreq;
550 bend_initresult *binitres;
552 logf(LOG_LOG, "Got initRequest");
553 if (req->implementationId)
554 logf(LOG_LOG, "Id: %s", req->implementationId);
555 if (req->implementationName)
556 logf(LOG_LOG, "Name: %s", req->implementationName);
557 if (req->implementationVersion)
558 logf(LOG_LOG, "Version: %s", req->implementationVersion);
560 binitreq.configname = "default-config";
561 binitreq.auth = req->idAuthentication;
562 if (!(binitres = bend_init(&binitreq)))
564 logf(LOG_WARN, "Bad response from backend.");
568 assoc->backend = binitres->handle;
569 resp->referenceId = req->referenceId;
570 /* let's tell the client what we can do */
571 if (ODR_MASK_GET(req->options, Z_Options_search))
572 ODR_MASK_SET(resp->options, Z_Options_search);
573 if (ODR_MASK_GET(req->options, Z_Options_present))
574 ODR_MASK_SET(resp->options, Z_Options_present);
576 if (ODR_MASK_GET(req->options, Z_Options_delSet))
577 ODR_MASK_SET(&options, Z_Options_delSet);
579 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
580 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
581 if (ODR_MASK_GET(req->options, Z_Options_scan))
582 ODR_MASK_SET(resp->options, Z_Options_scan);
583 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
584 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
586 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
587 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
588 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
589 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
590 assoc->maximumRecordSize = *req->maximumRecordSize;
591 if (assoc->maximumRecordSize > control_block->maxrecordsize)
592 assoc->maximumRecordSize = control_block->maxrecordsize;
593 assoc->preferredMessageSize = *req->preferredMessageSize;
594 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
595 assoc->preferredMessageSize = assoc->maximumRecordSize;
596 resp->preferredMessageSize = &assoc->preferredMessageSize;
597 resp->maximumRecordSize = &assoc->maximumRecordSize;
598 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
599 if (binitres->errcode)
601 logf(LOG_LOG, "Connection rejected by backend.");
609 * These functions should be merged.
613 * nonsurrogate diagnostic record.
615 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
617 static Z_Records rec;
621 static Z_DiagRec drec;
622 static Z_DefaultDiagFormat dr;
628 bib1.class = CLASS_DIAGSET;
629 bib1.value = VAL_BIB1;
631 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
634 rec.which = Z_Records_NSD;
636 rec.u.nonSurrogateDiagnostic = &drec;
637 drec.which = Z_DiagRec_defaultFormat;
638 drec.u.defaultFormat = &dr;
640 rec.u.nonSurrogateDiagnostic = &dr;
642 dr.diagnosticSetId = oid_getoidbyent(&bib1);
644 dr.which = Z_DiagForm_v2AddInfo;
645 dr.addinfo = addinfo ? addinfo : "";
650 * surrogate diagnostic.
652 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
653 int error, char *addinfo)
655 static Z_NamePlusRecord rec;
659 static Z_DiagRec drec;
660 static Z_DefaultDiagFormat dr;
666 bib1.class = CLASS_DIAGSET;
667 bib1.value = VAL_BIB1;
669 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
671 rec.databaseName = dbname;
672 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
674 rec.u.surrogateDiagnostic = &drec;
675 drec.which = Z_DiagRec_defaultFormat;
676 drec.u.defaultFormat = &dr;
678 rec.u.surrogateDiagnostic = &dr;
680 dr.diagnosticSetId = oid_getoidbyent(&bib1);
682 dr.which = Z_DiagForm_v2AddInfo;
683 dr.addinfo = addinfo ? addinfo : "";
688 * multiple nonsurrogate diagnostics.
690 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
692 static Z_DiagRecs recs;
696 static Z_DiagRec *recp[1], drec;
697 static Z_DefaultDiagFormat rec;
699 static Z_DiagRec *recp[1], rec;
702 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
704 bib1.class = CLASS_DIAGSET;
705 bib1.value = VAL_BIB1;
708 recs.num_diagRecs = 1;
709 recs.diagRecs = recp;
712 drec.which = Z_DiagRec_defaultFormat;
713 drec.u.defaultFormat = &rec;
717 rec.diagnosticSetId = oid_getoidbyent(&bib1);
718 rec.condition = &err;
719 rec.which = Z_DiagForm_v2AddInfo;
720 rec.addinfo = addinfo ? addinfo : "";
724 #define MAX_RECORDS 256
726 static Z_Records *pack_records(association *a, char *setname, int start,
727 int *num, Z_ElementSetNames *esn,
728 int *next, int *pres, oid_value format)
730 int recno, total_length = 0, toget = *num;
731 static Z_Records records;
732 static Z_NamePlusRecordList reclist;
733 static Z_NamePlusRecord *list[MAX_RECORDS];
736 records.which = Z_Records_DBOSD;
737 records.u.databaseOrSurDiagnostics = &reclist;
738 reclist.num_records = 0;
739 reclist.records = list;
740 *pres = Z_PRES_SUCCESS;
744 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
745 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
746 a->maximumRecordSize);
747 for (recno = start; reclist.num_records < toget; recno++)
749 bend_fetchrequest freq;
750 bend_fetchresult *fres;
751 Z_NamePlusRecord *thisrec;
752 Z_DatabaseRecord *thisext;
754 if (reclist.num_records == MAX_RECORDS - 1)
756 *pres = Z_PRES_PARTIAL_2;
759 freq.setname = setname;
761 freq.format = format;
762 if (!(fres = bend_fetch(a->backend, &freq, 0)))
764 *pres = Z_PRES_FAILURE;
765 return diagrec(a->proto, 2, "Backend interface problem");
767 /* backend should be able to signal whether error is system-wide
768 or only pertaining to current record */
771 *pres = Z_PRES_FAILURE;
772 return diagrec(a->proto, fres->errcode, fres->errstring);
774 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
775 fres->len, total_length);
776 if (fres->len + total_length > a->preferredMessageSize)
778 /* record is small enough, really */
779 if (fres->len <= a->preferredMessageSize)
781 logf(LOG_DEBUG, " Dropped last normal-sized record");
782 *pres = Z_PRES_PARTIAL_2;
785 /* record can only be fetched by itself */
786 if (fres->len < a->maximumRecordSize)
788 logf(LOG_DEBUG, " Record > prefmsgsz");
791 logf(LOG_DEBUG, " Dropped it");
792 reclist.records[reclist.num_records] =
793 surrogatediagrec(a->proto, fres->basename, 16, 0);
794 reclist.num_records++;
795 total_length += 10; /* totally arbitrary */
799 else /* too big entirely */
801 logf(LOG_DEBUG, "Record > maxrcdsz");
802 reclist.records[reclist.num_records] =
803 surrogatediagrec(a->proto, fres->basename, 17, 0);
804 reclist.num_records++;
805 total_length += 10; /* totally arbitrary */
809 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
811 if (!(thisrec->databaseName = odr_malloc(a->encode,
812 strlen(fres->basename) + 1)))
814 strcpy(thisrec->databaseName, fres->basename);
815 thisrec->which = Z_NamePlusRecord_databaseRecord;
816 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
817 sizeof(Z_DatabaseRecord))))
819 recform.proto = a->proto;
820 recform.class = CLASS_RECSYN;
821 recform.value = fres->format;
822 thisext->direct_reference = odr_oiddup(a->encode,
823 oid_getoidbyent(&recform));
824 thisext->indirect_reference = 0;
825 thisext->descriptor = 0;
826 if (fres->format == VAL_SUTRS) /* SUTRS ios a single-ASN.1-type */
829 Odr_oct *sp = &sutrs_asn;
830 Odr_any *single = odr_malloc(a->encode, sizeof(*single));
831 char *buf, *remember;
834 sutrs_asn.buf = (unsigned char*) fres->record;
835 sutrs_asn.len = sutrs_asn.size = fres->len;
837 * we borrow the encoding stream for preparing the buffer. This
838 * is not the most elegant solution - a better way might have been
839 * to reserve a different stream, or to devise a better system
840 * for handling externals in general.
842 remember = odr_getbuf(a->encode, &len, &s_remember);
843 buf = odr_malloc(a->encode, fres->len + 10); /* buf for encoding */
844 odr_setbuf(a->encode, buf, fres->len + 10, 0); /* can_grow==0 */
845 if (!z_SUTRS(a->encode, &sp, 0))
847 logf(LOG_LOG, "ODR error encoding SUTRS: %s",
848 odr_errlist[odr_geterror(a->encode)]);
851 thisext->which = ODR_EXTERNAL_single;
852 thisext->u.single_ASN1_type = single;
853 single->buf = (unsigned char*)odr_getbuf(a->encode, &single->len,
855 /* Now restore the encoding stream */
856 odr_setbuf(a->encode, remember, s_remember, 1);
857 logf(LOG_DEBUG, " Format is SUTRS. len %d, encoded len %d",
858 fres->len, single->len);
860 else /* octet-aligned record. Easy as pie */
862 thisext->which = ODR_EXTERNAL_octet;
863 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
866 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
869 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
870 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
873 reclist.records[reclist.num_records] = thisrec;
874 reclist.num_records++;
875 total_length += fres->len;
876 *next = fres->last_in_set ? 0 : recno + 1;
878 *num = reclist.num_records;
882 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
885 Z_SearchRequest *req = reqb->request->u.searchRequest;
886 bend_searchrequest bsrq;
887 bend_searchresult *bsrt;
889 logf(LOG_LOG, "Got SearchRequest.");
891 bsrq.setname = req->resultSetName;
892 bsrq.replace_set = *req->replaceIndicator;
893 bsrq.num_bases = req->num_databaseNames;
894 bsrq.basenames = req->databaseNames;
895 bsrq.query = req->query;
897 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
899 return response_searchRequest(assoc, reqb, bsrt, fd);
902 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
905 * Prepare a searchresponse based on the backend results. We probably want
906 * to look at making the fetching of records nonblocking as well, but
907 * so far, we'll keep things simple.
908 * If bsrt is null, that means we're called in response to a communications
909 * event, and we'll have to get the response for ourselves.
911 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
912 bend_searchresult *bsrt, int *fd)
914 Z_SearchRequest *req = reqb->request->u.searchRequest;
916 static Z_SearchResponse resp;
917 static int nulint = 0;
918 static bool_t sr = 1;
920 static int none = Z_RES_NONE;
922 apdu.which = Z_APDU_searchResponse;
923 apdu.u.searchResponse = &resp;
924 resp.referenceId = req->referenceId;
926 resp.additionalSearchInfo = 0;
930 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
932 logf(LOG_FATAL, "Bad result from backend");
935 else if (bsrt->errcode)
937 resp.records = diagrec(assoc->proto, bsrt->errcode,
939 resp.resultCount = &nulint;
940 resp.numberOfRecordsReturned = &nulint;
941 resp.nextResultSetPosition = &nulint;
942 resp.searchStatus = &nulint;
943 resp.resultSetStatus = &none;
944 resp.presentStatus = 0;
949 Z_ElementSetNames *setnames;
950 static int presst = 0;
953 resp.resultCount = &bsrt->hits;
955 /* how many records does the user agent want, then? */
956 if (bsrt->hits <= *req->smallSetUpperBound)
959 setnames = req->smallSetElementSetNames;
961 else if (bsrt->hits < *req->largeSetLowerBound)
963 toget = *req->mediumSetPresentNumber;
964 if (toget > bsrt->hits)
966 setnames = req->mediumSetElementSetNames;
971 if (toget && !resp.records)
976 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
977 prefformat->class != CLASS_RECSYN)
980 form = prefformat->value;
981 resp.records = pack_records(assoc, req->resultSetName, 1,
982 &toget, setnames, &next, &presst, form);
985 resp.numberOfRecordsReturned = &toget;
986 resp.nextResultSetPosition = &next;
987 resp.searchStatus = &sr;
988 resp.resultSetStatus = 0;
989 resp.presentStatus = &presst;
993 resp.numberOfRecordsReturned = &nulint;
994 resp.nextResultSetPosition = &next;
995 resp.searchStatus = &sr;
996 resp.resultSetStatus = 0;
997 resp.presentStatus = 0;
1004 * Maybe we got a little over-friendly when we designed bend_fetch to
1005 * get only one record at a time. Some backends can optimise multiple-record
1006 * fetches, and at any rate, there is some overhead involved in
1007 * all that selecting and hopping around. Problem is, of course, that the
1008 * frontend can't know ahead of time how many records it'll need to
1009 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1010 * is downright lousy as a bulk data transfer protocol.
1012 * To start with, we'll do the fetching of records from the backend
1013 * in one operation: To save some trips in and out of the event-handler,
1014 * and to simplify the interface to pack_records. At any rate, asynch
1015 * operation is more fun in operations that have an unpredictable execution
1016 * speed - which is normally more true for search than for present.
1018 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1021 Z_PresentRequest *req = reqb->request->u.presentRequest;
1023 static Z_PresentResponse resp;
1024 static int presst, next, num;
1029 logf(LOG_LOG, "Got PresentRequest.");
1030 apdu.which = Z_APDU_presentResponse;
1031 apdu.u.presentResponse = &resp;
1032 resp.referenceId = req->referenceId;
1037 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1038 prefformat->class != CLASS_RECSYN)
1041 form = prefformat->value;
1042 num = *req->numberOfRecordsRequested;
1043 resp.records = pack_records(assoc, req->resultSetId,
1044 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1047 resp.numberOfRecordsReturned = #
1048 resp.presentStatus = &presst;
1049 resp.nextResultSetPosition = &next;
1055 * Scan was implemented rather in a hurry, and with support for only the basic
1056 * elements of the service in the backend API. Suggestions are welcome.
1058 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1060 Z_ScanRequest *req = reqb->request->u.scanRequest;
1062 static Z_ScanResponse res;
1063 static int scanStatus = Z_Scan_failure;
1064 static int numberOfEntriesReturned = 0;
1066 static Z_ListEntries ents;
1067 #define SCAN_MAX_ENTRIES 200
1068 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1069 bend_scanrequest srq;
1070 bend_scanresult *srs;
1072 logf(LOG_LOG, "Got scanrequest");
1073 apdu.which = Z_APDU_scanResponse;
1074 apdu.u.scanResponse = &res;
1075 res.referenceId = req->referenceId;
1077 res.scanStatus = &scanStatus;
1078 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1079 res.positionOfTerm = 0;
1080 res.entries = &ents;
1081 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1082 res.attributeSet = 0;
1087 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1088 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1089 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1090 else if (req->stepSize && *req->stepSize > 0)
1091 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1094 if (req->termListAndStartPoint->term->which == Z_Term_general)
1095 logf(LOG_DEBUG, " term: '%.*s'",
1096 req->termListAndStartPoint->term->u.general->len,
1097 req->termListAndStartPoint->term->u.general->buf);
1098 srq.num_bases = req->num_databaseNames;
1099 srq.basenames = req->databaseNames;
1100 srq.num_entries = *req->numberOfTermsRequested;
1101 srq.term = req->termListAndStartPoint;
1102 srq.term_position = req->preferredPositionInResponse ?
1103 *req->preferredPositionInResponse : 1;
1104 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1105 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1106 else if (srs->errcode)
1107 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1108 srs->errcode, srs->errstring);
1112 static Z_Entries list;
1114 if (srs->status == BEND_SCAN_PARTIAL)
1115 scanStatus = Z_Scan_partial_5;
1117 scanStatus = Z_Scan_success;
1118 ents.which = Z_ListEntries_entries;
1119 ents.u.entries = &list;
1121 for (i = 0; i < srs->num_entries; i++)
1127 if (i >= SCAN_MAX_ENTRIES)
1129 scanStatus = Z_Scan_partial_4;
1132 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1133 e->which = Z_Entry_termInfo;
1134 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1135 t->suggestedAttributes = 0;
1136 t->alternativeTerm = 0;
1137 t->byAttributes = 0;
1138 t->globalOccurrences = &srs->entries[i].occurrences;
1139 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1140 t->term->which = Z_Term_general;
1141 t->term->u.general = o = odr_malloc(assoc->encode,
1143 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1144 strlen(srs->entries[i].term));
1145 memcpy(o->buf, srs->entries[i].term, o->len);
1146 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1147 srs->entries[i].term, srs->entries[i].occurrences);
1149 list.num_entries = i;
1150 res.numberOfEntriesReturned = &list.num_entries;
1151 res.positionOfTerm = &srs->term_position;