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