ZOOM fix: fatal errors aren't reset.
[yaz-moved-to-github.git] / zoom / zoom-c.c
1 /*
2  * $Id: zoom-c.c,v 1.20 2002-01-09 12:44:31 adam Exp $
3  *
4  * ZOOM layer for C, connections, result sets, queries.
5  */
6 #include <assert.h>
7 #include <yaz/xmalloc.h>
8 #include <yaz/otherinfo.h>
9 #include <yaz/log.h>
10 #include <yaz/pquery.h>
11 #include <yaz/diagbib1.h>
12
13 #include "zoom-p.h"
14
15 #if HAVE_SYS_POLL_H
16 #include <sys/poll.h>
17 #endif
18
19 static ZOOM_Event ZOOM_Event_create (int kind)
20 {
21     ZOOM_Event event = xmalloc (sizeof(*event));
22     event->kind = kind;
23     event->next = 0;
24     event->prev = 0;
25     return event;
26 }
27
28 static void ZOOM_Event_destroy (ZOOM_Event event)
29 {
30     xfree (event);
31 }
32
33 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
34 {
35     // put in back of queue
36     if (c->m_queue_back)
37     {
38         c->m_queue_back->prev = event;
39         assert (c->m_queue_front);
40     }
41     else
42     {
43         assert (!c->m_queue_front);
44         c->m_queue_front = event;
45     }
46     event->next = c->m_queue_back;
47     event->prev = 0;
48     c->m_queue_back = event;
49 }
50
51 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
52 {
53     // get from front of queue
54     ZOOM_Event event = c->m_queue_front;
55     if (!event)
56         return 0;
57     assert (c->m_queue_back);
58     c->m_queue_front = event->prev;
59     if (c->m_queue_front)
60     {
61         assert (c->m_queue_back);
62         c->m_queue_front->next = 0;
63     }
64     else
65         c->m_queue_back = 0;
66     c->last_event = event->kind;
67     return event;
68 }
69
70 static void clear_error (ZOOM_connection c)
71 {
72
73     switch (c->error)
74     {
75     case ZOOM_ERROR_CONNECT:
76     case ZOOM_ERROR_MEMORY:
77     case ZOOM_ERROR_DECODE:
78     case ZOOM_ERROR_CONNECTION_LOST:
79     case ZOOM_ERROR_INIT:
80     case ZOOM_ERROR_INTERNAL:
81         break;
82     default:
83         c->error = ZOOM_ERROR_NONE;
84         xfree (c->addinfo);
85         c->addinfo = 0;
86     }
87 }
88
89 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
90 {
91     ZOOM_task *taskp = &c->tasks;
92     while (*taskp)
93         taskp = &(*taskp)->next;
94     *taskp = xmalloc (sizeof(**taskp));
95     (*taskp)->running = 0;
96     (*taskp)->which = which;
97     (*taskp)->next = 0;
98     clear_error (c);
99     return *taskp;
100 }
101
102 void ZOOM_connection_remove_task (ZOOM_connection c)
103 {
104     ZOOM_task task = c->tasks;
105
106     if (task)
107     {
108         c->tasks = task->next;
109         switch (task->which)
110         {
111         case ZOOM_TASK_SEARCH:
112             ZOOM_resultset_destroy (task->u.search.resultset);
113             break;
114         case ZOOM_TASK_RETRIEVE:
115             ZOOM_resultset_destroy (task->u.retrieve.resultset);
116             break;
117         case ZOOM_TASK_CONNECT:
118             break;
119         case ZOOM_TASK_SCAN:
120             ZOOM_scanset_destroy (task->u.scan.scan);
121             break;
122         default:
123             assert (0);
124         }
125         xfree (task);
126     }
127 }
128
129 void ZOOM_connection_remove_tasks (ZOOM_connection c)
130 {
131     while (c->tasks)
132         ZOOM_connection_remove_task(c);
133 }
134
135 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
136                                          int pos,
137                                          const char *elementSetName);
138
139 ZOOM_connection ZOOM_connection_create (ZOOM_options options)
140 {
141     ZOOM_connection c = xmalloc (sizeof(*c));
142
143     c->cs = 0;
144     c->mask = 0;
145     c->state = STATE_IDLE;
146     c->error = ZOOM_ERROR_NONE;
147     c->addinfo = 0;
148     c->buf_in = 0;
149     c->len_in = 0;
150     c->buf_out = 0;
151     c->len_out = 0;
152     c->resultsets = 0;
153
154     c->options = ZOOM_options_create_with_parent(options);
155
156     c->host_port = 0;
157     c->proxy = 0;
158
159     c->cookie_out = 0;
160     c->cookie_in = 0;
161     c->tasks = 0;
162
163     c->odr_in = odr_createmem (ODR_DECODE);
164     c->odr_out = odr_createmem (ODR_ENCODE);
165
166     c->async = 0;
167     c->support_named_resultsets = 0;
168     c->last_event = ZOOM_EVENT_NONE;
169
170     c->m_queue_front = 0;
171     c->m_queue_back = 0;
172     return c;
173 }
174
175 /* set database names. Take local databases (if set); otherwise
176    take databases given in ZURL (if set); otherwise use Default */
177 static char **set_DatabaseNames (ZOOM_connection con, ZOOM_options options,
178                                  int *num)
179 {
180     char **databaseNames;
181     const char *c;
182     int no = 2;
183     const char *cp = ZOOM_options_get (options, "databaseName");
184     
185     if (!cp || !*cp)
186     {
187         cp = strchr (con->host_port, '/');
188         if (cp)
189             cp++;
190         }
191     if (cp)
192     {
193         c = cp;
194         while ((c = strchr(c, '+')))
195         {
196             c++;
197             no++;
198         }
199     }
200     else
201         cp = "Default";
202     databaseNames = odr_malloc (con->odr_out, no * sizeof(*databaseNames));
203     no = 0;
204     while (*cp)
205     {
206         c = strchr (cp, '+');
207         if (!c)
208             c = cp + strlen(cp);
209         else if (c == cp)
210         {
211             cp++;
212             continue;
213         }
214         /* cp ptr to first char of db name, c is char
215            following db name */
216         databaseNames[no] = odr_malloc (con->odr_out, 1+c-cp);
217         memcpy (databaseNames[no], cp, c-cp);
218         databaseNames[no++][c-cp] = '\0';
219         cp = c;
220         if (*cp)
221             cp++;
222     }
223     databaseNames[no] = NULL;
224     *num = no;
225     return databaseNames;
226 }
227
228 ZOOM_connection ZOOM_connection_new (const char *host, int portnum)
229 {
230     ZOOM_connection c = ZOOM_connection_create (0);
231
232     ZOOM_connection_connect (c, host, portnum);
233     return c;
234 }
235
236 void ZOOM_connection_connect(ZOOM_connection c,
237                               const char *host, int portnum)
238 {
239     const char *val;
240     ZOOM_task task;
241
242     val = ZOOM_options_get (c->options, "proxy");
243     if (val && *val)
244         c->proxy = xstrdup (val);
245     else
246         c->proxy = 0;
247
248     if (portnum)
249     {
250         char hostn[128];
251         sprintf (hostn, "%.80s:%d", host, portnum);
252         c->host_port = xstrdup(hostn);
253     }
254     else
255         c->host_port = xstrdup(host);
256
257     ZOOM_options_set(c->options, "host", c->host_port);
258
259     c->async = ZOOM_options_get_bool (c->options, "async", 0);
260  
261     c->error = ZOOM_ERROR_NONE;
262
263     task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
264
265     if (!c->async)
266     {
267         while (ZOOM_event (1, &c))
268             ;
269     }
270 }
271
272 ZOOM_query ZOOM_query_create(void)
273 {
274     ZOOM_query s = xmalloc (sizeof(*s));
275
276     s->refcount = 1;
277     s->query = 0;
278     s->sort_spec = 0;
279     s->odr = odr_createmem (ODR_ENCODE);
280
281     return s;
282 }
283
284 void ZOOM_query_destroy(ZOOM_query s)
285 {
286     if (!s)
287         return;
288
289     (s->refcount)--;
290     yaz_log (LOG_DEBUG, "ZOOM_query_destroy count=%d", s->refcount);
291     if (s->refcount == 0)
292     {
293         odr_destroy (s->odr);
294         xfree (s);
295     }
296 }
297
298 int ZOOM_query_prefix(ZOOM_query s, const char *str)
299 {
300     s->query = odr_malloc (s->odr, sizeof(*s->query));
301     s->query->which = Z_Query_type_1;
302     s->query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
303     if (!s->query->u.type_1)
304         return -1;
305     return 0;
306 }
307
308 int ZOOM_query_sortby(ZOOM_query s, const char *criteria)
309 {
310     s->sort_spec = yaz_sort_spec (s->odr, criteria);
311     if (!s->sort_spec)
312         return -1;
313     return 0;
314 }
315
316 static int do_write(ZOOM_connection c);
317
318 void ZOOM_connection_destroy(ZOOM_connection c)
319 {
320     ZOOM_resultset r;
321     if (!c)
322         return;
323     if (c->cs)
324         cs_close (c->cs);
325     for (r = c->resultsets; r; r = r->next)
326         r->connection = 0;
327
328     xfree (c->buf_in);
329     xfree (c->addinfo);
330     odr_destroy (c->odr_in);
331     odr_destroy (c->odr_out);
332     ZOOM_options_destroy (c->options);
333     ZOOM_connection_remove_tasks (c);
334     xfree (c->host_port);
335     xfree (c);
336 }
337
338 void ZOOM_resultset_addref (ZOOM_resultset r)
339 {
340     if (r)
341         (r->refcount)++;
342 }
343 ZOOM_resultset ZOOM_resultset_create ()
344 {
345     ZOOM_resultset r = xmalloc (sizeof(*r));
346
347     r->refcount = 1;
348     r->size = 0;
349     r->odr = odr_createmem (ODR_ENCODE);
350     r->start = 0;
351     r->piggyback = 1;
352     r->setname = 0;
353     r->count = 0;
354     r->record_cache = 0;
355     r->r_sort_spec = 0;
356     r->r_query = 0;
357     r->search = 0;
358     r->connection = 0;
359     r->next = 0;
360     return r;
361 }
362
363 ZOOM_resultset ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
364 {
365     ZOOM_resultset r;
366     ZOOM_query s = ZOOM_query_create();
367
368     ZOOM_query_prefix (s, q);
369
370     r = ZOOM_connection_search (c, s);
371     ZOOM_query_destroy (s);
372     return r;
373 }
374
375 ZOOM_resultset ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
376 {
377     ZOOM_resultset r = ZOOM_resultset_create ();
378     ZOOM_task task;
379     const char *cp;
380
381     r->r_sort_spec = q->sort_spec;
382     r->r_query = q->query;
383     r->search = q;
384
385     r->options = ZOOM_options_create_with_parent(c->options);
386
387     r->start = ZOOM_options_get_int(r->options, "start", 0);
388     r->count = ZOOM_options_get_int(r->options, "count", 0);
389     r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
390     cp = ZOOM_options_get (r->options, "setname");
391     if (cp)
392         r->setname = xstrdup (cp);
393     
394     r->connection = c;
395
396     r->next = c->resultsets;
397     c->resultsets = r;
398
399     task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
400     task->u.search.resultset = r;
401     ZOOM_resultset_addref (r);  
402
403     (q->refcount)++;
404
405     if (!c->async)
406     {
407         while (ZOOM_event (1, &c))
408             ;
409     }
410     return r;
411 }
412
413 void ZOOM_resultset_destroy(ZOOM_resultset r)
414 {
415     if (!r)
416         return;
417     (r->refcount)--;
418     yaz_log (LOG_DEBUG, "destroy r = %p count=%d", r, r->refcount);
419     if (r->refcount == 0)
420     {
421         if (r->connection)
422         {
423             /* remove ourselves from the resultsets in connection */
424             ZOOM_resultset *rp = &r->connection->resultsets;
425             while (1)
426             {
427                 assert (*rp);   /* we must be in this list!! */
428                 if (*rp == r)
429                 {   /* OK, we're here - take us out of it */
430                     *rp = (*rp)->next;
431                     break;
432                 }
433                 rp = &(*rp)->next;
434             }
435         }
436         ZOOM_query_destroy (r->search);
437         ZOOM_options_destroy (r->options);
438         odr_destroy (r->odr);
439         xfree (r->setname);
440         xfree (r);
441     }
442 }
443
444 size_t ZOOM_resultset_size (ZOOM_resultset r)
445 {
446     return r->size;
447 }
448
449 static void do_close (ZOOM_connection c)
450 {
451     if (c->cs)
452         cs_close(c->cs);
453     c->cs = 0;
454     c->mask = 0;
455     c->state = STATE_IDLE;
456 }
457
458 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
459                                       int force_sync, int start, int count)
460 {
461     ZOOM_task task;
462     ZOOM_connection c;
463
464     if (!r)
465         return;
466     c = r->connection;
467     if (!c)
468         return;
469     task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
470     task->u.retrieve.resultset = r;
471     task->u.retrieve.start = start;
472     task->u.retrieve.count = count;
473
474     ZOOM_resultset_addref (r);
475
476     if (!r->connection->async || force_sync)
477         while (r->connection && ZOOM_event (1, &r->connection))
478             ;
479 }
480
481 void ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
482                               size_t start, size_t count)
483 {
484     int force_present = 0;
485
486     if (!r)
487         return ;
488     if (count && recs)
489         force_present = 1;
490     ZOOM_resultset_retrieve (r, force_present, start, count);
491     if (force_present)
492     {
493         size_t i;
494         for (i = 0; i< count; i++)
495             recs[i] = ZOOM_resultset_record_immediate (r, i+start);
496     }
497 }
498
499 static int do_connect (ZOOM_connection c)
500 {
501     void *add;
502     const char *effective_host;
503
504     if (c->proxy)
505         effective_host = c->proxy;
506     else
507         effective_host = c->host_port;
508
509     yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
510
511     assert (!c->cs);
512     c->cs = cs_create_host (effective_host, 0, &add);
513
514     if (c->cs)
515     {
516         int ret = cs_connect (c->cs, add);
517         yaz_log (LOG_DEBUG, "cs_connect returned %d", ret);
518         if (ret >= 0)
519         {
520             c->state = STATE_CONNECTING; 
521             c->mask = ZOOM_SELECT_READ | ZOOM_SELECT_WRITE | 
522                 ZOOM_SELECT_EXCEPT;
523             return 1;
524         }
525     }
526     c->state = STATE_IDLE;
527     c->error = ZOOM_ERROR_CONNECT;
528     return 0;
529 }
530
531 int z3950_connection_socket(ZOOM_connection c)
532 {
533     if (c->cs)
534         return cs_fileno(c->cs);
535     return -1;
536 }
537
538 int z3950_connection_mask(ZOOM_connection c)
539 {
540     if (c->cs)
541         return c->mask;
542     return 0;
543 }
544
545 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
546 {
547     char str[120];
548
549     assert (a);
550     sprintf (str, "send_APDU t=%p type=%d", c, a->which);
551     if (c->cookie_out)
552     {
553         Z_OtherInformation **oi;
554         yaz_oi_APDU(a, &oi);
555         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
556     }
557     if (!z_APDU(out, &a, 0, 0))
558     {
559         FILE *outf = fopen("/tmp/apdu.txt", "w");
560         if (outf)
561         {
562             ODR odr_pr = odr_createmem(ODR_PRINT);
563             fprintf (outf, "a=%p\n", a);
564             odr_setprint(odr_pr, outf);
565             z_APDU(odr_pr, &a, 0, 0);
566             odr_destroy(odr_pr);
567             fclose (outf);
568         }
569         c->error = ZOOM_ERROR_ENCODE;
570         do_close (c);
571         return -1;
572     }
573     
574     return 0;
575 }
576
577 static int send_APDU (ZOOM_connection c, Z_APDU *a)
578 {
579     ZOOM_Event event;
580     assert (a);
581     if (encode_APDU(c, a, c->odr_out))
582         return -1;
583     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
584     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
585     ZOOM_connection_put_event (c, event);
586     odr_reset(c->odr_out);
587     do_write (c);
588     return 0;   
589 }
590
591 static int ZOOM_connection_send_init (ZOOM_connection c)
592 {
593     const char *impname;
594     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
595     Z_InitRequest *ireq = apdu->u.initRequest;
596     Z_IdAuthentication *auth = odr_malloc(c->odr_out, sizeof(*auth));
597     const char *auth_groupId = ZOOM_options_get (c->options, "group");
598     const char *auth_userId = ZOOM_options_get (c->options, "user");
599     const char *auth_password = ZOOM_options_get (c->options, "pass");
600     
601     ODR_MASK_SET(ireq->options, Z_Options_search);
602     ODR_MASK_SET(ireq->options, Z_Options_present);
603     ODR_MASK_SET(ireq->options, Z_Options_scan);
604     ODR_MASK_SET(ireq->options, Z_Options_sort);
605     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
606     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
607     
608     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
609     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
610     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
611     
612     impname = ZOOM_options_get (c->options, "implementationName");
613     ireq->implementationName =
614         odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
615     strcpy (ireq->implementationName, "");
616     if (impname)
617     {
618         strcat (ireq->implementationName, impname);
619         strcat (ireq->implementationName, "/");
620     }                                          
621     strcat (ireq->implementationName, "ZOOM-C/YAZ");
622     
623     *ireq->maximumRecordSize =
624         ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
625     *ireq->preferredMessageSize =
626         ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
627     
628     if (auth_groupId || auth_password)
629     {
630         Z_IdPass *pass = odr_malloc(c->odr_out, sizeof(*pass));
631         int i = 0;
632         pass->groupId = 0;
633         if (auth_groupId && *auth_groupId)
634         {
635             pass->groupId = odr_malloc(c->odr_out, strlen(auth_groupId)+1);
636             strcpy(pass->groupId, auth_groupId);
637             i++;
638         }
639         pass->userId = 0;
640         if (auth_userId && *auth_userId)
641         {
642             pass->userId = odr_malloc(c->odr_out, strlen(auth_userId)+1);
643             strcpy(pass->userId, auth_userId);
644             i++;
645         }
646         pass->password = 0;
647         if (auth_password && *auth_password)
648         {
649             pass->password = odr_malloc(c->odr_out, strlen(auth_password)+1);
650             strcpy(pass->password, auth_password);
651             i++;
652         }
653         if (i)
654         {
655             auth->which = Z_IdAuthentication_idPass;
656             auth->u.idPass = pass;
657             ireq->idAuthentication = auth;
658         }
659     }
660     else if (auth_userId)
661     {
662         auth->which = Z_IdAuthentication_open;
663         auth->u.open = odr_malloc(c->odr_out, strlen(auth_userId)+1);
664         strcpy(auth->u.open, auth_userId);
665         ireq->idAuthentication = auth;
666     }
667     if (c->proxy)
668         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
669                                  VAL_PROXY, 1, c->host_port);
670     assert (apdu);
671     send_APDU (c, apdu);
672     
673     return 0;
674 }
675
676 static int ZOOM_connection_send_search (ZOOM_connection c)
677 {
678     ZOOM_resultset r;
679     int lslb, ssub, mspn;
680     const char *syntax;
681     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
682     Z_SearchRequest *search_req = apdu->u.searchRequest;
683     const char *elementSetName;
684     const char *smallSetElementSetName;
685     const char *mediumSetElementSetName;
686     const char *schema;
687
688     assert (c->tasks);
689     assert (c->tasks->which == ZOOM_TASK_SEARCH);
690
691     r = c->tasks->u.search.resultset;
692
693     elementSetName =
694         ZOOM_options_get (r->options, "elementSetName");
695     smallSetElementSetName  =
696         ZOOM_options_get (r->options, "smallSetElementSetName");
697     mediumSetElementSetName =
698         ZOOM_options_get (r->options, "mediumSetElementSetName");
699     schema =
700         ZOOM_options_get (r->options, "schema");
701
702     if (!smallSetElementSetName)
703         smallSetElementSetName = elementSetName;
704
705     if (!mediumSetElementSetName)
706         mediumSetElementSetName = elementSetName;
707
708     assert (r);
709     assert (r->r_query);
710
711     /* prepare query for the search request */
712     search_req->query = r->r_query;
713
714     search_req->databaseNames =
715         set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
716
717     /* get syntax (no need to provide unless piggyback is in effect) */
718     syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
719
720     lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
721     ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
722     mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
723     if (lslb != -1 && ssub != -1 && mspn != -1)
724     {
725         /* So're a Z39.50 expert? Let's hope you don't do sort */
726         *search_req->largeSetLowerBound = lslb;
727         *search_req->smallSetUpperBound = ssub;
728         *search_req->mediumSetPresentNumber = mspn;
729     }
730     else if (r->start == 0 && r->count > 0
731              && r->piggyback && !r->r_sort_spec && !schema)
732     {
733         /* Regular piggyback - do it unless we're going to do sort */
734         *search_req->largeSetLowerBound = 2000000000;
735         *search_req->smallSetUpperBound = r->count;
736         *search_req->mediumSetPresentNumber = r->count;
737         smallSetElementSetName = 0;  /* no need to provide this */
738     }
739     else
740     {
741         /* non-piggyback. Need not provide elementsets or syntaxes .. */
742         smallSetElementSetName = 0;
743         mediumSetElementSetName = 0;
744         syntax = 0;
745     }
746     if (smallSetElementSetName && *smallSetElementSetName)
747     {
748         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
749         
750         esn->which = Z_ElementSetNames_generic;
751         esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
752         search_req->smallSetElementSetNames = esn;
753     }
754     if (mediumSetElementSetName && *mediumSetElementSetName)
755     {
756         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
757         
758         esn->which = Z_ElementSetNames_generic;
759         esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
760         search_req->mediumSetElementSetNames = esn;
761     }
762     if (syntax)
763         search_req->preferredRecordSyntax =
764             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
765     
766     if (!r->setname)
767     {
768         if (c->support_named_resultsets)
769         {
770             char setname[14];
771             int ord;
772             /* find the lowest unused ordinal so that we re-use
773                result sets on the server. */
774             for (ord = 1; ; ord++)
775             {
776                 ZOOM_resultset rp;
777                 sprintf (setname, "%d", ord);
778                 for (rp = c->resultsets; rp; rp = rp->next)
779                     if (rp->setname && !strcmp (rp->setname, setname))
780                         break;
781                 if (!rp)
782                     break;
783             }
784             r->setname = xstrdup (setname);
785             yaz_log (LOG_DEBUG, "allocating %s", r->setname);
786         }
787         else
788             r->setname = xstrdup ("default");
789         ZOOM_options_set (r->options, "setname", r->setname);
790     }
791     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
792     /* send search request */
793     send_APDU (c, apdu);
794     r->r_query = 0;
795     return 1;
796 }
797
798 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
799 {
800     Z_DefaultDiagFormat *r;
801     char *addinfo = 0;
802     
803     xfree (c->addinfo);
804     c->addinfo = 0;
805     if (p->which != Z_DiagRec_defaultFormat)
806     {
807         c->error = ZOOM_ERROR_DECODE;
808         return;
809     }
810     r = p->u.defaultFormat;
811     switch (r->which)
812     {
813     case Z_DefaultDiagFormat_v2Addinfo:
814         addinfo = r->u.v2Addinfo;
815         break;
816     case Z_DefaultDiagFormat_v3Addinfo:
817         addinfo = r->u.v3Addinfo;
818         break;
819     }
820     if (addinfo)
821         c->addinfo = xstrdup (addinfo);
822     c->error = *r->condition;
823 }
824
825 ZOOM_record ZOOM_record_clone (ZOOM_record srec)
826 {
827     char *buf;
828     int size;
829     ODR odr_enc;
830     ZOOM_record nrec;
831
832     odr_enc = odr_createmem(ODR_ENCODE);
833     if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
834         return 0;
835     buf = odr_getbuf (odr_enc, &size, 0);
836     
837     nrec = xmalloc (sizeof(*nrec));
838     nrec->odr = odr_createmem(ODR_DECODE);
839     nrec->wrbuf_marc = 0;
840     odr_setbuf (nrec->odr, buf, size, 0);
841     z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
842     
843     odr_destroy (odr_enc);
844     return nrec;
845 }
846
847 ZOOM_record ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
848 {
849     return record_cache_lookup (s, pos, 0);
850 }
851
852 ZOOM_record ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
853 {
854     ZOOM_resultset_retrieve (r, 1, pos, 1);
855     return ZOOM_resultset_record_immediate (r, pos);
856 }
857
858 void ZOOM_record_destroy (ZOOM_record rec)
859 {
860     if (!rec)
861         return;
862     if (rec->wrbuf_marc)
863         wrbuf_free (rec->wrbuf_marc, 1);
864     odr_destroy (rec->odr);
865     xfree (rec);
866 }
867
868 void *ZOOM_record_get (ZOOM_record rec, const char *type, size_t *len)
869 {
870     Z_NamePlusRecord *npr;
871     if (!rec)
872         return 0;
873     npr = rec->npr;
874     if (!npr)
875         return 0;
876     if (!strcmp (type, "database"))
877     {
878         return npr->databaseName;
879     }
880     else if (!strcmp (type, "syntax"))
881     {
882         if (npr->which == Z_NamePlusRecord_databaseRecord)
883         {
884             Z_External *r = (Z_External *) npr->u.databaseRecord;
885             oident *ent = oid_getentbyoid(r->direct_reference);
886             if (ent)
887                 return ent->desc;
888         }
889         return "none";
890     }
891     else if (!strcmp (type, "render"))
892     {
893         if (npr->which == Z_NamePlusRecord_databaseRecord)
894         {
895             Z_External *r = (Z_External *) npr->u.databaseRecord;
896             oident *ent = oid_getentbyoid(r->direct_reference);
897             
898             if (r->which == Z_External_sutrs)
899             {
900                 *len = r->u.sutrs->len;
901                 return r->u.sutrs->buf;
902             }
903             else if (r->which == Z_External_octet)
904             {
905                 switch (ent->value)
906                 {
907                 case VAL_SOIF:
908                 case VAL_HTML:
909                 case VAL_SUTRS:
910                     break;
911                 case VAL_TEXT_XML:
912                 case VAL_APPLICATION_XML:
913                     break;
914                 default:
915                     if (!rec->wrbuf_marc)
916                         rec->wrbuf_marc = wrbuf_alloc();
917                     if (marc_display_wrbuf (r->u.octet_aligned->buf,
918                                         rec->wrbuf_marc, 0,
919                                             r->u.octet_aligned->len) > 0)
920                     {
921                         *len = wrbuf_len(rec->wrbuf_marc);
922                         return wrbuf_buf(rec->wrbuf_marc);
923                     }
924                 }
925                 *len = r->u.octet_aligned->len;
926                 return r->u.octet_aligned->buf;
927             }
928             else if (r->which == Z_External_grs1)
929             {
930                 *len = 5;
931                 return "GRS-1";
932             }
933         }
934         return 0;
935     }
936     else if (!strcmp (type, "raw"))
937     {
938         if (npr->which == Z_NamePlusRecord_databaseRecord)
939         {
940             Z_External *r = (Z_External *) npr->u.databaseRecord;
941             
942             if (r->which == Z_External_sutrs)
943             {
944                 *len = r->u.sutrs->len;
945                 return r->u.sutrs->buf;
946             }
947             else if (r->which == Z_External_octet)
948             {
949                 *len = r->u.octet_aligned->len;
950                 return r->u.octet_aligned->buf;
951             }
952             else /* grs-1, explain, ... */
953             {
954                 *len = -1;
955                 return (Z_External *) npr->u.databaseRecord;
956             }
957         }
958         return 0;
959     }
960     return 0;
961 }
962
963 static void record_cache_add (ZOOM_resultset r,
964                               Z_NamePlusRecord *npr,
965                               int pos,
966                               const char *elementSetName)
967 {
968     ZOOM_record_cache rc;
969
970     for (rc = r->record_cache; rc; rc = rc->next)
971     {
972         if (pos == rc->pos)
973         {
974             if ((!elementSetName && !rc->elementSetName)
975                 || (elementSetName && rc->elementSetName &&
976                     !strcmp (elementSetName, rc->elementSetName)))
977             {
978                 /* not destroying rc->npr (it's handled by nmem )*/
979                 rc->rec.npr = npr;
980                 /* keeping wrbuf_marc too */
981                 return;
982             }
983         }
984
985     }
986     rc = odr_malloc (r->odr, sizeof(*rc));
987     rc->rec.npr = npr; 
988     rc->rec.odr = 0;
989     rc->rec.wrbuf_marc = 0;
990     if (elementSetName)
991         rc->elementSetName = odr_strdup (r->odr, elementSetName);
992     else
993         rc->elementSetName = 0;
994     rc->pos = pos;
995     rc->next = r->record_cache;
996     r->record_cache = rc;
997 }
998
999 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
1000                                          int pos,
1001                                          const char *elementSetName)
1002 {
1003     ZOOM_record_cache rc;
1004
1005     for (rc = r->record_cache; rc; rc = rc->next)
1006     {
1007         if (pos == rc->pos)
1008         {
1009             if ((!elementSetName && !rc->elementSetName)
1010                 || (elementSetName && rc->elementSetName &&
1011                     !strcmp (elementSetName, rc->elementSetName)))
1012                 return &rc->rec;
1013         }
1014     }
1015     return 0;
1016 }
1017                                              
1018 static void handle_records (ZOOM_connection c, Z_Records *sr,
1019                             int present_phase)
1020 {
1021     ZOOM_resultset resultset;
1022
1023     if (!c->tasks)
1024         return ;
1025     switch (c->tasks->which)
1026     {
1027     case ZOOM_TASK_SEARCH:
1028         resultset = c->tasks->u.search.resultset;
1029         break;
1030     case ZOOM_TASK_RETRIEVE:
1031         resultset = c->tasks->u.retrieve.resultset;        
1032         break;
1033     default:
1034         return;
1035     }
1036     if (sr && sr->which == Z_Records_NSD)
1037     {
1038         Z_DiagRec dr, *dr_p = &dr;
1039         dr.which = Z_DiagRec_defaultFormat;
1040         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1041         
1042         response_diag (c, dr_p);
1043     }
1044     else if (sr && sr->which == Z_Records_multipleNSD)
1045     {
1046         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1047             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1048         else
1049             c->error = ZOOM_ERROR_DECODE;
1050     }
1051     else 
1052     {
1053         if (resultset->count + resultset->start > resultset->size)
1054             resultset->count = resultset->size - resultset->start;
1055         if (resultset->count < 0)
1056             resultset->count = 0;
1057         if (sr && sr->which == Z_Records_DBOSD)
1058         {
1059             int i;
1060             NMEM nmem = odr_extract_mem (c->odr_in);
1061             Z_NamePlusRecordList *p =
1062                 sr->u.databaseOrSurDiagnostics;
1063             for (i = 0; i<p->num_records; i++)
1064             {
1065                 record_cache_add (resultset, p->records[i],
1066                                   i+ resultset->start, 0);
1067             }
1068             /* transfer our response to search_nmem .. we need it later */
1069             nmem_transfer (resultset->odr->mem, nmem);
1070             nmem_destroy (nmem);
1071             if (present_phase && p->num_records == 0)
1072             {
1073                 /* present response and we didn't get any records! */
1074                 c->error = ZOOM_ERROR_DECODE;
1075             }
1076         }
1077         else if (present_phase)
1078         {
1079             /* present response and we didn't get any records! */
1080             c->error = ZOOM_ERROR_DECODE;
1081         }
1082     }
1083 }
1084
1085 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1086 {
1087     handle_records (c, pr->records, 1);
1088 }
1089
1090 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1091 {
1092     ZOOM_resultset resultset;
1093
1094     yaz_log (LOG_DEBUG, "got search response");
1095
1096     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1097         return ;
1098
1099     resultset = c->tasks->u.search.resultset;
1100
1101     resultset->size = *sr->resultCount;
1102     handle_records (c, sr->records, 0);
1103 }
1104
1105 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1106 {
1107     if (res->diagnostics && res->num_diagnostics > 0)
1108         response_diag (c, res->diagnostics[0]);
1109 }
1110
1111 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1112 {
1113     NMEM nmem = odr_extract_mem (c->odr_in);
1114     ZOOM_scanset scan;
1115
1116     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1117         return 0;
1118     scan = c->tasks->u.scan.scan;
1119
1120     if (res->entries && res->entries->nonsurrogateDiagnostics)
1121         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1122     scan->scan_response = res;
1123     nmem_transfer (scan->odr->mem, nmem);
1124     if (res->stepSize)
1125         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1126     if (res->positionOfTerm)
1127         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1128     if (res->scanStatus)
1129         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1130     if (res->numberOfEntriesReturned)
1131         ZOOM_options_set_int (scan->options, "number",
1132                               *res->numberOfEntriesReturned);
1133     nmem_destroy (nmem);
1134     return 1;
1135 }
1136
1137 static int send_sort (ZOOM_connection c)
1138 {
1139     ZOOM_resultset  resultset;
1140
1141     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1142         return 0;
1143
1144     resultset = c->tasks->u.search.resultset;
1145
1146     if (c->error)
1147     {
1148         resultset->r_sort_spec = 0;
1149         return 0;
1150     }
1151     if (resultset->r_sort_spec)
1152     {
1153         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1154         Z_SortRequest *req = apdu->u.sortRequest;
1155         
1156         req->num_inputResultSetNames = 1;
1157         req->inputResultSetNames = (Z_InternationalString **)
1158             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1159         req->inputResultSetNames[0] =
1160             odr_strdup (c->odr_out, resultset->setname);
1161         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1162         req->sortSequence = resultset->r_sort_spec;
1163         resultset->r_sort_spec = 0;
1164         send_APDU (c, apdu);
1165         return 1;
1166     }
1167     return 0;
1168 }
1169
1170 static int send_present (ZOOM_connection c)
1171 {
1172     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1173     Z_PresentRequest *req = apdu->u.presentRequest;
1174     int i = 0;
1175     const char *syntax = 
1176         ZOOM_options_get (c->options, "preferredRecordSyntax");
1177     const char *element =
1178         ZOOM_options_get (c->options, "elementSetName");
1179     const char *schema =
1180         ZOOM_options_get (c->options, "schema");
1181     ZOOM_resultset  resultset;
1182
1183     if (!c->tasks)
1184         return 0;
1185
1186     switch (c->tasks->which)
1187     {
1188     case ZOOM_TASK_SEARCH:
1189         resultset = c->tasks->u.search.resultset;
1190         break;
1191     case ZOOM_TASK_RETRIEVE:
1192         resultset = c->tasks->u.retrieve.resultset;
1193         resultset->start = c->tasks->u.retrieve.start;
1194         resultset->count = c->tasks->u.retrieve.count;
1195
1196         if (resultset->start >= resultset->size)
1197             return 0;
1198         if (resultset->start + resultset->count > resultset->size)
1199             resultset->count = resultset->size - resultset->start;
1200         break;
1201     default:
1202         return 0;
1203     }
1204
1205     if (c->error)                  /* don't continue on error */
1206         return 0;
1207     if (resultset->start < 0)
1208         return 0;
1209     for (i = 0; i<resultset->count; i++)
1210     {
1211         ZOOM_record rec =
1212             record_cache_lookup (resultset, i + resultset->start, 0);
1213         if (!rec)
1214             break;
1215     }
1216     if (i == resultset->count)
1217         return 0;
1218
1219     resultset->start += i;
1220     resultset->count -= i;
1221     *req->resultSetStartPoint = resultset->start + 1;
1222     *req->numberOfRecordsRequested = resultset->count;
1223     assert (*req->numberOfRecordsRequested > 0);
1224
1225     if (syntax && *syntax)
1226         req->preferredRecordSyntax =
1227             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1228
1229     if (schema && *schema)
1230     {
1231         Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1232
1233         req->recordComposition = compo;
1234         compo->which = Z_RecordComp_complex;
1235         compo->u.complex = (Z_CompSpec *)
1236             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1237         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
1238             odr_malloc(c->odr_out, sizeof(bool_t));
1239         *compo->u.complex->selectAlternativeSyntax = 0;
1240
1241         compo->u.complex->generic = (Z_Specification *)
1242             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1243
1244         compo->u.complex->generic->schema = (Odr_oid *)
1245             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, schema);
1246
1247         if (!compo->u.complex->generic->schema)
1248         {
1249             /* OID wasn't a schema! Try record syntax instead. */
1250
1251             compo->u.complex->generic->schema = (Odr_oid *)
1252                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, schema);
1253         }
1254         if (element && *element)
1255         {
1256             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1257                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1258             compo->u.complex->generic->elementSpec->which =
1259                 Z_ElementSpec_elementSetName;
1260             compo->u.complex->generic->elementSpec->u.elementSetName =
1261                 odr_strdup (c->odr_out, element);
1262         }
1263         else
1264             compo->u.complex->generic->elementSpec = 0;
1265         compo->u.complex->num_dbSpecific = 0;
1266         compo->u.complex->dbSpecific = 0;
1267         compo->u.complex->num_recordSyntax = 0;
1268         compo->u.complex->recordSyntax = 0;
1269     }
1270     else if (element && *element)
1271     {
1272         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
1273         Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1274         
1275         esn->which = Z_ElementSetNames_generic;
1276         esn->u.generic = odr_strdup (c->odr_out, element);
1277         compo->which = Z_RecordComp_simple;
1278         compo->u.simple = esn;
1279         req->recordComposition = compo;
1280     }
1281     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1282     send_APDU (c, apdu);
1283     return 1;
1284 }
1285
1286 ZOOM_scanset ZOOM_connection_scan (ZOOM_connection c, const char *start)
1287 {
1288     ZOOM_scanset scan = xmalloc (sizeof(*scan));
1289
1290     scan->connection = c;
1291     scan->odr = odr_createmem (ODR_DECODE);
1292     scan->options = ZOOM_options_create_with_parent (c->options);
1293     scan->refcount = 1;
1294     scan->scan_response = 0;
1295
1296     if ((scan->termListAndStartPoint =
1297          p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
1298                       start)))
1299     {
1300         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
1301         task->u.scan.scan = scan;
1302         
1303         (scan->refcount)++;
1304         if (!c->async)
1305         {
1306             while (ZOOM_event (1, &c))
1307                 ;
1308         }
1309     }
1310     return scan;
1311 }
1312
1313 void ZOOM_scanset_destroy (ZOOM_scanset scan)
1314 {
1315     if (!scan)
1316         return;
1317     (scan->refcount)--;
1318     if (scan->refcount == 0)
1319     {
1320         odr_destroy (scan->odr);
1321         
1322         ZOOM_options_destroy (scan->options);
1323         xfree (scan);
1324     }
1325 }
1326
1327 int send_scan (ZOOM_connection c)
1328 {
1329     ZOOM_scanset scan;
1330     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
1331     Z_ScanRequest *req = apdu->u.scanRequest;
1332     if (!c->tasks)
1333         return 0;
1334     assert (c->tasks->which == ZOOM_TASK_SCAN);
1335     scan = c->tasks->u.scan.scan;
1336
1337     req->termListAndStartPoint = scan->termListAndStartPoint;
1338     req->attributeSet = scan->attributeSet;
1339
1340     *req->numberOfTermsRequested =
1341         ZOOM_options_get_int(scan->options, "number", 10);
1342
1343     req->preferredPositionInResponse =
1344         odr_intdup (c->odr_out,
1345                     ZOOM_options_get_int(scan->options, "position", 1));
1346
1347     req->stepSize =
1348         odr_intdup (c->odr_out,
1349                     ZOOM_options_get_int(scan->options, "stepSize", 0));
1350     
1351     req->databaseNames = set_DatabaseNames (c, scan->options, 
1352                                             &req->num_databaseNames);
1353
1354     send_APDU (c, apdu);
1355
1356     return 1;
1357 }
1358
1359 size_t ZOOM_scanset_size (ZOOM_scanset scan)
1360 {
1361     if (!scan || !scan->scan_response || !scan->scan_response->entries)
1362         return 0;
1363     return scan->scan_response->entries->num_entries;
1364 }
1365
1366 const char *ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
1367                                int *occ, size_t *len)
1368 {
1369     const char *term = 0;
1370     size_t noent = ZOOM_scanset_size (scan);
1371     Z_ScanResponse *res = scan->scan_response;
1372     
1373     *len = 0;
1374     *occ = 0;
1375     if (pos >= noent)
1376         return 0;
1377     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
1378     {
1379         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
1380         
1381         if (t->term->which == Z_Term_general)
1382         {
1383             term = t->term->u.general->buf;
1384             *len = t->term->u.general->len;
1385         }
1386         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
1387     }
1388     return term;
1389 }
1390
1391 const char *ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
1392 {
1393     return ZOOM_options_get (scan->options, key);
1394 }
1395
1396 void ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
1397                               const char *val)
1398 {
1399     ZOOM_options_set (scan->options, key, val);
1400 }
1401
1402 static int ZOOM_connection_exec_task (ZOOM_connection c)
1403 {
1404     ZOOM_task task = c->tasks;
1405
1406     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task");
1407     if (!task)
1408         return 0;
1409     if (c->error != ZOOM_ERROR_NONE ||
1410         (!c->cs && task->which != ZOOM_TASK_CONNECT))
1411     {
1412         ZOOM_connection_remove_tasks (c);
1413         return 0;
1414     }
1415     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d", task->which);
1416     if (task->running)
1417         return 0;
1418     task->running = 1;
1419     switch (task->which)
1420     {
1421     case ZOOM_TASK_SEARCH:
1422         /* see if search hasn't been sent yet. */
1423         if (ZOOM_connection_send_search (c))
1424             return 1;
1425         break;
1426     case ZOOM_TASK_RETRIEVE:
1427         if (send_present (c))
1428             return 1;
1429         break;
1430     case ZOOM_TASK_CONNECT:
1431         if (do_connect(c))
1432             return 1;
1433         break;
1434     case ZOOM_TASK_SCAN:
1435         if (send_scan(c))
1436             return 1;
1437     }
1438     ZOOM_connection_remove_task (c);
1439     return 0;
1440 }
1441
1442 static int send_sort_present (ZOOM_connection c)
1443 {
1444     int r = send_sort (c);
1445     if (!r)
1446         r = send_present (c);
1447     return r;
1448 }
1449
1450 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
1451 {
1452     Z_InitResponse *initrs;
1453     
1454     yaz_log (LOG_DEBUG, "hande_apdu type=%d", apdu->which);
1455     c->mask = 0;
1456     switch(apdu->which)
1457     {
1458     case Z_APDU_initResponse:
1459         initrs = apdu->u.initResponse;
1460         if (!*initrs->result)
1461         {
1462             c->error = ZOOM_ERROR_INIT;
1463         }
1464         else
1465         {
1466             char *cookie =
1467                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
1468                                           VAL_COOKIE, 1, 0);
1469             xfree (c->cookie_in);
1470             c->cookie_in = 0;
1471             if (cookie)
1472                 c->cookie_in = xstrdup(cookie);
1473             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
1474                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
1475                 c->support_named_resultsets = 1;
1476             if (c->tasks)
1477             {
1478                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
1479                 ZOOM_connection_remove_task (c);
1480             }
1481             ZOOM_connection_exec_task (c);
1482         }
1483         break;
1484     case Z_APDU_searchResponse:
1485         handle_search_response (c, apdu->u.searchResponse);
1486         if (!send_sort_present (c))
1487             ZOOM_connection_remove_task (c);
1488         break;
1489     case Z_APDU_presentResponse:
1490         handle_present_response (c, apdu->u.presentResponse);
1491         if (!send_present (c))
1492             ZOOM_connection_remove_task (c);
1493         break;
1494     case Z_APDU_sortResponse:
1495         sort_response (c, apdu->u.sortResponse);
1496         if (!send_present (c))
1497             ZOOM_connection_remove_task (c);
1498         break;
1499     case Z_APDU_scanResponse:
1500         scan_response (c, apdu->u.scanResponse);
1501         ZOOM_connection_remove_task (c);
1502     }
1503 }
1504
1505 static int do_read (ZOOM_connection c)
1506 {
1507     int r;
1508     Z_APDU *apdu;
1509     ZOOM_Event event;
1510     
1511     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
1512     ZOOM_connection_put_event (c, event);
1513     
1514     r = cs_get (c->cs, &c->buf_in, &c->len_in);
1515     if (r == 1)
1516         return 0;
1517     if (r <= 0)
1518     {
1519         c->error= ZOOM_ERROR_CONNECTION_LOST;
1520         do_close (c);
1521     }
1522     else
1523     {
1524         ZOOM_Event event;
1525         odr_reset (c->odr_in);
1526         odr_setbuf (c->odr_in, c->buf_in, r, 0);
1527         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
1528         ZOOM_connection_put_event (c, event);
1529         if (!z_APDU (c->odr_in, &apdu, 0, 0))
1530         {
1531             c->error = ZOOM_ERROR_DECODE;
1532             do_close (c);
1533         }
1534         else
1535         {
1536             handle_apdu (c, apdu);
1537         }
1538     }
1539     return 1;
1540 }
1541
1542 static int do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
1543 {
1544     int r;
1545     ZOOM_Event event;
1546     
1547     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
1548     ZOOM_connection_put_event (c, event);
1549
1550     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
1551     {
1552         if (c->state == STATE_CONNECTING)
1553             c->error = ZOOM_ERROR_CONNECT;
1554         else
1555             c->error = ZOOM_ERROR_CONNECTION_LOST;
1556         do_close (c);
1557         return 1;
1558     }
1559     else if (r == 1)
1560     {
1561         c->state = STATE_ESTABLISHED;
1562         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_WRITE|ZOOM_SELECT_EXCEPT;
1563     }
1564     else
1565     {
1566         c->state = STATE_ESTABLISHED;
1567         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
1568     }
1569     return 0;
1570 }
1571
1572 static int do_write(ZOOM_connection c)
1573 {
1574     return do_write_ex (c, c->buf_out, c->len_out);
1575 }
1576
1577
1578 const char *ZOOM_connection_option_get (ZOOM_connection c, const char *key)
1579 {
1580     return ZOOM_options_get (c->options, key);
1581 }
1582
1583 void ZOOM_connection_option_set (ZOOM_connection c, const char *key,
1584                                   const char *val)
1585 {
1586     ZOOM_options_set (c->options, key, val);
1587 }
1588
1589 const char *ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
1590 {
1591     return ZOOM_options_get (r->options, key);
1592 }
1593
1594 void ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
1595                                   const char *val)
1596 {
1597     ZOOM_options_set (r->options, key, val);
1598 }
1599
1600
1601 int ZOOM_connection_errcode (ZOOM_connection c)
1602 {
1603     return ZOOM_connection_error (c, 0, 0);
1604 }
1605
1606 const char *ZOOM_connection_errmsg (ZOOM_connection c)
1607 {
1608     const char *msg;
1609     ZOOM_connection_error (c, &msg, 0);
1610     return msg;
1611 }
1612
1613 const char *ZOOM_connection_addinfo (ZOOM_connection c)
1614 {
1615     const char *addinfo;
1616     ZOOM_connection_error (c, 0, &addinfo);
1617     return addinfo;
1618 }
1619
1620 int ZOOM_connection_error (ZOOM_connection c, const char **cp,
1621                             const char **addinfo)
1622 {
1623     int error = c->error;
1624     if (cp)
1625     {
1626         switch (error)
1627         {
1628         case ZOOM_ERROR_NONE:
1629             *cp = "No error"; break;
1630         case ZOOM_ERROR_CONNECT:
1631             *cp = "Connect failed"; break;
1632         case ZOOM_ERROR_MEMORY:
1633             *cp = "Out of memory"; break;
1634         case ZOOM_ERROR_ENCODE:
1635             *cp = "Encoding failed"; break;
1636         case ZOOM_ERROR_DECODE:
1637             *cp = "Decoding failed"; break;
1638         case ZOOM_ERROR_CONNECTION_LOST:
1639             *cp = "Connection lost"; break;
1640         case ZOOM_ERROR_INIT:
1641             *cp = "Init rejected"; break;
1642         case ZOOM_ERROR_INTERNAL:
1643             *cp = "Internal failure"; break;
1644         case ZOOM_ERROR_TIMEOUT:
1645             *cp = "Timeout"; break;
1646         default:
1647             *cp = diagbib1_str (error);
1648         }
1649     }
1650     if (addinfo)
1651     {
1652         if (c->addinfo)
1653             *addinfo = c->addinfo;
1654         else
1655             *addinfo = "";
1656     }
1657     return c->error;
1658 }
1659
1660 int ZOOM_connection_do_io(ZOOM_connection c, int mask)
1661 {
1662     ZOOM_Event event = 0;
1663 #if 0
1664     int r = cs_look(c->cs);
1665     yaz_log (LOG_LOG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
1666              c, mask, r);
1667     
1668     if (r == CS_NONE)
1669     {
1670         event = ZOOM_Event_create (ZOOM_EVENT_IO_CONNECT);
1671         c->error = ZOOM_ERROR_CONNECT;
1672         do_close (c);
1673         ZOOM_connection_put_event (c, event);
1674     }
1675     else if (r == CS_CONNECT)
1676     {
1677         event = ZOOM_Event_create (ZOOM_EVENT_IO_CONNECT);
1678         yaz_log (LOG_LOG, "calling rcvconnect");
1679         if (cs_rcvconnect (c->cs) < 0)
1680         {
1681             c->error = ZOOM_ERROR_CONNECT;
1682             do_close (c);
1683             ZOOM_connection_put_event (c, event);
1684         }
1685         else
1686         {
1687             ZOOM_connection_put_event (c, event);
1688             ZOOM_connection_send_init (c);
1689         }
1690     }
1691     else
1692     {
1693         if (mask & ZOOM_SELECT_READ)
1694             do_read (c);
1695         if (c->cs && (mask & ZOOM_SELECT_WRITE))
1696             do_write (c);
1697     }   
1698 #else
1699     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d", c, mask);
1700     if (c->state == STATE_CONNECTING)
1701     {
1702         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
1703         if (mask & ZOOM_SELECT_WRITE)
1704         {
1705             ZOOM_connection_put_event (c, event);
1706             ZOOM_connection_send_init (c);
1707         }
1708         else
1709         {
1710             c->error = ZOOM_ERROR_CONNECT;
1711             do_close (c);
1712             ZOOM_connection_put_event (c, event);
1713         }
1714     }
1715     else if (c->state == STATE_ESTABLISHED)
1716     {
1717         if (mask & ZOOM_SELECT_READ)
1718             do_read (c);
1719         if (c->cs && (mask & ZOOM_SELECT_WRITE))
1720             do_write (c);
1721     }
1722     else
1723     {
1724         event = ZOOM_Event_create (ZOOM_EVENT_UNKNOWN);
1725         ZOOM_connection_put_event (c, event);
1726         c->error = ZOOM_ERROR_INTERNAL;
1727         do_close (c);
1728     }
1729 #endif
1730     return 1;
1731 }
1732
1733 int ZOOM_connection_last_event(ZOOM_connection cs)
1734 {
1735     if (!cs)
1736         return ZOOM_EVENT_NONE;
1737     return cs->last_event;
1738 }
1739
1740 int ZOOM_event (int no, ZOOM_connection *cs)
1741 {
1742 #if HAVE_SYS_POLL_H
1743     struct pollfd pollfds[1024];
1744     ZOOM_connection poll_cs[1024];
1745 #else
1746     struct timeval tv;
1747     fd_set input, output, except;
1748 #endif
1749     int i, r, nfds;
1750     int max_fd = 0;
1751
1752     for (i = 0; i<no; i++)
1753     {
1754         ZOOM_connection c = cs[i];
1755         ZOOM_Event event;
1756         if (c && (event = ZOOM_connection_get_event(c)))
1757         {
1758             ZOOM_Event_destroy (event);
1759             return i+1;
1760         }
1761     }
1762     for (i = 0; i<no; i++)
1763     {
1764         ZOOM_connection c = cs[i];
1765         ZOOM_Event event;
1766         if (c && ZOOM_connection_exec_task (c))
1767         {
1768             if ((event = ZOOM_connection_get_event(c)))
1769             {
1770                 ZOOM_Event_destroy (event);
1771                 return i+1;
1772             }
1773         }
1774     }
1775 #if HAVE_SYS_POLL_H
1776
1777 #else
1778     tv.tv_sec = 15;
1779     tv.tv_usec = 0;
1780     
1781     FD_ZERO (&input);
1782     FD_ZERO (&output);
1783     FD_ZERO (&except);
1784 #endif
1785     nfds = 0;
1786     for (i = 0; i<no; i++)
1787     {
1788         ZOOM_connection c = cs[i];
1789         int fd, mask;
1790         
1791         if (!c)
1792             continue;
1793         fd = z3950_connection_socket(c);
1794         mask = z3950_connection_mask(c);
1795
1796         if (fd == -1)
1797             continue;
1798         if (max_fd < fd)
1799             max_fd = fd;
1800
1801 #if HAVE_SYS_POLL_H
1802         if (mask)
1803         {
1804             short poll_events = 0;
1805
1806             if (mask & ZOOM_SELECT_READ)
1807                 poll_events += POLLIN;
1808             if (mask & ZOOM_SELECT_WRITE)
1809                 poll_events += POLLOUT;
1810             if (mask & ZOOM_SELECT_EXCEPT)
1811                 poll_events += POLLERR;
1812             pollfds[nfds].fd = fd;
1813             pollfds[nfds].events = poll_events;
1814             pollfds[nfds].revents = 0;
1815             poll_cs[nfds] = c;
1816             nfds++;
1817         }
1818 #else
1819         if (mask & ZOOM_SELECT_READ)
1820         {
1821             FD_SET (fd, &input);
1822             nfds++;
1823         }
1824         if (mask & ZOOM_SELECT_WRITE)
1825         {
1826             FD_SET (fd, &output);
1827             nfds++;
1828         }
1829         if (mask & ZOOM_SELECT_EXCEPT)
1830         {
1831             FD_SET (fd, &except);
1832             nfds++;
1833         }
1834 #endif
1835     }
1836     if (!nfds)
1837         return 0;
1838 #if HAVE_SYS_POLL_H
1839     yaz_log (LOG_DEBUG, "poll start");
1840     r = poll (pollfds, nfds, 15000);
1841     yaz_log (LOG_DEBUG, "poll stop, returned r=%d", r);
1842     for (i = 0; i<nfds; i++)
1843     {
1844         ZOOM_connection c = poll_cs[i];
1845         if (r && c->mask)
1846         {
1847             int mask = 0;
1848             if (pollfds[i].revents & POLLIN)
1849                 mask += ZOOM_SELECT_READ;
1850             if (pollfds[i].revents & POLLOUT)
1851                 mask += ZOOM_SELECT_WRITE;
1852             if (pollfds[i].revents & POLLERR)
1853                 mask += ZOOM_SELECT_EXCEPT;
1854             if (mask)
1855                 ZOOM_connection_do_io(c, mask);
1856         }
1857         else if (r == 0 && c->mask)
1858         {
1859             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1860             /* timeout and this connection was waiting */
1861             c->error = ZOOM_ERROR_TIMEOUT;
1862             do_close (c);
1863             ZOOM_connection_put_event(c, event);
1864         }
1865     }
1866 #else
1867     yaz_log (LOG_DEBUG, "select start");
1868     r = select (max_fd+1, &input, &output, &except, &tv);
1869     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
1870     for (i = 0; i<no; i++)
1871     {
1872         ZOOM_connection c = cs[i];
1873         int fd, mask;
1874
1875         if (!c)
1876             continue;
1877         fd = z3950_connection_socket(c);
1878         mask = 0;
1879         if (r && c->mask)
1880         {
1881             /* no timeout and real socket */
1882             if (FD_ISSET(fd, &input))
1883                 mask += ZOOM_SELECT_READ;
1884             if (FD_ISSET(fd, &output))
1885                 mask += ZOOM_SELECT_WRITE;
1886             if (FD_ISSET(fd, &except))
1887                 mask += ZOOM_SELECT_EXCEPT;
1888             if (mask)
1889                 ZOOM_connection_do_io(c, mask);
1890         }
1891         if (r == 0 && c->mask)
1892         {
1893             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1894             /* timeout and this connection was waiting */
1895             c->error = ZOOM_ERROR_TIMEOUT;
1896             do_close (c);
1897             yaz_log (LOG_DEBUG, "timeout");
1898             ZOOM_connection_put_event(c, event);
1899         }
1900     }
1901 #endif
1902     for (i = 0; i<no; i++)
1903     {
1904         ZOOM_connection c = cs[i];
1905         ZOOM_Event event;
1906         if (c && (event = ZOOM_connection_get_event(c)))
1907         {
1908             ZOOM_Event_destroy (event);
1909             return i+1;
1910         }
1911     }
1912     return 0;
1913 }