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