2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.54 1995-11-08 15:11:29 quinn
8 * Log of close transmit.
10 * Revision 1.53 1995/11/01 13:54:58 quinn
13 * Revision 1.52 1995/11/01 12:19:13 quinn
14 * Second attempt to fix same bug.
16 * Revision 1.50 1995/10/25 16:58:32 quinn
19 * Revision 1.49 1995/10/16 13:51:53 quinn
20 * Changes to provide Especs to the backend.
22 * Revision 1.48 1995/10/06 08:51:20 quinn
25 * Revision 1.47 1995/08/29 14:24:16 quinn
26 * Added second half of close-handshake
28 * Revision 1.46 1995/08/29 11:17:58 quinn
29 * Added code to receive close
31 * Revision 1.45 1995/08/21 09:11:00 quinn
32 * Smallish fixes to suppport new formats.
34 * Revision 1.44 1995/08/17 12:45:25 quinn
35 * Fixed minor problems with GRS-1. Added support in c&s.
37 * Revision 1.43 1995/08/15 12:00:31 quinn
40 * Revision 1.42 1995/08/15 11:16:50 quinn
42 * Revision 1.41 1995/08/02 10:23:06 quinn
45 * Revision 1.40 1995/07/31 14:34:26 quinn
46 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
48 * Revision 1.39 1995/06/27 13:21:00 quinn
51 * Revision 1.38 1995/06/19 12:39:11 quinn
52 * Fixed bug in timeout code. Added BER dumper.
54 * Revision 1.37 1995/06/16 13:16:14 quinn
55 * Fixed Defaultdiagformat.
57 * Revision 1.36 1995/06/16 10:31:36 quinn
58 * Added session timeout.
60 * Revision 1.35 1995/06/15 07:45:14 quinn
63 * Revision 1.34 1995/06/14 15:26:46 quinn
64 * *** empty log message ***
66 * Revision 1.33 1995/06/06 14:57:05 quinn
69 * Revision 1.32 1995/06/06 08:41:44 quinn
72 * Revision 1.31 1995/06/06 08:15:37 quinn
75 * Revision 1.30 1995/06/05 10:53:32 quinn
76 * Added a better SCAN.
78 * Revision 1.29 1995/06/01 11:25:03 quinn
81 * Revision 1.28 1995/06/01 11:21:01 quinn
82 * Attempting to fix a bug in pack-records. replaced break with continue
83 * for large records, according to standard.
85 * Revision 1.27 1995/05/29 08:12:06 quinn
88 * Revision 1.26 1995/05/18 13:02:12 quinn
91 * Revision 1.25 1995/05/17 08:42:26 quinn
92 * Transfer auth info to backend. Allow backend to reject init gracefully.
94 * Revision 1.24 1995/05/16 08:51:04 quinn
95 * License, documentation, and memory fixes
97 * Revision 1.23 1995/05/15 13:25:10 quinn
100 * Revision 1.22 1995/05/15 11:56:39 quinn
101 * Asynchronous facilities. Restructuring of seshigh code.
103 * Revision 1.21 1995/05/02 08:53:19 quinn
104 * Trying in vain to fix comm with ISODE
106 * Revision 1.20 1995/04/20 15:13:00 quinn
109 * Revision 1.19 1995/04/18 08:15:34 quinn
110 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
111 * neater. We'll make the same change for decoding one day.
113 * Revision 1.18 1995/04/17 11:28:25 quinn
116 * Revision 1.17 1995/04/10 10:23:36 quinn
117 * Some work to add scan and other things.
119 * Revision 1.16 1995/03/31 09:18:55 quinn
122 * Revision 1.15 1995/03/30 14:03:23 quinn
123 * Added RFC1006 as separate library
125 * Revision 1.14 1995/03/30 12:18:17 quinn
128 * Revision 1.13 1995/03/30 09:09:24 quinn
129 * Added state-handle and some support for asynchronous activities.
131 * Revision 1.12 1995/03/29 15:40:16 quinn
132 * Ongoing work. Statserv is now dynamic by default
134 * Revision 1.11 1995/03/28 09:16:21 quinn
135 * Added record packing to the search request
137 * Revision 1.10 1995/03/27 08:34:24 quinn
138 * Added dynamic server functionality.
139 * Released bindings to session.c (is now redundant)
141 * Revision 1.9 1995/03/22 15:01:26 quinn
142 * Adjusting record packing.
144 * Revision 1.8 1995/03/22 10:13:21 quinn
145 * Working on record packer
147 * Revision 1.7 1995/03/21 15:53:31 quinn
150 * Revision 1.6 1995/03/21 12:30:09 quinn
151 * Beginning to add support for record packing.
153 * Revision 1.5 1995/03/17 10:44:13 quinn
154 * Added catch of null-string in makediagrec
156 * Revision 1.4 1995/03/17 10:18:08 quinn
157 * Added memory management.
159 * Revision 1.3 1995/03/16 17:42:39 quinn
162 * Revision 1.2 1995/03/16 13:29:01 quinn
163 * Partitioned server.
165 * Revision 1.1 1995/03/15 16:02:10 quinn
166 * Modded session.c to seshigh.c
171 * Frontend server logic.
173 * This code receives incoming APDUs, and handles client requests by means
174 * of the backend API.
176 * Some of the code is getting quite involved, compared to simpler servers -
177 * primarily because it is asynchronous both in the communication with
178 * the user and the backend. We think the complexity will pay off in
179 * the form of greater flexibility when more asynchronous facilities
182 * Memory management has become somewhat involved. In the simple case, where
183 * only one PDU is pending at a time, it will simply reuse the same memory,
184 * once it has found its working size. When we enable multiple concurrent
185 * operations, perhaps even with multiple parallel calls to the backend, it
186 * will maintain a pool of buffers for encoding and decoding, trying to
187 * minimize memory allocation/deallocation during normal operation.
189 * TODOs include (and will be done in order of public interest):
191 * Support for EXPLAIN - provide simple meta-database system.
192 * Support for access control.
193 * Support for resource control.
194 * Support for extended services - primarily Item Order.
195 * Rest of Z39.50-1994
203 #include <sys/time.h>
206 #include <comstack.h>
212 #include <statserv.h>
216 static int process_request(association *assoc);
217 void backend_response(IOCHAN i, int event);
218 static int process_response(association *assoc, request *req, Z_APDU *res);
219 static Z_APDU *process_initRequest(association *assoc, request *reqb);
220 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
222 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
223 bend_searchresult *bsrt, int *fd);
224 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
226 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
227 static void process_close(association *assoc, request *reqb);
229 static FILE *apduf = 0; /* for use in static mode */
230 static statserv_options_block *control_block = 0;
233 * Create and initialize a new association-handle.
234 * channel : iochannel for the current line.
235 * link : communications channel.
236 * Returns: 0 or a new association handle.
238 association *create_association(IOCHAN channel, COMSTACK link)
243 control_block = statserv_getcontrol();
244 if (!(new = xmalloc(sizeof(*new))))
246 new->client_chan = channel;
247 new->client_link = link;
248 if (!(new->decode = odr_createmem(ODR_DECODE)) ||
249 !(new->encode = odr_createmem(ODR_ENCODE)))
251 if (*control_block->apdufile)
256 strcpy(filename, control_block->apdufile);
257 if (!(new->print = odr_createmem(ODR_PRINT)))
259 if (*control_block->apdufile != '-')
261 strcpy(filename, control_block->apdufile);
262 if (!control_block->dynamic)
266 if (!(apduf = fopen(filename, "w")))
268 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
271 setvbuf(apduf, 0, _IONBF, 0);
277 sprintf(filename + strlen(filename), ".%d", getpid());
278 if (!(f = fopen(filename, "w")))
280 logf(LOG_WARN|LOG_ERRNO, "%s", filename);
283 setvbuf(f, 0, _IONBF, 0);
285 odr_setprint(new->print, f);
290 new->input_buffer = 0;
291 new->input_buffer_len = 0;
293 new->state = ASSOC_NEW;
294 request_initq(&new->incoming);
295 request_initq(&new->outgoing);
296 new->proto = cs_getproto(link);
301 * Free association and release resources.
303 void destroy_association(association *h)
305 odr_destroy(h->decode);
306 odr_destroy(h->encode);
308 odr_destroy(h->print);
310 xfree(h->input_buffer);
312 bend_close(h->backend);
313 while (request_deq(&h->incoming));
314 while (request_deq(&h->outgoing));
318 static void do_close(association *a, int reason, char *message)
321 Z_Close *cls = zget_Close(a->encode);
322 request *req = request_get();
324 /* Purge request queue */
325 while (request_deq(&a->incoming));
326 while (request_deq(&a->outgoing));
329 logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
330 reason, message ? message : "none");
331 apdu.which = Z_APDU_close;
333 *cls->closeReason = reason;
334 cls->diagnosticInformation = message;
335 process_response(a, req, &apdu);
336 iochan_settimeout(a->client_chan, 60);
340 logf(LOG_DEBUG, "v2 client. No Close PDU");
341 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
343 a->state = ASSOC_DEAD;
347 * This is where PDUs from the client are read and the further
348 * processing is initiated. Flow of control moves down through the
349 * various process_* functions below, until the encoded result comes back up
350 * to the output handler in here.
352 * h : the I/O channel that has an outstanding event.
353 * event : the current outstanding event.
355 void ir_session(IOCHAN h, int event)
358 association *assoc = iochan_getdata(h);
359 COMSTACK conn = assoc->client_link;
362 assert(h && conn && assoc);
363 if (event == EVENT_TIMEOUT)
365 if (assoc->state != ASSOC_UP)
367 logf(LOG_LOG, "Final timeout - closing connection.");
369 destroy_association(assoc);
374 logf(LOG_LOG, "Session idle too long. Sending close.");
375 do_close(assoc, Z_Close_lackOfActivity, 0);
379 if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
381 if (event & EVENT_INPUT)
383 logf(LOG_DEBUG, "ir_session (input)");
384 assert(assoc && conn);
385 /* We aren't speaking to this fellow */
386 if (assoc->state == ASSOC_DEAD)
388 logf(LOG_LOG, "Closed connection after reject");
390 destroy_association(assoc);
394 if ((res = cs_get(conn, &assoc->input_buffer,
395 &assoc->input_buffer_len)) <= 0)
397 logf(LOG_LOG, "Connection closed by client");
399 destroy_association(assoc);
403 else if (res == 1) /* incomplete read - wait for more */
405 if (cs_more(conn)) /* more stuff - call us again later, please */
406 iochan_setevent(h, EVENT_INPUT);
408 /* we got a complete PDU. Let's decode it */
409 logf(LOG_DEBUG, "Got PDU, %d bytes", res);
410 req = request_get(); /* get a new request structure */
411 odr_reset(assoc->decode);
412 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
413 if (!z_APDU(assoc->decode, &req->request, 0))
415 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
416 odr_errlist[odr_geterror(assoc->decode)],
417 odr_offset(assoc->decode));
418 logf(LOG_LOG, "PDU dump:");
419 odr_dumpBER(log_file(), assoc->input_buffer, res);
420 do_close(assoc, Z_Close_protocolError, "Malformed package");
423 req->request_mem = odr_extract_mem(assoc->decode);
424 if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
426 logf(LOG_WARN, "ODR print error: %s",
427 odr_errlist[odr_geterror(assoc->print)]);
428 odr_reset(assoc->print);
430 request_enq(&assoc->incoming, req);
433 /* can we do something yet? */
434 req = request_head(&assoc->incoming);
435 if (req->state == REQUEST_IDLE)
436 if (process_request(assoc) < 0)
437 do_close(assoc, Z_Close_systemProblem, "Unknown error");
439 if (event & EVENT_OUTPUT)
441 request *req = request_head(&assoc->outgoing);
443 logf(LOG_DEBUG, "ir_session (output)");
444 req->state = REQUEST_PENDING;
445 switch (res = cs_put(conn, req->response, req->len_response))
448 logf(LOG_LOG, "Connection closed by client");
450 destroy_association(assoc);
453 case 0: /* all sent - release the request structure */
454 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
455 odr_release_mem(req->request_mem);
456 request_deq(&assoc->outgoing);
457 request_release(req);
458 if (!request_head(&assoc->outgoing))
459 iochan_clearflag(h, EVENT_OUTPUT);
461 /* value of 1 -- partial send -- is simply ignored */
464 if (event & EVENT_EXCEPT)
466 logf(LOG_DEBUG, "ir_session (exception)");
468 destroy_association(assoc);
474 * Initiate request processing.
476 static int process_request(association *assoc)
478 request *req = request_head(&assoc->incoming);
482 logf(LOG_DEBUG, "process_request");
483 assert(req && req->state == REQUEST_IDLE);
484 switch (req->request->which)
486 case Z_APDU_initRequest:
487 res = process_initRequest(assoc, req); break;
488 case Z_APDU_searchRequest:
489 res = process_searchRequest(assoc, req, &fd); break;
490 case Z_APDU_presentRequest:
491 res = process_presentRequest(assoc, req, &fd); break;
492 case Z_APDU_scanRequest:
493 res = process_scanRequest(assoc, req, &fd); break;
495 process_close(assoc, req); return 0;
497 logf(LOG_WARN, "Bad APDU received");
502 logf(LOG_DEBUG, " result immediately available");
503 return process_response(assoc, req, res);
507 logf(LOG_WARN, " bad result");
510 else /* no result yet - one will be provided later */
514 /* Set up an I/O handler for the fd supplied by the backend */
516 logf(LOG_DEBUG, " establishing handler for result");
517 req->state = REQUEST_PENDING;
518 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
520 iochan_setdata(chan, assoc);
526 * Handle message from the backend.
528 void backend_response(IOCHAN i, int event)
530 association *assoc = iochan_getdata(i);
531 request *req = request_head(&assoc->incoming);
535 logf(LOG_DEBUG, "backend_response");
536 assert(assoc && req && req->state != REQUEST_IDLE);
537 /* determine what it is we're waiting for */
538 switch (req->request->which)
540 case Z_APDU_searchRequest:
541 res = response_searchRequest(assoc, req, 0, &fd); break;
543 case Z_APDU_presentRequest:
544 res = response_presentRequest(assoc, req, 0, &fd); break;
545 case Z_APDU_scanRequest:
546 res = response_scanRequest(assoc, req, 0, &fd); break;
549 logf(LOG_WARN, "Serious programmer's lapse or bug");
552 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
554 logf(LOG_LOG, "Fatal error when talking to backend");
555 do_close(assoc, Z_Close_systemProblem, 0);
559 else if (!res) /* no result yet - try again later */
561 logf(LOG_DEBUG, " no result yet");
562 iochan_setfd(i, fd); /* in case fd has changed */
567 * Encode response, and transfer the request structure to the outgoing queue.
569 static int process_response(association *assoc, request *req, Z_APDU *res)
571 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
572 if (!z_APDU(assoc->encode, &res, 0))
574 logf(LOG_WARN, "ODR error when encoding response: %s",
575 odr_errlist[odr_geterror(assoc->decode)]);
578 req->response = odr_getbuf(assoc->encode, &req->len_response,
579 &req->size_response);
580 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
581 odr_reset(assoc->encode);
582 if (assoc->print && !z_APDU(assoc->print, &res, 0))
584 logf(LOG_WARN, "ODR print error: %s",
585 odr_errlist[odr_geterror(assoc->print)]);
586 odr_reset(assoc->print);
588 /* change this when we make the backend reentrant */
589 if (req == request_head(&assoc->incoming))
591 req->state = REQUEST_IDLE;
592 request_deq(&assoc->incoming);
594 request_enq(&assoc->outgoing, req);
595 /* turn the work over to the ir_session handler */
596 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
597 /* Is there more work to be done? give that to the input handler too */
598 if (request_head(&assoc->incoming))
599 iochan_setevent(assoc->client_chan, EVENT_WORK);
604 * Handle init request.
605 * At the moment, we don't check the options
606 * anywhere else in the code - we just try not to do anything that would
607 * break a naive client. We'll toss 'em into the association block when
608 * we need them there.
610 static Z_APDU *process_initRequest(association *assoc, request *reqb)
612 Z_InitRequest *req = reqb->request->u.initRequest;
613 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
614 Z_InitResponse *resp = apdu->u.initResponse;
615 bend_initrequest binitreq;
616 bend_initresult *binitres;
619 logf(LOG_LOG, "Got initRequest");
620 if (req->implementationId)
621 logf(LOG_LOG, "Id: %s", req->implementationId);
622 if (req->implementationName)
623 logf(LOG_LOG, "Name: %s", req->implementationName);
624 if (req->implementationVersion)
625 logf(LOG_LOG, "Version: %s", req->implementationVersion);
627 binitreq.configname = "default-config";
628 binitreq.auth = req->idAuthentication;
629 if (!(binitres = bend_init(&binitreq)))
631 logf(LOG_WARN, "Bad response from backend.");
635 assoc->backend = binitres->handle;
636 resp->referenceId = req->referenceId;
638 /* let's tell the client what we can do */
639 if (ODR_MASK_GET(req->options, Z_Options_search))
641 ODR_MASK_SET(resp->options, Z_Options_search);
642 strcat(options, "srch");
644 if (ODR_MASK_GET(req->options, Z_Options_present))
646 ODR_MASK_SET(resp->options, Z_Options_present);
647 strcat(options, " prst");
650 if (ODR_MASK_GET(req->options, Z_Options_delSet))
652 ODR_MASK_SET(&options, Z_Options_delSet);
653 strcat(options, " del");
656 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
658 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
659 strcat(options, " namedresults");
661 if (ODR_MASK_GET(req->options, Z_Options_scan))
663 ODR_MASK_SET(resp->options, Z_Options_scan);
664 strcat(options, " scan");
666 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
668 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
669 strcat(options, " concurop");
672 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
674 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
675 assoc->version = 2; /* 1 & 2 are equivalent */
677 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
679 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
682 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
684 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
687 logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
688 assoc->maximumRecordSize = *req->maximumRecordSize;
689 if (assoc->maximumRecordSize > control_block->maxrecordsize)
690 assoc->maximumRecordSize = control_block->maxrecordsize;
691 assoc->preferredMessageSize = *req->preferredMessageSize;
692 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
693 assoc->preferredMessageSize = assoc->maximumRecordSize;
694 resp->preferredMessageSize = &assoc->preferredMessageSize;
695 resp->maximumRecordSize = &assoc->maximumRecordSize;
696 resp->implementationName = "Index Data/YAZ Generic Frontend Server";
697 if (binitres->errcode)
699 logf(LOG_LOG, "Connection rejected by backend.");
701 assoc->state = ASSOC_DEAD;
704 assoc->state = ASSOC_UP;
709 * These functions should be merged.
713 * nonsurrogate diagnostic record.
715 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
717 static Z_Records rec;
721 static Z_DiagRec drec;
722 static Z_DefaultDiagFormat dr;
728 bib1.class = CLASS_DIAGSET;
729 bib1.value = VAL_BIB1;
731 logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
734 rec.which = Z_Records_NSD;
736 rec.u.nonSurrogateDiagnostic = &drec;
737 drec.which = Z_DiagRec_defaultFormat;
738 drec.u.defaultFormat = &dr;
740 rec.u.nonSurrogateDiagnostic = &dr;
742 dr.diagnosticSetId = oid_getoidbyent(&bib1);
744 dr.which = Z_DiagForm_v2AddInfo;
745 dr.addinfo = addinfo ? addinfo : "";
750 * surrogate diagnostic.
752 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
753 int error, char *addinfo)
755 static Z_NamePlusRecord rec;
759 static Z_DiagRec drec;
760 static Z_DefaultDiagFormat dr;
766 bib1.class = CLASS_DIAGSET;
767 bib1.value = VAL_BIB1;
769 logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
771 rec.databaseName = dbname;
772 rec.which = Z_NamePlusRecord_surrogateDiagnostic;
774 rec.u.surrogateDiagnostic = &drec;
775 drec.which = Z_DiagRec_defaultFormat;
776 drec.u.defaultFormat = &dr;
778 rec.u.surrogateDiagnostic = &dr;
780 dr.diagnosticSetId = oid_getoidbyent(&bib1);
782 dr.which = Z_DiagForm_v2AddInfo;
783 dr.addinfo = addinfo ? addinfo : "";
788 * multiple nonsurrogate diagnostics.
790 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
792 static Z_DiagRecs recs;
796 static Z_DiagRec *recp[1], drec;
797 static Z_DefaultDiagFormat rec;
799 static Z_DiagRec *recp[1], rec;
802 logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
804 bib1.class = CLASS_DIAGSET;
805 bib1.value = VAL_BIB1;
808 recs.num_diagRecs = 1;
809 recs.diagRecs = recp;
812 drec.which = Z_DiagRec_defaultFormat;
813 drec.u.defaultFormat = &rec;
817 rec.diagnosticSetId = oid_getoidbyent(&bib1);
818 rec.condition = &err;
819 rec.which = Z_DiagForm_v2AddInfo;
820 rec.addinfo = addinfo ? addinfo : "";
824 #define MAX_RECORDS 256
826 static Z_Records *pack_records(association *a, char *setname, int start,
827 int *num, Z_RecordComposition *comp,
828 int *next, int *pres, oid_value format)
830 int recno, total_length = 0, toget = *num;
831 static Z_Records records;
832 static Z_NamePlusRecordList reclist;
833 static Z_NamePlusRecord *list[MAX_RECORDS];
836 records.which = Z_Records_DBOSD;
837 records.u.databaseOrSurDiagnostics = &reclist;
838 reclist.num_records = 0;
839 reclist.records = list;
840 *pres = Z_PRES_SUCCESS;
844 logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
845 logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
846 a->maximumRecordSize);
847 for (recno = start; reclist.num_records < toget; recno++)
849 bend_fetchrequest freq;
850 bend_fetchresult *fres;
851 Z_NamePlusRecord *thisrec;
852 Z_DatabaseRecord *thisext;
856 * we get the number of bytes allocated on the stream before any
857 * allocation done by the backend - this should give us a reasonable
858 * idea of the total size of the data so far.
860 total_length = odr_total(a->encode);
861 if (reclist.num_records == MAX_RECORDS - 1)
863 *pres = Z_PRES_PARTIAL_2;
866 freq.setname = setname;
869 freq.format = format;
870 freq.stream = a->encode;
871 if (!(fres = bend_fetch(a->backend, &freq, 0)))
873 *pres = Z_PRES_FAILURE;
874 return diagrec(a->proto, 2, "Backend interface problem");
876 /* backend should be able to signal whether error is system-wide
877 or only pertaining to current record */
880 *pres = Z_PRES_FAILURE;
881 return diagrec(a->proto, fres->errcode, fres->errstring);
884 this_length = fres->len;
886 this_length = odr_total(a->encode) - total_length;
887 logf(LOG_DEBUG, " fetched record, len=%d, total=%d",
888 this_length, total_length);
889 if (this_length + total_length > a->preferredMessageSize)
891 /* record is small enough, really */
892 if (this_length <= a->preferredMessageSize)
894 logf(LOG_DEBUG, " Dropped last normal-sized record");
895 *pres = Z_PRES_PARTIAL_2;
898 /* record can only be fetched by itself */
899 if (this_length < a->maximumRecordSize)
901 logf(LOG_DEBUG, " Record > prefmsgsz");
904 logf(LOG_DEBUG, " Dropped it");
905 reclist.records[reclist.num_records] =
906 surrogatediagrec(a->proto, fres->basename, 16, 0);
907 reclist.num_records++;
911 else /* too big entirely */
913 logf(LOG_DEBUG, "Record > maxrcdsz");
914 reclist.records[reclist.num_records] =
915 surrogatediagrec(a->proto, fres->basename, 17, 0);
916 reclist.num_records++;
920 if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
922 if (!(thisrec->databaseName = odr_malloc(a->encode,
923 strlen(fres->basename) + 1)))
925 strcpy(thisrec->databaseName, fres->basename);
926 thisrec->which = Z_NamePlusRecord_databaseRecord;
927 if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
928 sizeof(Z_DatabaseRecord))))
930 recform.proto = a->proto;
931 recform.class = CLASS_RECSYN;
932 recform.value = fres->format;
933 thisext->direct_reference = odr_oiddup(a->encode,
934 oid_getoidbyent(&recform));
935 thisext->indirect_reference = 0;
936 thisext->descriptor = 0;
937 if (fres->len < 0) /* Structured data */
939 switch (fres->format)
941 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
942 case VAL_GRS1: thisext->which = Z_External_grs1; break;
943 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
947 logf(LOG_FATAL, "Unknown structured format from backend.");
952 * We cheat on the pointers here. Obviously, the record field
953 * of the backend-fetch structure should have been a union for
954 * correctness, but we're stuck with this for backwards
957 thisext->u.grs1 = (Z_GenericRecord*) fres->record;
959 else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
961 Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
963 thisext->which = Z_External_sutrs;
964 thisext->u.sutrs = sutrs;
965 sutrs->buf = odr_malloc(a->encode, fres->len);
966 sutrs->len = sutrs->size = fres->len;
967 memcpy(sutrs->buf, fres->record, fres->len);
969 else /* octet-aligned record. */
971 thisext->which = Z_External_octet;
972 if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
975 if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
978 memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
979 thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
982 reclist.records[reclist.num_records] = thisrec;
983 reclist.num_records++;
984 *next = fres->last_in_set ? 0 : recno + 1;
986 *num = reclist.num_records;
990 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
993 Z_SearchRequest *req = reqb->request->u.searchRequest;
994 bend_searchrequest bsrq;
995 bend_searchresult *bsrt;
997 logf(LOG_LOG, "Got SearchRequest.");
999 bsrq.setname = req->resultSetName;
1000 bsrq.replace_set = *req->replaceIndicator;
1001 bsrq.num_bases = req->num_databaseNames;
1002 bsrq.basenames = req->databaseNames;
1003 bsrq.query = req->query;
1005 if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1007 return response_searchRequest(assoc, reqb, bsrt, fd);
1010 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1013 * Prepare a searchresponse based on the backend results. We probably want
1014 * to look at making the fetching of records nonblocking as well, but
1015 * so far, we'll keep things simple.
1016 * If bsrt is null, that means we're called in response to a communications
1017 * event, and we'll have to get the response for ourselves.
1019 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1020 bend_searchresult *bsrt, int *fd)
1022 Z_SearchRequest *req = reqb->request->u.searchRequest;
1024 static Z_SearchResponse resp;
1025 static int nulint = 0;
1026 static bool_t sr = 1;
1027 static int next = 0;
1028 static int none = Z_RES_NONE;
1030 apdu.which = Z_APDU_searchResponse;
1031 apdu.u.searchResponse = &resp;
1032 resp.referenceId = req->referenceId;
1034 resp.additionalSearchInfo = 0;
1038 if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1040 logf(LOG_FATAL, "Bad result from backend");
1043 else if (bsrt->errcode)
1045 resp.records = diagrec(assoc->proto, bsrt->errcode,
1047 resp.resultCount = &nulint;
1048 resp.numberOfRecordsReturned = &nulint;
1049 resp.nextResultSetPosition = &nulint;
1050 resp.searchStatus = &nulint;
1051 resp.resultSetStatus = &none;
1052 resp.presentStatus = 0;
1057 Z_RecordComposition comp, *compp = 0;
1058 static int presst = 0;
1061 resp.resultCount = &bsrt->hits;
1063 comp.which = Z_RecordComp_simple;
1064 /* how many records does the user agent want, then? */
1065 if (bsrt->hits <= *req->smallSetUpperBound)
1068 if ((comp.u.simple = req->smallSetElementSetNames))
1071 else if (bsrt->hits < *req->largeSetLowerBound)
1073 toget = *req->mediumSetPresentNumber;
1074 if (toget > bsrt->hits)
1076 if ((comp.u.simple = req->mediumSetElementSetNames))
1082 if (toget && !resp.records)
1087 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1088 prefformat->class != CLASS_RECSYN)
1091 form = prefformat->value;
1092 resp.records = pack_records(assoc, req->resultSetName, 1,
1093 &toget, compp, &next, &presst, form);
1096 resp.numberOfRecordsReturned = &toget;
1097 resp.nextResultSetPosition = &next;
1098 resp.searchStatus = &sr;
1099 resp.resultSetStatus = 0;
1100 resp.presentStatus = &presst;
1104 if (*resp.resultCount)
1106 resp.numberOfRecordsReturned = &nulint;
1107 resp.nextResultSetPosition = &next;
1108 resp.searchStatus = &sr;
1109 resp.resultSetStatus = 0;
1110 resp.presentStatus = 0;
1117 * Maybe we got a little over-friendly when we designed bend_fetch to
1118 * get only one record at a time. Some backends can optimise multiple-record
1119 * fetches, and at any rate, there is some overhead involved in
1120 * all that selecting and hopping around. Problem is, of course, that the
1121 * frontend can't know ahead of time how many records it'll need to
1122 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1123 * is downright lousy as a bulk data transfer protocol.
1125 * To start with, we'll do the fetching of records from the backend
1126 * in one operation: To save some trips in and out of the event-handler,
1127 * and to simplify the interface to pack_records. At any rate, asynch
1128 * operation is more fun in operations that have an unpredictable execution
1129 * speed - which is normally more true for search than for present.
1131 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1134 Z_PresentRequest *req = reqb->request->u.presentRequest;
1136 static Z_PresentResponse resp;
1137 static int presst, next, num;
1142 logf(LOG_LOG, "Got PresentRequest.");
1143 apdu.which = Z_APDU_presentResponse;
1144 apdu.u.presentResponse = &resp;
1145 resp.referenceId = req->referenceId;
1150 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1151 prefformat->class != CLASS_RECSYN)
1154 form = prefformat->value;
1155 num = *req->numberOfRecordsRequested;
1156 resp.records = pack_records(assoc, req->resultSetId,
1157 *req->resultSetStartPoint, &num, req->recordComposition, &next,
1161 resp.numberOfRecordsReturned = #
1162 resp.presentStatus = &presst;
1163 resp.nextResultSetPosition = &next;
1169 * Scan was implemented rather in a hurry, and with support for only the basic
1170 * elements of the service in the backend API. Suggestions are welcome.
1172 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1174 Z_ScanRequest *req = reqb->request->u.scanRequest;
1176 static Z_ScanResponse res;
1177 static int scanStatus = Z_Scan_failure;
1178 static int numberOfEntriesReturned = 0;
1180 static Z_ListEntries ents;
1181 #define SCAN_MAX_ENTRIES 200
1182 static Z_Entry *tab[SCAN_MAX_ENTRIES];
1183 bend_scanrequest srq;
1184 bend_scanresult *srs;
1186 logf(LOG_LOG, "Got scanrequest");
1187 apdu.which = Z_APDU_scanResponse;
1188 apdu.u.scanResponse = &res;
1189 res.referenceId = req->referenceId;
1191 res.scanStatus = &scanStatus;
1192 res.numberOfEntriesReturned = &numberOfEntriesReturned;
1193 res.positionOfTerm = 0;
1194 res.entries = &ents;
1195 ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1196 res.attributeSet = 0;
1201 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1202 attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1203 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1204 else if (req->stepSize && *req->stepSize > 0)
1205 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1208 if (req->termListAndStartPoint->term->which == Z_Term_general)
1209 logf(LOG_DEBUG, " term: '%.*s'",
1210 req->termListAndStartPoint->term->u.general->len,
1211 req->termListAndStartPoint->term->u.general->buf);
1212 srq.num_bases = req->num_databaseNames;
1213 srq.basenames = req->databaseNames;
1214 srq.num_entries = *req->numberOfTermsRequested;
1215 srq.term = req->termListAndStartPoint;
1216 srq.term_position = req->preferredPositionInResponse ?
1217 *req->preferredPositionInResponse : 1;
1218 if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1219 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1220 else if (srs->errcode)
1221 ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1222 srs->errcode, srs->errstring);
1226 static Z_Entries list;
1228 if (srs->status == BEND_SCAN_PARTIAL)
1229 scanStatus = Z_Scan_partial_5;
1231 scanStatus = Z_Scan_success;
1232 ents.which = Z_ListEntries_entries;
1233 ents.u.entries = &list;
1235 for (i = 0; i < srs->num_entries; i++)
1241 if (i >= SCAN_MAX_ENTRIES)
1243 scanStatus = Z_Scan_partial_4;
1246 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1247 e->which = Z_Entry_termInfo;
1248 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1249 t->suggestedAttributes = 0;
1250 t->alternativeTerm = 0;
1251 t->byAttributes = 0;
1252 t->globalOccurrences = &srs->entries[i].occurrences;
1253 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1254 t->term->which = Z_Term_general;
1255 t->term->u.general = o = odr_malloc(assoc->encode,
1257 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1258 strlen(srs->entries[i].term));
1259 memcpy(o->buf, srs->entries[i].term, o->len);
1260 logf(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1261 srs->entries[i].term, srs->entries[i].occurrences);
1263 list.num_entries = i;
1264 res.numberOfEntriesReturned = &list.num_entries;
1265 res.positionOfTerm = &srs->term_position;
1272 static void process_close(association *assoc, request *reqb)
1274 Z_Close *req = reqb->request->u.close;
1275 static char *reasons[] =
1282 "securityViolation",
1289 logf(LOG_LOG, "Got close, reason %s, message %s",
1290 reasons[*req->closeReason], req->diagnosticInformation ?
1291 req->diagnosticInformation : "NULL");
1292 if (assoc->version < 3) /* to make do_force respond with close */
1294 do_close(assoc, Z_Close_finished, "Association terminated by client");