MARC8 decoding for yaz_iconv.
[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.12 2002-12-16 13:13:54 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             yaz_marc_t mt;
1098             switch (ent->value)
1099             {
1100             case VAL_SOIF:
1101             case VAL_HTML:
1102             case VAL_SUTRS:
1103                 break;
1104             case VAL_TEXT_XML:
1105             case VAL_APPLICATION_XML:
1106                 break;
1107             default:
1108                 if (!rec->wrbuf_marc)
1109                     rec->wrbuf_marc = wrbuf_alloc();
1110
1111                 mt = yaz_marc_create();
1112                 wrbuf_rewind (rec->wrbuf_marc);
1113                 if (yaz_marc_decode_wrbuf (
1114                         mt, (const char *) r->u.octet_aligned->buf,
1115                         r->u.octet_aligned->len,
1116                         rec->wrbuf_marc) > 0)
1117                 {
1118                     if (len)
1119                         *len = wrbuf_len(rec->wrbuf_marc);
1120                     yaz_marc_destroy(mt);
1121                     return wrbuf_buf(rec->wrbuf_marc);
1122                 }
1123                 yaz_marc_destroy(mt);
1124             }
1125             if (len) 
1126                 *len = r->u.octet_aligned->len;
1127             return (const char *) r->u.octet_aligned->buf;
1128         }
1129         else if (r->which == Z_External_grs1)
1130         {
1131             if (!rec->wrbuf_marc)
1132                 rec->wrbuf_marc = wrbuf_alloc();
1133             wrbuf_rewind (rec->wrbuf_marc);
1134             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1135             if (len) 
1136                 *len = wrbuf_len(rec->wrbuf_marc);
1137             return wrbuf_buf(rec->wrbuf_marc);
1138         }
1139         return 0;
1140     }
1141     else if (npr->which == Z_NamePlusRecord_databaseRecord &&
1142              (!strcmp (type, "xml") || !strcmp(type, "oai")))
1143     {
1144         Z_External *r = (Z_External *) npr->u.databaseRecord;
1145         oident *ent = oid_getentbyoid(r->direct_reference);
1146         
1147         if (r->which == Z_External_sutrs)
1148         {
1149             if (len) *len = r->u.sutrs->len;
1150             return (const char *) r->u.sutrs->buf;
1151         }
1152         else if (r->which == Z_External_octet)
1153         {
1154             yaz_marc_t mt;
1155             int marc_decode_type = YAZ_MARC_MARCXML;
1156
1157             if (!strcmp(type, "oai"))
1158                 marc_decode_type = YAZ_MARC_OAIMARC;
1159             switch (ent->value)
1160             {
1161             case VAL_SOIF:
1162             case VAL_HTML:
1163             case VAL_SUTRS:
1164                 break;
1165             case VAL_TEXT_XML:
1166             case VAL_APPLICATION_XML:
1167                 break;
1168             default:
1169                 if (!rec->wrbuf_marc)
1170                     rec->wrbuf_marc = wrbuf_alloc();
1171                 wrbuf_rewind (rec->wrbuf_marc);
1172                 mt = yaz_marc_create();
1173
1174                 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1175                 if (yaz_marc_decode_wrbuf (
1176                         mt, (const char *) r->u.octet_aligned->buf,
1177                         r->u.octet_aligned->len,
1178                         rec->wrbuf_marc) > 0)
1179                 {
1180                     if (len) 
1181                         *len = wrbuf_len(rec->wrbuf_marc);
1182                     yaz_marc_destroy(mt);
1183                     return wrbuf_buf(rec->wrbuf_marc);
1184                 }
1185                 yaz_marc_destroy(mt);
1186             }
1187             if (len) *len = r->u.octet_aligned->len;
1188             return (const char *) r->u.octet_aligned->buf;
1189         }
1190         else if (r->which == Z_External_grs1)
1191         {
1192             if (len) *len = 5;
1193             return "GRS-1";
1194         }
1195         return 0;
1196     }
1197     else if (!strcmp (type, "raw"))
1198     {
1199         if (npr->which == Z_NamePlusRecord_databaseRecord)
1200         {
1201             Z_External *r = (Z_External *) npr->u.databaseRecord;
1202             
1203             if (r->which == Z_External_sutrs)
1204             {
1205                 if (len) *len = r->u.sutrs->len;
1206                 return (const char *) r->u.sutrs->buf;
1207             }
1208             else if (r->which == Z_External_octet)
1209             {
1210                 if (len) *len = r->u.octet_aligned->len;
1211                 return (const char *) r->u.octet_aligned->buf;
1212             }
1213             else /* grs-1, explain, ... */
1214             {
1215                 if (len) *len = -1;
1216                 return (const char *) npr->u.databaseRecord;
1217             }
1218         }
1219         return 0;
1220     }
1221     else if (!strcmp (type, "ext"))
1222     {
1223         if (npr->which == Z_NamePlusRecord_databaseRecord)
1224             return (const char *) npr->u.databaseRecord;
1225         return 0;
1226     }
1227     return 0;
1228 }
1229
1230 static void record_cache_add (ZOOM_resultset r, Z_NamePlusRecord *npr, int pos)
1231 {
1232     ZOOM_record_cache rc;
1233     const char *elementSetName =
1234         ZOOM_resultset_option_get (r, "elementSetName");
1235     const char *syntax = 
1236         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1237     
1238
1239     for (rc = r->record_cache; rc; rc = rc->next)
1240     {
1241         if (pos == rc->pos)
1242         {
1243             if ((!elementSetName && !rc->elementSetName)
1244                 || (elementSetName && rc->elementSetName &&
1245                     !strcmp (elementSetName, rc->elementSetName)))
1246             {
1247                 if ((!syntax && !rc->syntax)
1248                     || (syntax && rc->syntax &&
1249                         !strcmp (syntax, rc->syntax)))
1250                 {
1251                     /* not destroying rc->npr (it's handled by nmem )*/
1252                     rc->rec.npr = npr;
1253                     /* keeping wrbuf_marc too */
1254                     return;
1255                 }
1256             }
1257         }
1258     }
1259     rc = (ZOOM_record_cache) odr_malloc (r->odr, sizeof(*rc));
1260     rc->rec.npr = npr; 
1261     rc->rec.odr = 0;
1262     rc->rec.wrbuf_marc = 0;
1263     if (elementSetName)
1264         rc->elementSetName = odr_strdup (r->odr, elementSetName);
1265     else
1266         rc->elementSetName = 0;
1267
1268     if (syntax)
1269         rc->syntax = odr_strdup (r->odr, syntax);
1270     else
1271         rc->syntax = 0;
1272
1273     rc->pos = pos;
1274     rc->next = r->record_cache;
1275     r->record_cache = rc;
1276 }
1277
1278 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos)
1279 {
1280     ZOOM_record_cache rc;
1281     const char *elementSetName =
1282         ZOOM_resultset_option_get (r, "elementSetName");
1283     const char *syntax = 
1284         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1285     
1286     for (rc = r->record_cache; rc; rc = rc->next)
1287     {
1288         if (pos == rc->pos)
1289         {
1290             if ((!elementSetName && !rc->elementSetName)
1291                 || (elementSetName && rc->elementSetName &&
1292                     !strcmp (elementSetName, rc->elementSetName)))
1293             {
1294                 if ((!syntax && !rc->syntax)
1295                     || (syntax && rc->syntax &&
1296                         !strcmp (syntax, rc->syntax)))
1297                     return &rc->rec;
1298             }
1299         }
1300     }
1301     return 0;
1302 }
1303                                              
1304 static void handle_records (ZOOM_connection c, Z_Records *sr,
1305                             int present_phase)
1306 {
1307     ZOOM_resultset resultset;
1308
1309     if (!c->tasks)
1310         return ;
1311     switch (c->tasks->which)
1312     {
1313     case ZOOM_TASK_SEARCH:
1314         resultset = c->tasks->u.search.resultset;
1315         break;
1316     case ZOOM_TASK_RETRIEVE:
1317         resultset = c->tasks->u.retrieve.resultset;        
1318         break;
1319     default:
1320         return;
1321     }
1322     if (sr && sr->which == Z_Records_NSD)
1323     {
1324         Z_DiagRec dr, *dr_p = &dr;
1325         dr.which = Z_DiagRec_defaultFormat;
1326         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1327         
1328         response_diag (c, dr_p);
1329     }
1330     else if (sr && sr->which == Z_Records_multipleNSD)
1331     {
1332         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1333             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1334         else
1335             set_bib1_error(c, ZOOM_ERROR_DECODE);
1336     }
1337     else 
1338     {
1339         if (resultset->count + resultset->start > resultset->size)
1340             resultset->count = resultset->size - resultset->start;
1341         if (resultset->count < 0)
1342             resultset->count = 0;
1343         if (sr && sr->which == Z_Records_DBOSD)
1344         {
1345             int i;
1346             NMEM nmem = odr_extract_mem (c->odr_in);
1347             Z_NamePlusRecordList *p =
1348                 sr->u.databaseOrSurDiagnostics;
1349             for (i = 0; i<p->num_records; i++)
1350             {
1351                 record_cache_add (resultset, p->records[i],
1352                                   i+ resultset->start);
1353             }
1354             /* transfer our response to search_nmem .. we need it later */
1355             nmem_transfer (resultset->odr->mem, nmem);
1356             nmem_destroy (nmem);
1357             if (present_phase && p->num_records == 0)
1358             {
1359                 /* present response and we didn't get any records! */
1360                 c->error = ZOOM_ERROR_DECODE;
1361             }
1362         }
1363         else if (present_phase)
1364         {
1365             /* present response and we didn't get any records! */
1366             set_bib1_error(c, ZOOM_ERROR_DECODE);
1367         }
1368     }
1369 }
1370
1371 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1372 {
1373     handle_records (c, pr->records, 1);
1374 }
1375
1376 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1377 {
1378     ZOOM_resultset resultset;
1379
1380     yaz_log (LOG_DEBUG, "got search response");
1381
1382     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1383         return ;
1384
1385     resultset = c->tasks->u.search.resultset;
1386
1387     resultset->size = *sr->resultCount;
1388     handle_records (c, sr->records, 0);
1389 }
1390
1391 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1392 {
1393     if (res->diagnostics && res->num_diagnostics > 0)
1394         response_diag (c, res->diagnostics[0]);
1395 }
1396
1397 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1398 {
1399     NMEM nmem = odr_extract_mem (c->odr_in);
1400     ZOOM_scanset scan;
1401
1402     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1403         return 0;
1404     scan = c->tasks->u.scan.scan;
1405
1406     if (res->entries && res->entries->nonsurrogateDiagnostics)
1407         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1408     scan->scan_response = res;
1409     nmem_transfer (scan->odr->mem, nmem);
1410     if (res->stepSize)
1411         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1412     if (res->positionOfTerm)
1413         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1414     if (res->scanStatus)
1415         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1416     if (res->numberOfEntriesReturned)
1417         ZOOM_options_set_int (scan->options, "number",
1418                               *res->numberOfEntriesReturned);
1419     nmem_destroy (nmem);
1420     return 1;
1421 }
1422
1423 static zoom_ret send_sort (ZOOM_connection c)
1424 {
1425     ZOOM_resultset  resultset;
1426
1427     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1428         return zoom_complete;
1429
1430     resultset = c->tasks->u.search.resultset;
1431
1432     if (c->error)
1433     {
1434         resultset->r_sort_spec = 0;
1435         return zoom_complete;
1436     }
1437     if (resultset->r_sort_spec)
1438     {
1439         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1440         Z_SortRequest *req = apdu->u.sortRequest;
1441         
1442         req->num_inputResultSetNames = 1;
1443         req->inputResultSetNames = (Z_InternationalString **)
1444             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1445         req->inputResultSetNames[0] =
1446             odr_strdup (c->odr_out, resultset->setname);
1447         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1448         req->sortSequence = resultset->r_sort_spec;
1449         resultset->r_sort_spec = 0;
1450         return send_APDU (c, apdu);
1451     }
1452     return zoom_complete;
1453 }
1454
1455 static zoom_ret send_present (ZOOM_connection c)
1456 {
1457     Z_APDU *apdu = 0;
1458     Z_PresentRequest *req = 0;
1459     int i = 0;
1460     const char *syntax = 0;
1461     const char *elementSetName = 0;
1462     const char *schema = 0;
1463     ZOOM_resultset  resultset;
1464
1465     if (!c->tasks)
1466         return zoom_complete;
1467
1468     switch (c->tasks->which)
1469     {
1470     case ZOOM_TASK_SEARCH:
1471         resultset = c->tasks->u.search.resultset;
1472         break;
1473     case ZOOM_TASK_RETRIEVE:
1474         resultset = c->tasks->u.retrieve.resultset;
1475         resultset->start = c->tasks->u.retrieve.start;
1476         resultset->count = c->tasks->u.retrieve.count;
1477
1478         if (resultset->start >= resultset->size)
1479             return zoom_complete;
1480         if (resultset->start + resultset->count > resultset->size)
1481             resultset->count = resultset->size - resultset->start;
1482         break;
1483     default:
1484         return zoom_complete;
1485     }
1486
1487     syntax = ZOOM_resultset_option_get (resultset, "preferredRecordSyntax");
1488     elementSetName = ZOOM_resultset_option_get (resultset, "elementSetName");
1489     schema = ZOOM_resultset_option_get (resultset, "schema");
1490
1491     if (c->error)                  /* don't continue on error */
1492         return zoom_complete;
1493     if (resultset->start < 0)
1494         return zoom_complete;
1495     for (i = 0; i<resultset->count; i++)
1496     {
1497         ZOOM_record rec =
1498             record_cache_lookup (resultset, i + resultset->start);
1499         if (!rec)
1500             break;
1501     }
1502     if (i == resultset->count)
1503         return zoom_complete;
1504
1505     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1506     req = apdu->u.presentRequest;
1507
1508     resultset->start += i;
1509     resultset->count -= i;
1510     *req->resultSetStartPoint = resultset->start + 1;
1511     *req->numberOfRecordsRequested = resultset->count;
1512     assert (*req->numberOfRecordsRequested > 0);
1513
1514     if (syntax && *syntax)
1515         req->preferredRecordSyntax =
1516             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1517
1518     if (schema && *schema)
1519     {
1520         Z_RecordComposition *compo = (Z_RecordComposition *)
1521             odr_malloc (c->odr_out, sizeof(*compo));
1522
1523         req->recordComposition = compo;
1524         compo->which = Z_RecordComp_complex;
1525         compo->u.complex = (Z_CompSpec *)
1526             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1527         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
1528             odr_malloc(c->odr_out, sizeof(bool_t));
1529         *compo->u.complex->selectAlternativeSyntax = 0;
1530
1531         compo->u.complex->generic = (Z_Specification *)
1532             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1533
1534         compo->u.complex->generic->schema = (Odr_oid *)
1535             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, schema);
1536
1537         if (!compo->u.complex->generic->schema)
1538         {
1539             /* OID wasn't a schema! Try record syntax instead. */
1540
1541             compo->u.complex->generic->schema = (Odr_oid *)
1542                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, schema);
1543         }
1544         if (elementSetName && *elementSetName)
1545         {
1546             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1547                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1548             compo->u.complex->generic->elementSpec->which =
1549                 Z_ElementSpec_elementSetName;
1550             compo->u.complex->generic->elementSpec->u.elementSetName =
1551                 odr_strdup (c->odr_out, elementSetName);
1552         }
1553         else
1554             compo->u.complex->generic->elementSpec = 0;
1555         compo->u.complex->num_dbSpecific = 0;
1556         compo->u.complex->dbSpecific = 0;
1557         compo->u.complex->num_recordSyntax = 0;
1558         compo->u.complex->recordSyntax = 0;
1559     }
1560     else if (elementSetName && *elementSetName)
1561     {
1562         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1563             odr_malloc (c->odr_out, sizeof(*esn));
1564         Z_RecordComposition *compo = (Z_RecordComposition *)
1565             odr_malloc (c->odr_out, sizeof(*compo));
1566         
1567         esn->which = Z_ElementSetNames_generic;
1568         esn->u.generic = odr_strdup (c->odr_out, elementSetName);
1569         compo->which = Z_RecordComp_simple;
1570         compo->u.simple = esn;
1571         req->recordComposition = compo;
1572     }
1573     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1574     return send_APDU (c, apdu);
1575 }
1576
1577 ZOOM_API(ZOOM_scanset)
1578 ZOOM_connection_scan (ZOOM_connection c, const char *start)
1579 {
1580     ZOOM_scanset scan = (ZOOM_scanset) xmalloc (sizeof(*scan));
1581
1582     scan->connection = c;
1583     scan->odr = odr_createmem (ODR_DECODE);
1584     scan->options = ZOOM_options_create_with_parent (c->options);
1585     scan->refcount = 1;
1586     scan->scan_response = 0;
1587
1588     if ((scan->termListAndStartPoint =
1589          p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
1590                       start)))
1591     {
1592         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
1593         task->u.scan.scan = scan;
1594         
1595         (scan->refcount)++;
1596         if (!c->async)
1597         {
1598             while (ZOOM_event (1, &c))
1599                 ;
1600         }
1601     }
1602     return scan;
1603 }
1604
1605 ZOOM_API(void)
1606 ZOOM_scanset_destroy (ZOOM_scanset scan)
1607 {
1608     if (!scan)
1609         return;
1610     (scan->refcount)--;
1611     if (scan->refcount == 0)
1612     {
1613         odr_destroy (scan->odr);
1614         
1615         ZOOM_options_destroy (scan->options);
1616         xfree (scan);
1617     }
1618 }
1619
1620 static zoom_ret send_package (ZOOM_connection c)
1621 {
1622     ZOOM_Event event;
1623     if (!c->tasks)
1624         return zoom_complete;
1625     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
1626     
1627     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
1628     ZOOM_connection_put_event (c, event);
1629     
1630     return do_write_ex (c, c->tasks->u.package->buf_out,
1631                         c->tasks->u.package->len_out);
1632 }
1633
1634 static zoom_ret send_scan (ZOOM_connection c)
1635 {
1636     ZOOM_scanset scan;
1637     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
1638     Z_ScanRequest *req = apdu->u.scanRequest;
1639     if (!c->tasks)
1640         return zoom_complete;
1641     assert (c->tasks->which == ZOOM_TASK_SCAN);
1642     scan = c->tasks->u.scan.scan;
1643
1644     req->termListAndStartPoint = scan->termListAndStartPoint;
1645     req->attributeSet = scan->attributeSet;
1646
1647     *req->numberOfTermsRequested =
1648         ZOOM_options_get_int(scan->options, "number", 10);
1649
1650     req->preferredPositionInResponse =
1651         odr_intdup (c->odr_out,
1652                     ZOOM_options_get_int(scan->options, "position", 1));
1653
1654     req->stepSize =
1655         odr_intdup (c->odr_out,
1656                     ZOOM_options_get_int(scan->options, "stepSize", 0));
1657     
1658     req->databaseNames = set_DatabaseNames (c, scan->options, 
1659                                             &req->num_databaseNames);
1660
1661     return send_APDU (c, apdu);
1662 }
1663
1664 ZOOM_API(size_t)
1665 ZOOM_scanset_size (ZOOM_scanset scan)
1666 {
1667     if (!scan || !scan->scan_response || !scan->scan_response->entries)
1668         return 0;
1669     return scan->scan_response->entries->num_entries;
1670 }
1671
1672 ZOOM_API(const char *)
1673 ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
1674                                int *occ, int *len)
1675 {
1676     const char *term = 0;
1677     size_t noent = ZOOM_scanset_size (scan);
1678     Z_ScanResponse *res = scan->scan_response;
1679     
1680     *len = 0;
1681     *occ = 0;
1682     if (pos >= noent)
1683         return 0;
1684     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
1685     {
1686         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
1687         
1688         if (t->term->which == Z_Term_general)
1689         {
1690             term = (const char *) t->term->u.general->buf;
1691             *len = t->term->u.general->len;
1692         }
1693         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
1694     }
1695     return term;
1696 }
1697
1698 ZOOM_API(const char *)
1699 ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
1700 {
1701     return ZOOM_options_get (scan->options, key);
1702 }
1703
1704 ZOOM_API(void)
1705 ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
1706                               const char *val)
1707 {
1708     ZOOM_options_set (scan->options, key, val);
1709 }
1710
1711 static Z_APDU *create_es_package (ZOOM_package p, int type)
1712 {
1713     const char *str;
1714     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
1715     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1716     
1717     *req->function = Z_ExtendedServicesRequest_create;
1718     
1719     str = ZOOM_options_get(p->options, "package-name");
1720     if (str && *str)
1721         req->packageName = nmem_strdup (p->odr_out->mem, str);
1722     
1723     str = ZOOM_options_get(p->options, "user-id");
1724     if (str)
1725         req->userId = nmem_strdup (p->odr_out->mem, str);
1726     
1727     req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
1728                                               type);
1729
1730     str = ZOOM_options_get(p->options, "function");
1731     if (str)
1732     {
1733         if (!strcmp (str, "create"))
1734             *req->function = 1;
1735         if (!strcmp (str, "delete"))
1736             *req->function = 2;
1737         if (!strcmp (str, "modify"))
1738             *req->function = 3;
1739     }
1740     return apdu;
1741 }
1742
1743 static const char *ill_array_lookup (void *clientData, const char *idx)
1744 {
1745     ZOOM_package p = (ZOOM_package) clientData;
1746     return ZOOM_options_get (p->options, idx+4);
1747 }
1748
1749 static Z_External *encode_ill_request (ZOOM_package p)
1750 {
1751     ODR out = p->odr_out;
1752     ILL_Request *req;
1753     Z_External *r = 0;
1754     struct ill_get_ctl ctl;
1755         
1756     ctl.odr = p->odr_out;
1757     ctl.clientData = p;
1758     ctl.f = ill_array_lookup;
1759         
1760     req = ill_get_ILLRequest(&ctl, "ill", 0);
1761         
1762     if (!ill_Request (out, &req, 0, 0))
1763     {
1764         int ill_request_size;
1765         char *ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1766         if (ill_request_buf)
1767             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1768         return 0;
1769     }
1770     else
1771     {
1772         oident oid;
1773         int illRequest_size = 0;
1774         char *illRequest_buf = odr_getbuf (out, &illRequest_size, 0);
1775                 
1776         oid.proto = PROTO_GENERAL;
1777         oid.oclass = CLASS_GENERAL;
1778         oid.value = VAL_ISO_ILL_1;
1779                 
1780         r = (Z_External *) odr_malloc (out, sizeof(*r));
1781         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1782         r->indirect_reference = 0;
1783         r->descriptor = 0;
1784         r->which = Z_External_single;
1785                 
1786         r->u.single_ASN1_type = (Odr_oct *)
1787             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1788         r->u.single_ASN1_type->buf = (unsigned char*)
1789             odr_malloc (out, illRequest_size);
1790         r->u.single_ASN1_type->len = illRequest_size;
1791         r->u.single_ASN1_type->size = illRequest_size;
1792         memcpy (r->u.single_ASN1_type->buf, illRequest_buf, illRequest_size);
1793     }
1794     return r;
1795 }
1796
1797 static Z_ItemOrder *encode_item_order(ZOOM_package p)
1798 {
1799     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc (p->odr_out, sizeof(*req));
1800     const char *str;
1801     
1802     req->which=Z_IOItemOrder_esRequest;
1803     req->u.esRequest = (Z_IORequest *) 
1804         odr_malloc(p->odr_out,sizeof(Z_IORequest));
1805
1806     /* to keep part ... */
1807     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1808         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
1809     req->u.esRequest->toKeep->supplDescription = 0;
1810     req->u.esRequest->toKeep->contact = (Z_IOContact *)
1811         odr_malloc (p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
1812         
1813     str = ZOOM_options_get(p->options, "contact-name");
1814     req->u.esRequest->toKeep->contact->name = str ?
1815         nmem_strdup (p->odr_out->mem, str) : 0;
1816         
1817     str = ZOOM_options_get(p->options, "contact-phone");
1818     req->u.esRequest->toKeep->contact->phone = str ?
1819         nmem_strdup (p->odr_out->mem, str) : 0;
1820         
1821     str = ZOOM_options_get(p->options, "contact-email");
1822     req->u.esRequest->toKeep->contact->email = str ?
1823         nmem_strdup (p->odr_out->mem, str) : 0;
1824         
1825     req->u.esRequest->toKeep->addlBilling = 0;
1826         
1827     /* not to keep part ... */
1828     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1829         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
1830         
1831     req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
1832         odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
1833
1834     str = ZOOM_options_get(p->options, "itemorder-setname");
1835     if (!str)
1836         str = "default";
1837     req->u.esRequest->notToKeep->resultSetItem->resultSetId =
1838         nmem_strdup (p->odr_out->mem, str);
1839     req->u.esRequest->notToKeep->resultSetItem->item =
1840         (int *) odr_malloc(p->odr_out, sizeof(int));
1841         
1842     str = ZOOM_options_get(p->options, "itemorder-item");
1843     *req->u.esRequest->notToKeep->resultSetItem->item =
1844         (str ? atoi(str) : 1);
1845     
1846     req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
1847     
1848     return req;
1849 }
1850
1851 ZOOM_API(void)
1852     ZOOM_package_send (ZOOM_package p, const char *type)
1853 {
1854     Z_APDU *apdu = 0;
1855     ZOOM_connection c;
1856     if (!p)
1857         return;
1858     c = p->connection;
1859     odr_reset (p->odr_out);
1860     xfree (p->buf_out);
1861     p->buf_out = 0;
1862     if (!strcmp(type, "itemorder"))
1863     {
1864         Z_External *r;
1865         apdu = create_es_package (p, VAL_ITEMORDER);
1866         if (apdu)
1867         {
1868             r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
1869             
1870             r->direct_reference =
1871                 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
1872                                        VAL_ITEMORDER);
1873             r->descriptor = 0;
1874             r->which = Z_External_itemOrder;
1875             r->indirect_reference = 0;
1876             r->u.itemOrder = encode_item_order (p);
1877
1878             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
1879         }
1880     }
1881     if (apdu)
1882     {
1883         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
1884         {
1885             char *buf;
1886
1887             ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_PACKAGE);
1888             task->u.package = p;
1889             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
1890             p->buf_out = (char *) xmalloc (p->len_out);
1891             memcpy (p->buf_out, buf, p->len_out);
1892             
1893             (p->refcount)++;
1894             if (!c->async)
1895             {
1896                 while (ZOOM_event (1, &c))
1897                     ;
1898             }
1899         }
1900     }
1901 }
1902
1903 ZOOM_API(ZOOM_package)
1904     ZOOM_connection_package (ZOOM_connection c, ZOOM_options options)
1905 {
1906     ZOOM_package p = (ZOOM_package) xmalloc (sizeof(*p));
1907
1908     p->connection = c;
1909     p->odr_out = odr_createmem (ODR_ENCODE);
1910     p->options = ZOOM_options_create_with_parent2 (options, c->options);
1911     p->refcount = 1;
1912     p->buf_out = 0;
1913     p->len_out = 0;
1914     return p;
1915 }
1916
1917 ZOOM_API(void)
1918     ZOOM_package_destroy(ZOOM_package p)
1919 {
1920     if (!p)
1921         return;
1922     (p->refcount)--;
1923     if (p->refcount == 0)
1924     {
1925         odr_destroy (p->odr_out);
1926         xfree (p->buf_out);
1927         
1928         ZOOM_options_destroy (p->options);
1929         xfree (p);
1930     }
1931 }
1932
1933 ZOOM_API(const char *)
1934 ZOOM_package_option_get (ZOOM_package p, const char *key)
1935 {
1936     return ZOOM_options_get (p->options, key);
1937 }
1938
1939 ZOOM_API(void)
1940 ZOOM_package_option_set (ZOOM_package p, const char *key,
1941                               const char *val)
1942 {
1943     ZOOM_options_set (p->options, key, val);
1944 }
1945
1946 static int ZOOM_connection_exec_task (ZOOM_connection c)
1947 {
1948     ZOOM_task task = c->tasks;
1949     zoom_ret ret = zoom_complete;
1950
1951     if (!task)
1952     {
1953         yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task task=<null>");
1954         return 0;
1955     }
1956     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d run=%d",
1957              task->which, task->running);
1958     if (c->error != ZOOM_ERROR_NONE ||
1959         (!c->cs && task->which != ZOOM_TASK_CONNECT))
1960     {
1961         yaz_log (LOG_DEBUG, "remove tasks because of error = %d", c->error);
1962         ZOOM_connection_remove_tasks (c);
1963         return 0;
1964     }
1965     if (task->running)
1966     {
1967         yaz_log (LOG_DEBUG, "task already running");
1968         return 0;
1969     }
1970     task->running = 1;
1971     switch (task->which)
1972     {
1973     case ZOOM_TASK_SEARCH:
1974         ret = ZOOM_connection_send_search (c);
1975         break;
1976     case ZOOM_TASK_RETRIEVE:
1977         ret = send_present (c);
1978         break;
1979     case ZOOM_TASK_CONNECT:
1980         ret = do_connect(c);
1981         break;
1982     case ZOOM_TASK_SCAN:
1983         ret = send_scan(c);
1984         break;
1985     case ZOOM_TASK_PACKAGE:
1986         ret = send_package(c);
1987         break;
1988     }
1989     if (ret == zoom_complete)
1990     {
1991         yaz_log (LOG_DEBUG, "task removed (complete)");
1992         ZOOM_connection_remove_task (c);
1993         return 0;
1994     }
1995     yaz_log (LOG_DEBUG, "task pending");
1996     return 1;
1997 }
1998
1999 static zoom_ret send_sort_present (ZOOM_connection c)
2000 {
2001     zoom_ret r = send_sort (c);
2002     if (r == zoom_complete)
2003         r = send_present (c);
2004     return r;
2005 }
2006
2007 static int es_response (ZOOM_connection c,
2008                         Z_ExtendedServicesResponse *res)
2009 {
2010     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
2011         return 0;
2012     if (res->diagnostics && res->num_diagnostics > 0)
2013         response_diag(c, res->diagnostics[0]);
2014     if (res->taskPackage &&
2015         res->taskPackage->which == Z_External_extendedService)
2016     {
2017         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
2018         Odr_oct *id = taskPackage->targetReference;
2019         
2020         if (id)
2021             ZOOM_options_setl (c->tasks->u.package->options,
2022                                "targetReference", (char*) id->buf, id->len);
2023     }
2024     return 1;
2025 }
2026
2027
2028 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
2029 {
2030     Z_InitResponse *initrs;
2031     
2032     c->mask = 0;
2033     yaz_log (LOG_DEBUG, "handle_apdu type=%d", apdu->which);
2034     switch(apdu->which)
2035     {
2036     case Z_APDU_initResponse:
2037         initrs = apdu->u.initResponse;
2038         ZOOM_connection_option_set(c, "targetImplementationId",
2039                                    initrs->implementationId ?
2040                                    initrs->implementationId : "");
2041         ZOOM_connection_option_set(c, "targetImplementationName",
2042                                    initrs->implementationName ?
2043                                    initrs->implementationName : "");
2044         ZOOM_connection_option_set(c, "targetImplementationVersion",
2045                                    initrs->implementationVersion ?
2046                                    initrs->implementationVersion : "");
2047         if (!*initrs->result)
2048         {
2049             set_bib1_error(c, ZOOM_ERROR_INIT);
2050         }
2051         else
2052         {
2053             char *cookie =
2054                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
2055                                           VAL_COOKIE, 1, 0);
2056             xfree (c->cookie_in);
2057             c->cookie_in = 0;
2058             if (cookie)
2059                 c->cookie_in = xstrdup(cookie);
2060             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
2061                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
2062                 c->support_named_resultsets = 1;
2063             if (c->tasks)
2064             {
2065                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
2066                 ZOOM_connection_remove_task (c);
2067             }
2068             ZOOM_connection_exec_task (c);
2069         }
2070         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
2071         {
2072             NMEM tmpmem = nmem_create();
2073             Z_CharSetandLanguageNegotiation *p =
2074                 yaz_get_charneg_record(initrs->otherInfo);
2075             
2076             if (p)
2077             {
2078                 char *charset=NULL, *lang=NULL;
2079                 int sel;
2080                 
2081                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
2082                 yaz_log(LOG_DEBUG, "Target accepted: charset %s, "
2083                         "language %s, select %d",
2084                         charset ? charset : "none", lang ? lang : "none", sel);
2085                 if (charset)
2086                     ZOOM_connection_option_set (c, "negotiation-charset",
2087                                                 charset);
2088                 if (lang)
2089                     ZOOM_connection_option_set (c, "negotiation-lang",
2090                                                 lang);
2091                 nmem_destroy(tmpmem);
2092             }
2093         }       
2094         break;
2095     case Z_APDU_searchResponse:
2096         handle_search_response (c, apdu->u.searchResponse);
2097         if (send_sort_present (c) == zoom_complete)
2098             ZOOM_connection_remove_task (c);
2099         break;
2100     case Z_APDU_presentResponse:
2101         handle_present_response (c, apdu->u.presentResponse);
2102         if (send_present (c) == zoom_complete)
2103             ZOOM_connection_remove_task (c);
2104         break;
2105     case Z_APDU_sortResponse:
2106         sort_response (c, apdu->u.sortResponse);
2107         if (send_present (c) == zoom_complete)
2108             ZOOM_connection_remove_task (c);
2109         break;
2110     case Z_APDU_scanResponse:
2111         scan_response (c, apdu->u.scanResponse);
2112         ZOOM_connection_remove_task (c);
2113         break;
2114     case Z_APDU_extendedServicesResponse:
2115         es_response (c, apdu->u.extendedServicesResponse);
2116         ZOOM_connection_remove_task (c);
2117         break;
2118     case Z_APDU_close:
2119         if (c->reconnect_ok)
2120         {
2121             do_close(c);
2122             c->tasks->running = 0;
2123             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2124         }
2125         else
2126         {
2127             set_bib1_error(c, ZOOM_ERROR_CONNECTION_LOST);
2128             do_close(c);
2129         }
2130         break;
2131     default:
2132         set_bib1_error(c, ZOOM_ERROR_DECODE);
2133         do_close(c);
2134     }
2135 }
2136
2137 static int do_read (ZOOM_connection c)
2138 {
2139     int r;
2140     Z_APDU *apdu;
2141     ZOOM_Event event;
2142     
2143     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
2144     ZOOM_connection_put_event (c, event);
2145     
2146     yaz_log (LOG_DEBUG, "do_read len=%d", c->len_in);
2147
2148     r = cs_get (c->cs, &c->buf_in, &c->len_in);
2149     if (r == 1)
2150         return 0;
2151     if (r <= 0)
2152     {
2153         if (c->reconnect_ok)
2154         {
2155             do_close (c);
2156             c->reconnect_ok = 0;
2157             yaz_log (LOG_DEBUG, "reconnect read");
2158             c->tasks->running = 0;
2159             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2160         }
2161         else
2162         {
2163             c->error= ZOOM_ERROR_CONNECTION_LOST;
2164             do_close (c);
2165         }
2166     }
2167     else
2168     {
2169         ZOOM_Event event;
2170         odr_reset (c->odr_in);
2171         odr_setbuf (c->odr_in, c->buf_in, r, 0);
2172         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
2173         ZOOM_connection_put_event (c, event);
2174         if (!z_APDU (c->odr_in, &apdu, 0, 0))
2175         {
2176             set_bib1_error(c, ZOOM_ERROR_DECODE);
2177             do_close (c);
2178         }
2179         else
2180             handle_apdu (c, apdu);
2181         c->reconnect_ok = 0;
2182     }
2183     return 1;
2184 }
2185
2186 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
2187 {
2188     int r;
2189     ZOOM_Event event;
2190     
2191     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
2192     ZOOM_connection_put_event (c, event);
2193
2194     yaz_log (LOG_DEBUG, "do_write_ex len=%d", len_out);
2195     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
2196     {
2197         if (c->reconnect_ok)
2198         {
2199             do_close (c);
2200             c->reconnect_ok = 0;
2201             yaz_log (LOG_DEBUG, "reconnect write");
2202             c->tasks->running = 0;
2203             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2204             return zoom_complete;
2205         }
2206         if (c->state == STATE_CONNECTING)
2207             set_bib1_error(c, ZOOM_ERROR_CONNECT);
2208         else
2209             set_bib1_error(c, ZOOM_ERROR_CONNECTION_LOST);
2210         do_close (c);
2211         return zoom_complete;
2212     }
2213     else if (r == 1)
2214     {    
2215         c->mask = ZOOM_SELECT_EXCEPT;
2216         if (c->cs->io_pending & CS_WANT_WRITE)
2217             c->mask += ZOOM_SELECT_WRITE;
2218         if (c->cs->io_pending & CS_WANT_READ)
2219             c->mask += ZOOM_SELECT_READ;
2220         yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
2221     }
2222     else
2223     {
2224         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
2225         yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
2226     }
2227     return zoom_pending;
2228 }
2229
2230 static zoom_ret do_write(ZOOM_connection c)
2231 {
2232     return do_write_ex (c, c->buf_out, c->len_out);
2233 }
2234
2235
2236 ZOOM_API(const char *)
2237 ZOOM_connection_option_get (ZOOM_connection c, const char *key)
2238 {
2239     return ZOOM_options_get (c->options, key);
2240 }
2241
2242 ZOOM_API(void)
2243 ZOOM_connection_option_set (ZOOM_connection c, const char *key,
2244                                   const char *val)
2245 {
2246     ZOOM_options_set (c->options, key, val);
2247 }
2248
2249 ZOOM_API(const char *)
2250 ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
2251 {
2252     return ZOOM_options_get (r->options, key);
2253 }
2254
2255 ZOOM_API(void)
2256 ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
2257                                   const char *val)
2258 {
2259     ZOOM_options_set (r->options, key, val);
2260 }
2261
2262
2263 ZOOM_API(int)
2264 ZOOM_connection_errcode (ZOOM_connection c)
2265 {
2266     return ZOOM_connection_error (c, 0, 0);
2267 }
2268
2269 ZOOM_API(const char *)
2270 ZOOM_connection_errmsg (ZOOM_connection c)
2271 {
2272     const char *msg;
2273     ZOOM_connection_error (c, &msg, 0);
2274     return msg;
2275 }
2276
2277 ZOOM_API(const char *)
2278 ZOOM_connection_addinfo (ZOOM_connection c)
2279 {
2280     const char *addinfo;
2281     ZOOM_connection_error (c, 0, &addinfo);
2282     return addinfo;
2283 }
2284
2285 ZOOM_API(const char *)
2286 ZOOM_diag_str (int error)
2287 {
2288     switch (error)
2289     {
2290     case ZOOM_ERROR_NONE:
2291         return "No error";
2292     case ZOOM_ERROR_CONNECT:
2293         return "Connect failed";
2294     case ZOOM_ERROR_MEMORY:
2295         return "Out of memory";
2296     case ZOOM_ERROR_ENCODE:
2297         return "Encoding failed";
2298     case ZOOM_ERROR_DECODE:
2299         return "Decoding failed";
2300     case ZOOM_ERROR_CONNECTION_LOST:
2301         return "Connection lost";
2302     case ZOOM_ERROR_INIT:
2303         return "Init rejected";
2304     case ZOOM_ERROR_INTERNAL:
2305         return "Internal failure";
2306     case ZOOM_ERROR_TIMEOUT:
2307         return "Timeout";
2308     default:
2309         return diagbib1_str (error);
2310     }
2311 }
2312
2313 ZOOM_API(int)
2314 ZOOM_connection_error_x (ZOOM_connection c, const char **cp,
2315                          const char **addinfo, const char **diagset)
2316 {
2317     int error = c->error;
2318     if (cp)
2319     {
2320         *cp = ZOOM_diag_str(error);
2321     }
2322     if (addinfo)
2323         *addinfo = c->addinfo ? c->addinfo : "";
2324     if (diagset)
2325         *diagset = c->diagset ? c->diagset : "";
2326     return c->error;
2327 }
2328
2329 ZOOM_API(int)
2330 ZOOM_connection_error (ZOOM_connection c, const char **cp,
2331                        const char **addinfo)
2332 {
2333     return ZOOM_connection_error_x(c, cp, addinfo, 0);
2334 }
2335
2336 static int ZOOM_connection_do_io(ZOOM_connection c, int mask)
2337 {
2338     ZOOM_Event event = 0;
2339     int r = cs_look(c->cs);
2340     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
2341              c, mask, r);
2342     
2343     if (r == CS_NONE)
2344     {
2345         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
2346         set_bib1_error(c, ZOOM_ERROR_CONNECT);
2347         do_close (c);
2348         ZOOM_connection_put_event (c, event);
2349     }
2350     else if (r == CS_CONNECT)
2351     {
2352         int ret;
2353         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
2354
2355         ret = cs_rcvconnect (c->cs);
2356         yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
2357         if (ret == 1)
2358         {
2359             c->mask = ZOOM_SELECT_EXCEPT;
2360             if (c->cs->io_pending & CS_WANT_WRITE)
2361                 c->mask += ZOOM_SELECT_WRITE;
2362             if (c->cs->io_pending & CS_WANT_READ)
2363                 c->mask += ZOOM_SELECT_READ;
2364             ZOOM_connection_put_event (c, event);
2365         }
2366         else if (ret == 0)
2367         {
2368             ZOOM_connection_put_event (c, event);
2369             ZOOM_connection_send_init (c);
2370             c->state = STATE_ESTABLISHED;
2371         }
2372         else
2373         {
2374             set_bib1_error(c, ZOOM_ERROR_CONNECT);
2375             do_close (c);
2376             ZOOM_connection_put_event (c, event);
2377         }
2378     }
2379     else
2380     {
2381         if (mask & ZOOM_SELECT_READ)
2382             do_read (c);
2383         if (c->cs && (mask & ZOOM_SELECT_WRITE))
2384             do_write (c);
2385     }
2386     return 1;
2387 }
2388
2389 ZOOM_API(int)
2390 ZOOM_connection_last_event(ZOOM_connection cs)
2391 {
2392     if (!cs)
2393         return ZOOM_EVENT_NONE;
2394     return cs->last_event;
2395 }
2396
2397 ZOOM_API(int)
2398 ZOOM_event (int no, ZOOM_connection *cs)
2399 {
2400     int timeout = 5000;
2401 #if HAVE_SYS_POLL_H
2402     struct pollfd pollfds[1024];
2403     ZOOM_connection poll_cs[1024];
2404 #else
2405     struct timeval tv;
2406     fd_set input, output, except;
2407 #endif
2408     int i, r, nfds;
2409     int max_fd = 0;
2410
2411     for (i = 0; i<no; i++)
2412     {
2413         ZOOM_connection c = cs[i];
2414         ZOOM_Event event;
2415         if (c && (event = ZOOM_connection_get_event(c)))
2416         {
2417             ZOOM_Event_destroy (event);
2418             return i+1;
2419         }
2420     }
2421     for (i = 0; i<no; i++)
2422     {
2423         ZOOM_connection c = cs[i];
2424         ZOOM_Event event;
2425         if (c && ZOOM_connection_exec_task (c))
2426         {
2427             if ((event = ZOOM_connection_get_event(c)))
2428             {
2429                 ZOOM_Event_destroy (event);
2430                 return i+1;
2431             }
2432         }
2433     }
2434 #if HAVE_SYS_POLL_H
2435
2436 #else
2437     FD_ZERO (&input);
2438     FD_ZERO (&output);
2439     FD_ZERO (&except);
2440 #endif
2441     nfds = 0;
2442     for (i = 0; i<no; i++)
2443     {
2444         ZOOM_connection c = cs[i];
2445         int fd, mask;
2446         int this_timeout;
2447         
2448         if (!c)
2449             continue;
2450         fd = z3950_connection_socket(c);
2451         mask = z3950_connection_mask(c);
2452
2453         if (fd == -1)
2454             continue;
2455         if (max_fd < fd)
2456             max_fd = fd;
2457
2458         this_timeout = ZOOM_options_get_int (c->options, "timeout", -1);
2459         if (this_timeout != -1 && this_timeout < timeout)
2460             timeout = this_timeout;
2461 #if HAVE_SYS_POLL_H
2462         if (mask)
2463         {
2464             short poll_events = 0;
2465
2466             if (mask & ZOOM_SELECT_READ)
2467                 poll_events += POLLIN;
2468             if (mask & ZOOM_SELECT_WRITE)
2469                 poll_events += POLLOUT;
2470             if (mask & ZOOM_SELECT_EXCEPT)
2471                 poll_events += POLLERR;
2472             pollfds[nfds].fd = fd;
2473             pollfds[nfds].events = poll_events;
2474             pollfds[nfds].revents = 0;
2475             poll_cs[nfds] = c;
2476             nfds++;
2477         }
2478 #else
2479         if (mask & ZOOM_SELECT_READ)
2480         {
2481             FD_SET (fd, &input);
2482             nfds++;
2483         }
2484         if (mask & ZOOM_SELECT_WRITE)
2485         {
2486             FD_SET (fd, &output);
2487             nfds++;
2488         }
2489         if (mask & ZOOM_SELECT_EXCEPT)
2490         {
2491             FD_SET (fd, &except);
2492             nfds++;
2493         }
2494 #endif
2495     }
2496     if (timeout >= 5000)
2497         timeout = 30;
2498
2499     if (!nfds)
2500         return 0;
2501
2502 #if HAVE_SYS_POLL_H
2503     r = poll (pollfds, nfds, timeout * 1000);
2504     for (i = 0; i<nfds; i++)
2505     {
2506         ZOOM_connection c = poll_cs[i];
2507         if (r && c->mask)
2508         {
2509             int mask = 0;
2510             if (pollfds[i].revents & POLLIN)
2511                 mask += ZOOM_SELECT_READ;
2512             if (pollfds[i].revents & POLLOUT)
2513                 mask += ZOOM_SELECT_WRITE;
2514             if (pollfds[i].revents & POLLERR)
2515                 mask += ZOOM_SELECT_EXCEPT;
2516             if (mask)
2517                 ZOOM_connection_do_io(c, mask);
2518         }
2519         else if (r == 0 && c->mask)
2520         {
2521             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
2522             /* timeout and this connection was waiting */
2523             set_bib1_error(c, ZOOM_ERROR_TIMEOUT);
2524             do_close (c);
2525             ZOOM_connection_put_event(c, event);
2526         }
2527     }
2528 #else
2529     tv.tv_sec = timeout;
2530     tv.tv_usec = 0;
2531     yaz_log (LOG_DEBUG, "select start");
2532     r = select (max_fd+1, &input, &output, &except, &tv);
2533     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
2534     for (i = 0; i<no; i++)
2535     {
2536         ZOOM_connection c = cs[i];
2537         int fd, mask;
2538
2539         if (!c)
2540             continue;
2541         fd = z3950_connection_socket(c);
2542         mask = 0;
2543         if (r && c->mask)
2544         {
2545             /* no timeout and real socket */
2546             if (FD_ISSET(fd, &input))
2547                 mask += ZOOM_SELECT_READ;
2548             if (FD_ISSET(fd, &output))
2549                 mask += ZOOM_SELECT_WRITE;
2550             if (FD_ISSET(fd, &except))
2551                 mask += ZOOM_SELECT_EXCEPT;
2552             if (mask)
2553                 ZOOM_connection_do_io(c, mask);
2554         }
2555         if (r == 0 && c->mask)
2556         {
2557             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
2558             /* timeout and this connection was waiting */
2559             set_bib1_error(c, ZOOM_ERROR_TIMEOUT);
2560             do_close (c);
2561             yaz_log (LOG_DEBUG, "timeout");
2562             ZOOM_connection_put_event(c, event);
2563         }
2564     }
2565 #endif
2566     for (i = 0; i<no; i++)
2567     {
2568         ZOOM_connection c = cs[i];
2569         ZOOM_Event event;
2570         if (c && (event = ZOOM_connection_get_event(c)))
2571         {
2572             ZOOM_Event_destroy (event);
2573             return i+1;
2574         }
2575     }
2576     return 0;
2577 }