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