2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.40 1995-07-31 14:34:26 quinn
8 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
10 * Revision 1.39 1995/06/27 13:21:00 quinn
13 * Revision 1.38 1995/06/19 12:39:11 quinn
14 * Fixed bug in timeout code. Added BER dumper.
16 * Revision 1.37 1995/06/16 13:16:14 quinn
17 * Fixed Defaultdiagformat.
19 * Revision 1.36 1995/06/16 10:31:36 quinn
20 * Added session timeout.
22 * Revision 1.35 1995/06/15 07:45:14 quinn
25 * Revision 1.34 1995/06/14 15:26:46 quinn
26 * *** empty log message ***
28 * Revision 1.33 1995/06/06 14:57:05 quinn
31 * Revision 1.32 1995/06/06 08:41:44 quinn
34 * Revision 1.31 1995/06/06 08:15:37 quinn
37 * Revision 1.30 1995/06/05 10:53:32 quinn
38 * Added a better SCAN.
40 * Revision 1.29 1995/06/01 11:25:03 quinn
43 * Revision 1.28 1995/06/01 11:21:01 quinn
44 * Attempting to fix a bug in pack-records. replaced break with continue
45 * for large records, according to standard.
47 * Revision 1.27 1995/05/29 08:12:06 quinn
50 * Revision 1.26 1995/05/18 13:02:12 quinn
53 * Revision 1.25 1995/05/17 08:42:26 quinn
54 * Transfer auth info to backend. Allow backend to reject init gracefully.
56 * Revision 1.24 1995/05/16 08:51:04 quinn
57 * License, documentation, and memory fixes
59 * Revision 1.23 1995/05/15 13:25:10 quinn
62 * Revision 1.22 1995/05/15 11:56:39 quinn
63 * Asynchronous facilities. Restructuring of seshigh code.
65 * Revision 1.21 1995/05/02 08:53:19 quinn
66 * Trying in vain to fix comm with ISODE
68 * Revision 1.20 1995/04/20 15:13:00 quinn
71 * Revision 1.19 1995/04/18 08:15:34 quinn
72 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
73 * neater. We'll make the same change for decoding one day.
75 * Revision 1.18 1995/04/17 11:28:25 quinn
78 * Revision 1.17 1995/04/10 10:23:36 quinn
79 * Some work to add scan and other things.
81 * Revision 1.16 1995/03/31 09:18:55 quinn
84 * Revision 1.15 1995/03/30 14:03:23 quinn
85 * Added RFC1006 as separate library
87 * Revision 1.14 1995/03/30 12:18:17 quinn
90 * Revision 1.13 1995/03/30 09:09:24 quinn
91 * Added state-handle and some support for asynchronous activities.
93 * Revision 1.12 1995/03/29 15:40:16 quinn
94 * Ongoing work. Statserv is now dynamic by default
96 * Revision 1.11 1995/03/28 09:16:21 quinn
97 * Added record packing to the search request
99 * Revision 1.10 1995/03/27 08:34:24 quinn
100 * Added dynamic server functionality.
101 * Released bindings to session.c (is now redundant)
103 * Revision 1.9 1995/03/22 15:01:26 quinn
104 * Adjusting record packing.
106 * Revision 1.8 1995/03/22 10:13:21 quinn
107 * Working on record packer
109 * Revision 1.7 1995/03/21 15:53:31 quinn
112 * Revision 1.6 1995/03/21 12:30:09 quinn
113 * Beginning to add support for record packing.
115 * Revision 1.5 1995/03/17 10:44:13 quinn
116 * Added catch of null-string in makediagrec
118 * Revision 1.4 1995/03/17 10:18:08 quinn
119 * Added memory management.
121 * Revision 1.3 1995/03/16 17:42:39 quinn
124 * Revision 1.2 1995/03/16 13:29:01 quinn
125 * Partitioned server.
127 * Revision 1.1 1995/03/15 16:02:10 quinn
128 * Modded session.c to seshigh.c
133 * Frontend server logic.
135 * This code receives incoming APDUs, and handles client requests by means
136 * of the backend API.
138 * Some of the code is getting quite involved, compared to simpler servers -
139 * primarily because it is asynchronous both in the communication with
140 * the user and the backend. We think the complexity will pay off in
141 * the form of greater flexibility when more asynchronous facilities
144 * Memory management has become somewhat involved. In the simple case, where
145 * only one PDU is pending at a time, it will simply reuse the same memory,
146 * once it has found its working size. When we enable multiple concurrent
147 * operations, perhaps even with multiple parallel calls to the backend, it
148 * will maintain a pool of buffers for encoding and decoding, trying to
149 * minimize memory allocation/deallocation during normal operation.
151 * TODOs include (and will be done in order of public interest):
153 * Support for EXPLAIN - provide simple meta-database system.
154 * Support for access control.
155 * Support for resource control.
156 * Support for extended services - primarily Item Order.
157 * Rest of Z39.50-1994
167 #include <comstack.h>
173 #include <statserv.h>
177 static int process_request(association *assoc);
178 void backend_response(IOCHAN i, int event);
179 static int process_response(association *assoc, request *req, Z_APDU *res);
180 static Z_APDU *process_initRequest(association *assoc, request *reqb);
181 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
183 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
184 bend_searchresult *bsrt, int *fd);
185 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
187 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
189 static FILE *apduf = 0; /* for use in static mode */
190 static statserv_options_block *control_block = 0;
193 * Create and initialize a new association-handle.
194 * channel : iochannel for the current line.
195 * link : communications channel.
196 * Returns: 0 or a new association handle.
198 association *create_association(IOCHAN channel, COMSTACK link)
203 control_block = statserv_getcontrol();
204 if (!(new = malloc(sizeof(*new))))
206 new->client_chan = channel;
207 new->client_link = link;
208 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
209 !(new->encode = odr_createmem(ODR_ENCODE)))
211 if (*control_block->apdufile)
216 strcpy(filename, control_block->apdufile);
217 if (!(new->print = odr_createmem(ODR_PRINT)))
219 if (*control_block->apdufile != '-')
221 strcpy(filename, control_block->apdufile);
222 if (!control_block->dynamic)
226 if (!(apduf = fopen(filename, "w")))
228 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
231 setvbuf(apduf, 0, _IONBF, 0);
237 sprintf(filename + strlen(filename), ".%d", getpid());
238 if (!(f = fopen(filename, "w")))
240 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
243 setvbuf(f, 0, _IONBF, 0);
245 odr_setprint(new->print, f);
250 new->input_buffer = 0;
251 new->input_buffer_len = 0;
254 request_initq(&new->incoming);
255 request_initq(&new->outgoing);
256 new->proto = cs_getproto(link);
261 * Free association and release resources.
263 void destroy_association(association *h)
265 odr_destroy(h->decode);
266 odr_destroy(h->encode);
268 odr_destroy(h->print);
270 free(h->input_buffer);
272 bend_close(h->backend);
273 while (request_deq(&h->incoming));
274 while (request_deq(&h->outgoing));
279 * This is where PDUs from the client are read and the further
280 * processing is initiated. Flow of control moves down through the
281 * various process_* functions below, until the encoded result comes back up
282 * to the output handler in here.
284 * h : the I/O channel that has an outstanding event.
285 * event : the current outstanding event.
287 void ir_session(IOCHAN h, int event)
290 association *assoc = iochan_getdata(h);
291 COMSTACK conn = assoc->client_link;
294 assert(h && conn && assoc);
295 if (event == EVENT_TIMEOUT)
297 logf(LOG_LOG, "Timeout - closing connection.");
299 destroy_association(assoc);
303 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
305 if (event & EVENT_INPUT)
307 logf(LOG_DEBUG, "ir_session (input)");
308 assert(assoc && conn);
309 /* We aren't speaking to this fellow */
312 logf(LOG_LOG, "Closed connection after reject");
314 destroy_association(assoc);
318 if ((res = cs_get(conn, &assoc->input_buffer,
319 &assoc->input_buffer_len)) <= 0)
321 logf(LOG_LOG, "Connection closed by client");
323 destroy_association(assoc);
327 else if (res == 1) /* incomplete read - wait for more */
329 if (cs_more(conn)) /* more stuff - call us again later, please */
330 iochan_setevent(h, EVENT_INPUT);
332 /* we got a complete PDU. Let's decode it */
333 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
334 req = request_get(); /* get a new request structure */
335 odr_reset(assoc->decode);
336 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
337 if (!z_APDU(assoc->decode, &req->request, 0))
339 logf(LOG_LOG, "ODR error on incoming PDU: %s",
340 odr_errlist[odr_geterror(assoc->decode)]);
341 logf(LOG_LOG, "PDU dump:");
342 odr_dumpBER(log_file(), assoc->input_buffer, res);
344 destroy_association(assoc);
348 req->request_mem = odr_extract_mem(assoc->decode);
349 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
351 logf(LOG_WARN, "ODR print error: %s",
352 odr_errlist[odr_geterror(assoc->print)]);
353 odr_reset(assoc->print);
355 request_enq(&assoc->incoming, req);
358 /* can we do something yet? */
359 req = request_head(&assoc->incoming);
360 if (req->state == REQUEST_IDLE)
361 if (process_request(assoc) < 0)
364 destroy_association(assoc);
368 if (event & EVENT_OUTPUT)
370 request *req = request_head(&assoc->outgoing);
372 logf(LOG_DEBUG, "ir_session (output)");
373 req->state = REQUEST_PENDING;
374 switch (res = cs_put(conn, req->response, req->len_response))
377 logf(LOG_LOG, "Connection closed by client");
379 destroy_association(assoc);
382 case 0: /* all sent - release the request structure */
383 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
384 odr_release_mem(req->request_mem);
385 request_deq(&assoc->outgoing);
386 request_release(req);
387 if (!request_head(&assoc->outgoing))
388 iochan_clearflag(h, EVENT_OUTPUT);
390 /* value of 1 -- partial send -- is simply ignored */
393 if (event & EVENT_EXCEPT)
395 logf(LOG_DEBUG, "ir_session (exception)");
397 destroy_association(assoc);
403 * Initiate request processing.
405 static int process_request(association *assoc)
407 request *req = request_head(&assoc->incoming);
411 logf(LOG_DEBUG, "process_request");
412 assert(req && req->state == REQUEST_IDLE);
413 switch (req->request->which)
415 case Z_APDU_initRequest:
416 res = process_initRequest(assoc, req); break;
417 case Z_APDU_searchRequest:
418 res = process_searchRequest(assoc, req, &fd); break;
419 case Z_APDU_presentRequest:
420 res = process_presentRequest(assoc, req, &fd); break;
421 case Z_APDU_scanRequest:
422 res = process_scanRequest(assoc, req, &fd); break;
424 logf(LOG_WARN, "Bad APDU received");
429 logf(LOG_DEBUG, " result immediately available");
430 return process_response(assoc, req, res);
434 logf(LOG_WARN, " bad result");
437 else /* no result yet - one will be provided later */
441 /* Set up an I/O handler for the fd supplied by the backend */
443 logf(LOG_DEBUG, " establishing handler for result");
444 req->state = REQUEST_PENDING;
445 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
447 iochan_setdata(chan, assoc);
453 * Handle message from the backend.
455 void backend_response(IOCHAN i, int event)
457 association *assoc = iochan_getdata(i);
458 request *req = request_head(&assoc->incoming);
462 logf(LOG_DEBUG, "backend_response");
463 assert(assoc && req && req->state != REQUEST_IDLE);
464 /* determine what it is we're waiting for */
465 switch (req->request->which)
467 case Z_APDU_searchRequest:
468 res = response_searchRequest(assoc, req, 0, &fd); break;
470 case Z_APDU_presentRequest:
471 res = response_presentRequest(assoc, req, 0, &fd); break;
472 case Z_APDU_scanRequest:
473 res = response_scanRequest(assoc, req, 0, &fd); break;
476 logf(LOG_WARN, "Serious programmer's lapse or bug");
479 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
481 logf(LOG_LOG, "Fatal error when talking to backend");
482 cs_close(assoc->client_link);
483 destroy_association(assoc);
484 iochan_destroy(assoc->client_chan);
488 else if (!res) /* no result yet - try again later */
490 logf(LOG_DEBUG, " no result yet");
491 iochan_setfd(i, fd); /* in case fd has changed */
496 * Encode response, and transfer the request structure to the outgoing queue.
498 static int process_response(association *assoc, request *req, Z_APDU *res)
500 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
501 if (!z_APDU(assoc->encode, &res, 0))
503 logf(LOG_WARN, "ODR error when encoding response: %s",
504 odr_errlist[odr_geterror(assoc->decode)]);
507 req->response = odr_getbuf(assoc->encode, &req->len_response,
508 &req->size_response);
509 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
510 odr_reset(assoc->encode);
511 if (assoc->print && !z_APDU(assoc->print, &res, 0))
513 logf(LOG_WARN, "ODR print error: %s",
514 odr_errlist[odr_geterror(assoc->print)]);
515 odr_reset(assoc->print);
517 /* change this when we make the backend reentrant */
518 assert(req == request_head(&assoc->incoming));
519 req->state = REQUEST_IDLE;
520 request_deq(&assoc->incoming);
521 request_enq(&assoc->outgoing, req);
522 /* turn the work over to the ir_session handler */
523 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
524 /* Is there more work to be done? give that to the input handler too */
525 if (request_head(&assoc->incoming))
526 iochan_setevent(assoc->client_chan, EVENT_WORK);
531 * Handle init request.
532 * At the moment, we don't check the protocol version or the options
533 * anywhere else in the code - we just try not to do anything that would
534 * break a naive client. We'll toss 'em into the association block when
535 * we need them there.
537 static Z_APDU *process_initRequest(association *assoc, request *reqb)
539 Z_InitRequest *req = reqb->request->u.initRequest;
540 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
541 Z_InitResponse *resp = apdu->u.initResponse;
542 bend_initrequest binitreq;
543 bend_initresult *binitres;
545 logf(LOG_LOG, "Got initRequest");
546 if (req->implementationId)
547 logf(LOG_LOG, "Id: %s", req->implementationId);
548 if (req->implementationName)
549 logf(LOG_LOG, "Name: %s", req->implementationName);
550 if (req->implementationVersion)
551 logf(LOG_LOG, "Version: %s", req->implementationVersion);
553 binitreq.configname = "default-config";
554 binitreq.auth = req->idAuthentication;
555 if (!(binitres = bend_init(&binitreq)))
557 logf(LOG_WARN, "Bad response from backend.");
561 assoc->backend = binitres->handle;
562 resp->referenceId = req->referenceId;
563 /* let's tell the client what we can do */
564 if (ODR_MASK_GET(req->options, Z_Options_search))
565 ODR_MASK_SET(resp->options, Z_Options_search);
566 if (ODR_MASK_GET(req->options, Z_Options_present))
567 ODR_MASK_SET(resp->options, Z_Options_present);
569 if (ODR_MASK_GET(req->options, Z_Options_delSet))
570 ODR_MASK_SET(&options, Z_Options_delSet);
572 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
573 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
574 if (ODR_MASK_GET(req->options, Z_Options_scan))
575 ODR_MASK_SET(resp->options, Z_Options_scan);
576 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
577 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
579 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
580 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
581 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
582 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
583 assoc->maximumRecordSize = *req->maximumRecordSize;
584 if (assoc->maximumRecordSize > control_block->maxrecordsize)
585 assoc->maximumRecordSize = control_block->maxrecordsize;
586 assoc->preferredMessageSize = *req->preferredMessageSize;
587 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
588 assoc->preferredMessageSize = assoc->maximumRecordSize;
589 resp->preferredMessageSize = &assoc->preferredMessageSize;
590 resp->maximumRecordSize = &assoc->maximumRecordSize;
591 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
592 if (binitres->errcode)
594 logf(LOG_LOG, "Connection rejected by backend.");
602 * These functions should be merged.
606 * nonsurrogate diagnostic record.
608 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
610 static Z_Records rec;
614 static Z_DiagRec drec;
615 static Z_DefaultDiagFormat dr;
621 bib1.class = CLASS_DIAGSET;
622 bib1.value = VAL_BIB1;
624 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
627 rec.which = Z_Records_NSD;
629 rec.u.nonSurrogateDiagnostic = &drec;
630 drec.which = Z_DiagRec_defaultFormat;
631 drec.u.defaultFormat = &dr;
633 rec.u.nonSurrogateDiagnostic = &dr;
635 dr.diagnosticSetId = oid_getoidbyent(&bib1);
637 dr.which = Z_DiagForm_v2AddInfo;
638 dr.addinfo = addinfo ? addinfo : "";
643 * surrogate diagnostic.
645 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
646 int error, char *addinfo)
648 static Z_NamePlusRecord rec;
652 static Z_DiagRec drec;
653 static Z_DefaultDiagFormat dr;
659 bib1.class = CLASS_DIAGSET;
660 bib1.value = VAL_BIB1;
662 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
664 rec.databaseName = dbname;
665 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
667 rec.u.surrogateDiagnostic = &drec;
668 drec.which = Z_DiagRec_defaultFormat;
669 drec.u.defaultFormat = &dr;
671 rec.u.surrogateDiagnostic = &dr;
673 dr.diagnosticSetId = oid_getoidbyent(&bib1);
675 dr.which = Z_DiagForm_v2AddInfo;
676 dr.addinfo = addinfo ? addinfo : "";
681 * multiple nonsurrogate diagnostics.
683 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
685 static Z_DiagRecs recs;
689 static Z_DiagRec *recp[1], drec;
690 static Z_DefaultDiagFormat rec;
692 static Z_DiagRec *recp[1], rec;
695 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
697 bib1.class = CLASS_DIAGSET;
698 bib1.value = VAL_BIB1;
701 recs.num_diagRecs = 1;
702 recs.diagRecs = recp;
705 drec.which = Z_DiagRec_defaultFormat;
706 drec.u.defaultFormat = &rec;
710 rec.diagnosticSetId = oid_getoidbyent(&bib1);
711 rec.condition = &err;
712 rec.which = Z_DiagForm_v2AddInfo;
713 rec.addinfo = addinfo ? addinfo : "";
717 #define MAX_RECORDS 256
719 static Z_Records *pack_records(association *a, char *setname, int start,
720 int *num, Z_ElementSetNames *esn,
721 int *next, int *pres, oid_value format)
723 int recno, total_length = 0, toget = *num;
724 static Z_Records records;
725 static Z_NamePlusRecordList reclist;
726 static Z_NamePlusRecord *list[MAX_RECORDS];
729 records.which = Z_Records_DBOSD;
730 records.u.databaseOrSurDiagnostics = &reclist;
731 reclist.num_records = 0;
732 reclist.records = list;
733 *pres = Z_PRES_SUCCESS;
737 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
738 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
739 a->maximumRecordSize);
740 for (recno = start; reclist.num_records < toget; recno++)
742 bend_fetchrequest freq;
743 bend_fetchresult *fres;
744 Z_NamePlusRecord *thisrec;
745 Z_DatabaseRecord *thisext;
747 if (reclist.num_records == MAX_RECORDS - 1)
749 *pres = Z_PRES_PARTIAL_2;
752 freq.setname = setname;
754 freq.format = format;
755 if (!(fres = bend_fetch(a->backend, &freq, 0)))
757 *pres = Z_PRES_FAILURE;
758 return diagrec(a->proto, 2, "Backend interface problem");
760 /* backend should be able to signal whether error is system-wide
761 or only pertaining to current record */
764 *pres = Z_PRES_FAILURE;
765 return diagrec(a->proto, fres->errcode, fres->errstring);
767 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
768 fres->len, total_length);
769 if (fres->len + total_length > a->preferredMessageSize)
771 /* record is small enough, really */
772 if (fres->len <= a->preferredMessageSize)
774 logf(LOG_DEBUG, " Dropped last normal-sized record");
775 *pres = Z_PRES_PARTIAL_2;
778 /* record can only be fetched by itself */
779 if (fres->len < a->maximumRecordSize)
781 logf(LOG_DEBUG, " Record > prefmsgsz");
784 logf(LOG_DEBUG, " Dropped it");
785 reclist.records[reclist.num_records] =
786 surrogatediagrec(a->proto, fres->basename, 16, 0);
787 reclist.num_records++;
788 total_length += 10; /* totally arbitrary */
792 else /* too big entirely */
794 logf(LOG_DEBUG, "Record > maxrcdsz");
795 reclist.records[reclist.num_records] =
796 surrogatediagrec(a->proto, fres->basename, 17, 0);
797 reclist.num_records++;
798 total_length += 10; /* totally arbitrary */
802 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
804 if (!(thisrec->databaseName = odr_malloc(a->encode,
805 strlen(fres->basename) + 1)))
807 strcpy(thisrec->databaseName, fres->basename);
808 thisrec->which = Z_NamePlusRecord_databaseRecord;
809 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
810 sizeof(Z_DatabaseRecord))))
812 recform.proto = a->proto;
813 recform.class = CLASS_RECSYN;
814 recform.value = fres->format;
815 thisext->direct_reference = odr_oiddup(a->encode,
816 oid_getoidbyent(&recform));
817 thisext->indirect_reference = 0;
818 thisext->descriptor = 0;
819 if (fres->format == VAL_SUTRS) /* SUTRS ios a single-ASN.1-type */
822 Odr_oct *sp = &sutrs_asn;
823 Odr_any *single = odr_malloc(a->encode, sizeof(*single));
824 char *buf, *remember;
827 sutrs_asn.buf = (unsigned char*) fres->record;
828 sutrs_asn.len = sutrs_asn.size = fres->len;
830 * we borrow the encoding stream for preparing the buffer. This
831 * is not the most elegant solution - a better way might have been
832 * to reserve a different stream, or to devise a better system
833 * for handling externals in general.
835 remember = odr_getbuf(a->encode, &len, &s_remember);
836 buf = odr_malloc(a->encode, fres->len + 10); /* buf for encoding */
837 odr_setbuf(a->encode, buf, fres->len + 10, 0); /* can_grow==0 */
838 if (!z_SUTRS(a->encode, &sp, 0))
840 logf(LOG_LOG, "ODR error encoding SUTRS: %s",
841 odr_errlist[odr_geterror(a->encode)]);
844 thisext->which = ODR_EXTERNAL_single;
845 thisext->u.single_ASN1_type = single;
846 single->buf = (unsigned char*)odr_getbuf(a->encode, &single->len,
848 /* Now restore the encoding stream */
849 odr_setbuf(a->encode, remember, s_remember, 1);
850 logf(LOG_DEBUG, " Format is SUTRS. len %d, encoded len %d",
851 fres->len, single->len);
853 else /* octet-aligned record. Easy as pie */
855 thisext->which = ODR_EXTERNAL_octet;
856 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
859 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
862 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
863 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
866 reclist.records[reclist.num_records] = thisrec;
867 reclist.num_records++;
868 total_length += fres->len;
869 *next = fres->last_in_set ? 0 : recno + 1;
871 *num = reclist.num_records;
875 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
878 Z_SearchRequest *req = reqb->request->u.searchRequest;
879 bend_searchrequest bsrq;
880 bend_searchresult *bsrt;
882 logf(LOG_LOG, "Got SearchRequest.");
884 bsrq.setname = req->resultSetName;
885 bsrq.replace_set = *req->replaceIndicator;
886 bsrq.num_bases = req->num_databaseNames;
887 bsrq.basenames = req->databaseNames;
888 bsrq.query = req->query;
890 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
892 return response_searchRequest(assoc, reqb, bsrt, fd);
895 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
898 * Prepare a searchresponse based on the backend results. We probably want
899 * to look at making the fetching of records nonblocking as well, but
900 * so far, we'll keep things simple.
901 * If bsrt is null, that means we're called in response to a communications
902 * event, and we'll have to get the response for ourselves.
904 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
905 bend_searchresult *bsrt, int *fd)
907 Z_SearchRequest *req = reqb->request->u.searchRequest;
909 static Z_SearchResponse resp;
910 static int nulint = 0;
911 static bool_t sr = 1;
913 static int none = Z_RES_NONE;
915 apdu.which = Z_APDU_searchResponse;
916 apdu.u.searchResponse = &resp;
917 resp.referenceId = req->referenceId;
919 resp.additionalSearchInfo = 0;
923 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
925 logf(LOG_FATAL, "Bad result from backend");
928 else if (bsrt->errcode)
930 resp.records = diagrec(assoc->proto, bsrt->errcode,
932 resp.resultCount = &nulint;
933 resp.numberOfRecordsReturned = &nulint;
934 resp.nextResultSetPosition = &nulint;
935 resp.searchStatus = &nulint;
936 resp.resultSetStatus = &none;
937 resp.presentStatus = 0;
942 Z_ElementSetNames *setnames;
943 static int presst = 0;
946 resp.resultCount = &bsrt->hits;
948 /* how many records does the user agent want, then? */
949 if (bsrt->hits <= *req->smallSetUpperBound)
952 setnames = req->smallSetElementSetNames;
954 else if (bsrt->hits < *req->largeSetLowerBound)
956 toget = *req->mediumSetPresentNumber;
957 if (toget > bsrt->hits)
959 setnames = req->mediumSetElementSetNames;
964 if (toget && !resp.records)
969 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
970 prefformat->class != CLASS_RECSYN)
973 form = prefformat->value;
974 resp.records = pack_records(assoc, req->resultSetName, 1,
975 &toget, setnames, &next, &presst, form);
978 resp.numberOfRecordsReturned = &toget;
979 resp.nextResultSetPosition = &next;
980 resp.searchStatus = &sr;
981 resp.resultSetStatus = 0;
982 resp.presentStatus = &presst;
986 resp.numberOfRecordsReturned = &nulint;
987 resp.nextResultSetPosition = &next;
988 resp.searchStatus = &sr;
989 resp.resultSetStatus = 0;
990 resp.presentStatus = 0;
997 * Maybe we got a little over-friendly when we designed bend_fetch to
998 * get only one record at a time. Some backends can optimise multiple-record
999 * fetches, and at any rate, there is some overhead involved in
1000 * all that selecting and hopping around. Problem is, of course, that the
1001 * frontend can't know ahead of time how many records it'll need to
1002 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1003 * is downright lousy as a bulk data transfer protocol.
1005 * To start with, we'll do the fetching of records from the backend
1006 * in one operation: To save some trips in and out of the event-handler,
1007 * and to simplify the interface to pack_records. At any rate, asynch
1008 * operation is more fun in operations that have an unpredictable execution
1009 * speed - which is normally more true for search than for present.
1011 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1014 Z_PresentRequest *req = reqb->request->u.presentRequest;
1016 static Z_PresentResponse resp;
1017 static int presst, next, num;
1022 logf(LOG_LOG, "Got PresentRequest.");
1023 apdu.which = Z_APDU_presentResponse;
1024 apdu.u.presentResponse = &resp;
1025 resp.referenceId = req->referenceId;
1030 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1031 prefformat->class != CLASS_RECSYN)
1034 form = prefformat->value;
1035 num = *req->numberOfRecordsRequested;
1036 resp.records = pack_records(assoc, req->resultSetId,
1037 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1040 resp.numberOfRecordsReturned = #
1041 resp.presentStatus = &presst;
1042 resp.nextResultSetPosition = &next;
1048 * Scan was implemented rather in a hurry, and with support for only the basic
1049 * elements of the service in the backend API. Suggestions are welcome.
1051 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1053 Z_ScanRequest *req = reqb->request->u.scanRequest;
1055 static Z_ScanResponse res;
1056 static int scanStatus = Z_Scan_failure;
1057 static int numberOfEntriesReturned = 0;
1059 static Z_ListEntries ents;
1060 #define SCAN_MAX_ENTRIES 200
1061 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1062 bend_scanrequest srq;
1063 bend_scanresult *srs;
1065 logf(LOG_LOG, "Got scanrequest");
1066 apdu.which = Z_APDU_scanResponse;
1067 apdu.u.scanResponse = &res;
1068 res.referenceId = req->referenceId;
1070 res.scanStatus = &scanStatus;
1071 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1072 res.positionOfTerm = 0;
1073 res.entries = &ents;
1074 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1075 res.attributeSet = 0;
1080 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1081 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1082 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1083 else if (req->stepSize && *req->stepSize > 0)
1084 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1087 if (req->termListAndStartPoint->term->which == Z_Term_general)
1088 logf(LOG_DEBUG, " term: '%.*s'",
1089 req->termListAndStartPoint->term->u.general->len,
1090 req->termListAndStartPoint->term->u.general->buf);
1091 srq.num_bases = req->num_databaseNames;
1092 srq.basenames = req->databaseNames;
1093 srq.num_entries = *req->numberOfTermsRequested;
1094 srq.term = req->termListAndStartPoint;
1095 srq.term_position = req->preferredPositionInResponse ?
1096 *req->preferredPositionInResponse : 1;
1097 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1098 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1099 else if (srs->errcode)
1100 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1101 srs->errcode, srs->errstring);
1105 static Z_Entries list;
1107 if (srs->status == BEND_SCAN_PARTIAL)
1108 scanStatus = Z_Scan_partial_5;
1110 scanStatus = Z_Scan_success;
1111 ents.which = Z_ListEntries_entries;
1112 ents.u.entries = &list;
1114 for (i = 0; i < srs->num_entries; i++)
1120 if (i >= SCAN_MAX_ENTRIES)
1122 scanStatus = Z_Scan_partial_4;
1125 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1126 e->which = Z_Entry_termInfo;
1127 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1128 t->suggestedAttributes = 0;
1129 t->alternativeTerm = 0;
1130 t->byAttributes = 0;
1131 t->globalOccurrences = &srs->entries[i].occurrences;
1132 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1133 t->term->which = Z_Term_general;
1134 t->term->u.general = o = odr_malloc(assoc->encode,
1136 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1137 strlen(srs->entries[i].term));
1138 memcpy(o->buf, srs->entries[i].term, o->len);
1139 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1140 srs->entries[i].term, srs->entries[i].occurrences);
1142 list.num_entries = i;
1143 res.numberOfEntriesReturned = &list.num_entries;
1144 res.positionOfTerm = &srs->term_position;