2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.56 1995-12-14 11:09:57 quinn
10 * Revision 1.55 1995/11/08 17:41:37 quinn
13 * Revision 1.54 1995/11/08 15:11:29 quinn
14 * Log of close transmit.
16 * Revision 1.53 1995/11/01 13:54:58 quinn
19 * Revision 1.52 1995/11/01 12:19:13 quinn
20 * Second attempt to fix same bug.
22 * Revision 1.50 1995/10/25 16:58:32 quinn
25 * Revision 1.49 1995/10/16 13:51:53 quinn
26 * Changes to provide Especs to the backend.
28 * Revision 1.48 1995/10/06 08:51:20 quinn
31 * Revision 1.47 1995/08/29 14:24:16 quinn
32 * Added second half of close-handshake
34 * Revision 1.46 1995/08/29 11:17:58 quinn
35 * Added code to receive close
37 * Revision 1.45 1995/08/21 09:11:00 quinn
38 * Smallish fixes to suppport new formats.
40 * Revision 1.44 1995/08/17 12:45:25 quinn
41 * Fixed minor problems with GRS-1. Added support in c&s.
43 * Revision 1.43 1995/08/15 12:00:31 quinn
46 * Revision 1.42 1995/08/15 11:16:50 quinn
48 * Revision 1.41 1995/08/02 10:23:06 quinn
51 * Revision 1.40 1995/07/31 14:34:26 quinn
52 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
54 * Revision 1.39 1995/06/27 13:21:00 quinn
57 * Revision 1.38 1995/06/19 12:39:11 quinn
58 * Fixed bug in timeout code. Added BER dumper.
60 * Revision 1.37 1995/06/16 13:16:14 quinn
61 * Fixed Defaultdiagformat.
63 * Revision 1.36 1995/06/16 10:31:36 quinn
64 * Added session timeout.
66 * Revision 1.35 1995/06/15 07:45:14 quinn
69 * Revision 1.34 1995/06/14 15:26:46 quinn
70 * *** empty log message ***
72 * Revision 1.33 1995/06/06 14:57:05 quinn
75 * Revision 1.32 1995/06/06 08:41:44 quinn
78 * Revision 1.31 1995/06/06 08:15:37 quinn
81 * Revision 1.30 1995/06/05 10:53:32 quinn
82 * Added a better SCAN.
84 * Revision 1.29 1995/06/01 11:25:03 quinn
87 * Revision 1.28 1995/06/01 11:21:01 quinn
88 * Attempting to fix a bug in pack-records. replaced break with continue
89 * for large records, according to standard.
91 * Revision 1.27 1995/05/29 08:12:06 quinn
94 * Revision 1.26 1995/05/18 13:02:12 quinn
97 * Revision 1.25 1995/05/17 08:42:26 quinn
98 * Transfer auth info to backend. Allow backend to reject init gracefully.
100 * Revision 1.24 1995/05/16 08:51:04 quinn
101 * License, documentation, and memory fixes
103 * Revision 1.23 1995/05/15 13:25:10 quinn
106 * Revision 1.22 1995/05/15 11:56:39 quinn
107 * Asynchronous facilities. Restructuring of seshigh code.
109 * Revision 1.21 1995/05/02 08:53:19 quinn
110 * Trying in vain to fix comm with ISODE
112 * Revision 1.20 1995/04/20 15:13:00 quinn
115 * Revision 1.19 1995/04/18 08:15:34 quinn
116 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
117 * neater. We'll make the same change for decoding one day.
119 * Revision 1.18 1995/04/17 11:28:25 quinn
122 * Revision 1.17 1995/04/10 10:23:36 quinn
123 * Some work to add scan and other things.
125 * Revision 1.16 1995/03/31 09:18:55 quinn
128 * Revision 1.15 1995/03/30 14:03:23 quinn
129 * Added RFC1006 as separate library
131 * Revision 1.14 1995/03/30 12:18:17 quinn
134 * Revision 1.13 1995/03/30 09:09:24 quinn
135 * Added state-handle and some support for asynchronous activities.
137 * Revision 1.12 1995/03/29 15:40:16 quinn
138 * Ongoing work. Statserv is now dynamic by default
140 * Revision 1.11 1995/03/28 09:16:21 quinn
141 * Added record packing to the search request
143 * Revision 1.10 1995/03/27 08:34:24 quinn
144 * Added dynamic server functionality.
145 * Released bindings to session.c (is now redundant)
147 * Revision 1.9 1995/03/22 15:01:26 quinn
148 * Adjusting record packing.
150 * Revision 1.8 1995/03/22 10:13:21 quinn
151 * Working on record packer
153 * Revision 1.7 1995/03/21 15:53:31 quinn
156 * Revision 1.6 1995/03/21 12:30:09 quinn
157 * Beginning to add support for record packing.
159 * Revision 1.5 1995/03/17 10:44:13 quinn
160 * Added catch of null-string in makediagrec
162 * Revision 1.4 1995/03/17 10:18:08 quinn
163 * Added memory management.
165 * Revision 1.3 1995/03/16 17:42:39 quinn
168 * Revision 1.2 1995/03/16 13:29:01 quinn
169 * Partitioned server.
171 * Revision 1.1 1995/03/15 16:02:10 quinn
172 * Modded session.c to seshigh.c
177 * Frontend server logic.
179 * This code receives incoming APDUs, and handles client requests by means
180 * of the backend API.
182 * Some of the code is getting quite involved, compared to simpler servers -
183 * primarily because it is asynchronous both in the communication with
184 * the user and the backend. We think the complexity will pay off in
185 * the form of greater flexibility when more asynchronous facilities
188 * Memory management has become somewhat involved. In the simple case, where
189 * only one PDU is pending at a time, it will simply reuse the same memory,
190 * once it has found its working size. When we enable multiple concurrent
191 * operations, perhaps even with multiple parallel calls to the backend, it
192 * will maintain a pool of buffers for encoding and decoding, trying to
193 * minimize memory allocation/deallocation during normal operation.
195 * TODOs include (and will be done in order of public interest):
197 * Support for EXPLAIN - provide simple meta-database system.
198 * Support for access control.
199 * Support for resource control.
200 * Support for extended services - primarily Item Order.
201 * Rest of Z39.50-1994
209 #include <sys/time.h>
212 #include <comstack.h>
218 #include <statserv.h>
222 static int process_request(association *assoc);
223 void backend_response(IOCHAN i, int event);
224 static int process_response(association *assoc, request *req, Z_APDU *res);
225 static Z_APDU *process_initRequest(association *assoc, request *reqb);
226 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
228 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
229 bend_searchresult *bsrt, int *fd);
230 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
232 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
233 static void process_close(association *assoc, request *reqb);
235 static FILE *apduf = 0; /* for use in static mode */
236 static statserv_options_block *control_block = 0;
239 * Create and initialize a new association-handle.
240 * channel : iochannel for the current line.
241 * link : communications channel.
242 * Returns: 0 or a new association handle.
244 association *create_association(IOCHAN channel, COMSTACK link)
249 control_block = statserv_getcontrol();
250 if (!(new = xmalloc(sizeof(*new))))
252 new->client_chan = channel;
253 new->client_link = link;
254 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
255 !(new->encode = odr_createmem(ODR_ENCODE)))
257 if (*control_block->apdufile)
262 strcpy(filename, control_block->apdufile);
263 if (!(new->print = odr_createmem(ODR_PRINT)))
265 if (*control_block->apdufile != '-')
267 strcpy(filename, control_block->apdufile);
268 if (!control_block->dynamic)
272 if (!(apduf = fopen(filename, "w")))
274 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
277 setvbuf(apduf, 0, _IONBF, 0);
283 sprintf(filename + strlen(filename), ".%d", getpid());
284 if (!(f = fopen(filename, "w")))
286 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
289 setvbuf(f, 0, _IONBF, 0);
291 odr_setprint(new->print, f);
296 new->input_buffer = 0;
297 new->input_buffer_len = 0;
299 new->state = ASSOC_NEW;
300 request_initq(&new->incoming);
301 request_initq(&new->outgoing);
302 new->proto = cs_getproto(link);
307 * Free association and release resources.
309 void destroy_association(association *h)
311 odr_destroy(h->decode);
312 odr_destroy(h->encode);
314 odr_destroy(h->print);
316 xfree(h->input_buffer);
318 bend_close(h->backend);
319 while (request_deq(&h->incoming));
320 while (request_deq(&h->outgoing));
324 static void do_close(association *a, int reason, char *message)
327 Z_Close *cls = zget_Close(a->encode);
328 request *req = request_get();
330 /* Purge request queue */
331 while (request_deq(&a->incoming));
332 while (request_deq(&a->outgoing));
335 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
336 reason, message ? message : "none");
337 apdu.which = Z_APDU_close;
339 *cls->closeReason = reason;
340 cls->diagnosticInformation = message;
341 process_response(a, req, &apdu);
342 iochan_settimeout(a->client_chan, 60);
346 logf(LOG_DEBUG, "v2 client. No Close PDU");
347 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
349 a->state = ASSOC_DEAD;
353 * This is where PDUs from the client are read and the further
354 * processing is initiated. Flow of control moves down through the
355 * various process_* functions below, until the encoded result comes back up
356 * to the output handler in here.
358 * h : the I/O channel that has an outstanding event.
359 * event : the current outstanding event.
361 void ir_session(IOCHAN h, int event)
364 association *assoc = iochan_getdata(h);
365 COMSTACK conn = assoc->client_link;
368 assert(h && conn && assoc);
369 if (event == EVENT_TIMEOUT)
371 if (assoc->state != ASSOC_UP)
373 logf(LOG_LOG, "Final timeout - closing connection.");
375 destroy_association(assoc);
380 logf(LOG_LOG, "Session idle too long. Sending close.");
381 do_close(assoc, Z_Close_lackOfActivity, 0);
385 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
387 if (event & EVENT_INPUT)
389 logf(LOG_DEBUG, "ir_session (input)");
390 assert(assoc && conn);
391 /* We aren't speaking to this fellow */
392 if (assoc->state == ASSOC_DEAD)
394 logf(LOG_LOG, "Closed connection after reject");
396 destroy_association(assoc);
400 if ((res = cs_get(conn, &assoc->input_buffer,
401 &assoc->input_buffer_len)) <= 0)
403 logf(LOG_LOG, "Connection closed by client");
405 destroy_association(assoc);
409 else if (res == 1) /* incomplete read - wait for more */
411 if (cs_more(conn)) /* more stuff - call us again later, please */
412 iochan_setevent(h, EVENT_INPUT);
414 /* we got a complete PDU. Let's decode it */
415 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
416 req = request_get(); /* get a new request structure */
417 odr_reset(assoc->decode);
418 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
419 if (!z_APDU(assoc->decode, &req->request, 0))
421 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
422 odr_errlist[odr_geterror(assoc->decode)],
423 odr_offset(assoc->decode));
424 logf(LOG_LOG, "PDU dump:");
425 odr_dumpBER(log_file(), assoc->input_buffer, res);
426 do_close(assoc, Z_Close_protocolError, "Malformed package");
429 req->request_mem = odr_extract_mem(assoc->decode);
430 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
432 logf(LOG_WARN, "ODR print error: %s",
433 odr_errlist[odr_geterror(assoc->print)]);
434 odr_reset(assoc->print);
436 request_enq(&assoc->incoming, req);
439 /* can we do something yet? */
440 req = request_head(&assoc->incoming);
441 if (req->state == REQUEST_IDLE)
442 if (process_request(assoc) < 0)
443 do_close(assoc, Z_Close_systemProblem, "Unknown error");
445 if (event & EVENT_OUTPUT)
447 request *req = request_head(&assoc->outgoing);
449 logf(LOG_DEBUG, "ir_session (output)");
450 req->state = REQUEST_PENDING;
451 switch (res = cs_put(conn, req->response, req->len_response))
454 logf(LOG_LOG, "Connection closed by client");
456 destroy_association(assoc);
459 case 0: /* all sent - release the request structure */
460 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
461 nmem_destroy(req->request_mem);
462 request_deq(&assoc->outgoing);
463 request_release(req);
464 if (!request_head(&assoc->outgoing))
465 iochan_clearflag(h, EVENT_OUTPUT);
467 /* value of 1 -- partial send -- is simply ignored */
470 if (event & EVENT_EXCEPT)
472 logf(LOG_DEBUG, "ir_session (exception)");
474 destroy_association(assoc);
480 * Initiate request processing.
482 static int process_request(association *assoc)
484 request *req = request_head(&assoc->incoming);
488 logf(LOG_DEBUG, "process_request");
489 assert(req && req->state == REQUEST_IDLE);
490 switch (req->request->which)
492 case Z_APDU_initRequest:
493 res = process_initRequest(assoc, req); break;
494 case Z_APDU_searchRequest:
495 res = process_searchRequest(assoc, req, &fd); break;
496 case Z_APDU_presentRequest:
497 res = process_presentRequest(assoc, req, &fd); break;
498 case Z_APDU_scanRequest:
499 res = process_scanRequest(assoc, req, &fd); break;
501 process_close(assoc, req); return 0;
503 logf(LOG_WARN, "Bad APDU received");
508 logf(LOG_DEBUG, " result immediately available");
509 return process_response(assoc, req, res);
513 logf(LOG_WARN, " bad result");
516 else /* no result yet - one will be provided later */
520 /* Set up an I/O handler for the fd supplied by the backend */
522 logf(LOG_DEBUG, " establishing handler for result");
523 req->state = REQUEST_PENDING;
524 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
526 iochan_setdata(chan, assoc);
532 * Handle message from the backend.
534 void backend_response(IOCHAN i, int event)
536 association *assoc = iochan_getdata(i);
537 request *req = request_head(&assoc->incoming);
541 logf(LOG_DEBUG, "backend_response");
542 assert(assoc && req && req->state != REQUEST_IDLE);
543 /* determine what it is we're waiting for */
544 switch (req->request->which)
546 case Z_APDU_searchRequest:
547 res = response_searchRequest(assoc, req, 0, &fd); break;
549 case Z_APDU_presentRequest:
550 res = response_presentRequest(assoc, req, 0, &fd); break;
551 case Z_APDU_scanRequest:
552 res = response_scanRequest(assoc, req, 0, &fd); break;
555 logf(LOG_WARN, "Serious programmer's lapse or bug");
558 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
560 logf(LOG_LOG, "Fatal error when talking to backend");
561 do_close(assoc, Z_Close_systemProblem, 0);
565 else if (!res) /* no result yet - try again later */
567 logf(LOG_DEBUG, " no result yet");
568 iochan_setfd(i, fd); /* in case fd has changed */
573 * Encode response, and transfer the request structure to the outgoing queue.
575 static int process_response(association *assoc, request *req, Z_APDU *res)
577 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
578 if (!z_APDU(assoc->encode, &res, 0))
580 logf(LOG_WARN, "ODR error when encoding response: %s",
581 odr_errlist[odr_geterror(assoc->decode)]);
582 odr_reset(assoc->encode);
585 req->response = odr_getbuf(assoc->encode, &req->len_response,
586 &req->size_response);
587 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
588 odr_reset(assoc->encode);
589 if (assoc->print && !z_APDU(assoc->print, &res, 0))
591 logf(LOG_WARN, "ODR print error: %s",
592 odr_errlist[odr_geterror(assoc->print)]);
593 odr_reset(assoc->print);
595 /* change this when we make the backend reentrant */
596 if (req == request_head(&assoc->incoming))
598 req->state = REQUEST_IDLE;
599 request_deq(&assoc->incoming);
601 request_enq(&assoc->outgoing, req);
602 /* turn the work over to the ir_session handler */
603 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
604 /* Is there more work to be done? give that to the input handler too */
605 if (request_head(&assoc->incoming))
606 iochan_setevent(assoc->client_chan, EVENT_WORK);
611 * Handle init request.
612 * At the moment, we don't check the options
613 * anywhere else in the code - we just try not to do anything that would
614 * break a naive client. We'll toss 'em into the association block when
615 * we need them there.
617 static Z_APDU *process_initRequest(association *assoc, request *reqb)
619 Z_InitRequest *req = reqb->request->u.initRequest;
620 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
621 Z_InitResponse *resp = apdu->u.initResponse;
622 bend_initrequest binitreq;
623 bend_initresult *binitres;
626 logf(LOG_LOG, "Got initRequest");
627 if (req->implementationId)
628 logf(LOG_LOG, "Id: %s", req->implementationId);
629 if (req->implementationName)
630 logf(LOG_LOG, "Name: %s", req->implementationName);
631 if (req->implementationVersion)
632 logf(LOG_LOG, "Version: %s", req->implementationVersion);
634 binitreq.configname = "default-config";
635 binitreq.auth = req->idAuthentication;
636 if (!(binitres = bend_init(&binitreq)))
638 logf(LOG_WARN, "Bad response from backend.");
642 assoc->backend = binitres->handle;
643 resp->referenceId = req->referenceId;
645 /* let's tell the client what we can do */
646 if (ODR_MASK_GET(req->options, Z_Options_search))
648 ODR_MASK_SET(resp->options, Z_Options_search);
649 strcat(options, "srch");
651 if (ODR_MASK_GET(req->options, Z_Options_present))
653 ODR_MASK_SET(resp->options, Z_Options_present);
654 strcat(options, " prst");
657 if (ODR_MASK_GET(req->options, Z_Options_delSet))
659 ODR_MASK_SET(&options, Z_Options_delSet);
660 strcat(options, " del");
663 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
665 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
666 strcat(options, " namedresults");
668 if (ODR_MASK_GET(req->options, Z_Options_scan))
670 ODR_MASK_SET(resp->options, Z_Options_scan);
671 strcat(options, " scan");
673 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
675 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
676 strcat(options, " concurop");
679 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
681 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
682 assoc->version = 2; /* 1 & 2 are equivalent */
684 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
686 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
689 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
691 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
694 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
695 assoc->maximumRecordSize = *req->maximumRecordSize;
696 if (assoc->maximumRecordSize > control_block->maxrecordsize)
697 assoc->maximumRecordSize = control_block->maxrecordsize;
698 assoc->preferredMessageSize = *req->preferredMessageSize;
699 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
700 assoc->preferredMessageSize = assoc->maximumRecordSize;
701 resp->preferredMessageSize = &assoc->preferredMessageSize;
702 resp->maximumRecordSize = &assoc->maximumRecordSize;
703 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
704 if (binitres->errcode)
706 logf(LOG_LOG, "Connection rejected by backend.");
708 assoc->state = ASSOC_DEAD;
711 assoc->state = ASSOC_UP;
716 * These functions should be merged.
720 * nonsurrogate diagnostic record.
722 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
724 static Z_Records rec;
728 static Z_DiagRec drec;
729 static Z_DefaultDiagFormat dr;
735 bib1.class = CLASS_DIAGSET;
736 bib1.value = VAL_BIB1;
738 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
741 rec.which = Z_Records_NSD;
743 rec.u.nonSurrogateDiagnostic = &drec;
744 drec.which = Z_DiagRec_defaultFormat;
745 drec.u.defaultFormat = &dr;
747 rec.u.nonSurrogateDiagnostic = &dr;
749 dr.diagnosticSetId = oid_getoidbyent(&bib1);
751 dr.which = Z_DiagForm_v2AddInfo;
752 dr.addinfo = addinfo ? addinfo : "";
757 * surrogate diagnostic.
759 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
760 int error, char *addinfo)
762 static Z_NamePlusRecord rec;
766 static Z_DiagRec drec;
767 static Z_DefaultDiagFormat dr;
773 bib1.class = CLASS_DIAGSET;
774 bib1.value = VAL_BIB1;
776 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
778 rec.databaseName = dbname;
779 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
781 rec.u.surrogateDiagnostic = &drec;
782 drec.which = Z_DiagRec_defaultFormat;
783 drec.u.defaultFormat = &dr;
785 rec.u.surrogateDiagnostic = &dr;
787 dr.diagnosticSetId = oid_getoidbyent(&bib1);
789 dr.which = Z_DiagForm_v2AddInfo;
790 dr.addinfo = addinfo ? addinfo : "";
795 * multiple nonsurrogate diagnostics.
797 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
799 static Z_DiagRecs recs;
803 static Z_DiagRec *recp[1], drec;
804 static Z_DefaultDiagFormat rec;
806 static Z_DiagRec *recp[1], rec;
809 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
811 bib1.class = CLASS_DIAGSET;
812 bib1.value = VAL_BIB1;
815 recs.num_diagRecs = 1;
816 recs.diagRecs = recp;
819 drec.which = Z_DiagRec_defaultFormat;
820 drec.u.defaultFormat = &rec;
824 rec.diagnosticSetId = oid_getoidbyent(&bib1);
825 rec.condition = &err;
826 rec.which = Z_DiagForm_v2AddInfo;
827 rec.addinfo = addinfo ? addinfo : "";
831 #define MAX_RECORDS 256
833 static Z_Records *pack_records(association *a, char *setname, int start,
834 int *num, Z_RecordComposition *comp,
835 int *next, int *pres, oid_value format)
837 int recno, total_length = 0, toget = *num;
838 static Z_Records records;
839 static Z_NamePlusRecordList reclist;
840 static Z_NamePlusRecord *list[MAX_RECORDS];
843 records.which = Z_Records_DBOSD;
844 records.u.databaseOrSurDiagnostics = &reclist;
845 reclist.num_records = 0;
846 reclist.records = list;
847 *pres = Z_PRES_SUCCESS;
851 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
852 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
853 a->maximumRecordSize);
854 for (recno = start; reclist.num_records < toget; recno++)
856 bend_fetchrequest freq;
857 bend_fetchresult *fres;
858 Z_NamePlusRecord *thisrec;
859 Z_DatabaseRecord *thisext;
863 * we get the number of bytes allocated on the stream before any
864 * allocation done by the backend - this should give us a reasonable
865 * idea of the total size of the data so far.
867 total_length = odr_total(a->encode);
868 if (reclist.num_records == MAX_RECORDS - 1)
870 *pres = Z_PRES_PARTIAL_2;
873 freq.setname = setname;
876 freq.format = format;
877 freq.stream = a->encode;
878 if (!(fres = bend_fetch(a->backend, &freq, 0)))
880 *pres = Z_PRES_FAILURE;
881 return diagrec(a->proto, 2, "Backend interface problem");
883 /* backend should be able to signal whether error is system-wide
884 or only pertaining to current record */
887 *pres = Z_PRES_FAILURE;
888 return diagrec(a->proto, fres->errcode, fres->errstring);
891 this_length = fres->len;
893 this_length = odr_total(a->encode) - total_length;
894 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
895 this_length, total_length);
896 if (this_length + total_length > a->preferredMessageSize)
898 /* record is small enough, really */
899 if (this_length <= a->preferredMessageSize)
901 logf(LOG_DEBUG, " Dropped last normal-sized record");
902 *pres = Z_PRES_PARTIAL_2;
905 /* record can only be fetched by itself */
906 if (this_length < a->maximumRecordSize)
908 logf(LOG_DEBUG, " Record > prefmsgsz");
911 logf(LOG_DEBUG, " Dropped it");
912 reclist.records[reclist.num_records] =
913 surrogatediagrec(a->proto, fres->basename, 16, 0);
914 reclist.num_records++;
918 else /* too big entirely */
920 logf(LOG_DEBUG, "Record > maxrcdsz");
921 reclist.records[reclist.num_records] =
922 surrogatediagrec(a->proto, fres->basename, 17, 0);
923 reclist.num_records++;
927 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
929 if (!(thisrec->databaseName = odr_malloc(a->encode,
930 strlen(fres->basename) + 1)))
932 strcpy(thisrec->databaseName, fres->basename);
933 thisrec->which = Z_NamePlusRecord_databaseRecord;
934 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
935 sizeof(Z_DatabaseRecord))))
937 recform.proto = a->proto;
938 recform.class = CLASS_RECSYN;
939 recform.value = fres->format;
940 thisext->direct_reference = odr_oiddup(a->encode,
941 oid_getoidbyent(&recform));
942 thisext->indirect_reference = 0;
943 thisext->descriptor = 0;
944 if (fres->len < 0) /* Structured data */
946 switch (fres->format)
948 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
949 case VAL_GRS1: thisext->which = Z_External_grs1; break;
950 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
954 logf(LOG_FATAL, "Unknown structured format from backend.");
959 * We cheat on the pointers here. Obviously, the record field
960 * of the backend-fetch structure should have been a union for
961 * correctness, but we're stuck with this for backwards
964 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
966 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
968 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
970 thisext->which = Z_External_sutrs;
971 thisext->u.sutrs = sutrs;
972 sutrs->buf = odr_malloc(a->encode, fres->len);
973 sutrs->len = sutrs->size = fres->len;
974 memcpy(sutrs->buf, fres->record, fres->len);
976 else /* octet-aligned record. */
978 thisext->which = Z_External_octet;
979 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
982 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
985 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
986 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
989 reclist.records[reclist.num_records] = thisrec;
990 reclist.num_records++;
991 *next = fres->last_in_set ? 0 : recno + 1;
993 *num = reclist.num_records;
997 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1000 Z_SearchRequest *req = reqb->request->u.searchRequest;
1001 bend_searchrequest bsrq;
1002 bend_searchresult *bsrt;
1004 logf(LOG_LOG, "Got SearchRequest.");
1006 bsrq.setname = req->resultSetName;
1007 bsrq.replace_set = *req->replaceIndicator;
1008 bsrq.num_bases = req->num_databaseNames;
1009 bsrq.basenames = req->databaseNames;
1010 bsrq.query = req->query;
1012 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1014 return response_searchRequest(assoc, reqb, bsrt, fd);
1017 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1020 * Prepare a searchresponse based on the backend results. We probably want
1021 * to look at making the fetching of records nonblocking as well, but
1022 * so far, we'll keep things simple.
1023 * If bsrt is null, that means we're called in response to a communications
1024 * event, and we'll have to get the response for ourselves.
1026 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1027 bend_searchresult *bsrt, int *fd)
1029 Z_SearchRequest *req = reqb->request->u.searchRequest;
1031 static Z_SearchResponse resp;
1032 static int nulint = 0;
1033 static bool_t sr = 1;
1034 static int next = 0;
1035 static int none = Z_RES_NONE;
1037 apdu.which = Z_APDU_searchResponse;
1038 apdu.u.searchResponse = &resp;
1039 resp.referenceId = req->referenceId;
1041 resp.additionalSearchInfo = 0;
1045 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1047 logf(LOG_FATAL, "Bad result from backend");
1050 else if (bsrt->errcode)
1052 resp.records = diagrec(assoc->proto, bsrt->errcode,
1054 resp.resultCount = &nulint;
1055 resp.numberOfRecordsReturned = &nulint;
1056 resp.nextResultSetPosition = &nulint;
1057 resp.searchStatus = &nulint;
1058 resp.resultSetStatus = &none;
1059 resp.presentStatus = 0;
1064 Z_RecordComposition comp, *compp = 0;
1065 static int presst = 0;
1068 resp.resultCount = &bsrt->hits;
1070 comp.which = Z_RecordComp_simple;
1071 /* how many records does the user agent want, then? */
1072 if (bsrt->hits <= *req->smallSetUpperBound)
1075 if ((comp.u.simple = req->smallSetElementSetNames))
1078 else if (bsrt->hits < *req->largeSetLowerBound)
1080 toget = *req->mediumSetPresentNumber;
1081 if (toget > bsrt->hits)
1083 if ((comp.u.simple = req->mediumSetElementSetNames))
1089 if (toget && !resp.records)
1094 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1095 prefformat->class != CLASS_RECSYN)
1098 form = prefformat->value;
1099 resp.records = pack_records(assoc, req->resultSetName, 1,
1100 &toget, compp, &next, &presst, form);
1103 resp.numberOfRecordsReturned = &toget;
1104 resp.nextResultSetPosition = &next;
1105 resp.searchStatus = &sr;
1106 resp.resultSetStatus = 0;
1107 resp.presentStatus = &presst;
1111 if (*resp.resultCount)
1113 resp.numberOfRecordsReturned = &nulint;
1114 resp.nextResultSetPosition = &next;
1115 resp.searchStatus = &sr;
1116 resp.resultSetStatus = 0;
1117 resp.presentStatus = 0;
1124 * Maybe we got a little over-friendly when we designed bend_fetch to
1125 * get only one record at a time. Some backends can optimise multiple-record
1126 * fetches, and at any rate, there is some overhead involved in
1127 * all that selecting and hopping around. Problem is, of course, that the
1128 * frontend can't know ahead of time how many records it'll need to
1129 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1130 * is downright lousy as a bulk data transfer protocol.
1132 * To start with, we'll do the fetching of records from the backend
1133 * in one operation: To save some trips in and out of the event-handler,
1134 * and to simplify the interface to pack_records. At any rate, asynch
1135 * operation is more fun in operations that have an unpredictable execution
1136 * speed - which is normally more true for search than for present.
1138 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1141 Z_PresentRequest *req = reqb->request->u.presentRequest;
1143 static Z_PresentResponse resp;
1144 static int presst, next, num;
1149 logf(LOG_LOG, "Got PresentRequest.");
1150 apdu.which = Z_APDU_presentResponse;
1151 apdu.u.presentResponse = &resp;
1152 resp.referenceId = req->referenceId;
1157 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1158 prefformat->class != CLASS_RECSYN)
1161 form = prefformat->value;
1162 num = *req->numberOfRecordsRequested;
1163 resp.records = pack_records(assoc, req->resultSetId,
1164 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1168 resp.numberOfRecordsReturned = #
1169 resp.presentStatus = &presst;
1170 resp.nextResultSetPosition = &next;
1176 * Scan was implemented rather in a hurry, and with support for only the basic
1177 * elements of the service in the backend API. Suggestions are welcome.
1179 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1181 Z_ScanRequest *req = reqb->request->u.scanRequest;
1183 static Z_ScanResponse res;
1184 static int scanStatus = Z_Scan_failure;
1185 static int numberOfEntriesReturned = 0;
1187 static Z_ListEntries ents;
1188 #define SCAN_MAX_ENTRIES 200
1189 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1190 bend_scanrequest srq;
1191 bend_scanresult *srs;
1193 logf(LOG_LOG, "Got scanrequest");
1194 apdu.which = Z_APDU_scanResponse;
1195 apdu.u.scanResponse = &res;
1196 res.referenceId = req->referenceId;
1198 res.scanStatus = &scanStatus;
1199 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1200 res.positionOfTerm = 0;
1201 res.entries = &ents;
1202 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1203 res.attributeSet = 0;
1208 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1209 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1210 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1211 else if (req->stepSize && *req->stepSize > 0)
1212 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1215 if (req->termListAndStartPoint->term->which == Z_Term_general)
1216 logf(LOG_DEBUG, " term: '%.*s'",
1217 req->termListAndStartPoint->term->u.general->len,
1218 req->termListAndStartPoint->term->u.general->buf);
1219 srq.num_bases = req->num_databaseNames;
1220 srq.basenames = req->databaseNames;
1221 srq.num_entries = *req->numberOfTermsRequested;
1222 srq.term = req->termListAndStartPoint;
1223 srq.term_position = req->preferredPositionInResponse ?
1224 *req->preferredPositionInResponse : 1;
1225 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1226 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1227 else if (srs->errcode)
1228 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1229 srs->errcode, srs->errstring);
1233 static Z_Entries list;
1235 if (srs->status == BEND_SCAN_PARTIAL)
1236 scanStatus = Z_Scan_partial_5;
1238 scanStatus = Z_Scan_success;
1239 ents.which = Z_ListEntries_entries;
1240 ents.u.entries = &list;
1242 for (i = 0; i < srs->num_entries; i++)
1248 if (i >= SCAN_MAX_ENTRIES)
1250 scanStatus = Z_Scan_partial_4;
1253 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1254 e->which = Z_Entry_termInfo;
1255 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1256 t->suggestedAttributes = 0;
1257 t->alternativeTerm = 0;
1258 t->byAttributes = 0;
1259 t->globalOccurrences = &srs->entries[i].occurrences;
1260 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1261 t->term->which = Z_Term_general;
1262 t->term->u.general = o = odr_malloc(assoc->encode,
1264 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1265 strlen(srs->entries[i].term));
1266 memcpy(o->buf, srs->entries[i].term, o->len);
1267 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1268 srs->entries[i].term, srs->entries[i].occurrences);
1270 list.num_entries = i;
1271 res.numberOfEntriesReturned = &list.num_entries;
1272 res.positionOfTerm = &srs->term_position;
1279 static void process_close(association *assoc, request *reqb)
1281 Z_Close *req = reqb->request->u.close;
1282 static char *reasons[] =
1289 "securityViolation",
1296 logf(LOG_LOG, "Got close, reason %s, message %s",
1297 reasons[*req->closeReason], req->diagnosticInformation ?
1298 req->diagnosticInformation : "NULL");
1299 if (assoc->version < 3) /* to make do_force respond with close */
1301 do_close(assoc, Z_Close_finished, "Association terminated by client");