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