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