2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.67 1997-09-17 12:10:40 adam
10 * Revision 1.66 1997/09/05 15:26:44 adam
11 * Added ODR encode in search and scen bend request structures.
12 * Fixed a few enums that caused trouble with C++.
14 * Revision 1.65 1997/09/01 08:53:01 adam
15 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
16 * moved a separate directory. MSV5.0 project server.dsp created.
17 * As an option, the server can now operate as an NT service.
19 * Revision 1.64 1997/04/30 08:52:11 quinn
22 * Revision 1.63 1996/10/11 11:57:26 quinn
25 * Revision 1.62 1996/07/06 19:58:35 quinn
26 * System headerfiles gathered in yconfig
28 * Revision 1.61 1996/06/10 08:56:16 quinn
31 * Revision 1.60 1996/05/30 11:03:10 quinn
32 * Fixed NextresultSetPosition bug fixed.
34 * Revision 1.59 1996/05/14 09:26:46 quinn
35 * Added attribute set to scan backend
37 * Revision 1.58 1996/02/20 12:53:04 quinn
40 * Revision 1.57 1996/01/02 08:57:47 quinn
41 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
43 * Revision 1.56 1995/12/14 11:09:57 quinn
46 * Revision 1.55 1995/11/08 17:41:37 quinn
49 * Revision 1.54 1995/11/08 15:11:29 quinn
50 * Log of close transmit.
52 * Revision 1.53 1995/11/01 13:54:58 quinn
55 * Revision 1.52 1995/11/01 12:19:13 quinn
56 * Second attempt to fix same bug.
58 * Revision 1.50 1995/10/25 16:58:32 quinn
61 * Revision 1.49 1995/10/16 13:51:53 quinn
62 * Changes to provide Especs to the backend.
64 * Revision 1.48 1995/10/06 08:51:20 quinn
67 * Revision 1.47 1995/08/29 14:24:16 quinn
68 * Added second half of close-handshake
70 * Revision 1.46 1995/08/29 11:17:58 quinn
71 * Added code to receive close
73 * Revision 1.45 1995/08/21 09:11:00 quinn
74 * Smallish fixes to suppport new formats.
76 * Revision 1.44 1995/08/17 12:45:25 quinn
77 * Fixed minor problems with GRS-1. Added support in c&s.
79 * Revision 1.43 1995/08/15 12:00:31 quinn
82 * Revision 1.42 1995/08/15 11:16:50 quinn
84 * Revision 1.41 1995/08/02 10:23:06 quinn
87 * Revision 1.40 1995/07/31 14:34:26 quinn
88 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
90 * Revision 1.39 1995/06/27 13:21:00 quinn
93 * Revision 1.38 1995/06/19 12:39:11 quinn
94 * Fixed bug in timeout code. Added BER dumper.
96 * Revision 1.37 1995/06/16 13:16:14 quinn
97 * Fixed Defaultdiagformat.
99 * Revision 1.36 1995/06/16 10:31:36 quinn
100 * Added session timeout.
102 * Revision 1.35 1995/06/15 07:45:14 quinn
105 * Revision 1.34 1995/06/14 15:26:46 quinn
106 * *** empty log message ***
108 * Revision 1.33 1995/06/06 14:57:05 quinn
109 * Better diagnostics.
111 * Revision 1.32 1995/06/06 08:41:44 quinn
112 * Better diagnostics.
114 * Revision 1.31 1995/06/06 08:15:37 quinn
117 * Revision 1.30 1995/06/05 10:53:32 quinn
118 * Added a better SCAN.
120 * Revision 1.29 1995/06/01 11:25:03 quinn
123 * Revision 1.28 1995/06/01 11:21:01 quinn
124 * Attempting to fix a bug in pack-records. replaced break with continue
125 * for large records, according to standard.
127 * Revision 1.27 1995/05/29 08:12:06 quinn
130 * Revision 1.26 1995/05/18 13:02:12 quinn
133 * Revision 1.25 1995/05/17 08:42:26 quinn
134 * Transfer auth info to backend. Allow backend to reject init gracefully.
136 * Revision 1.24 1995/05/16 08:51:04 quinn
137 * License, documentation, and memory fixes
139 * Revision 1.23 1995/05/15 13:25:10 quinn
142 * Revision 1.22 1995/05/15 11:56:39 quinn
143 * Asynchronous facilities. Restructuring of seshigh code.
145 * Revision 1.21 1995/05/02 08:53:19 quinn
146 * Trying in vain to fix comm with ISODE
148 * Revision 1.20 1995/04/20 15:13:00 quinn
151 * Revision 1.19 1995/04/18 08:15:34 quinn
152 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
153 * neater. We'll make the same change for decoding one day.
155 * Revision 1.18 1995/04/17 11:28:25 quinn
158 * Revision 1.17 1995/04/10 10:23:36 quinn
159 * Some work to add scan and other things.
161 * Revision 1.16 1995/03/31 09:18:55 quinn
164 * Revision 1.15 1995/03/30 14:03:23 quinn
165 * Added RFC1006 as separate library
167 * Revision 1.14 1995/03/30 12:18:17 quinn
170 * Revision 1.13 1995/03/30 09:09:24 quinn
171 * Added state-handle and some support for asynchronous activities.
173 * Revision 1.12 1995/03/29 15:40:16 quinn
174 * Ongoing work. Statserv is now dynamic by default
176 * Revision 1.11 1995/03/28 09:16:21 quinn
177 * Added record packing to the search request
179 * Revision 1.10 1995/03/27 08:34:24 quinn
180 * Added dynamic server functionality.
181 * Released bindings to session.c (is now redundant)
183 * Revision 1.9 1995/03/22 15:01:26 quinn
184 * Adjusting record packing.
186 * Revision 1.8 1995/03/22 10:13:21 quinn
187 * Working on record packer
189 * Revision 1.7 1995/03/21 15:53:31 quinn
192 * Revision 1.6 1995/03/21 12:30:09 quinn
193 * Beginning to add support for record packing.
195 * Revision 1.5 1995/03/17 10:44:13 quinn
196 * Added catch of null-string in makediagrec
198 * Revision 1.4 1995/03/17 10:18:08 quinn
199 * Added memory management.
201 * Revision 1.3 1995/03/16 17:42:39 quinn
204 * Revision 1.2 1995/03/16 13:29:01 quinn
205 * Partitioned server.
207 * Revision 1.1 1995/03/15 16:02:10 quinn
208 * Modded session.c to seshigh.c
213 * Frontend server logic.
215 * This code receives incoming APDUs, and handles client requests by means
216 * of the backend API.
218 * Some of the code is getting quite involved, compared to simpler servers -
219 * primarily because it is asynchronous both in the communication with
220 * the user and the backend. We think the complexity will pay off in
221 * the form of greater flexibility when more asynchronous facilities
224 * Memory management has become somewhat involved. In the simple case, where
225 * only one PDU is pending at a time, it will simply reuse the same memory,
226 * once it has found its working size. When we enable multiple concurrent
227 * operations, perhaps even with multiple parallel calls to the backend, it
228 * will maintain a pool of buffers for encoding and decoding, trying to
229 * minimize memory allocation/deallocation during normal operation.
231 * TODOs include (and will be done in order of public interest):
233 * Support for EXPLAIN - provide simple meta-database system.
234 * Support for access control.
235 * Support for resource control.
236 * Support for extended services - primarily Item Order.
237 * Rest of Z39.50-1994
252 #include <comstack.h>
258 #include <statserv.h>
262 static int process_request(association *assoc);
263 void backend_response(IOCHAN i, int event);
264 static int process_response(association *assoc, request *req, Z_APDU *res);
265 static Z_APDU *process_initRequest(association *assoc, request *reqb);
266 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
268 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
269 bend_searchresult *bsrt, int *fd);
270 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
272 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
273 static void process_close(association *assoc, request *reqb);
275 static FILE *apduf = 0; /* for use in static mode */
276 static statserv_options_block *control_block = 0;
279 * Create and initialize a new association-handle.
280 * channel : iochannel for the current line.
281 * link : communications channel.
282 * Returns: 0 or a new association handle.
284 association *create_association(IOCHAN channel, COMSTACK link)
289 control_block = statserv_getcontrol();
290 if (!(new = xmalloc(sizeof(*new))))
292 new->client_chan = channel;
293 new->client_link = link;
294 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
295 !(new->encode = odr_createmem(ODR_ENCODE)))
297 if (*control_block->apdufile)
302 strcpy(filename, control_block->apdufile);
303 if (!(new->print = odr_createmem(ODR_PRINT)))
305 if (*control_block->apdufile != '-')
307 strcpy(filename, control_block->apdufile);
308 if (!control_block->dynamic)
312 if (!(apduf = fopen(filename, "w")))
314 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
317 setvbuf(apduf, 0, _IONBF, 0);
323 sprintf(filename + strlen(filename), ".%d", getpid());
324 if (!(f = fopen(filename, "w")))
326 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
329 setvbuf(f, 0, _IONBF, 0);
331 odr_setprint(new->print, f);
336 new->input_buffer = 0;
337 new->input_buffer_len = 0;
339 new->state = ASSOC_NEW;
340 request_initq(&new->incoming);
341 request_initq(&new->outgoing);
342 new->proto = cs_getproto(link);
347 * Free association and release resources.
349 void destroy_association(association *h)
351 odr_destroy(h->decode);
352 odr_destroy(h->encode);
354 odr_destroy(h->print);
356 xfree(h->input_buffer);
358 bend_close(h->backend);
359 while (request_deq(&h->incoming));
360 while (request_deq(&h->outgoing));
361 request_delq(&h->incoming);
362 request_delq(&h->outgoing);
366 static void do_close(association *a, int reason, char *message)
369 Z_Close *cls = zget_Close(a->encode);
370 request *req = request_get(&a->outgoing);
372 /* Purge request queue */
373 while (request_deq(&a->incoming));
374 while (request_deq(&a->outgoing));
377 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
378 reason, message ? message : "none");
379 apdu.which = Z_APDU_close;
381 *cls->closeReason = reason;
382 cls->diagnosticInformation = message;
383 process_response(a, req, &apdu);
384 iochan_settimeout(a->client_chan, 60);
388 logf(LOG_DEBUG, "v2 client. No Close PDU");
389 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
391 a->state = ASSOC_DEAD;
395 * This is where PDUs from the client are read and the further
396 * processing is initiated. Flow of control moves down through the
397 * various process_* functions below, until the encoded result comes back up
398 * to the output handler in here.
400 * h : the I/O channel that has an outstanding event.
401 * event : the current outstanding event.
403 void ir_session(IOCHAN h, int event)
406 association *assoc = iochan_getdata(h);
407 COMSTACK conn = assoc->client_link;
410 assert(h && conn && assoc);
411 if (event == EVENT_TIMEOUT)
413 if (assoc->state != ASSOC_UP)
415 logf(LOG_LOG, "Final timeout - closing connection.");
417 destroy_association(assoc);
422 logf(LOG_LOG, "Session idle too long. Sending close.");
423 do_close(assoc, Z_Close_lackOfActivity, 0);
427 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
429 if (event & EVENT_INPUT)
431 logf(LOG_DEBUG, "ir_session (input)");
432 assert(assoc && conn);
433 /* We aren't speaking to this fellow */
434 if (assoc->state == ASSOC_DEAD)
436 logf(LOG_LOG, "Closed connection after reject");
438 destroy_association(assoc);
442 if ((res = cs_get(conn, &assoc->input_buffer,
443 &assoc->input_buffer_len)) <= 0)
445 logf(LOG_LOG, "Connection closed by client");
447 destroy_association(assoc);
451 else if (res == 1) /* incomplete read - wait for more */
453 if (cs_more(conn)) /* more stuff - call us again later, please */
454 iochan_setevent(h, EVENT_INPUT);
456 /* we got a complete PDU. Let's decode it */
457 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
458 req = request_get(&assoc->incoming); /* get a new request structure */
459 odr_reset(assoc->decode);
460 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
461 if (!z_APDU(assoc->decode, &req->request, 0))
463 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
464 odr_errmsg(odr_geterror(assoc->decode)),
465 odr_offset(assoc->decode));
466 logf(LOG_LOG, "PDU dump:");
467 odr_dumpBER(log_file(), assoc->input_buffer, res);
468 do_close(assoc, Z_Close_protocolError, "Malformed package");
471 req->request_mem = odr_extract_mem(assoc->decode);
472 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
474 logf(LOG_WARN, "ODR print error: %s",
475 odr_errmsg(odr_geterror(assoc->print)));
476 odr_reset(assoc->print);
478 request_enq(&assoc->incoming, req);
481 /* can we do something yet? */
482 req = request_head(&assoc->incoming);
483 if (req->state == REQUEST_IDLE)
484 if (process_request(assoc) < 0)
485 do_close(assoc, Z_Close_systemProblem, "Unknown error");
487 if (event & EVENT_OUTPUT)
489 request *req = request_head(&assoc->outgoing);
491 logf(LOG_DEBUG, "ir_session (output)");
492 req->state = REQUEST_PENDING;
493 switch (res = cs_put(conn, req->response, req->len_response))
496 logf(LOG_LOG, "Connection closed by client");
498 destroy_association(assoc);
501 case 0: /* all sent - release the request structure */
502 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
503 nmem_destroy(req->request_mem);
504 request_deq(&assoc->outgoing);
505 request_release(req);
506 if (!request_head(&assoc->outgoing))
507 iochan_clearflag(h, EVENT_OUTPUT);
509 /* value of 1 -- partial send -- is simply ignored */
512 if (event & EVENT_EXCEPT)
514 logf(LOG_DEBUG, "ir_session (exception)");
516 destroy_association(assoc);
522 * Initiate request processing.
524 static int process_request(association *assoc)
526 request *req = request_head(&assoc->incoming);
530 logf(LOG_DEBUG, "process_request");
531 assert(req && req->state == REQUEST_IDLE);
532 switch (req->request->which)
534 case Z_APDU_initRequest:
535 res = process_initRequest(assoc, req); break;
536 case Z_APDU_searchRequest:
537 res = process_searchRequest(assoc, req, &fd); break;
538 case Z_APDU_presentRequest:
539 res = process_presentRequest(assoc, req, &fd); break;
540 case Z_APDU_scanRequest:
541 res = process_scanRequest(assoc, req, &fd); break;
543 process_close(assoc, req); return 0;
545 logf(LOG_WARN, "Bad APDU received");
550 logf(LOG_DEBUG, " result immediately available");
551 return process_response(assoc, req, res);
555 logf(LOG_WARN, " bad result");
558 else /* no result yet - one will be provided later */
562 /* Set up an I/O handler for the fd supplied by the backend */
564 logf(LOG_DEBUG, " establishing handler for result");
565 req->state = REQUEST_PENDING;
566 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
568 iochan_setdata(chan, assoc);
574 * Handle message from the backend.
576 void backend_response(IOCHAN i, int event)
578 association *assoc = iochan_getdata(i);
579 request *req = request_head(&assoc->incoming);
583 logf(LOG_DEBUG, "backend_response");
584 assert(assoc && req && req->state != REQUEST_IDLE);
585 /* determine what it is we're waiting for */
586 switch (req->request->which)
588 case Z_APDU_searchRequest:
589 res = response_searchRequest(assoc, req, 0, &fd); break;
591 case Z_APDU_presentRequest:
592 res = response_presentRequest(assoc, req, 0, &fd); break;
593 case Z_APDU_scanRequest:
594 res = response_scanRequest(assoc, req, 0, &fd); break;
597 logf(LOG_WARN, "Serious programmer's lapse or bug");
600 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
602 logf(LOG_LOG, "Fatal error when talking to backend");
603 do_close(assoc, Z_Close_systemProblem, 0);
607 else if (!res) /* no result yet - try again later */
609 logf(LOG_DEBUG, " no result yet");
610 iochan_setfd(i, fd); /* in case fd has changed */
615 * Encode response, and transfer the request structure to the outgoing queue.
617 static int process_response(association *assoc, request *req, Z_APDU *res)
619 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
620 if (!z_APDU(assoc->encode, &res, 0))
622 logf(LOG_WARN, "ODR error when encoding response: %s",
623 odr_errmsg(odr_geterror(assoc->decode)));
624 odr_reset(assoc->encode);
627 req->response = odr_getbuf(assoc->encode, &req->len_response,
628 &req->size_response);
629 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
630 odr_reset(assoc->encode);
631 if (assoc->print && !z_APDU(assoc->print, &res, 0))
633 logf(LOG_WARN, "ODR print error: %s",
634 odr_errmsg(odr_geterror(assoc->print)));
635 odr_reset(assoc->print);
637 /* change this when we make the backend reentrant */
638 if (req == request_head(&assoc->incoming))
640 req->state = REQUEST_IDLE;
641 request_deq(&assoc->incoming);
643 request_enq(&assoc->outgoing, req);
644 /* turn the work over to the ir_session handler */
645 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
646 /* Is there more work to be done? give that to the input handler too */
647 if (request_head(&assoc->incoming))
648 iochan_setevent(assoc->client_chan, EVENT_WORK);
653 * Handle init request.
654 * At the moment, we don't check the options
655 * anywhere else in the code - we just try not to do anything that would
656 * break a naive client. We'll toss 'em into the association block when
657 * we need them there.
659 static Z_APDU *process_initRequest(association *assoc, request *reqb)
661 Z_InitRequest *req = reqb->request->u.initRequest;
662 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
663 Z_InitResponse *resp = apdu->u.initResponse;
664 bend_initrequest binitreq;
665 bend_initresult *binitres;
668 logf(LOG_LOG, "Got initRequest");
669 if (req->implementationId)
670 logf(LOG_LOG, "Id: %s", req->implementationId);
671 if (req->implementationName)
672 logf(LOG_LOG, "Name: %s", req->implementationName);
673 if (req->implementationVersion)
674 logf(LOG_LOG, "Version: %s", req->implementationVersion);
676 binitreq.stream = assoc->encode;
677 binitreq.configname = "default-config";
678 binitreq.auth = req->idAuthentication;
679 if (!(binitres = bend_init(&binitreq)))
681 logf(LOG_WARN, "Bad response from backend.");
685 assoc->backend = binitres->handle;
686 resp->referenceId = req->referenceId;
688 /* let's tell the client what we can do */
689 if (ODR_MASK_GET(req->options, Z_Options_search))
691 ODR_MASK_SET(resp->options, Z_Options_search);
692 strcat(options, "srch");
694 if (ODR_MASK_GET(req->options, Z_Options_present))
696 ODR_MASK_SET(resp->options, Z_Options_present);
697 strcat(options, " prst");
700 if (ODR_MASK_GET(req->options, Z_Options_delSet))
702 ODR_MASK_SET(&options, Z_Options_delSet);
703 strcat(options, " del");
706 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
708 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
709 strcat(options, " namedresults");
711 if (ODR_MASK_GET(req->options, Z_Options_scan))
713 ODR_MASK_SET(resp->options, Z_Options_scan);
714 strcat(options, " scan");
716 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
718 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
719 strcat(options, " concurop");
722 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
724 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
725 assoc->version = 2; /* 1 & 2 are equivalent */
727 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
729 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
732 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
734 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
737 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
738 assoc->maximumRecordSize = *req->maximumRecordSize;
739 if (assoc->maximumRecordSize > control_block->maxrecordsize)
740 assoc->maximumRecordSize = control_block->maxrecordsize;
741 assoc->preferredMessageSize = *req->preferredMessageSize;
742 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
743 assoc->preferredMessageSize = assoc->maximumRecordSize;
744 resp->preferredMessageSize = &assoc->preferredMessageSize;
745 resp->maximumRecordSize = &assoc->maximumRecordSize;
746 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
747 if (binitres->errcode)
749 logf(LOG_LOG, "Connection rejected by backend.");
751 assoc->state = ASSOC_DEAD;
754 assoc->state = ASSOC_UP;
759 * These functions should be merged.
763 * nonsurrogate diagnostic record.
765 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
767 Z_Records *rec = odr_malloc (assoc->encode, sizeof(*rec));
769 int *err = odr_malloc (assoc->encode, sizeof(*err));
770 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
771 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
773 bib1.proto = assoc->proto;
774 bib1.oclass = CLASS_DIAGSET;
775 bib1.value = VAL_BIB1;
777 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
780 rec->which = Z_Records_NSD;
782 rec->u.nonSurrogateDiagnostic = drec;
783 drec->which = Z_DiagRec_defaultFormat;
784 drec->u.defaultFormat = dr;
786 rec->u.nonSurrogateDiagnostic = dr;
788 dr->diagnosticSetId = oid_getoidbyent(&bib1);
790 dr->which = Z_DiagForm_v2AddInfo;
791 dr->addinfo = addinfo ? addinfo : "";
796 * surrogate diagnostic.
798 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
799 int error, char *addinfo)
801 Z_NamePlusRecord *rec = odr_malloc (assoc->encode, sizeof(*rec));
802 int *err = odr_malloc (assoc->encode, sizeof(*err));
804 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
805 Z_DefaultDiagFormat *dr = odr_malloc (assoc->encode, sizeof(*dr));
807 bib1.proto = assoc->proto;
808 bib1.oclass = CLASS_DIAGSET;
809 bib1.value = VAL_BIB1;
811 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
813 rec->databaseName = dbname;
814 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
815 rec->u.surrogateDiagnostic = drec;
816 drec->which = Z_DiagRec_defaultFormat;
817 drec->u.defaultFormat = dr;
818 dr->diagnosticSetId = oid_getoidbyent(&bib1);
820 dr->which = Z_DiagForm_v2AddInfo;
821 dr->addinfo = addinfo ? addinfo : "";
826 * multiple nonsurrogate diagnostics.
828 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
830 Z_DiagRecs *recs = odr_malloc (assoc->encode, sizeof(*recs));
831 int *err = odr_malloc (assoc->encode, sizeof(*err));
833 Z_DiagRec **recp = odr_malloc (assoc->encode, sizeof(*recp));
834 Z_DiagRec *drec = odr_malloc (assoc->encode, sizeof(*drec));
835 Z_DefaultDiagFormat *rec = odr_malloc (assoc->encode, sizeof(*rec));
837 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
838 bib1.proto = assoc->proto;
839 bib1.oclass = CLASS_DIAGSET;
840 bib1.value = VAL_BIB1;
843 recs->num_diagRecs = 1;
844 recs->diagRecs = recp;
846 drec->which = Z_DiagRec_defaultFormat;
847 drec->u.defaultFormat = rec;
849 rec->diagnosticSetId = oid_getoidbyent(&bib1);
850 rec->condition = err;
851 rec->which = Z_DiagForm_v2AddInfo;
852 rec->addinfo = addinfo ? addinfo : "";
856 static Z_Records *pack_records(association *a, char *setname, int start,
857 int *num, Z_RecordComposition *comp,
858 int *next, int *pres, oid_value format)
860 int recno, total_length = 0, toget = *num, dumped_records = 0;
861 Z_Records *records = odr_malloc (a->encode, sizeof(*records));
862 Z_NamePlusRecordList *reclist = odr_malloc (a->encode, sizeof(*reclist));
863 Z_NamePlusRecord **list = odr_malloc (a->encode, sizeof(*list) * toget);
866 records->which = Z_Records_DBOSD;
867 records->u.databaseOrSurDiagnostics = reclist;
868 reclist->num_records = 0;
869 reclist->records = list;
870 *pres = Z_PRES_SUCCESS;
874 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
875 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
876 a->maximumRecordSize);
877 for (recno = start; reclist->num_records < toget; recno++)
879 bend_fetchrequest freq;
880 bend_fetchresult *fres;
881 Z_NamePlusRecord *thisrec;
882 Z_DatabaseRecord *thisext;
886 * we get the number of bytes allocated on the stream before any
887 * allocation done by the backend - this should give us a reasonable
888 * idea of the total size of the data so far.
890 total_length = odr_total(a->encode) - dumped_records;
891 freq.setname = setname;
894 freq.format = format;
895 freq.stream = a->encode;
896 if (!(fres = bend_fetch(a->backend, &freq, 0)))
898 *pres = Z_PRES_FAILURE;
899 return diagrec(a, 2, "Backend interface problem");
901 /* backend should be able to signal whether error is system-wide
902 or only pertaining to current record */
905 *pres = Z_PRES_FAILURE;
906 return diagrec(a, fres->errcode, fres->errstring);
909 this_length = fres->len;
911 this_length = odr_total(a->encode) - total_length;
912 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
913 this_length, total_length);
914 if (this_length + total_length > a->preferredMessageSize)
916 /* record is small enough, really */
917 if (this_length <= a->preferredMessageSize)
919 logf(LOG_DEBUG, " Dropped last normal-sized record");
920 *pres = Z_PRES_PARTIAL_2;
923 /* record can only be fetched by itself */
924 if (this_length < a->maximumRecordSize)
926 logf(LOG_DEBUG, " Record > prefmsgsz");
929 logf(LOG_DEBUG, " Dropped it");
930 reclist->records[reclist->num_records] =
931 surrogatediagrec(a, fres->basename, 16, 0);
932 reclist->num_records++;
933 *next = fres->last_in_set ? 0 : recno + 1;
934 dumped_records += this_length;
938 else /* too big entirely */
940 logf(LOG_DEBUG, "Record > maxrcdsz");
941 reclist->records[reclist->num_records] =
942 surrogatediagrec(a, fres->basename, 17, 0);
943 reclist->num_records++;
944 *next = fres->last_in_set ? 0 : recno + 1;
945 dumped_records += this_length;
949 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
951 if (!(thisrec->databaseName = odr_malloc(a->encode,
952 strlen(fres->basename) + 1)))
954 strcpy(thisrec->databaseName, fres->basename);
955 thisrec->which = Z_NamePlusRecord_databaseRecord;
956 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
957 sizeof(Z_DatabaseRecord))))
959 recform.proto = a->proto;
960 recform.oclass = CLASS_RECSYN;
961 recform.value = fres->format;
962 thisext->direct_reference = odr_oiddup(a->encode,
963 oid_getoidbyent(&recform));
964 thisext->indirect_reference = 0;
965 thisext->descriptor = 0;
966 if (fres->len < 0) /* Structured data */
968 switch (fres->format)
970 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
971 case VAL_GRS1: thisext->which = Z_External_grs1; break;
972 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
974 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
975 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
978 logf(LOG_FATAL, "Unknown structured format from backend.");
983 * We cheat on the pointers here. Obviously, the record field
984 * of the backend-fetch structure should have been a union for
985 * correctness, but we're stuck with this for backwards
988 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
990 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
992 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
994 thisext->which = Z_External_sutrs;
995 thisext->u.sutrs = sutrs;
996 sutrs->buf = odr_malloc(a->encode, fres->len);
997 sutrs->len = sutrs->size = fres->len;
998 memcpy(sutrs->buf, fres->record, fres->len);
1000 else /* octet-aligned record. */
1002 thisext->which = Z_External_octet;
1003 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
1006 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1009 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1010 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1013 reclist->records[reclist->num_records] = thisrec;
1014 reclist->num_records++;
1015 *next = fres->last_in_set ? 0 : recno + 1;
1017 *num = reclist->num_records;
1021 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1024 Z_SearchRequest *req = reqb->request->u.searchRequest;
1025 bend_searchrequest bsrq;
1026 bend_searchresult *bsrt;
1028 logf(LOG_LOG, "Got SearchRequest.");
1030 bsrq.setname = req->resultSetName;
1031 bsrq.replace_set = *req->replaceIndicator;
1032 bsrq.num_bases = req->num_databaseNames;
1033 bsrq.basenames = req->databaseNames;
1034 bsrq.query = req->query;
1035 bsrq.stream = assoc->encode;
1037 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1039 return response_searchRequest(assoc, reqb, bsrt, fd);
1042 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1045 * Prepare a searchresponse based on the backend results. We probably want
1046 * to look at making the fetching of records nonblocking as well, but
1047 * so far, we'll keep things simple.
1048 * If bsrt is null, that means we're called in response to a communications
1049 * event, and we'll have to get the response for ourselves.
1051 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1052 bend_searchresult *bsrt, int *fd)
1054 Z_SearchRequest *req = reqb->request->u.searchRequest;
1055 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1056 Z_SearchResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1057 int *nulint = odr_malloc (assoc->encode, sizeof(*nulint));
1058 bool_t *sr = odr_malloc (assoc->encode, sizeof(*sr));
1059 int *next = odr_malloc (assoc->encode, sizeof(*next));
1060 int *none = odr_malloc (assoc->encode, sizeof(*none));
1067 apdu->which = Z_APDU_searchResponse;
1068 apdu->u.searchResponse = resp;
1069 resp->referenceId = req->referenceId;
1070 resp->additionalSearchInfo = 0;
1071 resp->otherInfo = 0;
1073 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1075 logf(LOG_FATAL, "Bad result from backend");
1078 else if (bsrt->errcode)
1080 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1081 resp->resultCount = nulint;
1082 resp->numberOfRecordsReturned = nulint;
1083 resp->nextResultSetPosition = nulint;
1084 resp->searchStatus = nulint;
1085 resp->resultSetStatus = none;
1086 resp->presentStatus = 0;
1090 int *toget = odr_malloc (assoc->encode, sizeof(*toget));
1091 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1092 Z_RecordComposition comp, *compp = 0;
1097 resp->resultCount = &bsrt->hits;
1099 comp.which = Z_RecordComp_simple;
1100 /* how many records does the user agent want, then? */
1101 if (bsrt->hits <= *req->smallSetUpperBound)
1103 *toget = bsrt->hits;
1104 if ((comp.u.simple = req->smallSetElementSetNames))
1107 else if (bsrt->hits < *req->largeSetLowerBound)
1109 *toget = *req->mediumSetPresentNumber;
1110 if (*toget > bsrt->hits)
1111 *toget = bsrt->hits;
1112 if ((comp.u.simple = req->mediumSetElementSetNames))
1118 if (*toget && !resp->records)
1123 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1124 prefformat->oclass != CLASS_RECSYN)
1127 form = prefformat->value;
1128 resp->records = pack_records(assoc, req->resultSetName, 1,
1129 toget, compp, next, presst, form);
1132 resp->numberOfRecordsReturned = toget;
1133 resp->nextResultSetPosition = next;
1134 resp->searchStatus = sr;
1135 resp->resultSetStatus = 0;
1136 resp->presentStatus = presst;
1140 if (*resp->resultCount)
1142 resp->numberOfRecordsReturned = nulint;
1143 resp->nextResultSetPosition = next;
1144 resp->searchStatus = sr;
1145 resp->resultSetStatus = 0;
1146 resp->presentStatus = 0;
1153 * Maybe we got a little over-friendly when we designed bend_fetch to
1154 * get only one record at a time. Some backends can optimise multiple-record
1155 * fetches, and at any rate, there is some overhead involved in
1156 * all that selecting and hopping around. Problem is, of course, that the
1157 * frontend can't know ahead of time how many records it'll need to
1158 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1159 * is downright lousy as a bulk data transfer protocol.
1161 * To start with, we'll do the fetching of records from the backend
1162 * in one operation: To save some trips in and out of the event-handler,
1163 * and to simplify the interface to pack_records. At any rate, asynch
1164 * operation is more fun in operations that have an unpredictable execution
1165 * speed - which is normally more true for search than for present.
1167 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1170 Z_PresentRequest *req = reqb->request->u.presentRequest;
1171 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1172 Z_PresentResponse *resp = odr_malloc (assoc->encode, sizeof(*resp));
1173 int *presst = odr_malloc (assoc->encode, sizeof(*presst));
1174 int *next = odr_malloc (assoc->encode, sizeof(*next));
1175 int *num = odr_malloc (assoc->encode, sizeof(*num));
1179 logf(LOG_LOG, "Got PresentRequest.");
1184 apdu->which = Z_APDU_presentResponse;
1185 apdu->u.presentResponse = resp;
1186 resp->referenceId = req->referenceId;
1187 resp->otherInfo = 0;
1189 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1190 prefformat->oclass != CLASS_RECSYN)
1193 form = prefformat->value;
1194 *num = *req->numberOfRecordsRequested;
1195 resp->records = pack_records(assoc, req->resultSetId,
1196 *req->resultSetStartPoint, num, req->recordComposition, next,
1200 resp->numberOfRecordsReturned = num;
1201 resp->presentStatus = presst;
1202 resp->nextResultSetPosition = next;
1208 * Scan was implemented rather in a hurry, and with support for only the basic
1209 * elements of the service in the backend API. Suggestions are welcome.
1211 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1213 Z_ScanRequest *req = reqb->request->u.scanRequest;
1214 Z_APDU *apdu = odr_malloc (assoc->encode, sizeof(*apdu));
1215 Z_ScanResponse *res = odr_malloc (assoc->encode, sizeof(*res));
1216 int *scanStatus = odr_malloc (assoc->encode, sizeof(*scanStatus));
1217 int *numberOfEntriesReturned =
1218 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1219 Z_ListEntries *ents = odr_malloc (assoc->encode, sizeof(*ents));
1221 bend_scanrequest srq;
1222 bend_scanresult *srs;
1225 logf(LOG_LOG, "Got scanrequest");
1226 *scanStatus = Z_Scan_failure;
1227 *numberOfEntriesReturned = 0;
1229 apdu->which = Z_APDU_scanResponse;
1230 apdu->u.scanResponse = res;
1231 res->referenceId = req->referenceId;
1233 res->scanStatus = scanStatus;
1234 res->numberOfEntriesReturned = numberOfEntriesReturned;
1235 res->positionOfTerm = 0;
1236 res->entries = ents;
1237 ents->which = Z_ListEntries_nonSurrogateDiagnostics;
1238 res->attributeSet = 0;
1241 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1242 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1243 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 121, 0);
1244 else if (req->stepSize && *req->stepSize > 0)
1245 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 205, 0);
1248 if (req->termListAndStartPoint->term->which == Z_Term_general)
1249 logf(LOG_DEBUG, " term: '%.*s'",
1250 req->termListAndStartPoint->term->u.general->len,
1251 req->termListAndStartPoint->term->u.general->buf);
1252 srq.num_bases = req->num_databaseNames;
1253 srq.basenames = req->databaseNames;
1254 srq.num_entries = *req->numberOfTermsRequested;
1255 srq.term = req->termListAndStartPoint;
1256 srq.stream = assoc->encode;
1257 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1258 attset->oclass != CLASS_RECSYN)
1259 srq.attributeset = VAL_NONE;
1261 srq.attributeset = attset->value;
1262 srq.term_position = req->preferredPositionInResponse ?
1263 *req->preferredPositionInResponse : 1;
1264 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1265 ents->u.nonSurrogateDiagnostics = diagrecs(assoc, 2, 0);
1266 else if (srs->errcode)
1267 ents->u.nonSurrogateDiagnostics = diagrecs(assoc,
1268 srs->errcode, srs->errstring);
1272 Z_Entries *list = odr_malloc (assoc->encode, sizeof(*list));
1273 Z_Entry **tab = odr_malloc (assoc->encode,
1274 sizeof(*tab) * srs->num_entries);
1276 if (srs->status == BEND_SCAN_PARTIAL)
1277 *scanStatus = Z_Scan_partial_5;
1279 *scanStatus = Z_Scan_success;
1280 ents->which = Z_ListEntries_entries;
1281 ents->u.entries = list;
1282 list->entries = tab;
1283 for (i = 0; i < srs->num_entries; i++)
1289 list->entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1290 e->which = Z_Entry_termInfo;
1291 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1292 t->suggestedAttributes = 0;
1294 t->alternativeTerm = 0;
1295 t->byAttributes = 0;
1296 t->otherTermInfo = 0;
1297 t->globalOccurrences = &srs->entries[i].occurrences;
1298 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1299 t->term->which = Z_Term_general;
1300 t->term->u.general = o = odr_malloc(assoc->encode,
1302 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1303 strlen(srs->entries[i].term));
1304 memcpy(o->buf, srs->entries[i].term, o->len);
1305 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1306 srs->entries[i].term, srs->entries[i].occurrences);
1308 list->num_entries = i;
1309 res->numberOfEntriesReturned = &list->num_entries;
1310 res->positionOfTerm = &srs->term_position;
1317 static void process_close(association *assoc, request *reqb)
1319 Z_Close *req = reqb->request->u.close;
1320 static char *reasons[] =
1327 "securityViolation",
1334 logf(LOG_LOG, "Got close, reason %s, message %s",
1335 reasons[*req->closeReason], req->diagnosticInformation ?
1336 req->diagnosticInformation : "NULL");
1337 if (assoc->version < 3) /* to make do_force respond with close */
1339 do_close(assoc, Z_Close_finished, "Association terminated by client");