2 * Copyright (c) 1995-1998, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.70 1998-01-29 13:15:35 adam
8 * Implemented sort for the backend interface.
10 * Revision 1.69 1997/09/30 11:48:12 adam
11 * Fixed bug introduced by previous commit.
13 * Revision 1.68 1997/09/29 13:18:59 adam
14 * Added function, oid_ent_to_oid, to replace the function
15 * oid_getoidbyent, which is not thread safe.
17 * Revision 1.67 1997/09/17 12:10:40 adam
20 * Revision 1.66 1997/09/05 15:26:44 adam
21 * Added ODR encode in search and scen bend request structures.
22 * Fixed a few enums that caused trouble with C++.
24 * Revision 1.65 1997/09/01 08:53:01 adam
25 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
26 * moved a separate directory. MSV5.0 project server.dsp created.
27 * As an option, the server can now operate as an NT service.
29 * Revision 1.64 1997/04/30 08:52:11 quinn
32 * Revision 1.63 1996/10/11 11:57:26 quinn
35 * Revision 1.62 1996/07/06 19:58:35 quinn
36 * System headerfiles gathered in yconfig
38 * Revision 1.61 1996/06/10 08:56:16 quinn
41 * Revision 1.60 1996/05/30 11:03:10 quinn
42 * Fixed NextresultSetPosition bug fixed.
44 * Revision 1.59 1996/05/14 09:26:46 quinn
45 * Added attribute set to scan backend
47 * Revision 1.58 1996/02/20 12:53:04 quinn
50 * Revision 1.57 1996/01/02 08:57:47 quinn
51 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
53 * Revision 1.56 1995/12/14 11:09:57 quinn
56 * Revision 1.55 1995/11/08 17:41:37 quinn
59 * Revision 1.54 1995/11/08 15:11:29 quinn
60 * Log of close transmit.
62 * Revision 1.53 1995/11/01 13:54:58 quinn
65 * Revision 1.52 1995/11/01 12:19:13 quinn
66 * Second attempt to fix same bug.
68 * Revision 1.50 1995/10/25 16:58:32 quinn
71 * Revision 1.49 1995/10/16 13:51:53 quinn
72 * Changes to provide Especs to the backend.
74 * Revision 1.48 1995/10/06 08:51:20 quinn
77 * Revision 1.47 1995/08/29 14:24:16 quinn
78 * Added second half of close-handshake
80 * Revision 1.46 1995/08/29 11:17:58 quinn
81 * Added code to receive close
83 * Revision 1.45 1995/08/21 09:11:00 quinn
84 * Smallish fixes to suppport new formats.
86 * Revision 1.44 1995/08/17 12:45:25 quinn
87 * Fixed minor problems with GRS-1. Added support in c&s.
89 * Revision 1.43 1995/08/15 12:00:31 quinn
92 * Revision 1.42 1995/08/15 11:16:50 quinn
94 * Revision 1.41 1995/08/02 10:23:06 quinn
97 * Revision 1.40 1995/07/31 14:34:26 quinn
98 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
100 * Revision 1.39 1995/06/27 13:21:00 quinn
103 * Revision 1.38 1995/06/19 12:39:11 quinn
104 * Fixed bug in timeout code. Added BER dumper.
106 * Revision 1.37 1995/06/16 13:16:14 quinn
107 * Fixed Defaultdiagformat.
109 * Revision 1.36 1995/06/16 10:31:36 quinn
110 * Added session timeout.
112 * Revision 1.35 1995/06/15 07:45:14 quinn
115 * Revision 1.34 1995/06/14 15:26:46 quinn
116 * *** empty log message ***
118 * Revision 1.33 1995/06/06 14:57:05 quinn
119 * Better diagnostics.
121 * Revision 1.32 1995/06/06 08:41:44 quinn
122 * Better diagnostics.
124 * Revision 1.31 1995/06/06 08:15:37 quinn
127 * Revision 1.30 1995/06/05 10:53:32 quinn
128 * Added a better SCAN.
130 * Revision 1.29 1995/06/01 11:25:03 quinn
133 * Revision 1.28 1995/06/01 11:21:01 quinn
134 * Attempting to fix a bug in pack-records. replaced break with continue
135 * for large records, according to standard.
137 * Revision 1.27 1995/05/29 08:12:06 quinn
140 * Revision 1.26 1995/05/18 13:02:12 quinn
143 * Revision 1.25 1995/05/17 08:42:26 quinn
144 * Transfer auth info to backend. Allow backend to reject init gracefully.
146 * Revision 1.24 1995/05/16 08:51:04 quinn
147 * License, documentation, and memory fixes
149 * Revision 1.23 1995/05/15 13:25:10 quinn
152 * Revision 1.22 1995/05/15 11:56:39 quinn
153 * Asynchronous facilities. Restructuring of seshigh code.
155 * Revision 1.21 1995/05/02 08:53:19 quinn
156 * Trying in vain to fix comm with ISODE
158 * Revision 1.20 1995/04/20 15:13:00 quinn
161 * Revision 1.19 1995/04/18 08:15:34 quinn
162 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
163 * neater. We'll make the same change for decoding one day.
165 * Revision 1.18 1995/04/17 11:28:25 quinn
168 * Revision 1.17 1995/04/10 10:23:36 quinn
169 * Some work to add scan and other things.
171 * Revision 1.16 1995/03/31 09:18:55 quinn
174 * Revision 1.15 1995/03/30 14:03:23 quinn
175 * Added RFC1006 as separate library
177 * Revision 1.14 1995/03/30 12:18:17 quinn
180 * Revision 1.13 1995/03/30 09:09:24 quinn
181 * Added state-handle and some support for asynchronous activities.
183 * Revision 1.12 1995/03/29 15:40:16 quinn
184 * Ongoing work. Statserv is now dynamic by default
186 * Revision 1.11 1995/03/28 09:16:21 quinn
187 * Added record packing to the search request
189 * Revision 1.10 1995/03/27 08:34:24 quinn
190 * Added dynamic server functionality.
191 * Released bindings to session.c (is now redundant)
193 * Revision 1.9 1995/03/22 15:01:26 quinn
194 * Adjusting record packing.
196 * Revision 1.8 1995/03/22 10:13:21 quinn
197 * Working on record packer
199 * Revision 1.7 1995/03/21 15:53:31 quinn
202 * Revision 1.6 1995/03/21 12:30:09 quinn
203 * Beginning to add support for record packing.
205 * Revision 1.5 1995/03/17 10:44:13 quinn
206 * Added catch of null-string in makediagrec
208 * Revision 1.4 1995/03/17 10:18:08 quinn
209 * Added memory management.
211 * Revision 1.3 1995/03/16 17:42:39 quinn
214 * Revision 1.2 1995/03/16 13:29:01 quinn
215 * Partitioned server.
217 * Revision 1.1 1995/03/15 16:02:10 quinn
218 * Modded session.c to seshigh.c
223 * Frontend server logic.
225 * This code receives incoming APDUs, and handles client requests by means
226 * of the backend API.
228 * Some of the code is getting quite involved, compared to simpler servers -
229 * primarily because it is asynchronous both in the communication with
230 * the user and the backend. We think the complexity will pay off in
231 * the form of greater flexibility when more asynchronous facilities
234 * Memory management has become somewhat involved. In the simple case, where
235 * only one PDU is pending at a time, it will simply reuse the same memory,
236 * once it has found its working size. When we enable multiple concurrent
237 * operations, perhaps even with multiple parallel calls to the backend, it
238 * will maintain a pool of buffers for encoding and decoding, trying to
239 * minimize memory allocation/deallocation during normal operation.
241 * TODOs include (and will be done in order of public interest):
243 * Support for EXPLAIN - provide simple meta-database system.
244 * Support for access control.
245 * Support for resource control.
246 * Support for extended services - primarily Item Order.
247 * Rest of Z39.50-1994
262 #include <comstack.h>
268 #include <statserv.h>
272 static int process_request(association *assoc);
273 void backend_response(IOCHAN i, int event);
274 static int process_response(association *assoc, request *req, Z_APDU *res);
275 static Z_APDU *process_initRequest(association *assoc, request *reqb);
276 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
278 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
279 bend_searchresult *bsrt, int *fd);
280 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
282 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
283 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
284 static void process_close(association *assoc, request *reqb);
286 static FILE *apduf = 0; /* for use in static mode */
287 static statserv_options_block *control_block = 0;
290 * Create and initialize a new association-handle.
291 * channel : iochannel for the current line.
292 * link : communications channel.
293 * Returns: 0 or a new association handle.
295 association *create_association(IOCHAN channel, COMSTACK link)
300 control_block = statserv_getcontrol();
301 if (!(new = xmalloc(sizeof(*new))))
303 new->client_chan = channel;
304 new->client_link = link;
305 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
306 !(new->encode = odr_createmem(ODR_ENCODE)))
308 if (*control_block->apdufile)
313 strcpy(filename, control_block->apdufile);
314 if (!(new->print = odr_createmem(ODR_PRINT)))
316 if (*control_block->apdufile != '-')
318 strcpy(filename, control_block->apdufile);
319 if (!control_block->dynamic)
323 if (!(apduf = fopen(filename, "w")))
325 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
328 setvbuf(apduf, 0, _IONBF, 0);
334 sprintf(filename + strlen(filename), ".%d", getpid());
335 if (!(f = fopen(filename, "w")))
337 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
340 setvbuf(f, 0, _IONBF, 0);
342 odr_setprint(new->print, f);
347 new->input_buffer = 0;
348 new->input_buffer_len = 0;
350 new->state = ASSOC_NEW;
351 request_initq(&new->incoming);
352 request_initq(&new->outgoing);
353 new->proto = cs_getproto(link);
358 * Free association and release resources.
360 void destroy_association(association *h)
362 odr_destroy(h->decode);
363 odr_destroy(h->encode);
365 odr_destroy(h->print);
367 xfree(h->input_buffer);
369 bend_close(h->backend);
370 while (request_deq(&h->incoming));
371 while (request_deq(&h->outgoing));
372 request_delq(&h->incoming);
373 request_delq(&h->outgoing);
377 static void do_close(association *a, int reason, char *message)
380 Z_Close *cls = zget_Close(a->encode);
381 request *req = request_get(&a->outgoing);
383 /* Purge request queue */
384 while (request_deq(&a->incoming));
385 while (request_deq(&a->outgoing));
388 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
389 reason, message ? message : "none");
390 apdu.which = Z_APDU_close;
392 *cls->closeReason = reason;
393 cls->diagnosticInformation = message;
394 process_response(a, req, &apdu);
395 iochan_settimeout(a->client_chan, 60);
399 logf(LOG_DEBUG, "v2 client. No Close PDU");
400 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
402 a->state = ASSOC_DEAD;
406 * This is where PDUs from the client are read and the further
407 * processing is initiated. Flow of control moves down through the
408 * various process_* functions below, until the encoded result comes back up
409 * to the output handler in here.
411 * h : the I/O channel that has an outstanding event.
412 * event : the current outstanding event.
414 void ir_session(IOCHAN h, int event)
417 association *assoc = iochan_getdata(h);
418 COMSTACK conn = assoc->client_link;
421 assert(h && conn && assoc);
422 if (event == EVENT_TIMEOUT)
424 if (assoc->state != ASSOC_UP)
426 logf(LOG_LOG, "Final timeout - closing connection.");
428 destroy_association(assoc);
433 logf(LOG_LOG, "Session idle too long. Sending close.");
434 do_close(assoc, Z_Close_lackOfActivity, 0);
438 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
440 if (event & EVENT_INPUT)
442 logf(LOG_DEBUG, "ir_session (input)");
443 assert(assoc && conn);
444 /* We aren't speaking to this fellow */
445 if (assoc->state == ASSOC_DEAD)
447 logf(LOG_LOG, "Closed connection after reject");
449 destroy_association(assoc);
453 if ((res = cs_get(conn, &assoc->input_buffer,
454 &assoc->input_buffer_len)) <= 0)
456 logf(LOG_LOG, "Connection closed by client");
458 destroy_association(assoc);
462 else if (res == 1) /* incomplete read - wait for more */
464 if (cs_more(conn)) /* more stuff - call us again later, please */
465 iochan_setevent(h, EVENT_INPUT);
467 /* we got a complete PDU. Let's decode it */
468 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
469 req = request_get(&assoc->incoming); /* get a new request structure */
470 odr_reset(assoc->decode);
471 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
472 if (!z_APDU(assoc->decode, &req->request, 0))
474 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
475 odr_errmsg(odr_geterror(assoc->decode)),
476 odr_offset(assoc->decode));
477 logf(LOG_LOG, "PDU dump:");
478 odr_dumpBER(log_file(), assoc->input_buffer, res);
479 do_close(assoc, Z_Close_protocolError, "Malformed package");
482 req->request_mem = odr_extract_mem(assoc->decode);
483 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
485 logf(LOG_WARN, "ODR print error: %s",
486 odr_errmsg(odr_geterror(assoc->print)));
487 odr_reset(assoc->print);
489 request_enq(&assoc->incoming, req);
492 /* can we do something yet? */
493 req = request_head(&assoc->incoming);
494 if (req->state == REQUEST_IDLE)
495 if (process_request(assoc) < 0)
496 do_close(assoc, Z_Close_systemProblem, "Unknown error");
498 if (event & EVENT_OUTPUT)
500 request *req = request_head(&assoc->outgoing);
502 logf(LOG_DEBUG, "ir_session (output)");
503 req->state = REQUEST_PENDING;
504 switch (res = cs_put(conn, req->response, req->len_response))
507 logf(LOG_LOG, "Connection closed by client");
509 destroy_association(assoc);
512 case 0: /* all sent - release the request structure */
513 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
514 nmem_destroy(req->request_mem);
515 request_deq(&assoc->outgoing);
516 request_release(req);
517 if (!request_head(&assoc->outgoing))
518 iochan_clearflag(h, EVENT_OUTPUT);
520 /* value of 1 -- partial send -- is simply ignored */
523 if (event & EVENT_EXCEPT)
525 logf(LOG_DEBUG, "ir_session (exception)");
527 destroy_association(assoc);
533 * Initiate request processing.
535 static int process_request(association *assoc)
537 request *req = request_head(&assoc->incoming);
541 logf(LOG_DEBUG, "process_request");
542 assert(req && req->state == REQUEST_IDLE);
543 switch (req->request->which)
545 case Z_APDU_initRequest:
546 res = process_initRequest(assoc, req); break;
547 case Z_APDU_searchRequest:
548 res = process_searchRequest(assoc, req, &fd); break;
549 case Z_APDU_presentRequest:
550 res = process_presentRequest(assoc, req, &fd); break;
551 case Z_APDU_scanRequest:
552 res = process_scanRequest(assoc, req, &fd); break;
553 case Z_APDU_sortRequest:
554 if (assoc->bend_sort)
555 res = process_sortRequest(assoc, req, &fd);
558 logf(LOG_WARN, "Cannot handle SORT APDU");
563 process_close(assoc, req); return 0;
565 logf(LOG_WARN, "Bad APDU received");
570 logf(LOG_DEBUG, " result immediately available");
571 return process_response(assoc, req, res);
575 logf(LOG_WARN, " bad result");
578 else /* no result yet - one will be provided later */
582 /* Set up an I/O handler for the fd supplied by the backend */
584 logf(LOG_DEBUG, " establishing handler for result");
585 req->state = REQUEST_PENDING;
586 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
588 iochan_setdata(chan, assoc);
594 * Handle message from the backend.
596 void backend_response(IOCHAN i, int event)
598 association *assoc = iochan_getdata(i);
599 request *req = request_head(&assoc->incoming);
603 logf(LOG_DEBUG, "backend_response");
604 assert(assoc && req && req->state != REQUEST_IDLE);
605 /* determine what it is we're waiting for */
606 switch (req->request->which)
608 case Z_APDU_searchRequest:
609 res = response_searchRequest(assoc, req, 0, &fd); break;
611 case Z_APDU_presentRequest:
612 res = response_presentRequest(assoc, req, 0, &fd); break;
613 case Z_APDU_scanRequest:
614 res = response_scanRequest(assoc, req, 0, &fd); break;
617 logf(LOG_WARN, "Serious programmer's lapse or bug");
620 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
622 logf(LOG_LOG, "Fatal error when talking to backend");
623 do_close(assoc, Z_Close_systemProblem, 0);
627 else if (!res) /* no result yet - try again later */
629 logf(LOG_DEBUG, " no result yet");
630 iochan_setfd(i, fd); /* in case fd has changed */
635 * Encode response, and transfer the request structure to the outgoing queue.
637 static int process_response(association *assoc, request *req, Z_APDU *res)
639 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
640 if (!z_APDU(assoc->encode, &res, 0))
642 logf(LOG_WARN, "ODR error when encoding response: %s",
643 odr_errmsg(odr_geterror(assoc->decode)));
644 odr_reset(assoc->encode);
647 req->response = odr_getbuf(assoc->encode, &req->len_response,
648 &req->size_response);
649 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
650 odr_reset(assoc->encode);
651 if (assoc->print && !z_APDU(assoc->print, &res, 0))
653 logf(LOG_WARN, "ODR print error: %s",
654 odr_errmsg(odr_geterror(assoc->print)));
655 odr_reset(assoc->print);
657 /* change this when we make the backend reentrant */
658 if (req == request_head(&assoc->incoming))
660 req->state = REQUEST_IDLE;
661 request_deq(&assoc->incoming);
663 request_enq(&assoc->outgoing, req);
664 /* turn the work over to the ir_session handler */
665 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
666 /* Is there more work to be done? give that to the input handler too */
667 if (request_head(&assoc->incoming))
668 iochan_setevent(assoc->client_chan, EVENT_WORK);
673 * Handle init request.
674 * At the moment, we don't check the options
675 * anywhere else in the code - we just try not to do anything that would
676 * break a naive client. We'll toss 'em into the association block when
677 * we need them there.
679 static Z_APDU *process_initRequest(association *assoc, request *reqb)
681 Z_InitRequest *req = reqb->request->u.initRequest;
682 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
683 Z_InitResponse *resp = apdu->u.initResponse;
684 bend_initrequest binitreq;
685 bend_initresult *binitres;
688 logf(LOG_LOG, "Got initRequest");
689 if (req->implementationId)
690 logf(LOG_LOG, "Id: %s", req->implementationId);
691 if (req->implementationName)
692 logf(LOG_LOG, "Name: %s", req->implementationName);
693 if (req->implementationVersion)
694 logf(LOG_LOG, "Version: %s", req->implementationVersion);
696 binitreq.stream = assoc->encode;
697 binitreq.configname = "default-config";
698 binitreq.auth = req->idAuthentication;
699 binitreq.bend_sort = NULL;
700 if (!(binitres = bend_init(&binitreq)))
702 logf(LOG_WARN, "Bad response from backend.");
706 assoc->backend = binitres->handle;
707 if ((assoc->bend_sort = binitreq.bend_sort))
708 logf (LOG_DEBUG, "Sort handler installed");
709 resp->referenceId = req->referenceId;
711 /* let's tell the client what we can do */
712 if (ODR_MASK_GET(req->options, Z_Options_search))
714 ODR_MASK_SET(resp->options, Z_Options_search);
715 strcat(options, "srch");
717 if (ODR_MASK_GET(req->options, Z_Options_present))
719 ODR_MASK_SET(resp->options, Z_Options_present);
720 strcat(options, " prst");
723 if (ODR_MASK_GET(req->options, Z_Options_delSet))
725 ODR_MASK_SET(&options, Z_Options_delSet);
726 strcat(options, " del");
729 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
731 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
732 strcat(options, " namedresults");
734 if (ODR_MASK_GET(req->options, Z_Options_scan))
736 ODR_MASK_SET(resp->options, Z_Options_scan);
737 strcat(options, " scan");
739 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
741 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
742 strcat(options, " concurop");
744 if (ODR_MASK_GET(req->options, Z_Options_sort && binitreq.bend_sort))
746 ODR_MASK_SET(resp->options, Z_Options_sort);
747 strcat(options, " sort");
749 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
751 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
752 assoc->version = 2; /* 1 & 2 are equivalent */
754 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
756 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
759 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
761 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
764 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
765 assoc->maximumRecordSize = *req->maximumRecordSize;
766 if (assoc->maximumRecordSize > control_block->maxrecordsize)
767 assoc->maximumRecordSize = control_block->maxrecordsize;
768 assoc->preferredMessageSize = *req->preferredMessageSize;
769 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
770 assoc->preferredMessageSize = assoc->maximumRecordSize;
771 resp->preferredMessageSize = &assoc->preferredMessageSize;
772 resp->maximumRecordSize = &assoc->maximumRecordSize;
773 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
774 if (binitres->errcode)
776 logf(LOG_LOG, "Connection rejected by backend.");
778 assoc->state = ASSOC_DEAD;
781 assoc->state = ASSOC_UP;
786 * These functions should be merged.
790 * nonsurrogate diagnostic record.
792 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
795 Z_Records *rec = odr_malloc (assoc->encode, sizeof(*rec));
797 int *err = odr_malloc (assoc->encode, sizeof(*err));
798 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
799 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
801 bib1.proto = assoc->proto;
802 bib1.oclass = CLASS_DIAGSET;
803 bib1.value = VAL_BIB1;
805 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
808 rec->which = Z_Records_NSD;
810 rec->u.nonSurrogateDiagnostic = drec;
811 drec->which = Z_DiagRec_defaultFormat;
812 drec->u.defaultFormat = dr;
814 rec->u.nonSurrogateDiagnostic = dr;
816 dr->diagnosticSetId = odr_oiddup (assoc->encode,
817 oid_ent_to_oid(&bib1, oid));
819 dr->which = Z_DiagForm_v2AddInfo;
820 dr->addinfo = addinfo ? addinfo : "";
825 * surrogate diagnostic.
827 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
828 int error, char *addinfo)
831 Z_NamePlusRecord *rec = odr_malloc (assoc->encode, sizeof(*rec));
832 int *err = odr_malloc (assoc->encode, sizeof(*err));
834 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
835 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
837 bib1.proto = assoc->proto;
838 bib1.oclass = CLASS_DIAGSET;
839 bib1.value = VAL_BIB1;
841 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
843 rec->databaseName = dbname;
844 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
845 rec->u.surrogateDiagnostic = drec;
846 drec->which = Z_DiagRec_defaultFormat;
847 drec->u.defaultFormat = dr;
848 dr->diagnosticSetId = odr_oiddup (assoc->encode,
849 oid_ent_to_oid(&bib1, oid));
851 dr->which = Z_DiagForm_v2AddInfo;
852 dr->addinfo = addinfo ? addinfo : "";
857 * multiple nonsurrogate diagnostics.
859 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
862 Z_DiagRecs *recs = odr_malloc (assoc->encode, sizeof(*recs));
863 int *err = odr_malloc (assoc->encode, sizeof(*err));
865 Z_DiagRec **recp = odr_malloc (assoc->encode, sizeof(*recp));
866 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
867 Z_DefaultDiagFormat *rec = odr_malloc (assoc->encode, sizeof(*rec));
869 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
870 bib1.proto = assoc->proto;
871 bib1.oclass = CLASS_DIAGSET;
872 bib1.value = VAL_BIB1;
875 recs->num_diagRecs = 1;
876 recs->diagRecs = recp;
878 drec->which = Z_DiagRec_defaultFormat;
879 drec->u.defaultFormat = rec;
881 rec->diagnosticSetId = odr_oiddup (assoc->encode,
882 oid_ent_to_oid(&bib1, oid));
883 rec->condition = err;
884 rec->which = Z_DiagForm_v2AddInfo;
885 rec->addinfo = addinfo ? addinfo : "";
889 static Z_Records *pack_records(association *a, char *setname, int start,
890 int *num, Z_RecordComposition *comp,
891 int *next, int *pres, oid_value format)
894 int recno, total_length = 0, toget = *num, dumped_records = 0;
895 Z_Records *records = odr_malloc (a->encode, sizeof(*records));
896 Z_NamePlusRecordList *reclist = odr_malloc (a->encode, sizeof(*reclist));
897 Z_NamePlusRecord **list = odr_malloc (a->encode, sizeof(*list) * toget);
900 records->which = Z_Records_DBOSD;
901 records->u.databaseOrSurDiagnostics = reclist;
902 reclist->num_records = 0;
903 reclist->records = list;
904 *pres = Z_PRES_SUCCESS;
908 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
909 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
910 a->maximumRecordSize);
911 for (recno = start; reclist->num_records < toget; recno++)
913 bend_fetchrequest freq;
914 bend_fetchresult *fres;
915 Z_NamePlusRecord *thisrec;
916 Z_DatabaseRecord *thisext;
920 * we get the number of bytes allocated on the stream before any
921 * allocation done by the backend - this should give us a reasonable
922 * idea of the total size of the data so far.
924 total_length = odr_total(a->encode) - dumped_records;
925 freq.setname = setname;
928 freq.format = format;
929 freq.stream = a->encode;
930 if (!(fres = bend_fetch(a->backend, &freq, 0)))
932 *pres = Z_PRES_FAILURE;
933 return diagrec(a, 2, "Backend interface problem");
935 /* backend should be able to signal whether error is system-wide
936 or only pertaining to current record */
939 *pres = Z_PRES_FAILURE;
940 return diagrec(a, fres->errcode, fres->errstring);
943 this_length = fres->len;
945 this_length = odr_total(a->encode) - total_length;
946 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
947 this_length, total_length);
948 if (this_length + total_length > a->preferredMessageSize)
950 /* record is small enough, really */
951 if (this_length <= a->preferredMessageSize)
953 logf(LOG_DEBUG, " Dropped last normal-sized record");
954 *pres = Z_PRES_PARTIAL_2;
957 /* record can only be fetched by itself */
958 if (this_length < a->maximumRecordSize)
960 logf(LOG_DEBUG, " Record > prefmsgsz");
963 logf(LOG_DEBUG, " Dropped it");
964 reclist->records[reclist->num_records] =
965 surrogatediagrec(a, fres->basename, 16, 0);
966 reclist->num_records++;
967 *next = fres->last_in_set ? 0 : recno + 1;
968 dumped_records += this_length;
972 else /* too big entirely */
974 logf(LOG_DEBUG, "Record > maxrcdsz");
975 reclist->records[reclist->num_records] =
976 surrogatediagrec(a, fres->basename, 17, 0);
977 reclist->num_records++;
978 *next = fres->last_in_set ? 0 : recno + 1;
979 dumped_records += this_length;
983 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
985 if (!(thisrec->databaseName = odr_malloc(a->encode,
986 strlen(fres->basename) + 1)))
988 strcpy(thisrec->databaseName, fres->basename);
989 thisrec->which = Z_NamePlusRecord_databaseRecord;
990 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
991 sizeof(Z_DatabaseRecord))))
993 recform.proto = a->proto;
994 recform.oclass = CLASS_RECSYN;
995 recform.value = fres->format;
996 thisext->direct_reference = odr_oiddup(a->encode,
997 oid_ent_to_oid(&recform, oid));
998 thisext->indirect_reference = 0;
999 thisext->descriptor = 0;
1000 if (fres->len < 0) /* Structured data */
1002 switch (fres->format)
1004 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
1005 case VAL_GRS1: thisext->which = Z_External_grs1; break;
1006 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
1008 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
1009 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
1012 logf(LOG_FATAL, "Unknown structured format from backend.");
1017 * We cheat on the pointers here. Obviously, the record field
1018 * of the backend-fetch structure should have been a union for
1019 * correctness, but we're stuck with this for backwards
1022 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
1024 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
1026 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
1028 thisext->which = Z_External_sutrs;
1029 thisext->u.sutrs = sutrs;
1030 sutrs->buf = odr_malloc(a->encode, fres->len);
1031 sutrs->len = sutrs->size = fres->len;
1032 memcpy(sutrs->buf, fres->record, fres->len);
1034 else /* octet-aligned record. */
1036 thisext->which = Z_External_octet;
1037 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
1040 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1043 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1044 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1047 reclist->records[reclist->num_records] = thisrec;
1048 reclist->num_records++;
1049 *next = fres->last_in_set ? 0 : recno + 1;
1051 *num = reclist->num_records;
1055 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1058 Z_SearchRequest *req = reqb->request->u.searchRequest;
1059 bend_searchrequest bsrq;
1060 bend_searchresult *bsrt;
1062 logf(LOG_LOG, "Got SearchRequest.");
1064 bsrq.setname = req->resultSetName;
1065 bsrq.replace_set = *req->replaceIndicator;
1066 bsrq.num_bases = req->num_databaseNames;
1067 bsrq.basenames = req->databaseNames;
1068 bsrq.query = req->query;
1069 bsrq.stream = assoc->encode;
1071 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1073 return response_searchRequest(assoc, reqb, bsrt, fd);
1076 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1079 * Prepare a searchresponse based on the backend results. We probably want
1080 * to look at making the fetching of records nonblocking as well, but
1081 * so far, we'll keep things simple.
1082 * If bsrt is null, that means we're called in response to a communications
1083 * event, and we'll have to get the response for ourselves.
1085 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1086 bend_searchresult *bsrt, int *fd)
1088 Z_SearchRequest *req = reqb->request->u.searchRequest;
1089 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1090 Z_SearchResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1091 int *nulint = odr_malloc (assoc->encode, sizeof(*nulint));
1092 bool_t *sr = odr_malloc (assoc->encode, sizeof(*sr));
1093 int *next = odr_malloc (assoc->encode, sizeof(*next));
1094 int *none = odr_malloc (assoc->encode, sizeof(*none));
1101 apdu->which = Z_APDU_searchResponse;
1102 apdu->u.searchResponse = resp;
1103 resp->referenceId = req->referenceId;
1104 resp->additionalSearchInfo = 0;
1105 resp->otherInfo = 0;
1107 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1109 logf(LOG_FATAL, "Bad result from backend");
1112 else if (bsrt->errcode)
1114 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1115 resp->resultCount = nulint;
1116 resp->numberOfRecordsReturned = nulint;
1117 resp->nextResultSetPosition = nulint;
1118 resp->searchStatus = nulint;
1119 resp->resultSetStatus = none;
1120 resp->presentStatus = 0;
1124 int *toget = odr_malloc (assoc->encode, sizeof(*toget));
1125 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1126 Z_RecordComposition comp, *compp = 0;
1131 resp->resultCount = &bsrt->hits;
1133 comp.which = Z_RecordComp_simple;
1134 /* how many records does the user agent want, then? */
1135 if (bsrt->hits <= *req->smallSetUpperBound)
1137 *toget = bsrt->hits;
1138 if ((comp.u.simple = req->smallSetElementSetNames))
1141 else if (bsrt->hits < *req->largeSetLowerBound)
1143 *toget = *req->mediumSetPresentNumber;
1144 if (*toget > bsrt->hits)
1145 *toget = bsrt->hits;
1146 if ((comp.u.simple = req->mediumSetElementSetNames))
1152 if (*toget && !resp->records)
1157 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1158 prefformat->oclass != CLASS_RECSYN)
1161 form = prefformat->value;
1162 resp->records = pack_records(assoc, req->resultSetName, 1,
1163 toget, compp, next, presst, form);
1166 resp->numberOfRecordsReturned = toget;
1167 resp->nextResultSetPosition = next;
1168 resp->searchStatus = sr;
1169 resp->resultSetStatus = 0;
1170 resp->presentStatus = presst;
1174 if (*resp->resultCount)
1176 resp->numberOfRecordsReturned = nulint;
1177 resp->nextResultSetPosition = next;
1178 resp->searchStatus = sr;
1179 resp->resultSetStatus = 0;
1180 resp->presentStatus = 0;
1187 * Maybe we got a little over-friendly when we designed bend_fetch to
1188 * get only one record at a time. Some backends can optimise multiple-record
1189 * fetches, and at any rate, there is some overhead involved in
1190 * all that selecting and hopping around. Problem is, of course, that the
1191 * frontend can't know ahead of time how many records it'll need to
1192 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1193 * is downright lousy as a bulk data transfer protocol.
1195 * To start with, we'll do the fetching of records from the backend
1196 * in one operation: To save some trips in and out of the event-handler,
1197 * and to simplify the interface to pack_records. At any rate, asynch
1198 * operation is more fun in operations that have an unpredictable execution
1199 * speed - which is normally more true for search than for present.
1201 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1204 Z_PresentRequest *req = reqb->request->u.presentRequest;
1205 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1206 Z_PresentResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1207 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1208 int *next = odr_malloc (assoc->encode, sizeof(*next));
1209 int *num = odr_malloc (assoc->encode, sizeof(*num));
1213 logf(LOG_LOG, "Got PresentRequest.");
1218 apdu->which = Z_APDU_presentResponse;
1219 apdu->u.presentResponse = resp;
1220 resp->referenceId = req->referenceId;
1221 resp->otherInfo = 0;
1223 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1224 prefformat->oclass != CLASS_RECSYN)
1227 form = prefformat->value;
1228 *num = *req->numberOfRecordsRequested;
1229 resp->records = pack_records(assoc, req->resultSetId,
1230 *req->resultSetStartPoint, num, req->recordComposition, next,
1234 resp->numberOfRecordsReturned = num;
1235 resp->presentStatus = presst;
1236 resp->nextResultSetPosition = next;
1242 * Scan was implemented rather in a hurry, and with support for only the basic
1243 * elements of the service in the backend API. Suggestions are welcome.
1245 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1247 Z_ScanRequest *req = reqb->request->u.scanRequest;
1248 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1249 Z_ScanResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1250 int *scanStatus = odr_malloc (assoc->encode, sizeof(*scanStatus));
1251 int *numberOfEntriesReturned =
1252 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1253 Z_ListEntries *ents = odr_malloc (assoc->encode, sizeof(*ents));
1255 bend_scanrequest srq;
1256 bend_scanresult *srs;
1259 logf(LOG_LOG, "Got ScanRequest");
1260 *scanStatus = Z_Scan_failure;
1261 *numberOfEntriesReturned = 0;
1263 apdu->which = Z_APDU_scanResponse;
1264 apdu->u.scanResponse = res;
1265 res->referenceId = req->referenceId;
1267 res->scanStatus = scanStatus;
1268 res->numberOfEntriesReturned = numberOfEntriesReturned;
1269 res->positionOfTerm = 0;
1270 res->entries = ents;
1271 ents->which = Z_ListEntries_nonSurrogateDiagnostics;
1272 res->attributeSet = 0;
1275 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1276 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1277 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 121, 0);
1278 else if (req->stepSize && *req->stepSize > 0)
1279 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 205, 0);
1282 if (req->termListAndStartPoint->term->which == Z_Term_general)
1283 logf(LOG_DEBUG, " term: '%.*s'",
1284 req->termListAndStartPoint->term->u.general->len,
1285 req->termListAndStartPoint->term->u.general->buf);
1286 srq.num_bases = req->num_databaseNames;
1287 srq.basenames = req->databaseNames;
1288 srq.num_entries = *req->numberOfTermsRequested;
1289 srq.term = req->termListAndStartPoint;
1290 srq.stream = assoc->encode;
1291 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1292 attset->oclass != CLASS_RECSYN)
1293 srq.attributeset = VAL_NONE;
1295 srq.attributeset = attset->value;
1296 srq.term_position = req->preferredPositionInResponse ?
1297 *req->preferredPositionInResponse : 1;
1298 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1299 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 2, 0);
1300 else if (srs->errcode)
1301 ents->u.nonSurrogateDiagnostics = diagrecs(assoc,
1302 srs->errcode, srs->errstring);
1306 Z_Entries *list = odr_malloc (assoc->encode, sizeof(*list));
1307 Z_Entry **tab = odr_malloc (assoc->encode,
1308 sizeof(*tab) * srs->num_entries);
1310 if (srs->status == BEND_SCAN_PARTIAL)
1311 *scanStatus = Z_Scan_partial_5;
1313 *scanStatus = Z_Scan_success;
1314 ents->which = Z_ListEntries_entries;
1315 ents->u.entries = list;
1316 list->entries = tab;
1317 for (i = 0; i < srs->num_entries; i++)
1323 list->entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1324 e->which = Z_Entry_termInfo;
1325 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1326 t->suggestedAttributes = 0;
1328 t->alternativeTerm = 0;
1329 t->byAttributes = 0;
1330 t->otherTermInfo = 0;
1331 t->globalOccurrences = &srs->entries[i].occurrences;
1332 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1333 t->term->which = Z_Term_general;
1334 t->term->u.general = o = odr_malloc(assoc->encode,
1336 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1337 strlen(srs->entries[i].term));
1338 memcpy(o->buf, srs->entries[i].term, o->len);
1339 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1340 srs->entries[i].term, srs->entries[i].occurrences);
1342 list->num_entries = i;
1343 res->numberOfEntriesReturned = &list->num_entries;
1344 res->positionOfTerm = &srs->term_position;
1351 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1354 Z_SortRequest *req = reqb->request->u.sortRequest;
1355 Z_SortResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1356 bend_sortrequest bsrq;
1357 bend_sortresult *bsrt;
1358 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1360 logf(LOG_LOG, "Got SortRequest.");
1362 bsrq.num_input_setnames = req->inputResultSetNames->num_strings;
1363 bsrq.input_setnames = req->inputResultSetNames->strings;
1364 bsrq.output_setname = req->sortedResultSetName;
1365 bsrq.sort_sequence = req->sortSequence;
1366 bsrq.stream = assoc->encode;
1368 bsrt = odr_malloc (assoc->encode, sizeof(*bsrt));
1369 bsrt->sort_status = Z_SortStatus_failure;
1371 bsrt->errstring = 0;
1373 (*assoc->bend_sort)(assoc->backend, &bsrq, bsrt);
1375 res->referenceId = req->referenceId;
1376 res->sortStatus = odr_malloc (assoc->encode, sizeof(*res->sortStatus));
1377 *res->sortStatus = bsrt->sort_status;
1378 res->resultSetStatus = 0;
1380 res->diagnostics = diagrecs(assoc, bsrt->errcode, bsrt->errstring);
1383 apdu->which = Z_APDU_sortResponse;
1384 apdu->u.sortResponse = res;
1388 static void process_close(association *assoc, request *reqb)
1390 Z_Close *req = reqb->request->u.close;
1391 static char *reasons[] =
1398 "securityViolation",
1405 logf(LOG_LOG, "Got Close, reason %s, message %s",
1406 reasons[*req->closeReason], req->diagnosticInformation ?
1407 req->diagnosticInformation : "NULL");
1408 if (assoc->version < 3) /* to make do_force respond with close */
1410 do_close(assoc, Z_Close_finished, "Association terminated by client");