2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.48 1995-10-06 08:51:20 quinn
10 * Revision 1.47 1995/08/29 14:24:16 quinn
11 * Added second half of close-handshake
13 * Revision 1.46 1995/08/29 11:17:58 quinn
14 * Added code to receive close
16 * Revision 1.45 1995/08/21 09:11:00 quinn
17 * Smallish fixes to suppport new formats.
19 * Revision 1.44 1995/08/17 12:45:25 quinn
20 * Fixed minor problems with GRS-1. Added support in c&s.
22 * Revision 1.43 1995/08/15 12:00:31 quinn
25 * Revision 1.42 1995/08/15 11:16:50 quinn
27 * Revision 1.41 1995/08/02 10:23:06 quinn
30 * Revision 1.40 1995/07/31 14:34:26 quinn
31 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
33 * Revision 1.39 1995/06/27 13:21:00 quinn
36 * Revision 1.38 1995/06/19 12:39:11 quinn
37 * Fixed bug in timeout code. Added BER dumper.
39 * Revision 1.37 1995/06/16 13:16:14 quinn
40 * Fixed Defaultdiagformat.
42 * Revision 1.36 1995/06/16 10:31:36 quinn
43 * Added session timeout.
45 * Revision 1.35 1995/06/15 07:45:14 quinn
48 * Revision 1.34 1995/06/14 15:26:46 quinn
49 * *** empty log message ***
51 * Revision 1.33 1995/06/06 14:57:05 quinn
54 * Revision 1.32 1995/06/06 08:41:44 quinn
57 * Revision 1.31 1995/06/06 08:15:37 quinn
60 * Revision 1.30 1995/06/05 10:53:32 quinn
61 * Added a better SCAN.
63 * Revision 1.29 1995/06/01 11:25:03 quinn
66 * Revision 1.28 1995/06/01 11:21:01 quinn
67 * Attempting to fix a bug in pack-records. replaced break with continue
68 * for large records, according to standard.
70 * Revision 1.27 1995/05/29 08:12:06 quinn
73 * Revision 1.26 1995/05/18 13:02:12 quinn
76 * Revision 1.25 1995/05/17 08:42:26 quinn
77 * Transfer auth info to backend. Allow backend to reject init gracefully.
79 * Revision 1.24 1995/05/16 08:51:04 quinn
80 * License, documentation, and memory fixes
82 * Revision 1.23 1995/05/15 13:25:10 quinn
85 * Revision 1.22 1995/05/15 11:56:39 quinn
86 * Asynchronous facilities. Restructuring of seshigh code.
88 * Revision 1.21 1995/05/02 08:53:19 quinn
89 * Trying in vain to fix comm with ISODE
91 * Revision 1.20 1995/04/20 15:13:00 quinn
94 * Revision 1.19 1995/04/18 08:15:34 quinn
95 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
96 * neater. We'll make the same change for decoding one day.
98 * Revision 1.18 1995/04/17 11:28:25 quinn
101 * Revision 1.17 1995/04/10 10:23:36 quinn
102 * Some work to add scan and other things.
104 * Revision 1.16 1995/03/31 09:18:55 quinn
107 * Revision 1.15 1995/03/30 14:03:23 quinn
108 * Added RFC1006 as separate library
110 * Revision 1.14 1995/03/30 12:18:17 quinn
113 * Revision 1.13 1995/03/30 09:09:24 quinn
114 * Added state-handle and some support for asynchronous activities.
116 * Revision 1.12 1995/03/29 15:40:16 quinn
117 * Ongoing work. Statserv is now dynamic by default
119 * Revision 1.11 1995/03/28 09:16:21 quinn
120 * Added record packing to the search request
122 * Revision 1.10 1995/03/27 08:34:24 quinn
123 * Added dynamic server functionality.
124 * Released bindings to session.c (is now redundant)
126 * Revision 1.9 1995/03/22 15:01:26 quinn
127 * Adjusting record packing.
129 * Revision 1.8 1995/03/22 10:13:21 quinn
130 * Working on record packer
132 * Revision 1.7 1995/03/21 15:53:31 quinn
135 * Revision 1.6 1995/03/21 12:30:09 quinn
136 * Beginning to add support for record packing.
138 * Revision 1.5 1995/03/17 10:44:13 quinn
139 * Added catch of null-string in makediagrec
141 * Revision 1.4 1995/03/17 10:18:08 quinn
142 * Added memory management.
144 * Revision 1.3 1995/03/16 17:42:39 quinn
147 * Revision 1.2 1995/03/16 13:29:01 quinn
148 * Partitioned server.
150 * Revision 1.1 1995/03/15 16:02:10 quinn
151 * Modded session.c to seshigh.c
156 * Frontend server logic.
158 * This code receives incoming APDUs, and handles client requests by means
159 * of the backend API.
161 * Some of the code is getting quite involved, compared to simpler servers -
162 * primarily because it is asynchronous both in the communication with
163 * the user and the backend. We think the complexity will pay off in
164 * the form of greater flexibility when more asynchronous facilities
167 * Memory management has become somewhat involved. In the simple case, where
168 * only one PDU is pending at a time, it will simply reuse the same memory,
169 * once it has found its working size. When we enable multiple concurrent
170 * operations, perhaps even with multiple parallel calls to the backend, it
171 * will maintain a pool of buffers for encoding and decoding, trying to
172 * minimize memory allocation/deallocation during normal operation.
174 * TODOs include (and will be done in order of public interest):
176 * Support for EXPLAIN - provide simple meta-database system.
177 * Support for access control.
178 * Support for resource control.
179 * Support for extended services - primarily Item Order.
180 * Rest of Z39.50-1994
188 #include <sys/time.h>
191 #include <comstack.h>
197 #include <statserv.h>
201 static int process_request(association *assoc);
202 void backend_response(IOCHAN i, int event);
203 static int process_response(association *assoc, request *req, Z_APDU *res);
204 static Z_APDU *process_initRequest(association *assoc, request *reqb);
205 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
207 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
208 bend_searchresult *bsrt, int *fd);
209 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
211 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
212 static void process_close(association *assoc, request *reqb);
214 static FILE *apduf = 0; /* for use in static mode */
215 static statserv_options_block *control_block = 0;
218 * Create and initialize a new association-handle.
219 * channel : iochannel for the current line.
220 * link : communications channel.
221 * Returns: 0 or a new association handle.
223 association *create_association(IOCHAN channel, COMSTACK link)
228 control_block = statserv_getcontrol();
229 if (!(new = malloc(sizeof(*new))))
231 new->client_chan = channel;
232 new->client_link = link;
233 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
234 !(new->encode = odr_createmem(ODR_ENCODE)))
236 if (*control_block->apdufile)
241 strcpy(filename, control_block->apdufile);
242 if (!(new->print = odr_createmem(ODR_PRINT)))
244 if (*control_block->apdufile != '-')
246 strcpy(filename, control_block->apdufile);
247 if (!control_block->dynamic)
251 if (!(apduf = fopen(filename, "w")))
253 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
256 setvbuf(apduf, 0, _IONBF, 0);
262 sprintf(filename + strlen(filename), ".%d", getpid());
263 if (!(f = fopen(filename, "w")))
265 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
268 setvbuf(f, 0, _IONBF, 0);
270 odr_setprint(new->print, f);
275 new->input_buffer = 0;
276 new->input_buffer_len = 0;
278 new->state = ASSOC_NEW;
279 request_initq(&new->incoming);
280 request_initq(&new->outgoing);
281 new->proto = cs_getproto(link);
286 * Free association and release resources.
288 void destroy_association(association *h)
290 odr_destroy(h->decode);
291 odr_destroy(h->encode);
293 odr_destroy(h->print);
295 free(h->input_buffer);
297 bend_close(h->backend);
298 while (request_deq(&h->incoming));
299 while (request_deq(&h->outgoing));
303 static void do_close(association *a, int reason, char *message)
306 Z_Close *cls = zget_Close(a->encode);
307 request *req = request_get();
309 /* Purge request queue */
310 while (request_deq(&a->incoming));
311 while (request_deq(&a->outgoing));
314 logf(LOG_DEBUG, "Generating Close PDU");
315 apdu.which = Z_APDU_close;
317 *cls->closeReason = reason;
318 cls->diagnosticInformation = message;
319 process_response(a, req, &apdu);
320 iochan_settimeout(a->client_chan, 60);
324 logf(LOG_DEBUG, "v2 client. No Close PDU");
325 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
327 a->state = ASSOC_DEAD;
331 * This is where PDUs from the client are read and the further
332 * processing is initiated. Flow of control moves down through the
333 * various process_* functions below, until the encoded result comes back up
334 * to the output handler in here.
336 * h : the I/O channel that has an outstanding event.
337 * event : the current outstanding event.
339 void ir_session(IOCHAN h, int event)
342 association *assoc = iochan_getdata(h);
343 COMSTACK conn = assoc->client_link;
346 assert(h && conn && assoc);
347 if (event == EVENT_TIMEOUT)
349 if (assoc->state != ASSOC_UP)
351 logf(LOG_LOG, "Final timeout - closing connection.");
353 destroy_association(assoc);
358 logf(LOG_LOG, "Session idle too long. Sending close.");
359 do_close(assoc, Z_Close_lackOfActivity, 0);
363 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
365 if (event & EVENT_INPUT)
367 logf(LOG_DEBUG, "ir_session (input)");
368 assert(assoc && conn);
369 /* We aren't speaking to this fellow */
370 if (assoc->state == ASSOC_DEAD)
372 logf(LOG_LOG, "Closed connection after reject");
374 destroy_association(assoc);
378 if ((res = cs_get(conn, &assoc->input_buffer,
379 &assoc->input_buffer_len)) <= 0)
381 logf(LOG_LOG, "Connection closed by client");
383 destroy_association(assoc);
387 else if (res == 1) /* incomplete read - wait for more */
389 if (cs_more(conn)) /* more stuff - call us again later, please */
390 iochan_setevent(h, EVENT_INPUT);
392 /* we got a complete PDU. Let's decode it */
393 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
394 req = request_get(); /* get a new request structure */
395 odr_reset(assoc->decode);
396 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
397 if (!z_APDU(assoc->decode, &req->request, 0))
399 logf(LOG_LOG, "ODR error on incoming PDU: %s",
400 odr_errlist[odr_geterror(assoc->decode)]);
401 logf(LOG_LOG, "PDU dump:");
402 odr_dumpBER(log_file(), assoc->input_buffer, res);
403 do_close(assoc, Z_Close_protocolError, "Malformed package");
406 req->request_mem = odr_extract_mem(assoc->decode);
407 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
409 logf(LOG_WARN, "ODR print error: %s",
410 odr_errlist[odr_geterror(assoc->print)]);
411 odr_reset(assoc->print);
413 request_enq(&assoc->incoming, req);
416 /* can we do something yet? */
417 req = request_head(&assoc->incoming);
418 if (req->state == REQUEST_IDLE)
419 if (process_request(assoc) < 0)
420 do_close(assoc, Z_Close_systemProblem, "Unknown error");
422 if (event & EVENT_OUTPUT)
424 request *req = request_head(&assoc->outgoing);
426 logf(LOG_DEBUG, "ir_session (output)");
427 req->state = REQUEST_PENDING;
428 switch (res = cs_put(conn, req->response, req->len_response))
431 logf(LOG_LOG, "Connection closed by client");
433 destroy_association(assoc);
436 case 0: /* all sent - release the request structure */
437 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
438 odr_release_mem(req->request_mem);
439 request_deq(&assoc->outgoing);
440 request_release(req);
441 if (!request_head(&assoc->outgoing))
442 iochan_clearflag(h, EVENT_OUTPUT);
444 /* value of 1 -- partial send -- is simply ignored */
447 if (event & EVENT_EXCEPT)
449 logf(LOG_DEBUG, "ir_session (exception)");
451 destroy_association(assoc);
457 * Initiate request processing.
459 static int process_request(association *assoc)
461 request *req = request_head(&assoc->incoming);
465 logf(LOG_DEBUG, "process_request");
466 assert(req && req->state == REQUEST_IDLE);
467 switch (req->request->which)
469 case Z_APDU_initRequest:
470 res = process_initRequest(assoc, req); break;
471 case Z_APDU_searchRequest:
472 res = process_searchRequest(assoc, req, &fd); break;
473 case Z_APDU_presentRequest:
474 res = process_presentRequest(assoc, req, &fd); break;
475 case Z_APDU_scanRequest:
476 res = process_scanRequest(assoc, req, &fd); break;
478 process_close(assoc, req); return 0;
480 logf(LOG_WARN, "Bad APDU received");
485 logf(LOG_DEBUG, " result immediately available");
486 return process_response(assoc, req, res);
490 logf(LOG_WARN, " bad result");
493 else /* no result yet - one will be provided later */
497 /* Set up an I/O handler for the fd supplied by the backend */
499 logf(LOG_DEBUG, " establishing handler for result");
500 req->state = REQUEST_PENDING;
501 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
503 iochan_setdata(chan, assoc);
509 * Handle message from the backend.
511 void backend_response(IOCHAN i, int event)
513 association *assoc = iochan_getdata(i);
514 request *req = request_head(&assoc->incoming);
518 logf(LOG_DEBUG, "backend_response");
519 assert(assoc && req && req->state != REQUEST_IDLE);
520 /* determine what it is we're waiting for */
521 switch (req->request->which)
523 case Z_APDU_searchRequest:
524 res = response_searchRequest(assoc, req, 0, &fd); break;
526 case Z_APDU_presentRequest:
527 res = response_presentRequest(assoc, req, 0, &fd); break;
528 case Z_APDU_scanRequest:
529 res = response_scanRequest(assoc, req, 0, &fd); break;
532 logf(LOG_WARN, "Serious programmer's lapse or bug");
535 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
537 logf(LOG_LOG, "Fatal error when talking to backend");
538 do_close(assoc, Z_Close_systemProblem, 0);
542 else if (!res) /* no result yet - try again later */
544 logf(LOG_DEBUG, " no result yet");
545 iochan_setfd(i, fd); /* in case fd has changed */
550 * Encode response, and transfer the request structure to the outgoing queue.
552 static int process_response(association *assoc, request *req, Z_APDU *res)
554 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
555 if (!z_APDU(assoc->encode, &res, 0))
557 logf(LOG_WARN, "ODR error when encoding response: %s",
558 odr_errlist[odr_geterror(assoc->decode)]);
561 req->response = odr_getbuf(assoc->encode, &req->len_response,
562 &req->size_response);
563 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
564 odr_reset(assoc->encode);
565 if (assoc->print && !z_APDU(assoc->print, &res, 0))
567 logf(LOG_WARN, "ODR print error: %s",
568 odr_errlist[odr_geterror(assoc->print)]);
569 odr_reset(assoc->print);
571 /* change this when we make the backend reentrant */
572 if (req == request_head(&assoc->incoming))
574 req->state = REQUEST_IDLE;
575 request_deq(&assoc->incoming);
577 request_enq(&assoc->outgoing, req);
578 /* turn the work over to the ir_session handler */
579 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
580 /* Is there more work to be done? give that to the input handler too */
581 if (request_head(&assoc->incoming))
582 iochan_setevent(assoc->client_chan, EVENT_WORK);
587 * Handle init request.
588 * At the moment, we don't check the options
589 * anywhere else in the code - we just try not to do anything that would
590 * break a naive client. We'll toss 'em into the association block when
591 * we need them there.
593 static Z_APDU *process_initRequest(association *assoc, request *reqb)
595 Z_InitRequest *req = reqb->request->u.initRequest;
596 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
597 Z_InitResponse *resp = apdu->u.initResponse;
598 bend_initrequest binitreq;
599 bend_initresult *binitres;
602 logf(LOG_LOG, "Got initRequest");
603 if (req->implementationId)
604 logf(LOG_LOG, "Id: %s", req->implementationId);
605 if (req->implementationName)
606 logf(LOG_LOG, "Name: %s", req->implementationName);
607 if (req->implementationVersion)
608 logf(LOG_LOG, "Version: %s", req->implementationVersion);
610 binitreq.configname = "default-config";
611 binitreq.auth = req->idAuthentication;
612 if (!(binitres = bend_init(&binitreq)))
614 logf(LOG_WARN, "Bad response from backend.");
618 assoc->backend = binitres->handle;
619 resp->referenceId = req->referenceId;
621 /* let's tell the client what we can do */
622 if (ODR_MASK_GET(req->options, Z_Options_search))
624 ODR_MASK_SET(resp->options, Z_Options_search);
625 strcat(options, "srch");
627 if (ODR_MASK_GET(req->options, Z_Options_present))
629 ODR_MASK_SET(resp->options, Z_Options_present);
630 strcat(options, " prst");
633 if (ODR_MASK_GET(req->options, Z_Options_delSet))
635 ODR_MASK_SET(&options, Z_Options_delSet);
636 strcat(options, " del");
639 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
641 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
642 strcat(options, " namedresults");
644 if (ODR_MASK_GET(req->options, Z_Options_scan))
646 ODR_MASK_SET(resp->options, Z_Options_scan);
647 strcat(options, " scan");
649 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
651 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
652 strcat(options, " concurop");
655 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
657 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
658 assoc->version = 2; /* 1 & 2 are equivalent */
660 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
662 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
665 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
667 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
670 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
671 assoc->maximumRecordSize = *req->maximumRecordSize;
672 if (assoc->maximumRecordSize > control_block->maxrecordsize)
673 assoc->maximumRecordSize = control_block->maxrecordsize;
674 assoc->preferredMessageSize = *req->preferredMessageSize;
675 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
676 assoc->preferredMessageSize = assoc->maximumRecordSize;
677 resp->preferredMessageSize = &assoc->preferredMessageSize;
678 resp->maximumRecordSize = &assoc->maximumRecordSize;
679 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
680 if (binitres->errcode)
682 logf(LOG_LOG, "Connection rejected by backend.");
684 assoc->state = ASSOC_DEAD;
687 assoc->state = ASSOC_UP;
692 * These functions should be merged.
696 * nonsurrogate diagnostic record.
698 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
700 static Z_Records rec;
704 static Z_DiagRec drec;
705 static Z_DefaultDiagFormat dr;
711 bib1.class = CLASS_DIAGSET;
712 bib1.value = VAL_BIB1;
714 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
717 rec.which = Z_Records_NSD;
719 rec.u.nonSurrogateDiagnostic = &drec;
720 drec.which = Z_DiagRec_defaultFormat;
721 drec.u.defaultFormat = &dr;
723 rec.u.nonSurrogateDiagnostic = &dr;
725 dr.diagnosticSetId = oid_getoidbyent(&bib1);
727 dr.which = Z_DiagForm_v2AddInfo;
728 dr.addinfo = addinfo ? addinfo : "";
733 * surrogate diagnostic.
735 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
736 int error, char *addinfo)
738 static Z_NamePlusRecord rec;
742 static Z_DiagRec drec;
743 static Z_DefaultDiagFormat dr;
749 bib1.class = CLASS_DIAGSET;
750 bib1.value = VAL_BIB1;
752 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
754 rec.databaseName = dbname;
755 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
757 rec.u.surrogateDiagnostic = &drec;
758 drec.which = Z_DiagRec_defaultFormat;
759 drec.u.defaultFormat = &dr;
761 rec.u.surrogateDiagnostic = &dr;
763 dr.diagnosticSetId = oid_getoidbyent(&bib1);
765 dr.which = Z_DiagForm_v2AddInfo;
766 dr.addinfo = addinfo ? addinfo : "";
771 * multiple nonsurrogate diagnostics.
773 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
775 static Z_DiagRecs recs;
779 static Z_DiagRec *recp[1], drec;
780 static Z_DefaultDiagFormat rec;
782 static Z_DiagRec *recp[1], rec;
785 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
787 bib1.class = CLASS_DIAGSET;
788 bib1.value = VAL_BIB1;
791 recs.num_diagRecs = 1;
792 recs.diagRecs = recp;
795 drec.which = Z_DiagRec_defaultFormat;
796 drec.u.defaultFormat = &rec;
800 rec.diagnosticSetId = oid_getoidbyent(&bib1);
801 rec.condition = &err;
802 rec.which = Z_DiagForm_v2AddInfo;
803 rec.addinfo = addinfo ? addinfo : "";
807 #define MAX_RECORDS 256
809 static Z_Records *pack_records(association *a, char *setname, int start,
810 int *num, Z_ElementSetNames *esn,
811 int *next, int *pres, oid_value format)
813 int recno, total_length = 0, toget = *num;
814 static Z_Records records;
815 static Z_NamePlusRecordList reclist;
816 static Z_NamePlusRecord *list[MAX_RECORDS];
819 records.which = Z_Records_DBOSD;
820 records.u.databaseOrSurDiagnostics = &reclist;
821 reclist.num_records = 0;
822 reclist.records = list;
823 *pres = Z_PRES_SUCCESS;
827 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
828 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
829 a->maximumRecordSize);
830 for (recno = start; reclist.num_records < toget; recno++)
832 bend_fetchrequest freq;
833 bend_fetchresult *fres;
834 Z_NamePlusRecord *thisrec;
835 Z_DatabaseRecord *thisext;
839 * we get the number of bytes allocated on the stream before any
840 * allocation done by the backend - this should give us a reasonable
841 * idea of the total size of the data so far.
843 total_length = odr_total(a->encode);
844 if (reclist.num_records == MAX_RECORDS - 1)
846 *pres = Z_PRES_PARTIAL_2;
849 freq.setname = setname;
851 freq.format = format;
852 freq.stream = a->encode;
853 if (!(fres = bend_fetch(a->backend, &freq, 0)))
855 *pres = Z_PRES_FAILURE;
856 return diagrec(a->proto, 2, "Backend interface problem");
858 /* backend should be able to signal whether error is system-wide
859 or only pertaining to current record */
862 *pres = Z_PRES_FAILURE;
863 return diagrec(a->proto, fres->errcode, fres->errstring);
866 this_length = fres->len;
868 this_length = odr_total(a->encode) - total_length;
869 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
870 this_length, total_length);
871 if (this_length + total_length > a->preferredMessageSize)
873 /* record is small enough, really */
874 if (this_length <= a->preferredMessageSize)
876 logf(LOG_DEBUG, " Dropped last normal-sized record");
877 *pres = Z_PRES_PARTIAL_2;
880 /* record can only be fetched by itself */
881 if (this_length < a->maximumRecordSize)
883 logf(LOG_DEBUG, " Record > prefmsgsz");
886 logf(LOG_DEBUG, " Dropped it");
887 reclist.records[reclist.num_records] =
888 surrogatediagrec(a->proto, fres->basename, 16, 0);
889 reclist.num_records++;
893 else /* too big entirely */
895 logf(LOG_DEBUG, "Record > maxrcdsz");
896 reclist.records[reclist.num_records] =
897 surrogatediagrec(a->proto, fres->basename, 17, 0);
898 reclist.num_records++;
902 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
904 if (!(thisrec->databaseName = odr_malloc(a->encode,
905 strlen(fres->basename) + 1)))
907 strcpy(thisrec->databaseName, fres->basename);
908 thisrec->which = Z_NamePlusRecord_databaseRecord;
909 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
910 sizeof(Z_DatabaseRecord))))
912 recform.proto = a->proto;
913 recform.class = CLASS_RECSYN;
914 recform.value = fres->format;
915 thisext->direct_reference = odr_oiddup(a->encode,
916 oid_getoidbyent(&recform));
917 thisext->indirect_reference = 0;
918 thisext->descriptor = 0;
919 if (fres->len < 0) /* Structured data */
921 switch (fres->format)
923 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
924 case VAL_GRS1: thisext->which = Z_External_grs1; break;
925 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
929 logf(LOG_FATAL, "Unknown structured format from backend.");
934 * We cheat on the pointers here. Obviously, the record field
935 * of the backend-fetch structure should have been a union for
936 * correctness, but we're stuck with this for backwards
939 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
941 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
943 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
945 thisext->which = Z_External_sutrs;
946 thisext->u.sutrs = sutrs;
947 sutrs->buf = odr_malloc(a->encode, fres->len);
948 sutrs->len = sutrs->size = fres->len;
949 memcpy(sutrs->buf, fres->record, fres->len);
951 else /* octet-aligned record. */
953 thisext->which = Z_External_octet;
954 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
957 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
960 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
961 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
964 reclist.records[reclist.num_records] = thisrec;
965 reclist.num_records++;
966 *next = fres->last_in_set ? 0 : recno + 1;
968 *num = reclist.num_records;
972 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
975 Z_SearchRequest *req = reqb->request->u.searchRequest;
976 bend_searchrequest bsrq;
977 bend_searchresult *bsrt;
979 logf(LOG_LOG, "Got SearchRequest.");
981 bsrq.setname = req->resultSetName;
982 bsrq.replace_set = *req->replaceIndicator;
983 bsrq.num_bases = req->num_databaseNames;
984 bsrq.basenames = req->databaseNames;
985 bsrq.query = req->query;
987 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
989 return response_searchRequest(assoc, reqb, bsrt, fd);
992 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
995 * Prepare a searchresponse based on the backend results. We probably want
996 * to look at making the fetching of records nonblocking as well, but
997 * so far, we'll keep things simple.
998 * If bsrt is null, that means we're called in response to a communications
999 * event, and we'll have to get the response for ourselves.
1001 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1002 bend_searchresult *bsrt, int *fd)
1004 Z_SearchRequest *req = reqb->request->u.searchRequest;
1006 static Z_SearchResponse resp;
1007 static int nulint = 0;
1008 static bool_t sr = 1;
1009 static int next = 0;
1010 static int none = Z_RES_NONE;
1012 apdu.which = Z_APDU_searchResponse;
1013 apdu.u.searchResponse = &resp;
1014 resp.referenceId = req->referenceId;
1016 resp.additionalSearchInfo = 0;
1020 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1022 logf(LOG_FATAL, "Bad result from backend");
1025 else if (bsrt->errcode)
1027 resp.records = diagrec(assoc->proto, bsrt->errcode,
1029 resp.resultCount = &nulint;
1030 resp.numberOfRecordsReturned = &nulint;
1031 resp.nextResultSetPosition = &nulint;
1032 resp.searchStatus = &nulint;
1033 resp.resultSetStatus = &none;
1034 resp.presentStatus = 0;
1039 Z_ElementSetNames *setnames;
1040 static int presst = 0;
1043 resp.resultCount = &bsrt->hits;
1045 /* how many records does the user agent want, then? */
1046 if (bsrt->hits <= *req->smallSetUpperBound)
1049 setnames = req->smallSetElementSetNames;
1051 else if (bsrt->hits < *req->largeSetLowerBound)
1053 toget = *req->mediumSetPresentNumber;
1054 if (toget > bsrt->hits)
1056 setnames = req->mediumSetElementSetNames;
1061 if (toget && !resp.records)
1066 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1067 prefformat->class != CLASS_RECSYN)
1070 form = prefformat->value;
1071 resp.records = pack_records(assoc, req->resultSetName, 1,
1072 &toget, setnames, &next, &presst, form);
1075 resp.numberOfRecordsReturned = &toget;
1076 resp.nextResultSetPosition = &next;
1077 resp.searchStatus = &sr;
1078 resp.resultSetStatus = 0;
1079 resp.presentStatus = &presst;
1083 if (*resp.resultCount)
1085 resp.numberOfRecordsReturned = &nulint;
1086 resp.nextResultSetPosition = &next;
1087 resp.searchStatus = &sr;
1088 resp.resultSetStatus = 0;
1089 resp.presentStatus = 0;
1096 * Maybe we got a little over-friendly when we designed bend_fetch to
1097 * get only one record at a time. Some backends can optimise multiple-record
1098 * fetches, and at any rate, there is some overhead involved in
1099 * all that selecting and hopping around. Problem is, of course, that the
1100 * frontend can't know ahead of time how many records it'll need to
1101 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1102 * is downright lousy as a bulk data transfer protocol.
1104 * To start with, we'll do the fetching of records from the backend
1105 * in one operation: To save some trips in and out of the event-handler,
1106 * and to simplify the interface to pack_records. At any rate, asynch
1107 * operation is more fun in operations that have an unpredictable execution
1108 * speed - which is normally more true for search than for present.
1110 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1113 Z_PresentRequest *req = reqb->request->u.presentRequest;
1115 static Z_PresentResponse resp;
1116 static int presst, next, num;
1121 logf(LOG_LOG, "Got PresentRequest.");
1122 apdu.which = Z_APDU_presentResponse;
1123 apdu.u.presentResponse = &resp;
1124 resp.referenceId = req->referenceId;
1129 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1130 prefformat->class != CLASS_RECSYN)
1133 form = prefformat->value;
1134 num = *req->numberOfRecordsRequested;
1135 resp.records = pack_records(assoc, req->resultSetId,
1136 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1139 resp.numberOfRecordsReturned = #
1140 resp.presentStatus = &presst;
1141 resp.nextResultSetPosition = &next;
1147 * Scan was implemented rather in a hurry, and with support for only the basic
1148 * elements of the service in the backend API. Suggestions are welcome.
1150 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1152 Z_ScanRequest *req = reqb->request->u.scanRequest;
1154 static Z_ScanResponse res;
1155 static int scanStatus = Z_Scan_failure;
1156 static int numberOfEntriesReturned = 0;
1158 static Z_ListEntries ents;
1159 #define SCAN_MAX_ENTRIES 200
1160 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1161 bend_scanrequest srq;
1162 bend_scanresult *srs;
1164 logf(LOG_LOG, "Got scanrequest");
1165 apdu.which = Z_APDU_scanResponse;
1166 apdu.u.scanResponse = &res;
1167 res.referenceId = req->referenceId;
1169 res.scanStatus = &scanStatus;
1170 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1171 res.positionOfTerm = 0;
1172 res.entries = &ents;
1173 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1174 res.attributeSet = 0;
1179 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1180 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1181 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1182 else if (req->stepSize && *req->stepSize > 0)
1183 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1186 if (req->termListAndStartPoint->term->which == Z_Term_general)
1187 logf(LOG_DEBUG, " term: '%.*s'",
1188 req->termListAndStartPoint->term->u.general->len,
1189 req->termListAndStartPoint->term->u.general->buf);
1190 srq.num_bases = req->num_databaseNames;
1191 srq.basenames = req->databaseNames;
1192 srq.num_entries = *req->numberOfTermsRequested;
1193 srq.term = req->termListAndStartPoint;
1194 srq.term_position = req->preferredPositionInResponse ?
1195 *req->preferredPositionInResponse : 1;
1196 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1197 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1198 else if (srs->errcode)
1199 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1200 srs->errcode, srs->errstring);
1204 static Z_Entries list;
1206 if (srs->status == BEND_SCAN_PARTIAL)
1207 scanStatus = Z_Scan_partial_5;
1209 scanStatus = Z_Scan_success;
1210 ents.which = Z_ListEntries_entries;
1211 ents.u.entries = &list;
1213 for (i = 0; i < srs->num_entries; i++)
1219 if (i >= SCAN_MAX_ENTRIES)
1221 scanStatus = Z_Scan_partial_4;
1224 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1225 e->which = Z_Entry_termInfo;
1226 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1227 t->suggestedAttributes = 0;
1228 t->alternativeTerm = 0;
1229 t->byAttributes = 0;
1230 t->globalOccurrences = &srs->entries[i].occurrences;
1231 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1232 t->term->which = Z_Term_general;
1233 t->term->u.general = o = odr_malloc(assoc->encode,
1235 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1236 strlen(srs->entries[i].term));
1237 memcpy(o->buf, srs->entries[i].term, o->len);
1238 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1239 srs->entries[i].term, srs->entries[i].occurrences);
1241 list.num_entries = i;
1242 res.numberOfEntriesReturned = &list.num_entries;
1243 res.positionOfTerm = &srs->term_position;
1250 static void process_close(association *assoc, request *reqb)
1252 Z_Close *req = reqb->request->u.close;
1253 static char *reasons[] =
1260 "securityViolation",
1267 logf(LOG_LOG, "Got close, reason %s, message %s",
1268 reasons[*req->closeReason], req->diagnosticInformation ?
1269 req->diagnosticInformation : "NULL");
1270 if (assoc->version < 3) /* to make do_force respond with close */
1272 do_close(assoc, Z_Close_finished, "Association terminated by client");