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