Add detail logging of record create/destroy
[yaz-moved-to-github.git] / src / zoom-c.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file zoom-c.c
7  * \brief Implements ZOOM C interface.
8  */
9
10 #include <assert.h>
11 #include <string.h>
12 #include <errno.h>
13 #include "zoom-p.h"
14
15 #include <yaz/yaz-util.h>
16 #include <yaz/xmalloc.h>
17 #include <yaz/otherinfo.h>
18 #include <yaz/log.h>
19 #include <yaz/pquery.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/charneg.h>
23 #include <yaz/ill.h>
24 #include <yaz/srw.h>
25 #include <yaz/cql.h>
26 #include <yaz/ccl.h>
27 #include <yaz/query-charset.h>
28 #include <yaz/copy_types.h>
29 #include <yaz/snprintf.h>
30
31 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 ZOOM_API(const char *) ZOOM_get_event_str(int event)
45 {
46     static const char *ar[] = {
47         "NONE",
48         "CONNECT",
49         "SEND_DATA",
50         "RECV_DATA",
51         "TIMEOUT",
52         "UNKNOWN",
53         "SEND_APDU",
54         "RECV_APDU",
55         "RECV_RECORD",
56         "RECV_SEARCH",
57         "END"
58     };
59     return ar[event];
60 }
61
62 /*
63  * This wrapper is just for logging failed lookups.  It would be nicer
64  * if it could cause failure when a lookup fails, but that's hard.
65  */
66 static Odr_oid *zoom_yaz_str_to_z3950oid(ZOOM_connection c,
67                                      oid_class oid_class, const char *str) {
68     Odr_oid *res = yaz_string_to_oid_odr(yaz_oid_std(), oid_class, str,
69                                      c->odr_out);
70     if (res == 0)
71         yaz_log(YLOG_WARN, "%p OID lookup (%d, '%s') failed",
72                 c, (int) oid_class, str);
73     return res;
74 }
75
76
77 static void initlog(void)
78 {
79     static int log_level_initialized = 0;
80     if (!log_level_initialized)
81     {
82         log_api = yaz_log_module_level("zoom");
83         log_details = yaz_log_module_level("zoomdetails");
84         log_level_initialized = 1;
85     }
86 }
87
88 static ZOOM_Event ZOOM_Event_create(int kind)
89 {
90     ZOOM_Event event = (ZOOM_Event) xmalloc(sizeof(*event));
91     event->kind = kind;
92     event->next = 0;
93     event->prev = 0;
94     yaz_log(log_details, "ZOOM_Event_create(kind=%d)", kind);
95     return event;
96 }
97
98 static void ZOOM_Event_destroy(ZOOM_Event event)
99 {
100     xfree(event);
101 }
102
103 static void ZOOM_connection_put_event(ZOOM_connection c, ZOOM_Event event)
104 {
105     if (c->m_queue_back)
106     {
107         c->m_queue_back->prev = event;
108         assert(c->m_queue_front);
109     }
110     else
111     {
112         assert(!c->m_queue_front);
113         c->m_queue_front = event;
114     }
115     event->next = c->m_queue_back;
116     event->prev = 0;
117     c->m_queue_back = event;
118 }
119
120 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
121 {
122     ZOOM_Event event = c->m_queue_front;
123     if (!event)
124     {
125         c->last_event = ZOOM_EVENT_NONE;
126         return 0;
127     }
128     assert(c->m_queue_back);
129     c->m_queue_front = event->prev;
130     if (c->m_queue_front)
131     {
132         assert(c->m_queue_back);
133         c->m_queue_front->next = 0;
134     }
135     else
136         c->m_queue_back = 0;
137     c->last_event = event->kind;
138     return event;
139 }
140
141 static void ZOOM_connection_remove_events(ZOOM_connection c)
142 {
143     ZOOM_Event event;
144     while ((event = ZOOM_connection_get_event(c)))
145         ZOOM_Event_destroy(event);
146 }
147
148 ZOOM_API(int) ZOOM_connection_peek_event(ZOOM_connection c)
149 {
150     ZOOM_Event event = c->m_queue_front;
151
152     return event ? event->kind : ZOOM_EVENT_NONE;
153 }
154
155 void ZOOM_connection_remove_tasks(ZOOM_connection c);
156
157 static void set_dset_error(ZOOM_connection c, int error,
158                            const char *dset,
159                            const char *addinfo, const char *addinfo2)
160 {
161     char *cp;
162
163     xfree(c->addinfo);
164     c->addinfo = 0;
165     c->error = error;
166     if (!c->diagset || strcmp(dset, c->diagset))
167     {
168         xfree(c->diagset);
169         c->diagset = xstrdup(dset);
170         /* remove integer part from SRW diagset .. */
171         if ((cp = strrchr(c->diagset, '/')))
172             *cp = '\0';
173     }
174     if (addinfo && addinfo2)
175     {
176         c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
177         strcpy(c->addinfo, addinfo);
178         strcat(c->addinfo, addinfo2);
179     }
180     else if (addinfo)
181         c->addinfo = xstrdup(addinfo);
182     if (error != ZOOM_ERROR_NONE)
183     {
184         yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
185                 c, c->host_port ? c->host_port : "<>", dset, error,
186                 addinfo ? addinfo : "",
187                 addinfo2 ? addinfo2 : "");
188         ZOOM_connection_remove_tasks(c);
189     }
190 }
191
192 static int uri_to_code(const char *uri)
193 {
194     int code = 0;       
195     const char *cp;
196     if ((cp = strrchr(uri, '/')))
197         code = atoi(cp+1);
198     return code;
199 }
200
201 #if YAZ_HAVE_XML2
202 static void set_HTTP_error(ZOOM_connection c, int error,
203                            const char *addinfo, const char *addinfo2)
204 {
205     set_dset_error(c, error, "HTTP", addinfo, addinfo2);
206 }
207
208 static void set_SRU_error(ZOOM_connection c, Z_SRW_diagnostic *d)
209 {
210     const char *uri = d->uri;
211     if (uri)
212         set_dset_error(c, uri_to_code(uri), uri, d->details, 0);
213 }
214
215 #endif
216
217
218 static void set_ZOOM_error(ZOOM_connection c, int error,
219                            const char *addinfo)
220 {
221     set_dset_error(c, error, "ZOOM", addinfo, 0);
222 }
223
224 static void clear_error(ZOOM_connection c)
225 {
226     /*
227      * If an error is tied to an operation then it's ok to clear: for
228      * example, a diagnostic returned from a search is cleared by a
229      * subsequent search.  However, problems such as Connection Lost
230      * or Init Refused are not cleared, because they are not
231      * recoverable: doing another search doesn't help.
232      */
233
234     ZOOM_connection_remove_events(c);
235     switch (c->error)
236     {
237     case ZOOM_ERROR_CONNECT:
238     case ZOOM_ERROR_MEMORY:
239     case ZOOM_ERROR_DECODE:
240     case ZOOM_ERROR_CONNECTION_LOST:
241     case ZOOM_ERROR_INIT:
242     case ZOOM_ERROR_INTERNAL:
243     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
244         break;
245     default:
246         set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
247     }
248 }
249
250 void ZOOM_connection_show_task(ZOOM_task task)
251 {
252     switch(task->which)
253     {
254     case ZOOM_TASK_SEARCH:
255         yaz_log(YLOG_LOG, "search p=%p", task);
256         break;
257     case ZOOM_TASK_RETRIEVE:
258         yaz_log(YLOG_LOG, "retrieve p=%p", task);
259         break;
260     case ZOOM_TASK_CONNECT:
261         yaz_log(YLOG_LOG, "connect p=%p", task);
262         break;
263     case ZOOM_TASK_SCAN:
264         yaz_log(YLOG_LOG, "scan p=%p", task);
265         break;
266     }
267 }
268
269 void ZOOM_connection_show_tasks(ZOOM_connection c)
270 {
271     ZOOM_task task;
272     yaz_log(YLOG_LOG, "connection p=%p tasks", c);
273     for (task = c->tasks; task; task = task->next)
274         ZOOM_connection_show_task(task);
275 }
276
277 ZOOM_task ZOOM_connection_add_task(ZOOM_connection c, int which)
278 {
279     ZOOM_task *taskp = &c->tasks;
280     while (*taskp)
281         taskp = &(*taskp)->next;
282     *taskp = (ZOOM_task) xmalloc(sizeof(**taskp));
283     (*taskp)->running = 0;
284     (*taskp)->which = which;
285     (*taskp)->next = 0;
286     clear_error(c);
287     return *taskp;
288 }
289
290 ZOOM_API(int) ZOOM_connection_is_idle(ZOOM_connection c)
291 {
292     return c->tasks ? 0 : 1;
293 }
294
295 ZOOM_task ZOOM_connection_insert_task(ZOOM_connection c, int which)
296 {
297     ZOOM_task task = (ZOOM_task) xmalloc(sizeof(*task));
298
299     task->next = c->tasks;
300     c->tasks = task;
301
302     task->running = 0;
303     task->which = which;
304     clear_error(c);
305     return task;
306 }
307
308 void ZOOM_connection_remove_task(ZOOM_connection c)
309 {
310     ZOOM_task task = c->tasks;
311
312     if (task)
313     {
314         c->tasks = task->next;
315         switch (task->which)
316         {
317         case ZOOM_TASK_SEARCH:
318             resultset_destroy(task->u.search.resultset);
319             xfree(task->u.search.syntax);
320             xfree(task->u.search.elementSetName);
321             break;
322         case ZOOM_TASK_RETRIEVE:
323             resultset_destroy(task->u.retrieve.resultset);
324             xfree(task->u.retrieve.syntax);
325             xfree(task->u.retrieve.elementSetName);
326             break;
327         case ZOOM_TASK_CONNECT:
328             break;
329         case ZOOM_TASK_SCAN:
330             ZOOM_scanset_destroy(task->u.scan.scan);
331             break;
332         case ZOOM_TASK_PACKAGE:
333             ZOOM_package_destroy(task->u.package);
334             break;
335         case ZOOM_TASK_SORT:
336             resultset_destroy(task->u.sort.resultset);
337             ZOOM_query_destroy(task->u.sort.q);
338             break;
339         default:
340             assert(0);
341         }
342         xfree(task);
343
344         if (!c->tasks)
345         {
346             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
347             ZOOM_connection_put_event(c, event);
348         }
349     }
350 }
351
352 void ZOOM_connection_remove_tasks(ZOOM_connection c)
353 {
354     while (c->tasks)
355         ZOOM_connection_remove_task(c);
356 }
357
358 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
359                                        const char *syntax,
360                                        const char *elementSetName);
361
362 ZOOM_API(ZOOM_connection)
363     ZOOM_connection_create(ZOOM_options options)
364 {
365     ZOOM_connection c = (ZOOM_connection) xmalloc(sizeof(*c));
366
367     initlog();
368
369     yaz_log(log_api, "%p ZOOM_connection_create", c);
370
371     c->proto = PROTO_Z3950;
372     c->cs = 0;
373     ZOOM_connection_set_mask(c, 0);
374     c->reconnect_ok = 0;
375     c->state = STATE_IDLE;
376     c->addinfo = 0;
377     c->diagset = 0;
378     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
379     c->buf_in = 0;
380     c->len_in = 0;
381     c->buf_out = 0;
382     c->len_out = 0;
383     c->resultsets = 0;
384
385     c->options = ZOOM_options_create_with_parent(options);
386
387     c->host_port = 0;
388     c->path = 0;
389     c->proxy = 0;
390     
391     c->charset = c->lang = 0;
392
393     c->cookie_out = 0;
394     c->cookie_in = 0;
395     c->client_IP = 0;
396     c->tasks = 0;
397
398     c->user = 0;
399     c->group = 0;
400     c->password = 0;
401
402     c->maximum_record_size = 0;
403     c->preferred_message_size = 0;
404
405     c->odr_in = odr_createmem(ODR_DECODE);
406     c->odr_out = odr_createmem(ODR_ENCODE);
407     c->odr_print = 0;
408
409     c->async = 0;
410     c->support_named_resultsets = 0;
411     c->last_event = ZOOM_EVENT_NONE;
412
413     c->m_queue_front = 0;
414     c->m_queue_back = 0;
415
416     c->sru_version = 0;
417     c->no_redirects = 0;
418     return c;
419 }
420
421
422 /* set database names. Take local databases (if set); otherwise
423    take databases given in ZURL (if set); otherwise use Default */
424 static char **set_DatabaseNames(ZOOM_connection con, ZOOM_options options,
425                                 int *num, ODR odr)
426 {
427     char **databaseNames;
428     const char *cp = ZOOM_options_get(options, "databaseName");
429     
430     if ((!cp || !*cp) && con->host_port)
431     {
432         if (strncmp(con->host_port, "unix:", 5) == 0)
433             cp = strchr(con->host_port+5, ':');
434         else
435             cp = strchr(con->host_port, '/');
436         if (cp)
437             cp++;
438     }
439     if (!cp)
440         cp = "Default";
441     nmem_strsplit(odr_getmem(odr), "+", cp,  &databaseNames, num);
442     return databaseNames;
443 }
444
445 ZOOM_API(ZOOM_connection)
446     ZOOM_connection_new(const char *host, int portnum)
447 {
448     ZOOM_connection c = ZOOM_connection_create(0);
449
450     ZOOM_connection_connect(c, host, portnum);
451     return c;
452 }
453
454 static zoom_sru_mode get_sru_mode_from_string(const char *s)
455 {
456     if (!s || !*s)
457         return zoom_sru_soap;
458     if (!yaz_matchstr(s, "soap"))
459         return zoom_sru_soap;
460     else if (!yaz_matchstr(s, "get"))
461         return zoom_sru_get;
462     else if (!yaz_matchstr(s, "post"))
463         return zoom_sru_post;
464     return zoom_sru_error;
465 }
466
467 ZOOM_API(void)
468     ZOOM_connection_connect(ZOOM_connection c,
469                             const char *host, int portnum)
470 {
471     const char *val;
472     ZOOM_task task;
473
474     initlog();
475
476     yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
477             c, host ? host : "null", portnum);
478
479     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
480     ZOOM_connection_remove_tasks(c);
481
482     if (c->odr_print)
483     {
484         odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
485         odr_destroy(c->odr_print);
486     }
487     if (ZOOM_options_get_bool(c->options, "apdulog", 0))
488     {
489         c->odr_print = odr_createmem(ODR_PRINT);
490         odr_setprint(c->odr_print, yaz_log_file());
491     }
492     else
493         c->odr_print = 0;
494
495     if (c->cs)
496     {
497         yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
498         c->reconnect_ok = 1;
499         return;
500     }
501     yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
502     xfree(c->proxy);
503     c->proxy = 0;
504     val = ZOOM_options_get(c->options, "proxy");
505     if (val && *val)
506     {
507         yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
508         c->proxy = xstrdup(val);
509     }
510
511     xfree(c->charset);
512     c->charset = 0;
513     val = ZOOM_options_get(c->options, "charset");
514     if (val && *val)
515     {
516         yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
517         c->charset = xstrdup(val);
518     }
519
520     xfree(c->lang);
521     val = ZOOM_options_get(c->options, "lang");
522     if (val && *val)
523     {
524         yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
525         c->lang = xstrdup(val);
526     }
527     else
528         c->lang = 0;
529
530     if (host)
531     {
532         xfree(c->host_port);
533         if (portnum)
534         {
535             char hostn[128];
536             sprintf(hostn, "%.80s:%d", host, portnum);
537             c->host_port = xstrdup(hostn);
538         }
539         else
540             c->host_port = xstrdup(host);
541     }        
542
543     {
544         /*
545          * If the "<scheme>:" part of the host string is preceded by one
546          * or more comma-separated <name>=<value> pairs, these are taken
547          * to be options to be set on the connection object.  Among other
548          * applications, this facility can be used to embed authentication
549          * in a host string:
550          *          user=admin,password=secret,tcp:localhost:9999
551          */
552         char *remainder = c->host_port;
553         char *pcolon = strchr(remainder, ':');
554         char *pcomma;
555         char *pequals;
556         while ((pcomma = strchr(remainder, ',')) != 0 &&
557                (pcolon == 0 || pcomma < pcolon)) {
558             *pcomma = '\0';
559             if ((pequals = strchr(remainder, '=')) != 0) {
560                 *pequals = '\0';
561                 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
562                 ZOOM_connection_option_set(c, remainder, pequals+1);
563             }
564             remainder = pcomma+1;
565         }
566
567         if (remainder != c->host_port) {
568             xfree(c->host_port);
569             c->host_port = xstrdup(remainder);
570             /*printf("# reset hp='%s'\n", remainder);*/
571         }
572     }
573
574     val = ZOOM_options_get(c->options, "sru");
575     c->sru_mode = get_sru_mode_from_string(val);
576
577     xfree(c->sru_version);
578     val = ZOOM_options_get(c->options, "sru_version");
579     c->sru_version = xstrdup(val ? val : "1.2");
580
581     ZOOM_options_set(c->options, "host", c->host_port);
582
583     xfree(c->cookie_out);
584     c->cookie_out = 0;
585     val = ZOOM_options_get(c->options, "cookie");
586     if (val && *val)
587     { 
588         yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
589         c->cookie_out = xstrdup(val);
590     }
591
592     xfree(c->client_IP);
593     c->client_IP = 0;
594     val = ZOOM_options_get(c->options, "clientIP");
595     if (val && *val)
596     {
597         yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
598                 c, val);
599         c->client_IP = xstrdup(val);
600     }
601
602     xfree(c->group);
603     c->group = 0;
604     val = ZOOM_options_get(c->options, "group");
605     if (val && *val)
606         c->group = xstrdup(val);
607
608     xfree(c->user);
609     c->user = 0;
610     val = ZOOM_options_get(c->options, "user");
611     if (val && *val)
612         c->user = xstrdup(val);
613
614     xfree(c->password);
615     c->password = 0;
616     val = ZOOM_options_get(c->options, "password");
617     if (!val)
618         val = ZOOM_options_get(c->options, "pass");
619
620     if (val && *val)
621         c->password = xstrdup(val);
622     
623     c->maximum_record_size =
624         ZOOM_options_get_int(c->options, "maximumRecordSize", 1024*1024);
625     c->preferred_message_size =
626         ZOOM_options_get_int(c->options, "preferredMessageSize", 1024*1024);
627
628     c->async = ZOOM_options_get_bool(c->options, "async", 0);
629     yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
630  
631     task = ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
632
633     if (!c->async)
634     {
635         while (ZOOM_event(1, &c))
636             ;
637     }
638 }
639
640 ZOOM_API(ZOOM_query)
641     ZOOM_query_create(void)
642 {
643     ZOOM_query s = (ZOOM_query) xmalloc(sizeof(*s));
644
645     yaz_log(log_details, "%p ZOOM_query_create", s);
646     s->refcount = 1;
647     s->z_query = 0;
648     s->sort_spec = 0;
649     s->odr = odr_createmem(ODR_ENCODE);
650     s->query_string = 0;
651
652     return s;
653 }
654
655 ZOOM_API(void)
656     ZOOM_query_destroy(ZOOM_query s)
657 {
658     if (!s)
659         return;
660
661     (s->refcount)--;
662     yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
663     if (s->refcount == 0)
664     {
665         odr_destroy(s->odr);
666         xfree(s);
667     }
668 }
669
670 ZOOM_API(int)
671     ZOOM_query_prefix(ZOOM_query s, const char *str)
672 {
673     s->query_string = odr_strdup(s->odr, str);
674     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
675     s->z_query->which = Z_Query_type_1;
676     s->z_query->u.type_1 =  p_query_rpn(s->odr, str);
677     if (!s->z_query->u.type_1)
678     {
679         yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
680         s->z_query = 0;
681         return -1;
682     }
683     yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
684     return 0;
685 }
686
687 ZOOM_API(int)
688     ZOOM_query_cql(ZOOM_query s, const char *str)
689 {
690     Z_External *ext;
691
692     s->query_string = odr_strdup(s->odr, str);
693
694     ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
695     ext->direct_reference = odr_oiddup(s->odr, yaz_oid_userinfo_cql);
696     ext->indirect_reference = 0;
697     ext->descriptor = 0;
698     ext->which = Z_External_CQL;
699     ext->u.cql = s->query_string;
700     
701     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
702     s->z_query->which = Z_Query_type_104;
703     s->z_query->u.type_104 =  ext;
704
705     yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
706
707     return 0;
708 }
709
710 /*
711  * Translate the CQL string client-side into RPN which is passed to
712  * the server.  This is useful for server's that don't themselves
713  * support CQL, for which ZOOM_query_cql() is useless.  `conn' is used
714  * only as a place to stash diagnostics if compilation fails; if this
715  * information is not needed, a null pointer may be used.
716  */
717 ZOOM_API(int)
718     ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
719 {
720     char *rpn;
721     int ret;
722     ZOOM_connection freeme = 0;
723
724     yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
725     if (conn == 0)
726         conn = freeme = ZOOM_connection_create(0);
727
728     rpn = cql2pqf(conn, str);
729     if (freeme != 0)
730         ZOOM_connection_destroy(freeme);
731     if (rpn == 0)
732         return -1;
733
734     ret = ZOOM_query_prefix(s, rpn);
735     xfree(rpn);
736     return ret;
737 }
738
739 /*
740  * Analogous in every way to ZOOM_query_cql2rpn(), except that there
741  * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
742  * to the server, as the YAZ GFS doesn't know how to handle this.
743  */
744 ZOOM_API(int)
745     ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, const char *config,
746                        int *ccl_error, const char **error_string,
747                        int *error_pos)
748 {
749     int ret;
750     struct ccl_rpn_node *rpn;
751     CCL_bibset bibset = ccl_qual_mk();
752
753     if (config)
754         ccl_qual_buf(bibset, config);
755
756     rpn = ccl_find_str(bibset, str, ccl_error, error_pos);
757     if (!rpn)
758     {
759         *error_string = ccl_err_msg(*ccl_error);
760         ret = -1;
761     }
762     else
763     {
764         WRBUF wr = wrbuf_alloc();
765         ccl_pquery(wr, rpn);
766         ccl_rpn_delete(rpn);
767         ret = ZOOM_query_prefix(s, wrbuf_cstr(wr));
768         wrbuf_destroy(wr);
769     }
770     ccl_qual_rm(&bibset);
771     return ret;
772 }
773
774 ZOOM_API(int)
775     ZOOM_query_sortby(ZOOM_query s, const char *criteria)
776 {
777     s->sort_spec = yaz_sort_spec(s->odr, criteria);
778     if (!s->sort_spec)
779     {
780         yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
781                 s, criteria);
782         return -1;
783     }
784     yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
785     return 0;
786 }
787
788 static zoom_ret do_write(ZOOM_connection c);
789
790 ZOOM_API(void)
791     ZOOM_connection_destroy(ZOOM_connection c)
792 {
793     ZOOM_resultsets list;
794     if (!c)
795         return;
796     yaz_log(log_api, "%p ZOOM_connection_destroy", c);
797     if (c->cs)
798         cs_close(c->cs);
799
800     // Remove the connection's usage of resultsets
801     list = c->resultsets;
802     while (list) {
803         ZOOM_resultsets removed = list;
804         ZOOM_resultset_destroy(list->resultset);
805         list = list->next;
806         xfree(removed);
807     }
808
809     xfree(c->buf_in);
810     xfree(c->addinfo);
811     xfree(c->diagset);
812     odr_destroy(c->odr_in);
813     odr_destroy(c->odr_out);
814     if (c->odr_print)
815     {
816         odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
817         odr_destroy(c->odr_print);
818     }
819     ZOOM_options_destroy(c->options);
820     ZOOM_connection_remove_tasks(c);
821     ZOOM_connection_remove_events(c);
822     xfree(c->host_port);
823     xfree(c->path);
824     xfree(c->proxy);
825     xfree(c->charset);
826     xfree(c->lang);
827     xfree(c->cookie_out);
828     xfree(c->cookie_in);
829     xfree(c->client_IP);
830     xfree(c->user);
831     xfree(c->group);
832     xfree(c->password);
833     xfree(c->sru_version);
834     xfree(c);
835 }
836
837 void ZOOM_resultset_addref(ZOOM_resultset r)
838 {
839     if (r)
840     {
841         yaz_mutex_enter(r->mutex);
842         (r->refcount)++;
843         yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
844                 r, r->refcount);
845         yaz_mutex_leave(r->mutex);
846     }
847 }
848
849 ZOOM_resultset ZOOM_resultset_create(void)
850 {
851     int i;
852     ZOOM_resultset r = (ZOOM_resultset) xmalloc(sizeof(*r));
853
854     initlog();
855
856     yaz_log(log_details, "%p ZOOM_resultset_create", r);
857     r->refcount = 1;
858     r->size = 0;
859     r->odr = odr_createmem(ODR_ENCODE);
860     r->piggyback = 1;
861     r->setname = 0;
862     r->schema = 0;
863     r->step = 0;
864     for (i = 0; i<RECORD_HASH_SIZE; i++)
865         r->record_hash[i] = 0;
866     r->r_sort_spec = 0;
867     r->query = 0;
868     r->connection = 0;
869     r->databaseNames = 0;
870     r->num_databaseNames = 0;
871     r->mutex = 0;
872     yaz_mutex_create(&r->mutex);
873     return r;
874 }
875
876 ZOOM_API(ZOOM_resultset)
877     ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
878 {
879     ZOOM_resultset r;
880     ZOOM_query s = ZOOM_query_create();
881
882     ZOOM_query_prefix(s, q);
883
884     r = ZOOM_connection_search(c, s);
885     ZOOM_query_destroy(s);
886     return r;
887 }
888
889 ZOOM_API(ZOOM_resultset)
890     ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
891 {
892     ZOOM_resultset r = ZOOM_resultset_create();
893     ZOOM_task task;
894     const char *cp;
895     int start, count;
896     const char *syntax, *elementSetName;
897     ZOOM_resultsets set;
898
899     yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
900     r->r_sort_spec = q->sort_spec;
901     r->query = q;
902
903     r->options = ZOOM_options_create_with_parent(c->options);
904     
905     start = ZOOM_options_get_int(r->options, "start", 0);
906     count = ZOOM_options_get_int(r->options, "count", 0);
907     {
908         /* If "presentChunk" is defined use that; otherwise "step" */
909         const char *cp = ZOOM_options_get(r->options, "presentChunk");
910         r->step = ZOOM_options_get_int(r->options,
911                                        (cp != 0 ? "presentChunk": "step"), 0);
912     }
913     r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
914     cp = ZOOM_options_get(r->options, "setname");
915     if (cp)
916         r->setname = xstrdup(cp);
917     cp = ZOOM_options_get(r->options, "schema");
918     if (cp)
919         r->schema = xstrdup(cp);
920
921     r->databaseNames = set_DatabaseNames(c, c->options, &r->num_databaseNames,
922                                          r->odr);
923     
924     r->connection = c;
925
926     yaz_log(log_details, "%p ZOOM_connection_search: Adding new resultset (%p) to resultsets (%p) ", c, r, c->resultsets);
927     set = xmalloc(sizeof(*set));
928     ZOOM_resultset_addref(r);
929     set->resultset = r;
930     set->next = c->resultsets;
931     c->resultsets = set;
932
933     if (c->host_port && c->proto == PROTO_HTTP)
934     {
935         if (!c->cs)
936         {
937             yaz_log(log_details, "ZOOM_connection_search: no comstack");
938             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
939         }
940         else
941         {
942             yaz_log(log_details, "ZOOM_connection_search: reconnect");
943             c->reconnect_ok = 1;
944         }
945     }
946
947     task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
948     task->u.search.resultset = r;
949     task->u.search.start = start;
950     task->u.search.count = count;
951     task->u.search.recv_search_fired = 0;
952
953     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
954     task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
955     elementSetName = ZOOM_options_get(r->options, "elementSetName");
956     task->u.search.elementSetName = elementSetName 
957         ? xstrdup(elementSetName) : 0;
958    
959     ZOOM_resultset_addref(r);
960
961     (q->refcount)++;
962
963     if (!c->async)
964     {
965         while (ZOOM_event(1, &c))
966             ;
967     }
968     return r;
969 }
970
971 ZOOM_API(void)
972     ZOOM_resultset_sort(ZOOM_resultset r,
973                          const char *sort_type, const char *sort_spec)
974 {
975     (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
976 }
977
978 ZOOM_API(int)
979     ZOOM_resultset_sort1(ZOOM_resultset r,
980                          const char *sort_type, const char *sort_spec)
981 {
982     ZOOM_connection c = r->connection;
983     ZOOM_task task;
984     ZOOM_query newq;
985
986     newq = ZOOM_query_create();
987     if (ZOOM_query_sortby(newq, sort_spec) < 0)
988         return -1;
989
990     yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
991             r, r, sort_type, sort_spec);
992     if (!c)
993         return 0;
994
995     if (c->host_port && c->proto == PROTO_HTTP)
996     {
997         if (!c->cs)
998         {
999             yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
1000             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1001         }
1002         else
1003         {
1004             yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
1005                     r);
1006             c->reconnect_ok = 1;
1007         }
1008     }
1009     
1010     ZOOM_resultset_cache_reset(r);
1011     task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
1012     task->u.sort.resultset = r;
1013     task->u.sort.q = newq;
1014
1015     ZOOM_resultset_addref(r);  
1016
1017     if (!c->async)
1018     {
1019         while (ZOOM_event(1, &c))
1020             ;
1021     }
1022
1023     return 0;
1024 }
1025
1026 static void ZOOM_record_release(ZOOM_record rec)
1027 {
1028     if (!rec)
1029         return;
1030     if (rec->wrbuf)
1031         wrbuf_destroy(rec->wrbuf);
1032 #if YAZ_HAVE_XML2
1033     if (rec->xml_mem)
1034         xmlFree(rec->xml_mem);
1035 #endif
1036     if (rec->odr)
1037         odr_destroy(rec->odr);
1038 }
1039
1040 ZOOM_API(void)
1041     ZOOM_resultset_cache_reset(ZOOM_resultset r)
1042 {
1043     int i;
1044     for (i = 0; i<RECORD_HASH_SIZE; i++)
1045     {
1046         ZOOM_record_cache rc;
1047         for (rc = r->record_hash[i]; rc; rc = rc->next)
1048         {
1049             ZOOM_record_release(&rc->rec);
1050         }
1051         r->record_hash[i] = 0;
1052     }
1053 }
1054
1055 ZOOM_API(void)
1056     ZOOM_resultset_destroy(ZOOM_resultset r)
1057 {
1058     resultset_destroy(r);
1059 }
1060
1061 static void resultset_destroy(ZOOM_resultset r)
1062 {
1063     if (!r)
1064         return;
1065     yaz_mutex_enter(r->mutex);
1066     (r->refcount)--;
1067     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
1068             r, r, r->refcount);
1069     if (r->refcount == 0)
1070     {
1071         yaz_mutex_leave(r->mutex);
1072         yaz_log(log_details, "%p ZOOM_connection resultset_destroy: Deleting resultset (%p) ", r->connection, r);
1073         ZOOM_resultset_cache_reset(r);
1074         ZOOM_query_destroy(r->query);
1075         ZOOM_options_destroy(r->options);
1076         odr_destroy(r->odr);
1077         xfree(r->setname);
1078         xfree(r->schema);
1079         yaz_mutex_destroy(&r->mutex);
1080         xfree(r);
1081     }
1082     else
1083         yaz_mutex_leave(r->mutex);
1084 }
1085
1086 ZOOM_API(size_t)
1087     ZOOM_resultset_size(ZOOM_resultset r)
1088 {
1089     yaz_log(log_details, "ZOOM_resultset_size r=%p count=" ODR_INT_PRINTF,
1090             r, r->size);
1091     return r->size;
1092 }
1093
1094 static void do_close(ZOOM_connection c)
1095 {
1096     if (c->cs)
1097         cs_close(c->cs);
1098     c->cs = 0;
1099     ZOOM_connection_set_mask(c, 0);
1100     c->state = STATE_IDLE;
1101 }
1102
1103 static int ZOOM_test_reconnect(ZOOM_connection c)
1104 {
1105     ZOOM_Event event;
1106
1107     if (!c->reconnect_ok)
1108         return 0;
1109     do_close(c);
1110     c->reconnect_ok = 0;
1111     c->tasks->running = 0;
1112     ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
1113
1114     event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1115     ZOOM_connection_put_event(c, event);
1116
1117     return 1;
1118 }
1119
1120 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
1121                                     int force_sync, int start, int count)
1122 {
1123     ZOOM_task task;
1124     ZOOM_connection c;
1125     const char *cp;
1126     const char *syntax, *elementSetName;
1127
1128     if (!r)
1129         return;
1130     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1131             " count=%d", r, force_sync, start, count);
1132     c = r->connection;
1133     if (!c)
1134         return;
1135
1136     if (c->host_port && c->proto == PROTO_HTTP)
1137     {
1138         if (!c->cs)
1139         {
1140             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1141             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1142         }
1143         else
1144         {
1145             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1146                     "reconnect", r);
1147             c->reconnect_ok = 1;
1148         }
1149     }
1150     task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1151     task->u.retrieve.resultset = r;
1152     task->u.retrieve.start = start;
1153     task->u.retrieve.count = count;
1154
1155     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1156     task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1157     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1158     task->u.retrieve.elementSetName = elementSetName 
1159         ? xstrdup(elementSetName) : 0;
1160
1161     cp = ZOOM_options_get(r->options, "schema");
1162     if (cp)
1163     {
1164         if (!r->schema || strcmp(r->schema, cp))
1165         {
1166             xfree(r->schema);
1167             r->schema = xstrdup(cp);
1168         }
1169     }
1170
1171     ZOOM_resultset_addref(r);
1172
1173     if (!r->connection->async || force_sync)
1174         while (r->connection && ZOOM_event(1, &r->connection))
1175             ;
1176 }
1177
1178 ZOOM_API(void)
1179     ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1180                            size_t start, size_t count)
1181 {
1182     int force_present = 0;
1183
1184     if (!r)
1185         return ;
1186     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1187             r, r, (long) start, (long) count);
1188     if (count && recs)
1189         force_present = 1;
1190     ZOOM_resultset_retrieve(r, force_present, start, count);
1191     if (force_present)
1192     {
1193         size_t i;
1194         for (i = 0; i< count; i++)
1195             recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1196     }
1197 }
1198
1199 static void get_cert(ZOOM_connection c)
1200 {
1201     char *cert_buf;
1202     int cert_len;
1203     
1204     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1205     {
1206         ZOOM_connection_option_setl(c, "sslPeerCert",
1207                                     cert_buf, cert_len);
1208         xfree(cert_buf);
1209     }
1210 }
1211
1212 static zoom_ret do_connect_host(ZOOM_connection c,
1213                                 const char *effective_host,
1214                                 const char *logical_url);
1215
1216 static zoom_ret do_connect(ZOOM_connection c)
1217 {
1218     const char *effective_host;
1219
1220     if (c->proxy)
1221         effective_host = c->proxy;
1222     else
1223         effective_host = c->host_port;
1224     return do_connect_host(c, effective_host, c->host_port);
1225 }
1226
1227 static zoom_ret do_connect_host(ZOOM_connection c, const char *effective_host,
1228     const char *logical_url)
1229 {
1230     void *add;
1231
1232     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1233
1234     if (c->cs)
1235         cs_close(c->cs);
1236     c->cs = cs_create_host(effective_host, 0, &add);
1237
1238     if (c->cs && c->cs->protocol == PROTO_HTTP)
1239     {
1240 #if YAZ_HAVE_XML2
1241         if (logical_url)
1242         {
1243             const char *db = 0;
1244             
1245             c->proto = PROTO_HTTP;
1246             cs_get_host_args(logical_url, &db);
1247             xfree(c->path);
1248             
1249             c->path = xmalloc(strlen(db) * 3 + 2);
1250             yaz_encode_sru_dbpath_buf(c->path, db);
1251         }
1252 #else
1253         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1254         do_close(c);
1255         return zoom_complete;
1256 #endif
1257     }
1258     if (c->cs)
1259     {
1260         int ret = cs_connect(c->cs, add);
1261         if (ret == 0)
1262         {
1263             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1264             ZOOM_connection_put_event(c, event);
1265             get_cert(c);
1266             if (c->proto == PROTO_Z3950)
1267                 ZOOM_connection_send_init(c);
1268             else
1269             {
1270                 /* no init request for SRW .. */
1271                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1272                 ZOOM_connection_remove_task(c);
1273                 ZOOM_connection_set_mask(c, 0);
1274                 ZOOM_connection_exec_task(c);
1275             }
1276             c->state = STATE_ESTABLISHED;
1277             return zoom_pending;
1278         }
1279         else if (ret > 0)
1280         {
1281             int mask = ZOOM_SELECT_EXCEPT;
1282             if (c->cs->io_pending & CS_WANT_WRITE)
1283                 mask += ZOOM_SELECT_WRITE;
1284             if (c->cs->io_pending & CS_WANT_READ)
1285                 mask += ZOOM_SELECT_READ;
1286             ZOOM_connection_set_mask(c, mask);
1287             c->state = STATE_CONNECTING; 
1288             return zoom_pending;
1289         }
1290     }
1291     c->state = STATE_IDLE;
1292     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, logical_url);
1293     return zoom_complete;
1294 }
1295
1296 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1297 {
1298     int i;
1299     for (i = 0; i<200; i++)
1300     {
1301         size_t len;
1302         Odr_oid *oid;
1303         Z_OtherInformation **oi;
1304         char buf[80];
1305         const char *val;
1306         const char *cp;
1307
1308         sprintf(buf, "otherInfo%d", i);
1309         val = ZOOM_options_get(c->options, buf);
1310         if (!val)
1311             break;
1312         cp = strchr(val, ':');
1313         if (!cp)
1314             continue;
1315         len = cp - val;
1316         if (len >= sizeof(buf))
1317             len = sizeof(buf)-1;
1318         memcpy(buf, val, len);
1319         buf[len] = '\0';
1320         
1321         oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
1322                                     buf, out);
1323         if (!oid)
1324             continue;
1325         
1326         yaz_oi_APDU(a, &oi);
1327         yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
1328     }
1329 }
1330
1331 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1332 {
1333     assert(a);
1334     if (c->cookie_out)
1335     {
1336         Z_OtherInformation **oi;
1337         yaz_oi_APDU(a, &oi);
1338         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie, 
1339                               1, c->cookie_out);
1340     }
1341     if (c->client_IP)
1342     {
1343         Z_OtherInformation **oi;
1344         yaz_oi_APDU(a, &oi);
1345         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip, 
1346                               1, c->client_IP);
1347     }
1348     otherInfo_attach(c, a, out);
1349     if (!z_APDU(out, &a, 0, 0))
1350     {
1351         FILE *outf = fopen("/tmp/apdu.txt", "a");
1352         if (a && outf)
1353         {
1354             ODR odr_pr = odr_createmem(ODR_PRINT);
1355             fprintf(outf, "a=%p\n", a);
1356             odr_setprint(odr_pr, outf);
1357             z_APDU(odr_pr, &a, 0, 0);
1358             odr_destroy(odr_pr);
1359         }
1360         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1361         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1362         odr_reset(out);
1363         return -1;
1364     }
1365     if (c->odr_print)
1366         z_APDU(c->odr_print, &a, 0, 0);
1367     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1368     return 0;
1369 }
1370
1371 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1372 {
1373     ZOOM_Event event;
1374     assert(a);
1375     if (encode_APDU(c, a, c->odr_out))
1376         return zoom_complete;
1377     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1378     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1379     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1380     ZOOM_connection_put_event(c, event);
1381     odr_reset(c->odr_out);
1382     return do_write(c);
1383 }
1384
1385 /* returns 1 if PDU was sent OK (still pending )
1386    0 if PDU was not sent OK (nothing to wait for) 
1387 */
1388
1389 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1390 {
1391     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1392     Z_InitRequest *ireq = apdu->u.initRequest;
1393     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1394         odr_malloc(c->odr_out, sizeof(*auth));
1395
1396     ODR_MASK_SET(ireq->options, Z_Options_search);
1397     ODR_MASK_SET(ireq->options, Z_Options_present);
1398     ODR_MASK_SET(ireq->options, Z_Options_scan);
1399     ODR_MASK_SET(ireq->options, Z_Options_sort);
1400     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1401     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1402     
1403     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1404     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1405     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1406     
1407     ireq->implementationId =
1408         odr_prepend(c->odr_out,
1409                     ZOOM_options_get(c->options, "implementationId"),
1410                     ireq->implementationId);
1411     
1412     ireq->implementationName = 
1413         odr_prepend(c->odr_out,
1414                     ZOOM_options_get(c->options, "implementationName"),
1415                     odr_prepend(c->odr_out, "ZOOM-C",
1416                                 ireq->implementationName));
1417     
1418     ireq->implementationVersion = 
1419         odr_prepend(c->odr_out,
1420                     ZOOM_options_get(c->options, "implementationVersion"),
1421                                 ireq->implementationVersion);
1422     
1423     *ireq->maximumRecordSize = c->maximum_record_size;
1424     *ireq->preferredMessageSize = c->preferred_message_size;
1425     
1426     if (c->group || c->password)
1427     {
1428         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1429         pass->groupId = odr_strdup_null(c->odr_out, c->group);
1430         pass->userId = odr_strdup_null(c->odr_out, c->user);
1431         pass->password = odr_strdup_null(c->odr_out, c->password);
1432         auth->which = Z_IdAuthentication_idPass;
1433         auth->u.idPass = pass;
1434         ireq->idAuthentication = auth;
1435     }
1436     else if (c->user)
1437     {
1438         auth->which = Z_IdAuthentication_open;
1439         auth->u.open = odr_strdup(c->odr_out, c->user);
1440         ireq->idAuthentication = auth;
1441     }
1442     if (c->proxy)
1443     {
1444         yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
1445                               yaz_oid_userinfo_proxy, 1, c->host_port);
1446     }
1447     if (c->charset || c->lang)
1448     {
1449         Z_OtherInformation **oi;
1450         Z_OtherInformationUnit *oi_unit;
1451         
1452         yaz_oi_APDU(apdu, &oi);
1453         
1454         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1455         {
1456             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1457             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1458             oi_unit->information.externallyDefinedInfo =
1459                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1460                                               c->charset, c->lang, 1);
1461         }
1462     }
1463     assert(apdu);
1464     return send_APDU(c, apdu);
1465 }
1466
1467 #if YAZ_HAVE_XML2
1468 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1469 {
1470     Z_GDU *gdu;
1471     ZOOM_Event event;
1472     const char *database =  ZOOM_options_get(c->options, "databaseName");
1473     char *fdatabase = 0;
1474     
1475     if (database)
1476         fdatabase = yaz_encode_sru_dbpath_odr(c->odr_out, database);
1477     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port,
1478                                        fdatabase ? fdatabase : c->path);
1479
1480     if (c->sru_mode == zoom_sru_get)
1481     {
1482         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1483     }
1484     else if (c->sru_mode == zoom_sru_post)
1485     {
1486         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1487     }
1488     else if (c->sru_mode == zoom_sru_soap)
1489     {
1490         yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1491     }
1492     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1493         return zoom_complete;
1494     if (c->odr_print)
1495         z_GDU(c->odr_print, &gdu, 0, 0);
1496     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1497         
1498     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1499     ZOOM_connection_put_event(c, event);
1500     odr_reset(c->odr_out);
1501     return do_write(c);
1502 }
1503 #endif
1504
1505 #if YAZ_HAVE_XML2
1506 static Z_SRW_PDU *ZOOM_srw_get_pdu(ZOOM_connection c, int type)
1507 {
1508     Z_SRW_PDU *sr = yaz_srw_get_pdu(c->odr_out, type, c->sru_version);
1509     sr->username = c->user;
1510     sr->password = c->password;
1511     return sr;
1512 }
1513 #endif
1514
1515 #if YAZ_HAVE_XML2
1516 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1517 {
1518     int i;
1519     int *start, *count;
1520     ZOOM_resultset resultset = 0;
1521     Z_SRW_PDU *sr = 0;
1522     const char *option_val = 0;
1523
1524     if (c->error)                  /* don't continue on error */
1525         return zoom_complete;
1526     assert(c->tasks);
1527     switch(c->tasks->which)
1528     {
1529     case ZOOM_TASK_SEARCH:
1530         resultset = c->tasks->u.search.resultset;
1531         if (!resultset->setname)
1532             resultset->setname = xstrdup("default");
1533         ZOOM_options_set(resultset->options, "setname", resultset->setname);
1534         start = &c->tasks->u.search.start;
1535         count = &c->tasks->u.search.count;
1536         break;
1537     case ZOOM_TASK_RETRIEVE:
1538         resultset = c->tasks->u.retrieve.resultset;
1539
1540         start = &c->tasks->u.retrieve.start;
1541         count = &c->tasks->u.retrieve.count;
1542
1543         if (*start >= resultset->size)
1544             return zoom_complete;
1545         if (*start + *count > resultset->size)
1546             *count = resultset->size - *start;
1547
1548         for (i = 0; i < *count; i++)
1549         {
1550             ZOOM_record rec =
1551                 record_cache_lookup(resultset, i + *start,
1552                                     c->tasks->u.retrieve.syntax,
1553                                     c->tasks->u.retrieve.elementSetName);
1554             if (!rec)
1555                 break;
1556             else
1557             {
1558                 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1559                 ZOOM_connection_put_event(c, event);
1560             }
1561         }
1562         *start += i;
1563         *count -= i;
1564
1565         if (*count == 0)
1566             return zoom_complete;
1567         break;
1568     default:
1569         return zoom_complete;
1570     }
1571     assert(resultset->query);
1572         
1573     sr = ZOOM_srw_get_pdu(c, Z_SRW_searchRetrieve_request);
1574     if (resultset->query->z_query->which == Z_Query_type_104
1575         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1576     {
1577         sr->u.request->query_type = Z_SRW_query_type_cql;
1578         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1579     }
1580     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1581              resultset->query->z_query->u.type_1)
1582     {
1583         sr->u.request->query_type = Z_SRW_query_type_pqf;
1584         sr->u.request->query.pqf = resultset->query->query_string;
1585     }
1586     else
1587     {
1588         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1589         return zoom_complete;
1590     }
1591     sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1592     sr->u.request->maximumRecords = odr_intdup(
1593         c->odr_out, (resultset->step > 0 && resultset->step < *count) ? 
1594         resultset->step : *count);
1595     sr->u.request->recordSchema = resultset->schema;
1596     
1597     option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1598     if (option_val)
1599         sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1600
1601     option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1602     yaz_encode_sru_extra(sr, c->odr_out, option_val);
1603     return send_srw(c, sr);
1604 }
1605 #else
1606 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1607 {
1608     return zoom_complete;
1609 }
1610 #endif
1611
1612 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1613 {
1614     ZOOM_resultset r;
1615     int lslb, ssub, mspn;
1616     const char *syntax;
1617     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1618     Z_SearchRequest *search_req = apdu->u.searchRequest;
1619     const char *elementSetName;
1620     const char *smallSetElementSetName;
1621     const char *mediumSetElementSetName;
1622
1623     assert(c->tasks);
1624     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1625
1626     r = c->tasks->u.search.resultset;
1627
1628     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1629
1630     elementSetName =
1631         ZOOM_options_get(r->options, "elementSetName");
1632     smallSetElementSetName  =
1633         ZOOM_options_get(r->options, "smallSetElementSetName");
1634     mediumSetElementSetName =
1635         ZOOM_options_get(r->options, "mediumSetElementSetName");
1636
1637     if (!smallSetElementSetName)
1638         smallSetElementSetName = elementSetName;
1639
1640     if (!mediumSetElementSetName)
1641         mediumSetElementSetName = elementSetName;
1642
1643     assert(r);
1644     assert(r->query);
1645
1646     /* prepare query for the search request */
1647     search_req->query = r->query->z_query;
1648     if (!search_req->query)
1649     {
1650         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1651         return zoom_complete;
1652     }
1653     if (r->query->z_query->which == Z_Query_type_1 || 
1654         r->query->z_query->which == Z_Query_type_101)
1655     {
1656         const char *cp = ZOOM_options_get(r->options, "rpnCharset");
1657         if (cp)
1658         {
1659             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
1660             if (cd)
1661             {
1662                 int r;
1663                 search_req->query = yaz_copy_Z_Query(search_req->query,
1664                                                      c->odr_out);
1665                 
1666                 r = yaz_query_charset_convert_rpnquery_check(
1667                     search_req->query->u.type_1,
1668                     c->odr_out, cd);
1669                 yaz_iconv_close(cd);
1670                 if (r)
1671                 {  /* query could not be char converted */
1672                     set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1673                     return zoom_complete;
1674                 }
1675             }
1676         }
1677     }
1678     search_req->databaseNames = r->databaseNames;
1679     search_req->num_databaseNames = r->num_databaseNames;
1680
1681     /* get syntax (no need to provide unless piggyback is in effect) */
1682     syntax = c->tasks->u.search.syntax;
1683
1684     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1685     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1686     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1687     if (lslb != -1 && ssub != -1 && mspn != -1)
1688     {
1689         /* So're a Z39.50 expert? Let's hope you don't do sort */
1690         *search_req->largeSetLowerBound = lslb;
1691         *search_req->smallSetUpperBound = ssub;
1692         *search_req->mediumSetPresentNumber = mspn;
1693     }
1694     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1695              && r->piggyback && !r->r_sort_spec && !r->schema)
1696     {
1697         /* Regular piggyback - do it unless we're going to do sort */
1698         *search_req->largeSetLowerBound = 2000000000;
1699         *search_req->smallSetUpperBound = 1;
1700         *search_req->mediumSetPresentNumber = 
1701             r->step>0 ? r->step : c->tasks->u.search.count;
1702     }
1703     else
1704     {
1705         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1706         smallSetElementSetName = 0;
1707         mediumSetElementSetName = 0;
1708         syntax = 0;
1709     }
1710     if (smallSetElementSetName && *smallSetElementSetName)
1711     {
1712         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1713             odr_malloc(c->odr_out, sizeof(*esn));
1714         
1715         esn->which = Z_ElementSetNames_generic;
1716         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1717         search_req->smallSetElementSetNames = esn;
1718     }
1719     if (mediumSetElementSetName && *mediumSetElementSetName)
1720     {
1721         Z_ElementSetNames *esn =(Z_ElementSetNames *)
1722             odr_malloc(c->odr_out, sizeof(*esn));
1723         
1724         esn->which = Z_ElementSetNames_generic;
1725         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1726         search_req->mediumSetElementSetNames = esn;
1727     }
1728     if (syntax)
1729         search_req->preferredRecordSyntax =
1730             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1731     
1732     if (!r->setname)
1733     {
1734         if (c->support_named_resultsets)
1735         {
1736             char setname[14];
1737             int ord;
1738             /* find the lowest unused ordinal so that we re-use
1739                result sets on the server. */
1740             for (ord = 1; ; ord++)
1741             {
1742                 ZOOM_resultsets rsp;
1743                 sprintf(setname, "%d", ord);
1744                 for (rsp = c->resultsets; rsp; rsp = rsp->next)
1745                     if (rsp->resultset->setname && !strcmp(rsp->resultset->setname, setname))
1746                         break;
1747                 if (!rsp)
1748                     break;
1749             }
1750             r->setname = xstrdup(setname);
1751             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1752                     "set %s", c, r->setname);
1753         }
1754         else
1755         {
1756             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1757                     "default set", c);
1758             r->setname = xstrdup("default");
1759         }
1760         ZOOM_options_set(r->options, "setname", r->setname);
1761     }
1762     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1763     return send_APDU(c, apdu);
1764 }
1765
1766 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1767 {
1768     char oid_name_buf[OID_STR_MAX];
1769     const char *oid_name;
1770     char *addinfo = 0;
1771
1772     oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
1773     switch (r->which)
1774     {
1775     case Z_DefaultDiagFormat_v2Addinfo:
1776         addinfo = r->u.v2Addinfo;
1777         break;
1778     case Z_DefaultDiagFormat_v3Addinfo:
1779         addinfo = r->u.v3Addinfo;
1780         break;
1781     }
1782     xfree(c->addinfo);
1783     c->addinfo = 0;
1784     set_dset_error(c, *r->condition, oid_name, addinfo, 0);
1785 }
1786
1787 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1788 {
1789     if (p->which != Z_DiagRec_defaultFormat)
1790         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1791     else
1792         response_default_diag(c, p->u.defaultFormat);
1793 }
1794
1795 ZOOM_API(ZOOM_record)
1796     ZOOM_record_clone(ZOOM_record srec)
1797 {
1798     char *buf;
1799     int size;
1800     ODR odr_enc;
1801     ZOOM_record nrec;
1802
1803     odr_enc = odr_createmem(ODR_ENCODE);
1804     if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1805         return 0;
1806     buf = odr_getbuf(odr_enc, &size, 0);
1807     
1808     nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1809     yaz_log(log_details, "ZOOM_record create");
1810     nrec->odr = odr_createmem(ODR_DECODE);
1811     nrec->wrbuf = 0;
1812 #if YAZ_HAVE_XML2
1813     nrec->xml_mem = 0;
1814     nrec->xml_size = 0;
1815 #endif
1816     odr_setbuf(nrec->odr, buf, size, 0);
1817     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1818     
1819     nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1820     nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1821     nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1822     nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1823     nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1824     odr_destroy(odr_enc);
1825     return nrec;
1826 }
1827
1828 ZOOM_API(ZOOM_record)
1829     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1830 {
1831     const char *syntax =
1832         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1833     const char *elementSetName =
1834         ZOOM_options_get(s->options, "elementSetName");
1835
1836     return record_cache_lookup(s, pos, syntax, elementSetName);
1837 }
1838
1839 ZOOM_API(ZOOM_record)
1840     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1841 {
1842     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1843
1844     if (!rec)
1845     {
1846         /*
1847          * MIKE: I think force_sync should always be zero, but I don't
1848          * want to make this change until I get the go-ahead from
1849          * Adam, in case something depends on the old synchronous
1850          * behaviour.
1851          */
1852         int force_sync = 1;
1853         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1854         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1855         rec = ZOOM_resultset_record_immediate(r, pos);
1856     }
1857     return rec;
1858 }
1859
1860 ZOOM_API(void)
1861     ZOOM_record_destroy(ZOOM_record rec)
1862 {
1863     ZOOM_record_release(rec);
1864     yaz_log(log_details, "ZOOM_record destroy");
1865     xfree(rec);
1866 }
1867
1868
1869 static yaz_iconv_t iconv_create_charset(const char *record_charset)
1870 {
1871     char to[40];
1872     char from[40];
1873     yaz_iconv_t cd = 0;
1874
1875     *from = '\0';
1876     strcpy(to, "UTF-8");
1877     if (record_charset && *record_charset)
1878     {
1879         /* Use "from,to" or just "from" */
1880         const char *cp = strchr(record_charset, ',');
1881         size_t clen = strlen(record_charset);
1882         if (cp && cp[1])
1883         {
1884             strncpy( to, cp+1, sizeof(to)-1);
1885             to[sizeof(to)-1] = '\0';
1886             clen = cp - record_charset;
1887         }
1888         if (clen > sizeof(from)-1)
1889             clen = sizeof(from)-1;
1890         
1891         if (clen)
1892             strncpy(from, record_charset, clen);
1893         from[clen] = '\0';
1894     }
1895     if (*from && *to)
1896         cd = yaz_iconv_open(to, from);
1897     return cd;
1898 }
1899
1900 static const char *return_marc_record(ZOOM_record rec, int marc_type,
1901                                       int *len,
1902                                       const char *buf, int sz,
1903                                       const char *record_charset)
1904 {
1905     yaz_iconv_t cd = iconv_create_charset(record_charset);
1906     yaz_marc_t mt = yaz_marc_create();
1907     const char *ret_string = 0;
1908
1909     if (cd)
1910         yaz_marc_iconv(mt, cd);
1911     yaz_marc_xml(mt, marc_type);
1912     if (!rec->wrbuf)
1913         rec->wrbuf = wrbuf_alloc();
1914     wrbuf_rewind(rec->wrbuf);
1915     if (yaz_marc_decode_wrbuf(mt, buf, sz, rec->wrbuf) > 0)
1916     {
1917         if (len)
1918             *len = wrbuf_len(rec->wrbuf);
1919         ret_string = wrbuf_cstr(rec->wrbuf);
1920     }
1921     yaz_marc_destroy(mt);
1922     if (cd)
1923         yaz_iconv_close(cd);
1924     return ret_string;
1925 }
1926
1927 static const char *return_opac_record(ZOOM_record rec, int marc_type,
1928                                       int *len,
1929                                       Z_OPACRecord *opac_rec,
1930                                       const char *record_charset)
1931 {
1932     yaz_iconv_t cd = iconv_create_charset(record_charset);
1933     yaz_marc_t mt = yaz_marc_create();
1934
1935     if (cd)
1936         yaz_marc_iconv(mt, cd);
1937     yaz_marc_xml(mt, marc_type);
1938
1939     if (!rec->wrbuf)
1940         rec->wrbuf = wrbuf_alloc();
1941     wrbuf_rewind(rec->wrbuf);
1942
1943     yaz_opac_decode_wrbuf(mt, opac_rec, rec->wrbuf);
1944     yaz_marc_destroy(mt);
1945
1946     if (cd)
1947         yaz_iconv_close(cd);
1948     if (len)
1949         *len = wrbuf_len(rec->wrbuf);
1950     return wrbuf_cstr(rec->wrbuf);
1951 }
1952
1953 static const char *return_string_record(ZOOM_record rec, int *len,
1954                                         const char *buf, int sz,
1955                                         const char *record_charset)
1956 {
1957     yaz_iconv_t cd = iconv_create_charset(record_charset);
1958
1959     if (cd)
1960     {
1961         if (!rec->wrbuf)
1962             rec->wrbuf = wrbuf_alloc();
1963
1964         wrbuf_rewind(rec->wrbuf);
1965
1966         wrbuf_iconv_write(rec->wrbuf, cd, buf, sz);
1967         wrbuf_iconv_reset(rec->wrbuf, cd);
1968
1969         buf = wrbuf_cstr(rec->wrbuf);
1970         sz = wrbuf_len(rec->wrbuf);
1971         yaz_iconv_close(cd);
1972     }
1973     if (len)
1974         *len = sz;
1975     return buf;
1976 }
1977
1978 static const char *return_record(ZOOM_record rec, int *len,
1979                                  Z_NamePlusRecord *npr,
1980                                  int marctype, const char *charset)
1981 {
1982     Z_External *r = (Z_External *) npr->u.databaseRecord;
1983     const Odr_oid *oid = r->direct_reference;
1984     
1985     /* render bibliographic record .. */
1986     if (r->which == Z_External_OPAC)
1987     {
1988         return return_opac_record(rec, marctype, len,
1989                                   r->u.opac, charset);
1990     }
1991     if (r->which == Z_External_sutrs)
1992         return return_string_record(rec, len,
1993                                     (char*) r->u.sutrs->buf,
1994                                     r->u.sutrs->len,
1995                                     charset);
1996     else if (r->which == Z_External_octet)
1997     {
1998         if (yaz_oid_is_iso2709(oid))
1999         {
2000             const char *ret_buf = return_marc_record(
2001                 rec, marctype, len,
2002                 (const char *) r->u.octet_aligned->buf,
2003                 r->u.octet_aligned->len,
2004                 charset);
2005             if (ret_buf)
2006                 return ret_buf;
2007             /* bad ISO2709. Return fail unless raw (ISO2709) is wanted */
2008             if (marctype != YAZ_MARC_ISO2709)
2009                 return 0;
2010         }
2011         return return_string_record(rec, len,
2012                                     (const char *) r->u.octet_aligned->buf,
2013                                     r->u.octet_aligned->len,
2014                                     charset);
2015     }
2016     else if (r->which == Z_External_grs1)
2017     {
2018         if (!rec->wrbuf)
2019             rec->wrbuf = wrbuf_alloc();
2020         wrbuf_rewind(rec->wrbuf);
2021         yaz_display_grs1(rec->wrbuf, r->u.grs1, 0);
2022         return return_string_record(rec, len,
2023                                     wrbuf_buf(rec->wrbuf),
2024                                     wrbuf_len(rec->wrbuf),
2025                                     charset);
2026     }
2027     return 0;
2028 }
2029     
2030
2031 ZOOM_API(int)
2032     ZOOM_record_error(ZOOM_record rec, const char **cp,
2033                       const char **addinfo, const char **diagset)
2034 {
2035     Z_NamePlusRecord *npr;
2036     
2037     if (!rec)
2038         return 0;
2039
2040     npr = rec->npr;
2041     if (rec->diag_uri)
2042     {
2043         if (cp)
2044             *cp = rec->diag_message;
2045         if (addinfo)
2046             *addinfo = rec->diag_details;
2047         if (diagset)
2048             *diagset = rec->diag_set;
2049         return uri_to_code(rec->diag_uri);
2050     }
2051     if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
2052     {
2053         Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
2054         int error = YAZ_BIB1_UNSPECIFIED_ERROR;
2055         const char *add = 0;
2056
2057         if (diag_rec->which == Z_DiagRec_defaultFormat)
2058         {
2059             Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
2060             oid_class oclass;
2061     
2062             error = *ddf->condition;
2063             switch (ddf->which)
2064             {
2065             case Z_DefaultDiagFormat_v2Addinfo:
2066                 add = ddf->u.v2Addinfo;
2067                 break;
2068             case Z_DefaultDiagFormat_v3Addinfo:
2069                 add = ddf->u.v3Addinfo;
2070                 break;
2071             }
2072             if (diagset)
2073                 *diagset =
2074                     yaz_oid_to_string(yaz_oid_std(),
2075                                       ddf->diagnosticSetId, &oclass);
2076         }
2077         else
2078         {
2079             if (diagset)
2080                 *diagset = "Bib-1";
2081         }
2082         if (addinfo)
2083             *addinfo = add ? add : "";
2084         if (cp)
2085             *cp = diagbib1_str(error);
2086         return error;
2087     }
2088     return 0;
2089 }
2090
2091 static const char *get_record_format(ZOOM_record rec, int *len,
2092                                      Z_NamePlusRecord *npr,
2093                                      int marctype, const char *charset,
2094                                      const char *format)
2095 {
2096     const char *res = return_record(rec, len, npr, marctype, charset);
2097 #if YAZ_HAVE_XML2
2098     if (*format == '1' && len)
2099     {
2100         /* try to XML format res */
2101         xmlDocPtr doc;
2102         xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
2103         doc = xmlParseMemory(res, *len);
2104         if (doc)
2105         {
2106             if (rec->xml_mem)
2107                 xmlFree(rec->xml_mem);
2108             xmlDocDumpFormatMemory(doc, &rec->xml_mem, &rec->xml_size, 1);
2109             xmlFreeDoc(doc);
2110             res = (char *) rec->xml_mem;
2111             *len = rec->xml_size;
2112         } 
2113     }
2114 #endif
2115     return res;
2116 }
2117
2118
2119 ZOOM_API(const char *)
2120     ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2121 {
2122     char type[40];
2123     char charset[40];
2124     char format[3];
2125     const char *cp;
2126     size_t i;
2127     Z_NamePlusRecord *npr;
2128     
2129     if (len)
2130         *len = 0; /* default return */
2131         
2132     if (!rec)
2133         return 0;
2134     npr = rec->npr;
2135     if (!npr)
2136         return 0;
2137
2138     cp = type_spec;
2139     for (i = 0; cp[i] && cp[i] != ';' && cp[i] != ' ' && i < sizeof(type)-1;
2140          i++)
2141         type[i] = cp[i];
2142     type[i] = '\0';
2143     charset[0] = '\0';
2144     format[0] = '\0';
2145     while (1)
2146     {
2147         while (cp[i] == ' ')
2148             i++;
2149         if (cp[i] != ';')
2150             break;
2151         i++;
2152         while (cp[i] == ' ')
2153             i++;
2154         if (!strncmp(cp + i, "charset=", 8))
2155         {
2156             size_t j = 0;
2157             i = i + 8; /* skip charset= */
2158             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2159             {
2160                 if (j < sizeof(charset)-1)
2161                     charset[j++] = cp[i];
2162             }
2163             charset[j] = '\0';
2164         }
2165         else if (!strncmp(cp + i, "format=", 7))
2166         {
2167             size_t j = 0; 
2168             i = i + 7;
2169             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2170             {
2171                 if (j < sizeof(format)-1)
2172                     format[j++] = cp[i];
2173             }
2174             format[j] = '\0';
2175         } 
2176     }
2177     if (!strcmp(type, "database"))
2178     {
2179         if (len)
2180             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2181         return npr->databaseName;
2182     }
2183     else if (!strcmp(type, "schema"))
2184     {
2185         if (len)
2186             *len = rec->schema ? strlen(rec->schema) : 0;
2187         return rec->schema;
2188     }
2189     else if (!strcmp(type, "syntax"))
2190     {
2191         const char *desc = 0;   
2192         if (npr->which == Z_NamePlusRecord_databaseRecord)
2193         {
2194             Z_External *r = (Z_External *) npr->u.databaseRecord;
2195             desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2196         }
2197         if (!desc)
2198             desc = "none";
2199         if (len)
2200             *len = strlen(desc);
2201         return desc;
2202     }
2203     if (npr->which != Z_NamePlusRecord_databaseRecord)
2204         return 0;
2205
2206     /* from now on - we have a database record .. */
2207     if (!strcmp(type, "render"))
2208     {
2209         return get_record_format(rec, len, npr, YAZ_MARC_LINE, charset, format);
2210     }
2211     else if (!strcmp(type, "xml"))
2212     {
2213         return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2214                                  format);
2215     }
2216     else if (!strcmp(type, "txml"))
2217     {
2218         return get_record_format(rec, len, npr, YAZ_MARC_TURBOMARC, charset,
2219                                  format);
2220     }
2221     else if (!strcmp(type, "raw"))
2222     {
2223         return get_record_format(rec, len, npr, YAZ_MARC_ISO2709, charset,
2224             format);
2225     }
2226     else if (!strcmp(type, "ext"))
2227     {
2228         if (len) *len = -1;
2229         return (const char *) npr->u.databaseRecord;
2230     }
2231     else if (!strcmp(type, "opac"))
2232     {
2233         if (npr->u.databaseRecord->which == Z_External_OPAC)
2234             return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2235                 format);
2236     }
2237     return 0;
2238 }
2239
2240 static int strcmp_null(const char *v1, const char *v2)
2241 {
2242     if (!v1 && !v2)
2243         return 0;
2244     if (!v1 || !v2)
2245         return -1;
2246     return strcmp(v1, v2);
2247 }
2248
2249 static size_t record_hash(int pos)
2250 {
2251     if (pos < 0)
2252         pos = 0;
2253     return pos % RECORD_HASH_SIZE;
2254 }
2255
2256 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr, 
2257                              int pos,
2258                              const char *syntax, const char *elementSetName,
2259                              const char *schema,
2260                              Z_SRW_diagnostic *diag)
2261 {
2262     ZOOM_record_cache rc = 0;
2263     
2264     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2265     ZOOM_connection_put_event(r->connection, event);
2266
2267     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2268     {
2269         if (pos == rc->pos 
2270             && strcmp_null(r->schema, rc->schema) == 0
2271             && strcmp_null(elementSetName,rc->elementSetName) == 0
2272             && strcmp_null(syntax, rc->syntax) == 0)
2273             break;
2274     }
2275     if (!rc)
2276     {
2277         rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2278         rc->rec.odr = 0;
2279         rc->rec.wrbuf = 0;
2280 #if YAZ_HAVE_XML2
2281         rc->rec.xml_mem = 0;
2282 #endif
2283         rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2284         
2285         rc->syntax = odr_strdup_null(r->odr, syntax);
2286         
2287         rc->schema = odr_strdup_null(r->odr, r->schema);
2288
2289         rc->pos = pos;
2290         rc->next = r->record_hash[record_hash(pos)];
2291         r->record_hash[record_hash(pos)] = rc;
2292     }
2293     rc->rec.npr = npr;
2294     rc->rec.schema = odr_strdup_null(r->odr, schema);
2295     rc->rec.diag_set = 0;
2296     rc->rec.diag_uri = 0;
2297     rc->rec.diag_message = 0;
2298     rc->rec.diag_details = 0;
2299     if (diag)
2300     {
2301         if (diag->uri)
2302         {
2303             char *cp;
2304             rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2305             if ((cp = strrchr(rc->rec.diag_set, '/')))
2306                 *cp = '\0';
2307             rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2308         }
2309         rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);            
2310         rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2311     }
2312 }
2313
2314 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2315                                        const char *syntax,
2316                                        const char *elementSetName)
2317 {
2318     ZOOM_record_cache rc;
2319     
2320     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2321     {
2322         if (pos == rc->pos)
2323         {
2324             if (strcmp_null(r->schema, rc->schema))
2325                 continue;
2326             if (strcmp_null(elementSetName,rc->elementSetName))
2327                 continue;
2328             if (strcmp_null(syntax, rc->syntax))
2329                 continue;
2330             return &rc->rec;
2331         }
2332     }
2333     return 0;
2334 }
2335                                              
2336 static void handle_records(ZOOM_connection c, Z_Records *sr,
2337                            int present_phase)
2338 {
2339     ZOOM_resultset resultset;
2340     int *start, *count;
2341     const char *syntax = 0, *elementSetName = 0;
2342
2343     if (!c->tasks)
2344         return ;
2345     switch (c->tasks->which)
2346     {
2347     case ZOOM_TASK_SEARCH:
2348         resultset = c->tasks->u.search.resultset;
2349         start = &c->tasks->u.search.start;
2350         count = &c->tasks->u.search.count;
2351         syntax = c->tasks->u.search.syntax;
2352         elementSetName = c->tasks->u.search.elementSetName;
2353         break;
2354     case ZOOM_TASK_RETRIEVE:
2355         resultset = c->tasks->u.retrieve.resultset;        
2356         start = &c->tasks->u.retrieve.start;
2357         count = &c->tasks->u.retrieve.count;
2358         syntax = c->tasks->u.retrieve.syntax;
2359         elementSetName = c->tasks->u.retrieve.elementSetName;
2360         break;
2361     default:
2362         return;
2363     }
2364     if (sr && sr->which == Z_Records_NSD)
2365         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2366     else if (sr && sr->which == Z_Records_multipleNSD)
2367     {
2368         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2369             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2370         else
2371             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2372     }
2373     else 
2374     {
2375         if (*count + *start > resultset->size)
2376             *count = resultset->size - *start;
2377         if (*count < 0)
2378             *count = 0;
2379         if (sr && sr->which == Z_Records_DBOSD)
2380         {
2381             int i;
2382             NMEM nmem = odr_extract_mem(c->odr_in);
2383             Z_NamePlusRecordList *p =
2384                 sr->u.databaseOrSurDiagnostics;
2385             for (i = 0; i<p->num_records; i++)
2386             {
2387                 record_cache_add(resultset, p->records[i], i + *start,
2388                                  syntax, elementSetName,
2389                                  elementSetName, 0);
2390             }
2391             *count -= i;
2392             if (*count < 0)
2393                 *count = 0;
2394             *start += i;
2395             yaz_log(log_details, 
2396                     "handle_records resultset=%p start=%d count=%d",
2397                     resultset, *start, *count);
2398
2399             /* transfer our response to search_nmem .. we need it later */
2400             nmem_transfer(odr_getmem(resultset->odr), nmem);
2401             nmem_destroy(nmem);
2402             if (present_phase && p->num_records == 0)
2403             {
2404                 /* present response and we didn't get any records! */
2405                 Z_NamePlusRecord *myrec = 
2406                     zget_surrogateDiagRec(
2407                         resultset->odr, 0, 
2408                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2409                         "ZOOM C generated. Present phase and no records");
2410                 record_cache_add(resultset, myrec, *start,
2411                                  syntax, elementSetName, 0, 0);
2412             }
2413         }
2414         else if (present_phase)
2415         {
2416             /* present response and we didn't get any records! */
2417             Z_NamePlusRecord *myrec = 
2418                 zget_surrogateDiagRec(
2419                     resultset->odr, 0,
2420                     YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2421                     "ZOOM C generated: Present response and no records");
2422             record_cache_add(resultset, myrec, *start, syntax, elementSetName,
2423                              0, 0);
2424         }
2425     }
2426 }
2427
2428 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2429 {
2430     handle_records(c, pr->records, 1);
2431 }
2432
2433 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2434                                        Z_Term *term)
2435 {
2436     switch (term->which)
2437     {
2438     case Z_Term_general:
2439         ZOOM_options_setl(opt, name,
2440                           (const char *)(term->u.general->buf), 
2441                           term->u.general->len);
2442         break;
2443     case Z_Term_characterString:
2444         ZOOM_options_set(opt, name, term->u.characterString);
2445         break;
2446     case Z_Term_numeric:
2447         ZOOM_options_set_int(opt, name, *term->u.numeric);
2448         break;
2449     }
2450 }
2451
2452 static void handle_queryExpression(ZOOM_options opt, const char *name,
2453                                    Z_QueryExpression *exp)
2454 {
2455     char opt_name[80];
2456     
2457     switch (exp->which)
2458     {
2459     case Z_QueryExpression_term:
2460         if (exp->u.term && exp->u.term->queryTerm)
2461         {
2462             sprintf(opt_name, "%s.term", name);
2463             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2464         }
2465         break;
2466     case Z_QueryExpression_query:
2467         break;
2468     }
2469 }
2470
2471 static void handle_searchResult(ZOOM_connection c, ZOOM_resultset resultset,
2472                                 Z_OtherInformation *o)
2473 {
2474     int i;
2475     for (i = 0; o && i < o->num_elements; i++)
2476     {
2477         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2478         {
2479             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2480             
2481             if (ext->which == Z_External_searchResult1)
2482             {
2483                 int j;
2484                 Z_SearchInfoReport *sr = ext->u.searchResult1;
2485                 
2486                 if (sr->num)
2487                     ZOOM_options_set_int(
2488                         resultset->options, "searchresult.size", sr->num);
2489
2490                 for (j = 0; j < sr->num; j++)
2491                 {
2492                     Z_SearchInfoReport_s *ent =
2493                         ext->u.searchResult1->elements[j];
2494                     char pref[80];
2495                     
2496                     sprintf(pref, "searchresult.%d", j);
2497
2498                     if (ent->subqueryId)
2499                     {
2500                         char opt_name[80];
2501                         sprintf(opt_name, "%s.id", pref);
2502                         ZOOM_options_set(resultset->options, opt_name,
2503                                          ent->subqueryId);
2504                     }
2505                     if (ent->subqueryExpression)
2506                     {
2507                         char opt_name[80];
2508                         sprintf(opt_name, "%s.subquery", pref);
2509                         handle_queryExpression(resultset->options, opt_name,
2510                                                ent->subqueryExpression);
2511                     }
2512                     if (ent->subqueryInterpretation)
2513                     {
2514                         char opt_name[80];
2515                         sprintf(opt_name, "%s.interpretation", pref);
2516                         handle_queryExpression(resultset->options, opt_name,
2517                                                ent->subqueryInterpretation);
2518                     }
2519                     if (ent->subqueryRecommendation)
2520                     {
2521                         char opt_name[80];
2522                         sprintf(opt_name, "%s.recommendation", pref);
2523                         handle_queryExpression(resultset->options, opt_name,
2524                                                ent->subqueryRecommendation);
2525                     }
2526                     if (ent->subqueryCount)
2527                     {
2528                         char opt_name[80];
2529                         sprintf(opt_name, "%s.count", pref);
2530                         ZOOM_options_set_int(resultset->options, opt_name,
2531                                              *ent->subqueryCount);
2532                     }                                             
2533                 }
2534             }
2535         }
2536     }
2537 }
2538
2539 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2540 {
2541     ZOOM_resultset resultset;
2542     ZOOM_Event event;
2543
2544     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2545         return ;
2546
2547     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2548     ZOOM_connection_put_event(c, event);
2549
2550     resultset = c->tasks->u.search.resultset;
2551
2552     if (sr->resultSetStatus)
2553     {
2554         ZOOM_options_set_int(resultset->options, "resultSetStatus",
2555                              *sr->resultSetStatus);
2556     }
2557     if (sr->presentStatus)
2558     {
2559         ZOOM_options_set_int(resultset->options, "presentStatus",
2560                              *sr->presentStatus);
2561     }
2562     handle_searchResult(c, resultset, sr->additionalSearchInfo);
2563
2564     resultset->size = *sr->resultCount;
2565     handle_records(c, sr->records, 0);
2566 }
2567
2568 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2569 {
2570     if (res->diagnostics && res->num_diagnostics > 0)
2571         response_diag(c, res->diagnostics[0]);
2572 }
2573
2574 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2575 {
2576     NMEM nmem = odr_extract_mem(c->odr_in);
2577     ZOOM_scanset scan;
2578
2579     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2580         return 0;
2581     scan = c->tasks->u.scan.scan;
2582
2583     if (res->entries && res->entries->nonsurrogateDiagnostics)
2584         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2585     scan->scan_response = res;
2586     scan->srw_scan_response = 0;
2587     nmem_transfer(odr_getmem(scan->odr), nmem);
2588     if (res->stepSize)
2589         ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2590     if (res->positionOfTerm)
2591         ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2592     if (res->scanStatus)
2593         ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2594     if (res->numberOfEntriesReturned)
2595         ZOOM_options_set_int(scan->options, "number",
2596                              *res->numberOfEntriesReturned);
2597     nmem_destroy(nmem);
2598     return 1;
2599 }
2600
2601 static zoom_ret send_sort(ZOOM_connection c,
2602                           ZOOM_resultset resultset)
2603 {
2604     if (c->error)
2605         resultset->r_sort_spec = 0;
2606     if (resultset->r_sort_spec)
2607     {
2608         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2609         Z_SortRequest *req = apdu->u.sortRequest;
2610         
2611         req->num_inputResultSetNames = 1;
2612         req->inputResultSetNames = (Z_InternationalString **)
2613             odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2614         req->inputResultSetNames[0] =
2615             odr_strdup(c->odr_out, resultset->setname);
2616         req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2617         req->sortSequence = resultset->r_sort_spec;
2618         resultset->r_sort_spec = 0;
2619         return send_APDU(c, apdu);
2620     }
2621     return zoom_complete;
2622 }
2623
2624 static zoom_ret send_present(ZOOM_connection c)
2625 {
2626     Z_APDU *apdu = 0;
2627     Z_PresentRequest *req = 0;
2628     int i = 0;
2629     const char *syntax = 0;
2630     const char *elementSetName = 0;
2631     ZOOM_resultset  resultset;
2632     int *start, *count;
2633
2634     if (!c->tasks)
2635     {
2636         yaz_log(log_details, "%p send_present no tasks", c);
2637         return zoom_complete;
2638     }
2639     
2640     switch (c->tasks->which)
2641     {
2642     case ZOOM_TASK_SEARCH:
2643         resultset = c->tasks->u.search.resultset;
2644         start = &c->tasks->u.search.start;
2645         count = &c->tasks->u.search.count;
2646         syntax = c->tasks->u.search.syntax;
2647         elementSetName = c->tasks->u.search.elementSetName;
2648         break;
2649     case ZOOM_TASK_RETRIEVE:
2650         resultset = c->tasks->u.retrieve.resultset;
2651         start = &c->tasks->u.retrieve.start;
2652         count = &c->tasks->u.retrieve.count;
2653         syntax = c->tasks->u.retrieve.syntax;
2654         elementSetName = c->tasks->u.retrieve.elementSetName;
2655         break;
2656     default:
2657         return zoom_complete;
2658     }
2659     yaz_log(log_details, "%p send_present start=%d count=%d",
2660             c, *start, *count);
2661
2662     if (*start < 0 || *count < 0 || *start + *count > resultset->size)
2663     {
2664         set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
2665                        "", 0);
2666     }
2667     if (c->error)                  /* don't continue on error */
2668         return zoom_complete;
2669     yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2670             resultset, *start, *count);
2671
2672     for (i = 0; i < *count; i++)
2673     {
2674         ZOOM_record rec =
2675             record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2676         if (!rec)
2677             break;
2678         else
2679         {
2680             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2681             ZOOM_connection_put_event(c, event);
2682         }
2683     }
2684     *start += i;
2685     *count -= i;
2686
2687     if (*count == 0)
2688     {
2689         yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2690         return zoom_complete;
2691     }
2692
2693     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2694     req = apdu->u.presentRequest;
2695
2696     if (i)
2697         yaz_log(log_details, "%p send_present skip=%d", c, i);
2698
2699     *req->resultSetStartPoint = *start + 1;
2700
2701     if (resultset->step > 0 && resultset->step < *count)
2702         *req->numberOfRecordsRequested = resultset->step;
2703     else
2704         *req->numberOfRecordsRequested = *count;
2705     
2706     if (*req->numberOfRecordsRequested + *start > resultset->size)
2707         *req->numberOfRecordsRequested = resultset->size - *start;
2708     assert(*req->numberOfRecordsRequested > 0);
2709
2710     if (syntax && *syntax)
2711         req->preferredRecordSyntax =
2712             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
2713
2714     if (resultset->schema && *resultset->schema)
2715     {
2716         Z_RecordComposition *compo = (Z_RecordComposition *)
2717             odr_malloc(c->odr_out, sizeof(*compo));
2718
2719         req->recordComposition = compo;
2720         compo->which = Z_RecordComp_complex;
2721         compo->u.complex = (Z_CompSpec *)
2722             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2723         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2724             odr_malloc(c->odr_out, sizeof(bool_t));
2725         *compo->u.complex->selectAlternativeSyntax = 0;
2726
2727         compo->u.complex->generic = (Z_Specification *)
2728             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2729
2730         compo->u.complex->generic->which = Z_Schema_oid;
2731         compo->u.complex->generic->schema.oid = (Odr_oid *)
2732             zoom_yaz_str_to_z3950oid (c, CLASS_SCHEMA, resultset->schema);
2733
2734         if (!compo->u.complex->generic->schema.oid)
2735         {
2736             /* OID wasn't a schema! Try record syntax instead. */
2737
2738             compo->u.complex->generic->schema.oid = (Odr_oid *)
2739                 zoom_yaz_str_to_z3950oid (c, CLASS_RECSYN, resultset->schema);
2740         }
2741         if (elementSetName && *elementSetName)
2742         {
2743             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2744                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2745             compo->u.complex->generic->elementSpec->which =
2746                 Z_ElementSpec_elementSetName;
2747             compo->u.complex->generic->elementSpec->u.elementSetName =
2748                 odr_strdup(c->odr_out, elementSetName);
2749         }
2750         else
2751             compo->u.complex->generic->elementSpec = 0;
2752         compo->u.complex->num_dbSpecific = 0;
2753         compo->u.complex->dbSpecific = 0;
2754         compo->u.complex->num_recordSyntax = 0;
2755         compo->u.complex->recordSyntax = 0;
2756     }
2757     else if (elementSetName && *elementSetName)
2758     {
2759         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2760             odr_malloc(c->odr_out, sizeof(*esn));
2761         Z_RecordComposition *compo = (Z_RecordComposition *)
2762             odr_malloc(c->odr_out, sizeof(*compo));
2763         
2764         esn->which = Z_ElementSetNames_generic;
2765         esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2766         compo->which = Z_RecordComp_simple;
2767         compo->u.simple = esn;
2768         req->recordComposition = compo;
2769     }
2770     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2771     return send_APDU(c, apdu);
2772 }
2773
2774 ZOOM_API(ZOOM_scanset)
2775     ZOOM_connection_scan(ZOOM_connection c, const char *start)
2776 {
2777     ZOOM_scanset s;
2778     ZOOM_query q = ZOOM_query_create();
2779
2780     ZOOM_query_prefix(q, start);
2781
2782     s = ZOOM_connection_scan1(c, q);
2783     ZOOM_query_destroy(q);
2784     return s;
2785
2786 }
2787
2788 ZOOM_API(ZOOM_scanset)
2789     ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
2790 {
2791     ZOOM_scanset scan = 0;
2792
2793     if (!q->z_query)
2794         return 0;
2795     scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
2796     scan->connection = c;
2797     scan->odr = odr_createmem(ODR_DECODE);
2798     scan->options = ZOOM_options_create_with_parent(c->options);
2799     scan->refcount = 1;
2800     scan->scan_response = 0;
2801     scan->srw_scan_response = 0;
2802
2803     scan->query = q;
2804     (q->refcount)++;
2805     scan->databaseNames = set_DatabaseNames(c, c->options,
2806                                             &scan->num_databaseNames,
2807                                             scan->odr);
2808
2809     if (1)
2810     {
2811         ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
2812         task->u.scan.scan = scan;
2813         
2814         (scan->refcount)++;
2815         if (!c->async)
2816         {
2817             while (ZOOM_event(1, &c))
2818                 ;
2819         }
2820     }
2821     return scan;
2822 }
2823
2824 ZOOM_API(void)
2825     ZOOM_scanset_destroy(ZOOM_scanset scan)
2826 {
2827     if (!scan)
2828         return;
2829     (scan->refcount)--;
2830     if (scan->refcount == 0)
2831     {
2832         ZOOM_query_destroy(scan->query);
2833
2834         odr_destroy(scan->odr);
2835         
2836         ZOOM_options_destroy(scan->options);
2837         xfree(scan);
2838     }
2839 }
2840
2841 static zoom_ret send_package(ZOOM_connection c)
2842 {
2843     ZOOM_Event event;
2844
2845     yaz_log(log_details, "%p send_package", c);
2846     if (!c->tasks)
2847         return zoom_complete;
2848     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2849     
2850     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
2851     ZOOM_connection_put_event(c, event);
2852     
2853     c->buf_out = c->tasks->u.package->buf_out;
2854     c->len_out = c->tasks->u.package->len_out;
2855
2856     return do_write(c);
2857 }
2858
2859 static zoom_ret ZOOM_connection_send_scan(ZOOM_connection c)
2860 {
2861     ZOOM_scanset scan;
2862     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2863     Z_ScanRequest *req = apdu->u.scanRequest;
2864
2865     yaz_log(log_details, "%p send_scan", c);
2866     if (!c->tasks)
2867         return zoom_complete;
2868     assert (c->tasks->which == ZOOM_TASK_SCAN);
2869     scan = c->tasks->u.scan.scan;
2870
2871     /* Z39.50 scan can only carry RPN */
2872     if (scan->query->z_query->which == Z_Query_type_1 ||
2873         scan->query->z_query->which == Z_Query_type_101)
2874     {
2875         Z_RPNQuery *rpn = scan->query->z_query->u.type_1;
2876         const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
2877         if (cp)
2878         {
2879             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
2880             if (cd)
2881             {
2882                 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
2883
2884                 yaz_query_charset_convert_rpnquery(
2885                     rpn, c->odr_out, cd);
2886                 yaz_iconv_close(cd);
2887             }
2888         }
2889         req->attributeSet = rpn->attributeSetId;
2890         if (!req->attributeSet)
2891             req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
2892         if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
2893             rpn->RPNStructure->u.simple->which == Z_Operand_APT)
2894         {
2895             req->termListAndStartPoint =
2896                 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
2897         }
2898         else
2899         {
2900             set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
2901             return zoom_complete;
2902         }
2903     }
2904     else
2905     {
2906         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
2907         return zoom_complete;
2908     }
2909
2910     *req->numberOfTermsRequested =
2911         ZOOM_options_get_int(scan->options, "number", 10);
2912
2913     req->preferredPositionInResponse =
2914         odr_intdup(c->odr_out,
2915                    ZOOM_options_get_int(scan->options, "position", 1));
2916
2917     req->stepSize =
2918         odr_intdup(c->odr_out,
2919                    ZOOM_options_get_int(scan->options, "stepSize", 0));
2920     
2921     req->databaseNames = scan->databaseNames;
2922     req->num_databaseNames = scan->num_databaseNames;
2923
2924     return send_APDU(c, apdu);
2925 }
2926
2927 #if YAZ_HAVE_XML2
2928 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
2929 {
2930     ZOOM_scanset scan;
2931     Z_SRW_PDU *sr = 0;
2932     const char *option_val = 0;
2933
2934     if (!c->tasks)
2935         return zoom_complete;
2936     assert (c->tasks->which == ZOOM_TASK_SCAN);
2937     scan = c->tasks->u.scan.scan;
2938         
2939     sr = ZOOM_srw_get_pdu(c, Z_SRW_scan_request);
2940
2941     /* SRU scan can only carry CQL and PQF */
2942     if (scan->query->z_query->which == Z_Query_type_104)
2943     {
2944         sr->u.scan_request->query_type = Z_SRW_query_type_cql;
2945         sr->u.scan_request->scanClause.cql = scan->query->query_string;
2946     }
2947     else if (scan->query->z_query->which == Z_Query_type_1
2948              || scan->query->z_query->which == Z_Query_type_101)
2949     {
2950         sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
2951         sr->u.scan_request->scanClause.pqf = scan->query->query_string;
2952     }
2953     else
2954     {
2955         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
2956         return zoom_complete;
2957     }
2958
2959     sr->u.scan_request->maximumTerms = odr_intdup(
2960         c->odr_out, ZOOM_options_get_int(scan->options, "number", 10));
2961     
2962     sr->u.scan_request->responsePosition = odr_intdup(
2963         c->odr_out, ZOOM_options_get_int(scan->options, "position", 1));
2964     
2965     option_val = ZOOM_options_get(scan->options, "extraArgs");
2966     yaz_encode_sru_extra(sr, c->odr_out, option_val);
2967     return send_srw(c, sr);
2968 }
2969 #else
2970 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
2971 {
2972     return zoom_complete;
2973 }
2974 #endif
2975
2976
2977 ZOOM_API(size_t)
2978     ZOOM_scanset_size(ZOOM_scanset scan)
2979 {
2980     if (!scan)
2981         return 0;
2982
2983     if (scan->scan_response && scan->scan_response->entries)
2984         return scan->scan_response->entries->num_entries;
2985     else if (scan->srw_scan_response)
2986         return scan->srw_scan_response->num_terms;
2987     return 0;
2988 }
2989
2990 static void ZOOM_scanset_term_x(ZOOM_scanset scan, size_t pos,
2991                                 size_t *occ,
2992                                 const char **value_term, size_t *value_len,
2993                                 const char **disp_term, size_t *disp_len)
2994 {
2995     size_t noent = ZOOM_scanset_size(scan);
2996     
2997     *value_term = 0;
2998     *value_len = 0;
2999
3000     *disp_term = 0;
3001     *disp_len = 0;
3002
3003     *occ = 0;
3004     if (pos >= noent)
3005         return;
3006     if (scan->scan_response)
3007     {
3008         Z_ScanResponse *res = scan->scan_response;
3009         if (res->entries->entries[pos]->which == Z_Entry_termInfo)
3010         {
3011             Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
3012             
3013             *value_term = (const char *) t->term->u.general->buf;
3014             *value_len = t->term->u.general->len;
3015             if (t->displayTerm)
3016             {
3017                 *disp_term = t->displayTerm;
3018                 *disp_len = strlen(*disp_term);
3019             }
3020             else if (t->term->which == Z_Term_general)
3021             {
3022                 *disp_term = (const char *) t->term->u.general->buf;
3023                 *disp_len = t->term->u.general->len;
3024             }
3025             *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
3026         }
3027     }
3028     if (scan->srw_scan_response)
3029     {
3030         Z_SRW_scanResponse *res = scan->srw_scan_response;
3031         Z_SRW_scanTerm *t = res->terms + pos;
3032         if (t)
3033         {
3034             *value_term = t->value;
3035             *value_len = strlen(*value_term);
3036
3037             if (t->displayTerm)
3038                 *disp_term = t->displayTerm;
3039             else
3040                 *disp_term = t->value;
3041             *disp_len = strlen(*disp_term);
3042             *occ = t->numberOfRecords ? *t->numberOfRecords : 0;
3043         }
3044     }
3045 }
3046
3047 ZOOM_API(const char *)
3048     ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
3049                       size_t *occ, size_t *len)
3050 {
3051     const char *value_term = 0;
3052     size_t value_len = 0;
3053     const char *disp_term = 0;
3054     size_t disp_len = 0;
3055
3056     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3057                         &disp_term, &disp_len);
3058     
3059     *len = value_len;
3060     return value_term;
3061 }
3062
3063 ZOOM_API(const char *)
3064     ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
3065                               size_t *occ, size_t *len)
3066 {
3067     const char *value_term = 0;
3068     size_t value_len = 0;
3069     const char *disp_term = 0;
3070     size_t disp_len = 0;
3071
3072     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3073                         &disp_term, &disp_len);
3074     
3075     *len = disp_len;
3076     return disp_term;
3077 }
3078
3079 ZOOM_API(const char *)
3080     ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
3081 {
3082     return ZOOM_options_get(scan->options, key);
3083 }
3084
3085 ZOOM_API(void)
3086     ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
3087                             const char *val)
3088 {
3089     ZOOM_options_set(scan->options, key, val);
3090 }
3091
3092 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
3093 {
3094     const char *str;
3095     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
3096     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3097     
3098     str = ZOOM_options_get(p->options, "package-name");
3099     if (str && *str)
3100         req->packageName = odr_strdup(p->odr_out, str);
3101     
3102     str = ZOOM_options_get(p->options, "user-id");
3103     if (str)
3104         req->userId = odr_strdup_null(p->odr_out, str);
3105     
3106     req->packageType = odr_oiddup(p->odr_out, oid);
3107
3108     str = ZOOM_options_get(p->options, "function");
3109     if (str)
3110     {
3111         if (!strcmp (str, "create"))
3112             *req->function = Z_ExtendedServicesRequest_create;
3113         if (!strcmp (str, "delete"))
3114             *req->function = Z_ExtendedServicesRequest_delete;
3115         if (!strcmp (str, "modify"))
3116             *req->function = Z_ExtendedServicesRequest_modify;
3117     }
3118
3119     str = ZOOM_options_get(p->options, "waitAction");
3120     if (str)
3121     {
3122         if (!strcmp (str, "wait"))
3123             *req->waitAction = Z_ExtendedServicesRequest_wait;
3124         if (!strcmp (str, "waitIfPossible"))
3125             *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
3126         if (!strcmp (str, "dontWait"))
3127             *req->waitAction = Z_ExtendedServicesRequest_dontWait;
3128         if (!strcmp (str, "dontReturnPackage"))
3129             *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
3130     }
3131     return apdu;
3132 }
3133
3134 static const char *ill_array_lookup(void *clientData, const char *idx)
3135 {
3136     ZOOM_package p = (ZOOM_package) clientData;
3137     return ZOOM_options_get(p->options, idx+4);
3138 }
3139
3140 static Z_External *encode_ill_request(ZOOM_package p)
3141 {
3142     ODR out = p->odr_out;
3143     ILL_Request *req;
3144     Z_External *r = 0;
3145     struct ill_get_ctl ctl;
3146         
3147     ctl.odr = p->odr_out;
3148     ctl.clientData = p;
3149     ctl.f = ill_array_lookup;
3150         
3151     req = ill_get_ILLRequest(&ctl, "ill", 0);
3152         
3153     if (!ill_Request(out, &req, 0, 0))
3154     {
3155         int ill_request_size;
3156         char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
3157         if (ill_request_buf)
3158             odr_setbuf(out, ill_request_buf, ill_request_size, 1);
3159         return 0;
3160     }
3161     else
3162     {
3163         int illRequest_size = 0;
3164         char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
3165                 
3166         r = (Z_External *) odr_malloc(out, sizeof(*r));
3167         r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
3168         r->indirect_reference = 0;
3169         r->descriptor = 0;
3170         r->which = Z_External_single;
3171                 
3172         r->u.single_ASN1_type =
3173             odr_create_Odr_oct(out,
3174                                (unsigned char *)illRequest_buf,
3175                                illRequest_size);
3176     }
3177     return r;
3178 }
3179
3180 static Z_ItemOrder *encode_item_order(ZOOM_package p)
3181 {
3182     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
3183     const char *str;
3184     int len;
3185     
3186     req->which = Z_IOItemOrder_esRequest;
3187     req->u.esRequest = (Z_IORequest *) 
3188         odr_malloc(p->odr_out,sizeof(Z_IORequest));
3189
3190     /* to keep part ... */
3191     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
3192         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
3193     req->u.esRequest->toKeep->supplDescription = 0;
3194     req->u.esRequest->toKeep->contact = (Z_IOContact *)
3195         odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
3196         
3197     str = ZOOM_options_get(p->options, "contact-name");
3198     req->u.esRequest->toKeep->contact->name =
3199         odr_strdup_null(p->odr_out, str);
3200         
3201     str = ZOOM_options_get(p->options, "contact-phone");
3202     req->u.esRequest->toKeep->contact->phone =
3203         odr_strdup_null(p->odr_out, str);
3204         
3205     str = ZOOM_options_get(p->options, "contact-email");
3206     req->u.esRequest->toKeep->contact->email =
3207         odr_strdup_null(p->odr_out, str);
3208         
3209     req->u.esRequest->toKeep->addlBilling = 0;
3210         
3211     /* not to keep part ... */
3212     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
3213         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
3214         
3215     str = ZOOM_options_get(p->options, "itemorder-setname");
3216     if (!str)
3217         str = "default";
3218
3219     if (!*str) 
3220         req->u.esRequest->notToKeep->resultSetItem = 0;
3221     else
3222     {
3223         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
3224             odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
3225
3226         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
3227             odr_strdup(p->odr_out, str);
3228         req->u.esRequest->notToKeep->resultSetItem->item =
3229             odr_intdup(p->odr_out, 0);
3230         
3231         str = ZOOM_options_get(p->options, "itemorder-item");
3232         *req->u.esRequest->notToKeep->resultSetItem->item =
3233             (str ? atoi(str) : 1);
3234     }
3235
3236     str = ZOOM_options_getl(p->options, "doc", &len);
3237     if (str)
3238     {
3239         req->u.esRequest->notToKeep->itemRequest =
3240             z_ext_record_xml(p->odr_out, str, len);
3241     }
3242     else
3243         req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
3244     
3245     return req;
3246 }
3247
3248 Z_APDU *create_admin_package(ZOOM_package p, int type, 
3249                              Z_ESAdminOriginPartToKeep **toKeepP,
3250                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
3251 {
3252     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
3253     if (apdu)
3254     {
3255         Z_ESAdminOriginPartToKeep  *toKeep;
3256         Z_ESAdminOriginPartNotToKeep  *notToKeep;
3257         Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3258         const char *first_db = "Default";
3259         int num_db;
3260         char **db = set_DatabaseNames(p->connection, p->options, &num_db,
3261                                       p->odr_out);
3262         if (num_db > 0)
3263             first_db = db[0];
3264             
3265         r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
3266         r->descriptor = 0;
3267         r->indirect_reference = 0;
3268         r->which = Z_External_ESAdmin;
3269         
3270         r->u.adminService = (Z_Admin *)
3271             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
3272         r->u.adminService->which = Z_Admin_esRequest;
3273         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
3274             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
3275         
3276         toKeep = r->u.adminService->u.esRequest->toKeep =
3277             (Z_ESAdminOriginPartToKeep *) 
3278             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
3279         toKeep->which = type;
3280         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3281         toKeep->u.create = odr_nullval();
3282         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3283         
3284         r->u.adminService->u.esRequest->notToKeep = notToKeep =
3285             (Z_ESAdminOriginPartNotToKeep *)
3286             odr_malloc(p->odr_out,
3287                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
3288         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
3289         notToKeep->u.recordsWillFollow = odr_nullval();
3290         if (toKeepP)
3291             *toKeepP = toKeep;
3292         if (notToKeepP)
3293             *notToKeepP = notToKeep;
3294     }
3295     return apdu;
3296 }
3297
3298 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
3299 {
3300     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
3301     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3302     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
3303     int len;
3304     const char *doc = ZOOM_options_getl(p->options, "doc", &len);
3305
3306     if (!doc)
3307     {
3308         doc = "";
3309         len = 0;
3310     }
3311
3312     req->taskSpecificParameters = ext;
3313     ext->direct_reference = req->packageType;
3314     ext->descriptor = 0;
3315     ext->indirect_reference = 0;
3316     
3317     ext->which = Z_External_octet;
3318     ext->u.single_ASN1_type =
3319         odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc, len);
3320     return apdu;
3321 }
3322
3323 static Z_APDU *create_update_package(ZOOM_package p)
3324 {
3325     Z_APDU *apdu = 0;
3326     const char *first_db = "Default";
3327     int num_db;
3328     char **db = set_DatabaseNames(p->connection, p->options, &num_db, p->odr_out);
3329     const char *action = ZOOM_options_get(p->options, "action");
3330     int recordIdOpaque_len;
3331     const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
3332         &recordIdOpaque_len);
3333     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
3334     int record_len;
3335     const char *record_buf = ZOOM_options_getl(p->options, "record",
3336         &record_len);
3337     int recordOpaque_len;
3338     const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
3339         &recordOpaque_len);
3340     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
3341     const char *version = ZOOM_options_get(p->options, "updateVersion");
3342
3343     const char *correlationInfo_note =
3344         ZOOM_options_get(p->options, "correlationInfo.note");
3345     const char *correlationInfo_id =
3346         ZOOM_options_get(p->options, "correlationInfo.id");
3347     int action_no = -1;
3348     Odr_oid *syntax_oid = 0;
3349     const Odr_oid *package_oid = yaz_oid_extserv_database_update;
3350
3351     if (!version)
3352         version = "3";
3353     if (!syntax_str)
3354         syntax_str = "xml";
3355     if (!record_buf && !recordOpaque_buf)
3356     {
3357         record_buf = "void";
3358         record_len = 4;
3359         syntax_str = "SUTRS";
3360     }
3361
3362     if (syntax_str)
3363     {
3364         syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
3365                                            CLASS_RECSYN, syntax_str,
3366                                            p->odr_out);
3367     }
3368     if (!syntax_oid)
3369         return 0;
3370
3371     if (num_db > 0)
3372         first_db = db[0];
3373     
3374     switch(*version)
3375     {
3376     case '1':
3377         package_oid = yaz_oid_extserv_database_update_first_version;
3378         /* old update does not support specialUpdate */
3379         if (!action)
3380             action = "recordInsert";
3381         break;
3382     case '2':
3383         if (!action)
3384             action = "specialUpdate";
3385         package_oid = yaz_oid_extserv_database_update_second_version;
3386         break;
3387     case '3':
3388         if (!action)
3389             action = "specialUpdate";
3390         package_oid = yaz_oid_extserv_database_update;
3391         break;
3392     default:
3393         return 0;
3394     }
3395     
3396     if (!strcmp(action, "recordInsert"))
3397         action_no = Z_IUOriginPartToKeep_recordInsert;
3398     else if (!strcmp(action, "recordReplace"))
3399         action_no = Z_IUOriginPartToKeep_recordReplace;
3400     else if (!strcmp(action, "recordDelete"))
3401         action_no = Z_IUOriginPartToKeep_recordDelete;
3402     else if (!strcmp(action, "elementUpdate"))
3403         action_no = Z_IUOriginPartToKeep_elementUpdate;
3404     else if (!strcmp(action, "specialUpdate"))
3405         action_no = Z_IUOriginPartToKeep_specialUpdate;
3406     else
3407         return 0;
3408
3409     apdu = create_es_package(p, package_oid);
3410     if (apdu)
3411     {
3412         Z_IUOriginPartToKeep *toKeep;
3413         Z_IUSuppliedRecords *notToKeep;
3414         Z_External *r = (Z_External *)
3415             odr_malloc(p->odr_out, sizeof(*r));
3416         const char *elementSetName =
3417             ZOOM_options_get(p->options, "elementSetName");
3418         
3419         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3420         
3421         r->direct_reference = odr_oiddup(p->odr_out, package_oid);
3422         r->descriptor = 0;
3423         r->which = Z_External_update;
3424         r->indirect_reference = 0;
3425         r->u.update = (Z_IUUpdate *)
3426             odr_malloc(p->odr_out, sizeof(*r->u.update));
3427         
3428         r->u.update->which = Z_IUUpdate_esRequest;
3429         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3430             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3431         toKeep = r->u.update->u.esRequest->toKeep = 
3432             (Z_IUOriginPartToKeep *)
3433             odr_malloc(p->odr_out, sizeof(*toKeep));
3434         
3435         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3436         toKeep->schema = 0;
3437         
3438         toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
3439             
3440         toKeep->actionQualifier = 0;
3441         toKeep->action = odr_intdup(p->odr_out, action_no);
3442         
3443         notToKeep = r->u.update->u.esRequest->notToKeep = 
3444             (Z_IUSuppliedRecords *)
3445             odr_malloc(p->odr_out, sizeof(*notToKeep));
3446         notToKeep->num = 1;
3447         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3448             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3449         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3450             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3451         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3452         if (recordIdOpaque)
3453         {
3454             notToKeep->elements[0]->u.opaque = 
3455                 odr_create_Odr_oct(p->odr_out,
3456                                    (const unsigned char *) recordIdOpaque,
3457                                    recordIdOpaque_len);
3458         }
3459         else if (recordIdNumber)
3460         {
3461             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3462             
3463             notToKeep->elements[0]->u.number =
3464                 odr_intdup(p->odr_out, atoi(recordIdNumber));
3465         }
3466         else
3467             notToKeep->elements[0]->u.opaque = 0;
3468         notToKeep->elements[0]->supplementalId = 0;
3469         if (correlationInfo_note || correlationInfo_id)
3470         {
3471             Z_IUCorrelationInfo *ci;
3472             ci = notToKeep->elements[0]->correlationInfo =
3473                 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
3474             ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
3475             ci->id = correlationInfo_id ?
3476                 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
3477         }
3478         else
3479             notToKeep->elements[0]->correlationInfo = 0;
3480         if (recordOpaque_buf)
3481         {
3482             notToKeep->elements[0]->record =
3483                 z_ext_record_oid_any(p->odr_out, syntax_oid,
3484                                  recordOpaque_buf, recordOpaque_len);
3485         }
3486         else
3487         {
3488             notToKeep->elements[0]->record =
3489                 z_ext_record_oid(p->odr_out, syntax_oid,
3490                                  record_buf, record_len);
3491         }
3492     }
3493     if (0 && apdu)
3494     {
3495         ODR print = odr_createmem(ODR_PRINT);
3496
3497         z_APDU(print, &apdu, 0, 0);
3498         odr_destroy(print);
3499     }
3500     return apdu;
3501 }
3502
3503 ZOOM_API(void)
3504     ZOOM_package_send(ZOOM_package p, const char *type)
3505 {
3506     Z_APDU *apdu = 0;
3507     ZOOM_connection c;
3508     if (!p)
3509         return;
3510     c = p->connection;
3511     odr_reset(p->odr_out);
3512     xfree(p->buf_out);
3513     p->buf_out = 0;
3514     if (!strcmp(type, "itemorder"))
3515     {
3516         apdu = create_es_package(p, yaz_oid_extserv_item_order);
3517         if (apdu)
3518         {
3519             Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3520             
3521             r->direct_reference = 
3522                 odr_oiddup(p->odr_out, yaz_oid_extserv_item_order);
3523             r->descriptor = 0;
3524             r->which = Z_External_itemOrder;
3525             r->indirect_reference = 0;
3526             r->u.itemOrder = encode_item_order(p);
3527
3528             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3529         }
3530     }
3531     else if (!strcmp(type, "create"))  /* create database */
3532     {
3533         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3534                                     0, 0);
3535     }   
3536     else if (!strcmp(type, "drop"))  /* drop database */
3537     {
3538         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3539                                     0, 0);
3540     }
3541     else if (!strcmp(type, "commit"))  /* commit changes */
3542     {
3543         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3544                                     0, 0);
3545     }
3546     else if (!strcmp(type, "update")) /* update record(s) */
3547     {
3548         apdu = create_update_package(p);
3549     }
3550     else if (!strcmp(type, "xmlupdate"))
3551     {
3552         apdu = create_xmlupdate_package(p);
3553     }
3554     if (apdu)
3555     {
3556         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3557         {
3558             char *buf;
3559
3560             ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
3561             task->u.package = p;
3562             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3563             p->buf_out = (char *) xmalloc(p->len_out);
3564             memcpy(p->buf_out, buf, p->len_out);
3565             
3566             (p->refcount)++;
3567             if (!c->async)
3568             {
3569                 while (ZOOM_event(1, &c))
3570                     ;
3571             }
3572         }
3573     }
3574 }
3575
3576 ZOOM_API(ZOOM_package)
3577     ZOOM_connection_package(ZOOM_connection c, ZOOM_options options)
3578 {
3579     ZOOM_package p = (ZOOM_package) xmalloc(sizeof(*p));
3580
3581     p->connection = c;
3582     p->odr_out = odr_createmem(ODR_ENCODE);
3583     p->options = ZOOM_options_create_with_parent2(options, c->options);
3584     p->refcount = 1;
3585     p->buf_out = 0;
3586     p->len_out = 0;
3587     return p;
3588 }
3589
3590 ZOOM_API(void)
3591     ZOOM_package_destroy(ZOOM_package p)
3592 {
3593     if (!p)
3594         return;
3595     (p->refcount)--;
3596     if (p->refcount == 0)
3597     {
3598         odr_destroy(p->odr_out);
3599         xfree(p->buf_out);
3600         
3601         ZOOM_options_destroy(p->options);
3602         xfree(p);
3603     }
3604 }
3605
3606 ZOOM_API(const char *)
3607     ZOOM_package_option_get(ZOOM_package p, const char *key)
3608 {
3609     return ZOOM_options_get(p->options, key);
3610 }
3611
3612 ZOOM_API(const char *)
3613     ZOOM_package_option_getl(ZOOM_package p, const char *key, int *lenp)
3614 {
3615     return ZOOM_options_getl(p->options, key, lenp);
3616 }
3617
3618 ZOOM_API(void)
3619     ZOOM_package_option_set(ZOOM_package p, const char *key,
3620                             const char *val)
3621 {
3622     ZOOM_options_set(p->options, key, val);
3623 }
3624
3625 ZOOM_API(void)
3626     ZOOM_package_option_setl(ZOOM_package p, const char *key,
3627                              const char *val, int len)
3628 {
3629     ZOOM_options_setl(p->options, key, val, len);
3630 }
3631
3632 ZOOM_API(int)
3633     ZOOM_connection_exec_task(ZOOM_connection c)
3634 {
3635     ZOOM_task task = c->tasks;
3636     zoom_ret ret = zoom_complete;
3637
3638     if (!task)
3639         return 0;
3640     yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3641             c, task->which, task->running);
3642     if (c->error != ZOOM_ERROR_NONE)
3643     {
3644         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3645                 "removing tasks because of error = %d", c, c->error);
3646         ZOOM_connection_remove_tasks(c);
3647         return 0;
3648     }
3649     if (task->running)
3650     {
3651         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3652                 "task already running", c);
3653         return 0;
3654     }
3655     task->running = 1;
3656     ret = zoom_complete;
3657     if (c->cs || task->which == ZOOM_TASK_CONNECT)
3658     {
3659         switch (task->which)
3660         {
3661         case ZOOM_TASK_SEARCH:
3662             if (c->proto == PROTO_HTTP)
3663                 ret = ZOOM_connection_srw_send_search(c);
3664             else
3665                 ret = ZOOM_connection_send_search(c);
3666             break;
3667         case ZOOM_TASK_RETRIEVE:
3668             if (c->proto == PROTO_HTTP)
3669                 ret = ZOOM_connection_srw_send_search(c);
3670             else
3671                 ret = send_present(c);
3672             break;
3673         case ZOOM_TASK_CONNECT:
3674             ret = do_connect(c);
3675             break;
3676         case ZOOM_TASK_SCAN:
3677             if (c->proto == PROTO_HTTP)
3678                 ret = ZOOM_connection_srw_send_scan(c);
3679             else
3680                 ret = ZOOM_connection_send_scan(c);
3681             break;
3682         case ZOOM_TASK_PACKAGE:
3683             ret = send_package(c);
3684             break;
3685         case ZOOM_TASK_SORT:
3686             c->tasks->u.sort.resultset->r_sort_spec = 
3687                 c->tasks->u.sort.q->sort_spec;
3688             ret = send_sort(c, c->tasks->u.sort.resultset);
3689             break;
3690         }
3691     }
3692     else
3693     {
3694         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3695                 "remove tasks because no connection exist", c);
3696         ZOOM_connection_remove_tasks(c);
3697     }
3698     if (ret == zoom_complete)
3699     {
3700         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3701                 "task removed (complete)", c);
3702         ZOOM_connection_remove_task(c);
3703         return 0;
3704     }
3705     yaz_log(log_details, "%p ZOOM_connection_exec_task "
3706             "task pending", c);
3707     return 1;
3708 }
3709
3710 static zoom_ret send_sort_present(ZOOM_connection c)
3711 {
3712     zoom_ret r = zoom_complete;
3713
3714     if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3715         r = send_sort(c, c->tasks->u.search.resultset);
3716     if (r == zoom_complete)
3717         r = send_present(c);
3718     return r;
3719 }
3720
3721 static int es_response_taskpackage_update(ZOOM_connection c,
3722                 Z_IUUpdateTaskPackage *utp)
3723 {
3724         if (utp && utp->targetPart)
3725         {
3726                 Z_IUTargetPart *targetPart = utp->targetPart;
3727                 switch ( *targetPart->updateStatus ) {
3728                         case Z_IUTargetPart_success:
3729                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "success");
3730                                 break;
3731                         case Z_IUTargetPart_partial:
3732                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "partial");
3733                                 break;
3734                         case Z_IUTargetPart_failure:
3735                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "failure");
3736                                 if (targetPart->globalDiagnostics && targetPart->num_globalDiagnostics > 0)
3737                                         response_diag(c, targetPart->globalDiagnostics[0]);
3738                                 break;
3739                 }
3740                 // NOTE: Individual record status, surrogate diagnostics, and supplemental diagnostics ARE NOT REPORTED.
3741         }
3742     return 1;
3743 }
3744
3745 static int es_response_taskpackage(ZOOM_connection c,
3746                                    Z_TaskPackage *taskPackage)
3747 {
3748         // targetReference
3749         Odr_oct *id = taskPackage->targetReference;
3750         if (id)
3751                 ZOOM_options_setl(c->tasks->u.package->options,
3752                                                         "targetReference", (char*) id->buf, id->len);
3753         
3754         // taskStatus
3755         switch ( *taskPackage->taskStatus ) {
3756                 case Z_TaskPackage_pending:
3757                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "pending");
3758                         break;
3759                 case Z_TaskPackage_active:
3760                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "active");
3761                         break;
3762                 case Z_TaskPackage_complete:
3763                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "complete");
3764                         break;
3765                 case Z_TaskPackage_aborted:
3766                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "aborted");
3767                         if ( taskPackage->num_packageDiagnostics && taskPackage->packageDiagnostics )
3768                                 response_diag(c, taskPackage->packageDiagnostics[0]);
3769                         break;
3770         }
3771         
3772         // taskSpecificParameters
3773         // NOTE: Only Update implemented, no others.
3774         if ( taskPackage->taskSpecificParameters->which == Z_External_update ) {
3775                         Z_IUUpdateTaskPackage *utp = taskPackage->taskSpecificParameters->u.update->u.taskPackage;
3776                         es_response_taskpackage_update(c, utp);
3777         }
3778         return 1;
3779 }
3780
3781
3782 static int es_response(ZOOM_connection c,
3783                        Z_ExtendedServicesResponse *res)
3784 {
3785     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3786         return 0;
3787     switch (*res->operationStatus) {
3788         case Z_ExtendedServicesResponse_done:
3789             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "done");
3790             break;
3791         case Z_ExtendedServicesResponse_accepted:
3792             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "accepted");
3793             break;
3794         case Z_ExtendedServicesResponse_failure:
3795             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "failure");
3796             if (res->diagnostics && res->num_diagnostics > 0)
3797                 response_diag(c, res->diagnostics[0]);
3798             break;
3799     }
3800     if (res->taskPackage &&
3801         res->taskPackage->which == Z_External_extendedService)
3802     {
3803         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
3804         es_response_taskpackage(c, taskPackage);
3805     }
3806     if (res->taskPackage && 
3807         res->taskPackage->which == Z_External_octet)
3808     {
3809         Odr_oct *doc = res->taskPackage->u.octet_aligned;
3810         ZOOM_options_setl(c->tasks->u.package->options,
3811                           "xmlUpdateDoc", (char*) doc->buf, doc->len);
3812     }
3813     return 1;
3814 }
3815
3816 static void interpret_init_diag(ZOOM_connection c,
3817                                 Z_DiagnosticFormat *diag)
3818 {
3819     if (diag->num > 0)
3820     {
3821         Z_DiagnosticFormat_s *ds = diag->elements[0];
3822         if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
3823             response_default_diag(c, ds->u.defaultDiagRec);
3824     }
3825 }
3826
3827
3828 static void interpret_otherinformation_field(ZOOM_connection c,
3829                                              Z_OtherInformation *ui)
3830 {
3831     int i;
3832     for (i = 0; i < ui->num_elements; i++)
3833     {
3834         Z_OtherInformationUnit *unit = ui->list[i];
3835         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
3836             unit->information.externallyDefinedInfo &&
3837             unit->information.externallyDefinedInfo->which ==
3838             Z_External_diag1) 
3839         {
3840             interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
3841         } 
3842     }
3843 }
3844
3845
3846 static void set_init_option(const char *name, void *clientData) {
3847     ZOOM_connection c = (ZOOM_connection) clientData;
3848     char buf[80];
3849
3850     sprintf(buf, "init_opt_%.70s", name);
3851     ZOOM_connection_option_set(c, buf, "1");
3852 }
3853
3854
3855 static void recv_apdu(ZOOM_connection c, Z_APDU *apdu)
3856 {
3857     Z_InitResponse *initrs;
3858     
3859     ZOOM_connection_set_mask(c, 0);
3860     yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
3861     switch(apdu->which)
3862     {
3863     case Z_APDU_initResponse:
3864         yaz_log(log_api, "%p recv_apdu: Received Init response", c);
3865         initrs = apdu->u.initResponse;
3866         ZOOM_connection_option_set(c, "serverImplementationId",
3867                                    initrs->implementationId ?
3868                                    initrs->implementationId : "");
3869         ZOOM_connection_option_set(c, "serverImplementationName",
3870                                    initrs->implementationName ?
3871                                    initrs->implementationName : "");
3872         ZOOM_connection_option_set(c, "serverImplementationVersion",
3873                                    initrs->implementationVersion ?
3874                                    initrs->implementationVersion : "");
3875         /* Set the three old options too, for old applications */
3876         ZOOM_connection_option_set(c, "targetImplementationId",
3877                                    initrs->implementationId ?
3878                                    initrs->implementationId : "");
3879         ZOOM_connection_option_set(c, "targetImplementationName",
3880                                    initrs->implementationName ?
3881                                    initrs->implementationName : "");
3882         ZOOM_connection_option_set(c, "targetImplementationVersion",
3883                                    initrs->implementationVersion ?
3884                                    initrs->implementationVersion : "");
3885
3886         /* Make initrs->options available as ZOOM-level options */
3887         yaz_init_opt_decode(initrs->options, set_init_option, (void*) c);
3888
3889         if (!*initrs->result)
3890         {
3891             Z_External *uif = initrs->userInformationField;
3892
3893             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
3894
3895             if (uif && uif->which == Z_External_userInfo1)
3896                 interpret_otherinformation_field(c, uif->u.userInfo1);
3897         }
3898         else
3899         {
3900             char *cookie =
3901                 yaz_oi_get_string_oid(&apdu->u.initResponse->otherInfo,
3902                                       yaz_oid_userinfo_cookie, 1, 0);
3903             xfree(c->cookie_in);
3904             c->cookie_in = 0;
3905             if (cookie)
3906                 c->cookie_in = xstrdup(cookie);
3907             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
3908                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
3909                 c->support_named_resultsets = 1;
3910             if (c->tasks)
3911             {
3912                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
3913                 ZOOM_connection_remove_task(c);
3914             }
3915             ZOOM_connection_exec_task(c);
3916         }
3917         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
3918         {
3919             NMEM tmpmem = nmem_create();
3920             Z_CharSetandLanguageNegotiation *p =
3921                 yaz_get_charneg_record(initrs->otherInfo);
3922             
3923             if (p)
3924             {
3925                 char *charset = NULL, *lang = NULL;
3926                 int sel;
3927                 
3928                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
3929                 yaz_log(log_details, "%p recv_apdu target accepted: "
3930                         "charset %s, language %s, select %d",
3931                         c,
3932                         charset ? charset : "none", lang ? lang : "none", sel);
3933                 if (charset)
3934                     ZOOM_connection_option_set(c, "negotiation-charset",
3935                                                charset);
3936                 if (lang)
3937                     ZOOM_connection_option_set(c, "negotiation-lang",
3938                                                lang);
3939
3940                 ZOOM_connection_option_set(
3941                     c,  "negotiation-charset-in-effect-for-records",
3942                     (sel != 0) ? "1" : "0");
3943                 nmem_destroy(tmpmem);
3944             }
3945         }       
3946         break;
3947     case Z_APDU_searchResponse:
3948         yaz_log(log_api, "%p recv_apdu Search response", c);
3949         handle_search_response(c, apdu->u.searchResponse);
3950         if (send_sort_present(c) == zoom_complete)
3951             ZOOM_connection_remove_task(c);
3952         break;
3953     case Z_APDU_presentResponse:
3954         yaz_log(log_api, "%p recv_apdu Present response", c);
3955         handle_present_response(c, apdu->u.presentResponse);
3956         if (send_present(c) == zoom_complete)
3957             ZOOM_connection_remove_task(c);
3958         break;
3959     case Z_APDU_sortResponse:
3960         yaz_log(log_api, "%p recv_apdu Sort response", c);
3961         sort_response(c, apdu->u.sortResponse);
3962         if (send_present(c) == zoom_complete)
3963             ZOOM_connection_remove_task(c);
3964         break;
3965     case Z_APDU_scanResponse:
3966         yaz_log(log_api, "%p recv_apdu Scan response", c);
3967         scan_response(c, apdu->u.scanResponse);
3968         ZOOM_connection_remove_task(c);
3969         break;
3970     case Z_APDU_extendedServicesResponse:
3971         yaz_log(log_api, "%p recv_apdu Extended Services response", c);
3972         es_response(c, apdu->u.extendedServicesResponse);
3973         ZOOM_connection_remove_task(c);
3974         break;
3975     case Z_APDU_close:
3976         yaz_log(log_api, "%p recv_apdu Close PDU", c);
3977         if (!ZOOM_test_reconnect(c))
3978         {
3979             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3980             do_close(c);
3981         }
3982         break;
3983     default:
3984         yaz_log(log_api, "%p Received unknown PDU", c);
3985         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3986         do_close(c);
3987     }
3988 }
3989
3990 #if YAZ_HAVE_XML2
3991 static zoom_ret handle_srw_response(ZOOM_connection c,
3992                                     Z_SRW_searchRetrieveResponse *res)
3993 {
3994     ZOOM_resultset resultset = 0;
3995     int i;
3996     NMEM nmem;
3997     ZOOM_Event event;
3998     int *start, *count;
3999     const char *syntax, *elementSetName;
4000
4001     if (!c->tasks)
4002         return zoom_complete;
4003
4004     switch(c->tasks->which)
4005     {
4006     case ZOOM_TASK_SEARCH:
4007         resultset = c->tasks->u.search.resultset;
4008         start = &c->tasks->u.search.start;
4009         count = &c->tasks->u.search.count;
4010         syntax = c->tasks->u.search.syntax;
4011         elementSetName = c->tasks->u.search.elementSetName;        
4012
4013         if (!c->tasks->u.search.recv_search_fired)
4014         {
4015             event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
4016             ZOOM_connection_put_event(c, event);
4017             c->tasks->u.search.recv_search_fired = 1;
4018         }
4019         break;
4020     case ZOOM_TASK_RETRIEVE:
4021         resultset = c->tasks->u.retrieve.resultset;
4022         start = &c->tasks->u.retrieve.start;
4023         count = &c->tasks->u.retrieve.count;
4024         syntax = c->tasks->u.retrieve.syntax;
4025         elementSetName = c->tasks->u.retrieve.elementSetName;
4026         break;
4027     default:
4028         return zoom_complete;
4029     }
4030
4031     resultset->size = 0;
4032
4033     if (res->resultSetId)
4034         ZOOM_resultset_option_set(resultset, "resultSetId", res->resultSetId);
4035
4036     yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
4037
4038     if (res->num_diagnostics > 0)
4039     {
4040         set_SRU_error(c, &res->diagnostics[0]);
4041     }
4042     else
4043     {
4044         if (res->numberOfRecords)
4045             resultset->size = *res->numberOfRecords;
4046         for (i = 0; i<res->num_records; i++)
4047         {
4048             int pos;
4049             Z_SRW_record *sru_rec;
4050             Z_SRW_diagnostic *diag = 0;
4051             int num_diag;
4052             
4053             Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
4054                 odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
4055             
4056             if (res->records[i].recordPosition && 
4057                 *res->records[i].recordPosition > 0)
4058                 pos = *res->records[i].recordPosition - 1;
4059             else
4060                 pos = *start + i;
4061             
4062             sru_rec = &res->records[i];
4063             
4064             npr->databaseName = 0;
4065             npr->which = Z_NamePlusRecord_databaseRecord;
4066             npr->u.databaseRecord = (Z_External *)
4067                 odr_malloc(c->odr_in, sizeof(Z_External));
4068             npr->u.databaseRecord->descriptor = 0;
4069             npr->u.databaseRecord->direct_reference =
4070                 odr_oiddup(c->odr_in, yaz_oid_recsyn_xml);
4071             npr->u.databaseRecord->which = Z_External_octet;
4072             
4073             npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
4074                 odr_malloc(c->odr_in, sizeof(Odr_oct));
4075             npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
4076                 sru_rec->recordData_buf;
4077             npr->u.databaseRecord->u.octet_aligned->len = 
4078                 npr->u.databaseRecord->u.octet_aligned->size = 
4079                 sru_rec->recordData_len;
4080             
4081             if (sru_rec->recordSchema 
4082                 && !strcmp(sru_rec->recordSchema,
4083                            "info:srw/schema/1/diagnostics-v1.1"))
4084             {
4085                 sru_decode_surrogate_diagnostics(sru_rec->recordData_buf,
4086                                                  sru_rec->recordData_len,
4087                                                  &diag, &num_diag,
4088                                                  resultset->odr);
4089             }
4090             record_cache_add(resultset, npr, pos, syntax, elementSetName,
4091                              sru_rec->recordSchema, diag);
4092         }
4093         *count -= i;
4094         *start += i;
4095         if (*count + *start > resultset->size)
4096             *count = resultset->size - *start;
4097         if (*count < 0)
4098             *count = 0;
4099         
4100         nmem = odr_extract_mem(c->odr_in);
4101         nmem_transfer(odr_getmem(resultset->odr), nmem);
4102         nmem_destroy(nmem);
4103
4104         if (*count > 0)
4105             return ZOOM_connection_srw_send_search(c);
4106     }
4107     return zoom_complete;
4108 }
4109 #endif
4110
4111 #if YAZ_HAVE_XML2
4112 static void handle_srw_scan_response(ZOOM_connection c,
4113                                      Z_SRW_scanResponse *res)
4114 {
4115     NMEM nmem = odr_extract_mem(c->odr_in);
4116     ZOOM_scanset scan;
4117
4118     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
4119         return;
4120     scan = c->tasks->u.scan.scan;
4121
4122     if (res->num_diagnostics > 0)
4123         set_SRU_error(c, &res->diagnostics[0]);
4124
4125     scan->scan_response = 0;
4126     scan->srw_scan_response = res;
4127     nmem_transfer(odr_getmem(scan->odr), nmem);
4128
4129     ZOOM_options_set_int(scan->options, "number", res->num_terms);
4130     nmem_destroy(nmem);
4131 }
4132 #endif
4133
4134 #if YAZ_HAVE_XML2
4135 static Z_GDU *get_HTTP_Request_url(ODR odr, const char *url)
4136 {
4137     Z_GDU *p = z_get_HTTP_Request(odr);
4138     const char *host = url;
4139     const char *cp0 = strstr(host, "://");
4140     const char *cp1 = 0;
4141     if (cp0)
4142         cp0 = cp0+3;
4143     else
4144         cp0 = host;
4145     
4146     cp1 = strchr(cp0, '/');
4147     if (!cp1)
4148         cp1 = cp0 + strlen(cp0);
4149     
4150     if (cp0 && cp1)
4151     {
4152         char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
4153         memcpy (h, cp0, cp1 - cp0);
4154         h[cp1-cp0] = '\0';
4155         z_HTTP_header_add(odr, &p->u.HTTP_Request->headers, "Host", h);
4156     }
4157     p->u.HTTP_Request->path = odr_strdup(odr, *cp1 ? cp1 : "/");
4158     return p;
4159 }
4160
4161 static zoom_ret send_SRW_redirect(ZOOM_connection c, const char *uri,
4162                                   Z_HTTP_Response *cookie_hres)
4163 {
4164     struct Z_HTTP_Header *h;
4165     Z_GDU *gdu = get_HTTP_Request_url(c->odr_out, uri);
4166
4167     gdu->u.HTTP_Request->method = odr_strdup(c->odr_out, "GET");
4168     z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers, "Accept",
4169                       "text/xml");
4170     
4171     for (h = cookie_hres->headers; h; h = h->next)
4172     {
4173         if (!strcmp(h->name, "Set-Cookie"))
4174             z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers,
4175                               "Cookie", h->value);
4176     }
4177     if (c->user && c->password)
4178     {
4179         z_HTTP_header_add_basic_auth(c->odr_out, &gdu->u.HTTP_Request->headers,
4180                                      c->user, c->password);
4181     }
4182     if (!z_GDU(c->odr_out, &gdu, 0, 0))
4183         return zoom_complete;
4184     if (c->odr_print)
4185         z_GDU(c->odr_print, &gdu, 0, 0);
4186     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
4187
4188     odr_reset(c->odr_out);
4189     return do_write(c);
4190 }
4191
4192 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
4193 {
4194     zoom_ret cret = zoom_complete;
4195     int ret = -1;
4196     const char *addinfo = 0;
4197     const char *connection_head = z_HTTP_header_lookup(hres->headers,
4198                                                        "Connection");
4199     const char *location;
4200
4201     ZOOM_connection_set_mask(c, 0);
4202     yaz_log(log_details, "%p handle_http", c);
4203     
4204     if ((hres->code == 301 || hres->code == 302) && c->sru_mode == zoom_sru_get
4205         && (location = z_HTTP_header_lookup(hres->headers, "Location")))
4206     {
4207         c->no_redirects++;
4208         if (c->no_redirects > 10)
4209         {
4210             set_HTTP_error(c, hres->code, 0, 0);
4211             c->no_redirects = 0;
4212             do_close(c);
4213         }
4214         else
4215         {
4216             /* since redirect may change host we just reconnect. A smarter
4217                implementation might check whether it's the same server */
4218             do_connect_host(c, location, 0);
4219             send_SRW_redirect(c, location, hres);
4220             /* we're OK for now. Operation is not really complete */
4221             ret = 0;
4222             cret = zoom_pending;
4223         }
4224     }
4225     else 
4226     {   /* not redirect (normal response) */
4227         if (!yaz_srw_check_content_type(hres))
4228             addinfo = "content-type";
4229         else
4230         {
4231             Z_SOAP *soap_package = 0;
4232             ODR o = c->odr_in;
4233             Z_SOAP_Handler soap_handlers[2] = {
4234                 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
4235                 {0, 0, 0}
4236             };
4237             ret = z_soap_codec(o, &soap_package,
4238                                &hres->content_buf, &hres->content_len,
4239                                soap_handlers);
4240             if (!ret && soap_package->which == Z_SOAP_generic &&
4241                 soap_package->u.generic->no == 0)
4242             {
4243                 Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
4244                 
4245                 ZOOM_options_set(c->options, "sru_version", sr->srw_version);
4246                 ZOOM_options_setl(c->options, "sru_extra_response_data",
4247                                   sr->extraResponseData_buf, sr->extraResponseData_len);
4248                 if (sr->which == Z_SRW_searchRetrieve_response)
4249                     cret = handle_srw_response(c, sr->u.response);
4250                 else if (sr->which == Z_SRW_scan_response)
4251                     handle_srw_scan_response(c, sr->u.scan_response);
4252                 else
4253                     ret = -1;
4254             }
4255             else if (!ret && (soap_package->which == Z_SOAP_fault
4256                               || soap_package->which == Z_SOAP_error))
4257             {
4258                 set_HTTP_error(c, hres->code,
4259                                soap_package->u.fault->fault_code,
4260                                soap_package->u.fault->fault_string);
4261             }
4262             else
4263                 ret = -1;
4264         }   
4265         if (ret == 0)
4266         {
4267             if (c->no_redirects) /* end of redirect. change hosts again */
4268                 do_close(c);
4269         }
4270         c->no_redirects = 0;
4271     }
4272     if (ret)
4273     {
4274         if (hres->code != 200)
4275             set_HTTP_error(c, hres->code, 0, 0);
4276         else
4277             set_ZOOM_error(c, ZOOM_ERROR_DECODE, addinfo);
4278         do_close(c);
4279     }
4280     if (cret == zoom_complete)
4281         ZOOM_connection_remove_task(c);
4282     if (!strcmp(hres->version, "1.0"))
4283     {
4284         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
4285         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
4286             do_close(c);
4287     }
4288     else 
4289     {
4290         /* HTTP 1.1: only if no close we stay alive .. */
4291         if (connection_head && !strcmp(connection_head, "close"))
4292             do_close(c);
4293     }
4294 }
4295 #endif
4296
4297 static int do_read(ZOOM_connection c)
4298 {
4299     int r, more;
4300     ZOOM_Event event;
4301     
4302     event = ZOOM_Event_create(ZOOM_EVENT_RECV_DATA);
4303     ZOOM_connection_put_event(c, event);
4304     
4305     r = cs_get(c->cs, &c->buf_in, &c->len_in);
4306     more = cs_more(c->cs);
4307     yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
4308     if (r == 1)
4309         return 0;
4310     if (r <= 0)
4311     {
4312         if (!ZOOM_test_reconnect(c))
4313         {
4314             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4315             do_close(c);
4316         }
4317     }
4318     else
4319     {
4320         Z_GDU *gdu;
4321         ZOOM_Event event;
4322
4323         odr_reset(c->odr_in);
4324         odr_setbuf(c->odr_in, c->buf_in, r, 0);
4325         event = ZOOM_Event_create(ZOOM_EVENT_RECV_APDU);
4326         ZOOM_connection_put_event(c, event);
4327
4328         if (!z_GDU(c->odr_in, &gdu, 0, 0))
4329         {
4330             int x;
4331             int err = odr_geterrorx(c->odr_in, &x);
4332             char msg[100];
4333             const char *element = odr_getelement(c->odr_in);
4334             yaz_snprintf(msg, sizeof(msg),
4335                     "ODR code %d:%d element=%s offset=%d",
4336                     err, x, element ? element : "<unknown>",
4337                     odr_offset(c->odr_in));
4338             set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
4339             if (log_api)
4340             {
4341                 FILE *ber_file = yaz_log_file();
4342                 if (ber_file)
4343                     odr_dumpBER(ber_file, c->buf_in, r);
4344             }
4345             do_close(c);
4346         }
4347         else
4348         {
4349             if (c->odr_print)
4350                 z_GDU(c->odr_print, &gdu, 0, 0);
4351             if (gdu->which == Z_GDU_Z3950)
4352                 recv_apdu(c, gdu->u.z3950);
4353             else if (gdu->which == Z_GDU_HTTP_Response)
4354             {
4355 #if YAZ_HAVE_XML2
4356                 handle_http(c, gdu->u.HTTP_Response);
4357 #else
4358                 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
4359                 do_close(c);
4360 #endif
4361             }
4362         }
4363         c->reconnect_ok = 0;
4364     }
4365     return 1;
4366 }
4367
4368 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out)
4369 {
4370     int r;
4371     ZOOM_Event event;
4372     
4373     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
4374     ZOOM_connection_put_event(c, event);
4375
4376     yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
4377     if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
4378     {
4379         yaz_log(log_details, "%p do_write_ex write failed", c);
4380         if (ZOOM_test_reconnect(c))
4381         {
4382             return zoom_pending;
4383         }
4384         if (c->state == STATE_CONNECTING)
4385             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4386         else
4387             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4388         do_close(c);
4389         return zoom_complete;
4390     }
4391     else if (r == 1)
4392     {    
4393         int mask = ZOOM_SELECT_EXCEPT;
4394         if (c->cs->io_pending & CS_WANT_WRITE)
4395             mask += ZOOM_SELECT_WRITE;
4396         if (c->cs->io_pending & CS_WANT_READ)
4397             mask += ZOOM_SELECT_READ;
4398         ZOOM_connection_set_mask(c, mask);
4399         yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
4400                 c, c->mask);
4401     }
4402     else
4403     {
4404         ZOOM_connection_set_mask(c, ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT);
4405         yaz_log(log_details, "%p do_write_ex write complete mask=%d",
4406                 c, c->mask);
4407     }
4408     return zoom_pending;
4409 }
4410
4411 static zoom_ret do_write(ZOOM_connection c)
4412 {
4413     return do_write_ex(c, c->buf_out, c->len_out);
4414 }
4415
4416
4417 ZOOM_API(const char *)
4418     ZOOM_connection_option_get(ZOOM_connection c, const char *key)
4419 {
4420     return ZOOM_options_get(c->options, key);
4421 }
4422
4423 ZOOM_API(const char *)
4424     ZOOM_connection_option_getl(ZOOM_connection c, const char *key, int *lenp)
4425 {
4426     return ZOOM_options_getl(c->options, key, lenp);
4427 }
4428
4429 ZOOM_API(void)
4430     ZOOM_connection_option_set(ZOOM_connection c, const char *key,
4431                                const char *val)
4432 {
4433     ZOOM_options_set(c->options, key, val);
4434 }
4435
4436 ZOOM_API(void)
4437     ZOOM_connection_option_setl(ZOOM_connection c, const char *key,
4438                                 const char *val, int len)
4439 {
4440     ZOOM_options_setl(c->options, key, val, len);
4441 }
4442
4443 ZOOM_API(const char *)
4444     ZOOM_resultset_option_get(ZOOM_resultset r, const char *key)
4445 {
4446     return ZOOM_options_get(r->options, key);
4447 }
4448
4449 ZOOM_API(void)
4450     ZOOM_resultset_option_set(ZOOM_resultset r, const char *key,
4451                               const char *val)
4452 {
4453     ZOOM_options_set(r->options, key, val);
4454 }
4455
4456
4457 ZOOM_API(int)
4458     ZOOM_connection_errcode(ZOOM_connection c)
4459 {
4460     return ZOOM_connection_error(c, 0, 0);
4461 }
4462
4463 ZOOM_API(const char *)
4464     ZOOM_connection_errmsg(ZOOM_connection c)
4465 {
4466     const char *msg;
4467     ZOOM_connection_error(c, &msg, 0);
4468     return msg;
4469 }
4470
4471 ZOOM_API(const char *)
4472     ZOOM_connection_addinfo(ZOOM_connection c)
4473 {
4474     const char *addinfo;
4475     ZOOM_connection_error(c, 0, &addinfo);
4476     return addinfo;
4477 }
4478
4479 ZOOM_API(const char *)
4480     ZOOM_connection_diagset(ZOOM_connection c)
4481 {
4482     const char *diagset;
4483     ZOOM_connection_error_x(c, 0, 0, &diagset);
4484     return diagset;
4485 }
4486
4487 ZOOM_API(const char *)
4488     ZOOM_diag_str(int error)
4489 {
4490     switch (error)
4491     {
4492     case ZOOM_ERROR_NONE:
4493         return "No error";
4494     case ZOOM_ERROR_CONNECT:
4495         return "Connect failed";
4496     case ZOOM_ERROR_MEMORY:
4497         return "Out of memory";
4498     case ZOOM_ERROR_ENCODE:
4499         return "Encoding failed";
4500     case ZOOM_ERROR_DECODE:
4501         return "Decoding failed";
4502     case ZOOM_ERROR_CONNECTION_LOST:
4503         return "Connection lost";
4504     case ZOOM_ERROR_INIT:
4505         return "Init rejected";
4506     case ZOOM_ERROR_INTERNAL:
4507         return "Internal failure";
4508     case ZOOM_ERROR_TIMEOUT:
4509         return "Timeout";
4510     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
4511         return "Unsupported protocol";
4512     case ZOOM_ERROR_UNSUPPORTED_QUERY:
4513         return "Unsupported query type";
4514     case ZOOM_ERROR_INVALID_QUERY:
4515         return "Invalid query";
4516     case ZOOM_ERROR_CQL_PARSE:
4517         return "CQL parsing error";
4518     case ZOOM_ERROR_CQL_TRANSFORM:
4519         return "CQL transformation error";
4520     case ZOOM_ERROR_CCL_CONFIG:
4521         return "CCL configuration error";
4522     case ZOOM_ERROR_CCL_PARSE:
4523         return "CCL parsing error";
4524     default:
4525         return diagbib1_str(error);
4526     }
4527 }
4528
4529 ZOOM_API(int)
4530     ZOOM_connection_error_x(ZOOM_connection c, const char **cp,
4531                             const char **addinfo, const char **diagset)
4532 {
4533     int error = c->error;
4534     if (cp)
4535     {
4536         if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
4537             *cp = ZOOM_diag_str(error);
4538         else if (!strcmp(c->diagset, "HTTP"))
4539             *cp = z_HTTP_errmsg(c->error);
4540         else if (!strcmp(c->diagset, "Bib-1"))
4541             *cp = ZOOM_diag_str(error);
4542         else if (!strcmp(c->diagset, "info:srw/diagnostic/1"))
4543             *cp = yaz_diag_srw_str(c->error);
4544         else
4545             *cp = "Unknown error and diagnostic set";
4546     }
4547     if (addinfo)
4548         *addinfo = c->addinfo ? c->addinfo : "";
4549     if (diagset)
4550         *diagset = c->diagset ? c->diagset : "";
4551     return c->error;
4552 }
4553
4554 ZOOM_API(int)
4555     ZOOM_connection_error(ZOOM_connection c, const char **cp,
4556                           const char **addinfo)
4557 {
4558     return ZOOM_connection_error_x(c, cp, addinfo, 0);
4559 }
4560
4561 static void ZOOM_connection_do_io(ZOOM_connection c, int mask)
4562 {
4563     ZOOM_Event event = 0;
4564     int r = cs_look(c->cs);
4565     yaz_log(log_details, "%p ZOOM_connection_do_io mask=%d cs_look=%d",
4566             c, mask, r);
4567     
4568     if (r == CS_NONE)
4569     {
4570         event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4571         set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4572         do_close(c);
4573         ZOOM_connection_put_event(c, event);
4574     }
4575     else if (r == CS_CONNECT)
4576     {
4577         int ret = ret = cs_rcvconnect(c->cs);
4578         yaz_log(log_details, "%p ZOOM_connection_do_io "
4579                 "cs_rcvconnect returned %d", c, ret);
4580         if (ret == 1)
4581         {
4582             int mask = ZOOM_SELECT_EXCEPT;
4583             if (c->cs->io_pending & CS_WANT_WRITE)
4584                 mask += ZOOM_SELECT_WRITE;
4585             if (c->cs->io_pending & CS_WANT_READ)
4586                 mask += ZOOM_SELECT_READ;
4587             ZOOM_connection_set_mask(c, mask);
4588             event = ZOOM_Event_create(ZOOM_EVENT_NONE);
4589             ZOOM_connection_put_event(c, event);
4590         }
4591         else if (ret == 0)
4592         {
4593             event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4594             ZOOM_connection_put_event(c, event);
4595             get_cert(c);
4596             if (c->proto == PROTO_Z3950)
4597                 ZOOM_connection_send_init(c);
4598             else
4599             {
4600                 /* no init request for SRW .. */
4601                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
4602                 ZOOM_connection_remove_task(c);
4603                 ZOOM_connection_set_mask(c, 0);
4604                 ZOOM_connection_exec_task(c);
4605             }
4606             c->state = STATE_ESTABLISHED;
4607         }
4608         else
4609         {
4610             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4611             do_close(c);
4612         }
4613     }
4614     else
4615     {
4616         if (mask & ZOOM_SELECT_EXCEPT)
4617         {
4618             if (!ZOOM_test_reconnect(c))
4619             {
4620                 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4621                 do_close(c);
4622             }
4623             return;
4624         }
4625         if (mask & ZOOM_SELECT_READ)
4626             do_read(c);
4627         if (c->cs && (mask & ZOOM_SELECT_WRITE))
4628             do_write(c);
4629     }
4630 }
4631
4632 ZOOM_API(int)
4633     ZOOM_connection_last_event(ZOOM_connection cs)
4634 {
4635     if (!cs)
4636         return ZOOM_EVENT_NONE;
4637     return cs->last_event;
4638 }
4639
4640
4641 static void cql2pqf_wrbuf_puts(const char *buf, void *client_data)
4642 {
4643     WRBUF wrbuf = (WRBUF) client_data;
4644     wrbuf_puts(wrbuf, buf);
4645 }
4646
4647 /*
4648  * Returns an xmalloc()d string containing RPN that corresponds to the
4649  * CQL passed in.  On error, sets the Connection object's error state
4650  * and returns a null pointer.
4651  * ### We could cache CQL parser and/or transformer in Connection.
4652  */
4653 static char *cql2pqf(ZOOM_connection c, const char *cql)
4654 {
4655     CQL_parser parser;
4656     int error;
4657     const char *cqlfile;
4658     cql_transform_t trans;
4659     char *result = 0;
4660
4661     parser = cql_parser_create();
4662     if ((error = cql_parser_string(parser, cql)) != 0) {
4663         cql_parser_destroy(parser);
4664         set_ZOOM_error(c, ZOOM_ERROR_CQL_PARSE, cql);
4665         return 0;
4666     }
4667
4668     cqlfile = ZOOM_connection_option_get(c, "cqlfile");
4669     if (cqlfile == 0) 
4670     {
4671         set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, "no CQL transform file");
4672     }
4673     else if ((trans = cql_transform_open_fname(cqlfile)) == 0) 
4674     {
4675         char buf[512];        
4676         sprintf(buf, "can't open CQL transform file '%.200s': %.200s",
4677                 cqlfile, strerror(errno));
4678         set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4679     }
4680     else 
4681     {
4682         WRBUF wrbuf_result = wrbuf_alloc();
4683         error = cql_transform(trans, cql_parser_result(parser),
4684                               cql2pqf_wrbuf_puts, wrbuf_result);
4685         if (error != 0) {
4686             char buf[512];
4687             const char *addinfo;
4688             error = cql_transform_error(trans, &addinfo);
4689             sprintf(buf, "%.200s (addinfo=%.200s)", 
4690                     cql_strerror(error), addinfo);
4691             set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4692         }
4693         else
4694         {
4695             result = xstrdup(wrbuf_cstr(wrbuf_result));
4696         }
4697         cql_transform_close(trans);
4698         wrbuf_destroy(wrbuf_result);
4699     }
4700     cql_parser_destroy(parser);
4701     return result;
4702 }
4703
4704 ZOOM_API(int) ZOOM_connection_fire_event_timeout(ZOOM_connection c)
4705 {
4706     if (c->mask)
4707     {
4708         ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
4709         /* timeout and this connection was waiting */
4710         set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
4711         do_close(c);
4712         ZOOM_connection_put_event(c, event);
4713     }
4714     return 0;
4715 }
4716
4717 ZOOM_API(int)
4718     ZOOM_connection_process(ZOOM_connection c)
4719 {
4720     ZOOM_Event event;
4721     if (!c)
4722         return 0;
4723
4724     event = ZOOM_connection_get_event(c);
4725     if (event)
4726     {
4727         ZOOM_Event_destroy(event);
4728         return 1;
4729     }
4730     ZOOM_connection_exec_task(c);
4731     event = ZOOM_connection_get_event(c);
4732     if (event)
4733     {
4734         ZOOM_Event_destroy(event);
4735         return 1;
4736     }
4737     return 0;
4738 }
4739
4740 ZOOM_API(int)
4741     ZOOM_event_nonblock(int no, ZOOM_connection *cs)
4742 {
4743     int i;
4744
4745     yaz_log(log_details, "ZOOM_process_event(no=%d,cs=%p)", no, cs);
4746     
4747     for (i = 0; i<no; i++)
4748     {
4749         ZOOM_connection c = cs[i];
4750
4751         if (c && ZOOM_connection_process(c))
4752             return i+1;
4753     }
4754     return 0;
4755 }
4756
4757 ZOOM_API(int) ZOOM_connection_fire_event_socket(ZOOM_connection c, int mask)
4758 {
4759     if (c->mask && mask)
4760         ZOOM_connection_do_io(c, mask);
4761     return 0;
4762 }
4763
4764 ZOOM_API(int) ZOOM_connection_get_socket(ZOOM_connection c)
4765 {
4766     if (c->cs)
4767         return cs_fileno(c->cs);
4768     return -1;
4769 }
4770
4771 ZOOM_API(int) ZOOM_connection_set_mask(ZOOM_connection c, int mask)
4772 {
4773     c->mask = mask;
4774     if (!c->cs)
4775         return -1; 
4776     return 0;
4777 }
4778
4779 ZOOM_API(int) ZOOM_connection_get_mask(ZOOM_connection c)
4780 {
4781     if (c->cs)
4782         return c->mask;
4783     return 0;
4784 }
4785
4786 ZOOM_API(int) ZOOM_connection_get_timeout(ZOOM_connection c)
4787 {
4788     return ZOOM_options_get_int(c->options, "timeout", 30);
4789 }
4790
4791 ZOOM_API(void) ZOOM_connection_close(ZOOM_connection c)
4792 {
4793     do_close(c);
4794 }
4795
4796 /*
4797  * Local variables:
4798  * c-basic-offset: 4
4799  * c-file-style: "Stroustrup"
4800  * indent-tabs-mode: nil
4801  * End:
4802  * vim: shiftwidth=4 tabstop=8 expandtab
4803  */
4804