2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.45 1995-08-21 09:11:00 quinn
8 * Smallish fixes to suppport new formats.
10 * Revision 1.44 1995/08/17 12:45:25 quinn
11 * Fixed minor problems with GRS-1. Added support in c&s.
13 * Revision 1.43 1995/08/15 12:00:31 quinn
16 * Revision 1.42 1995/08/15 11:16:50 quinn
17 * CV:e ----------------------------------------------------------------------
18 * CV:e ----------------------------------------------------------------------
20 * Revision 1.41 1995/08/02 10:23:06 quinn
23 * Revision 1.40 1995/07/31 14:34:26 quinn
24 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
26 * Revision 1.39 1995/06/27 13:21:00 quinn
29 * Revision 1.38 1995/06/19 12:39:11 quinn
30 * Fixed bug in timeout code. Added BER dumper.
32 * Revision 1.37 1995/06/16 13:16:14 quinn
33 * Fixed Defaultdiagformat.
35 * Revision 1.36 1995/06/16 10:31:36 quinn
36 * Added session timeout.
38 * Revision 1.35 1995/06/15 07:45:14 quinn
41 * Revision 1.34 1995/06/14 15:26:46 quinn
42 * *** empty log message ***
44 * Revision 1.33 1995/06/06 14:57:05 quinn
47 * Revision 1.32 1995/06/06 08:41:44 quinn
50 * Revision 1.31 1995/06/06 08:15:37 quinn
53 * Revision 1.30 1995/06/05 10:53:32 quinn
54 * Added a better SCAN.
56 * Revision 1.29 1995/06/01 11:25:03 quinn
59 * Revision 1.28 1995/06/01 11:21:01 quinn
60 * Attempting to fix a bug in pack-records. replaced break with continue
61 * for large records, according to standard.
63 * Revision 1.27 1995/05/29 08:12:06 quinn
66 * Revision 1.26 1995/05/18 13:02:12 quinn
69 * Revision 1.25 1995/05/17 08:42:26 quinn
70 * Transfer auth info to backend. Allow backend to reject init gracefully.
72 * Revision 1.24 1995/05/16 08:51:04 quinn
73 * License, documentation, and memory fixes
75 * Revision 1.23 1995/05/15 13:25:10 quinn
78 * Revision 1.22 1995/05/15 11:56:39 quinn
79 * Asynchronous facilities. Restructuring of seshigh code.
81 * Revision 1.21 1995/05/02 08:53:19 quinn
82 * Trying in vain to fix comm with ISODE
84 * Revision 1.20 1995/04/20 15:13:00 quinn
87 * Revision 1.19 1995/04/18 08:15:34 quinn
88 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
89 * neater. We'll make the same change for decoding one day.
91 * Revision 1.18 1995/04/17 11:28:25 quinn
94 * Revision 1.17 1995/04/10 10:23:36 quinn
95 * Some work to add scan and other things.
97 * Revision 1.16 1995/03/31 09:18:55 quinn
100 * Revision 1.15 1995/03/30 14:03:23 quinn
101 * Added RFC1006 as separate library
103 * Revision 1.14 1995/03/30 12:18:17 quinn
106 * Revision 1.13 1995/03/30 09:09:24 quinn
107 * Added state-handle and some support for asynchronous activities.
109 * Revision 1.12 1995/03/29 15:40:16 quinn
110 * Ongoing work. Statserv is now dynamic by default
112 * Revision 1.11 1995/03/28 09:16:21 quinn
113 * Added record packing to the search request
115 * Revision 1.10 1995/03/27 08:34:24 quinn
116 * Added dynamic server functionality.
117 * Released bindings to session.c (is now redundant)
119 * Revision 1.9 1995/03/22 15:01:26 quinn
120 * Adjusting record packing.
122 * Revision 1.8 1995/03/22 10:13:21 quinn
123 * Working on record packer
125 * Revision 1.7 1995/03/21 15:53:31 quinn
128 * Revision 1.6 1995/03/21 12:30:09 quinn
129 * Beginning to add support for record packing.
131 * Revision 1.5 1995/03/17 10:44:13 quinn
132 * Added catch of null-string in makediagrec
134 * Revision 1.4 1995/03/17 10:18:08 quinn
135 * Added memory management.
137 * Revision 1.3 1995/03/16 17:42:39 quinn
140 * Revision 1.2 1995/03/16 13:29:01 quinn
141 * Partitioned server.
143 * Revision 1.1 1995/03/15 16:02:10 quinn
144 * Modded session.c to seshigh.c
149 * Frontend server logic.
151 * This code receives incoming APDUs, and handles client requests by means
152 * of the backend API.
154 * Some of the code is getting quite involved, compared to simpler servers -
155 * primarily because it is asynchronous both in the communication with
156 * the user and the backend. We think the complexity will pay off in
157 * the form of greater flexibility when more asynchronous facilities
160 * Memory management has become somewhat involved. In the simple case, where
161 * only one PDU is pending at a time, it will simply reuse the same memory,
162 * once it has found its working size. When we enable multiple concurrent
163 * operations, perhaps even with multiple parallel calls to the backend, it
164 * will maintain a pool of buffers for encoding and decoding, trying to
165 * minimize memory allocation/deallocation during normal operation.
167 * TODOs include (and will be done in order of public interest):
169 * Support for EXPLAIN - provide simple meta-database system.
170 * Support for access control.
171 * Support for resource control.
172 * Support for extended services - primarily Item Order.
173 * Rest of Z39.50-1994
183 #include <comstack.h>
189 #include <statserv.h>
193 static int process_request(association *assoc);
194 void backend_response(IOCHAN i, int event);
195 static int process_response(association *assoc, request *req, Z_APDU *res);
196 static Z_APDU *process_initRequest(association *assoc, request *reqb);
197 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
199 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
200 bend_searchresult *bsrt, int *fd);
201 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
203 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
205 static FILE *apduf = 0; /* for use in static mode */
206 static statserv_options_block *control_block = 0;
209 * Create and initialize a new association-handle.
210 * channel : iochannel for the current line.
211 * link : communications channel.
212 * Returns: 0 or a new association handle.
214 association *create_association(IOCHAN channel, COMSTACK link)
219 control_block = statserv_getcontrol();
220 if (!(new = malloc(sizeof(*new))))
222 new->client_chan = channel;
223 new->client_link = link;
224 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
225 !(new->encode = odr_createmem(ODR_ENCODE)))
227 if (*control_block->apdufile)
232 strcpy(filename, control_block->apdufile);
233 if (!(new->print = odr_createmem(ODR_PRINT)))
235 if (*control_block->apdufile != '-')
237 strcpy(filename, control_block->apdufile);
238 if (!control_block->dynamic)
242 if (!(apduf = fopen(filename, "w")))
244 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
247 setvbuf(apduf, 0, _IONBF, 0);
253 sprintf(filename + strlen(filename), ".%d", getpid());
254 if (!(f = fopen(filename, "w")))
256 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
259 setvbuf(f, 0, _IONBF, 0);
261 odr_setprint(new->print, f);
266 new->input_buffer = 0;
267 new->input_buffer_len = 0;
270 request_initq(&new->incoming);
271 request_initq(&new->outgoing);
272 new->proto = cs_getproto(link);
277 * Free association and release resources.
279 void destroy_association(association *h)
281 odr_destroy(h->decode);
282 odr_destroy(h->encode);
284 odr_destroy(h->print);
286 free(h->input_buffer);
288 bend_close(h->backend);
289 while (request_deq(&h->incoming));
290 while (request_deq(&h->outgoing));
295 * This is where PDUs from the client are read and the further
296 * processing is initiated. Flow of control moves down through the
297 * various process_* functions below, until the encoded result comes back up
298 * to the output handler in here.
300 * h : the I/O channel that has an outstanding event.
301 * event : the current outstanding event.
303 void ir_session(IOCHAN h, int event)
306 association *assoc = iochan_getdata(h);
307 COMSTACK conn = assoc->client_link;
310 assert(h && conn && assoc);
311 if (event == EVENT_TIMEOUT)
313 logf(LOG_LOG, "Timeout - closing connection.");
315 destroy_association(assoc);
319 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
321 if (event & EVENT_INPUT)
323 logf(LOG_DEBUG, "ir_session (input)");
324 assert(assoc && conn);
325 /* We aren't speaking to this fellow */
328 logf(LOG_LOG, "Closed connection after reject");
330 destroy_association(assoc);
334 if ((res = cs_get(conn, &assoc->input_buffer,
335 &assoc->input_buffer_len)) <= 0)
337 logf(LOG_LOG, "Connection closed by client");
339 destroy_association(assoc);
343 else if (res == 1) /* incomplete read - wait for more */
345 if (cs_more(conn)) /* more stuff - call us again later, please */
346 iochan_setevent(h, EVENT_INPUT);
348 /* we got a complete PDU. Let's decode it */
349 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
350 req = request_get(); /* get a new request structure */
351 odr_reset(assoc->decode);
352 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
353 if (!z_APDU(assoc->decode, &req->request, 0))
355 logf(LOG_LOG, "ODR error on incoming PDU: %s",
356 odr_errlist[odr_geterror(assoc->decode)]);
357 logf(LOG_LOG, "PDU dump:");
358 odr_dumpBER(log_file(), assoc->input_buffer, res);
360 destroy_association(assoc);
364 req->request_mem = odr_extract_mem(assoc->decode);
365 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
367 logf(LOG_WARN, "ODR print error: %s",
368 odr_errlist[odr_geterror(assoc->print)]);
369 odr_reset(assoc->print);
371 request_enq(&assoc->incoming, req);
374 /* can we do something yet? */
375 req = request_head(&assoc->incoming);
376 if (req->state == REQUEST_IDLE)
377 if (process_request(assoc) < 0)
380 destroy_association(assoc);
384 if (event & EVENT_OUTPUT)
386 request *req = request_head(&assoc->outgoing);
388 logf(LOG_DEBUG, "ir_session (output)");
389 req->state = REQUEST_PENDING;
390 switch (res = cs_put(conn, req->response, req->len_response))
393 logf(LOG_LOG, "Connection closed by client");
395 destroy_association(assoc);
398 case 0: /* all sent - release the request structure */
399 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
400 odr_release_mem(req->request_mem);
401 request_deq(&assoc->outgoing);
402 request_release(req);
403 if (!request_head(&assoc->outgoing))
404 iochan_clearflag(h, EVENT_OUTPUT);
406 /* value of 1 -- partial send -- is simply ignored */
409 if (event & EVENT_EXCEPT)
411 logf(LOG_DEBUG, "ir_session (exception)");
413 destroy_association(assoc);
419 * Initiate request processing.
421 static int process_request(association *assoc)
423 request *req = request_head(&assoc->incoming);
427 logf(LOG_DEBUG, "process_request");
428 assert(req && req->state == REQUEST_IDLE);
429 switch (req->request->which)
431 case Z_APDU_initRequest:
432 res = process_initRequest(assoc, req); break;
433 case Z_APDU_searchRequest:
434 res = process_searchRequest(assoc, req, &fd); break;
435 case Z_APDU_presentRequest:
436 res = process_presentRequest(assoc, req, &fd); break;
437 case Z_APDU_scanRequest:
438 res = process_scanRequest(assoc, req, &fd); break;
440 logf(LOG_WARN, "Bad APDU received");
445 logf(LOG_DEBUG, " result immediately available");
446 return process_response(assoc, req, res);
450 logf(LOG_WARN, " bad result");
453 else /* no result yet - one will be provided later */
457 /* Set up an I/O handler for the fd supplied by the backend */
459 logf(LOG_DEBUG, " establishing handler for result");
460 req->state = REQUEST_PENDING;
461 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
463 iochan_setdata(chan, assoc);
469 * Handle message from the backend.
471 void backend_response(IOCHAN i, int event)
473 association *assoc = iochan_getdata(i);
474 request *req = request_head(&assoc->incoming);
478 logf(LOG_DEBUG, "backend_response");
479 assert(assoc && req && req->state != REQUEST_IDLE);
480 /* determine what it is we're waiting for */
481 switch (req->request->which)
483 case Z_APDU_searchRequest:
484 res = response_searchRequest(assoc, req, 0, &fd); break;
486 case Z_APDU_presentRequest:
487 res = response_presentRequest(assoc, req, 0, &fd); break;
488 case Z_APDU_scanRequest:
489 res = response_scanRequest(assoc, req, 0, &fd); break;
492 logf(LOG_WARN, "Serious programmer's lapse or bug");
495 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
497 logf(LOG_LOG, "Fatal error when talking to backend");
498 cs_close(assoc->client_link);
499 destroy_association(assoc);
500 iochan_destroy(assoc->client_chan);
504 else if (!res) /* no result yet - try again later */
506 logf(LOG_DEBUG, " no result yet");
507 iochan_setfd(i, fd); /* in case fd has changed */
512 * Encode response, and transfer the request structure to the outgoing queue.
514 static int process_response(association *assoc, request *req, Z_APDU *res)
516 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
517 if (!z_APDU(assoc->encode, &res, 0))
519 logf(LOG_WARN, "ODR error when encoding response: %s",
520 odr_errlist[odr_geterror(assoc->decode)]);
523 req->response = odr_getbuf(assoc->encode, &req->len_response,
524 &req->size_response);
525 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
526 odr_reset(assoc->encode);
527 if (assoc->print && !z_APDU(assoc->print, &res, 0))
529 logf(LOG_WARN, "ODR print error: %s",
530 odr_errlist[odr_geterror(assoc->print)]);
531 odr_reset(assoc->print);
533 /* change this when we make the backend reentrant */
534 assert(req == request_head(&assoc->incoming));
535 req->state = REQUEST_IDLE;
536 request_deq(&assoc->incoming);
537 request_enq(&assoc->outgoing, req);
538 /* turn the work over to the ir_session handler */
539 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
540 /* Is there more work to be done? give that to the input handler too */
541 if (request_head(&assoc->incoming))
542 iochan_setevent(assoc->client_chan, EVENT_WORK);
547 * Handle init request.
548 * At the moment, we don't check the protocol version or the options
549 * anywhere else in the code - we just try not to do anything that would
550 * break a naive client. We'll toss 'em into the association block when
551 * we need them there.
553 static Z_APDU *process_initRequest(association *assoc, request *reqb)
555 Z_InitRequest *req = reqb->request->u.initRequest;
556 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
557 Z_InitResponse *resp = apdu->u.initResponse;
558 bend_initrequest binitreq;
559 bend_initresult *binitres;
561 logf(LOG_LOG, "Got initRequest");
562 if (req->implementationId)
563 logf(LOG_LOG, "Id: %s", req->implementationId);
564 if (req->implementationName)
565 logf(LOG_LOG, "Name: %s", req->implementationName);
566 if (req->implementationVersion)
567 logf(LOG_LOG, "Version: %s", req->implementationVersion);
569 binitreq.configname = "default-config";
570 binitreq.auth = req->idAuthentication;
571 if (!(binitres = bend_init(&binitreq)))
573 logf(LOG_WARN, "Bad response from backend.");
577 assoc->backend = binitres->handle;
578 resp->referenceId = req->referenceId;
579 /* let's tell the client what we can do */
580 if (ODR_MASK_GET(req->options, Z_Options_search))
581 ODR_MASK_SET(resp->options, Z_Options_search);
582 if (ODR_MASK_GET(req->options, Z_Options_present))
583 ODR_MASK_SET(resp->options, Z_Options_present);
585 if (ODR_MASK_GET(req->options, Z_Options_delSet))
586 ODR_MASK_SET(&options, Z_Options_delSet);
588 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
589 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
590 if (ODR_MASK_GET(req->options, Z_Options_scan))
591 ODR_MASK_SET(resp->options, Z_Options_scan);
592 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
593 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
595 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
596 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
597 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
598 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
599 assoc->maximumRecordSize = *req->maximumRecordSize;
600 if (assoc->maximumRecordSize > control_block->maxrecordsize)
601 assoc->maximumRecordSize = control_block->maxrecordsize;
602 assoc->preferredMessageSize = *req->preferredMessageSize;
603 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
604 assoc->preferredMessageSize = assoc->maximumRecordSize;
605 resp->preferredMessageSize = &assoc->preferredMessageSize;
606 resp->maximumRecordSize = &assoc->maximumRecordSize;
607 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
608 if (binitres->errcode)
610 logf(LOG_LOG, "Connection rejected by backend.");
618 * These functions should be merged.
622 * nonsurrogate diagnostic record.
624 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
626 static Z_Records rec;
630 static Z_DiagRec drec;
631 static Z_DefaultDiagFormat dr;
637 bib1.class = CLASS_DIAGSET;
638 bib1.value = VAL_BIB1;
640 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
643 rec.which = Z_Records_NSD;
645 rec.u.nonSurrogateDiagnostic = &drec;
646 drec.which = Z_DiagRec_defaultFormat;
647 drec.u.defaultFormat = &dr;
649 rec.u.nonSurrogateDiagnostic = &dr;
651 dr.diagnosticSetId = oid_getoidbyent(&bib1);
653 dr.which = Z_DiagForm_v2AddInfo;
654 dr.addinfo = addinfo ? addinfo : "";
659 * surrogate diagnostic.
661 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
662 int error, char *addinfo)
664 static Z_NamePlusRecord rec;
668 static Z_DiagRec drec;
669 static Z_DefaultDiagFormat dr;
675 bib1.class = CLASS_DIAGSET;
676 bib1.value = VAL_BIB1;
678 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
680 rec.databaseName = dbname;
681 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
683 rec.u.surrogateDiagnostic = &drec;
684 drec.which = Z_DiagRec_defaultFormat;
685 drec.u.defaultFormat = &dr;
687 rec.u.surrogateDiagnostic = &dr;
689 dr.diagnosticSetId = oid_getoidbyent(&bib1);
691 dr.which = Z_DiagForm_v2AddInfo;
692 dr.addinfo = addinfo ? addinfo : "";
697 * multiple nonsurrogate diagnostics.
699 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
701 static Z_DiagRecs recs;
705 static Z_DiagRec *recp[1], drec;
706 static Z_DefaultDiagFormat rec;
708 static Z_DiagRec *recp[1], rec;
711 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
713 bib1.class = CLASS_DIAGSET;
714 bib1.value = VAL_BIB1;
717 recs.num_diagRecs = 1;
718 recs.diagRecs = recp;
721 drec.which = Z_DiagRec_defaultFormat;
722 drec.u.defaultFormat = &rec;
726 rec.diagnosticSetId = oid_getoidbyent(&bib1);
727 rec.condition = &err;
728 rec.which = Z_DiagForm_v2AddInfo;
729 rec.addinfo = addinfo ? addinfo : "";
733 #define MAX_RECORDS 256
735 static Z_Records *pack_records(association *a, char *setname, int start,
736 int *num, Z_ElementSetNames *esn,
737 int *next, int *pres, oid_value format)
739 int recno, total_length = 0, toget = *num;
740 static Z_Records records;
741 static Z_NamePlusRecordList reclist;
742 static Z_NamePlusRecord *list[MAX_RECORDS];
745 records.which = Z_Records_DBOSD;
746 records.u.databaseOrSurDiagnostics = &reclist;
747 reclist.num_records = 0;
748 reclist.records = list;
749 *pres = Z_PRES_SUCCESS;
753 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
754 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
755 a->maximumRecordSize);
756 for (recno = start; reclist.num_records < toget; recno++)
758 bend_fetchrequest freq;
759 bend_fetchresult *fres;
760 Z_NamePlusRecord *thisrec;
761 Z_DatabaseRecord *thisext;
765 * we get the number of bytes allocated on the stream before any
766 * allocation done by the backend - this should give us a reasonable
767 * idea of the total size of the data so far.
769 total_length = odr_total(a->encode);
770 if (reclist.num_records == MAX_RECORDS - 1)
772 *pres = Z_PRES_PARTIAL_2;
775 freq.setname = setname;
777 freq.format = format;
778 freq.stream = a->encode;
779 if (!(fres = bend_fetch(a->backend, &freq, 0)))
781 *pres = Z_PRES_FAILURE;
782 return diagrec(a->proto, 2, "Backend interface problem");
784 /* backend should be able to signal whether error is system-wide
785 or only pertaining to current record */
788 *pres = Z_PRES_FAILURE;
789 return diagrec(a->proto, fres->errcode, fres->errstring);
792 this_length = fres->len;
794 this_length = odr_total(a->encode) - total_length;
795 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
796 this_length, total_length);
797 if (this_length + total_length > a->preferredMessageSize)
799 /* record is small enough, really */
800 if (this_length <= a->preferredMessageSize)
802 logf(LOG_DEBUG, " Dropped last normal-sized record");
803 *pres = Z_PRES_PARTIAL_2;
806 /* record can only be fetched by itself */
807 if (this_length < a->maximumRecordSize)
809 logf(LOG_DEBUG, " Record > prefmsgsz");
812 logf(LOG_DEBUG, " Dropped it");
813 reclist.records[reclist.num_records] =
814 surrogatediagrec(a->proto, fres->basename, 16, 0);
815 reclist.num_records++;
819 else /* too big entirely */
821 logf(LOG_DEBUG, "Record > maxrcdsz");
822 reclist.records[reclist.num_records] =
823 surrogatediagrec(a->proto, fres->basename, 17, 0);
824 reclist.num_records++;
828 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
830 if (!(thisrec->databaseName = odr_malloc(a->encode,
831 strlen(fres->basename) + 1)))
833 strcpy(thisrec->databaseName, fres->basename);
834 thisrec->which = Z_NamePlusRecord_databaseRecord;
835 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
836 sizeof(Z_DatabaseRecord))))
838 recform.proto = a->proto;
839 recform.class = CLASS_RECSYN;
840 recform.value = fres->format;
841 thisext->direct_reference = odr_oiddup(a->encode,
842 oid_getoidbyent(&recform));
843 thisext->indirect_reference = 0;
844 thisext->descriptor = 0;
845 if (fres->len < 0) /* Structured data */
847 switch (fres->format)
849 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
850 case VAL_GRS1: thisext->which = Z_External_grs1; break;
851 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
855 logf(LOG_FATAL, "Unknown structured format from backend.");
860 * We cheat on the pointers here. Obviously, the record field
861 * of the backend-fetch structure should have been a union for
862 * correctness, but we're stuck with this for backwards
865 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
867 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
869 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
871 thisext->which = Z_External_sutrs;
872 thisext->u.sutrs = sutrs;
873 sutrs->buf = odr_malloc(a->encode, fres->len);
874 sutrs->len = sutrs->size = fres->len;
875 memcpy(sutrs->buf, fres->record, fres->len);
877 else /* octet-aligned record. */
879 thisext->which = Z_External_octet;
880 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
883 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
886 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
887 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
890 reclist.records[reclist.num_records] = thisrec;
891 reclist.num_records++;
892 *next = fres->last_in_set ? 0 : recno + 1;
894 *num = reclist.num_records;
898 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
901 Z_SearchRequest *req = reqb->request->u.searchRequest;
902 bend_searchrequest bsrq;
903 bend_searchresult *bsrt;
905 logf(LOG_LOG, "Got SearchRequest.");
907 bsrq.setname = req->resultSetName;
908 bsrq.replace_set = *req->replaceIndicator;
909 bsrq.num_bases = req->num_databaseNames;
910 bsrq.basenames = req->databaseNames;
911 bsrq.query = req->query;
913 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
915 return response_searchRequest(assoc, reqb, bsrt, fd);
918 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
921 * Prepare a searchresponse based on the backend results. We probably want
922 * to look at making the fetching of records nonblocking as well, but
923 * so far, we'll keep things simple.
924 * If bsrt is null, that means we're called in response to a communications
925 * event, and we'll have to get the response for ourselves.
927 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
928 bend_searchresult *bsrt, int *fd)
930 Z_SearchRequest *req = reqb->request->u.searchRequest;
932 static Z_SearchResponse resp;
933 static int nulint = 0;
934 static bool_t sr = 1;
936 static int none = Z_RES_NONE;
938 apdu.which = Z_APDU_searchResponse;
939 apdu.u.searchResponse = &resp;
940 resp.referenceId = req->referenceId;
942 resp.additionalSearchInfo = 0;
946 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
948 logf(LOG_FATAL, "Bad result from backend");
951 else if (bsrt->errcode)
953 resp.records = diagrec(assoc->proto, bsrt->errcode,
955 resp.resultCount = &nulint;
956 resp.numberOfRecordsReturned = &nulint;
957 resp.nextResultSetPosition = &nulint;
958 resp.searchStatus = &nulint;
959 resp.resultSetStatus = &none;
960 resp.presentStatus = 0;
965 Z_ElementSetNames *setnames;
966 static int presst = 0;
969 resp.resultCount = &bsrt->hits;
971 /* how many records does the user agent want, then? */
972 if (bsrt->hits <= *req->smallSetUpperBound)
975 setnames = req->smallSetElementSetNames;
977 else if (bsrt->hits < *req->largeSetLowerBound)
979 toget = *req->mediumSetPresentNumber;
980 if (toget > bsrt->hits)
982 setnames = req->mediumSetElementSetNames;
987 if (toget && !resp.records)
992 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
993 prefformat->class != CLASS_RECSYN)
996 form = prefformat->value;
997 resp.records = pack_records(assoc, req->resultSetName, 1,
998 &toget, setnames, &next, &presst, form);
1001 resp.numberOfRecordsReturned = &toget;
1002 resp.nextResultSetPosition = &next;
1003 resp.searchStatus = &sr;
1004 resp.resultSetStatus = 0;
1005 resp.presentStatus = &presst;
1009 if (*resp.resultCount)
1011 resp.numberOfRecordsReturned = &nulint;
1012 resp.nextResultSetPosition = &next;
1013 resp.searchStatus = &sr;
1014 resp.resultSetStatus = 0;
1015 resp.presentStatus = 0;
1022 * Maybe we got a little over-friendly when we designed bend_fetch to
1023 * get only one record at a time. Some backends can optimise multiple-record
1024 * fetches, and at any rate, there is some overhead involved in
1025 * all that selecting and hopping around. Problem is, of course, that the
1026 * frontend can't know ahead of time how many records it'll need to
1027 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1028 * is downright lousy as a bulk data transfer protocol.
1030 * To start with, we'll do the fetching of records from the backend
1031 * in one operation: To save some trips in and out of the event-handler,
1032 * and to simplify the interface to pack_records. At any rate, asynch
1033 * operation is more fun in operations that have an unpredictable execution
1034 * speed - which is normally more true for search than for present.
1036 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1039 Z_PresentRequest *req = reqb->request->u.presentRequest;
1041 static Z_PresentResponse resp;
1042 static int presst, next, num;
1047 logf(LOG_LOG, "Got PresentRequest.");
1048 apdu.which = Z_APDU_presentResponse;
1049 apdu.u.presentResponse = &resp;
1050 resp.referenceId = req->referenceId;
1055 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1056 prefformat->class != CLASS_RECSYN)
1059 form = prefformat->value;
1060 num = *req->numberOfRecordsRequested;
1061 resp.records = pack_records(assoc, req->resultSetId,
1062 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1065 resp.numberOfRecordsReturned = #
1066 resp.presentStatus = &presst;
1067 resp.nextResultSetPosition = &next;
1073 * Scan was implemented rather in a hurry, and with support for only the basic
1074 * elements of the service in the backend API. Suggestions are welcome.
1076 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1078 Z_ScanRequest *req = reqb->request->u.scanRequest;
1080 static Z_ScanResponse res;
1081 static int scanStatus = Z_Scan_failure;
1082 static int numberOfEntriesReturned = 0;
1084 static Z_ListEntries ents;
1085 #define SCAN_MAX_ENTRIES 200
1086 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1087 bend_scanrequest srq;
1088 bend_scanresult *srs;
1090 logf(LOG_LOG, "Got scanrequest");
1091 apdu.which = Z_APDU_scanResponse;
1092 apdu.u.scanResponse = &res;
1093 res.referenceId = req->referenceId;
1095 res.scanStatus = &scanStatus;
1096 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1097 res.positionOfTerm = 0;
1098 res.entries = &ents;
1099 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1100 res.attributeSet = 0;
1105 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1106 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1107 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1108 else if (req->stepSize && *req->stepSize > 0)
1109 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1112 if (req->termListAndStartPoint->term->which == Z_Term_general)
1113 logf(LOG_DEBUG, " term: '%.*s'",
1114 req->termListAndStartPoint->term->u.general->len,
1115 req->termListAndStartPoint->term->u.general->buf);
1116 srq.num_bases = req->num_databaseNames;
1117 srq.basenames = req->databaseNames;
1118 srq.num_entries = *req->numberOfTermsRequested;
1119 srq.term = req->termListAndStartPoint;
1120 srq.term_position = req->preferredPositionInResponse ?
1121 *req->preferredPositionInResponse : 1;
1122 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1123 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1124 else if (srs->errcode)
1125 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1126 srs->errcode, srs->errstring);
1130 static Z_Entries list;
1132 if (srs->status == BEND_SCAN_PARTIAL)
1133 scanStatus = Z_Scan_partial_5;
1135 scanStatus = Z_Scan_success;
1136 ents.which = Z_ListEntries_entries;
1137 ents.u.entries = &list;
1139 for (i = 0; i < srs->num_entries; i++)
1145 if (i >= SCAN_MAX_ENTRIES)
1147 scanStatus = Z_Scan_partial_4;
1150 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1151 e->which = Z_Entry_termInfo;
1152 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1153 t->suggestedAttributes = 0;
1154 t->alternativeTerm = 0;
1155 t->byAttributes = 0;
1156 t->globalOccurrences = &srs->entries[i].occurrences;
1157 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1158 t->term->which = Z_Term_general;
1159 t->term->u.general = o = odr_malloc(assoc->encode,
1161 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1162 strlen(srs->entries[i].term));
1163 memcpy(o->buf, srs->entries[i].term, o->len);
1164 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1165 srs->entries[i].term, srs->entries[i].occurrences);
1167 list.num_entries = i;
1168 res.numberOfEntriesReturned = &list.num_entries;
1169 res.positionOfTerm = &srs->term_position;