2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.37 1995-06-16 13:16:14 quinn
8 * Fixed Defaultdiagformat.
10 * Revision 1.36 1995/06/16 10:31:36 quinn
11 * Added session timeout.
13 * Revision 1.35 1995/06/15 07:45:14 quinn
16 * Revision 1.34 1995/06/14 15:26:46 quinn
17 * *** empty log message ***
19 * Revision 1.33 1995/06/06 14:57:05 quinn
22 * Revision 1.32 1995/06/06 08:41:44 quinn
25 * Revision 1.31 1995/06/06 08:15:37 quinn
28 * Revision 1.30 1995/06/05 10:53:32 quinn
29 * Added a better SCAN.
31 * Revision 1.29 1995/06/01 11:25:03 quinn
34 * Revision 1.28 1995/06/01 11:21:01 quinn
35 * Attempting to fix a bug in pack-records. replaced break with continue
36 * for large records, according to standard.
38 * Revision 1.27 1995/05/29 08:12:06 quinn
41 * Revision 1.26 1995/05/18 13:02:12 quinn
44 * Revision 1.25 1995/05/17 08:42:26 quinn
45 * Transfer auth info to backend. Allow backend to reject init gracefully.
47 * Revision 1.24 1995/05/16 08:51:04 quinn
48 * License, documentation, and memory fixes
50 * Revision 1.23 1995/05/15 13:25:10 quinn
53 * Revision 1.22 1995/05/15 11:56:39 quinn
54 * Asynchronous facilities. Restructuring of seshigh code.
56 * Revision 1.21 1995/05/02 08:53:19 quinn
57 * Trying in vain to fix comm with ISODE
59 * Revision 1.20 1995/04/20 15:13:00 quinn
62 * Revision 1.19 1995/04/18 08:15:34 quinn
63 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
64 * neater. We'll make the same change for decoding one day.
66 * Revision 1.18 1995/04/17 11:28:25 quinn
69 * Revision 1.17 1995/04/10 10:23:36 quinn
70 * Some work to add scan and other things.
72 * Revision 1.16 1995/03/31 09:18:55 quinn
75 * Revision 1.15 1995/03/30 14:03:23 quinn
76 * Added RFC1006 as separate library
78 * Revision 1.14 1995/03/30 12:18:17 quinn
81 * Revision 1.13 1995/03/30 09:09:24 quinn
82 * Added state-handle and some support for asynchronous activities.
84 * Revision 1.12 1995/03/29 15:40:16 quinn
85 * Ongoing work. Statserv is now dynamic by default
87 * Revision 1.11 1995/03/28 09:16:21 quinn
88 * Added record packing to the search request
90 * Revision 1.10 1995/03/27 08:34:24 quinn
91 * Added dynamic server functionality.
92 * Released bindings to session.c (is now redundant)
94 * Revision 1.9 1995/03/22 15:01:26 quinn
95 * Adjusting record packing.
97 * Revision 1.8 1995/03/22 10:13:21 quinn
98 * Working on record packer
100 * Revision 1.7 1995/03/21 15:53:31 quinn
103 * Revision 1.6 1995/03/21 12:30:09 quinn
104 * Beginning to add support for record packing.
106 * Revision 1.5 1995/03/17 10:44:13 quinn
107 * Added catch of null-string in makediagrec
109 * Revision 1.4 1995/03/17 10:18:08 quinn
110 * Added memory management.
112 * Revision 1.3 1995/03/16 17:42:39 quinn
115 * Revision 1.2 1995/03/16 13:29:01 quinn
116 * Partitioned server.
118 * Revision 1.1 1995/03/15 16:02:10 quinn
119 * Modded session.c to seshigh.c
124 * Frontend server logic.
126 * This code receives incoming APDUs, and handles client requests by means
127 * of the backend API.
129 * Some of the code is getting quite involved, compared to simpler servers -
130 * primarily because it is asynchronous both in the communication with
131 * the user and the backend. We think the complexity will pay off in
132 * the form of greater flexibility when more asynchronous facilities
135 * Memory management has become somewhat involved. In the simple case, where
136 * only one PDU is pending at a time, it will simply reuse the same memory,
137 * once it has found its working size. When we enable multiple concurrent
138 * operations, perhaps even with multiple parallel calls to the backend, it
139 * will maintain a pool of buffers for encoding and decoding, trying to
140 * minimize memory allocation/deallocation during normal operation.
142 * TODOs include (and will be done in order of public interest):
144 * Support for EXPLAIN - provide simple meta-database system.
145 * Support for access control.
146 * Support for resource control.
147 * Support for extended services - primarily Item Order.
148 * Rest of Z39.50-1994
158 #include <comstack.h>
164 #include <statserv.h>
168 static int process_request(association *assoc);
169 void backend_response(IOCHAN i, int event);
170 static int process_response(association *assoc, request *req, Z_APDU *res);
171 static Z_APDU *process_initRequest(association *assoc, request *reqb);
172 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
174 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
175 bend_searchresult *bsrt, int *fd);
176 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
178 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
180 static FILE *apduf = 0; /* for use in static mode */
181 static statserv_options_block *control_block = 0;
184 * Create and initialize a new association-handle.
185 * channel : iochannel for the current line.
186 * link : communications channel.
187 * Returns: 0 or a new association handle.
189 association *create_association(IOCHAN channel, COMSTACK link)
194 control_block = statserv_getcontrol();
195 if (!(new = malloc(sizeof(*new))))
197 new->client_chan = channel;
198 new->client_link = link;
199 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
200 !(new->encode = odr_createmem(ODR_ENCODE)))
202 if (*control_block->apdufile)
207 strcpy(filename, control_block->apdufile);
208 if (!(new->print = odr_createmem(ODR_PRINT)))
210 if (*control_block->apdufile != '-')
212 strcpy(filename, control_block->apdufile);
213 if (!control_block->dynamic)
217 if (!(apduf = fopen(filename, "w")))
219 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
222 setvbuf(apduf, 0, _IONBF, 0);
228 sprintf(filename + strlen(filename), ".%d", getpid());
229 if (!(f = fopen(filename, "w")))
231 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
234 setvbuf(f, 0, _IONBF, 0);
236 odr_setprint(new->print, f);
241 new->input_buffer = 0;
242 new->input_buffer_len = 0;
245 request_initq(&new->incoming);
246 request_initq(&new->outgoing);
247 new->proto = cs_getproto(link);
252 * Free association and release resources.
254 void destroy_association(association *h)
256 odr_destroy(h->decode);
257 odr_destroy(h->encode);
259 odr_destroy(h->print);
261 free(h->input_buffer);
263 bend_close(h->backend);
264 while (request_deq(&h->incoming));
265 while (request_deq(&h->outgoing));
270 * This is where PDUs from the client are read and the further
271 * processing is initiated. Flow of control moves down through the
272 * various process_* functions below, until the encoded result comes back up
273 * to the output handler in here.
275 * h : the I/O channel that has an outstanding event.
276 * event : the current outstanding event.
278 void ir_session(IOCHAN h, int event)
281 association *assoc = iochan_getdata(h);
282 COMSTACK conn = assoc->client_link;
285 assert(h && conn && assoc);
286 if (event == EVENT_TIMEOUT)
288 logf(LOG_LOG, "Timeout - closing connection.");
290 destroy_association(assoc);
294 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
296 if (event & EVENT_INPUT)
298 logf(LOG_DEBUG, "ir_session (input)");
299 assert(assoc && conn);
300 /* We aren't speaking to this fellow */
303 logf(LOG_LOG, "Closed connection after reject");
305 destroy_association(assoc);
309 if ((res = cs_get(conn, &assoc->input_buffer,
310 &assoc->input_buffer_len)) <= 0)
312 logf(LOG_LOG, "Connection closed by client");
314 destroy_association(assoc);
318 else if (res == 1) /* incomplete read - wait for more */
320 if (cs_more(conn)) /* more stuff - call us again later, please */
321 iochan_setevent(h, EVENT_INPUT);
323 /* we got a complete PDU. Let's decode it */
324 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
325 req = request_get(); /* get a new request structure */
326 odr_reset(assoc->decode);
327 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
328 if (!z_APDU(assoc->decode, &req->request, 0))
330 logf(LOG_WARN, "ODR error: %s",
331 odr_errlist[odr_geterror(assoc->decode)]);
333 destroy_association(assoc);
337 req->request_mem = odr_extract_mem(assoc->decode);
338 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
340 logf(LOG_WARN, "ODR print error: %s",
341 odr_errlist[odr_geterror(assoc->print)]);
342 odr_reset(assoc->print);
344 request_enq(&assoc->incoming, req);
347 /* can we do something yet? */
348 req = request_head(&assoc->incoming);
349 if (req->state == REQUEST_IDLE)
350 if (process_request(assoc) < 0)
353 destroy_association(assoc);
357 if (event & EVENT_OUTPUT)
359 request *req = request_head(&assoc->outgoing);
361 logf(LOG_DEBUG, "ir_session (output)");
362 req->state = REQUEST_PENDING;
363 switch (res = cs_put(conn, req->response, req->len_response))
366 logf(LOG_LOG, "Connection closed by client");
368 destroy_association(assoc);
371 case 0: /* all sent - release the request structure */
372 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
373 odr_release_mem(req->request_mem);
374 request_deq(&assoc->outgoing);
375 request_release(req);
376 if (!request_head(&assoc->outgoing))
377 iochan_clearflag(h, EVENT_OUTPUT);
379 /* value of 1 -- partial send -- is simply ignored */
382 if (event & EVENT_EXCEPT)
384 logf(LOG_DEBUG, "ir_session (exception)");
386 destroy_association(assoc);
392 * Initiate request processing.
394 static int process_request(association *assoc)
396 request *req = request_head(&assoc->incoming);
400 logf(LOG_DEBUG, "process_request");
401 assert(req && req->state == REQUEST_IDLE);
402 switch (req->request->which)
404 case Z_APDU_initRequest:
405 res = process_initRequest(assoc, req); break;
406 case Z_APDU_searchRequest:
407 res = process_searchRequest(assoc, req, &fd); break;
408 case Z_APDU_presentRequest:
409 res = process_presentRequest(assoc, req, &fd); break;
410 case Z_APDU_scanRequest:
411 res = process_scanRequest(assoc, req, &fd); break;
413 logf(LOG_WARN, "Bad APDU received");
418 logf(LOG_DEBUG, " result immediately available");
419 return process_response(assoc, req, res);
423 logf(LOG_WARN, " bad result");
426 else /* no result yet - one will be provided later */
430 /* Set up an I/O handler for the fd supplied by the backend */
432 logf(LOG_DEBUG, " establishing handler for result");
433 req->state = REQUEST_PENDING;
434 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
436 iochan_setdata(chan, assoc);
442 * Handle message from the backend.
444 void backend_response(IOCHAN i, int event)
446 association *assoc = iochan_getdata(i);
447 request *req = request_head(&assoc->incoming);
451 logf(LOG_DEBUG, "backend_response");
452 assert(assoc && req && req->state != REQUEST_IDLE);
453 /* determine what it is we're waiting for */
454 switch (req->request->which)
456 case Z_APDU_searchRequest:
457 res = response_searchRequest(assoc, req, 0, &fd); break;
459 case Z_APDU_presentRequest:
460 res = response_presentRequest(assoc, req, 0, &fd); break;
461 case Z_APDU_scanRequest:
462 res = response_scanRequest(assoc, req, 0, &fd); break;
465 logf(LOG_WARN, "Serious programmer's lapse or bug");
468 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
470 logf(LOG_LOG, "Fatal error when talking to backend");
471 cs_close(assoc->client_link);
472 destroy_association(assoc);
473 iochan_destroy(assoc->client_chan);
477 else if (!res) /* no result yet - try again later */
479 logf(LOG_DEBUG, " no result yet");
480 iochan_setfd(i, fd); /* in case fd has changed */
485 * Encode response, and transfer the request structure to the outgoing queue.
487 static int process_response(association *assoc, request *req, Z_APDU *res)
489 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
490 if (!z_APDU(assoc->encode, &res, 0))
492 logf(LOG_WARN, "ODR error when encoding response: %s",
493 odr_errlist[odr_geterror(assoc->decode)]);
496 req->response = odr_getbuf(assoc->encode, &req->len_response,
497 &req->size_response);
498 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
499 odr_reset(assoc->encode);
500 if (assoc->print && !z_APDU(assoc->print, &res, 0))
502 logf(LOG_WARN, "ODR print error: %s",
503 odr_errlist[odr_geterror(assoc->print)]);
504 odr_reset(assoc->print);
506 /* change this when we make the backend reentrant */
507 assert(req == request_head(&assoc->incoming));
508 req->state = REQUEST_IDLE;
509 request_deq(&assoc->incoming);
510 request_enq(&assoc->outgoing, req);
511 /* turn the work over to the ir_session handler */
512 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
513 /* Is there more work to be done? give that to the input handler too */
514 if (request_head(&assoc->incoming))
515 iochan_setevent(assoc->client_chan, EVENT_WORK);
520 * Handle init request.
521 * At the moment, we don't check the protocol version or the options
522 * anywhere else in the code - we just try not to do anything that would
523 * break a naive client. We'll toss 'em into the association block when
524 * we need them there.
526 static Z_APDU *process_initRequest(association *assoc, request *reqb)
528 Z_InitRequest *req = reqb->request->u.initRequest;
529 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
530 Z_InitResponse *resp = apdu->u.initResponse;
531 bend_initrequest binitreq;
532 bend_initresult *binitres;
534 logf(LOG_LOG, "Got initRequest");
535 if (req->implementationId)
536 logf(LOG_LOG, "Id: %s", req->implementationId);
537 if (req->implementationName)
538 logf(LOG_LOG, "Name: %s", req->implementationName);
539 if (req->implementationVersion)
540 logf(LOG_LOG, "Version: %s", req->implementationVersion);
542 binitreq.configname = "default-config";
543 binitreq.auth = req->idAuthentication;
544 if (!(binitres = bend_init(&binitreq)))
546 logf(LOG_WARN, "Bad response from backend.");
550 assoc->backend = binitres->handle;
551 resp->referenceId = req->referenceId;
552 /* let's tell the client what we can do */
553 if (ODR_MASK_GET(req->options, Z_Options_search))
554 ODR_MASK_SET(resp->options, Z_Options_search);
555 if (ODR_MASK_GET(req->options, Z_Options_present))
556 ODR_MASK_SET(resp->options, Z_Options_present);
558 if (ODR_MASK_GET(req->options, Z_Options_delSet))
559 ODR_MASK_SET(&options, Z_Options_delSet);
561 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
562 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
563 if (ODR_MASK_GET(req->options, Z_Options_scan))
564 ODR_MASK_SET(resp->options, Z_Options_scan);
565 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
566 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
568 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
569 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
570 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
571 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
572 assoc->maximumRecordSize = *req->maximumRecordSize;
573 if (assoc->maximumRecordSize > control_block->maxrecordsize)
574 assoc->maximumRecordSize = control_block->maxrecordsize;
575 assoc->preferredMessageSize = *req->preferredMessageSize;
576 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
577 assoc->preferredMessageSize = assoc->maximumRecordSize;
578 resp->preferredMessageSize = &assoc->preferredMessageSize;
579 resp->maximumRecordSize = &assoc->maximumRecordSize;
580 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
581 if (binitres->errcode)
583 logf(LOG_LOG, "Connection rejected by backend.");
591 * These functions should be merged.
595 * nonsurrogate diagnostic record.
597 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
599 static Z_Records rec;
603 static Z_DiagRec drec;
604 static Z_DefaultDiagFormat dr;
610 bib1.class = CLASS_DIAGSET;
611 bib1.value = VAL_BIB1;
613 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
616 rec.which = Z_Records_NSD;
618 rec.u.nonSurrogateDiagnostic = &drec;
619 drec.which = Z_DiagRec_defaultFormat;
620 drec.u.defaultFormat = &dr;
622 rec.u.nonSurrogateDiagnostic = &dr;
624 dr.diagnosticSetId = oid_getoidbyent(&bib1);
626 dr.which = Z_DiagForm_v2AddInfo;
627 dr.addinfo = addinfo ? addinfo : "";
632 * surrogate diagnostic.
634 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
635 int error, char *addinfo)
637 static Z_NamePlusRecord rec;
641 static Z_DiagRec drec;
642 static Z_DefaultDiagFormat dr;
648 bib1.class = CLASS_DIAGSET;
649 bib1.value = VAL_BIB1;
651 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
653 rec.databaseName = dbname;
654 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
656 rec.u.surrogateDiagnostic = &drec;
657 drec.which = Z_DiagRec_defaultFormat;
658 drec.u.defaultFormat = &dr;
660 rec.u.surrogateDiagnostic = &dr;
662 dr.diagnosticSetId = oid_getoidbyent(&bib1);
664 dr.which = Z_DiagForm_v2AddInfo;
665 dr.addinfo = addinfo ? addinfo : "";
670 * multiple nonsurrogate diagnostics.
672 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
674 static Z_DiagRecs recs;
678 static Z_DiagRec *recp[1], drec;
679 static Z_DefaultDiagFormat rec;
681 static Z_DiagRec *recp[1], rec;
684 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
686 bib1.class = CLASS_DIAGSET;
687 bib1.value = VAL_BIB1;
690 recs.num_diagRecs = 1;
691 recs.diagRecs = recp;
694 drec.which = Z_DiagRec_defaultFormat;
695 drec.u.defaultFormat = &rec;
699 rec.diagnosticSetId = oid_getoidbyent(&bib1);
700 rec.condition = &err;
701 rec.which = Z_DiagForm_v2AddInfo;
702 rec.addinfo = addinfo ? addinfo : "";
706 #define MAX_RECORDS 256
708 static Z_Records *pack_records(association *a, char *setname, int start,
709 int *num, Z_ElementSetNames *esn,
710 int *next, int *pres)
712 int recno, total_length = 0, toget = *num;
713 static Z_Records records;
714 static Z_NamePlusRecordList reclist;
715 static Z_NamePlusRecord *list[MAX_RECORDS];
719 records.which = Z_Records_DBOSD;
720 records.u.databaseOrSurDiagnostics = &reclist;
721 reclist.num_records = 0;
722 reclist.records = list;
723 *pres = Z_PRES_SUCCESS;
727 recform.proto = a->proto;
728 recform.class = CLASS_RECSYN;
729 recform.value = VAL_USMARC;
730 if (!(oid = odr_oiddup(a->encode, oid_getoidbyent(&recform))))
733 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
734 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
735 a->maximumRecordSize);
736 for (recno = start; reclist.num_records < toget; recno++)
738 bend_fetchrequest freq;
739 bend_fetchresult *fres;
740 Z_NamePlusRecord *thisrec;
741 Z_DatabaseRecord *thisext;
743 if (reclist.num_records == MAX_RECORDS - 1)
745 *pres = Z_PRES_PARTIAL_2;
748 freq.setname = setname;
750 if (!(fres = bend_fetch(a->backend, &freq, 0)))
752 *pres = Z_PRES_FAILURE;
753 return diagrec(a->proto, 2, "Backend interface problem");
755 /* backend should be able to signal whether error is system-wide
756 or only pertaining to current record */
759 *pres = Z_PRES_FAILURE;
760 return diagrec(a->proto, fres->errcode, fres->errstring);
762 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
763 fres->len, total_length);
764 if (fres->len + total_length > a->preferredMessageSize)
766 /* record is small enough, really */
767 if (fres->len <= a->preferredMessageSize)
769 logf(LOG_DEBUG, " Dropped last normal-sized record");
770 *pres = Z_PRES_PARTIAL_2;
773 /* record can only be fetched by itself */
774 if (fres->len < a->maximumRecordSize)
776 logf(LOG_DEBUG, " Record > prefmsgsz");
779 logf(LOG_DEBUG, " Dropped it");
780 reclist.records[reclist.num_records] =
781 surrogatediagrec(a->proto, fres->basename, 16, 0);
782 reclist.num_records++;
783 total_length += 10; /* totally arbitrary */
787 else /* too big entirely */
789 logf(LOG_DEBUG, "Record > maxrcdsz");
790 reclist.records[reclist.num_records] =
791 surrogatediagrec(a->proto, fres->basename, 17, 0);
792 reclist.num_records++;
793 total_length += 10; /* totally arbitrary */
797 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
799 if (!(thisrec->databaseName = odr_malloc(a->encode,
800 strlen(fres->basename) + 1)))
802 strcpy(thisrec->databaseName, fres->basename);
803 thisrec->which = Z_NamePlusRecord_databaseRecord;
804 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
805 sizeof(Z_DatabaseRecord))))
807 thisext->direct_reference = oid; /* should be OID for current MARC */
808 thisext->indirect_reference = 0;
809 thisext->descriptor = 0;
810 thisext->which = ODR_EXTERNAL_octet;
811 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
814 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode, fres->len)))
816 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
817 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
819 reclist.records[reclist.num_records] = thisrec;
820 reclist.num_records++;
821 total_length += fres->len;
822 *next = fres->last_in_set ? 0 : recno + 1;
824 *num = reclist.num_records;
828 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
831 Z_SearchRequest *req = reqb->request->u.searchRequest;
832 bend_searchrequest bsrq;
833 bend_searchresult *bsrt;
835 logf(LOG_LOG, "Got SearchRequest.");
837 bsrq.setname = req->resultSetName;
838 bsrq.replace_set = *req->replaceIndicator;
839 bsrq.num_bases = req->num_databaseNames;
840 bsrq.basenames = req->databaseNames;
841 bsrq.query = req->query;
843 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
845 return response_searchRequest(assoc, reqb, bsrt, fd);
848 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
851 * Prepare a searchresponse based on the backend results. We probably want
852 * to look at making the fetching of records nonblocking as well, but
853 * so far, we'll keep things simple.
854 * If bsrt is null, that means we're called in response to a communications
855 * event, and we'll have to get the response for ourselves.
857 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
858 bend_searchresult *bsrt, int *fd)
860 Z_SearchRequest *req = reqb->request->u.searchRequest;
862 static Z_SearchResponse resp;
863 static int nulint = 0;
864 static bool_t sr = 1;
866 static int none = Z_RES_NONE;
868 apdu.which = Z_APDU_searchResponse;
869 apdu.u.searchResponse = &resp;
870 resp.referenceId = req->referenceId;
872 resp.additionalSearchInfo = 0;
876 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
878 logf(LOG_FATAL, "Bad result from backend");
881 else if (bsrt->errcode)
883 resp.records = diagrec(assoc->proto, bsrt->errcode,
885 resp.resultCount = &nulint;
886 resp.numberOfRecordsReturned = &nulint;
887 resp.nextResultSetPosition = &nulint;
888 resp.searchStatus = &nulint;
889 resp.resultSetStatus = &none;
890 resp.presentStatus = 0;
895 Z_ElementSetNames *setnames;
899 resp.resultCount = &bsrt->hits;
901 /* how many records does the user agent want, then? */
902 if (bsrt->hits <= *req->smallSetUpperBound)
905 setnames = req->smallSetElementSetNames;
907 else if (bsrt->hits < *req->largeSetLowerBound)
909 toget = *req->mediumSetPresentNumber;
910 if (toget > bsrt->hits)
912 setnames = req->mediumSetElementSetNames;
917 if (toget && !resp.records)
919 resp.records = pack_records(assoc, req->resultSetName, 1,
920 &toget, setnames, &next, &presst);
923 resp.numberOfRecordsReturned = &toget;
924 resp.nextResultSetPosition = &next;
925 resp.searchStatus = &sr;
926 resp.resultSetStatus = 0;
927 resp.presentStatus = &presst;
931 resp.numberOfRecordsReturned = &nulint;
932 resp.nextResultSetPosition = &next;
933 resp.searchStatus = &sr;
934 resp.resultSetStatus = 0;
935 resp.presentStatus = 0;
942 * Maybe we got a little over-friendly when we designed bend_fetch to
943 * get only one record at a time. Some backends can optimise multiple-record
944 * fetches, and at any rate, there is some overhead involved in
945 * all that selecting and hopping around. Problem is, of course, that the
946 * frontend can't know ahead of time how many records it'll need to
947 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
948 * is downright lousy as a bulk data transfer protocol.
950 * To start with, we'll do the fetching of records from the backend
951 * in one operation: To save some trips in and out of the event-handler,
952 * and to simplify the interface to pack_records. At any rate, asynch
953 * operation is more fun in operations that have an unpredictable execution
954 * speed - which is normally more true for search than for present.
956 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
959 Z_PresentRequest *req = reqb->request->u.presentRequest;
961 static Z_PresentResponse resp;
962 static int presst, next, num;
964 logf(LOG_LOG, "Got PresentRequest.");
965 apdu.which = Z_APDU_presentResponse;
966 apdu.u.presentResponse = &resp;
967 resp.referenceId = req->referenceId;
972 num = *req->numberOfRecordsRequested;
973 resp.records = pack_records(assoc, req->resultSetId,
974 *req->resultSetStartPoint, &num, 0, &next, &presst);
977 resp.numberOfRecordsReturned = #
978 resp.presentStatus = &presst;
979 resp.nextResultSetPosition = &next;
985 * Scan was implemented rather in a hurry, and with support for only the basic
986 * elements of the service in the backend API. Suggestions are welcome.
988 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
990 Z_ScanRequest *req = reqb->request->u.scanRequest;
992 static Z_ScanResponse res;
993 static int scanStatus = Z_Scan_failure;
994 static int numberOfEntriesReturned = 0;
996 static Z_ListEntries ents;
997 #define SCAN_MAX_ENTRIES 200
998 static Z_Entry *tab[SCAN_MAX_ENTRIES];
999 bend_scanrequest srq;
1000 bend_scanresult *srs;
1002 logf(LOG_LOG, "Got scanrequest");
1003 apdu.which = Z_APDU_scanResponse;
1004 apdu.u.scanResponse = &res;
1005 res.referenceId = req->referenceId;
1007 res.scanStatus = &scanStatus;
1008 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1009 res.positionOfTerm = 0;
1010 res.entries = &ents;
1011 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1012 res.attributeSet = 0;
1017 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1018 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1019 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1020 else if (req->stepSize && *req->stepSize > 0)
1021 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1024 if (req->termListAndStartPoint->term->which == Z_Term_general)
1025 logf(LOG_DEBUG, " term: '%.*s'",
1026 req->termListAndStartPoint->term->u.general->len,
1027 req->termListAndStartPoint->term->u.general->buf);
1028 srq.num_bases = req->num_databaseNames;
1029 srq.basenames = req->databaseNames;
1030 srq.num_entries = *req->numberOfTermsRequested;
1031 srq.term = req->termListAndStartPoint;
1032 srq.term_position = req->preferredPositionInResponse ?
1033 *req->preferredPositionInResponse : 1;
1034 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1035 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1036 else if (srs->errcode)
1037 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1038 srs->errcode, srs->errstring);
1042 static Z_Entries list;
1044 if (srs->status == BEND_SCAN_PARTIAL)
1045 scanStatus = Z_Scan_partial_5;
1047 scanStatus = Z_Scan_success;
1048 ents.which = Z_ListEntries_entries;
1049 ents.u.entries = &list;
1051 for (i = 0; i < srs->num_entries; i++)
1057 if (i >= SCAN_MAX_ENTRIES)
1059 scanStatus = Z_Scan_partial_4;
1062 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1063 e->which = Z_Entry_termInfo;
1064 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1065 t->suggestedAttributes = 0;
1066 t->alternativeTerm = 0;
1067 t->byAttributes = 0;
1068 t->globalOccurrences = &srs->entries[i].occurrences;
1069 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1070 t->term->which = Z_Term_general;
1071 t->term->u.general = o = odr_malloc(assoc->encode,
1073 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1074 strlen(srs->entries[i].term));
1075 memcpy(o->buf, srs->entries[i].term, o->len);
1076 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1077 srs->entries[i].term, srs->entries[i].occurrences);
1079 list.num_entries = i;
1080 res.numberOfEntriesReturned = &list.num_entries;
1081 res.positionOfTerm = &srs->term_position;