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