40919491420a6f178e82cd59f3918ff87af4dcec
[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     nrec->odr = odr_createmem(ODR_DECODE);
1877 #if SHPTR
1878     nrec->record_wrbuf = 0;
1879 #else
1880     nrec->wrbuf = 0;
1881 #endif
1882 #if YAZ_HAVE_XML2
1883     nrec->xml_mem = 0;
1884     nrec->xml_size = 0;
1885 #endif
1886     odr_setbuf(nrec->odr, buf, size, 0);
1887     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1888     
1889     nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1890     nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1891     nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1892     nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1893     nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1894     odr_destroy(odr_enc);
1895     return nrec;
1896 }
1897
1898 ZOOM_API(ZOOM_record)
1899     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1900 {
1901     const char *syntax =
1902         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1903     const char *elementSetName =
1904         ZOOM_options_get(s->options, "elementSetName");
1905
1906     return record_cache_lookup(s, pos, syntax, elementSetName);
1907 }
1908
1909 ZOOM_API(ZOOM_record)
1910     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1911 {
1912     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1913
1914     if (!rec)
1915     {
1916         /*
1917          * MIKE: I think force_sync should always be zero, but I don't
1918          * want to make this change until I get the go-ahead from
1919          * Adam, in case something depends on the old synchronous
1920          * behaviour.
1921          */
1922         int force_sync = 1;
1923         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1924         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1925         rec = ZOOM_resultset_record_immediate(r, pos);
1926     }
1927     return rec;
1928 }
1929
1930 ZOOM_API(void)
1931     ZOOM_record_destroy(ZOOM_record rec)
1932 {
1933     ZOOM_record_release(rec);
1934     xfree(rec);
1935 }
1936
1937
1938 static yaz_iconv_t iconv_create_charset(const char *record_charset)
1939 {
1940     char to[40];
1941     char from[40];
1942     yaz_iconv_t cd = 0;
1943
1944     *from = '\0';
1945     strcpy(to, "UTF-8");
1946     if (record_charset && *record_charset)
1947     {
1948         /* Use "from,to" or just "from" */
1949         const char *cp = strchr(record_charset, ',');
1950         size_t clen = strlen(record_charset);
1951         if (cp && cp[1])
1952         {
1953             strncpy( to, cp+1, sizeof(to)-1);
1954             to[sizeof(to)-1] = '\0';
1955             clen = cp - record_charset;
1956         }
1957         if (clen > sizeof(from)-1)
1958             clen = sizeof(from)-1;
1959         
1960         if (clen)
1961             strncpy(from, record_charset, clen);
1962         from[clen] = '\0';
1963     }
1964     if (*from && *to)
1965         cd = yaz_iconv_open(to, from);
1966     return cd;
1967 }
1968
1969 static const char *return_marc_record(ZOOM_record rec, WRBUF wrbuf,
1970                                       int marc_type,
1971                                       int *len,
1972                                       const char *buf, int sz,
1973                                       const char *record_charset)
1974 {
1975     yaz_iconv_t cd = iconv_create_charset(record_charset);
1976     yaz_marc_t mt = yaz_marc_create();
1977     const char *ret_string = 0;
1978
1979     if (cd)
1980         yaz_marc_iconv(mt, cd);
1981     yaz_marc_xml(mt, marc_type);
1982     if (yaz_marc_decode_wrbuf(mt, buf, sz, wrbuf) > 0)
1983     {
1984         if (len)
1985             *len = wrbuf_len(wrbuf);
1986         ret_string = wrbuf_cstr(wrbuf);
1987     }
1988     yaz_marc_destroy(mt);
1989     if (cd)
1990         yaz_iconv_close(cd);
1991     return ret_string;
1992 }
1993
1994 static const char *return_opac_record(ZOOM_record rec, WRBUF wrbuf,
1995                                       int marc_type,
1996                                       int *len,
1997                                       Z_OPACRecord *opac_rec,
1998                                       const char *record_charset)
1999 {
2000     yaz_iconv_t cd = iconv_create_charset(record_charset);
2001     yaz_marc_t mt = yaz_marc_create();
2002
2003     if (cd)
2004         yaz_marc_iconv(mt, cd);
2005     yaz_marc_xml(mt, marc_type);
2006
2007     yaz_opac_decode_wrbuf(mt, opac_rec, wrbuf);
2008     yaz_marc_destroy(mt);
2009
2010     if (cd)
2011         yaz_iconv_close(cd);
2012     if (len)
2013         *len = wrbuf_len(wrbuf);
2014     return wrbuf_cstr(wrbuf);
2015 }
2016
2017 static const char *return_string_record(ZOOM_record rec, WRBUF wrbuf,
2018                                         int *len,
2019                                         const char *buf, int sz,
2020                                         const char *record_charset)
2021 {
2022     yaz_iconv_t cd = iconv_create_charset(record_charset);
2023
2024     if (cd)
2025     {
2026         wrbuf_iconv_write(wrbuf, cd, buf, sz);
2027         wrbuf_iconv_reset(wrbuf, cd);
2028
2029         buf = wrbuf_cstr(wrbuf);
2030         sz = wrbuf_len(wrbuf);
2031         yaz_iconv_close(cd);
2032     }
2033     if (len)
2034         *len = sz;
2035     return buf;
2036 }
2037
2038 static const char *return_record(ZOOM_record rec, int *len,
2039                                  Z_NamePlusRecord *npr,
2040                                  int marctype, const char *charset)
2041 {
2042     Z_External *r = (Z_External *) npr->u.databaseRecord;
2043     const Odr_oid *oid = r->direct_reference;
2044     WRBUF wrbuf;
2045
2046 #if SHPTR
2047     if (!rec->record_wrbuf)
2048     {
2049         WRBUF w = wrbuf_alloc();
2050         YAZ_SHPTR_INIT(rec->record_wrbuf, w);
2051     }
2052     wrbuf = rec->record_wrbuf->ptr;
2053 #else
2054     if (!rec->wrbuf)
2055         rec->wrbuf = wrbuf_alloc();
2056     wrbuf = rec->wrbuf;
2057 #endif
2058     wrbuf_rewind(wrbuf);
2059     /* render bibliographic record .. */
2060     if (r->which == Z_External_OPAC)
2061     {
2062         return return_opac_record(rec, wrbuf, marctype, len,
2063                                   r->u.opac, charset);
2064     }
2065     if (r->which == Z_External_sutrs)
2066         return return_string_record(rec, wrbuf, len,
2067                                     (char*) r->u.sutrs->buf,
2068                                     r->u.sutrs->len,
2069                                     charset);
2070     else if (r->which == Z_External_octet)
2071     {
2072         if (yaz_oid_is_iso2709(oid))
2073         {
2074             const char *ret_buf = return_marc_record(
2075                 rec, wrbuf, marctype, len,
2076                 (const char *) r->u.octet_aligned->buf,
2077                 r->u.octet_aligned->len,
2078                 charset);
2079             if (ret_buf)
2080                 return ret_buf;
2081             /* bad ISO2709. Return fail unless raw (ISO2709) is wanted */
2082             if (marctype != YAZ_MARC_ISO2709)
2083                 return 0;
2084         }
2085         return return_string_record(rec, wrbuf, len,
2086                                     (const char *) r->u.octet_aligned->buf,
2087                                     r->u.octet_aligned->len,
2088                                     charset);
2089     }
2090     else if (r->which == Z_External_grs1)
2091     {
2092         yaz_display_grs1(wrbuf, r->u.grs1, 0);
2093         return return_string_record(rec, wrbuf, len,
2094                                     wrbuf_buf(wrbuf),
2095                                     wrbuf_len(wrbuf),
2096                                     charset);
2097     }
2098     return 0;
2099 }
2100     
2101
2102 ZOOM_API(int)
2103     ZOOM_record_error(ZOOM_record rec, const char **cp,
2104                       const char **addinfo, const char **diagset)
2105 {
2106     Z_NamePlusRecord *npr;
2107     
2108     if (!rec)
2109         return 0;
2110
2111     npr = rec->npr;
2112     if (rec->diag_uri)
2113     {
2114         if (cp)
2115             *cp = rec->diag_message;
2116         if (addinfo)
2117             *addinfo = rec->diag_details;
2118         if (diagset)
2119             *diagset = rec->diag_set;
2120         return uri_to_code(rec->diag_uri);
2121     }
2122     if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
2123     {
2124         Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
2125         int error = YAZ_BIB1_UNSPECIFIED_ERROR;
2126         const char *add = 0;
2127
2128         if (diag_rec->which == Z_DiagRec_defaultFormat)
2129         {
2130             Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
2131             oid_class oclass;
2132     
2133             error = *ddf->condition;
2134             switch (ddf->which)
2135             {
2136             case Z_DefaultDiagFormat_v2Addinfo:
2137                 add = ddf->u.v2Addinfo;
2138                 break;
2139             case Z_DefaultDiagFormat_v3Addinfo:
2140                 add = ddf->u.v3Addinfo;
2141                 break;
2142             }
2143             if (diagset)
2144                 *diagset =
2145                     yaz_oid_to_string(yaz_oid_std(),
2146                                       ddf->diagnosticSetId, &oclass);
2147         }
2148         else
2149         {
2150             if (diagset)
2151                 *diagset = "Bib-1";
2152         }
2153         if (addinfo)
2154             *addinfo = add ? add : "";
2155         if (cp)
2156             *cp = diagbib1_str(error);
2157         return error;
2158     }
2159     return 0;
2160 }
2161
2162 static const char *get_record_format(ZOOM_record rec, int *len,
2163                                      Z_NamePlusRecord *npr,
2164                                      int marctype, const char *charset,
2165                                      const char *format)
2166 {
2167     const char *res = return_record(rec, len, npr, marctype, charset);
2168 #if YAZ_HAVE_XML2
2169     if (*format == '1' && len)
2170     {
2171         /* try to XML format res */
2172         xmlDocPtr doc;
2173         xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
2174         doc = xmlParseMemory(res, *len);
2175         if (doc)
2176         {
2177             if (rec->xml_mem)
2178                 xmlFree(rec->xml_mem);
2179             xmlDocDumpFormatMemory(doc, &rec->xml_mem, &rec->xml_size, 1);
2180             xmlFreeDoc(doc);
2181             res = (char *) rec->xml_mem;
2182             *len = rec->xml_size;
2183         } 
2184     }
2185 #endif
2186     return res;
2187 }
2188
2189
2190 ZOOM_API(const char *)
2191     ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2192 {
2193     char type[40];
2194     char charset[40];
2195     char format[3];
2196     const char *cp;
2197     size_t i;
2198     Z_NamePlusRecord *npr;
2199     
2200     if (len)
2201         *len = 0; /* default return */
2202         
2203     if (!rec)
2204         return 0;
2205     npr = rec->npr;
2206     if (!npr)
2207         return 0;
2208
2209     cp = type_spec;
2210     for (i = 0; cp[i] && cp[i] != ';' && cp[i] != ' ' && i < sizeof(type)-1;
2211          i++)
2212         type[i] = cp[i];
2213     type[i] = '\0';
2214     charset[0] = '\0';
2215     format[0] = '\0';
2216     while (1)
2217     {
2218         while (cp[i] == ' ')
2219             i++;
2220         if (cp[i] != ';')
2221             break;
2222         i++;
2223         while (cp[i] == ' ')
2224             i++;
2225         if (!strncmp(cp + i, "charset=", 8))
2226         {
2227             size_t j = 0;
2228             i = i + 8; /* skip charset= */
2229             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2230             {
2231                 if (j < sizeof(charset)-1)
2232                     charset[j++] = cp[i];
2233             }
2234             charset[j] = '\0';
2235         }
2236         else if (!strncmp(cp + i, "format=", 7))
2237         {
2238             size_t j = 0; 
2239             i = i + 7;
2240             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2241             {
2242                 if (j < sizeof(format)-1)
2243                     format[j++] = cp[i];
2244             }
2245             format[j] = '\0';
2246         } 
2247     }
2248     if (!strcmp(type, "database"))
2249     {
2250         if (len)
2251             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2252         return npr->databaseName;
2253     }
2254     else if (!strcmp(type, "schema"))
2255     {
2256         if (len)
2257             *len = rec->schema ? strlen(rec->schema) : 0;
2258         return rec->schema;
2259     }
2260     else if (!strcmp(type, "syntax"))
2261     {
2262         const char *desc = 0;   
2263         if (npr->which == Z_NamePlusRecord_databaseRecord)
2264         {
2265             Z_External *r = (Z_External *) npr->u.databaseRecord;
2266             desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2267         }
2268         if (!desc)
2269             desc = "none";
2270         if (len)
2271             *len = strlen(desc);
2272         return desc;
2273     }
2274     if (npr->which != Z_NamePlusRecord_databaseRecord)
2275         return 0;
2276
2277     /* from now on - we have a database record .. */
2278     if (!strcmp(type, "render"))
2279     {
2280         return get_record_format(rec, len, npr, YAZ_MARC_LINE, charset, format);
2281     }
2282     else if (!strcmp(type, "xml"))
2283     {
2284         return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2285                                  format);
2286     }
2287     else if (!strcmp(type, "txml"))
2288     {
2289         return get_record_format(rec, len, npr, YAZ_MARC_TURBOMARC, charset,
2290                                  format);
2291     }
2292     else if (!strcmp(type, "raw"))
2293     {
2294         return get_record_format(rec, len, npr, YAZ_MARC_ISO2709, charset,
2295             format);
2296     }
2297     else if (!strcmp(type, "ext"))
2298     {
2299         if (len) *len = -1;
2300         return (const char *) npr->u.databaseRecord;
2301     }
2302     else if (!strcmp(type, "opac"))
2303     {
2304         if (npr->u.databaseRecord->which == Z_External_OPAC)
2305             return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2306                 format);
2307     }
2308     return 0;
2309 }
2310
2311 static int strcmp_null(const char *v1, const char *v2)
2312 {
2313     if (!v1 && !v2)
2314         return 0;
2315     if (!v1 || !v2)
2316         return -1;
2317     return strcmp(v1, v2);
2318 }
2319
2320 static size_t record_hash(int pos)
2321 {
2322     if (pos < 0)
2323         pos = 0;
2324     return pos % RECORD_HASH_SIZE;
2325 }
2326
2327 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr, 
2328                              int pos,
2329                              const char *syntax, const char *elementSetName,
2330                              const char *schema,
2331                              Z_SRW_diagnostic *diag)
2332 {
2333     ZOOM_record_cache rc = 0;
2334     
2335     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2336     ZOOM_connection_put_event(r->connection, event);
2337
2338     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2339     {
2340         if (pos == rc->pos 
2341             && strcmp_null(r->schema, rc->schema) == 0
2342             && strcmp_null(elementSetName,rc->elementSetName) == 0
2343             && strcmp_null(syntax, rc->syntax) == 0)
2344             break;
2345     }
2346     if (!rc)
2347     {
2348         rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2349         rc->rec.odr = 0;
2350 #if SHPTR
2351         YAZ_SHPTR_INC(r->record_wrbuf);
2352         rc->rec.record_wrbuf = r->record_wrbuf;
2353 #else
2354         rc->rec.wrbuf = 0;
2355 #endif
2356 #if YAZ_HAVE_XML2
2357         rc->rec.xml_mem = 0;
2358 #endif
2359         rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2360         
2361         rc->syntax = odr_strdup_null(r->odr, syntax);
2362         
2363         rc->schema = odr_strdup_null(r->odr, r->schema);
2364
2365         rc->pos = pos;
2366         rc->next = r->record_hash[record_hash(pos)];
2367         r->record_hash[record_hash(pos)] = rc;
2368     }
2369     rc->rec.npr = npr;
2370     rc->rec.schema = odr_strdup_null(r->odr, schema);
2371     rc->rec.diag_set = 0;
2372     rc->rec.diag_uri = 0;
2373     rc->rec.diag_message = 0;
2374     rc->rec.diag_details = 0;
2375     if (diag)
2376     {
2377         if (diag->uri)
2378         {
2379             char *cp;
2380             rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2381             if ((cp = strrchr(rc->rec.diag_set, '/')))
2382                 *cp = '\0';
2383             rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2384         }
2385         rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);            
2386         rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2387     }
2388 }
2389
2390 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2391                                        const char *syntax,
2392                                        const char *elementSetName)
2393 {
2394     ZOOM_record_cache rc;
2395     
2396     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2397     {
2398         if (pos == rc->pos)
2399         {
2400             if (strcmp_null(r->schema, rc->schema))
2401                 continue;
2402             if (strcmp_null(elementSetName,rc->elementSetName))
2403                 continue;
2404             if (strcmp_null(syntax, rc->syntax))
2405                 continue;
2406             return &rc->rec;
2407         }
2408     }
2409     return 0;
2410 }
2411                                              
2412 static void handle_records(ZOOM_connection c, Z_Records *sr,
2413                            int present_phase)
2414 {
2415     ZOOM_resultset resultset;
2416     int *start, *count;
2417     const char *syntax = 0, *elementSetName = 0;
2418
2419     if (!c->tasks)
2420         return ;
2421     switch (c->tasks->which)
2422     {
2423     case ZOOM_TASK_SEARCH:
2424         resultset = c->tasks->u.search.resultset;
2425         start = &c->tasks->u.search.start;
2426         count = &c->tasks->u.search.count;
2427         syntax = c->tasks->u.search.syntax;
2428         elementSetName = c->tasks->u.search.elementSetName;
2429         break;
2430     case ZOOM_TASK_RETRIEVE:
2431         resultset = c->tasks->u.retrieve.resultset;        
2432         start = &c->tasks->u.retrieve.start;
2433         count = &c->tasks->u.retrieve.count;
2434         syntax = c->tasks->u.retrieve.syntax;
2435         elementSetName = c->tasks->u.retrieve.elementSetName;
2436         break;
2437     default:
2438         return;
2439     }
2440     if (sr && sr->which == Z_Records_NSD)
2441         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2442     else if (sr && sr->which == Z_Records_multipleNSD)
2443     {
2444         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2445             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2446         else
2447             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2448     }
2449     else 
2450     {
2451         if (*count + *start > resultset->size)
2452             *count = resultset->size - *start;
2453         if (*count < 0)
2454             *count = 0;
2455         if (sr && sr->which == Z_Records_DBOSD)
2456         {
2457             int i;
2458             NMEM nmem = odr_extract_mem(c->odr_in);
2459             Z_NamePlusRecordList *p =
2460                 sr->u.databaseOrSurDiagnostics;
2461             for (i = 0; i<p->num_records; i++)
2462             {
2463                 record_cache_add(resultset, p->records[i], i + *start,
2464                                  syntax, elementSetName,
2465                                  elementSetName, 0);
2466             }
2467             *count -= i;
2468             if (*count < 0)
2469                 *count = 0;
2470             *start += i;
2471             yaz_log(log_details, 
2472                     "handle_records resultset=%p start=%d count=%d",
2473                     resultset, *start, *count);
2474
2475             /* transfer our response to search_nmem .. we need it later */
2476             nmem_transfer(odr_getmem(resultset->odr), nmem);
2477             nmem_destroy(nmem);
2478             if (present_phase && p->num_records == 0)
2479             {
2480                 /* present response and we didn't get any records! */
2481                 Z_NamePlusRecord *myrec = 
2482                     zget_surrogateDiagRec(
2483                         resultset->odr, 0, 
2484                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2485                         "ZOOM C generated. Present phase and no records");
2486                 record_cache_add(resultset, myrec, *start,
2487                                  syntax, elementSetName, 0, 0);
2488             }
2489         }
2490         else if (present_phase)
2491         {
2492             /* present response and we didn't get any records! */
2493             Z_NamePlusRecord *myrec = 
2494                 zget_surrogateDiagRec(
2495                     resultset->odr, 0,
2496                     YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2497                     "ZOOM C generated: Present response and no records");
2498             record_cache_add(resultset, myrec, *start, syntax, elementSetName,
2499                              0, 0);
2500         }
2501     }
2502 }
2503
2504 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2505 {
2506     handle_records(c, pr->records, 1);
2507 }
2508
2509 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2510                                        Z_Term *term)
2511 {
2512     switch (term->which)
2513     {
2514     case Z_Term_general:
2515         ZOOM_options_setl(opt, name,
2516                           (const char *)(term->u.general->buf), 
2517                           term->u.general->len);
2518         break;
2519     case Z_Term_characterString:
2520         ZOOM_options_set(opt, name, term->u.characterString);
2521         break;
2522     case Z_Term_numeric:
2523         ZOOM_options_set_int(opt, name, *term->u.numeric);
2524         break;
2525     }
2526 }
2527
2528 static void handle_queryExpression(ZOOM_options opt, const char *name,
2529                                    Z_QueryExpression *exp)
2530 {
2531     char opt_name[80];
2532     
2533     switch (exp->which)
2534     {
2535     case Z_QueryExpression_term:
2536         if (exp->u.term && exp->u.term->queryTerm)
2537         {
2538             sprintf(opt_name, "%s.term", name);
2539             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2540         }
2541         break;
2542     case Z_QueryExpression_query:
2543         break;
2544     }
2545 }
2546
2547 static void handle_searchResult(ZOOM_connection c, ZOOM_resultset resultset,
2548                                 Z_OtherInformation *o)
2549 {
2550     int i;
2551     for (i = 0; o && i < o->num_elements; i++)
2552     {
2553         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2554         {
2555             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2556             
2557             if (ext->which == Z_External_searchResult1)
2558             {
2559                 int j;
2560                 Z_SearchInfoReport *sr = ext->u.searchResult1;
2561                 
2562                 if (sr->num)
2563                     ZOOM_options_set_int(
2564                         resultset->options, "searchresult.size", sr->num);
2565
2566                 for (j = 0; j < sr->num; j++)
2567                 {
2568                     Z_SearchInfoReport_s *ent =
2569                         ext->u.searchResult1->elements[j];
2570                     char pref[80];
2571                     
2572                     sprintf(pref, "searchresult.%d", j);
2573
2574                     if (ent->subqueryId)
2575                     {
2576                         char opt_name[80];
2577                         sprintf(opt_name, "%s.id", pref);
2578                         ZOOM_options_set(resultset->options, opt_name,
2579                                          ent->subqueryId);
2580                     }
2581                     if (ent->subqueryExpression)
2582                     {
2583                         char opt_name[80];
2584                         sprintf(opt_name, "%s.subquery", pref);
2585                         handle_queryExpression(resultset->options, opt_name,
2586                                                ent->subqueryExpression);
2587                     }
2588                     if (ent->subqueryInterpretation)
2589                     {
2590                         char opt_name[80];
2591                         sprintf(opt_name, "%s.interpretation", pref);
2592                         handle_queryExpression(resultset->options, opt_name,
2593                                                ent->subqueryInterpretation);
2594                     }
2595                     if (ent->subqueryRecommendation)
2596                     {
2597                         char opt_name[80];
2598                         sprintf(opt_name, "%s.recommendation", pref);
2599                         handle_queryExpression(resultset->options, opt_name,
2600                                                ent->subqueryRecommendation);
2601                     }
2602                     if (ent->subqueryCount)
2603                     {
2604                         char opt_name[80];
2605                         sprintf(opt_name, "%s.count", pref);
2606                         ZOOM_options_set_int(resultset->options, opt_name,
2607                                              *ent->subqueryCount);
2608                     }                                             
2609                 }
2610             }
2611         }
2612     }
2613 }
2614
2615 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2616 {
2617     ZOOM_resultset resultset;
2618     ZOOM_Event event;
2619
2620     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2621         return ;
2622
2623     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2624     ZOOM_connection_put_event(c, event);
2625
2626     resultset = c->tasks->u.search.resultset;
2627
2628     if (sr->resultSetStatus)
2629     {
2630         ZOOM_options_set_int(resultset->options, "resultSetStatus",
2631                              *sr->resultSetStatus);
2632     }
2633     if (sr->presentStatus)
2634     {
2635         ZOOM_options_set_int(resultset->options, "presentStatus",
2636                              *sr->presentStatus);
2637     }
2638     handle_searchResult(c, resultset, sr->additionalSearchInfo);
2639
2640     resultset->size = *sr->resultCount;
2641     handle_records(c, sr->records, 0);
2642 }
2643
2644 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2645 {
2646     if (res->diagnostics && res->num_diagnostics > 0)
2647         response_diag(c, res->diagnostics[0]);
2648 }
2649
2650 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2651 {
2652     NMEM nmem = odr_extract_mem(c->odr_in);
2653     ZOOM_scanset scan;
2654
2655     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2656         return 0;
2657     scan = c->tasks->u.scan.scan;
2658
2659     if (res->entries && res->entries->nonsurrogateDiagnostics)
2660         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2661     scan->scan_response = res;
2662     scan->srw_scan_response = 0;
2663     nmem_transfer(odr_getmem(scan->odr), nmem);
2664     if (res->stepSize)
2665         ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2666     if (res->positionOfTerm)
2667         ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2668     if (res->scanStatus)
2669         ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2670     if (res->numberOfEntriesReturned)
2671         ZOOM_options_set_int(scan->options, "number",
2672                              *res->numberOfEntriesReturned);
2673     nmem_destroy(nmem);
2674     return 1;
2675 }
2676
2677 static zoom_ret send_sort(ZOOM_connection c,
2678                           ZOOM_resultset resultset)
2679 {
2680     if (c->error)
2681         resultset->r_sort_spec = 0;
2682     if (resultset->r_sort_spec)
2683     {
2684         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2685         Z_SortRequest *req = apdu->u.sortRequest;
2686         
2687         req->num_inputResultSetNames = 1;
2688         req->inputResultSetNames = (Z_InternationalString **)
2689             odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2690         req->inputResultSetNames[0] =
2691             odr_strdup(c->odr_out, resultset->setname);
2692         req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2693         req->sortSequence = resultset->r_sort_spec;
2694         resultset->r_sort_spec = 0;
2695         return send_APDU(c, apdu);
2696     }
2697     return zoom_complete;
2698 }
2699
2700 static zoom_ret send_present(ZOOM_connection c)
2701 {
2702     Z_APDU *apdu = 0;
2703     Z_PresentRequest *req = 0;
2704     int i = 0;
2705     const char *syntax = 0;
2706     const char *elementSetName = 0;
2707     ZOOM_resultset  resultset;
2708     int *start, *count;
2709
2710     if (!c->tasks)
2711     {
2712         yaz_log(log_details, "%p send_present no tasks", c);
2713         return zoom_complete;
2714     }
2715     
2716     switch (c->tasks->which)
2717     {
2718     case ZOOM_TASK_SEARCH:
2719         resultset = c->tasks->u.search.resultset;
2720         start = &c->tasks->u.search.start;
2721         count = &c->tasks->u.search.count;
2722         syntax = c->tasks->u.search.syntax;
2723         elementSetName = c->tasks->u.search.elementSetName;
2724         break;
2725     case ZOOM_TASK_RETRIEVE:
2726         resultset = c->tasks->u.retrieve.resultset;
2727         start = &c->tasks->u.retrieve.start;
2728         count = &c->tasks->u.retrieve.count;
2729         syntax = c->tasks->u.retrieve.syntax;
2730         elementSetName = c->tasks->u.retrieve.elementSetName;
2731         break;
2732     default:
2733         return zoom_complete;
2734     }
2735     yaz_log(log_details, "%p send_present start=%d count=%d",
2736             c, *start, *count);
2737
2738     if (*start < 0 || *count < 0 || *start + *count > resultset->size)
2739     {
2740         set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
2741                        "", 0);
2742     }
2743     if (c->error)                  /* don't continue on error */
2744         return zoom_complete;
2745     yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2746             resultset, *start, *count);
2747
2748     for (i = 0; i < *count; i++)
2749     {
2750         ZOOM_record rec =
2751             record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2752         if (!rec)
2753             break;
2754         else
2755         {
2756             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2757             ZOOM_connection_put_event(c, event);
2758         }
2759     }
2760     *start += i;
2761     *count -= i;
2762
2763     if (*count == 0)
2764     {
2765         yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2766         return zoom_complete;
2767     }
2768
2769     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2770     req = apdu->u.presentRequest;
2771
2772     if (i)
2773         yaz_log(log_details, "%p send_present skip=%d", c, i);
2774
2775     *req->resultSetStartPoint = *start + 1;
2776
2777     if (resultset->step > 0 && resultset->step < *count)
2778         *req->numberOfRecordsRequested = resultset->step;
2779     else
2780         *req->numberOfRecordsRequested = *count;
2781     
2782     if (*req->numberOfRecordsRequested + *start > resultset->size)
2783         *req->numberOfRecordsRequested = resultset->size - *start;
2784     assert(*req->numberOfRecordsRequested > 0);
2785
2786     if (syntax && *syntax)
2787         req->preferredRecordSyntax =
2788             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
2789
2790     if (resultset->schema && *resultset->schema)
2791     {
2792         Z_RecordComposition *compo = (Z_RecordComposition *)
2793             odr_malloc(c->odr_out, sizeof(*compo));
2794
2795         req->recordComposition = compo;
2796         compo->which = Z_RecordComp_complex;
2797         compo->u.complex = (Z_CompSpec *)
2798             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2799         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2800             odr_malloc(c->odr_out, sizeof(bool_t));
2801         *compo->u.complex->selectAlternativeSyntax = 0;
2802
2803         compo->u.complex->generic = (Z_Specification *)
2804             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2805
2806         compo->u.complex->generic->which = Z_Schema_oid;
2807         compo->u.complex->generic->schema.oid = (Odr_oid *)
2808             zoom_yaz_str_to_z3950oid (c, CLASS_SCHEMA, resultset->schema);
2809
2810         if (!compo->u.complex->generic->schema.oid)
2811         {
2812             /* OID wasn't a schema! Try record syntax instead. */
2813
2814             compo->u.complex->generic->schema.oid = (Odr_oid *)
2815                 zoom_yaz_str_to_z3950oid (c, CLASS_RECSYN, resultset->schema);
2816         }
2817         if (elementSetName && *elementSetName)
2818         {
2819             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2820                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2821             compo->u.complex->generic->elementSpec->which =
2822                 Z_ElementSpec_elementSetName;
2823             compo->u.complex->generic->elementSpec->u.elementSetName =
2824                 odr_strdup(c->odr_out, elementSetName);
2825         }
2826         else
2827             compo->u.complex->generic->elementSpec = 0;
2828         compo->u.complex->num_dbSpecific = 0;
2829         compo->u.complex->dbSpecific = 0;
2830         compo->u.complex->num_recordSyntax = 0;
2831         compo->u.complex->recordSyntax = 0;
2832     }
2833     else if (elementSetName && *elementSetName)
2834     {
2835         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2836             odr_malloc(c->odr_out, sizeof(*esn));
2837         Z_RecordComposition *compo = (Z_RecordComposition *)
2838             odr_malloc(c->odr_out, sizeof(*compo));
2839         
2840         esn->which = Z_ElementSetNames_generic;
2841         esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2842         compo->which = Z_RecordComp_simple;
2843         compo->u.simple = esn;
2844         req->recordComposition = compo;
2845     }
2846     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2847     return send_APDU(c, apdu);
2848 }
2849
2850 ZOOM_API(ZOOM_scanset)
2851     ZOOM_connection_scan(ZOOM_connection c, const char *start)
2852 {
2853     ZOOM_scanset s;
2854     ZOOM_query q = ZOOM_query_create();
2855
2856     ZOOM_query_prefix(q, start);
2857
2858     s = ZOOM_connection_scan1(c, q);
2859     ZOOM_query_destroy(q);
2860     return s;
2861
2862 }
2863
2864 ZOOM_API(ZOOM_scanset)
2865     ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
2866 {
2867     ZOOM_scanset scan = 0;
2868
2869     if (!q->z_query)
2870         return 0;
2871     scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
2872     scan->connection = c;
2873     scan->odr = odr_createmem(ODR_DECODE);
2874     scan->options = ZOOM_options_create_with_parent(c->options);
2875     scan->refcount = 1;
2876     scan->scan_response = 0;
2877     scan->srw_scan_response = 0;
2878
2879     scan->query = q;
2880     (q->refcount)++;
2881     scan->databaseNames = set_DatabaseNames(c, c->options,
2882                                             &scan->num_databaseNames,
2883                                             scan->odr);
2884
2885     if (1)
2886     {
2887         ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
2888         task->u.scan.scan = scan;
2889         
2890         (scan->refcount)++;
2891         if (!c->async)
2892         {
2893             while (ZOOM_event(1, &c))
2894                 ;
2895         }
2896     }
2897     return scan;
2898 }
2899
2900 ZOOM_API(void)
2901     ZOOM_scanset_destroy(ZOOM_scanset scan)
2902 {
2903     if (!scan)
2904         return;
2905     (scan->refcount)--;
2906     if (scan->refcount == 0)
2907     {
2908         ZOOM_query_destroy(scan->query);
2909
2910         odr_destroy(scan->odr);
2911         
2912         ZOOM_options_destroy(scan->options);
2913         xfree(scan);
2914     }
2915 }
2916
2917 static zoom_ret send_package(ZOOM_connection c)
2918 {
2919     ZOOM_Event event;
2920
2921     yaz_log(log_details, "%p send_package", c);
2922     if (!c->tasks)
2923         return zoom_complete;
2924     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2925     
2926     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
2927     ZOOM_connection_put_event(c, event);
2928     
2929     c->buf_out = c->tasks->u.package->buf_out;
2930     c->len_out = c->tasks->u.package->len_out;
2931
2932     return do_write(c);
2933 }
2934
2935 static zoom_ret ZOOM_connection_send_scan(ZOOM_connection c)
2936 {
2937     ZOOM_scanset scan;
2938     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2939     Z_ScanRequest *req = apdu->u.scanRequest;
2940
2941     yaz_log(log_details, "%p send_scan", c);
2942     if (!c->tasks)
2943         return zoom_complete;
2944     assert (c->tasks->which == ZOOM_TASK_SCAN);
2945     scan = c->tasks->u.scan.scan;
2946
2947     /* Z39.50 scan can only carry RPN */
2948     if (scan->query->z_query->which == Z_Query_type_1 ||
2949         scan->query->z_query->which == Z_Query_type_101)
2950     {
2951         Z_RPNQuery *rpn = scan->query->z_query->u.type_1;
2952         const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
2953         if (cp)
2954         {
2955             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
2956             if (cd)
2957             {
2958                 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
2959
2960                 yaz_query_charset_convert_rpnquery(
2961                     rpn, c->odr_out, cd);
2962                 yaz_iconv_close(cd);
2963             }
2964         }
2965         req->attributeSet = rpn->attributeSetId;
2966         if (!req->attributeSet)
2967             req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
2968         if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
2969             rpn->RPNStructure->u.simple->which == Z_Operand_APT)
2970         {
2971             req->termListAndStartPoint =
2972                 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
2973         }
2974         else
2975         {
2976             set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
2977             return zoom_complete;
2978         }
2979     }
2980     else
2981     {
2982         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
2983         return zoom_complete;
2984     }
2985
2986     *req->numberOfTermsRequested =
2987         ZOOM_options_get_int(scan->options, "number", 20);
2988
2989     req->preferredPositionInResponse =
2990         odr_intdup(c->odr_out,
2991                    ZOOM_options_get_int(scan->options, "position", 1));
2992
2993     req->stepSize =
2994         odr_intdup(c->odr_out,
2995                    ZOOM_options_get_int(scan->options, "stepSize", 0));
2996     
2997     req->databaseNames = scan->databaseNames;
2998     req->num_databaseNames = scan->num_databaseNames;
2999
3000     return send_APDU(c, apdu);
3001 }
3002
3003 #if YAZ_HAVE_XML2
3004 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3005 {
3006     ZOOM_scanset scan;
3007     Z_SRW_PDU *sr = 0;
3008     const char *option_val = 0;
3009
3010     if (!c->tasks)
3011         return zoom_complete;
3012     assert (c->tasks->which == ZOOM_TASK_SCAN);
3013     scan = c->tasks->u.scan.scan;
3014         
3015     sr = ZOOM_srw_get_pdu(c, Z_SRW_scan_request);
3016
3017     /* SRU scan can only carry CQL and PQF */
3018     if (scan->query->z_query->which == Z_Query_type_104)
3019     {
3020         sr->u.scan_request->query_type = Z_SRW_query_type_cql;
3021         sr->u.scan_request->scanClause.cql = scan->query->query_string;
3022     }
3023     else if (scan->query->z_query->which == Z_Query_type_1
3024              || scan->query->z_query->which == Z_Query_type_101)
3025     {
3026         sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
3027         sr->u.scan_request->scanClause.pqf = scan->query->query_string;
3028     }
3029     else
3030     {
3031         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
3032         return zoom_complete;
3033     }
3034
3035     sr->u.scan_request->maximumTerms = odr_intdup(
3036         c->odr_out, ZOOM_options_get_int(scan->options, "number", 10));
3037     
3038     sr->u.scan_request->responsePosition = odr_intdup(
3039         c->odr_out, ZOOM_options_get_int(scan->options, "position", 1));
3040     
3041     option_val = ZOOM_options_get(scan->options, "extraArgs");
3042     yaz_encode_sru_extra(sr, c->odr_out, option_val);
3043     return send_srw(c, sr);
3044 }
3045 #else
3046 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3047 {
3048     return zoom_complete;
3049 }
3050 #endif
3051
3052
3053 ZOOM_API(size_t)
3054     ZOOM_scanset_size(ZOOM_scanset scan)
3055 {
3056     if (!scan)
3057         return 0;
3058
3059     if (scan->scan_response && scan->scan_response->entries)
3060         return scan->scan_response->entries->num_entries;
3061     else if (scan->srw_scan_response)
3062         return scan->srw_scan_response->num_terms;
3063     return 0;
3064 }
3065
3066 static void ZOOM_scanset_term_x(ZOOM_scanset scan, size_t pos,
3067                                 size_t *occ,
3068                                 const char **value_term, size_t *value_len,
3069                                 const char **disp_term, size_t *disp_len)
3070 {
3071     size_t noent = ZOOM_scanset_size(scan);
3072     
3073     *value_term = 0;
3074     *value_len = 0;
3075
3076     *disp_term = 0;
3077     *disp_len = 0;
3078
3079     *occ = 0;
3080     if (pos >= noent)
3081         return;
3082     if (scan->scan_response)
3083     {
3084         Z_ScanResponse *res = scan->scan_response;
3085         if (res->entries->entries[pos]->which == Z_Entry_termInfo)
3086         {
3087             Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
3088             
3089             *value_term = (const char *) t->term->u.general->buf;
3090             *value_len = t->term->u.general->len;
3091             if (t->displayTerm)
3092             {
3093                 *disp_term = t->displayTerm;
3094                 *disp_len = strlen(*disp_term);
3095             }
3096             else if (t->term->which == Z_Term_general)
3097             {
3098                 *disp_term = (const char *) t->term->u.general->buf;
3099                 *disp_len = t->term->u.general->len;
3100             }
3101             *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
3102         }
3103     }
3104     if (scan->srw_scan_response)
3105     {
3106         Z_SRW_scanResponse *res = scan->srw_scan_response;
3107         Z_SRW_scanTerm *t = res->terms + pos;
3108         if (t)
3109         {
3110             *value_term = t->value;
3111             *value_len = strlen(*value_term);
3112
3113             if (t->displayTerm)
3114                 *disp_term = t->displayTerm;
3115             else
3116                 *disp_term = t->value;
3117             *disp_len = strlen(*disp_term);
3118             *occ = t->numberOfRecords ? *t->numberOfRecords : 0;
3119         }
3120     }
3121 }
3122
3123 ZOOM_API(const char *)
3124     ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
3125                       size_t *occ, size_t *len)
3126 {
3127     const char *value_term = 0;
3128     size_t value_len = 0;
3129     const char *disp_term = 0;
3130     size_t disp_len = 0;
3131
3132     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3133                         &disp_term, &disp_len);
3134     
3135     *len = value_len;
3136     return value_term;
3137 }
3138
3139 ZOOM_API(const char *)
3140     ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
3141                               size_t *occ, size_t *len)
3142 {
3143     const char *value_term = 0;
3144     size_t value_len = 0;
3145     const char *disp_term = 0;
3146     size_t disp_len = 0;
3147
3148     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3149                         &disp_term, &disp_len);
3150     
3151     *len = disp_len;
3152     return disp_term;
3153 }
3154
3155 ZOOM_API(const char *)
3156     ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
3157 {
3158     return ZOOM_options_get(scan->options, key);
3159 }
3160
3161 ZOOM_API(void)
3162     ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
3163                             const char *val)
3164 {
3165     ZOOM_options_set(scan->options, key, val);
3166 }
3167
3168 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
3169 {
3170     const char *str;
3171     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
3172     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3173     
3174     str = ZOOM_options_get(p->options, "package-name");
3175     if (str && *str)
3176         req->packageName = odr_strdup(p->odr_out, str);
3177     
3178     str = ZOOM_options_get(p->options, "user-id");
3179     if (str)
3180         req->userId = odr_strdup_null(p->odr_out, str);
3181     
3182     req->packageType = odr_oiddup(p->odr_out, oid);
3183
3184     str = ZOOM_options_get(p->options, "function");
3185     if (str)
3186     {
3187         if (!strcmp (str, "create"))
3188             *req->function = Z_ExtendedServicesRequest_create;
3189         if (!strcmp (str, "delete"))
3190             *req->function = Z_ExtendedServicesRequest_delete;
3191         if (!strcmp (str, "modify"))
3192             *req->function = Z_ExtendedServicesRequest_modify;
3193     }
3194
3195     str = ZOOM_options_get(p->options, "waitAction");
3196     if (str)
3197     {
3198         if (!strcmp (str, "wait"))
3199             *req->waitAction = Z_ExtendedServicesRequest_wait;
3200         if (!strcmp (str, "waitIfPossible"))
3201             *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
3202         if (!strcmp (str, "dontWait"))
3203             *req->waitAction = Z_ExtendedServicesRequest_dontWait;
3204         if (!strcmp (str, "dontReturnPackage"))
3205             *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
3206     }
3207     return apdu;
3208 }
3209
3210 static const char *ill_array_lookup(void *clientData, const char *idx)
3211 {
3212     ZOOM_package p = (ZOOM_package) clientData;
3213     return ZOOM_options_get(p->options, idx+4);
3214 }
3215
3216 static Z_External *encode_ill_request(ZOOM_package p)
3217 {
3218     ODR out = p->odr_out;
3219     ILL_Request *req;
3220     Z_External *r = 0;
3221     struct ill_get_ctl ctl;
3222         
3223     ctl.odr = p->odr_out;
3224     ctl.clientData = p;
3225     ctl.f = ill_array_lookup;
3226         
3227     req = ill_get_ILLRequest(&ctl, "ill", 0);
3228         
3229     if (!ill_Request(out, &req, 0, 0))
3230     {
3231         int ill_request_size;
3232         char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
3233         if (ill_request_buf)
3234             odr_setbuf(out, ill_request_buf, ill_request_size, 1);
3235         return 0;
3236     }
3237     else
3238     {
3239         int illRequest_size = 0;
3240         char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
3241                 
3242         r = (Z_External *) odr_malloc(out, sizeof(*r));
3243         r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
3244         r->indirect_reference = 0;
3245         r->descriptor = 0;
3246         r->which = Z_External_single;
3247                 
3248         r->u.single_ASN1_type =
3249             odr_create_Odr_oct(out,
3250                                (unsigned char *)illRequest_buf,
3251                                illRequest_size);
3252     }
3253     return r;
3254 }
3255
3256 static Z_ItemOrder *encode_item_order(ZOOM_package p)
3257 {
3258     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
3259     const char *str;
3260     int len;
3261     
3262     req->which = Z_IOItemOrder_esRequest;
3263     req->u.esRequest = (Z_IORequest *) 
3264         odr_malloc(p->odr_out,sizeof(Z_IORequest));
3265
3266     /* to keep part ... */
3267     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
3268         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
3269     req->u.esRequest->toKeep->supplDescription = 0;
3270     req->u.esRequest->toKeep->contact = (Z_IOContact *)
3271         odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
3272         
3273     str = ZOOM_options_get(p->options, "contact-name");
3274     req->u.esRequest->toKeep->contact->name =
3275         odr_strdup_null(p->odr_out, str);
3276         
3277     str = ZOOM_options_get(p->options, "contact-phone");
3278     req->u.esRequest->toKeep->contact->phone =
3279         odr_strdup_null(p->odr_out, str);
3280         
3281     str = ZOOM_options_get(p->options, "contact-email");
3282     req->u.esRequest->toKeep->contact->email =
3283         odr_strdup_null(p->odr_out, str);
3284         
3285     req->u.esRequest->toKeep->addlBilling = 0;
3286         
3287     /* not to keep part ... */
3288     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
3289         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
3290         
3291     str = ZOOM_options_get(p->options, "itemorder-setname");
3292     if (!str)
3293         str = "default";
3294
3295     if (!*str) 
3296         req->u.esRequest->notToKeep->resultSetItem = 0;
3297     else
3298     {
3299         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
3300             odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
3301
3302         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
3303             odr_strdup(p->odr_out, str);
3304         req->u.esRequest->notToKeep->resultSetItem->item =
3305             odr_intdup(p->odr_out, 0);
3306         
3307         str = ZOOM_options_get(p->options, "itemorder-item");
3308         *req->u.esRequest->notToKeep->resultSetItem->item =
3309             (str ? atoi(str) : 1);
3310     }
3311
3312     str = ZOOM_options_getl(p->options, "doc", &len);
3313     if (str)
3314     {
3315         req->u.esRequest->notToKeep->itemRequest =
3316             z_ext_record_xml(p->odr_out, str, len);
3317     }
3318     else
3319         req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
3320     
3321     return req;
3322 }
3323
3324 Z_APDU *create_admin_package(ZOOM_package p, int type, 
3325                              Z_ESAdminOriginPartToKeep **toKeepP,
3326                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
3327 {
3328     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
3329     if (apdu)
3330     {
3331         Z_ESAdminOriginPartToKeep  *toKeep;
3332         Z_ESAdminOriginPartNotToKeep  *notToKeep;
3333         Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3334         const char *first_db = "Default";
3335         int num_db;
3336         char **db = set_DatabaseNames(p->connection, p->options, &num_db,
3337                                       p->odr_out);
3338         if (num_db > 0)
3339             first_db = db[0];
3340             
3341         r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
3342         r->descriptor = 0;
3343         r->indirect_reference = 0;
3344         r->which = Z_External_ESAdmin;
3345         
3346         r->u.adminService = (Z_Admin *)
3347             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
3348         r->u.adminService->which = Z_Admin_esRequest;
3349         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
3350             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
3351         
3352         toKeep = r->u.adminService->u.esRequest->toKeep =
3353             (Z_ESAdminOriginPartToKeep *) 
3354             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
3355         toKeep->which = type;
3356         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3357         toKeep->u.create = odr_nullval();
3358         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3359         
3360         r->u.adminService->u.esRequest->notToKeep = notToKeep =
3361             (Z_ESAdminOriginPartNotToKeep *)
3362             odr_malloc(p->odr_out,
3363                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
3364         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
3365         notToKeep->u.recordsWillFollow = odr_nullval();
3366         if (toKeepP)
3367             *toKeepP = toKeep;
3368         if (notToKeepP)
3369             *notToKeepP = notToKeep;
3370     }
3371     return apdu;
3372 }
3373
3374 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
3375 {
3376     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
3377     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3378     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
3379     int len;
3380     const char *doc = ZOOM_options_getl(p->options, "doc", &len);
3381
3382     if (!doc)
3383     {
3384         doc = "";
3385         len = 0;
3386     }
3387
3388     req->taskSpecificParameters = ext;
3389     ext->direct_reference = req->packageType;
3390     ext->descriptor = 0;
3391     ext->indirect_reference = 0;
3392     
3393     ext->which = Z_External_octet;
3394     ext->u.single_ASN1_type =
3395         odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc, len);
3396     return apdu;
3397 }
3398
3399 static Z_APDU *create_update_package(ZOOM_package p)
3400 {
3401     Z_APDU *apdu = 0;
3402     const char *first_db = "Default";
3403     int num_db;
3404     char **db = set_DatabaseNames(p->connection, p->options, &num_db, p->odr_out);
3405     const char *action = ZOOM_options_get(p->options, "action");
3406     int recordIdOpaque_len;
3407     const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
3408         &recordIdOpaque_len);
3409     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
3410     int record_len;
3411     const char *record_buf = ZOOM_options_getl(p->options, "record",
3412         &record_len);
3413     int recordOpaque_len;
3414     const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
3415         &recordOpaque_len);
3416     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
3417     const char *version = ZOOM_options_get(p->options, "updateVersion");
3418
3419     const char *correlationInfo_note =
3420         ZOOM_options_get(p->options, "correlationInfo.note");
3421     const char *correlationInfo_id =
3422         ZOOM_options_get(p->options, "correlationInfo.id");
3423     int action_no = -1;
3424     Odr_oid *syntax_oid = 0;
3425     const Odr_oid *package_oid = yaz_oid_extserv_database_update;
3426
3427     if (!version)
3428         version = "3";
3429     if (!syntax_str)
3430         syntax_str = "xml";
3431     if (!record_buf && !recordOpaque_buf)
3432     {
3433         record_buf = "void";
3434         record_len = 4;
3435         syntax_str = "SUTRS";
3436     }
3437
3438     if (syntax_str)
3439     {
3440         syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
3441                                            CLASS_RECSYN, syntax_str,
3442                                            p->odr_out);
3443     }
3444     if (!syntax_oid)
3445         return 0;
3446
3447     if (num_db > 0)
3448         first_db = db[0];
3449     
3450     switch(*version)
3451     {
3452     case '1':
3453         package_oid = yaz_oid_extserv_database_update_first_version;
3454         /* old update does not support specialUpdate */
3455         if (!action)
3456             action = "recordInsert";
3457         break;
3458     case '2':
3459         if (!action)
3460             action = "specialUpdate";
3461         package_oid = yaz_oid_extserv_database_update_second_version;
3462         break;
3463     case '3':
3464         if (!action)
3465             action = "specialUpdate";
3466         package_oid = yaz_oid_extserv_database_update;
3467         break;
3468     default:
3469         return 0;
3470     }
3471     
3472     if (!strcmp(action, "recordInsert"))
3473         action_no = Z_IUOriginPartToKeep_recordInsert;
3474     else if (!strcmp(action, "recordReplace"))
3475         action_no = Z_IUOriginPartToKeep_recordReplace;
3476     else if (!strcmp(action, "recordDelete"))
3477         action_no = Z_IUOriginPartToKeep_recordDelete;
3478     else if (!strcmp(action, "elementUpdate"))
3479         action_no = Z_IUOriginPartToKeep_elementUpdate;
3480     else if (!strcmp(action, "specialUpdate"))
3481         action_no = Z_IUOriginPartToKeep_specialUpdate;
3482     else
3483         return 0;
3484
3485     apdu = create_es_package(p, package_oid);
3486     if (apdu)
3487     {
3488         Z_IUOriginPartToKeep *toKeep;
3489         Z_IUSuppliedRecords *notToKeep;
3490         Z_External *r = (Z_External *)
3491             odr_malloc(p->odr_out, sizeof(*r));
3492         const char *elementSetName =
3493             ZOOM_options_get(p->options, "elementSetName");
3494         
3495         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3496         
3497         r->direct_reference = odr_oiddup(p->odr_out, package_oid);
3498         r->descriptor = 0;
3499         r->which = Z_External_update;
3500         r->indirect_reference = 0;
3501         r->u.update = (Z_IUUpdate *)
3502             odr_malloc(p->odr_out, sizeof(*r->u.update));
3503         
3504         r->u.update->which = Z_IUUpdate_esRequest;
3505         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3506             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3507         toKeep = r->u.update->u.esRequest->toKeep = 
3508             (Z_IUOriginPartToKeep *)
3509             odr_malloc(p->odr_out, sizeof(*toKeep));
3510         
3511         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3512         toKeep->schema = 0;
3513         
3514         toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
3515             
3516         toKeep->actionQualifier = 0;
3517         toKeep->action = odr_intdup(p->odr_out, action_no);
3518         
3519         notToKeep = r->u.update->u.esRequest->notToKeep = 
3520             (Z_IUSuppliedRecords *)
3521             odr_malloc(p->odr_out, sizeof(*notToKeep));
3522         notToKeep->num = 1;
3523         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3524             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3525         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3526             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3527         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3528         if (recordIdOpaque)
3529         {
3530             notToKeep->elements[0]->u.opaque = 
3531                 odr_create_Odr_oct(p->odr_out,
3532                                    (const unsigned char *) recordIdOpaque,
3533                                    recordIdOpaque_len);
3534         }
3535         else if (recordIdNumber)
3536         {
3537             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3538             
3539             notToKeep->elements[0]->u.number =
3540                 odr_intdup(p->odr_out, atoi(recordIdNumber));
3541         }
3542         else
3543             notToKeep->elements[0]->u.opaque = 0;
3544         notToKeep->elements[0]->supplementalId = 0;
3545         if (correlationInfo_note || correlationInfo_id)
3546         {
3547             Z_IUCorrelationInfo *ci;
3548             ci = notToKeep->elements[0]->correlationInfo =
3549                 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
3550             ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
3551             ci->id = correlationInfo_id ?
3552                 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
3553         }
3554         else
3555             notToKeep->elements[0]->correlationInfo = 0;
3556         if (recordOpaque_buf)
3557         {
3558             notToKeep->elements[0]->record =
3559                 z_ext_record_oid_any(p->odr_out, syntax_oid,
3560                                  recordOpaque_buf, recordOpaque_len);
3561         }
3562         else
3563         {
3564             notToKeep->elements[0]->record =
3565                 z_ext_record_oid(p->odr_out, syntax_oid,
3566                                  record_buf, record_len);
3567         }
3568     }
3569     if (0 && apdu)
3570     {
3571         ODR print = odr_createmem(ODR_PRINT);
3572
3573         z_APDU(print, &apdu, 0, 0);
3574         odr_destroy(print);
3575     }
3576     return apdu;
3577 }
3578
3579 ZOOM_API(void)
3580     ZOOM_package_send(ZOOM_package p, const char *type)
3581 {
3582     Z_APDU *apdu = 0;
3583     ZOOM_connection c;
3584     if (!p)
3585         return;
3586     c = p->connection;
3587     odr_reset(p->odr_out);
3588     xfree(p->buf_out);
3589     p->buf_out = 0;
3590     if (!strcmp(type, "itemorder"))
3591     {
3592         apdu = create_es_package(p, yaz_oid_extserv_item_order);
3593         if (apdu)
3594         {
3595             Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3596             
3597             r->direct_reference = 
3598                 odr_oiddup(p->odr_out, yaz_oid_extserv_item_order);
3599             r->descriptor = 0;
3600             r->which = Z_External_itemOrder;
3601             r->indirect_reference = 0;
3602             r->u.itemOrder = encode_item_order(p);
3603
3604             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3605         }
3606     }
3607     else if (!strcmp(type, "create"))  /* create database */
3608     {
3609         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3610                                     0, 0);
3611     }   
3612     else if (!strcmp(type, "drop"))  /* drop database */
3613     {
3614         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3615                                     0, 0);
3616     }
3617     else if (!strcmp(type, "commit"))  /* commit changes */
3618     {
3619         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3620                                     0, 0);
3621     }
3622     else if (!strcmp(type, "update")) /* update record(s) */
3623     {
3624         apdu = create_update_package(p);
3625     }
3626     else if (!strcmp(type, "xmlupdate"))
3627     {
3628         apdu = create_xmlupdate_package(p);
3629     }
3630     if (apdu)
3631     {
3632         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3633         {
3634             char *buf;
3635
3636             ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
3637             task->u.package = p;
3638             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3639             p->buf_out = (char *) xmalloc(p->len_out);
3640             memcpy(p->buf_out, buf, p->len_out);
3641             
3642             (p->refcount)++;
3643             if (!c->async)
3644             {
3645                 while (ZOOM_event(1, &c))
3646                     ;
3647             }
3648         }
3649     }
3650 }
3651
3652 ZOOM_API(ZOOM_package)
3653     ZOOM_connection_package(ZOOM_connection c, ZOOM_options options)
3654 {
3655     ZOOM_package p = (ZOOM_package) xmalloc(sizeof(*p));
3656
3657     p->connection = c;
3658     p->odr_out = odr_createmem(ODR_ENCODE);
3659     p->options = ZOOM_options_create_with_parent2(options, c->options);
3660     p->refcount = 1;
3661     p->buf_out = 0;
3662     p->len_out = 0;
3663     return p;
3664 }
3665
3666 ZOOM_API(void)
3667     ZOOM_package_destroy(ZOOM_package p)
3668 {
3669     if (!p)
3670         return;
3671     (p->refcount)--;
3672     if (p->refcount == 0)
3673     {
3674         odr_destroy(p->odr_out);
3675         xfree(p->buf_out);
3676         
3677         ZOOM_options_destroy(p->options);
3678         xfree(p);
3679     }
3680 }
3681
3682 ZOOM_API(const char *)
3683     ZOOM_package_option_get(ZOOM_package p, const char *key)
3684 {
3685     return ZOOM_options_get(p->options, key);
3686 }
3687
3688 ZOOM_API(const char *)
3689     ZOOM_package_option_getl(ZOOM_package p, const char *key, int *lenp)
3690 {
3691     return ZOOM_options_getl(p->options, key, lenp);
3692 }
3693
3694 ZOOM_API(void)
3695     ZOOM_package_option_set(ZOOM_package p, const char *key,
3696                             const char *val)
3697 {
3698     ZOOM_options_set(p->options, key, val);
3699 }
3700
3701 ZOOM_API(void)
3702     ZOOM_package_option_setl(ZOOM_package p, const char *key,
3703                              const char *val, int len)