2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.39 1995-06-27 13:21:00 quinn
10 * Revision 1.38 1995/06/19 12:39:11 quinn
11 * Fixed bug in timeout code. Added BER dumper.
13 * Revision 1.37 1995/06/16 13:16:14 quinn
14 * Fixed Defaultdiagformat.
16 * Revision 1.36 1995/06/16 10:31:36 quinn
17 * Added session timeout.
19 * Revision 1.35 1995/06/15 07:45:14 quinn
22 * Revision 1.34 1995/06/14 15:26:46 quinn
23 * *** empty log message ***
25 * Revision 1.33 1995/06/06 14:57:05 quinn
28 * Revision 1.32 1995/06/06 08:41:44 quinn
31 * Revision 1.31 1995/06/06 08:15:37 quinn
34 * Revision 1.30 1995/06/05 10:53:32 quinn
35 * Added a better SCAN.
37 * Revision 1.29 1995/06/01 11:25:03 quinn
40 * Revision 1.28 1995/06/01 11:21:01 quinn
41 * Attempting to fix a bug in pack-records. replaced break with continue
42 * for large records, according to standard.
44 * Revision 1.27 1995/05/29 08:12:06 quinn
47 * Revision 1.26 1995/05/18 13:02:12 quinn
50 * Revision 1.25 1995/05/17 08:42:26 quinn
51 * Transfer auth info to backend. Allow backend to reject init gracefully.
53 * Revision 1.24 1995/05/16 08:51:04 quinn
54 * License, documentation, and memory fixes
56 * Revision 1.23 1995/05/15 13:25:10 quinn
59 * Revision 1.22 1995/05/15 11:56:39 quinn
60 * Asynchronous facilities. Restructuring of seshigh code.
62 * Revision 1.21 1995/05/02 08:53:19 quinn
63 * Trying in vain to fix comm with ISODE
65 * Revision 1.20 1995/04/20 15:13:00 quinn
68 * Revision 1.19 1995/04/18 08:15:34 quinn
69 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
70 * neater. We'll make the same change for decoding one day.
72 * Revision 1.18 1995/04/17 11:28:25 quinn
75 * Revision 1.17 1995/04/10 10:23:36 quinn
76 * Some work to add scan and other things.
78 * Revision 1.16 1995/03/31 09:18:55 quinn
81 * Revision 1.15 1995/03/30 14:03:23 quinn
82 * Added RFC1006 as separate library
84 * Revision 1.14 1995/03/30 12:18:17 quinn
87 * Revision 1.13 1995/03/30 09:09:24 quinn
88 * Added state-handle and some support for asynchronous activities.
90 * Revision 1.12 1995/03/29 15:40:16 quinn
91 * Ongoing work. Statserv is now dynamic by default
93 * Revision 1.11 1995/03/28 09:16:21 quinn
94 * Added record packing to the search request
96 * Revision 1.10 1995/03/27 08:34:24 quinn
97 * Added dynamic server functionality.
98 * Released bindings to session.c (is now redundant)
100 * Revision 1.9 1995/03/22 15:01:26 quinn
101 * Adjusting record packing.
103 * Revision 1.8 1995/03/22 10:13:21 quinn
104 * Working on record packer
106 * Revision 1.7 1995/03/21 15:53:31 quinn
109 * Revision 1.6 1995/03/21 12:30:09 quinn
110 * Beginning to add support for record packing.
112 * Revision 1.5 1995/03/17 10:44:13 quinn
113 * Added catch of null-string in makediagrec
115 * Revision 1.4 1995/03/17 10:18:08 quinn
116 * Added memory management.
118 * Revision 1.3 1995/03/16 17:42:39 quinn
121 * Revision 1.2 1995/03/16 13:29:01 quinn
122 * Partitioned server.
124 * Revision 1.1 1995/03/15 16:02:10 quinn
125 * Modded session.c to seshigh.c
130 * Frontend server logic.
132 * This code receives incoming APDUs, and handles client requests by means
133 * of the backend API.
135 * Some of the code is getting quite involved, compared to simpler servers -
136 * primarily because it is asynchronous both in the communication with
137 * the user and the backend. We think the complexity will pay off in
138 * the form of greater flexibility when more asynchronous facilities
141 * Memory management has become somewhat involved. In the simple case, where
142 * only one PDU is pending at a time, it will simply reuse the same memory,
143 * once it has found its working size. When we enable multiple concurrent
144 * operations, perhaps even with multiple parallel calls to the backend, it
145 * will maintain a pool of buffers for encoding and decoding, trying to
146 * minimize memory allocation/deallocation during normal operation.
148 * TODOs include (and will be done in order of public interest):
150 * Support for EXPLAIN - provide simple meta-database system.
151 * Support for access control.
152 * Support for resource control.
153 * Support for extended services - primarily Item Order.
154 * Rest of Z39.50-1994
164 #include <comstack.h>
170 #include <statserv.h>
174 static int process_request(association *assoc);
175 void backend_response(IOCHAN i, int event);
176 static int process_response(association *assoc, request *req, Z_APDU *res);
177 static Z_APDU *process_initRequest(association *assoc, request *reqb);
178 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
180 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
181 bend_searchresult *bsrt, int *fd);
182 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
184 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
186 static FILE *apduf = 0; /* for use in static mode */
187 static statserv_options_block *control_block = 0;
190 * Create and initialize a new association-handle.
191 * channel : iochannel for the current line.
192 * link : communications channel.
193 * Returns: 0 or a new association handle.
195 association *create_association(IOCHAN channel, COMSTACK link)
200 control_block = statserv_getcontrol();
201 if (!(new = malloc(sizeof(*new))))
203 new->client_chan = channel;
204 new->client_link = link;
205 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
206 !(new->encode = odr_createmem(ODR_ENCODE)))
208 if (*control_block->apdufile)
213 strcpy(filename, control_block->apdufile);
214 if (!(new->print = odr_createmem(ODR_PRINT)))
216 if (*control_block->apdufile != '-')
218 strcpy(filename, control_block->apdufile);
219 if (!control_block->dynamic)
223 if (!(apduf = fopen(filename, "w")))
225 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
228 setvbuf(apduf, 0, _IONBF, 0);
234 sprintf(filename + strlen(filename), ".%d", getpid());
235 if (!(f = fopen(filename, "w")))
237 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
240 setvbuf(f, 0, _IONBF, 0);
242 odr_setprint(new->print, f);
247 new->input_buffer = 0;
248 new->input_buffer_len = 0;
251 request_initq(&new->incoming);
252 request_initq(&new->outgoing);
253 new->proto = cs_getproto(link);
258 * Free association and release resources.
260 void destroy_association(association *h)
262 odr_destroy(h->decode);
263 odr_destroy(h->encode);
265 odr_destroy(h->print);
267 free(h->input_buffer);
269 bend_close(h->backend);
270 while (request_deq(&h->incoming));
271 while (request_deq(&h->outgoing));
276 * This is where PDUs from the client are read and the further
277 * processing is initiated. Flow of control moves down through the
278 * various process_* functions below, until the encoded result comes back up
279 * to the output handler in here.
281 * h : the I/O channel that has an outstanding event.
282 * event : the current outstanding event.
284 void ir_session(IOCHAN h, int event)
287 association *assoc = iochan_getdata(h);
288 COMSTACK conn = assoc->client_link;
291 assert(h && conn && assoc);
292 if (event == EVENT_TIMEOUT)
294 logf(LOG_LOG, "Timeout - closing connection.");
296 destroy_association(assoc);
300 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
302 if (event & EVENT_INPUT)
304 logf(LOG_DEBUG, "ir_session (input)");
305 assert(assoc && conn);
306 /* We aren't speaking to this fellow */
309 logf(LOG_LOG, "Closed connection after reject");
311 destroy_association(assoc);
315 if ((res = cs_get(conn, &assoc->input_buffer,
316 &assoc->input_buffer_len)) <= 0)
318 logf(LOG_LOG, "Connection closed by client");
320 destroy_association(assoc);
324 else if (res == 1) /* incomplete read - wait for more */
326 if (cs_more(conn)) /* more stuff - call us again later, please */
327 iochan_setevent(h, EVENT_INPUT);
329 /* we got a complete PDU. Let's decode it */
330 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
331 req = request_get(); /* get a new request structure */
332 odr_reset(assoc->decode);
333 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
334 if (!z_APDU(assoc->decode, &req->request, 0))
336 logf(LOG_LOG, "ODR error on incoming PDU: %s",
337 odr_errlist[odr_geterror(assoc->decode)]);
338 logf(LOG_LOG, "PDU dump:");
339 odr_dumpBER(log_file(), assoc->input_buffer, res);
341 destroy_association(assoc);
345 req->request_mem = odr_extract_mem(assoc->decode);
346 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
348 logf(LOG_WARN, "ODR print error: %s",
349 odr_errlist[odr_geterror(assoc->print)]);
350 odr_reset(assoc->print);
352 request_enq(&assoc->incoming, req);
355 /* can we do something yet? */
356 req = request_head(&assoc->incoming);
357 if (req->state == REQUEST_IDLE)
358 if (process_request(assoc) < 0)
361 destroy_association(assoc);
365 if (event & EVENT_OUTPUT)
367 request *req = request_head(&assoc->outgoing);
369 logf(LOG_DEBUG, "ir_session (output)");
370 req->state = REQUEST_PENDING;
371 switch (res = cs_put(conn, req->response, req->len_response))
374 logf(LOG_LOG, "Connection closed by client");
376 destroy_association(assoc);
379 case 0: /* all sent - release the request structure */
380 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
381 odr_release_mem(req->request_mem);
382 request_deq(&assoc->outgoing);
383 request_release(req);
384 if (!request_head(&assoc->outgoing))
385 iochan_clearflag(h, EVENT_OUTPUT);
387 /* value of 1 -- partial send -- is simply ignored */
390 if (event & EVENT_EXCEPT)
392 logf(LOG_DEBUG, "ir_session (exception)");
394 destroy_association(assoc);
400 * Initiate request processing.
402 static int process_request(association *assoc)
404 request *req = request_head(&assoc->incoming);
408 logf(LOG_DEBUG, "process_request");
409 assert(req && req->state == REQUEST_IDLE);
410 switch (req->request->which)
412 case Z_APDU_initRequest:
413 res = process_initRequest(assoc, req); break;
414 case Z_APDU_searchRequest:
415 res = process_searchRequest(assoc, req, &fd); break;
416 case Z_APDU_presentRequest:
417 res = process_presentRequest(assoc, req, &fd); break;
418 case Z_APDU_scanRequest:
419 res = process_scanRequest(assoc, req, &fd); break;
421 logf(LOG_WARN, "Bad APDU received");
426 logf(LOG_DEBUG, " result immediately available");
427 return process_response(assoc, req, res);
431 logf(LOG_WARN, " bad result");
434 else /* no result yet - one will be provided later */
438 /* Set up an I/O handler for the fd supplied by the backend */
440 logf(LOG_DEBUG, " establishing handler for result");
441 req->state = REQUEST_PENDING;
442 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
444 iochan_setdata(chan, assoc);
450 * Handle message from the backend.
452 void backend_response(IOCHAN i, int event)
454 association *assoc = iochan_getdata(i);
455 request *req = request_head(&assoc->incoming);
459 logf(LOG_DEBUG, "backend_response");
460 assert(assoc && req && req->state != REQUEST_IDLE);
461 /* determine what it is we're waiting for */
462 switch (req->request->which)
464 case Z_APDU_searchRequest:
465 res = response_searchRequest(assoc, req, 0, &fd); break;
467 case Z_APDU_presentRequest:
468 res = response_presentRequest(assoc, req, 0, &fd); break;
469 case Z_APDU_scanRequest:
470 res = response_scanRequest(assoc, req, 0, &fd); break;
473 logf(LOG_WARN, "Serious programmer's lapse or bug");
476 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
478 logf(LOG_LOG, "Fatal error when talking to backend");
479 cs_close(assoc->client_link);
480 destroy_association(assoc);
481 iochan_destroy(assoc->client_chan);
485 else if (!res) /* no result yet - try again later */
487 logf(LOG_DEBUG, " no result yet");
488 iochan_setfd(i, fd); /* in case fd has changed */
493 * Encode response, and transfer the request structure to the outgoing queue.
495 static int process_response(association *assoc, request *req, Z_APDU *res)
497 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
498 if (!z_APDU(assoc->encode, &res, 0))
500 logf(LOG_WARN, "ODR error when encoding response: %s",
501 odr_errlist[odr_geterror(assoc->decode)]);
504 req->response = odr_getbuf(assoc->encode, &req->len_response,
505 &req->size_response);
506 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
507 odr_reset(assoc->encode);
508 if (assoc->print && !z_APDU(assoc->print, &res, 0))
510 logf(LOG_WARN, "ODR print error: %s",
511 odr_errlist[odr_geterror(assoc->print)]);
512 odr_reset(assoc->print);
514 /* change this when we make the backend reentrant */
515 assert(req == request_head(&assoc->incoming));
516 req->state = REQUEST_IDLE;
517 request_deq(&assoc->incoming);
518 request_enq(&assoc->outgoing, req);
519 /* turn the work over to the ir_session handler */
520 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
521 /* Is there more work to be done? give that to the input handler too */
522 if (request_head(&assoc->incoming))
523 iochan_setevent(assoc->client_chan, EVENT_WORK);
528 * Handle init request.
529 * At the moment, we don't check the protocol version or the options
530 * anywhere else in the code - we just try not to do anything that would
531 * break a naive client. We'll toss 'em into the association block when
532 * we need them there.
534 static Z_APDU *process_initRequest(association *assoc, request *reqb)
536 Z_InitRequest *req = reqb->request->u.initRequest;
537 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
538 Z_InitResponse *resp = apdu->u.initResponse;
539 bend_initrequest binitreq;
540 bend_initresult *binitres;
542 logf(LOG_LOG, "Got initRequest");
543 if (req->implementationId)
544 logf(LOG_LOG, "Id: %s", req->implementationId);
545 if (req->implementationName)
546 logf(LOG_LOG, "Name: %s", req->implementationName);
547 if (req->implementationVersion)
548 logf(LOG_LOG, "Version: %s", req->implementationVersion);
550 binitreq.configname = "default-config";
551 binitreq.auth = req->idAuthentication;
552 if (!(binitres = bend_init(&binitreq)))
554 logf(LOG_WARN, "Bad response from backend.");
558 assoc->backend = binitres->handle;
559 resp->referenceId = req->referenceId;
560 /* let's tell the client what we can do */
561 if (ODR_MASK_GET(req->options, Z_Options_search))
562 ODR_MASK_SET(resp->options, Z_Options_search);
563 if (ODR_MASK_GET(req->options, Z_Options_present))
564 ODR_MASK_SET(resp->options, Z_Options_present);
566 if (ODR_MASK_GET(req->options, Z_Options_delSet))
567 ODR_MASK_SET(&options, Z_Options_delSet);
569 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
570 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
571 if (ODR_MASK_GET(req->options, Z_Options_scan))
572 ODR_MASK_SET(resp->options, Z_Options_scan);
573 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
574 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
576 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
577 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
578 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
579 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
580 assoc->maximumRecordSize = *req->maximumRecordSize;
581 if (assoc->maximumRecordSize > control_block->maxrecordsize)
582 assoc->maximumRecordSize = control_block->maxrecordsize;
583 assoc->preferredMessageSize = *req->preferredMessageSize;
584 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
585 assoc->preferredMessageSize = assoc->maximumRecordSize;
586 resp->preferredMessageSize = &assoc->preferredMessageSize;
587 resp->maximumRecordSize = &assoc->maximumRecordSize;
588 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
589 if (binitres->errcode)
591 logf(LOG_LOG, "Connection rejected by backend.");
599 * These functions should be merged.
603 * nonsurrogate diagnostic record.
605 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
607 static Z_Records rec;
611 static Z_DiagRec drec;
612 static Z_DefaultDiagFormat dr;
618 bib1.class = CLASS_DIAGSET;
619 bib1.value = VAL_BIB1;
621 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
624 rec.which = Z_Records_NSD;
626 rec.u.nonSurrogateDiagnostic = &drec;
627 drec.which = Z_DiagRec_defaultFormat;
628 drec.u.defaultFormat = &dr;
630 rec.u.nonSurrogateDiagnostic = &dr;
632 dr.diagnosticSetId = oid_getoidbyent(&bib1);
634 dr.which = Z_DiagForm_v2AddInfo;
635 dr.addinfo = addinfo ? addinfo : "";
640 * surrogate diagnostic.
642 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
643 int error, char *addinfo)
645 static Z_NamePlusRecord rec;
649 static Z_DiagRec drec;
650 static Z_DefaultDiagFormat dr;
656 bib1.class = CLASS_DIAGSET;
657 bib1.value = VAL_BIB1;
659 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
661 rec.databaseName = dbname;
662 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
664 rec.u.surrogateDiagnostic = &drec;
665 drec.which = Z_DiagRec_defaultFormat;
666 drec.u.defaultFormat = &dr;
668 rec.u.surrogateDiagnostic = &dr;
670 dr.diagnosticSetId = oid_getoidbyent(&bib1);
672 dr.which = Z_DiagForm_v2AddInfo;
673 dr.addinfo = addinfo ? addinfo : "";
678 * multiple nonsurrogate diagnostics.
680 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
682 static Z_DiagRecs recs;
686 static Z_DiagRec *recp[1], drec;
687 static Z_DefaultDiagFormat rec;
689 static Z_DiagRec *recp[1], rec;
692 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
694 bib1.class = CLASS_DIAGSET;
695 bib1.value = VAL_BIB1;
698 recs.num_diagRecs = 1;
699 recs.diagRecs = recp;
702 drec.which = Z_DiagRec_defaultFormat;
703 drec.u.defaultFormat = &rec;
707 rec.diagnosticSetId = oid_getoidbyent(&bib1);
708 rec.condition = &err;
709 rec.which = Z_DiagForm_v2AddInfo;
710 rec.addinfo = addinfo ? addinfo : "";
714 #define MAX_RECORDS 256
716 static Z_Records *pack_records(association *a, char *setname, int start,
717 int *num, Z_ElementSetNames *esn,
718 int *next, int *pres, oid_value format)
720 int recno, total_length = 0, toget = *num;
721 static Z_Records records;
722 static Z_NamePlusRecordList reclist;
723 static Z_NamePlusRecord *list[MAX_RECORDS];
726 records.which = Z_Records_DBOSD;
727 records.u.databaseOrSurDiagnostics = &reclist;
728 reclist.num_records = 0;
729 reclist.records = list;
730 *pres = Z_PRES_SUCCESS;
734 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
735 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
736 a->maximumRecordSize);
737 for (recno = start; reclist.num_records < toget; recno++)
739 bend_fetchrequest freq;
740 bend_fetchresult *fres;
741 Z_NamePlusRecord *thisrec;
742 Z_DatabaseRecord *thisext;
744 if (reclist.num_records == MAX_RECORDS - 1)
746 *pres = Z_PRES_PARTIAL_2;
749 freq.setname = setname;
751 freq.format = format;
752 if (!(fres = bend_fetch(a->backend, &freq, 0)))
754 *pres = Z_PRES_FAILURE;
755 return diagrec(a->proto, 2, "Backend interface problem");
757 /* backend should be able to signal whether error is system-wide
758 or only pertaining to current record */
761 *pres = Z_PRES_FAILURE;
762 return diagrec(a->proto, fres->errcode, fres->errstring);
764 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
765 fres->len, total_length);
766 if (fres->len + total_length > a->preferredMessageSize)
768 /* record is small enough, really */
769 if (fres->len <= a->preferredMessageSize)
771 logf(LOG_DEBUG, " Dropped last normal-sized record");
772 *pres = Z_PRES_PARTIAL_2;
775 /* record can only be fetched by itself */
776 if (fres->len < a->maximumRecordSize)
778 logf(LOG_DEBUG, " Record > prefmsgsz");
781 logf(LOG_DEBUG, " Dropped it");
782 reclist.records[reclist.num_records] =
783 surrogatediagrec(a->proto, fres->basename, 16, 0);
784 reclist.num_records++;
785 total_length += 10; /* totally arbitrary */
789 else /* too big entirely */
791 logf(LOG_DEBUG, "Record > maxrcdsz");
792 reclist.records[reclist.num_records] =
793 surrogatediagrec(a->proto, fres->basename, 17, 0);
794 reclist.num_records++;
795 total_length += 10; /* totally arbitrary */
799 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
801 if (!(thisrec->databaseName = odr_malloc(a->encode,
802 strlen(fres->basename) + 1)))
804 strcpy(thisrec->databaseName, fres->basename);
805 thisrec->which = Z_NamePlusRecord_databaseRecord;
806 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
807 sizeof(Z_DatabaseRecord))))
809 recform.proto = a->proto;
810 recform.class = CLASS_RECSYN;
811 recform.value = fres->format;
812 thisext->direct_reference = odr_oiddup(a->encode,
813 oid_getoidbyent(&recform));
814 thisext->indirect_reference = 0;
815 thisext->descriptor = 0;
816 if (fres->format == VAL_SUTRS) /* SUTRS ios a single-ASN.1-type */
819 Odr_oct *sp = &sutrs_asn;
820 Odr_any *single = odr_malloc(a->encode, sizeof(*single));
821 char *buf, *remember;
824 sutrs_asn.buf = (unsigned char*) fres->record;
825 sutrs_asn.len = sutrs_asn.size = fres->len;
827 * we borrow the encoding stream for preparing the buffer. This
828 * is not the most elegant solution - a better way might have been
829 * to reserve a different stream, or to devise a better system
830 * for handling externals in general.
832 remember = odr_getbuf(a->encode, &len, &s_remember);
833 buf = odr_malloc(a->encode, fres->len + 10); /* buf for encoding */
834 odr_setbuf(a->encode, buf, fres->len + 10, 0); /* can_grow==0 */
835 if (!z_SUTRS(a->encode, &sp, 0))
837 logf(LOG_LOG, "ODR error encoding SUTRS: %s",
838 odr_errlist[odr_geterror(a->encode)]);
841 thisext->which = ODR_EXTERNAL_single;
842 thisext->u.single_ASN1_type = single;
843 single->buf = (unsigned char*)odr_getbuf(a->encode, &single->len,
845 /* Now restore the encoding stream */
846 odr_setbuf(a->encode, remember, s_remember, 1);
847 logf(LOG_DEBUG, " Format is SUTRS. len %d, encoded len %d",
848 fres->len, single->len);
850 else /* octet-aligned record. Easy as pie */
852 thisext->which = ODR_EXTERNAL_octet;
853 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
856 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
859 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
860 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
863 reclist.records[reclist.num_records] = thisrec;
864 reclist.num_records++;
865 total_length += fres->len;
866 *next = fres->last_in_set ? 0 : recno + 1;
868 *num = reclist.num_records;
872 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
875 Z_SearchRequest *req = reqb->request->u.searchRequest;
876 bend_searchrequest bsrq;
877 bend_searchresult *bsrt;
879 logf(LOG_LOG, "Got SearchRequest.");
881 bsrq.setname = req->resultSetName;
882 bsrq.replace_set = *req->replaceIndicator;
883 bsrq.num_bases = req->num_databaseNames;
884 bsrq.basenames = req->databaseNames;
885 bsrq.query = req->query;
887 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
889 return response_searchRequest(assoc, reqb, bsrt, fd);
892 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
895 * Prepare a searchresponse based on the backend results. We probably want
896 * to look at making the fetching of records nonblocking as well, but
897 * so far, we'll keep things simple.
898 * If bsrt is null, that means we're called in response to a communications
899 * event, and we'll have to get the response for ourselves.
901 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
902 bend_searchresult *bsrt, int *fd)
904 Z_SearchRequest *req = reqb->request->u.searchRequest;
906 static Z_SearchResponse resp;
907 static int nulint = 0;
908 static bool_t sr = 1;
910 static int none = Z_RES_NONE;
912 apdu.which = Z_APDU_searchResponse;
913 apdu.u.searchResponse = &resp;
914 resp.referenceId = req->referenceId;
916 resp.additionalSearchInfo = 0;
920 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
922 logf(LOG_FATAL, "Bad result from backend");
925 else if (bsrt->errcode)
927 resp.records = diagrec(assoc->proto, bsrt->errcode,
929 resp.resultCount = &nulint;
930 resp.numberOfRecordsReturned = &nulint;
931 resp.nextResultSetPosition = &nulint;
932 resp.searchStatus = &nulint;
933 resp.resultSetStatus = &none;
934 resp.presentStatus = 0;
939 Z_ElementSetNames *setnames;
943 resp.resultCount = &bsrt->hits;
945 /* how many records does the user agent want, then? */
946 if (bsrt->hits <= *req->smallSetUpperBound)
949 setnames = req->smallSetElementSetNames;
951 else if (bsrt->hits < *req->largeSetLowerBound)
953 toget = *req->mediumSetPresentNumber;
954 if (toget > bsrt->hits)
956 setnames = req->mediumSetElementSetNames;
961 if (toget && !resp.records)
966 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
967 prefformat->class != CLASS_RECSYN)
970 form = prefformat->value;
971 resp.records = pack_records(assoc, req->resultSetName, 1,
972 &toget, setnames, &next, &presst, form);
975 resp.numberOfRecordsReturned = &toget;
976 resp.nextResultSetPosition = &next;
977 resp.searchStatus = &sr;
978 resp.resultSetStatus = 0;
979 resp.presentStatus = &presst;
983 resp.numberOfRecordsReturned = &nulint;
984 resp.nextResultSetPosition = &next;
985 resp.searchStatus = &sr;
986 resp.resultSetStatus = 0;
987 resp.presentStatus = 0;
994 * Maybe we got a little over-friendly when we designed bend_fetch to
995 * get only one record at a time. Some backends can optimise multiple-record
996 * fetches, and at any rate, there is some overhead involved in
997 * all that selecting and hopping around. Problem is, of course, that the
998 * frontend can't know ahead of time how many records it'll need to
999 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1000 * is downright lousy as a bulk data transfer protocol.
1002 * To start with, we'll do the fetching of records from the backend
1003 * in one operation: To save some trips in and out of the event-handler,
1004 * and to simplify the interface to pack_records. At any rate, asynch
1005 * operation is more fun in operations that have an unpredictable execution
1006 * speed - which is normally more true for search than for present.
1008 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1011 Z_PresentRequest *req = reqb->request->u.presentRequest;
1013 static Z_PresentResponse resp;
1014 static int presst, next, num;
1019 logf(LOG_LOG, "Got PresentRequest.");
1020 apdu.which = Z_APDU_presentResponse;
1021 apdu.u.presentResponse = &resp;
1022 resp.referenceId = req->referenceId;
1027 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1028 prefformat->class != CLASS_RECSYN)
1031 form = prefformat->value;
1032 num = *req->numberOfRecordsRequested;
1033 resp.records = pack_records(assoc, req->resultSetId,
1034 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1037 resp.numberOfRecordsReturned = #
1038 resp.presentStatus = &presst;
1039 resp.nextResultSetPosition = &next;
1045 * Scan was implemented rather in a hurry, and with support for only the basic
1046 * elements of the service in the backend API. Suggestions are welcome.
1048 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1050 Z_ScanRequest *req = reqb->request->u.scanRequest;
1052 static Z_ScanResponse res;
1053 static int scanStatus = Z_Scan_failure;
1054 static int numberOfEntriesReturned = 0;
1056 static Z_ListEntries ents;
1057 #define SCAN_MAX_ENTRIES 200
1058 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1059 bend_scanrequest srq;
1060 bend_scanresult *srs;
1062 logf(LOG_LOG, "Got scanrequest");
1063 apdu.which = Z_APDU_scanResponse;
1064 apdu.u.scanResponse = &res;
1065 res.referenceId = req->referenceId;
1067 res.scanStatus = &scanStatus;
1068 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1069 res.positionOfTerm = 0;
1070 res.entries = &ents;
1071 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1072 res.attributeSet = 0;
1077 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1078 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1079 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1080 else if (req->stepSize && *req->stepSize > 0)
1081 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1084 if (req->termListAndStartPoint->term->which == Z_Term_general)
1085 logf(LOG_DEBUG, " term: '%.*s'",
1086 req->termListAndStartPoint->term->u.general->len,
1087 req->termListAndStartPoint->term->u.general->buf);
1088 srq.num_bases = req->num_databaseNames;
1089 srq.basenames = req->databaseNames;
1090 srq.num_entries = *req->numberOfTermsRequested;
1091 srq.term = req->termListAndStartPoint;
1092 srq.term_position = req->preferredPositionInResponse ?
1093 *req->preferredPositionInResponse : 1;
1094 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1095 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1096 else if (srs->errcode)
1097 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1098 srs->errcode, srs->errstring);
1102 static Z_Entries list;
1104 if (srs->status == BEND_SCAN_PARTIAL)
1105 scanStatus = Z_Scan_partial_5;
1107 scanStatus = Z_Scan_success;
1108 ents.which = Z_ListEntries_entries;
1109 ents.u.entries = &list;
1111 for (i = 0; i < srs->num_entries; i++)
1117 if (i >= SCAN_MAX_ENTRIES)
1119 scanStatus = Z_Scan_partial_4;
1122 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1123 e->which = Z_Entry_termInfo;
1124 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1125 t->suggestedAttributes = 0;
1126 t->alternativeTerm = 0;
1127 t->byAttributes = 0;
1128 t->globalOccurrences = &srs->entries[i].occurrences;
1129 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1130 t->term->which = Z_Term_general;
1131 t->term->u.general = o = odr_malloc(assoc->encode,
1133 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1134 strlen(srs->entries[i].term));
1135 memcpy(o->buf, srs->entries[i].term, o->len);
1136 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1137 srs->entries[i].term, srs->entries[i].occurrences);
1139 list.num_entries = i;
1140 res.numberOfEntriesReturned = &list.num_entries;
1141 res.positionOfTerm = &srs->term_position;