2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.44 1995-08-17 12:45:25 quinn
8 * Fixed minor problems with GRS-1. Added support in c&s.
10 * Revision 1.43 1995/08/15 12:00:31 quinn
13 * Revision 1.42 1995/08/15 11:16:50 quinn
14 * CV:e ----------------------------------------------------------------------
15 * CV:e ----------------------------------------------------------------------
17 * Revision 1.41 1995/08/02 10:23:06 quinn
20 * Revision 1.40 1995/07/31 14:34:26 quinn
21 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
23 * Revision 1.39 1995/06/27 13:21:00 quinn
26 * Revision 1.38 1995/06/19 12:39:11 quinn
27 * Fixed bug in timeout code. Added BER dumper.
29 * Revision 1.37 1995/06/16 13:16:14 quinn
30 * Fixed Defaultdiagformat.
32 * Revision 1.36 1995/06/16 10:31:36 quinn
33 * Added session timeout.
35 * Revision 1.35 1995/06/15 07:45:14 quinn
38 * Revision 1.34 1995/06/14 15:26:46 quinn
39 * *** empty log message ***
41 * Revision 1.33 1995/06/06 14:57:05 quinn
44 * Revision 1.32 1995/06/06 08:41:44 quinn
47 * Revision 1.31 1995/06/06 08:15:37 quinn
50 * Revision 1.30 1995/06/05 10:53:32 quinn
51 * Added a better SCAN.
53 * Revision 1.29 1995/06/01 11:25:03 quinn
56 * Revision 1.28 1995/06/01 11:21:01 quinn
57 * Attempting to fix a bug in pack-records. replaced break with continue
58 * for large records, according to standard.
60 * Revision 1.27 1995/05/29 08:12:06 quinn
63 * Revision 1.26 1995/05/18 13:02:12 quinn
66 * Revision 1.25 1995/05/17 08:42:26 quinn
67 * Transfer auth info to backend. Allow backend to reject init gracefully.
69 * Revision 1.24 1995/05/16 08:51:04 quinn
70 * License, documentation, and memory fixes
72 * Revision 1.23 1995/05/15 13:25:10 quinn
75 * Revision 1.22 1995/05/15 11:56:39 quinn
76 * Asynchronous facilities. Restructuring of seshigh code.
78 * Revision 1.21 1995/05/02 08:53:19 quinn
79 * Trying in vain to fix comm with ISODE
81 * Revision 1.20 1995/04/20 15:13:00 quinn
84 * Revision 1.19 1995/04/18 08:15:34 quinn
85 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
86 * neater. We'll make the same change for decoding one day.
88 * Revision 1.18 1995/04/17 11:28:25 quinn
91 * Revision 1.17 1995/04/10 10:23:36 quinn
92 * Some work to add scan and other things.
94 * Revision 1.16 1995/03/31 09:18:55 quinn
97 * Revision 1.15 1995/03/30 14:03:23 quinn
98 * Added RFC1006 as separate library
100 * Revision 1.14 1995/03/30 12:18:17 quinn
103 * Revision 1.13 1995/03/30 09:09:24 quinn
104 * Added state-handle and some support for asynchronous activities.
106 * Revision 1.12 1995/03/29 15:40:16 quinn
107 * Ongoing work. Statserv is now dynamic by default
109 * Revision 1.11 1995/03/28 09:16:21 quinn
110 * Added record packing to the search request
112 * Revision 1.10 1995/03/27 08:34:24 quinn
113 * Added dynamic server functionality.
114 * Released bindings to session.c (is now redundant)
116 * Revision 1.9 1995/03/22 15:01:26 quinn
117 * Adjusting record packing.
119 * Revision 1.8 1995/03/22 10:13:21 quinn
120 * Working on record packer
122 * Revision 1.7 1995/03/21 15:53:31 quinn
125 * Revision 1.6 1995/03/21 12:30:09 quinn
126 * Beginning to add support for record packing.
128 * Revision 1.5 1995/03/17 10:44:13 quinn
129 * Added catch of null-string in makediagrec
131 * Revision 1.4 1995/03/17 10:18:08 quinn
132 * Added memory management.
134 * Revision 1.3 1995/03/16 17:42:39 quinn
137 * Revision 1.2 1995/03/16 13:29:01 quinn
138 * Partitioned server.
140 * Revision 1.1 1995/03/15 16:02:10 quinn
141 * Modded session.c to seshigh.c
146 * Frontend server logic.
148 * This code receives incoming APDUs, and handles client requests by means
149 * of the backend API.
151 * Some of the code is getting quite involved, compared to simpler servers -
152 * primarily because it is asynchronous both in the communication with
153 * the user and the backend. We think the complexity will pay off in
154 * the form of greater flexibility when more asynchronous facilities
157 * Memory management has become somewhat involved. In the simple case, where
158 * only one PDU is pending at a time, it will simply reuse the same memory,
159 * once it has found its working size. When we enable multiple concurrent
160 * operations, perhaps even with multiple parallel calls to the backend, it
161 * will maintain a pool of buffers for encoding and decoding, trying to
162 * minimize memory allocation/deallocation during normal operation.
164 * TODOs include (and will be done in order of public interest):
166 * Support for EXPLAIN - provide simple meta-database system.
167 * Support for access control.
168 * Support for resource control.
169 * Support for extended services - primarily Item Order.
170 * Rest of Z39.50-1994
180 #include <comstack.h>
186 #include <statserv.h>
190 static int process_request(association *assoc);
191 void backend_response(IOCHAN i, int event);
192 static int process_response(association *assoc, request *req, Z_APDU *res);
193 static Z_APDU *process_initRequest(association *assoc, request *reqb);
194 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
196 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
197 bend_searchresult *bsrt, int *fd);
198 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
200 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
202 static FILE *apduf = 0; /* for use in static mode */
203 static statserv_options_block *control_block = 0;
206 * Create and initialize a new association-handle.
207 * channel : iochannel for the current line.
208 * link : communications channel.
209 * Returns: 0 or a new association handle.
211 association *create_association(IOCHAN channel, COMSTACK link)
216 control_block = statserv_getcontrol();
217 if (!(new = malloc(sizeof(*new))))
219 new->client_chan = channel;
220 new->client_link = link;
221 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
222 !(new->encode = odr_createmem(ODR_ENCODE)))
224 if (*control_block->apdufile)
229 strcpy(filename, control_block->apdufile);
230 if (!(new->print = odr_createmem(ODR_PRINT)))
232 if (*control_block->apdufile != '-')
234 strcpy(filename, control_block->apdufile);
235 if (!control_block->dynamic)
239 if (!(apduf = fopen(filename, "w")))
241 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
244 setvbuf(apduf, 0, _IONBF, 0);
250 sprintf(filename + strlen(filename), ".%d", getpid());
251 if (!(f = fopen(filename, "w")))
253 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
256 setvbuf(f, 0, _IONBF, 0);
258 odr_setprint(new->print, f);
263 new->input_buffer = 0;
264 new->input_buffer_len = 0;
267 request_initq(&new->incoming);
268 request_initq(&new->outgoing);
269 new->proto = cs_getproto(link);
274 * Free association and release resources.
276 void destroy_association(association *h)
278 odr_destroy(h->decode);
279 odr_destroy(h->encode);
281 odr_destroy(h->print);
283 free(h->input_buffer);
285 bend_close(h->backend);
286 while (request_deq(&h->incoming));
287 while (request_deq(&h->outgoing));
292 * This is where PDUs from the client are read and the further
293 * processing is initiated. Flow of control moves down through the
294 * various process_* functions below, until the encoded result comes back up
295 * to the output handler in here.
297 * h : the I/O channel that has an outstanding event.
298 * event : the current outstanding event.
300 void ir_session(IOCHAN h, int event)
303 association *assoc = iochan_getdata(h);
304 COMSTACK conn = assoc->client_link;
307 assert(h && conn && assoc);
308 if (event == EVENT_TIMEOUT)
310 logf(LOG_LOG, "Timeout - closing connection.");
312 destroy_association(assoc);
316 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
318 if (event & EVENT_INPUT)
320 logf(LOG_DEBUG, "ir_session (input)");
321 assert(assoc && conn);
322 /* We aren't speaking to this fellow */
325 logf(LOG_LOG, "Closed connection after reject");
327 destroy_association(assoc);
331 if ((res = cs_get(conn, &assoc->input_buffer,
332 &assoc->input_buffer_len)) <= 0)
334 logf(LOG_LOG, "Connection closed by client");
336 destroy_association(assoc);
340 else if (res == 1) /* incomplete read - wait for more */
342 if (cs_more(conn)) /* more stuff - call us again later, please */
343 iochan_setevent(h, EVENT_INPUT);
345 /* we got a complete PDU. Let's decode it */
346 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
347 req = request_get(); /* get a new request structure */
348 odr_reset(assoc->decode);
349 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
350 if (!z_APDU(assoc->decode, &req->request, 0))
352 logf(LOG_LOG, "ODR error on incoming PDU: %s",
353 odr_errlist[odr_geterror(assoc->decode)]);
354 logf(LOG_LOG, "PDU dump:");
355 odr_dumpBER(log_file(), assoc->input_buffer, res);
357 destroy_association(assoc);
361 req->request_mem = odr_extract_mem(assoc->decode);
362 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
364 logf(LOG_WARN, "ODR print error: %s",
365 odr_errlist[odr_geterror(assoc->print)]);
366 odr_reset(assoc->print);
368 request_enq(&assoc->incoming, req);
371 /* can we do something yet? */
372 req = request_head(&assoc->incoming);
373 if (req->state == REQUEST_IDLE)
374 if (process_request(assoc) < 0)
377 destroy_association(assoc);
381 if (event & EVENT_OUTPUT)
383 request *req = request_head(&assoc->outgoing);
385 logf(LOG_DEBUG, "ir_session (output)");
386 req->state = REQUEST_PENDING;
387 switch (res = cs_put(conn, req->response, req->len_response))
390 logf(LOG_LOG, "Connection closed by client");
392 destroy_association(assoc);
395 case 0: /* all sent - release the request structure */
396 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
397 odr_release_mem(req->request_mem);
398 request_deq(&assoc->outgoing);
399 request_release(req);
400 if (!request_head(&assoc->outgoing))
401 iochan_clearflag(h, EVENT_OUTPUT);
403 /* value of 1 -- partial send -- is simply ignored */
406 if (event & EVENT_EXCEPT)
408 logf(LOG_DEBUG, "ir_session (exception)");
410 destroy_association(assoc);
416 * Initiate request processing.
418 static int process_request(association *assoc)
420 request *req = request_head(&assoc->incoming);
424 logf(LOG_DEBUG, "process_request");
425 assert(req && req->state == REQUEST_IDLE);
426 switch (req->request->which)
428 case Z_APDU_initRequest:
429 res = process_initRequest(assoc, req); break;
430 case Z_APDU_searchRequest:
431 res = process_searchRequest(assoc, req, &fd); break;
432 case Z_APDU_presentRequest:
433 res = process_presentRequest(assoc, req, &fd); break;
434 case Z_APDU_scanRequest:
435 res = process_scanRequest(assoc, req, &fd); break;
437 logf(LOG_WARN, "Bad APDU received");
442 logf(LOG_DEBUG, " result immediately available");
443 return process_response(assoc, req, res);
447 logf(LOG_WARN, " bad result");
450 else /* no result yet - one will be provided later */
454 /* Set up an I/O handler for the fd supplied by the backend */
456 logf(LOG_DEBUG, " establishing handler for result");
457 req->state = REQUEST_PENDING;
458 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
460 iochan_setdata(chan, assoc);
466 * Handle message from the backend.
468 void backend_response(IOCHAN i, int event)
470 association *assoc = iochan_getdata(i);
471 request *req = request_head(&assoc->incoming);
475 logf(LOG_DEBUG, "backend_response");
476 assert(assoc && req && req->state != REQUEST_IDLE);
477 /* determine what it is we're waiting for */
478 switch (req->request->which)
480 case Z_APDU_searchRequest:
481 res = response_searchRequest(assoc, req, 0, &fd); break;
483 case Z_APDU_presentRequest:
484 res = response_presentRequest(assoc, req, 0, &fd); break;
485 case Z_APDU_scanRequest:
486 res = response_scanRequest(assoc, req, 0, &fd); break;
489 logf(LOG_WARN, "Serious programmer's lapse or bug");
492 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
494 logf(LOG_LOG, "Fatal error when talking to backend");
495 cs_close(assoc->client_link);
496 destroy_association(assoc);
497 iochan_destroy(assoc->client_chan);
501 else if (!res) /* no result yet - try again later */
503 logf(LOG_DEBUG, " no result yet");
504 iochan_setfd(i, fd); /* in case fd has changed */
509 * Encode response, and transfer the request structure to the outgoing queue.
511 static int process_response(association *assoc, request *req, Z_APDU *res)
513 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
514 if (!z_APDU(assoc->encode, &res, 0))
516 logf(LOG_WARN, "ODR error when encoding response: %s",
517 odr_errlist[odr_geterror(assoc->decode)]);
520 req->response = odr_getbuf(assoc->encode, &req->len_response,
521 &req->size_response);
522 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
523 odr_reset(assoc->encode);
524 if (assoc->print && !z_APDU(assoc->print, &res, 0))
526 logf(LOG_WARN, "ODR print error: %s",
527 odr_errlist[odr_geterror(assoc->print)]);
528 odr_reset(assoc->print);
530 /* change this when we make the backend reentrant */
531 assert(req == request_head(&assoc->incoming));
532 req->state = REQUEST_IDLE;
533 request_deq(&assoc->incoming);
534 request_enq(&assoc->outgoing, req);
535 /* turn the work over to the ir_session handler */
536 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
537 /* Is there more work to be done? give that to the input handler too */
538 if (request_head(&assoc->incoming))
539 iochan_setevent(assoc->client_chan, EVENT_WORK);
544 * Handle init request.
545 * At the moment, we don't check the protocol version or the options
546 * anywhere else in the code - we just try not to do anything that would
547 * break a naive client. We'll toss 'em into the association block when
548 * we need them there.
550 static Z_APDU *process_initRequest(association *assoc, request *reqb)
552 Z_InitRequest *req = reqb->request->u.initRequest;
553 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
554 Z_InitResponse *resp = apdu->u.initResponse;
555 bend_initrequest binitreq;
556 bend_initresult *binitres;
558 logf(LOG_LOG, "Got initRequest");
559 if (req->implementationId)
560 logf(LOG_LOG, "Id: %s", req->implementationId);
561 if (req->implementationName)
562 logf(LOG_LOG, "Name: %s", req->implementationName);
563 if (req->implementationVersion)
564 logf(LOG_LOG, "Version: %s", req->implementationVersion);
566 binitreq.configname = "default-config";
567 binitreq.auth = req->idAuthentication;
568 if (!(binitres = bend_init(&binitreq)))
570 logf(LOG_WARN, "Bad response from backend.");
574 assoc->backend = binitres->handle;
575 resp->referenceId = req->referenceId;
576 /* let's tell the client what we can do */
577 if (ODR_MASK_GET(req->options, Z_Options_search))
578 ODR_MASK_SET(resp->options, Z_Options_search);
579 if (ODR_MASK_GET(req->options, Z_Options_present))
580 ODR_MASK_SET(resp->options, Z_Options_present);
582 if (ODR_MASK_GET(req->options, Z_Options_delSet))
583 ODR_MASK_SET(&options, Z_Options_delSet);
585 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
586 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
587 if (ODR_MASK_GET(req->options, Z_Options_scan))
588 ODR_MASK_SET(resp->options, Z_Options_scan);
589 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
590 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
592 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
593 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
594 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
595 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
596 assoc->maximumRecordSize = *req->maximumRecordSize;
597 if (assoc->maximumRecordSize > control_block->maxrecordsize)
598 assoc->maximumRecordSize = control_block->maxrecordsize;
599 assoc->preferredMessageSize = *req->preferredMessageSize;
600 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
601 assoc->preferredMessageSize = assoc->maximumRecordSize;
602 resp->preferredMessageSize = &assoc->preferredMessageSize;
603 resp->maximumRecordSize = &assoc->maximumRecordSize;
604 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
605 if (binitres->errcode)
607 logf(LOG_LOG, "Connection rejected by backend.");
615 * These functions should be merged.
619 * nonsurrogate diagnostic record.
621 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
623 static Z_Records rec;
627 static Z_DiagRec drec;
628 static Z_DefaultDiagFormat dr;
634 bib1.class = CLASS_DIAGSET;
635 bib1.value = VAL_BIB1;
637 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
640 rec.which = Z_Records_NSD;
642 rec.u.nonSurrogateDiagnostic = &drec;
643 drec.which = Z_DiagRec_defaultFormat;
644 drec.u.defaultFormat = &dr;
646 rec.u.nonSurrogateDiagnostic = &dr;
648 dr.diagnosticSetId = oid_getoidbyent(&bib1);
650 dr.which = Z_DiagForm_v2AddInfo;
651 dr.addinfo = addinfo ? addinfo : "";
656 * surrogate diagnostic.
658 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
659 int error, char *addinfo)
661 static Z_NamePlusRecord rec;
665 static Z_DiagRec drec;
666 static Z_DefaultDiagFormat dr;
672 bib1.class = CLASS_DIAGSET;
673 bib1.value = VAL_BIB1;
675 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
677 rec.databaseName = dbname;
678 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
680 rec.u.surrogateDiagnostic = &drec;
681 drec.which = Z_DiagRec_defaultFormat;
682 drec.u.defaultFormat = &dr;
684 rec.u.surrogateDiagnostic = &dr;
686 dr.diagnosticSetId = oid_getoidbyent(&bib1);
688 dr.which = Z_DiagForm_v2AddInfo;
689 dr.addinfo = addinfo ? addinfo : "";
694 * multiple nonsurrogate diagnostics.
696 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
698 static Z_DiagRecs recs;
702 static Z_DiagRec *recp[1], drec;
703 static Z_DefaultDiagFormat rec;
705 static Z_DiagRec *recp[1], rec;
708 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
710 bib1.class = CLASS_DIAGSET;
711 bib1.value = VAL_BIB1;
714 recs.num_diagRecs = 1;
715 recs.diagRecs = recp;
718 drec.which = Z_DiagRec_defaultFormat;
719 drec.u.defaultFormat = &rec;
723 rec.diagnosticSetId = oid_getoidbyent(&bib1);
724 rec.condition = &err;
725 rec.which = Z_DiagForm_v2AddInfo;
726 rec.addinfo = addinfo ? addinfo : "";
730 #define MAX_RECORDS 256
732 static Z_Records *pack_records(association *a, char *setname, int start,
733 int *num, Z_ElementSetNames *esn,
734 int *next, int *pres, oid_value format)
736 int recno, total_length = 0, toget = *num;
737 static Z_Records records;
738 static Z_NamePlusRecordList reclist;
739 static Z_NamePlusRecord *list[MAX_RECORDS];
742 records.which = Z_Records_DBOSD;
743 records.u.databaseOrSurDiagnostics = &reclist;
744 reclist.num_records = 0;
745 reclist.records = list;
746 *pres = Z_PRES_SUCCESS;
750 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
751 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
752 a->maximumRecordSize);
753 for (recno = start; reclist.num_records < toget; recno++)
755 bend_fetchrequest freq;
756 bend_fetchresult *fres;
757 Z_NamePlusRecord *thisrec;
758 Z_DatabaseRecord *thisext;
760 if (reclist.num_records == MAX_RECORDS - 1)
762 *pres = Z_PRES_PARTIAL_2;
765 freq.setname = setname;
767 freq.format = format;
768 freq.stream = a->encode;
769 if (!(fres = bend_fetch(a->backend, &freq, 0)))
771 *pres = Z_PRES_FAILURE;
772 return diagrec(a->proto, 2, "Backend interface problem");
774 /* backend should be able to signal whether error is system-wide
775 or only pertaining to current record */
778 *pres = Z_PRES_FAILURE;
779 return diagrec(a->proto, fres->errcode, fres->errstring);
781 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
782 fres->len, total_length);
783 if (fres->len + total_length > a->preferredMessageSize)
785 /* record is small enough, really */
786 if (fres->len <= a->preferredMessageSize)
788 logf(LOG_DEBUG, " Dropped last normal-sized record");
789 *pres = Z_PRES_PARTIAL_2;
792 /* record can only be fetched by itself */
793 if (fres->len < a->maximumRecordSize)
795 logf(LOG_DEBUG, " Record > prefmsgsz");
798 logf(LOG_DEBUG, " Dropped it");
799 reclist.records[reclist.num_records] =
800 surrogatediagrec(a->proto, fres->basename, 16, 0);
801 reclist.num_records++;
802 total_length += 10; /* totally arbitrary */
806 else /* too big entirely */
808 logf(LOG_DEBUG, "Record > maxrcdsz");
809 reclist.records[reclist.num_records] =
810 surrogatediagrec(a->proto, fres->basename, 17, 0);
811 reclist.num_records++;
812 total_length += 10; /* totally arbitrary */
816 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
818 if (!(thisrec->databaseName = odr_malloc(a->encode,
819 strlen(fres->basename) + 1)))
821 strcpy(thisrec->databaseName, fres->basename);
822 thisrec->which = Z_NamePlusRecord_databaseRecord;
823 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
824 sizeof(Z_DatabaseRecord))))
826 recform.proto = a->proto;
827 recform.class = CLASS_RECSYN;
828 recform.value = fres->format;
829 thisext->direct_reference = odr_oiddup(a->encode,
830 oid_getoidbyent(&recform));
831 thisext->indirect_reference = 0;
832 thisext->descriptor = 0;
833 if (fres->len < 0) /* Structured data */
835 switch (fres->format)
837 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
838 case VAL_GRS1: thisext->which = Z_External_grs1; break;
839 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
843 logf(LOG_FATAL, "Unknown structured format from backend.");
848 * We cheat on the pointers here. Obviously, the record field
849 * of the backend-fetch structure should have been a union for
850 * correctness, but we're stuck with this for backwards
853 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
855 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
857 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
859 thisext->which = Z_External_sutrs;
860 thisext->u.sutrs = sutrs;
861 sutrs->buf = odr_malloc(a->encode, fres->len);
862 sutrs->len = sutrs->size = fres->len;
863 memcpy(sutrs->buf, fres->record, fres->len);
865 else /* octet-aligned record. */
867 thisext->which = Z_External_octet;
868 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
871 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
874 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
875 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
878 reclist.records[reclist.num_records] = thisrec;
879 reclist.num_records++;
880 total_length += fres->len;
881 *next = fres->last_in_set ? 0 : recno + 1;
883 *num = reclist.num_records;
887 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
890 Z_SearchRequest *req = reqb->request->u.searchRequest;
891 bend_searchrequest bsrq;
892 bend_searchresult *bsrt;
894 logf(LOG_LOG, "Got SearchRequest.");
896 bsrq.setname = req->resultSetName;
897 bsrq.replace_set = *req->replaceIndicator;
898 bsrq.num_bases = req->num_databaseNames;
899 bsrq.basenames = req->databaseNames;
900 bsrq.query = req->query;
902 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
904 return response_searchRequest(assoc, reqb, bsrt, fd);
907 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
910 * Prepare a searchresponse based on the backend results. We probably want
911 * to look at making the fetching of records nonblocking as well, but
912 * so far, we'll keep things simple.
913 * If bsrt is null, that means we're called in response to a communications
914 * event, and we'll have to get the response for ourselves.
916 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
917 bend_searchresult *bsrt, int *fd)
919 Z_SearchRequest *req = reqb->request->u.searchRequest;
921 static Z_SearchResponse resp;
922 static int nulint = 0;
923 static bool_t sr = 1;
925 static int none = Z_RES_NONE;
927 apdu.which = Z_APDU_searchResponse;
928 apdu.u.searchResponse = &resp;
929 resp.referenceId = req->referenceId;
931 resp.additionalSearchInfo = 0;
935 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
937 logf(LOG_FATAL, "Bad result from backend");
940 else if (bsrt->errcode)
942 resp.records = diagrec(assoc->proto, bsrt->errcode,
944 resp.resultCount = &nulint;
945 resp.numberOfRecordsReturned = &nulint;
946 resp.nextResultSetPosition = &nulint;
947 resp.searchStatus = &nulint;
948 resp.resultSetStatus = &none;
949 resp.presentStatus = 0;
954 Z_ElementSetNames *setnames;
955 static int presst = 0;
958 resp.resultCount = &bsrt->hits;
960 /* how many records does the user agent want, then? */
961 if (bsrt->hits <= *req->smallSetUpperBound)
964 setnames = req->smallSetElementSetNames;
966 else if (bsrt->hits < *req->largeSetLowerBound)
968 toget = *req->mediumSetPresentNumber;
969 if (toget > bsrt->hits)
971 setnames = req->mediumSetElementSetNames;
976 if (toget && !resp.records)
981 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
982 prefformat->class != CLASS_RECSYN)
985 form = prefformat->value;
986 resp.records = pack_records(assoc, req->resultSetName, 1,
987 &toget, setnames, &next, &presst, form);
990 resp.numberOfRecordsReturned = &toget;
991 resp.nextResultSetPosition = &next;
992 resp.searchStatus = &sr;
993 resp.resultSetStatus = 0;
994 resp.presentStatus = &presst;
998 if (*resp.resultCount)
1000 resp.numberOfRecordsReturned = &nulint;
1001 resp.nextResultSetPosition = &next;
1002 resp.searchStatus = &sr;
1003 resp.resultSetStatus = 0;
1004 resp.presentStatus = 0;
1011 * Maybe we got a little over-friendly when we designed bend_fetch to
1012 * get only one record at a time. Some backends can optimise multiple-record
1013 * fetches, and at any rate, there is some overhead involved in
1014 * all that selecting and hopping around. Problem is, of course, that the
1015 * frontend can't know ahead of time how many records it'll need to
1016 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1017 * is downright lousy as a bulk data transfer protocol.
1019 * To start with, we'll do the fetching of records from the backend
1020 * in one operation: To save some trips in and out of the event-handler,
1021 * and to simplify the interface to pack_records. At any rate, asynch
1022 * operation is more fun in operations that have an unpredictable execution
1023 * speed - which is normally more true for search than for present.
1025 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1028 Z_PresentRequest *req = reqb->request->u.presentRequest;
1030 static Z_PresentResponse resp;
1031 static int presst, next, num;
1036 logf(LOG_LOG, "Got PresentRequest.");
1037 apdu.which = Z_APDU_presentResponse;
1038 apdu.u.presentResponse = &resp;
1039 resp.referenceId = req->referenceId;
1044 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1045 prefformat->class != CLASS_RECSYN)
1048 form = prefformat->value;
1049 num = *req->numberOfRecordsRequested;
1050 resp.records = pack_records(assoc, req->resultSetId,
1051 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1054 resp.numberOfRecordsReturned = #
1055 resp.presentStatus = &presst;
1056 resp.nextResultSetPosition = &next;
1062 * Scan was implemented rather in a hurry, and with support for only the basic
1063 * elements of the service in the backend API. Suggestions are welcome.
1065 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1067 Z_ScanRequest *req = reqb->request->u.scanRequest;
1069 static Z_ScanResponse res;
1070 static int scanStatus = Z_Scan_failure;
1071 static int numberOfEntriesReturned = 0;
1073 static Z_ListEntries ents;
1074 #define SCAN_MAX_ENTRIES 200
1075 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1076 bend_scanrequest srq;
1077 bend_scanresult *srs;
1079 logf(LOG_LOG, "Got scanrequest");
1080 apdu.which = Z_APDU_scanResponse;
1081 apdu.u.scanResponse = &res;
1082 res.referenceId = req->referenceId;
1084 res.scanStatus = &scanStatus;
1085 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1086 res.positionOfTerm = 0;
1087 res.entries = &ents;
1088 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1089 res.attributeSet = 0;
1094 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1095 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1096 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1097 else if (req->stepSize && *req->stepSize > 0)
1098 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1101 if (req->termListAndStartPoint->term->which == Z_Term_general)
1102 logf(LOG_DEBUG, " term: '%.*s'",
1103 req->termListAndStartPoint->term->u.general->len,
1104 req->termListAndStartPoint->term->u.general->buf);
1105 srq.num_bases = req->num_databaseNames;
1106 srq.basenames = req->databaseNames;
1107 srq.num_entries = *req->numberOfTermsRequested;
1108 srq.term = req->termListAndStartPoint;
1109 srq.term_position = req->preferredPositionInResponse ?
1110 *req->preferredPositionInResponse : 1;
1111 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1112 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1113 else if (srs->errcode)
1114 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1115 srs->errcode, srs->errstring);
1119 static Z_Entries list;
1121 if (srs->status == BEND_SCAN_PARTIAL)
1122 scanStatus = Z_Scan_partial_5;
1124 scanStatus = Z_Scan_success;
1125 ents.which = Z_ListEntries_entries;
1126 ents.u.entries = &list;
1128 for (i = 0; i < srs->num_entries; i++)
1134 if (i >= SCAN_MAX_ENTRIES)
1136 scanStatus = Z_Scan_partial_4;
1139 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1140 e->which = Z_Entry_termInfo;
1141 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1142 t->suggestedAttributes = 0;
1143 t->alternativeTerm = 0;
1144 t->byAttributes = 0;
1145 t->globalOccurrences = &srs->entries[i].occurrences;
1146 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1147 t->term->which = Z_Term_general;
1148 t->term->u.general = o = odr_malloc(assoc->encode,
1150 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1151 strlen(srs->entries[i].term));
1152 memcpy(o->buf, srs->entries[i].term, o->len);
1153 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1154 srs->entries[i].term, srs->entries[i].occurrences);
1156 list.num_entries = i;
1157 res.numberOfEntriesReturned = &list.num_entries;
1158 res.positionOfTerm = &srs->term_position;