2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.41 1995-08-02 10:23:06 quinn
10 * Revision 1.40 1995/07/31 14:34:26 quinn
11 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
13 * Revision 1.39 1995/06/27 13:21:00 quinn
16 * Revision 1.38 1995/06/19 12:39:11 quinn
17 * Fixed bug in timeout code. Added BER dumper.
19 * Revision 1.37 1995/06/16 13:16:14 quinn
20 * Fixed Defaultdiagformat.
22 * Revision 1.36 1995/06/16 10:31:36 quinn
23 * Added session timeout.
25 * Revision 1.35 1995/06/15 07:45:14 quinn
28 * Revision 1.34 1995/06/14 15:26:46 quinn
29 * *** empty log message ***
31 * Revision 1.33 1995/06/06 14:57:05 quinn
34 * Revision 1.32 1995/06/06 08:41:44 quinn
37 * Revision 1.31 1995/06/06 08:15:37 quinn
40 * Revision 1.30 1995/06/05 10:53:32 quinn
41 * Added a better SCAN.
43 * Revision 1.29 1995/06/01 11:25:03 quinn
46 * Revision 1.28 1995/06/01 11:21:01 quinn
47 * Attempting to fix a bug in pack-records. replaced break with continue
48 * for large records, according to standard.
50 * Revision 1.27 1995/05/29 08:12:06 quinn
53 * Revision 1.26 1995/05/18 13:02:12 quinn
56 * Revision 1.25 1995/05/17 08:42:26 quinn
57 * Transfer auth info to backend. Allow backend to reject init gracefully.
59 * Revision 1.24 1995/05/16 08:51:04 quinn
60 * License, documentation, and memory fixes
62 * Revision 1.23 1995/05/15 13:25:10 quinn
65 * Revision 1.22 1995/05/15 11:56:39 quinn
66 * Asynchronous facilities. Restructuring of seshigh code.
68 * Revision 1.21 1995/05/02 08:53:19 quinn
69 * Trying in vain to fix comm with ISODE
71 * Revision 1.20 1995/04/20 15:13:00 quinn
74 * Revision 1.19 1995/04/18 08:15:34 quinn
75 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
76 * neater. We'll make the same change for decoding one day.
78 * Revision 1.18 1995/04/17 11:28:25 quinn
81 * Revision 1.17 1995/04/10 10:23:36 quinn
82 * Some work to add scan and other things.
84 * Revision 1.16 1995/03/31 09:18:55 quinn
87 * Revision 1.15 1995/03/30 14:03:23 quinn
88 * Added RFC1006 as separate library
90 * Revision 1.14 1995/03/30 12:18:17 quinn
93 * Revision 1.13 1995/03/30 09:09:24 quinn
94 * Added state-handle and some support for asynchronous activities.
96 * Revision 1.12 1995/03/29 15:40:16 quinn
97 * Ongoing work. Statserv is now dynamic by default
99 * Revision 1.11 1995/03/28 09:16:21 quinn
100 * Added record packing to the search request
102 * Revision 1.10 1995/03/27 08:34:24 quinn
103 * Added dynamic server functionality.
104 * Released bindings to session.c (is now redundant)
106 * Revision 1.9 1995/03/22 15:01:26 quinn
107 * Adjusting record packing.
109 * Revision 1.8 1995/03/22 10:13:21 quinn
110 * Working on record packer
112 * Revision 1.7 1995/03/21 15:53:31 quinn
115 * Revision 1.6 1995/03/21 12:30:09 quinn
116 * Beginning to add support for record packing.
118 * Revision 1.5 1995/03/17 10:44:13 quinn
119 * Added catch of null-string in makediagrec
121 * Revision 1.4 1995/03/17 10:18:08 quinn
122 * Added memory management.
124 * Revision 1.3 1995/03/16 17:42:39 quinn
127 * Revision 1.2 1995/03/16 13:29:01 quinn
128 * Partitioned server.
130 * Revision 1.1 1995/03/15 16:02:10 quinn
131 * Modded session.c to seshigh.c
136 * Frontend server logic.
138 * This code receives incoming APDUs, and handles client requests by means
139 * of the backend API.
141 * Some of the code is getting quite involved, compared to simpler servers -
142 * primarily because it is asynchronous both in the communication with
143 * the user and the backend. We think the complexity will pay off in
144 * the form of greater flexibility when more asynchronous facilities
147 * Memory management has become somewhat involved. In the simple case, where
148 * only one PDU is pending at a time, it will simply reuse the same memory,
149 * once it has found its working size. When we enable multiple concurrent
150 * operations, perhaps even with multiple parallel calls to the backend, it
151 * will maintain a pool of buffers for encoding and decoding, trying to
152 * minimize memory allocation/deallocation during normal operation.
154 * TODOs include (and will be done in order of public interest):
156 * Support for EXPLAIN - provide simple meta-database system.
157 * Support for access control.
158 * Support for resource control.
159 * Support for extended services - primarily Item Order.
160 * Rest of Z39.50-1994
170 #include <comstack.h>
176 #include <statserv.h>
180 static int process_request(association *assoc);
181 void backend_response(IOCHAN i, int event);
182 static int process_response(association *assoc, request *req, Z_APDU *res);
183 static Z_APDU *process_initRequest(association *assoc, request *reqb);
184 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
186 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
187 bend_searchresult *bsrt, int *fd);
188 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
190 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
192 static FILE *apduf = 0; /* for use in static mode */
193 static statserv_options_block *control_block = 0;
196 * Create and initialize a new association-handle.
197 * channel : iochannel for the current line.
198 * link : communications channel.
199 * Returns: 0 or a new association handle.
201 association *create_association(IOCHAN channel, COMSTACK link)
206 control_block = statserv_getcontrol();
207 if (!(new = malloc(sizeof(*new))))
209 new->client_chan = channel;
210 new->client_link = link;
211 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
212 !(new->encode = odr_createmem(ODR_ENCODE)))
214 if (*control_block->apdufile)
219 strcpy(filename, control_block->apdufile);
220 if (!(new->print = odr_createmem(ODR_PRINT)))
222 if (*control_block->apdufile != '-')
224 strcpy(filename, control_block->apdufile);
225 if (!control_block->dynamic)
229 if (!(apduf = fopen(filename, "w")))
231 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
234 setvbuf(apduf, 0, _IONBF, 0);
240 sprintf(filename + strlen(filename), ".%d", getpid());
241 if (!(f = fopen(filename, "w")))
243 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
246 setvbuf(f, 0, _IONBF, 0);
248 odr_setprint(new->print, f);
253 new->input_buffer = 0;
254 new->input_buffer_len = 0;
257 request_initq(&new->incoming);
258 request_initq(&new->outgoing);
259 new->proto = cs_getproto(link);
264 * Free association and release resources.
266 void destroy_association(association *h)
268 odr_destroy(h->decode);
269 odr_destroy(h->encode);
271 odr_destroy(h->print);
273 free(h->input_buffer);
275 bend_close(h->backend);
276 while (request_deq(&h->incoming));
277 while (request_deq(&h->outgoing));
282 * This is where PDUs from the client are read and the further
283 * processing is initiated. Flow of control moves down through the
284 * various process_* functions below, until the encoded result comes back up
285 * to the output handler in here.
287 * h : the I/O channel that has an outstanding event.
288 * event : the current outstanding event.
290 void ir_session(IOCHAN h, int event)
293 association *assoc = iochan_getdata(h);
294 COMSTACK conn = assoc->client_link;
297 assert(h && conn && assoc);
298 if (event == EVENT_TIMEOUT)
300 logf(LOG_LOG, "Timeout - closing connection.");
302 destroy_association(assoc);
306 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
308 if (event & EVENT_INPUT)
310 logf(LOG_DEBUG, "ir_session (input)");
311 assert(assoc && conn);
312 /* We aren't speaking to this fellow */
315 logf(LOG_LOG, "Closed connection after reject");
317 destroy_association(assoc);
321 if ((res = cs_get(conn, &assoc->input_buffer,
322 &assoc->input_buffer_len)) <= 0)
324 logf(LOG_LOG, "Connection closed by client");
326 destroy_association(assoc);
330 else if (res == 1) /* incomplete read - wait for more */
332 if (cs_more(conn)) /* more stuff - call us again later, please */
333 iochan_setevent(h, EVENT_INPUT);
335 /* we got a complete PDU. Let's decode it */
336 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
337 req = request_get(); /* get a new request structure */
338 odr_reset(assoc->decode);
339 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
340 odr_dumpBER(log_file(), assoc->input_buffer, res);
341 if (!z_APDU(assoc->decode, &req->request, 0))
343 logf(LOG_LOG, "ODR error on incoming PDU: %s",
344 odr_errlist[odr_geterror(assoc->decode)]);
345 logf(LOG_LOG, "PDU dump:");
346 odr_dumpBER(log_file(), assoc->input_buffer, res);
348 destroy_association(assoc);
352 req->request_mem = odr_extract_mem(assoc->decode);
353 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
355 logf(LOG_WARN, "ODR print error: %s",
356 odr_errlist[odr_geterror(assoc->print)]);
357 odr_reset(assoc->print);
359 request_enq(&assoc->incoming, req);
362 /* can we do something yet? */
363 req = request_head(&assoc->incoming);
364 if (req->state == REQUEST_IDLE)
365 if (process_request(assoc) < 0)
368 destroy_association(assoc);
372 if (event & EVENT_OUTPUT)
374 request *req = request_head(&assoc->outgoing);
376 logf(LOG_DEBUG, "ir_session (output)");
377 req->state = REQUEST_PENDING;
378 switch (res = cs_put(conn, req->response, req->len_response))
381 logf(LOG_LOG, "Connection closed by client");
383 destroy_association(assoc);
386 case 0: /* all sent - release the request structure */
387 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
388 odr_release_mem(req->request_mem);
389 request_deq(&assoc->outgoing);
390 request_release(req);
391 if (!request_head(&assoc->outgoing))
392 iochan_clearflag(h, EVENT_OUTPUT);
394 /* value of 1 -- partial send -- is simply ignored */
397 if (event & EVENT_EXCEPT)
399 logf(LOG_DEBUG, "ir_session (exception)");
401 destroy_association(assoc);
407 * Initiate request processing.
409 static int process_request(association *assoc)
411 request *req = request_head(&assoc->incoming);
415 logf(LOG_DEBUG, "process_request");
416 assert(req && req->state == REQUEST_IDLE);
417 switch (req->request->which)
419 case Z_APDU_initRequest:
420 res = process_initRequest(assoc, req); break;
421 case Z_APDU_searchRequest:
422 res = process_searchRequest(assoc, req, &fd); break;
423 case Z_APDU_presentRequest:
424 res = process_presentRequest(assoc, req, &fd); break;
425 case Z_APDU_scanRequest:
426 res = process_scanRequest(assoc, req, &fd); break;
428 logf(LOG_WARN, "Bad APDU received");
433 logf(LOG_DEBUG, " result immediately available");
434 return process_response(assoc, req, res);
438 logf(LOG_WARN, " bad result");
441 else /* no result yet - one will be provided later */
445 /* Set up an I/O handler for the fd supplied by the backend */
447 logf(LOG_DEBUG, " establishing handler for result");
448 req->state = REQUEST_PENDING;
449 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
451 iochan_setdata(chan, assoc);
457 * Handle message from the backend.
459 void backend_response(IOCHAN i, int event)
461 association *assoc = iochan_getdata(i);
462 request *req = request_head(&assoc->incoming);
466 logf(LOG_DEBUG, "backend_response");
467 assert(assoc && req && req->state != REQUEST_IDLE);
468 /* determine what it is we're waiting for */
469 switch (req->request->which)
471 case Z_APDU_searchRequest:
472 res = response_searchRequest(assoc, req, 0, &fd); break;
474 case Z_APDU_presentRequest:
475 res = response_presentRequest(assoc, req, 0, &fd); break;
476 case Z_APDU_scanRequest:
477 res = response_scanRequest(assoc, req, 0, &fd); break;
480 logf(LOG_WARN, "Serious programmer's lapse or bug");
483 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
485 logf(LOG_LOG, "Fatal error when talking to backend");
486 cs_close(assoc->client_link);
487 destroy_association(assoc);
488 iochan_destroy(assoc->client_chan);
492 else if (!res) /* no result yet - try again later */
494 logf(LOG_DEBUG, " no result yet");
495 iochan_setfd(i, fd); /* in case fd has changed */
500 * Encode response, and transfer the request structure to the outgoing queue.
502 static int process_response(association *assoc, request *req, Z_APDU *res)
504 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
505 if (!z_APDU(assoc->encode, &res, 0))
507 logf(LOG_WARN, "ODR error when encoding response: %s",
508 odr_errlist[odr_geterror(assoc->decode)]);
511 req->response = odr_getbuf(assoc->encode, &req->len_response,
512 &req->size_response);
513 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
514 odr_reset(assoc->encode);
515 if (assoc->print && !z_APDU(assoc->print, &res, 0))
517 logf(LOG_WARN, "ODR print error: %s",
518 odr_errlist[odr_geterror(assoc->print)]);
519 odr_reset(assoc->print);
521 /* change this when we make the backend reentrant */
522 assert(req == request_head(&assoc->incoming));
523 req->state = REQUEST_IDLE;
524 request_deq(&assoc->incoming);
525 request_enq(&assoc->outgoing, req);
526 /* turn the work over to the ir_session handler */
527 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
528 /* Is there more work to be done? give that to the input handler too */
529 if (request_head(&assoc->incoming))
530 iochan_setevent(assoc->client_chan, EVENT_WORK);
535 * Handle init request.
536 * At the moment, we don't check the protocol version or the options
537 * anywhere else in the code - we just try not to do anything that would
538 * break a naive client. We'll toss 'em into the association block when
539 * we need them there.
541 static Z_APDU *process_initRequest(association *assoc, request *reqb)
543 Z_InitRequest *req = reqb->request->u.initRequest;
544 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
545 Z_InitResponse *resp = apdu->u.initResponse;
546 bend_initrequest binitreq;
547 bend_initresult *binitres;
549 logf(LOG_LOG, "Got initRequest");
550 if (req->implementationId)
551 logf(LOG_LOG, "Id: %s", req->implementationId);
552 if (req->implementationName)
553 logf(LOG_LOG, "Name: %s", req->implementationName);
554 if (req->implementationVersion)
555 logf(LOG_LOG, "Version: %s", req->implementationVersion);
557 binitreq.configname = "default-config";
558 binitreq.auth = req->idAuthentication;
559 if (!(binitres = bend_init(&binitreq)))
561 logf(LOG_WARN, "Bad response from backend.");
565 assoc->backend = binitres->handle;
566 resp->referenceId = req->referenceId;
567 /* let's tell the client what we can do */
568 if (ODR_MASK_GET(req->options, Z_Options_search))
569 ODR_MASK_SET(resp->options, Z_Options_search);
570 if (ODR_MASK_GET(req->options, Z_Options_present))
571 ODR_MASK_SET(resp->options, Z_Options_present);
573 if (ODR_MASK_GET(req->options, Z_Options_delSet))
574 ODR_MASK_SET(&options, Z_Options_delSet);
576 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
577 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
578 if (ODR_MASK_GET(req->options, Z_Options_scan))
579 ODR_MASK_SET(resp->options, Z_Options_scan);
580 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
581 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
583 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
584 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
585 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
586 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
587 assoc->maximumRecordSize = *req->maximumRecordSize;
588 if (assoc->maximumRecordSize > control_block->maxrecordsize)
589 assoc->maximumRecordSize = control_block->maxrecordsize;
590 assoc->preferredMessageSize = *req->preferredMessageSize;
591 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
592 assoc->preferredMessageSize = assoc->maximumRecordSize;
593 resp->preferredMessageSize = &assoc->preferredMessageSize;
594 resp->maximumRecordSize = &assoc->maximumRecordSize;
595 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
596 if (binitres->errcode)
598 logf(LOG_LOG, "Connection rejected by backend.");
606 * These functions should be merged.
610 * nonsurrogate diagnostic record.
612 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
614 static Z_Records rec;
618 static Z_DiagRec drec;
619 static Z_DefaultDiagFormat dr;
625 bib1.class = CLASS_DIAGSET;
626 bib1.value = VAL_BIB1;
628 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
631 rec.which = Z_Records_NSD;
633 rec.u.nonSurrogateDiagnostic = &drec;
634 drec.which = Z_DiagRec_defaultFormat;
635 drec.u.defaultFormat = &dr;
637 rec.u.nonSurrogateDiagnostic = &dr;
639 dr.diagnosticSetId = oid_getoidbyent(&bib1);
641 dr.which = Z_DiagForm_v2AddInfo;
642 dr.addinfo = addinfo ? addinfo : "";
647 * surrogate diagnostic.
649 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
650 int error, char *addinfo)
652 static Z_NamePlusRecord rec;
656 static Z_DiagRec drec;
657 static Z_DefaultDiagFormat dr;
663 bib1.class = CLASS_DIAGSET;
664 bib1.value = VAL_BIB1;
666 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
668 rec.databaseName = dbname;
669 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
671 rec.u.surrogateDiagnostic = &drec;
672 drec.which = Z_DiagRec_defaultFormat;
673 drec.u.defaultFormat = &dr;
675 rec.u.surrogateDiagnostic = &dr;
677 dr.diagnosticSetId = oid_getoidbyent(&bib1);
679 dr.which = Z_DiagForm_v2AddInfo;
680 dr.addinfo = addinfo ? addinfo : "";
685 * multiple nonsurrogate diagnostics.
687 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
689 static Z_DiagRecs recs;
693 static Z_DiagRec *recp[1], drec;
694 static Z_DefaultDiagFormat rec;
696 static Z_DiagRec *recp[1], rec;
699 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
701 bib1.class = CLASS_DIAGSET;
702 bib1.value = VAL_BIB1;
705 recs.num_diagRecs = 1;
706 recs.diagRecs = recp;
709 drec.which = Z_DiagRec_defaultFormat;
710 drec.u.defaultFormat = &rec;
714 rec.diagnosticSetId = oid_getoidbyent(&bib1);
715 rec.condition = &err;
716 rec.which = Z_DiagForm_v2AddInfo;
717 rec.addinfo = addinfo ? addinfo : "";
721 #define MAX_RECORDS 256
723 static Z_Records *pack_records(association *a, char *setname, int start,
724 int *num, Z_ElementSetNames *esn,
725 int *next, int *pres, oid_value format)
727 int recno, total_length = 0, toget = *num;
728 static Z_Records records;
729 static Z_NamePlusRecordList reclist;
730 static Z_NamePlusRecord *list[MAX_RECORDS];
733 records.which = Z_Records_DBOSD;
734 records.u.databaseOrSurDiagnostics = &reclist;
735 reclist.num_records = 0;
736 reclist.records = list;
737 *pres = Z_PRES_SUCCESS;
741 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
742 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
743 a->maximumRecordSize);
744 for (recno = start; reclist.num_records < toget; recno++)
746 bend_fetchrequest freq;
747 bend_fetchresult *fres;
748 Z_NamePlusRecord *thisrec;
749 Z_DatabaseRecord *thisext;
751 if (reclist.num_records == MAX_RECORDS - 1)
753 *pres = Z_PRES_PARTIAL_2;
756 freq.setname = setname;
758 freq.format = format;
759 if (!(fres = bend_fetch(a->backend, &freq, 0)))
761 *pres = Z_PRES_FAILURE;
762 return diagrec(a->proto, 2, "Backend interface problem");
764 /* backend should be able to signal whether error is system-wide
765 or only pertaining to current record */
768 *pres = Z_PRES_FAILURE;
769 return diagrec(a->proto, fres->errcode, fres->errstring);
771 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
772 fres->len, total_length);
773 if (fres->len + total_length > a->preferredMessageSize)
775 /* record is small enough, really */
776 if (fres->len <= a->preferredMessageSize)
778 logf(LOG_DEBUG, " Dropped last normal-sized record");
779 *pres = Z_PRES_PARTIAL_2;
782 /* record can only be fetched by itself */
783 if (fres->len < a->maximumRecordSize)
785 logf(LOG_DEBUG, " Record > prefmsgsz");
788 logf(LOG_DEBUG, " Dropped it");
789 reclist.records[reclist.num_records] =
790 surrogatediagrec(a->proto, fres->basename, 16, 0);
791 reclist.num_records++;
792 total_length += 10; /* totally arbitrary */
796 else /* too big entirely */
798 logf(LOG_DEBUG, "Record > maxrcdsz");
799 reclist.records[reclist.num_records] =
800 surrogatediagrec(a->proto, fres->basename, 17, 0);
801 reclist.num_records++;
802 total_length += 10; /* totally arbitrary */
806 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
808 if (!(thisrec->databaseName = odr_malloc(a->encode,
809 strlen(fres->basename) + 1)))
811 strcpy(thisrec->databaseName, fres->basename);
812 thisrec->which = Z_NamePlusRecord_databaseRecord;
813 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
814 sizeof(Z_DatabaseRecord))))
816 recform.proto = a->proto;
817 recform.class = CLASS_RECSYN;
818 recform.value = fres->format;
819 thisext->direct_reference = odr_oiddup(a->encode,
820 oid_getoidbyent(&recform));
821 thisext->indirect_reference = 0;
822 thisext->descriptor = 0;
823 if (fres->format == VAL_SUTRS) /* SUTRS ios a single-ASN.1-type */
826 Odr_oct *sp = &sutrs_asn;
827 Odr_any *single = odr_malloc(a->encode, sizeof(*single));
828 char *buf, *remember;
831 sutrs_asn.buf = (unsigned char*) fres->record;
832 sutrs_asn.len = sutrs_asn.size = fres->len;
834 * we borrow the encoding stream for preparing the buffer. This
835 * is not the most elegant solution - a better way might have been
836 * to reserve a different stream, or to devise a better system
837 * for handling externals in general.
839 remember = odr_getbuf(a->encode, &len, &s_remember);
840 buf = odr_malloc(a->encode, fres->len + 10); /* buf for encoding */
841 odr_setbuf(a->encode, buf, fres->len + 10, 0); /* can_grow==0 */
842 if (!z_SUTRS(a->encode, &sp, 0))
844 logf(LOG_LOG, "ODR error encoding SUTRS: %s",
845 odr_errlist[odr_geterror(a->encode)]);
848 thisext->which = ODR_EXTERNAL_single;
849 thisext->u.single_ASN1_type = single;
850 single->buf = (unsigned char*)odr_getbuf(a->encode, &single->len,
852 /* Now restore the encoding stream */
853 odr_setbuf(a->encode, remember, s_remember, 1);
854 logf(LOG_DEBUG, " Format is SUTRS. len %d, encoded len %d",
855 fres->len, single->len);
857 else /* octet-aligned record. Easy as pie */
859 thisext->which = ODR_EXTERNAL_octet;
860 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
863 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
866 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
867 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
870 reclist.records[reclist.num_records] = thisrec;
871 reclist.num_records++;
872 total_length += fres->len;
873 *next = fres->last_in_set ? 0 : recno + 1;
875 *num = reclist.num_records;
879 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
882 Z_SearchRequest *req = reqb->request->u.searchRequest;
883 bend_searchrequest bsrq;
884 bend_searchresult *bsrt;
886 logf(LOG_LOG, "Got SearchRequest.");
888 bsrq.setname = req->resultSetName;
889 bsrq.replace_set = *req->replaceIndicator;
890 bsrq.num_bases = req->num_databaseNames;
891 bsrq.basenames = req->databaseNames;
892 bsrq.query = req->query;
894 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
896 return response_searchRequest(assoc, reqb, bsrt, fd);
899 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
902 * Prepare a searchresponse based on the backend results. We probably want
903 * to look at making the fetching of records nonblocking as well, but
904 * so far, we'll keep things simple.
905 * If bsrt is null, that means we're called in response to a communications
906 * event, and we'll have to get the response for ourselves.
908 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
909 bend_searchresult *bsrt, int *fd)
911 Z_SearchRequest *req = reqb->request->u.searchRequest;
913 static Z_SearchResponse resp;
914 static int nulint = 0;
915 static bool_t sr = 1;
917 static int none = Z_RES_NONE;
919 apdu.which = Z_APDU_searchResponse;
920 apdu.u.searchResponse = &resp;
921 resp.referenceId = req->referenceId;
923 resp.additionalSearchInfo = 0;
927 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
929 logf(LOG_FATAL, "Bad result from backend");
932 else if (bsrt->errcode)
934 resp.records = diagrec(assoc->proto, bsrt->errcode,
936 resp.resultCount = &nulint;
937 resp.numberOfRecordsReturned = &nulint;
938 resp.nextResultSetPosition = &nulint;
939 resp.searchStatus = &nulint;
940 resp.resultSetStatus = &none;
941 resp.presentStatus = 0;
946 Z_ElementSetNames *setnames;
947 static int presst = 0;
950 resp.resultCount = &bsrt->hits;
952 /* how many records does the user agent want, then? */
953 if (bsrt->hits <= *req->smallSetUpperBound)
956 setnames = req->smallSetElementSetNames;
958 else if (bsrt->hits < *req->largeSetLowerBound)
960 toget = *req->mediumSetPresentNumber;
961 if (toget > bsrt->hits)
963 setnames = req->mediumSetElementSetNames;
968 if (toget && !resp.records)
973 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
974 prefformat->class != CLASS_RECSYN)
977 form = prefformat->value;
978 resp.records = pack_records(assoc, req->resultSetName, 1,
979 &toget, setnames, &next, &presst, form);
982 resp.numberOfRecordsReturned = &toget;
983 resp.nextResultSetPosition = &next;
984 resp.searchStatus = &sr;
985 resp.resultSetStatus = 0;
986 resp.presentStatus = &presst;
990 resp.numberOfRecordsReturned = &nulint;
991 resp.nextResultSetPosition = &next;
992 resp.searchStatus = &sr;
993 resp.resultSetStatus = 0;
994 resp.presentStatus = 0;
1001 * Maybe we got a little over-friendly when we designed bend_fetch to
1002 * get only one record at a time. Some backends can optimise multiple-record
1003 * fetches, and at any rate, there is some overhead involved in
1004 * all that selecting and hopping around. Problem is, of course, that the
1005 * frontend can't know ahead of time how many records it'll need to
1006 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1007 * is downright lousy as a bulk data transfer protocol.
1009 * To start with, we'll do the fetching of records from the backend
1010 * in one operation: To save some trips in and out of the event-handler,
1011 * and to simplify the interface to pack_records. At any rate, asynch
1012 * operation is more fun in operations that have an unpredictable execution
1013 * speed - which is normally more true for search than for present.
1015 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1018 Z_PresentRequest *req = reqb->request->u.presentRequest;
1020 static Z_PresentResponse resp;
1021 static int presst, next, num;
1026 logf(LOG_LOG, "Got PresentRequest.");
1027 apdu.which = Z_APDU_presentResponse;
1028 apdu.u.presentResponse = &resp;
1029 resp.referenceId = req->referenceId;
1034 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1035 prefformat->class != CLASS_RECSYN)
1038 form = prefformat->value;
1039 num = *req->numberOfRecordsRequested;
1040 resp.records = pack_records(assoc, req->resultSetId,
1041 *req->resultSetStartPoint, &num, 0, &next, &presst, form);
1044 resp.numberOfRecordsReturned = #
1045 resp.presentStatus = &presst;
1046 resp.nextResultSetPosition = &next;
1052 * Scan was implemented rather in a hurry, and with support for only the basic
1053 * elements of the service in the backend API. Suggestions are welcome.
1055 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1057 Z_ScanRequest *req = reqb->request->u.scanRequest;
1059 static Z_ScanResponse res;
1060 static int scanStatus = Z_Scan_failure;
1061 static int numberOfEntriesReturned = 0;
1063 static Z_ListEntries ents;
1064 #define SCAN_MAX_ENTRIES 200
1065 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1066 bend_scanrequest srq;
1067 bend_scanresult *srs;
1069 logf(LOG_LOG, "Got scanrequest");
1070 apdu.which = Z_APDU_scanResponse;
1071 apdu.u.scanResponse = &res;
1072 res.referenceId = req->referenceId;
1074 res.scanStatus = &scanStatus;
1075 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1076 res.positionOfTerm = 0;
1077 res.entries = &ents;
1078 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1079 res.attributeSet = 0;
1084 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1085 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1086 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1087 else if (req->stepSize && *req->stepSize > 0)
1088 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1091 if (req->termListAndStartPoint->term->which == Z_Term_general)
1092 logf(LOG_DEBUG, " term: '%.*s'",
1093 req->termListAndStartPoint->term->u.general->len,
1094 req->termListAndStartPoint->term->u.general->buf);
1095 srq.num_bases = req->num_databaseNames;
1096 srq.basenames = req->databaseNames;
1097 srq.num_entries = *req->numberOfTermsRequested;
1098 srq.term = req->termListAndStartPoint;
1099 srq.term_position = req->preferredPositionInResponse ?
1100 *req->preferredPositionInResponse : 1;
1101 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1102 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1103 else if (srs->errcode)
1104 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1105 srs->errcode, srs->errstring);
1109 static Z_Entries list;
1111 if (srs->status == BEND_SCAN_PARTIAL)
1112 scanStatus = Z_Scan_partial_5;
1114 scanStatus = Z_Scan_success;
1115 ents.which = Z_ListEntries_entries;
1116 ents.u.entries = &list;
1118 for (i = 0; i < srs->num_entries; i++)
1124 if (i >= SCAN_MAX_ENTRIES)
1126 scanStatus = Z_Scan_partial_4;
1129 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1130 e->which = Z_Entry_termInfo;
1131 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1132 t->suggestedAttributes = 0;
1133 t->alternativeTerm = 0;
1134 t->byAttributes = 0;
1135 t->globalOccurrences = &srs->entries[i].occurrences;
1136 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1137 t->term->which = Z_Term_general;
1138 t->term->u.general = o = odr_malloc(assoc->encode,
1140 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1141 strlen(srs->entries[i].term));
1142 memcpy(o->buf, srs->entries[i].term, o->len);
1143 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1144 srs->entries[i].term, srs->entries[i].occurrences);
1146 list.num_entries = i;
1147 res.numberOfEntriesReturned = &list.num_entries;
1148 res.positionOfTerm = &srs->term_position;