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