2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.43 1995-08-15 12:00:31 quinn
10 * Revision 1.42 1995/08/15 11:16:50 quinn
11 * CV:e ----------------------------------------------------------------------
12 * CV:e ----------------------------------------------------------------------
14 * Revision 1.41 1995/08/02 10:23:06 quinn
17 * Revision 1.40 1995/07/31 14:34:26 quinn
18 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
20 * Revision 1.39 1995/06/27 13:21:00 quinn
23 * Revision 1.38 1995/06/19 12:39:11 quinn
24 * Fixed bug in timeout code. Added BER dumper.
26 * Revision 1.37 1995/06/16 13:16:14 quinn
27 * Fixed Defaultdiagformat.
29 * Revision 1.36 1995/06/16 10:31:36 quinn
30 * Added session timeout.
32 * Revision 1.35 1995/06/15 07:45:14 quinn
35 * Revision 1.34 1995/06/14 15:26:46 quinn
36 * *** empty log message ***
38 * Revision 1.33 1995/06/06 14:57:05 quinn
41 * Revision 1.32 1995/06/06 08:41:44 quinn
44 * Revision 1.31 1995/06/06 08:15:37 quinn
47 * Revision 1.30 1995/06/05 10:53:32 quinn
48 * Added a better SCAN.
50 * Revision 1.29 1995/06/01 11:25:03 quinn
53 * Revision 1.28 1995/06/01 11:21:01 quinn
54 * Attempting to fix a bug in pack-records. replaced break with continue
55 * for large records, according to standard.
57 * Revision 1.27 1995/05/29 08:12:06 quinn
60 * Revision 1.26 1995/05/18 13:02:12 quinn
63 * Revision 1.25 1995/05/17 08:42:26 quinn
64 * Transfer auth info to backend. Allow backend to reject init gracefully.
66 * Revision 1.24 1995/05/16 08:51:04 quinn
67 * License, documentation, and memory fixes
69 * Revision 1.23 1995/05/15 13:25:10 quinn
72 * Revision 1.22 1995/05/15 11:56:39 quinn
73 * Asynchronous facilities. Restructuring of seshigh code.
75 * Revision 1.21 1995/05/02 08:53:19 quinn
76 * Trying in vain to fix comm with ISODE
78 * Revision 1.20 1995/04/20 15:13:00 quinn
81 * Revision 1.19 1995/04/18 08:15:34 quinn
82 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
83 * neater. We'll make the same change for decoding one day.
85 * Revision 1.18 1995/04/17 11:28:25 quinn
88 * Revision 1.17 1995/04/10 10:23:36 quinn
89 * Some work to add scan and other things.
91 * Revision 1.16 1995/03/31 09:18:55 quinn
94 * Revision 1.15 1995/03/30 14:03:23 quinn
95 * Added RFC1006 as separate library
97 * Revision 1.14 1995/03/30 12:18:17 quinn
100 * Revision 1.13 1995/03/30 09:09:24 quinn
101 * Added state-handle and some support for asynchronous activities.
103 * Revision 1.12 1995/03/29 15:40:16 quinn
104 * Ongoing work. Statserv is now dynamic by default
106 * Revision 1.11 1995/03/28 09:16:21 quinn
107 * Added record packing to the search request
109 * Revision 1.10 1995/03/27 08:34:24 quinn
110 * Added dynamic server functionality.
111 * Released bindings to session.c (is now redundant)
113 * Revision 1.9 1995/03/22 15:01:26 quinn
114 * Adjusting record packing.
116 * Revision 1.8 1995/03/22 10:13:21 quinn
117 * Working on record packer
119 * Revision 1.7 1995/03/21 15:53:31 quinn
122 * Revision 1.6 1995/03/21 12:30:09 quinn
123 * Beginning to add support for record packing.
125 * Revision 1.5 1995/03/17 10:44:13 quinn
126 * Added catch of null-string in makediagrec
128 * Revision 1.4 1995/03/17 10:18:08 quinn
129 * Added memory management.
131 * Revision 1.3 1995/03/16 17:42:39 quinn
134 * Revision 1.2 1995/03/16 13:29:01 quinn
135 * Partitioned server.
137 * Revision 1.1 1995/03/15 16:02:10 quinn
138 * Modded session.c to seshigh.c
143 * Frontend server logic.
145 * This code receives incoming APDUs, and handles client requests by means
146 * of the backend API.
148 * Some of the code is getting quite involved, compared to simpler servers -
149 * primarily because it is asynchronous both in the communication with
150 * the user and the backend. We think the complexity will pay off in
151 * the form of greater flexibility when more asynchronous facilities
154 * Memory management has become somewhat involved. In the simple case, where
155 * only one PDU is pending at a time, it will simply reuse the same memory,
156 * once it has found its working size. When we enable multiple concurrent
157 * operations, perhaps even with multiple parallel calls to the backend, it
158 * will maintain a pool of buffers for encoding and decoding, trying to
159 * minimize memory allocation/deallocation during normal operation.
161 * TODOs include (and will be done in order of public interest):
163 * Support for EXPLAIN - provide simple meta-database system.
164 * Support for access control.
165 * Support for resource control.
166 * Support for extended services - primarily Item Order.
167 * Rest of Z39.50-1994
177 #include <comstack.h>
183 #include <statserv.h>
187 static int process_request(association *assoc);
188 void backend_response(IOCHAN i, int event);
189 static int process_response(association *assoc, request *req, Z_APDU *res);
190 static Z_APDU *process_initRequest(association *assoc, request *reqb);
191 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
193 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
194 bend_searchresult *bsrt, int *fd);
195 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
197 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
199 static FILE *apduf = 0; /* for use in static mode */
200 static statserv_options_block *control_block = 0;
203 * Create and initialize a new association-handle.
204 * channel : iochannel for the current line.
205 * link : communications channel.
206 * Returns: 0 or a new association handle.
208 association *create_association(IOCHAN channel, COMSTACK link)
213 control_block = statserv_getcontrol();
214 if (!(new = malloc(sizeof(*new))))
216 new->client_chan = channel;
217 new->client_link = link;
218 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
219 !(new->encode = odr_createmem(ODR_ENCODE)))
221 if (*control_block->apdufile)
226 strcpy(filename, control_block->apdufile);
227 if (!(new->print = odr_createmem(ODR_PRINT)))
229 if (*control_block->apdufile != '-')
231 strcpy(filename, control_block->apdufile);
232 if (!control_block->dynamic)
236 if (!(apduf = fopen(filename, "w")))
238 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
241 setvbuf(apduf, 0, _IONBF, 0);
247 sprintf(filename + strlen(filename), ".%d", getpid());
248 if (!(f = fopen(filename, "w")))
250 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
253 setvbuf(f, 0, _IONBF, 0);
255 odr_setprint(new->print, f);
260 new->input_buffer = 0;
261 new->input_buffer_len = 0;
264 request_initq(&new->incoming);
265 request_initq(&new->outgoing);
266 new->proto = cs_getproto(link);
271 * Free association and release resources.
273 void destroy_association(association *h)
275 odr_destroy(h->decode);
276 odr_destroy(h->encode);
278 odr_destroy(h->print);
280 free(h->input_buffer);
282 bend_close(h->backend);
283 while (request_deq(&h->incoming));
284 while (request_deq(&h->outgoing));
289 * This is where PDUs from the client are read and the further
290 * processing is initiated. Flow of control moves down through the
291 * various process_* functions below, until the encoded result comes back up
292 * to the output handler in here.
294 * h : the I/O channel that has an outstanding event.
295 * event : the current outstanding event.
297 void ir_session(IOCHAN h, int event)
300 association *assoc = iochan_getdata(h);
301 COMSTACK conn = assoc->client_link;
304 assert(h && conn && assoc);
305 if (event == EVENT_TIMEOUT)
307 logf(LOG_LOG, "Timeout - closing connection.");
309 destroy_association(assoc);
313 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
315 if (event & EVENT_INPUT)
317 logf(LOG_DEBUG, "ir_session (input)");
318 assert(assoc && conn);
319 /* We aren't speaking to this fellow */
322 logf(LOG_LOG, "Closed connection after reject");
324 destroy_association(assoc);
328 if ((res = cs_get(conn, &assoc->input_buffer,
329 &assoc->input_buffer_len)) <= 0)
331 logf(LOG_LOG, "Connection closed by client");
333 destroy_association(assoc);
337 else if (res == 1) /* incomplete read - wait for more */
339 if (cs_more(conn)) /* more stuff - call us again later, please */
340 iochan_setevent(h, EVENT_INPUT);
342 /* we got a complete PDU. Let's decode it */
343 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
344 req = request_get(); /* get a new request structure */
345 odr_reset(assoc->decode);
346 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
347 if (!z_APDU(assoc->decode, &req->request, 0))
349 logf(LOG_LOG, "ODR error on incoming PDU: %s",
350 odr_errlist[odr_geterror(assoc->decode)]);
351 logf(LOG_LOG, "PDU dump:");
352 odr_dumpBER(log_file(), assoc->input_buffer, res);
354 destroy_association(assoc);
358 req->request_mem = odr_extract_mem(assoc->decode);
359 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
361 logf(LOG_WARN, "ODR print error: %s",
362 odr_errlist[odr_geterror(assoc->print)]);
363 odr_reset(assoc->print);
365 request_enq(&assoc->incoming, req);
368 /* can we do something yet? */
369 req = request_head(&assoc->incoming);
370 if (req->state == REQUEST_IDLE)
371 if (process_request(assoc) < 0)
374 destroy_association(assoc);
378 if (event & EVENT_OUTPUT)
380 request *req = request_head(&assoc->outgoing);
382 logf(LOG_DEBUG, "ir_session (output)");
383 req->state = REQUEST_PENDING;
384 switch (res = cs_put(conn, req->response, req->len_response))
387 logf(LOG_LOG, "Connection closed by client");
389 destroy_association(assoc);
392 case 0: /* all sent - release the request structure */
393 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
394 odr_release_mem(req->request_mem);
395 request_deq(&assoc->outgoing);
396 request_release(req);
397 if (!request_head(&assoc->outgoing))
398 iochan_clearflag(h, EVENT_OUTPUT);
400 /* value of 1 -- partial send -- is simply ignored */
403 if (event & EVENT_EXCEPT)
405 logf(LOG_DEBUG, "ir_session (exception)");
407 destroy_association(assoc);
413 * Initiate request processing.
415 static int process_request(association *assoc)
417 request *req = request_head(&assoc->incoming);
421 logf(LOG_DEBUG, "process_request");
422 assert(req && req->state == REQUEST_IDLE);
423 switch (req->request->which)
425 case Z_APDU_initRequest:
426 res = process_initRequest(assoc, req); break;
427 case Z_APDU_searchRequest:
428 res = process_searchRequest(assoc, req, &fd); break;
429 case Z_APDU_presentRequest:
430 res = process_presentRequest(assoc, req, &fd); break;
431 case Z_APDU_scanRequest:
432 res = process_scanRequest(assoc, req, &fd); break;
434 logf(LOG_WARN, "Bad APDU received");
439 logf(LOG_DEBUG, " result immediately available");
440 return process_response(assoc, req, res);
444 logf(LOG_WARN, " bad result");
447 else /* no result yet - one will be provided later */
451 /* Set up an I/O handler for the fd supplied by the backend */
453 logf(LOG_DEBUG, " establishing handler for result");
454 req->state = REQUEST_PENDING;
455 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
457 iochan_setdata(chan, assoc);
463 * Handle message from the backend.
465 void backend_response(IOCHAN i, int event)
467 association *assoc = iochan_getdata(i);
468 request *req = request_head(&assoc->incoming);
472 logf(LOG_DEBUG, "backend_response");
473 assert(assoc && req && req->state != REQUEST_IDLE);
474 /* determine what it is we're waiting for */
475 switch (req->request->which)
477 case Z_APDU_searchRequest:
478 res = response_searchRequest(assoc, req, 0, &fd); break;
480 case Z_APDU_presentRequest:
481 res = response_presentRequest(assoc, req, 0, &fd); break;
482 case Z_APDU_scanRequest:
483 res = response_scanRequest(assoc, req, 0, &fd); break;
486 logf(LOG_WARN, "Serious programmer's lapse or bug");
489 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
491 logf(LOG_LOG, "Fatal error when talking to backend");
492 cs_close(assoc->client_link);
493 destroy_association(assoc);
494 iochan_destroy(assoc->client_chan);
498 else if (!res) /* no result yet - try again later */
500 logf(LOG_DEBUG, " no result yet");
501 iochan_setfd(i, fd); /* in case fd has changed */
506 * Encode response, and transfer the request structure to the outgoing queue.
508 static int process_response(association *assoc, request *req, Z_APDU *res)
510 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
511 if (!z_APDU(assoc->encode, &res, 0))
513 logf(LOG_WARN, "ODR error when encoding response: %s",
514 odr_errlist[odr_geterror(assoc->decode)]);
517 req->response = odr_getbuf(assoc->encode, &req->len_response,
518 &req->size_response);
519 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
520 odr_reset(assoc->encode);
521 if (assoc->print && !z_APDU(assoc->print, &res, 0))
523 logf(LOG_WARN, "ODR print error: %s",
524 odr_errlist[odr_geterror(assoc->print)]);
525 odr_reset(assoc->print);
527 /* change this when we make the backend reentrant */
528 assert(req == request_head(&assoc->incoming));
529 req->state = REQUEST_IDLE;
530 request_deq(&assoc->incoming);
531 request_enq(&assoc->outgoing, req);
532 /* turn the work over to the ir_session handler */
533 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
534 /* Is there more work to be done? give that to the input handler too */
535 if (request_head(&assoc->incoming))
536 iochan_setevent(assoc->client_chan, EVENT_WORK);
541 * Handle init request.
542 * At the moment, we don't check the protocol version or the options
543 * anywhere else in the code - we just try not to do anything that would
544 * break a naive client. We'll toss 'em into the association block when
545 * we need them there.
547 static Z_APDU *process_initRequest(association *assoc, request *reqb)
549 Z_InitRequest *req = reqb->request->u.initRequest;
550 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
551 Z_InitResponse *resp = apdu->u.initResponse;
552 bend_initrequest binitreq;
553 bend_initresult *binitres;
555 logf(LOG_LOG, "Got initRequest");
556 if (req->implementationId)
557 logf(LOG_LOG, "Id: %s", req->implementationId);
558 if (req->implementationName)
559 logf(LOG_LOG, "Name: %s", req->implementationName);
560 if (req->implementationVersion)
561 logf(LOG_LOG, "Version: %s", req->implementationVersion);
563 binitreq.configname = "default-config";
564 binitreq.auth = req->idAuthentication;
565 if (!(binitres = bend_init(&binitreq)))
567 logf(LOG_WARN, "Bad response from backend.");
571 assoc->backend = binitres->handle;
572 resp->referenceId = req->referenceId;
573 /* let's tell the client what we can do */
574 if (ODR_MASK_GET(req->options, Z_Options_search))
575 ODR_MASK_SET(resp->options, Z_Options_search);
576 if (ODR_MASK_GET(req->options, Z_Options_present))
577 ODR_MASK_SET(resp->options, Z_Options_present);
579 if (ODR_MASK_GET(req->options, Z_Options_delSet))
580 ODR_MASK_SET(&options, Z_Options_delSet);
582 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
583 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
584 if (ODR_MASK_GET(req->options, Z_Options_scan))
585 ODR_MASK_SET(resp->options, Z_Options_scan);
586 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
587 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
589 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
590 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
591 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
592 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
593 assoc->maximumRecordSize = *req->maximumRecordSize;
594 if (assoc->maximumRecordSize > control_block->maxrecordsize)
595 assoc->maximumRecordSize = control_block->maxrecordsize;
596 assoc->preferredMessageSize = *req->preferredMessageSize;
597 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
598 assoc->preferredMessageSize = assoc->maximumRecordSize;
599 resp->preferredMessageSize = &assoc->preferredMessageSize;
600 resp->maximumRecordSize = &assoc->maximumRecordSize;
601 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
602 if (binitres->errcode)
604 logf(LOG_LOG, "Connection rejected by backend.");
612 * These functions should be merged.
616 * nonsurrogate diagnostic record.
618 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
620 static Z_Records rec;
624 static Z_DiagRec drec;
625 static Z_DefaultDiagFormat dr;
631 bib1.class = CLASS_DIAGSET;
632 bib1.value = VAL_BIB1;
634 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
637 rec.which = Z_Records_NSD;
639 rec.u.nonSurrogateDiagnostic = &drec;
640 drec.which = Z_DiagRec_defaultFormat;
641 drec.u.defaultFormat = &dr;
643 rec.u.nonSurrogateDiagnostic = &dr;
645 dr.diagnosticSetId = oid_getoidbyent(&bib1);
647 dr.which = Z_DiagForm_v2AddInfo;
648 dr.addinfo = addinfo ? addinfo : "";
653 * surrogate diagnostic.
655 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
656 int error, char *addinfo)
658 static Z_NamePlusRecord rec;
662 static Z_DiagRec drec;
663 static Z_DefaultDiagFormat dr;
669 bib1.class = CLASS_DIAGSET;
670 bib1.value = VAL_BIB1;
672 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
674 rec.databaseName = dbname;
675 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
677 rec.u.surrogateDiagnostic = &drec;
678 drec.which = Z_DiagRec_defaultFormat;
679 drec.u.defaultFormat = &dr;
681 rec.u.surrogateDiagnostic = &dr;
683 dr.diagnosticSetId = oid_getoidbyent(&bib1);
685 dr.which = Z_DiagForm_v2AddInfo;
686 dr.addinfo = addinfo ? addinfo : "";
691 * multiple nonsurrogate diagnostics.
693 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
695 static Z_DiagRecs recs;
699 static Z_DiagRec *recp[1], drec;
700 static Z_DefaultDiagFormat rec;
702 static Z_DiagRec *recp[1], rec;
705 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
707 bib1.class = CLASS_DIAGSET;
708 bib1.value = VAL_BIB1;
711 recs.num_diagRecs = 1;
712 recs.diagRecs = recp;
715 drec.which = Z_DiagRec_defaultFormat;
716 drec.u.defaultFormat = &rec;
720 rec.diagnosticSetId = oid_getoidbyent(&bib1);
721 rec.condition = &err;
722 rec.which = Z_DiagForm_v2AddInfo;
723 rec.addinfo = addinfo ? addinfo : "";
727 #define MAX_RECORDS 256
729 static Z_Records *pack_records(association *a, char *setname, int start,
730 int *num, Z_ElementSetNames *esn,
731 int *next, int *pres, oid_value format)
733 int recno, total_length = 0, toget = *num;
734 static Z_Records records;
735 static Z_NamePlusRecordList reclist;
736 static Z_NamePlusRecord *list[MAX_RECORDS];
739 records.which = Z_Records_DBOSD;
740 records.u.databaseOrSurDiagnostics = &reclist;
741 reclist.num_records = 0;
742 reclist.records = list;
743 *pres = Z_PRES_SUCCESS;
747 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
748 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
749 a->maximumRecordSize);
750 for (recno = start; reclist.num_records < toget; recno++)
752 bend_fetchrequest freq;
753 bend_fetchresult *fres;
754 Z_NamePlusRecord *thisrec;
755 Z_DatabaseRecord *thisext;
757 if (reclist.num_records == MAX_RECORDS - 1)
759 *pres = Z_PRES_PARTIAL_2;
762 freq.setname = setname;
764 freq.format = format;
765 if (!(fres = bend_fetch(a->backend, &freq, 0)))
767 *pres = Z_PRES_FAILURE;
768 return diagrec(a->proto, 2, "Backend interface problem");
770 /* backend should be able to signal whether error is system-wide
771 or only pertaining to current record */
774 *pres = Z_PRES_FAILURE;
775 return diagrec(a->proto, fres->errcode, fres->errstring);
777 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
778 fres->len, total_length);
779 if (fres->len + total_length > a->preferredMessageSize)
781 /* record is small enough, really */
782 if (fres->len <= a->preferredMessageSize)
784 logf(LOG_DEBUG, " Dropped last normal-sized record");
785 *pres = Z_PRES_PARTIAL_2;
788 /* record can only be fetched by itself */
789 if (fres->len < a->maximumRecordSize)
791 logf(LOG_DEBUG, " Record > prefmsgsz");
794 logf(LOG_DEBUG, " Dropped it");
795 reclist.records[reclist.num_records] =
796 surrogatediagrec(a->proto, fres->basename, 16, 0);
797 reclist.num_records++;
798 total_length += 10; /* totally arbitrary */
802 else /* too big entirely */
804 logf(LOG_DEBUG, "Record > maxrcdsz");
805 reclist.records[reclist.num_records] =
806 surrogatediagrec(a->proto, fres->basename, 17, 0);
807 reclist.num_records++;
808 total_length += 10; /* totally arbitrary */
812 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
814 if (!(thisrec->databaseName = odr_malloc(a->encode,
815 strlen(fres->basename) + 1)))
817 strcpy(thisrec->databaseName, fres->basename);
818 thisrec->which = Z_NamePlusRecord_databaseRecord;
819 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
820 sizeof(Z_DatabaseRecord))))
822 recform.proto = a->proto;
823 recform.class = CLASS_RECSYN;
824 recform.value = fres->format;
825 thisext->direct_reference = odr_oiddup(a->encode,
826 oid_getoidbyent(&recform));
827 thisext->indirect_reference = 0;
828 thisext->descriptor = 0;
829 if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
831 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
833 thisext->which = Z_External_SUTRS;
834 thisext->u.sutrs = sutrs;
835 sutrs->buf = odr_malloc(a->encode, fres->len);
836 sutrs->len = sutrs->size = fres->len;
837 memcpy(sutrs->buf, fres->record, fres->len);
840 Odr_oct *sp = &sutrs_asn;
841 Odr_any *single = odr_malloc(a->encode, sizeof(*single));
842 char *buf, *remember;
845 sutrs_asn.buf = (unsigned char*) fres->record;
846 sutrs_asn.len = sutrs_asn.size = fres->len;
848 * we borrow the encoding stream for preparing the buffer. This
849 * is not the most elegant solution - a better way might have been
850 * to reserve a different stream, or to devise a better system
851 * for handling externals in general.
853 remember = odr_getbuf(a->encode, &len, &s_remember);
854 buf = odr_malloc(a->encode, fres->len + 10); /* buf for encoding */
855 odr_setbuf(a->encode, buf, fres->len + 10, 0); /* can_grow==0 */
856 if (!z_SUTRS(a->encode, &sp, 0))
858 logf(LOG_LOG, "ODR error encoding SUTRS: %s",
859 odr_errlist[odr_geterror(a->encode)]);
862 thisext->which = ODR_EXTERNAL_single;
863 thisext->u.single_ASN1_type = single;
864 single->buf = (unsigned char*)odr_getbuf(a->encode, &single->len,
866 /* Now restore the encoding stream */
867 odr_setbuf(a->encode, remember, s_remember, 1);
868 logf(LOG_DEBUG, " Format is SUTRS. len %d, encoded len %d",
869 fres->len, single->len);
872 else /* octet-aligned record. Easy as pie */
874 thisext->which = Z_External_octet;
875 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
878 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
881 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
882 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
885 reclist.records[reclist.num_records] = thisrec;
886 reclist.num_records++;
887 total_length += fres->len;
888 *next = fres->last_in_set ? 0 : recno + 1;
890 *num = reclist.num_records;
894 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
897 Z_SearchRequest *req = reqb->request->u.searchRequest;
898 bend_searchrequest bsrq;
899 bend_searchresult *bsrt;
901 logf(LOG_LOG, "Got SearchRequest.");
903 bsrq.setname = req->resultSetName;
904 bsrq.replace_set = *req->replaceIndicator;
905 bsrq.num_bases = req->num_databaseNames;
906 bsrq.basenames = req->databaseNames;
907 bsrq.query = req->query;
909 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
911 return response_searchRequest(assoc, reqb, bsrt, fd);
914 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
917 * Prepare a searchresponse based on the backend results. We probably want
918 * to look at making the fetching of records nonblocking as well, but
919 * so far, we'll keep things simple.
920 * If bsrt is null, that means we're called in response to a communications
921 * event, and we'll have to get the response for ourselves.
923 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
924 bend_searchresult *bsrt, int *fd)
926 Z_SearchRequest *req = reqb->request->u.searchRequest;
928 static Z_SearchResponse resp;
929 static int nulint = 0;
930 static bool_t sr = 1;
932 static int none = Z_RES_NONE;
934 apdu.which = Z_APDU_searchResponse;
935 apdu.u.searchResponse = &resp;
936 resp.referenceId = req->referenceId;
938 resp.additionalSearchInfo = 0;
942 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
944 logf(LOG_FATAL, "Bad result from backend");
947 else if (bsrt->errcode)
949 resp.records = diagrec(assoc->proto, bsrt->errcode,
951 resp.resultCount = &nulint;
952 resp.numberOfRecordsReturned = &nulint;
953 resp.nextResultSetPosition = &nulint;
954 resp.searchStatus = &nulint;
955 resp.resultSetStatus = &none;
956 resp.presentStatus = 0;
961 Z_ElementSetNames *setnames;
962 static int presst = 0;
965 resp.resultCount = &bsrt->hits;
967 /* how many records does the user agent want, then? */
968 if (bsrt->hits <= *req->smallSetUpperBound)
971 setnames = req->smallSetElementSetNames;
973 else if (bsrt->hits < *req->largeSetLowerBound)
975 toget = *req->mediumSetPresentNumber;
976 if (toget > bsrt->hits)
978 setnames = req->mediumSetElementSetNames;
983 if (toget && !resp.records)
988 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
989 prefformat->class != CLASS_RECSYN)
992 form = prefformat->value;
993 resp.records = pack_records(assoc, req->resultSetName, 1,
994 &toget, setnames, &next, &presst, form);
997 resp.numberOfRecordsReturned = &toget;
998 resp.nextResultSetPosition = &next;
999 resp.searchStatus = &sr;
1000 resp.resultSetStatus = 0;
1001 resp.presentStatus = &presst;
1005 if (*resp.resultCount)
1007 resp.numberOfRecordsReturned = &nulint;
1008 resp.nextResultSetPosition = &next;
1009 resp.searchStatus = &sr;
1010 resp.resultSetStatus = 0;
1011 resp.presentStatus = 0;
1018 * Maybe we got a little over-friendly when we designed bend_fetch to
1019 * get only one record at a time. Some backends can optimise multiple-record
1020 * fetches, and at any rate, there is some overhead involved in
1021 * all that selecting and hopping around. Problem is, of course, that the
1022 * frontend can't know ahead of time how many records it'll need to
1023 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1024 * is downright lousy as a bulk data transfer protocol.
1026 * To start with, we'll do the fetching of records from the backend
1027 * in one operation: To save some trips in and out of the event-handler,
1028 * and to simplify the interface to pack_records. At any rate, asynch
1029 * operation is more fun in operations that have an unpredictable execution
1030 * speed - which is normally more true for search than for present.
1032 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1035 Z_PresentRequest *req = reqb->request->u.presentRequest;
1037 static Z_PresentResponse resp;
1038 static int presst, next, num;
1043 logf(LOG_LOG, "Got PresentRequest.");
1044 apdu.which = Z_APDU_presentResponse;
1045 apdu.u.presentResponse = &resp;
1046 resp.referenceId = req->referenceId;
1051 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1052 prefformat->class != CLASS_RECSYN)
1055 form = prefformat->value;
1056 num = *req->numberOfRecordsRequested;
1057 resp.records = pack_records(assoc, req->resultSetId,
1058 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1061 resp.numberOfRecordsReturned = #
1062 resp.presentStatus = &presst;
1063 resp.nextResultSetPosition = &next;
1069 * Scan was implemented rather in a hurry, and with support for only the basic
1070 * elements of the service in the backend API. Suggestions are welcome.
1072 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1074 Z_ScanRequest *req = reqb->request->u.scanRequest;
1076 static Z_ScanResponse res;
1077 static int scanStatus = Z_Scan_failure;
1078 static int numberOfEntriesReturned = 0;
1080 static Z_ListEntries ents;
1081 #define SCAN_MAX_ENTRIES 200
1082 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1083 bend_scanrequest srq;
1084 bend_scanresult *srs;
1086 logf(LOG_LOG, "Got scanrequest");
1087 apdu.which = Z_APDU_scanResponse;
1088 apdu.u.scanResponse = &res;
1089 res.referenceId = req->referenceId;
1091 res.scanStatus = &scanStatus;
1092 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1093 res.positionOfTerm = 0;
1094 res.entries = &ents;
1095 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1096 res.attributeSet = 0;
1101 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1102 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1103 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1104 else if (req->stepSize && *req->stepSize > 0)
1105 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1108 if (req->termListAndStartPoint->term->which == Z_Term_general)
1109 logf(LOG_DEBUG, " term: '%.*s'",
1110 req->termListAndStartPoint->term->u.general->len,
1111 req->termListAndStartPoint->term->u.general->buf);
1112 srq.num_bases = req->num_databaseNames;
1113 srq.basenames = req->databaseNames;
1114 srq.num_entries = *req->numberOfTermsRequested;
1115 srq.term = req->termListAndStartPoint;
1116 srq.term_position = req->preferredPositionInResponse ?
1117 *req->preferredPositionInResponse : 1;
1118 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1119 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1120 else if (srs->errcode)
1121 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1122 srs->errcode, srs->errstring);
1126 static Z_Entries list;
1128 if (srs->status == BEND_SCAN_PARTIAL)
1129 scanStatus = Z_Scan_partial_5;
1131 scanStatus = Z_Scan_success;
1132 ents.which = Z_ListEntries_entries;
1133 ents.u.entries = &list;
1135 for (i = 0; i < srs->num_entries; i++)
1141 if (i >= SCAN_MAX_ENTRIES)
1143 scanStatus = Z_Scan_partial_4;
1146 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1147 e->which = Z_Entry_termInfo;
1148 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1149 t->suggestedAttributes = 0;
1150 t->alternativeTerm = 0;
1151 t->byAttributes = 0;
1152 t->globalOccurrences = &srs->entries[i].occurrences;
1153 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1154 t->term->which = Z_Term_general;
1155 t->term->u.general = o = odr_malloc(assoc->encode,
1157 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1158 strlen(srs->entries[i].term));
1159 memcpy(o->buf, srs->entries[i].term, o->len);
1160 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1161 srs->entries[i].term, srs->entries[i].occurrences);
1163 list.num_entries = i;
1164 res.numberOfEntriesReturned = &list.num_entries;
1165 res.positionOfTerm = &srs->term_position;