2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.61 1996-06-10 08:56:16 quinn
10 * Revision 1.60 1996/05/30 11:03:10 quinn
11 * Fixed NextresultSetPosition bug fixed.
13 * Revision 1.59 1996/05/14 09:26:46 quinn
14 * Added attribute set to scan backend
16 * Revision 1.58 1996/02/20 12:53:04 quinn
19 * Revision 1.57 1996/01/02 08:57:47 quinn
20 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
22 * Revision 1.56 1995/12/14 11:09:57 quinn
25 * Revision 1.55 1995/11/08 17:41:37 quinn
28 * Revision 1.54 1995/11/08 15:11:29 quinn
29 * Log of close transmit.
31 * Revision 1.53 1995/11/01 13:54:58 quinn
34 * Revision 1.52 1995/11/01 12:19:13 quinn
35 * Second attempt to fix same bug.
37 * Revision 1.50 1995/10/25 16:58:32 quinn
40 * Revision 1.49 1995/10/16 13:51:53 quinn
41 * Changes to provide Especs to the backend.
43 * Revision 1.48 1995/10/06 08:51:20 quinn
46 * Revision 1.47 1995/08/29 14:24:16 quinn
47 * Added second half of close-handshake
49 * Revision 1.46 1995/08/29 11:17:58 quinn
50 * Added code to receive close
52 * Revision 1.45 1995/08/21 09:11:00 quinn
53 * Smallish fixes to suppport new formats.
55 * Revision 1.44 1995/08/17 12:45:25 quinn
56 * Fixed minor problems with GRS-1. Added support in c&s.
58 * Revision 1.43 1995/08/15 12:00:31 quinn
61 * Revision 1.42 1995/08/15 11:16:50 quinn
63 * Revision 1.41 1995/08/02 10:23:06 quinn
66 * Revision 1.40 1995/07/31 14:34:26 quinn
67 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
69 * Revision 1.39 1995/06/27 13:21:00 quinn
72 * Revision 1.38 1995/06/19 12:39:11 quinn
73 * Fixed bug in timeout code. Added BER dumper.
75 * Revision 1.37 1995/06/16 13:16:14 quinn
76 * Fixed Defaultdiagformat.
78 * Revision 1.36 1995/06/16 10:31:36 quinn
79 * Added session timeout.
81 * Revision 1.35 1995/06/15 07:45:14 quinn
84 * Revision 1.34 1995/06/14 15:26:46 quinn
85 * *** empty log message ***
87 * Revision 1.33 1995/06/06 14:57:05 quinn
90 * Revision 1.32 1995/06/06 08:41:44 quinn
93 * Revision 1.31 1995/06/06 08:15:37 quinn
96 * Revision 1.30 1995/06/05 10:53:32 quinn
97 * Added a better SCAN.
99 * Revision 1.29 1995/06/01 11:25:03 quinn
102 * Revision 1.28 1995/06/01 11:21:01 quinn
103 * Attempting to fix a bug in pack-records. replaced break with continue
104 * for large records, according to standard.
106 * Revision 1.27 1995/05/29 08:12:06 quinn
109 * Revision 1.26 1995/05/18 13:02:12 quinn
112 * Revision 1.25 1995/05/17 08:42:26 quinn
113 * Transfer auth info to backend. Allow backend to reject init gracefully.
115 * Revision 1.24 1995/05/16 08:51:04 quinn
116 * License, documentation, and memory fixes
118 * Revision 1.23 1995/05/15 13:25:10 quinn
121 * Revision 1.22 1995/05/15 11:56:39 quinn
122 * Asynchronous facilities. Restructuring of seshigh code.
124 * Revision 1.21 1995/05/02 08:53:19 quinn
125 * Trying in vain to fix comm with ISODE
127 * Revision 1.20 1995/04/20 15:13:00 quinn
130 * Revision 1.19 1995/04/18 08:15:34 quinn
131 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
132 * neater. We'll make the same change for decoding one day.
134 * Revision 1.18 1995/04/17 11:28:25 quinn
137 * Revision 1.17 1995/04/10 10:23:36 quinn
138 * Some work to add scan and other things.
140 * Revision 1.16 1995/03/31 09:18:55 quinn
143 * Revision 1.15 1995/03/30 14:03:23 quinn
144 * Added RFC1006 as separate library
146 * Revision 1.14 1995/03/30 12:18:17 quinn
149 * Revision 1.13 1995/03/30 09:09:24 quinn
150 * Added state-handle and some support for asynchronous activities.
152 * Revision 1.12 1995/03/29 15:40:16 quinn
153 * Ongoing work. Statserv is now dynamic by default
155 * Revision 1.11 1995/03/28 09:16:21 quinn
156 * Added record packing to the search request
158 * Revision 1.10 1995/03/27 08:34:24 quinn
159 * Added dynamic server functionality.
160 * Released bindings to session.c (is now redundant)
162 * Revision 1.9 1995/03/22 15:01:26 quinn
163 * Adjusting record packing.
165 * Revision 1.8 1995/03/22 10:13:21 quinn
166 * Working on record packer
168 * Revision 1.7 1995/03/21 15:53:31 quinn
171 * Revision 1.6 1995/03/21 12:30:09 quinn
172 * Beginning to add support for record packing.
174 * Revision 1.5 1995/03/17 10:44:13 quinn
175 * Added catch of null-string in makediagrec
177 * Revision 1.4 1995/03/17 10:18:08 quinn
178 * Added memory management.
180 * Revision 1.3 1995/03/16 17:42:39 quinn
183 * Revision 1.2 1995/03/16 13:29:01 quinn
184 * Partitioned server.
186 * Revision 1.1 1995/03/15 16:02:10 quinn
187 * Modded session.c to seshigh.c
192 * Frontend server logic.
194 * This code receives incoming APDUs, and handles client requests by means
195 * of the backend API.
197 * Some of the code is getting quite involved, compared to simpler servers -
198 * primarily because it is asynchronous both in the communication with
199 * the user and the backend. We think the complexity will pay off in
200 * the form of greater flexibility when more asynchronous facilities
203 * Memory management has become somewhat involved. In the simple case, where
204 * only one PDU is pending at a time, it will simply reuse the same memory,
205 * once it has found its working size. When we enable multiple concurrent
206 * operations, perhaps even with multiple parallel calls to the backend, it
207 * will maintain a pool of buffers for encoding and decoding, trying to
208 * minimize memory allocation/deallocation during normal operation.
210 * TODOs include (and will be done in order of public interest):
212 * Support for EXPLAIN - provide simple meta-database system.
213 * Support for access control.
214 * Support for resource control.
215 * Support for extended services - primarily Item Order.
216 * Rest of Z39.50-1994
224 #include <sys/time.h>
227 #include <comstack.h>
233 #include <statserv.h>
237 static int process_request(association *assoc);
238 void backend_response(IOCHAN i, int event);
239 static int process_response(association *assoc, request *req, Z_APDU *res);
240 static Z_APDU *process_initRequest(association *assoc, request *reqb);
241 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
243 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
244 bend_searchresult *bsrt, int *fd);
245 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
247 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
248 static void process_close(association *assoc, request *reqb);
250 static FILE *apduf = 0; /* for use in static mode */
251 static statserv_options_block *control_block = 0;
254 * Create and initialize a new association-handle.
255 * channel : iochannel for the current line.
256 * link : communications channel.
257 * Returns: 0 or a new association handle.
259 association *create_association(IOCHAN channel, COMSTACK link)
264 control_block = statserv_getcontrol();
265 if (!(new = xmalloc(sizeof(*new))))
267 new->client_chan = channel;
268 new->client_link = link;
269 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
270 !(new->encode = odr_createmem(ODR_ENCODE)))
272 if (*control_block->apdufile)
277 strcpy(filename, control_block->apdufile);
278 if (!(new->print = odr_createmem(ODR_PRINT)))
280 if (*control_block->apdufile != '-')
282 strcpy(filename, control_block->apdufile);
283 if (!control_block->dynamic)
287 if (!(apduf = fopen(filename, "w")))
289 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
292 setvbuf(apduf, 0, _IONBF, 0);
298 sprintf(filename + strlen(filename), ".%d", getpid());
299 if (!(f = fopen(filename, "w")))
301 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
304 setvbuf(f, 0, _IONBF, 0);
306 odr_setprint(new->print, f);
311 new->input_buffer = 0;
312 new->input_buffer_len = 0;
314 new->state = ASSOC_NEW;
315 request_initq(&new->incoming);
316 request_initq(&new->outgoing);
317 new->proto = cs_getproto(link);
322 * Free association and release resources.
324 void destroy_association(association *h)
326 odr_destroy(h->decode);
327 odr_destroy(h->encode);
329 odr_destroy(h->print);
331 xfree(h->input_buffer);
333 bend_close(h->backend);
334 while (request_deq(&h->incoming));
335 while (request_deq(&h->outgoing));
339 static void do_close(association *a, int reason, char *message)
342 Z_Close *cls = zget_Close(a->encode);
343 request *req = request_get();
345 /* Purge request queue */
346 while (request_deq(&a->incoming));
347 while (request_deq(&a->outgoing));
350 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
351 reason, message ? message : "none");
352 apdu.which = Z_APDU_close;
354 *cls->closeReason = reason;
355 cls->diagnosticInformation = message;
356 process_response(a, req, &apdu);
357 iochan_settimeout(a->client_chan, 60);
361 logf(LOG_DEBUG, "v2 client. No Close PDU");
362 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
364 a->state = ASSOC_DEAD;
368 * This is where PDUs from the client are read and the further
369 * processing is initiated. Flow of control moves down through the
370 * various process_* functions below, until the encoded result comes back up
371 * to the output handler in here.
373 * h : the I/O channel that has an outstanding event.
374 * event : the current outstanding event.
376 void ir_session(IOCHAN h, int event)
379 association *assoc = iochan_getdata(h);
380 COMSTACK conn = assoc->client_link;
383 assert(h && conn && assoc);
384 if (event == EVENT_TIMEOUT)
386 if (assoc->state != ASSOC_UP)
388 logf(LOG_LOG, "Final timeout - closing connection.");
390 destroy_association(assoc);
395 logf(LOG_LOG, "Session idle too long. Sending close.");
396 do_close(assoc, Z_Close_lackOfActivity, 0);
400 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
402 if (event & EVENT_INPUT)
404 logf(LOG_DEBUG, "ir_session (input)");
405 assert(assoc && conn);
406 /* We aren't speaking to this fellow */
407 if (assoc->state == ASSOC_DEAD)
409 logf(LOG_LOG, "Closed connection after reject");
411 destroy_association(assoc);
415 if ((res = cs_get(conn, &assoc->input_buffer,
416 &assoc->input_buffer_len)) <= 0)
418 logf(LOG_LOG, "Connection closed by client");
420 destroy_association(assoc);
424 else if (res == 1) /* incomplete read - wait for more */
426 if (cs_more(conn)) /* more stuff - call us again later, please */
427 iochan_setevent(h, EVENT_INPUT);
429 /* we got a complete PDU. Let's decode it */
430 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
431 req = request_get(); /* get a new request structure */
432 odr_reset(assoc->decode);
433 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
434 if (!z_APDU(assoc->decode, &req->request, 0))
436 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
437 odr_errlist[odr_geterror(assoc->decode)],
438 odr_offset(assoc->decode));
439 logf(LOG_LOG, "PDU dump:");
440 odr_dumpBER(log_file(), assoc->input_buffer, res);
441 do_close(assoc, Z_Close_protocolError, "Malformed package");
444 req->request_mem = odr_extract_mem(assoc->decode);
445 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
447 logf(LOG_WARN, "ODR print error: %s",
448 odr_errlist[odr_geterror(assoc->print)]);
449 odr_reset(assoc->print);
451 request_enq(&assoc->incoming, req);
454 /* can we do something yet? */
455 req = request_head(&assoc->incoming);
456 if (req->state == REQUEST_IDLE)
457 if (process_request(assoc) < 0)
458 do_close(assoc, Z_Close_systemProblem, "Unknown error");
460 if (event & EVENT_OUTPUT)
462 request *req = request_head(&assoc->outgoing);
464 logf(LOG_DEBUG, "ir_session (output)");
465 req->state = REQUEST_PENDING;
466 switch (res = cs_put(conn, req->response, req->len_response))
469 logf(LOG_LOG, "Connection closed by client");
471 destroy_association(assoc);
474 case 0: /* all sent - release the request structure */
475 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
476 nmem_destroy(req->request_mem);
477 request_deq(&assoc->outgoing);
478 request_release(req);
479 if (!request_head(&assoc->outgoing))
480 iochan_clearflag(h, EVENT_OUTPUT);
482 /* value of 1 -- partial send -- is simply ignored */
485 if (event & EVENT_EXCEPT)
487 logf(LOG_DEBUG, "ir_session (exception)");
489 destroy_association(assoc);
495 * Initiate request processing.
497 static int process_request(association *assoc)
499 request *req = request_head(&assoc->incoming);
503 logf(LOG_DEBUG, "process_request");
504 assert(req && req->state == REQUEST_IDLE);
505 switch (req->request->which)
507 case Z_APDU_initRequest:
508 res = process_initRequest(assoc, req); break;
509 case Z_APDU_searchRequest:
510 res = process_searchRequest(assoc, req, &fd); break;
511 case Z_APDU_presentRequest:
512 res = process_presentRequest(assoc, req, &fd); break;
513 case Z_APDU_scanRequest:
514 res = process_scanRequest(assoc, req, &fd); break;
516 process_close(assoc, req); return 0;
518 logf(LOG_WARN, "Bad APDU received");
523 logf(LOG_DEBUG, " result immediately available");
524 return process_response(assoc, req, res);
528 logf(LOG_WARN, " bad result");
531 else /* no result yet - one will be provided later */
535 /* Set up an I/O handler for the fd supplied by the backend */
537 logf(LOG_DEBUG, " establishing handler for result");
538 req->state = REQUEST_PENDING;
539 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
541 iochan_setdata(chan, assoc);
547 * Handle message from the backend.
549 void backend_response(IOCHAN i, int event)
551 association *assoc = iochan_getdata(i);
552 request *req = request_head(&assoc->incoming);
556 logf(LOG_DEBUG, "backend_response");
557 assert(assoc && req && req->state != REQUEST_IDLE);
558 /* determine what it is we're waiting for */
559 switch (req->request->which)
561 case Z_APDU_searchRequest:
562 res = response_searchRequest(assoc, req, 0, &fd); break;
564 case Z_APDU_presentRequest:
565 res = response_presentRequest(assoc, req, 0, &fd); break;
566 case Z_APDU_scanRequest:
567 res = response_scanRequest(assoc, req, 0, &fd); break;
570 logf(LOG_WARN, "Serious programmer's lapse or bug");
573 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
575 logf(LOG_LOG, "Fatal error when talking to backend");
576 do_close(assoc, Z_Close_systemProblem, 0);
580 else if (!res) /* no result yet - try again later */
582 logf(LOG_DEBUG, " no result yet");
583 iochan_setfd(i, fd); /* in case fd has changed */
588 * Encode response, and transfer the request structure to the outgoing queue.
590 static int process_response(association *assoc, request *req, Z_APDU *res)
592 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
593 if (!z_APDU(assoc->encode, &res, 0))
595 logf(LOG_WARN, "ODR error when encoding response: %s",
596 odr_errlist[odr_geterror(assoc->decode)]);
597 odr_reset(assoc->encode);
600 req->response = odr_getbuf(assoc->encode, &req->len_response,
601 &req->size_response);
602 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
603 odr_reset(assoc->encode);
604 if (assoc->print && !z_APDU(assoc->print, &res, 0))
606 logf(LOG_WARN, "ODR print error: %s",
607 odr_errlist[odr_geterror(assoc->print)]);
608 odr_reset(assoc->print);
610 /* change this when we make the backend reentrant */
611 if (req == request_head(&assoc->incoming))
613 req->state = REQUEST_IDLE;
614 request_deq(&assoc->incoming);
616 request_enq(&assoc->outgoing, req);
617 /* turn the work over to the ir_session handler */
618 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
619 /* Is there more work to be done? give that to the input handler too */
620 if (request_head(&assoc->incoming))
621 iochan_setevent(assoc->client_chan, EVENT_WORK);
626 * Handle init request.
627 * At the moment, we don't check the options
628 * anywhere else in the code - we just try not to do anything that would
629 * break a naive client. We'll toss 'em into the association block when
630 * we need them there.
632 static Z_APDU *process_initRequest(association *assoc, request *reqb)
634 Z_InitRequest *req = reqb->request->u.initRequest;
635 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
636 Z_InitResponse *resp = apdu->u.initResponse;
637 bend_initrequest binitreq;
638 bend_initresult *binitres;
641 logf(LOG_LOG, "Got initRequest");
642 if (req->implementationId)
643 logf(LOG_LOG, "Id: %s", req->implementationId);
644 if (req->implementationName)
645 logf(LOG_LOG, "Name: %s", req->implementationName);
646 if (req->implementationVersion)
647 logf(LOG_LOG, "Version: %s", req->implementationVersion);
649 binitreq.configname = "default-config";
650 binitreq.auth = req->idAuthentication;
651 if (!(binitres = bend_init(&binitreq)))
653 logf(LOG_WARN, "Bad response from backend.");
657 assoc->backend = binitres->handle;
658 resp->referenceId = req->referenceId;
660 /* let's tell the client what we can do */
661 if (ODR_MASK_GET(req->options, Z_Options_search))
663 ODR_MASK_SET(resp->options, Z_Options_search);
664 strcat(options, "srch");
666 if (ODR_MASK_GET(req->options, Z_Options_present))
668 ODR_MASK_SET(resp->options, Z_Options_present);
669 strcat(options, " prst");
672 if (ODR_MASK_GET(req->options, Z_Options_delSet))
674 ODR_MASK_SET(&options, Z_Options_delSet);
675 strcat(options, " del");
678 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
680 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
681 strcat(options, " namedresults");
683 if (ODR_MASK_GET(req->options, Z_Options_scan))
685 ODR_MASK_SET(resp->options, Z_Options_scan);
686 strcat(options, " scan");
688 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
690 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
691 strcat(options, " concurop");
694 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
696 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
697 assoc->version = 2; /* 1 & 2 are equivalent */
699 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
701 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
704 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
706 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
709 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
710 assoc->maximumRecordSize = *req->maximumRecordSize;
711 if (assoc->maximumRecordSize > control_block->maxrecordsize)
712 assoc->maximumRecordSize = control_block->maxrecordsize;
713 assoc->preferredMessageSize = *req->preferredMessageSize;
714 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
715 assoc->preferredMessageSize = assoc->maximumRecordSize;
716 resp->preferredMessageSize = &assoc->preferredMessageSize;
717 resp->maximumRecordSize = &assoc->maximumRecordSize;
718 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
719 if (binitres->errcode)
721 logf(LOG_LOG, "Connection rejected by backend.");
723 assoc->state = ASSOC_DEAD;
726 assoc->state = ASSOC_UP;
731 * These functions should be merged.
735 * nonsurrogate diagnostic record.
737 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
739 static Z_Records rec;
743 static Z_DiagRec drec;
744 static Z_DefaultDiagFormat dr;
750 bib1.oclass = CLASS_DIAGSET;
751 bib1.value = VAL_BIB1;
753 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
756 rec.which = Z_Records_NSD;
758 rec.u.nonSurrogateDiagnostic = &drec;
759 drec.which = Z_DiagRec_defaultFormat;
760 drec.u.defaultFormat = &dr;
762 rec.u.nonSurrogateDiagnostic = &dr;
764 dr.diagnosticSetId = oid_getoidbyent(&bib1);
766 dr.which = Z_DiagForm_v2AddInfo;
767 dr.addinfo = addinfo ? addinfo : "";
772 * surrogate diagnostic.
774 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
775 int error, char *addinfo)
777 static Z_NamePlusRecord rec;
781 static Z_DiagRec drec;
782 static Z_DefaultDiagFormat dr;
788 bib1.oclass = CLASS_DIAGSET;
789 bib1.value = VAL_BIB1;
791 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
793 rec.databaseName = dbname;
794 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
796 rec.u.surrogateDiagnostic = &drec;
797 drec.which = Z_DiagRec_defaultFormat;
798 drec.u.defaultFormat = &dr;
800 rec.u.surrogateDiagnostic = &dr;
802 dr.diagnosticSetId = oid_getoidbyent(&bib1);
804 dr.which = Z_DiagForm_v2AddInfo;
805 dr.addinfo = addinfo ? addinfo : "";
810 * multiple nonsurrogate diagnostics.
812 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
814 static Z_DiagRecs recs;
818 static Z_DiagRec *recp[1], drec;
819 static Z_DefaultDiagFormat rec;
821 static Z_DiagRec *recp[1], rec;
824 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
826 bib1.oclass = CLASS_DIAGSET;
827 bib1.value = VAL_BIB1;
830 recs.num_diagRecs = 1;
831 recs.diagRecs = recp;
834 drec.which = Z_DiagRec_defaultFormat;
835 drec.u.defaultFormat = &rec;
839 rec.diagnosticSetId = oid_getoidbyent(&bib1);
840 rec.condition = &err;
841 rec.which = Z_DiagForm_v2AddInfo;
842 rec.addinfo = addinfo ? addinfo : "";
846 #define MAX_RECORDS 256
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;
853 static Z_Records records;
854 static Z_NamePlusRecordList reclist;
855 static Z_NamePlusRecord *list[MAX_RECORDS];
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);
883 if (reclist.num_records == MAX_RECORDS - 1)
885 *pres = Z_PRES_PARTIAL_2;
888 freq.setname = setname;
891 freq.format = format;
892 freq.stream = a->encode;
893 if (!(fres = bend_fetch(a->backend, &freq, 0)))
895 *pres = Z_PRES_FAILURE;
896 return diagrec(a->proto, 2, "Backend interface problem");
898 /* backend should be able to signal whether error is system-wide
899 or only pertaining to current record */
902 *pres = Z_PRES_FAILURE;
903 return diagrec(a->proto, fres->errcode, fres->errstring);
906 this_length = fres->len;
908 this_length = odr_total(a->encode) - total_length;
909 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
910 this_length, total_length);
911 if (this_length + total_length > a->preferredMessageSize)
913 /* record is small enough, really */
914 if (this_length <= a->preferredMessageSize)
916 logf(LOG_DEBUG, " Dropped last normal-sized record");
917 *pres = Z_PRES_PARTIAL_2;
920 /* record can only be fetched by itself */
921 if (this_length < a->maximumRecordSize)
923 logf(LOG_DEBUG, " Record > prefmsgsz");
926 logf(LOG_DEBUG, " Dropped it");
927 reclist.records[reclist.num_records] =
928 surrogatediagrec(a->proto, fres->basename, 16, 0);
929 reclist.num_records++;
930 *next = fres->last_in_set ? 0 : recno + 1;
934 else /* too big entirely */
936 logf(LOG_DEBUG, "Record > maxrcdsz");
937 reclist.records[reclist.num_records] =
938 surrogatediagrec(a->proto, fres->basename, 17, 0);
939 reclist.num_records++;
940 *next = fres->last_in_set ? 0 : recno + 1;
944 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
946 if (!(thisrec->databaseName = odr_malloc(a->encode,
947 strlen(fres->basename) + 1)))
949 strcpy(thisrec->databaseName, fres->basename);
950 thisrec->which = Z_NamePlusRecord_databaseRecord;
951 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
952 sizeof(Z_DatabaseRecord))))
954 recform.proto = a->proto;
955 recform.oclass = CLASS_RECSYN;
956 recform.value = fres->format;
957 thisext->direct_reference = odr_oiddup(a->encode,
958 oid_getoidbyent(&recform));
959 thisext->indirect_reference = 0;
960 thisext->descriptor = 0;
961 if (fres->len < 0) /* Structured data */
963 switch (fres->format)
965 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
966 case VAL_GRS1: thisext->which = Z_External_grs1; break;
967 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
969 case VAL_SUMMARY: thisext->which = Z_External_summary; break;
970 case VAL_OPAC: thisext->which = Z_External_OPAC; break;
973 logf(LOG_FATAL, "Unknown structured format from backend.");
978 * We cheat on the pointers here. Obviously, the record field
979 * of the backend-fetch structure should have been a union for
980 * correctness, but we're stuck with this for backwards
983 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
985 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
987 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
989 thisext->which = Z_External_sutrs;
990 thisext->u.sutrs = sutrs;
991 sutrs->buf = odr_malloc(a->encode, fres->len);
992 sutrs->len = sutrs->size = fres->len;
993 memcpy(sutrs->buf, fres->record, fres->len);
995 else /* octet-aligned record. */
997 thisext->which = Z_External_octet;
998 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
1001 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
1004 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
1005 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
1008 reclist.records[reclist.num_records] = thisrec;
1009 reclist.num_records++;
1010 *next = fres->last_in_set ? 0 : recno + 1;
1012 *num = reclist.num_records;
1016 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1019 Z_SearchRequest *req = reqb->request->u.searchRequest;
1020 bend_searchrequest bsrq;
1021 bend_searchresult *bsrt;
1023 logf(LOG_LOG, "Got SearchRequest.");
1025 bsrq.setname = req->resultSetName;
1026 bsrq.replace_set = *req->replaceIndicator;
1027 bsrq.num_bases = req->num_databaseNames;
1028 bsrq.basenames = req->databaseNames;
1029 bsrq.query = req->query;
1031 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1033 return response_searchRequest(assoc, reqb, bsrt, fd);
1036 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1039 * Prepare a searchresponse based on the backend results. We probably want
1040 * to look at making the fetching of records nonblocking as well, but
1041 * so far, we'll keep things simple.
1042 * If bsrt is null, that means we're called in response to a communications
1043 * event, and we'll have to get the response for ourselves.
1045 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1046 bend_searchresult *bsrt, int *fd)
1048 Z_SearchRequest *req = reqb->request->u.searchRequest;
1050 static Z_SearchResponse resp;
1051 static int nulint = 0;
1052 static bool_t sr = 1;
1053 static int next = 0;
1054 static int none = Z_RES_NONE;
1056 apdu.which = Z_APDU_searchResponse;
1057 apdu.u.searchResponse = &resp;
1058 resp.referenceId = req->referenceId;
1060 resp.additionalSearchInfo = 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->proto, bsrt->errcode,
1073 resp.resultCount = &nulint;
1074 resp.numberOfRecordsReturned = &nulint;
1075 resp.nextResultSetPosition = &nulint;
1076 resp.searchStatus = &nulint;
1077 resp.resultSetStatus = &none;
1078 resp.presentStatus = 0;
1083 Z_RecordComposition comp, *compp = 0;
1084 static int presst = 0;
1087 resp.resultCount = &bsrt->hits;
1089 comp.which = Z_RecordComp_simple;
1090 /* how many records does the user agent want, then? */
1091 if (bsrt->hits <= *req->smallSetUpperBound)
1094 if ((comp.u.simple = req->smallSetElementSetNames))
1097 else if (bsrt->hits < *req->largeSetLowerBound)
1099 toget = *req->mediumSetPresentNumber;
1100 if (toget > bsrt->hits)
1102 if ((comp.u.simple = req->mediumSetElementSetNames))
1108 if (toget && !resp.records)
1113 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1114 prefformat->oclass != CLASS_RECSYN)
1117 form = prefformat->value;
1118 resp.records = pack_records(assoc, req->resultSetName, 1,
1119 &toget, compp, &next, &presst, form);
1122 resp.numberOfRecordsReturned = &toget;
1123 resp.nextResultSetPosition = &next;
1124 resp.searchStatus = &sr;
1125 resp.resultSetStatus = 0;
1126 resp.presentStatus = &presst;
1130 if (*resp.resultCount)
1132 resp.numberOfRecordsReturned = &nulint;
1133 resp.nextResultSetPosition = &next;
1134 resp.searchStatus = &sr;
1135 resp.resultSetStatus = 0;
1136 resp.presentStatus = 0;
1143 * Maybe we got a little over-friendly when we designed bend_fetch to
1144 * get only one record at a time. Some backends can optimise multiple-record
1145 * fetches, and at any rate, there is some overhead involved in
1146 * all that selecting and hopping around. Problem is, of course, that the
1147 * frontend can't know ahead of time how many records it'll need to
1148 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1149 * is downright lousy as a bulk data transfer protocol.
1151 * To start with, we'll do the fetching of records from the backend
1152 * in one operation: To save some trips in and out of the event-handler,
1153 * and to simplify the interface to pack_records. At any rate, asynch
1154 * operation is more fun in operations that have an unpredictable execution
1155 * speed - which is normally more true for search than for present.
1157 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1160 Z_PresentRequest *req = reqb->request->u.presentRequest;
1162 static Z_PresentResponse resp;
1163 static int presst, next, num;
1168 logf(LOG_LOG, "Got PresentRequest.");
1169 apdu.which = Z_APDU_presentResponse;
1170 apdu.u.presentResponse = &resp;
1171 resp.referenceId = req->referenceId;
1176 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1177 prefformat->oclass != CLASS_RECSYN)
1180 form = prefformat->value;
1181 num = *req->numberOfRecordsRequested;
1182 resp.records = pack_records(assoc, req->resultSetId,
1183 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1187 resp.numberOfRecordsReturned = #
1188 resp.presentStatus = &presst;
1189 resp.nextResultSetPosition = &next;
1195 * Scan was implemented rather in a hurry, and with support for only the basic
1196 * elements of the service in the backend API. Suggestions are welcome.
1198 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1200 Z_ScanRequest *req = reqb->request->u.scanRequest;
1202 static Z_ScanResponse res;
1203 static int scanStatus = Z_Scan_failure;
1204 static int numberOfEntriesReturned = 0;
1206 static Z_ListEntries ents;
1207 #define SCAN_MAX_ENTRIES 200
1208 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1209 bend_scanrequest srq;
1210 bend_scanresult *srs;
1213 logf(LOG_LOG, "Got scanrequest");
1214 apdu.which = Z_APDU_scanResponse;
1215 apdu.u.scanResponse = &res;
1216 res.referenceId = req->referenceId;
1218 res.scanStatus = &scanStatus;
1219 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1220 res.positionOfTerm = 0;
1221 res.entries = &ents;
1222 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1223 res.attributeSet = 0;
1228 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1229 attent->oclass != CLASS_ATTSET || attent->value != VAL_BIB1))
1230 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1231 else if (req->stepSize && *req->stepSize > 0)
1232 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1235 if (req->termListAndStartPoint->term->which == Z_Term_general)
1236 logf(LOG_DEBUG, " term: '%.*s'",
1237 req->termListAndStartPoint->term->u.general->len,
1238 req->termListAndStartPoint->term->u.general->buf);
1239 srq.num_bases = req->num_databaseNames;
1240 srq.basenames = req->databaseNames;
1241 srq.num_entries = *req->numberOfTermsRequested;
1242 srq.term = req->termListAndStartPoint;
1243 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1244 attset->oclass != CLASS_RECSYN)
1245 srq.attributeset = VAL_NONE;
1247 srq.attributeset = attset->value;
1248 srq.term_position = req->preferredPositionInResponse ?
1249 *req->preferredPositionInResponse : 1;
1250 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1251 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1252 else if (srs->errcode)
1253 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1254 srs->errcode, srs->errstring);
1258 static Z_Entries list;
1260 if (srs->status == BEND_SCAN_PARTIAL)
1261 scanStatus = Z_Scan_partial_5;
1263 scanStatus = Z_Scan_success;
1264 ents.which = Z_ListEntries_entries;
1265 ents.u.entries = &list;
1267 for (i = 0; i < srs->num_entries; i++)
1273 if (i >= SCAN_MAX_ENTRIES)
1275 scanStatus = Z_Scan_partial_4;
1278 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1279 e->which = Z_Entry_termInfo;
1280 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1281 t->suggestedAttributes = 0;
1283 t->alternativeTerm = 0;
1284 t->byAttributes = 0;
1285 t->otherTermInfo = 0;
1286 t->globalOccurrences = &srs->entries[i].occurrences;
1287 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1288 t->term->which = Z_Term_general;
1289 t->term->u.general = o = odr_malloc(assoc->encode,
1291 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1292 strlen(srs->entries[i].term));
1293 memcpy(o->buf, srs->entries[i].term, o->len);
1294 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1295 srs->entries[i].term, srs->entries[i].occurrences);
1297 list.num_entries = i;
1298 res.numberOfEntriesReturned = &list.num_entries;
1299 res.positionOfTerm = &srs->term_position;
1306 static void process_close(association *assoc, request *reqb)
1308 Z_Close *req = reqb->request->u.close;
1309 static char *reasons[] =
1316 "securityViolation",
1323 logf(LOG_LOG, "Got close, reason %s, message %s",
1324 reasons[*req->closeReason], req->diagnosticInformation ?
1325 req->diagnosticInformation : "NULL");
1326 if (assoc->version < 3) /* to make do_force respond with close */
1328 do_close(assoc, Z_Close_finished, "Association terminated by client");