Moved prototype of ZOOM_connection_remove_tasks further to the "top" of
[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.113 2007-02-21 09:19:26 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 #define TASK_FIX 1
31
32 static int log_api = 0;
33 static int log_details = 0;
34
35 typedef enum {
36     zoom_pending,
37     zoom_complete
38 } zoom_ret;
39
40 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c);
41 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out);
42 static char *cql2pqf(ZOOM_connection c, const char *cql);
43
44
45 /*
46  * This wrapper is just for logging failed lookups.  It would be nicer
47  * if it could cause failure when a lookup fails, but that's hard.
48  */
49 static Odr_oid *zoom_yaz_str_to_z3950oid(ZOOM_connection c,
50                                          int oid_class, const char *str) {
51     Odr_oid *res = yaz_str_to_z3950oid(c->odr_out, oid_class, str);
52     if (res == 0)
53         yaz_log(YLOG_WARN, "%p OID lookup (%d, '%s') failed",
54                 c, (int) oid_class, str);
55     return res;
56 }
57
58
59 static void initlog(void)
60 {
61     static int log_level_initialized = 0;
62     if (!log_level_initialized)
63     {
64         log_api = yaz_log_module_level("zoom");
65         log_details = yaz_log_module_level("zoomdetails");
66         log_level_initialized = 1;
67     }
68 }
69
70 static ZOOM_Event ZOOM_Event_create(int kind)
71 {
72     ZOOM_Event event = (ZOOM_Event) xmalloc(sizeof(*event));
73     event->kind = kind;
74     event->next = 0;
75     event->prev = 0;
76     yaz_log(log_details, "ZOOM_Event_create(kind=%d)", kind);
77     return event;
78 }
79
80 static void ZOOM_Event_destroy(ZOOM_Event event)
81 {
82     xfree(event);
83 }
84
85 static void ZOOM_connection_put_event(ZOOM_connection c, ZOOM_Event event)
86 {
87     if (c->m_queue_back)
88     {
89         c->m_queue_back->prev = event;
90         assert(c->m_queue_front);
91     }
92     else
93     {
94         assert(!c->m_queue_front);
95         c->m_queue_front = event;
96     }
97     event->next = c->m_queue_back;
98     event->prev = 0;
99     c->m_queue_back = event;
100 }
101
102 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
103 {
104     ZOOM_Event event = c->m_queue_front;
105     if (!event)
106     {
107         c->last_event = ZOOM_EVENT_NONE;
108         return 0;
109     }
110     assert(c->m_queue_back);
111     c->m_queue_front = event->prev;
112     if (c->m_queue_front)
113     {
114         assert(c->m_queue_back);
115         c->m_queue_front->next = 0;
116     }
117     else
118         c->m_queue_back = 0;
119     c->last_event = event->kind;
120     return event;
121 }
122
123 ZOOM_API(int) ZOOM_connection_peek_event(ZOOM_connection c)
124 {
125     ZOOM_Event event = c->m_queue_front;
126
127     return event ? event->kind : ZOOM_EVENT_NONE;
128 }
129
130 void ZOOM_connection_remove_tasks(ZOOM_connection c);
131
132 static void set_dset_error(ZOOM_connection c, int error,
133                            const char *dset,
134                            const char *addinfo, const char *addinfo2)
135 {
136     char *cp;
137
138     xfree(c->addinfo);
139     c->addinfo = 0;
140     c->error = error;
141     if (!c->diagset || strcmp(dset, c->diagset))
142     {
143         xfree(c->diagset);
144         c->diagset = xstrdup(dset);
145         /* remove integer part from SRW diagset .. */
146         if ((cp = strrchr(c->diagset, '/')))
147             *cp = '\0';
148     }
149     if (addinfo && addinfo2)
150     {
151         c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
152         strcpy(c->addinfo, addinfo);
153         strcat(c->addinfo, addinfo2);
154     }
155     else if (addinfo)
156         c->addinfo = xstrdup(addinfo);
157     if (error != ZOOM_ERROR_NONE)
158     {
159         yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
160                 c, c->host_port ? c->host_port : "<>", dset, error,
161                 addinfo ? addinfo : "",
162                 addinfo2 ? addinfo2 : "");
163 #if TASK_FIX
164         ZOOM_connection_remove_tasks(c);
165 #endif
166     }
167 }
168
169 #if YAZ_HAVE_XML2
170 static void set_HTTP_error(ZOOM_connection c, int error,
171                            const char *addinfo, const char *addinfo2)
172 {
173     set_dset_error(c, error, "HTTP", addinfo, addinfo2);
174 }
175 #endif
176
177
178 static void set_ZOOM_error(ZOOM_connection c, int error,
179                            const char *addinfo)
180 {
181     set_dset_error(c, error, "ZOOM", addinfo, 0);
182 }
183
184 static void clear_error(ZOOM_connection c)
185 {
186     /*
187      * If an error is tied to an operation then it's ok to clear: for
188      * example, a diagnostic returned from a search is cleared by a
189      * subsequent search.  However, problems such as Connection Lost
190      * or Init Refused are not cleared, because they are not
191      * recoverable: doing another search doesn't help.
192      */
193     switch (c->error)
194     {
195     case ZOOM_ERROR_CONNECT:
196     case ZOOM_ERROR_MEMORY:
197     case ZOOM_ERROR_DECODE:
198     case ZOOM_ERROR_CONNECTION_LOST:
199     case ZOOM_ERROR_INIT:
200     case ZOOM_ERROR_INTERNAL:
201     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
202         break;
203     default:
204         set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
205     }
206 }
207
208 void ZOOM_connection_show_task(ZOOM_task task)
209 {
210     switch(task->which)
211     {
212     case ZOOM_TASK_SEARCH:
213         yaz_log(YLOG_LOG, "search p=%p", task);
214         break;
215     case ZOOM_TASK_RETRIEVE:
216         yaz_log(YLOG_LOG, "retrieve p=%p", task);
217         break;
218     case ZOOM_TASK_CONNECT:
219         yaz_log(YLOG_LOG, "connect p=%p", task);
220         break;
221     case ZOOM_TASK_SCAN:
222         yaz_log(YLOG_LOG, "scant p=%p", task);
223         break;
224     }
225 }
226
227 void ZOOM_connection_show_tasks(ZOOM_connection c)
228 {
229     ZOOM_task task;
230     yaz_log(YLOG_LOG, "connection p=%p tasks", c);
231     for (task = c->tasks; task; task = task->next)
232         ZOOM_connection_show_task(task);
233 }
234
235 ZOOM_task ZOOM_connection_add_task(ZOOM_connection c, int which)
236 {
237     ZOOM_task *taskp = &c->tasks;
238     while (*taskp)
239         taskp = &(*taskp)->next;
240     *taskp = (ZOOM_task) xmalloc(sizeof(**taskp));
241     (*taskp)->running = 0;
242     (*taskp)->which = which;
243     (*taskp)->next = 0;
244     clear_error(c);
245     return *taskp;
246 }
247
248 ZOOM_API(int) ZOOM_connection_is_idle(ZOOM_connection c)
249 {
250     return c->tasks ? 0 : 1;
251 }
252
253 ZOOM_task ZOOM_connection_insert_task(ZOOM_connection c, int which)
254 {
255     ZOOM_task task = (ZOOM_task) xmalloc(sizeof(*task));
256
257     task->next = c->tasks;
258     c->tasks = task;
259
260     task->running = 0;
261     task->which = which;
262     clear_error(c);
263     return task;
264 }
265
266 void ZOOM_connection_remove_task(ZOOM_connection c)
267 {
268     ZOOM_task task = c->tasks;
269
270     if (task)
271     {
272         c->tasks = task->next;
273         switch (task->which)
274         {
275         case ZOOM_TASK_SEARCH:
276             ZOOM_resultset_destroy(task->u.search.resultset);
277             xfree(task->u.search.syntax);
278             xfree(task->u.search.elementSetName);
279             break;
280         case ZOOM_TASK_RETRIEVE:
281             ZOOM_resultset_destroy(task->u.retrieve.resultset);
282             xfree(task->u.retrieve.syntax);
283             xfree(task->u.retrieve.elementSetName);
284             break;
285         case ZOOM_TASK_CONNECT:
286             break;
287         case ZOOM_TASK_SCAN:
288             ZOOM_scanset_destroy(task->u.scan.scan);
289             break;
290         case ZOOM_TASK_PACKAGE:
291             ZOOM_package_destroy(task->u.package);
292             break;
293         case ZOOM_TASK_SORT:
294             ZOOM_resultset_destroy(task->u.sort.resultset);
295             ZOOM_query_destroy(task->u.sort.q);
296             break;
297         default:
298             assert(0);
299         }
300         xfree(task);
301
302         if (!c->tasks)
303         {
304             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
305             ZOOM_connection_put_event(c, event);
306         }
307     }
308 }
309
310 static int ZOOM_connection_exec_task(ZOOM_connection c);
311
312 void ZOOM_connection_remove_tasks(ZOOM_connection c)
313 {
314     while (c->tasks)
315         ZOOM_connection_remove_task(c);
316 }
317
318 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
319                                        const char *syntax,
320                                        const char *elementSetName);
321
322 ZOOM_API(ZOOM_connection)
323     ZOOM_connection_create(ZOOM_options options)
324 {
325     ZOOM_connection c = (ZOOM_connection) xmalloc(sizeof(*c));
326
327     initlog();
328
329     yaz_log(log_api, "%p ZOOM_connection_create", c);
330
331     c->proto = PROTO_Z3950;
332     c->cs = 0;
333     ZOOM_connection_set_mask(c, 0);
334     c->reconnect_ok = 0;
335     c->state = STATE_IDLE;
336     c->addinfo = 0;
337     c->diagset = 0;
338     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
339     c->buf_in = 0;
340     c->len_in = 0;
341     c->buf_out = 0;
342     c->len_out = 0;
343     c->resultsets = 0;
344
345     c->options = ZOOM_options_create_with_parent(options);
346
347     c->host_port = 0;
348     c->path = 0;
349     c->proxy = 0;
350     
351     c->charset = c->lang = 0;
352
353     c->cookie_out = 0;
354     c->cookie_in = 0;
355     c->client_IP = 0;
356     c->tasks = 0;
357
358     c->odr_in = odr_createmem(ODR_DECODE);
359     c->odr_out = odr_createmem(ODR_ENCODE);
360
361     c->async = 0;
362     c->support_named_resultsets = 0;
363     c->last_event = ZOOM_EVENT_NONE;
364
365     c->m_queue_front = 0;
366     c->m_queue_back = 0;
367     return c;
368 }
369
370
371 /* set database names. Take local databases (if set); otherwise
372    take databases given in ZURL (if set); otherwise use Default */
373 static char **set_DatabaseNames(ZOOM_connection con, ZOOM_options options,
374                                 int *num, ODR odr)
375 {
376     char **databaseNames;
377     const char *cp = ZOOM_options_get(options, "databaseName");
378     
379     if ((!cp || !*cp) && con->host_port)
380     {
381         if (strncmp(con->host_port, "unix:", 5) == 0)
382             cp = strchr(con->host_port+5, ':');
383         else
384             cp = strchr(con->host_port, '/');
385         if (cp)
386             cp++;
387     }
388     if (!cp)
389         cp = "Default";
390     nmem_strsplit(odr->mem, "+", cp,  &databaseNames, num);
391     return databaseNames;
392 }
393
394 ZOOM_API(ZOOM_connection)
395     ZOOM_connection_new(const char *host, int portnum)
396 {
397     ZOOM_connection c = ZOOM_connection_create(0);
398
399     ZOOM_connection_connect(c, host, portnum);
400     return c;
401 }
402
403 static zoom_sru_mode get_sru_mode_from_string(const char *s)
404 {
405     if (!s || !*s)
406         return zoom_sru_soap;
407     if (!yaz_matchstr(s, "soap"))
408         return zoom_sru_soap;
409     else if (!yaz_matchstr(s, "get"))
410         return zoom_sru_get;
411     else if (!yaz_matchstr(s, "post"))
412         return zoom_sru_post;
413     return zoom_sru_error;
414 }
415
416 ZOOM_API(void)
417     ZOOM_connection_connect(ZOOM_connection c,
418                             const char *host, int portnum)
419 {
420     const char *val;
421     ZOOM_task task;
422
423     initlog();
424
425     yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
426             c, host, portnum);
427
428     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
429     ZOOM_connection_remove_tasks(c);
430
431     if (c->cs)
432     {
433         yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
434         c->reconnect_ok = 1;
435         return;
436     }
437     yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
438     xfree(c->proxy);
439     val = ZOOM_options_get(c->options, "proxy");
440     if (val && *val)
441     {
442         yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
443         c->proxy = xstrdup(val);
444     }
445     else
446         c->proxy = 0;
447
448     xfree(c->charset);
449     val = ZOOM_options_get(c->options, "charset");
450     if (val && *val)
451     {
452         yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
453         c->charset = xstrdup(val);
454     }
455     else
456         c->charset = 0;
457
458     xfree(c->lang);
459     val = ZOOM_options_get(c->options, "lang");
460     if (val && *val)
461     {
462         yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
463         c->lang = xstrdup(val);
464     }
465     else
466         c->lang = 0;
467
468     xfree(c->host_port);
469     if (portnum)
470     {
471         char hostn[128];
472         sprintf(hostn, "%.80s:%d", host, portnum);
473         c->host_port = xstrdup(hostn);
474     }
475     else
476         c->host_port = xstrdup(host);
477
478     {
479         /*
480          * If the "<scheme>:" part of the host string is preceded by one
481          * or more comma-separated <name>=<value> pairs, these are taken
482          * to be options to be set on the connection object.  Among other
483          * applications, this facility can be used to embed authentication
484          * in a host string:
485          *          user=admin,password=secret,tcp:localhost:9999
486          */
487         char *remainder = c->host_port;
488         char *pcolon = strchr(remainder, ':');
489         char *pcomma;
490         char *pequals;
491         while ((pcomma = strchr(remainder, ',')) != 0 &&
492                (pcolon == 0 || pcomma < pcolon)) {
493             *pcomma = '\0';
494             if ((pequals = strchr(remainder, '=')) != 0) {
495                 *pequals = '\0';
496                 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
497                 ZOOM_connection_option_set(c, remainder, pequals+1);
498             }
499             remainder = pcomma+1;
500         }
501
502         if (remainder != c->host_port) {
503             xfree(c->host_port);
504             c->host_port = xstrdup(remainder);
505             /*printf("# reset hp='%s'\n", remainder);*/
506         }
507     }
508
509     val = ZOOM_options_get(c->options, "sru");
510     c->sru_mode = get_sru_mode_from_string(val);
511
512     ZOOM_options_set(c->options, "host", c->host_port);
513
514     val = ZOOM_options_get(c->options, "cookie");
515     if (val && *val)
516     { 
517         yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
518         c->cookie_out = xstrdup(val);
519     }
520
521     val = ZOOM_options_get(c->options, "clientIP");
522     if (val && *val)
523     {
524         yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
525                 c, val);
526         c->client_IP = xstrdup(val);
527     }
528
529     c->async = ZOOM_options_get_bool(c->options, "async", 0);
530     yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
531  
532     task = ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
533
534     if (!c->async)
535     {
536         while (ZOOM_event(1, &c))
537             ;
538     }
539 }
540
541 ZOOM_API(ZOOM_query)
542     ZOOM_query_create(void)
543 {
544     ZOOM_query s = (ZOOM_query) xmalloc(sizeof(*s));
545
546     yaz_log(log_details, "%p ZOOM_query_create", s);
547     s->refcount = 1;
548     s->z_query = 0;
549     s->sort_spec = 0;
550     s->odr = odr_createmem(ODR_ENCODE);
551     s->query_string = 0;
552
553     return s;
554 }
555
556 ZOOM_API(void)
557     ZOOM_query_destroy(ZOOM_query s)
558 {
559     if (!s)
560         return;
561
562     (s->refcount)--;
563     yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
564     if (s->refcount == 0)
565     {
566         odr_destroy(s->odr);
567         xfree(s);
568     }
569 }
570
571 ZOOM_API(int)
572     ZOOM_query_prefix(ZOOM_query s, const char *str)
573 {
574     s->query_string = odr_strdup(s->odr, str);
575     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
576     s->z_query->which = Z_Query_type_1;
577     s->z_query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
578     if (!s->z_query->u.type_1)
579     {
580         yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
581         s->z_query = 0;
582         return -1;
583     }
584     yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
585     return 0;
586 }
587
588 ZOOM_API(int)
589     ZOOM_query_cql(ZOOM_query s, const char *str)
590 {
591     Z_External *ext;
592
593     s->query_string = odr_strdup(s->odr, str);
594
595     ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
596     ext->direct_reference = odr_getoidbystr(s->odr, "1.2.840.10003.16.2");
597     ext->indirect_reference = 0;
598     ext->descriptor = 0;
599     ext->which = Z_External_CQL;
600     ext->u.cql = s->query_string;
601     
602     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
603     s->z_query->which = Z_Query_type_104;
604     s->z_query->u.type_104 =  ext;
605
606     yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
607
608     return 0;
609 }
610
611 /*
612  * Translate the CQL string client-side into RPN which is passed to
613  * the server.  This is useful for server's that don't themselves
614  * support CQL, for which ZOOM_query_cql() is useless.  `conn' is used
615  * only as a place to stash diagnostics if compilation fails; if this
616  * information is not needed, a null pointer may be used.
617  */
618 ZOOM_API(int)
619     ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
620 {
621     char *rpn;
622     int ret;
623     ZOOM_connection freeme = 0;
624
625     yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
626     if (conn == 0)
627         conn = freeme = ZOOM_connection_create(0);
628
629     rpn = cql2pqf(conn, str);
630     if (freeme != 0)
631         ZOOM_connection_destroy(freeme);
632     if (rpn == 0)
633         return -1;
634
635     ret = ZOOM_query_prefix(s, rpn);
636     xfree(rpn);
637     return ret;
638 }
639
640 /*
641  * Analogous in every way to ZOOM_query_cql2rpn(), except that there
642  * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
643  * to the server, as the YAZ GFS doesn't know how to handle this.
644  */
645 ZOOM_API(int)
646     ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, const char *config,
647                        int *ccl_error, const char **error_string,
648                        int *error_pos)
649 {
650     int ret;
651     struct ccl_rpn_node *rpn;
652     CCL_bibset bibset = ccl_qual_mk();
653
654     if (config)
655         ccl_qual_buf(bibset, config);
656
657     rpn = ccl_find_str(bibset, str, ccl_error, error_pos);
658     if (!rpn)
659     {
660         *error_string = ccl_err_msg(*ccl_error);
661         ret = -1;
662     }
663     else
664     {
665         WRBUF wr = wrbuf_alloc();
666         ccl_pquery(wr, rpn);
667         ccl_rpn_delete(rpn);
668         ret = ZOOM_query_prefix(s, wrbuf_buf(wr));
669         wrbuf_free(wr, 1);
670     }
671     ccl_qual_rm(&bibset);
672     return ret;
673 }
674
675 ZOOM_API(int)
676     ZOOM_query_sortby(ZOOM_query s, const char *criteria)
677 {
678     s->sort_spec = yaz_sort_spec(s->odr, criteria);
679     if (!s->sort_spec)
680     {
681         yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
682                 s, criteria);
683         return -1;
684     }
685     yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
686     return 0;
687 }
688
689 static zoom_ret do_write(ZOOM_connection c);
690
691 ZOOM_API(void)
692     ZOOM_connection_destroy(ZOOM_connection c)
693 {
694     ZOOM_resultset r;
695     if (!c)
696         return;
697     yaz_log(log_api, "%p ZOOM_connection_destroy", c);
698     if (c->cs)
699         cs_close(c->cs);
700     for (r = c->resultsets; r; r = r->next)
701         r->connection = 0;
702
703     xfree(c->buf_in);
704     xfree(c->addinfo);
705     xfree(c->diagset);
706     odr_destroy(c->odr_in);
707     odr_destroy(c->odr_out);
708     ZOOM_options_destroy(c->options);
709     ZOOM_connection_remove_tasks(c);
710     xfree(c->host_port);
711     xfree(c->path);
712     xfree(c->proxy);
713     xfree(c->charset);
714     xfree(c->lang);
715     xfree(c->cookie_out);
716     xfree(c->cookie_in);
717     xfree(c->client_IP);
718     xfree(c);
719 }
720
721 void ZOOM_resultset_addref(ZOOM_resultset r)
722 {
723     if (r)
724     {
725         (r->refcount)++;
726         yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
727                 r, r->refcount);
728     }
729 }
730
731 ZOOM_resultset ZOOM_resultset_create(void)
732 {
733     int i;
734     ZOOM_resultset r = (ZOOM_resultset) xmalloc(sizeof(*r));
735
736     initlog();
737
738     yaz_log(log_details, "%p ZOOM_resultset_create", r);
739     r->refcount = 1;
740     r->size = 0;
741     r->odr = odr_createmem(ODR_ENCODE);
742     r->piggyback = 1;
743     r->setname = 0;
744     r->schema = 0;
745     r->step = 0;
746     for (i = 0; i<RECORD_HASH_SIZE; i++)
747         r->record_hash[i] = 0;
748     r->r_sort_spec = 0;
749     r->query = 0;
750     r->connection = 0;
751     r->next = 0;
752     r->databaseNames = 0;
753     r->num_databaseNames = 0;
754     return r;
755 }
756
757 ZOOM_API(ZOOM_resultset)
758     ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
759 {
760     ZOOM_resultset r;
761     ZOOM_query s = ZOOM_query_create();
762
763     ZOOM_query_prefix(s, q);
764
765     r = ZOOM_connection_search(c, s);
766     ZOOM_query_destroy(s);
767     return r;
768 }
769
770 ZOOM_API(ZOOM_resultset)
771     ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
772 {
773     ZOOM_resultset r = ZOOM_resultset_create();
774     ZOOM_task task;
775     const char *cp;
776     int start, count;
777     const char *syntax, *elementSetName;
778
779     yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
780     r->r_sort_spec = q->sort_spec;
781     r->query = q;
782
783     r->options = ZOOM_options_create_with_parent(c->options);
784
785     start = ZOOM_options_get_int(r->options, "start", 0);
786     count = ZOOM_options_get_int(r->options, "count", 0);
787     {
788         /* If "presentChunk" is defined use that; otherwise "step" */
789         const char *cp = ZOOM_options_get(r->options, "presentChunk");
790         r->step = ZOOM_options_get_int(r->options,
791                                        (cp != 0 ? "presentChunk": "step"), 0);
792     }
793     r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
794     cp = ZOOM_options_get(r->options, "setname");
795     if (cp)
796         r->setname = xstrdup(cp);
797     cp = ZOOM_options_get(r->options, "schema");
798     if (cp)
799         r->schema = xstrdup(cp);
800
801     r->databaseNames = set_DatabaseNames(c, c->options, &r->num_databaseNames,
802                                          r->odr);
803     
804     r->connection = c;
805
806     r->next = c->resultsets;
807     c->resultsets = r;
808
809     if (c->host_port && c->proto == PROTO_HTTP)
810     {
811         if (!c->cs)
812         {
813             yaz_log(log_details, "ZOOM_connection_search: no comstack");
814             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
815         }
816         else
817         {
818             yaz_log(log_details, "ZOOM_connection_search: reconnect");
819             c->reconnect_ok = 1;
820         }
821     }
822
823     task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
824     task->u.search.resultset = r;
825     task->u.search.start = start;
826     task->u.search.count = count;
827
828     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
829     task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
830     elementSetName = ZOOM_options_get(r->options, "elementSetName");
831     task->u.search.elementSetName = elementSetName 
832         ? xstrdup(elementSetName) : 0;
833    
834     ZOOM_resultset_addref(r);
835
836     (q->refcount)++;
837
838     if (!c->async)
839     {
840         while (ZOOM_event(1, &c))
841             ;
842     }
843     return r;
844 }
845
846 /*
847  * This is the old result-set sorting API, which is maintained only
848  * for the sake of binary compatibility.  There is no reason ever to
849  * use this rather than ZOOM_resultset_sort1().
850  */
851 ZOOM_API(void)
852     ZOOM_resultset_sort(ZOOM_resultset r,
853                         const char *sort_type, const char *sort_spec)
854 {
855     (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
856 }
857
858 ZOOM_API(int)
859     ZOOM_resultset_sort1(ZOOM_resultset r,
860                          const char *sort_type, const char *sort_spec)
861 {
862     ZOOM_connection c = r->connection;
863     ZOOM_task task;
864     ZOOM_query newq;
865
866     newq = ZOOM_query_create();
867     if (ZOOM_query_sortby(newq, sort_spec) < 0)
868         return -1;
869
870     yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
871             r, r, sort_type, sort_spec);
872     if (!c)
873         return 0;
874
875     if (c->host_port && c->proto == PROTO_HTTP)
876     {
877         if (!c->cs)
878         {
879             yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
880             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
881         }
882         else
883         {
884             yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
885                     r);
886             c->reconnect_ok = 1;
887         }
888     }
889     
890     ZOOM_resultset_cache_reset(r);
891     task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
892     task->u.sort.resultset = r;
893     task->u.sort.q = newq;
894
895     ZOOM_resultset_addref(r);  
896
897     if (!c->async)
898     {
899         while (ZOOM_event(1, &c))
900             ;
901     }
902
903     return 0;
904 }
905
906 ZOOM_API(void)
907     ZOOM_resultset_cache_reset(ZOOM_resultset r)
908 {
909     int i;
910     for (i = 0; i<RECORD_HASH_SIZE; i++)
911     {
912         ZOOM_record_cache rc;
913         for (rc = r->record_hash[i]; rc; rc = rc->next)
914         {
915             if (rc->rec.wrbuf_marc)
916                 wrbuf_free(rc->rec.wrbuf_marc, 1);
917             if (rc->rec.wrbuf_iconv)
918                 wrbuf_free(rc->rec.wrbuf_iconv, 1);
919             if (rc->rec.wrbuf_opac)
920                 wrbuf_free(rc->rec.wrbuf_opac, 1);
921         }
922         r->record_hash[i] = 0;
923     }
924 }
925
926 ZOOM_API(void)
927     ZOOM_resultset_destroy(ZOOM_resultset r)
928 {
929     if (!r)
930         return;
931     (r->refcount)--;
932     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
933             r, r, r->refcount);
934     if (r->refcount == 0)
935     {
936         ZOOM_resultset_cache_reset(r);
937
938         if (r->connection)
939         {
940             /* remove ourselves from the resultsets in connection */
941             ZOOM_resultset *rp = &r->connection->resultsets;
942             while (1)
943             {
944                 assert(*rp);   /* we must be in this list!! */
945                 if (*rp == r)
946                 {   /* OK, we're here - take us out of it */
947                     *rp = (*rp)->next;
948                     break;
949                 }
950                 rp = &(*rp)->next;
951             }
952         }
953         ZOOM_query_destroy(r->query);
954         ZOOM_options_destroy(r->options);
955         odr_destroy(r->odr);
956         xfree(r->setname);
957         xfree(r->schema);
958         xfree(r);
959     }
960 }
961
962 ZOOM_API(size_t)
963     ZOOM_resultset_size(ZOOM_resultset r)
964 {
965     yaz_log(log_details, "ZOOM_resultset_size r=%p count=%d",
966             r, r->size);
967     return r->size;
968 }
969
970 static void do_close(ZOOM_connection c)
971 {
972     if (c->cs)
973         cs_close(c->cs);
974     c->cs = 0;
975     ZOOM_connection_set_mask(c, 0);
976     c->state = STATE_IDLE;
977 }
978
979 static int ZOOM_test_reconnect(ZOOM_connection c)
980 {
981     if (!c->reconnect_ok)
982         return 0;
983     do_close(c);
984     c->reconnect_ok = 0;
985     c->tasks->running = 0;
986     ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
987     return 1;
988 }
989
990 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
991                                     int force_sync, int start, int count)
992 {
993     ZOOM_task task;
994     ZOOM_connection c;
995     const char *cp;
996     const char *syntax, *elementSetName;
997
998     if (!r)
999         return;
1000     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1001             " count=%d", r, force_sync, start, count);
1002     c = r->connection;
1003     if (!c)
1004         return;
1005
1006     if (c->host_port && c->proto == PROTO_HTTP)
1007     {
1008         if (!c->cs)
1009         {
1010             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1011             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1012         }
1013         else
1014         {
1015             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1016                     "reconnect", r);
1017             c->reconnect_ok = 1;
1018         }
1019     }
1020     task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1021     task->u.retrieve.resultset = r;
1022     task->u.retrieve.start = start;
1023     task->u.retrieve.count = count;
1024
1025     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1026     task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1027     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1028     task->u.retrieve.elementSetName = elementSetName 
1029         ? xstrdup(elementSetName) : 0;
1030
1031     cp = ZOOM_options_get(r->options, "schema");
1032     if (cp)
1033     {
1034         if (!r->schema || strcmp(r->schema, cp))
1035         {
1036             xfree(r->schema);
1037             r->schema = xstrdup(cp);
1038         }
1039     }
1040
1041     ZOOM_resultset_addref(r);
1042
1043     if (!r->connection->async || force_sync)
1044         while (r->connection && ZOOM_event(1, &r->connection))
1045             ;
1046 }
1047
1048 ZOOM_API(void)
1049     ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1050                            size_t start, size_t count)
1051 {
1052     int force_present = 0;
1053
1054     if (!r)
1055         return ;
1056     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1057             r, r, (long) start, (long) count);
1058     if (count && recs)
1059         force_present = 1;
1060     ZOOM_resultset_retrieve(r, force_present, start, count);
1061     if (force_present)
1062     {
1063         size_t i;
1064         for (i = 0; i< count; i++)
1065             recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1066     }
1067 }
1068
1069 static void get_cert(ZOOM_connection c)
1070 {
1071     char *cert_buf;
1072     int cert_len;
1073     
1074     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1075     {
1076         ZOOM_connection_option_setl(c, "sslPeerCert",
1077                                     cert_buf, cert_len);
1078         xfree(cert_buf);
1079     }
1080 }
1081
1082 static zoom_ret do_connect(ZOOM_connection c)
1083 {
1084     void *add;
1085     const char *effective_host;
1086
1087     if (c->proxy)
1088         effective_host = c->proxy;
1089     else
1090         effective_host = c->host_port;
1091
1092     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1093
1094     if (c->cs)
1095         cs_close(c->cs);
1096     c->cs = cs_create_host(effective_host, 0, &add);
1097
1098     if (c->cs && c->cs->protocol == PROTO_HTTP)
1099     {
1100 #if YAZ_HAVE_XML2
1101         const char *path = 0;
1102
1103         c->proto = PROTO_HTTP;
1104         cs_get_host_args(c->host_port, &path);
1105         xfree(c->path);
1106         c->path = (char*) xmalloc(strlen(path)+2);
1107         c->path[0] = '/';
1108         strcpy(c->path+1, path);
1109 #else
1110         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1111         do_close(c);
1112         return zoom_complete;
1113 #endif
1114     }
1115     if (c->cs)
1116     {
1117         int ret = cs_connect(c->cs, add);
1118         if (ret == 0)
1119         {
1120             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1121             ZOOM_connection_put_event(c, event);
1122             get_cert(c);
1123             if (c->proto == PROTO_Z3950)
1124                 ZOOM_connection_send_init(c);
1125             else
1126             {
1127                 /* no init request for SRW .. */
1128                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1129                 ZOOM_connection_remove_task(c);
1130                 ZOOM_connection_set_mask(c, 0);
1131                 ZOOM_connection_exec_task(c);
1132             }
1133             c->state = STATE_ESTABLISHED;
1134             return zoom_pending;
1135         }
1136         else if (ret > 0)
1137         {
1138             int mask = ZOOM_SELECT_EXCEPT;
1139             if (c->cs->io_pending & CS_WANT_WRITE)
1140                 mask += ZOOM_SELECT_WRITE;
1141             if (c->cs->io_pending & CS_WANT_READ)
1142                 mask += ZOOM_SELECT_READ;
1143             ZOOM_connection_set_mask(c, mask);
1144             c->state = STATE_CONNECTING; 
1145             return zoom_pending;
1146         }
1147     }
1148     c->state = STATE_IDLE;
1149     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
1150     return zoom_complete;
1151 }
1152
1153 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1154 {
1155     int i;
1156     for (i = 0; i<200; i++)
1157     {
1158         size_t len;
1159         Z_OtherInformation **oi;
1160         char buf[80];
1161         const char *val;
1162         const char *cp;
1163         int oidval;
1164
1165         sprintf(buf, "otherInfo%d", i);
1166         val = ZOOM_options_get(c->options, buf);
1167         if (!val)
1168             break;
1169         cp = strchr(val, ':');
1170         if (!cp)
1171             continue;
1172         len = cp - val;
1173         if (len >= sizeof(buf))
1174             len = sizeof(buf)-1;
1175         memcpy(buf, val, len);
1176         buf[len] = '\0';
1177         oidval = oid_getvalbyname(buf);
1178         if (oidval == VAL_NONE)
1179             continue;
1180         
1181         yaz_oi_APDU(a, &oi);
1182         yaz_oi_set_string_oidval(oi, out, oidval, 1, cp+1);
1183     }
1184 }
1185
1186 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1187 {
1188     assert(a);
1189     if (c->cookie_out)
1190     {
1191         Z_OtherInformation **oi;
1192         yaz_oi_APDU(a, &oi);
1193         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
1194     }
1195     if (c->client_IP)
1196     {
1197         Z_OtherInformation **oi;
1198         yaz_oi_APDU(a, &oi);
1199         yaz_oi_set_string_oidval(oi, out, VAL_CLIENT_IP, 1, c->client_IP);
1200     }
1201     otherInfo_attach(c, a, out);
1202     if (!z_APDU(out, &a, 0, 0))
1203     {
1204         FILE *outf = fopen("/tmp/apdu.txt", "a");
1205         if (a && outf)
1206         {
1207             ODR odr_pr = odr_createmem(ODR_PRINT);
1208             fprintf(outf, "a=%p\n", a);
1209             odr_setprint(odr_pr, outf);
1210             z_APDU(odr_pr, &a, 0, 0);
1211             odr_destroy(odr_pr);
1212         }
1213         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1214         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1215         odr_reset(out);
1216         return -1;
1217     }
1218     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1219     return 0;
1220 }
1221
1222 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1223 {
1224     ZOOM_Event event;
1225     assert(a);
1226     if (encode_APDU(c, a, c->odr_out))
1227         return zoom_complete;
1228     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1229     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1230     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1231     ZOOM_connection_put_event(c, event);
1232     odr_reset(c->odr_out);
1233     return do_write(c);
1234 }
1235
1236 /* returns 1 if PDU was sent OK (still pending )
1237    0 if PDU was not sent OK (nothing to wait for) 
1238 */
1239
1240 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1241 {
1242     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1243     Z_InitRequest *ireq = apdu->u.initRequest;
1244     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1245         odr_malloc(c->odr_out, sizeof(*auth));
1246     const char *auth_groupId = ZOOM_options_get(c->options, "group");
1247     const char *auth_userId = ZOOM_options_get(c->options, "user");
1248     const char *auth_password = ZOOM_options_get(c->options, "password");
1249     char *version;
1250
1251     /* support the pass for backwards compatibility */
1252     if (!auth_password)
1253         auth_password = ZOOM_options_get(c->options, "pass");
1254         
1255     ODR_MASK_SET(ireq->options, Z_Options_search);
1256     ODR_MASK_SET(ireq->options, Z_Options_present);
1257     ODR_MASK_SET(ireq->options, Z_Options_scan);
1258     ODR_MASK_SET(ireq->options, Z_Options_sort);
1259     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1260     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1261     
1262     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1263     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1264     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1265     
1266     /* Index Data's Z39.50 Implementor Id is 81 */
1267     ireq->implementationId =
1268         odr_prepend(c->odr_out,
1269                     ZOOM_options_get(c->options, "implementationId"),
1270                     odr_prepend(c->odr_out, "81", ireq->implementationId));
1271     
1272     ireq->implementationName = 
1273         odr_prepend(c->odr_out,
1274                     ZOOM_options_get(c->options, "implementationName"),
1275                     odr_prepend(c->odr_out, "ZOOM-C",
1276                                 ireq->implementationName));
1277     
1278     version = odr_strdup(c->odr_out, "$Revision: 1.113 $");
1279     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1280         version[strlen(version)-2] = '\0';
1281     ireq->implementationVersion = 
1282         odr_prepend(c->odr_out,
1283                     ZOOM_options_get(c->options, "implementationVersion"),
1284                     odr_prepend(c->odr_out, &version[11],
1285                                 ireq->implementationVersion));
1286     
1287     *ireq->maximumRecordSize =
1288         ZOOM_options_get_int(c->options, "maximumRecordSize", 1024*1024);
1289     *ireq->preferredMessageSize =
1290         ZOOM_options_get_int(c->options, "preferredMessageSize", 1024*1024);
1291     
1292     if (auth_groupId || auth_password)
1293     {
1294         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1295         int i = 0;
1296         pass->groupId = 0;
1297         if (auth_groupId && *auth_groupId)
1298         {
1299             pass->groupId = (char *)
1300                 odr_malloc(c->odr_out, strlen(auth_groupId)+1);
1301             strcpy(pass->groupId, auth_groupId);
1302             i++;
1303         }
1304         pass->userId = 0;
1305         if (auth_userId && *auth_userId)
1306         {
1307             pass->userId = (char *)
1308                 odr_malloc(c->odr_out, strlen(auth_userId)+1);
1309             strcpy(pass->userId, auth_userId);
1310             i++;
1311         }
1312         pass->password = 0;
1313         if (auth_password && *auth_password)
1314         {
1315             pass->password = (char *)
1316                 odr_malloc(c->odr_out, strlen(auth_password)+1);
1317             strcpy(pass->password, auth_password);
1318             i++;
1319         }
1320         if (i)
1321         {
1322             auth->which = Z_IdAuthentication_idPass;
1323             auth->u.idPass = pass;
1324             ireq->idAuthentication = auth;
1325         }
1326     }
1327     else if (auth_userId)
1328     {
1329         auth->which = Z_IdAuthentication_open;
1330         auth->u.open = (char *)
1331             odr_malloc(c->odr_out, strlen(auth_userId)+1);
1332         strcpy(auth->u.open, auth_userId);
1333         ireq->idAuthentication = auth;
1334     }
1335     if (c->proxy)
1336         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
1337                                  VAL_PROXY, 1, c->host_port);
1338     if (c->charset || c->lang)
1339     {
1340         Z_OtherInformation **oi;
1341         Z_OtherInformationUnit *oi_unit;
1342         
1343         yaz_oi_APDU(apdu, &oi);
1344         
1345         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1346         {
1347             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1348             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1349             oi_unit->information.externallyDefinedInfo =
1350                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1351                                               c->charset, c->lang, 1);
1352         }
1353     }
1354     assert(apdu);
1355     return send_APDU(c, apdu);
1356 }
1357
1358 #if YAZ_HAVE_XML2
1359 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1360 {
1361     Z_GDU *gdu;
1362     ZOOM_Event event;
1363
1364     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port, c->path);
1365
1366     if (c->sru_mode == zoom_sru_get)
1367     {
1368         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1369     }
1370     else if (c->sru_mode == zoom_sru_post)
1371     {
1372         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1373     }
1374     else if (c->sru_mode == zoom_sru_soap)
1375     {
1376         yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1377     }
1378     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1379         return zoom_complete;
1380     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1381         
1382     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1383     ZOOM_connection_put_event(c, event);
1384     odr_reset(c->odr_out);
1385     return do_write(c);
1386 }
1387 #endif
1388
1389 #if YAZ_HAVE_XML2
1390 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1391 {
1392     int i;
1393     int *start, *count;
1394     ZOOM_resultset resultset = 0;
1395     Z_SRW_PDU *sr = 0;
1396     const char *option_val = 0;
1397
1398     if (c->error)                  /* don't continue on error */
1399         return zoom_complete;
1400     assert(c->tasks);
1401     switch(c->tasks->which)
1402     {
1403     case ZOOM_TASK_SEARCH:
1404         resultset = c->tasks->u.search.resultset;
1405         resultset->setname = xstrdup("default");
1406         ZOOM_options_set(resultset->options, "setname", resultset->setname);
1407         start = &c->tasks->u.search.start;
1408         count = &c->tasks->u.search.count;
1409         break;
1410     case ZOOM_TASK_RETRIEVE:
1411         resultset = c->tasks->u.retrieve.resultset;
1412
1413         start = &c->tasks->u.retrieve.start;
1414         count = &c->tasks->u.retrieve.count;
1415         
1416         if (*start >= resultset->size)
1417             return zoom_complete;
1418         if (*start + *count > resultset->size)
1419             *count = resultset->size - *start;
1420
1421         for (i = 0; i < *count; i++)
1422         {
1423             ZOOM_record rec =
1424                 record_cache_lookup(resultset, i + *start,
1425                                     c->tasks->u.retrieve.syntax,
1426                                     c->tasks->u.retrieve.elementSetName);
1427             if (!rec)
1428                 break;
1429             else
1430             {
1431                 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1432                 ZOOM_connection_put_event(c, event);
1433             }
1434         }
1435         *start += i;
1436         *count -= i;
1437
1438         if (*count == 0)
1439             return zoom_complete;
1440         break;
1441     default:
1442         return zoom_complete;
1443     }
1444     assert(resultset->query);
1445         
1446     sr = yaz_srw_get(c->odr_out, Z_SRW_searchRetrieve_request);
1447
1448     if (resultset->query->z_query->which == Z_Query_type_104
1449         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1450     {
1451         sr->u.request->query_type = Z_SRW_query_type_cql;
1452         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1453     }
1454     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1455              resultset->query->z_query->u.type_1)
1456     {
1457         sr->u.request->query_type = Z_SRW_query_type_pqf;
1458         sr->u.request->query.pqf = resultset->query->query_string;
1459     }
1460     else
1461     {
1462         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1463         return zoom_complete;
1464     }
1465     sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1466     sr->u.request->maximumRecords = odr_intdup(
1467         c->odr_out, resultset->step>0 ? resultset->step : *count);
1468     sr->u.request->recordSchema = resultset->schema;
1469     
1470     option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1471     if (option_val)
1472         sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1473
1474     option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1475     if (option_val)
1476         sr->extra_args = odr_strdup(c->odr_out, option_val);
1477     return send_srw(c, sr);
1478 }
1479 #else
1480 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1481 {
1482     return zoom_complete;
1483 }
1484 #endif
1485
1486 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1487 {
1488     ZOOM_resultset r;
1489     int lslb, ssub, mspn;
1490     const char *syntax;
1491     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1492     Z_SearchRequest *search_req = apdu->u.searchRequest;
1493     const char *elementSetName;
1494     const char *smallSetElementSetName;
1495     const char *mediumSetElementSetName;
1496
1497     assert(c->tasks);
1498     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1499
1500     r = c->tasks->u.search.resultset;
1501
1502     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1503
1504     elementSetName =
1505         ZOOM_options_get(r->options, "elementSetName");
1506     smallSetElementSetName  =
1507         ZOOM_options_get(r->options, "smallSetElementSetName");
1508     mediumSetElementSetName =
1509         ZOOM_options_get(r->options, "mediumSetElementSetName");
1510
1511     if (!smallSetElementSetName)
1512         smallSetElementSetName = elementSetName;
1513
1514     if (!mediumSetElementSetName)
1515         mediumSetElementSetName = elementSetName;
1516
1517     assert(r);
1518     assert(r->query);
1519
1520     /* prepare query for the search request */
1521     search_req->query = r->query->z_query;
1522     if (!search_req->query)
1523     {
1524         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1525         return zoom_complete;
1526     }
1527
1528     search_req->databaseNames = r->databaseNames;
1529     search_req->num_databaseNames = r->num_databaseNames;
1530
1531     /* get syntax (no need to provide unless piggyback is in effect) */
1532     syntax = c->tasks->u.search.syntax;
1533
1534     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1535     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1536     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1537     if (lslb != -1 && ssub != -1 && mspn != -1)
1538     {
1539         /* So're a Z39.50 expert? Let's hope you don't do sort */
1540         *search_req->largeSetLowerBound = lslb;
1541         *search_req->smallSetUpperBound = ssub;
1542         *search_req->mediumSetPresentNumber = mspn;
1543     }
1544     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1545              && r->piggyback && !r->r_sort_spec && !r->schema)
1546     {
1547         /* Regular piggyback - do it unless we're going to do sort */
1548         *search_req->largeSetLowerBound = 2000000000;
1549         *search_req->smallSetUpperBound = 1;
1550         *search_req->mediumSetPresentNumber = 
1551             r->step>0 ? r->step : c->tasks->u.search.count;
1552     }
1553     else
1554     {
1555         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1556         smallSetElementSetName = 0;
1557         mediumSetElementSetName = 0;
1558         syntax = 0;
1559     }
1560     if (smallSetElementSetName && *smallSetElementSetName)
1561     {
1562         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1563             odr_malloc(c->odr_out, sizeof(*esn));
1564         
1565         esn->which = Z_ElementSetNames_generic;
1566         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1567         search_req->smallSetElementSetNames = esn;
1568     }
1569     if (mediumSetElementSetName && *mediumSetElementSetName)
1570     {
1571         Z_ElementSetNames *esn =(Z_ElementSetNames *)
1572             odr_malloc(c->odr_out, sizeof(*esn));
1573         
1574         esn->which = Z_ElementSetNames_generic;
1575         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1576         search_req->mediumSetElementSetNames = esn;
1577     }
1578     if (syntax)
1579         search_req->preferredRecordSyntax =
1580             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1581     
1582     if (!r->setname)
1583     {
1584         if (c->support_named_resultsets)
1585         {
1586             char setname[14];
1587             int ord;
1588             /* find the lowest unused ordinal so that we re-use
1589                result sets on the server. */
1590             for (ord = 1; ; ord++)
1591             {
1592                 ZOOM_resultset rp;
1593                 sprintf(setname, "%d", ord);
1594                 for (rp = c->resultsets; rp; rp = rp->next)
1595                     if (rp->setname && !strcmp(rp->setname, setname))
1596                         break;
1597                 if (!rp)
1598                     break;
1599             }
1600             r->setname = xstrdup(setname);
1601             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1602                     "set %s", c, r->setname);
1603         }
1604         else
1605         {
1606             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1607                     "default set", c);
1608             r->setname = xstrdup("default");
1609         }
1610         ZOOM_options_set(r->options, "setname", r->setname);
1611     }
1612     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1613     return send_APDU(c, apdu);
1614 }
1615
1616 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1617 {
1618     int oclass;
1619     char *addinfo = 0;
1620
1621     switch (r->which)
1622     {
1623     case Z_DefaultDiagFormat_v2Addinfo:
1624         addinfo = r->u.v2Addinfo;
1625         break;
1626     case Z_DefaultDiagFormat_v3Addinfo:
1627         addinfo = r->u.v3Addinfo;
1628         break;
1629     }
1630     xfree(c->addinfo);
1631     c->addinfo = 0;
1632     set_dset_error(c, *r->condition,
1633                    yaz_z3950oid_to_str(r->diagnosticSetId, &oclass),
1634                    addinfo, 0);
1635 }
1636
1637 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1638 {
1639     if (p->which != Z_DiagRec_defaultFormat)
1640         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1641     else
1642         response_default_diag(c, p->u.defaultFormat);
1643 }
1644
1645 ZOOM_API(ZOOM_record)
1646     ZOOM_record_clone(ZOOM_record srec)
1647 {
1648     char *buf;
1649     int size;
1650     ODR odr_enc;
1651     ZOOM_record nrec;
1652
1653     odr_enc = odr_createmem(ODR_ENCODE);
1654     if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1655         return 0;
1656     buf = odr_getbuf(odr_enc, &size, 0);
1657     
1658     nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1659     nrec->odr = odr_createmem(ODR_DECODE);
1660     nrec->wrbuf_marc = 0;
1661     nrec->wrbuf_iconv = 0;
1662     nrec->wrbuf_opac = 0;
1663     odr_setbuf(nrec->odr, buf, size, 0);
1664     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1665     
1666     odr_destroy(odr_enc);
1667     return nrec;
1668 }
1669
1670 ZOOM_API(ZOOM_record)
1671     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1672 {
1673     const char *syntax =
1674         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1675     const char *elementSetName =
1676         ZOOM_options_get(s->options, "elementSetName");
1677
1678     return record_cache_lookup(s, pos, syntax, elementSetName);
1679 }
1680
1681 ZOOM_API(ZOOM_record)
1682     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1683 {
1684     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1685
1686     if (!rec)
1687     {
1688         /*
1689          * MIKE: I think force_sync should always be zero, but I don't
1690          * want to make this change until I get the go-ahead from
1691          * Adam, in case something depends on the old synchronous
1692          * behaviour.
1693          */
1694         int force_sync = 1;
1695         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1696         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1697         rec = ZOOM_resultset_record_immediate(r, pos);
1698     }
1699     return rec;
1700 }
1701
1702 ZOOM_API(void)
1703     ZOOM_record_destroy(ZOOM_record rec)
1704 {
1705     if (!rec)
1706         return;
1707     if (rec->wrbuf_marc)
1708         wrbuf_free(rec->wrbuf_marc, 1);
1709     if (rec->wrbuf_iconv)
1710         wrbuf_free(rec->wrbuf_iconv, 1);
1711     if (rec->wrbuf_opac)
1712         wrbuf_free(rec->wrbuf_opac, 1);
1713     odr_destroy(rec->odr);
1714     xfree(rec);
1715 }
1716
1717 static const char *marc_iconv_return(ZOOM_record rec, int marc_type,
1718                                      int *len,
1719                                      const char *buf, int sz,
1720                                      const char *record_charset)
1721 {
1722     char to[40];
1723     char from[40];
1724     yaz_iconv_t cd = 0;
1725     yaz_marc_t mt = yaz_marc_create();
1726
1727     *from = '\0';
1728     strcpy(to, "UTF-8");
1729     if (record_charset && *record_charset)
1730     {
1731         /* Use "from,to" or just "from" */
1732         const char *cp = strchr(record_charset, ',');
1733         int clen = strlen(record_charset);
1734         if (cp && cp[1])
1735         {
1736             strncpy( to, cp+1, sizeof(to)-1);
1737             to[sizeof(to)-1] = '\0';
1738             clen = cp - record_charset;
1739         }
1740         if (clen > sizeof(from)-1)
1741             clen = sizeof(from)-1;
1742         
1743         if (clen)
1744             strncpy(from, record_charset, clen);
1745         from[clen] = '\0';
1746     }
1747
1748     if (*from && *to)
1749     {
1750         cd = yaz_iconv_open(to, from);
1751         yaz_marc_iconv(mt, cd);
1752     }
1753
1754     yaz_marc_xml(mt, marc_type);
1755     if (!rec->wrbuf_marc)
1756         rec->wrbuf_marc = wrbuf_alloc();
1757     wrbuf_rewind(rec->wrbuf_marc);
1758     if (yaz_marc_decode_wrbuf(mt, buf, sz, rec->wrbuf_marc) > 0)
1759     {
1760         yaz_marc_destroy(mt);
1761         if (cd)
1762             yaz_iconv_close(cd);
1763         if (len)
1764             *len = wrbuf_len(rec->wrbuf_marc);
1765         return wrbuf_buf(rec->wrbuf_marc);
1766     }
1767     yaz_marc_destroy(mt);
1768     if (cd)
1769         yaz_iconv_close(cd);
1770     return 0;
1771 }
1772
1773 static const char *record_iconv_return(ZOOM_record rec, int *len,
1774                                        const char *buf, int sz,
1775                                        const char *record_charset)
1776 {
1777     char to[40];
1778     char from[40];
1779     yaz_iconv_t cd = 0;
1780
1781     *from = '\0';
1782     strcpy(to, "UTF-8");
1783     if (record_charset && *record_charset)
1784     {
1785         /* Use "from,to" or just "from" */
1786         const char *cp = strchr(record_charset, ',');
1787         int clen = strlen(record_charset);
1788         if (cp && cp[1])
1789         {
1790             strncpy( to, cp+1, sizeof(to)-1);
1791             to[sizeof(to)-1] = '\0';
1792             clen = cp - record_charset;
1793         }
1794         if (clen > sizeof(from)-1)
1795             clen = sizeof(from)-1;
1796         
1797         if (clen)
1798             strncpy(from, record_charset, clen);
1799         from[clen] = '\0';
1800     }
1801
1802     if (*from && *to && (cd = yaz_iconv_open(to, from)))
1803     {
1804         char outbuf[12];
1805         size_t inbytesleft = sz;
1806         const char *inp = buf;
1807         
1808         if (!rec->wrbuf_iconv)
1809             rec->wrbuf_iconv = wrbuf_alloc();
1810
1811         wrbuf_rewind(rec->wrbuf_iconv);
1812
1813         while (inbytesleft)
1814         {
1815             size_t outbytesleft = sizeof(outbuf);
1816             char *outp = outbuf;
1817             size_t r = yaz_iconv(cd, (char**) &inp,
1818                                  &inbytesleft, 
1819                                  &outp, &outbytesleft);
1820             if (r == (size_t) (-1))
1821             {
1822                 int e = yaz_iconv_error(cd);
1823                 if (e != YAZ_ICONV_E2BIG)
1824                     break;
1825             }
1826             wrbuf_write(rec->wrbuf_iconv, outbuf, outp - outbuf);
1827         }
1828         wrbuf_puts(rec->wrbuf_iconv, "");
1829         buf = wrbuf_buf(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));