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