Move otherinfo facet stuff to facet.c
[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->num_facets = 0;
912     r->facets_names = 0;
913     r->mutex = 0;
914     yaz_mutex_create(&r->mutex);
915 #if SHPTR
916     {
917         WRBUF w = wrbuf_alloc();
918         YAZ_SHPTR_INIT(r->record_wrbuf, w);
919     }
920 #endif
921     return r;
922 }
923
924 ZOOM_API(ZOOM_resultset)
925     ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
926 {
927     ZOOM_resultset r;
928     ZOOM_query s = ZOOM_query_create();
929
930     ZOOM_query_prefix(s, q);
931
932     r = ZOOM_connection_search(c, s);
933     ZOOM_query_destroy(s);
934     return r;
935 }
936
937 ZOOM_API(ZOOM_resultset)
938     ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
939 {
940     ZOOM_resultset r = ZOOM_resultset_create();
941     ZOOM_task task;
942     const char *cp;
943     int start, count;
944     const char *syntax, *elementSetName;
945 #if ZOOM_RESULT_LISTS
946     ZOOM_resultsets set;
947 #endif
948
949     yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
950     r->r_sort_spec = q->sort_spec;
951     r->query = q;
952
953     r->options = ZOOM_options_create_with_parent(c->options);
954     
955     start = ZOOM_options_get_int(r->options, "start", 0);
956     count = ZOOM_options_get_int(r->options, "count", 0);
957     {
958         /* If "presentChunk" is defined use that; otherwise "step" */
959         const char *cp = ZOOM_options_get(r->options, "presentChunk");
960         r->step = ZOOM_options_get_int(r->options,
961                                        (cp != 0 ? "presentChunk": "step"), 0);
962     }
963     r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
964     cp = ZOOM_options_get(r->options, "setname");
965     if (cp)
966         r->setname = xstrdup(cp);
967     cp = ZOOM_options_get(r->options, "schema");
968     if (cp)
969         r->schema = xstrdup(cp);
970
971     r->databaseNames = set_DatabaseNames(c, c->options, &r->num_databaseNames,
972                                          r->odr);
973     
974     r->connection = c;
975
976 #if ZOOM_RESULT_LISTS
977     yaz_log(log_details, "%p ZOOM_connection_search: Adding new resultset (%p) to resultsets (%p) ", c, r, c->resultsets);
978     set = xmalloc(sizeof(*set));
979     ZOOM_resultset_addref(r);
980     set->resultset = r;
981     set->next = c->resultsets;
982     c->resultsets = set;
983 #else
984     r->next = c->resultsets;
985     c->resultsets = r;
986 #endif
987     if (c->host_port && c->proto == PROTO_HTTP)
988     {
989         if (!c->cs)
990         {
991             yaz_log(log_details, "ZOOM_connection_search: no comstack");
992             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
993         }
994         else
995         {
996             yaz_log(log_details, "ZOOM_connection_search: reconnect");
997             c->reconnect_ok = 1;
998         }
999     }
1000
1001     task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
1002     task->u.search.resultset = r;
1003     task->u.search.start = start;
1004     task->u.search.count = count;
1005     task->u.search.recv_search_fired = 0;
1006
1007     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1008     task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
1009     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1010     task->u.search.elementSetName = elementSetName 
1011         ? xstrdup(elementSetName) : 0;
1012    
1013     ZOOM_resultset_addref(r);
1014
1015     (q->refcount)++;
1016
1017     if (!c->async)
1018     {
1019         while (ZOOM_event(1, &c))
1020             ;
1021     }
1022     return r;
1023 }
1024
1025 ZOOM_API(void)
1026     ZOOM_resultset_sort(ZOOM_resultset r,
1027                          const char *sort_type, const char *sort_spec)
1028 {
1029     (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
1030 }
1031
1032 ZOOM_API(int)
1033     ZOOM_resultset_sort1(ZOOM_resultset r,
1034                          const char *sort_type, const char *sort_spec)
1035 {
1036     ZOOM_connection c = r->connection;
1037     ZOOM_task task;
1038     ZOOM_query newq;
1039
1040     newq = ZOOM_query_create();
1041     if (ZOOM_query_sortby(newq, sort_spec) < 0)
1042         return -1;
1043
1044     yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
1045             r, r, sort_type, sort_spec);
1046     if (!c)
1047         return 0;
1048
1049     if (c->host_port && c->proto == PROTO_HTTP)
1050     {
1051         if (!c->cs)
1052         {
1053             yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
1054             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1055         }
1056         else
1057         {
1058             yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
1059                     r);
1060             c->reconnect_ok = 1;
1061         }
1062     }
1063     
1064     ZOOM_resultset_cache_reset(r);
1065     task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
1066     task->u.sort.resultset = r;
1067     task->u.sort.q = newq;
1068
1069     ZOOM_resultset_addref(r);  
1070
1071     if (!c->async)
1072     {
1073         while (ZOOM_event(1, &c))
1074             ;
1075     }
1076
1077     return 0;
1078 }
1079
1080 static void ZOOM_record_release(ZOOM_record rec)
1081 {
1082     if (!rec)
1083         return;
1084
1085 #if SHPTR
1086     if (rec->record_wrbuf)
1087         YAZ_SHPTR_DEC(rec->record_wrbuf, wrbuf_destroy);
1088 #else
1089     if (rec->wrbuf)
1090         wrbuf_destroy(rec->wrbuf);
1091 #endif
1092
1093     if (rec->odr)
1094         odr_destroy(rec->odr);
1095 }
1096
1097 ZOOM_API(void)
1098     ZOOM_resultset_cache_reset(ZOOM_resultset r)
1099 {
1100     int i;
1101     for (i = 0; i<RECORD_HASH_SIZE; i++)
1102     {
1103         ZOOM_record_cache rc;
1104         for (rc = r->record_hash[i]; rc; rc = rc->next)
1105         {
1106             ZOOM_record_release(&rc->rec);
1107         }
1108         r->record_hash[i] = 0;
1109     }
1110 }
1111
1112 ZOOM_API(void)
1113     ZOOM_resultset_destroy(ZOOM_resultset r)
1114 {
1115     resultset_destroy(r);
1116 }
1117
1118 static void resultset_destroy(ZOOM_resultset r)
1119 {
1120     if (!r)
1121         return;
1122     yaz_mutex_enter(r->mutex);
1123     (r->refcount)--;
1124     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
1125             r, r, r->refcount);
1126     if (r->refcount == 0)
1127     {
1128         yaz_mutex_leave(r->mutex);
1129
1130         yaz_log(log_details, "%p ZOOM_connection resultset_destroy: Deleting resultset (%p) ", r->connection, r);
1131         ZOOM_resultset_cache_reset(r);
1132         ZOOM_resultset_release(r);
1133         ZOOM_query_destroy(r->query);
1134         ZOOM_options_destroy(r->options);
1135         odr_destroy(r->odr);
1136         xfree(r->setname);
1137         xfree(r->schema);
1138         yaz_mutex_destroy(&r->mutex);
1139 #if SHPTR
1140         YAZ_SHPTR_DEC(r->record_wrbuf, wrbuf_destroy);
1141 #endif
1142         xfree(r);
1143     }
1144     else
1145         yaz_mutex_leave(r->mutex);
1146 }
1147
1148 ZOOM_API(size_t)
1149     ZOOM_resultset_size(ZOOM_resultset r)
1150 {
1151     yaz_log(log_details, "ZOOM_resultset_size r=%p count=" ODR_INT_PRINTF,
1152             r, r->size);
1153     return r->size;
1154 }
1155
1156 static void do_close(ZOOM_connection c)
1157 {
1158     if (c->cs)
1159         cs_close(c->cs);
1160     c->cs = 0;
1161     ZOOM_connection_set_mask(c, 0);
1162     c->state = STATE_IDLE;
1163 }
1164
1165 static int ZOOM_test_reconnect(ZOOM_connection c)
1166 {
1167     ZOOM_Event event;
1168
1169     if (!c->reconnect_ok)
1170         return 0;
1171     do_close(c);
1172     c->reconnect_ok = 0;
1173     c->tasks->running = 0;
1174     ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
1175
1176     event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1177     ZOOM_connection_put_event(c, event);
1178
1179     return 1;
1180 }
1181
1182 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
1183                                     int force_sync, int start, int count)
1184 {
1185     ZOOM_task task;
1186     ZOOM_connection c;
1187     const char *cp;
1188     const char *syntax, *elementSetName;
1189
1190     if (!r)
1191         return;
1192     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1193             " count=%d", r, force_sync, start, count);
1194     c = r->connection;
1195     if (!c)
1196         return;
1197
1198     if (c->host_port && c->proto == PROTO_HTTP)
1199     {
1200         if (!c->cs)
1201         {
1202             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1203             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1204         }
1205         else
1206         {
1207             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1208                     "reconnect", r);
1209             c->reconnect_ok = 1;
1210         }
1211     }
1212     task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1213     task->u.retrieve.resultset = r;
1214     task->u.retrieve.start = start;
1215     task->u.retrieve.count = count;
1216
1217     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1218     task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1219     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1220     task->u.retrieve.elementSetName = elementSetName 
1221         ? xstrdup(elementSetName) : 0;
1222
1223     cp = ZOOM_options_get(r->options, "schema");
1224     if (cp)
1225     {
1226         if (!r->schema || strcmp(r->schema, cp))
1227         {
1228             xfree(r->schema);
1229             r->schema = xstrdup(cp);
1230         }
1231     }
1232
1233     ZOOM_resultset_addref(r);
1234
1235     if (!r->connection->async || force_sync)
1236         while (r->connection && ZOOM_event(1, &r->connection))
1237             ;
1238 }
1239
1240 ZOOM_API(void)
1241     ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1242                            size_t start, size_t count)
1243 {
1244     int force_present = 0;
1245
1246     if (!r)
1247         return ;
1248     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1249             r, r, (long) start, (long) count);
1250     if (count && recs)
1251         force_present = 1;
1252     ZOOM_resultset_retrieve(r, force_present, start, count);
1253     if (force_present)
1254     {
1255         size_t i;
1256         for (i = 0; i< count; i++)
1257             recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1258     }
1259 }
1260
1261 ZOOM_API(size_t)
1262     ZOOM_resultset_facets_size(ZOOM_resultset r) {
1263     return r->num_facets;
1264 }
1265
1266 ZOOM_API(ZOOM_facet_field)
1267     ZOOM_resultset_get_facet_field(ZOOM_resultset r, const char *name) {
1268     int num = r->num_facets;
1269     ZOOM_facet_field *facets = r->facets;
1270     int index;
1271     for (index = 0; index < num; index++) {
1272         if (!strcmp(facets[index]->facet_name, name)) {
1273             return facets[index];
1274         }
1275     }
1276     return 0;
1277 }
1278
1279
1280 ZOOM_API(ZOOM_facet_field *)
1281     ZOOM_resultset_facets(ZOOM_resultset r)
1282 {
1283     return r->facets;
1284 }
1285
1286 ZOOM_API(const char**)
1287     ZOOM_resultset_facet_names(ZOOM_resultset r)
1288 {
1289     return (const char **) r->facets_names;
1290 }
1291
1292 ZOOM_API(const char*)
1293     ZOOM_facet_field_name(ZOOM_facet_field field)
1294 {
1295     return field->facet_name;
1296 }
1297
1298 ZOOM_API(size_t)
1299     ZOOM_facet_field_term_count(ZOOM_facet_field field)
1300 {
1301     return field->num_terms;
1302 }
1303
1304 ZOOM_API(const char*)
1305     ZOOM_facet_field_get_term(ZOOM_facet_field field, size_t idx, int *freq) {
1306     *freq = field->facet_terms[idx].frequency;
1307     return field->facet_terms[idx].term;
1308 }
1309
1310
1311 static void get_cert(ZOOM_connection c)
1312 {
1313     char *cert_buf;
1314     int cert_len;
1315     
1316     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1317     {
1318         ZOOM_connection_option_setl(c, "sslPeerCert",
1319                                     cert_buf, cert_len);
1320         xfree(cert_buf);
1321     }
1322 }
1323
1324 static zoom_ret do_connect_host(ZOOM_connection c,
1325                                 const char *effective_host,
1326                                 const char *logical_url);
1327
1328 static zoom_ret do_connect(ZOOM_connection c)
1329 {
1330     const char *effective_host;
1331
1332     if (c->proxy)
1333         effective_host = c->proxy;
1334     else
1335         effective_host = c->host_port;
1336     return do_connect_host(c, effective_host, c->host_port);
1337 }
1338
1339 static zoom_ret do_connect_host(ZOOM_connection c, const char *effective_host,
1340     const char *logical_url)
1341 {
1342     void *add;
1343
1344     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1345
1346     if (c->cs)
1347         cs_close(c->cs);
1348     c->cs = cs_create_host(effective_host, 0, &add);
1349
1350     if (c->cs && c->cs->protocol == PROTO_HTTP)
1351     {
1352 #if YAZ_HAVE_XML2
1353         if (logical_url)
1354         {
1355             const char *db = 0;
1356             
1357             c->proto = PROTO_HTTP;
1358             cs_get_host_args(logical_url, &db);
1359             xfree(c->path);
1360             
1361             c->path = xmalloc(strlen(db) * 3 + 2);
1362             yaz_encode_sru_dbpath_buf(c->path, db);
1363         }
1364 #else
1365         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1366         do_close(c);
1367         return zoom_complete;
1368 #endif
1369     }
1370     if (c->cs)
1371     {
1372         int ret = cs_connect(c->cs, add);
1373         if (ret == 0)
1374         {
1375             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1376             ZOOM_connection_put_event(c, event);
1377             get_cert(c);
1378             if (c->proto == PROTO_Z3950)
1379                 ZOOM_connection_send_init(c);
1380             else
1381             {
1382                 /* no init request for SRW .. */
1383                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1384                 ZOOM_connection_remove_task(c);
1385                 ZOOM_connection_set_mask(c, 0);
1386                 ZOOM_connection_exec_task(c);
1387             }
1388             c->state = STATE_ESTABLISHED;
1389             return zoom_pending;
1390         }
1391         else if (ret > 0)
1392         {
1393             int mask = ZOOM_SELECT_EXCEPT;
1394             if (c->cs->io_pending & CS_WANT_WRITE)
1395                 mask += ZOOM_SELECT_WRITE;
1396             if (c->cs->io_pending & CS_WANT_READ)
1397                 mask += ZOOM_SELECT_READ;
1398             ZOOM_connection_set_mask(c, mask);
1399             c->state = STATE_CONNECTING; 
1400             return zoom_pending;
1401         }
1402     }
1403     c->state = STATE_IDLE;
1404     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, logical_url);
1405     return zoom_complete;
1406 }
1407
1408 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1409 {
1410     int i;
1411     for (i = 0; i<200; i++)
1412     {
1413         size_t len;
1414         Odr_oid *oid;
1415         Z_OtherInformation **oi;
1416         char buf[80];
1417         const char *val;
1418         const char *cp;
1419
1420         sprintf(buf, "otherInfo%d", i);
1421         val = ZOOM_options_get(c->options, buf);
1422         if (!val)
1423             break;
1424         cp = strchr(val, ':');
1425         if (!cp)
1426             continue;
1427         len = cp - val;
1428         if (len >= sizeof(buf))
1429             len = sizeof(buf)-1;
1430         memcpy(buf, val, len);
1431         buf[len] = '\0';
1432         
1433         oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
1434                                     buf, out);
1435         if (!oid)
1436             continue;
1437         
1438         yaz_oi_APDU(a, &oi);
1439         yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
1440     }
1441 }
1442
1443 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1444 {
1445     assert(a);
1446     if (c->cookie_out)
1447     {
1448         Z_OtherInformation **oi;
1449         yaz_oi_APDU(a, &oi);
1450         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie, 
1451                               1, c->cookie_out);
1452     }
1453     if (c->client_IP)
1454     {
1455         Z_OtherInformation **oi;
1456         yaz_oi_APDU(a, &oi);
1457         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip, 
1458                               1, c->client_IP);
1459     }
1460     otherInfo_attach(c, a, out);
1461     if (!z_APDU(out, &a, 0, 0))
1462     {
1463         FILE *outf = fopen("/tmp/apdu.txt", "a");
1464         if (a && outf)
1465         {
1466             ODR odr_pr = odr_createmem(ODR_PRINT);
1467             fprintf(outf, "a=%p\n", a);
1468             odr_setprint(odr_pr, outf);
1469             z_APDU(odr_pr, &a, 0, 0);
1470             odr_destroy(odr_pr);
1471         }
1472         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1473         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1474         odr_reset(out);
1475         return -1;
1476     }
1477     if (c->odr_print)
1478         z_APDU(c->odr_print, &a, 0, 0);
1479     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1480     return 0;
1481 }
1482
1483 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1484 {
1485     ZOOM_Event event;
1486     assert(a);
1487     if (encode_APDU(c, a, c->odr_out))
1488         return zoom_complete;
1489     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1490     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1491     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1492     ZOOM_connection_put_event(c, event);
1493     odr_reset(c->odr_out);
1494     return do_write(c);
1495 }
1496
1497 /* returns 1 if PDU was sent OK (still pending )
1498    0 if PDU was not sent OK (nothing to wait for) 
1499 */
1500
1501 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1502 {
1503     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1504     Z_InitRequest *ireq = apdu->u.initRequest;
1505     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1506         odr_malloc(c->odr_out, sizeof(*auth));
1507
1508     ODR_MASK_SET(ireq->options, Z_Options_search);
1509     ODR_MASK_SET(ireq->options, Z_Options_present);
1510     ODR_MASK_SET(ireq->options, Z_Options_scan);
1511     ODR_MASK_SET(ireq->options, Z_Options_sort);
1512     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1513     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1514     
1515     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1516     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1517     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1518     
1519     ireq->implementationId =
1520         odr_prepend(c->odr_out,
1521                     ZOOM_options_get(c->options, "implementationId"),
1522                     ireq->implementationId);
1523     
1524     ireq->implementationName = 
1525         odr_prepend(c->odr_out,
1526                     ZOOM_options_get(c->options, "implementationName"),
1527                     odr_prepend(c->odr_out, "ZOOM-C",
1528                                 ireq->implementationName));
1529     
1530     ireq->implementationVersion = 
1531         odr_prepend(c->odr_out,
1532                     ZOOM_options_get(c->options, "implementationVersion"),
1533                                 ireq->implementationVersion);
1534     
1535     *ireq->maximumRecordSize = c->maximum_record_size;
1536     *ireq->preferredMessageSize = c->preferred_message_size;
1537     
1538     if (c->group || c->password)
1539     {
1540         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1541         pass->groupId = odr_strdup_null(c->odr_out, c->group);
1542         pass->userId = odr_strdup_null(c->odr_out, c->user);
1543         pass->password = odr_strdup_null(c->odr_out, c->password);
1544         auth->which = Z_IdAuthentication_idPass;
1545         auth->u.idPass = pass;
1546         ireq->idAuthentication = auth;
1547     }
1548     else if (c->user)
1549     {
1550         auth->which = Z_IdAuthentication_open;
1551         auth->u.open = odr_strdup(c->odr_out, c->user);
1552         ireq->idAuthentication = auth;
1553     }
1554     if (c->proxy)
1555     {
1556         yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
1557                               yaz_oid_userinfo_proxy, 1, c->host_port);
1558     }
1559     if (c->charset || c->lang)
1560     {
1561         Z_OtherInformation **oi;
1562         Z_OtherInformationUnit *oi_unit;
1563         
1564         yaz_oi_APDU(apdu, &oi);
1565         
1566         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1567         {
1568             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1569             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1570             oi_unit->information.externallyDefinedInfo =
1571                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1572                                               c->charset, c->lang, 1);
1573         }
1574     }
1575     assert(apdu);
1576     return send_APDU(c, apdu);
1577 }
1578
1579 #if YAZ_HAVE_XML2
1580 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1581 {
1582     Z_GDU *gdu;
1583     ZOOM_Event event;
1584     const char *database =  ZOOM_options_get(c->options, "databaseName");
1585     char *fdatabase = 0;
1586     
1587     if (database)
1588         fdatabase = yaz_encode_sru_dbpath_odr(c->odr_out, database);
1589     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port,
1590                                        fdatabase ? fdatabase : c->path);
1591
1592     if (c->sru_mode == zoom_sru_get)
1593     {
1594         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1595     }
1596     else if (c->sru_mode == zoom_sru_post)
1597     {
1598         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1599     }
1600     else if (c->sru_mode == zoom_sru_soap)
1601     {
1602         yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1603     }
1604     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1605         return zoom_complete;
1606     if (c->odr_print)
1607         z_GDU(c->odr_print, &gdu, 0, 0);
1608     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1609         
1610     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1611     ZOOM_connection_put_event(c, event);
1612     odr_reset(c->odr_out);
1613     return do_write(c);
1614 }
1615 #endif
1616
1617 #if YAZ_HAVE_XML2
1618 static Z_SRW_PDU *ZOOM_srw_get_pdu(ZOOM_connection c, int type)
1619 {
1620     Z_SRW_PDU *sr = yaz_srw_get_pdu(c->odr_out, type, c->sru_version);
1621     sr->username = c->user;
1622     sr->password = c->password;
1623     return sr;
1624 }
1625 #endif
1626
1627 #if YAZ_HAVE_XML2
1628 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1629 {
1630     int i;
1631     int *start, *count;
1632     ZOOM_resultset resultset = 0;
1633     Z_SRW_PDU *sr = 0;
1634     const char *option_val = 0;
1635
1636     if (c->error)                  /* don't continue on error */
1637         return zoom_complete;
1638     assert(c->tasks);
1639     switch(c->tasks->which)
1640     {
1641     case ZOOM_TASK_SEARCH:
1642         resultset = c->tasks->u.search.resultset;
1643         if (!resultset->setname)
1644             resultset->setname = xstrdup("default");
1645         ZOOM_options_set(resultset->options, "setname", resultset->setname);
1646         start = &c->tasks->u.search.start;
1647         count = &c->tasks->u.search.count;
1648         break;
1649     case ZOOM_TASK_RETRIEVE:
1650         resultset = c->tasks->u.retrieve.resultset;
1651
1652         start = &c->tasks->u.retrieve.start;
1653         count = &c->tasks->u.retrieve.count;
1654
1655         if (*start >= resultset->size)
1656             return zoom_complete;
1657         if (*start + *count > resultset->size)
1658             *count = resultset->size - *start;
1659
1660         for (i = 0; i < *count; i++)
1661         {
1662             ZOOM_record rec =
1663                 record_cache_lookup(resultset, i + *start,
1664                                     c->tasks->u.retrieve.syntax,
1665                                     c->tasks->u.retrieve.elementSetName);
1666             if (!rec)
1667                 break;
1668             else
1669             {
1670                 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1671                 ZOOM_connection_put_event(c, event);
1672             }
1673         }
1674         *start += i;
1675         *count -= i;
1676
1677         if (*count == 0)
1678             return zoom_complete;
1679         break;
1680     default:
1681         return zoom_complete;
1682     }
1683     assert(resultset->query);
1684         
1685     sr = ZOOM_srw_get_pdu(c, Z_SRW_searchRetrieve_request);
1686     if (resultset->query->z_query->which == Z_Query_type_104
1687         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1688     {
1689         sr->u.request->query_type = Z_SRW_query_type_cql;
1690         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1691     }
1692     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1693              resultset->query->z_query->u.type_1)
1694     {
1695         sr->u.request->query_type = Z_SRW_query_type_pqf;
1696         sr->u.request->query.pqf = resultset->query->query_string;
1697     }
1698     else
1699     {
1700         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1701         return zoom_complete;
1702     }
1703     sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1704     sr->u.request->maximumRecords = odr_intdup(
1705         c->odr_out, (resultset->step > 0 && resultset->step < *count) ? 
1706         resultset->step : *count);
1707     sr->u.request->recordSchema = resultset->schema;
1708     
1709     option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1710     if (option_val)
1711         sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1712
1713     option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1714     yaz_encode_sru_extra(sr, c->odr_out, option_val);
1715     return send_srw(c, sr);
1716 }
1717 #else
1718 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1719 {
1720     return zoom_complete;
1721 }
1722 #endif
1723
1724 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1725 {
1726     ZOOM_resultset r;
1727     int lslb, ssub, mspn;
1728     const char *syntax;
1729     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1730     Z_SearchRequest *search_req = apdu->u.searchRequest;
1731     const char *elementSetName;
1732     const char *smallSetElementSetName;
1733     const char *mediumSetElementSetName;
1734     const char *facets;
1735
1736     assert(c->tasks);
1737     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1738
1739     r = c->tasks->u.search.resultset;
1740
1741     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1742
1743     elementSetName =
1744         ZOOM_options_get(r->options, "elementSetName");
1745     smallSetElementSetName  =
1746         ZOOM_options_get(r->options, "smallSetElementSetName");
1747     mediumSetElementSetName =
1748         ZOOM_options_get(r->options, "mediumSetElementSetName");
1749
1750     if (!smallSetElementSetName)
1751         smallSetElementSetName = elementSetName;
1752
1753     if (!mediumSetElementSetName)
1754         mediumSetElementSetName = elementSetName;
1755
1756     facets = ZOOM_options_get(r->options, "facets");
1757     if (facets) {
1758         Z_FacetList *facet_list = yaz_pqf_parse_facet_list(c->odr_out, facets);
1759         if (facet_list) {
1760             Z_OtherInformation **oi;
1761             yaz_oi_APDU(apdu, &oi);
1762             if (facet_list) {
1763                 yaz_oi_set_facetlist(oi, c->odr_out, facet_list);
1764             }
1765         }
1766     }
1767
1768     assert(r);
1769     assert(r->query);
1770
1771     /* prepare query for the search request */
1772     search_req->query = r->query->z_query;
1773     if (!search_req->query)
1774     {
1775         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1776         return zoom_complete;
1777     }
1778     if (r->query->z_query->which == Z_Query_type_1 || 
1779         r->query->z_query->which == Z_Query_type_101)
1780     {
1781         const char *cp = ZOOM_options_get(r->options, "rpnCharset");
1782         if (cp)
1783         {
1784             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
1785             if (cd)
1786             {
1787                 int r;
1788                 search_req->query = yaz_copy_Z_Query(search_req->query,
1789                                                      c->odr_out);
1790                 
1791                 r = yaz_query_charset_convert_rpnquery_check(
1792                     search_req->query->u.type_1,
1793                     c->odr_out, cd);
1794                 yaz_iconv_close(cd);
1795                 if (r)
1796                 {  /* query could not be char converted */
1797                     set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1798                     return zoom_complete;
1799                 }
1800             }
1801         }
1802     }
1803     search_req->databaseNames = r->databaseNames;
1804     search_req->num_databaseNames = r->num_databaseNames;
1805
1806     /* get syntax (no need to provide unless piggyback is in effect) */
1807     syntax = c->tasks->u.search.syntax;
1808
1809     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1810     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1811     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1812     if (lslb != -1 && ssub != -1 && mspn != -1)
1813     {
1814         /* So're a Z39.50 expert? Let's hope you don't do sort */
1815         *search_req->largeSetLowerBound = lslb;
1816         *search_req->smallSetUpperBound = ssub;
1817         *search_req->mediumSetPresentNumber = mspn;
1818     }
1819     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1820              && r->piggyback && !r->r_sort_spec && !r->schema)
1821     {
1822         /* Regular piggyback - do it unless we're going to do sort */
1823         *search_req->largeSetLowerBound = 2000000000;
1824         *search_req->smallSetUpperBound = 1;
1825         *search_req->mediumSetPresentNumber = 
1826             r->step>0 ? r->step : c->tasks->u.search.count;
1827     }
1828     else
1829     {
1830         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1831         smallSetElementSetName = 0;
1832         mediumSetElementSetName = 0;
1833         syntax = 0;
1834     }
1835     if (smallSetElementSetName && *smallSetElementSetName)
1836     {
1837         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1838             odr_malloc(c->odr_out, sizeof(*esn));
1839         
1840         esn->which = Z_ElementSetNames_generic;
1841         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1842         search_req->smallSetElementSetNames = esn;
1843     }
1844     if (mediumSetElementSetName && *mediumSetElementSetName)
1845     {
1846         Z_ElementSetNames *esn =(Z_ElementSetNames *)
1847             odr_malloc(c->odr_out, sizeof(*esn));
1848         
1849         esn->which = Z_ElementSetNames_generic;
1850         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1851         search_req->mediumSetElementSetNames = esn;
1852     }
1853     if (syntax)
1854         search_req->preferredRecordSyntax =
1855             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1856     
1857     if (!r->setname)
1858     {
1859         if (c->support_named_resultsets)
1860         {
1861             char setname[14];
1862             int ord;
1863             /* find the lowest unused ordinal so that we re-use
1864                result sets on the server. */
1865             for (ord = 1; ; ord++)
1866             {
1867 #if ZOOM_RESULT_LISTS
1868                 ZOOM_resultsets rsp;
1869                 sprintf(setname, "%d", ord);
1870                 for (rsp = c->resultsets; rsp; rsp = rsp->next)
1871                     if (rsp->resultset->setname && !strcmp(rsp->resultset->setname, setname))
1872                         break;
1873                 if (!rsp)
1874                     break;
1875 #else
1876                 ZOOM_resultset rp;
1877                 sprintf(setname, "%d", ord);
1878                 for (rp = c->resultsets; rp; rp = rp->next)
1879                     if (rp->setname && !strcmp(rp->setname, setname))
1880                         break;
1881                 if (!rp)
1882                     break;
1883 #endif
1884
1885             }
1886             r->setname = xstrdup(setname);
1887             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1888                     "set %s", c, r->setname);
1889         }
1890         else
1891         {
1892             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1893                     "default set", c);
1894             r->setname = xstrdup("default");
1895         }
1896         ZOOM_options_set(r->options, "setname", r->setname);
1897     }
1898     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1899     return send_APDU(c, apdu);
1900 }
1901
1902 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1903 {
1904     char oid_name_buf[OID_STR_MAX];
1905     const char *oid_name;
1906     char *addinfo = 0;
1907
1908     oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
1909     switch (r->which)
1910     {
1911     case Z_DefaultDiagFormat_v2Addinfo:
1912         addinfo = r->u.v2Addinfo;
1913         break;
1914     case Z_DefaultDiagFormat_v3Addinfo:
1915         addinfo = r->u.v3Addinfo;
1916         break;
1917     }
1918     xfree(c->addinfo);
1919     c->addinfo = 0;
1920     set_dset_error(c, *r->condition, oid_name, addinfo, 0);
1921 }
1922
1923 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1924 {
1925     if (p->which != Z_DiagRec_defaultFormat)
1926         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1927     else
1928         response_default_diag(c, p->u.defaultFormat);
1929 }
1930
1931 ZOOM_API(ZOOM_record)
1932     ZOOM_record_clone(ZOOM_record srec)
1933 {
1934     char *buf;
1935     int size;
1936     ODR odr_enc;
1937     ZOOM_record nrec;
1938
1939     odr_enc = odr_createmem(ODR_ENCODE);
1940     if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1941         return 0;
1942     buf = odr_getbuf(odr_enc, &size, 0);
1943     
1944     nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1945     yaz_log(log_details, "ZOOM_record create");
1946     nrec->odr = odr_createmem(ODR_DECODE);
1947 #if SHPTR
1948     nrec->record_wrbuf = 0;
1949 #else
1950     nrec->wrbuf = 0;
1951 #endif
1952     odr_setbuf(nrec->odr, buf, size, 0);
1953     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1954     
1955     nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1956     nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1957     nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1958     nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1959     nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1960     odr_destroy(odr_enc);
1961     return nrec;
1962 }
1963
1964 ZOOM_API(ZOOM_record)
1965     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1966 {
1967     const char *syntax =
1968         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1969     const char *elementSetName =
1970         ZOOM_options_get(s->options, "elementSetName");
1971
1972     return record_cache_lookup(s, pos, syntax, elementSetName);
1973 }
1974
1975 ZOOM_API(ZOOM_record)
1976     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1977 {
1978     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1979
1980     if (!rec)
1981     {
1982         /*
1983          * MIKE: I think force_sync should always be zero, but I don't
1984          * want to make this change until I get the go-ahead from
1985          * Adam, in case something depends on the old synchronous
1986          * behaviour.
1987          */
1988         int force_sync = 1;
1989         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1990         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1991         rec = ZOOM_resultset_record_immediate(r, pos);
1992     }
1993     return rec;
1994 }
1995
1996 ZOOM_API(void)
1997     ZOOM_record_destroy(ZOOM_record rec)
1998 {
1999     ZOOM_record_release(rec);
2000     yaz_log(log_details, "ZOOM_record destroy");
2001     xfree(rec);
2002 }
2003
2004
2005 static yaz_iconv_t iconv_create_charset(const char *record_charset)
2006 {
2007     char to[40];
2008     char from[40];
2009     yaz_iconv_t cd = 0;
2010
2011     *from = '\0';
2012     strcpy(to, "UTF-8");
2013     if (record_charset && *record_charset)
2014     {
2015         /* Use "from,to" or just "from" */
2016         const char *cp = strchr(record_charset, ',');
2017         size_t clen = strlen(record_charset);
2018         if (cp && cp[1])
2019         {
2020             strncpy( to, cp+1, sizeof(to)-1);
2021             to[sizeof(to)-1] = '\0';
2022             clen = cp - record_charset;
2023         }
2024         if (clen > sizeof(from)-1)
2025             clen = sizeof(from)-1;
2026         
2027         if (clen)
2028             strncpy(from, record_charset, clen);
2029         from[clen] = '\0';
2030     }
2031     if (*from && *to)
2032         cd = yaz_iconv_open(to, from);
2033     return cd;
2034 }
2035
2036 static const char *return_marc_record(WRBUF wrbuf,
2037                                       int marc_type,
2038                                       int *len,
2039                                       const char *buf, int sz,
2040                                       const char *record_charset)
2041 {
2042     yaz_iconv_t cd = iconv_create_charset(record_charset);
2043     yaz_marc_t mt = yaz_marc_create();
2044     const char *ret_string = 0;
2045
2046     if (cd)
2047         yaz_marc_iconv(mt, cd);
2048     yaz_marc_xml(mt, marc_type);
2049     if (yaz_marc_decode_wrbuf(mt, buf, sz, wrbuf) > 0)
2050     {
2051         if (len)
2052             *len = wrbuf_len(wrbuf);
2053         ret_string = wrbuf_cstr(wrbuf);
2054     }
2055     yaz_marc_destroy(mt);
2056     if (cd)
2057         yaz_iconv_close(cd);
2058     return ret_string;
2059 }
2060
2061 static const char *return_opac_record(WRBUF wrbuf,
2062                                       int marc_type,
2063                                       int *len,
2064                                       Z_OPACRecord *opac_rec,
2065                                       const char *record_charset)
2066 {
2067     yaz_iconv_t cd = iconv_create_charset(record_charset);
2068     yaz_marc_t mt = yaz_marc_create();
2069
2070     if (cd)
2071         yaz_marc_iconv(mt, cd);
2072     yaz_marc_xml(mt, marc_type);
2073
2074     yaz_opac_decode_wrbuf(mt, opac_rec, wrbuf);
2075     yaz_marc_destroy(mt);
2076
2077     if (cd)
2078         yaz_iconv_close(cd);
2079     if (len)
2080         *len = wrbuf_len(wrbuf);
2081     return wrbuf_cstr(wrbuf);
2082 }
2083
2084 static const char *return_string_record(WRBUF wrbuf,
2085                                         int *len,
2086                                         const char *buf, int sz,
2087                                         const char *record_charset)
2088 {
2089     yaz_iconv_t cd = iconv_create_charset(record_charset);
2090
2091     if (cd)
2092     {
2093         wrbuf_iconv_write(wrbuf, cd, buf, sz);
2094         wrbuf_iconv_reset(wrbuf, cd);
2095
2096         buf = wrbuf_cstr(wrbuf);
2097         sz = wrbuf_len(wrbuf);
2098         yaz_iconv_close(cd);
2099     }
2100     if (len)
2101         *len = sz;
2102     return buf;
2103 }
2104
2105 static const char *return_record_wrbuf(WRBUF wrbuf, int *len,
2106                                        Z_NamePlusRecord *npr,
2107                                        int marctype, const char *charset)
2108 {
2109     Z_External *r = (Z_External *) npr->u.databaseRecord;
2110     const Odr_oid *oid = r->direct_reference;
2111
2112     wrbuf_rewind(wrbuf);
2113     /* render bibliographic record .. */
2114     if (r->which == Z_External_OPAC)
2115     {
2116         return return_opac_record(wrbuf, marctype, len,
2117                                   r->u.opac, charset);
2118     }
2119     if (r->which == Z_External_sutrs)
2120         return return_string_record(wrbuf, len,
2121                                     (char*) r->u.sutrs->buf,
2122                                     r->u.sutrs->len,
2123                                     charset);
2124     else if (r->which == Z_External_octet)
2125     {
2126         if (yaz_oid_is_iso2709(oid))
2127         {
2128             const char *ret_buf = return_marc_record(
2129                 wrbuf, marctype, len,
2130                 (const char *) r->u.octet_aligned->buf,
2131                 r->u.octet_aligned->len,
2132                 charset);
2133             if (ret_buf)
2134                 return ret_buf;
2135             /* bad ISO2709. Return fail unless raw (ISO2709) is wanted */
2136             if (marctype != YAZ_MARC_ISO2709)
2137                 return 0;
2138         }
2139         return return_string_record(wrbuf, len,
2140                                     (const char *) r->u.octet_aligned->buf,
2141                                     r->u.octet_aligned->len,
2142                                     charset);
2143     }
2144     else if (r->which == Z_External_grs1)
2145     {
2146         yaz_display_grs1(wrbuf, r->u.grs1, 0);
2147         return return_string_record(wrbuf, len,
2148                                     wrbuf_buf(wrbuf),
2149                                     wrbuf_len(wrbuf),
2150                                     charset);
2151     }
2152     return 0;
2153 }
2154     
2155 ZOOM_API(int)
2156     ZOOM_record_error(ZOOM_record rec, const char **cp,
2157                       const char **addinfo, const char **diagset)
2158 {
2159     Z_NamePlusRecord *npr;
2160     
2161     if (!rec)
2162         return 0;
2163
2164     npr = rec->npr;
2165     if (rec->diag_uri)
2166     {
2167         if (cp)
2168             *cp = rec->diag_message;
2169         if (addinfo)
2170             *addinfo = rec->diag_details;
2171         if (diagset)
2172             *diagset = rec->diag_set;
2173         return uri_to_code(rec->diag_uri);
2174     }
2175     if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
2176     {
2177         Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
2178         int error = YAZ_BIB1_UNSPECIFIED_ERROR;
2179         const char *add = 0;
2180
2181         if (diag_rec->which == Z_DiagRec_defaultFormat)
2182         {
2183             Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
2184             oid_class oclass;
2185     
2186             error = *ddf->condition;
2187             switch (ddf->which)
2188             {
2189             case Z_DefaultDiagFormat_v2Addinfo:
2190                 add = ddf->u.v2Addinfo;
2191                 break;
2192             case Z_DefaultDiagFormat_v3Addinfo:
2193                 add = ddf->u.v3Addinfo;
2194                 break;
2195             }
2196             if (diagset)
2197                 *diagset =
2198                     yaz_oid_to_string(yaz_oid_std(),
2199                                       ddf->diagnosticSetId, &oclass);
2200         }
2201         else
2202         {
2203             if (diagset)
2204                 *diagset = "Bib-1";
2205         }
2206         if (addinfo)
2207             *addinfo = add ? add : "";
2208         if (cp)
2209             *cp = diagbib1_str(error);
2210         return error;
2211     }
2212     return 0;
2213 }
2214
2215 static const char *get_record_format(WRBUF wrbuf, int *len,
2216                                      Z_NamePlusRecord *npr,
2217                                      int marctype, const char *charset,
2218                                      const char *format)
2219 {
2220     const char *res = return_record_wrbuf(wrbuf, len, npr, marctype, charset);
2221 #if YAZ_HAVE_XML2
2222     if (*format == '1' && len)
2223     {
2224         /* try to XML format res */
2225         xmlDocPtr doc;
2226         xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
2227         doc = xmlParseMemory(res, *len);
2228         if (doc)
2229         {
2230             xmlChar *xml_mem;
2231             int xml_size;
2232             xmlDocDumpFormatMemory(doc, &xml_mem, &xml_size, 1);
2233             wrbuf_rewind(wrbuf);
2234             wrbuf_write(wrbuf, (const char *) xml_mem, xml_size);
2235             xmlFree(xml_mem);
2236             xmlFreeDoc(doc);
2237             res = wrbuf_cstr(wrbuf);
2238             *len = wrbuf_len(wrbuf);
2239         } 
2240     }
2241 #endif
2242     return res;
2243 }
2244
2245
2246 static const char *npr_format(Z_NamePlusRecord *npr, const char *schema,
2247                               WRBUF wrbuf,
2248                               const char *type_spec, int *len)
2249 {
2250     size_t i;
2251     char type[40];
2252     char charset[40];
2253     char format[3];
2254     const char *cp = type_spec;
2255
2256     for (i = 0; cp[i] && cp[i] != ';' && cp[i] != ' ' && i < sizeof(type)-1;
2257          i++)
2258         type[i] = cp[i];
2259     type[i] = '\0';
2260     charset[0] = '\0';
2261     format[0] = '\0';
2262     while (1)
2263     {
2264         while (cp[i] == ' ')
2265             i++;
2266         if (cp[i] != ';')
2267             break;
2268         i++;
2269         while (cp[i] == ' ')
2270             i++;
2271         if (!strncmp(cp + i, "charset=", 8))
2272         {
2273             size_t j = 0;
2274             i = i + 8; /* skip charset= */
2275             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2276             {
2277                 if (j < sizeof(charset)-1)
2278                     charset[j++] = cp[i];
2279             }
2280             charset[j] = '\0';
2281         }
2282         else if (!strncmp(cp + i, "format=", 7))
2283         {
2284             size_t j = 0; 
2285             i = i + 7;
2286             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2287             {
2288                 if (j < sizeof(format)-1)
2289                     format[j++] = cp[i];
2290             }
2291             format[j] = '\0';
2292         } 
2293     }
2294     if (!strcmp(type, "database"))
2295     {
2296         if (len)
2297             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2298         return npr->databaseName;
2299     }
2300     else if (!strcmp(type, "schema"))
2301     {
2302         if (len)
2303             *len = schema ? strlen(schema) : 0;
2304         return schema;
2305     }
2306     else if (!strcmp(type, "syntax"))
2307     {
2308         const char *desc = 0;   
2309         if (npr->which == Z_NamePlusRecord_databaseRecord)
2310         {
2311             Z_External *r = (Z_External *) npr->u.databaseRecord;
2312             desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2313         }
2314         if (!desc)
2315             desc = "none";
2316         if (len)
2317             *len = strlen(desc);
2318         return desc;
2319     }
2320     if (npr->which != Z_NamePlusRecord_databaseRecord)
2321         return 0;
2322
2323     /* from now on - we have a database record .. */
2324     if (!strcmp(type, "render"))
2325     {
2326         return get_record_format(wrbuf, len, npr, YAZ_MARC_LINE, charset, format);
2327     }
2328     else if (!strcmp(type, "xml"))
2329     {
2330         return get_record_format(wrbuf, len, npr, YAZ_MARC_MARCXML, charset,
2331                                  format);
2332     }
2333     else if (!strcmp(type, "txml"))
2334     {
2335         return get_record_format(wrbuf, len, npr, YAZ_MARC_TURBOMARC, charset,
2336                                  format);
2337     }
2338     else if (!strcmp(type, "raw"))
2339     {
2340         return get_record_format(wrbuf, len, npr, YAZ_MARC_ISO2709, charset,
2341             format);
2342     }
2343     else if (!strcmp(type, "ext"))
2344     {
2345         if (len) *len = -1;
2346         return (const char *) npr->u.databaseRecord;
2347     }
2348     else if (!strcmp(type, "opac"))
2349     {
2350         if (npr->u.databaseRecord->which == Z_External_OPAC)
2351             return get_record_format(wrbuf, len, npr, YAZ_MARC_MARCXML, charset,
2352                                      format);
2353     }
2354     return 0;
2355 }
2356
2357 ZOOM_API(const char *)
2358     ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2359 {
2360     WRBUF wrbuf;
2361     
2362     if (len)
2363         *len = 0; /* default return */
2364         
2365     if (!rec || !rec->npr)
2366         return 0;
2367
2368 #if SHPTR
2369     if (!rec->record_wrbuf)
2370     {
2371         WRBUF w = wrbuf_alloc();
2372         YAZ_SHPTR_INIT(rec->record_wrbuf, w);
2373     }
2374     wrbuf = rec->record_wrbuf->ptr;
2375 #else
2376     if (!rec->wrbuf)
2377         rec->wrbuf = wrbuf_alloc();
2378     wrbuf = rec->wrbuf;
2379 #endif
2380     return npr_format(rec->npr, rec->schema, wrbuf, type_spec, len);
2381 }
2382
2383 static int strcmp_null(const char *v1, const char *v2)
2384 {
2385     if (!v1 && !v2)
2386         return 0;
2387     if (!v1 || !v2)
2388         return -1;
2389     return strcmp(v1, v2);
2390 }
2391
2392 static size_t record_hash(int pos)
2393 {
2394     if (pos < 0)
2395         pos = 0;
2396     return pos % RECORD_HASH_SIZE;
2397 }
2398
2399 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr, 
2400                              int pos,
2401                              const char *syntax, const char *elementSetName,
2402                              const char *schema,
2403                              Z_SRW_diagnostic *diag)
2404 {
2405     ZOOM_record_cache rc = 0;
2406     
2407     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2408     ZOOM_connection_put_event(r->connection, event);
2409
2410     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2411     {
2412         if (pos == rc->pos 
2413             && strcmp_null(r->schema, rc->schema) == 0
2414             && strcmp_null(elementSetName,rc->elementSetName) == 0
2415             && strcmp_null(syntax, rc->syntax) == 0)
2416             break;
2417     }
2418     if (!rc)
2419     {
2420         rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2421         rc->rec.odr = 0;
2422 #if SHPTR
2423         YAZ_SHPTR_INC(r->record_wrbuf);
2424         rc->rec.record_wrbuf = r->record_wrbuf;
2425 #else
2426         rc->rec.wrbuf = 0;
2427 #endif
2428         rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2429         
2430         rc->syntax = odr_strdup_null(r->odr, syntax);
2431         
2432         rc->schema = odr_strdup_null(r->odr, r->schema);
2433
2434         rc->pos = pos;
2435         rc->next = r->record_hash[record_hash(pos)];
2436         r->record_hash[record_hash(pos)] = rc;
2437     }
2438     rc->rec.npr = npr;
2439     rc->rec.schema = odr_strdup_null(r->odr, schema);
2440     rc->rec.diag_set = 0;
2441     rc->rec.diag_uri = 0;
2442     rc->rec.diag_message = 0;
2443     rc->rec.diag_details = 0;
2444     if (diag)
2445     {
2446         if (diag->uri)
2447         {
2448             char *cp;
2449             rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2450             if ((cp = strrchr(rc->rec.diag_set, '/')))
2451                 *cp = '\0';
2452             rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2453         }
2454         rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);            
2455         rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2456     }
2457 }
2458
2459 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2460                                        const char *syntax,
2461                                        const char *elementSetName)
2462 {
2463     ZOOM_record_cache rc;
2464     
2465     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2466     {
2467         if (pos == rc->pos)
2468         {
2469             if (strcmp_null(r->schema, rc->schema))
2470                 continue;
2471             if (strcmp_null(elementSetName,rc->elementSetName))
2472                 continue;
2473             if (strcmp_null(syntax, rc->syntax))
2474                 continue;
2475             return &rc->rec;
2476         }
2477     }
2478     return 0;
2479 }
2480                                              
2481 static void handle_records(ZOOM_connection c, Z_Records *sr,
2482                            int present_phase)
2483 {
2484     ZOOM_resultset resultset;
2485     int *start, *count;
2486     const char *syntax = 0, *elementSetName = 0;
2487
2488     if (!c->tasks)
2489         return ;
2490     switch (c->tasks->which)
2491     {
2492     case ZOOM_TASK_SEARCH:
2493         resultset = c->tasks->u.search.resultset;
2494         start = &c->tasks->u.search.start;
2495         count = &c->tasks->u.search.count;
2496         syntax = c->tasks->u.search.syntax;
2497         elementSetName = c->tasks->u.search.elementSetName;
2498         break;
2499     case ZOOM_TASK_RETRIEVE:
2500         resultset = c->tasks->u.retrieve.resultset;        
2501         start = &c->tasks->u.retrieve.start;
2502         count = &c->tasks->u.retrieve.count;
2503         syntax = c->tasks->u.retrieve.syntax;
2504         elementSetName = c->tasks->u.retrieve.elementSetName;
2505         break;
2506     default:
2507         return;
2508     }
2509     if (sr && sr->which == Z_Records_NSD)
2510         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2511     else if (sr && sr->which == Z_Records_multipleNSD)
2512     {
2513         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2514             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2515         else
2516             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2517     }
2518     else 
2519     {
2520         if (*count + *start > resultset->size)
2521             *count = resultset->size - *start;
2522         if (*count < 0)
2523             *count = 0;
2524         if (sr && sr->which == Z_Records_DBOSD)
2525         {
2526             int i;
2527             NMEM nmem = odr_extract_mem(c->odr_in);
2528             Z_NamePlusRecordList *p =
2529                 sr->u.databaseOrSurDiagnostics;
2530             for (i = 0; i<p->num_records; i++)
2531             {
2532                 record_cache_add(resultset, p->records[i], i + *start,
2533                                  syntax, elementSetName,
2534                                  elementSetName, 0);
2535             }
2536             *count -= i;
2537             if (*count < 0)
2538                 *count = 0;
2539             *start += i;
2540             yaz_log(log_details, 
2541                     "handle_records resultset=%p start=%d count=%d",
2542                     resultset, *start, *count);
2543
2544             /* transfer our response to search_nmem .. we need it later */
2545             nmem_transfer(odr_getmem(resultset->odr), nmem);
2546             nmem_destroy(nmem);
2547             if (present_phase && p->num_records == 0)
2548             {
2549                 /* present response and we didn't get any records! */
2550                 Z_NamePlusRecord *myrec = 
2551                     zget_surrogateDiagRec(
2552                         resultset->odr, 0, 
2553                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2554                         "ZOOM C generated. Present phase and no records");
2555                 record_cache_add(resultset, myrec, *start,
2556                                  syntax, elementSetName, 0, 0);
2557             }
2558         }
2559         else if (present_phase)
2560         {
2561             /* present response and we didn't get any records! */
2562             Z_NamePlusRecord *myrec = 
2563                 zget_surrogateDiagRec(
2564                     resultset->odr, 0,
2565                     YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2566                     "ZOOM C generated: Present response and no records");
2567             record_cache_add(resultset, myrec, *start, syntax, elementSetName,
2568                              0, 0);
2569         }
2570     }
2571 }
2572
2573 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2574 {
2575     handle_records(c, pr->records, 1);
2576 }
2577
2578 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2579                                        Z_Term *term)
2580 {
2581     switch (term->which)
2582     {
2583     case Z_Term_general:
2584         ZOOM_options_setl(opt, name,
2585                           (const char *)(term->u.general->buf), 
2586                           term->u.general->len);
2587         break;
2588     case Z_Term_characterString:
2589         ZOOM_options_set(opt, name, term->u.characterString);
2590         break;
2591     case Z_Term_numeric:
2592         ZOOM_options_set_int(opt, name, *term->u.numeric);
2593         break;
2594     }
2595 }
2596
2597 static void handle_queryExpression(ZOOM_options opt, const char *name,
2598                                    Z_QueryExpression *exp)
2599 {
2600     char opt_name[80];
2601     
2602     switch (exp->which)
2603     {
2604     case Z_QueryExpression_term:
2605         if (exp->u.term && exp->u.term->queryTerm)
2606         {
2607             sprintf(opt_name, "%s.term", name);
2608             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2609         }
2610         break;
2611     case Z_QueryExpression_query:
2612         break;
2613     }
2614 }
2615
2616 static void handle_search_result(ZOOM_connection c, ZOOM_resultset resultset,
2617                                 Z_OtherInformation *o)
2618 {
2619     int i;
2620     for (i = 0; o && i < o->num_elements; i++)
2621     {
2622         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2623         {
2624             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2625             
2626             if (ext->which == Z_External_searchResult1)
2627             {
2628                 int j;
2629                 Z_SearchInfoReport *sr = ext->u.searchResult1;
2630                 
2631                 if (sr->num)
2632                     ZOOM_options_set_int(
2633                         resultset->options, "searchresult.size", sr->num);
2634
2635                 for (j = 0; j < sr->num; j++)
2636                 {
2637                     Z_SearchInfoReport_s *ent =
2638                         ext->u.searchResult1->elements[j];
2639                     char pref[80];
2640                     
2641                     sprintf(pref, "searchresult.%d", j);
2642
2643                     if (ent->subqueryId)
2644                     {
2645                         char opt_name[80];
2646                         sprintf(opt_name, "%s.id", pref);
2647                         ZOOM_options_set(resultset->options, opt_name,
2648                                          ent->subqueryId);
2649                     }
2650                     if (ent->subqueryExpression)
2651                     {
2652                         char opt_name[80];
2653                         sprintf(opt_name, "%s.subquery", pref);
2654                         handle_queryExpression(resultset->options, opt_name,
2655                                                ent->subqueryExpression);
2656                     }
2657                     if (ent->subqueryInterpretation)
2658                     {
2659                         char opt_name[80];
2660                         sprintf(opt_name, "%s.interpretation", pref);
2661                         handle_queryExpression(resultset->options, opt_name,
2662                                                ent->subqueryInterpretation);
2663                     }
2664                     if (ent->subqueryRecommendation)
2665                     {
2666                         char opt_name[80];
2667                         sprintf(opt_name, "%s.recommendation", pref);
2668                         handle_queryExpression(resultset->options, opt_name,
2669                                                ent->subqueryRecommendation);
2670                     }
2671                     if (ent->subqueryCount)
2672                     {
2673                         char opt_name[80];
2674                         sprintf(opt_name, "%s.count", pref);
2675                         ZOOM_options_set_int(resultset->options, opt_name,
2676                                              *ent->subqueryCount);
2677                     }                                             
2678                 }
2679             }
2680         }
2681     }
2682 }
2683
2684 static char *get_term_cstr(ODR odr, Z_Term *term) {
2685
2686     switch (term->which) {
2687     case Z_Term_general:
2688             return odr_strdupn(odr, (const char *) term->u.general->buf, (size_t) term->u.general->len);
2689         break;
2690     case Z_Term_characterString:
2691         return odr_strdup(odr, term->u.characterString);
2692     }
2693     return 0;
2694 }
2695
2696 static ZOOM_facet_field get_zoom_facet_field(ODR odr, Z_FacetField *facet) {
2697     int term_index;
2698     struct yaz_facet_attr attr_values;
2699     ZOOM_facet_field facet_field = odr_malloc(odr, sizeof(*facet_field));
2700     yaz_facet_attr_init(&attr_values);
2701     yaz_facet_attr_get_z_attributes(facet->attributes, &attr_values);
2702     facet_field->facet_name = odr_strdup(odr, attr_values.useattr);
2703     facet_field->num_terms = facet->num_terms;
2704     yaz_log(YLOG_DEBUG, "ZOOM_facet_field %s %d terms %d", attr_values.useattr, attr_values.limit, facet->num_terms);
2705     facet_field->facet_terms = odr_malloc(odr, facet_field->num_terms * sizeof(*facet_field->facet_terms));
2706     for (term_index = 0 ; term_index < facet->num_terms; term_index++) {
2707         Z_FacetTerm *facetTerm = facet->terms[term_index];
2708         facet_field->facet_terms[term_index].frequency = *facetTerm->count;
2709         facet_field->facet_terms[term_index].term = get_term_cstr(odr, facetTerm->term);
2710         yaz_log(YLOG_DEBUG, "    term[%d] %s %d",
2711                 term_index, facet_field->facet_terms[term_index].term, facet_field->facet_terms[term_index].frequency);
2712     }
2713     return facet_field;
2714 }
2715
2716 static void handle_facet_result(ZOOM_connection c, ZOOM_resultset r,
2717                                 Z_OtherInformation *o)
2718 {
2719     int i;
2720     for (i = 0; o && i < o->num_elements; i++)
2721     {
2722         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2723         {
2724             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2725             if (ext->which == Z_External_userFacets)
2726             {
2727                 int j;
2728                 Z_FacetList *fl = ext->u.facetList;
2729                 r->num_facets   = fl->num;
2730                 yaz_log(YLOG_DEBUG, "Facets found: %d", fl->num);
2731                 r->facets       =  odr_malloc(r->odr, r->num_facets * sizeof(*r->facets));
2732                 r->facets_names =  odr_malloc(r->odr, r->num_facets * sizeof(*r->facets_names));
2733                 for (j = 0; j < fl->num; j++)
2734                 {
2735                     r->facets[j] = get_zoom_facet_field(r->odr, fl->elements[j]);
2736                     if (!r->facets[j])
2737                         yaz_log(YLOG_DEBUG, "Facet field missing on index %d !", j);
2738                     r->facets_names[j] = (char *) ZOOM_facet_field_name(r->facets[j]);
2739                 }
2740             }
2741         }
2742     }
2743 }
2744
2745
2746 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2747 {
2748     ZOOM_resultset resultset;
2749     ZOOM_Event event;
2750
2751     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2752         return ;
2753
2754     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2755     ZOOM_connection_put_event(c, event);
2756
2757     resultset = c->tasks->u.search.resultset;
2758
2759     if (sr->resultSetStatus)
2760     {
2761         ZOOM_options_set_int(resultset->options, "resultSetStatus",
2762                              *sr->resultSetStatus);
2763     }
2764     if (sr->presentStatus)
2765     {
2766         ZOOM_options_set_int(resultset->options, "presentStatus",
2767                              *sr->presentStatus);
2768     }
2769     handle_search_result(c, resultset, sr->additionalSearchInfo);
2770
2771     handle_facet_result(c, resultset, sr->additionalSearchInfo);
2772
2773     resultset->size = *sr->resultCount;
2774     handle_records(c, sr->records, 0);
2775 }
2776
2777 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2778 {
2779     if (res->diagnostics && res->num_diagnostics > 0)
2780         response_diag(c, res->diagnostics[0]);
2781 }
2782
2783 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2784 {
2785     NMEM nmem = odr_extract_mem(c->odr_in);
2786     ZOOM_scanset scan;
2787
2788     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2789         return 0;
2790     scan = c->tasks->u.scan.scan;
2791
2792     if (res->entries && res->entries->nonsurrogateDiagnostics)
2793         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2794     scan->scan_response = res;
2795     scan->srw_scan_response = 0;
2796     nmem_transfer(odr_getmem(scan->odr), nmem);
2797     if (res->stepSize)
2798         ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2799     if (res->positionOfTerm)
2800         ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2801     if (res->scanStatus)
2802         ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2803     if (res->numberOfEntriesReturned)
2804         ZOOM_options_set_int(scan->options, "number",
2805                              *res->numberOfEntriesReturned);
2806     nmem_destroy(nmem);
2807     return 1;
2808 }
2809
2810 static zoom_ret send_sort(ZOOM_connection c,
2811                           ZOOM_resultset resultset)
2812 {
2813     if (c->error)
2814         resultset->r_sort_spec = 0;
2815     if (resultset->r_sort_spec)
2816     {
2817         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2818         Z_SortRequest *req = apdu->u.sortRequest;
2819         
2820         req->num_inputResultSetNames = 1;
2821         req->inputResultSetNames = (Z_InternationalString **)
2822             odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2823         req->inputResultSetNames[0] =
2824             odr_strdup(c->odr_out, resultset->setname);
2825         req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2826         req->sortSequence = resultset->r_sort_spec;
2827         resultset->r_sort_spec = 0;
2828         return send_APDU(c, apdu);
2829     }
2830     return zoom_complete;
2831 }
2832
2833 static zoom_ret send_present(ZOOM_connection c)
2834 {
2835     Z_APDU *apdu = 0;
2836     Z_PresentRequest *req = 0;
2837     int i = 0;
2838     const char *syntax = 0;
2839     const char *elementSetName = 0;
2840     ZOOM_resultset  resultset;
2841     int *start, *count;
2842
2843     if (!c->tasks)
2844     {
2845         yaz_log(log_details, "%p send_present no tasks", c);
2846         return zoom_complete;
2847     }
2848     
2849     switch (c->tasks->which)
2850     {
2851     case ZOOM_TASK_SEARCH:
2852         resultset = c->tasks->u.search.resultset;
2853         start = &c->tasks->u.search.start;
2854         count = &c->tasks->u.search.count;
2855         syntax = c->tasks->u.search.syntax;
2856         elementSetName = c->tasks->u.search.elementSetName;
2857         break;
2858     case ZOOM_TASK_RETRIEVE:
2859         resultset = c->tasks->u.retrieve.resultset;
2860         start = &c->tasks->u.retrieve.start;
2861         count = &c->tasks->u.retrieve.count;
2862         syntax = c->tasks->u.retrieve.syntax;
2863         elementSetName = c->tasks->u.retrieve.elementSetName;
2864         break;
2865     default:
2866         return zoom_complete;
2867     }
2868     yaz_log(log_details, "%p send_present start=%d count=%d",
2869             c, *start, *count);
2870
2871     if (*start < 0 || *count < 0 || *start + *count > resultset->size)
2872     {
2873         set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
2874                        "", 0);
2875     }
2876     if (c->error)                  /* don't continue on error */
2877         return zoom_complete;
2878     yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2879             resultset, *start, *count);
2880
2881     for (i = 0; i < *count; i++)
2882     {
2883         ZOOM_record rec =
2884             record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2885         if (!rec)
2886             break;
2887         else
2888         {
2889             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2890             ZOOM_connection_put_event(c, event);
2891         }
2892     }
2893     *start += i;
2894     *count -= i;
2895
2896     if (*count == 0)
2897     {
2898         yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2899         return zoom_complete;
2900     }
2901
2902     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2903     req = apdu->u.presentRequest;
2904
2905     if (i)
2906         yaz_log(log_details, "%p send_present skip=%d", c, i);
2907
2908     *req->resultSetStartPoint = *start + 1;
2909
2910     if (resultset->step > 0 && resultset->step < *count)
2911         *req->numberOfRecordsRequested = resultset->step;
2912     else
2913         *req->numberOfRecordsRequested = *count;
2914     
2915     if (*req->numberOfRecordsRequested + *start > resultset->size)
2916         *req->numberOfRecordsRequested = resultset->size - *start;
2917     assert(*req->numberOfRecordsRequested > 0);
2918
2919     if (syntax && *syntax)
2920         req->preferredRecordSyntax =
2921             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
2922
2923     if (resultset->schema && *resultset->schema)
2924     {
2925         Z_RecordComposition *compo = (Z_RecordComposition *)
2926             odr_malloc(c->odr_out, sizeof(*compo));
2927
2928         req->recordComposition = compo;
2929         compo->which = Z_RecordComp_complex;
2930         compo->u.complex = (Z_CompSpec *)
2931             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2932         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2933             odr_malloc(c->odr_out, sizeof(bool_t));
2934         *compo->u.complex->selectAlternativeSyntax = 0;
2935
2936         compo->u.complex->generic = (Z_Specification *)
2937             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2938
2939         compo->u.complex->generic->which = Z_Schema_oid;
2940         compo->u.complex->generic->schema.oid = (Odr_oid *)
2941             zoom_yaz_str_to_z3950oid (c, CLASS_SCHEMA, resultset->schema);
2942
2943         if (!compo->u.complex->generic->schema.oid)
2944         {
2945             /* OID wasn't a schema! Try record syntax instead. */
2946
2947             compo->u.complex->generic->schema.oid = (Odr_oid *)
2948                 zoom_yaz_str_to_z3950oid (c, CLASS_RECSYN, resultset->schema);
2949         }
2950         if (elementSetName && *elementSetName)
2951         {
2952             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2953                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2954             compo->u.complex->generic->elementSpec->which =
2955                 Z_ElementSpec_elementSetName;
2956             compo->u.complex->generic->elementSpec->u.elementSetName =
2957                 odr_strdup(c->odr_out, elementSetName);
2958         }
2959         else
2960             compo->u.complex->generic->elementSpec = 0;
2961         compo->u.complex->num_dbSpecific = 0;
2962         compo->u.complex->dbSpecific = 0;
2963         compo->u.complex->num_recordSyntax = 0;
2964         compo->u.complex->recordSyntax = 0;
2965     }
2966     else if (elementSetName && *elementSetName)
2967     {
2968         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2969             odr_malloc(c->odr_out, sizeof(*esn));
2970         Z_RecordComposition *compo = (Z_RecordComposition *)
2971             odr_malloc(c->odr_out, sizeof(*compo));
2972         
2973         esn->which = Z_ElementSetNames_generic;
2974         esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2975         compo->which = Z_RecordComp_simple;
2976         compo->u.simple = esn;
2977         req->recordComposition = compo;
2978     }
2979     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2980     return send_APDU(c, apdu);
2981 }
2982
2983 ZOOM_API(ZOOM_scanset)
2984     ZOOM_connection_scan(ZOOM_connection c, const char *start)
2985 {
2986     ZOOM_scanset s;
2987     ZOOM_query q = ZOOM_query_create();
2988
2989     ZOOM_query_prefix(q, start);
2990
2991     s = ZOOM_connection_scan1(c, q);
2992     ZOOM_query_destroy(q);
2993     return s;
2994
2995 }
2996
2997 ZOOM_API(ZOOM_scanset)
2998     ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
2999 {
3000     ZOOM_scanset scan = 0;
3001
3002     if (!q->z_query)
3003         return 0;
3004     scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
3005     scan->connection = c;
3006     scan->odr = odr_createmem(ODR_DECODE);
3007     scan->options = ZOOM_options_create_with_parent(c->options);
3008     scan->refcount = 1;
3009     scan->scan_response = 0;
3010     scan->srw_scan_response = 0;
3011
3012     scan->query = q;
3013     (q->refcount)++;
3014     scan->databaseNames = set_DatabaseNames(c, c->options,
3015                                             &scan->num_databaseNames,
3016                                             scan->odr);
3017
3018     if (1)
3019     {
3020         ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
3021         task->u.scan.scan = scan;
3022         
3023         (scan->refcount)++;
3024         if (!c->async)
3025         {
3026             while (ZOOM_event(1, &c))
3027                 ;
3028         }
3029     }
3030     return scan;
3031 }
3032
3033 ZOOM_API(void)
3034     ZOOM_scanset_destroy(ZOOM_scanset scan)
3035 {
3036     if (!scan)
3037         return;
3038     (scan->refcount)--;
3039     if (scan->refcount == 0)
3040     {
3041         ZOOM_query_destroy(scan->query);
3042
3043         odr_destroy(scan->odr);
3044         
3045         ZOOM_options_destroy(scan->options);
3046         xfree(scan);
3047     }
3048 }
3049
3050 static zoom_ret send_package(ZOOM_connection c)
3051 {
3052     ZOOM_Event event;
3053
3054     yaz_log(log_details, "%p send_package", c);
3055     if (!c->tasks)
3056         return zoom_complete;
3057     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
3058     
3059     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
3060     ZOOM_connection_put_event(c, event);
3061     
3062     c->buf_out = c->tasks->u.package->buf_out;
3063     c->len_out = c->tasks->u.package->len_out;
3064
3065     return do_write(c);
3066 }
3067
3068 static zoom_ret ZOOM_connection_send_scan(ZOOM_connection c)
3069 {
3070     ZOOM_scanset scan;
3071     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
3072     Z_ScanRequest *req = apdu->u.scanRequest;
3073
3074     yaz_log(log_details, "%p send_scan", c);
3075     if (!c->tasks)
3076         return zoom_complete;
3077     assert (c->tasks->which == ZOOM_TASK_SCAN);
3078     scan = c->tasks->u.scan.scan;
3079
3080     /* Z39.50 scan can only carry RPN */
3081     if (scan->query->z_query->which == Z_Query_type_1 ||
3082         scan->query->z_query->which == Z_Query_type_101)
3083     {
3084         Z_RPNQuery *rpn = scan->query->z_query->u.type_1;
3085         const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
3086         if (cp)
3087         {
3088             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
3089             if (cd)
3090             {
3091                 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
3092
3093                 yaz_query_charset_convert_rpnquery(
3094                     rpn, c->odr_out, cd);
3095                 yaz_iconv_close(cd);
3096             }
3097         }
3098         req->attributeSet = rpn->attributeSetId;
3099         if (!req->attributeSet)
3100             req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
3101         if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
3102             rpn->RPNStructure->u.simple->which == Z_Operand_APT)
3103         {
3104             req->termListAndStartPoint =
3105                 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
3106         }
3107         else
3108         {
3109             set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
3110             return zoom_complete;
3111         }
3112     }
3113     else
3114     {
3115         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
3116         return zoom_complete;
3117     }
3118
3119     *req->numberOfTermsRequested =
3120         ZOOM_options_get_int(scan->options, "number", 20);
3121
3122     req->preferredPositionInResponse =
3123         odr_intdup(c->odr_out,
3124                    ZOOM_options_get_int(scan->options, "position", 1));
3125
3126     req->stepSize =
3127         odr_intdup(c->odr_out,
3128                    ZOOM_options_get_int(scan->options, "stepSize", 0));
3129     
3130     req->databaseNames = scan->databaseNames;
3131     req->num_databaseNames = scan->num_databaseNames;
3132
3133     return send_APDU(c, apdu);
3134 }
3135
3136 #if YAZ_HAVE_XML2
3137 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3138 {
3139     ZOOM_scanset scan;
3140     Z_SRW_PDU *sr = 0;
3141     const char *option_val = 0;
3142
3143     if (!c->tasks)
3144         return zoom_complete;
3145     assert (c->tasks->which == ZOOM_TASK_SCAN);
3146     scan = c->tasks->u.scan.scan;
3147         
3148     sr = ZOOM_srw_get_pdu(c, Z_SRW_scan_request);
3149
3150     /* SRU scan can only carry CQL and PQF */
3151     if (scan->query->z_query->which == Z_Query_type_104)
3152     {
3153         sr->u.scan_request->query_type = Z_SRW_query_type_cql;
3154         sr->u.scan_request->scanClause.cql = scan->query->query_string;
3155     }
3156     else if (scan->query->z_query->which == Z_Query_type_1
3157              || scan->query->z_query->which == Z_Query_type_101)
3158     {
3159         sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
3160         sr->u.scan_request->scanClause.pqf = scan->query->query_string;
3161     }
3162     else
3163     {
3164         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
3165         return zoom_complete;
3166     }
3167
3168     sr->u.scan_request->maximumTerms = odr_intdup(
3169         c->odr_out, ZOOM_options_get_int(scan->options, "number", 10));
3170     
3171     sr->u.scan_request->responsePosition = odr_intdup(
3172         c->odr_out, ZOOM_options_get_int(scan->options, "position", 1));
3173     
3174     option_val = ZOOM_options_get(scan->options, "extraArgs");
3175     yaz_encode_sru_extra(sr, c->odr_out, option_val);
3176     return send_srw(c, sr);
3177 }
3178 #else
3179 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3180 {
3181     return zoom_complete;
3182 }
3183 #endif
3184
3185
3186 ZOOM_API(size_t)
3187     ZOOM_scanset_size(ZOOM_scanset scan)
3188 {
3189     if (!scan)
3190         return 0;
3191
3192     if (scan->scan_response && scan->scan_response->entries)
3193         return scan->scan_response->entries->num_entries;
3194     else if (scan->srw_scan_response)
3195         return scan->srw_scan_response->num_terms;
3196     return 0;
3197 }
3198
3199 static void ZOOM_scanset_term_x(ZOOM_scanset scan, size_t pos,
3200                                 size_t *occ,
3201                                 const char **value_term, size_t *value_len,
3202                                 const char **disp_term, size_t *disp_len)
3203 {
3204     size_t noent = ZOOM_scanset_size(scan);
3205     
3206     *value_term = 0;
3207     *value_len = 0;
3208
3209     *disp_term = 0;
3210     *disp_len = 0;
3211
3212     *occ = 0;
3213     if (pos >= noent)
3214         return;
3215     if (scan->scan_response)
3216     {
3217         Z_ScanResponse *res = scan->scan_response;
3218         if (res->entries->entries[pos]->which == Z_Entry_termInfo)
3219         {
3220             Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
3221             
3222             *value_term = (const char *) t->term->u.general->buf;
3223             *value_len = t->term->u.general->len;
3224             if (t->displayTerm)
3225             {
3226                 *disp_term = t->displayTerm;
3227                 *disp_len = strlen(*disp_term);
3228             }
3229             else if (t->term->which == Z_Term_general)
3230             {
3231                 *disp_term = (const char *) t->term->u.general->buf;
3232                 *disp_len = t->term->u.general->len;
3233             }
3234             *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
3235         }
3236     }
3237     if (scan->srw_scan_response)
3238     {
3239         Z_SRW_scanResponse *res = scan->srw_scan_response;
3240         Z_SRW_scanTerm *t = res->terms + pos;
3241         if (t)
3242         {
3243             *value_term = t->value;
3244             *value_len = strlen(*value_term);
3245
3246             if (t->displayTerm)
3247                 *disp_term = t->displayTerm;
3248             else
3249                 *disp_term = t->value;
3250             *disp_len = strlen(*disp_term);
3251             *occ = t->numberOfRecords ? *t->numberOfRecords : 0;
3252         }
3253     }
3254 }
3255
3256 ZOOM_API(const char *)
3257     ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
3258                       size_t *occ, size_t *len)
3259 {
3260     const char *value_term = 0;
3261     size_t value_len = 0;
3262     const char *disp_term = 0;
3263     size_t disp_len = 0;
3264
3265     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3266                         &disp_term, &disp_len);
3267     
3268     *len = value_len;
3269     return value_term;
3270 }
3271
3272 ZOOM_API(const char *)
3273     ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
3274                               size_t *occ, size_t *len)
3275 {
3276     const char *value_term = 0;
3277     size_t value_len = 0;
3278     const char *disp_term = 0;
3279     size_t disp_len = 0;
3280
3281     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3282                         &disp_term, &disp_len);
3283     
3284     *len = disp_len;
3285     return disp_term;
3286 }
3287
3288 ZOOM_API(const char *)
3289     ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
3290 {
3291     return ZOOM_options_get(scan->options, key);
3292 }
3293
3294 ZOOM_API(void)
3295     ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
3296                             const char *val)
3297 {
3298     ZOOM_options_set(scan->options, key, val);
3299 }
3300
3301 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
3302 {
3303     const char *str;
3304     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
3305     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3306     
3307     str = ZOOM_options_get(p->options, "package-name");
3308     if (str && *str)
3309         req->packageName = odr_strdup(p->odr_out, str);
3310     
3311     str = ZOOM_options_get(p->options, "user-id");
3312     if (str)
3313         req->userId = odr_strdup_null(p->odr_out, str);
3314     
3315     req->packageType = odr_oiddup(p->odr_out, oid);
3316
3317     str = ZOOM_options_get(p->options, "function");
3318     if (str)
3319     {
3320         if (!strcmp (str, "create"))
3321             *req->function = Z_ExtendedServicesRequest_create;
3322         if (!strcmp (str, "delete"))
3323             *req->function = Z_ExtendedServicesRequest_delete;
3324         if (!strcmp (str, "modify"))
3325             *req->function = Z_ExtendedServicesRequest_modify;
3326     }
3327
3328     str = ZOOM_options_get(p->options, "waitAction");
3329     if (str)
3330     {
3331         if (!strcmp (str, "wait"))
3332             *req->waitAction = Z_ExtendedServicesRequest_wait;
3333         if (!strcmp (str, "waitIfPossible"))
3334             *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
3335         if (!strcmp (str, "dontWait"))
3336             *req->waitAction = Z_ExtendedServicesRequest_dontWait;
3337         if (!strcmp (str, "dontReturnPackage"))
3338             *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
3339     }
3340     return apdu;
3341 }
3342
3343 static const char *ill_array_lookup(void *clientData, const char *idx)
3344 {
3345     ZOOM_package p = (ZOOM_package) clientData;
3346     return ZOOM_options_get(p->options, idx+4);
3347 }
3348
3349 static Z_External *encode_ill_request(ZOOM_package p)
3350 {
3351     ODR out = p->odr_out;
3352     ILL_Request *req;
3353     Z_External *r = 0;
3354     struct ill_get_ctl ctl;
3355         
3356     ctl.odr = p->odr_out;
3357     ctl.clientData = p;
3358     ctl.f = ill_array_lookup;
3359         
3360     req = ill_get_ILLRequest(&ctl, "ill", 0);
3361         
3362     if (!ill_Request(out, &req, 0, 0))
3363     {
3364         int ill_request_size;
3365         char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
3366         if (ill_request_buf)
3367             odr_setbuf(out, ill_request_buf, ill_request_size, 1);
3368         return 0;
3369     }
3370     else
3371     {
3372         int illRequest_size = 0;
3373         char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
3374                 
3375         r = (Z_External *) odr_malloc(out, sizeof(*r));
3376         r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
3377         r->indirect_reference = 0;
3378         r->descriptor = 0;
3379         r->which = Z_External_single;
3380                 
3381         r->u.single_ASN1_type =
3382             odr_create_Odr_oct(out,
3383                                (unsigned char *)illRequest_buf,
3384                                illRequest_size);
3385     }
3386     return r;
3387 }
3388
3389 static Z_ItemOrder *encode_item_order(ZOOM_package p)
3390 {
3391     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
3392     const char *str;
3393     int len;
3394     
3395     req->which = Z_IOItemOrder_esRequest;
3396     req->u.esRequest = (Z_IORequest *) 
3397         odr_malloc(p->odr_out,sizeof(Z_IORequest));
3398
3399     /* to keep part ... */
3400     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
3401         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
3402     req->u.esRequest->toKeep->supplDescription = 0;
3403     req->u.esRequest->toKeep->contact = (Z_IOContact *)
3404         odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
3405         
3406     str = ZOOM_options_get(p->options, "contact-name");
3407     req->u.esRequest->toKeep->contact->name =
3408         odr_strdup_null(p->odr_out, str);
3409         
3410     str = ZOOM_options_get(p->options, "contact-phone");
3411     req->u.esRequest->toKeep->contact->phone =
3412         odr_strdup_null(p->odr_out, str);
3413         
3414     str = ZOOM_options_get(p->options, "contact-email");
3415     req->u.esRequest->toKeep->contact->email =
3416         odr_strdup_null(p->odr_out, str);
3417         
3418     req->u.esRequest->toKeep->addlBilling = 0;
3419         
3420     /* not to keep part ... */
3421     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
3422         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
3423         
3424     str = ZOOM_options_get(p->options, "itemorder-setname");
3425     if (!str)
3426         str = "default";
3427
3428     if (!*str) 
3429         req->u.esRequest->notToKeep->resultSetItem = 0;
3430     else
3431     {
3432         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
3433             odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
3434
3435         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
3436             odr_strdup(p->odr_out, str);
3437         req->u.esRequest->notToKeep->resultSetItem->item =
3438             odr_intdup(p->odr_out, 0);
3439         
3440         str = ZOOM_options_get(p->options, "itemorder-item");
3441         *req->u.esRequest->notToKeep->resultSetItem->item =
3442             (str ? atoi(str) : 1);
3443     }
3444
3445     str = ZOOM_options_getl(p->options, "doc", &len);
3446     if (str)
3447     {
3448         req->u.esRequest->notToKeep->itemRequest =
3449             z_ext_record_xml(p->odr_out, str, len);
3450     }
3451     else
3452         req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
3453     
3454     return req;
3455 }
3456
3457 Z_APDU *create_admin_package(ZOOM_package p, int type, 
3458                              Z_ESAdminOriginPartToKeep **toKeepP,
3459                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
3460 {
3461     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
3462     if (apdu)
3463     {
3464         Z_ESAdminOriginPartToKeep  *toKeep;
3465         Z_ESAdminOriginPartNotToKeep  *notToKeep;
3466         Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3467         const char *first_db = "Default";
3468         int num_db;
3469         char **db = set_DatabaseNames(p->connection, p->options, &num_db,
3470                                       p->odr_out);
3471         if (num_db > 0)
3472             first_db = db[0];
3473             
3474         r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
3475         r->descriptor = 0;
3476         r->indirect_reference = 0;
3477         r->which = Z_External_ESAdmin;
3478         
3479         r->u.adminService = (Z_Admin *)
3480             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
3481         r->u.adminService->which = Z_Admin_esRequest;
3482         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
3483             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
3484         
3485         toKeep = r->u.adminService->u.esRequest->toKeep =
3486             (Z_ESAdminOriginPartToKeep *) 
3487             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
3488         toKeep->which = type;
3489         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3490         toKeep->u.create = odr_nullval();
3491         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3492         
3493         r->u.adminService->u.esRequest->notToKeep = notToKeep =
3494             (Z_ESAdminOriginPartNotToKeep *)
3495             odr_malloc(p->odr_out,
3496                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
3497         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
3498         notToKeep->u.recordsWillFollow = odr_nullval();
3499         if (toKeepP)
3500             *toKeepP = toKeep;
3501         if (notToKeepP)
3502             *notToKeepP = notToKeep;
3503     }
3504     return apdu;
3505 }
3506
3507 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
3508 {
3509     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
3510     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3511     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
3512     int len;
3513     const char *doc = ZOOM_options_getl(p->options, "doc", &len);
3514
3515     if (!doc)
3516     {
3517         doc = "";
3518         len = 0;
3519     }
3520
3521     req->taskSpecificParameters = ext;
3522     ext->direct_reference = req->packageType;
3523     ext->descriptor = 0;
3524     ext->indirect_reference = 0;
3525     
3526     ext->which = Z_External_octet;
3527     ext->u.single_ASN1_type =
3528         odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc, len);
3529     return apdu;
3530 }
3531
3532 static Z_APDU *create_update_package(ZOOM_package p)
3533 {
3534     Z_APDU *apdu = 0;
3535     const char *first_db = "Default";
3536     int num_db;
3537     char **db = set_DatabaseNames(p->connection, p->options, &num_db, p->odr_out);
3538     const char *action = ZOOM_options_get(p->options, "action");
3539     int recordIdOpaque_len;
3540     const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
3541         &recordIdOpaque_len);
3542     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
3543     int record_len;
3544     const char *record_buf = ZOOM_options_getl(p->options, "record",
3545         &record_len);
3546     int recordOpaque_len;
3547     const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
3548         &recordOpaque_len);
3549     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
3550     const char *version = ZOOM_options_get(p->options, "updateVersion");
3551
3552     const char *correlationInfo_note =
3553         ZOOM_options_get(p->options, "correlationInfo.note");
3554     const char *correlationInfo_id =
3555         ZOOM_options_get(p->options, "correlationInfo.id");
3556     int action_no = -1;
3557     Odr_oid *syntax_oid = 0;
3558     const Odr_oid *package_oid = yaz_oid_extserv_database_update;
3559
3560     if (!version)
3561         version = "3";
3562     if (!syntax_str)
3563         syntax_str = "xml";
3564     if (!record_buf && !recordOpaque_buf)
3565     {
3566         record_buf = "void";
3567         record_len = 4;
3568         syntax_str = "SUTRS";
3569     }
3570
3571     if (syntax_str)
3572     {
3573         syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
3574                                            CLASS_RECSYN, syntax_str,
3575                                            p->odr_out);
3576     }
3577     if (!syntax_oid)
3578         return 0;
3579
3580     if (num_db > 0)
3581         first_db = db[0];
3582     
3583     switch(*version)
3584     {
3585     case '1':
3586         package_oid = yaz_oid_extserv_database_update_first_version;
3587         /* old update does not support specialUpdate */
3588         if (!action)
3589             action = "recordInsert";
3590         break;
3591     case '2':
3592         if (!action)
3593             action = "specialUpdate";
3594         package_oid = yaz_oid_extserv_database_update_second_version;
3595         break;
3596     case '3':
3597         if (!action)
3598             action = "specialUpdate";
3599         package_oid = yaz_oid_extserv_database_update;
3600         break;
3601     default:
3602         return 0;
3603     }
3604     
3605     if (!strcmp(action, "recordInsert"))
3606         action_no = Z_IUOriginPartToKeep_recordInsert;
3607     else if (!strcmp(action, "recordReplace"))
3608         action_no = Z_IUOriginPartToKeep_recordReplace;
3609     else if (!strcmp(action, "recordDelete"))
3610         action_no = Z_IUOriginPartToKeep_recordDelete;
3611     else if (!strcmp(action, "elementUpdate"))
3612         action_no = Z_IUOriginPartToKeep_elementUpdate;
3613     else if (!strcmp(action, "specialUpdate"))
3614         action_no = Z_IUOriginPartToKeep_specialUpdate;
3615     else
3616         return 0;
3617
3618     apdu = create_es_package(p, package_oid);
3619     if (apdu)
3620     {
3621         Z_IUOriginPartToKeep *toKeep;
3622         Z_IUSuppliedRecords *notToKeep;
3623         Z_External *r = (Z_External *)
3624             odr_malloc(p->odr_out, sizeof(*r));
3625         const char *elementSetName =
3626             ZOOM_options_get(p->options, "elementSetName");
3627         
3628         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3629         
3630         r->direct_reference = odr_oiddup(p->odr_out, package_oid);
3631         r->descriptor = 0;
3632         r->which = Z_External_update;
3633         r->indirect_reference = 0;
3634         r->u.update = (Z_IUUpdate *)
3635             odr_malloc(p->odr_out, sizeof(*r->u.update));
3636         
3637         r->u.update->which = Z_IUUpdate_esRequest;
3638         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3639             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3640         toKeep = r->u.update->u.esRequest->toKeep = 
3641             (Z_IUOriginPartToKeep *)
3642             odr_malloc(p->odr_out, sizeof(*toKeep));
3643         
3644         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3645         toKeep->schema = 0;
3646         
3647         toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
3648             
3649         toKeep->actionQualifier = 0;
3650         toKeep->action = odr_intdup(p->odr_out, action_no);
3651         
3652         notToKeep = r->u.update->u.esRequest->notToKeep = 
3653             (Z_IUSuppliedRecords *)
3654             odr_malloc(p->odr_out, sizeof(*notToKeep));
3655         notToKeep->num = 1;
3656         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3657             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3658         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3659             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3660         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3661         if (recordIdOpaque)
3662         {
3663             notToKeep->elements[0]->u.opaque = 
3664                 odr_create_Odr_oct(p->odr_out,
3665                                    (const unsigned char *) recordIdOpaque,
3666                                    recordIdOpaque_len);
3667         }
3668         else if (recordIdNumber)
3669         {
3670             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3671             
3672             notToKeep->elements[0]->u.number =
3673                 odr_intdup(p->odr_out, atoi(recordIdNumber));
3674         }
3675         else
3676             notToKeep->elements[0]->u.opaque = 0;
3677         notToKeep->elements[0]->supplementalId = 0;
3678         if (correlationInfo_note || correlationInfo_id)
3679         {
3680             Z_IUCorrelationInfo *ci;
3681             ci = notToKeep->elements[0]->correlationInfo =
3682                 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
3683             ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
3684             ci->id = correlationInfo_id ?
3685                 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
3686         }
3687         else
3688             notToKeep->elements[0]->correlationInfo = 0;
3689         if (recordOpaque_buf)
3690         {
3691             notToKeep->elements[0]->record =
3692                 z_ext_record_oid_any(p->odr_out, syntax_oid,
3693                                  recordOpaque_buf, recordOpaque_len);
3694         }
3695         else
3696         {