GRS-1 render for ZOOM.
[yaz-moved-to-github.git] / zutil / zoom-c.c
1 /*
2  * $Id: zoom-c.c,v 1.5 2002-10-22 10:05:36 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 #include <yaz/charneg.h>
13 #include <yaz/ill.h>
14
15 #include "zoom-p.h"
16
17 #if HAVE_SYS_POLL_H
18 #include <sys/poll.h>
19 #endif
20
21 typedef enum {
22     zoom_pending,
23     zoom_complete
24 } zoom_ret;
25
26
27 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c);
28 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out);
29
30 static ZOOM_Event ZOOM_Event_create (int kind)
31 {
32     ZOOM_Event event = (ZOOM_Event) xmalloc (sizeof(*event));
33     event->kind = kind;
34     event->next = 0;
35     event->prev = 0;
36     return event;
37 }
38
39 static void ZOOM_Event_destroy (ZOOM_Event event)
40 {
41     xfree (event);
42 }
43
44 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
45 {
46     if (c->m_queue_back)
47     {
48         c->m_queue_back->prev = event;
49         assert (c->m_queue_front);
50     }
51     else
52     {
53         assert (!c->m_queue_front);
54         c->m_queue_front = event;
55     }
56     event->next = c->m_queue_back;
57     event->prev = 0;
58     c->m_queue_back = event;
59 }
60
61 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
62 {
63     ZOOM_Event event = c->m_queue_front;
64     if (!event)
65         return 0;
66     assert (c->m_queue_back);
67     c->m_queue_front = event->prev;
68     if (c->m_queue_front)
69     {
70         assert (c->m_queue_back);
71         c->m_queue_front->next = 0;
72     }
73     else
74         c->m_queue_back = 0;
75     c->last_event = event->kind;
76     return event;
77 }
78
79 static void clear_error (ZOOM_connection c)
80 {
81
82     switch (c->error)
83     {
84     case ZOOM_ERROR_CONNECT:
85     case ZOOM_ERROR_MEMORY:
86     case ZOOM_ERROR_DECODE:
87     case ZOOM_ERROR_CONNECTION_LOST:
88     case ZOOM_ERROR_INIT:
89     case ZOOM_ERROR_INTERNAL:
90         break;
91     default:
92         c->error = ZOOM_ERROR_NONE;
93         xfree (c->addinfo);
94         c->addinfo = 0;
95     }
96 }
97
98 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
99 {
100     ZOOM_task *taskp = &c->tasks;
101     while (*taskp)
102         taskp = &(*taskp)->next;
103     *taskp = (ZOOM_task) xmalloc (sizeof(**taskp));
104     (*taskp)->running = 0;
105     (*taskp)->which = which;
106     (*taskp)->next = 0;
107     clear_error (c);
108     return *taskp;
109 }
110
111 ZOOM_task ZOOM_connection_insert_task (ZOOM_connection c, int which)
112 {
113     ZOOM_task task = (ZOOM_task) xmalloc (sizeof(*task));
114
115     task->next = c->tasks;
116     c->tasks = task;
117
118     task->running = 0;
119     task->which = which;
120     clear_error (c);
121     return task;
122 }
123
124 void ZOOM_connection_remove_task (ZOOM_connection c)
125 {
126     ZOOM_task task = c->tasks;
127
128     if (task)
129     {
130         c->tasks = task->next;
131         switch (task->which)
132         {
133         case ZOOM_TASK_SEARCH:
134             ZOOM_resultset_destroy (task->u.search.resultset);
135             break;
136         case ZOOM_TASK_RETRIEVE:
137             ZOOM_resultset_destroy (task->u.retrieve.resultset);
138             break;
139         case ZOOM_TASK_CONNECT:
140             break;
141         case ZOOM_TASK_SCAN:
142             ZOOM_scanset_destroy (task->u.scan.scan);
143             break;
144         case ZOOM_TASK_PACKAGE:
145             ZOOM_package_destroy (task->u.package);
146             break;
147         default:
148             assert (0);
149         }
150         xfree (task);
151     }
152 }
153
154 void ZOOM_connection_remove_tasks (ZOOM_connection c)
155 {
156     while (c->tasks)
157         ZOOM_connection_remove_task(c);
158 }
159
160 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos);
161
162 ZOOM_API(ZOOM_connection)
163 ZOOM_connection_create (ZOOM_options options)
164 {
165     ZOOM_connection c = (ZOOM_connection) xmalloc (sizeof(*c));
166
167     c->cs = 0;
168     c->mask = 0;
169     c->reconnect_ok = 0;
170     c->state = STATE_IDLE;
171     c->error = ZOOM_ERROR_NONE;
172     c->addinfo = 0;
173     c->buf_in = 0;
174     c->len_in = 0;
175     c->buf_out = 0;
176     c->len_out = 0;
177     c->resultsets = 0;
178
179     c->options = ZOOM_options_create_with_parent(options);
180
181     c->host_port = 0;
182     c->proxy = 0;
183     
184     c->charset = c->lang = 0;
185
186     c->cookie_out = 0;
187     c->cookie_in = 0;
188     c->client_IP = 0;
189     c->tasks = 0;
190
191     c->odr_in = odr_createmem (ODR_DECODE);
192     c->odr_out = odr_createmem (ODR_ENCODE);
193
194     c->async = 0;
195     c->support_named_resultsets = 0;
196     c->last_event = ZOOM_EVENT_NONE;
197
198     c->m_queue_front = 0;
199     c->m_queue_back = 0;
200     return c;
201 }
202
203 /* set database names. Take local databases (if set); otherwise
204    take databases given in ZURL (if set); otherwise use Default */
205 static char **set_DatabaseNames (ZOOM_connection con, ZOOM_options options,
206                                  int *num)
207 {
208     char **databaseNames;
209     const char *c;
210     int no = 2;
211     const char *cp = ZOOM_options_get (options, "databaseName");
212     
213     if (!cp || !*cp)
214     {
215         if (strncmp (con->host_port, "unix:", 5) == 0)
216             cp = strchr (con->host_port+5, ':');
217         else
218             cp = strchr (con->host_port, '/');
219         if (cp)
220             cp++;
221     }
222     if (cp)
223     {
224         c = cp;
225         while ((c = strchr(c, '+')))
226         {
227             c++;
228             no++;
229         }
230     }
231     else
232         cp = "Default";
233     databaseNames = (char**)
234         odr_malloc (con->odr_out, no * sizeof(*databaseNames));
235     no = 0;
236     while (*cp)
237     {
238         c = strchr (cp, '+');
239         if (!c)
240             c = cp + strlen(cp);
241         else if (c == cp)
242         {
243             cp++;
244             continue;
245         }
246         /* cp ptr to first char of db name, c is char
247            following db name */
248         databaseNames[no] = (char*) odr_malloc (con->odr_out, 1+c-cp);
249         memcpy (databaseNames[no], cp, c-cp);
250         databaseNames[no++][c-cp] = '\0';
251         cp = c;
252         if (*cp)
253             cp++;
254     }
255     databaseNames[no] = NULL;
256     *num = no;
257     return databaseNames;
258 }
259
260 ZOOM_API(ZOOM_connection)
261 ZOOM_connection_new (const char *host, int portnum)
262 {
263     ZOOM_connection c = ZOOM_connection_create (0);
264
265     ZOOM_connection_connect (c, host, portnum);
266     return c;
267 }
268
269 ZOOM_API(void)
270 ZOOM_connection_connect(ZOOM_connection c,
271                         const char *host, int portnum)
272 {
273     const char *val;
274     ZOOM_task task;
275
276     if (c->cs)
277     {
278         yaz_log (LOG_DEBUG, "reconnect");
279         c->reconnect_ok = 1;
280         return;
281     }
282     yaz_log(LOG_DEBUG, "connect");
283     xfree (c->proxy);
284     val = ZOOM_options_get (c->options, "proxy");
285     if (val && *val)
286         c->proxy = xstrdup (val);
287     else
288         c->proxy = 0;
289
290     xfree (c->charset);
291     val = ZOOM_options_get (c->options, "charset");
292     if (val && *val)
293         c->charset = xstrdup (val);
294     else
295         c->charset = 0;
296
297     xfree (c->lang);
298     val = ZOOM_options_get (c->options, "lang");
299     if (val && *val)
300         c->lang = xstrdup (val);
301     else
302         c->lang = 0;
303
304     xfree (c->host_port);
305     if (portnum)
306     {
307         char hostn[128];
308         sprintf (hostn, "%.80s:%d", host, portnum);
309         c->host_port = xstrdup(hostn);
310     }
311     else
312         c->host_port = xstrdup(host);
313
314     ZOOM_options_set(c->options, "host", c->host_port);
315
316     val = ZOOM_options_get (c->options, "cookie");
317     if (val && *val)
318         c->cookie_out = xstrdup (val);
319
320     val = ZOOM_options_get (c->options, "clientIP");
321     if (val && *val)
322         c->client_IP = xstrdup (val);
323
324     c->async = ZOOM_options_get_bool (c->options, "async", 0);
325  
326     c->error = ZOOM_ERROR_NONE;
327
328     task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
329
330     if (!c->async)
331     {
332         while (ZOOM_event (1, &c))
333             ;
334     }
335 }
336
337 ZOOM_API(ZOOM_query)
338 ZOOM_query_create(void)
339 {
340     ZOOM_query s = (ZOOM_query) xmalloc (sizeof(*s));
341
342     s->refcount = 1;
343     s->query = 0;
344     s->sort_spec = 0;
345     s->odr = odr_createmem (ODR_ENCODE);
346
347     return s;
348 }
349
350 ZOOM_API(void)
351 ZOOM_query_destroy(ZOOM_query s)
352 {
353     if (!s)
354         return;
355
356     (s->refcount)--;
357     yaz_log (LOG_DEBUG, "ZOOM_query_destroy count=%d", s->refcount);
358     if (s->refcount == 0)
359     {
360         odr_destroy (s->odr);
361         xfree (s);
362     }
363 }
364
365 ZOOM_API(int)
366 ZOOM_query_prefix(ZOOM_query s, const char *str)
367 {
368     s->query = (Z_Query *) odr_malloc (s->odr, sizeof(*s->query));
369     s->query->which = Z_Query_type_1;
370     s->query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
371     if (!s->query->u.type_1)
372         return -1;
373     return 0;
374 }
375
376 ZOOM_API(int)
377 ZOOM_query_sortby(ZOOM_query s, const char *criteria)
378 {
379     s->sort_spec = yaz_sort_spec (s->odr, criteria);
380     if (!s->sort_spec)
381         return -1;
382     return 0;
383 }
384
385 static zoom_ret do_write(ZOOM_connection c);
386
387 ZOOM_API(void)
388 ZOOM_connection_destroy(ZOOM_connection c)
389 {
390     ZOOM_resultset r;
391     if (!c)
392         return;
393     if (c->cs)
394         cs_close (c->cs);
395     for (r = c->resultsets; r; r = r->next)
396         r->connection = 0;
397
398     xfree (c->buf_in);
399     xfree (c->addinfo);
400     odr_destroy (c->odr_in);
401     odr_destroy (c->odr_out);
402     ZOOM_options_destroy (c->options);
403     ZOOM_connection_remove_tasks (c);
404     xfree (c->host_port);
405     xfree (c->proxy);
406     xfree (c->charset);
407     xfree (c->lang);
408     xfree (c->cookie_out);
409     xfree (c->cookie_in);
410     xfree (c->client_IP);
411     xfree (c);
412 }
413
414 void ZOOM_resultset_addref (ZOOM_resultset r)
415 {
416     if (r)
417     {
418         (r->refcount)++;
419         yaz_log (LOG_DEBUG, "ZOOM_resultset_addref r=%p count=%d",
420                  r, r->refcount);
421     }
422 }
423 ZOOM_resultset ZOOM_resultset_create ()
424 {
425     ZOOM_resultset r = (ZOOM_resultset) xmalloc (sizeof(*r));
426
427     yaz_log (LOG_DEBUG, "ZOOM_resultset_create r = %p", r);
428     r->refcount = 1;
429     r->size = 0;
430     r->odr = odr_createmem (ODR_ENCODE);
431     r->start = 0;
432     r->piggyback = 1;
433     r->setname = 0;
434     r->count = 0;
435     r->record_cache = 0;
436     r->r_sort_spec = 0;
437     r->r_query = 0;
438     r->search = 0;
439     r->connection = 0;
440     r->next = 0;
441     return r;
442 }
443
444 ZOOM_API(ZOOM_resultset)
445 ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
446 {
447     ZOOM_resultset r;
448     ZOOM_query s = ZOOM_query_create();
449
450     ZOOM_query_prefix (s, q);
451
452     r = ZOOM_connection_search (c, s);
453     ZOOM_query_destroy (s);
454     return r;
455 }
456
457 ZOOM_API(ZOOM_resultset)
458 ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
459 {
460     ZOOM_resultset r = ZOOM_resultset_create ();
461     ZOOM_task task;
462     const char *cp;
463
464     r->r_sort_spec = q->sort_spec;
465     r->r_query = q->query;
466     r->search = q;
467
468     r->options = ZOOM_options_create_with_parent(c->options);
469
470     r->start = ZOOM_options_get_int(r->options, "start", 0);
471     r->count = ZOOM_options_get_int(r->options, "count", 0);
472     r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
473     cp = ZOOM_options_get (r->options, "setname");
474     if (cp)
475         r->setname = xstrdup (cp);
476     
477     r->connection = c;
478
479     r->next = c->resultsets;
480     c->resultsets = r;
481
482     task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
483     task->u.search.resultset = r;
484     ZOOM_resultset_addref (r);  
485
486     (q->refcount)++;
487
488     if (!c->async)
489     {
490         while (ZOOM_event (1, &c))
491             ;
492     }
493     return r;
494 }
495
496 ZOOM_API(void)
497 ZOOM_resultset_destroy(ZOOM_resultset r)
498 {
499     if (!r)
500         return;
501     (r->refcount)--;
502     yaz_log (LOG_DEBUG, "ZOOM_resultset_destroy r = %p count=%d",
503              r, r->refcount);
504     if (r->refcount == 0)
505     {
506         ZOOM_record_cache rc;
507
508         for (rc = r->record_cache; rc; rc = rc->next)
509             if (rc->rec.wrbuf_marc)
510                 wrbuf_free (rc->rec.wrbuf_marc, 1);
511         if (r->connection)
512         {
513             /* remove ourselves from the resultsets in connection */
514             ZOOM_resultset *rp = &r->connection->resultsets;
515             while (1)
516             {
517                 assert (*rp);   /* we must be in this list!! */
518                 if (*rp == r)
519                 {   /* OK, we're here - take us out of it */
520                     *rp = (*rp)->next;
521                     break;
522                 }
523                 rp = &(*rp)->next;
524             }
525         }
526         ZOOM_query_destroy (r->search);
527         ZOOM_options_destroy (r->options);
528         odr_destroy (r->odr);
529         xfree (r->setname);
530         xfree (r);
531     }
532 }
533
534 ZOOM_API(size_t)
535 ZOOM_resultset_size (ZOOM_resultset r)
536 {
537     return r->size;
538 }
539
540 static void do_close (ZOOM_connection c)
541 {
542     if (c->cs)
543         cs_close(c->cs);
544     c->cs = 0;
545     c->mask = 0;
546     c->state = STATE_IDLE;
547 }
548
549 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
550                                      int force_sync, int start, int count)
551 {
552     ZOOM_task task;
553     ZOOM_connection c;
554
555     if (!r)
556         return;
557     c = r->connection;
558     if (!c)
559         return;
560     task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
561     task->u.retrieve.resultset = r;
562     task->u.retrieve.start = start;
563     task->u.retrieve.count = count;
564
565     ZOOM_resultset_addref (r);
566
567     if (!r->connection->async || force_sync)
568         while (r->connection && ZOOM_event (1, &r->connection))
569             ;
570 }
571
572 ZOOM_API(void)
573 ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
574                         size_t start, size_t count)
575 {
576     int force_present = 0;
577
578     if (!r)
579         return ;
580     if (count && recs)
581         force_present = 1;
582     ZOOM_resultset_retrieve (r, force_present, start, count);
583     if (force_present)
584     {
585         size_t i;
586         for (i = 0; i< count; i++)
587             recs[i] = ZOOM_resultset_record_immediate (r, i+start);
588     }
589 }
590
591 static zoom_ret do_connect (ZOOM_connection c)
592 {
593     void *add;
594     const char *effective_host;
595
596     if (c->proxy)
597         effective_host = c->proxy;
598     else
599         effective_host = c->host_port;
600
601     yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
602
603     assert (!c->cs);
604     c->cs = cs_create_host (effective_host, 0, &add);
605
606     if (c->cs)
607     {
608         int ret = cs_connect (c->cs, add);
609         if (ret == 0)
610         {
611             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
612             ZOOM_connection_put_event(c, event);
613             ZOOM_connection_send_init(c);
614             c->state = STATE_ESTABLISHED;
615             return zoom_pending;
616         }
617         else if (ret > 0)
618         {
619             c->state = STATE_CONNECTING; 
620             c->mask = ZOOM_SELECT_EXCEPT;
621             if (c->cs->io_pending & CS_WANT_WRITE)
622                 c->mask += ZOOM_SELECT_WRITE;
623             if (c->cs->io_pending & CS_WANT_READ)
624                 c->mask += ZOOM_SELECT_READ;
625             return zoom_pending;
626         }
627     }
628     c->state = STATE_IDLE;
629     c->error = ZOOM_ERROR_CONNECT;
630     return zoom_complete;
631 }
632
633 int z3950_connection_socket(ZOOM_connection c)
634 {
635     if (c->cs)
636         return cs_fileno(c->cs);
637     return -1;
638 }
639
640 int z3950_connection_mask(ZOOM_connection c)
641 {
642     if (c->cs)
643         return c->mask;
644     return 0;
645 }
646
647 static void otherInfo_attach (ZOOM_connection c, Z_APDU *a, ODR out)
648 {
649     int i;
650     for (i = 0; i<200; i++)
651     {
652         size_t len;
653         Z_OtherInformation **oi;
654         char buf[80];
655         const char *val;
656         const char *cp;
657         int oidval;
658
659         sprintf (buf, "otherInfo%d", i);
660         val = ZOOM_options_get (c->options, buf);
661         if (!val)
662             break;
663         cp = strchr (val, ':');
664         if (!cp)
665             continue;
666         len = cp - val;
667         if (len >= sizeof(buf))
668             len = sizeof(buf)-1;
669         memcpy (buf, val, len);
670         buf[len] = '\0';
671         oidval = oid_getvalbyname (buf);
672         if (oidval == VAL_NONE)
673             continue;
674         
675         yaz_oi_APDU(a, &oi);
676         yaz_oi_set_string_oidval(oi, out, oidval, 1, cp+1);
677     }
678 }
679
680 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
681 {
682     assert (a);
683     if (c->cookie_out)
684     {
685         Z_OtherInformation **oi;
686         yaz_oi_APDU(a, &oi);
687         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
688     }
689     if (c->client_IP)
690     {
691         Z_OtherInformation **oi;
692         yaz_oi_APDU(a, &oi);
693         yaz_oi_set_string_oidval(oi, out, VAL_CLIENT_IP, 1, c->client_IP);
694     }
695     otherInfo_attach (c, a, out);
696     if (!z_APDU(out, &a, 0, 0))
697     {
698         FILE *outf = fopen("/tmp/apdu.txt", "a");
699         if (a && outf)
700         {
701             ODR odr_pr = odr_createmem(ODR_PRINT);
702             fprintf (outf, "a=%p\n", a);
703             odr_setprint(odr_pr, outf);
704             z_APDU(odr_pr, &a, 0, 0);
705             odr_destroy(odr_pr);
706         }
707         yaz_log (LOG_DEBUG, "encoding failed");
708         c->error = ZOOM_ERROR_ENCODE;
709         odr_reset(out);
710         return -1;
711     }
712     
713     return 0;
714 }
715
716 static zoom_ret send_APDU (ZOOM_connection c, Z_APDU *a)
717 {
718     ZOOM_Event event;
719     assert (a);
720     if (encode_APDU(c, a, c->odr_out))
721         return zoom_complete;
722     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
723     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
724     ZOOM_connection_put_event (c, event);
725     odr_reset(c->odr_out);
726     return do_write (c);
727 }
728
729 /* returns 1 if PDU was sent OK (still pending )
730            0 if PDU was not sent OK (nothing to wait for) 
731 */
732
733 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c)
734 {
735     const char *impname;
736     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
737     Z_InitRequest *ireq = apdu->u.initRequest;
738     Z_IdAuthentication *auth = (Z_IdAuthentication *)
739         odr_malloc(c->odr_out, sizeof(*auth));
740     const char *auth_groupId = ZOOM_options_get (c->options, "group");
741     const char *auth_userId = ZOOM_options_get (c->options, "user");
742     const char *auth_password = ZOOM_options_get (c->options, "pass");
743     
744     ODR_MASK_SET(ireq->options, Z_Options_search);
745     ODR_MASK_SET(ireq->options, Z_Options_present);
746     ODR_MASK_SET(ireq->options, Z_Options_scan);
747     ODR_MASK_SET(ireq->options, Z_Options_sort);
748     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
749     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
750     
751     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
752     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
753     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
754     
755     impname = ZOOM_options_get (c->options, "implementationName");
756     ireq->implementationName =
757         (char *) odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
758     strcpy (ireq->implementationName, "");
759     if (impname)
760     {
761         strcat (ireq->implementationName, impname);
762         strcat (ireq->implementationName, "/");
763     }                                          
764     strcat (ireq->implementationName, "ZOOM-C/YAZ");
765     
766     *ireq->maximumRecordSize =
767         ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
768     *ireq->preferredMessageSize =
769         ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
770     
771     if (auth_groupId || auth_password)
772     {
773         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
774         int i = 0;
775         pass->groupId = 0;
776         if (auth_groupId && *auth_groupId)
777         {
778             pass->groupId = (char *)
779                 odr_malloc(c->odr_out, strlen(auth_groupId)+1);
780             strcpy(pass->groupId, auth_groupId);
781             i++;
782         }
783         pass->userId = 0;
784         if (auth_userId && *auth_userId)
785         {
786             pass->userId = (char *)
787                 odr_malloc(c->odr_out, strlen(auth_userId)+1);
788             strcpy(pass->userId, auth_userId);
789             i++;
790         }
791         pass->password = 0;
792         if (auth_password && *auth_password)
793         {
794             pass->password = (char *)
795                 odr_malloc(c->odr_out, strlen(auth_password)+1);
796             strcpy(pass->password, auth_password);
797             i++;
798         }
799         if (i)
800         {
801             auth->which = Z_IdAuthentication_idPass;
802             auth->u.idPass = pass;
803             ireq->idAuthentication = auth;
804         }
805     }
806     else if (auth_userId)
807     {
808         auth->which = Z_IdAuthentication_open;
809         auth->u.open = (char *)
810             odr_malloc(c->odr_out, strlen(auth_userId)+1);
811         strcpy(auth->u.open, auth_userId);
812         ireq->idAuthentication = auth;
813     }
814     if (c->proxy)
815         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
816                                  VAL_PROXY, 1, c->host_port);
817     if (c->charset||c->lang)
818     {
819         Z_OtherInformation **oi;
820         Z_OtherInformationUnit *oi_unit;
821         
822         yaz_oi_APDU(apdu, &oi);
823         
824         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
825         {
826             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
827             
828             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
829             oi_unit->information.externallyDefinedInfo =
830                 yaz_set_proposal_charneg
831                 (c->odr_out,
832                  (const char **)&c->charset, (c->charset) ? 1:0,
833                  (const char **)&c->lang, (c->lang) ? 1:0, 1);
834         }
835     }
836     assert (apdu);
837     return send_APDU (c, apdu);
838 }
839
840 static zoom_ret ZOOM_connection_send_search (ZOOM_connection c)
841 {
842     ZOOM_resultset r;
843     int lslb, ssub, mspn;
844     const char *syntax;
845     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
846     Z_SearchRequest *search_req = apdu->u.searchRequest;
847     const char *elementSetName;
848     const char *smallSetElementSetName;
849     const char *mediumSetElementSetName;
850     const char *schema;
851
852     assert (c->tasks);
853     assert (c->tasks->which == ZOOM_TASK_SEARCH);
854
855     r = c->tasks->u.search.resultset;
856
857     elementSetName =
858         ZOOM_options_get (r->options, "elementSetName");
859     smallSetElementSetName  =
860         ZOOM_options_get (r->options, "smallSetElementSetName");
861     mediumSetElementSetName =
862         ZOOM_options_get (r->options, "mediumSetElementSetName");
863     schema =
864         ZOOM_options_get (r->options, "schema");
865
866     if (!smallSetElementSetName)
867         smallSetElementSetName = elementSetName;
868
869     if (!mediumSetElementSetName)
870         mediumSetElementSetName = elementSetName;
871
872     assert (r);
873     assert (r->r_query);
874
875     /* prepare query for the search request */
876     search_req->query = r->r_query;
877
878     search_req->databaseNames =
879         set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
880
881     /* get syntax (no need to provide unless piggyback is in effect) */
882     syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
883
884     lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
885     ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
886     mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
887     if (lslb != -1 && ssub != -1 && mspn != -1)
888     {
889         /* So're a Z39.50 expert? Let's hope you don't do sort */
890         *search_req->largeSetLowerBound = lslb;
891         *search_req->smallSetUpperBound = ssub;
892         *search_req->mediumSetPresentNumber = mspn;
893     }
894     else if (r->start == 0 && r->count > 0
895              && r->piggyback && !r->r_sort_spec && !schema)
896     {
897         /* Regular piggyback - do it unless we're going to do sort */
898         *search_req->largeSetLowerBound = 2000000000;
899         *search_req->smallSetUpperBound = r->count;
900         *search_req->mediumSetPresentNumber = r->count;
901         smallSetElementSetName = 0;  /* no need to provide this */
902     }
903     else
904     {
905         /* non-piggyback. Need not provide elementsets or syntaxes .. */
906         smallSetElementSetName = 0;
907         mediumSetElementSetName = 0;
908         syntax = 0;
909     }
910     if (smallSetElementSetName && *smallSetElementSetName)
911     {
912         Z_ElementSetNames *esn = (Z_ElementSetNames *)
913             odr_malloc (c->odr_out, sizeof(*esn));
914         
915         esn->which = Z_ElementSetNames_generic;
916         esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
917         search_req->smallSetElementSetNames = esn;
918     }
919     if (mediumSetElementSetName && *mediumSetElementSetName)
920     {
921         Z_ElementSetNames *esn = (Z_ElementSetNames *)
922             odr_malloc (c->odr_out, sizeof(*esn));
923         
924         esn->which = Z_ElementSetNames_generic;
925         esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
926         search_req->mediumSetElementSetNames = esn;
927     }
928     if (syntax)
929         search_req->preferredRecordSyntax =
930             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
931     
932     if (!r->setname)
933     {
934         if (c->support_named_resultsets)
935         {
936             char setname[14];
937             int ord;
938             /* find the lowest unused ordinal so that we re-use
939                result sets on the server. */
940             for (ord = 1; ; ord++)
941             {
942                 ZOOM_resultset rp;
943                 sprintf (setname, "%d", ord);
944                 for (rp = c->resultsets; rp; rp = rp->next)
945                     if (rp->setname && !strcmp (rp->setname, setname))
946                         break;
947                 if (!rp)
948                     break;
949             }
950             r->setname = xstrdup (setname);
951             yaz_log (LOG_DEBUG, "allocating set %s", r->setname);
952         }
953         else
954             r->setname = xstrdup ("default");
955         ZOOM_options_set (r->options, "setname", r->setname);
956     }
957     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
958     /* send search request */
959     return send_APDU (c, apdu);
960 }
961
962 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
963 {
964     Z_DefaultDiagFormat *r;
965     char *addinfo = 0;
966     
967     xfree (c->addinfo);
968     c->addinfo = 0;
969     if (p->which != Z_DiagRec_defaultFormat)
970     {
971         c->error = ZOOM_ERROR_DECODE;
972         return;
973     }
974     r = p->u.defaultFormat;
975     switch (r->which)
976     {
977     case Z_DefaultDiagFormat_v2Addinfo:
978         addinfo = r->u.v2Addinfo;
979         break;
980     case Z_DefaultDiagFormat_v3Addinfo:
981         addinfo = r->u.v3Addinfo;
982         break;
983     }
984     if (addinfo)
985         c->addinfo = xstrdup (addinfo);
986     c->error = *r->condition;
987 }
988
989 ZOOM_API(ZOOM_record)
990 ZOOM_record_clone (ZOOM_record srec)
991 {
992     char *buf;
993     int size;
994     ODR odr_enc;
995     ZOOM_record nrec;
996
997     odr_enc = odr_createmem(ODR_ENCODE);
998     if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
999         return 0;
1000     buf = odr_getbuf (odr_enc, &size, 0);
1001     
1002     nrec = (ZOOM_record) xmalloc (sizeof(*nrec));
1003     nrec->odr = odr_createmem(ODR_DECODE);
1004     nrec->wrbuf_marc = 0;
1005     odr_setbuf (nrec->odr, buf, size, 0);
1006     z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
1007     
1008     odr_destroy (odr_enc);
1009     return nrec;
1010 }
1011
1012 ZOOM_API(ZOOM_record)
1013 ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
1014 {
1015     return record_cache_lookup (s, pos);
1016 }
1017
1018 ZOOM_API(ZOOM_record)
1019 ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
1020 {
1021     ZOOM_resultset_retrieve (r, 1, pos, 1);
1022     return ZOOM_resultset_record_immediate (r, pos);
1023 }
1024
1025 ZOOM_API(void)
1026 ZOOM_record_destroy (ZOOM_record rec)
1027 {
1028     if (!rec)
1029         return;
1030     if (rec->wrbuf_marc)
1031         wrbuf_free (rec->wrbuf_marc, 1);
1032     odr_destroy (rec->odr);
1033     xfree (rec);
1034 }
1035
1036 ZOOM_API(const char *)
1037 ZOOM_record_get (ZOOM_record rec, const char *type, int *len)
1038 {
1039     Z_NamePlusRecord *npr;
1040     
1041     if (len)
1042         *len = 0; /* default return */
1043         
1044     if (!rec)
1045         return 0;
1046     npr = rec->npr;
1047     if (!npr)
1048         return 0;
1049     if (!strcmp (type, "database"))
1050     {
1051         if (len)
1052             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
1053         return npr->databaseName;
1054     }
1055     else if (!strcmp (type, "syntax"))
1056     {
1057         if (npr->which == Z_NamePlusRecord_databaseRecord)
1058         {
1059             Z_External *r = (Z_External *) npr->u.databaseRecord;
1060             oident *ent = oid_getentbyoid(r->direct_reference);
1061             if (ent)
1062             {
1063                 if (len)
1064                     *len = strlen(ent->desc);
1065                 return ent->desc;
1066             }
1067         }
1068         return "none";
1069     }
1070     else if (!strcmp (type, "render") && 
1071              npr->which == Z_NamePlusRecord_databaseRecord)
1072     {
1073         Z_External *r = (Z_External *) npr->u.databaseRecord;
1074         oident *ent = oid_getentbyoid(r->direct_reference);
1075         
1076         if (r->which == Z_External_sutrs)
1077         {
1078             if (len) *len = r->u.sutrs->len;
1079             return (const char *) r->u.sutrs->buf;
1080         }
1081         else if (r->which == Z_External_octet)
1082         {
1083             switch (ent->value)
1084             {
1085             case VAL_SOIF:
1086             case VAL_HTML:
1087             case VAL_SUTRS:
1088                 break;
1089             case VAL_TEXT_XML:
1090             case VAL_APPLICATION_XML:
1091                 break;
1092             default:
1093                 if (!rec->wrbuf_marc)
1094                     rec->wrbuf_marc = wrbuf_alloc();
1095                 wrbuf_rewind (rec->wrbuf_marc);
1096                 if (yaz_marc_decode ((const char *)
1097                                      r->u.octet_aligned->buf,
1098                                      rec->wrbuf_marc, 0,
1099                                      r->u.octet_aligned->len,
1100                                      0) > 0)
1101                 {
1102                     if (len) *len = wrbuf_len(rec->wrbuf_marc);
1103                     return wrbuf_buf(rec->wrbuf_marc);
1104                 }
1105             }
1106             if (len) *len = r->u.octet_aligned->len;
1107             return (const char *) r->u.octet_aligned->buf;
1108         }
1109         else if (r->which == Z_External_grs1)
1110         {
1111             if (!rec->wrbuf_marc)
1112                 rec->wrbuf_marc = wrbuf_alloc();
1113             wrbuf_rewind (rec->wrbuf_marc);
1114             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1115             if (len) 
1116                 *len = wrbuf_len(rec->wrbuf_marc);
1117             return wrbuf_buf(rec->wrbuf_marc);
1118         }
1119         return 0;
1120     }
1121     else if (!strcmp (type, "xml") && 
1122              npr->which == Z_NamePlusRecord_databaseRecord)
1123     {
1124         Z_External *r = (Z_External *) npr->u.databaseRecord;
1125         oident *ent = oid_getentbyoid(r->direct_reference);
1126         
1127         if (r->which == Z_External_sutrs)
1128         {
1129             if (len) *len = r->u.sutrs->len;
1130             return (const char *) r->u.sutrs->buf;
1131         }
1132         else if (r->which == Z_External_octet)
1133         {
1134             switch (ent->value)
1135             {
1136             case VAL_SOIF:
1137             case VAL_HTML:
1138             case VAL_SUTRS:
1139                 break;
1140             case VAL_TEXT_XML:
1141             case VAL_APPLICATION_XML:
1142                 break;
1143             default:
1144                 if (!rec->wrbuf_marc)
1145                     rec->wrbuf_marc = wrbuf_alloc();
1146                 wrbuf_rewind (rec->wrbuf_marc);
1147                 if (yaz_marc_decode ((const char *)
1148                                      r->u.octet_aligned->buf,
1149                                      rec->wrbuf_marc, 0,
1150                                      r->u.octet_aligned->len,
1151                                      2) > 0)
1152                 {
1153                     if (len) *len = wrbuf_len(rec->wrbuf_marc);
1154                     return wrbuf_buf(rec->wrbuf_marc);
1155                 }
1156             }
1157             if (len) *len = r->u.octet_aligned->len;
1158             return (const char *) r->u.octet_aligned->buf;
1159         }
1160         else if (r->which == Z_External_grs1)
1161         {
1162             if (len) *len = 5;
1163             return "GRS-1";
1164         }
1165         return 0;
1166     }
1167     else if (!strcmp (type, "raw"))
1168     {
1169         if (npr->which == Z_NamePlusRecord_databaseRecord)
1170         {
1171             Z_External *r = (Z_External *) npr->u.databaseRecord;
1172             
1173             if (r->which == Z_External_sutrs)
1174             {
1175                 if (len) *len = r->u.sutrs->len;
1176                 return (const char *) r->u.sutrs->buf;
1177             }
1178             else if (r->which == Z_External_octet)
1179             {
1180                 if (len) *len = r->u.octet_aligned->len;
1181                 return (const char *) r->u.octet_aligned->buf;
1182             }
1183             else /* grs-1, explain, ... */
1184             {
1185                 if (len) *len = -1;
1186                 return (const char *) npr->u.databaseRecord;
1187             }
1188         }
1189         return 0;
1190     }
1191     else if (!strcmp (type, "ext"))
1192     {
1193         if (npr->which == Z_NamePlusRecord_databaseRecord)
1194             return (const char *) npr->u.databaseRecord;
1195         return 0;
1196     }
1197     return 0;
1198 }
1199
1200 static void record_cache_add (ZOOM_resultset r, Z_NamePlusRecord *npr, int pos)
1201 {
1202     ZOOM_record_cache rc;
1203     const char *elementSetName =
1204         ZOOM_resultset_option_get (r, "elementSetName");
1205     const char *syntax = 
1206         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1207     
1208
1209     for (rc = r->record_cache; rc; rc = rc->next)
1210     {
1211         if (pos == rc->pos)
1212         {
1213             if ((!elementSetName && !rc->elementSetName)
1214                 || (elementSetName && rc->elementSetName &&
1215                     !strcmp (elementSetName, rc->elementSetName)))
1216             {
1217                 if ((!syntax && !rc->syntax)
1218                     || (syntax && rc->syntax &&
1219                         !strcmp (syntax, rc->syntax)))
1220                 {
1221                     /* not destroying rc->npr (it's handled by nmem )*/
1222                     rc->rec.npr = npr;
1223                     /* keeping wrbuf_marc too */
1224                     return;
1225                 }
1226             }
1227         }
1228     }
1229     rc = (ZOOM_record_cache) odr_malloc (r->odr, sizeof(*rc));
1230     rc->rec.npr = npr; 
1231     rc->rec.odr = 0;
1232     rc->rec.wrbuf_marc = 0;
1233     if (elementSetName)
1234         rc->elementSetName = odr_strdup (r->odr, elementSetName);
1235     else
1236         rc->elementSetName = 0;
1237
1238     if (syntax)
1239         rc->syntax = odr_strdup (r->odr, syntax);
1240     else
1241         rc->syntax = 0;
1242
1243     rc->pos = pos;
1244     rc->next = r->record_cache;
1245     r->record_cache = rc;
1246 }
1247
1248 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos)
1249 {
1250     ZOOM_record_cache rc;
1251     const char *elementSetName =
1252         ZOOM_resultset_option_get (r, "elementSetName");
1253     const char *syntax = 
1254         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1255     
1256     for (rc = r->record_cache; rc; rc = rc->next)
1257     {
1258         if (pos == rc->pos)
1259         {
1260             if ((!elementSetName && !rc->elementSetName)
1261                 || (elementSetName && rc->elementSetName &&
1262                     !strcmp (elementSetName, rc->elementSetName)))
1263             {
1264                 if ((!syntax && !rc->syntax)
1265                     || (syntax && rc->syntax &&
1266                         !strcmp (syntax, rc->syntax)))
1267                     return &rc->rec;
1268             }
1269         }
1270     }
1271     return 0;
1272 }
1273                                              
1274 static void handle_records (ZOOM_connection c, Z_Records *sr,
1275                             int present_phase)
1276 {
1277     ZOOM_resultset resultset;
1278
1279     if (!c->tasks)
1280         return ;
1281     switch (c->tasks->which)
1282     {
1283     case ZOOM_TASK_SEARCH:
1284         resultset = c->tasks->u.search.resultset;
1285         break;
1286     case ZOOM_TASK_RETRIEVE:
1287         resultset = c->tasks->u.retrieve.resultset;        
1288         break;
1289     default:
1290         return;
1291     }
1292     if (sr && sr->which == Z_Records_NSD)
1293     {
1294         Z_DiagRec dr, *dr_p = &dr;
1295         dr.which = Z_DiagRec_defaultFormat;
1296         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1297         
1298         response_diag (c, dr_p);
1299     }
1300     else if (sr && sr->which == Z_Records_multipleNSD)
1301     {
1302         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1303             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1304         else
1305             c->error = ZOOM_ERROR_DECODE;
1306     }
1307     else 
1308     {
1309         if (resultset->count + resultset->start > resultset->size)
1310             resultset->count = resultset->size - resultset->start;
1311         if (resultset->count < 0)
1312             resultset->count = 0;
1313         if (sr && sr->which == Z_Records_DBOSD)
1314         {
1315             int i;
1316             NMEM nmem = odr_extract_mem (c->odr_in);
1317             Z_NamePlusRecordList *p =
1318                 sr->u.databaseOrSurDiagnostics;
1319             for (i = 0; i<p->num_records; i++)
1320             {
1321                 record_cache_add (resultset, p->records[i],
1322                                   i+ resultset->start);
1323             }
1324             /* transfer our response to search_nmem .. we need it later */
1325             nmem_transfer (resultset->odr->mem, nmem);
1326             nmem_destroy (nmem);
1327             if (present_phase && p->num_records == 0)
1328             {
1329                 /* present response and we didn't get any records! */
1330                 c->error = ZOOM_ERROR_DECODE;
1331             }
1332         }
1333         else if (present_phase)
1334         {
1335             /* present response and we didn't get any records! */
1336             c->error = ZOOM_ERROR_DECODE;
1337         }
1338     }
1339 }
1340
1341 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1342 {
1343     handle_records (c, pr->records, 1);
1344 }
1345
1346 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1347 {
1348     ZOOM_resultset resultset;
1349
1350     yaz_log (LOG_DEBUG, "got search response");
1351
1352     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1353         return ;
1354
1355     resultset = c->tasks->u.search.resultset;
1356
1357     resultset->size = *sr->resultCount;
1358     handle_records (c, sr->records, 0);
1359 }
1360
1361 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1362 {
1363     if (res->diagnostics && res->num_diagnostics > 0)
1364         response_diag (c, res->diagnostics[0]);
1365 }
1366
1367 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1368 {
1369     NMEM nmem = odr_extract_mem (c->odr_in);
1370     ZOOM_scanset scan;
1371
1372     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1373         return 0;
1374     scan = c->tasks->u.scan.scan;
1375
1376     if (res->entries && res->entries->nonsurrogateDiagnostics)
1377         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1378     scan->scan_response = res;
1379     nmem_transfer (scan->odr->mem, nmem);
1380     if (res->stepSize)
1381         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1382     if (res->positionOfTerm)
1383         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1384     if (res->scanStatus)
1385         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1386     if (res->numberOfEntriesReturned)
1387         ZOOM_options_set_int (scan->options, "number",
1388                               *res->numberOfEntriesReturned);
1389     nmem_destroy (nmem);
1390     return 1;
1391 }
1392
1393 static zoom_ret send_sort (ZOOM_connection c)
1394 {
1395     ZOOM_resultset  resultset;
1396
1397     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1398         return zoom_complete;
1399
1400     resultset = c->tasks->u.search.resultset;
1401
1402     if (c->error)
1403     {
1404         resultset->r_sort_spec = 0;
1405         return zoom_complete;
1406     }
1407     if (resultset->r_sort_spec)
1408     {
1409         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1410         Z_SortRequest *req = apdu->u.sortRequest;
1411         
1412         req->num_inputResultSetNames = 1;
1413         req->inputResultSetNames = (Z_InternationalString **)
1414             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1415         req->inputResultSetNames[0] =
1416             odr_strdup (c->odr_out, resultset->setname);
1417         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1418         req->sortSequence = resultset->r_sort_spec;
1419         resultset->r_sort_spec = 0;
1420         return send_APDU (c, apdu);
1421     }
1422     return zoom_complete;
1423 }
1424
1425 static zoom_ret send_present (ZOOM_connection c)
1426 {
1427     Z_APDU *apdu = 0;
1428     Z_PresentRequest *req = 0;
1429     int i = 0;
1430     const char *syntax = 0;
1431     const char *elementSetName = 0;
1432     const char *schema = 0;
1433     ZOOM_resultset  resultset;
1434
1435     if (!c->tasks)
1436         return zoom_complete;
1437
1438     switch (c->tasks->which)
1439     {
1440     case ZOOM_TASK_SEARCH:
1441         resultset = c->tasks->u.search.resultset;
1442         break;
1443     case ZOOM_TASK_RETRIEVE:
1444         resultset = c->tasks->u.retrieve.resultset;
1445         resultset->start = c->tasks->u.retrieve.start;
1446         resultset->count = c->tasks->u.retrieve.count;
1447
1448         if (resultset->start >= resultset->size)
1449             return zoom_complete;
1450         if (resultset->start + resultset->count > resultset->size)
1451             resultset->count = resultset->size - resultset->start;
1452         break;
1453     default:
1454         return zoom_complete;
1455     }
1456
1457     syntax = ZOOM_resultset_option_get (resultset, "preferredRecordSyntax");
1458     elementSetName = ZOOM_resultset_option_get (resultset, "elementSetName");
1459     schema = ZOOM_resultset_option_get (resultset, "schema");
1460
1461     if (c->error)                  /* don't continue on error */
1462         return zoom_complete;
1463     if (resultset->start < 0)
1464         return zoom_complete;
1465     for (i = 0; i<resultset->count; i++)
1466     {
1467         ZOOM_record rec =
1468             record_cache_lookup (resultset, i + resultset->start);
1469         if (!rec)
1470             break;
1471     }
1472     if (i == resultset->count)
1473         return zoom_complete;
1474
1475     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1476     req = apdu->u.presentRequest;
1477
1478     resultset->start += i;
1479     resultset->count -= i;
1480     *req->resultSetStartPoint = resultset->start + 1;
1481     *req->numberOfRecordsRequested = resultset->count;
1482     assert (*req->numberOfRecordsRequested > 0);
1483
1484     if (syntax && *syntax)
1485         req->preferredRecordSyntax =
1486             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1487
1488     if (schema && *schema)
1489     {
1490         Z_RecordComposition *compo = (Z_RecordComposition *)
1491             odr_malloc (c->odr_out, sizeof(*compo));
1492
1493         req->recordComposition = compo;
1494         compo->which = Z_RecordComp_complex;
1495         compo->u.complex = (Z_CompSpec *)
1496             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1497         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
1498             odr_malloc(c->odr_out, sizeof(bool_t));
1499         *compo->u.complex->selectAlternativeSyntax = 0;
1500
1501         compo->u.complex->generic = (Z_Specification *)
1502             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1503
1504         compo->u.complex->generic->schema = (Odr_oid *)
1505             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, schema);
1506
1507         if (!compo->u.complex->generic->schema)
1508         {
1509             /* OID wasn't a schema! Try record syntax instead. */
1510
1511             compo->u.complex->generic->schema = (Odr_oid *)
1512                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, schema);
1513         }
1514         if (elementSetName && *elementSetName)
1515         {
1516             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1517                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1518             compo->u.complex->generic->elementSpec->which =
1519                 Z_ElementSpec_elementSetName;
1520             compo->u.complex->generic->elementSpec->u.elementSetName =
1521                 odr_strdup (c->odr_out, elementSetName);
1522         }
1523         else
1524             compo->u.complex->generic->elementSpec = 0;
1525         compo->u.complex->num_dbSpecific = 0;
1526         compo->u.complex->dbSpecific = 0;
1527         compo->u.complex->num_recordSyntax = 0;
1528         compo->u.complex->recordSyntax = 0;
1529     }
1530     else if (elementSetName && *elementSetName)
1531     {
1532         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1533             odr_malloc (c->odr_out, sizeof(*esn));
1534         Z_RecordComposition *compo = (Z_RecordComposition *)
1535             odr_malloc (c->odr_out, sizeof(*compo));
1536         
1537         esn->which = Z_ElementSetNames_generic;
1538         esn->u.generic = odr_strdup (c->odr_out, elementSetName);
1539         compo->which = Z_RecordComp_simple;
1540         compo->u.simple = esn;
1541         req->recordComposition = compo;
1542     }
1543     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1544     return send_APDU (c, apdu);
1545 }
1546
1547 ZOOM_API(ZOOM_scanset)
1548 ZOOM_connection_scan (ZOOM_connection c, const char *start)
1549 {
1550     ZOOM_scanset scan = (ZOOM_scanset) xmalloc (sizeof(*scan));
1551
1552     scan->connection = c;
1553     scan->odr = odr_createmem (ODR_DECODE);
1554     scan->options = ZOOM_options_create_with_parent (c->options);
1555     scan->refcount = 1;
1556     scan->scan_response = 0;
1557
1558     if ((scan->termListAndStartPoint =
1559          p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
1560                       start)))
1561     {
1562         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
1563         task->u.scan.scan = scan;
1564         
1565         (scan->refcount)++;
1566         if (!c->async)
1567         {
1568             while (ZOOM_event (1, &c))
1569                 ;
1570         }
1571     }
1572     return scan;
1573 }
1574
1575 ZOOM_API(void)
1576 ZOOM_scanset_destroy (ZOOM_scanset scan)
1577 {
1578     if (!scan)
1579         return;
1580     (scan->refcount)--;
1581     if (scan->refcount == 0)
1582     {
1583         odr_destroy (scan->odr);
1584         
1585         ZOOM_options_destroy (scan->options);
1586         xfree (scan);
1587     }
1588 }
1589
1590 static zoom_ret send_package (ZOOM_connection c)
1591 {
1592     ZOOM_Event event;
1593     if (!c->tasks)
1594         return zoom_complete;
1595     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
1596     
1597     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
1598     ZOOM_connection_put_event (c, event);
1599     
1600     return do_write_ex (c, c->tasks->u.package->buf_out,
1601                         c->tasks->u.package->len_out);
1602 }
1603
1604 static zoom_ret send_scan (ZOOM_connection c)
1605 {
1606     ZOOM_scanset scan;
1607     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
1608     Z_ScanRequest *req = apdu->u.scanRequest;
1609     if (!c->tasks)
1610         return zoom_complete;
1611     assert (c->tasks->which == ZOOM_TASK_SCAN);
1612     scan = c->tasks->u.scan.scan;
1613
1614     req->termListAndStartPoint = scan->termListAndStartPoint;
1615     req->attributeSet = scan->attributeSet;
1616
1617     *req->numberOfTermsRequested =
1618         ZOOM_options_get_int(scan->options, "number", 10);
1619
1620     req->preferredPositionInResponse =
1621         odr_intdup (c->odr_out,
1622                     ZOOM_options_get_int(scan->options, "position", 1));
1623
1624     req->stepSize =
1625         odr_intdup (c->odr_out,
1626                     ZOOM_options_get_int(scan->options, "stepSize", 0));
1627     
1628     req->databaseNames = set_DatabaseNames (c, scan->options, 
1629                                             &req->num_databaseNames);
1630
1631     return send_APDU (c, apdu);
1632 }
1633
1634 ZOOM_API(size_t)
1635 ZOOM_scanset_size (ZOOM_scanset scan)
1636 {
1637     if (!scan || !scan->scan_response || !scan->scan_response->entries)
1638         return 0;
1639     return scan->scan_response->entries->num_entries;
1640 }
1641
1642 ZOOM_API(const char *)
1643 ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
1644                                int *occ, int *len)
1645 {
1646     const char *term = 0;
1647     size_t noent = ZOOM_scanset_size (scan);
1648     Z_ScanResponse *res = scan->scan_response;
1649     
1650     *len = 0;
1651     *occ = 0;
1652     if (pos >= noent)
1653         return 0;
1654     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
1655     {
1656         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
1657         
1658         if (t->term->which == Z_Term_general)
1659         {
1660             term = (const char *) t->term->u.general->buf;
1661             *len = t->term->u.general->len;
1662         }
1663         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
1664     }
1665     return term;
1666 }
1667
1668 ZOOM_API(const char *)
1669 ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
1670 {
1671     return ZOOM_options_get (scan->options, key);
1672 }
1673
1674 ZOOM_API(void)
1675 ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
1676                               const char *val)
1677 {
1678     ZOOM_options_set (scan->options, key, val);
1679 }
1680
1681 static Z_APDU *create_es_package (ZOOM_package p, int type)
1682 {
1683     const char *str;
1684     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
1685     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1686     
1687     *req->function = Z_ExtendedServicesRequest_create;
1688     
1689     str = ZOOM_options_get(p->options, "package-name");
1690     if (str && *str)
1691         req->packageName = nmem_strdup (p->odr_out->mem, str);
1692     
1693     str = ZOOM_options_get(p->options, "user-id");
1694     if (str)
1695         req->userId = nmem_strdup (p->odr_out->mem, str);
1696     
1697     req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
1698                                               type);
1699
1700     str = ZOOM_options_get(p->options, "function");
1701     if (str)
1702     {
1703         if (!strcmp (str, "create"))
1704             *req->function = 1;
1705         if (!strcmp (str, "delete"))
1706             *req->function = 2;
1707         if (!strcmp (str, "modify"))
1708             *req->function = 3;
1709     }
1710     return apdu;
1711 }
1712
1713 static const char *ill_array_lookup (void *clientData, const char *idx)
1714 {
1715     ZOOM_package p = (ZOOM_package) clientData;
1716     return ZOOM_options_get (p->options, idx+4);
1717 }
1718
1719 static Z_External *encode_ill_request (ZOOM_package p)
1720 {
1721     ODR out = p->odr_out;
1722     ILL_Request *req;
1723     Z_External *r = 0;
1724     struct ill_get_ctl ctl;
1725         
1726     ctl.odr = p->odr_out;
1727     ctl.clientData = p;
1728     ctl.f = ill_array_lookup;
1729         
1730     req = ill_get_ILLRequest(&ctl, "ill", 0);
1731         
1732     if (!ill_Request (out, &req, 0, 0))
1733     {
1734         int ill_request_size;
1735         char *ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1736         if (ill_request_buf)
1737             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1738         return 0;
1739     }
1740     else
1741     {
1742         oident oid;
1743         int illRequest_size = 0;
1744         char *illRequest_buf = odr_getbuf (out, &illRequest_size, 0);
1745                 
1746         oid.proto = PROTO_GENERAL;
1747         oid.oclass = CLASS_GENERAL;
1748         oid.value = VAL_ISO_ILL_1;
1749                 
1750         r = (Z_External *) odr_malloc (out, sizeof(*r));
1751         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1752         r->indirect_reference = 0;
1753         r->descriptor = 0;
1754         r->which = Z_External_single;
1755                 
1756         r->u.single_ASN1_type = (Odr_oct *)
1757             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1758         r->u.single_ASN1_type->buf = (unsigned char*)
1759             odr_malloc (out, illRequest_size);
1760         r->u.single_ASN1_type->len = illRequest_size;
1761         r->u.single_ASN1_type->size = illRequest_size;
1762         memcpy (r->u.single_ASN1_type->buf, illRequest_buf, illRequest_size);
1763     }
1764     return r;
1765 }
1766
1767 static Z_ItemOrder *encode_item_order(ZOOM_package p)
1768 {
1769     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc (p->odr_out, sizeof(*req));
1770     const char *str;
1771     
1772     req->which=Z_IOItemOrder_esRequest;
1773     req->u.esRequest = (Z_IORequest *) 
1774         odr_malloc(p->odr_out,sizeof(Z_IORequest));
1775
1776     /* to keep part ... */
1777     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1778         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
1779     req->u.esRequest->toKeep->supplDescription = 0;
1780     req->u.esRequest->toKeep->contact = (Z_IOContact *)
1781         odr_malloc (p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
1782         
1783     str = ZOOM_options_get(p->options, "contact-name");
1784     req->u.esRequest->toKeep->contact->name = str ?
1785         nmem_strdup (p->odr_out->mem, str) : 0;
1786         
1787     str = ZOOM_options_get(p->options, "contact-phone");
1788     req->u.esRequest->toKeep->contact->phone = str ?
1789         nmem_strdup (p->odr_out->mem, str) : 0;
1790         
1791     str = ZOOM_options_get(p->options, "contact-email");
1792     req->u.esRequest->toKeep->contact->email = str ?
1793         nmem_strdup (p->odr_out->mem, str) : 0;
1794         
1795     req->u.esRequest->toKeep->addlBilling = 0;
1796         
1797     /* not to keep part ... */
1798     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1799         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
1800         
1801     req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
1802         odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
1803
1804     str = ZOOM_options_get(p->options, "itemorder-setname");
1805     if (!str)
1806         str = "default";
1807     req->u.esRequest->notToKeep->resultSetItem->resultSetId =
1808         nmem_strdup (p->odr_out->mem, str);
1809     req->u.esRequest->notToKeep->resultSetItem->item =
1810         (int *) odr_malloc(p->odr_out, sizeof(int));
1811         
1812     str = ZOOM_options_get(p->options, "itemorder-item");
1813     *req->u.esRequest->notToKeep->resultSetItem->item =
1814         (str ? atoi(str) : 1);
1815     
1816     req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
1817     
1818     return req;
1819 }
1820
1821 ZOOM_API(void)
1822     ZOOM_package_send (ZOOM_package p, const char *type)
1823 {
1824     Z_APDU *apdu = 0;
1825     ZOOM_connection c;
1826     if (!p)
1827         return;
1828     c = p->connection;
1829     odr_reset (p->odr_out);
1830     xfree (p->buf_out);
1831     p->buf_out = 0;
1832     if (!strcmp(type, "itemorder"))
1833     {
1834         Z_External *r;
1835         apdu = create_es_package (p, VAL_ITEMORDER);
1836         if (apdu)
1837         {
1838             r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
1839             
1840             r->direct_reference =
1841                 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
1842                                        VAL_ITEMORDER);
1843             r->descriptor = 0;
1844             r->which = Z_External_itemOrder;
1845             r->indirect_reference = 0;
1846             r->u.itemOrder = encode_item_order (p);
1847
1848             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
1849         }
1850     }
1851     if (apdu)
1852     {
1853         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
1854         {
1855             char *buf;
1856
1857             ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_PACKAGE);
1858             task->u.package = p;
1859             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
1860             p->buf_out = (char *) xmalloc (p->len_out);
1861             memcpy (p->buf_out, buf, p->len_out);
1862             
1863             (p->refcount)++;
1864             if (!c->async)
1865             {
1866                 while (ZOOM_event (1, &c))
1867                     ;
1868             }
1869         }
1870     }
1871 }
1872
1873 ZOOM_API(ZOOM_package)
1874     ZOOM_connection_package (ZOOM_connection c, ZOOM_options options)
1875 {
1876     ZOOM_package p = (ZOOM_package) xmalloc (sizeof(*p));
1877
1878     p->connection = c;
1879     p->odr_out = odr_createmem (ODR_ENCODE);
1880     p->options = ZOOM_options_create_with_parent2 (options, c->options);
1881     p->refcount = 1;
1882     p->buf_out = 0;
1883     p->len_out = 0;
1884     return p;
1885 }
1886
1887 ZOOM_API(void)
1888     ZOOM_package_destroy(ZOOM_package p)
1889 {
1890     if (!p)
1891         return;
1892     (p->refcount)--;
1893     if (p->refcount == 0)
1894     {
1895         odr_destroy (p->odr_out);
1896         xfree (p->buf_out);
1897         
1898         ZOOM_options_destroy (p->options);
1899         xfree (p);
1900     }
1901 }
1902
1903 ZOOM_API(const char *)
1904 ZOOM_package_option_get (ZOOM_package p, const char *key)
1905 {
1906     return ZOOM_options_get (p->options, key);
1907 }
1908
1909 ZOOM_API(void)
1910 ZOOM_package_option_set (ZOOM_package p, const char *key,
1911                               const char *val)
1912 {
1913     ZOOM_options_set (p->options, key, val);
1914 }
1915
1916 static int ZOOM_connection_exec_task (ZOOM_connection c)
1917 {
1918     ZOOM_task task = c->tasks;
1919     zoom_ret ret = zoom_complete;
1920
1921     if (!task)
1922     {
1923         yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task task=<null>");
1924         return 0;
1925     }
1926     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d run=%d",
1927              task->which, task->running);
1928     if (c->error != ZOOM_ERROR_NONE ||
1929         (!c->cs && task->which != ZOOM_TASK_CONNECT))
1930     {
1931         yaz_log (LOG_DEBUG, "remove tasks because of error = %d", c->error);
1932         ZOOM_connection_remove_tasks (c);
1933         return 0;
1934     }
1935     if (task->running)
1936     {
1937         yaz_log (LOG_DEBUG, "task already running");
1938         return 0;
1939     }
1940     task->running = 1;
1941     switch (task->which)
1942     {
1943     case ZOOM_TASK_SEARCH:
1944         ret = ZOOM_connection_send_search (c);
1945         break;
1946     case ZOOM_TASK_RETRIEVE:
1947         ret = send_present (c);
1948         break;
1949     case ZOOM_TASK_CONNECT:
1950         ret = do_connect(c);
1951         break;
1952     case ZOOM_TASK_SCAN:
1953         ret = send_scan(c);
1954         break;
1955     case ZOOM_TASK_PACKAGE:
1956         ret = send_package(c);
1957         break;
1958     }
1959     if (ret == zoom_complete)
1960     {
1961         yaz_log (LOG_DEBUG, "task removed (complete)");
1962         ZOOM_connection_remove_task (c);
1963         return 0;
1964     }
1965     yaz_log (LOG_DEBUG, "task pending");
1966     return 1;
1967 }
1968
1969 static zoom_ret send_sort_present (ZOOM_connection c)
1970 {
1971     zoom_ret r = send_sort (c);
1972     if (r == zoom_complete)
1973         r = send_present (c);
1974     return r;
1975 }
1976
1977 static int es_response (ZOOM_connection c,
1978                         Z_ExtendedServicesResponse *res)
1979 {
1980     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
1981         return 0;
1982     if (res->diagnostics && res->num_diagnostics > 0)
1983         response_diag(c, res->diagnostics[0]);
1984     if (res->taskPackage &&
1985         res->taskPackage->which == Z_External_extendedService)
1986     {
1987         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1988         Odr_oct *id = taskPackage->targetReference;
1989         
1990         if (id)
1991             ZOOM_options_setl (c->tasks->u.package->options,
1992                                "targetReference", (char*) id->buf, id->len);
1993     }
1994     return 1;
1995 }
1996
1997
1998 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
1999 {
2000     Z_InitResponse *initrs;
2001     
2002     c->mask = 0;
2003     yaz_log (LOG_DEBUG, "handle_apdu type=%d", apdu->which);
2004     switch(apdu->which)
2005     {
2006     case Z_APDU_initResponse:
2007         initrs = apdu->u.initResponse;
2008         if (!*initrs->result)
2009         {
2010             c->error = ZOOM_ERROR_INIT;
2011         }
2012         else
2013         {
2014             char *cookie =
2015                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
2016                                           VAL_COOKIE, 1, 0);
2017             xfree (c->cookie_in);
2018             c->cookie_in = 0;
2019             if (cookie)
2020                 c->cookie_in = xstrdup(cookie);
2021             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
2022                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
2023                 c->support_named_resultsets = 1;
2024             if (c->tasks)
2025             {
2026                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
2027                 ZOOM_connection_remove_task (c);
2028             }
2029             ZOOM_connection_exec_task (c);
2030         }
2031         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
2032         {
2033             NMEM tmpmem = nmem_create();
2034             Z_CharSetandLanguageNegotiation *p =
2035                 yaz_get_charneg_record(initrs->otherInfo);
2036             
2037             if (p)
2038             {
2039                 char *charset=NULL, *lang=NULL;
2040                 int sel;
2041                 
2042                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
2043                 yaz_log(LOG_DEBUG, "Target accepted: charset %s, "
2044                         "language %s, select %d",
2045                         charset ? charset : "none", lang ? lang : "none", sel);
2046                 if (charset)
2047                     ZOOM_connection_option_set (c, "negotiation-charset",
2048                                                 charset);
2049                 if (lang)
2050                     ZOOM_connection_option_set (c, "negotiation-lang",
2051                                                 lang);
2052                 nmem_destroy(tmpmem);
2053             }
2054         }       
2055         break;
2056     case Z_APDU_searchResponse:
2057         handle_search_response (c, apdu->u.searchResponse);
2058         if (send_sort_present (c) == zoom_complete)
2059             ZOOM_connection_remove_task (c);
2060         break;
2061     case Z_APDU_presentResponse:
2062         handle_present_response (c, apdu->u.presentResponse);
2063         if (send_present (c) == zoom_complete)
2064             ZOOM_connection_remove_task (c);
2065         break;
2066     case Z_APDU_sortResponse:
2067         sort_response (c, apdu->u.sortResponse);
2068         if (send_present (c) == zoom_complete)
2069             ZOOM_connection_remove_task (c);
2070         break;
2071     case Z_APDU_scanResponse:
2072         scan_response (c, apdu->u.scanResponse);
2073         ZOOM_connection_remove_task (c);
2074         break;
2075     case Z_APDU_extendedServicesResponse:
2076         es_response (c, apdu->u.extendedServicesResponse);
2077         ZOOM_connection_remove_task (c);
2078         break;
2079     case Z_APDU_close:
2080         if (c->reconnect_ok)
2081         {
2082             do_close(c);
2083             c->tasks->running = 0;
2084             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2085         }
2086         else
2087         {
2088             c->error = ZOOM_ERROR_CONNECTION_LOST;
2089             do_close(c);
2090         }
2091         break;
2092     default:
2093         c->error = ZOOM_ERROR_DECODE;
2094         do_close(c);
2095     }
2096 }
2097
2098 static int do_read (ZOOM_connection c)
2099 {
2100     int r;
2101     Z_APDU *apdu;
2102     ZOOM_Event event;
2103     
2104     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
2105     ZOOM_connection_put_event (c, event);
2106     
2107     yaz_log (LOG_DEBUG, "do_read len=%d", c->len_in);
2108
2109     r = cs_get (c->cs, &c->buf_in, &c->len_in);
2110     if (r == 1)
2111         return 0;
2112     if (r <= 0)
2113     {
2114         if (c->reconnect_ok)
2115         {
2116             do_close (c);
2117             c->reconnect_ok = 0;
2118             yaz_log (LOG_DEBUG, "reconnect read");
2119             c->tasks->running = 0;
2120             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2121         }
2122         else
2123         {
2124             c->error= ZOOM_ERROR_CONNECTION_LOST;
2125             do_close (c);
2126         }
2127     }
2128     else
2129     {
2130         ZOOM_Event event;
2131         odr_reset (c->odr_in);
2132         odr_setbuf (c->odr_in, c->buf_in, r, 0);
2133         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
2134         ZOOM_connection_put_event (c, event);
2135         if (!z_APDU (c->odr_in, &apdu, 0, 0))
2136         {
2137             c->error = ZOOM_ERROR_DECODE;
2138             do_close (c);
2139         }
2140         else
2141             handle_apdu (c, apdu);
2142         c->reconnect_ok = 0;
2143     }
2144     return 1;
2145 }
2146
2147 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
2148 {
2149     int r;
2150     ZOOM_Event event;
2151     
2152     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
2153     ZOOM_connection_put_event (c, event);
2154
2155     yaz_log (LOG_DEBUG, "do_write_ex len=%d", len_out);
2156     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
2157     {
2158         if (c->reconnect_ok)
2159         {
2160             do_close (c);
2161             c->reconnect_ok = 0;
2162             yaz_log (LOG_DEBUG, "reconnect write");
2163             c->tasks->running = 0;
2164             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2165             return zoom_complete;
2166         }
2167         if (c->state == STATE_CONNECTING)
2168             c->error = ZOOM_ERROR_CONNECT;
2169         else
2170             c->error = ZOOM_ERROR_CONNECTION_LOST;
2171         do_close (c);
2172         return zoom_complete;
2173     }
2174     else if (r == 1)
2175     {    
2176         c->mask = ZOOM_SELECT_EXCEPT;
2177         if (c->cs->io_pending & CS_WANT_WRITE)
2178             c->mask += ZOOM_SELECT_WRITE;
2179         if (c->cs->io_pending & CS_WANT_READ)
2180             c->mask += ZOOM_SELECT_READ;
2181         yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
2182     }
2183     else
2184     {
2185         // c->reconnect_ok = 0;
2186         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
2187         yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
2188     }
2189     return zoom_pending;
2190 }
2191
2192 static zoom_ret do_write(ZOOM_connection c)
2193 {
2194     return do_write_ex (c, c->buf_out, c->len_out);
2195 }
2196
2197
2198 ZOOM_API(const char *)
2199 ZOOM_connection_option_get (ZOOM_connection c, const char *key)
2200 {
2201     return ZOOM_options_get (c->options, key);
2202 }
2203
2204 ZOOM_API(void)
2205 ZOOM_connection_option_set (ZOOM_connection c, const char *key,
2206                                   const char *val)
2207 {
2208     ZOOM_options_set (c->options, key, val);
2209 }
2210
2211 ZOOM_API(const char *)
2212 ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
2213 {
2214     return ZOOM_options_get (r->options, key);
2215 }
2216
2217 ZOOM_API(void)
2218 ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
2219                                   const char *val)
2220 {
2221     ZOOM_options_set (r->options, key, val);
2222 }
2223
2224
2225 ZOOM_API(int)
2226 ZOOM_connection_errcode (ZOOM_connection c)
2227 {
2228     return ZOOM_connection_error (c, 0, 0);
2229 }
2230
2231 ZOOM_API(const char *)
2232 ZOOM_connection_errmsg (ZOOM_connection c)
2233 {
2234     const char *msg;
2235     ZOOM_connection_error (c, &msg, 0);
2236     return msg;
2237 }
2238
2239 ZOOM_API(const char *)
2240 ZOOM_connection_addinfo (ZOOM_connection c)
2241 {
2242     const char *addinfo;
2243     ZOOM_connection_error (c, 0, &addinfo);
2244     return addinfo;
2245 }
2246
2247 ZOOM_API(int)
2248 ZOOM_connection_error (ZOOM_connection c, const char **cp,
2249                             const char **addinfo)
2250 {
2251     int error = c->error;
2252     if (cp)
2253     {
2254         switch (error)
2255         {
2256         case ZOOM_ERROR_NONE:
2257             *cp = "No error"; break;
2258         case ZOOM_ERROR_CONNECT:
2259             *cp = "Connect failed"; break;
2260         case ZOOM_ERROR_MEMORY:
2261             *cp = "Out of memory"; break;
2262         case ZOOM_ERROR_ENCODE:
2263             *cp = "Encoding failed"; break;
2264         case ZOOM_ERROR_DECODE:
2265             *cp = "Decoding failed"; break;
2266         case ZOOM_ERROR_CONNECTION_LOST:
2267             *cp = "Connection lost"; break;
2268         case ZOOM_ERROR_INIT:
2269             *cp = "Init rejected"; break;
2270         case ZOOM_ERROR_INTERNAL:
2271             *cp = "Internal failure"; break;
2272         case ZOOM_ERROR_TIMEOUT:
2273             *cp = "Timeout"; break;
2274         default:
2275             *cp = diagbib1_str (error);
2276         }
2277     }
2278     if (addinfo)
2279     {
2280         if (c->addinfo)
2281             *addinfo = c->addinfo;
2282         else
2283             *addinfo = "";
2284     }
2285     return c->error;
2286 }
2287
2288 static int ZOOM_connection_do_io(ZOOM_connection c, int mask)
2289 {
2290     ZOOM_Event event = 0;
2291     int r = cs_look(c->cs);
2292     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
2293              c, mask, r);
2294     
2295     if (r == CS_NONE)
2296     {
2297         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
2298         c->error = ZOOM_ERROR_CONNECT;
2299         do_close (c);
2300         ZOOM_connection_put_event (c, event);
2301     }
2302     else if (r == CS_CONNECT)
2303     {
2304         int ret;
2305         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
2306
2307         ret = cs_rcvconnect (c->cs);
2308         yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
2309         if (ret == 1)
2310         {
2311             c->mask = ZOOM_SELECT_EXCEPT;
2312             if (c->cs->io_pending & CS_WANT_WRITE)
2313                 c->mask += ZOOM_SELECT_WRITE;
2314             if (c->cs->io_pending & CS_WANT_READ)
2315                 c->mask += ZOOM_SELECT_READ;
2316             ZOOM_connection_put_event (c, event);
2317         }
2318         else if (ret == 0)
2319         {
2320             ZOOM_connection_put_event (c, event);
2321             ZOOM_connection_send_init (c);
2322             c->state = STATE_ESTABLISHED;
2323         }
2324         else
2325         {
2326             c->error = ZOOM_ERROR_CONNECT;
2327             do_close (c);
2328             ZOOM_connection_put_event (c, event);
2329         }
2330     }
2331     else
2332     {
2333         if (mask & ZOOM_SELECT_READ)
2334             do_read (c);
2335         if (c->cs && (mask & ZOOM_SELECT_WRITE))
2336             do_write (c);
2337     }
2338     return 1;
2339 }
2340
2341 ZOOM_API(int)
2342 ZOOM_connection_last_event(ZOOM_connection cs)
2343 {
2344     if (!cs)
2345         return ZOOM_EVENT_NONE;
2346     return cs->last_event;
2347 }
2348
2349 ZOOM_API(int)
2350 ZOOM_event (int no, ZOOM_connection *cs)
2351 {
2352     int timeout = 5000;
2353 #if HAVE_SYS_POLL_H
2354     struct pollfd pollfds[1024];
2355     ZOOM_connection poll_cs[1024];
2356 #else
2357     struct timeval tv;
2358     fd_set input, output, except;
2359 #endif
2360     int i, r, nfds;
2361     int max_fd = 0;
2362
2363     for (i = 0; i<no; i++)
2364     {
2365         ZOOM_connection c = cs[i];
2366         ZOOM_Event event;
2367         if (c && (event = ZOOM_connection_get_event(c)))
2368         {
2369             ZOOM_Event_destroy (event);
2370             return i+1;
2371         }
2372     }
2373     for (i = 0; i<no; i++)
2374     {
2375         ZOOM_connection c = cs[i];
2376         ZOOM_Event event;
2377         if (c && ZOOM_connection_exec_task (c))
2378         {
2379             if ((event = ZOOM_connection_get_event(c)))
2380             {
2381                 ZOOM_Event_destroy (event);
2382                 return i+1;
2383             }
2384         }
2385     }
2386 #if HAVE_SYS_POLL_H
2387
2388 #else
2389     FD_ZERO (&input);
2390     FD_ZERO (&output);
2391     FD_ZERO (&except);
2392 #endif
2393     nfds = 0;
2394     for (i = 0; i<no; i++)
2395     {
2396         ZOOM_connection c = cs[i];
2397         int fd, mask;
2398         int this_timeout;
2399         
2400         if (!c)
2401             continue;
2402         fd = z3950_connection_socket(c);
2403         mask = z3950_connection_mask(c);
2404
2405         if (fd == -1)
2406             continue;
2407         if (max_fd < fd)
2408             max_fd = fd;
2409
2410         this_timeout = ZOOM_options_get_int (c->options, "timeout", -1);
2411         if (this_timeout != -1 && this_timeout < timeout)
2412             timeout = this_timeout;
2413 #if HAVE_SYS_POLL_H
2414         if (mask)
2415         {
2416             short poll_events = 0;
2417
2418             if (mask & ZOOM_SELECT_READ)
2419                 poll_events += POLLIN;
2420             if (mask & ZOOM_SELECT_WRITE)
2421                 poll_events += POLLOUT;
2422             if (mask & ZOOM_SELECT_EXCEPT)
2423                 poll_events += POLLERR;
2424             pollfds[nfds].fd = fd;
2425             pollfds[nfds].events = poll_events;
2426             pollfds[nfds].revents = 0;
2427             poll_cs[nfds] = c;
2428             nfds++;
2429         }
2430 #else
2431         if (mask & ZOOM_SELECT_READ)
2432         {
2433             FD_SET (fd, &input);
2434             nfds++;
2435         }
2436         if (mask & ZOOM_SELECT_WRITE)
2437         {
2438             FD_SET (fd, &output);
2439             nfds++;
2440         }
2441         if (mask & ZOOM_SELECT_EXCEPT)
2442         {
2443             FD_SET (fd, &except);
2444             nfds++;
2445         }
2446 #endif
2447     }
2448     if (timeout >= 5000)
2449         timeout = 30;
2450
2451     if (!nfds)
2452         return 0;
2453
2454 #if HAVE_SYS_POLL_H
2455     r = poll (pollfds, nfds, timeout * 1000);
2456     for (i = 0; i<nfds; i++)
2457     {
2458         ZOOM_connection c = poll_cs[i];
2459         if (r && c->mask)
2460         {
2461             int mask = 0;
2462             if (pollfds[i].revents & POLLIN)
2463                 mask += ZOOM_SELECT_READ;
2464             if (pollfds[i].revents & POLLOUT)
2465                 mask += ZOOM_SELECT_WRITE;
2466             if (pollfds[i].revents & POLLERR)
2467                 mask += ZOOM_SELECT_EXCEPT;
2468             if (mask)
2469                 ZOOM_connection_do_io(c, mask);
2470         }
2471         else if (r == 0 && c->mask)
2472         {
2473             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
2474             /* timeout and this connection was waiting */
2475             c->error = ZOOM_ERROR_TIMEOUT;
2476             do_close (c);
2477             ZOOM_connection_put_event(c, event);
2478         }
2479     }
2480 #else
2481     tv.tv_sec = timeout;
2482     tv.tv_usec = 0;
2483     yaz_log (LOG_DEBUG, "select start");
2484     r = select (max_fd+1, &input, &output, &except, &tv);
2485     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
2486     for (i = 0; i<no; i++)
2487     {
2488         ZOOM_connection c = cs[i];
2489         int fd, mask;
2490
2491         if (!c)
2492             continue;
2493         fd = z3950_connection_socket(c);
2494         mask = 0;
2495         if (r && c->mask)
2496         {
2497             /* no timeout and real socket */
2498             if (FD_ISSET(fd, &input))
2499                 mask += ZOOM_SELECT_READ;
2500             if (FD_ISSET(fd, &output))
2501                 mask += ZOOM_SELECT_WRITE;
2502             if (FD_ISSET(fd, &except))
2503                 mask += ZOOM_SELECT_EXCEPT;
2504             if (mask)
2505                 ZOOM_connection_do_io(c, mask);
2506         }
2507         if (r == 0 && c->mask)
2508         {
2509             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
2510             /* timeout and this connection was waiting */
2511             c->error = ZOOM_ERROR_TIMEOUT;
2512             do_close (c);
2513             yaz_log (LOG_DEBUG, "timeout");
2514             ZOOM_connection_put_event(c, event);
2515         }
2516     }
2517 #endif
2518     for (i = 0; i<no; i++)
2519     {
2520         ZOOM_connection c = cs[i];
2521         ZOOM_Event event;
2522         if (c && (event = ZOOM_connection_get_event(c)))
2523         {
2524             ZOOM_Event_destroy (event);
2525             return i+1;
2526         }
2527     }
2528     return 0;
2529 }