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