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