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