2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.38 1995-06-19 12:39:11 quinn
8 * Fixed bug in timeout code. Added BER dumper.
10 * Revision 1.37 1995/06/16 13:16:14 quinn
11 * Fixed Defaultdiagformat.
13 * Revision 1.36 1995/06/16 10:31:36 quinn
14 * Added session timeout.
16 * Revision 1.35 1995/06/15 07:45:14 quinn
19 * Revision 1.34 1995/06/14 15:26:46 quinn
20 * *** empty log message ***
22 * Revision 1.33 1995/06/06 14:57:05 quinn
25 * Revision 1.32 1995/06/06 08:41:44 quinn
28 * Revision 1.31 1995/06/06 08:15:37 quinn
31 * Revision 1.30 1995/06/05 10:53:32 quinn
32 * Added a better SCAN.
34 * Revision 1.29 1995/06/01 11:25:03 quinn
37 * Revision 1.28 1995/06/01 11:21:01 quinn
38 * Attempting to fix a bug in pack-records. replaced break with continue
39 * for large records, according to standard.
41 * Revision 1.27 1995/05/29 08:12:06 quinn
44 * Revision 1.26 1995/05/18 13:02:12 quinn
47 * Revision 1.25 1995/05/17 08:42:26 quinn
48 * Transfer auth info to backend. Allow backend to reject init gracefully.
50 * Revision 1.24 1995/05/16 08:51:04 quinn
51 * License, documentation, and memory fixes
53 * Revision 1.23 1995/05/15 13:25:10 quinn
56 * Revision 1.22 1995/05/15 11:56:39 quinn
57 * Asynchronous facilities. Restructuring of seshigh code.
59 * Revision 1.21 1995/05/02 08:53:19 quinn
60 * Trying in vain to fix comm with ISODE
62 * Revision 1.20 1995/04/20 15:13:00 quinn
65 * Revision 1.19 1995/04/18 08:15:34 quinn
66 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
67 * neater. We'll make the same change for decoding one day.
69 * Revision 1.18 1995/04/17 11:28:25 quinn
72 * Revision 1.17 1995/04/10 10:23:36 quinn
73 * Some work to add scan and other things.
75 * Revision 1.16 1995/03/31 09:18:55 quinn
78 * Revision 1.15 1995/03/30 14:03:23 quinn
79 * Added RFC1006 as separate library
81 * Revision 1.14 1995/03/30 12:18:17 quinn
84 * Revision 1.13 1995/03/30 09:09:24 quinn
85 * Added state-handle and some support for asynchronous activities.
87 * Revision 1.12 1995/03/29 15:40:16 quinn
88 * Ongoing work. Statserv is now dynamic by default
90 * Revision 1.11 1995/03/28 09:16:21 quinn
91 * Added record packing to the search request
93 * Revision 1.10 1995/03/27 08:34:24 quinn
94 * Added dynamic server functionality.
95 * Released bindings to session.c (is now redundant)
97 * Revision 1.9 1995/03/22 15:01:26 quinn
98 * Adjusting record packing.
100 * Revision 1.8 1995/03/22 10:13:21 quinn
101 * Working on record packer
103 * Revision 1.7 1995/03/21 15:53:31 quinn
106 * Revision 1.6 1995/03/21 12:30:09 quinn
107 * Beginning to add support for record packing.
109 * Revision 1.5 1995/03/17 10:44:13 quinn
110 * Added catch of null-string in makediagrec
112 * Revision 1.4 1995/03/17 10:18:08 quinn
113 * Added memory management.
115 * Revision 1.3 1995/03/16 17:42:39 quinn
118 * Revision 1.2 1995/03/16 13:29:01 quinn
119 * Partitioned server.
121 * Revision 1.1 1995/03/15 16:02:10 quinn
122 * Modded session.c to seshigh.c
127 * Frontend server logic.
129 * This code receives incoming APDUs, and handles client requests by means
130 * of the backend API.
132 * Some of the code is getting quite involved, compared to simpler servers -
133 * primarily because it is asynchronous both in the communication with
134 * the user and the backend. We think the complexity will pay off in
135 * the form of greater flexibility when more asynchronous facilities
138 * Memory management has become somewhat involved. In the simple case, where
139 * only one PDU is pending at a time, it will simply reuse the same memory,
140 * once it has found its working size. When we enable multiple concurrent
141 * operations, perhaps even with multiple parallel calls to the backend, it
142 * will maintain a pool of buffers for encoding and decoding, trying to
143 * minimize memory allocation/deallocation during normal operation.
145 * TODOs include (and will be done in order of public interest):
147 * Support for EXPLAIN - provide simple meta-database system.
148 * Support for access control.
149 * Support for resource control.
150 * Support for extended services - primarily Item Order.
151 * Rest of Z39.50-1994
161 #include <comstack.h>
167 #include <statserv.h>
171 static int process_request(association *assoc);
172 void backend_response(IOCHAN i, int event);
173 static int process_response(association *assoc, request *req, Z_APDU *res);
174 static Z_APDU *process_initRequest(association *assoc, request *reqb);
175 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
177 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
178 bend_searchresult *bsrt, int *fd);
179 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
181 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
183 static FILE *apduf = 0; /* for use in static mode */
184 static statserv_options_block *control_block = 0;
187 * Create and initialize a new association-handle.
188 * channel : iochannel for the current line.
189 * link : communications channel.
190 * Returns: 0 or a new association handle.
192 association *create_association(IOCHAN channel, COMSTACK link)
197 control_block = statserv_getcontrol();
198 if (!(new = malloc(sizeof(*new))))
200 new->client_chan = channel;
201 new->client_link = link;
202 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
203 !(new->encode = odr_createmem(ODR_ENCODE)))
205 if (*control_block->apdufile)
210 strcpy(filename, control_block->apdufile);
211 if (!(new->print = odr_createmem(ODR_PRINT)))
213 if (*control_block->apdufile != '-')
215 strcpy(filename, control_block->apdufile);
216 if (!control_block->dynamic)
220 if (!(apduf = fopen(filename, "w")))
222 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
225 setvbuf(apduf, 0, _IONBF, 0);
231 sprintf(filename + strlen(filename), ".%d", getpid());
232 if (!(f = fopen(filename, "w")))
234 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
237 setvbuf(f, 0, _IONBF, 0);
239 odr_setprint(new->print, f);
244 new->input_buffer = 0;
245 new->input_buffer_len = 0;
248 request_initq(&new->incoming);
249 request_initq(&new->outgoing);
250 new->proto = cs_getproto(link);
255 * Free association and release resources.
257 void destroy_association(association *h)
259 odr_destroy(h->decode);
260 odr_destroy(h->encode);
262 odr_destroy(h->print);
264 free(h->input_buffer);
266 bend_close(h->backend);
267 while (request_deq(&h->incoming));
268 while (request_deq(&h->outgoing));
273 * This is where PDUs from the client are read and the further
274 * processing is initiated. Flow of control moves down through the
275 * various process_* functions below, until the encoded result comes back up
276 * to the output handler in here.
278 * h : the I/O channel that has an outstanding event.
279 * event : the current outstanding event.
281 void ir_session(IOCHAN h, int event)
284 association *assoc = iochan_getdata(h);
285 COMSTACK conn = assoc->client_link;
288 assert(h && conn && assoc);
289 if (event == EVENT_TIMEOUT)
291 logf(LOG_LOG, "Timeout - closing connection.");
293 destroy_association(assoc);
297 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
299 if (event & EVENT_INPUT)
301 logf(LOG_DEBUG, "ir_session (input)");
302 assert(assoc && conn);
303 /* We aren't speaking to this fellow */
306 logf(LOG_LOG, "Closed connection after reject");
308 destroy_association(assoc);
312 if ((res = cs_get(conn, &assoc->input_buffer,
313 &assoc->input_buffer_len)) <= 0)
315 logf(LOG_LOG, "Connection closed by client");
317 destroy_association(assoc);
321 else if (res == 1) /* incomplete read - wait for more */
323 if (cs_more(conn)) /* more stuff - call us again later, please */
324 iochan_setevent(h, EVENT_INPUT);
326 /* we got a complete PDU. Let's decode it */
327 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
328 req = request_get(); /* get a new request structure */
329 odr_reset(assoc->decode);
330 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
331 if (!z_APDU(assoc->decode, &req->request, 0))
333 logf(LOG_LOG, "ODR error on incoming PDU: %s",
334 odr_errlist[odr_geterror(assoc->decode)]);
335 logf(LOG_LOG, "PDU dump:");
336 odr_dumpBER(log_file(), assoc->input_buffer, res);
338 destroy_association(assoc);
342 req->request_mem = odr_extract_mem(assoc->decode);
343 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
345 logf(LOG_WARN, "ODR print error: %s",
346 odr_errlist[odr_geterror(assoc->print)]);
347 odr_reset(assoc->print);
349 request_enq(&assoc->incoming, req);
352 /* can we do something yet? */
353 req = request_head(&assoc->incoming);
354 if (req->state == REQUEST_IDLE)
355 if (process_request(assoc) < 0)
358 destroy_association(assoc);
362 if (event & EVENT_OUTPUT)
364 request *req = request_head(&assoc->outgoing);
366 logf(LOG_DEBUG, "ir_session (output)");
367 req->state = REQUEST_PENDING;
368 switch (res = cs_put(conn, req->response, req->len_response))
371 logf(LOG_LOG, "Connection closed by client");
373 destroy_association(assoc);
376 case 0: /* all sent - release the request structure */
377 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
378 odr_release_mem(req->request_mem);
379 request_deq(&assoc->outgoing);
380 request_release(req);
381 if (!request_head(&assoc->outgoing))
382 iochan_clearflag(h, EVENT_OUTPUT);
384 /* value of 1 -- partial send -- is simply ignored */
387 if (event & EVENT_EXCEPT)
389 logf(LOG_DEBUG, "ir_session (exception)");
391 destroy_association(assoc);
397 * Initiate request processing.
399 static int process_request(association *assoc)
401 request *req = request_head(&assoc->incoming);
405 logf(LOG_DEBUG, "process_request");
406 assert(req && req->state == REQUEST_IDLE);
407 switch (req->request->which)
409 case Z_APDU_initRequest:
410 res = process_initRequest(assoc, req); break;
411 case Z_APDU_searchRequest:
412 res = process_searchRequest(assoc, req, &fd); break;
413 case Z_APDU_presentRequest:
414 res = process_presentRequest(assoc, req, &fd); break;
415 case Z_APDU_scanRequest:
416 res = process_scanRequest(assoc, req, &fd); break;
418 logf(LOG_WARN, "Bad APDU received");
423 logf(LOG_DEBUG, " result immediately available");
424 return process_response(assoc, req, res);
428 logf(LOG_WARN, " bad result");
431 else /* no result yet - one will be provided later */
435 /* Set up an I/O handler for the fd supplied by the backend */
437 logf(LOG_DEBUG, " establishing handler for result");
438 req->state = REQUEST_PENDING;
439 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
441 iochan_setdata(chan, assoc);
447 * Handle message from the backend.
449 void backend_response(IOCHAN i, int event)
451 association *assoc = iochan_getdata(i);
452 request *req = request_head(&assoc->incoming);
456 logf(LOG_DEBUG, "backend_response");
457 assert(assoc && req && req->state != REQUEST_IDLE);
458 /* determine what it is we're waiting for */
459 switch (req->request->which)
461 case Z_APDU_searchRequest:
462 res = response_searchRequest(assoc, req, 0, &fd); break;
464 case Z_APDU_presentRequest:
465 res = response_presentRequest(assoc, req, 0, &fd); break;
466 case Z_APDU_scanRequest:
467 res = response_scanRequest(assoc, req, 0, &fd); break;
470 logf(LOG_WARN, "Serious programmer's lapse or bug");
473 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
475 logf(LOG_LOG, "Fatal error when talking to backend");
476 cs_close(assoc->client_link);
477 destroy_association(assoc);
478 iochan_destroy(assoc->client_chan);
482 else if (!res) /* no result yet - try again later */
484 logf(LOG_DEBUG, " no result yet");
485 iochan_setfd(i, fd); /* in case fd has changed */
490 * Encode response, and transfer the request structure to the outgoing queue.
492 static int process_response(association *assoc, request *req, Z_APDU *res)
494 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
495 if (!z_APDU(assoc->encode, &res, 0))
497 logf(LOG_WARN, "ODR error when encoding response: %s",
498 odr_errlist[odr_geterror(assoc->decode)]);
501 req->response = odr_getbuf(assoc->encode, &req->len_response,
502 &req->size_response);
503 odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
504 odr_reset(assoc->encode);
505 if (assoc->print && !z_APDU(assoc->print, &res, 0))
507 logf(LOG_WARN, "ODR print error: %s",
508 odr_errlist[odr_geterror(assoc->print)]);
509 odr_reset(assoc->print);
511 /* change this when we make the backend reentrant */
512 assert(req == request_head(&assoc->incoming));
513 req->state = REQUEST_IDLE;
514 request_deq(&assoc->incoming);
515 request_enq(&assoc->outgoing, req);
516 /* turn the work over to the ir_session handler */
517 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
518 /* Is there more work to be done? give that to the input handler too */
519 if (request_head(&assoc->incoming))
520 iochan_setevent(assoc->client_chan, EVENT_WORK);
525 * Handle init request.
526 * At the moment, we don't check the protocol version or the options
527 * anywhere else in the code - we just try not to do anything that would
528 * break a naive client. We'll toss 'em into the association block when
529 * we need them there.
531 static Z_APDU *process_initRequest(association *assoc, request *reqb)
533 Z_InitRequest *req = reqb->request->u.initRequest;
534 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
535 Z_InitResponse *resp = apdu->u.initResponse;
536 bend_initrequest binitreq;
537 bend_initresult *binitres;
539 logf(LOG_LOG, "Got initRequest");
540 if (req->implementationId)
541 logf(LOG_LOG, "Id: %s", req->implementationId);
542 if (req->implementationName)
543 logf(LOG_LOG, "Name: %s", req->implementationName);
544 if (req->implementationVersion)
545 logf(LOG_LOG, "Version: %s", req->implementationVersion);
547 binitreq.configname = "default-config";
548 binitreq.auth = req->idAuthentication;
549 if (!(binitres = bend_init(&binitreq)))
551 logf(LOG_WARN, "Bad response from backend.");
555 assoc->backend = binitres->handle;
556 resp->referenceId = req->referenceId;
557 /* let's tell the client what we can do */
558 if (ODR_MASK_GET(req->options, Z_Options_search))
559 ODR_MASK_SET(resp->options, Z_Options_search);
560 if (ODR_MASK_GET(req->options, Z_Options_present))
561 ODR_MASK_SET(resp->options, Z_Options_present);
563 if (ODR_MASK_GET(req->options, Z_Options_delSet))
564 ODR_MASK_SET(&options, Z_Options_delSet);
566 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
567 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
568 if (ODR_MASK_GET(req->options, Z_Options_scan))
569 ODR_MASK_SET(resp->options, Z_Options_scan);
570 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
571 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
573 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
574 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
575 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
576 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
577 assoc->maximumRecordSize = *req->maximumRecordSize;
578 if (assoc->maximumRecordSize > control_block->maxrecordsize)
579 assoc->maximumRecordSize = control_block->maxrecordsize;
580 assoc->preferredMessageSize = *req->preferredMessageSize;
581 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
582 assoc->preferredMessageSize = assoc->maximumRecordSize;
583 resp->preferredMessageSize = &assoc->preferredMessageSize;
584 resp->maximumRecordSize = &assoc->maximumRecordSize;
585 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
586 if (binitres->errcode)
588 logf(LOG_LOG, "Connection rejected by backend.");
596 * These functions should be merged.
600 * nonsurrogate diagnostic record.
602 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
604 static Z_Records rec;
608 static Z_DiagRec drec;
609 static Z_DefaultDiagFormat dr;
615 bib1.class = CLASS_DIAGSET;
616 bib1.value = VAL_BIB1;
618 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
621 rec.which = Z_Records_NSD;
623 rec.u.nonSurrogateDiagnostic = &drec;
624 drec.which = Z_DiagRec_defaultFormat;
625 drec.u.defaultFormat = &dr;
627 rec.u.nonSurrogateDiagnostic = &dr;
629 dr.diagnosticSetId = oid_getoidbyent(&bib1);
631 dr.which = Z_DiagForm_v2AddInfo;
632 dr.addinfo = addinfo ? addinfo : "";
637 * surrogate diagnostic.
639 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
640 int error, char *addinfo)
642 static Z_NamePlusRecord rec;
646 static Z_DiagRec drec;
647 static Z_DefaultDiagFormat dr;
653 bib1.class = CLASS_DIAGSET;
654 bib1.value = VAL_BIB1;
656 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
658 rec.databaseName = dbname;
659 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
661 rec.u.surrogateDiagnostic = &drec;
662 drec.which = Z_DiagRec_defaultFormat;
663 drec.u.defaultFormat = &dr;
665 rec.u.surrogateDiagnostic = &dr;
667 dr.diagnosticSetId = oid_getoidbyent(&bib1);
669 dr.which = Z_DiagForm_v2AddInfo;
670 dr.addinfo = addinfo ? addinfo : "";
675 * multiple nonsurrogate diagnostics.
677 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
679 static Z_DiagRecs recs;
683 static Z_DiagRec *recp[1], drec;
684 static Z_DefaultDiagFormat rec;
686 static Z_DiagRec *recp[1], rec;
689 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
691 bib1.class = CLASS_DIAGSET;
692 bib1.value = VAL_BIB1;
695 recs.num_diagRecs = 1;
696 recs.diagRecs = recp;
699 drec.which = Z_DiagRec_defaultFormat;
700 drec.u.defaultFormat = &rec;
704 rec.diagnosticSetId = oid_getoidbyent(&bib1);
705 rec.condition = &err;
706 rec.which = Z_DiagForm_v2AddInfo;
707 rec.addinfo = addinfo ? addinfo : "";
711 #define MAX_RECORDS 256
713 static Z_Records *pack_records(association *a, char *setname, int start,
714 int *num, Z_ElementSetNames *esn,
715 int *next, int *pres)
717 int recno, total_length = 0, toget = *num;
718 static Z_Records records;
719 static Z_NamePlusRecordList reclist;
720 static Z_NamePlusRecord *list[MAX_RECORDS];
724 records.which = Z_Records_DBOSD;
725 records.u.databaseOrSurDiagnostics = &reclist;
726 reclist.num_records = 0;
727 reclist.records = list;
728 *pres = Z_PRES_SUCCESS;
732 recform.proto = a->proto;
733 recform.class = CLASS_RECSYN;
734 recform.value = VAL_USMARC;
735 if (!(oid = odr_oiddup(a->encode, oid_getoidbyent(&recform))))
738 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
739 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
740 a->maximumRecordSize);
741 for (recno = start; reclist.num_records < toget; recno++)
743 bend_fetchrequest freq;
744 bend_fetchresult *fres;
745 Z_NamePlusRecord *thisrec;
746 Z_DatabaseRecord *thisext;
748 if (reclist.num_records == MAX_RECORDS - 1)
750 *pres = Z_PRES_PARTIAL_2;
753 freq.setname = setname;
755 if (!(fres = bend_fetch(a->backend, &freq, 0)))
757 *pres = Z_PRES_FAILURE;
758 return diagrec(a->proto, 2, "Backend interface problem");
760 /* backend should be able to signal whether error is system-wide
761 or only pertaining to current record */
764 *pres = Z_PRES_FAILURE;
765 return diagrec(a->proto, fres->errcode, fres->errstring);
767 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
768 fres->len, total_length);
769 if (fres->len + total_length > a->preferredMessageSize)
771 /* record is small enough, really */
772 if (fres->len <= a->preferredMessageSize)
774 logf(LOG_DEBUG, " Dropped last normal-sized record");
775 *pres = Z_PRES_PARTIAL_2;
778 /* record can only be fetched by itself */
779 if (fres->len < a->maximumRecordSize)
781 logf(LOG_DEBUG, " Record > prefmsgsz");
784 logf(LOG_DEBUG, " Dropped it");
785 reclist.records[reclist.num_records] =
786 surrogatediagrec(a->proto, fres->basename, 16, 0);
787 reclist.num_records++;
788 total_length += 10; /* totally arbitrary */
792 else /* too big entirely */
794 logf(LOG_DEBUG, "Record > maxrcdsz");
795 reclist.records[reclist.num_records] =
796 surrogatediagrec(a->proto, fres->basename, 17, 0);
797 reclist.num_records++;
798 total_length += 10; /* totally arbitrary */
802 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
804 if (!(thisrec->databaseName = odr_malloc(a->encode,
805 strlen(fres->basename) + 1)))
807 strcpy(thisrec->databaseName, fres->basename);
808 thisrec->which = Z_NamePlusRecord_databaseRecord;
809 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
810 sizeof(Z_DatabaseRecord))))
812 thisext->direct_reference = oid; /* should be OID for current MARC */
813 thisext->indirect_reference = 0;
814 thisext->descriptor = 0;
815 thisext->which = ODR_EXTERNAL_octet;
816 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
819 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode, fres->len)))
821 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
822 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
824 reclist.records[reclist.num_records] = thisrec;
825 reclist.num_records++;
826 total_length += fres->len;
827 *next = fres->last_in_set ? 0 : recno + 1;
829 *num = reclist.num_records;
833 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
836 Z_SearchRequest *req = reqb->request->u.searchRequest;
837 bend_searchrequest bsrq;
838 bend_searchresult *bsrt;
840 logf(LOG_LOG, "Got SearchRequest.");
842 bsrq.setname = req->resultSetName;
843 bsrq.replace_set = *req->replaceIndicator;
844 bsrq.num_bases = req->num_databaseNames;
845 bsrq.basenames = req->databaseNames;
846 bsrq.query = req->query;
848 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
850 return response_searchRequest(assoc, reqb, bsrt, fd);
853 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
856 * Prepare a searchresponse based on the backend results. We probably want
857 * to look at making the fetching of records nonblocking as well, but
858 * so far, we'll keep things simple.
859 * If bsrt is null, that means we're called in response to a communications
860 * event, and we'll have to get the response for ourselves.
862 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
863 bend_searchresult *bsrt, int *fd)
865 Z_SearchRequest *req = reqb->request->u.searchRequest;
867 static Z_SearchResponse resp;
868 static int nulint = 0;
869 static bool_t sr = 1;
871 static int none = Z_RES_NONE;
873 apdu.which = Z_APDU_searchResponse;
874 apdu.u.searchResponse = &resp;
875 resp.referenceId = req->referenceId;
877 resp.additionalSearchInfo = 0;
881 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
883 logf(LOG_FATAL, "Bad result from backend");
886 else if (bsrt->errcode)
888 resp.records = diagrec(assoc->proto, bsrt->errcode,
890 resp.resultCount = &nulint;
891 resp.numberOfRecordsReturned = &nulint;
892 resp.nextResultSetPosition = &nulint;
893 resp.searchStatus = &nulint;
894 resp.resultSetStatus = &none;
895 resp.presentStatus = 0;
900 Z_ElementSetNames *setnames;
904 resp.resultCount = &bsrt->hits;
906 /* how many records does the user agent want, then? */
907 if (bsrt->hits <= *req->smallSetUpperBound)
910 setnames = req->smallSetElementSetNames;
912 else if (bsrt->hits < *req->largeSetLowerBound)
914 toget = *req->mediumSetPresentNumber;
915 if (toget > bsrt->hits)
917 setnames = req->mediumSetElementSetNames;
922 if (toget && !resp.records)
924 resp.records = pack_records(assoc, req->resultSetName, 1,
925 &toget, setnames, &next, &presst);
928 resp.numberOfRecordsReturned = &toget;
929 resp.nextResultSetPosition = &next;
930 resp.searchStatus = &sr;
931 resp.resultSetStatus = 0;
932 resp.presentStatus = &presst;
936 resp.numberOfRecordsReturned = &nulint;
937 resp.nextResultSetPosition = &next;
938 resp.searchStatus = &sr;
939 resp.resultSetStatus = 0;
940 resp.presentStatus = 0;
947 * Maybe we got a little over-friendly when we designed bend_fetch to
948 * get only one record at a time. Some backends can optimise multiple-record
949 * fetches, and at any rate, there is some overhead involved in
950 * all that selecting and hopping around. Problem is, of course, that the
951 * frontend can't know ahead of time how many records it'll need to
952 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
953 * is downright lousy as a bulk data transfer protocol.
955 * To start with, we'll do the fetching of records from the backend
956 * in one operation: To save some trips in and out of the event-handler,
957 * and to simplify the interface to pack_records. At any rate, asynch
958 * operation is more fun in operations that have an unpredictable execution
959 * speed - which is normally more true for search than for present.
961 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
964 Z_PresentRequest *req = reqb->request->u.presentRequest;
966 static Z_PresentResponse resp;
967 static int presst, next, num;
969 logf(LOG_LOG, "Got PresentRequest.");
970 apdu.which = Z_APDU_presentResponse;
971 apdu.u.presentResponse = &resp;
972 resp.referenceId = req->referenceId;
977 num = *req->numberOfRecordsRequested;
978 resp.records = pack_records(assoc, req->resultSetId,
979 *req->resultSetStartPoint, &num, 0, &next, &presst);
982 resp.numberOfRecordsReturned = #
983 resp.presentStatus = &presst;
984 resp.nextResultSetPosition = &next;
990 * Scan was implemented rather in a hurry, and with support for only the basic
991 * elements of the service in the backend API. Suggestions are welcome.
993 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
995 Z_ScanRequest *req = reqb->request->u.scanRequest;
997 static Z_ScanResponse res;
998 static int scanStatus = Z_Scan_failure;
999 static int numberOfEntriesReturned = 0;
1001 static Z_ListEntries ents;
1002 #define SCAN_MAX_ENTRIES 200
1003 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1004 bend_scanrequest srq;
1005 bend_scanresult *srs;
1007 logf(LOG_LOG, "Got scanrequest");
1008 apdu.which = Z_APDU_scanResponse;
1009 apdu.u.scanResponse = &res;
1010 res.referenceId = req->referenceId;
1012 res.scanStatus = &scanStatus;
1013 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1014 res.positionOfTerm = 0;
1015 res.entries = &ents;
1016 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1017 res.attributeSet = 0;
1022 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1023 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1024 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1025 else if (req->stepSize && *req->stepSize > 0)
1026 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1029 if (req->termListAndStartPoint->term->which == Z_Term_general)
1030 logf(LOG_DEBUG, " term: '%.*s'",
1031 req->termListAndStartPoint->term->u.general->len,
1032 req->termListAndStartPoint->term->u.general->buf);
1033 srq.num_bases = req->num_databaseNames;
1034 srq.basenames = req->databaseNames;
1035 srq.num_entries = *req->numberOfTermsRequested;
1036 srq.term = req->termListAndStartPoint;
1037 srq.term_position = req->preferredPositionInResponse ?
1038 *req->preferredPositionInResponse : 1;
1039 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1040 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1041 else if (srs->errcode)
1042 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1043 srs->errcode, srs->errstring);
1047 static Z_Entries list;
1049 if (srs->status == BEND_SCAN_PARTIAL)
1050 scanStatus = Z_Scan_partial_5;
1052 scanStatus = Z_Scan_success;
1053 ents.which = Z_ListEntries_entries;
1054 ents.u.entries = &list;
1056 for (i = 0; i < srs->num_entries; i++)
1062 if (i >= SCAN_MAX_ENTRIES)
1064 scanStatus = Z_Scan_partial_4;
1067 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1068 e->which = Z_Entry_termInfo;
1069 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1070 t->suggestedAttributes = 0;
1071 t->alternativeTerm = 0;
1072 t->byAttributes = 0;
1073 t->globalOccurrences = &srs->entries[i].occurrences;
1074 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1075 t->term->which = Z_Term_general;
1076 t->term->u.general = o = odr_malloc(assoc->encode,
1078 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1079 strlen(srs->entries[i].term));
1080 memcpy(o->buf, srs->entries[i].term, o->len);
1081 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1082 srs->entries[i].term, srs->entries[i].occurrences);
1084 list.num_entries = i;
1085 res.numberOfEntriesReturned = &list.num_entries;
1086 res.positionOfTerm = &srs->term_position;