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