License, documentation, and memory fixes
[yaz-moved-to-github.git] / server / seshigh.c
1 /*
2  * Copyright (c) 1995, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: seshigh.c,v $
7  * Revision 1.24  1995-05-16 08:51:04  quinn
8  * License, documentation, and memory fixes
9  *
10  * Revision 1.23  1995/05/15  13:25:10  quinn
11  * Fixed memory bug.
12  *
13  * Revision 1.22  1995/05/15  11:56:39  quinn
14  * Asynchronous facilities. Restructuring of seshigh code.
15  *
16  * Revision 1.21  1995/05/02  08:53:19  quinn
17  * Trying in vain to fix comm with ISODE
18  *
19  * Revision 1.20  1995/04/20  15:13:00  quinn
20  * Cosmetic
21  *
22  * Revision 1.19  1995/04/18  08:15:34  quinn
23  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
24  * neater. We'll make the same change for decoding one day.
25  *
26  * Revision 1.18  1995/04/17  11:28:25  quinn
27  * Smallish
28  *
29  * Revision 1.17  1995/04/10  10:23:36  quinn
30  * Some work to add scan and other things.
31  *
32  * Revision 1.16  1995/03/31  09:18:55  quinn
33  * Added logging.
34  *
35  * Revision 1.15  1995/03/30  14:03:23  quinn
36  * Added RFC1006 as separate library
37  *
38  * Revision 1.14  1995/03/30  12:18:17  quinn
39  * Fixed bug.
40  *
41  * Revision 1.13  1995/03/30  09:09:24  quinn
42  * Added state-handle and some support for asynchronous activities.
43  *
44  * Revision 1.12  1995/03/29  15:40:16  quinn
45  * Ongoing work. Statserv is now dynamic by default
46  *
47  * Revision 1.11  1995/03/28  09:16:21  quinn
48  * Added record packing to the search request
49  *
50  * Revision 1.10  1995/03/27  08:34:24  quinn
51  * Added dynamic server functionality.
52  * Released bindings to session.c (is now redundant)
53  *
54  * Revision 1.9  1995/03/22  15:01:26  quinn
55  * Adjusting record packing.
56  *
57  * Revision 1.8  1995/03/22  10:13:21  quinn
58  * Working on record packer
59  *
60  * Revision 1.7  1995/03/21  15:53:31  quinn
61  * Little changes.
62  *
63  * Revision 1.6  1995/03/21  12:30:09  quinn
64  * Beginning to add support for record packing.
65  *
66  * Revision 1.5  1995/03/17  10:44:13  quinn
67  * Added catch of null-string in makediagrec
68  *
69  * Revision 1.4  1995/03/17  10:18:08  quinn
70  * Added memory management.
71  *
72  * Revision 1.3  1995/03/16  17:42:39  quinn
73  * Little changes
74  *
75  * Revision 1.2  1995/03/16  13:29:01  quinn
76  * Partitioned server.
77  *
78  * Revision 1.1  1995/03/15  16:02:10  quinn
79  * Modded session.c to seshigh.c
80  *
81  */
82
83 /*
84  * Frontend server logic.
85  *
86  * This code receives incoming APDUs, and handles client requests by means
87  * of the backend API.
88  *
89  * Some of the code is getting quite involved, compared to simpler servers -
90  * primarily because it is asynchronous both in the communication with
91  * the user and the backend. We think the complexity will pay off in
92  * the form of greater flexibility when more asynchronous facilities
93  * are implemented.
94  *
95  * Memory management has become somewhat involved. In the simple case, where
96  * only one PDU is pending at a time, it will simply reuse the same memory,
97  * once it has found its working size. When we enable multiple concurrent
98  * operations, perhaps even with multiple parallel calls to the backend, it
99  * will maintain a pool of buffers for encoding and decoding, trying to
100  * minimize memory allocation/deallocation during normal operation.
101  *
102  * TODOs include (and will be done in order of public interest):
103  * 
104  * Support for EXPLAIN - provide simple meta-database system.
105  * Support for access control.
106  * Support for resource control.
107  * Support for extended services - primarily Item Order.
108  * Rest of Z39.50-1994
109  *
110  */
111
112 #include <stdlib.h>
113 #include <stdio.h>
114 #include <unistd.h>
115 #include <assert.h>
116
117 #include <dmalloc.h>
118 #include <comstack.h>
119 #include <eventl.h>
120 #include <session.h>
121 #include <proto.h>
122 #include <oid.h>
123 #include <log.h>
124 #include <statserv.h>
125 #include "../version.h"
126
127 #include <backend.h>
128
129 static int process_request(association *assoc);
130 void backend_response(IOCHAN i, int event);
131 static int process_response(association *assoc, request *req, Z_APDU *res);
132 static Z_APDU *process_initRequest(association *assoc, request *reqb);
133 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
134     int *fd);
135 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
136     bend_searchresult *bsrt, int *fd);
137 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
138     int *fd);
139 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
140
141 static FILE *apduf = 0; /* for use in static mode */
142 static statserv_options_block *control_block = 0;
143
144 /*
145  * Create and initialize a new association-handle.
146  *  channel  : iochannel for the current line.
147  *  link     : communications channel.
148  * Returns: 0 or a new association handle.
149  */
150 association *create_association(IOCHAN channel, COMSTACK link)
151 {
152     association *new;
153
154     if (!control_block)
155         control_block = statserv_getcontrol();
156     if (!(new = malloc(sizeof(*new))))
157         return 0;
158     new->client_chan = channel;
159     new->client_link = link;
160     if (!(new->decode = odr_createmem(ODR_DECODE)) ||
161         !(new->encode = odr_createmem(ODR_ENCODE)))
162         return 0;
163     if (*control_block->apdufile)
164     {
165         char filename[256];
166         FILE *f;
167
168         strcpy(filename, control_block->apdufile);
169         if (!(new->print = odr_createmem(ODR_PRINT)))
170             return 0;
171         if (*control_block->apdufile != '-')
172         {
173             strcpy(filename, control_block->apdufile);
174             if (!control_block->dynamic)
175             {
176                 if (!apduf)
177                 {
178                     if (!(apduf = fopen(filename, "w")))
179                     {
180                         logf(LOG_WARN|LOG_ERRNO, "%s", filename);
181                         return 0;
182                     }
183                     setvbuf(apduf, 0, _IONBF, 0);
184                 }
185                 f = apduf;
186             }
187             else 
188             {
189                 sprintf(filename + strlen(filename), ".%d", getpid());
190                 if (!(f = fopen(filename, "w")))
191                 {
192                     logf(LOG_WARN|LOG_ERRNO, "%s", filename);
193                     return 0;
194                 }
195                 setvbuf(f, 0, _IONBF, 0);
196             }
197             odr_setprint(new->print, f);
198         }
199     }
200     else
201         new->print = 0;
202     new->input_buffer = 0;
203     new->input_buffer_len = 0;
204     new->backend = 0;
205     request_initq(&new->incoming);
206     request_initq(&new->outgoing);
207     if (cs_getproto(link) == CS_Z3950)
208         new->proto = PROTO_Z3950;
209     else
210         new->proto = PROTO_SR;
211     return new;
212 }
213
214 /*
215  * Free association and release resources.
216  */
217 void destroy_association(association *h)
218 {
219     odr_destroy(h->decode);
220     odr_destroy(h->encode);
221     if (h->print)
222         odr_destroy(h->print);
223     if (h->input_buffer)
224         free(h->input_buffer);
225     if (h->backend)
226         bend_close(h->backend);
227     while (request_deq(&h->incoming));
228     while (request_deq(&h->outgoing));
229     free(h);
230 }
231
232 /*
233  * This is where PDUs from the client are read and the further
234  * processing is initiated. Flow of control moves down through the
235  * various process_* functions below, until the encoded result comes back up
236  * to the output handler in here.
237  * 
238  *  h     : the I/O channel that has an outstanding event.
239  *  event : the current outstanding event.
240  */
241 void ir_session(IOCHAN h, int event)
242 {
243     int res;
244     association *assoc = iochan_getdata(h);
245     COMSTACK conn = assoc->client_link;
246     request *req;
247
248     assert(h && conn && assoc);
249     if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
250     {
251         if (event & EVENT_INPUT)
252         {
253             logf(LOG_DEBUG, "ir_session (input)");
254             assert(assoc && conn);
255             if ((res = cs_get(conn, &assoc->input_buffer,
256                 &assoc->input_buffer_len)) <= 0)
257             {
258                 logf(LOG_LOG, "Connection closed by client");
259                 cs_close(conn);
260                 destroy_association(assoc);
261                 iochan_destroy(h);
262                 return;
263             }
264             else if (res == 1) /* incomplete read - wait for more  */
265                 return;
266             if (cs_more(conn)) /* more stuff - call us again later, please */
267                 iochan_setevent(h, EVENT_INPUT);
268                 
269             /* we got a complete PDU. Let's decode it */
270             req = request_get(); /* get a new request structure */
271             odr_reset(assoc->decode);
272             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
273             if (!z_APDU(assoc->decode, &req->request, 0))
274             {
275                 logf(LOG_WARN, "ODR error: %s",
276                     odr_errlist[odr_geterror(assoc->decode)]);
277                 cs_close(conn);
278                 destroy_association(assoc);
279                 iochan_destroy(h);
280                 return;
281             }
282             req->request_mem = odr_extract_mem(assoc->decode);
283             if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
284             {
285                 logf(LOG_WARN, "ODR print error: %s", 
286                     odr_errlist[odr_geterror(assoc->print)]);
287                 odr_reset(assoc->print);
288             }
289             request_enq(&assoc->incoming, req);
290         }
291
292         /* can we do something yet? */
293         req = request_head(&assoc->incoming);
294         if (req->state == REQUEST_IDLE)
295             if (process_request(assoc) < 0)
296             {
297                 cs_close(conn);
298                 destroy_association(assoc);
299                 iochan_destroy(h);
300             }
301     }
302     if (event & EVENT_OUTPUT)
303     {
304         request *req = request_head(&assoc->outgoing);
305
306         logf(LOG_DEBUG, "ir_session (output)");
307         req->state = REQUEST_PENDING;
308         switch (res = cs_put(conn, req->response, req->len_response))
309         {
310             case -1:
311                 logf(LOG_LOG, "Connection closed by client");
312                 cs_close(conn);
313                 destroy_association(assoc);
314                 iochan_destroy(h);
315                 break;
316             case 0: /* all sent - release the request structure */
317                 odr_release_mem(req->request_mem);
318                 request_deq(&assoc->outgoing);
319                 request_release(req);
320                 if (!request_head(&assoc->outgoing))
321                     iochan_clearflag(h, EVENT_OUTPUT);
322                 break;
323             /* value of 1 -- partial send -- is simply ignored */
324         }
325     }
326     if (event & EVENT_EXCEPT)
327     {
328         logf(LOG_DEBUG, "ir_session (exception)");
329         cs_close(conn);
330         destroy_association(assoc);
331         iochan_destroy(h);
332     }
333 }
334
335 /*
336  * Initiate request processing.
337  */
338 static int process_request(association *assoc)
339 {
340     request *req = request_head(&assoc->incoming);
341     int fd = -1;
342     Z_APDU *res;
343
344     logf(LOG_DEBUG, "process_request");
345     assert(req && req->state == REQUEST_IDLE);
346     switch (req->request->which)
347     {
348         case Z_APDU_initRequest:
349             res = process_initRequest(assoc, req); break;
350         case Z_APDU_searchRequest:
351             res = process_searchRequest(assoc, req, &fd); break;
352         case Z_APDU_presentRequest:
353             res = process_presentRequest(assoc, req, &fd); break;
354         case Z_APDU_scanRequest:
355             res = process_scanRequest(assoc, req, &fd); break;
356         default:
357             logf(LOG_WARN, "Bad APDU");
358             return -1;
359     }
360     if (res)
361     {
362         logf(LOG_DEBUG, "  result immediately available");
363         return process_response(assoc, req, res);
364     }
365     else if (fd < 0)
366     {
367         logf(LOG_WARN, "   bad result");
368         return -1;
369     }
370     else /* no result yet - one will be provided later */
371     {
372         IOCHAN chan;
373
374         /* Set up an I/O handler for the fd supplied by the backend */
375
376         logf(LOG_DEBUG, "   establishing handler for result");
377         req->state = REQUEST_PENDING;
378         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
379             abort();
380         iochan_setdata(chan, assoc);
381         return 0;
382     }
383 }
384
385 /*
386  * Handle message from the backend.
387  */
388 void backend_response(IOCHAN i, int event)
389 {
390     association *assoc = iochan_getdata(i);
391     request *req = request_head(&assoc->incoming);
392     Z_APDU *res;
393     int fd;
394
395     logf(LOG_DEBUG, "backend_response");
396     assert(assoc && req && req->state != REQUEST_IDLE);
397     /* determine what it is we're waiting for */
398     switch (req->request->which)
399     {
400         case Z_APDU_searchRequest:
401             res = response_searchRequest(assoc, req, 0, &fd); break;
402 #if 0
403         case Z_APDU_presentRequest:
404             res = response_presentRequest(assoc, req, 0, &fd); break;
405         case Z_APDU_scanRequest:
406             res = response_scanRequest(assoc, req, 0, &fd); break;
407 #endif
408         default:
409             logf(LOG_WARN, "Serious programmer's lapse or bug");
410             abort();
411     }
412     if ((res && process_response(assoc, req, res) < 0) || fd < 0)
413     {
414         logf(LOG_LOG, "Fatal error when talking to backend");
415         cs_close(assoc->client_link);
416         destroy_association(assoc);
417         iochan_destroy(assoc->client_chan);
418         iochan_destroy(i);
419         return;
420     }
421     else if (!res) /* no result yet - try again later */
422     {
423         logf(LOG_DEBUG, "   no result yet");
424         iochan_setfd(i, fd); /* in case fd has changed */
425     }
426 }
427
428 /*
429  * Encode response, and transfer the request structure to the outgoing queue.
430  */
431 static int process_response(association *assoc, request *req, Z_APDU *res)
432 {
433     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
434     if (!z_APDU(assoc->encode, &res, 0))
435     {
436         logf(LOG_WARN, "ODR error when encoding response: %s",
437             odr_errlist[odr_geterror(assoc->decode)]);
438         return -1;
439     }
440     req->response = odr_getbuf(assoc->encode, &req->len_response,
441         &req->size_response);
442     odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we have to quit */
443     odr_reset(assoc->encode);
444     if (assoc->print && !z_APDU(assoc->print, &res, 0))
445     {
446         logf(LOG_WARN, "ODR print error: %s", 
447             odr_errlist[odr_geterror(assoc->print)]);
448         odr_reset(assoc->print);
449     }
450     /* change this when we make the backend reentrant */
451     assert(req == request_head(&assoc->incoming));
452     req->state = REQUEST_IDLE;
453     request_deq(&assoc->incoming);
454     request_enq(&assoc->outgoing, req);
455     /* turn the work over to the ir_session handler */
456     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
457     /* Is there more work to be done? */
458     if (request_head(&assoc->incoming))
459         iochan_setevent(assoc->client_chan, EVENT_WORK);
460     return 0;
461 }
462
463 static Z_APDU *process_initRequest(association *assoc, request *reqb)
464 {
465     Z_InitRequest *req = reqb->request->u.initRequest;
466     static Z_APDU apdu;
467     static Z_InitResponse resp;
468     static bool_t result = 1;
469     static Odr_bitmask options, protocolVersion;
470     bend_initrequest binitreq;
471     bend_initresult *binitres;
472
473     logf(LOG_LOG, "Got initRequest");
474     if (req->implementationId)
475         logf(LOG_LOG, "Id:        %s", req->implementationId);
476     if (req->implementationName)
477         logf(LOG_LOG, "Name:      %s", req->implementationName);
478     if (req->implementationVersion)
479         logf(LOG_LOG, "Version:   %s", req->implementationVersion);
480
481     binitreq.configname = "default-config";
482     if (!(binitres = bend_init(&binitreq)) || binitres->errcode)
483     {
484         logf(LOG_WARN, "Negative response from backend");
485         return 0;
486     }
487
488     assoc->backend = binitres->handle;
489     apdu.which = Z_APDU_initResponse;
490     apdu.u.initResponse = &resp;
491     resp.referenceId = req->referenceId;
492     /* let's tell the client what we can do */
493     ODR_MASK_ZERO(&options);
494     if (ODR_MASK_GET(req->options, Z_Options_search))
495         ODR_MASK_SET(&options, Z_Options_search);
496     if (ODR_MASK_GET(req->options, Z_Options_present))
497         ODR_MASK_SET(&options, Z_Options_present);
498 #if 0
499     if (ODR_MASK_GET(req->options, Z_Options_delSet))
500         ODR_MASK_SET(&options, Z_Options_delSet);
501 #endif
502     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
503         ODR_MASK_SET(&options, Z_Options_namedResultSets);
504     if (ODR_MASK_GET(req->options, Z_Options_scan))
505         ODR_MASK_SET(&options, Z_Options_scan);
506     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
507         ODR_MASK_SET(&options, Z_Options_concurrentOperations);
508     resp.options = &options;
509
510     ODR_MASK_ZERO(&protocolVersion);
511     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
512         ODR_MASK_SET(&protocolVersion, Z_ProtocolVersion_1);
513     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
514         ODR_MASK_SET(&protocolVersion, Z_ProtocolVersion_2);
515     resp.protocolVersion = &protocolVersion;
516     assoc->maximumRecordSize = *req->maximumRecordSize;
517     if (assoc->maximumRecordSize > control_block->maxrecordsize)
518         assoc->maximumRecordSize = control_block->maxrecordsize;
519     assoc->preferredMessageSize = *req->preferredMessageSize;
520     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
521         assoc->preferredMessageSize = assoc->maximumRecordSize;
522     resp.preferredMessageSize = &assoc->preferredMessageSize;
523     resp.maximumRecordSize = &assoc->maximumRecordSize;
524     resp.result = &result;
525     resp.implementationId = "YAZ";
526     resp.implementationName = "Index Data/YAZ Generic Frontend Server";
527     resp.implementationVersion = YAZ_VERSION;
528     resp.userInformationField = 0;
529     return &apdu;
530 }
531
532 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
533 {
534     static Z_Records rec;
535     oident bib1;
536     static Z_DiagRec dr;
537     static int err;
538
539     bib1.proto = proto;
540     bib1.class = CLASS_DIAGSET;
541     bib1.value = VAL_BIB1;
542
543     logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
544         "NULL");
545     err = error;
546     rec.which = Z_Records_NSD;
547     rec.u.nonSurrogateDiagnostic = &dr;
548     dr.diagnosticSetId = oid_getoidbyent(&bib1);
549     dr.condition = &err;
550     dr.addinfo = addinfo ? addinfo : "";
551     return &rec;
552 }
553
554 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
555                                             int error, char *addinfo)
556 {
557     static Z_NamePlusRecord rec;
558     static Z_DiagRec dr;
559     static int err;
560     oident bib1;
561
562     bib1.proto = proto;
563     bib1.class = CLASS_DIAGSET;
564     bib1.value = VAL_BIB1;
565
566     logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
567     err = error;
568     rec.databaseName = dbname;
569     rec.which = Z_NamePlusRecord_surrogateDiagnostic;
570     rec.u.surrogateDiagnostic = &dr;
571     dr.diagnosticSetId = oid_getoidbyent(&bib1);
572     dr.condition = &err;
573     dr.addinfo = addinfo ? addinfo : "";
574     return &rec;
575 }
576
577 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
578 {
579     static Z_DiagRecs recs;
580     static Z_DiagRec *recp[1], rec;
581     static int err;
582     oident bib1;
583
584     logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
585     bib1.proto = proto;
586     bib1.class = CLASS_DIAGSET;
587     bib1.value = VAL_BIB1;
588
589     err = error;
590     recs.num_diagRecs = 1;
591     recs.diagRecs = recp;
592     recp[0] = &rec;
593     rec.diagnosticSetId = oid_getoidbyent(&bib1);
594     rec.condition = &err;
595     rec.addinfo = addinfo ? addinfo : "";
596     return &recs;
597 }
598
599 #define MAX_RECORDS 256
600
601 static Z_Records *pack_records(association *a, char *setname, int start,
602                                 int *num, Z_ElementSetNames *esn,
603                                 int *next, int *pres)
604 {
605     int recno, total_length = 0, toget = *num;
606     static Z_Records records;
607     static Z_NamePlusRecordList reclist;
608     static Z_NamePlusRecord *list[MAX_RECORDS];
609     oident recform;
610     Odr_oid *oid;
611
612     records.which = Z_Records_DBOSD;
613     records.u.databaseOrSurDiagnostics = &reclist;
614     reclist.num_records = 0;
615     reclist.records = list;
616     *pres = Z_PRES_SUCCESS;
617     *num = 0;
618     *next = 0;
619
620     recform.proto = a->proto;
621     recform.class = CLASS_RECSYN;
622     recform.value = VAL_USMARC;
623     if (!(oid = odr_oiddup(a->encode, oid_getoidbyent(&recform))))
624         return 0;
625
626     logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
627     logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
628         a->maximumRecordSize);
629     for (recno = start; reclist.num_records < toget; recno++)
630     {
631         bend_fetchrequest freq;
632         bend_fetchresult *fres;
633         Z_NamePlusRecord *thisrec;
634         Z_DatabaseRecord *thisext;
635
636         if (reclist.num_records == MAX_RECORDS - 1)
637         {
638             *pres = Z_PRES_PARTIAL_2;
639             break;
640         }
641         freq.setname = setname;
642         freq.number = recno;
643         if (!(fres = bend_fetch(a->backend, &freq, 0)))
644         {
645             *pres = Z_PRES_FAILURE;
646             return diagrec(a->proto, 2, "Backend interface problem");
647         }
648         /* backend should be able to signal whether error is system-wide
649            or only pertaining to current record */
650         if (fres->errcode)
651         {
652             *pres = Z_PRES_FAILURE;
653             return diagrec(a->proto, fres->errcode, fres->errstring);
654         }
655         logf(LOG_DEBUG, "  fetched record, len=%d, total=%d",
656             fres->len, total_length);
657         if (fres->len + total_length > a->preferredMessageSize)
658         {
659             /* record is small enough, really */
660             if (fres->len <= a->preferredMessageSize)
661             {
662                 logf(LOG_DEBUG, "  Dropped last normal-sized record");
663                 *pres = Z_PRES_PARTIAL_2;
664                 break;
665             }
666             /* record can only be fetched by itself */
667             if (fres->len < a->maximumRecordSize)
668             {
669                 logf(LOG_DEBUG, "  Record > prefmsgsz");
670                 if (toget > 1)
671                 {
672                     logf(LOG_DEBUG, "  Dropped it");
673                     reclist.records[reclist.num_records] =
674                          surrogatediagrec(a->proto, fres->basename, 16, 0);
675                     reclist.num_records++;
676                     *pres = Z_PRES_PARTIAL_2;
677                     break;
678                 }
679             }
680             else /* too big entirely */
681             {
682                 logf(LOG_DEBUG, "Record > maxrcdsz");
683                 reclist.records[reclist.num_records] =
684                     surrogatediagrec(a->proto, fres->basename, 17, 0);
685                 reclist.num_records++;
686                 *pres = Z_PRES_PARTIAL_2;
687                 break;
688             }
689         }
690         if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
691             return 0;
692         if (!(thisrec->databaseName = odr_malloc(a->encode,
693             strlen(fres->basename) + 1)))
694             return 0;
695         strcpy(thisrec->databaseName, fres->basename);
696         thisrec->which = Z_NamePlusRecord_databaseRecord;
697         if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
698             sizeof(Z_DatabaseRecord))))
699             return 0;
700         thisext->direct_reference = oid; /* should be OID for current MARC */
701         thisext->indirect_reference = 0;
702         thisext->descriptor = 0;
703         thisext->which = ODR_EXTERNAL_octet;
704         if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
705             sizeof(Odr_oct))))
706             return 0;
707         if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode, fres->len)))
708             return 0;
709         memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
710         thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
711             fres->len;
712         reclist.records[reclist.num_records] = thisrec;
713         reclist.num_records++;
714         total_length += fres->len;
715         (*num)++;
716         *next = fres->last_in_set ? 0 : recno + 1;
717     }
718     return &records;
719 }
720
721 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
722     int *fd)
723 {
724     Z_SearchRequest *req = reqb->request->u.searchRequest;
725     bend_searchrequest bsrq;
726     bend_searchresult *bsrt;
727
728     logf(LOG_LOG, "Got SearchRequest.");
729
730     bsrq.setname = req->resultSetName;
731     bsrq.replace_set = *req->replaceIndicator;
732     bsrq.num_bases = req->num_databaseNames;
733     bsrq.basenames = req->databaseNames;
734     bsrq.query = req->query;
735
736     if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
737         return 0;
738     return response_searchRequest(assoc, reqb, bsrt, fd);
739 }
740
741 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
742
743 /*
744  * Prepare a searchresponse based on the backend results. We probably want
745  * to look at making the fetching of records nonblocking as well, but
746  * so far, we'll keep things simple.
747  * If bsrt is null, that means we're called in response to a communications
748  * event, and we'll have to get the response for ourselves.
749  */
750 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
751     bend_searchresult *bsrt, int *fd)
752 {
753     Z_SearchRequest *req = reqb->request->u.searchRequest;
754     static Z_APDU apdu;
755     static Z_SearchResponse resp;
756     static int nulint = 0;
757     static bool_t sr = 1;
758     static int next = 0;
759     static int none = Z_RES_NONE;
760
761     apdu.which = Z_APDU_searchResponse;
762     apdu.u.searchResponse = &resp;
763     resp.referenceId = req->referenceId;
764     *fd = -1;
765     if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
766     {
767         logf(LOG_FATAL, "Bad result from backend");
768         return 0;
769     }
770     else if (bsrt->errcode)
771     {
772         resp.records = diagrec(assoc->proto, bsrt->errcode,
773             bsrt->errstring);
774         resp.resultCount = &nulint;
775         resp.numberOfRecordsReturned = &nulint;
776         resp.nextResultSetPosition = &nulint;
777         resp.searchStatus = &nulint;
778         resp.resultSetStatus = &none;
779         resp.presentStatus = 0;
780     }
781     else
782     {
783         int toget;
784         Z_ElementSetNames *setnames;
785         int presst = 0;
786
787         resp.records = 0;
788         resp.resultCount = &bsrt->hits;
789
790         /* how many records does the user agent want, then? */
791         if (bsrt->hits <= *req->smallSetUpperBound)
792         {
793             toget = bsrt->hits;
794             setnames = req->smallSetElementSetNames;
795         }
796         else if (bsrt->hits < *req->largeSetLowerBound)
797         {
798             toget = *req->mediumSetPresentNumber;
799             if (toget > bsrt->hits)
800                 toget = bsrt->hits;
801             setnames = req->mediumSetElementSetNames;
802         }
803         else
804             toget = 0;
805
806         if (toget && !resp.records)
807         {
808             resp.records = pack_records(assoc, req->resultSetName, 1,
809                 &toget, setnames, &next, &presst);
810             if (!resp.records)
811                 return 0;
812             resp.numberOfRecordsReturned = &toget;
813             resp.nextResultSetPosition = &next;
814             resp.searchStatus = &sr;
815             resp.resultSetStatus = 0;
816             resp.presentStatus = &presst;
817         }
818         else
819         {
820             resp.numberOfRecordsReturned = &nulint;
821             resp.nextResultSetPosition = &next;
822             resp.searchStatus = &sr;
823             resp.resultSetStatus = 0;
824             resp.presentStatus = 0;
825         }
826     }
827     return &apdu;
828 }
829
830 /*
831  * Maybe we got a little over-friendly when we designed bend_fetch to
832  * get only one record at a time. Some backends can optimise multiple-record
833  * fetches, and at any rate, there is some overhead involved in
834  * all that selecting and hopping around. Problem is, of course, that the
835  * frontend can't know ahead of time how many records it'll need to
836  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
837  * is downright lousy as a bulk data transfer protocol.
838  *
839  * To start with, we'll do the fetching of records from the backend
840  * in one operation: To save some trips in and out of the event-handler,
841  * and to simplify the interface to pack_records. At any rate, asynch
842  * operation is more fun in operations that have an unpredictable execution
843  * speed - which is normally more true for search than for present.
844  */
845 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
846     int *fd)
847 {
848     Z_PresentRequest *req = reqb->request->u.presentRequest;
849     static Z_APDU apdu;
850     static Z_PresentResponse resp;
851     static int presst, next, num;
852
853     logf(LOG_LOG, "Got PresentRequest.");
854     apdu.which = Z_APDU_presentResponse;
855     apdu.u.presentResponse = &resp;
856     resp.referenceId = req->referenceId;
857
858     num = *req->numberOfRecordsRequested;
859     resp.records = pack_records(assoc, req->resultSetId,
860         *req->resultSetStartPoint, &num, req->elementSetNames, &next, &presst);
861     if (!resp.records)
862         return 0;
863     resp.numberOfRecordsReturned = &num;
864     resp.presentStatus = &presst;
865     resp.nextResultSetPosition = &next;
866
867     return &apdu;
868 }
869
870 /*
871  * Scan was implemented rather in a hurry, and with support for only the basic
872  * elements of the service in the backend API. Suggestions are welcome.
873  */
874 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
875 {
876     Z_ScanRequest *req = reqb->request->u.scanRequest;
877     static Z_APDU apdu;
878     static Z_ScanResponse res;
879     static int scanStatus = Z_Scan_failure;
880     static int numberOfEntriesReturned = 0;
881     oident *attent;
882     static Z_ListEntries ents;
883 #define SCAN_MAX_ENTRIES 200
884     static Z_Entry *tab[SCAN_MAX_ENTRIES];
885     bend_scanrequest srq;
886     bend_scanresult *srs;
887
888     apdu.which = Z_APDU_scanResponse;
889     apdu.u.scanResponse = &res;
890     res.referenceId = req->referenceId;
891     res.stepSize = 0;
892     res.scanStatus = &scanStatus;
893     res.numberOfEntriesReturned = &numberOfEntriesReturned;
894     res.positionOfTerm = 0;
895     res.entries = &ents;
896     ents.which = Z_ListEntries_nonSurrogateDiagnostics;
897     res.attributeSet = 0;
898
899     if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
900         attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
901         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
902     else if (req->stepSize && *req->stepSize > 0)
903         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
904     else
905     {
906         srq.num_bases = req->num_databaseNames;
907         srq.basenames = req->databaseNames;
908         srq.num_entries = *req->numberOfTermsRequested;
909         srq.term = req->termListAndStartPoint;
910         srq.term_position = req->preferredPositionInResponse ?
911             *req->preferredPositionInResponse : 1;
912         if (!(srs = bend_scan(assoc->backend, &srq, 0)))
913             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
914         else if (srs->errcode)
915             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
916                 srs->errcode, srs->errstring);
917         else
918         {
919             int i;
920             static Z_Entries list;
921
922             if (srs->status == BEND_SCAN_PARTIAL)
923                 scanStatus = Z_Scan_partial_5;
924             else
925                 scanStatus = Z_Scan_success;
926             ents.which = Z_ListEntries_entries;
927             ents.u.entries = &list;
928             list.entries = tab;
929             for (i = 0; i < srs->num_entries; i++)
930             {
931                 Z_Entry *e;
932                 Z_TermInfo *t;
933                 Odr_oct *o;
934
935                 if (i >= SCAN_MAX_ENTRIES)
936                 {
937                     scanStatus = Z_Scan_partial_4;
938                     break;
939                 }
940                 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
941                 e->which = Z_Entry_termInfo;
942                 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
943                 t->suggestedAttributes = 0;
944                 t->alternativeTerm = 0;
945                 t->byAttributes = 0;
946                 t->globalOccurrences = &srs->entries[i].occurrences;
947                 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
948                 t->term->which = Z_Term_general;
949                 t->term->u.general = o = odr_malloc(assoc->encode,
950                     sizeof(Odr_oct));
951                 o->buf = odr_malloc(assoc->encode, o->len = o->size =
952                     strlen(srs->entries[i].term));
953                 memcpy(o->buf, srs->entries[i].term, o->len);
954             }
955             list.num_entries = i;
956             res.numberOfEntriesReturned = &list.num_entries;
957             res.positionOfTerm = &srs->term_position;
958         }
959     }
960
961     return &apdu;
962 }