2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.65 1997-09-01 08:53:01 adam
8 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
9 * moved a separate directory. MSV5.0 project server.dsp created.
10 * As an option, the server can now operate as an NT service.
12 * Revision 1.64 1997/04/30 08:52:11 quinn
15 * Revision 1.63 1996/10/11 11:57:26 quinn
18 * Revision 1.62 1996/07/06 19:58:35 quinn
19 * System headerfiles gathered in yconfig
21 * Revision 1.61 1996/06/10 08:56:16 quinn
24 * Revision 1.60 1996/05/30 11:03:10 quinn
25 * Fixed NextresultSetPosition bug fixed.
27 * Revision 1.59 1996/05/14 09:26:46 quinn
28 * Added attribute set to scan backend
30 * Revision 1.58 1996/02/20 12:53:04 quinn
33 * Revision 1.57 1996/01/02 08:57:47 quinn
34 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
36 * Revision 1.56 1995/12/14 11:09:57 quinn
39 * Revision 1.55 1995/11/08 17:41:37 quinn
42 * Revision 1.54 1995/11/08 15:11:29 quinn
43 * Log of close transmit.
45 * Revision 1.53 1995/11/01 13:54:58 quinn
48 * Revision 1.52 1995/11/01 12:19:13 quinn
49 * Second attempt to fix same bug.
51 * Revision 1.50 1995/10/25 16:58:32 quinn
54 * Revision 1.49 1995/10/16 13:51:53 quinn
55 * Changes to provide Especs to the backend.
57 * Revision 1.48 1995/10/06 08:51:20 quinn
60 * Revision 1.47 1995/08/29 14:24:16 quinn
61 * Added second half of close-handshake
63 * Revision 1.46 1995/08/29 11:17:58 quinn
64 * Added code to receive close
66 * Revision 1.45 1995/08/21 09:11:00 quinn
67 * Smallish fixes to suppport new formats.
69 * Revision 1.44 1995/08/17 12:45:25 quinn
70 * Fixed minor problems with GRS-1. Added support in c&s.
72 * Revision 1.43 1995/08/15 12:00:31 quinn
75 * Revision 1.42 1995/08/15 11:16:50 quinn
77 * Revision 1.41 1995/08/02 10:23:06 quinn
80 * Revision 1.40 1995/07/31 14:34:26 quinn
81 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
83 * Revision 1.39 1995/06/27 13:21:00 quinn
86 * Revision 1.38 1995/06/19 12:39:11 quinn
87 * Fixed bug in timeout code. Added BER dumper.
89 * Revision 1.37 1995/06/16 13:16:14 quinn
90 * Fixed Defaultdiagformat.
92 * Revision 1.36 1995/06/16 10:31:36 quinn
93 * Added session timeout.
95 * Revision 1.35 1995/06/15 07:45:14 quinn
98 * Revision 1.34 1995/06/14 15:26:46 quinn
99 * *** empty log message ***
101 * Revision 1.33 1995/06/06 14:57:05 quinn
102 * Better diagnostics.
104 * Revision 1.32 1995/06/06 08:41:44 quinn
105 * Better diagnostics.
107 * Revision 1.31 1995/06/06 08:15:37 quinn
110 * Revision 1.30 1995/06/05 10:53:32 quinn
111 * Added a better SCAN.
113 * Revision 1.29 1995/06/01 11:25:03 quinn
116 * Revision 1.28 1995/06/01 11:21:01 quinn
117 * Attempting to fix a bug in pack-records. replaced break with continue
118 * for large records, according to standard.
120 * Revision 1.27 1995/05/29 08:12:06 quinn
123 * Revision 1.26 1995/05/18 13:02:12 quinn
126 * Revision 1.25 1995/05/17 08:42:26 quinn
127 * Transfer auth info to backend. Allow backend to reject init gracefully.
129 * Revision 1.24 1995/05/16 08:51:04 quinn
130 * License, documentation, and memory fixes
132 * Revision 1.23 1995/05/15 13:25:10 quinn
135 * Revision 1.22 1995/05/15 11:56:39 quinn
136 * Asynchronous facilities. Restructuring of seshigh code.
138 * Revision 1.21 1995/05/02 08:53:19 quinn
139 * Trying in vain to fix comm with ISODE
141 * Revision 1.20 1995/04/20 15:13:00 quinn
144 * Revision 1.19 1995/04/18 08:15:34 quinn
145 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
146 * neater. We'll make the same change for decoding one day.
148 * Revision 1.18 1995/04/17 11:28:25 quinn
151 * Revision 1.17 1995/04/10 10:23:36 quinn
152 * Some work to add scan and other things.
154 * Revision 1.16 1995/03/31 09:18:55 quinn
157 * Revision 1.15 1995/03/30 14:03:23 quinn
158 * Added RFC1006 as separate library
160 * Revision 1.14 1995/03/30 12:18:17 quinn
163 * Revision 1.13 1995/03/30 09:09:24 quinn
164 * Added state-handle and some support for asynchronous activities.
166 * Revision 1.12 1995/03/29 15:40:16 quinn
167 * Ongoing work. Statserv is now dynamic by default
169 * Revision 1.11 1995/03/28 09:16:21 quinn
170 * Added record packing to the search request
172 * Revision 1.10 1995/03/27 08:34:24 quinn
173 * Added dynamic server functionality.
174 * Released bindings to session.c (is now redundant)
176 * Revision 1.9 1995/03/22 15:01:26 quinn
177 * Adjusting record packing.
179 * Revision 1.8 1995/03/22 10:13:21 quinn
180 * Working on record packer
182 * Revision 1.7 1995/03/21 15:53:31 quinn
185 * Revision 1.6 1995/03/21 12:30:09 quinn
186 * Beginning to add support for record packing.
188 * Revision 1.5 1995/03/17 10:44:13 quinn
189 * Added catch of null-string in makediagrec
191 * Revision 1.4 1995/03/17 10:18:08 quinn
192 * Added memory management.
194 * Revision 1.3 1995/03/16 17:42:39 quinn
197 * Revision 1.2 1995/03/16 13:29:01 quinn
198 * Partitioned server.
200 * Revision 1.1 1995/03/15 16:02:10 quinn
201 * Modded session.c to seshigh.c
206 * Frontend server logic.
208 * This code receives incoming APDUs, and handles client requests by means
209 * of the backend API.
211 * Some of the code is getting quite involved, compared to simpler servers -
212 * primarily because it is asynchronous both in the communication with
213 * the user and the backend. We think the complexity will pay off in
214 * the form of greater flexibility when more asynchronous facilities
217 * Memory management has become somewhat involved. In the simple case, where
218 * only one PDU is pending at a time, it will simply reuse the same memory,
219 * once it has found its working size. When we enable multiple concurrent
220 * operations, perhaps even with multiple parallel calls to the backend, it
221 * will maintain a pool of buffers for encoding and decoding, trying to
222 * minimize memory allocation/deallocation during normal operation.
224 * TODOs include (and will be done in order of public interest):
226 * Support for EXPLAIN - provide simple meta-database system.
227 * Support for access control.
228 * Support for resource control.
229 * Support for extended services - primarily Item Order.
230 * Rest of Z39.50-1994
245 #include <comstack.h>
251 #include <statserv.h>
255 static int process_request(association *assoc);
256 void backend_response(IOCHAN i, int event);
257 static int process_response(association *assoc, request *req, Z_APDU *res);
258 static Z_APDU *process_initRequest(association *assoc, request *reqb);
259 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
261 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
262 bend_searchresult *bsrt, int *fd);
263 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
265 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
266 static void process_close(association *assoc, request *reqb);
268 static FILE *apduf = 0; /* for use in static mode */
269 static statserv_options_block *control_block = 0;
272 * Create and initialize a new association-handle.
273 * channel : iochannel for the current line.
274 * link : communications channel.
275 * Returns: 0 or a new association handle.
277 association *create_association(IOCHAN channel, COMSTACK link)
282 control_block = statserv_getcontrol();
283 if (!(new = xmalloc(sizeof(*new))))
285 new->client_chan = channel;
286 new->client_link = link;
287 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
288 !(new->encode = odr_createmem(ODR_ENCODE)))
290 if (*control_block->apdufile)
295 strcpy(filename, control_block->apdufile);
296 if (!(new->print = odr_createmem(ODR_PRINT)))
298 if (*control_block->apdufile != '-')
300 strcpy(filename, control_block->apdufile);
301 if (!control_block->dynamic)
305 if (!(apduf = fopen(filename, "w")))
307 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
310 setvbuf(apduf, 0, _IONBF, 0);
316 sprintf(filename + strlen(filename), ".%d", getpid());
317 if (!(f = fopen(filename, "w")))
319 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
322 setvbuf(f, 0, _IONBF, 0);
324 odr_setprint(new->print, f);
329 new->input_buffer = 0;
330 new->input_buffer_len = 0;
332 new->state = ASSOC_NEW;
333 request_initq(&new->incoming);
334 request_initq(&new->outgoing);
335 new->proto = cs_getproto(link);
340 * Free association and release resources.
342 void destroy_association(association *h)
344 odr_destroy(h->decode);
345 odr_destroy(h->encode);
347 odr_destroy(h->print);
349 xfree(h->input_buffer);
351 bend_close(h->backend);
352 while (request_deq(&h->incoming));
353 while (request_deq(&h->outgoing));
354 request_delq(&h->incoming);
355 request_delq(&h->outgoing);
359 static void do_close(association *a, int reason, char *message)
362 Z_Close *cls = zget_Close(a->encode);
363 request *req = request_get(&a->outgoing);
365 /* Purge request queue */
366 while (request_deq(&a->incoming));
367 while (request_deq(&a->outgoing));
370 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
371 reason, message ? message : "none");
372 apdu.which = Z_APDU_close;
374 *cls->closeReason = reason;
375 cls->diagnosticInformation = message;
376 process_response(a, req, &apdu);
377 iochan_settimeout(a->client_chan, 60);
381 logf(LOG_DEBUG, "v2 client. No Close PDU");
382 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
384 a->state = ASSOC_DEAD;
388 * This is where PDUs from the client are read and the further
389 * processing is initiated. Flow of control moves down through the
390 * various process_* functions below, until the encoded result comes back up
391 * to the output handler in here.
393 * h : the I/O channel that has an outstanding event.
394 * event : the current outstanding event.
396 void ir_session(IOCHAN h, int event)
399 association *assoc = iochan_getdata(h);
400 COMSTACK conn = assoc->client_link;
403 assert(h && conn && assoc);
404 if (event == EVENT_TIMEOUT)
406 if (assoc->state != ASSOC_UP)
408 logf(LOG_LOG, "Final timeout - closing connection.");
410 destroy_association(assoc);
415 logf(LOG_LOG, "Session idle too long. Sending close.");
416 do_close(assoc, Z_Close_lackOfActivity, 0);
420 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
422 if (event & EVENT_INPUT)
424 logf(LOG_DEBUG, "ir_session (input)");
425 assert(assoc && conn);
426 /* We aren't speaking to this fellow */
427 if (assoc->state == ASSOC_DEAD)
429 logf(LOG_LOG, "Closed connection after reject");
431 destroy_association(assoc);
435 if ((res = cs_get(conn, &assoc->input_buffer,
436 &assoc->input_buffer_len)) <= 0)
438 logf(LOG_LOG, "Connection closed by client");
440 destroy_association(assoc);
444 else if (res == 1) /* incomplete read - wait for more */
446 if (cs_more(conn)) /* more stuff - call us again later, please */
447 iochan_setevent(h, EVENT_INPUT);
449 /* we got a complete PDU. Let's decode it */
450 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
451 req = request_get(&assoc->incoming); /* get a new request structure */
452 odr_reset(assoc->decode);
453 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
454 if (!z_APDU(assoc->decode, &req->request, 0))
456 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
457 odr_errmsg(odr_geterror(assoc->decode)),
458 odr_offset(assoc->decode));
459 logf(LOG_LOG, "PDU dump:");
460 odr_dumpBER(log_file(), assoc->input_buffer, res);
461 do_close(assoc, Z_Close_protocolError, "Malformed package");
464 req->request_mem = odr_extract_mem(assoc->decode);
465 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
467 logf(LOG_WARN, "ODR print error: %s",
468 odr_errmsg(odr_geterror(assoc->print)));
469 odr_reset(assoc->print);
471 request_enq(&assoc->incoming, req);
474 /* can we do something yet? */
475 req = request_head(&assoc->incoming);
476 if (req->state == REQUEST_IDLE)
477 if (process_request(assoc) < 0)
478 do_close(assoc, Z_Close_systemProblem, "Unknown error");
480 if (event & EVENT_OUTPUT)
482 request *req = request_head(&assoc->outgoing);
484 logf(LOG_DEBUG, "ir_session (output)");
485 req->state = REQUEST_PENDING;
486 switch (res = cs_put(conn, req->response, req->len_response))
489 logf(LOG_LOG, "Connection closed by client");
491 destroy_association(assoc);
494 case 0: /* all sent - release the request structure */
495 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
496 nmem_destroy(req->request_mem);
497 request_deq(&assoc->outgoing);
498 request_release(req);
499 if (!request_head(&assoc->outgoing))
500 iochan_clearflag(h, EVENT_OUTPUT);
502 /* value of 1 -- partial send -- is simply ignored */
505 if (event & EVENT_EXCEPT)
507 logf(LOG_DEBUG, "ir_session (exception)");
509 destroy_association(assoc);
515 * Initiate request processing.
517 static int process_request(association *assoc)
519 request *req = request_head(&assoc->incoming);
523 logf(LOG_DEBUG, "process_request");
524 assert(req && req->state == REQUEST_IDLE);
525 switch (req->request->which)
527 case Z_APDU_initRequest:
528 res = process_initRequest(assoc, req); break;
529 case Z_APDU_searchRequest:
530 res = process_searchRequest(assoc, req, &fd); break;
531 case Z_APDU_presentRequest:
532 res = process_presentRequest(assoc, req, &fd); break;
533 case Z_APDU_scanRequest:
534 res = process_scanRequest(assoc, req, &fd); break;
536 process_close(assoc, req); return 0;
538 logf(LOG_WARN, "Bad APDU received");
543 logf(LOG_DEBUG, " result immediately available");
544 return process_response(assoc, req, res);
548 logf(LOG_WARN, " bad result");
551 else /* no result yet - one will be provided later */
555 /* Set up an I/O handler for the fd supplied by the backend */
557 logf(LOG_DEBUG, " establishing handler for result");
558 req->state = REQUEST_PENDING;
559 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
561 iochan_setdata(chan, assoc);
567 * Handle message from the backend.
569 void backend_response(IOCHAN i, int event)
571 association *assoc = iochan_getdata(i);
572 request *req = request_head(&assoc->incoming);
576 logf(LOG_DEBUG, "backend_response");
577 assert(assoc && req && req->state != REQUEST_IDLE);
578 /* determine what it is we're waiting for */
579 switch (req->request->which)
581 case Z_APDU_searchRequest:
582 res = response_searchRequest(assoc, req, 0, &fd); break;
584 case Z_APDU_presentRequest:
585 res = response_presentRequest(assoc, req, 0, &fd); break;
586 case Z_APDU_scanRequest:
587 res = response_scanRequest(assoc, req, 0, &fd); break;
590 logf(LOG_WARN, "Serious programmer's lapse or bug");
593 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
595 logf(LOG_LOG, "Fatal error when talking to backend");
596 do_close(assoc, Z_Close_systemProblem, 0);
600 else if (!res) /* no result yet - try again later */
602 logf(LOG_DEBUG, " no result yet");
603 iochan_setfd(i, fd); /* in case fd has changed */
608 * Encode response, and transfer the request structure to the outgoing queue.
610 static int process_response(association *assoc, request *req, Z_APDU *res)
612 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
613 if (!z_APDU(assoc->encode, &res, 0))
615 logf(LOG_WARN, "ODR error when encoding response: %s",
616 odr_errmsg(odr_geterror(assoc->decode)));
617 odr_reset(assoc->encode);
620 req->response = odr_getbuf(assoc->encode, &req->len_response,
621 &req->size_response);
622 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
623 odr_reset(assoc->encode);
624 if (assoc->print && !z_APDU(assoc->print, &res, 0))
626 logf(LOG_WARN, "ODR print error: %s",
627 odr_errmsg(odr_geterror(assoc->print)));
628 odr_reset(assoc->print);
630 /* change this when we make the backend reentrant */
631 if (req == request_head(&assoc->incoming))
633 req->state = REQUEST_IDLE;
634 request_deq(&assoc->incoming);
636 request_enq(&assoc->outgoing, req);
637 /* turn the work over to the ir_session handler */
638 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
639 /* Is there more work to be done? give that to the input handler too */
640 if (request_head(&assoc->incoming))
641 iochan_setevent(assoc->client_chan, EVENT_WORK);
646 * Handle init request.
647 * At the moment, we don't check the options
648 * anywhere else in the code - we just try not to do anything that would
649 * break a naive client. We'll toss 'em into the association block when
650 * we need them there.
652 static Z_APDU *process_initRequest(association *assoc, request *reqb)
654 Z_InitRequest *req = reqb->request->u.initRequest;
655 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
656 Z_InitResponse *resp = apdu->u.initResponse;
657 bend_initrequest binitreq;
658 bend_initresult *binitres;
661 logf(LOG_LOG, "Got initRequest");
662 if (req->implementationId)
663 logf(LOG_LOG, "Id: %s", req->implementationId);
664 if (req->implementationName)
665 logf(LOG_LOG, "Name: %s", req->implementationName);
666 if (req->implementationVersion)
667 logf(LOG_LOG, "Version: %s", req->implementationVersion);
669 binitreq.configname = "default-config";
670 binitreq.auth = req->idAuthentication;
671 if (!(binitres = bend_init(&binitreq)))
673 logf(LOG_WARN, "Bad response from backend.");
677 assoc->backend = binitres->handle;
678 resp->referenceId = req->referenceId;
680 /* let's tell the client what we can do */
681 if (ODR_MASK_GET(req->options, Z_Options_search))
683 ODR_MASK_SET(resp->options, Z_Options_search);
684 strcat(options, "srch");
686 if (ODR_MASK_GET(req->options, Z_Options_present))
688 ODR_MASK_SET(resp->options, Z_Options_present);
689 strcat(options, " prst");
692 if (ODR_MASK_GET(req->options, Z_Options_delSet))
694 ODR_MASK_SET(&options, Z_Options_delSet);
695 strcat(options, " del");
698 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
700 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
701 strcat(options, " namedresults");
703 if (ODR_MASK_GET(req->options, Z_Options_scan))
705 ODR_MASK_SET(resp->options, Z_Options_scan);
706 strcat(options, " scan");
708 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
710 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
711 strcat(options, " concurop");
714 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
716 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
717 assoc->version = 2; /* 1 & 2 are equivalent */
719 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
721 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
724 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
726 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
729 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
730 assoc->maximumRecordSize = *req->maximumRecordSize;
731 if (assoc->maximumRecordSize > control_block->maxrecordsize)
732 assoc->maximumRecordSize = control_block->maxrecordsize;
733 assoc->preferredMessageSize = *req->preferredMessageSize;
734 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
735 assoc->preferredMessageSize = assoc->maximumRecordSize;
736 resp->preferredMessageSize = &assoc->preferredMessageSize;
737 resp->maximumRecordSize = &assoc->maximumRecordSize;
738 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
739 if (binitres->errcode)
741 logf(LOG_LOG, "Connection rejected by backend.");
743 assoc->state = ASSOC_DEAD;
746 assoc->state = ASSOC_UP;
751 * These functions should be merged.
755 * nonsurrogate diagnostic record.
757 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
759 Z_Records *rec = odr_malloc (assoc->encode, sizeof(*rec));
761 int *err = odr_malloc (assoc->encode, sizeof(*err));
762 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
763 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
765 bib1.proto = assoc->proto;
766 bib1.oclass = CLASS_DIAGSET;
767 bib1.value = VAL_BIB1;
769 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
772 rec->which = Z_Records_NSD;
774 rec->u.nonSurrogateDiagnostic = drec;
775 drec->which = Z_DiagRec_defaultFormat;
776 drec->u.defaultFormat = dr;
778 rec->u.nonSurrogateDiagnostic = dr;
780 dr->diagnosticSetId = oid_getoidbyent(&bib1);
782 dr->which = Z_DiagForm_v2AddInfo;
783 dr->addinfo = addinfo ? addinfo : "";
788 * surrogate diagnostic.
790 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
791 int error, char *addinfo)
793 Z_NamePlusRecord *rec = odr_malloc (assoc->encode, sizeof(*rec));
794 int *err = odr_malloc (assoc->encode, sizeof(*err));
796 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
797 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
799 bib1.proto = assoc->proto;
800 bib1.oclass = CLASS_DIAGSET;
801 bib1.value = VAL_BIB1;
803 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
805 rec->databaseName = dbname;
806 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
807 rec->u.surrogateDiagnostic = drec;
808 drec->which = Z_DiagRec_defaultFormat;
809 drec->u.defaultFormat = dr;
810 dr->diagnosticSetId = oid_getoidbyent(&bib1);
812 dr->which = Z_DiagForm_v2AddInfo;
813 dr->addinfo = addinfo ? addinfo : "";
818 * multiple nonsurrogate diagnostics.
820 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
822 Z_DiagRecs *recs = odr_malloc (assoc->encode, sizeof(*recs));
823 int *err = odr_malloc (assoc->encode, sizeof(*err));
825 Z_DiagRec **recp = odr_malloc (assoc->encode, sizeof(*recp));
826 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
827 Z_DefaultDiagFormat *rec = odr_malloc (assoc->encode, sizeof(*rec));
829 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
830 bib1.proto = assoc->proto;
831 bib1.oclass = CLASS_DIAGSET;
832 bib1.value = VAL_BIB1;
835 recs->num_diagRecs = 1;
836 recs->diagRecs = recp;
838 drec->which = Z_DiagRec_defaultFormat;
839 drec->u.defaultFormat = rec;
841 rec->diagnosticSetId = oid_getoidbyent(&bib1);
842 rec->condition = err;
843 rec->which = Z_DiagForm_v2AddInfo;
844 rec->addinfo = addinfo ? addinfo : "";
848 static Z_Records *pack_records(association *a, char *setname, int start,
849 int *num, Z_RecordComposition *comp,
850 int *next, int *pres, oid_value format)
852 int recno, total_length = 0, toget = *num, dumped_records = 0;
853 Z_Records *records = odr_malloc (a->encode, sizeof(*records));
854 Z_NamePlusRecordList *reclist = odr_malloc (a->encode, sizeof(*reclist));
855 Z_NamePlusRecord **list = odr_malloc (a->encode, sizeof(*list) * toget);
858 records->which = Z_Records_DBOSD;
859 records->u.databaseOrSurDiagnostics = reclist;
860 reclist->num_records = 0;
861 reclist->records = list;
862 *pres = Z_PRES_SUCCESS;
866 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
867 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
868 a->maximumRecordSize);
869 for (recno = start; reclist->num_records < toget; recno++)
871 bend_fetchrequest freq;
872 bend_fetchresult *fres;
873 Z_NamePlusRecord *thisrec;
874 Z_DatabaseRecord *thisext;
878 * we get the number of bytes allocated on the stream before any
879 * allocation done by the backend - this should give us a reasonable
880 * idea of the total size of the data so far.
882 total_length = odr_total(a->encode) - dumped_records;
883 freq.setname = setname;
886 freq.format = format;
887 freq.stream = a->encode;
888 if (!(fres = bend_fetch(a->backend, &freq, 0)))
890 *pres = Z_PRES_FAILURE;
891 return diagrec(a, 2, "Backend interface problem");
893 /* backend should be able to signal whether error is system-wide
894 or only pertaining to current record */
897 *pres = Z_PRES_FAILURE;
898 return diagrec(a, fres->errcode, fres->errstring);
901 this_length = fres->len;
903 this_length = odr_total(a->encode) - total_length;
904 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
905 this_length, total_length);
906 if (this_length + total_length > a->preferredMessageSize)
908 /* record is small enough, really */
909 if (this_length <= a->preferredMessageSize)
911 logf(LOG_DEBUG, " Dropped last normal-sized record");
912 *pres = Z_PRES_PARTIAL_2;
915 /* record can only be fetched by itself */
916 if (this_length < a->maximumRecordSize)
918 logf(LOG_DEBUG, " Record > prefmsgsz");
921 logf(LOG_DEBUG, " Dropped it");
922 reclist->records[reclist->num_records] =
923 surrogatediagrec(a, fres->basename, 16, 0);
924 reclist->num_records++;
925 *next = fres->last_in_set ? 0 : recno + 1;
926 dumped_records += this_length;
930 else /* too big entirely */
932 logf(LOG_DEBUG, "Record > maxrcdsz");
933 reclist->records[reclist->num_records] =
934 surrogatediagrec(a, fres->basename, 17, 0);
935 reclist->num_records++;
936 *next = fres->last_in_set ? 0 : recno + 1;
937 dumped_records += this_length;
941 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
943 if (!(thisrec->databaseName = odr_malloc(a->encode,
944 strlen(fres->basename) + 1)))
946 strcpy(thisrec->databaseName, fres->basename);
947 thisrec->which = Z_NamePlusRecord_databaseRecord;
948 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
949 sizeof(Z_DatabaseRecord))))
951 recform.proto = a->proto;
952 recform.oclass = CLASS_RECSYN;
953 recform.value = fres->format;
954 thisext->direct_reference = odr_oiddup(a->encode,
955 oid_getoidbyent(&recform));
956 thisext->indirect_reference = 0;
957 thisext->descriptor = 0;
958 if (fres->len < 0) /* Structured data */
960 switch (fres->format)
962 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
963 case VAL_GRS1: thisext->which = Z_External_grs1; break;
964 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
966 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
967 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
970 logf(LOG_FATAL, "Unknown structured format from backend.");
975 * We cheat on the pointers here. Obviously, the record field
976 * of the backend-fetch structure should have been a union for
977 * correctness, but we're stuck with this for backwards
980 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
982 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
984 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
986 thisext->which = Z_External_sutrs;
987 thisext->u.sutrs = sutrs;
988 sutrs->buf = odr_malloc(a->encode, fres->len);
989 sutrs->len = sutrs->size = fres->len;
990 memcpy(sutrs->buf, fres->record, fres->len);
992 else /* octet-aligned record. */
994 thisext->which = Z_External_octet;
995 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
998 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1001 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1002 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1005 reclist->records[reclist->num_records] = thisrec;
1006 reclist->num_records++;
1007 *next = fres->last_in_set ? 0 : recno + 1;
1009 *num = reclist->num_records;
1013 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1016 Z_SearchRequest *req = reqb->request->u.searchRequest;
1017 bend_searchrequest bsrq;
1018 bend_searchresult *bsrt;
1020 logf(LOG_LOG, "Got SearchRequest.");
1022 bsrq.setname = req->resultSetName;
1023 bsrq.replace_set = *req->replaceIndicator;
1024 bsrq.num_bases = req->num_databaseNames;
1025 bsrq.basenames = req->databaseNames;
1026 bsrq.query = req->query;
1028 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1030 return response_searchRequest(assoc, reqb, bsrt, fd);
1033 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1036 * Prepare a searchresponse based on the backend results. We probably want
1037 * to look at making the fetching of records nonblocking as well, but
1038 * so far, we'll keep things simple.
1039 * If bsrt is null, that means we're called in response to a communications
1040 * event, and we'll have to get the response for ourselves.
1042 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1043 bend_searchresult *bsrt, int *fd)
1045 Z_SearchRequest *req = reqb->request->u.searchRequest;
1046 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1047 Z_SearchResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1048 int *nulint = odr_malloc (assoc->encode, sizeof(*nulint));
1049 bool_t *sr = odr_malloc (assoc->encode, sizeof(*sr));
1050 int *next = odr_malloc (assoc->encode, sizeof(*next));
1051 int *none = odr_malloc (assoc->encode, sizeof(*none));
1058 apdu->which = Z_APDU_searchResponse;
1059 apdu->u.searchResponse = resp;
1060 resp->referenceId = req->referenceId;
1061 resp->additionalSearchInfo = 0;
1062 resp->otherInfo = 0;
1064 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1066 logf(LOG_FATAL, "Bad result from backend");
1069 else if (bsrt->errcode)
1071 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1072 resp->resultCount = nulint;
1073 resp->numberOfRecordsReturned = nulint;
1074 resp->nextResultSetPosition = nulint;
1075 resp->searchStatus = nulint;
1076 resp->resultSetStatus = none;
1077 resp->presentStatus = 0;
1081 int *toget = odr_malloc (assoc->encode, sizeof(*toget));
1082 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1083 Z_RecordComposition comp, *compp = 0;
1088 resp->resultCount = &bsrt->hits;
1090 comp.which = Z_RecordComp_simple;
1091 /* how many records does the user agent want, then? */
1092 if (bsrt->hits <= *req->smallSetUpperBound)
1094 *toget = bsrt->hits;
1095 if ((comp.u.simple = req->smallSetElementSetNames))
1098 else if (bsrt->hits < *req->largeSetLowerBound)
1100 *toget = *req->mediumSetPresentNumber;
1101 if (*toget > bsrt->hits)
1102 *toget = bsrt->hits;
1103 if ((comp.u.simple = req->mediumSetElementSetNames))
1109 if (*toget && !resp->records)
1114 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1115 prefformat->oclass != CLASS_RECSYN)
1118 form = prefformat->value;
1119 resp->records = pack_records(assoc, req->resultSetName, 1,
1120 toget, compp, next, presst, form);
1123 resp->numberOfRecordsReturned = toget;
1124 resp->nextResultSetPosition = next;
1125 resp->searchStatus = sr;
1126 resp->resultSetStatus = 0;
1127 resp->presentStatus = presst;
1131 if (*resp->resultCount)
1133 resp->numberOfRecordsReturned = nulint;
1134 resp->nextResultSetPosition = next;
1135 resp->searchStatus = sr;
1136 resp->resultSetStatus = 0;
1137 resp->presentStatus = 0;
1144 * Maybe we got a little over-friendly when we designed bend_fetch to
1145 * get only one record at a time. Some backends can optimise multiple-record
1146 * fetches, and at any rate, there is some overhead involved in
1147 * all that selecting and hopping around. Problem is, of course, that the
1148 * frontend can't know ahead of time how many records it'll need to
1149 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1150 * is downright lousy as a bulk data transfer protocol.
1152 * To start with, we'll do the fetching of records from the backend
1153 * in one operation: To save some trips in and out of the event-handler,
1154 * and to simplify the interface to pack_records. At any rate, asynch
1155 * operation is more fun in operations that have an unpredictable execution
1156 * speed - which is normally more true for search than for present.
1158 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1161 Z_PresentRequest *req = reqb->request->u.presentRequest;
1162 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1163 Z_PresentResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1164 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1165 int *next = odr_malloc (assoc->encode, sizeof(*next));
1166 int *num = odr_malloc (assoc->encode, sizeof(*num));
1170 logf(LOG_LOG, "Got PresentRequest.");
1175 apdu->which = Z_APDU_presentResponse;
1176 apdu->u.presentResponse = resp;
1177 resp->referenceId = req->referenceId;
1178 resp->otherInfo = 0;
1180 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1181 prefformat->oclass != CLASS_RECSYN)
1184 form = prefformat->value;
1185 *num = *req->numberOfRecordsRequested;
1186 resp->records = pack_records(assoc, req->resultSetId,
1187 *req->resultSetStartPoint, num, req->recordComposition, next,
1191 resp->numberOfRecordsReturned = num;
1192 resp->presentStatus = presst;
1193 resp->nextResultSetPosition = next;
1199 * Scan was implemented rather in a hurry, and with support for only the basic
1200 * elements of the service in the backend API. Suggestions are welcome.
1202 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1204 Z_ScanRequest *req = reqb->request->u.scanRequest;
1205 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1206 Z_ScanResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1207 int *scanStatus = odr_malloc (assoc->encode, sizeof(*scanStatus));
1208 int *numberOfEntriesReturned =
1209 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1210 Z_ListEntries *ents = odr_malloc (assoc->encode, sizeof(*ents));
1212 bend_scanrequest srq;
1213 bend_scanresult *srs;
1216 logf(LOG_LOG, "Got scanrequest");
1217 *scanStatus = Z_Scan_failure;
1218 *numberOfEntriesReturned = 0;
1220 apdu->which = Z_APDU_scanResponse;
1221 apdu->u.scanResponse = res;
1222 res->referenceId = req->referenceId;
1224 res->scanStatus = scanStatus;
1225 res->numberOfEntriesReturned = numberOfEntriesReturned;
1226 res->positionOfTerm = 0;
1227 res->entries = ents;
1228 ents->which = Z_ListEntries_nonSurrogateDiagnostics;
1229 res->attributeSet = 0;
1232 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1233 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1234 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 121, 0);
1235 else if (req->stepSize && *req->stepSize > 0)
1236 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 205, 0);
1239 if (req->termListAndStartPoint->term->which == Z_Term_general)
1240 logf(LOG_DEBUG, " term: '%.*s'",
1241 req->termListAndStartPoint->term->u.general->len,
1242 req->termListAndStartPoint->term->u.general->buf);
1243 srq.num_bases = req->num_databaseNames;
1244 srq.basenames = req->databaseNames;
1245 srq.num_entries = *req->numberOfTermsRequested;
1246 srq.term = req->termListAndStartPoint;
1247 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1248 attset->oclass != CLASS_RECSYN)
1249 srq.attributeset = VAL_NONE;
1251 srq.attributeset = attset->value;
1252 srq.term_position = req->preferredPositionInResponse ?
1253 *req->preferredPositionInResponse : 1;
1254 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1255 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 2, 0);
1256 else if (srs->errcode)
1257 ents->u.nonSurrogateDiagnostics = diagrecs(assoc,
1258 srs->errcode, srs->errstring);
1262 Z_Entries *list = odr_malloc (assoc->encode, sizeof(*list));
1263 Z_Entry **tab = odr_malloc (assoc->encode,
1264 sizeof(*tab) * srs->num_entries);
1266 if (srs->status == BEND_SCAN_PARTIAL)
1267 *scanStatus = Z_Scan_partial_5;
1269 *scanStatus = Z_Scan_success;
1270 ents->which = Z_ListEntries_entries;
1271 ents->u.entries = list;
1272 list->entries = tab;
1273 for (i = 0; i < srs->num_entries; i++)
1279 list->entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1280 e->which = Z_Entry_termInfo;
1281 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1282 t->suggestedAttributes = 0;
1284 t->alternativeTerm = 0;
1285 t->byAttributes = 0;
1286 t->otherTermInfo = 0;
1287 t->globalOccurrences = &srs->entries[i].occurrences;
1288 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1289 t->term->which = Z_Term_general;
1290 t->term->u.general = o = odr_malloc(assoc->encode,
1292 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1293 strlen(srs->entries[i].term));
1294 memcpy(o->buf, srs->entries[i].term, o->len);
1295 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1296 srs->entries[i].term, srs->entries[i].occurrences);
1298 list->num_entries = i;
1299 res->numberOfEntriesReturned = &list->num_entries;
1300 res->positionOfTerm = &srs->term_position;
1307 static void process_close(association *assoc, request *reqb)
1309 Z_Close *req = reqb->request->u.close;
1310 static char *reasons[] =
1317 "securityViolation",
1324 logf(LOG_LOG, "Got close, reason %s, message %s",
1325 reasons[*req->closeReason], req->diagnosticInformation ?
1326 req->diagnosticInformation : "NULL");
1327 if (assoc->version < 3) /* to make do_force respond with close */
1329 do_close(assoc, Z_Close_finished, "Association terminated by client");