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