Fix leak of temporary connections created by ZOOM_query_c[cq]l2rpn()
[yaz-moved-to-github.git] / src / zoom-c.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: zoom-c.c,v 1.77 2006-06-14 09:15:28 mike Exp $
6  */
7 /**
8  * \file zoom-c.c
9  * \brief Implements ZOOM C interface.
10  */
11
12 #include <assert.h>
13 #include <string.h>
14 #include <errno.h>
15 #include "zoom-p.h"
16
17 #include <yaz/yaz-util.h>
18 #include <yaz/xmalloc.h>
19 #include <yaz/otherinfo.h>
20 #include <yaz/log.h>
21 #include <yaz/pquery.h>
22 #include <yaz/marcdisp.h>
23 #include <yaz/diagbib1.h>
24 #include <yaz/charneg.h>
25 #include <yaz/ill.h>
26 #include <yaz/srw.h>
27 #include <yaz/cql.h>
28 #include <yaz/ccl.h>
29
30 #if HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #if HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
36 #if HAVE_SYS_POLL_H
37 #include <sys/poll.h>
38 #endif
39 #if HAVE_SYS_SELECT_H
40 #include <sys/select.h>
41 #endif
42 #ifdef WIN32
43 #include <winsock.h>
44 #endif
45
46 static int log_api = 0;
47 static int log_details = 0;
48
49 typedef enum {
50     zoom_pending,
51     zoom_complete
52 } zoom_ret;
53
54 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c);
55 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out);
56 static char *cql2pqf(ZOOM_connection c, const char *cql);
57 static char *ccl2pqf(ZOOM_connection c, const char *ccl);
58
59 static void initlog()
60 {
61     static int log_level_initialized = 0;
62     if (!log_level_initialized)
63     {
64         log_api = yaz_log_module_level("zoom");
65         log_details = yaz_log_module_level("zoomdetails");
66         log_level_initialized = 1;
67     }
68 }
69
70 static ZOOM_Event ZOOM_Event_create (int kind)
71 {
72     ZOOM_Event event = (ZOOM_Event) xmalloc (sizeof(*event));
73     event->kind = kind;
74     event->next = 0;
75     event->prev = 0;
76     return event;
77 }
78
79 static void ZOOM_Event_destroy (ZOOM_Event event)
80 {
81     xfree (event);
82 }
83
84 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
85 {
86     if (c->m_queue_back)
87     {
88         c->m_queue_back->prev = event;
89         assert (c->m_queue_front);
90     }
91     else
92     {
93         assert (!c->m_queue_front);
94         c->m_queue_front = event;
95     }
96     event->next = c->m_queue_back;
97     event->prev = 0;
98     c->m_queue_back = event;
99 }
100
101 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
102 {
103     ZOOM_Event event = c->m_queue_front;
104     if (!event)
105     {
106         c->last_event = ZOOM_EVENT_NONE;
107         return 0;
108     }
109     assert (c->m_queue_back);
110     c->m_queue_front = event->prev;
111     if (c->m_queue_front)
112     {
113         assert (c->m_queue_back);
114         c->m_queue_front->next = 0;
115     }
116     else
117         c->m_queue_back = 0;
118     c->last_event = event->kind;
119     return event;
120 }
121
122
123 static void set_dset_error (ZOOM_connection c, int error,
124                             const char *dset,
125                             const char *addinfo, const char *addinfo2)
126 {
127     char *cp;
128
129     xfree (c->addinfo);
130     c->addinfo = 0;
131     c->error = error;
132     if (!c->diagset || strcmp(dset, c->diagset))
133     {
134         xfree(c->diagset);
135         c->diagset = xstrdup(dset);
136         /* remove integer part from SRW diagset .. */
137         if ((cp = strrchr(c->diagset, '/')))
138            *cp = '\0';
139     }
140     if (addinfo && addinfo2)
141     {
142         c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
143         strcpy(c->addinfo, addinfo);
144         strcat(c->addinfo, addinfo2);
145     }
146     else if (addinfo)
147         c->addinfo = xstrdup(addinfo);
148     if (error)
149         yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
150                 c, c->host_port ? c->host_port : "<>", dset, error,
151                 addinfo ? addinfo : "",
152                 addinfo2 ? addinfo2 : "");
153 }
154
155 #if HAVE_XML2
156 static void set_HTTP_error (ZOOM_connection c, int error,
157                             const char *addinfo, const char *addinfo2)
158 {
159     set_dset_error(c, error, "HTTP", addinfo, addinfo2);
160 }
161 #endif
162
163 static void set_ZOOM_error (ZOOM_connection c, int error,
164                             const char *addinfo)
165 {
166     set_dset_error(c, error, "ZOOM", addinfo, 0);
167 }
168
169 static void clear_error (ZOOM_connection c)
170 {
171     /*
172      * If an error is tied to an operation then it's ok to clear: for
173      * example, a diagnostic returned from a search is cleared by a
174      * subsequent search.  However, problems such as Connection Lost
175      * or Init Refused are not cleared, because they are not
176      * recoverable: doing another search doesn't help.
177      */
178     switch (c->error)
179     {
180     case ZOOM_ERROR_CONNECT:
181     case ZOOM_ERROR_MEMORY:
182     case ZOOM_ERROR_DECODE:
183     case ZOOM_ERROR_CONNECTION_LOST:
184     case ZOOM_ERROR_INIT:
185     case ZOOM_ERROR_INTERNAL:
186     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
187         break;
188     default:
189         set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
190     }
191 }
192
193 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
194 {
195     ZOOM_task *taskp = &c->tasks;
196     while (*taskp)
197         taskp = &(*taskp)->next;
198     *taskp = (ZOOM_task) xmalloc (sizeof(**taskp));
199     (*taskp)->running = 0;
200     (*taskp)->which = which;
201     (*taskp)->next = 0;
202     clear_error (c);
203     return *taskp;
204 }
205
206 ZOOM_task ZOOM_connection_insert_task (ZOOM_connection c, int which)
207 {
208     ZOOM_task task = (ZOOM_task) xmalloc (sizeof(*task));
209
210     task->next = c->tasks;
211     c->tasks = task;
212
213     task->running = 0;
214     task->which = which;
215     clear_error (c);
216     return task;
217 }
218
219 void ZOOM_connection_remove_task (ZOOM_connection c)
220 {
221     ZOOM_task task = c->tasks;
222
223     if (task)
224     {
225         c->tasks = task->next;
226         switch (task->which)
227         {
228         case ZOOM_TASK_SEARCH:
229             ZOOM_resultset_destroy (task->u.search.resultset);
230             break;
231         case ZOOM_TASK_RETRIEVE:
232             ZOOM_resultset_destroy (task->u.retrieve.resultset);
233             break;
234         case ZOOM_TASK_CONNECT:
235             break;
236         case ZOOM_TASK_SCAN:
237             ZOOM_scanset_destroy (task->u.scan.scan);
238             break;
239         case ZOOM_TASK_PACKAGE:
240             ZOOM_package_destroy (task->u.package);
241             break;
242         case ZOOM_TASK_SORT:
243             ZOOM_resultset_destroy (task->u.sort.resultset);
244             ZOOM_query_destroy(task->u.sort.q);
245             break;
246         default:
247             assert (0);
248         }
249         xfree (task);
250
251         if (!c->tasks)
252         {
253             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
254             ZOOM_connection_put_event(c, event);
255         }
256     }
257 }
258
259 static int ZOOM_connection_exec_task (ZOOM_connection c);
260
261 void ZOOM_connection_remove_tasks (ZOOM_connection c)
262 {
263     while (c->tasks)
264         ZOOM_connection_remove_task(c);
265 }
266
267 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos);
268
269 ZOOM_API(ZOOM_connection)
270 ZOOM_connection_create (ZOOM_options options)
271 {
272     ZOOM_connection c = (ZOOM_connection) xmalloc (sizeof(*c));
273
274     initlog();
275
276     yaz_log(log_api, "%p ZOOM_connection_create", c);
277
278     c->proto = PROTO_Z3950;
279     c->cs = 0;
280     c->mask = 0;
281     c->reconnect_ok = 0;
282     c->state = STATE_IDLE;
283     c->addinfo = 0;
284     c->diagset = 0;
285     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
286     c->buf_in = 0;
287     c->len_in = 0;
288     c->buf_out = 0;
289     c->len_out = 0;
290     c->resultsets = 0;
291
292     c->options = ZOOM_options_create_with_parent(options);
293
294     c->host_port = 0;
295     c->path = 0;
296     c->proxy = 0;
297     
298     c->charset = c->lang = 0;
299
300     c->cookie_out = 0;
301     c->cookie_in = 0;
302     c->client_IP = 0;
303     c->tasks = 0;
304
305     c->odr_in = odr_createmem (ODR_DECODE);
306     c->odr_out = odr_createmem (ODR_ENCODE);
307
308     c->async = 0;
309     c->support_named_resultsets = 0;
310     c->last_event = ZOOM_EVENT_NONE;
311
312     c->m_queue_front = 0;
313     c->m_queue_back = 0;
314     return c;
315 }
316
317 /* set database names. Take local databases (if set); otherwise
318    take databases given in ZURL (if set); otherwise use Default */
319 static char **set_DatabaseNames (ZOOM_connection con, ZOOM_options options,
320                                  int *num)
321 {
322     char **databaseNames;
323     const char *cp = ZOOM_options_get (options, "databaseName");
324     
325     if ((!cp || !*cp) && con->host_port)
326     {
327         if (strncmp (con->host_port, "unix:", 5) == 0)
328             cp = strchr(con->host_port+5, ':');
329         else
330             cp = strchr(con->host_port, '/');
331         if (cp)
332             cp++;
333     }
334     if (!cp)
335         cp = "Default";
336     nmem_strsplit(con->odr_out->mem, "+", cp,  &databaseNames, num);
337     return databaseNames;
338 }
339
340 ZOOM_API(ZOOM_connection)
341 ZOOM_connection_new (const char *host, int portnum)
342 {
343     ZOOM_connection c = ZOOM_connection_create (0);
344
345     ZOOM_connection_connect (c, host, portnum);
346     return c;
347 }
348
349 static zoom_sru_mode get_sru_mode_from_string(const char *s)
350 {
351     if (!s || !*s)
352         return zoom_sru_soap;
353     if (!yaz_matchstr(s, "soap"))
354         return zoom_sru_soap;
355     else if (!yaz_matchstr(s, "get"))
356         return zoom_sru_get;
357     else if (!yaz_matchstr(s, "post"))
358         return zoom_sru_post;
359     return zoom_sru_error;
360 }
361
362 ZOOM_API(void)
363 ZOOM_connection_connect(ZOOM_connection c,
364                         const char *host, int portnum)
365 {
366     const char *val;
367     ZOOM_task task;
368
369     initlog();
370
371     yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
372             c, host, portnum);
373
374     if (c->cs)
375     {
376         yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
377         c->reconnect_ok = 1;
378         return;
379     }
380     yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
381     xfree (c->proxy);
382     val = ZOOM_options_get (c->options, "proxy");
383     if (val && *val)
384     {
385         yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
386         c->proxy = xstrdup (val);
387     }
388     else
389         c->proxy = 0;
390
391     xfree (c->charset);
392     val = ZOOM_options_get (c->options, "charset");
393     if (val && *val)
394     {
395         yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
396         c->charset = xstrdup (val);
397     }
398     else
399         c->charset = 0;
400
401     xfree (c->lang);
402     val = ZOOM_options_get (c->options, "lang");
403     if (val && *val)
404     {
405         yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
406         c->lang = xstrdup (val);
407     }
408     else
409         c->lang = 0;
410
411     val = ZOOM_options_get (c->options, "sru");
412     c->sru_mode = get_sru_mode_from_string(val);
413
414     xfree (c->host_port);
415     if (portnum)
416     {
417         char hostn[128];
418         sprintf (hostn, "%.80s:%d", host, portnum);
419         c->host_port = xstrdup(hostn);
420     }
421     else
422         c->host_port = xstrdup(host);
423
424     {
425         /*
426          * If the "<scheme>:" part of the host string is preceded by one
427          * or more comma-separated <name>=<value> pairs, these are taken
428          * to be options to be set on the connection object.  Among other
429          * applications, this facility can be used to embed authentication
430          * in a host string:
431          *          user=admin,password=secret,tcp:localhost:9999
432          */
433         char *remainder = c->host_port;
434         char *pcolon = strchr(remainder, ':');
435         char *pcomma;
436         char *pequals;
437         while ((pcomma = strchr(remainder, ',')) != 0 &&
438                (pcolon == 0 || pcomma < pcolon)) {
439             *pcomma = '\0';
440             if ((pequals = strchr(remainder, '=')) != 0) {
441                 *pequals = '\0';
442                 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
443                 ZOOM_connection_option_set(c, remainder, pequals+1);
444             }
445             remainder = pcomma+1;
446         }
447
448         if (remainder != c->host_port) {
449             xfree(c->host_port);
450             c->host_port = xstrdup(remainder);
451             /*printf("# reset hp='%s'\n", remainder);*/
452         }
453     }
454
455     ZOOM_options_set(c->options, "host", c->host_port);
456
457     val = ZOOM_options_get (c->options, "cookie");
458     if (val && *val)
459     { 
460         yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
461         c->cookie_out = xstrdup (val);
462     }
463
464     val = ZOOM_options_get (c->options, "clientIP");
465     if (val && *val)
466     {
467         yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
468                 c, val);
469         c->client_IP = xstrdup (val);
470     }
471
472     c->async = ZOOM_options_get_bool (c->options, "async", 0);
473     yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
474  
475     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
476
477     task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
478
479     if (!c->async)
480     {
481         while (ZOOM_event (1, &c))
482             ;
483     }
484 }
485
486 ZOOM_API(ZOOM_query)
487 ZOOM_query_create(void)
488 {
489     ZOOM_query s = (ZOOM_query) xmalloc (sizeof(*s));
490
491     yaz_log(log_details, "%p ZOOM_query_create", s);
492     s->refcount = 1;
493     s->z_query = 0;
494     s->sort_spec = 0;
495     s->odr = odr_createmem (ODR_ENCODE);
496     s->query_string = 0;
497
498     return s;
499 }
500
501 ZOOM_API(void)
502 ZOOM_query_destroy(ZOOM_query s)
503 {
504     if (!s)
505         return;
506
507     (s->refcount)--;
508     yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
509     if (s->refcount == 0)
510     {
511         odr_destroy (s->odr);
512         xfree (s);
513     }
514 }
515
516 ZOOM_API(int)
517 ZOOM_query_prefix(ZOOM_query s, const char *str)
518 {
519     s->query_string = odr_strdup(s->odr, str);
520     s->z_query = (Z_Query *) odr_malloc (s->odr, sizeof(*s->z_query));
521     s->z_query->which = Z_Query_type_1;
522     s->z_query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
523     if (!s->z_query->u.type_1)
524     {
525         yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
526         s->z_query = 0;
527         return -1;
528     }
529     yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
530     return 0;
531 }
532
533 ZOOM_API(int)
534 ZOOM_query_cql(ZOOM_query s, const char *str)
535 {
536     Z_External *ext;
537
538     s->query_string = odr_strdup(s->odr, str);
539
540     ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
541     ext->direct_reference = odr_getoidbystr(s->odr, "1.2.840.10003.16.2");
542     ext->indirect_reference = 0;
543     ext->descriptor = 0;
544     ext->which = Z_External_CQL;
545     ext->u.cql = s->query_string;
546     
547     s->z_query = (Z_Query *) odr_malloc (s->odr, sizeof(*s->z_query));
548     s->z_query->which = Z_Query_type_104;
549     s->z_query->u.type_104 =  ext;
550
551     yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
552
553     return 0;
554 }
555
556 /*
557  * Translate the CQL string client-side into RPN which is passed to
558  * the server.  This is useful for server's that don't themselves
559  * support CQL, for which ZOOM_query_cql() is useless.  `conn' is used
560  * only as a place to stash diagnostics if compilation fails; if this
561  * information is not needed, a null pointer may be used.
562  */
563 ZOOM_API(int)
564 ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
565 {
566     char *rpn;
567     int ret;
568     ZOOM_connection freeme = 0;
569
570     yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
571     if (conn == 0)
572         conn = freeme = ZOOM_connection_create(0);
573
574     rpn = cql2pqf(conn, str);
575     if (freeme != 0)
576         ZOOM_connection_destroy(freeme);
577     if (rpn == 0)
578         return -1;
579
580     ret = ZOOM_query_prefix(s, rpn);
581     xfree(rpn);
582     return ret;
583 }
584
585 /*
586  * Analogous in every way to ZOOM_query_cql2rpn(), except that there
587  * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
588  * to the server, as the YAZ GFS doesn't know how to handle this.
589  */
590 ZOOM_API(int)
591 ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
592 {
593     char *rpn;
594     int ret;
595     ZOOM_connection freeme = 0;
596
597     yaz_log(log_details, "%p ZOOM_query_ccl2rpn str=%s conn=%p", s, str, conn);
598     if (conn == 0)
599         conn = freeme = ZOOM_connection_create(0);
600
601     rpn = ccl2pqf(conn, str);
602     if (freeme != 0)
603         ZOOM_connection_destroy(freeme);
604     if (rpn == 0)
605         return -1;
606
607     ret = ZOOM_query_prefix(s, rpn);
608     xfree(rpn);
609     return ret;
610 }
611
612 ZOOM_API(int)
613 ZOOM_query_sortby(ZOOM_query s, const char *criteria)
614 {
615     s->sort_spec = yaz_sort_spec (s->odr, criteria);
616     if (!s->sort_spec)
617     {
618         yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
619                 s, criteria);
620         return -1;
621     }
622     yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
623     return 0;
624 }
625
626 static zoom_ret do_write(ZOOM_connection c);
627
628 ZOOM_API(void)
629 ZOOM_connection_destroy(ZOOM_connection c)
630 {
631     ZOOM_resultset r;
632     if (!c)
633         return;
634     yaz_log(log_api, "%p ZOOM_connection_destroy", c);
635     if (c->cs)
636         cs_close (c->cs);
637     for (r = c->resultsets; r; r = r->next)
638         r->connection = 0;
639
640     xfree (c->buf_in);
641     xfree (c->addinfo);
642     xfree (c->diagset);
643     odr_destroy (c->odr_in);
644     odr_destroy (c->odr_out);
645     ZOOM_options_destroy (c->options);
646     ZOOM_connection_remove_tasks (c);
647     xfree (c->host_port);
648     xfree (c->path);
649     xfree (c->proxy);
650     xfree (c->charset);
651     xfree (c->lang);
652     xfree (c->cookie_out);
653     xfree (c->cookie_in);
654     xfree (c->client_IP);
655     xfree (c);
656 }
657
658 void ZOOM_resultset_addref (ZOOM_resultset r)
659 {
660     if (r)
661     {
662         (r->refcount)++;
663         yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
664                 r, r->refcount);
665     }
666 }
667
668 ZOOM_resultset ZOOM_resultset_create ()
669 {
670     int i;
671     ZOOM_resultset r = (ZOOM_resultset) xmalloc (sizeof(*r));
672
673     initlog();
674
675     yaz_log(log_details, "%p ZOOM_resultset_create", r);
676     r->refcount = 1;
677     r->size = 0;
678     r->odr = odr_createmem (ODR_ENCODE);
679     r->start = 0;
680     r->piggyback = 1;
681     r->setname = 0;
682     r->schema = 0;
683     r->count = 0;
684     r->step = 0;
685     for (i = 0; i<RECORD_HASH_SIZE; i++)
686         r->record_hash[i] = 0;
687     r->r_sort_spec = 0;
688     r->query = 0;
689     r->connection = 0;
690     r->next = 0;
691     return r;
692 }
693
694 ZOOM_API(ZOOM_resultset)
695 ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
696 {
697     ZOOM_resultset r;
698     ZOOM_query s = ZOOM_query_create();
699
700     ZOOM_query_prefix (s, q);
701
702     r = ZOOM_connection_search (c, s);
703     ZOOM_query_destroy (s);
704     return r;
705 }
706
707 ZOOM_API(ZOOM_resultset)
708 ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
709 {
710     ZOOM_resultset r = ZOOM_resultset_create ();
711     ZOOM_task task;
712     const char *cp;
713
714     yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
715     r->r_sort_spec = q->sort_spec;
716     r->query = q;
717
718     r->options = ZOOM_options_create_with_parent(c->options);
719
720     r->start = ZOOM_options_get_int(r->options, "start", 0);
721     r->count = ZOOM_options_get_int(r->options, "count", 0);
722     {
723         /* If "presentChunk" is defined use that; otherwise "step" */
724         const char *cp = ZOOM_options_get (r->options, "presentChunk");
725         r->step = ZOOM_options_get_int(r->options,
726                                        (cp != 0 ? "presentChunk": "step"), 0);
727     }
728     r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
729     cp = ZOOM_options_get (r->options, "setname");
730     if (cp)
731         r->setname = xstrdup(cp);
732     cp = ZOOM_options_get (r->options, "schema");
733     if (cp)
734         r->schema = xstrdup(cp);
735     
736     r->connection = c;
737
738     r->next = c->resultsets;
739     c->resultsets = r;
740
741     if (c->host_port && c->proto == PROTO_HTTP)
742     {
743         if (!c->cs)
744         {
745             yaz_log(log_details, "ZOOM_connection_search: no comstack");
746             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
747         }
748         else
749         {
750             yaz_log(log_details, "ZOOM_connection_search: reconnect");
751             c->reconnect_ok = 1;
752         }
753     }
754
755     task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
756     task->u.search.resultset = r;
757     ZOOM_resultset_addref (r);  
758
759     (q->refcount)++;
760
761     if (!c->async)
762     {
763         while (ZOOM_event (1, &c))
764             ;
765     }
766     return r;
767 }
768
769 /*
770  * This is the old result-set sorting API, which is maintained only
771  * for the sake of binary compatibility.  There is no reason ever to
772  * use this rather than ZOOM_resultset_sort1().
773  */
774 ZOOM_API(void)
775 ZOOM_resultset_sort(ZOOM_resultset r,
776                     const char *sort_type, const char *sort_spec)
777 {
778     (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
779 }
780
781 ZOOM_API(int)
782 ZOOM_resultset_sort1(ZOOM_resultset r,
783                      const char *sort_type, const char *sort_spec)
784 {
785     ZOOM_connection c = r->connection;
786     ZOOM_task task;
787     ZOOM_query newq;
788
789     newq = ZOOM_query_create();
790     if (ZOOM_query_sortby(newq, sort_spec) < 0)
791         return -1;
792
793     yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
794             r, r, sort_type, sort_spec);
795     if (!c)
796         return 0;
797
798     if (c->host_port && c->proto == PROTO_HTTP)
799     {
800         if (!c->cs)
801         {
802             yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
803             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
804         }
805         else
806         {
807             yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
808                     r);
809             c->reconnect_ok = 1;
810         }
811     }
812     
813     ZOOM_resultset_cache_reset(r);
814     task = ZOOM_connection_add_task (c, ZOOM_TASK_SORT);
815     task->u.sort.resultset = r;
816     task->u.sort.q = newq;
817
818     ZOOM_resultset_addref (r);  
819
820     if (!c->async)
821     {
822         while (ZOOM_event (1, &c))
823             ;
824     }
825
826     return 0;
827 }
828
829 ZOOM_API(void)
830     ZOOM_resultset_cache_reset(ZOOM_resultset r)
831 {
832     int i;
833     for (i = 0; i<RECORD_HASH_SIZE; i++)
834     {
835         ZOOM_record_cache rc;
836         for (rc = r->record_hash[i]; rc; rc = rc->next)
837         {
838             if (rc->rec.wrbuf_marc)
839                 wrbuf_free (rc->rec.wrbuf_marc, 1);
840             if (rc->rec.wrbuf_iconv)
841                 wrbuf_free (rc->rec.wrbuf_iconv, 1);
842             if (rc->rec.wrbuf_opac)
843                 wrbuf_free (rc->rec.wrbuf_opac, 1);
844         }
845         r->record_hash[i] = 0;
846     }
847 }
848
849 ZOOM_API(void)
850 ZOOM_resultset_destroy(ZOOM_resultset r)
851 {
852     if (!r)
853         return;
854     (r->refcount)--;
855     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
856             r, r, r->refcount);
857     if (r->refcount == 0)
858     {
859         ZOOM_resultset_cache_reset(r);
860
861         if (r->connection)
862         {
863             /* remove ourselves from the resultsets in connection */
864             ZOOM_resultset *rp = &r->connection->resultsets;
865             while (1)
866             {
867                 assert (*rp);   /* we must be in this list!! */
868                 if (*rp == r)
869                 {   /* OK, we're here - take us out of it */
870                     *rp = (*rp)->next;
871                     break;
872                 }
873                 rp = &(*rp)->next;
874             }
875         }
876         ZOOM_query_destroy (r->query);
877         ZOOM_options_destroy (r->options);
878         odr_destroy (r->odr);
879         xfree (r->setname);
880         xfree (r->schema);
881         xfree (r);
882     }
883 }
884
885 ZOOM_API(size_t)
886 ZOOM_resultset_size (ZOOM_resultset r)
887 {
888     return r->size;
889 }
890
891 static void do_close (ZOOM_connection c)
892 {
893     if (c->cs)
894         cs_close(c->cs);
895     c->cs = 0;
896     c->mask = 0;
897     c->state = STATE_IDLE;
898 }
899
900 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
901                                      int force_sync, int start, int count)
902 {
903     ZOOM_task task;
904     ZOOM_connection c;
905     const char *cp;
906
907     if (!r)
908         return;
909     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
910             " count=%d", r, force_sync, start, count);
911     c = r->connection;
912     if (!c)
913         return;
914
915     if (c->host_port && c->proto == PROTO_HTTP)
916     {
917         if (!c->cs)
918         {
919             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
920             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
921         }
922         else
923         {
924             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
925                     "reconnect", r);
926             c->reconnect_ok = 1;
927         }
928     }
929     task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
930     task->u.retrieve.resultset = r;
931     task->u.retrieve.start = start;
932     task->u.retrieve.count = count;
933
934     cp = ZOOM_options_get (r->options, "schema");
935     if (cp)
936     {
937         if (!r->schema || strcmp(r->schema, cp))
938         {
939             xfree(r->schema);
940             r->schema = xstrdup(cp);
941         }
942     }
943
944     ZOOM_resultset_addref (r);
945
946     if (!r->connection->async || force_sync)
947         while (r->connection && ZOOM_event (1, &r->connection))
948             ;
949 }
950
951 ZOOM_API(void)
952 ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
953                         size_t start, size_t count)
954 {
955     int force_present = 0;
956
957     if (!r)
958         return ;
959     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
960             r, r, (long) start, (long) count);
961     if (count && recs)
962         force_present = 1;
963     ZOOM_resultset_retrieve (r, force_present, start, count);
964     if (force_present)
965     {
966         size_t i;
967         for (i = 0; i< count; i++)
968             recs[i] = ZOOM_resultset_record_immediate (r, i+start);
969     }
970 }
971
972 static void get_cert(ZOOM_connection c)
973 {
974     char *cert_buf;
975     int cert_len;
976     
977     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
978     {
979         ZOOM_connection_option_setl(c, "sslPeerCert",
980                                     cert_buf, cert_len);
981         xfree(cert_buf);
982     }
983 }
984
985 static zoom_ret do_connect (ZOOM_connection c)
986 {
987     void *add;
988     const char *effective_host;
989
990     if (c->proxy)
991         effective_host = c->proxy;
992     else
993         effective_host = c->host_port;
994
995     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
996
997     if (c->cs)
998         cs_close(c->cs);
999     c->cs = cs_create_host (effective_host, 0, &add);
1000
1001     if (c->cs && c->cs->protocol == PROTO_HTTP)
1002     {
1003 #if HAVE_XML2
1004         const char *path = 0;
1005
1006         c->proto = PROTO_HTTP;
1007         cs_get_host_args(c->host_port, &path);
1008         xfree(c->path);
1009         c->path = (char*) xmalloc(strlen(path)+2);
1010         c->path[0] = '/';
1011         strcpy (c->path+1, path);
1012 #else
1013         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1014         do_close(c);
1015         return zoom_complete;
1016 #endif
1017     }
1018     if (c->cs)
1019     {
1020         int ret = cs_connect (c->cs, add);
1021         if (ret == 0)
1022         {
1023             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1024             ZOOM_connection_put_event(c, event);
1025             get_cert(c);
1026             if (c->proto == PROTO_Z3950)
1027                 ZOOM_connection_send_init(c);
1028             else
1029             {
1030                 /* no init request for SRW .. */
1031                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
1032                 ZOOM_connection_remove_task (c);
1033                 c->mask = 0;
1034                 ZOOM_connection_exec_task (c);
1035             }
1036             c->state = STATE_ESTABLISHED;
1037             return zoom_pending;
1038         }
1039         else if (ret > 0)
1040         {
1041             c->state = STATE_CONNECTING; 
1042             c->mask = ZOOM_SELECT_EXCEPT;
1043             if (c->cs->io_pending & CS_WANT_WRITE)
1044                 c->mask += ZOOM_SELECT_WRITE;
1045             if (c->cs->io_pending & CS_WANT_READ)
1046                 c->mask += ZOOM_SELECT_READ;
1047             return zoom_pending;
1048         }
1049     }
1050     c->state = STATE_IDLE;
1051     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
1052     return zoom_complete;
1053 }
1054
1055 int z3950_connection_socket(ZOOM_connection c)
1056 {
1057     if (c->cs)
1058         return cs_fileno(c->cs);
1059     return -1;
1060 }
1061
1062 int z3950_connection_mask(ZOOM_connection c)
1063 {
1064     if (c->cs)
1065         return c->mask;
1066     return 0;
1067 }
1068
1069 static void otherInfo_attach (ZOOM_connection c, Z_APDU *a, ODR out)
1070 {
1071     int i;
1072     for (i = 0; i<200; i++)
1073     {
1074         size_t len;
1075         Z_OtherInformation **oi;
1076         char buf[80];
1077         const char *val;
1078         const char *cp;
1079         int oidval;
1080
1081         sprintf (buf, "otherInfo%d", i);
1082         val = ZOOM_options_get (c->options, buf);
1083         if (!val)
1084             break;
1085         cp = strchr(val, ':');
1086         if (!cp)
1087             continue;
1088         len = cp - val;
1089         if (len >= sizeof(buf))
1090             len = sizeof(buf)-1;
1091         memcpy (buf, val, len);
1092         buf[len] = '\0';
1093         oidval = oid_getvalbyname (buf);
1094         if (oidval == VAL_NONE)
1095             continue;
1096         
1097         yaz_oi_APDU(a, &oi);
1098         yaz_oi_set_string_oidval(oi, out, oidval, 1, cp+1);
1099     }
1100 }
1101
1102 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1103 {
1104     assert (a);
1105     if (c->cookie_out)
1106     {
1107         Z_OtherInformation **oi;
1108         yaz_oi_APDU(a, &oi);
1109         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
1110     }
1111     if (c->client_IP)
1112     {
1113         Z_OtherInformation **oi;
1114         yaz_oi_APDU(a, &oi);
1115         yaz_oi_set_string_oidval(oi, out, VAL_CLIENT_IP, 1, c->client_IP);
1116     }
1117     otherInfo_attach (c, a, out);
1118     if (!z_APDU(out, &a, 0, 0))
1119     {
1120         FILE *outf = fopen("/tmp/apdu.txt", "a");
1121         if (a && outf)
1122         {
1123             ODR odr_pr = odr_createmem(ODR_PRINT);
1124             fprintf (outf, "a=%p\n", a);
1125             odr_setprint(odr_pr, outf);
1126             z_APDU(odr_pr, &a, 0, 0);
1127             odr_destroy(odr_pr);
1128         }
1129         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1130         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1131         odr_reset(out);
1132         return -1;
1133     }
1134     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1135     return 0;
1136 }
1137
1138 static zoom_ret send_APDU (ZOOM_connection c, Z_APDU *a)
1139 {
1140     ZOOM_Event event;
1141     assert (a);
1142     if (encode_APDU(c, a, c->odr_out))
1143         return zoom_complete;
1144     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1145     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1146     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
1147     ZOOM_connection_put_event (c, event);
1148     odr_reset(c->odr_out);
1149     return do_write (c);
1150 }
1151
1152 /* returns 1 if PDU was sent OK (still pending )
1153            0 if PDU was not sent OK (nothing to wait for) 
1154 */
1155
1156 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c)
1157 {
1158     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1159     Z_InitRequest *ireq = apdu->u.initRequest;
1160     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1161         odr_malloc(c->odr_out, sizeof(*auth));
1162     const char *auth_groupId = ZOOM_options_get (c->options, "group");
1163     const char *auth_userId = ZOOM_options_get (c->options, "user");
1164     const char *auth_password = ZOOM_options_get (c->options, "password");
1165     char *version;
1166
1167     /* support the pass for backwards compatibility */
1168     if (!auth_password)
1169         auth_password = ZOOM_options_get (c->options, "pass");
1170         
1171     ODR_MASK_SET(ireq->options, Z_Options_search);
1172     ODR_MASK_SET(ireq->options, Z_Options_present);
1173     ODR_MASK_SET(ireq->options, Z_Options_scan);
1174     ODR_MASK_SET(ireq->options, Z_Options_sort);
1175     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1176     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1177     
1178     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1179     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1180     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1181
1182     /* Index Data's Z39.50 Implementor Id is 81 */
1183     ireq->implementationId = odr_prepend(c->odr_out,
1184         ZOOM_options_get(c->options, "implementationId"),
1185         odr_prepend(c->odr_out, "81", ireq->implementationId));
1186
1187     ireq->implementationName = odr_prepend(c->odr_out,
1188         ZOOM_options_get(c->options, "implementationName"),
1189         odr_prepend(c->odr_out, "ZOOM-C", ireq->implementationName));
1190
1191     version = odr_strdup(c->odr_out, "$Revision: 1.77 $");
1192     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1193         version[strlen(version)-2] = '\0';
1194     ireq->implementationVersion = odr_prepend(c->odr_out,
1195         ZOOM_options_get(c->options, "implementationVersion"),
1196         odr_prepend(c->odr_out, &version[11], ireq->implementationVersion));
1197
1198     *ireq->maximumRecordSize =
1199         ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
1200     *ireq->preferredMessageSize =
1201         ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
1202     
1203     if (auth_groupId || auth_password)
1204     {
1205         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1206         int i = 0;
1207         pass->groupId = 0;
1208         if (auth_groupId && *auth_groupId)
1209         {
1210             pass->groupId = (char *)
1211                 odr_malloc(c->odr_out, strlen(auth_groupId)+1);
1212             strcpy(pass->groupId, auth_groupId);
1213             i++;
1214         }
1215         pass->userId = 0;
1216         if (auth_userId && *auth_userId)
1217         {
1218             pass->userId = (char *)
1219                 odr_malloc(c->odr_out, strlen(auth_userId)+1);
1220             strcpy(pass->userId, auth_userId);
1221             i++;
1222         }
1223         pass->password = 0;
1224         if (auth_password && *auth_password)
1225         {
1226             pass->password = (char *)
1227                 odr_malloc(c->odr_out, strlen(auth_password)+1);
1228             strcpy(pass->password, auth_password);
1229             i++;
1230         }
1231         if (i)
1232         {
1233             auth->which = Z_IdAuthentication_idPass;
1234             auth->u.idPass = pass;
1235             ireq->idAuthentication = auth;
1236         }
1237     }
1238     else if (auth_userId)
1239     {
1240         auth->which = Z_IdAuthentication_open;
1241         auth->u.open = (char *)
1242             odr_malloc(c->odr_out, strlen(auth_userId)+1);
1243         strcpy(auth->u.open, auth_userId);
1244         ireq->idAuthentication = auth;
1245     }
1246     if (c->proxy)
1247         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
1248                                  VAL_PROXY, 1, c->host_port);
1249     if (c->charset || c->lang)
1250     {
1251         Z_OtherInformation **oi;
1252         Z_OtherInformationUnit *oi_unit;
1253         
1254         yaz_oi_APDU(apdu, &oi);
1255         
1256         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1257         {
1258             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1259             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1260             oi_unit->information.externallyDefinedInfo =
1261                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1262                                               c->charset, c->lang, 1);
1263         }
1264     }
1265     assert (apdu);
1266     return send_APDU (c, apdu);
1267 }
1268
1269 #if HAVE_XML2
1270 static zoom_ret send_srw (ZOOM_connection c, Z_SRW_PDU *sr)
1271 {
1272     Z_GDU *gdu;
1273     ZOOM_Event event;
1274
1275     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port, c->path);
1276
1277     if (c->sru_mode == zoom_sru_get)
1278     {
1279         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1280     }
1281     else if (c->sru_mode == zoom_sru_post)
1282     {
1283         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1284     }
1285     else if (c->sru_mode == zoom_sru_soap)
1286     {
1287         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1288     }
1289     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1290         return zoom_complete;
1291     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1292         
1293     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
1294     ZOOM_connection_put_event (c, event);
1295     odr_reset(c->odr_out);
1296     return do_write (c);
1297 }
1298 #endif
1299
1300 #if HAVE_XML2
1301 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1302 {
1303     int i;
1304     ZOOM_resultset resultset = 0;
1305     Z_SRW_PDU *sr = 0;
1306     const char *recordPacking = 0;
1307
1308     if (c->error)                  /* don't continue on error */
1309         return zoom_complete;
1310     assert (c->tasks);
1311     if (c->tasks->which == ZOOM_TASK_SEARCH)
1312     {
1313         resultset = c->tasks->u.search.resultset;
1314         resultset->setname = xstrdup ("default");
1315         ZOOM_options_set (resultset->options, "setname", resultset->setname);
1316     }
1317     else if(c->tasks->which == ZOOM_TASK_RETRIEVE)
1318     {
1319         resultset = c->tasks->u.retrieve.resultset;
1320
1321         resultset->start = c->tasks->u.retrieve.start;
1322         resultset->count = c->tasks->u.retrieve.count;
1323         
1324         if (resultset->start >= resultset->size)
1325             return zoom_complete;
1326         if (resultset->start + resultset->count > resultset->size)
1327             resultset->count = resultset->size - resultset->start;
1328
1329         for (i = 0; i<resultset->count; i++)
1330         {
1331             ZOOM_record rec =
1332                 record_cache_lookup (resultset, i + resultset->start);
1333             if (!rec)
1334                 break;
1335         }
1336         if (i == resultset->count)
1337             return zoom_complete;
1338     }
1339     assert(resultset->query);
1340         
1341     sr = yaz_srw_get(c->odr_out, Z_SRW_searchRetrieve_request);
1342
1343     if (resultset->query->z_query->which == Z_Query_type_104
1344         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1345     {
1346
1347         sr->u.request->query_type = Z_SRW_query_type_cql;
1348         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1349     }
1350     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1351              resultset->query->z_query->u.type_1)
1352     {
1353         sr->u.request->query_type = Z_SRW_query_type_pqf;
1354         sr->u.request->query.pqf = resultset->query->query_string;
1355     }
1356     else
1357     {
1358         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1359         return zoom_complete;
1360     }
1361     sr->u.request->startRecord = odr_intdup (c->odr_out, resultset->start + 1);
1362     sr->u.request->maximumRecords = odr_intdup (
1363         c->odr_out, resultset->step>0 ? resultset->step : resultset->count);
1364     sr->u.request->recordSchema = resultset->schema;
1365
1366     recordPacking = ZOOM_resultset_option_get (resultset, "recordPacking");
1367
1368     if (recordPacking)
1369         sr->u.request->recordPacking = odr_strdup(c->odr_out, recordPacking);
1370     
1371     return send_srw(c, sr);
1372 }
1373 #else
1374 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1375 {
1376     return zoom_complete;
1377 }
1378 #endif
1379
1380 static zoom_ret ZOOM_connection_send_search (ZOOM_connection c)
1381 {
1382     ZOOM_resultset r;
1383     int lslb, ssub, mspn;
1384     const char *syntax;
1385     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1386     Z_SearchRequest *search_req = apdu->u.searchRequest;
1387     const char *elementSetName;
1388     const char *smallSetElementSetName;
1389     const char *mediumSetElementSetName;
1390
1391     assert (c->tasks);
1392     assert (c->tasks->which == ZOOM_TASK_SEARCH);
1393
1394     r = c->tasks->u.search.resultset;
1395
1396     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1397
1398     elementSetName =
1399         ZOOM_options_get (r->options, "elementSetName");
1400     smallSetElementSetName  =
1401         ZOOM_options_get (r->options, "smallSetElementSetName");
1402     mediumSetElementSetName =
1403         ZOOM_options_get (r->options, "mediumSetElementSetName");
1404
1405     if (!smallSetElementSetName)
1406         smallSetElementSetName = elementSetName;
1407
1408     if (!mediumSetElementSetName)
1409         mediumSetElementSetName = elementSetName;
1410
1411     assert (r);
1412     assert (r->query);
1413
1414     /* prepare query for the search request */
1415     search_req->query = r->query->z_query;
1416     if (!search_req->query)
1417     {
1418         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1419         return zoom_complete;
1420     }
1421
1422     search_req->databaseNames =
1423         set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
1424
1425     /* get syntax (no need to provide unless piggyback is in effect) */
1426     syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
1427
1428     lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
1429     ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
1430     mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
1431     if (lslb != -1 && ssub != -1 && mspn != -1)
1432     {
1433         /* So're a Z39.50 expert? Let's hope you don't do sort */
1434         *search_req->largeSetLowerBound = lslb;
1435         *search_req->smallSetUpperBound = ssub;
1436         *search_req->mediumSetPresentNumber = mspn;
1437     }
1438     else if (r->start == 0 && r->count > 0
1439              && r->piggyback && !r->r_sort_spec && !r->schema)
1440     {
1441         /* Regular piggyback - do it unless we're going to do sort */
1442         *search_req->largeSetLowerBound = 2000000000;
1443         *search_req->smallSetUpperBound = 1;
1444         *search_req->mediumSetPresentNumber = r->step>0 ? r->step : r->count;
1445     }
1446     else
1447     {
1448         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1449         smallSetElementSetName = 0;
1450         mediumSetElementSetName = 0;
1451         syntax = 0;
1452     }
1453     if (smallSetElementSetName && *smallSetElementSetName)
1454     {
1455         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1456             odr_malloc (c->odr_out, sizeof(*esn));
1457         
1458         esn->which = Z_ElementSetNames_generic;
1459         esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
1460         search_req->smallSetElementSetNames = esn;
1461     }
1462     if (mediumSetElementSetName && *mediumSetElementSetName)
1463     {
1464         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1465             odr_malloc (c->odr_out, sizeof(*esn));
1466         
1467         esn->which = Z_ElementSetNames_generic;
1468         esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
1469         search_req->mediumSetElementSetNames = esn;
1470     }
1471     if (syntax)
1472         search_req->preferredRecordSyntax =
1473             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1474     
1475     if (!r->setname)
1476     {
1477         if (c->support_named_resultsets)
1478         {
1479             char setname[14];
1480             int ord;
1481             /* find the lowest unused ordinal so that we re-use
1482                result sets on the server. */
1483             for (ord = 1; ; ord++)
1484             {
1485                 ZOOM_resultset rp;
1486                 sprintf (setname, "%d", ord);
1487                 for (rp = c->resultsets; rp; rp = rp->next)
1488                     if (rp->setname && !strcmp (rp->setname, setname))
1489                         break;
1490                 if (!rp)
1491                     break;
1492             }
1493             r->setname = xstrdup (setname);
1494             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1495                     "set %s", c, r->setname);
1496         }
1497         else
1498         {
1499             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1500                     "default set", c);
1501             r->setname = xstrdup ("default");
1502         }
1503         ZOOM_options_set (r->options, "setname", r->setname);
1504     }
1505     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1506     return send_APDU (c, apdu);
1507 }
1508
1509 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1510 {
1511     int oclass;
1512     char *addinfo = 0;
1513
1514     switch (r->which)
1515     {
1516     case Z_DefaultDiagFormat_v2Addinfo:
1517         addinfo = r->u.v2Addinfo;
1518         break;
1519     case Z_DefaultDiagFormat_v3Addinfo:
1520         addinfo = r->u.v3Addinfo;
1521         break;
1522     }
1523     xfree (c->addinfo);
1524     c->addinfo = 0;
1525     set_dset_error(c, *r->condition,
1526                    yaz_z3950oid_to_str(r->diagnosticSetId, &oclass),
1527                    addinfo, 0);
1528 }
1529
1530 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1531 {
1532     if (p->which != Z_DiagRec_defaultFormat)
1533         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1534     else
1535         response_default_diag(c, p->u.defaultFormat);
1536 }
1537
1538 ZOOM_API(ZOOM_record)
1539 ZOOM_record_clone (ZOOM_record srec)
1540 {
1541     char *buf;
1542     int size;
1543     ODR odr_enc;
1544     ZOOM_record nrec;
1545
1546     odr_enc = odr_createmem(ODR_ENCODE);
1547     if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
1548         return 0;
1549     buf = odr_getbuf (odr_enc, &size, 0);
1550     
1551     nrec = (ZOOM_record) xmalloc (sizeof(*nrec));
1552     nrec->odr = odr_createmem(ODR_DECODE);
1553     nrec->wrbuf_marc = 0;
1554     nrec->wrbuf_iconv = 0;
1555     nrec->wrbuf_opac = 0;
1556     odr_setbuf (nrec->odr, buf, size, 0);
1557     z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
1558     
1559     odr_destroy (odr_enc);
1560     return nrec;
1561 }
1562
1563 ZOOM_API(ZOOM_record)
1564 ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
1565 {
1566     return record_cache_lookup (s, pos);
1567 }
1568
1569 ZOOM_API(ZOOM_record)
1570 ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
1571 {
1572     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1573
1574     if (!rec)
1575     {
1576         /*
1577          * MIKE: I think force_sync should always be zero, but I don't
1578          * want to make this change until I get the go-ahead from
1579          * Adam, in case something depends on the old synchronous
1580          * behaviour.
1581          */
1582         int force_sync = 1;
1583         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1584         ZOOM_resultset_retrieve (r, force_sync, pos, 1);
1585         rec = ZOOM_resultset_record_immediate (r, pos);
1586     }
1587     return rec;
1588 }
1589
1590 ZOOM_API(void)
1591 ZOOM_record_destroy (ZOOM_record rec)
1592 {
1593     if (!rec)
1594         return;
1595     if (rec->wrbuf_marc)
1596         wrbuf_free (rec->wrbuf_marc, 1);
1597     if (rec->wrbuf_iconv)
1598         wrbuf_free (rec->wrbuf_iconv, 1);
1599     if (rec->wrbuf_opac)
1600         wrbuf_free (rec->wrbuf_opac, 1);
1601     odr_destroy (rec->odr);
1602     xfree (rec);
1603 }
1604
1605 static const char *marc_iconv_return(ZOOM_record rec, int marc_type,
1606                                      int *len,
1607                                      const char *buf, int sz,
1608                                      const char *record_charset)
1609 {
1610     char to[40];
1611     char from[40];
1612     yaz_iconv_t cd = 0;
1613     yaz_marc_t mt = yaz_marc_create();
1614
1615     *from = '\0';
1616     strcpy(to, "UTF-8");
1617     if (record_charset && *record_charset)
1618     {
1619         /* Use "from,to" or just "from" */
1620         const char *cp = strchr(record_charset, ',');
1621         int clen = strlen(record_charset);
1622         if (cp && cp[1])
1623         {
1624             strncpy( to, cp+1, sizeof(to)-1);
1625             to[sizeof(to)-1] = '\0';
1626             clen = cp - record_charset;
1627         }
1628         if (clen > sizeof(from)-1)
1629             clen = sizeof(from)-1;
1630         
1631         if (clen)
1632             strncpy(from, record_charset, clen);
1633         from[clen] = '\0';
1634     }
1635
1636     if (*from && *to)
1637     {
1638         cd = yaz_iconv_open(to, from);
1639         yaz_marc_iconv(mt, cd);
1640     }
1641
1642     yaz_marc_xml(mt, marc_type);
1643     if (!rec->wrbuf_marc)
1644         rec->wrbuf_marc = wrbuf_alloc();
1645     wrbuf_rewind (rec->wrbuf_marc);
1646     if (yaz_marc_decode_wrbuf (mt, buf, sz, rec->wrbuf_marc) > 0)
1647     {
1648         yaz_marc_destroy(mt);
1649         if (cd)
1650             yaz_iconv_close(cd);
1651         if (len)
1652             *len = wrbuf_len(rec->wrbuf_marc);
1653         return wrbuf_buf(rec->wrbuf_marc);
1654     }
1655     yaz_marc_destroy(mt);
1656     if (cd)
1657         yaz_iconv_close(cd);
1658     return 0;
1659 }
1660
1661 static const char *record_iconv_return(ZOOM_record rec, int *len,
1662                                        const char *buf, int sz,
1663                                        const char *record_charset)
1664 {
1665     char to[40];
1666     char from[40];
1667     yaz_iconv_t cd = 0;
1668
1669     *from = '\0';
1670     strcpy(to, "UTF-8");
1671     if (record_charset && *record_charset)
1672     {
1673         /* Use "from,to" or just "from" */
1674         const char *cp = strchr(record_charset, ',');
1675         int clen = strlen(record_charset);
1676         if (cp && cp[1])
1677         {
1678             strncpy( to, cp+1, sizeof(to)-1);
1679             to[sizeof(to)-1] = '\0';
1680             clen = cp - record_charset;
1681         }
1682         if (clen > sizeof(from)-1)
1683             clen = sizeof(from)-1;
1684         
1685         if (clen)
1686             strncpy(from, record_charset, clen);
1687         from[clen] = '\0';
1688     }
1689
1690     if (*from && *to && (cd = yaz_iconv_open(to, from)))
1691     {
1692         char outbuf[12];
1693         size_t inbytesleft = sz;
1694         const char *inp = buf;
1695         
1696         if (!rec->wrbuf_iconv)
1697             rec->wrbuf_iconv = wrbuf_alloc();
1698
1699         wrbuf_rewind(rec->wrbuf_iconv);
1700
1701         while (inbytesleft)
1702         {
1703             size_t outbytesleft = sizeof(outbuf);
1704             char *outp = outbuf;
1705             size_t r = yaz_iconv (cd, (char**) &inp,
1706                                   &inbytesleft, 
1707                                   &outp, &outbytesleft);
1708             if (r == (size_t) (-1))
1709             {
1710                 int e = yaz_iconv_error(cd);
1711                 if (e != YAZ_ICONV_E2BIG)
1712                     break;
1713             }
1714             wrbuf_write(rec->wrbuf_iconv, outbuf, outp - outbuf);
1715         }
1716         wrbuf_puts(rec->wrbuf_iconv, "");
1717         buf = wrbuf_buf(rec->wrbuf_iconv);
1718         sz = wrbuf_len(rec->wrbuf_iconv);
1719         yaz_iconv_close(cd);
1720     }
1721     if (len)
1722         *len = sz;
1723     return buf;
1724 }
1725
1726 ZOOM_API(const char *)
1727 ZOOM_record_get (ZOOM_record rec, const char *type_spec, int *len)
1728 {
1729     char type[40];
1730     char charset[40];
1731     char xpath[512];
1732     const char *cp;
1733     int i;
1734     Z_NamePlusRecord *npr;
1735     
1736     if (len)
1737         *len = 0; /* default return */
1738         
1739     if (!rec)
1740         return 0;
1741     npr = rec->npr;
1742     if (!npr)
1743         return 0;
1744
1745     cp = type_spec;
1746     for (i = 0; cp[i] && i < sizeof(type)-1; i++)
1747     {
1748         if (cp[i] == ';' || cp[i] == ' ')
1749             break;
1750         type[i] = cp[i];
1751     }
1752     type[i] = '\0';
1753     charset[0] = '\0';
1754     while (type_spec[i] == ';')
1755     {
1756         i++;
1757         while (type_spec[i] == ' ')
1758             i++;
1759         if (!strncmp(type_spec+i, "charset=", 8))
1760         {
1761             int j = 0;
1762             i = i + 8; /* skip charset= */
1763             for (j = 0; type_spec[i]  && j < sizeof(charset)-1; i++, j++)
1764             {
1765                 if (type_spec[i] == ';' || type_spec[i] == ' ')
1766                     break;
1767                 charset[j] = cp[i];
1768             }
1769             charset[j] = '\0';
1770         }
1771         else if (!strncmp(type_spec+i, "xpath=", 6))
1772         {
1773             int j = 0; 
1774             i = i + 6;
1775             for (j = 0; type_spec[i] && j < sizeof(xpath)-1; i++, j++)
1776                 xpath[j] = cp[i];
1777             xpath[j] = '\0';
1778         } 
1779         while (type_spec[i] == ' ')
1780             i++;
1781     }
1782     if (!strcmp (type, "database"))
1783     {
1784         if (len)
1785             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
1786         return npr->databaseName;
1787     }
1788     else if (!strcmp (type, "syntax"))
1789     {
1790         const char *desc = 0;   
1791         if (npr->which == Z_NamePlusRecord_databaseRecord)
1792         {
1793             Z_External *r = (Z_External *) npr->u.databaseRecord;
1794             oident *ent = oid_getentbyoid(r->direct_reference);
1795             if (ent)
1796                 desc = ent->desc;
1797         }
1798         if (!desc)
1799             desc = "none";
1800         if (len)
1801             *len = strlen(desc);
1802         return desc;
1803     }
1804     if (npr->which != Z_NamePlusRecord_databaseRecord)
1805         return 0;
1806
1807     /* from now on - we have a database record .. */
1808     if (!strcmp (type, "render"))
1809     {
1810         Z_External *r = (Z_External *) npr->u.databaseRecord;
1811         oident *ent = oid_getentbyoid(r->direct_reference);
1812
1813         /* render bibliographic record .. */
1814         if (r->which == Z_External_OPAC)
1815         {
1816             r = r->u.opac->bibliographicRecord;
1817             if (!r)
1818                 return 0;
1819             ent = oid_getentbyoid(r->direct_reference);
1820         }
1821         if (r->which == Z_External_sutrs)
1822             return record_iconv_return(rec, len,
1823                                        (char*) r->u.sutrs->buf,
1824                                        r->u.sutrs->len,
1825                                        charset);
1826         else if (r->which == Z_External_octet)
1827         {
1828             const char *ret_buf;
1829             switch (ent->value)
1830             {
1831             case VAL_SOIF:
1832             case VAL_HTML:
1833             case VAL_SUTRS:
1834                 break;
1835             case VAL_TEXT_XML:
1836             case VAL_APPLICATION_XML:
1837                 break;
1838             default:
1839                 ret_buf = marc_iconv_return(
1840                     rec, YAZ_MARC_LINE, len,
1841                     (const char *) r->u.octet_aligned->buf,
1842                     r->u.octet_aligned->len,
1843                     charset);
1844                 if (ret_buf)
1845                     return ret_buf;
1846             }
1847             return record_iconv_return(rec, len,
1848                                        (const char *) r->u.octet_aligned->buf,
1849                                        r->u.octet_aligned->len,
1850                                        charset);
1851         }
1852         else if (r->which == Z_External_grs1)
1853         {
1854             if (!rec->wrbuf_marc)
1855                 rec->wrbuf_marc = wrbuf_alloc();
1856             wrbuf_rewind (rec->wrbuf_marc);
1857             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1858             return record_iconv_return(rec, len,
1859                                        wrbuf_buf(rec->wrbuf_marc),
1860                                        wrbuf_len(rec->wrbuf_marc),
1861                                        charset);
1862         }
1863         return 0;
1864     }
1865     else if (!strcmp (type, "xml"))
1866     {
1867         Z_External *r = (Z_External *) npr->u.databaseRecord;
1868         oident *ent = oid_getentbyoid(r->direct_reference);
1869
1870         /* render bibliographic record .. */
1871         if (r->which == Z_External_OPAC)
1872         {
1873             r = r->u.opac->bibliographicRecord;
1874             if (!r)
1875                 return 0;
1876             ent = oid_getentbyoid(r->direct_reference);
1877         }
1878         
1879         if (r->which == Z_External_sutrs)
1880             return record_iconv_return(rec, len,
1881                                        (const char *) r->u.sutrs->buf,
1882                                        r->u.sutrs->len,
1883                                        charset);
1884         else if (r->which == Z_External_octet)
1885         {
1886             const char *ret_buf;
1887             int marc_decode_type = YAZ_MARC_MARCXML;
1888
1889             switch (ent->value)
1890             {
1891             case VAL_SOIF:
1892             case VAL_HTML:
1893             case VAL_SUTRS:
1894                 break;
1895             case VAL_TEXT_XML:
1896             case VAL_APPLICATION_XML:
1897                 break;
1898             default:
1899                 ret_buf = marc_iconv_return(
1900                     rec, marc_decode_type, len,
1901                     (const char *) r->u.octet_aligned->buf,
1902                     r->u.octet_aligned->len,
1903                     charset);
1904                 if (ret_buf)
1905                     return ret_buf;
1906             }
1907             return record_iconv_return(rec, len,
1908                                        (const char *) r->u.octet_aligned->buf,
1909                                        r->u.octet_aligned->len,
1910                                        charset);
1911         }
1912         else if (r->which == Z_External_grs1)
1913         {
1914             if (len) *len = 5;
1915             return "GRS-1";
1916         }
1917         return 0;
1918     }
1919     else if (!strcmp (type, "raw"))
1920     {
1921         Z_External *r = (Z_External *) npr->u.databaseRecord;
1922         
1923         if (r->which == Z_External_sutrs)
1924         {
1925             if (len) *len = r->u.sutrs->len;
1926             return (const char *) r->u.sutrs->buf;
1927         }
1928         else if (r->which == Z_External_octet)
1929         {
1930             if (len) *len = r->u.octet_aligned->len;
1931             return (const char *) r->u.octet_aligned->buf;
1932         }
1933         else /* grs-1, explain, OPAC, ... */
1934         {
1935             if (len) *len = -1;
1936             return (const char *) npr->u.databaseRecord;
1937         }
1938         return 0;
1939     }
1940     else if (!strcmp (type, "ext"))
1941     {
1942         if (len) *len = -1;
1943         return (const char *) npr->u.databaseRecord;
1944     }
1945     else if (!strcmp (type, "opac"))
1946              
1947     {
1948         Z_External *r = (Z_External *) npr->u.databaseRecord;
1949         if (r->which == Z_External_OPAC)
1950         {
1951             if (!rec->wrbuf_opac)
1952                 rec->wrbuf_opac = wrbuf_alloc();
1953             wrbuf_rewind (rec->wrbuf_opac);
1954             yaz_display_OPAC(rec->wrbuf_opac, r->u.opac, 0);
1955             return record_iconv_return(rec, len,
1956                                        wrbuf_buf(rec->wrbuf_opac),
1957                                        wrbuf_len(rec->wrbuf_opac),
1958                                        charset);
1959         }
1960     }
1961     return 0;
1962 }
1963
1964 static int strcmp_null(const char *v1, const char *v2)
1965 {
1966     if (!v1 && !v2)
1967         return 0;
1968     if (!v1 || !v2)
1969         return -1;
1970     return strcmp(v1, v2);
1971 }
1972
1973 static size_t record_hash(int pos)
1974 {
1975     if (pos < 0)
1976         pos = 0;
1977     return pos % RECORD_HASH_SIZE;
1978 }
1979
1980 static void record_cache_add (ZOOM_resultset r, Z_NamePlusRecord *npr, 
1981                               int pos)
1982 {
1983     ZOOM_record_cache rc;
1984     const char *elementSetName =
1985         ZOOM_resultset_option_get (r, "elementSetName");
1986     const char *syntax = 
1987         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1988     
1989     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1990     ZOOM_connection_put_event(r->connection, event);
1991
1992     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
1993     {
1994         if (pos == rc->pos)
1995         {
1996             if (strcmp_null(r->schema, rc->schema))
1997                 continue;
1998             if (strcmp_null(elementSetName,rc->elementSetName))
1999                 continue;
2000             if (strcmp_null(syntax, rc->syntax))
2001                 continue;
2002             /* not destroying rc->npr (it's handled by nmem )*/
2003             rc->rec.npr = npr;
2004             /* keeping wrbuf_marc too */
2005             return;
2006         }
2007     }
2008     rc = (ZOOM_record_cache) odr_malloc (r->odr, sizeof(*rc));
2009     rc->rec.npr = npr; 
2010     rc->rec.odr = 0;
2011     rc->rec.wrbuf_marc = 0;
2012     rc->rec.wrbuf_iconv = 0;
2013     rc->rec.wrbuf_opac = 0;
2014     if (elementSetName)
2015         rc->elementSetName = odr_strdup (r->odr, elementSetName);
2016     else
2017         rc->elementSetName = 0;
2018
2019     if (syntax)
2020         rc->syntax = odr_strdup (r->odr, syntax);
2021     else
2022         rc->syntax = 0;
2023
2024     if (r->schema)
2025         rc->schema = odr_strdup (r->odr, r->schema);
2026     else
2027         rc->schema = 0;
2028
2029     rc->pos = pos;
2030     rc->next = r->record_hash[record_hash(pos)];
2031     r->record_hash[record_hash(pos)] = rc;
2032 }
2033
2034 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos)
2035 {
2036     ZOOM_record_cache rc;
2037     const char *elementSetName =
2038         ZOOM_resultset_option_get (r, "elementSetName");
2039     const char *syntax = 
2040         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
2041     
2042     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2043     {
2044         if (pos == rc->pos)
2045         {
2046             if (strcmp_null(r->schema, rc->schema))
2047                 continue;
2048             if (strcmp_null(elementSetName,rc->elementSetName))
2049                 continue;
2050             if (strcmp_null(syntax, rc->syntax))
2051                 continue;
2052             return &rc->rec;
2053         }
2054     }
2055     return 0;
2056 }
2057                                              
2058 static void handle_records (ZOOM_connection c, Z_Records *sr,
2059                             int present_phase)
2060 {
2061     ZOOM_resultset resultset;
2062
2063     if (!c->tasks)
2064         return ;
2065     switch (c->tasks->which)
2066     {
2067     case ZOOM_TASK_SEARCH:
2068         resultset = c->tasks->u.search.resultset;
2069         break;
2070     case ZOOM_TASK_RETRIEVE:
2071         resultset = c->tasks->u.retrieve.resultset;        
2072         break;
2073     default:
2074         return;
2075     }
2076     if (sr && sr->which == Z_Records_NSD)
2077         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2078     else if (sr && sr->which == Z_Records_multipleNSD)
2079     {
2080         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2081             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2082         else
2083             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2084     }
2085     else 
2086     {
2087         if (resultset->count + resultset->start > resultset->size)
2088             resultset->count = resultset->size - resultset->start;
2089         if (resultset->count < 0)
2090             resultset->count = 0;
2091         if (sr && sr->which == Z_Records_DBOSD)
2092         {
2093             int i;
2094             NMEM nmem = odr_extract_mem (c->odr_in);
2095             Z_NamePlusRecordList *p =
2096                 sr->u.databaseOrSurDiagnostics;
2097             for (i = 0; i<p->num_records; i++)
2098             {
2099                 record_cache_add (resultset, p->records[i],
2100                                   i+ resultset->start);
2101             }
2102             /* transfer our response to search_nmem .. we need it later */
2103             nmem_transfer (resultset->odr->mem, nmem);
2104             nmem_destroy (nmem);
2105             if (present_phase && p->num_records == 0)
2106             {
2107                 /* present response and we didn't get any records! */
2108                 Z_NamePlusRecord *myrec = 
2109                     zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2110                 record_cache_add(resultset, myrec, resultset->start);
2111             }
2112         }
2113         else if (present_phase)
2114         {
2115             /* present response and we didn't get any records! */
2116             Z_NamePlusRecord *myrec = 
2117                 zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2118             record_cache_add(resultset, myrec, resultset->start);
2119         }
2120     }
2121 }
2122
2123 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
2124 {
2125     handle_records (c, pr->records, 1);
2126 }
2127
2128 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2129                                        Z_Term *term)
2130 {
2131     switch (term->which)
2132     {
2133     case Z_Term_general:
2134         ZOOM_options_setl(opt, name,
2135                           (const char *)(term->u.general->buf), 
2136                           term->u.general->len);
2137         break;
2138     case Z_Term_characterString:
2139         ZOOM_options_set(opt, name, term->u.characterString);
2140         break;
2141     case Z_Term_numeric:
2142         ZOOM_options_set_int(opt, name, *term->u.numeric);
2143         break;
2144     }
2145 }
2146
2147 static void handle_queryExpression(ZOOM_options opt, const char *name,
2148                                    Z_QueryExpression *exp)
2149 {
2150     char opt_name[80];
2151     
2152     switch (exp->which)
2153     {
2154     case Z_QueryExpression_term:
2155         if (exp->u.term && exp->u.term->queryTerm)
2156         {
2157             sprintf(opt_name, "%s.term", name);
2158             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2159         }
2160         break;
2161     case Z_QueryExpression_query:
2162         break;
2163     }
2164 }
2165
2166 static void handle_searchResult(ZOOM_connection c, ZOOM_resultset resultset,
2167                                 Z_OtherInformation *o)
2168 {
2169     int i;
2170     for (i = 0; o && i < o->num_elements; i++)
2171     {
2172         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2173         {
2174             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2175             
2176             if (ext->which == Z_External_searchResult1)
2177             {
2178                 int j;
2179                 Z_SearchInfoReport *sr = ext->u.searchResult1;
2180                 
2181                 if (sr->num)
2182                     ZOOM_options_set_int(
2183                         resultset->options, "searchresult.size", sr->num);
2184
2185                 for (j = 0; j < sr->num; j++)
2186                 {
2187                     Z_SearchInfoReport_s *ent =
2188                         ext->u.searchResult1->elements[j];
2189                     char pref[80];
2190                     
2191                     sprintf(pref, "searchresult.%d", j);
2192
2193                     if (ent->subqueryId)
2194                     {
2195                         char opt_name[80];
2196                         sprintf(opt_name, "%s.id", pref);
2197                         ZOOM_options_set(resultset->options, opt_name,
2198                                          ent->subqueryId);
2199                     }
2200                     if (ent->subqueryExpression)
2201                     {
2202                         char opt_name[80];
2203                         sprintf(opt_name, "%s.subquery", pref);
2204                         handle_queryExpression(resultset->options, opt_name,
2205                                                ent->subqueryExpression);
2206                     }
2207                     if (ent->subqueryInterpretation)
2208                     {
2209                         char opt_name[80];
2210                         sprintf(opt_name, "%s.interpretation", pref);
2211                         handle_queryExpression(resultset->options, opt_name,
2212                                                ent->subqueryInterpretation);
2213                     }
2214                     if (ent->subqueryRecommendation)
2215                     {
2216                         char opt_name[80];
2217                         sprintf(opt_name, "%s.recommendation", pref);
2218                         handle_queryExpression(resultset->options, opt_name,
2219                                                ent->subqueryRecommendation);
2220                     }
2221                     if (ent->subqueryCount)
2222                     {
2223                         char opt_name[80];
2224                         sprintf(opt_name, "%s.count", pref);
2225                         ZOOM_options_set_int(resultset->options, opt_name,
2226                                              *ent->subqueryCount);
2227                     }                                             
2228                 }
2229             }
2230         }
2231     }
2232 }
2233
2234 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
2235 {
2236     ZOOM_resultset resultset;
2237     ZOOM_Event event;
2238
2239     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2240         return ;
2241
2242     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2243     ZOOM_connection_put_event(c, event);
2244
2245     resultset = c->tasks->u.search.resultset;
2246
2247     handle_searchResult(c, resultset, sr->additionalSearchInfo);
2248
2249     resultset->size = *sr->resultCount;
2250     handle_records (c, sr->records, 0);
2251 }
2252
2253 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
2254 {
2255     if (res->diagnostics && res->num_diagnostics > 0)
2256         response_diag (c, res->diagnostics[0]);
2257 }
2258
2259 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
2260 {
2261     NMEM nmem = odr_extract_mem (c->odr_in);
2262     ZOOM_scanset scan;
2263
2264     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2265         return 0;
2266     scan = c->tasks->u.scan.scan;
2267
2268     if (res->entries && res->entries->nonsurrogateDiagnostics)
2269         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2270     scan->scan_response = res;
2271     nmem_transfer (scan->odr->mem, nmem);
2272     if (res->stepSize)
2273         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
2274     if (res->positionOfTerm)
2275         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
2276     if (res->scanStatus)
2277         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
2278     if (res->numberOfEntriesReturned)
2279         ZOOM_options_set_int (scan->options, "number",
2280                               *res->numberOfEntriesReturned);
2281     nmem_destroy (nmem);
2282     return 1;
2283 }
2284
2285 static zoom_ret send_sort (ZOOM_connection c,
2286                            ZOOM_resultset resultset)
2287 {
2288     if (c->error)
2289         resultset->r_sort_spec = 0;
2290     if (resultset->r_sort_spec)
2291     {
2292         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2293         Z_SortRequest *req = apdu->u.sortRequest;
2294         
2295         req->num_inputResultSetNames = 1;
2296         req->inputResultSetNames = (Z_InternationalString **)
2297             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
2298         req->inputResultSetNames[0] =
2299             odr_strdup (c->odr_out, resultset->setname);
2300         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
2301         req->sortSequence = resultset->r_sort_spec;
2302         resultset->r_sort_spec = 0;
2303         return send_APDU (c, apdu);
2304     }
2305     return zoom_complete;
2306 }
2307
2308 static zoom_ret send_present(ZOOM_connection c)
2309 {
2310     Z_APDU *apdu = 0;
2311     Z_PresentRequest *req = 0;
2312     int i = 0;
2313     const char *syntax = 0;
2314     const char *elementSetName = 0;
2315     ZOOM_resultset  resultset;
2316
2317     if (!c->tasks)
2318     {
2319         yaz_log(log_details, "%p send_present no tasks", c);
2320         return zoom_complete;
2321     }
2322     switch (c->tasks->which)
2323     {
2324     case ZOOM_TASK_SEARCH:
2325         resultset = c->tasks->u.search.resultset;
2326         break;
2327     case ZOOM_TASK_RETRIEVE:
2328         resultset = c->tasks->u.retrieve.resultset;
2329         resultset->start = c->tasks->u.retrieve.start;
2330         resultset->count = c->tasks->u.retrieve.count;
2331
2332         if (resultset->start >= resultset->size)
2333         {
2334             yaz_log(log_details, "%p send_present start=%d >= size=%d",
2335                     c, resultset->start, resultset->size);
2336             return zoom_complete;
2337         }
2338         if (resultset->start + resultset->count > resultset->size)
2339             resultset->count = resultset->size - resultset->start;
2340         break;
2341     default:
2342         return zoom_complete;
2343     }
2344     yaz_log(log_details, "%p send_present start=%d count=%d",
2345             c, resultset->start, resultset->count);
2346
2347     syntax = ZOOM_resultset_option_get (resultset, "preferredRecordSyntax");
2348     elementSetName = ZOOM_resultset_option_get (resultset, "elementSetName");
2349
2350     if (c->error)                  /* don't continue on error */
2351         return zoom_complete;
2352     if (resultset->start < 0)
2353         return zoom_complete;
2354     for (i = 0; i<resultset->count; i++)
2355     {
2356         ZOOM_record rec =
2357             record_cache_lookup (resultset, i + resultset->start);
2358         if (!rec)
2359             break;
2360     }
2361     if (i == resultset->count)
2362     {
2363         yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2364         return zoom_complete;
2365     }
2366
2367     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2368     req = apdu->u.presentRequest;
2369
2370     resultset->start += i;
2371     resultset->count -= i;
2372
2373     if (i)
2374         yaz_log(log_details, "%p send_present skip=%d", c, i);
2375
2376     *req->resultSetStartPoint = resultset->start + 1;
2377     *req->numberOfRecordsRequested = resultset->step>0 ?
2378         resultset->step : resultset->count;
2379     if (*req->numberOfRecordsRequested + resultset->start > resultset->size)
2380         *req->numberOfRecordsRequested = resultset->size -  resultset->start;
2381     assert (*req->numberOfRecordsRequested > 0);
2382
2383     if (syntax && *syntax)
2384         req->preferredRecordSyntax =
2385             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
2386
2387     if (resultset->schema && *resultset->schema)
2388     {
2389         Z_RecordComposition *compo = (Z_RecordComposition *)
2390             odr_malloc (c->odr_out, sizeof(*compo));
2391
2392         req->recordComposition = compo;
2393         compo->which = Z_RecordComp_complex;
2394         compo->u.complex = (Z_CompSpec *)
2395             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2396         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2397             odr_malloc(c->odr_out, sizeof(bool_t));
2398         *compo->u.complex->selectAlternativeSyntax = 0;
2399
2400         compo->u.complex->generic = (Z_Specification *)
2401             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2402
2403         compo->u.complex->generic->which = Z_Schema_oid;
2404         compo->u.complex->generic->schema.oid = (Odr_oid *)
2405             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, resultset->schema);
2406
2407         if (!compo->u.complex->generic->schema.oid)
2408         {
2409             /* OID wasn't a schema! Try record syntax instead. */
2410
2411             compo->u.complex->generic->schema.oid = (Odr_oid *)
2412                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, resultset->schema);
2413         }
2414         if (elementSetName && *elementSetName)
2415         {
2416             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2417                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2418             compo->u.complex->generic->elementSpec->which =
2419                 Z_ElementSpec_elementSetName;
2420             compo->u.complex->generic->elementSpec->u.elementSetName =
2421                 odr_strdup (c->odr_out, elementSetName);
2422         }
2423         else
2424             compo->u.complex->generic->elementSpec = 0;
2425         compo->u.complex->num_dbSpecific = 0;
2426         compo->u.complex->dbSpecific = 0;
2427         compo->u.complex->num_recordSyntax = 0;
2428         compo->u.complex->recordSyntax = 0;
2429     }
2430     else if (elementSetName && *elementSetName)
2431     {
2432         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2433             odr_malloc (c->odr_out, sizeof(*esn));
2434         Z_RecordComposition *compo = (Z_RecordComposition *)
2435             odr_malloc (c->odr_out, sizeof(*compo));
2436         
2437         esn->which = Z_ElementSetNames_generic;
2438         esn->u.generic = odr_strdup (c->odr_out, elementSetName);
2439         compo->which = Z_RecordComp_simple;
2440         compo->u.simple = esn;
2441         req->recordComposition = compo;
2442     }
2443     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2444     return send_APDU (c, apdu);
2445 }
2446
2447 ZOOM_API(ZOOM_scanset)
2448 ZOOM_connection_scan (ZOOM_connection c, const char *start)
2449 {
2450     ZOOM_scanset s;
2451     ZOOM_query q = ZOOM_query_create();
2452
2453     ZOOM_query_prefix (q, start);
2454
2455     s = ZOOM_connection_scan1(c, q);
2456     ZOOM_query_destroy (q);
2457     return s;
2458
2459 }
2460
2461 ZOOM_API(ZOOM_scanset)
2462 ZOOM_connection_scan1 (ZOOM_connection c, ZOOM_query q)
2463 {
2464     ZOOM_scanset scan = (ZOOM_scanset) xmalloc (sizeof(*scan));
2465     char *start;
2466     char *freeme = 0;
2467
2468     scan->connection = c;
2469     scan->odr = odr_createmem (ODR_DECODE);
2470     scan->options = ZOOM_options_create_with_parent (c->options);
2471     scan->refcount = 1;
2472     scan->scan_response = 0;
2473
2474     /*
2475      * We need to check the query-type, so we can recognise CQL and
2476      * CCL and compile them into a form that we can use here.  The
2477      * ZOOM_query structure has no explicit `type' member, but
2478      * inspection of the ZOOM_query_prefix() and ZOOM_query_cql()
2479      * functions shows how the structure is set up in each case.
2480      */
2481     if (q->z_query->which == Z_Query_type_1) {
2482         yaz_log(log_api, "%p ZOOM_connection_scan1 q=%p PQF '%s'",
2483                 c, q, q->query_string);
2484         start = q->query_string;
2485     } else if (q->z_query->which == Z_Query_type_104) {
2486         yaz_log(log_api, "%p ZOOM_connection_scan1 q=%p CQL '%s'",
2487                 c, q, q->query_string);
2488         start = freeme = cql2pqf(c, q->query_string);
2489         if (start == 0)
2490             return 0;
2491     } else if (q->z_query->which == Z_Query_type_2) {
2492         yaz_log(log_api, "%p ZOOM_connection_scan1 q=%p CCL '%s'",
2493                 c, q, q->query_string);
2494         start = freeme = ccl2pqf(c, q->query_string);
2495         if (start == 0)
2496             return 0;
2497     } else {
2498         yaz_log(YLOG_FATAL, "%p ZOOM_connection_scan1 q=%p unknown type '%s'",
2499                 c, q, q->query_string);
2500         abort();
2501     }
2502
2503     scan->termListAndStartPoint =
2504         p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet, start);
2505     xfree (freeme);
2506     if (scan->termListAndStartPoint != 0)
2507     {
2508         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
2509         task->u.scan.scan = scan;
2510         
2511         (scan->refcount)++;
2512         if (!c->async)
2513         {
2514             while (ZOOM_event (1, &c))
2515                 ;
2516         }
2517     }
2518     return scan;
2519 }
2520
2521 ZOOM_API(void)
2522 ZOOM_scanset_destroy (ZOOM_scanset scan)
2523 {
2524     if (!scan)
2525         return;
2526     (scan->refcount)--;
2527     if (scan->refcount == 0)
2528     {
2529         odr_destroy (scan->odr);
2530         
2531         ZOOM_options_destroy (scan->options);
2532         xfree (scan);
2533     }
2534 }
2535
2536 static zoom_ret send_package (ZOOM_connection c)
2537 {
2538     ZOOM_Event event;
2539
2540     yaz_log(log_details, "%p send_package", c);
2541     if (!c->tasks)
2542         return zoom_complete;
2543     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2544     
2545     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
2546     ZOOM_connection_put_event (c, event);
2547     
2548     c->buf_out = c->tasks->u.package->buf_out;
2549     c->len_out = c->tasks->u.package->len_out;
2550
2551     return do_write(c);
2552 }
2553
2554 static zoom_ret send_scan (ZOOM_connection c)
2555 {
2556     ZOOM_scanset scan;
2557     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2558     Z_ScanRequest *req = apdu->u.scanRequest;
2559
2560     yaz_log(log_details, "%p send_scan", c);
2561     if (!c->tasks)
2562         return zoom_complete;
2563     assert (c->tasks->which == ZOOM_TASK_SCAN);
2564     scan = c->tasks->u.scan.scan;
2565
2566     req->termListAndStartPoint = scan->termListAndStartPoint;
2567     req->attributeSet = scan->attributeSet;
2568
2569     *req->numberOfTermsRequested =
2570         ZOOM_options_get_int(scan->options, "number", 10);
2571
2572     req->preferredPositionInResponse =
2573         odr_intdup (c->odr_out,
2574                     ZOOM_options_get_int(scan->options, "position", 1));
2575
2576     req->stepSize =
2577         odr_intdup (c->odr_out,
2578                     ZOOM_options_get_int(scan->options, "stepSize", 0));
2579     
2580     req->databaseNames = set_DatabaseNames (c, scan->options, 
2581                                             &req->num_databaseNames);
2582
2583     return send_APDU (c, apdu);
2584 }
2585
2586 ZOOM_API(size_t)
2587 ZOOM_scanset_size (ZOOM_scanset scan)
2588 {
2589     if (!scan || !scan->scan_response || !scan->scan_response->entries)
2590         return 0;
2591     return scan->scan_response->entries->num_entries;
2592 }
2593
2594 ZOOM_API(const char *)
2595 ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
2596                    int *occ, int *len)
2597 {
2598     const char *term = 0;
2599     size_t noent = ZOOM_scanset_size (scan);
2600     Z_ScanResponse *res = scan->scan_response;
2601     
2602     *len = 0;
2603     *occ = 0;
2604     if (pos >= noent)
2605         return 0;
2606     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2607     {
2608         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2609         
2610         if (t->term->which == Z_Term_general)
2611         {
2612             term = (const char *) t->term->u.general->buf;
2613             *len = t->term->u.general->len;
2614         }
2615         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2616     }
2617     return term;
2618 }
2619
2620 ZOOM_API(const char *)
2621 ZOOM_scanset_display_term (ZOOM_scanset scan, size_t pos,
2622                            int *occ, int *len)
2623 {
2624     const char *term = 0;
2625     size_t noent = ZOOM_scanset_size (scan);
2626     Z_ScanResponse *res = scan->scan_response;
2627     
2628     *len = 0;
2629     *occ = 0;
2630     if (pos >= noent)
2631         return 0;
2632     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2633     {
2634         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2635
2636         if (t->displayTerm)
2637         {
2638             term = t->displayTerm;
2639             *len = strlen(term);
2640         }
2641         else if (t->term->which == Z_Term_general)
2642         {
2643             term = (const char *) t->term->u.general->buf;
2644             *len = t->term->u.general->len;
2645         }
2646         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2647     }
2648     return term;
2649 }
2650
2651 ZOOM_API(const char *)
2652 ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
2653 {
2654     return ZOOM_options_get (scan->options, key);
2655 }
2656
2657 ZOOM_API(void)
2658 ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
2659                               const char *val)
2660 {
2661     ZOOM_options_set (scan->options, key, val);
2662 }
2663
2664 static Z_APDU *create_es_package (ZOOM_package p, int type)
2665 {
2666     const char *str;
2667     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
2668     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2669     
2670     *req->function = Z_ExtendedServicesRequest_create;
2671     
2672     str = ZOOM_options_get(p->options, "package-name");
2673     if (str && *str)
2674         req->packageName = nmem_strdup (p->odr_out->mem, str);
2675     
2676     str = ZOOM_options_get(p->options, "user-id");
2677     if (str)
2678         req->userId = nmem_strdup (p->odr_out->mem, str);
2679     
2680     req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2681                                               type);
2682
2683     str = ZOOM_options_get(p->options, "function");
2684     if (str)
2685     {
2686         if (!strcmp (str, "create"))
2687             *req->function = 1;
2688         if (!strcmp (str, "delete"))
2689             *req->function = 2;
2690         if (!strcmp (str, "modify"))
2691             *req->function = 3;
2692     }
2693     return apdu;
2694 }
2695
2696 static const char *ill_array_lookup (void *clientData, const char *idx)
2697 {
2698     ZOOM_package p = (ZOOM_package) clientData;
2699     return ZOOM_options_get (p->options, idx+4);
2700 }
2701
2702 static Z_External *encode_ill_request (ZOOM_package p)
2703 {
2704     ODR out = p->odr_out;
2705     ILL_Request *req;
2706     Z_External *r = 0;
2707     struct ill_get_ctl ctl;
2708         
2709     ctl.odr = p->odr_out;
2710     ctl.clientData = p;
2711     ctl.f = ill_array_lookup;
2712         
2713     req = ill_get_ILLRequest(&ctl, "ill", 0);
2714         
2715     if (!ill_Request (out, &req, 0, 0))
2716     {
2717         int ill_request_size;
2718         char *ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2719         if (ill_request_buf)
2720             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2721         return 0;
2722     }
2723     else
2724     {
2725         oident oid;
2726         int illRequest_size = 0;
2727         char *illRequest_buf = odr_getbuf (out, &illRequest_size, 0);
2728                 
2729         oid.proto = PROTO_GENERAL;
2730         oid.oclass = CLASS_GENERAL;
2731         oid.value = VAL_ISO_ILL_1;
2732                 
2733         r = (Z_External *) odr_malloc (out, sizeof(*r));
2734         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
2735         r->indirect_reference = 0;
2736         r->descriptor = 0;
2737         r->which = Z_External_single;
2738                 
2739         r->u.single_ASN1_type =
2740             odr_create_Odr_oct(out,
2741                                (unsigned char *)illRequest_buf,
2742                                illRequest_size);
2743     }
2744     return r;
2745 }
2746
2747 static Z_ItemOrder *encode_item_order(ZOOM_package p)
2748 {
2749     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc (p->odr_out, sizeof(*req));
2750     const char *str;
2751     
2752     req->which = Z_IOItemOrder_esRequest;
2753     req->u.esRequest = (Z_IORequest *) 
2754         odr_malloc(p->odr_out,sizeof(Z_IORequest));
2755
2756     /* to keep part ... */
2757     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2758         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
2759     req->u.esRequest->toKeep->supplDescription = 0;
2760     req->u.esRequest->toKeep->contact = (Z_IOContact *)
2761         odr_malloc (p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
2762         
2763     str = ZOOM_options_get(p->options, "contact-name");
2764     req->u.esRequest->toKeep->contact->name = str ?
2765         nmem_strdup (p->odr_out->mem, str) : 0;
2766         
2767     str = ZOOM_options_get(p->options, "contact-phone");
2768     req->u.esRequest->toKeep->contact->phone = str ?
2769         nmem_strdup (p->odr_out->mem, str) : 0;
2770         
2771     str = ZOOM_options_get(p->options, "contact-email");
2772     req->u.esRequest->toKeep->contact->email = str ?
2773         nmem_strdup (p->odr_out->mem, str) : 0;
2774         
2775     req->u.esRequest->toKeep->addlBilling = 0;
2776         
2777     /* not to keep part ... */
2778     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2779         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
2780         
2781     str = ZOOM_options_get(p->options, "itemorder-setname");
2782     if (!str)
2783         str = "default";
2784
2785     if (!*str) 
2786         req->u.esRequest->notToKeep->resultSetItem = 0;
2787     else
2788     {
2789         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
2790            odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
2791
2792         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
2793            nmem_strdup (p->odr_out->mem, str);
2794         req->u.esRequest->notToKeep->resultSetItem->item =
2795             (int *) odr_malloc(p->odr_out, sizeof(int));
2796         
2797         str = ZOOM_options_get(p->options, "itemorder-item");
2798         *req->u.esRequest->notToKeep->resultSetItem->item =
2799             (str ? atoi(str) : 1);
2800     }
2801     req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
2802     
2803     return req;
2804 }
2805
2806 Z_APDU *create_admin_package(ZOOM_package p, int type, 
2807                              Z_ESAdminOriginPartToKeep **toKeepP,
2808                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
2809 {
2810     Z_APDU *apdu = create_es_package (p, VAL_ADMINSERVICE);
2811     if (apdu)
2812     {
2813         Z_ESAdminOriginPartToKeep  *toKeep;
2814         Z_ESAdminOriginPartNotToKeep  *notToKeep;
2815         Z_External *r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
2816         const char *first_db = "Default";
2817         int num_db;
2818         char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2819         if (num_db > 0)
2820             first_db = db[0];
2821             
2822         r->direct_reference =
2823             yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2824                                    VAL_ADMINSERVICE);
2825         r->descriptor = 0;
2826         r->indirect_reference = 0;
2827         r->which = Z_External_ESAdmin;
2828         
2829         r->u.adminService = (Z_Admin *)
2830             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
2831         r->u.adminService->which = Z_Admin_esRequest;
2832         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
2833             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
2834         
2835         toKeep = r->u.adminService->u.esRequest->toKeep =
2836             (Z_ESAdminOriginPartToKeep *) 
2837             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
2838         toKeep->which = type;
2839         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
2840         toKeep->u.create = odr_nullval();
2841         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2842         
2843         r->u.adminService->u.esRequest->notToKeep = notToKeep =
2844             (Z_ESAdminOriginPartNotToKeep *)
2845             odr_malloc(p->odr_out,
2846                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
2847         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
2848         notToKeep->u.recordsWillFollow = odr_nullval();
2849         if (toKeepP)
2850             *toKeepP = toKeep;
2851         if (notToKeepP)
2852             *notToKeepP = notToKeep;
2853     }
2854     return apdu;
2855 }
2856
2857 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
2858 {
2859     Z_APDU *apdu = create_es_package(p, VAL_XMLES);
2860     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2861     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
2862     const char *doc = ZOOM_options_get(p->options, "doc");
2863
2864     if (!doc)
2865         doc = "";
2866
2867     req->taskSpecificParameters = ext;
2868     ext->direct_reference = req->packageType;
2869     ext->descriptor = 0;
2870     ext->indirect_reference = 0;
2871     
2872     ext->which = Z_External_octet;
2873     ext->u.single_ASN1_type =
2874         odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc,
2875                            strlen(doc));
2876     return apdu;
2877 }
2878
2879 static Z_APDU *create_update_package(ZOOM_package p)
2880 {
2881     Z_APDU *apdu = 0;
2882     const char *first_db = "Default";
2883     int num_db;
2884     char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2885     const char *action = ZOOM_options_get(p->options, "action");
2886     const char *recordIdOpaque = ZOOM_options_get(p->options, "recordIdOpaque");
2887     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
2888     const char *record_buf = ZOOM_options_get(p->options, "record");
2889     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
2890     int syntax_oid = VAL_NONE;
2891     int action_no = -1;
2892     
2893     if (syntax_str)
2894         syntax_oid = oid_getvalbyname(syntax_str);
2895     if (!record_buf)
2896     {
2897         record_buf = "void";
2898         syntax_oid = VAL_SUTRS;
2899     }
2900     if (syntax_oid == VAL_NONE)
2901         syntax_oid = VAL_TEXT_XML;
2902     
2903     if (num_db > 0)
2904         first_db = db[0];
2905     
2906     if (!action)
2907         action = "specialUpdate";
2908     
2909     if (!strcmp(action, "recordInsert"))
2910         action_no = Z_IUOriginPartToKeep_recordInsert;
2911     else if (!strcmp(action, "recordReplace"))
2912         action_no = Z_IUOriginPartToKeep_recordReplace;
2913     else if (!strcmp(action, "recordDelete"))
2914         action_no = Z_IUOriginPartToKeep_recordDelete;
2915     else if (!strcmp(action, "elementUpdate"))
2916         action_no = Z_IUOriginPartToKeep_elementUpdate;
2917     else if (!strcmp(action, "specialUpdate"))
2918         action_no = Z_IUOriginPartToKeep_specialUpdate;
2919     else
2920         return 0;
2921
2922     apdu = create_es_package (p, VAL_DBUPDATE);
2923     if (apdu)
2924     {
2925         Z_IUOriginPartToKeep *toKeep;
2926         Z_IUSuppliedRecords *notToKeep;
2927         Z_External *r = (Z_External *)
2928             odr_malloc (p->odr_out, sizeof(*r));
2929         
2930         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2931         
2932         r->direct_reference =
2933             yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2934                                    VAL_DBUPDATE);
2935         r->descriptor = 0;
2936         r->which = Z_External_update;
2937         r->indirect_reference = 0;
2938         r->u.update = (Z_IUUpdate *)
2939             odr_malloc(p->odr_out, sizeof(*r->u.update));
2940         
2941         r->u.update->which = Z_IUUpdate_esRequest;
2942         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2943             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
2944         toKeep = r->u.update->u.esRequest->toKeep = 
2945             (Z_IUOriginPartToKeep *)
2946             odr_malloc(p->odr_out, sizeof(*toKeep));
2947         
2948         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
2949         toKeep->schema = 0;
2950         toKeep->elementSetName = 0;
2951         toKeep->actionQualifier = 0;
2952         toKeep->action = odr_intdup(p->odr_out, action_no);
2953         
2954         notToKeep = r->u.update->u.esRequest->notToKeep = 
2955             (Z_IUSuppliedRecords *)
2956             odr_malloc(p->odr_out, sizeof(*notToKeep));
2957         notToKeep->num = 1;
2958         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2959             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
2960         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2961             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
2962         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2963         if (recordIdOpaque)
2964         {
2965             notToKeep->elements[0]->u.opaque = 
2966                 odr_create_Odr_oct(p->odr_out,
2967                                    (const unsigned char *) recordIdOpaque,
2968                                    strlen(recordIdOpaque));
2969         }
2970         else if (recordIdNumber)
2971         {
2972             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
2973             
2974             notToKeep->elements[0]->u.number =
2975                 odr_intdup(p->odr_out, atoi(recordIdNumber));
2976         }
2977         else
2978             notToKeep->elements[0]->u.opaque = 0;
2979         notToKeep->elements[0]->supplementalId = 0;
2980         notToKeep->elements[0]->correlationInfo = 0;
2981         notToKeep->elements[0]->record =
2982             z_ext_record(p->odr_out, syntax_oid,
2983                          record_buf, strlen(record_buf));
2984     }
2985     if (0 && apdu)
2986     {
2987        ODR print = odr_createmem(ODR_PRINT);
2988
2989        z_APDU(print, &apdu, 0, 0);
2990        odr_destroy(print);
2991     }
2992     return apdu;
2993 }
2994
2995 ZOOM_API(void)
2996     ZOOM_package_send (ZOOM_package p, const char *type)
2997 {
2998     Z_APDU *apdu = 0;
2999     ZOOM_connection c;
3000     if (!p)
3001         return;
3002     c = p->connection;
3003     odr_reset (p->odr_out);
3004     xfree (p->buf_out);
3005     p->buf_out = 0;
3006     if (!strcmp(type, "itemorder"))
3007     {
3008         apdu = create_es_package (p, VAL_ITEMORDER);
3009         if (apdu)
3010         {
3011             Z_External *r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
3012             
3013             r->direct_reference =
3014                 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
3015                                        VAL_ITEMORDER);
3016             r->descriptor = 0;
3017             r->which = Z_External_itemOrder;
3018             r->indirect_reference = 0;
3019             r->u.itemOrder = encode_item_order (p);
3020
3021             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3022         }
3023     }
3024     else if (!strcmp(type, "create"))  /* create database */
3025     {
3026         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3027                                     0, 0);
3028     }   
3029     else if (!strcmp(type, "drop"))  /* drop database */
3030     {
3031         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3032                                     0, 0);
3033     }
3034     else if (!strcmp(type, "commit"))  /* commit changes */
3035     {
3036         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3037                                     0, 0);
3038     }
3039     else if (!strcmp(type, "update")) /* update record(s) */
3040     {
3041         apdu = create_update_package(p);
3042     }
3043     else if (!strcmp(type, "xmlupdate"))
3044     {
3045         apdu = create_xmlupdate_package(p);
3046     }
3047     if (apdu)
3048     {
3049         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3050         {
3051             char *buf;
3052
3053             ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_PACKAGE);
3054             task->u.package = p;
3055             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3056             p->buf_out = (char *) xmalloc (p->len_out);
3057             memcpy (p->buf_out, buf, p->len_out);
3058             
3059             (p->refcount)++;
3060             if (!c->async)
3061             {
3062                 while (ZOOM_event (1, &c))
3063                     ;
3064             }
3065         }
3066     }
3067 }
3068
3069 ZOOM_API(ZOOM_package)
3070     ZOOM_connection_package (ZOOM_connection c, ZOOM_options options)
3071 {
3072     ZOOM_package p = (ZOOM_package) xmalloc (sizeof(*p));
3073
3074     p->connection = c;
3075     p->odr_out = odr_createmem (ODR_ENCODE);
3076     p->options = ZOOM_options_create_with_parent2 (options, c->options);
3077     p->refcount = 1;
3078     p->buf_out = 0;
3079     p->len_out = 0;
3080     return p;
3081 }
3082
3083 ZOOM_API(void)
3084     ZOOM_package_destroy(ZOOM_package p)
3085 {
3086     if (!p)
3087         return;
3088     (p->refcount)--;
3089     if (p->refcount == 0)
3090     {
3091         odr_destroy (p->odr_out);
3092         xfree (p->buf_out);
3093         
3094         ZOOM_options_destroy (p->options);
3095         xfree (p);
3096     }
3097 }
3098
3099 ZOOM_API(const char *)
3100 ZOOM_package_option_get (ZOOM_package p, const char *key)
3101 {
3102     return ZOOM_options_get (p->options, key);
3103 }
3104
3105
3106 ZOOM_API(void)
3107 ZOOM_package_option_set (ZOOM_package p, const char *key,
3108                               const char *val)
3109 {
3110     ZOOM_options_set (p->options, key, val);
3111 }
3112
3113 static int ZOOM_connection_exec_task (ZOOM_connection c)
3114 {
3115     ZOOM_task task = c->tasks;
3116     zoom_ret ret = zoom_complete;
3117
3118     if (!task)
3119         return 0;
3120     yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3121              c, task->which, task->running);
3122     if (c->error != ZOOM_ERROR_NONE)
3123     {
3124         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3125                 "removing tasks because of error = %d", c, c->error);
3126         ZOOM_connection_remove_tasks (c);
3127         return 0;
3128     }
3129     if (task->running)
3130     {
3131         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3132                  "task already running", c);
3133         return 0;
3134     }
3135     task->running = 1;
3136     ret = zoom_complete;
3137     if (c->cs || task->which == ZOOM_TASK_CONNECT)
3138     {
3139         switch (task->which)
3140         {
3141         case ZOOM_TASK_SEARCH:
3142             if (c->proto == PROTO_HTTP)
3143                 ret = ZOOM_connection_srw_send_search(c);
3144             else
3145                 ret = ZOOM_connection_send_search(c);
3146             break;
3147         case ZOOM_TASK_RETRIEVE:
3148             if (c->proto == PROTO_HTTP)
3149                 ret = ZOOM_connection_srw_send_search(c);
3150             else
3151                 ret = send_present (c);
3152             break;
3153         case ZOOM_TASK_CONNECT:
3154             ret = do_connect(c);
3155             break;
3156         case ZOOM_TASK_SCAN:
3157             ret = send_scan(c);
3158             break;
3159         case ZOOM_TASK_PACKAGE:
3160             ret = send_package(c);
3161             break;
3162         case ZOOM_TASK_SORT:
3163             c->tasks->u.sort.resultset->r_sort_spec = 
3164                 c->tasks->u.sort.q->sort_spec;
3165             ret = send_sort(c, c->tasks->u.sort.resultset);
3166             break;
3167         }
3168     }
3169     else
3170     {
3171         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3172                 "remove tasks because no connection exist", c);
3173         ZOOM_connection_remove_tasks (c);
3174     }
3175     if (ret == zoom_complete)
3176     {
3177         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3178                  "task removed (complete)", c);
3179         ZOOM_connection_remove_task (c);
3180         return 0;
3181     }
3182     yaz_log(log_details, "%p ZOOM_connection_exec_task "
3183             "task pending", c);
3184     return 1;
3185 }
3186
3187 static zoom_ret send_sort_present (ZOOM_connection c)
3188 {
3189     zoom_ret r = zoom_complete;
3190
3191     if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3192         r = send_sort (c, c->tasks->u.search.resultset);
3193     if (r == zoom_complete)
3194         r = send_present (c);
3195     return r;
3196 }
3197
3198 static int es_response (ZOOM_connection c,
3199                         Z_ExtendedServicesResponse *res)
3200 {
3201     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3202         return 0;
3203     if (res->diagnostics && res->num_diagnostics > 0)
3204         response_diag(c, res->diagnostics[0]);
3205     if (res->taskPackage &&
3206         res->taskPackage->which == Z_External_extendedService)
3207     {
3208         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
3209         Odr_oct *id = taskPackage->targetReference;
3210         
3211         if (id)
3212             ZOOM_options_setl (c->tasks->u.package->options,
3213                                "targetReference", (char*) id->buf, id->len);
3214     }
3215     if (res->taskPackage && 
3216         res->taskPackage->which == Z_External_octet)
3217     {
3218         Odr_oct *doc = res->taskPackage->u.octet_aligned;
3219         ZOOM_options_setl (c->tasks->u.package->options,
3220                            "xmlUpdateDoc", (char*) doc->buf, doc->len);
3221     }
3222     return 1;
3223 }
3224
3225 static void interpret_init_diag(ZOOM_connection c,
3226                                 Z_DiagnosticFormat *diag)
3227 {
3228     if (diag->num > 0)
3229     {
3230         Z_DiagnosticFormat_s *ds = diag->elements[0];
3231         if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
3232             response_default_diag(c, ds->u.defaultDiagRec);
3233     }
3234 }
3235
3236
3237 static void interpret_otherinformation_field(ZOOM_connection c,
3238                                              Z_OtherInformation *ui)
3239 {
3240     int i;
3241     for (i = 0; i < ui->num_elements; i++)
3242     {
3243         Z_OtherInformationUnit *unit = ui->list[i];
3244         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
3245             unit->information.externallyDefinedInfo &&
3246             unit->information.externallyDefinedInfo->which ==
3247             Z_External_diag1) 
3248         {
3249             interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
3250         } 
3251     }
3252 }
3253
3254 static void recv_apdu (ZOOM_connection c, Z_APDU *apdu)
3255 {
3256     Z_InitResponse *initrs;
3257     
3258     c->mask = 0;
3259     yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
3260     switch(apdu->which)
3261     {
3262     case Z_APDU_initResponse:
3263         yaz_log(log_api, "%p recv_apd: Received Init response", c);
3264         initrs = apdu->u.initResponse;
3265         ZOOM_connection_option_set(c, "serverImplementationId",
3266                                    initrs->implementationId ?
3267                                    initrs->implementationId : "");
3268         ZOOM_connection_option_set(c, "serverImplementationName",
3269                                    initrs->implementationName ?
3270                                    initrs->implementationName : "");
3271         ZOOM_connection_option_set(c, "serverImplementationVersion",
3272                                    initrs->implementationVersion ?
3273                                    initrs->implementationVersion : "");
3274         /* Set the three old options too, for old applications */
3275         ZOOM_connection_option_set(c, "targetImplementationId",
3276                                    initrs->implementationId ?
3277                                    initrs->implementationId : "");
3278         ZOOM_connection_option_set(c, "targetImplementationName",
3279                                    initrs->implementationName ?
3280                                    initrs->implementationName : "");
3281         ZOOM_connection_option_set(c, "targetImplementationVersion",
3282                                    initrs->implementationVersion ?
3283                                    initrs->implementationVersion : "");
3284         if (!*initrs->result)
3285         {
3286             Z_External *uif = initrs->userInformationField;
3287
3288             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
3289
3290             if (uif && uif->which == Z_External_userInfo1)
3291                 interpret_otherinformation_field(c, uif->u.userInfo1);
3292         }
3293         else
3294         {
3295             char *cookie =
3296                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
3297                                           VAL_COOKIE, 1, 0);
3298             xfree (c->cookie_in);
3299             c->cookie_in = 0;
3300             if (cookie)
3301                 c->cookie_in = xstrdup(cookie);
3302             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
3303                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
3304                 c->support_named_resultsets = 1;
3305             if (c->tasks)
3306             {
3307                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
3308                 ZOOM_connection_remove_task (c);
3309             }
3310             ZOOM_connection_exec_task (c);
3311         }
3312         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
3313         {
3314             NMEM tmpmem = nmem_create();
3315             Z_CharSetandLanguageNegotiation *p =
3316                 yaz_get_charneg_record(initrs->otherInfo);
3317             
3318             if (p)
3319             {
3320                 char *charset = NULL, *lang = NULL;
3321                 int sel;
3322                 
3323                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
3324                 yaz_log(log_details, "%p recv_apdu target accepted: "
3325                         "charset %s, language %s, select %d",
3326                         c,
3327                         charset ? charset : "none", lang ? lang : "none", sel);
3328                 if (charset)
3329                     ZOOM_connection_option_set (c, "negotiation-charset",
3330                                                 charset);
3331                 if (lang)
3332                     ZOOM_connection_option_set (c, "negotiation-lang",
3333                                                 lang);
3334
3335                 ZOOM_connection_option_set (
3336                     c,  "negotiation-charset-in-effect-for-records",
3337                     (sel != 0) ? "1" : "0");
3338                 nmem_destroy(tmpmem);
3339             }
3340         }       
3341         break;
3342     case Z_APDU_searchResponse:
3343         yaz_log(log_api, "%p recv_apdu Search response", c);
3344         handle_search_response (c, apdu->u.searchResponse);
3345         if (send_sort_present (c) == zoom_complete)
3346             ZOOM_connection_remove_task (c);
3347         break;
3348     case Z_APDU_presentResponse:
3349         yaz_log(log_api, "%p recv_apdu Present response", c);
3350         handle_present_response (c, apdu->u.presentResponse);
3351         if (send_present (c) == zoom_complete)
3352             ZOOM_connection_remove_task (c);
3353         break;
3354     case Z_APDU_sortResponse:
3355         yaz_log(log_api, "%p recv_apdu Sort response", c);
3356         sort_response (c, apdu->u.sortResponse);
3357         if (send_present (c) == zoom_complete)
3358             ZOOM_connection_remove_task (c);
3359         break;
3360     case Z_APDU_scanResponse:
3361         yaz_log(log_api, "%p recv_apdu Scan response", c);
3362         scan_response (c, apdu->u.scanResponse);
3363         ZOOM_connection_remove_task (c);
3364         break;
3365     case Z_APDU_extendedServicesResponse:
3366         yaz_log(log_api, "%p recv_apdu Extended Services response", c);
3367         es_response (c, apdu->u.extendedServicesResponse);
3368         ZOOM_connection_remove_task (c);
3369         break;
3370     case Z_APDU_close:
3371         yaz_log(log_api, "%p recv_apdu Close PDU", c);
3372         if (c->reconnect_ok)
3373         {
3374             do_close(c);
3375             c->tasks->running = 0;
3376             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
3377         }
3378         else
3379         {
3380             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3381             do_close(c);
3382         }
3383         break;
3384     default:
3385         yaz_log(log_api, "%p Received unknown PDU", c);
3386         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3387         do_close(c);
3388     }
3389 }
3390
3391 #if HAVE_XML2
3392 static void handle_srw_response(ZOOM_connection c,
3393                                 Z_SRW_searchRetrieveResponse *res)
3394 {
3395     ZOOM_resultset resultset = 0;
3396     int i;
3397     NMEM nmem;
3398     ZOOM_Event event;
3399
3400     if (!c->tasks)
3401         return;
3402
3403     if (c->tasks->which == ZOOM_TASK_SEARCH)
3404         resultset = c->tasks->u.search.resultset;
3405     else if (c->tasks->which == ZOOM_TASK_RETRIEVE)
3406         resultset = c->tasks->u.retrieve.resultset;
3407     else
3408         return ;
3409
3410     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
3411     ZOOM_connection_put_event(c, event);
3412
3413     resultset->size = 0;
3414
3415     yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
3416     
3417     if (res->numberOfRecords)
3418         resultset->size = *res->numberOfRecords;
3419
3420     for (i = 0; i<res->num_records; i++)
3421     {
3422         int pos;
3423
3424         Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
3425             odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
3426
3427         if (res->records[i].recordPosition && 
3428             *res->records[i].recordPosition > 0)
3429             pos = *res->records[i].recordPosition - 1;
3430         else
3431             pos = resultset->start + i;
3432         
3433         npr->databaseName = 0;
3434         npr->which = Z_NamePlusRecord_databaseRecord;
3435         npr->u.databaseRecord = (Z_External *)
3436             odr_malloc(c->odr_in, sizeof(Z_External));
3437         npr->u.databaseRecord->descriptor = 0;
3438         npr->u.databaseRecord->direct_reference =
3439             yaz_oidval_to_z3950oid(c->odr_in, CLASS_RECSYN, VAL_TEXT_XML);
3440         npr->u.databaseRecord->which = Z_External_octet;
3441
3442         npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
3443             odr_malloc(c->odr_in, sizeof(Odr_oct));
3444         npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
3445             res->records[i].recordData_buf;
3446         npr->u.databaseRecord->u.octet_aligned->len = 
3447             npr->u.databaseRecord->u.octet_aligned->size = 
3448             res->records[i].recordData_len;
3449         record_cache_add (resultset, npr, pos);
3450     }
3451     if (res->num_diagnostics > 0)
3452     {
3453         const char *uri = res->diagnostics[0].uri;
3454         if (uri)
3455         {
3456             int code = 0;       
3457             const char *cp;
3458             if ((cp = strrchr(uri, '/')))
3459                 code = atoi(cp+1);
3460             set_dset_error(c, code, uri,
3461                            res->diagnostics[0].details, 0);
3462         }
3463     }
3464     nmem = odr_extract_mem(c->odr_in);
3465     nmem_transfer(resultset->odr->mem, nmem);
3466     nmem_destroy(nmem);
3467 }
3468 #endif
3469
3470 #if HAVE_XML2
3471 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
3472 {
3473     int ret = -1;
3474     const char *content_type = z_HTTP_header_lookup(hres->headers,
3475                                                     "Content-Type");
3476     const char *connection_head = z_HTTP_header_lookup(hres->headers,
3477                                                        "Connection");
3478     c->mask = 0;
3479     yaz_log(log_details, "%p handle_http", c);
3480
3481     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3482     {
3483         Z_SOAP *soap_package = 0;
3484         ODR o = c->odr_in;
3485         Z_SOAP_Handler soap_handlers[2] = {
3486             {"http://www.loc.gov/zing/srw/", 0,
3487              (Z_SOAP_fun) yaz_srw_codec},
3488             {0, 0, 0}
3489         };
3490         ret = z_soap_codec(o, &soap_package,
3491                            &hres->content_buf, &hres->content_len,
3492                            soap_handlers);
3493         if (!ret && soap_package->which == Z_SOAP_generic &&
3494             soap_package->u.generic->no == 0)
3495         {
3496             Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
3497             if (sr->which == Z_SRW_searchRetrieve_response)
3498                 handle_srw_response(c, sr->u.response);
3499             else
3500                 ret = -1;
3501         }
3502         else if (!ret && (soap_package->which == Z_SOAP_fault
3503                           || soap_package->which == Z_SOAP_error))
3504         {
3505             set_HTTP_error(c, hres->code,
3506                            soap_package->u.fault->fault_code,
3507                            soap_package->u.fault->fault_string);
3508         }
3509         else
3510             ret = -1;
3511     }
3512     if (ret)
3513     {
3514         if (hres->code != 200)
3515             set_HTTP_error(c, hres->code, 0, 0);
3516         else
3517             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3518         do_close (c);
3519     }
3520     ZOOM_connection_remove_task(c);
3521     if (!strcmp(hres->version, "1.0"))
3522     {
3523         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3524         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3525             do_close(c);
3526     }
3527     else 
3528     {
3529         /* HTTP 1.1: only if no close we stay alive .. */
3530         if (connection_head && !strcmp(connection_head, "close"))
3531             do_close(c);
3532     }
3533 }
3534 #endif
3535
3536 static int do_read (ZOOM_connection c)
3537 {
3538     int r, more;
3539     ZOOM_Event event;
3540     
3541     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
3542     ZOOM_connection_put_event (c, event);
3543     
3544     r = cs_get (c->cs, &c->buf_in, &c->len_in);
3545     more = cs_more(c->cs);
3546     yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
3547     if (r == 1)
3548         return 0;
3549     if (r <= 0)
3550     {
3551         if (c->reconnect_ok)
3552         {
3553             do_close (c);
3554             c->reconnect_ok = 0;
3555             yaz_log(log_details, "%p do_read reconnect read", c);
3556             c->tasks->running = 0;
3557             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
3558         }
3559         else
3560         {
3561             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3562             do_close (c);
3563         }
3564     }
3565     else
3566     {
3567         Z_GDU *gdu;
3568         ZOOM_Event event;
3569
3570         odr_reset (c->odr_in);
3571         odr_setbuf (c->odr_in, c->buf_in, r, 0);
3572         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
3573         ZOOM_connection_put_event (c, event);
3574
3575         if (!z_GDU (c->odr_in, &gdu, 0, 0))
3576         {
3577             int x;
3578             int err = odr_geterrorx(c->odr_in, &x);
3579             char msg[60];
3580             const char *element = odr_getelement(c->odr_in);
3581             sprintf (msg, "ODR code %d:%d element=%-20s",
3582                      err, x, element ? element : "<unknown>");
3583             set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
3584             do_close (c);
3585         }
3586         else if (gdu->which == Z_GDU_Z3950)
3587             recv_apdu (c, gdu->u.z3950);
3588         else if (gdu->which == Z_GDU_HTTP_Response)
3589         {
3590 #if HAVE_XML2
3591             handle_http (c, gdu->u.HTTP_Response);
3592 #else
3593             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3594             do_close (c);
3595 #endif
3596         }
3597         c->reconnect_ok = 0;
3598     }
3599     return 1;
3600 }
3601
3602 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
3603 {
3604     int r;
3605     ZOOM_Event event;
3606     
3607     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
3608     ZOOM_connection_put_event (c, event);
3609
3610     yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
3611     if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
3612     {
3613         yaz_log(log_details, "%p do_write_ex write failed", c);
3614         if (c->reconnect_ok)
3615         {
3616             do_close (c);
3617             c->reconnect_ok = 0;
3618             yaz_log(log_details, "%p do_write_ex reconnect write", c);
3619             c->tasks->running = 0;
3620             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
3621             return zoom_pending;
3622         }
3623         if (c->state == STATE_CONNECTING)
3624             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
3625         else
3626             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3627         do_close (c);
3628         return zoom_complete;
3629     }
3630     else if (r == 1)
3631     {    
3632         c->mask = ZOOM_SELECT_EXCEPT;
3633         if (c->cs->io_pending & CS_WANT_WRITE)
3634             c->mask += ZOOM_SELECT_WRITE;
3635         if (c->cs->io_pending & CS_WANT_READ)
3636             c->mask += ZOOM_SELECT_READ;
3637         yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
3638                 c, c->mask);
3639     }
3640     else
3641     {
3642         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
3643         yaz_log(log_details, "%p do_write_ex write complete mask=%d",
3644                 c, c->mask);
3645     }
3646     return zoom_pending;
3647 }
3648
3649 static zoom_ret do_write(ZOOM_connection c)
3650 {
3651     return do_write_ex (c, c->buf_out, c->len_out);
3652 }
3653
3654
3655 ZOOM_API(const char *)
3656 ZOOM_connection_option_get (ZOOM_connection c, const char *key)
3657 {