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