2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.66 1997-09-05 15:26:44 adam
8 * Added ODR encode in search and scen bend request structures.
9 * Fixed a few enums that caused trouble with C++.
11 * Revision 1.65 1997/09/01 08:53:01 adam
12 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
13 * moved a separate directory. MSV5.0 project server.dsp created.
14 * As an option, the server can now operate as an NT service.
16 * Revision 1.64 1997/04/30 08:52:11 quinn
19 * Revision 1.63 1996/10/11 11:57:26 quinn
22 * Revision 1.62 1996/07/06 19:58:35 quinn
23 * System headerfiles gathered in yconfig
25 * Revision 1.61 1996/06/10 08:56:16 quinn
28 * Revision 1.60 1996/05/30 11:03:10 quinn
29 * Fixed NextresultSetPosition bug fixed.
31 * Revision 1.59 1996/05/14 09:26:46 quinn
32 * Added attribute set to scan backend
34 * Revision 1.58 1996/02/20 12:53:04 quinn
37 * Revision 1.57 1996/01/02 08:57:47 quinn
38 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
40 * Revision 1.56 1995/12/14 11:09:57 quinn
43 * Revision 1.55 1995/11/08 17:41:37 quinn
46 * Revision 1.54 1995/11/08 15:11:29 quinn
47 * Log of close transmit.
49 * Revision 1.53 1995/11/01 13:54:58 quinn
52 * Revision 1.52 1995/11/01 12:19:13 quinn
53 * Second attempt to fix same bug.
55 * Revision 1.50 1995/10/25 16:58:32 quinn
58 * Revision 1.49 1995/10/16 13:51:53 quinn
59 * Changes to provide Especs to the backend.
61 * Revision 1.48 1995/10/06 08:51:20 quinn
64 * Revision 1.47 1995/08/29 14:24:16 quinn
65 * Added second half of close-handshake
67 * Revision 1.46 1995/08/29 11:17:58 quinn
68 * Added code to receive close
70 * Revision 1.45 1995/08/21 09:11:00 quinn
71 * Smallish fixes to suppport new formats.
73 * Revision 1.44 1995/08/17 12:45:25 quinn
74 * Fixed minor problems with GRS-1. Added support in c&s.
76 * Revision 1.43 1995/08/15 12:00:31 quinn
79 * Revision 1.42 1995/08/15 11:16:50 quinn
81 * Revision 1.41 1995/08/02 10:23:06 quinn
84 * Revision 1.40 1995/07/31 14:34:26 quinn
85 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
87 * Revision 1.39 1995/06/27 13:21:00 quinn
90 * Revision 1.38 1995/06/19 12:39:11 quinn
91 * Fixed bug in timeout code. Added BER dumper.
93 * Revision 1.37 1995/06/16 13:16:14 quinn
94 * Fixed Defaultdiagformat.
96 * Revision 1.36 1995/06/16 10:31:36 quinn
97 * Added session timeout.
99 * Revision 1.35 1995/06/15 07:45:14 quinn
102 * Revision 1.34 1995/06/14 15:26:46 quinn
103 * *** empty log message ***
105 * Revision 1.33 1995/06/06 14:57:05 quinn
106 * Better diagnostics.
108 * Revision 1.32 1995/06/06 08:41:44 quinn
109 * Better diagnostics.
111 * Revision 1.31 1995/06/06 08:15:37 quinn
114 * Revision 1.30 1995/06/05 10:53:32 quinn
115 * Added a better SCAN.
117 * Revision 1.29 1995/06/01 11:25:03 quinn
120 * Revision 1.28 1995/06/01 11:21:01 quinn
121 * Attempting to fix a bug in pack-records. replaced break with continue
122 * for large records, according to standard.
124 * Revision 1.27 1995/05/29 08:12:06 quinn
127 * Revision 1.26 1995/05/18 13:02:12 quinn
130 * Revision 1.25 1995/05/17 08:42:26 quinn
131 * Transfer auth info to backend. Allow backend to reject init gracefully.
133 * Revision 1.24 1995/05/16 08:51:04 quinn
134 * License, documentation, and memory fixes
136 * Revision 1.23 1995/05/15 13:25:10 quinn
139 * Revision 1.22 1995/05/15 11:56:39 quinn
140 * Asynchronous facilities. Restructuring of seshigh code.
142 * Revision 1.21 1995/05/02 08:53:19 quinn
143 * Trying in vain to fix comm with ISODE
145 * Revision 1.20 1995/04/20 15:13:00 quinn
148 * Revision 1.19 1995/04/18 08:15:34 quinn
149 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
150 * neater. We'll make the same change for decoding one day.
152 * Revision 1.18 1995/04/17 11:28:25 quinn
155 * Revision 1.17 1995/04/10 10:23:36 quinn
156 * Some work to add scan and other things.
158 * Revision 1.16 1995/03/31 09:18:55 quinn
161 * Revision 1.15 1995/03/30 14:03:23 quinn
162 * Added RFC1006 as separate library
164 * Revision 1.14 1995/03/30 12:18:17 quinn
167 * Revision 1.13 1995/03/30 09:09:24 quinn
168 * Added state-handle and some support for asynchronous activities.
170 * Revision 1.12 1995/03/29 15:40:16 quinn
171 * Ongoing work. Statserv is now dynamic by default
173 * Revision 1.11 1995/03/28 09:16:21 quinn
174 * Added record packing to the search request
176 * Revision 1.10 1995/03/27 08:34:24 quinn
177 * Added dynamic server functionality.
178 * Released bindings to session.c (is now redundant)
180 * Revision 1.9 1995/03/22 15:01:26 quinn
181 * Adjusting record packing.
183 * Revision 1.8 1995/03/22 10:13:21 quinn
184 * Working on record packer
186 * Revision 1.7 1995/03/21 15:53:31 quinn
189 * Revision 1.6 1995/03/21 12:30:09 quinn
190 * Beginning to add support for record packing.
192 * Revision 1.5 1995/03/17 10:44:13 quinn
193 * Added catch of null-string in makediagrec
195 * Revision 1.4 1995/03/17 10:18:08 quinn
196 * Added memory management.
198 * Revision 1.3 1995/03/16 17:42:39 quinn
201 * Revision 1.2 1995/03/16 13:29:01 quinn
202 * Partitioned server.
204 * Revision 1.1 1995/03/15 16:02:10 quinn
205 * Modded session.c to seshigh.c
210 * Frontend server logic.
212 * This code receives incoming APDUs, and handles client requests by means
213 * of the backend API.
215 * Some of the code is getting quite involved, compared to simpler servers -
216 * primarily because it is asynchronous both in the communication with
217 * the user and the backend. We think the complexity will pay off in
218 * the form of greater flexibility when more asynchronous facilities
221 * Memory management has become somewhat involved. In the simple case, where
222 * only one PDU is pending at a time, it will simply reuse the same memory,
223 * once it has found its working size. When we enable multiple concurrent
224 * operations, perhaps even with multiple parallel calls to the backend, it
225 * will maintain a pool of buffers for encoding and decoding, trying to
226 * minimize memory allocation/deallocation during normal operation.
228 * TODOs include (and will be done in order of public interest):
230 * Support for EXPLAIN - provide simple meta-database system.
231 * Support for access control.
232 * Support for resource control.
233 * Support for extended services - primarily Item Order.
234 * Rest of Z39.50-1994
249 #include <comstack.h>
255 #include <statserv.h>
259 static int process_request(association *assoc);
260 void backend_response(IOCHAN i, int event);
261 static int process_response(association *assoc, request *req, Z_APDU *res);
262 static Z_APDU *process_initRequest(association *assoc, request *reqb);
263 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
265 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
266 bend_searchresult *bsrt, int *fd);
267 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
269 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
270 static void process_close(association *assoc, request *reqb);
272 static FILE *apduf = 0; /* for use in static mode */
273 static statserv_options_block *control_block = 0;
276 * Create and initialize a new association-handle.
277 * channel : iochannel for the current line.
278 * link : communications channel.
279 * Returns: 0 or a new association handle.
281 association *create_association(IOCHAN channel, COMSTACK link)
286 control_block = statserv_getcontrol();
287 if (!(new = xmalloc(sizeof(*new))))
289 new->client_chan = channel;
290 new->client_link = link;
291 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
292 !(new->encode = odr_createmem(ODR_ENCODE)))
294 if (*control_block->apdufile)
299 strcpy(filename, control_block->apdufile);
300 if (!(new->print = odr_createmem(ODR_PRINT)))
302 if (*control_block->apdufile != '-')
304 strcpy(filename, control_block->apdufile);
305 if (!control_block->dynamic)
309 if (!(apduf = fopen(filename, "w")))
311 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
314 setvbuf(apduf, 0, _IONBF, 0);
320 sprintf(filename + strlen(filename), ".%d", getpid());
321 if (!(f = fopen(filename, "w")))
323 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
326 setvbuf(f, 0, _IONBF, 0);
328 odr_setprint(new->print, f);
333 new->input_buffer = 0;
334 new->input_buffer_len = 0;
336 new->state = ASSOC_NEW;
337 request_initq(&new->incoming);
338 request_initq(&new->outgoing);
339 new->proto = cs_getproto(link);
344 * Free association and release resources.
346 void destroy_association(association *h)
348 odr_destroy(h->decode);
349 odr_destroy(h->encode);
351 odr_destroy(h->print);
353 xfree(h->input_buffer);
355 bend_close(h->backend);
356 while (request_deq(&h->incoming));
357 while (request_deq(&h->outgoing));
358 request_delq(&h->incoming);
359 request_delq(&h->outgoing);
363 static void do_close(association *a, int reason, char *message)
366 Z_Close *cls = zget_Close(a->encode);
367 request *req = request_get(&a->outgoing);
369 /* Purge request queue */
370 while (request_deq(&a->incoming));
371 while (request_deq(&a->outgoing));
374 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
375 reason, message ? message : "none");
376 apdu.which = Z_APDU_close;
378 *cls->closeReason = reason;
379 cls->diagnosticInformation = message;
380 process_response(a, req, &apdu);
381 iochan_settimeout(a->client_chan, 60);
385 logf(LOG_DEBUG, "v2 client. No Close PDU");
386 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
388 a->state = ASSOC_DEAD;
392 * This is where PDUs from the client are read and the further
393 * processing is initiated. Flow of control moves down through the
394 * various process_* functions below, until the encoded result comes back up
395 * to the output handler in here.
397 * h : the I/O channel that has an outstanding event.
398 * event : the current outstanding event.
400 void ir_session(IOCHAN h, int event)
403 association *assoc = iochan_getdata(h);
404 COMSTACK conn = assoc->client_link;
407 assert(h && conn && assoc);
408 if (event == EVENT_TIMEOUT)
410 if (assoc->state != ASSOC_UP)
412 logf(LOG_LOG, "Final timeout - closing connection.");
414 destroy_association(assoc);
419 logf(LOG_LOG, "Session idle too long. Sending close.");
420 do_close(assoc, Z_Close_lackOfActivity, 0);
424 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
426 if (event & EVENT_INPUT)
428 logf(LOG_DEBUG, "ir_session (input)");
429 assert(assoc && conn);
430 /* We aren't speaking to this fellow */
431 if (assoc->state == ASSOC_DEAD)
433 logf(LOG_LOG, "Closed connection after reject");
435 destroy_association(assoc);
439 if ((res = cs_get(conn, &assoc->input_buffer,
440 &assoc->input_buffer_len)) <= 0)
442 logf(LOG_LOG, "Connection closed by client");
444 destroy_association(assoc);
448 else if (res == 1) /* incomplete read - wait for more */
450 if (cs_more(conn)) /* more stuff - call us again later, please */
451 iochan_setevent(h, EVENT_INPUT);
453 /* we got a complete PDU. Let's decode it */
454 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
455 req = request_get(&assoc->incoming); /* get a new request structure */
456 odr_reset(assoc->decode);
457 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
458 if (!z_APDU(assoc->decode, &req->request, 0))
460 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
461 odr_errmsg(odr_geterror(assoc->decode)),
462 odr_offset(assoc->decode));
463 logf(LOG_LOG, "PDU dump:");
464 odr_dumpBER(log_file(), assoc->input_buffer, res);
465 do_close(assoc, Z_Close_protocolError, "Malformed package");
468 req->request_mem = odr_extract_mem(assoc->decode);
469 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
471 logf(LOG_WARN, "ODR print error: %s",
472 odr_errmsg(odr_geterror(assoc->print)));
473 odr_reset(assoc->print);
475 request_enq(&assoc->incoming, req);
478 /* can we do something yet? */
479 req = request_head(&assoc->incoming);
480 if (req->state == REQUEST_IDLE)
481 if (process_request(assoc) < 0)
482 do_close(assoc, Z_Close_systemProblem, "Unknown error");
484 if (event & EVENT_OUTPUT)
486 request *req = request_head(&assoc->outgoing);
488 logf(LOG_DEBUG, "ir_session (output)");
489 req->state = REQUEST_PENDING;
490 switch (res = cs_put(conn, req->response, req->len_response))
493 logf(LOG_LOG, "Connection closed by client");
495 destroy_association(assoc);
498 case 0: /* all sent - release the request structure */
499 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
500 nmem_destroy(req->request_mem);
501 request_deq(&assoc->outgoing);
502 request_release(req);
503 if (!request_head(&assoc->outgoing))
504 iochan_clearflag(h, EVENT_OUTPUT);
506 /* value of 1 -- partial send -- is simply ignored */
509 if (event & EVENT_EXCEPT)
511 logf(LOG_DEBUG, "ir_session (exception)");
513 destroy_association(assoc);
519 * Initiate request processing.
521 static int process_request(association *assoc)
523 request *req = request_head(&assoc->incoming);
527 logf(LOG_DEBUG, "process_request");
528 assert(req && req->state == REQUEST_IDLE);
529 switch (req->request->which)
531 case Z_APDU_initRequest:
532 res = process_initRequest(assoc, req); break;
533 case Z_APDU_searchRequest:
534 res = process_searchRequest(assoc, req, &fd); break;
535 case Z_APDU_presentRequest:
536 res = process_presentRequest(assoc, req, &fd); break;
537 case Z_APDU_scanRequest:
538 res = process_scanRequest(assoc, req, &fd); break;
540 process_close(assoc, req); return 0;
542 logf(LOG_WARN, "Bad APDU received");
547 logf(LOG_DEBUG, " result immediately available");
548 return process_response(assoc, req, res);
552 logf(LOG_WARN, " bad result");
555 else /* no result yet - one will be provided later */
559 /* Set up an I/O handler for the fd supplied by the backend */
561 logf(LOG_DEBUG, " establishing handler for result");
562 req->state = REQUEST_PENDING;
563 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
565 iochan_setdata(chan, assoc);
571 * Handle message from the backend.
573 void backend_response(IOCHAN i, int event)
575 association *assoc = iochan_getdata(i);
576 request *req = request_head(&assoc->incoming);
580 logf(LOG_DEBUG, "backend_response");
581 assert(assoc && req && req->state != REQUEST_IDLE);
582 /* determine what it is we're waiting for */
583 switch (req->request->which)
585 case Z_APDU_searchRequest:
586 res = response_searchRequest(assoc, req, 0, &fd); break;
588 case Z_APDU_presentRequest:
589 res = response_presentRequest(assoc, req, 0, &fd); break;
590 case Z_APDU_scanRequest:
591 res = response_scanRequest(assoc, req, 0, &fd); break;
594 logf(LOG_WARN, "Serious programmer's lapse or bug");
597 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
599 logf(LOG_LOG, "Fatal error when talking to backend");
600 do_close(assoc, Z_Close_systemProblem, 0);
604 else if (!res) /* no result yet - try again later */
606 logf(LOG_DEBUG, " no result yet");
607 iochan_setfd(i, fd); /* in case fd has changed */
612 * Encode response, and transfer the request structure to the outgoing queue.
614 static int process_response(association *assoc, request *req, Z_APDU *res)
616 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
617 if (!z_APDU(assoc->encode, &res, 0))
619 logf(LOG_WARN, "ODR error when encoding response: %s",
620 odr_errmsg(odr_geterror(assoc->decode)));
621 odr_reset(assoc->encode);
624 req->response = odr_getbuf(assoc->encode, &req->len_response,
625 &req->size_response);
626 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
627 odr_reset(assoc->encode);
628 if (assoc->print && !z_APDU(assoc->print, &res, 0))
630 logf(LOG_WARN, "ODR print error: %s",
631 odr_errmsg(odr_geterror(assoc->print)));
632 odr_reset(assoc->print);
634 /* change this when we make the backend reentrant */
635 if (req == request_head(&assoc->incoming))
637 req->state = REQUEST_IDLE;
638 request_deq(&assoc->incoming);
640 request_enq(&assoc->outgoing, req);
641 /* turn the work over to the ir_session handler */
642 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
643 /* Is there more work to be done? give that to the input handler too */
644 if (request_head(&assoc->incoming))
645 iochan_setevent(assoc->client_chan, EVENT_WORK);
650 * Handle init request.
651 * At the moment, we don't check the options
652 * anywhere else in the code - we just try not to do anything that would
653 * break a naive client. We'll toss 'em into the association block when
654 * we need them there.
656 static Z_APDU *process_initRequest(association *assoc, request *reqb)
658 Z_InitRequest *req = reqb->request->u.initRequest;
659 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
660 Z_InitResponse *resp = apdu->u.initResponse;
661 bend_initrequest binitreq;
662 bend_initresult *binitres;
665 logf(LOG_LOG, "Got initRequest");
666 if (req->implementationId)
667 logf(LOG_LOG, "Id: %s", req->implementationId);
668 if (req->implementationName)
669 logf(LOG_LOG, "Name: %s", req->implementationName);
670 if (req->implementationVersion)
671 logf(LOG_LOG, "Version: %s", req->implementationVersion);
673 binitreq.configname = "default-config";
674 binitreq.auth = req->idAuthentication;
675 if (!(binitres = bend_init(&binitreq)))
677 logf(LOG_WARN, "Bad response from backend.");
681 assoc->backend = binitres->handle;
682 resp->referenceId = req->referenceId;
684 /* let's tell the client what we can do */
685 if (ODR_MASK_GET(req->options, Z_Options_search))
687 ODR_MASK_SET(resp->options, Z_Options_search);
688 strcat(options, "srch");
690 if (ODR_MASK_GET(req->options, Z_Options_present))
692 ODR_MASK_SET(resp->options, Z_Options_present);
693 strcat(options, " prst");
696 if (ODR_MASK_GET(req->options, Z_Options_delSet))
698 ODR_MASK_SET(&options, Z_Options_delSet);
699 strcat(options, " del");
702 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
704 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
705 strcat(options, " namedresults");
707 if (ODR_MASK_GET(req->options, Z_Options_scan))
709 ODR_MASK_SET(resp->options, Z_Options_scan);
710 strcat(options, " scan");
712 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
714 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
715 strcat(options, " concurop");
718 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
720 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
721 assoc->version = 2; /* 1 & 2 are equivalent */
723 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
725 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
728 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
730 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
733 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
734 assoc->maximumRecordSize = *req->maximumRecordSize;
735 if (assoc->maximumRecordSize > control_block->maxrecordsize)
736 assoc->maximumRecordSize = control_block->maxrecordsize;
737 assoc->preferredMessageSize = *req->preferredMessageSize;
738 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
739 assoc->preferredMessageSize = assoc->maximumRecordSize;
740 resp->preferredMessageSize = &assoc->preferredMessageSize;
741 resp->maximumRecordSize = &assoc->maximumRecordSize;
742 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
743 if (binitres->errcode)
745 logf(LOG_LOG, "Connection rejected by backend.");
747 assoc->state = ASSOC_DEAD;
750 assoc->state = ASSOC_UP;
755 * These functions should be merged.
759 * nonsurrogate diagnostic record.
761 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
763 Z_Records *rec = odr_malloc (assoc->encode, sizeof(*rec));
765 int *err = odr_malloc (assoc->encode, sizeof(*err));
766 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
767 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
769 bib1.proto = assoc->proto;
770 bib1.oclass = CLASS_DIAGSET;
771 bib1.value = VAL_BIB1;
773 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
776 rec->which = Z_Records_NSD;
778 rec->u.nonSurrogateDiagnostic = drec;
779 drec->which = Z_DiagRec_defaultFormat;
780 drec->u.defaultFormat = dr;
782 rec->u.nonSurrogateDiagnostic = dr;
784 dr->diagnosticSetId = oid_getoidbyent(&bib1);
786 dr->which = Z_DiagForm_v2AddInfo;
787 dr->addinfo = addinfo ? addinfo : "";
792 * surrogate diagnostic.
794 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
795 int error, char *addinfo)
797 Z_NamePlusRecord *rec = odr_malloc (assoc->encode, sizeof(*rec));
798 int *err = odr_malloc (assoc->encode, sizeof(*err));
800 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
801 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
803 bib1.proto = assoc->proto;
804 bib1.oclass = CLASS_DIAGSET;
805 bib1.value = VAL_BIB1;
807 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
809 rec->databaseName = dbname;
810 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
811 rec->u.surrogateDiagnostic = drec;
812 drec->which = Z_DiagRec_defaultFormat;
813 drec->u.defaultFormat = dr;
814 dr->diagnosticSetId = oid_getoidbyent(&bib1);
816 dr->which = Z_DiagForm_v2AddInfo;
817 dr->addinfo = addinfo ? addinfo : "";
822 * multiple nonsurrogate diagnostics.
824 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
826 Z_DiagRecs *recs = odr_malloc (assoc->encode, sizeof(*recs));
827 int *err = odr_malloc (assoc->encode, sizeof(*err));
829 Z_DiagRec **recp = odr_malloc (assoc->encode, sizeof(*recp));
830 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
831 Z_DefaultDiagFormat *rec = odr_malloc (assoc->encode, sizeof(*rec));
833 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
834 bib1.proto = assoc->proto;
835 bib1.oclass = CLASS_DIAGSET;
836 bib1.value = VAL_BIB1;
839 recs->num_diagRecs = 1;
840 recs->diagRecs = recp;
842 drec->which = Z_DiagRec_defaultFormat;
843 drec->u.defaultFormat = rec;
845 rec->diagnosticSetId = oid_getoidbyent(&bib1);
846 rec->condition = err;
847 rec->which = Z_DiagForm_v2AddInfo;
848 rec->addinfo = addinfo ? addinfo : "";
852 static Z_Records *pack_records(association *a, char *setname, int start,
853 int *num, Z_RecordComposition *comp,
854 int *next, int *pres, oid_value format)
856 int recno, total_length = 0, toget = *num, dumped_records = 0;
857 Z_Records *records = odr_malloc (a->encode, sizeof(*records));
858 Z_NamePlusRecordList *reclist = odr_malloc (a->encode, sizeof(*reclist));
859 Z_NamePlusRecord **list = odr_malloc (a->encode, sizeof(*list) * toget);
862 records->which = Z_Records_DBOSD;
863 records->u.databaseOrSurDiagnostics = reclist;
864 reclist->num_records = 0;
865 reclist->records = list;
866 *pres = Z_PRES_SUCCESS;
870 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
871 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
872 a->maximumRecordSize);
873 for (recno = start; reclist->num_records < toget; recno++)
875 bend_fetchrequest freq;
876 bend_fetchresult *fres;
877 Z_NamePlusRecord *thisrec;
878 Z_DatabaseRecord *thisext;
882 * we get the number of bytes allocated on the stream before any
883 * allocation done by the backend - this should give us a reasonable
884 * idea of the total size of the data so far.
886 total_length = odr_total(a->encode) - dumped_records;
887 freq.setname = setname;
890 freq.format = format;
891 freq.stream = a->encode;
892 if (!(fres = bend_fetch(a->backend, &freq, 0)))
894 *pres = Z_PRES_FAILURE;
895 return diagrec(a, 2, "Backend interface problem");
897 /* backend should be able to signal whether error is system-wide
898 or only pertaining to current record */
901 *pres = Z_PRES_FAILURE;
902 return diagrec(a, fres->errcode, fres->errstring);
905 this_length = fres->len;
907 this_length = odr_total(a->encode) - total_length;
908 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
909 this_length, total_length);
910 if (this_length + total_length > a->preferredMessageSize)
912 /* record is small enough, really */
913 if (this_length <= a->preferredMessageSize)
915 logf(LOG_DEBUG, " Dropped last normal-sized record");
916 *pres = Z_PRES_PARTIAL_2;
919 /* record can only be fetched by itself */
920 if (this_length < a->maximumRecordSize)
922 logf(LOG_DEBUG, " Record > prefmsgsz");
925 logf(LOG_DEBUG, " Dropped it");
926 reclist->records[reclist->num_records] =
927 surrogatediagrec(a, fres->basename, 16, 0);
928 reclist->num_records++;
929 *next = fres->last_in_set ? 0 : recno + 1;
930 dumped_records += this_length;
934 else /* too big entirely */
936 logf(LOG_DEBUG, "Record > maxrcdsz");
937 reclist->records[reclist->num_records] =
938 surrogatediagrec(a, fres->basename, 17, 0);
939 reclist->num_records++;
940 *next = fres->last_in_set ? 0 : recno + 1;
941 dumped_records += this_length;
945 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
947 if (!(thisrec->databaseName = odr_malloc(a->encode,
948 strlen(fres->basename) + 1)))
950 strcpy(thisrec->databaseName, fres->basename);
951 thisrec->which = Z_NamePlusRecord_databaseRecord;
952 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
953 sizeof(Z_DatabaseRecord))))
955 recform.proto = a->proto;
956 recform.oclass = CLASS_RECSYN;
957 recform.value = fres->format;
958 thisext->direct_reference = odr_oiddup(a->encode,
959 oid_getoidbyent(&recform));
960 thisext->indirect_reference = 0;
961 thisext->descriptor = 0;
962 if (fres->len < 0) /* Structured data */
964 switch (fres->format)
966 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
967 case VAL_GRS1: thisext->which = Z_External_grs1; break;
968 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
970 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
971 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
974 logf(LOG_FATAL, "Unknown structured format from backend.");
979 * We cheat on the pointers here. Obviously, the record field
980 * of the backend-fetch structure should have been a union for
981 * correctness, but we're stuck with this for backwards
984 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
986 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
988 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
990 thisext->which = Z_External_sutrs;
991 thisext->u.sutrs = sutrs;
992 sutrs->buf = odr_malloc(a->encode, fres->len);
993 sutrs->len = sutrs->size = fres->len;
994 memcpy(sutrs->buf, fres->record, fres->len);
996 else /* octet-aligned record. */
998 thisext->which = Z_External_octet;
999 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
1002 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1005 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1006 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1009 reclist->records[reclist->num_records] = thisrec;
1010 reclist->num_records++;
1011 *next = fres->last_in_set ? 0 : recno + 1;
1013 *num = reclist->num_records;
1017 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1020 Z_SearchRequest *req = reqb->request->u.searchRequest;
1021 bend_searchrequest bsrq;
1022 bend_searchresult *bsrt;
1024 logf(LOG_LOG, "Got SearchRequest.");
1026 bsrq.setname = req->resultSetName;
1027 bsrq.replace_set = *req->replaceIndicator;
1028 bsrq.num_bases = req->num_databaseNames;
1029 bsrq.basenames = req->databaseNames;
1030 bsrq.query = req->query;
1031 bsrq.stream = assoc->encode;
1033 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1035 return response_searchRequest(assoc, reqb, bsrt, fd);
1038 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1041 * Prepare a searchresponse based on the backend results. We probably want
1042 * to look at making the fetching of records nonblocking as well, but
1043 * so far, we'll keep things simple.
1044 * If bsrt is null, that means we're called in response to a communications
1045 * event, and we'll have to get the response for ourselves.
1047 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1048 bend_searchresult *bsrt, int *fd)
1050 Z_SearchRequest *req = reqb->request->u.searchRequest;
1051 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1052 Z_SearchResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1053 int *nulint = odr_malloc (assoc->encode, sizeof(*nulint));
1054 bool_t *sr = odr_malloc (assoc->encode, sizeof(*sr));
1055 int *next = odr_malloc (assoc->encode, sizeof(*next));
1056 int *none = odr_malloc (assoc->encode, sizeof(*none));
1063 apdu->which = Z_APDU_searchResponse;
1064 apdu->u.searchResponse = resp;
1065 resp->referenceId = req->referenceId;
1066 resp->additionalSearchInfo = 0;
1067 resp->otherInfo = 0;
1069 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1071 logf(LOG_FATAL, "Bad result from backend");
1074 else if (bsrt->errcode)
1076 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1077 resp->resultCount = nulint;
1078 resp->numberOfRecordsReturned = nulint;
1079 resp->nextResultSetPosition = nulint;
1080 resp->searchStatus = nulint;
1081 resp->resultSetStatus = none;
1082 resp->presentStatus = 0;
1086 int *toget = odr_malloc (assoc->encode, sizeof(*toget));
1087 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1088 Z_RecordComposition comp, *compp = 0;
1093 resp->resultCount = &bsrt->hits;
1095 comp.which = Z_RecordComp_simple;
1096 /* how many records does the user agent want, then? */
1097 if (bsrt->hits <= *req->smallSetUpperBound)
1099 *toget = bsrt->hits;
1100 if ((comp.u.simple = req->smallSetElementSetNames))
1103 else if (bsrt->hits < *req->largeSetLowerBound)
1105 *toget = *req->mediumSetPresentNumber;
1106 if (*toget > bsrt->hits)
1107 *toget = bsrt->hits;
1108 if ((comp.u.simple = req->mediumSetElementSetNames))
1114 if (*toget && !resp->records)
1119 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1120 prefformat->oclass != CLASS_RECSYN)
1123 form = prefformat->value;
1124 resp->records = pack_records(assoc, req->resultSetName, 1,
1125 toget, compp, next, presst, form);
1128 resp->numberOfRecordsReturned = toget;
1129 resp->nextResultSetPosition = next;
1130 resp->searchStatus = sr;
1131 resp->resultSetStatus = 0;
1132 resp->presentStatus = presst;
1136 if (*resp->resultCount)
1138 resp->numberOfRecordsReturned = nulint;
1139 resp->nextResultSetPosition = next;
1140 resp->searchStatus = sr;
1141 resp->resultSetStatus = 0;
1142 resp->presentStatus = 0;
1149 * Maybe we got a little over-friendly when we designed bend_fetch to
1150 * get only one record at a time. Some backends can optimise multiple-record
1151 * fetches, and at any rate, there is some overhead involved in
1152 * all that selecting and hopping around. Problem is, of course, that the
1153 * frontend can't know ahead of time how many records it'll need to
1154 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1155 * is downright lousy as a bulk data transfer protocol.
1157 * To start with, we'll do the fetching of records from the backend
1158 * in one operation: To save some trips in and out of the event-handler,
1159 * and to simplify the interface to pack_records. At any rate, asynch
1160 * operation is more fun in operations that have an unpredictable execution
1161 * speed - which is normally more true for search than for present.
1163 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1166 Z_PresentRequest *req = reqb->request->u.presentRequest;
1167 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1168 Z_PresentResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1169 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1170 int *next = odr_malloc (assoc->encode, sizeof(*next));
1171 int *num = odr_malloc (assoc->encode, sizeof(*num));
1175 logf(LOG_LOG, "Got PresentRequest.");
1180 apdu->which = Z_APDU_presentResponse;
1181 apdu->u.presentResponse = resp;
1182 resp->referenceId = req->referenceId;
1183 resp->otherInfo = 0;
1185 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1186 prefformat->oclass != CLASS_RECSYN)
1189 form = prefformat->value;
1190 *num = *req->numberOfRecordsRequested;
1191 resp->records = pack_records(assoc, req->resultSetId,
1192 *req->resultSetStartPoint, num, req->recordComposition, next,
1196 resp->numberOfRecordsReturned = num;
1197 resp->presentStatus = presst;
1198 resp->nextResultSetPosition = next;
1204 * Scan was implemented rather in a hurry, and with support for only the basic
1205 * elements of the service in the backend API. Suggestions are welcome.
1207 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1209 Z_ScanRequest *req = reqb->request->u.scanRequest;
1210 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1211 Z_ScanResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1212 int *scanStatus = odr_malloc (assoc->encode, sizeof(*scanStatus));
1213 int *numberOfEntriesReturned =
1214 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1215 Z_ListEntries *ents = odr_malloc (assoc->encode, sizeof(*ents));
1217 bend_scanrequest srq;
1218 bend_scanresult *srs;
1221 logf(LOG_LOG, "Got scanrequest");
1222 *scanStatus = Z_Scan_failure;
1223 *numberOfEntriesReturned = 0;
1225 apdu->which = Z_APDU_scanResponse;
1226 apdu->u.scanResponse = res;
1227 res->referenceId = req->referenceId;
1229 res->scanStatus = scanStatus;
1230 res->numberOfEntriesReturned = numberOfEntriesReturned;
1231 res->positionOfTerm = 0;
1232 res->entries = ents;
1233 ents->which = Z_ListEntries_nonSurrogateDiagnostics;
1234 res->attributeSet = 0;
1237 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1238 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1239 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 121, 0);
1240 else if (req->stepSize && *req->stepSize > 0)
1241 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 205, 0);
1244 if (req->termListAndStartPoint->term->which == Z_Term_general)
1245 logf(LOG_DEBUG, " term: '%.*s'",
1246 req->termListAndStartPoint->term->u.general->len,
1247 req->termListAndStartPoint->term->u.general->buf);
1248 srq.num_bases = req->num_databaseNames;
1249 srq.basenames = req->databaseNames;
1250 srq.num_entries = *req->numberOfTermsRequested;
1251 srq.term = req->termListAndStartPoint;
1252 srq.stream = assoc->encode;
1253 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1254 attset->oclass != CLASS_RECSYN)
1255 srq.attributeset = VAL_NONE;
1257 srq.attributeset = attset->value;
1258 srq.term_position = req->preferredPositionInResponse ?
1259 *req->preferredPositionInResponse : 1;
1260 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1261 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 2, 0);
1262 else if (srs->errcode)
1263 ents->u.nonSurrogateDiagnostics = diagrecs(assoc,
1264 srs->errcode, srs->errstring);
1268 Z_Entries *list = odr_malloc (assoc->encode, sizeof(*list));
1269 Z_Entry **tab = odr_malloc (assoc->encode,
1270 sizeof(*tab) * srs->num_entries);
1272 if (srs->status == BEND_SCAN_PARTIAL)
1273 *scanStatus = Z_Scan_partial_5;
1275 *scanStatus = Z_Scan_success;
1276 ents->which = Z_ListEntries_entries;
1277 ents->u.entries = list;
1278 list->entries = tab;
1279 for (i = 0; i < srs->num_entries; i++)
1285 list->entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1286 e->which = Z_Entry_termInfo;
1287 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1288 t->suggestedAttributes = 0;
1290 t->alternativeTerm = 0;
1291 t->byAttributes = 0;
1292 t->otherTermInfo = 0;
1293 t->globalOccurrences = &srs->entries[i].occurrences;
1294 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1295 t->term->which = Z_Term_general;
1296 t->term->u.general = o = odr_malloc(assoc->encode,
1298 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1299 strlen(srs->entries[i].term));
1300 memcpy(o->buf, srs->entries[i].term, o->len);
1301 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1302 srs->entries[i].term, srs->entries[i].occurrences);
1304 list->num_entries = i;
1305 res->numberOfEntriesReturned = &list->num_entries;
1306 res->positionOfTerm = &srs->term_position;
1313 static void process_close(association *assoc, request *reqb)
1315 Z_Close *req = reqb->request->u.close;
1316 static char *reasons[] =
1323 "securityViolation",
1330 logf(LOG_LOG, "Got close, reason %s, message %s",
1331 reasons[*req->closeReason], req->diagnosticInformation ?
1332 req->diagnosticInformation : "NULL");
1333 if (assoc->version < 3) /* to make do_force respond with close */
1335 do_close(assoc, Z_Close_finished, "Association terminated by client");