2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.52 1995-11-01 12:19:13 quinn
8 * Second attempt to fix same bug.
10 * Revision 1.50 1995/10/25 16:58:32 quinn
13 * Revision 1.49 1995/10/16 13:51:53 quinn
14 * Changes to provide Especs to the backend.
16 * Revision 1.48 1995/10/06 08:51:20 quinn
19 * Revision 1.47 1995/08/29 14:24:16 quinn
20 * Added second half of close-handshake
22 * Revision 1.46 1995/08/29 11:17:58 quinn
23 * Added code to receive close
25 * Revision 1.45 1995/08/21 09:11:00 quinn
26 * Smallish fixes to suppport new formats.
28 * Revision 1.44 1995/08/17 12:45:25 quinn
29 * Fixed minor problems with GRS-1. Added support in c&s.
31 * Revision 1.43 1995/08/15 12:00:31 quinn
34 * Revision 1.42 1995/08/15 11:16:50 quinn
36 * Revision 1.41 1995/08/02 10:23:06 quinn
39 * Revision 1.40 1995/07/31 14:34:26 quinn
40 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
42 * Revision 1.39 1995/06/27 13:21:00 quinn
45 * Revision 1.38 1995/06/19 12:39:11 quinn
46 * Fixed bug in timeout code. Added BER dumper.
48 * Revision 1.37 1995/06/16 13:16:14 quinn
49 * Fixed Defaultdiagformat.
51 * Revision 1.36 1995/06/16 10:31:36 quinn
52 * Added session timeout.
54 * Revision 1.35 1995/06/15 07:45:14 quinn
57 * Revision 1.34 1995/06/14 15:26:46 quinn
58 * *** empty log message ***
60 * Revision 1.33 1995/06/06 14:57:05 quinn
63 * Revision 1.32 1995/06/06 08:41:44 quinn
66 * Revision 1.31 1995/06/06 08:15:37 quinn
69 * Revision 1.30 1995/06/05 10:53:32 quinn
70 * Added a better SCAN.
72 * Revision 1.29 1995/06/01 11:25:03 quinn
75 * Revision 1.28 1995/06/01 11:21:01 quinn
76 * Attempting to fix a bug in pack-records. replaced break with continue
77 * for large records, according to standard.
79 * Revision 1.27 1995/05/29 08:12:06 quinn
82 * Revision 1.26 1995/05/18 13:02:12 quinn
85 * Revision 1.25 1995/05/17 08:42:26 quinn
86 * Transfer auth info to backend. Allow backend to reject init gracefully.
88 * Revision 1.24 1995/05/16 08:51:04 quinn
89 * License, documentation, and memory fixes
91 * Revision 1.23 1995/05/15 13:25:10 quinn
94 * Revision 1.22 1995/05/15 11:56:39 quinn
95 * Asynchronous facilities. Restructuring of seshigh code.
97 * Revision 1.21 1995/05/02 08:53:19 quinn
98 * Trying in vain to fix comm with ISODE
100 * Revision 1.20 1995/04/20 15:13:00 quinn
103 * Revision 1.19 1995/04/18 08:15:34 quinn
104 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
105 * neater. We'll make the same change for decoding one day.
107 * Revision 1.18 1995/04/17 11:28:25 quinn
110 * Revision 1.17 1995/04/10 10:23:36 quinn
111 * Some work to add scan and other things.
113 * Revision 1.16 1995/03/31 09:18:55 quinn
116 * Revision 1.15 1995/03/30 14:03:23 quinn
117 * Added RFC1006 as separate library
119 * Revision 1.14 1995/03/30 12:18:17 quinn
122 * Revision 1.13 1995/03/30 09:09:24 quinn
123 * Added state-handle and some support for asynchronous activities.
125 * Revision 1.12 1995/03/29 15:40:16 quinn
126 * Ongoing work. Statserv is now dynamic by default
128 * Revision 1.11 1995/03/28 09:16:21 quinn
129 * Added record packing to the search request
131 * Revision 1.10 1995/03/27 08:34:24 quinn
132 * Added dynamic server functionality.
133 * Released bindings to session.c (is now redundant)
135 * Revision 1.9 1995/03/22 15:01:26 quinn
136 * Adjusting record packing.
138 * Revision 1.8 1995/03/22 10:13:21 quinn
139 * Working on record packer
141 * Revision 1.7 1995/03/21 15:53:31 quinn
144 * Revision 1.6 1995/03/21 12:30:09 quinn
145 * Beginning to add support for record packing.
147 * Revision 1.5 1995/03/17 10:44:13 quinn
148 * Added catch of null-string in makediagrec
150 * Revision 1.4 1995/03/17 10:18:08 quinn
151 * Added memory management.
153 * Revision 1.3 1995/03/16 17:42:39 quinn
156 * Revision 1.2 1995/03/16 13:29:01 quinn
157 * Partitioned server.
159 * Revision 1.1 1995/03/15 16:02:10 quinn
160 * Modded session.c to seshigh.c
165 * Frontend server logic.
167 * This code receives incoming APDUs, and handles client requests by means
168 * of the backend API.
170 * Some of the code is getting quite involved, compared to simpler servers -
171 * primarily because it is asynchronous both in the communication with
172 * the user and the backend. We think the complexity will pay off in
173 * the form of greater flexibility when more asynchronous facilities
176 * Memory management has become somewhat involved. In the simple case, where
177 * only one PDU is pending at a time, it will simply reuse the same memory,
178 * once it has found its working size. When we enable multiple concurrent
179 * operations, perhaps even with multiple parallel calls to the backend, it
180 * will maintain a pool of buffers for encoding and decoding, trying to
181 * minimize memory allocation/deallocation during normal operation.
183 * TODOs include (and will be done in order of public interest):
185 * Support for EXPLAIN - provide simple meta-database system.
186 * Support for access control.
187 * Support for resource control.
188 * Support for extended services - primarily Item Order.
189 * Rest of Z39.50-1994
197 #include <sys/time.h>
200 #include <comstack.h>
206 #include <statserv.h>
210 static int process_request(association *assoc);
211 void backend_response(IOCHAN i, int event);
212 static int process_response(association *assoc, request *req, Z_APDU *res);
213 static Z_APDU *process_initRequest(association *assoc, request *reqb);
214 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
216 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
217 bend_searchresult *bsrt, int *fd);
218 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
220 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
221 static void process_close(association *assoc, request *reqb);
223 static FILE *apduf = 0; /* for use in static mode */
224 static statserv_options_block *control_block = 0;
227 * Create and initialize a new association-handle.
228 * channel : iochannel for the current line.
229 * link : communications channel.
230 * Returns: 0 or a new association handle.
232 association *create_association(IOCHAN channel, COMSTACK link)
237 control_block = statserv_getcontrol();
238 if (!(new = malloc(sizeof(*new))))
240 new->client_chan = channel;
241 new->client_link = link;
242 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
243 !(new->encode = odr_createmem(ODR_ENCODE)))
245 if (*control_block->apdufile)
250 strcpy(filename, control_block->apdufile);
251 if (!(new->print = odr_createmem(ODR_PRINT)))
253 if (*control_block->apdufile != '-')
255 strcpy(filename, control_block->apdufile);
256 if (!control_block->dynamic)
260 if (!(apduf = fopen(filename, "w")))
262 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
265 setvbuf(apduf, 0, _IONBF, 0);
271 sprintf(filename + strlen(filename), ".%d", getpid());
272 if (!(f = fopen(filename, "w")))
274 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
277 setvbuf(f, 0, _IONBF, 0);
279 odr_setprint(new->print, f);
284 new->input_buffer = 0;
285 new->input_buffer_len = 0;
287 new->state = ASSOC_NEW;
288 request_initq(&new->incoming);
289 request_initq(&new->outgoing);
290 new->proto = cs_getproto(link);
295 * Free association and release resources.
297 void destroy_association(association *h)
299 odr_destroy(h->decode);
300 odr_destroy(h->encode);
302 odr_destroy(h->print);
304 free(h->input_buffer);
306 bend_close(h->backend);
307 while (request_deq(&h->incoming));
308 while (request_deq(&h->outgoing));
312 static void do_close(association *a, int reason, char *message)
315 Z_Close *cls = zget_Close(a->encode);
316 request *req = request_get();
318 /* Purge request queue */
319 while (request_deq(&a->incoming));
320 while (request_deq(&a->outgoing));
323 logf(LOG_DEBUG, "Generating Close PDU");
324 apdu.which = Z_APDU_close;
326 *cls->closeReason = reason;
327 cls->diagnosticInformation = message;
328 process_response(a, req, &apdu);
329 iochan_settimeout(a->client_chan, 60);
333 logf(LOG_DEBUG, "v2 client. No Close PDU");
334 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
336 a->state = ASSOC_DEAD;
340 * This is where PDUs from the client are read and the further
341 * processing is initiated. Flow of control moves down through the
342 * various process_* functions below, until the encoded result comes back up
343 * to the output handler in here.
345 * h : the I/O channel that has an outstanding event.
346 * event : the current outstanding event.
348 void ir_session(IOCHAN h, int event)
351 association *assoc = iochan_getdata(h);
352 COMSTACK conn = assoc->client_link;
355 assert(h && conn && assoc);
356 if (event == EVENT_TIMEOUT)
358 if (assoc->state != ASSOC_UP)
360 logf(LOG_LOG, "Final timeout - closing connection.");
362 destroy_association(assoc);
367 logf(LOG_LOG, "Session idle too long. Sending close.");
368 do_close(assoc, Z_Close_lackOfActivity, 0);
372 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
374 if (event & EVENT_INPUT)
376 logf(LOG_DEBUG, "ir_session (input)");
377 assert(assoc && conn);
378 /* We aren't speaking to this fellow */
379 if (assoc->state == ASSOC_DEAD)
381 logf(LOG_LOG, "Closed connection after reject");
383 destroy_association(assoc);
387 if ((res = cs_get(conn, &assoc->input_buffer,
388 &assoc->input_buffer_len)) <= 0)
390 logf(LOG_LOG, "Connection closed by client");
392 destroy_association(assoc);
396 else if (res == 1) /* incomplete read - wait for more */
398 if (cs_more(conn)) /* more stuff - call us again later, please */
399 iochan_setevent(h, EVENT_INPUT);
401 /* we got a complete PDU. Let's decode it */
402 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
403 req = request_get(); /* get a new request structure */
404 odr_reset(assoc->decode);
405 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
406 if (!z_APDU(assoc->decode, &req->request, 0))
408 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
409 odr_errlist[odr_geterror(assoc->decode)],
410 odr_offset(assoc->decode));
411 logf(LOG_LOG, "PDU dump:");
412 odr_dumpBER(log_file(), assoc->input_buffer, res);
413 do_close(assoc, Z_Close_protocolError, "Malformed package");
416 req->request_mem = odr_extract_mem(assoc->decode);
417 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
419 logf(LOG_WARN, "ODR print error: %s",
420 odr_errlist[odr_geterror(assoc->print)]);
421 odr_reset(assoc->print);
423 request_enq(&assoc->incoming, req);
426 /* can we do something yet? */
427 req = request_head(&assoc->incoming);
428 if (req->state == REQUEST_IDLE)
429 if (process_request(assoc) < 0)
430 do_close(assoc, Z_Close_systemProblem, "Unknown error");
432 if (event & EVENT_OUTPUT)
434 request *req = request_head(&assoc->outgoing);
436 logf(LOG_DEBUG, "ir_session (output)");
437 req->state = REQUEST_PENDING;
438 switch (res = cs_put(conn, req->response, req->len_response))
441 logf(LOG_LOG, "Connection closed by client");
443 destroy_association(assoc);
446 case 0: /* all sent - release the request structure */
447 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
448 odr_release_mem(req->request_mem);
449 request_deq(&assoc->outgoing);
450 request_release(req);
451 if (!request_head(&assoc->outgoing))
452 iochan_clearflag(h, EVENT_OUTPUT);
454 /* value of 1 -- partial send -- is simply ignored */
457 if (event & EVENT_EXCEPT)
459 logf(LOG_DEBUG, "ir_session (exception)");
461 destroy_association(assoc);
467 * Initiate request processing.
469 static int process_request(association *assoc)
471 request *req = request_head(&assoc->incoming);
475 logf(LOG_DEBUG, "process_request");
476 assert(req && req->state == REQUEST_IDLE);
477 switch (req->request->which)
479 case Z_APDU_initRequest:
480 res = process_initRequest(assoc, req); break;
481 case Z_APDU_searchRequest:
482 res = process_searchRequest(assoc, req, &fd); break;
483 case Z_APDU_presentRequest:
484 res = process_presentRequest(assoc, req, &fd); break;
485 case Z_APDU_scanRequest:
486 res = process_scanRequest(assoc, req, &fd); break;
488 process_close(assoc, req); return 0;
490 logf(LOG_WARN, "Bad APDU received");
495 logf(LOG_DEBUG, " result immediately available");
496 return process_response(assoc, req, res);
500 logf(LOG_WARN, " bad result");
503 else /* no result yet - one will be provided later */
507 /* Set up an I/O handler for the fd supplied by the backend */
509 logf(LOG_DEBUG, " establishing handler for result");
510 req->state = REQUEST_PENDING;
511 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
513 iochan_setdata(chan, assoc);
519 * Handle message from the backend.
521 void backend_response(IOCHAN i, int event)
523 association *assoc = iochan_getdata(i);
524 request *req = request_head(&assoc->incoming);
528 logf(LOG_DEBUG, "backend_response");
529 assert(assoc && req && req->state != REQUEST_IDLE);
530 /* determine what it is we're waiting for */
531 switch (req->request->which)
533 case Z_APDU_searchRequest:
534 res = response_searchRequest(assoc, req, 0, &fd); break;
536 case Z_APDU_presentRequest:
537 res = response_presentRequest(assoc, req, 0, &fd); break;
538 case Z_APDU_scanRequest:
539 res = response_scanRequest(assoc, req, 0, &fd); break;
542 logf(LOG_WARN, "Serious programmer's lapse or bug");
545 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
547 logf(LOG_LOG, "Fatal error when talking to backend");
548 do_close(assoc, Z_Close_systemProblem, 0);
552 else if (!res) /* no result yet - try again later */
554 logf(LOG_DEBUG, " no result yet");
555 iochan_setfd(i, fd); /* in case fd has changed */
560 * Encode response, and transfer the request structure to the outgoing queue.
562 static int process_response(association *assoc, request *req, Z_APDU *res)
564 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
565 if (!z_APDU(assoc->encode, &res, 0))
567 logf(LOG_WARN, "ODR error when encoding response: %s",
568 odr_errlist[odr_geterror(assoc->decode)]);
571 req->response = odr_getbuf(assoc->encode, &req->len_response,
572 &req->size_response);
573 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
574 odr_reset(assoc->encode);
575 if (assoc->print && !z_APDU(assoc->print, &res, 0))
577 logf(LOG_WARN, "ODR print error: %s",
578 odr_errlist[odr_geterror(assoc->print)]);
579 odr_reset(assoc->print);
581 /* change this when we make the backend reentrant */
582 if (req == request_head(&assoc->incoming))
584 req->state = REQUEST_IDLE;
585 request_deq(&assoc->incoming);
587 request_enq(&assoc->outgoing, req);
588 /* turn the work over to the ir_session handler */
589 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
590 /* Is there more work to be done? give that to the input handler too */
591 if (request_head(&assoc->incoming))
592 iochan_setevent(assoc->client_chan, EVENT_WORK);
597 * Handle init request.
598 * At the moment, we don't check the options
599 * anywhere else in the code - we just try not to do anything that would
600 * break a naive client. We'll toss 'em into the association block when
601 * we need them there.
603 static Z_APDU *process_initRequest(association *assoc, request *reqb)
605 Z_InitRequest *req = reqb->request->u.initRequest;
606 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
607 Z_InitResponse *resp = apdu->u.initResponse;
608 bend_initrequest binitreq;
609 bend_initresult *binitres;
612 logf(LOG_LOG, "Got initRequest");
613 if (req->implementationId)
614 logf(LOG_LOG, "Id: %s", req->implementationId);
615 if (req->implementationName)
616 logf(LOG_LOG, "Name: %s", req->implementationName);
617 if (req->implementationVersion)
618 logf(LOG_LOG, "Version: %s", req->implementationVersion);
620 binitreq.configname = "default-config";
621 binitreq.auth = req->idAuthentication;
622 if (!(binitres = bend_init(&binitreq)))
624 logf(LOG_WARN, "Bad response from backend.");
628 assoc->backend = binitres->handle;
629 resp->referenceId = req->referenceId;
631 /* let's tell the client what we can do */
632 if (ODR_MASK_GET(req->options, Z_Options_search))
634 ODR_MASK_SET(resp->options, Z_Options_search);
635 strcat(options, "srch");
637 if (ODR_MASK_GET(req->options, Z_Options_present))
639 ODR_MASK_SET(resp->options, Z_Options_present);
640 strcat(options, " prst");
643 if (ODR_MASK_GET(req->options, Z_Options_delSet))
645 ODR_MASK_SET(&options, Z_Options_delSet);
646 strcat(options, " del");
649 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
651 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
652 strcat(options, " namedresults");
654 if (ODR_MASK_GET(req->options, Z_Options_scan))
656 ODR_MASK_SET(resp->options, Z_Options_scan);
657 strcat(options, " scan");
659 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
661 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
662 strcat(options, " concurop");
665 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
667 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
668 assoc->version = 2; /* 1 & 2 are equivalent */
670 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
672 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
675 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
677 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
680 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
681 assoc->maximumRecordSize = *req->maximumRecordSize;
682 if (assoc->maximumRecordSize > control_block->maxrecordsize)
683 assoc->maximumRecordSize = control_block->maxrecordsize;
684 assoc->preferredMessageSize = *req->preferredMessageSize;
685 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
686 assoc->preferredMessageSize = assoc->maximumRecordSize;
687 resp->preferredMessageSize = &assoc->preferredMessageSize;
688 resp->maximumRecordSize = &assoc->maximumRecordSize;
689 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
690 if (binitres->errcode)
692 logf(LOG_LOG, "Connection rejected by backend.");
694 assoc->state = ASSOC_DEAD;
697 assoc->state = ASSOC_UP;
702 * These functions should be merged.
706 * nonsurrogate diagnostic record.
708 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
710 static Z_Records rec;
714 static Z_DiagRec drec;
715 static Z_DefaultDiagFormat dr;
721 bib1.class = CLASS_DIAGSET;
722 bib1.value = VAL_BIB1;
724 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
727 rec.which = Z_Records_NSD;
729 rec.u.nonSurrogateDiagnostic = &drec;
730 drec.which = Z_DiagRec_defaultFormat;
731 drec.u.defaultFormat = &dr;
733 rec.u.nonSurrogateDiagnostic = &dr;
735 dr.diagnosticSetId = oid_getoidbyent(&bib1);
737 dr.which = Z_DiagForm_v2AddInfo;
738 dr.addinfo = addinfo ? addinfo : "";
743 * surrogate diagnostic.
745 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
746 int error, char *addinfo)
748 static Z_NamePlusRecord rec;
752 static Z_DiagRec drec;
753 static Z_DefaultDiagFormat dr;
759 bib1.class = CLASS_DIAGSET;
760 bib1.value = VAL_BIB1;
762 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
764 rec.databaseName = dbname;
765 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
767 rec.u.surrogateDiagnostic = &drec;
768 drec.which = Z_DiagRec_defaultFormat;
769 drec.u.defaultFormat = &dr;
771 rec.u.surrogateDiagnostic = &dr;
773 dr.diagnosticSetId = oid_getoidbyent(&bib1);
775 dr.which = Z_DiagForm_v2AddInfo;
776 dr.addinfo = addinfo ? addinfo : "";
781 * multiple nonsurrogate diagnostics.
783 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
785 static Z_DiagRecs recs;
789 static Z_DiagRec *recp[1], drec;
790 static Z_DefaultDiagFormat rec;
792 static Z_DiagRec *recp[1], rec;
795 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
797 bib1.class = CLASS_DIAGSET;
798 bib1.value = VAL_BIB1;
801 recs.num_diagRecs = 1;
802 recs.diagRecs = recp;
805 drec.which = Z_DiagRec_defaultFormat;
806 drec.u.defaultFormat = &rec;
810 rec.diagnosticSetId = oid_getoidbyent(&bib1);
811 rec.condition = &err;
812 rec.which = Z_DiagForm_v2AddInfo;
813 rec.addinfo = addinfo ? addinfo : "";
817 #define MAX_RECORDS 256
819 static Z_Records *pack_records(association *a, char *setname, int start,
820 int *num, Z_RecordComposition *comp,
821 int *next, int *pres, oid_value format)
823 int recno, total_length = 0, toget = *num;
824 static Z_Records records;
825 static Z_NamePlusRecordList reclist;
826 static Z_NamePlusRecord *list[MAX_RECORDS];
829 records.which = Z_Records_DBOSD;
830 records.u.databaseOrSurDiagnostics = &reclist;
831 reclist.num_records = 0;
832 reclist.records = list;
833 *pres = Z_PRES_SUCCESS;
837 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
838 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
839 a->maximumRecordSize);
840 for (recno = start; reclist.num_records < toget; recno++)
842 bend_fetchrequest freq;
843 bend_fetchresult *fres;
844 Z_NamePlusRecord *thisrec;
845 Z_DatabaseRecord *thisext;
849 * we get the number of bytes allocated on the stream before any
850 * allocation done by the backend - this should give us a reasonable
851 * idea of the total size of the data so far.
853 total_length = odr_total(a->encode);
854 if (reclist.num_records == MAX_RECORDS - 1)
856 *pres = Z_PRES_PARTIAL_2;
859 freq.setname = setname;
862 freq.format = format;
863 freq.stream = a->encode;
864 if (!(fres = bend_fetch(a->backend, &freq, 0)))
866 *pres = Z_PRES_FAILURE;
867 return diagrec(a->proto, 2, "Backend interface problem");
869 /* backend should be able to signal whether error is system-wide
870 or only pertaining to current record */
873 *pres = Z_PRES_FAILURE;
874 return diagrec(a->proto, fres->errcode, fres->errstring);
877 this_length = fres->len;
879 this_length = odr_total(a->encode) - total_length;
880 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
881 this_length, total_length);
882 if (this_length + total_length > a->preferredMessageSize)
884 /* record is small enough, really */
885 if (this_length <= a->preferredMessageSize)
887 logf(LOG_DEBUG, " Dropped last normal-sized record");
888 *pres = Z_PRES_PARTIAL_2;
891 /* record can only be fetched by itself */
892 if (this_length < a->maximumRecordSize)
894 logf(LOG_DEBUG, " Record > prefmsgsz");
897 logf(LOG_DEBUG, " Dropped it");
898 reclist.records[reclist.num_records] =
899 surrogatediagrec(a->proto, fres->basename, 16, 0);
900 reclist.num_records++;
904 else /* too big entirely */
906 logf(LOG_DEBUG, "Record > maxrcdsz");
907 reclist.records[reclist.num_records] =
908 surrogatediagrec(a->proto, fres->basename, 17, 0);
909 reclist.num_records++;
913 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
915 if (!(thisrec->databaseName = odr_malloc(a->encode,
916 strlen(fres->basename) + 1)))
918 strcpy(thisrec->databaseName, fres->basename);
919 thisrec->which = Z_NamePlusRecord_databaseRecord;
920 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
921 sizeof(Z_DatabaseRecord))))
923 recform.proto = a->proto;
924 recform.class = CLASS_RECSYN;
925 recform.value = fres->format;
926 thisext->direct_reference = odr_oiddup(a->encode,
927 oid_getoidbyent(&recform));
928 thisext->indirect_reference = 0;
929 thisext->descriptor = 0;
930 if (fres->len < 0) /* Structured data */
932 switch (fres->format)
934 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
935 case VAL_GRS1: thisext->which = Z_External_grs1; break;
936 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
940 logf(LOG_FATAL, "Unknown structured format from backend.");
945 * We cheat on the pointers here. Obviously, the record field
946 * of the backend-fetch structure should have been a union for
947 * correctness, but we're stuck with this for backwards
950 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
952 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
954 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
956 thisext->which = Z_External_sutrs;
957 thisext->u.sutrs = sutrs;
958 sutrs->buf = odr_malloc(a->encode, fres->len);
959 sutrs->len = sutrs->size = fres->len;
960 memcpy(sutrs->buf, fres->record, fres->len);
962 else /* octet-aligned record. */
964 thisext->which = Z_External_octet;
965 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
968 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
971 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
972 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
975 reclist.records[reclist.num_records] = thisrec;
976 reclist.num_records++;
977 *next = fres->last_in_set ? 0 : recno + 1;
979 *num = reclist.num_records;
983 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
986 Z_SearchRequest *req = reqb->request->u.searchRequest;
987 bend_searchrequest bsrq;
988 bend_searchresult *bsrt;
990 logf(LOG_LOG, "Got SearchRequest.");
992 bsrq.setname = req->resultSetName;
993 bsrq.replace_set = *req->replaceIndicator;
994 bsrq.num_bases = req->num_databaseNames;
995 bsrq.basenames = req->databaseNames;
996 bsrq.query = req->query;
998 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1000 return response_searchRequest(assoc, reqb, bsrt, fd);
1003 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1006 * Prepare a searchresponse based on the backend results. We probably want
1007 * to look at making the fetching of records nonblocking as well, but
1008 * so far, we'll keep things simple.
1009 * If bsrt is null, that means we're called in response to a communications
1010 * event, and we'll have to get the response for ourselves.
1012 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1013 bend_searchresult *bsrt, int *fd)
1015 Z_SearchRequest *req = reqb->request->u.searchRequest;
1017 static Z_SearchResponse resp;
1018 static int nulint = 0;
1019 static bool_t sr = 1;
1020 static int next = 0;
1021 static int none = Z_RES_NONE;
1023 apdu.which = Z_APDU_searchResponse;
1024 apdu.u.searchResponse = &resp;
1025 resp.referenceId = req->referenceId;
1027 resp.additionalSearchInfo = 0;
1031 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1033 logf(LOG_FATAL, "Bad result from backend");
1036 else if (bsrt->errcode)
1038 resp.records = diagrec(assoc->proto, bsrt->errcode,
1040 resp.resultCount = &nulint;
1041 resp.numberOfRecordsReturned = &nulint;
1042 resp.nextResultSetPosition = &nulint;
1043 resp.searchStatus = &nulint;
1044 resp.resultSetStatus = &none;
1045 resp.presentStatus = 0;
1050 Z_RecordComposition comp, *compp = 0;
1051 static int presst = 0;
1054 resp.resultCount = &bsrt->hits;
1056 comp.which = Z_RecordComp_simple;
1057 /* how many records does the user agent want, then? */
1058 if (bsrt->hits <= *req->smallSetUpperBound)
1061 if ((comp.u.simple = req->smallSetElementSetNames))
1064 else if (bsrt->hits < *req->largeSetLowerBound)
1066 toget = *req->mediumSetPresentNumber;
1067 if (toget > bsrt->hits)
1069 if ((comp.u.simple = req->mediumSetElementSetNames))
1075 if (toget && !resp.records)
1080 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1081 prefformat->class != CLASS_RECSYN)
1084 form = prefformat->value;
1085 resp.records = pack_records(assoc, req->resultSetName, 1,
1086 &toget, compp, &next, &presst, form);
1089 resp.numberOfRecordsReturned = &toget;
1090 resp.nextResultSetPosition = &next;
1091 resp.searchStatus = &sr;
1092 resp.resultSetStatus = 0;
1093 resp.presentStatus = &presst;
1097 if (*resp.resultCount)
1099 resp.numberOfRecordsReturned = &nulint;
1100 resp.nextResultSetPosition = &next;
1101 resp.searchStatus = &sr;
1102 resp.resultSetStatus = 0;
1103 resp.presentStatus = 0;
1110 * Maybe we got a little over-friendly when we designed bend_fetch to
1111 * get only one record at a time. Some backends can optimise multiple-record
1112 * fetches, and at any rate, there is some overhead involved in
1113 * all that selecting and hopping around. Problem is, of course, that the
1114 * frontend can't know ahead of time how many records it'll need to
1115 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1116 * is downright lousy as a bulk data transfer protocol.
1118 * To start with, we'll do the fetching of records from the backend
1119 * in one operation: To save some trips in and out of the event-handler,
1120 * and to simplify the interface to pack_records. At any rate, asynch
1121 * operation is more fun in operations that have an unpredictable execution
1122 * speed - which is normally more true for search than for present.
1124 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1127 Z_PresentRequest *req = reqb->request->u.presentRequest;
1129 static Z_PresentResponse resp;
1130 static int presst, next, num;
1135 logf(LOG_LOG, "Got PresentRequest.");
1136 apdu.which = Z_APDU_presentResponse;
1137 apdu.u.presentResponse = &resp;
1138 resp.referenceId = req->referenceId;
1143 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1144 prefformat->class != CLASS_RECSYN)
1147 form = prefformat->value;
1148 num = *req->numberOfRecordsRequested;
1149 resp.records = pack_records(assoc, req->resultSetId,
1150 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1154 resp.numberOfRecordsReturned = #
1155 resp.presentStatus = &presst;
1156 resp.nextResultSetPosition = &next;
1162 * Scan was implemented rather in a hurry, and with support for only the basic
1163 * elements of the service in the backend API. Suggestions are welcome.
1165 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1167 Z_ScanRequest *req = reqb->request->u.scanRequest;
1169 static Z_ScanResponse res;
1170 static int scanStatus = Z_Scan_failure;
1171 static int numberOfEntriesReturned = 0;
1173 static Z_ListEntries ents;
1174 #define SCAN_MAX_ENTRIES 200
1175 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1176 bend_scanrequest srq;
1177 bend_scanresult *srs;
1179 logf(LOG_LOG, "Got scanrequest");
1180 apdu.which = Z_APDU_scanResponse;
1181 apdu.u.scanResponse = &res;
1182 res.referenceId = req->referenceId;
1184 res.scanStatus = &scanStatus;
1185 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1186 res.positionOfTerm = 0;
1187 res.entries = &ents;
1188 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1189 res.attributeSet = 0;
1194 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1195 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1196 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1197 else if (req->stepSize && *req->stepSize > 0)
1198 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1201 if (req->termListAndStartPoint->term->which == Z_Term_general)
1202 logf(LOG_DEBUG, " term: '%.*s'",
1203 req->termListAndStartPoint->term->u.general->len,
1204 req->termListAndStartPoint->term->u.general->buf);
1205 srq.num_bases = req->num_databaseNames;
1206 srq.basenames = req->databaseNames;
1207 srq.num_entries = *req->numberOfTermsRequested;
1208 srq.term = req->termListAndStartPoint;
1209 srq.term_position = req->preferredPositionInResponse ?
1210 *req->preferredPositionInResponse : 1;
1211 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1212 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1213 else if (srs->errcode)
1214 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1215 srs->errcode, srs->errstring);
1219 static Z_Entries list;
1221 if (srs->status == BEND_SCAN_PARTIAL)
1222 scanStatus = Z_Scan_partial_5;
1224 scanStatus = Z_Scan_success;
1225 ents.which = Z_ListEntries_entries;
1226 ents.u.entries = &list;
1228 for (i = 0; i < srs->num_entries; i++)
1234 if (i >= SCAN_MAX_ENTRIES)
1236 scanStatus = Z_Scan_partial_4;
1239 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1240 e->which = Z_Entry_termInfo;
1241 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1242 t->suggestedAttributes = 0;
1243 t->alternativeTerm = 0;
1244 t->byAttributes = 0;
1245 t->globalOccurrences = &srs->entries[i].occurrences;
1246 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1247 t->term->which = Z_Term_general;
1248 t->term->u.general = o = odr_malloc(assoc->encode,
1250 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1251 strlen(srs->entries[i].term));
1252 memcpy(o->buf, srs->entries[i].term, o->len);
1253 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1254 srs->entries[i].term, srs->entries[i].occurrences);
1256 list.num_entries = i;
1257 res.numberOfEntriesReturned = &list.num_entries;
1258 res.positionOfTerm = &srs->term_position;
1265 static void process_close(association *assoc, request *reqb)
1267 Z_Close *req = reqb->request->u.close;
1268 static char *reasons[] =
1275 "securityViolation",
1282 logf(LOG_LOG, "Got close, reason %s, message %s",
1283 reasons[*req->closeReason], req->diagnosticInformation ?
1284 req->diagnosticInformation : "NULL");
1285 if (assoc->version < 3) /* to make do_force respond with close */
1287 do_close(assoc, Z_Close_finished, "Association terminated by client");