2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.68 1997-09-29 13:18:59 adam
8 * Added function, oid_ent_to_oid, to replace the function
9 * oid_getoidbyent, which is not thread safe.
11 * Revision 1.67 1997/09/17 12:10:40 adam
14 * Revision 1.66 1997/09/05 15:26:44 adam
15 * Added ODR encode in search and scen bend request structures.
16 * Fixed a few enums that caused trouble with C++.
18 * Revision 1.65 1997/09/01 08:53:01 adam
19 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
20 * moved a separate directory. MSV5.0 project server.dsp created.
21 * As an option, the server can now operate as an NT service.
23 * Revision 1.64 1997/04/30 08:52:11 quinn
26 * Revision 1.63 1996/10/11 11:57:26 quinn
29 * Revision 1.62 1996/07/06 19:58:35 quinn
30 * System headerfiles gathered in yconfig
32 * Revision 1.61 1996/06/10 08:56:16 quinn
35 * Revision 1.60 1996/05/30 11:03:10 quinn
36 * Fixed NextresultSetPosition bug fixed.
38 * Revision 1.59 1996/05/14 09:26:46 quinn
39 * Added attribute set to scan backend
41 * Revision 1.58 1996/02/20 12:53:04 quinn
44 * Revision 1.57 1996/01/02 08:57:47 quinn
45 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
47 * Revision 1.56 1995/12/14 11:09:57 quinn
50 * Revision 1.55 1995/11/08 17:41:37 quinn
53 * Revision 1.54 1995/11/08 15:11:29 quinn
54 * Log of close transmit.
56 * Revision 1.53 1995/11/01 13:54:58 quinn
59 * Revision 1.52 1995/11/01 12:19:13 quinn
60 * Second attempt to fix same bug.
62 * Revision 1.50 1995/10/25 16:58:32 quinn
65 * Revision 1.49 1995/10/16 13:51:53 quinn
66 * Changes to provide Especs to the backend.
68 * Revision 1.48 1995/10/06 08:51:20 quinn
71 * Revision 1.47 1995/08/29 14:24:16 quinn
72 * Added second half of close-handshake
74 * Revision 1.46 1995/08/29 11:17:58 quinn
75 * Added code to receive close
77 * Revision 1.45 1995/08/21 09:11:00 quinn
78 * Smallish fixes to suppport new formats.
80 * Revision 1.44 1995/08/17 12:45:25 quinn
81 * Fixed minor problems with GRS-1. Added support in c&s.
83 * Revision 1.43 1995/08/15 12:00:31 quinn
86 * Revision 1.42 1995/08/15 11:16:50 quinn
88 * Revision 1.41 1995/08/02 10:23:06 quinn
91 * Revision 1.40 1995/07/31 14:34:26 quinn
92 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
94 * Revision 1.39 1995/06/27 13:21:00 quinn
97 * Revision 1.38 1995/06/19 12:39:11 quinn
98 * Fixed bug in timeout code. Added BER dumper.
100 * Revision 1.37 1995/06/16 13:16:14 quinn
101 * Fixed Defaultdiagformat.
103 * Revision 1.36 1995/06/16 10:31:36 quinn
104 * Added session timeout.
106 * Revision 1.35 1995/06/15 07:45:14 quinn
109 * Revision 1.34 1995/06/14 15:26:46 quinn
110 * *** empty log message ***
112 * Revision 1.33 1995/06/06 14:57:05 quinn
113 * Better diagnostics.
115 * Revision 1.32 1995/06/06 08:41:44 quinn
116 * Better diagnostics.
118 * Revision 1.31 1995/06/06 08:15:37 quinn
121 * Revision 1.30 1995/06/05 10:53:32 quinn
122 * Added a better SCAN.
124 * Revision 1.29 1995/06/01 11:25:03 quinn
127 * Revision 1.28 1995/06/01 11:21:01 quinn
128 * Attempting to fix a bug in pack-records. replaced break with continue
129 * for large records, according to standard.
131 * Revision 1.27 1995/05/29 08:12:06 quinn
134 * Revision 1.26 1995/05/18 13:02:12 quinn
137 * Revision 1.25 1995/05/17 08:42:26 quinn
138 * Transfer auth info to backend. Allow backend to reject init gracefully.
140 * Revision 1.24 1995/05/16 08:51:04 quinn
141 * License, documentation, and memory fixes
143 * Revision 1.23 1995/05/15 13:25:10 quinn
146 * Revision 1.22 1995/05/15 11:56:39 quinn
147 * Asynchronous facilities. Restructuring of seshigh code.
149 * Revision 1.21 1995/05/02 08:53:19 quinn
150 * Trying in vain to fix comm with ISODE
152 * Revision 1.20 1995/04/20 15:13:00 quinn
155 * Revision 1.19 1995/04/18 08:15:34 quinn
156 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
157 * neater. We'll make the same change for decoding one day.
159 * Revision 1.18 1995/04/17 11:28:25 quinn
162 * Revision 1.17 1995/04/10 10:23:36 quinn
163 * Some work to add scan and other things.
165 * Revision 1.16 1995/03/31 09:18:55 quinn
168 * Revision 1.15 1995/03/30 14:03:23 quinn
169 * Added RFC1006 as separate library
171 * Revision 1.14 1995/03/30 12:18:17 quinn
174 * Revision 1.13 1995/03/30 09:09:24 quinn
175 * Added state-handle and some support for asynchronous activities.
177 * Revision 1.12 1995/03/29 15:40:16 quinn
178 * Ongoing work. Statserv is now dynamic by default
180 * Revision 1.11 1995/03/28 09:16:21 quinn
181 * Added record packing to the search request
183 * Revision 1.10 1995/03/27 08:34:24 quinn
184 * Added dynamic server functionality.
185 * Released bindings to session.c (is now redundant)
187 * Revision 1.9 1995/03/22 15:01:26 quinn
188 * Adjusting record packing.
190 * Revision 1.8 1995/03/22 10:13:21 quinn
191 * Working on record packer
193 * Revision 1.7 1995/03/21 15:53:31 quinn
196 * Revision 1.6 1995/03/21 12:30:09 quinn
197 * Beginning to add support for record packing.
199 * Revision 1.5 1995/03/17 10:44:13 quinn
200 * Added catch of null-string in makediagrec
202 * Revision 1.4 1995/03/17 10:18:08 quinn
203 * Added memory management.
205 * Revision 1.3 1995/03/16 17:42:39 quinn
208 * Revision 1.2 1995/03/16 13:29:01 quinn
209 * Partitioned server.
211 * Revision 1.1 1995/03/15 16:02:10 quinn
212 * Modded session.c to seshigh.c
217 * Frontend server logic.
219 * This code receives incoming APDUs, and handles client requests by means
220 * of the backend API.
222 * Some of the code is getting quite involved, compared to simpler servers -
223 * primarily because it is asynchronous both in the communication with
224 * the user and the backend. We think the complexity will pay off in
225 * the form of greater flexibility when more asynchronous facilities
228 * Memory management has become somewhat involved. In the simple case, where
229 * only one PDU is pending at a time, it will simply reuse the same memory,
230 * once it has found its working size. When we enable multiple concurrent
231 * operations, perhaps even with multiple parallel calls to the backend, it
232 * will maintain a pool of buffers for encoding and decoding, trying to
233 * minimize memory allocation/deallocation during normal operation.
235 * TODOs include (and will be done in order of public interest):
237 * Support for EXPLAIN - provide simple meta-database system.
238 * Support for access control.
239 * Support for resource control.
240 * Support for extended services - primarily Item Order.
241 * Rest of Z39.50-1994
256 #include <comstack.h>
262 #include <statserv.h>
266 static int process_request(association *assoc);
267 void backend_response(IOCHAN i, int event);
268 static int process_response(association *assoc, request *req, Z_APDU *res);
269 static Z_APDU *process_initRequest(association *assoc, request *reqb);
270 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
272 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
273 bend_searchresult *bsrt, int *fd);
274 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
276 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
277 static void process_close(association *assoc, request *reqb);
279 static FILE *apduf = 0; /* for use in static mode */
280 static statserv_options_block *control_block = 0;
283 * Create and initialize a new association-handle.
284 * channel : iochannel for the current line.
285 * link : communications channel.
286 * Returns: 0 or a new association handle.
288 association *create_association(IOCHAN channel, COMSTACK link)
293 control_block = statserv_getcontrol();
294 if (!(new = xmalloc(sizeof(*new))))
296 new->client_chan = channel;
297 new->client_link = link;
298 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
299 !(new->encode = odr_createmem(ODR_ENCODE)))
301 if (*control_block->apdufile)
306 strcpy(filename, control_block->apdufile);
307 if (!(new->print = odr_createmem(ODR_PRINT)))
309 if (*control_block->apdufile != '-')
311 strcpy(filename, control_block->apdufile);
312 if (!control_block->dynamic)
316 if (!(apduf = fopen(filename, "w")))
318 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
321 setvbuf(apduf, 0, _IONBF, 0);
327 sprintf(filename + strlen(filename), ".%d", getpid());
328 if (!(f = fopen(filename, "w")))
330 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
333 setvbuf(f, 0, _IONBF, 0);
335 odr_setprint(new->print, f);
340 new->input_buffer = 0;
341 new->input_buffer_len = 0;
343 new->state = ASSOC_NEW;
344 request_initq(&new->incoming);
345 request_initq(&new->outgoing);
346 new->proto = cs_getproto(link);
351 * Free association and release resources.
353 void destroy_association(association *h)
355 odr_destroy(h->decode);
356 odr_destroy(h->encode);
358 odr_destroy(h->print);
360 xfree(h->input_buffer);
362 bend_close(h->backend);
363 while (request_deq(&h->incoming));
364 while (request_deq(&h->outgoing));
365 request_delq(&h->incoming);
366 request_delq(&h->outgoing);
370 static void do_close(association *a, int reason, char *message)
373 Z_Close *cls = zget_Close(a->encode);
374 request *req = request_get(&a->outgoing);
376 /* Purge request queue */
377 while (request_deq(&a->incoming));
378 while (request_deq(&a->outgoing));
381 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
382 reason, message ? message : "none");
383 apdu.which = Z_APDU_close;
385 *cls->closeReason = reason;
386 cls->diagnosticInformation = message;
387 process_response(a, req, &apdu);
388 iochan_settimeout(a->client_chan, 60);
392 logf(LOG_DEBUG, "v2 client. No Close PDU");
393 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
395 a->state = ASSOC_DEAD;
399 * This is where PDUs from the client are read and the further
400 * processing is initiated. Flow of control moves down through the
401 * various process_* functions below, until the encoded result comes back up
402 * to the output handler in here.
404 * h : the I/O channel that has an outstanding event.
405 * event : the current outstanding event.
407 void ir_session(IOCHAN h, int event)
410 association *assoc = iochan_getdata(h);
411 COMSTACK conn = assoc->client_link;
414 assert(h && conn && assoc);
415 if (event == EVENT_TIMEOUT)
417 if (assoc->state != ASSOC_UP)
419 logf(LOG_LOG, "Final timeout - closing connection.");
421 destroy_association(assoc);
426 logf(LOG_LOG, "Session idle too long. Sending close.");
427 do_close(assoc, Z_Close_lackOfActivity, 0);
431 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
433 if (event & EVENT_INPUT)
435 logf(LOG_DEBUG, "ir_session (input)");
436 assert(assoc && conn);
437 /* We aren't speaking to this fellow */
438 if (assoc->state == ASSOC_DEAD)
440 logf(LOG_LOG, "Closed connection after reject");
442 destroy_association(assoc);
446 if ((res = cs_get(conn, &assoc->input_buffer,
447 &assoc->input_buffer_len)) <= 0)
449 logf(LOG_LOG, "Connection closed by client");
451 destroy_association(assoc);
455 else if (res == 1) /* incomplete read - wait for more */
457 if (cs_more(conn)) /* more stuff - call us again later, please */
458 iochan_setevent(h, EVENT_INPUT);
460 /* we got a complete PDU. Let's decode it */
461 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
462 req = request_get(&assoc->incoming); /* get a new request structure */
463 odr_reset(assoc->decode);
464 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
465 if (!z_APDU(assoc->decode, &req->request, 0))
467 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
468 odr_errmsg(odr_geterror(assoc->decode)),
469 odr_offset(assoc->decode));
470 logf(LOG_LOG, "PDU dump:");
471 odr_dumpBER(log_file(), assoc->input_buffer, res);
472 do_close(assoc, Z_Close_protocolError, "Malformed package");
475 req->request_mem = odr_extract_mem(assoc->decode);
476 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
478 logf(LOG_WARN, "ODR print error: %s",
479 odr_errmsg(odr_geterror(assoc->print)));
480 odr_reset(assoc->print);
482 request_enq(&assoc->incoming, req);
485 /* can we do something yet? */
486 req = request_head(&assoc->incoming);
487 if (req->state == REQUEST_IDLE)
488 if (process_request(assoc) < 0)
489 do_close(assoc, Z_Close_systemProblem, "Unknown error");
491 if (event & EVENT_OUTPUT)
493 request *req = request_head(&assoc->outgoing);
495 logf(LOG_DEBUG, "ir_session (output)");
496 req->state = REQUEST_PENDING;
497 switch (res = cs_put(conn, req->response, req->len_response))
500 logf(LOG_LOG, "Connection closed by client");
502 destroy_association(assoc);
505 case 0: /* all sent - release the request structure */
506 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
507 nmem_destroy(req->request_mem);
508 request_deq(&assoc->outgoing);
509 request_release(req);
510 if (!request_head(&assoc->outgoing))
511 iochan_clearflag(h, EVENT_OUTPUT);
513 /* value of 1 -- partial send -- is simply ignored */
516 if (event & EVENT_EXCEPT)
518 logf(LOG_DEBUG, "ir_session (exception)");
520 destroy_association(assoc);
526 * Initiate request processing.
528 static int process_request(association *assoc)
530 request *req = request_head(&assoc->incoming);
534 logf(LOG_DEBUG, "process_request");
535 assert(req && req->state == REQUEST_IDLE);
536 switch (req->request->which)
538 case Z_APDU_initRequest:
539 res = process_initRequest(assoc, req); break;
540 case Z_APDU_searchRequest:
541 res = process_searchRequest(assoc, req, &fd); break;
542 case Z_APDU_presentRequest:
543 res = process_presentRequest(assoc, req, &fd); break;
544 case Z_APDU_scanRequest:
545 res = process_scanRequest(assoc, req, &fd); break;
547 process_close(assoc, req); return 0;
549 logf(LOG_WARN, "Bad APDU received");
554 logf(LOG_DEBUG, " result immediately available");
555 return process_response(assoc, req, res);
559 logf(LOG_WARN, " bad result");
562 else /* no result yet - one will be provided later */
566 /* Set up an I/O handler for the fd supplied by the backend */
568 logf(LOG_DEBUG, " establishing handler for result");
569 req->state = REQUEST_PENDING;
570 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
572 iochan_setdata(chan, assoc);
578 * Handle message from the backend.
580 void backend_response(IOCHAN i, int event)
582 association *assoc = iochan_getdata(i);
583 request *req = request_head(&assoc->incoming);
587 logf(LOG_DEBUG, "backend_response");
588 assert(assoc && req && req->state != REQUEST_IDLE);
589 /* determine what it is we're waiting for */
590 switch (req->request->which)
592 case Z_APDU_searchRequest:
593 res = response_searchRequest(assoc, req, 0, &fd); break;
595 case Z_APDU_presentRequest:
596 res = response_presentRequest(assoc, req, 0, &fd); break;
597 case Z_APDU_scanRequest:
598 res = response_scanRequest(assoc, req, 0, &fd); break;
601 logf(LOG_WARN, "Serious programmer's lapse or bug");
604 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
606 logf(LOG_LOG, "Fatal error when talking to backend");
607 do_close(assoc, Z_Close_systemProblem, 0);
611 else if (!res) /* no result yet - try again later */
613 logf(LOG_DEBUG, " no result yet");
614 iochan_setfd(i, fd); /* in case fd has changed */
619 * Encode response, and transfer the request structure to the outgoing queue.
621 static int process_response(association *assoc, request *req, Z_APDU *res)
623 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
624 if (!z_APDU(assoc->encode, &res, 0))
626 logf(LOG_WARN, "ODR error when encoding response: %s",
627 odr_errmsg(odr_geterror(assoc->decode)));
628 odr_reset(assoc->encode);
631 req->response = odr_getbuf(assoc->encode, &req->len_response,
632 &req->size_response);
633 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
634 odr_reset(assoc->encode);
635 if (assoc->print && !z_APDU(assoc->print, &res, 0))
637 logf(LOG_WARN, "ODR print error: %s",
638 odr_errmsg(odr_geterror(assoc->print)));
639 odr_reset(assoc->print);
641 /* change this when we make the backend reentrant */
642 if (req == request_head(&assoc->incoming))
644 req->state = REQUEST_IDLE;
645 request_deq(&assoc->incoming);
647 request_enq(&assoc->outgoing, req);
648 /* turn the work over to the ir_session handler */
649 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
650 /* Is there more work to be done? give that to the input handler too */
651 if (request_head(&assoc->incoming))
652 iochan_setevent(assoc->client_chan, EVENT_WORK);
657 * Handle init request.
658 * At the moment, we don't check the options
659 * anywhere else in the code - we just try not to do anything that would
660 * break a naive client. We'll toss 'em into the association block when
661 * we need them there.
663 static Z_APDU *process_initRequest(association *assoc, request *reqb)
665 Z_InitRequest *req = reqb->request->u.initRequest;
666 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
667 Z_InitResponse *resp = apdu->u.initResponse;
668 bend_initrequest binitreq;
669 bend_initresult *binitres;
672 logf(LOG_LOG, "Got initRequest");
673 if (req->implementationId)
674 logf(LOG_LOG, "Id: %s", req->implementationId);
675 if (req->implementationName)
676 logf(LOG_LOG, "Name: %s", req->implementationName);
677 if (req->implementationVersion)
678 logf(LOG_LOG, "Version: %s", req->implementationVersion);
680 binitreq.stream = assoc->encode;
681 binitreq.configname = "default-config";
682 binitreq.auth = req->idAuthentication;
683 if (!(binitres = bend_init(&binitreq)))
685 logf(LOG_WARN, "Bad response from backend.");
689 assoc->backend = binitres->handle;
690 resp->referenceId = req->referenceId;
692 /* let's tell the client what we can do */
693 if (ODR_MASK_GET(req->options, Z_Options_search))
695 ODR_MASK_SET(resp->options, Z_Options_search);
696 strcat(options, "srch");
698 if (ODR_MASK_GET(req->options, Z_Options_present))
700 ODR_MASK_SET(resp->options, Z_Options_present);
701 strcat(options, " prst");
704 if (ODR_MASK_GET(req->options, Z_Options_delSet))
706 ODR_MASK_SET(&options, Z_Options_delSet);
707 strcat(options, " del");
710 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
712 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
713 strcat(options, " namedresults");
715 if (ODR_MASK_GET(req->options, Z_Options_scan))
717 ODR_MASK_SET(resp->options, Z_Options_scan);
718 strcat(options, " scan");
720 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
722 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
723 strcat(options, " concurop");
726 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
728 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
729 assoc->version = 2; /* 1 & 2 are equivalent */
731 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
733 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
736 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
738 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
741 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
742 assoc->maximumRecordSize = *req->maximumRecordSize;
743 if (assoc->maximumRecordSize > control_block->maxrecordsize)
744 assoc->maximumRecordSize = control_block->maxrecordsize;
745 assoc->preferredMessageSize = *req->preferredMessageSize;
746 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
747 assoc->preferredMessageSize = assoc->maximumRecordSize;
748 resp->preferredMessageSize = &assoc->preferredMessageSize;
749 resp->maximumRecordSize = &assoc->maximumRecordSize;
750 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
751 if (binitres->errcode)
753 logf(LOG_LOG, "Connection rejected by backend.");
755 assoc->state = ASSOC_DEAD;
758 assoc->state = ASSOC_UP;
763 * These functions should be merged.
767 * nonsurrogate diagnostic record.
769 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
772 Z_Records *rec = odr_malloc (assoc->encode, sizeof(*rec));
774 int *err = odr_malloc (assoc->encode, sizeof(*err));
775 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
776 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
778 bib1.proto = assoc->proto;
779 bib1.oclass = CLASS_DIAGSET;
780 bib1.value = VAL_BIB1;
782 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
785 rec->which = Z_Records_NSD;
787 rec->u.nonSurrogateDiagnostic = drec;
788 drec->which = Z_DiagRec_defaultFormat;
789 drec->u.defaultFormat = dr;
791 rec->u.nonSurrogateDiagnostic = dr;
793 dr->diagnosticSetId = oid_ent_to_oid(&bib1, oid);
795 dr->which = Z_DiagForm_v2AddInfo;
796 dr->addinfo = addinfo ? addinfo : "";
801 * surrogate diagnostic.
803 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
804 int error, char *addinfo)
807 Z_NamePlusRecord *rec = odr_malloc (assoc->encode, sizeof(*rec));
808 int *err = odr_malloc (assoc->encode, sizeof(*err));
810 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
811 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
813 bib1.proto = assoc->proto;
814 bib1.oclass = CLASS_DIAGSET;
815 bib1.value = VAL_BIB1;
817 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
819 rec->databaseName = dbname;
820 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
821 rec->u.surrogateDiagnostic = drec;
822 drec->which = Z_DiagRec_defaultFormat;
823 drec->u.defaultFormat = dr;
824 dr->diagnosticSetId = oid_ent_to_oid(&bib1, oid);
826 dr->which = Z_DiagForm_v2AddInfo;
827 dr->addinfo = addinfo ? addinfo : "";
832 * multiple nonsurrogate diagnostics.
834 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
837 Z_DiagRecs *recs = odr_malloc (assoc->encode, sizeof(*recs));
838 int *err = odr_malloc (assoc->encode, sizeof(*err));
840 Z_DiagRec **recp = odr_malloc (assoc->encode, sizeof(*recp));
841 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
842 Z_DefaultDiagFormat *rec = odr_malloc (assoc->encode, sizeof(*rec));
844 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
845 bib1.proto = assoc->proto;
846 bib1.oclass = CLASS_DIAGSET;
847 bib1.value = VAL_BIB1;
850 recs->num_diagRecs = 1;
851 recs->diagRecs = recp;
853 drec->which = Z_DiagRec_defaultFormat;
854 drec->u.defaultFormat = rec;
856 rec->diagnosticSetId = oid_ent_to_oid(&bib1, oid);
857 rec->condition = err;
858 rec->which = Z_DiagForm_v2AddInfo;
859 rec->addinfo = addinfo ? addinfo : "";
863 static Z_Records *pack_records(association *a, char *setname, int start,
864 int *num, Z_RecordComposition *comp,
865 int *next, int *pres, oid_value format)
868 int recno, total_length = 0, toget = *num, dumped_records = 0;
869 Z_Records *records = odr_malloc (a->encode, sizeof(*records));
870 Z_NamePlusRecordList *reclist = odr_malloc (a->encode, sizeof(*reclist));
871 Z_NamePlusRecord **list = odr_malloc (a->encode, sizeof(*list) * toget);
874 records->which = Z_Records_DBOSD;
875 records->u.databaseOrSurDiagnostics = reclist;
876 reclist->num_records = 0;
877 reclist->records = list;
878 *pres = Z_PRES_SUCCESS;
882 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
883 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
884 a->maximumRecordSize);
885 for (recno = start; reclist->num_records < toget; recno++)
887 bend_fetchrequest freq;
888 bend_fetchresult *fres;
889 Z_NamePlusRecord *thisrec;
890 Z_DatabaseRecord *thisext;
894 * we get the number of bytes allocated on the stream before any
895 * allocation done by the backend - this should give us a reasonable
896 * idea of the total size of the data so far.
898 total_length = odr_total(a->encode) - dumped_records;
899 freq.setname = setname;
902 freq.format = format;
903 freq.stream = a->encode;
904 if (!(fres = bend_fetch(a->backend, &freq, 0)))
906 *pres = Z_PRES_FAILURE;
907 return diagrec(a, 2, "Backend interface problem");
909 /* backend should be able to signal whether error is system-wide
910 or only pertaining to current record */
913 *pres = Z_PRES_FAILURE;
914 return diagrec(a, fres->errcode, fres->errstring);
917 this_length = fres->len;
919 this_length = odr_total(a->encode) - total_length;
920 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
921 this_length, total_length);
922 if (this_length + total_length > a->preferredMessageSize)
924 /* record is small enough, really */
925 if (this_length <= a->preferredMessageSize)
927 logf(LOG_DEBUG, " Dropped last normal-sized record");
928 *pres = Z_PRES_PARTIAL_2;
931 /* record can only be fetched by itself */
932 if (this_length < a->maximumRecordSize)
934 logf(LOG_DEBUG, " Record > prefmsgsz");
937 logf(LOG_DEBUG, " Dropped it");
938 reclist->records[reclist->num_records] =
939 surrogatediagrec(a, fres->basename, 16, 0);
940 reclist->num_records++;
941 *next = fres->last_in_set ? 0 : recno + 1;
942 dumped_records += this_length;
946 else /* too big entirely */
948 logf(LOG_DEBUG, "Record > maxrcdsz");
949 reclist->records[reclist->num_records] =
950 surrogatediagrec(a, fres->basename, 17, 0);
951 reclist->num_records++;
952 *next = fres->last_in_set ? 0 : recno + 1;
953 dumped_records += this_length;
957 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
959 if (!(thisrec->databaseName = odr_malloc(a->encode,
960 strlen(fres->basename) + 1)))
962 strcpy(thisrec->databaseName, fres->basename);
963 thisrec->which = Z_NamePlusRecord_databaseRecord;
964 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
965 sizeof(Z_DatabaseRecord))))
967 recform.proto = a->proto;
968 recform.oclass = CLASS_RECSYN;
969 recform.value = fres->format;
970 thisext->direct_reference = odr_oiddup(a->encode,
971 oid_ent_to_oid(&recform, oid));
972 thisext->indirect_reference = 0;
973 thisext->descriptor = 0;
974 if (fres->len < 0) /* Structured data */
976 switch (fres->format)
978 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
979 case VAL_GRS1: thisext->which = Z_External_grs1; break;
980 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
982 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
983 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
986 logf(LOG_FATAL, "Unknown structured format from backend.");
991 * We cheat on the pointers here. Obviously, the record field
992 * of the backend-fetch structure should have been a union for
993 * correctness, but we're stuck with this for backwards
996 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
998 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
1000 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
1002 thisext->which = Z_External_sutrs;
1003 thisext->u.sutrs = sutrs;
1004 sutrs->buf = odr_malloc(a->encode, fres->len);
1005 sutrs->len = sutrs->size = fres->len;
1006 memcpy(sutrs->buf, fres->record, fres->len);
1008 else /* octet-aligned record. */
1010 thisext->which = Z_External_octet;
1011 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
1014 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1017 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1018 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1021 reclist->records[reclist->num_records] = thisrec;
1022 reclist->num_records++;
1023 *next = fres->last_in_set ? 0 : recno + 1;
1025 *num = reclist->num_records;
1029 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1032 Z_SearchRequest *req = reqb->request->u.searchRequest;
1033 bend_searchrequest bsrq;
1034 bend_searchresult *bsrt;
1036 logf(LOG_LOG, "Got SearchRequest.");
1038 bsrq.setname = req->resultSetName;
1039 bsrq.replace_set = *req->replaceIndicator;
1040 bsrq.num_bases = req->num_databaseNames;
1041 bsrq.basenames = req->databaseNames;
1042 bsrq.query = req->query;
1043 bsrq.stream = assoc->encode;
1045 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1047 return response_searchRequest(assoc, reqb, bsrt, fd);
1050 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1053 * Prepare a searchresponse based on the backend results. We probably want
1054 * to look at making the fetching of records nonblocking as well, but
1055 * so far, we'll keep things simple.
1056 * If bsrt is null, that means we're called in response to a communications
1057 * event, and we'll have to get the response for ourselves.
1059 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1060 bend_searchresult *bsrt, int *fd)
1062 Z_SearchRequest *req = reqb->request->u.searchRequest;
1063 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1064 Z_SearchResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1065 int *nulint = odr_malloc (assoc->encode, sizeof(*nulint));
1066 bool_t *sr = odr_malloc (assoc->encode, sizeof(*sr));
1067 int *next = odr_malloc (assoc->encode, sizeof(*next));
1068 int *none = odr_malloc (assoc->encode, sizeof(*none));
1075 apdu->which = Z_APDU_searchResponse;
1076 apdu->u.searchResponse = resp;
1077 resp->referenceId = req->referenceId;
1078 resp->additionalSearchInfo = 0;
1079 resp->otherInfo = 0;
1081 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1083 logf(LOG_FATAL, "Bad result from backend");
1086 else if (bsrt->errcode)
1088 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1089 resp->resultCount = nulint;
1090 resp->numberOfRecordsReturned = nulint;
1091 resp->nextResultSetPosition = nulint;
1092 resp->searchStatus = nulint;
1093 resp->resultSetStatus = none;
1094 resp->presentStatus = 0;
1098 int *toget = odr_malloc (assoc->encode, sizeof(*toget));
1099 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1100 Z_RecordComposition comp, *compp = 0;
1105 resp->resultCount = &bsrt->hits;
1107 comp.which = Z_RecordComp_simple;
1108 /* how many records does the user agent want, then? */
1109 if (bsrt->hits <= *req->smallSetUpperBound)
1111 *toget = bsrt->hits;
1112 if ((comp.u.simple = req->smallSetElementSetNames))
1115 else if (bsrt->hits < *req->largeSetLowerBound)
1117 *toget = *req->mediumSetPresentNumber;
1118 if (*toget > bsrt->hits)
1119 *toget = bsrt->hits;
1120 if ((comp.u.simple = req->mediumSetElementSetNames))
1126 if (*toget && !resp->records)
1131 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1132 prefformat->oclass != CLASS_RECSYN)
1135 form = prefformat->value;
1136 resp->records = pack_records(assoc, req->resultSetName, 1,
1137 toget, compp, next, presst, form);
1140 resp->numberOfRecordsReturned = toget;
1141 resp->nextResultSetPosition = next;
1142 resp->searchStatus = sr;
1143 resp->resultSetStatus = 0;
1144 resp->presentStatus = presst;
1148 if (*resp->resultCount)
1150 resp->numberOfRecordsReturned = nulint;
1151 resp->nextResultSetPosition = next;
1152 resp->searchStatus = sr;
1153 resp->resultSetStatus = 0;
1154 resp->presentStatus = 0;
1161 * Maybe we got a little over-friendly when we designed bend_fetch to
1162 * get only one record at a time. Some backends can optimise multiple-record
1163 * fetches, and at any rate, there is some overhead involved in
1164 * all that selecting and hopping around. Problem is, of course, that the
1165 * frontend can't know ahead of time how many records it'll need to
1166 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1167 * is downright lousy as a bulk data transfer protocol.
1169 * To start with, we'll do the fetching of records from the backend
1170 * in one operation: To save some trips in and out of the event-handler,
1171 * and to simplify the interface to pack_records. At any rate, asynch
1172 * operation is more fun in operations that have an unpredictable execution
1173 * speed - which is normally more true for search than for present.
1175 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1178 Z_PresentRequest *req = reqb->request->u.presentRequest;
1179 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1180 Z_PresentResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1181 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1182 int *next = odr_malloc (assoc->encode, sizeof(*next));
1183 int *num = odr_malloc (assoc->encode, sizeof(*num));
1187 logf(LOG_LOG, "Got PresentRequest.");
1192 apdu->which = Z_APDU_presentResponse;
1193 apdu->u.presentResponse = resp;
1194 resp->referenceId = req->referenceId;
1195 resp->otherInfo = 0;
1197 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1198 prefformat->oclass != CLASS_RECSYN)
1201 form = prefformat->value;
1202 *num = *req->numberOfRecordsRequested;
1203 resp->records = pack_records(assoc, req->resultSetId,
1204 *req->resultSetStartPoint, num, req->recordComposition, next,
1208 resp->numberOfRecordsReturned = num;
1209 resp->presentStatus = presst;
1210 resp->nextResultSetPosition = next;
1216 * Scan was implemented rather in a hurry, and with support for only the basic
1217 * elements of the service in the backend API. Suggestions are welcome.
1219 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1221 Z_ScanRequest *req = reqb->request->u.scanRequest;
1222 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1223 Z_ScanResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1224 int *scanStatus = odr_malloc (assoc->encode, sizeof(*scanStatus));
1225 int *numberOfEntriesReturned =
1226 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1227 Z_ListEntries *ents = odr_malloc (assoc->encode, sizeof(*ents));
1229 bend_scanrequest srq;
1230 bend_scanresult *srs;
1233 logf(LOG_LOG, "Got scanrequest");
1234 *scanStatus = Z_Scan_failure;
1235 *numberOfEntriesReturned = 0;
1237 apdu->which = Z_APDU_scanResponse;
1238 apdu->u.scanResponse = res;
1239 res->referenceId = req->referenceId;
1241 res->scanStatus = scanStatus;
1242 res->numberOfEntriesReturned = numberOfEntriesReturned;
1243 res->positionOfTerm = 0;
1244 res->entries = ents;
1245 ents->which = Z_ListEntries_nonSurrogateDiagnostics;
1246 res->attributeSet = 0;
1249 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1250 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1251 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 121, 0);
1252 else if (req->stepSize && *req->stepSize > 0)
1253 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 205, 0);
1256 if (req->termListAndStartPoint->term->which == Z_Term_general)
1257 logf(LOG_DEBUG, " term: '%.*s'",
1258 req->termListAndStartPoint->term->u.general->len,
1259 req->termListAndStartPoint->term->u.general->buf);
1260 srq.num_bases = req->num_databaseNames;
1261 srq.basenames = req->databaseNames;
1262 srq.num_entries = *req->numberOfTermsRequested;
1263 srq.term = req->termListAndStartPoint;
1264 srq.stream = assoc->encode;
1265 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1266 attset->oclass != CLASS_RECSYN)
1267 srq.attributeset = VAL_NONE;
1269 srq.attributeset = attset->value;
1270 srq.term_position = req->preferredPositionInResponse ?
1271 *req->preferredPositionInResponse : 1;
1272 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1273 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 2, 0);
1274 else if (srs->errcode)
1275 ents->u.nonSurrogateDiagnostics = diagrecs(assoc,
1276 srs->errcode, srs->errstring);
1280 Z_Entries *list = odr_malloc (assoc->encode, sizeof(*list));
1281 Z_Entry **tab = odr_malloc (assoc->encode,
1282 sizeof(*tab) * srs->num_entries);
1284 if (srs->status == BEND_SCAN_PARTIAL)
1285 *scanStatus = Z_Scan_partial_5;
1287 *scanStatus = Z_Scan_success;
1288 ents->which = Z_ListEntries_entries;
1289 ents->u.entries = list;
1290 list->entries = tab;
1291 for (i = 0; i < srs->num_entries; i++)
1297 list->entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1298 e->which = Z_Entry_termInfo;
1299 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1300 t->suggestedAttributes = 0;
1302 t->alternativeTerm = 0;
1303 t->byAttributes = 0;
1304 t->otherTermInfo = 0;
1305 t->globalOccurrences = &srs->entries[i].occurrences;
1306 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1307 t->term->which = Z_Term_general;
1308 t->term->u.general = o = odr_malloc(assoc->encode,
1310 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1311 strlen(srs->entries[i].term));
1312 memcpy(o->buf, srs->entries[i].term, o->len);
1313 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1314 srs->entries[i].term, srs->entries[i].occurrences);
1316 list->num_entries = i;
1317 res->numberOfEntriesReturned = &list->num_entries;
1318 res->positionOfTerm = &srs->term_position;
1325 static void process_close(association *assoc, request *reqb)
1327 Z_Close *req = reqb->request->u.close;
1328 static char *reasons[] =
1335 "securityViolation",
1342 logf(LOG_LOG, "Got close, reason %s, message %s",
1343 reasons[*req->closeReason], req->diagnosticInformation ?
1344 req->diagnosticInformation : "NULL");
1345 if (assoc->version < 3) /* to make do_force respond with close */
1347 do_close(assoc, Z_Close_finished, "Association terminated by client");