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