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