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