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