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