2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.46 1995-08-29 11:17:58 quinn
8 * Added code to receive close
10 * Revision 1.45 1995/08/21 09:11:00 quinn
11 * Smallish fixes to suppport new formats.
13 * Revision 1.44 1995/08/17 12:45:25 quinn
14 * Fixed minor problems with GRS-1. Added support in c&s.
16 * Revision 1.43 1995/08/15 12:00:31 quinn
19 * Revision 1.42 1995/08/15 11:16:50 quinn
20 * CV:e ----------------------------------------------------------------------
21 * CV:e ----------------------------------------------------------------------
23 * Revision 1.41 1995/08/02 10:23:06 quinn
26 * Revision 1.40 1995/07/31 14:34:26 quinn
27 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
29 * Revision 1.39 1995/06/27 13:21:00 quinn
32 * Revision 1.38 1995/06/19 12:39:11 quinn
33 * Fixed bug in timeout code. Added BER dumper.
35 * Revision 1.37 1995/06/16 13:16:14 quinn
36 * Fixed Defaultdiagformat.
38 * Revision 1.36 1995/06/16 10:31:36 quinn
39 * Added session timeout.
41 * Revision 1.35 1995/06/15 07:45:14 quinn
44 * Revision 1.34 1995/06/14 15:26:46 quinn
45 * *** empty log message ***
47 * Revision 1.33 1995/06/06 14:57:05 quinn
50 * Revision 1.32 1995/06/06 08:41:44 quinn
53 * Revision 1.31 1995/06/06 08:15:37 quinn
56 * Revision 1.30 1995/06/05 10:53:32 quinn
57 * Added a better SCAN.
59 * Revision 1.29 1995/06/01 11:25:03 quinn
62 * Revision 1.28 1995/06/01 11:21:01 quinn
63 * Attempting to fix a bug in pack-records. replaced break with continue
64 * for large records, according to standard.
66 * Revision 1.27 1995/05/29 08:12:06 quinn
69 * Revision 1.26 1995/05/18 13:02:12 quinn
72 * Revision 1.25 1995/05/17 08:42:26 quinn
73 * Transfer auth info to backend. Allow backend to reject init gracefully.
75 * Revision 1.24 1995/05/16 08:51:04 quinn
76 * License, documentation, and memory fixes
78 * Revision 1.23 1995/05/15 13:25:10 quinn
81 * Revision 1.22 1995/05/15 11:56:39 quinn
82 * Asynchronous facilities. Restructuring of seshigh code.
84 * Revision 1.21 1995/05/02 08:53:19 quinn
85 * Trying in vain to fix comm with ISODE
87 * Revision 1.20 1995/04/20 15:13:00 quinn
90 * Revision 1.19 1995/04/18 08:15:34 quinn
91 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
92 * neater. We'll make the same change for decoding one day.
94 * Revision 1.18 1995/04/17 11:28:25 quinn
97 * Revision 1.17 1995/04/10 10:23:36 quinn
98 * Some work to add scan and other things.
100 * Revision 1.16 1995/03/31 09:18:55 quinn
103 * Revision 1.15 1995/03/30 14:03:23 quinn
104 * Added RFC1006 as separate library
106 * Revision 1.14 1995/03/30 12:18:17 quinn
109 * Revision 1.13 1995/03/30 09:09:24 quinn
110 * Added state-handle and some support for asynchronous activities.
112 * Revision 1.12 1995/03/29 15:40:16 quinn
113 * Ongoing work. Statserv is now dynamic by default
115 * Revision 1.11 1995/03/28 09:16:21 quinn
116 * Added record packing to the search request
118 * Revision 1.10 1995/03/27 08:34:24 quinn
119 * Added dynamic server functionality.
120 * Released bindings to session.c (is now redundant)
122 * Revision 1.9 1995/03/22 15:01:26 quinn
123 * Adjusting record packing.
125 * Revision 1.8 1995/03/22 10:13:21 quinn
126 * Working on record packer
128 * Revision 1.7 1995/03/21 15:53:31 quinn
131 * Revision 1.6 1995/03/21 12:30:09 quinn
132 * Beginning to add support for record packing.
134 * Revision 1.5 1995/03/17 10:44:13 quinn
135 * Added catch of null-string in makediagrec
137 * Revision 1.4 1995/03/17 10:18:08 quinn
138 * Added memory management.
140 * Revision 1.3 1995/03/16 17:42:39 quinn
143 * Revision 1.2 1995/03/16 13:29:01 quinn
144 * Partitioned server.
146 * Revision 1.1 1995/03/15 16:02:10 quinn
147 * Modded session.c to seshigh.c
152 * Frontend server logic.
154 * This code receives incoming APDUs, and handles client requests by means
155 * of the backend API.
157 * Some of the code is getting quite involved, compared to simpler servers -
158 * primarily because it is asynchronous both in the communication with
159 * the user and the backend. We think the complexity will pay off in
160 * the form of greater flexibility when more asynchronous facilities
163 * Memory management has become somewhat involved. In the simple case, where
164 * only one PDU is pending at a time, it will simply reuse the same memory,
165 * once it has found its working size. When we enable multiple concurrent
166 * operations, perhaps even with multiple parallel calls to the backend, it
167 * will maintain a pool of buffers for encoding and decoding, trying to
168 * minimize memory allocation/deallocation during normal operation.
170 * TODOs include (and will be done in order of public interest):
172 * Support for EXPLAIN - provide simple meta-database system.
173 * Support for access control.
174 * Support for resource control.
175 * Support for extended services - primarily Item Order.
176 * Rest of Z39.50-1994
184 #include <sys/time.h>
187 #include <comstack.h>
193 #include <statserv.h>
197 static int process_request(association *assoc);
198 void backend_response(IOCHAN i, int event);
199 static int process_response(association *assoc, request *req, Z_APDU *res);
200 static Z_APDU *process_initRequest(association *assoc, request *reqb);
201 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
203 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
204 bend_searchresult *bsrt, int *fd);
205 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
207 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
209 static FILE *apduf = 0; /* for use in static mode */
210 static statserv_options_block *control_block = 0;
213 * Create and initialize a new association-handle.
214 * channel : iochannel for the current line.
215 * link : communications channel.
216 * Returns: 0 or a new association handle.
218 association *create_association(IOCHAN channel, COMSTACK link)
223 control_block = statserv_getcontrol();
224 if (!(new = malloc(sizeof(*new))))
226 new->client_chan = channel;
227 new->client_link = link;
228 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
229 !(new->encode = odr_createmem(ODR_ENCODE)))
231 if (*control_block->apdufile)
236 strcpy(filename, control_block->apdufile);
237 if (!(new->print = odr_createmem(ODR_PRINT)))
239 if (*control_block->apdufile != '-')
241 strcpy(filename, control_block->apdufile);
242 if (!control_block->dynamic)
246 if (!(apduf = fopen(filename, "w")))
248 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
251 setvbuf(apduf, 0, _IONBF, 0);
257 sprintf(filename + strlen(filename), ".%d", getpid());
258 if (!(f = fopen(filename, "w")))
260 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
263 setvbuf(f, 0, _IONBF, 0);
265 odr_setprint(new->print, f);
270 new->input_buffer = 0;
271 new->input_buffer_len = 0;
273 new->state = ASSOC_NEW;
274 request_initq(&new->incoming);
275 request_initq(&new->outgoing);
276 new->proto = cs_getproto(link);
281 * Free association and release resources.
283 void destroy_association(association *h)
285 odr_destroy(h->decode);
286 odr_destroy(h->encode);
288 odr_destroy(h->print);
290 free(h->input_buffer);
292 bend_close(h->backend);
293 while (request_deq(&h->incoming));
294 while (request_deq(&h->outgoing));
298 static void do_close(association *a, int reason, char *message)
301 Z_Close *cls = zget_Close(a->encode);
302 request *req = request_get();
304 /* Purge request queue */
305 while (request_deq(&a->incoming));
306 while (request_deq(&a->outgoing));
309 logf(LOG_DEBUG, "Generating Close PDU");
310 apdu.which = Z_APDU_close;
312 *cls->closeReason = reason;
313 cls->diagnosticInformation = message;
314 process_response(a, req, &apdu);
315 iochan_settimeout(a->client_chan, 60);
319 logf(LOG_DEBUG, "v2 client. No Close PDU");
320 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
322 a->state = ASSOC_DEAD;
326 * This is where PDUs from the client are read and the further
327 * processing is initiated. Flow of control moves down through the
328 * various process_* functions below, until the encoded result comes back up
329 * to the output handler in here.
331 * h : the I/O channel that has an outstanding event.
332 * event : the current outstanding event.
334 void ir_session(IOCHAN h, int event)
337 association *assoc = iochan_getdata(h);
338 COMSTACK conn = assoc->client_link;
341 assert(h && conn && assoc);
342 if (event == EVENT_TIMEOUT)
344 if (assoc->state != ASSOC_UP)
346 logf(LOG_LOG, "Final timeout - closing connection.");
348 destroy_association(assoc);
353 logf(LOG_LOG, "Session idle too long. Sending close.");
354 do_close(assoc, Z_Close_lackOfActivity, 0);
358 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
360 if (event & EVENT_INPUT)
362 logf(LOG_DEBUG, "ir_session (input)");
363 assert(assoc && conn);
364 /* We aren't speaking to this fellow */
365 if (assoc->state == ASSOC_DEAD)
367 logf(LOG_LOG, "Closed connection after reject");
369 destroy_association(assoc);
373 if ((res = cs_get(conn, &assoc->input_buffer,
374 &assoc->input_buffer_len)) <= 0)
376 logf(LOG_LOG, "Connection closed by client");
378 destroy_association(assoc);
382 else if (res == 1) /* incomplete read - wait for more */
384 if (cs_more(conn)) /* more stuff - call us again later, please */
385 iochan_setevent(h, EVENT_INPUT);
387 /* we got a complete PDU. Let's decode it */
388 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
389 req = request_get(); /* get a new request structure */
390 odr_reset(assoc->decode);
391 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
392 if (!z_APDU(assoc->decode, &req->request, 0))
394 logf(LOG_LOG, "ODR error on incoming PDU: %s",
395 odr_errlist[odr_geterror(assoc->decode)]);
396 logf(LOG_LOG, "PDU dump:");
397 odr_dumpBER(log_file(), assoc->input_buffer, res);
398 do_close(assoc, Z_Close_protocolError, "Malformed package");
401 req->request_mem = odr_extract_mem(assoc->decode);
402 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
404 logf(LOG_WARN, "ODR print error: %s",
405 odr_errlist[odr_geterror(assoc->print)]);
406 odr_reset(assoc->print);
408 request_enq(&assoc->incoming, req);
411 /* can we do something yet? */
412 req = request_head(&assoc->incoming);
413 if (req->state == REQUEST_IDLE)
414 if (process_request(assoc) < 0)
415 do_close(assoc, Z_Close_systemProblem, "Unknown error");
417 if (event & EVENT_OUTPUT)
419 request *req = request_head(&assoc->outgoing);
421 logf(LOG_DEBUG, "ir_session (output)");
422 req->state = REQUEST_PENDING;
423 switch (res = cs_put(conn, req->response, req->len_response))
426 logf(LOG_LOG, "Connection closed by client");
428 destroy_association(assoc);
431 case 0: /* all sent - release the request structure */
432 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
433 odr_release_mem(req->request_mem);
434 request_deq(&assoc->outgoing);
435 request_release(req);
436 if (!request_head(&assoc->outgoing))
437 iochan_clearflag(h, EVENT_OUTPUT);
439 /* value of 1 -- partial send -- is simply ignored */
442 if (event & EVENT_EXCEPT)
444 logf(LOG_DEBUG, "ir_session (exception)");
446 destroy_association(assoc);
452 * Initiate request processing.
454 static int process_request(association *assoc)
456 request *req = request_head(&assoc->incoming);
460 logf(LOG_DEBUG, "process_request");
461 assert(req && req->state == REQUEST_IDLE);
462 switch (req->request->which)
464 case Z_APDU_initRequest:
465 res = process_initRequest(assoc, req); break;
466 case Z_APDU_searchRequest:
467 res = process_searchRequest(assoc, req, &fd); break;
468 case Z_APDU_presentRequest:
469 res = process_presentRequest(assoc, req, &fd); break;
470 case Z_APDU_scanRequest:
471 res = process_scanRequest(assoc, req, &fd); break;
473 logf(LOG_WARN, "Bad APDU received");
478 logf(LOG_DEBUG, " result immediately available");
479 return process_response(assoc, req, res);
483 logf(LOG_WARN, " bad result");
486 else /* no result yet - one will be provided later */
490 /* Set up an I/O handler for the fd supplied by the backend */
492 logf(LOG_DEBUG, " establishing handler for result");
493 req->state = REQUEST_PENDING;
494 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
496 iochan_setdata(chan, assoc);
502 * Handle message from the backend.
504 void backend_response(IOCHAN i, int event)
506 association *assoc = iochan_getdata(i);
507 request *req = request_head(&assoc->incoming);
511 logf(LOG_DEBUG, "backend_response");
512 assert(assoc && req && req->state != REQUEST_IDLE);
513 /* determine what it is we're waiting for */
514 switch (req->request->which)
516 case Z_APDU_searchRequest:
517 res = response_searchRequest(assoc, req, 0, &fd); break;
519 case Z_APDU_presentRequest:
520 res = response_presentRequest(assoc, req, 0, &fd); break;
521 case Z_APDU_scanRequest:
522 res = response_scanRequest(assoc, req, 0, &fd); break;
525 logf(LOG_WARN, "Serious programmer's lapse or bug");
528 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
530 logf(LOG_LOG, "Fatal error when talking to backend");
531 do_close(assoc, Z_Close_systemProblem, 0);
535 else if (!res) /* no result yet - try again later */
537 logf(LOG_DEBUG, " no result yet");
538 iochan_setfd(i, fd); /* in case fd has changed */
543 * Encode response, and transfer the request structure to the outgoing queue.
545 static int process_response(association *assoc, request *req, Z_APDU *res)
547 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
548 if (!z_APDU(assoc->encode, &res, 0))
550 logf(LOG_WARN, "ODR error when encoding response: %s",
551 odr_errlist[odr_geterror(assoc->decode)]);
554 req->response = odr_getbuf(assoc->encode, &req->len_response,
555 &req->size_response);
556 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
557 odr_reset(assoc->encode);
558 if (assoc->print && !z_APDU(assoc->print, &res, 0))
560 logf(LOG_WARN, "ODR print error: %s",
561 odr_errlist[odr_geterror(assoc->print)]);
562 odr_reset(assoc->print);
564 /* change this when we make the backend reentrant */
565 if (req == request_head(&assoc->incoming))
567 req->state = REQUEST_IDLE;
568 request_deq(&assoc->incoming);
570 request_enq(&assoc->outgoing, req);
571 /* turn the work over to the ir_session handler */
572 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
573 /* Is there more work to be done? give that to the input handler too */
574 if (request_head(&assoc->incoming))
575 iochan_setevent(assoc->client_chan, EVENT_WORK);
580 * Handle init request.
581 * At the moment, we don't check the protocol version or the options
582 * anywhere else in the code - we just try not to do anything that would
583 * break a naive client. We'll toss 'em into the association block when
584 * we need them there.
586 static Z_APDU *process_initRequest(association *assoc, request *reqb)
588 Z_InitRequest *req = reqb->request->u.initRequest;
589 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
590 Z_InitResponse *resp = apdu->u.initResponse;
591 bend_initrequest binitreq;
592 bend_initresult *binitres;
595 logf(LOG_LOG, "Got initRequest");
596 if (req->implementationId)
597 logf(LOG_LOG, "Id: %s", req->implementationId);
598 if (req->implementationName)
599 logf(LOG_LOG, "Name: %s", req->implementationName);
600 if (req->implementationVersion)
601 logf(LOG_LOG, "Version: %s", req->implementationVersion);
603 binitreq.configname = "default-config";
604 binitreq.auth = req->idAuthentication;
605 if (!(binitres = bend_init(&binitreq)))
607 logf(LOG_WARN, "Bad response from backend.");
611 assoc->backend = binitres->handle;
612 resp->referenceId = req->referenceId;
614 /* let's tell the client what we can do */
615 if (ODR_MASK_GET(req->options, Z_Options_search))
617 ODR_MASK_SET(resp->options, Z_Options_search);
618 strcat(options, "srch");
620 if (ODR_MASK_GET(req->options, Z_Options_present))
622 ODR_MASK_SET(resp->options, Z_Options_present);
623 strcat(options, " prst");
626 if (ODR_MASK_GET(req->options, Z_Options_delSet))
628 ODR_MASK_SET(&options, Z_Options_delSet);
629 strcat(options, " del");
632 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
634 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
635 strcat(options, " namedresults");
637 if (ODR_MASK_GET(req->options, Z_Options_scan))
639 ODR_MASK_SET(resp->options, Z_Options_scan);
640 strcat(options, " scan");
642 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
644 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
645 strcat(options, " concurop");
648 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
650 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
651 assoc->version = 2; /* 1 & 2 are equivalent */
653 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
655 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
658 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
660 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
663 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
664 assoc->maximumRecordSize = *req->maximumRecordSize;
665 if (assoc->maximumRecordSize > control_block->maxrecordsize)
666 assoc->maximumRecordSize = control_block->maxrecordsize;
667 assoc->preferredMessageSize = *req->preferredMessageSize;
668 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
669 assoc->preferredMessageSize = assoc->maximumRecordSize;
670 resp->preferredMessageSize = &assoc->preferredMessageSize;
671 resp->maximumRecordSize = &assoc->maximumRecordSize;
672 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
673 if (binitres->errcode)
675 logf(LOG_LOG, "Connection rejected by backend.");
677 assoc->state = ASSOC_DEAD;
680 assoc->state = ASSOC_UP;
685 * These functions should be merged.
689 * nonsurrogate diagnostic record.
691 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
693 static Z_Records rec;
697 static Z_DiagRec drec;
698 static Z_DefaultDiagFormat dr;
704 bib1.class = CLASS_DIAGSET;
705 bib1.value = VAL_BIB1;
707 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
710 rec.which = Z_Records_NSD;
712 rec.u.nonSurrogateDiagnostic = &drec;
713 drec.which = Z_DiagRec_defaultFormat;
714 drec.u.defaultFormat = &dr;
716 rec.u.nonSurrogateDiagnostic = &dr;
718 dr.diagnosticSetId = oid_getoidbyent(&bib1);
720 dr.which = Z_DiagForm_v2AddInfo;
721 dr.addinfo = addinfo ? addinfo : "";
726 * surrogate diagnostic.
728 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
729 int error, char *addinfo)
731 static Z_NamePlusRecord rec;
735 static Z_DiagRec drec;
736 static Z_DefaultDiagFormat dr;
742 bib1.class = CLASS_DIAGSET;
743 bib1.value = VAL_BIB1;
745 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
747 rec.databaseName = dbname;
748 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
750 rec.u.surrogateDiagnostic = &drec;
751 drec.which = Z_DiagRec_defaultFormat;
752 drec.u.defaultFormat = &dr;
754 rec.u.surrogateDiagnostic = &dr;
756 dr.diagnosticSetId = oid_getoidbyent(&bib1);
758 dr.which = Z_DiagForm_v2AddInfo;
759 dr.addinfo = addinfo ? addinfo : "";
764 * multiple nonsurrogate diagnostics.
766 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
768 static Z_DiagRecs recs;
772 static Z_DiagRec *recp[1], drec;
773 static Z_DefaultDiagFormat rec;
775 static Z_DiagRec *recp[1], rec;
778 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
780 bib1.class = CLASS_DIAGSET;
781 bib1.value = VAL_BIB1;
784 recs.num_diagRecs = 1;
785 recs.diagRecs = recp;
788 drec.which = Z_DiagRec_defaultFormat;
789 drec.u.defaultFormat = &rec;
793 rec.diagnosticSetId = oid_getoidbyent(&bib1);
794 rec.condition = &err;
795 rec.which = Z_DiagForm_v2AddInfo;
796 rec.addinfo = addinfo ? addinfo : "";
800 #define MAX_RECORDS 256
802 static Z_Records *pack_records(association *a, char *setname, int start,
803 int *num, Z_ElementSetNames *esn,
804 int *next, int *pres, oid_value format)
806 int recno, total_length = 0, toget = *num;
807 static Z_Records records;
808 static Z_NamePlusRecordList reclist;
809 static Z_NamePlusRecord *list[MAX_RECORDS];
812 records.which = Z_Records_DBOSD;
813 records.u.databaseOrSurDiagnostics = &reclist;
814 reclist.num_records = 0;
815 reclist.records = list;
816 *pres = Z_PRES_SUCCESS;
820 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
821 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
822 a->maximumRecordSize);
823 for (recno = start; reclist.num_records < toget; recno++)
825 bend_fetchrequest freq;
826 bend_fetchresult *fres;
827 Z_NamePlusRecord *thisrec;
828 Z_DatabaseRecord *thisext;
832 * we get the number of bytes allocated on the stream before any
833 * allocation done by the backend - this should give us a reasonable
834 * idea of the total size of the data so far.
836 total_length = odr_total(a->encode);
837 if (reclist.num_records == MAX_RECORDS - 1)
839 *pres = Z_PRES_PARTIAL_2;
842 freq.setname = setname;
844 freq.format = format;
845 freq.stream = a->encode;
846 if (!(fres = bend_fetch(a->backend, &freq, 0)))
848 *pres = Z_PRES_FAILURE;
849 return diagrec(a->proto, 2, "Backend interface problem");
851 /* backend should be able to signal whether error is system-wide
852 or only pertaining to current record */
855 *pres = Z_PRES_FAILURE;
856 return diagrec(a->proto, fres->errcode, fres->errstring);
859 this_length = fres->len;
861 this_length = odr_total(a->encode) - total_length;
862 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
863 this_length, total_length);
864 if (this_length + total_length > a->preferredMessageSize)
866 /* record is small enough, really */
867 if (this_length <= a->preferredMessageSize)
869 logf(LOG_DEBUG, " Dropped last normal-sized record");
870 *pres = Z_PRES_PARTIAL_2;
873 /* record can only be fetched by itself */
874 if (this_length < a->maximumRecordSize)
876 logf(LOG_DEBUG, " Record > prefmsgsz");
879 logf(LOG_DEBUG, " Dropped it");
880 reclist.records[reclist.num_records] =
881 surrogatediagrec(a->proto, fres->basename, 16, 0);
882 reclist.num_records++;
886 else /* too big entirely */
888 logf(LOG_DEBUG, "Record > maxrcdsz");
889 reclist.records[reclist.num_records] =
890 surrogatediagrec(a->proto, fres->basename, 17, 0);
891 reclist.num_records++;
895 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
897 if (!(thisrec->databaseName = odr_malloc(a->encode,
898 strlen(fres->basename) + 1)))
900 strcpy(thisrec->databaseName, fres->basename);
901 thisrec->which = Z_NamePlusRecord_databaseRecord;
902 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
903 sizeof(Z_DatabaseRecord))))
905 recform.proto = a->proto;
906 recform.class = CLASS_RECSYN;
907 recform.value = fres->format;
908 thisext->direct_reference = odr_oiddup(a->encode,
909 oid_getoidbyent(&recform));
910 thisext->indirect_reference = 0;
911 thisext->descriptor = 0;
912 if (fres->len < 0) /* Structured data */
914 switch (fres->format)
916 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
917 case VAL_GRS1: thisext->which = Z_External_grs1; break;
918 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
922 logf(LOG_FATAL, "Unknown structured format from backend.");
927 * We cheat on the pointers here. Obviously, the record field
928 * of the backend-fetch structure should have been a union for
929 * correctness, but we're stuck with this for backwards
932 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
934 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
936 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
938 thisext->which = Z_External_sutrs;
939 thisext->u.sutrs = sutrs;
940 sutrs->buf = odr_malloc(a->encode, fres->len);
941 sutrs->len = sutrs->size = fres->len;
942 memcpy(sutrs->buf, fres->record, fres->len);
944 else /* octet-aligned record. */
946 thisext->which = Z_External_octet;
947 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
950 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
953 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
954 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
957 reclist.records[reclist.num_records] = thisrec;
958 reclist.num_records++;
959 *next = fres->last_in_set ? 0 : recno + 1;
961 *num = reclist.num_records;
965 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
968 Z_SearchRequest *req = reqb->request->u.searchRequest;
969 bend_searchrequest bsrq;
970 bend_searchresult *bsrt;
972 logf(LOG_LOG, "Got SearchRequest.");
974 bsrq.setname = req->resultSetName;
975 bsrq.replace_set = *req->replaceIndicator;
976 bsrq.num_bases = req->num_databaseNames;
977 bsrq.basenames = req->databaseNames;
978 bsrq.query = req->query;
980 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
982 return response_searchRequest(assoc, reqb, bsrt, fd);
985 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
988 * Prepare a searchresponse based on the backend results. We probably want
989 * to look at making the fetching of records nonblocking as well, but
990 * so far, we'll keep things simple.
991 * If bsrt is null, that means we're called in response to a communications
992 * event, and we'll have to get the response for ourselves.
994 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
995 bend_searchresult *bsrt, int *fd)
997 Z_SearchRequest *req = reqb->request->u.searchRequest;
999 static Z_SearchResponse resp;
1000 static int nulint = 0;
1001 static bool_t sr = 1;
1002 static int next = 0;
1003 static int none = Z_RES_NONE;
1005 apdu.which = Z_APDU_searchResponse;
1006 apdu.u.searchResponse = &resp;
1007 resp.referenceId = req->referenceId;
1009 resp.additionalSearchInfo = 0;
1013 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1015 logf(LOG_FATAL, "Bad result from backend");
1018 else if (bsrt->errcode)
1020 resp.records = diagrec(assoc->proto, bsrt->errcode,
1022 resp.resultCount = &nulint;
1023 resp.numberOfRecordsReturned = &nulint;
1024 resp.nextResultSetPosition = &nulint;
1025 resp.searchStatus = &nulint;
1026 resp.resultSetStatus = &none;
1027 resp.presentStatus = 0;
1032 Z_ElementSetNames *setnames;
1033 static int presst = 0;
1036 resp.resultCount = &bsrt->hits;
1038 /* how many records does the user agent want, then? */
1039 if (bsrt->hits <= *req->smallSetUpperBound)
1042 setnames = req->smallSetElementSetNames;
1044 else if (bsrt->hits < *req->largeSetLowerBound)
1046 toget = *req->mediumSetPresentNumber;
1047 if (toget > bsrt->hits)
1049 setnames = req->mediumSetElementSetNames;
1054 if (toget && !resp.records)
1059 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1060 prefformat->class != CLASS_RECSYN)
1063 form = prefformat->value;
1064 resp.records = pack_records(assoc, req->resultSetName, 1,
1065 &toget, setnames, &next, &presst, form);
1068 resp.numberOfRecordsReturned = &toget;
1069 resp.nextResultSetPosition = &next;
1070 resp.searchStatus = &sr;
1071 resp.resultSetStatus = 0;
1072 resp.presentStatus = &presst;
1076 if (*resp.resultCount)
1078 resp.numberOfRecordsReturned = &nulint;
1079 resp.nextResultSetPosition = &next;
1080 resp.searchStatus = &sr;
1081 resp.resultSetStatus = 0;
1082 resp.presentStatus = 0;
1089 * Maybe we got a little over-friendly when we designed bend_fetch to
1090 * get only one record at a time. Some backends can optimise multiple-record
1091 * fetches, and at any rate, there is some overhead involved in
1092 * all that selecting and hopping around. Problem is, of course, that the
1093 * frontend can't know ahead of time how many records it'll need to
1094 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1095 * is downright lousy as a bulk data transfer protocol.
1097 * To start with, we'll do the fetching of records from the backend
1098 * in one operation: To save some trips in and out of the event-handler,
1099 * and to simplify the interface to pack_records. At any rate, asynch
1100 * operation is more fun in operations that have an unpredictable execution
1101 * speed - which is normally more true for search than for present.
1103 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1106 Z_PresentRequest *req = reqb->request->u.presentRequest;
1108 static Z_PresentResponse resp;
1109 static int presst, next, num;
1114 logf(LOG_LOG, "Got PresentRequest.");
1115 apdu.which = Z_APDU_presentResponse;
1116 apdu.u.presentResponse = &resp;
1117 resp.referenceId = req->referenceId;
1122 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1123 prefformat->class != CLASS_RECSYN)
1126 form = prefformat->value;
1127 num = *req->numberOfRecordsRequested;
1128 resp.records = pack_records(assoc, req->resultSetId,
1129 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1132 resp.numberOfRecordsReturned = #
1133 resp.presentStatus = &presst;
1134 resp.nextResultSetPosition = &next;
1140 * Scan was implemented rather in a hurry, and with support for only the basic
1141 * elements of the service in the backend API. Suggestions are welcome.
1143 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1145 Z_ScanRequest *req = reqb->request->u.scanRequest;
1147 static Z_ScanResponse res;
1148 static int scanStatus = Z_Scan_failure;
1149 static int numberOfEntriesReturned = 0;
1151 static Z_ListEntries ents;
1152 #define SCAN_MAX_ENTRIES 200
1153 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1154 bend_scanrequest srq;
1155 bend_scanresult *srs;
1157 logf(LOG_LOG, "Got scanrequest");
1158 apdu.which = Z_APDU_scanResponse;
1159 apdu.u.scanResponse = &res;
1160 res.referenceId = req->referenceId;
1162 res.scanStatus = &scanStatus;
1163 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1164 res.positionOfTerm = 0;
1165 res.entries = &ents;
1166 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1167 res.attributeSet = 0;
1172 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1173 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1174 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1175 else if (req->stepSize && *req->stepSize > 0)
1176 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1179 if (req->termListAndStartPoint->term->which == Z_Term_general)
1180 logf(LOG_DEBUG, " term: '%.*s'",
1181 req->termListAndStartPoint->term->u.general->len,
1182 req->termListAndStartPoint->term->u.general->buf);
1183 srq.num_bases = req->num_databaseNames;
1184 srq.basenames = req->databaseNames;
1185 srq.num_entries = *req->numberOfTermsRequested;
1186 srq.term = req->termListAndStartPoint;
1187 srq.term_position = req->preferredPositionInResponse ?
1188 *req->preferredPositionInResponse : 1;
1189 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1190 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1191 else if (srs->errcode)
1192 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1193 srs->errcode, srs->errstring);
1197 static Z_Entries list;
1199 if (srs->status == BEND_SCAN_PARTIAL)
1200 scanStatus = Z_Scan_partial_5;
1202 scanStatus = Z_Scan_success;
1203 ents.which = Z_ListEntries_entries;
1204 ents.u.entries = &list;
1206 for (i = 0; i < srs->num_entries; i++)
1212 if (i >= SCAN_MAX_ENTRIES)
1214 scanStatus = Z_Scan_partial_4;
1217 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1218 e->which = Z_Entry_termInfo;
1219 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1220 t->suggestedAttributes = 0;
1221 t->alternativeTerm = 0;
1222 t->byAttributes = 0;
1223 t->globalOccurrences = &srs->entries[i].occurrences;
1224 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1225 t->term->which = Z_Term_general;
1226 t->term->u.general = o = odr_malloc(assoc->encode,
1228 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1229 strlen(srs->entries[i].term));
1230 memcpy(o->buf, srs->entries[i].term, o->len);
1231 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1232 srs->entries[i].term, srs->entries[i].occurrences);
1234 list.num_entries = i;
1235 res.numberOfEntriesReturned = &list.num_entries;
1236 res.positionOfTerm = &srs->term_position;