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