2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.47 1995-08-29 14:24:16 quinn
8 * Added second half of close-handshake
10 * Revision 1.46 1995/08/29 11:17:58 quinn
11 * Added code to receive close
13 * Revision 1.45 1995/08/21 09:11:00 quinn
14 * Smallish fixes to suppport new formats.
16 * Revision 1.44 1995/08/17 12:45:25 quinn
17 * Fixed minor problems with GRS-1. Added support in c&s.
19 * Revision 1.43 1995/08/15 12:00:31 quinn
22 * Revision 1.42 1995/08/15 11:16:50 quinn
23 * CV:e ----------------------------------------------------------------------
24 * CV:e ----------------------------------------------------------------------
26 * Revision 1.41 1995/08/02 10:23:06 quinn
29 * Revision 1.40 1995/07/31 14:34:26 quinn
30 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
32 * Revision 1.39 1995/06/27 13:21:00 quinn
35 * Revision 1.38 1995/06/19 12:39:11 quinn
36 * Fixed bug in timeout code. Added BER dumper.
38 * Revision 1.37 1995/06/16 13:16:14 quinn
39 * Fixed Defaultdiagformat.
41 * Revision 1.36 1995/06/16 10:31:36 quinn
42 * Added session timeout.
44 * Revision 1.35 1995/06/15 07:45:14 quinn
47 * Revision 1.34 1995/06/14 15:26:46 quinn
48 * *** empty log message ***
50 * Revision 1.33 1995/06/06 14:57:05 quinn
53 * Revision 1.32 1995/06/06 08:41:44 quinn
56 * Revision 1.31 1995/06/06 08:15:37 quinn
59 * Revision 1.30 1995/06/05 10:53:32 quinn
60 * Added a better SCAN.
62 * Revision 1.29 1995/06/01 11:25:03 quinn
65 * Revision 1.28 1995/06/01 11:21:01 quinn
66 * Attempting to fix a bug in pack-records. replaced break with continue
67 * for large records, according to standard.
69 * Revision 1.27 1995/05/29 08:12:06 quinn
72 * Revision 1.26 1995/05/18 13:02:12 quinn
75 * Revision 1.25 1995/05/17 08:42:26 quinn
76 * Transfer auth info to backend. Allow backend to reject init gracefully.
78 * Revision 1.24 1995/05/16 08:51:04 quinn
79 * License, documentation, and memory fixes
81 * Revision 1.23 1995/05/15 13:25:10 quinn
84 * Revision 1.22 1995/05/15 11:56:39 quinn
85 * Asynchronous facilities. Restructuring of seshigh code.
87 * Revision 1.21 1995/05/02 08:53:19 quinn
88 * Trying in vain to fix comm with ISODE
90 * Revision 1.20 1995/04/20 15:13:00 quinn
93 * Revision 1.19 1995/04/18 08:15:34 quinn
94 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
95 * neater. We'll make the same change for decoding one day.
97 * Revision 1.18 1995/04/17 11:28:25 quinn
100 * Revision 1.17 1995/04/10 10:23:36 quinn
101 * Some work to add scan and other things.
103 * Revision 1.16 1995/03/31 09:18:55 quinn
106 * Revision 1.15 1995/03/30 14:03:23 quinn
107 * Added RFC1006 as separate library
109 * Revision 1.14 1995/03/30 12:18:17 quinn
112 * Revision 1.13 1995/03/30 09:09:24 quinn
113 * Added state-handle and some support for asynchronous activities.
115 * Revision 1.12 1995/03/29 15:40:16 quinn
116 * Ongoing work. Statserv is now dynamic by default
118 * Revision 1.11 1995/03/28 09:16:21 quinn
119 * Added record packing to the search request
121 * Revision 1.10 1995/03/27 08:34:24 quinn
122 * Added dynamic server functionality.
123 * Released bindings to session.c (is now redundant)
125 * Revision 1.9 1995/03/22 15:01:26 quinn
126 * Adjusting record packing.
128 * Revision 1.8 1995/03/22 10:13:21 quinn
129 * Working on record packer
131 * Revision 1.7 1995/03/21 15:53:31 quinn
134 * Revision 1.6 1995/03/21 12:30:09 quinn
135 * Beginning to add support for record packing.
137 * Revision 1.5 1995/03/17 10:44:13 quinn
138 * Added catch of null-string in makediagrec
140 * Revision 1.4 1995/03/17 10:18:08 quinn
141 * Added memory management.
143 * Revision 1.3 1995/03/16 17:42:39 quinn
146 * Revision 1.2 1995/03/16 13:29:01 quinn
147 * Partitioned server.
149 * Revision 1.1 1995/03/15 16:02:10 quinn
150 * Modded session.c to seshigh.c
155 * Frontend server logic.
157 * This code receives incoming APDUs, and handles client requests by means
158 * of the backend API.
160 * Some of the code is getting quite involved, compared to simpler servers -
161 * primarily because it is asynchronous both in the communication with
162 * the user and the backend. We think the complexity will pay off in
163 * the form of greater flexibility when more asynchronous facilities
166 * Memory management has become somewhat involved. In the simple case, where
167 * only one PDU is pending at a time, it will simply reuse the same memory,
168 * once it has found its working size. When we enable multiple concurrent
169 * operations, perhaps even with multiple parallel calls to the backend, it
170 * will maintain a pool of buffers for encoding and decoding, trying to
171 * minimize memory allocation/deallocation during normal operation.
173 * TODOs include (and will be done in order of public interest):
175 * Support for EXPLAIN - provide simple meta-database system.
176 * Support for access control.
177 * Support for resource control.
178 * Support for extended services - primarily Item Order.
179 * Rest of Z39.50-1994
187 #include <sys/time.h>
190 #include <comstack.h>
196 #include <statserv.h>
200 static int process_request(association *assoc);
201 void backend_response(IOCHAN i, int event);
202 static int process_response(association *assoc, request *req, Z_APDU *res);
203 static Z_APDU *process_initRequest(association *assoc, request *reqb);
204 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
206 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
207 bend_searchresult *bsrt, int *fd);
208 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
210 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
211 static void process_close(association *assoc, request *reqb);
213 static FILE *apduf = 0; /* for use in static mode */
214 static statserv_options_block *control_block = 0;
217 * Create and initialize a new association-handle.
218 * channel : iochannel for the current line.
219 * link : communications channel.
220 * Returns: 0 or a new association handle.
222 association *create_association(IOCHAN channel, COMSTACK link)
227 control_block = statserv_getcontrol();
228 if (!(new = malloc(sizeof(*new))))
230 new->client_chan = channel;
231 new->client_link = link;
232 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
233 !(new->encode = odr_createmem(ODR_ENCODE)))
235 if (*control_block->apdufile)
240 strcpy(filename, control_block->apdufile);
241 if (!(new->print = odr_createmem(ODR_PRINT)))
243 if (*control_block->apdufile != '-')
245 strcpy(filename, control_block->apdufile);
246 if (!control_block->dynamic)
250 if (!(apduf = fopen(filename, "w")))
252 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
255 setvbuf(apduf, 0, _IONBF, 0);
261 sprintf(filename + strlen(filename), ".%d", getpid());
262 if (!(f = fopen(filename, "w")))
264 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
267 setvbuf(f, 0, _IONBF, 0);
269 odr_setprint(new->print, f);
274 new->input_buffer = 0;
275 new->input_buffer_len = 0;
277 new->state = ASSOC_NEW;
278 request_initq(&new->incoming);
279 request_initq(&new->outgoing);
280 new->proto = cs_getproto(link);
285 * Free association and release resources.
287 void destroy_association(association *h)
289 odr_destroy(h->decode);
290 odr_destroy(h->encode);
292 odr_destroy(h->print);
294 free(h->input_buffer);
296 bend_close(h->backend);
297 while (request_deq(&h->incoming));
298 while (request_deq(&h->outgoing));
302 static void do_close(association *a, int reason, char *message)
305 Z_Close *cls = zget_Close(a->encode);
306 request *req = request_get();
308 /* Purge request queue */
309 while (request_deq(&a->incoming));
310 while (request_deq(&a->outgoing));
313 logf(LOG_DEBUG, "Generating Close PDU");
314 apdu.which = Z_APDU_close;
316 *cls->closeReason = reason;
317 cls->diagnosticInformation = message;
318 process_response(a, req, &apdu);
319 iochan_settimeout(a->client_chan, 60);
323 logf(LOG_DEBUG, "v2 client. No Close PDU");
324 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
326 a->state = ASSOC_DEAD;
330 * This is where PDUs from the client are read and the further
331 * processing is initiated. Flow of control moves down through the
332 * various process_* functions below, until the encoded result comes back up
333 * to the output handler in here.
335 * h : the I/O channel that has an outstanding event.
336 * event : the current outstanding event.
338 void ir_session(IOCHAN h, int event)
341 association *assoc = iochan_getdata(h);
342 COMSTACK conn = assoc->client_link;
345 assert(h && conn && assoc);
346 if (event == EVENT_TIMEOUT)
348 if (assoc->state != ASSOC_UP)
350 logf(LOG_LOG, "Final timeout - closing connection.");
352 destroy_association(assoc);
357 logf(LOG_LOG, "Session idle too long. Sending close.");
358 do_close(assoc, Z_Close_lackOfActivity, 0);
362 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
364 if (event & EVENT_INPUT)
366 logf(LOG_DEBUG, "ir_session (input)");
367 assert(assoc && conn);
368 /* We aren't speaking to this fellow */
369 if (assoc->state == ASSOC_DEAD)
371 logf(LOG_LOG, "Closed connection after reject");
373 destroy_association(assoc);
377 if ((res = cs_get(conn, &assoc->input_buffer,
378 &assoc->input_buffer_len)) <= 0)
380 logf(LOG_LOG, "Connection closed by client");
382 destroy_association(assoc);
386 else if (res == 1) /* incomplete read - wait for more */
388 if (cs_more(conn)) /* more stuff - call us again later, please */
389 iochan_setevent(h, EVENT_INPUT);
391 /* we got a complete PDU. Let's decode it */
392 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
393 req = request_get(); /* get a new request structure */
394 odr_reset(assoc->decode);
395 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
396 if (!z_APDU(assoc->decode, &req->request, 0))
398 logf(LOG_LOG, "ODR error on incoming PDU: %s",
399 odr_errlist[odr_geterror(assoc->decode)]);
400 logf(LOG_LOG, "PDU dump:");
401 odr_dumpBER(log_file(), assoc->input_buffer, res);
402 do_close(assoc, Z_Close_protocolError, "Malformed package");
405 req->request_mem = odr_extract_mem(assoc->decode);
406 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
408 logf(LOG_WARN, "ODR print error: %s",
409 odr_errlist[odr_geterror(assoc->print)]);
410 odr_reset(assoc->print);
412 request_enq(&assoc->incoming, req);
415 /* can we do something yet? */
416 req = request_head(&assoc->incoming);
417 if (req->state == REQUEST_IDLE)
418 if (process_request(assoc) < 0)
419 do_close(assoc, Z_Close_systemProblem, "Unknown error");
421 if (event & EVENT_OUTPUT)
423 request *req = request_head(&assoc->outgoing);
425 logf(LOG_DEBUG, "ir_session (output)");
426 req->state = REQUEST_PENDING;
427 switch (res = cs_put(conn, req->response, req->len_response))
430 logf(LOG_LOG, "Connection closed by client");
432 destroy_association(assoc);
435 case 0: /* all sent - release the request structure */
436 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
437 odr_release_mem(req->request_mem);
438 request_deq(&assoc->outgoing);
439 request_release(req);
440 if (!request_head(&assoc->outgoing))
441 iochan_clearflag(h, EVENT_OUTPUT);
443 /* value of 1 -- partial send -- is simply ignored */
446 if (event & EVENT_EXCEPT)
448 logf(LOG_DEBUG, "ir_session (exception)");
450 destroy_association(assoc);
456 * Initiate request processing.
458 static int process_request(association *assoc)
460 request *req = request_head(&assoc->incoming);
464 logf(LOG_DEBUG, "process_request");
465 assert(req && req->state == REQUEST_IDLE);
466 switch (req->request->which)
468 case Z_APDU_initRequest:
469 res = process_initRequest(assoc, req); break;
470 case Z_APDU_searchRequest:
471 res = process_searchRequest(assoc, req, &fd); break;
472 case Z_APDU_presentRequest:
473 res = process_presentRequest(assoc, req, &fd); break;
474 case Z_APDU_scanRequest:
475 res = process_scanRequest(assoc, req, &fd); break;
477 process_close(assoc, req); return 0;
479 logf(LOG_WARN, "Bad APDU received");
484 logf(LOG_DEBUG, " result immediately available");
485 return process_response(assoc, req, res);
489 logf(LOG_WARN, " bad result");
492 else /* no result yet - one will be provided later */
496 /* Set up an I/O handler for the fd supplied by the backend */
498 logf(LOG_DEBUG, " establishing handler for result");
499 req->state = REQUEST_PENDING;
500 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
502 iochan_setdata(chan, assoc);
508 * Handle message from the backend.
510 void backend_response(IOCHAN i, int event)
512 association *assoc = iochan_getdata(i);
513 request *req = request_head(&assoc->incoming);
517 logf(LOG_DEBUG, "backend_response");
518 assert(assoc && req && req->state != REQUEST_IDLE);
519 /* determine what it is we're waiting for */
520 switch (req->request->which)
522 case Z_APDU_searchRequest:
523 res = response_searchRequest(assoc, req, 0, &fd); break;
525 case Z_APDU_presentRequest:
526 res = response_presentRequest(assoc, req, 0, &fd); break;
527 case Z_APDU_scanRequest:
528 res = response_scanRequest(assoc, req, 0, &fd); break;
531 logf(LOG_WARN, "Serious programmer's lapse or bug");
534 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
536 logf(LOG_LOG, "Fatal error when talking to backend");
537 do_close(assoc, Z_Close_systemProblem, 0);
541 else if (!res) /* no result yet - try again later */
543 logf(LOG_DEBUG, " no result yet");
544 iochan_setfd(i, fd); /* in case fd has changed */
549 * Encode response, and transfer the request structure to the outgoing queue.
551 static int process_response(association *assoc, request *req, Z_APDU *res)
553 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
554 if (!z_APDU(assoc->encode, &res, 0))
556 logf(LOG_WARN, "ODR error when encoding response: %s",
557 odr_errlist[odr_geterror(assoc->decode)]);
560 req->response = odr_getbuf(assoc->encode, &req->len_response,
561 &req->size_response);
562 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
563 odr_reset(assoc->encode);
564 if (assoc->print && !z_APDU(assoc->print, &res, 0))
566 logf(LOG_WARN, "ODR print error: %s",
567 odr_errlist[odr_geterror(assoc->print)]);
568 odr_reset(assoc->print);
570 /* change this when we make the backend reentrant */
571 if (req == request_head(&assoc->incoming))
573 req->state = REQUEST_IDLE;
574 request_deq(&assoc->incoming);
576 request_enq(&assoc->outgoing, req);
577 /* turn the work over to the ir_session handler */
578 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
579 /* Is there more work to be done? give that to the input handler too */
580 if (request_head(&assoc->incoming))
581 iochan_setevent(assoc->client_chan, EVENT_WORK);
586 * Handle init request.
587 * At the moment, we don't check the protocol version or the options
588 * anywhere else in the code - we just try not to do anything that would
589 * break a naive client. We'll toss 'em into the association block when
590 * we need them there.
592 static Z_APDU *process_initRequest(association *assoc, request *reqb)
594 Z_InitRequest *req = reqb->request->u.initRequest;
595 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
596 Z_InitResponse *resp = apdu->u.initResponse;
597 bend_initrequest binitreq;
598 bend_initresult *binitres;
601 logf(LOG_LOG, "Got initRequest");
602 if (req->implementationId)
603 logf(LOG_LOG, "Id: %s", req->implementationId);
604 if (req->implementationName)
605 logf(LOG_LOG, "Name: %s", req->implementationName);
606 if (req->implementationVersion)
607 logf(LOG_LOG, "Version: %s", req->implementationVersion);
609 binitreq.configname = "default-config";
610 binitreq.auth = req->idAuthentication;
611 if (!(binitres = bend_init(&binitreq)))
613 logf(LOG_WARN, "Bad response from backend.");
617 assoc->backend = binitres->handle;
618 resp->referenceId = req->referenceId;
620 /* let's tell the client what we can do */
621 if (ODR_MASK_GET(req->options, Z_Options_search))
623 ODR_MASK_SET(resp->options, Z_Options_search);
624 strcat(options, "srch");
626 if (ODR_MASK_GET(req->options, Z_Options_present))
628 ODR_MASK_SET(resp->options, Z_Options_present);
629 strcat(options, " prst");
632 if (ODR_MASK_GET(req->options, Z_Options_delSet))
634 ODR_MASK_SET(&options, Z_Options_delSet);
635 strcat(options, " del");
638 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
640 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
641 strcat(options, " namedresults");
643 if (ODR_MASK_GET(req->options, Z_Options_scan))
645 ODR_MASK_SET(resp->options, Z_Options_scan);
646 strcat(options, " scan");
648 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
650 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
651 strcat(options, " concurop");
654 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
656 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
657 assoc->version = 2; /* 1 & 2 are equivalent */
659 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
661 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
664 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
666 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
669 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
670 assoc->maximumRecordSize = *req->maximumRecordSize;
671 if (assoc->maximumRecordSize > control_block->maxrecordsize)
672 assoc->maximumRecordSize = control_block->maxrecordsize;
673 assoc->preferredMessageSize = *req->preferredMessageSize;
674 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
675 assoc->preferredMessageSize = assoc->maximumRecordSize;
676 resp->preferredMessageSize = &assoc->preferredMessageSize;
677 resp->maximumRecordSize = &assoc->maximumRecordSize;
678 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
679 if (binitres->errcode)
681 logf(LOG_LOG, "Connection rejected by backend.");
683 assoc->state = ASSOC_DEAD;
686 assoc->state = ASSOC_UP;
691 * These functions should be merged.
695 * nonsurrogate diagnostic record.
697 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
699 static Z_Records rec;
703 static Z_DiagRec drec;
704 static Z_DefaultDiagFormat dr;
710 bib1.class = CLASS_DIAGSET;
711 bib1.value = VAL_BIB1;
713 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
716 rec.which = Z_Records_NSD;
718 rec.u.nonSurrogateDiagnostic = &drec;
719 drec.which = Z_DiagRec_defaultFormat;
720 drec.u.defaultFormat = &dr;
722 rec.u.nonSurrogateDiagnostic = &dr;
724 dr.diagnosticSetId = oid_getoidbyent(&bib1);
726 dr.which = Z_DiagForm_v2AddInfo;
727 dr.addinfo = addinfo ? addinfo : "";
732 * surrogate diagnostic.
734 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
735 int error, char *addinfo)
737 static Z_NamePlusRecord rec;
741 static Z_DiagRec drec;
742 static Z_DefaultDiagFormat dr;
748 bib1.class = CLASS_DIAGSET;
749 bib1.value = VAL_BIB1;
751 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
753 rec.databaseName = dbname;
754 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
756 rec.u.surrogateDiagnostic = &drec;
757 drec.which = Z_DiagRec_defaultFormat;
758 drec.u.defaultFormat = &dr;
760 rec.u.surrogateDiagnostic = &dr;
762 dr.diagnosticSetId = oid_getoidbyent(&bib1);
764 dr.which = Z_DiagForm_v2AddInfo;
765 dr.addinfo = addinfo ? addinfo : "";
770 * multiple nonsurrogate diagnostics.
772 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
774 static Z_DiagRecs recs;
778 static Z_DiagRec *recp[1], drec;
779 static Z_DefaultDiagFormat rec;
781 static Z_DiagRec *recp[1], rec;
784 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
786 bib1.class = CLASS_DIAGSET;
787 bib1.value = VAL_BIB1;
790 recs.num_diagRecs = 1;
791 recs.diagRecs = recp;
794 drec.which = Z_DiagRec_defaultFormat;
795 drec.u.defaultFormat = &rec;
799 rec.diagnosticSetId = oid_getoidbyent(&bib1);
800 rec.condition = &err;
801 rec.which = Z_DiagForm_v2AddInfo;
802 rec.addinfo = addinfo ? addinfo : "";
806 #define MAX_RECORDS 256
808 static Z_Records *pack_records(association *a, char *setname, int start,
809 int *num, Z_ElementSetNames *esn,
810 int *next, int *pres, oid_value format)
812 int recno, total_length = 0, toget = *num;
813 static Z_Records records;
814 static Z_NamePlusRecordList reclist;
815 static Z_NamePlusRecord *list[MAX_RECORDS];
818 records.which = Z_Records_DBOSD;
819 records.u.databaseOrSurDiagnostics = &reclist;
820 reclist.num_records = 0;
821 reclist.records = list;
822 *pres = Z_PRES_SUCCESS;
826 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
827 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
828 a->maximumRecordSize);
829 for (recno = start; reclist.num_records < toget; recno++)
831 bend_fetchrequest freq;
832 bend_fetchresult *fres;
833 Z_NamePlusRecord *thisrec;
834 Z_DatabaseRecord *thisext;
838 * we get the number of bytes allocated on the stream before any
839 * allocation done by the backend - this should give us a reasonable
840 * idea of the total size of the data so far.
842 total_length = odr_total(a->encode);
843 if (reclist.num_records == MAX_RECORDS - 1)
845 *pres = Z_PRES_PARTIAL_2;
848 freq.setname = setname;
850 freq.format = format;
851 freq.stream = a->encode;
852 if (!(fres = bend_fetch(a->backend, &freq, 0)))
854 *pres = Z_PRES_FAILURE;
855 return diagrec(a->proto, 2, "Backend interface problem");
857 /* backend should be able to signal whether error is system-wide
858 or only pertaining to current record */
861 *pres = Z_PRES_FAILURE;
862 return diagrec(a->proto, fres->errcode, fres->errstring);
865 this_length = fres->len;
867 this_length = odr_total(a->encode) - total_length;
868 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
869 this_length, total_length);
870 if (this_length + total_length > a->preferredMessageSize)
872 /* record is small enough, really */
873 if (this_length <= a->preferredMessageSize)
875 logf(LOG_DEBUG, " Dropped last normal-sized record");
876 *pres = Z_PRES_PARTIAL_2;
879 /* record can only be fetched by itself */
880 if (this_length < a->maximumRecordSize)
882 logf(LOG_DEBUG, " Record > prefmsgsz");
885 logf(LOG_DEBUG, " Dropped it");
886 reclist.records[reclist.num_records] =
887 surrogatediagrec(a->proto, fres->basename, 16, 0);
888 reclist.num_records++;
892 else /* too big entirely */
894 logf(LOG_DEBUG, "Record > maxrcdsz");
895 reclist.records[reclist.num_records] =
896 surrogatediagrec(a->proto, fres->basename, 17, 0);
897 reclist.num_records++;
901 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
903 if (!(thisrec->databaseName = odr_malloc(a->encode,
904 strlen(fres->basename) + 1)))
906 strcpy(thisrec->databaseName, fres->basename);
907 thisrec->which = Z_NamePlusRecord_databaseRecord;
908 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
909 sizeof(Z_DatabaseRecord))))
911 recform.proto = a->proto;
912 recform.class = CLASS_RECSYN;
913 recform.value = fres->format;
914 thisext->direct_reference = odr_oiddup(a->encode,
915 oid_getoidbyent(&recform));
916 thisext->indirect_reference = 0;
917 thisext->descriptor = 0;
918 if (fres->len < 0) /* Structured data */
920 switch (fres->format)
922 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
923 case VAL_GRS1: thisext->which = Z_External_grs1; break;
924 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
928 logf(LOG_FATAL, "Unknown structured format from backend.");
933 * We cheat on the pointers here. Obviously, the record field
934 * of the backend-fetch structure should have been a union for
935 * correctness, but we're stuck with this for backwards
938 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
940 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
942 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
944 thisext->which = Z_External_sutrs;
945 thisext->u.sutrs = sutrs;
946 sutrs->buf = odr_malloc(a->encode, fres->len);
947 sutrs->len = sutrs->size = fres->len;
948 memcpy(sutrs->buf, fres->record, fres->len);
950 else /* octet-aligned record. */
952 thisext->which = Z_External_octet;
953 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
956 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
959 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
960 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
963 reclist.records[reclist.num_records] = thisrec;
964 reclist.num_records++;
965 *next = fres->last_in_set ? 0 : recno + 1;
967 *num = reclist.num_records;
971 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
974 Z_SearchRequest *req = reqb->request->u.searchRequest;
975 bend_searchrequest bsrq;
976 bend_searchresult *bsrt;
978 logf(LOG_LOG, "Got SearchRequest.");
980 bsrq.setname = req->resultSetName;
981 bsrq.replace_set = *req->replaceIndicator;
982 bsrq.num_bases = req->num_databaseNames;
983 bsrq.basenames = req->databaseNames;
984 bsrq.query = req->query;
986 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
988 return response_searchRequest(assoc, reqb, bsrt, fd);
991 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
994 * Prepare a searchresponse based on the backend results. We probably want
995 * to look at making the fetching of records nonblocking as well, but
996 * so far, we'll keep things simple.
997 * If bsrt is null, that means we're called in response to a communications
998 * event, and we'll have to get the response for ourselves.
1000 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1001 bend_searchresult *bsrt, int *fd)
1003 Z_SearchRequest *req = reqb->request->u.searchRequest;
1005 static Z_SearchResponse resp;
1006 static int nulint = 0;
1007 static bool_t sr = 1;
1008 static int next = 0;
1009 static int none = Z_RES_NONE;
1011 apdu.which = Z_APDU_searchResponse;
1012 apdu.u.searchResponse = &resp;
1013 resp.referenceId = req->referenceId;
1015 resp.additionalSearchInfo = 0;
1019 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1021 logf(LOG_FATAL, "Bad result from backend");
1024 else if (bsrt->errcode)
1026 resp.records = diagrec(assoc->proto, bsrt->errcode,
1028 resp.resultCount = &nulint;
1029 resp.numberOfRecordsReturned = &nulint;
1030 resp.nextResultSetPosition = &nulint;
1031 resp.searchStatus = &nulint;
1032 resp.resultSetStatus = &none;
1033 resp.presentStatus = 0;
1038 Z_ElementSetNames *setnames;
1039 static int presst = 0;
1042 resp.resultCount = &bsrt->hits;
1044 /* how many records does the user agent want, then? */
1045 if (bsrt->hits <= *req->smallSetUpperBound)
1048 setnames = req->smallSetElementSetNames;
1050 else if (bsrt->hits < *req->largeSetLowerBound)
1052 toget = *req->mediumSetPresentNumber;
1053 if (toget > bsrt->hits)
1055 setnames = req->mediumSetElementSetNames;
1060 if (toget && !resp.records)
1065 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1066 prefformat->class != CLASS_RECSYN)
1069 form = prefformat->value;
1070 resp.records = pack_records(assoc, req->resultSetName, 1,
1071 &toget, setnames, &next, &presst, form);
1074 resp.numberOfRecordsReturned = &toget;
1075 resp.nextResultSetPosition = &next;
1076 resp.searchStatus = &sr;
1077 resp.resultSetStatus = 0;
1078 resp.presentStatus = &presst;
1082 if (*resp.resultCount)
1084 resp.numberOfRecordsReturned = &nulint;
1085 resp.nextResultSetPosition = &next;
1086 resp.searchStatus = &sr;
1087 resp.resultSetStatus = 0;
1088 resp.presentStatus = 0;
1095 * Maybe we got a little over-friendly when we designed bend_fetch to
1096 * get only one record at a time. Some backends can optimise multiple-record
1097 * fetches, and at any rate, there is some overhead involved in
1098 * all that selecting and hopping around. Problem is, of course, that the
1099 * frontend can't know ahead of time how many records it'll need to
1100 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1101 * is downright lousy as a bulk data transfer protocol.
1103 * To start with, we'll do the fetching of records from the backend
1104 * in one operation: To save some trips in and out of the event-handler,
1105 * and to simplify the interface to pack_records. At any rate, asynch
1106 * operation is more fun in operations that have an unpredictable execution
1107 * speed - which is normally more true for search than for present.
1109 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1112 Z_PresentRequest *req = reqb->request->u.presentRequest;
1114 static Z_PresentResponse resp;
1115 static int presst, next, num;
1120 logf(LOG_LOG, "Got PresentRequest.");
1121 apdu.which = Z_APDU_presentResponse;
1122 apdu.u.presentResponse = &resp;
1123 resp.referenceId = req->referenceId;
1128 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1129 prefformat->class != CLASS_RECSYN)
1132 form = prefformat->value;
1133 num = *req->numberOfRecordsRequested;
1134 resp.records = pack_records(assoc, req->resultSetId,
1135 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1138 resp.numberOfRecordsReturned = #
1139 resp.presentStatus = &presst;
1140 resp.nextResultSetPosition = &next;
1146 * Scan was implemented rather in a hurry, and with support for only the basic
1147 * elements of the service in the backend API. Suggestions are welcome.
1149 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1151 Z_ScanRequest *req = reqb->request->u.scanRequest;
1153 static Z_ScanResponse res;
1154 static int scanStatus = Z_Scan_failure;
1155 static int numberOfEntriesReturned = 0;
1157 static Z_ListEntries ents;
1158 #define SCAN_MAX_ENTRIES 200
1159 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1160 bend_scanrequest srq;
1161 bend_scanresult *srs;
1163 logf(LOG_LOG, "Got scanrequest");
1164 apdu.which = Z_APDU_scanResponse;
1165 apdu.u.scanResponse = &res;
1166 res.referenceId = req->referenceId;
1168 res.scanStatus = &scanStatus;
1169 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1170 res.positionOfTerm = 0;
1171 res.entries = &ents;
1172 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1173 res.attributeSet = 0;
1178 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1179 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1180 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1181 else if (req->stepSize && *req->stepSize > 0)
1182 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1185 if (req->termListAndStartPoint->term->which == Z_Term_general)
1186 logf(LOG_DEBUG, " term: '%.*s'",
1187 req->termListAndStartPoint->term->u.general->len,
1188 req->termListAndStartPoint->term->u.general->buf);
1189 srq.num_bases = req->num_databaseNames;
1190 srq.basenames = req->databaseNames;
1191 srq.num_entries = *req->numberOfTermsRequested;
1192 srq.term = req->termListAndStartPoint;
1193 srq.term_position = req->preferredPositionInResponse ?
1194 *req->preferredPositionInResponse : 1;
1195 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1196 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1197 else if (srs->errcode)
1198 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1199 srs->errcode, srs->errstring);
1203 static Z_Entries list;
1205 if (srs->status == BEND_SCAN_PARTIAL)
1206 scanStatus = Z_Scan_partial_5;
1208 scanStatus = Z_Scan_success;
1209 ents.which = Z_ListEntries_entries;
1210 ents.u.entries = &list;
1212 for (i = 0; i < srs->num_entries; i++)
1218 if (i >= SCAN_MAX_ENTRIES)
1220 scanStatus = Z_Scan_partial_4;
1223 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1224 e->which = Z_Entry_termInfo;
1225 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1226 t->suggestedAttributes = 0;
1227 t->alternativeTerm = 0;
1228 t->byAttributes = 0;
1229 t->globalOccurrences = &srs->entries[i].occurrences;
1230 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1231 t->term->which = Z_Term_general;
1232 t->term->u.general = o = odr_malloc(assoc->encode,
1234 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1235 strlen(srs->entries[i].term));
1236 memcpy(o->buf, srs->entries[i].term, o->len);
1237 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1238 srs->entries[i].term, srs->entries[i].occurrences);
1240 list.num_entries = i;
1241 res.numberOfEntriesReturned = &list.num_entries;
1242 res.positionOfTerm = &srs->term_position;
1249 static void process_close(association *assoc, request *reqb)
1251 Z_Close *req = reqb->request->u.close;
1252 static char *reasons[] =
1259 "securityViolation",
1266 logf(LOG_LOG, "Got close, reason %s, message %s",
1267 reasons[*req->closeReason], req->diagnosticInformation ?
1268 req->diagnosticInformation : "NULL");
1269 if (assoc->version < 3) /* to make do_force respond with close */
1271 do_close(assoc, Z_Close_finished, "Association terminated by client");