2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.55 1995-11-08 17:41:37 quinn
10 * Revision 1.54 1995/11/08 15:11:29 quinn
11 * Log of close transmit.
13 * Revision 1.53 1995/11/01 13:54:58 quinn
16 * Revision 1.52 1995/11/01 12:19:13 quinn
17 * Second attempt to fix same bug.
19 * Revision 1.50 1995/10/25 16:58:32 quinn
22 * Revision 1.49 1995/10/16 13:51:53 quinn
23 * Changes to provide Especs to the backend.
25 * Revision 1.48 1995/10/06 08:51:20 quinn
28 * Revision 1.47 1995/08/29 14:24:16 quinn
29 * Added second half of close-handshake
31 * Revision 1.46 1995/08/29 11:17:58 quinn
32 * Added code to receive close
34 * Revision 1.45 1995/08/21 09:11:00 quinn
35 * Smallish fixes to suppport new formats.
37 * Revision 1.44 1995/08/17 12:45:25 quinn
38 * Fixed minor problems with GRS-1. Added support in c&s.
40 * Revision 1.43 1995/08/15 12:00:31 quinn
43 * Revision 1.42 1995/08/15 11:16:50 quinn
45 * Revision 1.41 1995/08/02 10:23:06 quinn
48 * Revision 1.40 1995/07/31 14:34:26 quinn
49 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
51 * Revision 1.39 1995/06/27 13:21:00 quinn
54 * Revision 1.38 1995/06/19 12:39:11 quinn
55 * Fixed bug in timeout code. Added BER dumper.
57 * Revision 1.37 1995/06/16 13:16:14 quinn
58 * Fixed Defaultdiagformat.
60 * Revision 1.36 1995/06/16 10:31:36 quinn
61 * Added session timeout.
63 * Revision 1.35 1995/06/15 07:45:14 quinn
66 * Revision 1.34 1995/06/14 15:26:46 quinn
67 * *** empty log message ***
69 * Revision 1.33 1995/06/06 14:57:05 quinn
72 * Revision 1.32 1995/06/06 08:41:44 quinn
75 * Revision 1.31 1995/06/06 08:15:37 quinn
78 * Revision 1.30 1995/06/05 10:53:32 quinn
79 * Added a better SCAN.
81 * Revision 1.29 1995/06/01 11:25:03 quinn
84 * Revision 1.28 1995/06/01 11:21:01 quinn
85 * Attempting to fix a bug in pack-records. replaced break with continue
86 * for large records, according to standard.
88 * Revision 1.27 1995/05/29 08:12:06 quinn
91 * Revision 1.26 1995/05/18 13:02:12 quinn
94 * Revision 1.25 1995/05/17 08:42:26 quinn
95 * Transfer auth info to backend. Allow backend to reject init gracefully.
97 * Revision 1.24 1995/05/16 08:51:04 quinn
98 * License, documentation, and memory fixes
100 * Revision 1.23 1995/05/15 13:25:10 quinn
103 * Revision 1.22 1995/05/15 11:56:39 quinn
104 * Asynchronous facilities. Restructuring of seshigh code.
106 * Revision 1.21 1995/05/02 08:53:19 quinn
107 * Trying in vain to fix comm with ISODE
109 * Revision 1.20 1995/04/20 15:13:00 quinn
112 * Revision 1.19 1995/04/18 08:15:34 quinn
113 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
114 * neater. We'll make the same change for decoding one day.
116 * Revision 1.18 1995/04/17 11:28:25 quinn
119 * Revision 1.17 1995/04/10 10:23:36 quinn
120 * Some work to add scan and other things.
122 * Revision 1.16 1995/03/31 09:18:55 quinn
125 * Revision 1.15 1995/03/30 14:03:23 quinn
126 * Added RFC1006 as separate library
128 * Revision 1.14 1995/03/30 12:18:17 quinn
131 * Revision 1.13 1995/03/30 09:09:24 quinn
132 * Added state-handle and some support for asynchronous activities.
134 * Revision 1.12 1995/03/29 15:40:16 quinn
135 * Ongoing work. Statserv is now dynamic by default
137 * Revision 1.11 1995/03/28 09:16:21 quinn
138 * Added record packing to the search request
140 * Revision 1.10 1995/03/27 08:34:24 quinn
141 * Added dynamic server functionality.
142 * Released bindings to session.c (is now redundant)
144 * Revision 1.9 1995/03/22 15:01:26 quinn
145 * Adjusting record packing.
147 * Revision 1.8 1995/03/22 10:13:21 quinn
148 * Working on record packer
150 * Revision 1.7 1995/03/21 15:53:31 quinn
153 * Revision 1.6 1995/03/21 12:30:09 quinn
154 * Beginning to add support for record packing.
156 * Revision 1.5 1995/03/17 10:44:13 quinn
157 * Added catch of null-string in makediagrec
159 * Revision 1.4 1995/03/17 10:18:08 quinn
160 * Added memory management.
162 * Revision 1.3 1995/03/16 17:42:39 quinn
165 * Revision 1.2 1995/03/16 13:29:01 quinn
166 * Partitioned server.
168 * Revision 1.1 1995/03/15 16:02:10 quinn
169 * Modded session.c to seshigh.c
174 * Frontend server logic.
176 * This code receives incoming APDUs, and handles client requests by means
177 * of the backend API.
179 * Some of the code is getting quite involved, compared to simpler servers -
180 * primarily because it is asynchronous both in the communication with
181 * the user and the backend. We think the complexity will pay off in
182 * the form of greater flexibility when more asynchronous facilities
185 * Memory management has become somewhat involved. In the simple case, where
186 * only one PDU is pending at a time, it will simply reuse the same memory,
187 * once it has found its working size. When we enable multiple concurrent
188 * operations, perhaps even with multiple parallel calls to the backend, it
189 * will maintain a pool of buffers for encoding and decoding, trying to
190 * minimize memory allocation/deallocation during normal operation.
192 * TODOs include (and will be done in order of public interest):
194 * Support for EXPLAIN - provide simple meta-database system.
195 * Support for access control.
196 * Support for resource control.
197 * Support for extended services - primarily Item Order.
198 * Rest of Z39.50-1994
206 #include <sys/time.h>
209 #include <comstack.h>
215 #include <statserv.h>
219 static int process_request(association *assoc);
220 void backend_response(IOCHAN i, int event);
221 static int process_response(association *assoc, request *req, Z_APDU *res);
222 static Z_APDU *process_initRequest(association *assoc, request *reqb);
223 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
225 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
226 bend_searchresult *bsrt, int *fd);
227 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
229 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
230 static void process_close(association *assoc, request *reqb);
232 static FILE *apduf = 0; /* for use in static mode */
233 static statserv_options_block *control_block = 0;
236 * Create and initialize a new association-handle.
237 * channel : iochannel for the current line.
238 * link : communications channel.
239 * Returns: 0 or a new association handle.
241 association *create_association(IOCHAN channel, COMSTACK link)
246 control_block = statserv_getcontrol();
247 if (!(new = xmalloc(sizeof(*new))))
249 new->client_chan = channel;
250 new->client_link = link;
251 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
252 !(new->encode = odr_createmem(ODR_ENCODE)))
254 if (*control_block->apdufile)
259 strcpy(filename, control_block->apdufile);
260 if (!(new->print = odr_createmem(ODR_PRINT)))
262 if (*control_block->apdufile != '-')
264 strcpy(filename, control_block->apdufile);
265 if (!control_block->dynamic)
269 if (!(apduf = fopen(filename, "w")))
271 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
274 setvbuf(apduf, 0, _IONBF, 0);
280 sprintf(filename + strlen(filename), ".%d", getpid());
281 if (!(f = fopen(filename, "w")))
283 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
286 setvbuf(f, 0, _IONBF, 0);
288 odr_setprint(new->print, f);
293 new->input_buffer = 0;
294 new->input_buffer_len = 0;
296 new->state = ASSOC_NEW;
297 request_initq(&new->incoming);
298 request_initq(&new->outgoing);
299 new->proto = cs_getproto(link);
304 * Free association and release resources.
306 void destroy_association(association *h)
308 odr_destroy(h->decode);
309 odr_destroy(h->encode);
311 odr_destroy(h->print);
313 xfree(h->input_buffer);
315 bend_close(h->backend);
316 while (request_deq(&h->incoming));
317 while (request_deq(&h->outgoing));
321 static void do_close(association *a, int reason, char *message)
324 Z_Close *cls = zget_Close(a->encode);
325 request *req = request_get();
327 /* Purge request queue */
328 while (request_deq(&a->incoming));
329 while (request_deq(&a->outgoing));
332 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
333 reason, message ? message : "none");
334 apdu.which = Z_APDU_close;
336 *cls->closeReason = reason;
337 cls->diagnosticInformation = message;
338 process_response(a, req, &apdu);
339 iochan_settimeout(a->client_chan, 60);
343 logf(LOG_DEBUG, "v2 client. No Close PDU");
344 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
346 a->state = ASSOC_DEAD;
350 * This is where PDUs from the client are read and the further
351 * processing is initiated. Flow of control moves down through the
352 * various process_* functions below, until the encoded result comes back up
353 * to the output handler in here.
355 * h : the I/O channel that has an outstanding event.
356 * event : the current outstanding event.
358 void ir_session(IOCHAN h, int event)
361 association *assoc = iochan_getdata(h);
362 COMSTACK conn = assoc->client_link;
365 assert(h && conn && assoc);
366 if (event == EVENT_TIMEOUT)
368 if (assoc->state != ASSOC_UP)
370 logf(LOG_LOG, "Final timeout - closing connection.");
372 destroy_association(assoc);
377 logf(LOG_LOG, "Session idle too long. Sending close.");
378 do_close(assoc, Z_Close_lackOfActivity, 0);
382 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
384 if (event & EVENT_INPUT)
386 logf(LOG_DEBUG, "ir_session (input)");
387 assert(assoc && conn);
388 /* We aren't speaking to this fellow */
389 if (assoc->state == ASSOC_DEAD)
391 logf(LOG_LOG, "Closed connection after reject");
393 destroy_association(assoc);
397 if ((res = cs_get(conn, &assoc->input_buffer,
398 &assoc->input_buffer_len)) <= 0)
400 logf(LOG_LOG, "Connection closed by client");
402 destroy_association(assoc);
406 else if (res == 1) /* incomplete read - wait for more */
408 if (cs_more(conn)) /* more stuff - call us again later, please */
409 iochan_setevent(h, EVENT_INPUT);
411 /* we got a complete PDU. Let's decode it */
412 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
413 req = request_get(); /* get a new request structure */
414 odr_reset(assoc->decode);
415 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
416 if (!z_APDU(assoc->decode, &req->request, 0))
418 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
419 odr_errlist[odr_geterror(assoc->decode)],
420 odr_offset(assoc->decode));
421 logf(LOG_LOG, "PDU dump:");
422 odr_dumpBER(log_file(), assoc->input_buffer, res);
423 do_close(assoc, Z_Close_protocolError, "Malformed package");
426 req->request_mem = odr_extract_mem(assoc->decode);
427 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
429 logf(LOG_WARN, "ODR print error: %s",
430 odr_errlist[odr_geterror(assoc->print)]);
431 odr_reset(assoc->print);
433 request_enq(&assoc->incoming, req);
436 /* can we do something yet? */
437 req = request_head(&assoc->incoming);
438 if (req->state == REQUEST_IDLE)
439 if (process_request(assoc) < 0)
440 do_close(assoc, Z_Close_systemProblem, "Unknown error");
442 if (event & EVENT_OUTPUT)
444 request *req = request_head(&assoc->outgoing);
446 logf(LOG_DEBUG, "ir_session (output)");
447 req->state = REQUEST_PENDING;
448 switch (res = cs_put(conn, req->response, req->len_response))
451 logf(LOG_LOG, "Connection closed by client");
453 destroy_association(assoc);
456 case 0: /* all sent - release the request structure */
457 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
458 nmem_destroy(req->request_mem);
459 request_deq(&assoc->outgoing);
460 request_release(req);
461 if (!request_head(&assoc->outgoing))
462 iochan_clearflag(h, EVENT_OUTPUT);
464 /* value of 1 -- partial send -- is simply ignored */
467 if (event & EVENT_EXCEPT)
469 logf(LOG_DEBUG, "ir_session (exception)");
471 destroy_association(assoc);
477 * Initiate request processing.
479 static int process_request(association *assoc)
481 request *req = request_head(&assoc->incoming);
485 logf(LOG_DEBUG, "process_request");
486 assert(req && req->state == REQUEST_IDLE);
487 switch (req->request->which)
489 case Z_APDU_initRequest:
490 res = process_initRequest(assoc, req); break;
491 case Z_APDU_searchRequest:
492 res = process_searchRequest(assoc, req, &fd); break;
493 case Z_APDU_presentRequest:
494 res = process_presentRequest(assoc, req, &fd); break;
495 case Z_APDU_scanRequest:
496 res = process_scanRequest(assoc, req, &fd); break;
498 process_close(assoc, req); return 0;
500 logf(LOG_WARN, "Bad APDU received");
505 logf(LOG_DEBUG, " result immediately available");
506 return process_response(assoc, req, res);
510 logf(LOG_WARN, " bad result");
513 else /* no result yet - one will be provided later */
517 /* Set up an I/O handler for the fd supplied by the backend */
519 logf(LOG_DEBUG, " establishing handler for result");
520 req->state = REQUEST_PENDING;
521 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
523 iochan_setdata(chan, assoc);
529 * Handle message from the backend.
531 void backend_response(IOCHAN i, int event)
533 association *assoc = iochan_getdata(i);
534 request *req = request_head(&assoc->incoming);
538 logf(LOG_DEBUG, "backend_response");
539 assert(assoc && req && req->state != REQUEST_IDLE);
540 /* determine what it is we're waiting for */
541 switch (req->request->which)
543 case Z_APDU_searchRequest:
544 res = response_searchRequest(assoc, req, 0, &fd); break;
546 case Z_APDU_presentRequest:
547 res = response_presentRequest(assoc, req, 0, &fd); break;
548 case Z_APDU_scanRequest:
549 res = response_scanRequest(assoc, req, 0, &fd); break;
552 logf(LOG_WARN, "Serious programmer's lapse or bug");
555 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
557 logf(LOG_LOG, "Fatal error when talking to backend");
558 do_close(assoc, Z_Close_systemProblem, 0);
562 else if (!res) /* no result yet - try again later */
564 logf(LOG_DEBUG, " no result yet");
565 iochan_setfd(i, fd); /* in case fd has changed */
570 * Encode response, and transfer the request structure to the outgoing queue.
572 static int process_response(association *assoc, request *req, Z_APDU *res)
574 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
575 if (!z_APDU(assoc->encode, &res, 0))
577 logf(LOG_WARN, "ODR error when encoding response: %s",
578 odr_errlist[odr_geterror(assoc->decode)]);
581 req->response = odr_getbuf(assoc->encode, &req->len_response,
582 &req->size_response);
583 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
584 odr_reset(assoc->encode);
585 if (assoc->print && !z_APDU(assoc->print, &res, 0))
587 logf(LOG_WARN, "ODR print error: %s",
588 odr_errlist[odr_geterror(assoc->print)]);
589 odr_reset(assoc->print);
591 /* change this when we make the backend reentrant */
592 if (req == request_head(&assoc->incoming))
594 req->state = REQUEST_IDLE;
595 request_deq(&assoc->incoming);
597 request_enq(&assoc->outgoing, req);
598 /* turn the work over to the ir_session handler */
599 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
600 /* Is there more work to be done? give that to the input handler too */
601 if (request_head(&assoc->incoming))
602 iochan_setevent(assoc->client_chan, EVENT_WORK);
607 * Handle init request.
608 * At the moment, we don't check the options
609 * anywhere else in the code - we just try not to do anything that would
610 * break a naive client. We'll toss 'em into the association block when
611 * we need them there.
613 static Z_APDU *process_initRequest(association *assoc, request *reqb)
615 Z_InitRequest *req = reqb->request->u.initRequest;
616 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
617 Z_InitResponse *resp = apdu->u.initResponse;
618 bend_initrequest binitreq;
619 bend_initresult *binitres;
622 logf(LOG_LOG, "Got initRequest");
623 if (req->implementationId)
624 logf(LOG_LOG, "Id: %s", req->implementationId);
625 if (req->implementationName)
626 logf(LOG_LOG, "Name: %s", req->implementationName);
627 if (req->implementationVersion)
628 logf(LOG_LOG, "Version: %s", req->implementationVersion);
630 binitreq.configname = "default-config";
631 binitreq.auth = req->idAuthentication;
632 if (!(binitres = bend_init(&binitreq)))
634 logf(LOG_WARN, "Bad response from backend.");
638 assoc->backend = binitres->handle;
639 resp->referenceId = req->referenceId;
641 /* let's tell the client what we can do */
642 if (ODR_MASK_GET(req->options, Z_Options_search))
644 ODR_MASK_SET(resp->options, Z_Options_search);
645 strcat(options, "srch");
647 if (ODR_MASK_GET(req->options, Z_Options_present))
649 ODR_MASK_SET(resp->options, Z_Options_present);
650 strcat(options, " prst");
653 if (ODR_MASK_GET(req->options, Z_Options_delSet))
655 ODR_MASK_SET(&options, Z_Options_delSet);
656 strcat(options, " del");
659 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
661 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
662 strcat(options, " namedresults");
664 if (ODR_MASK_GET(req->options, Z_Options_scan))
666 ODR_MASK_SET(resp->options, Z_Options_scan);
667 strcat(options, " scan");
669 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
671 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
672 strcat(options, " concurop");
675 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
677 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
678 assoc->version = 2; /* 1 & 2 are equivalent */
680 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
682 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
685 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
687 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
690 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
691 assoc->maximumRecordSize = *req->maximumRecordSize;
692 if (assoc->maximumRecordSize > control_block->maxrecordsize)
693 assoc->maximumRecordSize = control_block->maxrecordsize;
694 assoc->preferredMessageSize = *req->preferredMessageSize;
695 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
696 assoc->preferredMessageSize = assoc->maximumRecordSize;
697 resp->preferredMessageSize = &assoc->preferredMessageSize;
698 resp->maximumRecordSize = &assoc->maximumRecordSize;
699 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
700 if (binitres->errcode)
702 logf(LOG_LOG, "Connection rejected by backend.");
704 assoc->state = ASSOC_DEAD;
707 assoc->state = ASSOC_UP;
712 * These functions should be merged.
716 * nonsurrogate diagnostic record.
718 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
720 static Z_Records rec;
724 static Z_DiagRec drec;
725 static Z_DefaultDiagFormat dr;
731 bib1.class = CLASS_DIAGSET;
732 bib1.value = VAL_BIB1;
734 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
737 rec.which = Z_Records_NSD;
739 rec.u.nonSurrogateDiagnostic = &drec;
740 drec.which = Z_DiagRec_defaultFormat;
741 drec.u.defaultFormat = &dr;
743 rec.u.nonSurrogateDiagnostic = &dr;
745 dr.diagnosticSetId = oid_getoidbyent(&bib1);
747 dr.which = Z_DiagForm_v2AddInfo;
748 dr.addinfo = addinfo ? addinfo : "";
753 * surrogate diagnostic.
755 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
756 int error, char *addinfo)
758 static Z_NamePlusRecord rec;
762 static Z_DiagRec drec;
763 static Z_DefaultDiagFormat dr;
769 bib1.class = CLASS_DIAGSET;
770 bib1.value = VAL_BIB1;
772 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
774 rec.databaseName = dbname;
775 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
777 rec.u.surrogateDiagnostic = &drec;
778 drec.which = Z_DiagRec_defaultFormat;
779 drec.u.defaultFormat = &dr;
781 rec.u.surrogateDiagnostic = &dr;
783 dr.diagnosticSetId = oid_getoidbyent(&bib1);
785 dr.which = Z_DiagForm_v2AddInfo;
786 dr.addinfo = addinfo ? addinfo : "";
791 * multiple nonsurrogate diagnostics.
793 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
795 static Z_DiagRecs recs;
799 static Z_DiagRec *recp[1], drec;
800 static Z_DefaultDiagFormat rec;
802 static Z_DiagRec *recp[1], rec;
805 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
807 bib1.class = CLASS_DIAGSET;
808 bib1.value = VAL_BIB1;
811 recs.num_diagRecs = 1;
812 recs.diagRecs = recp;
815 drec.which = Z_DiagRec_defaultFormat;
816 drec.u.defaultFormat = &rec;
820 rec.diagnosticSetId = oid_getoidbyent(&bib1);
821 rec.condition = &err;
822 rec.which = Z_DiagForm_v2AddInfo;
823 rec.addinfo = addinfo ? addinfo : "";
827 #define MAX_RECORDS 256
829 static Z_Records *pack_records(association *a, char *setname, int start,
830 int *num, Z_RecordComposition *comp,
831 int *next, int *pres, oid_value format)
833 int recno, total_length = 0, toget = *num;
834 static Z_Records records;
835 static Z_NamePlusRecordList reclist;
836 static Z_NamePlusRecord *list[MAX_RECORDS];
839 records.which = Z_Records_DBOSD;
840 records.u.databaseOrSurDiagnostics = &reclist;
841 reclist.num_records = 0;
842 reclist.records = list;
843 *pres = Z_PRES_SUCCESS;
847 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
848 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
849 a->maximumRecordSize);
850 for (recno = start; reclist.num_records < toget; recno++)
852 bend_fetchrequest freq;
853 bend_fetchresult *fres;
854 Z_NamePlusRecord *thisrec;
855 Z_DatabaseRecord *thisext;
859 * we get the number of bytes allocated on the stream before any
860 * allocation done by the backend - this should give us a reasonable
861 * idea of the total size of the data so far.
863 total_length = odr_total(a->encode);
864 if (reclist.num_records == MAX_RECORDS - 1)
866 *pres = Z_PRES_PARTIAL_2;
869 freq.setname = setname;
872 freq.format = format;
873 freq.stream = a->encode;
874 if (!(fres = bend_fetch(a->backend, &freq, 0)))
876 *pres = Z_PRES_FAILURE;
877 return diagrec(a->proto, 2, "Backend interface problem");
879 /* backend should be able to signal whether error is system-wide
880 or only pertaining to current record */
883 *pres = Z_PRES_FAILURE;
884 return diagrec(a->proto, fres->errcode, fres->errstring);
887 this_length = fres->len;
889 this_length = odr_total(a->encode) - total_length;
890 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
891 this_length, total_length);
892 if (this_length + total_length > a->preferredMessageSize)
894 /* record is small enough, really */
895 if (this_length <= a->preferredMessageSize)
897 logf(LOG_DEBUG, " Dropped last normal-sized record");
898 *pres = Z_PRES_PARTIAL_2;
901 /* record can only be fetched by itself */
902 if (this_length < a->maximumRecordSize)
904 logf(LOG_DEBUG, " Record > prefmsgsz");
907 logf(LOG_DEBUG, " Dropped it");
908 reclist.records[reclist.num_records] =
909 surrogatediagrec(a->proto, fres->basename, 16, 0);
910 reclist.num_records++;
914 else /* too big entirely */
916 logf(LOG_DEBUG, "Record > maxrcdsz");
917 reclist.records[reclist.num_records] =
918 surrogatediagrec(a->proto, fres->basename, 17, 0);
919 reclist.num_records++;
923 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
925 if (!(thisrec->databaseName = odr_malloc(a->encode,
926 strlen(fres->basename) + 1)))
928 strcpy(thisrec->databaseName, fres->basename);
929 thisrec->which = Z_NamePlusRecord_databaseRecord;
930 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
931 sizeof(Z_DatabaseRecord))))
933 recform.proto = a->proto;
934 recform.class = CLASS_RECSYN;
935 recform.value = fres->format;
936 thisext->direct_reference = odr_oiddup(a->encode,
937 oid_getoidbyent(&recform));
938 thisext->indirect_reference = 0;
939 thisext->descriptor = 0;
940 if (fres->len < 0) /* Structured data */
942 switch (fres->format)
944 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
945 case VAL_GRS1: thisext->which = Z_External_grs1; break;
946 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
950 logf(LOG_FATAL, "Unknown structured format from backend.");
955 * We cheat on the pointers here. Obviously, the record field
956 * of the backend-fetch structure should have been a union for
957 * correctness, but we're stuck with this for backwards
960 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
962 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
964 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
966 thisext->which = Z_External_sutrs;
967 thisext->u.sutrs = sutrs;
968 sutrs->buf = odr_malloc(a->encode, fres->len);
969 sutrs->len = sutrs->size = fres->len;
970 memcpy(sutrs->buf, fres->record, fres->len);
972 else /* octet-aligned record. */
974 thisext->which = Z_External_octet;
975 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
978 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
981 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
982 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
985 reclist.records[reclist.num_records] = thisrec;
986 reclist.num_records++;
987 *next = fres->last_in_set ? 0 : recno + 1;
989 *num = reclist.num_records;
993 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
996 Z_SearchRequest *req = reqb->request->u.searchRequest;
997 bend_searchrequest bsrq;
998 bend_searchresult *bsrt;
1000 logf(LOG_LOG, "Got SearchRequest.");
1002 bsrq.setname = req->resultSetName;
1003 bsrq.replace_set = *req->replaceIndicator;
1004 bsrq.num_bases = req->num_databaseNames;
1005 bsrq.basenames = req->databaseNames;
1006 bsrq.query = req->query;
1008 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1010 return response_searchRequest(assoc, reqb, bsrt, fd);
1013 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1016 * Prepare a searchresponse based on the backend results. We probably want
1017 * to look at making the fetching of records nonblocking as well, but
1018 * so far, we'll keep things simple.
1019 * If bsrt is null, that means we're called in response to a communications
1020 * event, and we'll have to get the response for ourselves.
1022 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1023 bend_searchresult *bsrt, int *fd)
1025 Z_SearchRequest *req = reqb->request->u.searchRequest;
1027 static Z_SearchResponse resp;
1028 static int nulint = 0;
1029 static bool_t sr = 1;
1030 static int next = 0;
1031 static int none = Z_RES_NONE;
1033 apdu.which = Z_APDU_searchResponse;
1034 apdu.u.searchResponse = &resp;
1035 resp.referenceId = req->referenceId;
1037 resp.additionalSearchInfo = 0;
1041 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1043 logf(LOG_FATAL, "Bad result from backend");
1046 else if (bsrt->errcode)
1048 resp.records = diagrec(assoc->proto, bsrt->errcode,
1050 resp.resultCount = &nulint;
1051 resp.numberOfRecordsReturned = &nulint;
1052 resp.nextResultSetPosition = &nulint;
1053 resp.searchStatus = &nulint;
1054 resp.resultSetStatus = &none;
1055 resp.presentStatus = 0;
1060 Z_RecordComposition comp, *compp = 0;
1061 static int presst = 0;
1064 resp.resultCount = &bsrt->hits;
1066 comp.which = Z_RecordComp_simple;
1067 /* how many records does the user agent want, then? */
1068 if (bsrt->hits <= *req->smallSetUpperBound)
1071 if ((comp.u.simple = req->smallSetElementSetNames))
1074 else if (bsrt->hits < *req->largeSetLowerBound)
1076 toget = *req->mediumSetPresentNumber;
1077 if (toget > bsrt->hits)
1079 if ((comp.u.simple = req->mediumSetElementSetNames))
1085 if (toget && !resp.records)
1090 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1091 prefformat->class != CLASS_RECSYN)
1094 form = prefformat->value;
1095 resp.records = pack_records(assoc, req->resultSetName, 1,
1096 &toget, compp, &next, &presst, form);
1099 resp.numberOfRecordsReturned = &toget;
1100 resp.nextResultSetPosition = &next;
1101 resp.searchStatus = &sr;
1102 resp.resultSetStatus = 0;
1103 resp.presentStatus = &presst;
1107 if (*resp.resultCount)
1109 resp.numberOfRecordsReturned = &nulint;
1110 resp.nextResultSetPosition = &next;
1111 resp.searchStatus = &sr;
1112 resp.resultSetStatus = 0;
1113 resp.presentStatus = 0;
1120 * Maybe we got a little over-friendly when we designed bend_fetch to
1121 * get only one record at a time. Some backends can optimise multiple-record
1122 * fetches, and at any rate, there is some overhead involved in
1123 * all that selecting and hopping around. Problem is, of course, that the
1124 * frontend can't know ahead of time how many records it'll need to
1125 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1126 * is downright lousy as a bulk data transfer protocol.
1128 * To start with, we'll do the fetching of records from the backend
1129 * in one operation: To save some trips in and out of the event-handler,
1130 * and to simplify the interface to pack_records. At any rate, asynch
1131 * operation is more fun in operations that have an unpredictable execution
1132 * speed - which is normally more true for search than for present.
1134 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1137 Z_PresentRequest *req = reqb->request->u.presentRequest;
1139 static Z_PresentResponse resp;
1140 static int presst, next, num;
1145 logf(LOG_LOG, "Got PresentRequest.");
1146 apdu.which = Z_APDU_presentResponse;
1147 apdu.u.presentResponse = &resp;
1148 resp.referenceId = req->referenceId;
1153 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1154 prefformat->class != CLASS_RECSYN)
1157 form = prefformat->value;
1158 num = *req->numberOfRecordsRequested;
1159 resp.records = pack_records(assoc, req->resultSetId,
1160 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1164 resp.numberOfRecordsReturned = #
1165 resp.presentStatus = &presst;
1166 resp.nextResultSetPosition = &next;
1172 * Scan was implemented rather in a hurry, and with support for only the basic
1173 * elements of the service in the backend API. Suggestions are welcome.
1175 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1177 Z_ScanRequest *req = reqb->request->u.scanRequest;
1179 static Z_ScanResponse res;
1180 static int scanStatus = Z_Scan_failure;
1181 static int numberOfEntriesReturned = 0;
1183 static Z_ListEntries ents;
1184 #define SCAN_MAX_ENTRIES 200
1185 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1186 bend_scanrequest srq;
1187 bend_scanresult *srs;
1189 logf(LOG_LOG, "Got scanrequest");
1190 apdu.which = Z_APDU_scanResponse;
1191 apdu.u.scanResponse = &res;
1192 res.referenceId = req->referenceId;
1194 res.scanStatus = &scanStatus;
1195 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1196 res.positionOfTerm = 0;
1197 res.entries = &ents;
1198 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1199 res.attributeSet = 0;
1204 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1205 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1206 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1207 else if (req->stepSize && *req->stepSize > 0)
1208 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1211 if (req->termListAndStartPoint->term->which == Z_Term_general)
1212 logf(LOG_DEBUG, " term: '%.*s'",
1213 req->termListAndStartPoint->term->u.general->len,
1214 req->termListAndStartPoint->term->u.general->buf);
1215 srq.num_bases = req->num_databaseNames;
1216 srq.basenames = req->databaseNames;
1217 srq.num_entries = *req->numberOfTermsRequested;
1218 srq.term = req->termListAndStartPoint;
1219 srq.term_position = req->preferredPositionInResponse ?
1220 *req->preferredPositionInResponse : 1;
1221 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1222 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1223 else if (srs->errcode)
1224 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1225 srs->errcode, srs->errstring);
1229 static Z_Entries list;
1231 if (srs->status == BEND_SCAN_PARTIAL)
1232 scanStatus = Z_Scan_partial_5;
1234 scanStatus = Z_Scan_success;
1235 ents.which = Z_ListEntries_entries;
1236 ents.u.entries = &list;
1238 for (i = 0; i < srs->num_entries; i++)
1244 if (i >= SCAN_MAX_ENTRIES)
1246 scanStatus = Z_Scan_partial_4;
1249 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1250 e->which = Z_Entry_termInfo;
1251 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1252 t->suggestedAttributes = 0;
1253 t->alternativeTerm = 0;
1254 t->byAttributes = 0;
1255 t->globalOccurrences = &srs->entries[i].occurrences;
1256 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1257 t->term->which = Z_Term_general;
1258 t->term->u.general = o = odr_malloc(assoc->encode,
1260 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1261 strlen(srs->entries[i].term));
1262 memcpy(o->buf, srs->entries[i].term, o->len);
1263 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1264 srs->entries[i].term, srs->entries[i].occurrences);
1266 list.num_entries = i;
1267 res.numberOfEntriesReturned = &list.num_entries;
1268 res.positionOfTerm = &srs->term_position;
1275 static void process_close(association *assoc, request *reqb)
1277 Z_Close *req = reqb->request->u.close;
1278 static char *reasons[] =
1285 "securityViolation",
1292 logf(LOG_LOG, "Got close, reason %s, message %s",
1293 reasons[*req->closeReason], req->diagnosticInformation ?
1294 req->diagnosticInformation : "NULL");
1295 if (assoc->version < 3) /* to make do_force respond with close */
1297 do_close(assoc, Z_Close_finished, "Association terminated by client");