2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.57 1996-01-02 08:57:47 quinn
8 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
10 * Revision 1.56 1995/12/14 11:09:57 quinn
13 * Revision 1.55 1995/11/08 17:41:37 quinn
16 * Revision 1.54 1995/11/08 15:11:29 quinn
17 * Log of close transmit.
19 * Revision 1.53 1995/11/01 13:54:58 quinn
22 * Revision 1.52 1995/11/01 12:19:13 quinn
23 * Second attempt to fix same bug.
25 * Revision 1.50 1995/10/25 16:58:32 quinn
28 * Revision 1.49 1995/10/16 13:51:53 quinn
29 * Changes to provide Especs to the backend.
31 * Revision 1.48 1995/10/06 08:51:20 quinn
34 * Revision 1.47 1995/08/29 14:24:16 quinn
35 * Added second half of close-handshake
37 * Revision 1.46 1995/08/29 11:17:58 quinn
38 * Added code to receive close
40 * Revision 1.45 1995/08/21 09:11:00 quinn
41 * Smallish fixes to suppport new formats.
43 * Revision 1.44 1995/08/17 12:45:25 quinn
44 * Fixed minor problems with GRS-1. Added support in c&s.
46 * Revision 1.43 1995/08/15 12:00:31 quinn
49 * Revision 1.42 1995/08/15 11:16:50 quinn
51 * Revision 1.41 1995/08/02 10:23:06 quinn
54 * Revision 1.40 1995/07/31 14:34:26 quinn
55 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
57 * Revision 1.39 1995/06/27 13:21:00 quinn
60 * Revision 1.38 1995/06/19 12:39:11 quinn
61 * Fixed bug in timeout code. Added BER dumper.
63 * Revision 1.37 1995/06/16 13:16:14 quinn
64 * Fixed Defaultdiagformat.
66 * Revision 1.36 1995/06/16 10:31:36 quinn
67 * Added session timeout.
69 * Revision 1.35 1995/06/15 07:45:14 quinn
72 * Revision 1.34 1995/06/14 15:26:46 quinn
73 * *** empty log message ***
75 * Revision 1.33 1995/06/06 14:57:05 quinn
78 * Revision 1.32 1995/06/06 08:41:44 quinn
81 * Revision 1.31 1995/06/06 08:15:37 quinn
84 * Revision 1.30 1995/06/05 10:53:32 quinn
85 * Added a better SCAN.
87 * Revision 1.29 1995/06/01 11:25:03 quinn
90 * Revision 1.28 1995/06/01 11:21:01 quinn
91 * Attempting to fix a bug in pack-records. replaced break with continue
92 * for large records, according to standard.
94 * Revision 1.27 1995/05/29 08:12:06 quinn
97 * Revision 1.26 1995/05/18 13:02:12 quinn
100 * Revision 1.25 1995/05/17 08:42:26 quinn
101 * Transfer auth info to backend. Allow backend to reject init gracefully.
103 * Revision 1.24 1995/05/16 08:51:04 quinn
104 * License, documentation, and memory fixes
106 * Revision 1.23 1995/05/15 13:25:10 quinn
109 * Revision 1.22 1995/05/15 11:56:39 quinn
110 * Asynchronous facilities. Restructuring of seshigh code.
112 * Revision 1.21 1995/05/02 08:53:19 quinn
113 * Trying in vain to fix comm with ISODE
115 * Revision 1.20 1995/04/20 15:13:00 quinn
118 * Revision 1.19 1995/04/18 08:15:34 quinn
119 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
120 * neater. We'll make the same change for decoding one day.
122 * Revision 1.18 1995/04/17 11:28:25 quinn
125 * Revision 1.17 1995/04/10 10:23:36 quinn
126 * Some work to add scan and other things.
128 * Revision 1.16 1995/03/31 09:18:55 quinn
131 * Revision 1.15 1995/03/30 14:03:23 quinn
132 * Added RFC1006 as separate library
134 * Revision 1.14 1995/03/30 12:18:17 quinn
137 * Revision 1.13 1995/03/30 09:09:24 quinn
138 * Added state-handle and some support for asynchronous activities.
140 * Revision 1.12 1995/03/29 15:40:16 quinn
141 * Ongoing work. Statserv is now dynamic by default
143 * Revision 1.11 1995/03/28 09:16:21 quinn
144 * Added record packing to the search request
146 * Revision 1.10 1995/03/27 08:34:24 quinn
147 * Added dynamic server functionality.
148 * Released bindings to session.c (is now redundant)
150 * Revision 1.9 1995/03/22 15:01:26 quinn
151 * Adjusting record packing.
153 * Revision 1.8 1995/03/22 10:13:21 quinn
154 * Working on record packer
156 * Revision 1.7 1995/03/21 15:53:31 quinn
159 * Revision 1.6 1995/03/21 12:30:09 quinn
160 * Beginning to add support for record packing.
162 * Revision 1.5 1995/03/17 10:44:13 quinn
163 * Added catch of null-string in makediagrec
165 * Revision 1.4 1995/03/17 10:18:08 quinn
166 * Added memory management.
168 * Revision 1.3 1995/03/16 17:42:39 quinn
171 * Revision 1.2 1995/03/16 13:29:01 quinn
172 * Partitioned server.
174 * Revision 1.1 1995/03/15 16:02:10 quinn
175 * Modded session.c to seshigh.c
180 * Frontend server logic.
182 * This code receives incoming APDUs, and handles client requests by means
183 * of the backend API.
185 * Some of the code is getting quite involved, compared to simpler servers -
186 * primarily because it is asynchronous both in the communication with
187 * the user and the backend. We think the complexity will pay off in
188 * the form of greater flexibility when more asynchronous facilities
191 * Memory management has become somewhat involved. In the simple case, where
192 * only one PDU is pending at a time, it will simply reuse the same memory,
193 * once it has found its working size. When we enable multiple concurrent
194 * operations, perhaps even with multiple parallel calls to the backend, it
195 * will maintain a pool of buffers for encoding and decoding, trying to
196 * minimize memory allocation/deallocation during normal operation.
198 * TODOs include (and will be done in order of public interest):
200 * Support for EXPLAIN - provide simple meta-database system.
201 * Support for access control.
202 * Support for resource control.
203 * Support for extended services - primarily Item Order.
204 * Rest of Z39.50-1994
212 #include <sys/time.h>
215 #include <comstack.h>
221 #include <statserv.h>
225 static int process_request(association *assoc);
226 void backend_response(IOCHAN i, int event);
227 static int process_response(association *assoc, request *req, Z_APDU *res);
228 static Z_APDU *process_initRequest(association *assoc, request *reqb);
229 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
231 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
232 bend_searchresult *bsrt, int *fd);
233 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
235 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
236 static void process_close(association *assoc, request *reqb);
238 static FILE *apduf = 0; /* for use in static mode */
239 static statserv_options_block *control_block = 0;
242 * Create and initialize a new association-handle.
243 * channel : iochannel for the current line.
244 * link : communications channel.
245 * Returns: 0 or a new association handle.
247 association *create_association(IOCHAN channel, COMSTACK link)
252 control_block = statserv_getcontrol();
253 if (!(new = xmalloc(sizeof(*new))))
255 new->client_chan = channel;
256 new->client_link = link;
257 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
258 !(new->encode = odr_createmem(ODR_ENCODE)))
260 if (*control_block->apdufile)
265 strcpy(filename, control_block->apdufile);
266 if (!(new->print = odr_createmem(ODR_PRINT)))
268 if (*control_block->apdufile != '-')
270 strcpy(filename, control_block->apdufile);
271 if (!control_block->dynamic)
275 if (!(apduf = fopen(filename, "w")))
277 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
280 setvbuf(apduf, 0, _IONBF, 0);
286 sprintf(filename + strlen(filename), ".%d", getpid());
287 if (!(f = fopen(filename, "w")))
289 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
292 setvbuf(f, 0, _IONBF, 0);
294 odr_setprint(new->print, f);
299 new->input_buffer = 0;
300 new->input_buffer_len = 0;
302 new->state = ASSOC_NEW;
303 request_initq(&new->incoming);
304 request_initq(&new->outgoing);
305 new->proto = cs_getproto(link);
310 * Free association and release resources.
312 void destroy_association(association *h)
314 odr_destroy(h->decode);
315 odr_destroy(h->encode);
317 odr_destroy(h->print);
319 xfree(h->input_buffer);
321 bend_close(h->backend);
322 while (request_deq(&h->incoming));
323 while (request_deq(&h->outgoing));
327 static void do_close(association *a, int reason, char *message)
330 Z_Close *cls = zget_Close(a->encode);
331 request *req = request_get();
333 /* Purge request queue */
334 while (request_deq(&a->incoming));
335 while (request_deq(&a->outgoing));
338 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
339 reason, message ? message : "none");
340 apdu.which = Z_APDU_close;
342 *cls->closeReason = reason;
343 cls->diagnosticInformation = message;
344 process_response(a, req, &apdu);
345 iochan_settimeout(a->client_chan, 60);
349 logf(LOG_DEBUG, "v2 client. No Close PDU");
350 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
352 a->state = ASSOC_DEAD;
356 * This is where PDUs from the client are read and the further
357 * processing is initiated. Flow of control moves down through the
358 * various process_* functions below, until the encoded result comes back up
359 * to the output handler in here.
361 * h : the I/O channel that has an outstanding event.
362 * event : the current outstanding event.
364 void ir_session(IOCHAN h, int event)
367 association *assoc = iochan_getdata(h);
368 COMSTACK conn = assoc->client_link;
371 assert(h && conn && assoc);
372 if (event == EVENT_TIMEOUT)
374 if (assoc->state != ASSOC_UP)
376 logf(LOG_LOG, "Final timeout - closing connection.");
378 destroy_association(assoc);
383 logf(LOG_LOG, "Session idle too long. Sending close.");
384 do_close(assoc, Z_Close_lackOfActivity, 0);
388 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
390 if (event & EVENT_INPUT)
392 logf(LOG_DEBUG, "ir_session (input)");
393 assert(assoc && conn);
394 /* We aren't speaking to this fellow */
395 if (assoc->state == ASSOC_DEAD)
397 logf(LOG_LOG, "Closed connection after reject");
399 destroy_association(assoc);
403 if ((res = cs_get(conn, &assoc->input_buffer,
404 &assoc->input_buffer_len)) <= 0)
406 logf(LOG_LOG, "Connection closed by client");
408 destroy_association(assoc);
412 else if (res == 1) /* incomplete read - wait for more */
414 if (cs_more(conn)) /* more stuff - call us again later, please */
415 iochan_setevent(h, EVENT_INPUT);
417 /* we got a complete PDU. Let's decode it */
418 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
419 req = request_get(); /* get a new request structure */
420 odr_reset(assoc->decode);
421 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
422 if (!z_APDU(assoc->decode, &req->request, 0))
424 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
425 odr_errlist[odr_geterror(assoc->decode)],
426 odr_offset(assoc->decode));
427 logf(LOG_LOG, "PDU dump:");
428 odr_dumpBER(log_file(), assoc->input_buffer, res);
429 do_close(assoc, Z_Close_protocolError, "Malformed package");
432 req->request_mem = odr_extract_mem(assoc->decode);
433 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
435 logf(LOG_WARN, "ODR print error: %s",
436 odr_errlist[odr_geterror(assoc->print)]);
437 odr_reset(assoc->print);
439 request_enq(&assoc->incoming, req);
442 /* can we do something yet? */
443 req = request_head(&assoc->incoming);
444 if (req->state == REQUEST_IDLE)
445 if (process_request(assoc) < 0)
446 do_close(assoc, Z_Close_systemProblem, "Unknown error");
448 if (event & EVENT_OUTPUT)
450 request *req = request_head(&assoc->outgoing);
452 logf(LOG_DEBUG, "ir_session (output)");
453 req->state = REQUEST_PENDING;
454 switch (res = cs_put(conn, req->response, req->len_response))
457 logf(LOG_LOG, "Connection closed by client");
459 destroy_association(assoc);
462 case 0: /* all sent - release the request structure */
463 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
464 nmem_destroy(req->request_mem);
465 request_deq(&assoc->outgoing);
466 request_release(req);
467 if (!request_head(&assoc->outgoing))
468 iochan_clearflag(h, EVENT_OUTPUT);
470 /* value of 1 -- partial send -- is simply ignored */
473 if (event & EVENT_EXCEPT)
475 logf(LOG_DEBUG, "ir_session (exception)");
477 destroy_association(assoc);
483 * Initiate request processing.
485 static int process_request(association *assoc)
487 request *req = request_head(&assoc->incoming);
491 logf(LOG_DEBUG, "process_request");
492 assert(req && req->state == REQUEST_IDLE);
493 switch (req->request->which)
495 case Z_APDU_initRequest:
496 res = process_initRequest(assoc, req); break;
497 case Z_APDU_searchRequest:
498 res = process_searchRequest(assoc, req, &fd); break;
499 case Z_APDU_presentRequest:
500 res = process_presentRequest(assoc, req, &fd); break;
501 case Z_APDU_scanRequest:
502 res = process_scanRequest(assoc, req, &fd); break;
504 process_close(assoc, req); return 0;
506 logf(LOG_WARN, "Bad APDU received");
511 logf(LOG_DEBUG, " result immediately available");
512 return process_response(assoc, req, res);
516 logf(LOG_WARN, " bad result");
519 else /* no result yet - one will be provided later */
523 /* Set up an I/O handler for the fd supplied by the backend */
525 logf(LOG_DEBUG, " establishing handler for result");
526 req->state = REQUEST_PENDING;
527 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
529 iochan_setdata(chan, assoc);
535 * Handle message from the backend.
537 void backend_response(IOCHAN i, int event)
539 association *assoc = iochan_getdata(i);
540 request *req = request_head(&assoc->incoming);
544 logf(LOG_DEBUG, "backend_response");
545 assert(assoc && req && req->state != REQUEST_IDLE);
546 /* determine what it is we're waiting for */
547 switch (req->request->which)
549 case Z_APDU_searchRequest:
550 res = response_searchRequest(assoc, req, 0, &fd); break;
552 case Z_APDU_presentRequest:
553 res = response_presentRequest(assoc, req, 0, &fd); break;
554 case Z_APDU_scanRequest:
555 res = response_scanRequest(assoc, req, 0, &fd); break;
558 logf(LOG_WARN, "Serious programmer's lapse or bug");
561 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
563 logf(LOG_LOG, "Fatal error when talking to backend");
564 do_close(assoc, Z_Close_systemProblem, 0);
568 else if (!res) /* no result yet - try again later */
570 logf(LOG_DEBUG, " no result yet");
571 iochan_setfd(i, fd); /* in case fd has changed */
576 * Encode response, and transfer the request structure to the outgoing queue.
578 static int process_response(association *assoc, request *req, Z_APDU *res)
580 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
581 if (!z_APDU(assoc->encode, &res, 0))
583 logf(LOG_WARN, "ODR error when encoding response: %s",
584 odr_errlist[odr_geterror(assoc->decode)]);
585 odr_reset(assoc->encode);
588 req->response = odr_getbuf(assoc->encode, &req->len_response,
589 &req->size_response);
590 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
591 odr_reset(assoc->encode);
592 if (assoc->print && !z_APDU(assoc->print, &res, 0))
594 logf(LOG_WARN, "ODR print error: %s",
595 odr_errlist[odr_geterror(assoc->print)]);
596 odr_reset(assoc->print);
598 /* change this when we make the backend reentrant */
599 if (req == request_head(&assoc->incoming))
601 req->state = REQUEST_IDLE;
602 request_deq(&assoc->incoming);
604 request_enq(&assoc->outgoing, req);
605 /* turn the work over to the ir_session handler */
606 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
607 /* Is there more work to be done? give that to the input handler too */
608 if (request_head(&assoc->incoming))
609 iochan_setevent(assoc->client_chan, EVENT_WORK);
614 * Handle init request.
615 * At the moment, we don't check the options
616 * anywhere else in the code - we just try not to do anything that would
617 * break a naive client. We'll toss 'em into the association block when
618 * we need them there.
620 static Z_APDU *process_initRequest(association *assoc, request *reqb)
622 Z_InitRequest *req = reqb->request->u.initRequest;
623 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
624 Z_InitResponse *resp = apdu->u.initResponse;
625 bend_initrequest binitreq;
626 bend_initresult *binitres;
629 logf(LOG_LOG, "Got initRequest");
630 if (req->implementationId)
631 logf(LOG_LOG, "Id: %s", req->implementationId);
632 if (req->implementationName)
633 logf(LOG_LOG, "Name: %s", req->implementationName);
634 if (req->implementationVersion)
635 logf(LOG_LOG, "Version: %s", req->implementationVersion);
637 binitreq.configname = "default-config";
638 binitreq.auth = req->idAuthentication;
639 if (!(binitres = bend_init(&binitreq)))
641 logf(LOG_WARN, "Bad response from backend.");
645 assoc->backend = binitres->handle;
646 resp->referenceId = req->referenceId;
648 /* let's tell the client what we can do */
649 if (ODR_MASK_GET(req->options, Z_Options_search))
651 ODR_MASK_SET(resp->options, Z_Options_search);
652 strcat(options, "srch");
654 if (ODR_MASK_GET(req->options, Z_Options_present))
656 ODR_MASK_SET(resp->options, Z_Options_present);
657 strcat(options, " prst");
660 if (ODR_MASK_GET(req->options, Z_Options_delSet))
662 ODR_MASK_SET(&options, Z_Options_delSet);
663 strcat(options, " del");
666 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
668 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
669 strcat(options, " namedresults");
671 if (ODR_MASK_GET(req->options, Z_Options_scan))
673 ODR_MASK_SET(resp->options, Z_Options_scan);
674 strcat(options, " scan");
676 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
678 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
679 strcat(options, " concurop");
682 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
684 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
685 assoc->version = 2; /* 1 & 2 are equivalent */
687 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
689 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
692 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
694 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
697 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
698 assoc->maximumRecordSize = *req->maximumRecordSize;
699 if (assoc->maximumRecordSize > control_block->maxrecordsize)
700 assoc->maximumRecordSize = control_block->maxrecordsize;
701 assoc->preferredMessageSize = *req->preferredMessageSize;
702 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
703 assoc->preferredMessageSize = assoc->maximumRecordSize;
704 resp->preferredMessageSize = &assoc->preferredMessageSize;
705 resp->maximumRecordSize = &assoc->maximumRecordSize;
706 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
707 if (binitres->errcode)
709 logf(LOG_LOG, "Connection rejected by backend.");
711 assoc->state = ASSOC_DEAD;
714 assoc->state = ASSOC_UP;
719 * These functions should be merged.
723 * nonsurrogate diagnostic record.
725 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
727 static Z_Records rec;
731 static Z_DiagRec drec;
732 static Z_DefaultDiagFormat dr;
738 bib1.oclass = CLASS_DIAGSET;
739 bib1.value = VAL_BIB1;
741 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
744 rec.which = Z_Records_NSD;
746 rec.u.nonSurrogateDiagnostic = &drec;
747 drec.which = Z_DiagRec_defaultFormat;
748 drec.u.defaultFormat = &dr;
750 rec.u.nonSurrogateDiagnostic = &dr;
752 dr.diagnosticSetId = oid_getoidbyent(&bib1);
754 dr.which = Z_DiagForm_v2AddInfo;
755 dr.addinfo = addinfo ? addinfo : "";
760 * surrogate diagnostic.
762 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
763 int error, char *addinfo)
765 static Z_NamePlusRecord rec;
769 static Z_DiagRec drec;
770 static Z_DefaultDiagFormat dr;
776 bib1.oclass = CLASS_DIAGSET;
777 bib1.value = VAL_BIB1;
779 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
781 rec.databaseName = dbname;
782 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
784 rec.u.surrogateDiagnostic = &drec;
785 drec.which = Z_DiagRec_defaultFormat;
786 drec.u.defaultFormat = &dr;
788 rec.u.surrogateDiagnostic = &dr;
790 dr.diagnosticSetId = oid_getoidbyent(&bib1);
792 dr.which = Z_DiagForm_v2AddInfo;
793 dr.addinfo = addinfo ? addinfo : "";
798 * multiple nonsurrogate diagnostics.
800 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
802 static Z_DiagRecs recs;
806 static Z_DiagRec *recp[1], drec;
807 static Z_DefaultDiagFormat rec;
809 static Z_DiagRec *recp[1], rec;
812 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
814 bib1.oclass = CLASS_DIAGSET;
815 bib1.value = VAL_BIB1;
818 recs.num_diagRecs = 1;
819 recs.diagRecs = recp;
822 drec.which = Z_DiagRec_defaultFormat;
823 drec.u.defaultFormat = &rec;
827 rec.diagnosticSetId = oid_getoidbyent(&bib1);
828 rec.condition = &err;
829 rec.which = Z_DiagForm_v2AddInfo;
830 rec.addinfo = addinfo ? addinfo : "";
834 #define MAX_RECORDS 256
836 static Z_Records *pack_records(association *a, char *setname, int start,
837 int *num, Z_RecordComposition *comp,
838 int *next, int *pres, oid_value format)
840 int recno, total_length = 0, toget = *num;
841 static Z_Records records;
842 static Z_NamePlusRecordList reclist;
843 static Z_NamePlusRecord *list[MAX_RECORDS];
846 records.which = Z_Records_DBOSD;
847 records.u.databaseOrSurDiagnostics = &reclist;
848 reclist.num_records = 0;
849 reclist.records = list;
850 *pres = Z_PRES_SUCCESS;
854 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
855 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
856 a->maximumRecordSize);
857 for (recno = start; reclist.num_records < toget; recno++)
859 bend_fetchrequest freq;
860 bend_fetchresult *fres;
861 Z_NamePlusRecord *thisrec;
862 Z_DatabaseRecord *thisext;
866 * we get the number of bytes allocated on the stream before any
867 * allocation done by the backend - this should give us a reasonable
868 * idea of the total size of the data so far.
870 total_length = odr_total(a->encode);
871 if (reclist.num_records == MAX_RECORDS - 1)
873 *pres = Z_PRES_PARTIAL_2;
876 freq.setname = setname;
879 freq.format = format;
880 freq.stream = a->encode;
881 if (!(fres = bend_fetch(a->backend, &freq, 0)))
883 *pres = Z_PRES_FAILURE;
884 return diagrec(a->proto, 2, "Backend interface problem");
886 /* backend should be able to signal whether error is system-wide
887 or only pertaining to current record */
890 *pres = Z_PRES_FAILURE;
891 return diagrec(a->proto, fres->errcode, fres->errstring);
894 this_length = fres->len;
896 this_length = odr_total(a->encode) - total_length;
897 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
898 this_length, total_length);
899 if (this_length + total_length > a->preferredMessageSize)
901 /* record is small enough, really */
902 if (this_length <= a->preferredMessageSize)
904 logf(LOG_DEBUG, " Dropped last normal-sized record");
905 *pres = Z_PRES_PARTIAL_2;
908 /* record can only be fetched by itself */
909 if (this_length < a->maximumRecordSize)
911 logf(LOG_DEBUG, " Record > prefmsgsz");
914 logf(LOG_DEBUG, " Dropped it");
915 reclist.records[reclist.num_records] =
916 surrogatediagrec(a->proto, fres->basename, 16, 0);
917 reclist.num_records++;
921 else /* too big entirely */
923 logf(LOG_DEBUG, "Record > maxrcdsz");
924 reclist.records[reclist.num_records] =
925 surrogatediagrec(a->proto, fres->basename, 17, 0);
926 reclist.num_records++;
930 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
932 if (!(thisrec->databaseName = odr_malloc(a->encode,
933 strlen(fres->basename) + 1)))
935 strcpy(thisrec->databaseName, fres->basename);
936 thisrec->which = Z_NamePlusRecord_databaseRecord;
937 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
938 sizeof(Z_DatabaseRecord))))
940 recform.proto = a->proto;
941 recform.oclass = CLASS_RECSYN;
942 recform.value = fres->format;
943 thisext->direct_reference = odr_oiddup(a->encode,
944 oid_getoidbyent(&recform));
945 thisext->indirect_reference = 0;
946 thisext->descriptor = 0;
947 if (fres->len < 0) /* Structured data */
949 switch (fres->format)
951 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
952 case VAL_GRS1: thisext->which = Z_External_grs1; break;
953 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
957 logf(LOG_FATAL, "Unknown structured format from backend.");
962 * We cheat on the pointers here. Obviously, the record field
963 * of the backend-fetch structure should have been a union for
964 * correctness, but we're stuck with this for backwards
967 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
969 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
971 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
973 thisext->which = Z_External_sutrs;
974 thisext->u.sutrs = sutrs;
975 sutrs->buf = odr_malloc(a->encode, fres->len);
976 sutrs->len = sutrs->size = fres->len;
977 memcpy(sutrs->buf, fres->record, fres->len);
979 else /* octet-aligned record. */
981 thisext->which = Z_External_octet;
982 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
985 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
988 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
989 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
992 reclist.records[reclist.num_records] = thisrec;
993 reclist.num_records++;
994 *next = fres->last_in_set ? 0 : recno + 1;
996 *num = reclist.num_records;
1000 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1003 Z_SearchRequest *req = reqb->request->u.searchRequest;
1004 bend_searchrequest bsrq;
1005 bend_searchresult *bsrt;
1007 logf(LOG_LOG, "Got SearchRequest.");
1009 bsrq.setname = req->resultSetName;
1010 bsrq.replace_set = *req->replaceIndicator;
1011 bsrq.num_bases = req->num_databaseNames;
1012 bsrq.basenames = req->databaseNames;
1013 bsrq.query = req->query;
1015 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1017 return response_searchRequest(assoc, reqb, bsrt, fd);
1020 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1023 * Prepare a searchresponse based on the backend results. We probably want
1024 * to look at making the fetching of records nonblocking as well, but
1025 * so far, we'll keep things simple.
1026 * If bsrt is null, that means we're called in response to a communications
1027 * event, and we'll have to get the response for ourselves.
1029 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1030 bend_searchresult *bsrt, int *fd)
1032 Z_SearchRequest *req = reqb->request->u.searchRequest;
1034 static Z_SearchResponse resp;
1035 static int nulint = 0;
1036 static bool_t sr = 1;
1037 static int next = 0;
1038 static int none = Z_RES_NONE;
1040 apdu.which = Z_APDU_searchResponse;
1041 apdu.u.searchResponse = &resp;
1042 resp.referenceId = req->referenceId;
1044 resp.additionalSearchInfo = 0;
1048 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1050 logf(LOG_FATAL, "Bad result from backend");
1053 else if (bsrt->errcode)
1055 resp.records = diagrec(assoc->proto, bsrt->errcode,
1057 resp.resultCount = &nulint;
1058 resp.numberOfRecordsReturned = &nulint;
1059 resp.nextResultSetPosition = &nulint;
1060 resp.searchStatus = &nulint;
1061 resp.resultSetStatus = &none;
1062 resp.presentStatus = 0;
1067 Z_RecordComposition comp, *compp = 0;
1068 static int presst = 0;
1071 resp.resultCount = &bsrt->hits;
1073 comp.which = Z_RecordComp_simple;
1074 /* how many records does the user agent want, then? */
1075 if (bsrt->hits <= *req->smallSetUpperBound)
1078 if ((comp.u.simple = req->smallSetElementSetNames))
1081 else if (bsrt->hits < *req->largeSetLowerBound)
1083 toget = *req->mediumSetPresentNumber;
1084 if (toget > bsrt->hits)
1086 if ((comp.u.simple = req->mediumSetElementSetNames))
1092 if (toget && !resp.records)
1097 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1098 prefformat->oclass != CLASS_RECSYN)
1101 form = prefformat->value;
1102 resp.records = pack_records(assoc, req->resultSetName, 1,
1103 &toget, compp, &next, &presst, form);
1106 resp.numberOfRecordsReturned = &toget;
1107 resp.nextResultSetPosition = &next;
1108 resp.searchStatus = &sr;
1109 resp.resultSetStatus = 0;
1110 resp.presentStatus = &presst;
1114 if (*resp.resultCount)
1116 resp.numberOfRecordsReturned = &nulint;
1117 resp.nextResultSetPosition = &next;
1118 resp.searchStatus = &sr;
1119 resp.resultSetStatus = 0;
1120 resp.presentStatus = 0;
1127 * Maybe we got a little over-friendly when we designed bend_fetch to
1128 * get only one record at a time. Some backends can optimise multiple-record
1129 * fetches, and at any rate, there is some overhead involved in
1130 * all that selecting and hopping around. Problem is, of course, that the
1131 * frontend can't know ahead of time how many records it'll need to
1132 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1133 * is downright lousy as a bulk data transfer protocol.
1135 * To start with, we'll do the fetching of records from the backend
1136 * in one operation: To save some trips in and out of the event-handler,
1137 * and to simplify the interface to pack_records. At any rate, asynch
1138 * operation is more fun in operations that have an unpredictable execution
1139 * speed - which is normally more true for search than for present.
1141 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1144 Z_PresentRequest *req = reqb->request->u.presentRequest;
1146 static Z_PresentResponse resp;
1147 static int presst, next, num;
1152 logf(LOG_LOG, "Got PresentRequest.");
1153 apdu.which = Z_APDU_presentResponse;
1154 apdu.u.presentResponse = &resp;
1155 resp.referenceId = req->referenceId;
1160 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1161 prefformat->oclass != CLASS_RECSYN)
1164 form = prefformat->value;
1165 num = *req->numberOfRecordsRequested;
1166 resp.records = pack_records(assoc, req->resultSetId,
1167 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1171 resp.numberOfRecordsReturned = #
1172 resp.presentStatus = &presst;
1173 resp.nextResultSetPosition = &next;
1179 * Scan was implemented rather in a hurry, and with support for only the basic
1180 * elements of the service in the backend API. Suggestions are welcome.
1182 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1184 Z_ScanRequest *req = reqb->request->u.scanRequest;
1186 static Z_ScanResponse res;
1187 static int scanStatus = Z_Scan_failure;
1188 static int numberOfEntriesReturned = 0;
1190 static Z_ListEntries ents;
1191 #define SCAN_MAX_ENTRIES 200
1192 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1193 bend_scanrequest srq;
1194 bend_scanresult *srs;
1196 logf(LOG_LOG, "Got scanrequest");
1197 apdu.which = Z_APDU_scanResponse;
1198 apdu.u.scanResponse = &res;
1199 res.referenceId = req->referenceId;
1201 res.scanStatus = &scanStatus;
1202 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1203 res.positionOfTerm = 0;
1204 res.entries = &ents;
1205 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1206 res.attributeSet = 0;
1211 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1212 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1213 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1214 else if (req->stepSize && *req->stepSize > 0)
1215 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1218 if (req->termListAndStartPoint->term->which == Z_Term_general)
1219 logf(LOG_DEBUG, " term: '%.*s'",
1220 req->termListAndStartPoint->term->u.general->len,
1221 req->termListAndStartPoint->term->u.general->buf);
1222 srq.num_bases = req->num_databaseNames;
1223 srq.basenames = req->databaseNames;
1224 srq.num_entries = *req->numberOfTermsRequested;
1225 srq.term = req->termListAndStartPoint;
1226 srq.term_position = req->preferredPositionInResponse ?
1227 *req->preferredPositionInResponse : 1;
1228 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1229 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1230 else if (srs->errcode)
1231 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1232 srs->errcode, srs->errstring);
1236 static Z_Entries list;
1238 if (srs->status == BEND_SCAN_PARTIAL)
1239 scanStatus = Z_Scan_partial_5;
1241 scanStatus = Z_Scan_success;
1242 ents.which = Z_ListEntries_entries;
1243 ents.u.entries = &list;
1245 for (i = 0; i < srs->num_entries; i++)
1251 if (i >= SCAN_MAX_ENTRIES)
1253 scanStatus = Z_Scan_partial_4;
1256 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1257 e->which = Z_Entry_termInfo;
1258 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1259 t->suggestedAttributes = 0;
1260 t->alternativeTerm = 0;
1261 t->byAttributes = 0;
1262 t->globalOccurrences = &srs->entries[i].occurrences;
1263 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1264 t->term->which = Z_Term_general;
1265 t->term->u.general = o = odr_malloc(assoc->encode,
1267 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1268 strlen(srs->entries[i].term));
1269 memcpy(o->buf, srs->entries[i].term, o->len);
1270 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1271 srs->entries[i].term, srs->entries[i].occurrences);
1273 list.num_entries = i;
1274 res.numberOfEntriesReturned = &list.num_entries;
1275 res.positionOfTerm = &srs->term_position;
1282 static void process_close(association *assoc, request *reqb)
1284 Z_Close *req = reqb->request->u.close;
1285 static char *reasons[] =
1292 "securityViolation",
1299 logf(LOG_LOG, "Got close, reason %s, message %s",
1300 reasons[*req->closeReason], req->diagnosticInformation ?
1301 req->diagnosticInformation : "NULL");
1302 if (assoc->version < 3) /* to make do_force respond with close */
1304 do_close(assoc, Z_Close_finished, "Association terminated by client");