c579957484be7cb1f998d1056ce902d596e8f12e
[yaz-moved-to-github.git] / src / zoom-c.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file zoom-c.c
7  * \brief Implements ZOOM C interface.
8  */
9
10 #include <assert.h>
11 #include <string.h>
12 #include <errno.h>
13 #include "zoom-p.h"
14
15 #include <yaz/yaz-util.h>
16 #include <yaz/xmalloc.h>
17 #include <yaz/otherinfo.h>
18 #include <yaz/log.h>
19 #include <yaz/pquery.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/charneg.h>
23 #include <yaz/ill.h>
24 #include <yaz/srw.h>
25 #include <yaz/cql.h>
26 #include <yaz/ccl.h>
27 #include <yaz/query-charset.h>
28 #include <yaz/copy_types.h>
29 #include <yaz/snprintf.h>
30
31 static int log_api = 0;
32 static int log_details = 0;
33
34 typedef enum {
35     zoom_pending,
36     zoom_complete
37 } zoom_ret;
38
39 static void resultset_destroy(ZOOM_resultset r);
40 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c);
41 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out);
42 static char *cql2pqf(ZOOM_connection c, const char *cql);
43
44 ZOOM_API(const char *) ZOOM_get_event_str(int event)
45 {
46     static const char *ar[] = {
47         "NONE",
48         "CONNECT",
49         "SEND_DATA",
50         "RECV_DATA",
51         "TIMEOUT",
52         "UNKNOWN",
53         "SEND_APDU",
54         "RECV_APDU",
55         "RECV_RECORD",
56         "RECV_SEARCH",
57         "END"
58     };
59     return ar[event];
60 }
61
62 /*
63  * This wrapper is just for logging failed lookups.  It would be nicer
64  * if it could cause failure when a lookup fails, but that's hard.
65  */
66 static Odr_oid *zoom_yaz_str_to_z3950oid(ZOOM_connection c,
67                                      oid_class oid_class, const char *str) {
68     Odr_oid *res = yaz_string_to_oid_odr(yaz_oid_std(), oid_class, str,
69                                      c->odr_out);
70     if (res == 0)
71         yaz_log(YLOG_WARN, "%p OID lookup (%d, '%s') failed",
72                 c, (int) oid_class, str);
73     return res;
74 }
75
76
77 static void initlog(void)
78 {
79     static int log_level_initialized = 0;
80     if (!log_level_initialized)
81     {
82         log_api = yaz_log_module_level("zoom");
83         log_details = yaz_log_module_level("zoomdetails");
84         log_level_initialized = 1;
85     }
86 }
87
88 static ZOOM_Event ZOOM_Event_create(int kind)
89 {
90     ZOOM_Event event = (ZOOM_Event) xmalloc(sizeof(*event));
91     event->kind = kind;
92     event->next = 0;
93     event->prev = 0;
94     yaz_log(log_details, "ZOOM_Event_create(kind=%d)", kind);
95     return event;
96 }
97
98 static void ZOOM_Event_destroy(ZOOM_Event event)
99 {
100     xfree(event);
101 }
102
103 static void ZOOM_connection_put_event(ZOOM_connection c, ZOOM_Event event)
104 {
105     if (c->m_queue_back)
106     {
107         c->m_queue_back->prev = event;
108         assert(c->m_queue_front);
109     }
110     else
111     {
112         assert(!c->m_queue_front);
113         c->m_queue_front = event;
114     }
115     event->next = c->m_queue_back;
116     event->prev = 0;
117     c->m_queue_back = event;
118 }
119
120 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
121 {
122     ZOOM_Event event = c->m_queue_front;
123     if (!event)
124     {
125         c->last_event = ZOOM_EVENT_NONE;
126         return 0;
127     }
128     assert(c->m_queue_back);
129     c->m_queue_front = event->prev;
130     if (c->m_queue_front)
131     {
132         assert(c->m_queue_back);
133         c->m_queue_front->next = 0;
134     }
135     else
136         c->m_queue_back = 0;
137     c->last_event = event->kind;
138     return event;
139 }
140
141 static void ZOOM_connection_remove_events(ZOOM_connection c)
142 {
143     ZOOM_Event event;
144     while ((event = ZOOM_connection_get_event(c)))
145         ZOOM_Event_destroy(event);
146 }
147
148 ZOOM_API(int) ZOOM_connection_peek_event(ZOOM_connection c)
149 {
150     ZOOM_Event event = c->m_queue_front;
151
152     return event ? event->kind : ZOOM_EVENT_NONE;
153 }
154
155 void ZOOM_connection_remove_tasks(ZOOM_connection c);
156
157 static void set_dset_error(ZOOM_connection c, int error,
158                            const char *dset,
159                            const char *addinfo, const char *addinfo2)
160 {
161     char *cp;
162
163     xfree(c->addinfo);
164     c->addinfo = 0;
165     c->error = error;
166     if (!c->diagset || strcmp(dset, c->diagset))
167     {
168         xfree(c->diagset);
169         c->diagset = xstrdup(dset);
170         /* remove integer part from SRW diagset .. */
171         if ((cp = strrchr(c->diagset, '/')))
172             *cp = '\0';
173     }
174     if (addinfo && addinfo2)
175     {
176         c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
177         strcpy(c->addinfo, addinfo);
178         strcat(c->addinfo, addinfo2);
179     }
180     else if (addinfo)
181         c->addinfo = xstrdup(addinfo);
182     if (error != ZOOM_ERROR_NONE)
183     {
184         yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
185                 c, c->host_port ? c->host_port : "<>", dset, error,
186                 addinfo ? addinfo : "",
187                 addinfo2 ? addinfo2 : "");
188         ZOOM_connection_remove_tasks(c);
189     }
190 }
191
192 static int uri_to_code(const char *uri)
193 {
194     int code = 0;       
195     const char *cp;
196     if ((cp = strrchr(uri, '/')))
197         code = atoi(cp+1);
198     return code;
199 }
200
201 #if YAZ_HAVE_XML2
202 static void set_HTTP_error(ZOOM_connection c, int error,
203                            const char *addinfo, const char *addinfo2)
204 {
205     set_dset_error(c, error, "HTTP", addinfo, addinfo2);
206 }
207
208 static void set_SRU_error(ZOOM_connection c, Z_SRW_diagnostic *d)
209 {
210     const char *uri = d->uri;
211     if (uri)
212         set_dset_error(c, uri_to_code(uri), uri, d->details, 0);
213 }
214
215 #endif
216
217
218 static void set_ZOOM_error(ZOOM_connection c, int error,
219                            const char *addinfo)
220 {
221     set_dset_error(c, error, "ZOOM", addinfo, 0);
222 }
223
224 static void clear_error(ZOOM_connection c)
225 {
226     /*
227      * If an error is tied to an operation then it's ok to clear: for
228      * example, a diagnostic returned from a search is cleared by a
229      * subsequent search.  However, problems such as Connection Lost
230      * or Init Refused are not cleared, because they are not
231      * recoverable: doing another search doesn't help.
232      */
233
234     ZOOM_connection_remove_events(c);
235     switch (c->error)
236     {
237     case ZOOM_ERROR_CONNECT:
238     case ZOOM_ERROR_MEMORY:
239     case ZOOM_ERROR_DECODE:
240     case ZOOM_ERROR_CONNECTION_LOST:
241     case ZOOM_ERROR_INIT:
242     case ZOOM_ERROR_INTERNAL:
243     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
244         break;
245     default:
246         set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
247     }
248 }
249
250 void ZOOM_connection_show_task(ZOOM_task task)
251 {
252     switch(task->which)
253     {
254     case ZOOM_TASK_SEARCH:
255         yaz_log(YLOG_LOG, "search p=%p", task);
256         break;
257     case ZOOM_TASK_RETRIEVE:
258         yaz_log(YLOG_LOG, "retrieve p=%p", task);
259         break;
260     case ZOOM_TASK_CONNECT:
261         yaz_log(YLOG_LOG, "connect p=%p", task);
262         break;
263     case ZOOM_TASK_SCAN:
264         yaz_log(YLOG_LOG, "scan p=%p", task);
265         break;
266     }
267 }
268
269 void ZOOM_connection_show_tasks(ZOOM_connection c)
270 {
271     ZOOM_task task;
272     yaz_log(YLOG_LOG, "connection p=%p tasks", c);
273     for (task = c->tasks; task; task = task->next)
274         ZOOM_connection_show_task(task);
275 }
276
277 ZOOM_task ZOOM_connection_add_task(ZOOM_connection c, int which)
278 {
279     ZOOM_task *taskp = &c->tasks;
280     while (*taskp)
281         taskp = &(*taskp)->next;
282     *taskp = (ZOOM_task) xmalloc(sizeof(**taskp));
283     (*taskp)->running = 0;
284     (*taskp)->which = which;
285     (*taskp)->next = 0;
286     clear_error(c);
287     return *taskp;
288 }
289
290 ZOOM_API(int) ZOOM_connection_is_idle(ZOOM_connection c)
291 {
292     return c->tasks ? 0 : 1;
293 }
294
295 ZOOM_task ZOOM_connection_insert_task(ZOOM_connection c, int which)
296 {
297     ZOOM_task task = (ZOOM_task) xmalloc(sizeof(*task));
298
299     task->next = c->tasks;
300     c->tasks = task;
301
302     task->running = 0;
303     task->which = which;
304     clear_error(c);
305     return task;
306 }
307
308 void ZOOM_connection_remove_task(ZOOM_connection c)
309 {
310     ZOOM_task task = c->tasks;
311
312     if (task)
313     {
314         c->tasks = task->next;
315         switch (task->which)
316         {
317         case ZOOM_TASK_SEARCH:
318             resultset_destroy(task->u.search.resultset);
319             xfree(task->u.search.syntax);
320             xfree(task->u.search.elementSetName);
321             break;
322         case ZOOM_TASK_RETRIEVE:
323             resultset_destroy(task->u.retrieve.resultset);
324             xfree(task->u.retrieve.syntax);
325             xfree(task->u.retrieve.elementSetName);
326             break;
327         case ZOOM_TASK_CONNECT:
328             break;
329         case ZOOM_TASK_SCAN:
330             ZOOM_scanset_destroy(task->u.scan.scan);
331             break;
332         case ZOOM_TASK_PACKAGE:
333             ZOOM_package_destroy(task->u.package);
334             break;
335         case ZOOM_TASK_SORT:
336             resultset_destroy(task->u.sort.resultset);
337             ZOOM_query_destroy(task->u.sort.q);
338             break;
339         default:
340             assert(0);
341         }
342         xfree(task);
343
344         if (!c->tasks)
345         {
346             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
347             ZOOM_connection_put_event(c, event);
348         }
349     }
350 }
351
352 void ZOOM_connection_remove_tasks(ZOOM_connection c)
353 {
354     while (c->tasks)
355         ZOOM_connection_remove_task(c);
356 }
357
358 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
359                                        const char *syntax,
360                                        const char *elementSetName);
361
362 ZOOM_API(ZOOM_connection)
363     ZOOM_connection_create(ZOOM_options options)
364 {
365     ZOOM_connection c = (ZOOM_connection) xmalloc(sizeof(*c));
366
367     initlog();
368
369     yaz_log(log_api, "%p ZOOM_connection_create", c);
370
371     c->proto = PROTO_Z3950;
372     c->cs = 0;
373     ZOOM_connection_set_mask(c, 0);
374     c->reconnect_ok = 0;
375     c->state = STATE_IDLE;
376     c->addinfo = 0;
377     c->diagset = 0;
378     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
379     c->buf_in = 0;
380     c->len_in = 0;
381     c->buf_out = 0;
382     c->len_out = 0;
383     c->resultsets = 0;
384
385     c->options = ZOOM_options_create_with_parent(options);
386
387     c->host_port = 0;
388     c->path = 0;
389     c->proxy = 0;
390     
391     c->charset = c->lang = 0;
392
393     c->cookie_out = 0;
394     c->cookie_in = 0;
395     c->client_IP = 0;
396     c->tasks = 0;
397
398     c->user = 0;
399     c->group = 0;
400     c->password = 0;
401
402     c->maximum_record_size = 0;
403     c->preferred_message_size = 0;
404
405     c->odr_in = odr_createmem(ODR_DECODE);
406     c->odr_out = odr_createmem(ODR_ENCODE);
407     c->odr_print = 0;
408
409     c->async = 0;
410     c->support_named_resultsets = 0;
411     c->last_event = ZOOM_EVENT_NONE;
412
413     c->m_queue_front = 0;
414     c->m_queue_back = 0;
415
416     c->sru_version = 0;
417     return c;
418 }
419
420
421 /* set database names. Take local databases (if set); otherwise
422    take databases given in ZURL (if set); otherwise use Default */
423 static char **set_DatabaseNames(ZOOM_connection con, ZOOM_options options,
424                                 int *num, ODR odr)
425 {
426     char **databaseNames;
427     const char *cp = ZOOM_options_get(options, "databaseName");
428     
429     if ((!cp || !*cp) && con->host_port)
430     {
431         if (strncmp(con->host_port, "unix:", 5) == 0)
432             cp = strchr(con->host_port+5, ':');
433         else
434             cp = strchr(con->host_port, '/');
435         if (cp)
436             cp++;
437     }
438     if (!cp)
439         cp = "Default";
440     nmem_strsplit(odr_getmem(odr), "+", cp,  &databaseNames, num);
441     return databaseNames;
442 }
443
444 ZOOM_API(ZOOM_connection)
445     ZOOM_connection_new(const char *host, int portnum)
446 {
447     ZOOM_connection c = ZOOM_connection_create(0);
448
449     ZOOM_connection_connect(c, host, portnum);
450     return c;
451 }
452
453 static zoom_sru_mode get_sru_mode_from_string(const char *s)
454 {
455     if (!s || !*s)
456         return zoom_sru_soap;
457     if (!yaz_matchstr(s, "soap"))
458         return zoom_sru_soap;
459     else if (!yaz_matchstr(s, "get"))
460         return zoom_sru_get;
461     else if (!yaz_matchstr(s, "post"))
462         return zoom_sru_post;
463     return zoom_sru_error;
464 }
465
466 ZOOM_API(void)
467     ZOOM_connection_connect(ZOOM_connection c,
468                             const char *host, int portnum)
469 {
470     const char *val;
471     ZOOM_task task;
472
473     initlog();
474
475     yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
476             c, host ? host : "null", portnum);
477
478     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
479     ZOOM_connection_remove_tasks(c);
480
481     if (c->odr_print)
482     {
483         odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
484         odr_destroy(c->odr_print);
485     }
486     if (ZOOM_options_get_bool(c->options, "apdulog", 0))
487     {
488         c->odr_print = odr_createmem(ODR_PRINT);
489         odr_setprint(c->odr_print, yaz_log_file());
490     }
491     else
492         c->odr_print = 0;
493
494     if (c->cs)
495     {
496         yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
497         c->reconnect_ok = 1;
498         return;
499     }
500     yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
501     xfree(c->proxy);
502     c->proxy = 0;
503     val = ZOOM_options_get(c->options, "proxy");
504     if (val && *val)
505     {
506         yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
507         c->proxy = xstrdup(val);
508     }
509
510     xfree(c->charset);
511     c->charset = 0;
512     val = ZOOM_options_get(c->options, "charset");
513     if (val && *val)
514     {
515         yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
516         c->charset = xstrdup(val);
517     }
518
519     xfree(c->lang);
520     val = ZOOM_options_get(c->options, "lang");
521     if (val && *val)
522     {
523         yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
524         c->lang = xstrdup(val);
525     }
526     else
527         c->lang = 0;
528
529     if (host)
530     {
531         xfree(c->host_port);
532         if (portnum)
533         {
534             char hostn[128];
535             sprintf(hostn, "%.80s:%d", host, portnum);
536             c->host_port = xstrdup(hostn);
537         }
538         else
539             c->host_port = xstrdup(host);
540     }        
541
542     {
543         /*
544          * If the "<scheme>:" part of the host string is preceded by one
545          * or more comma-separated <name>=<value> pairs, these are taken
546          * to be options to be set on the connection object.  Among other
547          * applications, this facility can be used to embed authentication
548          * in a host string:
549          *          user=admin,password=secret,tcp:localhost:9999
550          */
551         char *remainder = c->host_port;
552         char *pcolon = strchr(remainder, ':');
553         char *pcomma;
554         char *pequals;
555         while ((pcomma = strchr(remainder, ',')) != 0 &&
556                (pcolon == 0 || pcomma < pcolon)) {
557             *pcomma = '\0';
558             if ((pequals = strchr(remainder, '=')) != 0) {
559                 *pequals = '\0';
560                 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
561                 ZOOM_connection_option_set(c, remainder, pequals+1);
562             }
563             remainder = pcomma+1;
564         }
565
566         if (remainder != c->host_port) {
567             xfree(c->host_port);
568             c->host_port = xstrdup(remainder);
569             /*printf("# reset hp='%s'\n", remainder);*/
570         }
571     }
572
573     val = ZOOM_options_get(c->options, "sru");
574     c->sru_mode = get_sru_mode_from_string(val);
575
576     xfree(c->sru_version);
577     val = ZOOM_options_get(c->options, "sru_version");
578     c->sru_version = xstrdup(val ? val : "1.2");
579
580     ZOOM_options_set(c->options, "host", c->host_port);
581
582     xfree(c->cookie_out);
583     c->cookie_out = 0;
584     val = ZOOM_options_get(c->options, "cookie");
585     if (val && *val)
586     { 
587         yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
588         c->cookie_out = xstrdup(val);
589     }
590
591     xfree(c->client_IP);
592     c->client_IP = 0;
593     val = ZOOM_options_get(c->options, "clientIP");
594     if (val && *val)
595     {
596         yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
597                 c, val);
598         c->client_IP = xstrdup(val);
599     }
600
601     xfree(c->group);
602     c->group = 0;
603     val = ZOOM_options_get(c->options, "group");
604     if (val && *val)
605         c->group = xstrdup(val);
606
607     xfree(c->user);
608     c->user = 0;
609     val = ZOOM_options_get(c->options, "user");
610     if (val && *val)
611         c->user = xstrdup(val);
612
613     xfree(c->password);
614     c->password = 0;
615     val = ZOOM_options_get(c->options, "password");
616     if (!val)
617         val = ZOOM_options_get(c->options, "pass");
618
619     if (val && *val)
620         c->password = xstrdup(val);
621     
622     c->maximum_record_size =
623         ZOOM_options_get_int(c->options, "maximumRecordSize", 1024*1024);
624     c->preferred_message_size =
625         ZOOM_options_get_int(c->options, "preferredMessageSize", 1024*1024);
626
627     c->async = ZOOM_options_get_bool(c->options, "async", 0);
628     yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
629  
630     task = ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
631
632     if (!c->async)
633     {
634         while (ZOOM_event(1, &c))
635             ;
636     }
637 }
638
639 ZOOM_API(ZOOM_query)
640     ZOOM_query_create(void)
641 {
642     ZOOM_query s = (ZOOM_query) xmalloc(sizeof(*s));
643
644     yaz_log(log_details, "%p ZOOM_query_create", s);
645     s->refcount = 1;
646     s->z_query = 0;
647     s->sort_spec = 0;
648     s->odr = odr_createmem(ODR_ENCODE);
649     s->query_string = 0;
650
651     return s;
652 }
653
654 ZOOM_API(void)
655     ZOOM_query_destroy(ZOOM_query s)
656 {
657     if (!s)
658         return;
659
660     (s->refcount)--;
661     yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
662     if (s->refcount == 0)
663     {
664         odr_destroy(s->odr);
665         xfree(s);
666     }
667 }
668
669 ZOOM_API(int)
670     ZOOM_query_prefix(ZOOM_query s, const char *str)
671 {
672     s->query_string = odr_strdup(s->odr, str);
673     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
674     s->z_query->which = Z_Query_type_1;
675     s->z_query->u.type_1 =  p_query_rpn(s->odr, str);
676     if (!s->z_query->u.type_1)
677     {
678         yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
679         s->z_query = 0;
680         return -1;
681     }
682     yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
683     return 0;
684 }
685
686 ZOOM_API(int)
687     ZOOM_query_cql(ZOOM_query s, const char *str)
688 {
689     Z_External *ext;
690
691     s->query_string = odr_strdup(s->odr, str);
692
693     ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
694     ext->direct_reference = odr_oiddup(s->odr, yaz_oid_userinfo_cql);
695     ext->indirect_reference = 0;
696     ext->descriptor = 0;
697     ext->which = Z_External_CQL;
698     ext->u.cql = s->query_string;
699     
700     s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
701     s->z_query->which = Z_Query_type_104;
702     s->z_query->u.type_104 =  ext;
703
704     yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
705
706     return 0;
707 }
708
709 /*
710  * Translate the CQL string client-side into RPN which is passed to
711  * the server.  This is useful for server's that don't themselves
712  * support CQL, for which ZOOM_query_cql() is useless.  `conn' is used
713  * only as a place to stash diagnostics if compilation fails; if this
714  * information is not needed, a null pointer may be used.
715  */
716 ZOOM_API(int)
717     ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
718 {
719     char *rpn;
720     int ret;
721     ZOOM_connection freeme = 0;
722
723     yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
724     if (conn == 0)
725         conn = freeme = ZOOM_connection_create(0);
726
727     rpn = cql2pqf(conn, str);
728     if (freeme != 0)
729         ZOOM_connection_destroy(freeme);
730     if (rpn == 0)
731         return -1;
732
733     ret = ZOOM_query_prefix(s, rpn);
734     xfree(rpn);
735     return ret;
736 }
737
738 /*
739  * Analogous in every way to ZOOM_query_cql2rpn(), except that there
740  * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
741  * to the server, as the YAZ GFS doesn't know how to handle this.
742  */
743 ZOOM_API(int)
744     ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, const char *config,
745                        int *ccl_error, const char **error_string,
746                        int *error_pos)
747 {
748     int ret;
749     struct ccl_rpn_node *rpn;
750     CCL_bibset bibset = ccl_qual_mk();
751
752     if (config)
753         ccl_qual_buf(bibset, config);
754
755     rpn = ccl_find_str(bibset, str, ccl_error, error_pos);
756     if (!rpn)
757     {
758         *error_string = ccl_err_msg(*ccl_error);
759         ret = -1;
760     }
761     else
762     {
763         WRBUF wr = wrbuf_alloc();
764         ccl_pquery(wr, rpn);
765         ccl_rpn_delete(rpn);
766         ret = ZOOM_query_prefix(s, wrbuf_cstr(wr));
767         wrbuf_destroy(wr);
768     }
769     ccl_qual_rm(&bibset);
770     return ret;
771 }
772
773 ZOOM_API(int)
774     ZOOM_query_sortby(ZOOM_query s, const char *criteria)
775 {
776     s->sort_spec = yaz_sort_spec(s->odr, criteria);
777     if (!s->sort_spec)
778     {
779         yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
780                 s, criteria);
781         return -1;
782     }
783     yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
784     return 0;
785 }
786
787 static zoom_ret do_write(ZOOM_connection c);
788
789 ZOOM_API(void)
790     ZOOM_connection_destroy(ZOOM_connection c)
791 {
792     ZOOM_resultset r;
793     if (!c)
794         return;
795     yaz_log(log_api, "%p ZOOM_connection_destroy", c);
796     if (c->cs)
797         cs_close(c->cs);
798     for (r = c->resultsets; r; r = r->next)
799         r->connection = 0;
800
801     xfree(c->buf_in);
802     xfree(c->addinfo);
803     xfree(c->diagset);
804     odr_destroy(c->odr_in);
805     odr_destroy(c->odr_out);
806     if (c->odr_print)
807     {
808         odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
809         odr_destroy(c->odr_print);
810     }
811     ZOOM_options_destroy(c->options);
812     ZOOM_connection_remove_tasks(c);
813     ZOOM_connection_remove_events(c);
814     xfree(c->host_port);
815     xfree(c->path);
816     xfree(c->proxy);
817     xfree(c->charset);
818     xfree(c->lang);
819     xfree(c->cookie_out);
820     xfree(c->cookie_in);
821     xfree(c->client_IP);
822     xfree(c->user);
823     xfree(c->group);
824     xfree(c->password);
825     xfree(c->sru_version);
826     xfree(c);
827 }
828
829 void ZOOM_resultset_addref(ZOOM_resultset r)
830 {
831     if (r)
832     {
833         (r->refcount)++;
834         yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
835                 r, r->refcount);
836     }
837 }
838
839 ZOOM_resultset ZOOM_resultset_create(void)
840 {
841     int i;
842     ZOOM_resultset r = (ZOOM_resultset) xmalloc(sizeof(*r));
843
844     initlog();
845
846     yaz_log(log_details, "%p ZOOM_resultset_create", r);
847     r->refcount = 1;
848     r->size = 0;
849     r->odr = odr_createmem(ODR_ENCODE);
850     r->piggyback = 1;
851     r->setname = 0;
852     r->schema = 0;
853     r->step = 0;
854     for (i = 0; i<RECORD_HASH_SIZE; i++)
855         r->record_hash[i] = 0;
856     r->r_sort_spec = 0;
857     r->query = 0;
858     r->connection = 0;
859     r->next = 0;
860     r->databaseNames = 0;
861     r->num_databaseNames = 0;
862     return r;
863 }
864
865 ZOOM_API(ZOOM_resultset)
866     ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
867 {
868     ZOOM_resultset r;
869     ZOOM_query s = ZOOM_query_create();
870
871     ZOOM_query_prefix(s, q);
872
873     r = ZOOM_connection_search(c, s);
874     ZOOM_query_destroy(s);
875     return r;
876 }
877
878 ZOOM_API(ZOOM_resultset)
879     ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
880 {
881     ZOOM_resultset r = ZOOM_resultset_create();
882     ZOOM_task task;
883     const char *cp;
884     int start, count;
885     const char *syntax, *elementSetName;
886
887     yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
888     r->r_sort_spec = q->sort_spec;
889     r->query = q;
890
891     r->options = ZOOM_options_create_with_parent(c->options);
892     
893     start = ZOOM_options_get_int(r->options, "start", 0);
894     count = ZOOM_options_get_int(r->options, "count", 0);
895     {
896         /* If "presentChunk" is defined use that; otherwise "step" */
897         const char *cp = ZOOM_options_get(r->options, "presentChunk");
898         r->step = ZOOM_options_get_int(r->options,
899                                        (cp != 0 ? "presentChunk": "step"), 0);
900     }
901     r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
902     cp = ZOOM_options_get(r->options, "setname");
903     if (cp)
904         r->setname = xstrdup(cp);
905     cp = ZOOM_options_get(r->options, "schema");
906     if (cp)
907         r->schema = xstrdup(cp);
908
909     r->databaseNames = set_DatabaseNames(c, c->options, &r->num_databaseNames,
910                                          r->odr);
911     
912     r->connection = c;
913
914     r->next = c->resultsets;
915     c->resultsets = r;
916
917     
918
919     if (c->host_port && c->proto == PROTO_HTTP)
920     {
921         if (!c->cs)
922         {
923             yaz_log(log_details, "ZOOM_connection_search: no comstack");
924             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
925         }
926         else
927         {
928             yaz_log(log_details, "ZOOM_connection_search: reconnect");
929             c->reconnect_ok = 1;
930         }
931     }
932
933     task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
934     task->u.search.resultset = r;
935     task->u.search.start = start;
936     task->u.search.count = count;
937     task->u.search.recv_search_fired = 0;
938
939     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
940     task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
941     elementSetName = ZOOM_options_get(r->options, "elementSetName");
942     task->u.search.elementSetName = elementSetName 
943         ? xstrdup(elementSetName) : 0;
944    
945     ZOOM_resultset_addref(r);
946
947     (q->refcount)++;
948
949     if (!c->async)
950     {
951         while (ZOOM_event(1, &c))
952             ;
953     }
954     return r;
955 }
956
957 ZOOM_API(void)
958     ZOOM_resultset_sort(ZOOM_resultset r,
959                          const char *sort_type, const char *sort_spec)
960 {
961     (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
962 }
963
964 ZOOM_API(int)
965     ZOOM_resultset_sort1(ZOOM_resultset r,
966                          const char *sort_type, const char *sort_spec)
967 {
968     ZOOM_connection c = r->connection;
969     ZOOM_task task;
970     ZOOM_query newq;
971
972     newq = ZOOM_query_create();
973     if (ZOOM_query_sortby(newq, sort_spec) < 0)
974         return -1;
975
976     yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
977             r, r, sort_type, sort_spec);
978     if (!c)
979         return 0;
980
981     if (c->host_port && c->proto == PROTO_HTTP)
982     {
983         if (!c->cs)
984         {
985             yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
986             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
987         }
988         else
989         {
990             yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
991                     r);
992             c->reconnect_ok = 1;
993         }
994     }
995     
996     ZOOM_resultset_cache_reset(r);
997     task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
998     task->u.sort.resultset = r;
999     task->u.sort.q = newq;
1000
1001     ZOOM_resultset_addref(r);  
1002
1003     if (!c->async)
1004     {
1005         while (ZOOM_event(1, &c))
1006             ;
1007     }
1008
1009     return 0;
1010 }
1011
1012 static void ZOOM_record_release(ZOOM_record rec)
1013 {
1014     if (!rec)
1015         return;
1016     if (rec->wrbuf)
1017         wrbuf_destroy(rec->wrbuf);
1018 #if YAZ_HAVE_XML2
1019     if (rec->xml_mem)
1020         xmlFree(rec->xml_mem);
1021 #endif
1022     if (rec->odr)
1023         odr_destroy(rec->odr);
1024 }
1025
1026 ZOOM_API(void)
1027     ZOOM_resultset_cache_reset(ZOOM_resultset r)
1028 {
1029     int i;
1030     for (i = 0; i<RECORD_HASH_SIZE; i++)
1031     {
1032         ZOOM_record_cache rc;
1033         for (rc = r->record_hash[i]; rc; rc = rc->next)
1034         {
1035             ZOOM_record_release(&rc->rec);
1036         }
1037         r->record_hash[i] = 0;
1038     }
1039 }
1040
1041 ZOOM_API(void)
1042     ZOOM_resultset_destroy(ZOOM_resultset r)
1043 {
1044     resultset_destroy(r);
1045 }
1046
1047 static void resultset_destroy(ZOOM_resultset r)
1048 {
1049     if (!r)
1050         return;
1051     (r->refcount)--;
1052     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
1053             r, r, r->refcount);
1054     if (r->refcount == 0)
1055     {
1056         ZOOM_resultset_cache_reset(r);
1057
1058         if (r->connection)
1059         {
1060             /* remove ourselves from the resultsets in connection */
1061             ZOOM_resultset *rp = &r->connection->resultsets;
1062             while (1)
1063             {
1064                 assert(*rp);   /* we must be in this list!! */
1065                 if (*rp == r)
1066                 {   /* OK, we're here - take us out of it */
1067                     *rp = (*rp)->next;
1068                     break;
1069                 }
1070                 rp = &(*rp)->next;
1071             }
1072         }
1073         ZOOM_query_destroy(r->query);
1074         ZOOM_options_destroy(r->options);
1075         odr_destroy(r->odr);
1076         xfree(r->setname);
1077         xfree(r->schema);
1078         xfree(r);
1079     }
1080 }
1081
1082 ZOOM_API(size_t)
1083     ZOOM_resultset_size(ZOOM_resultset r)
1084 {
1085     yaz_log(log_details, "ZOOM_resultset_size r=%p count=" ODR_INT_PRINTF,
1086             r, r->size);
1087     return r->size;
1088 }
1089
1090 static void do_close(ZOOM_connection c)
1091 {
1092     if (c->cs)
1093         cs_close(c->cs);
1094     c->cs = 0;
1095     ZOOM_connection_set_mask(c, 0);
1096     c->state = STATE_IDLE;
1097 }
1098
1099 static int ZOOM_test_reconnect(ZOOM_connection c)
1100 {
1101     ZOOM_Event event;
1102
1103     if (!c->reconnect_ok)
1104         return 0;
1105     do_close(c);
1106     c->reconnect_ok = 0;
1107     c->tasks->running = 0;
1108     ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
1109
1110     event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1111     ZOOM_connection_put_event(c, event);
1112
1113     return 1;
1114 }
1115
1116 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
1117                                     int force_sync, int start, int count)
1118 {
1119     ZOOM_task task;
1120     ZOOM_connection c;
1121     const char *cp;
1122     const char *syntax, *elementSetName;
1123
1124     if (!r)
1125         return;
1126     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1127             " count=%d", r, force_sync, start, count);
1128     c = r->connection;
1129     if (!c)
1130         return;
1131
1132     if (c->host_port && c->proto == PROTO_HTTP)
1133     {
1134         if (!c->cs)
1135         {
1136             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1137             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1138         }
1139         else
1140         {
1141             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1142                     "reconnect", r);
1143             c->reconnect_ok = 1;
1144         }
1145     }
1146     task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1147     task->u.retrieve.resultset = r;
1148     task->u.retrieve.start = start;
1149     task->u.retrieve.count = count;
1150
1151     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1152     task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1153     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1154     task->u.retrieve.elementSetName = elementSetName 
1155         ? xstrdup(elementSetName) : 0;
1156
1157     cp = ZOOM_options_get(r->options, "schema");
1158     if (cp)
1159     {
1160         if (!r->schema || strcmp(r->schema, cp))
1161         {
1162             xfree(r->schema);
1163             r->schema = xstrdup(cp);
1164         }
1165     }
1166
1167     ZOOM_resultset_addref(r);
1168
1169     if (!r->connection->async || force_sync)
1170         while (r->connection && ZOOM_event(1, &r->connection))
1171             ;
1172 }
1173
1174 ZOOM_API(void)
1175     ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1176                            size_t start, size_t count)
1177 {
1178     int force_present = 0;
1179
1180     if (!r)
1181         return ;
1182     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1183             r, r, (long) start, (long) count);
1184     if (count && recs)
1185         force_present = 1;
1186     ZOOM_resultset_retrieve(r, force_present, start, count);
1187     if (force_present)
1188     {
1189         size_t i;
1190         for (i = 0; i< count; i++)
1191             recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1192     }
1193 }
1194
1195 static void get_cert(ZOOM_connection c)
1196 {
1197     char *cert_buf;
1198     int cert_len;
1199     
1200     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1201     {
1202         ZOOM_connection_option_setl(c, "sslPeerCert",
1203                                     cert_buf, cert_len);
1204         xfree(cert_buf);
1205     }
1206 }
1207
1208 static zoom_ret do_connect(ZOOM_connection c)
1209 {
1210     void *add;
1211     const char *effective_host;
1212
1213     if (c->proxy)
1214         effective_host = c->proxy;
1215     else
1216         effective_host = c->host_port;
1217
1218     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1219
1220     if (c->cs)
1221         cs_close(c->cs);
1222     c->cs = cs_create_host(effective_host, 0, &add);
1223
1224     if (c->cs && c->cs->protocol == PROTO_HTTP)
1225     {
1226 #if YAZ_HAVE_XML2
1227         const char *db = 0;
1228
1229         c->proto = PROTO_HTTP;
1230         cs_get_host_args(c->host_port, &db);
1231         xfree(c->path);
1232
1233         c->path = xmalloc(strlen(db) * 3 + 2);
1234         yaz_encode_sru_dbpath_buf(c->path, db);
1235 #else
1236         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1237         do_close(c);
1238         return zoom_complete;
1239 #endif
1240     }
1241     if (c->cs)
1242     {
1243         int ret = cs_connect(c->cs, add);
1244         if (ret == 0)
1245         {
1246             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1247             ZOOM_connection_put_event(c, event);
1248             get_cert(c);
1249             if (c->proto == PROTO_Z3950)
1250                 ZOOM_connection_send_init(c);
1251             else
1252             {
1253                 /* no init request for SRW .. */
1254                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1255                 ZOOM_connection_remove_task(c);
1256                 ZOOM_connection_set_mask(c, 0);
1257                 ZOOM_connection_exec_task(c);
1258             }
1259             c->state = STATE_ESTABLISHED;
1260             return zoom_pending;
1261         }
1262         else if (ret > 0)
1263         {
1264             int mask = ZOOM_SELECT_EXCEPT;
1265             if (c->cs->io_pending & CS_WANT_WRITE)
1266                 mask += ZOOM_SELECT_WRITE;
1267             if (c->cs->io_pending & CS_WANT_READ)
1268                 mask += ZOOM_SELECT_READ;
1269             ZOOM_connection_set_mask(c, mask);
1270             c->state = STATE_CONNECTING; 
1271             return zoom_pending;
1272         }
1273     }
1274     c->state = STATE_IDLE;
1275     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
1276     return zoom_complete;
1277 }
1278
1279 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1280 {
1281     int i;
1282     for (i = 0; i<200; i++)
1283     {
1284         size_t len;
1285         Odr_oid *oid;
1286         Z_OtherInformation **oi;
1287         char buf[80];
1288         const char *val;
1289         const char *cp;
1290
1291         sprintf(buf, "otherInfo%d", i);
1292         val = ZOOM_options_get(c->options, buf);
1293         if (!val)
1294             break;
1295         cp = strchr(val, ':');
1296         if (!cp)
1297             continue;
1298         len = cp - val;
1299         if (len >= sizeof(buf))
1300             len = sizeof(buf)-1;
1301         memcpy(buf, val, len);
1302         buf[len] = '\0';
1303         
1304         oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
1305                                     buf, out);
1306         if (!oid)
1307             continue;
1308         
1309         yaz_oi_APDU(a, &oi);
1310         yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
1311     }
1312 }
1313
1314 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1315 {
1316     assert(a);
1317     if (c->cookie_out)
1318     {
1319         Z_OtherInformation **oi;
1320         yaz_oi_APDU(a, &oi);
1321         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie, 
1322                               1, c->cookie_out);
1323     }
1324     if (c->client_IP)
1325     {
1326         Z_OtherInformation **oi;
1327         yaz_oi_APDU(a, &oi);
1328         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip, 
1329                               1, c->client_IP);
1330     }
1331     otherInfo_attach(c, a, out);
1332     if (!z_APDU(out, &a, 0, 0))
1333     {
1334         FILE *outf = fopen("/tmp/apdu.txt", "a");
1335         if (a && outf)
1336         {
1337             ODR odr_pr = odr_createmem(ODR_PRINT);
1338             fprintf(outf, "a=%p\n", a);
1339             odr_setprint(odr_pr, outf);
1340             z_APDU(odr_pr, &a, 0, 0);
1341             odr_destroy(odr_pr);
1342         }
1343         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1344         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1345         odr_reset(out);
1346         return -1;
1347     }
1348     if (c->odr_print)
1349         z_APDU(c->odr_print, &a, 0, 0);
1350     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1351     return 0;
1352 }
1353
1354 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1355 {
1356     ZOOM_Event event;
1357     assert(a);
1358     if (encode_APDU(c, a, c->odr_out))
1359         return zoom_complete;
1360     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1361     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1362     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1363     ZOOM_connection_put_event(c, event);
1364     odr_reset(c->odr_out);
1365     return do_write(c);
1366 }
1367
1368 /* returns 1 if PDU was sent OK (still pending )
1369    0 if PDU was not sent OK (nothing to wait for) 
1370 */
1371
1372 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1373 {
1374     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1375     Z_InitRequest *ireq = apdu->u.initRequest;
1376     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1377         odr_malloc(c->odr_out, sizeof(*auth));
1378
1379     ODR_MASK_SET(ireq->options, Z_Options_search);
1380     ODR_MASK_SET(ireq->options, Z_Options_present);
1381     ODR_MASK_SET(ireq->options, Z_Options_scan);
1382     ODR_MASK_SET(ireq->options, Z_Options_sort);
1383     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1384     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1385     
1386     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1387     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1388     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1389     
1390     ireq->implementationId =
1391         odr_prepend(c->odr_out,
1392                     ZOOM_options_get(c->options, "implementationId"),
1393                     ireq->implementationId);
1394     
1395     ireq->implementationName = 
1396         odr_prepend(c->odr_out,
1397                     ZOOM_options_get(c->options, "implementationName"),
1398                     odr_prepend(c->odr_out, "ZOOM-C",
1399                                 ireq->implementationName));
1400     
1401     ireq->implementationVersion = 
1402         odr_prepend(c->odr_out,
1403                     ZOOM_options_get(c->options, "implementationVersion"),
1404                                 ireq->implementationVersion);
1405     
1406     *ireq->maximumRecordSize = c->maximum_record_size;
1407     *ireq->preferredMessageSize = c->preferred_message_size;
1408     
1409     if (c->group || c->password)
1410     {
1411         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1412         pass->groupId = odr_strdup_null(c->odr_out, c->group);
1413         pass->userId = odr_strdup_null(c->odr_out, c->user);
1414         pass->password = odr_strdup_null(c->odr_out, c->password);
1415         auth->which = Z_IdAuthentication_idPass;
1416         auth->u.idPass = pass;
1417         ireq->idAuthentication = auth;
1418     }
1419     else if (c->user)
1420     {
1421         auth->which = Z_IdAuthentication_open;
1422         auth->u.open = odr_strdup(c->odr_out, c->user);
1423         ireq->idAuthentication = auth;
1424     }
1425     if (c->proxy)
1426     {
1427         yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
1428                               yaz_oid_userinfo_proxy, 1, c->host_port);
1429     }
1430     if (c->charset || c->lang)
1431     {
1432         Z_OtherInformation **oi;
1433         Z_OtherInformationUnit *oi_unit;
1434         
1435         yaz_oi_APDU(apdu, &oi);
1436         
1437         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1438         {
1439             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1440             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1441             oi_unit->information.externallyDefinedInfo =
1442                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1443                                               c->charset, c->lang, 1);
1444         }
1445     }
1446     assert(apdu);
1447     return send_APDU(c, apdu);
1448 }
1449
1450 #if YAZ_HAVE_XML2
1451 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1452 {
1453     Z_GDU *gdu;
1454     ZOOM_Event event;
1455     const char *database =  ZOOM_options_get(c->options, "databaseName");
1456     char *fdatabase = 0;
1457     
1458     if (database)
1459         fdatabase = yaz_encode_sru_dbpath_odr(c->odr_out, database);
1460     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port,
1461                                        fdatabase ? fdatabase : c->path);
1462
1463     if (c->sru_mode == zoom_sru_get)
1464     {
1465         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1466     }
1467     else if (c->sru_mode == zoom_sru_post)
1468     {
1469         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1470     }
1471     else if (c->sru_mode == zoom_sru_soap)
1472     {
1473         yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1474     }
1475     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1476         return zoom_complete;
1477     if (c->odr_print)
1478         z_GDU(c->odr_print, &gdu, 0, 0);
1479     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1480         
1481     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1482     ZOOM_connection_put_event(c, event);
1483     odr_reset(c->odr_out);
1484     return do_write(c);
1485 }
1486 #endif
1487
1488 #if YAZ_HAVE_XML2
1489 static Z_SRW_PDU *ZOOM_srw_get_pdu(ZOOM_connection c, int type)
1490 {
1491     Z_SRW_PDU *sr = yaz_srw_get_pdu(c->odr_out, type, c->sru_version);
1492     sr->username = c->user;
1493     sr->password = c->password;
1494     return sr;
1495 }
1496 #endif
1497
1498 #if YAZ_HAVE_XML2
1499 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1500 {
1501     int i;
1502     int *start, *count;
1503     ZOOM_resultset resultset = 0;
1504     Z_SRW_PDU *sr = 0;
1505     const char *option_val = 0;
1506
1507     if (c->error)                  /* don't continue on error */
1508         return zoom_complete;
1509     assert(c->tasks);
1510     switch(c->tasks->which)
1511     {
1512     case ZOOM_TASK_SEARCH:
1513         resultset = c->tasks->u.search.resultset;
1514         if (!resultset->setname)
1515             resultset->setname = xstrdup("default");
1516         ZOOM_options_set(resultset->options, "setname", resultset->setname);
1517         start = &c->tasks->u.search.start;
1518         count = &c->tasks->u.search.count;
1519         break;
1520     case ZOOM_TASK_RETRIEVE:
1521         resultset = c->tasks->u.retrieve.resultset;
1522
1523         start = &c->tasks->u.retrieve.start;
1524         count = &c->tasks->u.retrieve.count;
1525
1526         if (*start >= resultset->size)
1527             return zoom_complete;
1528         if (*start + *count > resultset->size)
1529             *count = resultset->size - *start;
1530
1531         for (i = 0; i < *count; i++)
1532         {
1533             ZOOM_record rec =
1534                 record_cache_lookup(resultset, i + *start,
1535                                     c->tasks->u.retrieve.syntax,
1536                                     c->tasks->u.retrieve.elementSetName);
1537             if (!rec)
1538                 break;
1539             else
1540             {
1541                 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1542                 ZOOM_connection_put_event(c, event);
1543             }
1544         }
1545         *start += i;
1546         *count -= i;
1547
1548         if (*count == 0)
1549             return zoom_complete;
1550         break;
1551     default:
1552         return zoom_complete;
1553     }
1554     assert(resultset->query);
1555         
1556     sr = ZOOM_srw_get_pdu(c, Z_SRW_searchRetrieve_request);
1557     if (resultset->query->z_query->which == Z_Query_type_104
1558         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1559     {
1560         sr->u.request->query_type = Z_SRW_query_type_cql;
1561         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1562     }
1563     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1564              resultset->query->z_query->u.type_1)
1565     {
1566         sr->u.request->query_type = Z_SRW_query_type_pqf;
1567         sr->u.request->query.pqf = resultset->query->query_string;
1568     }
1569     else
1570     {
1571         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1572         return zoom_complete;
1573     }
1574     sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1575     sr->u.request->maximumRecords = odr_intdup(
1576         c->odr_out, (resultset->step > 0 && resultset->step < *count) ? 
1577         resultset->step : *count);
1578     sr->u.request->recordSchema = resultset->schema;
1579     
1580     option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1581     if (option_val)
1582         sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1583
1584     option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1585     yaz_encode_sru_extra(sr, c->odr_out, option_val);
1586     return send_srw(c, sr);
1587 }
1588 #else
1589 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1590 {
1591     return zoom_complete;
1592 }
1593 #endif
1594
1595 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1596 {
1597     ZOOM_resultset r;
1598     int lslb, ssub, mspn;
1599     const char *syntax;
1600     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1601     Z_SearchRequest *search_req = apdu->u.searchRequest;
1602     const char *elementSetName;
1603     const char *smallSetElementSetName;
1604     const char *mediumSetElementSetName;
1605
1606     assert(c->tasks);
1607     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1608
1609     r = c->tasks->u.search.resultset;
1610
1611     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1612
1613     elementSetName =
1614         ZOOM_options_get(r->options, "elementSetName");
1615     smallSetElementSetName  =
1616         ZOOM_options_get(r->options, "smallSetElementSetName");
1617     mediumSetElementSetName =
1618         ZOOM_options_get(r->options, "mediumSetElementSetName");
1619
1620     if (!smallSetElementSetName)
1621         smallSetElementSetName = elementSetName;
1622
1623     if (!mediumSetElementSetName)
1624         mediumSetElementSetName = elementSetName;
1625
1626     assert(r);
1627     assert(r->query);
1628
1629     /* prepare query for the search request */
1630     search_req->query = r->query->z_query;
1631     if (!search_req->query)
1632     {
1633         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1634         return zoom_complete;
1635     }
1636     if (r->query->z_query->which == Z_Query_type_1 || 
1637         r->query->z_query->which == Z_Query_type_101)
1638     {
1639         const char *cp = ZOOM_options_get(r->options, "rpnCharset");
1640         if (cp)
1641         {
1642             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
1643             if (cd)
1644             {
1645                 int r;
1646                 search_req->query = yaz_copy_Z_Query(search_req->query,
1647                                                      c->odr_out);
1648                 
1649                 r = yaz_query_charset_convert_rpnquery_check(
1650                     search_req->query->u.type_1,
1651                     c->odr_out, cd);
1652                 yaz_iconv_close(cd);
1653                 if (r)
1654                 {  /* query could not be char converted */
1655                     set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1656                     return zoom_complete;
1657                 }
1658             }
1659         }
1660     }
1661     search_req->databaseNames = r->databaseNames;
1662     search_req->num_databaseNames = r->num_databaseNames;
1663
1664     /* get syntax (no need to provide unless piggyback is in effect) */
1665     syntax = c->tasks->u.search.syntax;
1666
1667     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1668     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1669     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1670     if (lslb != -1 && ssub != -1 && mspn != -1)
1671     {
1672         /* So're a Z39.50 expert? Let's hope you don't do sort */
1673         *search_req->largeSetLowerBound = lslb;
1674         *search_req->smallSetUpperBound = ssub;
1675         *search_req->mediumSetPresentNumber = mspn;
1676     }
1677     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1678              && r->piggyback && !r->r_sort_spec && !r->schema)
1679     {
1680         /* Regular piggyback - do it unless we're going to do sort */
1681         *search_req->largeSetLowerBound = 2000000000;
1682         *search_req->smallSetUpperBound = 1;
1683         *search_req->mediumSetPresentNumber = 
1684             r->step>0 ? r->step : c->tasks->u.search.count;
1685     }
1686     else
1687     {
1688         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1689         smallSetElementSetName = 0;
1690         mediumSetElementSetName = 0;
1691         syntax = 0;
1692     }
1693     if (smallSetElementSetName && *smallSetElementSetName)
1694     {
1695         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1696             odr_malloc(c->odr_out, sizeof(*esn));
1697         
1698         esn->which = Z_ElementSetNames_generic;
1699         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1700         search_req->smallSetElementSetNames = esn;
1701     }
1702     if (mediumSetElementSetName && *mediumSetElementSetName)
1703     {
1704         Z_ElementSetNames *esn =(Z_ElementSetNames *)
1705             odr_malloc(c->odr_out, sizeof(*esn));
1706         
1707         esn->which = Z_ElementSetNames_generic;
1708         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1709         search_req->mediumSetElementSetNames = esn;
1710     }
1711     if (syntax)
1712         search_req->preferredRecordSyntax =
1713             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1714     
1715     if (!r->setname)
1716     {
1717         if (c->support_named_resultsets)
1718         {
1719             char setname[14];
1720             int ord;
1721             /* find the lowest unused ordinal so that we re-use
1722                result sets on the server. */
1723             for (ord = 1; ; ord++)
1724             {
1725                 ZOOM_resultset rp;
1726                 sprintf(setname, "%d", ord);
1727                 for (rp = c->resultsets; rp; rp = rp->next)
1728                     if (rp->setname && !strcmp(rp->setname, setname))
1729                         break;
1730                 if (!rp)
1731                     break;
1732             }
1733             r->setname = xstrdup(setname);
1734             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1735                     "set %s", c, r->setname);
1736         }
1737         else
1738         {
1739             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1740                     "default set", c);
1741             r->setname = xstrdup("default");
1742         }
1743         ZOOM_options_set(r->options, "setname", r->setname);
1744     }
1745     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1746     return send_APDU(c, apdu);
1747 }
1748
1749 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1750 {
1751     char oid_name_buf[OID_STR_MAX];
1752     const char *oid_name;
1753     char *addinfo = 0;
1754
1755     oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
1756     switch (r->which)
1757     {
1758     case Z_DefaultDiagFormat_v2Addinfo:
1759         addinfo = r->u.v2Addinfo;
1760         break;
1761     case Z_DefaultDiagFormat_v3Addinfo:
1762         addinfo = r->u.v3Addinfo;
1763         break;
1764     }
1765     xfree(c->addinfo);
1766     c->addinfo = 0;
1767     set_dset_error(c, *r->condition, oid_name, addinfo, 0);
1768 }
1769
1770 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1771 {
1772     if (p->which != Z_DiagRec_defaultFormat)
1773         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1774     else
1775         response_default_diag(c, p->u.defaultFormat);
1776 }
1777
1778 ZOOM_API(ZOOM_record)
1779     ZOOM_record_clone(ZOOM_record srec)
1780 {
1781     char *buf;
1782     int size;
1783     ODR odr_enc;
1784     ZOOM_record nrec;
1785
1786     odr_enc = odr_createmem(ODR_ENCODE);
1787     if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1788         return 0;
1789     buf = odr_getbuf(odr_enc, &size, 0);
1790     
1791     nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1792     nrec->odr = odr_createmem(ODR_DECODE);
1793     nrec->wrbuf = 0;
1794 #if YAZ_HAVE_XML2
1795     nrec->xml_mem = 0;
1796     nrec->xml_size = 0;
1797 #endif
1798     odr_setbuf(nrec->odr, buf, size, 0);
1799     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1800     
1801     nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1802     nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1803     nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1804     nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1805     nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1806     odr_destroy(odr_enc);
1807     return nrec;
1808 }
1809
1810 ZOOM_API(ZOOM_record)
1811     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1812 {
1813     const char *syntax =
1814         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1815     const char *elementSetName =
1816         ZOOM_options_get(s->options, "elementSetName");
1817
1818     return record_cache_lookup(s, pos, syntax, elementSetName);
1819 }
1820
1821 ZOOM_API(ZOOM_record)
1822     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1823 {
1824     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1825
1826     if (!rec)
1827     {
1828         /*
1829          * MIKE: I think force_sync should always be zero, but I don't
1830          * want to make this change until I get the go-ahead from
1831          * Adam, in case something depends on the old synchronous
1832          * behaviour.
1833          */
1834         int force_sync = 1;
1835         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1836         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1837         rec = ZOOM_resultset_record_immediate(r, pos);
1838     }
1839     return rec;
1840 }
1841
1842 ZOOM_API(void)
1843     ZOOM_record_destroy(ZOOM_record rec)
1844 {
1845     ZOOM_record_release(rec);
1846     xfree(rec);
1847 }
1848
1849
1850 static yaz_iconv_t iconv_create_charset(const char *record_charset)
1851 {
1852     char to[40];
1853     char from[40];
1854     yaz_iconv_t cd = 0;
1855
1856     *from = '\0';
1857     strcpy(to, "UTF-8");
1858     if (record_charset && *record_charset)
1859     {
1860         /* Use "from,to" or just "from" */
1861         const char *cp = strchr(record_charset, ',');
1862         size_t clen = strlen(record_charset);
1863         if (cp && cp[1])
1864         {
1865             strncpy( to, cp+1, sizeof(to)-1);
1866             to[sizeof(to)-1] = '\0';
1867             clen = cp - record_charset;
1868         }
1869         if (clen > sizeof(from)-1)
1870             clen = sizeof(from)-1;
1871         
1872         if (clen)
1873             strncpy(from, record_charset, clen);
1874         from[clen] = '\0';
1875     }
1876     if (*from && *to)
1877         cd = yaz_iconv_open(to, from);
1878     return cd;
1879 }
1880
1881 static const char *return_marc_record(ZOOM_record rec, int marc_type,
1882                                       int *len,
1883                                       const char *buf, int sz,
1884                                       const char *record_charset)
1885 {
1886     yaz_iconv_t cd = iconv_create_charset(record_charset);
1887     yaz_marc_t mt = yaz_marc_create();
1888     const char *ret_string = 0;
1889
1890     if (cd)
1891         yaz_marc_iconv(mt, cd);
1892     yaz_marc_xml(mt, marc_type);
1893     if (!rec->wrbuf)
1894         rec->wrbuf = wrbuf_alloc();
1895     wrbuf_rewind(rec->wrbuf);
1896     if (yaz_marc_decode_wrbuf(mt, buf, sz, rec->wrbuf) > 0)
1897     {
1898         if (len)
1899             *len = wrbuf_len(rec->wrbuf);
1900         ret_string = wrbuf_cstr(rec->wrbuf);
1901     }
1902     yaz_marc_destroy(mt);
1903     if (cd)
1904         yaz_iconv_close(cd);
1905     return ret_string;
1906 }
1907
1908 static const char *return_opac_record(ZOOM_record rec, int marc_type,
1909                                       int *len,
1910                                       Z_OPACRecord *opac_rec,
1911                                       const char *record_charset)
1912 {
1913     yaz_iconv_t cd = iconv_create_charset(record_charset);
1914     yaz_marc_t mt = yaz_marc_create();
1915
1916     if (cd)
1917         yaz_marc_iconv(mt, cd);
1918     yaz_marc_xml(mt, marc_type);
1919
1920     if (!rec->wrbuf)
1921         rec->wrbuf = wrbuf_alloc();
1922     wrbuf_rewind(rec->wrbuf);
1923
1924     yaz_opac_decode_wrbuf(mt, opac_rec, rec->wrbuf);
1925     yaz_marc_destroy(mt);
1926
1927     if (cd)
1928         yaz_iconv_close(cd);
1929     if (len)
1930         *len = wrbuf_len(rec->wrbuf);
1931     return wrbuf_cstr(rec->wrbuf);
1932 }
1933
1934 static const char *return_string_record(ZOOM_record rec, int *len,
1935                                         const char *buf, int sz,
1936                                         const char *record_charset)
1937 {
1938     yaz_iconv_t cd = iconv_create_charset(record_charset);
1939
1940     if (cd)
1941     {
1942         if (!rec->wrbuf)
1943             rec->wrbuf = wrbuf_alloc();
1944
1945         wrbuf_rewind(rec->wrbuf);
1946
1947         wrbuf_iconv_write(rec->wrbuf, cd, buf, sz);
1948         wrbuf_iconv_reset(rec->wrbuf, cd);
1949
1950         buf = wrbuf_cstr(rec->wrbuf);
1951         sz = wrbuf_len(rec->wrbuf);
1952         yaz_iconv_close(cd);
1953     }
1954     if (len)
1955         *len = sz;
1956     return buf;
1957 }
1958
1959 static const char *return_record(ZOOM_record rec, int *len,
1960                                  Z_NamePlusRecord *npr,
1961                                  int marctype, const char *charset)
1962 {
1963     Z_External *r = (Z_External *) npr->u.databaseRecord;
1964     const Odr_oid *oid = r->direct_reference;
1965     
1966     /* render bibliographic record .. */
1967     if (r->which == Z_External_OPAC)
1968     {
1969         return return_opac_record(rec, marctype, len,
1970                                   r->u.opac, charset);
1971     }
1972     if (r->which == Z_External_sutrs)
1973         return return_string_record(rec, len,
1974                                     (char*) r->u.sutrs->buf,
1975                                     r->u.sutrs->len,
1976                                     charset);
1977     else if (r->which == Z_External_octet)
1978     {
1979         if (yaz_oid_is_iso2709(oid))
1980         {
1981             const char *ret_buf = return_marc_record(
1982                 rec, marctype, len,
1983                 (const char *) r->u.octet_aligned->buf,
1984                 r->u.octet_aligned->len,
1985                 charset);
1986             if (ret_buf)
1987                 return ret_buf;
1988             /* bad ISO2709. Return fail unless raw (ISO2709) is wanted */
1989             if (marctype != YAZ_MARC_ISO2709)
1990                 return 0;
1991         }
1992         return return_string_record(rec, len,
1993                                     (const char *) r->u.octet_aligned->buf,
1994                                     r->u.octet_aligned->len,
1995                                     charset);
1996     }
1997     else if (r->which == Z_External_grs1)
1998     {
1999         if (!rec->wrbuf)
2000             rec->wrbuf = wrbuf_alloc();
2001         wrbuf_rewind(rec->wrbuf);
2002         yaz_display_grs1(rec->wrbuf, r->u.grs1, 0);
2003         return return_string_record(rec, len,
2004                                     wrbuf_buf(rec->wrbuf),
2005                                     wrbuf_len(rec->wrbuf),
2006                                     charset);
2007     }
2008     return 0;
2009 }
2010     
2011
2012 ZOOM_API(int)
2013     ZOOM_record_error(ZOOM_record rec, const char **cp,
2014                       const char **addinfo, const char **diagset)
2015 {
2016     Z_NamePlusRecord *npr;
2017     
2018     if (!rec)
2019         return 0;
2020
2021     npr = rec->npr;
2022     if (rec->diag_uri)
2023     {
2024         if (cp)
2025             *cp = rec->diag_message;
2026         if (addinfo)
2027             *addinfo = rec->diag_details;
2028         if (diagset)
2029             *diagset = rec->diag_set;
2030         return uri_to_code(rec->diag_uri);
2031     }
2032     if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
2033     {
2034         Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
2035         int error = YAZ_BIB1_UNSPECIFIED_ERROR;
2036         const char *add = 0;
2037
2038         if (diag_rec->which == Z_DiagRec_defaultFormat)
2039         {
2040             Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
2041             oid_class oclass;
2042     
2043             error = *ddf->condition;
2044             switch (ddf->which)
2045             {
2046             case Z_DefaultDiagFormat_v2Addinfo:
2047                 add = ddf->u.v2Addinfo;
2048                 break;
2049             case Z_DefaultDiagFormat_v3Addinfo:
2050                 add = ddf->u.v3Addinfo;
2051                 break;
2052             }
2053             if (diagset)
2054                 *diagset =
2055                     yaz_oid_to_string(yaz_oid_std(),
2056                                       ddf->diagnosticSetId, &oclass);
2057         }
2058         else
2059         {
2060             if (diagset)
2061                 *diagset = "Bib-1";
2062         }
2063         if (addinfo)
2064             *addinfo = add ? add : "";
2065         if (cp)
2066             *cp = diagbib1_str(error);
2067         return error;
2068     }
2069     return 0;
2070 }
2071
2072 static const char *get_record_format(ZOOM_record rec, int *len,
2073                                      Z_NamePlusRecord *npr,
2074                                      int marctype, const char *charset,
2075                                      const char *format)
2076 {
2077     const char *res = return_record(rec, len, npr, marctype, charset);
2078 #if YAZ_HAVE_XML2
2079     if (*format == '1' && len)
2080     {
2081         /* try to XML format res */
2082         xmlDocPtr doc;
2083         xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
2084         doc = xmlParseMemory(res, *len);
2085         if (doc)
2086         {
2087             if (rec->xml_mem)
2088                 xmlFree(rec->xml_mem);
2089             xmlDocDumpFormatMemory(doc, &rec->xml_mem, &rec->xml_size, 1);
2090             xmlFreeDoc(doc);
2091             res = (char *) rec->xml_mem;
2092             *len = rec->xml_size;
2093         } 
2094     }
2095 #endif
2096     return res;
2097 }
2098
2099
2100 ZOOM_API(const char *)
2101     ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2102 {
2103     char type[40];
2104     char charset[40];
2105     char format[3];
2106     const char *cp;
2107     size_t i;
2108     Z_NamePlusRecord *npr;
2109     
2110     if (len)
2111         *len = 0; /* default return */
2112         
2113     if (!rec)
2114         return 0;
2115     npr = rec->npr;
2116     if (!npr)
2117         return 0;
2118
2119     cp = type_spec;
2120     for (i = 0; cp[i] && cp[i] != ';' && cp[i] != ' ' && i < sizeof(type)-1;
2121          i++)
2122         type[i] = cp[i];
2123     type[i] = '\0';
2124     charset[0] = '\0';
2125     format[0] = '\0';
2126     while (1)
2127     {
2128         while (cp[i] == ' ')
2129             i++;
2130         if (cp[i] != ';')
2131             break;
2132         i++;
2133         while (cp[i] == ' ')
2134             i++;
2135         if (!strncmp(cp + i, "charset=", 8))
2136         {
2137             size_t j = 0;
2138             i = i + 8; /* skip charset= */
2139             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2140             {
2141                 if (j < sizeof(charset)-1)
2142                     charset[j++] = cp[i];
2143             }
2144             charset[j] = '\0';
2145         }
2146         else if (!strncmp(cp + i, "format=", 7))
2147         {
2148             size_t j = 0; 
2149             i = i + 7;
2150             for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2151             {
2152                 if (j < sizeof(format)-1)
2153                     format[j++] = cp[i];
2154             }
2155             format[j] = '\0';
2156         } 
2157     }
2158     if (!strcmp(type, "database"))
2159     {
2160         if (len)
2161             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2162         return npr->databaseName;
2163     }
2164     else if (!strcmp(type, "schema"))
2165     {
2166         if (len)
2167             *len = rec->schema ? strlen(rec->schema) : 0;
2168         return rec->schema;
2169     }
2170     else if (!strcmp(type, "syntax"))
2171     {
2172         const char *desc = 0;   
2173         if (npr->which == Z_NamePlusRecord_databaseRecord)
2174         {
2175             Z_External *r = (Z_External *) npr->u.databaseRecord;
2176             desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2177         }
2178         if (!desc)
2179             desc = "none";
2180         if (len)
2181             *len = strlen(desc);
2182         return desc;
2183     }
2184     if (npr->which != Z_NamePlusRecord_databaseRecord)
2185         return 0;
2186
2187     /* from now on - we have a database record .. */
2188     if (!strcmp(type, "render"))
2189     {
2190         return get_record_format(rec, len, npr, YAZ_MARC_LINE, charset, format);
2191     }
2192     else if (!strcmp(type, "xml"))
2193     {
2194         return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2195                                  format);
2196     }
2197     else if (!strcmp(type, "txml"))
2198     {
2199         return get_record_format(rec, len, npr, YAZ_MARC_TURBOMARC, charset,
2200                                  format);
2201     }
2202     else if (!strcmp(type, "raw"))
2203     {
2204         return get_record_format(rec, len, npr, YAZ_MARC_ISO2709, charset,
2205             format);
2206     }
2207     else if (!strcmp(type, "ext"))
2208     {
2209         if (len) *len = -1;
2210         return (const char *) npr->u.databaseRecord;
2211     }
2212     else if (!strcmp(type, "opac"))
2213     {
2214         if (npr->u.databaseRecord->which == Z_External_OPAC)
2215             return get_record_format(rec, len, npr, YAZ_MARC_MARCXML, charset,
2216                 format);
2217     }
2218     return 0;
2219 }
2220
2221 static int strcmp_null(const char *v1, const char *v2)
2222 {
2223     if (!v1 && !v2)
2224         return 0;
2225     if (!v1 || !v2)
2226         return -1;
2227     return strcmp(v1, v2);
2228 }
2229
2230 static size_t record_hash(int pos)
2231 {
2232     if (pos < 0)
2233         pos = 0;
2234     return pos % RECORD_HASH_SIZE;
2235 }
2236
2237 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr, 
2238                              int pos,
2239                              const char *syntax, const char *elementSetName,
2240                              const char *schema,
2241                              Z_SRW_diagnostic *diag)
2242 {
2243     ZOOM_record_cache rc = 0;
2244     
2245     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2246     ZOOM_connection_put_event(r->connection, event);
2247
2248     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2249     {
2250         if (pos == rc->pos 
2251             && strcmp_null(r->schema, rc->schema) == 0
2252             && strcmp_null(elementSetName,rc->elementSetName) == 0
2253             && strcmp_null(syntax, rc->syntax) == 0)
2254             break;
2255     }
2256     if (!rc)
2257     {
2258         rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2259         rc->rec.odr = 0;
2260         rc->rec.wrbuf = 0;
2261 #if YAZ_HAVE_XML2
2262         rc->rec.xml_mem = 0;
2263 #endif
2264         rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2265         
2266         rc->syntax = odr_strdup_null(r->odr, syntax);
2267         
2268         rc->schema = odr_strdup_null(r->odr, r->schema);
2269
2270         rc->pos = pos;
2271         rc->next = r->record_hash[record_hash(pos)];
2272         r->record_hash[record_hash(pos)] = rc;
2273     }
2274     rc->rec.npr = npr;
2275     rc->rec.schema = odr_strdup_null(r->odr, schema);
2276     rc->rec.diag_set = 0;
2277     rc->rec.diag_uri = 0;
2278     rc->rec.diag_message = 0;
2279     rc->rec.diag_details = 0;
2280     if (diag)
2281     {
2282         if (diag->uri)
2283         {
2284             char *cp;
2285             rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2286             if ((cp = strrchr(rc->rec.diag_set, '/')))
2287                 *cp = '\0';
2288             rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2289         }
2290         rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);            
2291         rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2292     }
2293 }
2294
2295 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2296                                        const char *syntax,
2297                                        const char *elementSetName)
2298 {
2299     ZOOM_record_cache rc;
2300     
2301     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2302     {
2303         if (pos == rc->pos)
2304         {
2305             if (strcmp_null(r->schema, rc->schema))
2306                 continue;
2307             if (strcmp_null(elementSetName,rc->elementSetName))
2308                 continue;
2309             if (strcmp_null(syntax, rc->syntax))
2310                 continue;
2311             return &rc->rec;
2312         }
2313     }
2314     return 0;
2315 }
2316                                              
2317 static void handle_records(ZOOM_connection c, Z_Records *sr,
2318                            int present_phase)
2319 {
2320     ZOOM_resultset resultset;
2321     int *start, *count;
2322     const char *syntax = 0, *elementSetName = 0;
2323
2324     if (!c->tasks)
2325         return ;
2326     switch (c->tasks->which)
2327     {
2328     case ZOOM_TASK_SEARCH:
2329         resultset = c->tasks->u.search.resultset;
2330         start = &c->tasks->u.search.start;
2331         count = &c->tasks->u.search.count;
2332         syntax = c->tasks->u.search.syntax;
2333         elementSetName = c->tasks->u.search.elementSetName;
2334         break;
2335     case ZOOM_TASK_RETRIEVE:
2336         resultset = c->tasks->u.retrieve.resultset;        
2337         start = &c->tasks->u.retrieve.start;
2338         count = &c->tasks->u.retrieve.count;
2339         syntax = c->tasks->u.retrieve.syntax;
2340         elementSetName = c->tasks->u.retrieve.elementSetName;
2341         break;
2342     default:
2343         return;
2344     }
2345     if (sr && sr->which == Z_Records_NSD)
2346         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2347     else if (sr && sr->which == Z_Records_multipleNSD)
2348     {
2349         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2350             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2351         else
2352             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2353     }
2354     else 
2355     {
2356         if (*count + *start > resultset->size)
2357             *count = resultset->size - *start;
2358         if (*count < 0)
2359             *count = 0;
2360         if (sr && sr->which == Z_Records_DBOSD)
2361         {
2362             int i;
2363             NMEM nmem = odr_extract_mem(c->odr_in);
2364             Z_NamePlusRecordList *p =
2365                 sr->u.databaseOrSurDiagnostics;
2366             for (i = 0; i<p->num_records; i++)
2367             {
2368                 record_cache_add(resultset, p->records[i], i + *start,
2369                                  syntax, elementSetName,
2370                                  elementSetName, 0);
2371             }
2372             *count -= i;
2373             if (*count < 0)
2374                 *count = 0;
2375             *start += i;
2376             yaz_log(log_details, 
2377                     "handle_records resultset=%p start=%d count=%d",
2378                     resultset, *start, *count);
2379
2380             /* transfer our response to search_nmem .. we need it later */
2381             nmem_transfer(odr_getmem(resultset->odr), nmem);
2382             nmem_destroy(nmem);
2383             if (present_phase && p->num_records == 0)
2384             {
2385                 /* present response and we didn't get any records! */
2386                 Z_NamePlusRecord *myrec = 
2387                     zget_surrogateDiagRec(
2388                         resultset->odr, 0, 
2389                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2390                         "ZOOM C generated. Present phase and no records");
2391                 record_cache_add(resultset, myrec, *start,
2392                                  syntax, elementSetName, 0, 0);
2393             }
2394         }
2395         else if (present_phase)
2396         {
2397             /* present response and we didn't get any records! */
2398             Z_NamePlusRecord *myrec = 
2399                 zget_surrogateDiagRec(
2400                     resultset->odr, 0,
2401                     YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2402                     "ZOOM C generated: Present response and no records");
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                                 size_t *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)
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                       size_t *occ, size_t *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                               size_t *occ, size_t *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             odr_intdup(p->odr_out, 0);
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 ZOOM_API(int)
3614     ZOOM_connection_exec_task(ZOOM_connection c)
3615 {
3616     ZOOM_task task = c->tasks;
3617     zoom_ret ret = zoom_complete;
3618
3619     if (!task)
3620         return 0;
3621     yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3622             c, task->which, task->running);
3623     if (c->error != ZOOM_ERROR_NONE)
3624     {
3625         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3626                 "removing tasks because of error = %d", c, c->error);
3627         ZOOM_connection_remove_tasks(c);
3628         return 0;
3629     }
3630     if (task->running)
3631     {
3632         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3633                 "task already running", c);
3634         return 0;
3635     }
3636     task->running = 1;
3637     ret = zoom_complete;
3638     if (c->cs || task->which == ZOOM_TASK_CONNECT)
3639     {
3640         switch (task->which)
3641         {
3642         case ZOOM_TASK_SEARCH:
3643             if (c->proto == PROTO_HTTP)
3644                 ret = ZOOM_connection_srw_send_search(c);
3645             else
3646                 ret = ZOOM_connection_send_search(c);
3647             break;
3648         case ZOOM_TASK_RETRIEVE:
3649             if (c->proto == PROTO_HTTP)
3650                 ret = ZOOM_connection_srw_send_search(c);
3651             else
3652                 ret = send_present(c);
3653             break;
3654         case ZOOM_TASK_CONNECT:
3655             ret = do_connect(c);
3656             break;
3657         case ZOOM_TASK_SCAN:
3658             if (c->proto == PROTO_HTTP)
3659                 ret = ZOOM_connection_srw_send_scan(c);
3660             else
3661                 ret = ZOOM_connection_send_scan(c);
3662             break;
3663         case ZOOM_TASK_PACKAGE:
3664             ret = send_package(c);
3665             break;
3666         case ZOOM_TASK_SORT:
3667             c->tasks->u.sort.resultset->r_sort_spec = 
3668                 c->tasks->u.sort.q->sort_spec;
3669             ret = send_sort(c, c->tasks->u.sort.resultset);
3670             break;
3671         }
3672     }
3673     else
3674     {
3675         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3676                 "remove tasks because no connection exist", c);
3677         ZOOM_connection_remove_tasks(c);
3678     }
3679     if (ret == zoom_complete)
3680     {
3681         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3682                 "task removed (complete)", c);
3683         ZOOM_connection_remove_task(c);
3684         return 0;
3685     }
3686     yaz_log(log_details, "%p ZOOM_connection_exec_task "
3687             "task pending", c);
3688     return 1;
3689 }
3690
3691 static zoom_ret send_sort_present(ZOOM_connection c)
3692 {
3693     zoom_ret r = zoom_complete;
3694
3695     if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3696         r = send_sort(c, c->tasks->u.search.resultset);
3697     if (r == zoom_complete)
3698         r = send_present(c);
3699     return r;
3700 }
3701
3702 static int es_response_taskpackage_update(ZOOM_connection c,
3703                 Z_IUUpdateTaskPackage *utp)
3704 {
3705         if (utp && utp->targetPart)
3706         {
3707                 Z_IUTargetPart *targetPart = utp->targetPart;
3708                 switch ( *targetPart->updateStatus ) {
3709                         case Z_IUTargetPart_success:
3710                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "success");
3711                                 break;
3712                         case Z_IUTargetPart_partial:
3713                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "partial");
3714                                 break;
3715                         case Z_IUTargetPart_failure:
3716                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "failure");
3717                                 if (targetPart->globalDiagnostics && targetPart->num_globalDiagnostics > 0)
3718                                         response_diag(c, targetPart->globalDiagnostics[0]);
3719                                 break;
3720                 }
3721                 // NOTE: Individual record status, surrogate diagnostics, and supplemental diagnostics ARE NOT REPORTED.
3722         }
3723     return 1;
3724 }
3725
3726 static int es_response_taskpackage(ZOOM_connection c,
3727                                    Z_TaskPackage *taskPackage)
3728 {
3729         // targetReference
3730         Odr_oct *id = taskPackage->targetReference;
3731         if (id)
3732                 ZOOM_options_setl(c->tasks->u.package->options,
3733                                                         "targetReference", (char*) id->buf, id->len);
3734         
3735         // taskStatus
3736         switch ( *taskPackage->taskStatus ) {
3737                 case Z_TaskPackage_pending:
3738                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "pending");
3739                         break;
3740                 case Z_TaskPackage_active:
3741                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "active");
3742                         break;
3743                 case Z_TaskPackage_complete:
3744                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "complete");
3745                         break;
3746                 case Z_TaskPackage_aborted:
3747                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "aborted");
3748                         if ( taskPackage->num_packageDiagnostics && taskPackage->packageDiagnostics )
3749                                 response_diag(c, taskPackage->packageDiagnostics[0]);
3750                         break;
3751         }
3752         
3753         // taskSpecificParameters
3754         // NOTE: Only Update implemented, no others.
3755         if ( taskPackage->taskSpecificParameters->which == Z_External_update ) {
3756                         Z_IUUpdateTaskPackage *utp = taskPackage->taskSpecificParameters->u.update->u.taskPackage;
3757                         es_response_taskpackage_update(c, utp);
3758         }
3759         return 1;
3760 }
3761
3762
3763 static int es_response(ZOOM_connection c,
3764                        Z_ExtendedServicesResponse *res)
3765 {
3766     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3767         return 0;
3768     switch (*res->operationStatus) {
3769         case Z_ExtendedServicesResponse_done:
3770             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "done");
3771             break;
3772         case Z_ExtendedServicesResponse_accepted:
3773             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "accepted");
3774             break;
3775         case Z_ExtendedServicesResponse_failure:
3776             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "failure");
3777             if (res->diagnostics && res->num_diagnostics > 0)
3778                 response_diag(c, res->diagnostics[0]);
3779             break;
3780     }
3781     if (res->taskPackage &&
3782         res->taskPackage->which == Z_External_extendedService)
3783     {
3784         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
3785         es_response_taskpackage(c, taskPackage);
3786     }
3787     if (res->taskPackage && 
3788         res->taskPackage->which == Z_External_octet)
3789     {
3790         Odr_oct *doc = res->taskPackage->u.octet_aligned;
3791         ZOOM_options_setl(c->tasks->u.package->options,
3792                           "xmlUpdateDoc", (char*) doc->buf, doc->len);
3793     }
3794     return 1;
3795 }
3796
3797 static void interpret_init_diag(ZOOM_connection c,
3798                                 Z_DiagnosticFormat *diag)
3799 {
3800     if (diag->num > 0)
3801     {
3802         Z_DiagnosticFormat_s *ds = diag->elements[0];
3803         if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
3804             response_default_diag(c, ds->u.defaultDiagRec);
3805     }
3806 }
3807
3808
3809 static void interpret_otherinformation_field(ZOOM_connection c,
3810                                              Z_OtherInformation *ui)
3811 {
3812     int i;
3813     for (i = 0; i < ui->num_elements; i++)
3814     {
3815         Z_OtherInformationUnit *unit = ui->list[i];
3816         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
3817             unit->information.externallyDefinedInfo &&
3818             unit->information.externallyDefinedInfo->which ==
3819             Z_External_diag1) 
3820         {
3821             interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
3822         } 
3823     }
3824 }
3825
3826
3827 static void set_init_option(const char *name, void *clientData) {
3828     ZOOM_connection c = (ZOOM_connection) clientData;
3829     char buf[80];
3830
3831     sprintf(buf, "init_opt_%.70s", name);
3832     ZOOM_connection_option_set(c, buf, "1");
3833 }
3834
3835
3836 static void recv_apdu(ZOOM_connection c, Z_APDU *apdu)
3837 {
3838     Z_InitResponse *initrs;
3839     
3840     ZOOM_connection_set_mask(c, 0);
3841     yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
3842     switch(apdu->which)
3843     {
3844     case Z_APDU_initResponse:
3845         yaz_log(log_api, "%p recv_apdu: Received Init response", c);
3846         initrs = apdu->u.initResponse;
3847         ZOOM_connection_option_set(c, "serverImplementationId",
3848                                    initrs->implementationId ?
3849                                    initrs->implementationId : "");
3850         ZOOM_connection_option_set(c, "serverImplementationName",
3851                                    initrs->implementationName ?
3852                                    initrs->implementationName : "");
3853         ZOOM_connection_option_set(c, "serverImplementationVersion",
3854                                    initrs->implementationVersion ?
3855                                    initrs->implementationVersion : "");
3856         /* Set the three old options too, for old applications */
3857         ZOOM_connection_option_set(c, "targetImplementationId",
3858                                    initrs->implementationId ?
3859                                    initrs->implementationId : "");
3860         ZOOM_connection_option_set(c, "targetImplementationName",
3861                                    initrs->implementationName ?
3862                                    initrs->implementationName : "");
3863         ZOOM_connection_option_set(c, "targetImplementationVersion",
3864                                    initrs->implementationVersion ?
3865                                    initrs->implementationVersion : "");
3866
3867         /* Make initrs->options available as ZOOM-level options */
3868         yaz_init_opt_decode(initrs->options, set_init_option, (void*) c);
3869
3870         if (!*initrs->result)
3871         {
3872             Z_External *uif = initrs->userInformationField;
3873
3874             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
3875
3876             if (uif && uif->which == Z_External_userInfo1)
3877                 interpret_otherinformation_field(c, uif->u.userInfo1);
3878         }
3879         else
3880         {
3881             char *cookie =
3882                 yaz_oi_get_string_oid(&apdu->u.initResponse->otherInfo,
3883                                       yaz_oid_userinfo_cookie, 1, 0);
3884             xfree(c->cookie_in);
3885             c->cookie_in = 0;
3886             if (cookie)
3887                 c->cookie_in = xstrdup(cookie);
3888             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
3889                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
3890                 c->support_named_resultsets = 1;
3891             if (c->tasks)
3892             {
3893                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
3894                 ZOOM_connection_remove_task(c);
3895             }
3896             ZOOM_connection_exec_task(c);
3897         }
3898         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
3899         {
3900             NMEM tmpmem = nmem_create();
3901             Z_CharSetandLanguageNegotiation *p =
3902                 yaz_get_charneg_record(initrs->otherInfo);
3903             
3904             if (p)
3905             {
3906                 char *charset = NULL, *lang = NULL;
3907                 int sel;
3908                 
3909                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
3910                 yaz_log(log_details, "%p recv_apdu target accepted: "
3911                         "charset %s, language %s, select %d",
3912                         c,
3913                         charset ? charset : "none", lang ? lang : "none", sel);
3914                 if (charset)
3915                     ZOOM_connection_option_set(c, "negotiation-charset",
3916                                                charset);
3917                 if (lang)
3918                     ZOOM_connection_option_set(c, "negotiation-lang",
3919                                                lang);
3920
3921                 ZOOM_connection_option_set(
3922                     c,  "negotiation-charset-in-effect-for-records",
3923                     (sel != 0) ? "1" : "0");
3924                 nmem_destroy(tmpmem);
3925             }
3926         }       
3927         break;
3928     case Z_APDU_searchResponse:
3929         yaz_log(log_api, "%p recv_apdu Search response", c);
3930         handle_search_response(c, apdu->u.searchResponse);
3931         if (send_sort_present(c) == zoom_complete)
3932             ZOOM_connection_remove_task(c);
3933         break;
3934     case Z_APDU_presentResponse:
3935         yaz_log(log_api, "%p recv_apdu Present response", c);
3936         handle_present_response(c, apdu->u.presentResponse);
3937         if (send_present(c) == zoom_complete)
3938             ZOOM_connection_remove_task(c);
3939         break;
3940     case Z_APDU_sortResponse:
3941         yaz_log(log_api, "%p recv_apdu Sort response", c);
3942         sort_response(c, apdu->u.sortResponse);
3943         if (send_present(c) == zoom_complete)
3944             ZOOM_connection_remove_task(c);
3945         break;
3946     case Z_APDU_scanResponse:
3947         yaz_log(log_api, "%p recv_apdu Scan response", c);
3948         scan_response(c, apdu->u.scanResponse);
3949         ZOOM_connection_remove_task(c);
3950         break;
3951     case Z_APDU_extendedServicesResponse:
3952         yaz_log(log_api, "%p recv_apdu Extended Services response", c);
3953         es_response(c, apdu->u.extendedServicesResponse);
3954         ZOOM_connection_remove_task(c);
3955         break;
3956     case Z_APDU_close:
3957         yaz_log(log_api, "%p recv_apdu Close PDU", c);
3958         if (!ZOOM_test_reconnect(c))
3959         {
3960             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3961             do_close(c);
3962         }
3963         break;
3964     default:
3965         yaz_log(log_api, "%p Received unknown PDU", c);
3966         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3967         do_close(c);
3968     }
3969 }
3970
3971 #if YAZ_HAVE_XML2
3972 static zoom_ret handle_srw_response(ZOOM_connection c,
3973                                     Z_SRW_searchRetrieveResponse *res)
3974 {
3975     ZOOM_resultset resultset = 0;
3976     int i;
3977     NMEM nmem;
3978     ZOOM_Event event;
3979     int *start, *count;
3980     const char *syntax, *elementSetName;
3981
3982     if (!c->tasks)
3983         return zoom_complete;
3984
3985     switch(c->tasks->which)
3986     {
3987     case ZOOM_TASK_SEARCH:
3988         resultset = c->tasks->u.search.resultset;
3989         start = &c->tasks->u.search.start;
3990         count = &c->tasks->u.search.count;
3991         syntax = c->tasks->u.search.syntax;
3992         elementSetName = c->tasks->u.search.elementSetName;        
3993
3994         if (!c->tasks->u.search.recv_search_fired)
3995         {
3996             event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
3997             ZOOM_connection_put_event(c, event);
3998             c->tasks->u.search.recv_search_fired = 1;
3999         }
4000         break;
4001     case ZOOM_TASK_RETRIEVE:
4002         resultset = c->tasks->u.retrieve.resultset;
4003         start = &c->tasks->u.retrieve.start;
4004         count = &c->tasks->u.retrieve.count;
4005         syntax = c->tasks->u.retrieve.syntax;
4006         elementSetName = c->tasks->u.retrieve.elementSetName;
4007         break;
4008     default:
4009         return zoom_complete;
4010     }
4011
4012     resultset->size = 0;
4013
4014     if (res->resultSetId)
4015         ZOOM_resultset_option_set(resultset, "resultSetId", res->resultSetId);
4016
4017     yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
4018
4019     if (res->num_diagnostics > 0)
4020     {
4021         set_SRU_error(c, &res->diagnostics[0]);
4022     }
4023     else
4024     {
4025         if (res->numberOfRecords)
4026             resultset->size = *res->numberOfRecords;
4027         for (i = 0; i<res->num_records; i++)
4028         {
4029             int pos;
4030             Z_SRW_record *sru_rec;
4031             Z_SRW_diagnostic *diag = 0;
4032             int num_diag;
4033             
4034             Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
4035                 odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
4036             
4037             if (res->records[i].recordPosition && 
4038                 *res->records[i].recordPosition > 0)
4039                 pos = *res->records[i].recordPosition - 1;
4040             else
4041                 pos = *start + i;
4042             
4043             sru_rec = &res->records[i];
4044             
4045             npr->databaseName = 0;
4046             npr->which = Z_NamePlusRecord_databaseRecord;
4047             npr->u.databaseRecord = (Z_External *)
4048                 odr_malloc(c->odr_in, sizeof(Z_External));
4049             npr->u.databaseRecord->descriptor = 0;
4050             npr->u.databaseRecord->direct_reference =
4051                 odr_oiddup(c->odr_in, yaz_oid_recsyn_xml);
4052             npr->u.databaseRecord->which = Z_External_octet;
4053             
4054             npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
4055                 odr_malloc(c->odr_in, sizeof(Odr_oct));
4056             npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
4057                 sru_rec->recordData_buf;
4058             npr->u.databaseRecord->u.octet_aligned->len = 
4059                 npr->u.databaseRecord->u.octet_aligned->size = 
4060                 sru_rec->recordData_len;
4061             
4062             if (sru_rec->recordSchema 
4063                 && !strcmp(sru_rec->recordSchema,
4064                            "info:srw/schema/1/diagnostics-v1.1"))
4065             {
4066                 sru_decode_surrogate_diagnostics(sru_rec->recordData_buf,
4067                                                  sru_rec->recordData_len,
4068                                                  &diag, &num_diag,
4069                                                  resultset->odr);
4070             }
4071             record_cache_add(resultset, npr, pos, syntax, elementSetName,
4072                              sru_rec->recordSchema, diag);
4073         }
4074         *count -= i;
4075         *start += i;
4076         if (*count + *start > resultset->size)
4077             *count = resultset->size - *start;
4078         if (*count < 0)
4079             *count = 0;
4080         
4081         nmem = odr_extract_mem(c->odr_in);
4082         nmem_transfer(odr_getmem(resultset->odr), nmem);
4083         nmem_destroy(nmem);
4084
4085         if (*count > 0)
4086             return ZOOM_connection_srw_send_search(c);
4087     }
4088     return zoom_complete;
4089 }
4090 #endif
4091
4092 #if YAZ_HAVE_XML2
4093 static void handle_srw_scan_response(ZOOM_connection c,
4094                                      Z_SRW_scanResponse *res)
4095 {
4096     NMEM nmem = odr_extract_mem(c->odr_in);
4097     ZOOM_scanset scan;
4098
4099     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
4100         return;
4101     scan = c->tasks->u.scan.scan;
4102
4103     if (res->num_diagnostics > 0)
4104         set_SRU_error(c, &res->diagnostics[0]);
4105
4106     scan->scan_response = 0;
4107     scan->srw_scan_response = res;
4108     nmem_transfer(odr_getmem(scan->odr), nmem);
4109
4110     ZOOM_options_set_int(scan->options, "number", res->num_terms);
4111     nmem_destroy(nmem);
4112 }
4113 #endif
4114
4115 #if YAZ_HAVE_XML2
4116 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
4117 {
4118     zoom_ret cret = zoom_complete;
4119     int ret = -1;
4120     const char *addinfo = 0;
4121     const char *connection_head = z_HTTP_header_lookup(hres->headers,
4122                                                        "Connection");
4123     ZOOM_connection_set_mask(c, 0);
4124     yaz_log(log_details, "%p handle_http", c);
4125     
4126     if (!yaz_srw_check_content_type(hres))
4127         addinfo = "content-type";
4128     else
4129     {
4130         Z_SOAP *soap_package = 0;
4131         ODR o = c->odr_in;
4132         Z_SOAP_Handler soap_handlers[2] = {
4133             {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
4134             {0, 0, 0}
4135         };
4136         ret = z_soap_codec(o, &soap_package,
4137                            &hres->content_buf, &hres->content_len,
4138                            soap_handlers);
4139         if (!ret && soap_package->which == Z_SOAP_generic &&
4140             soap_package->u.generic->no == 0)
4141         {
4142             Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
4143
4144             ZOOM_options_set(c->options, "sru_version", sr->srw_version);
4145             ZOOM_options_setl(c->options, "sru_extra_response_data",
4146                 sr->extraResponseData_buf, sr->extraResponseData_len);
4147             if (sr->which == Z_SRW_searchRetrieve_response)
4148                 cret = handle_srw_response(c, sr->u.response);
4149             else if (sr->which == Z_SRW_scan_response)
4150                 handle_srw_scan_response(c, sr->u.scan_response);
4151             else
4152                 ret = -1;
4153         }
4154         else if (!ret && (soap_package->which == Z_SOAP_fault
4155                           || soap_package->which == Z_SOAP_error))
4156         {
4157             set_HTTP_error(c, hres->code,
4158                            soap_package->u.fault->fault_code,
4159                            soap_package->u.fault->fault_string);
4160         }
4161         else
4162             ret = -1;
4163     }
4164     if (ret)
4165     {
4166         if (hres->code != 200)
4167             set_HTTP_error(c, hres->code, 0, 0);
4168         else
4169             set_ZOOM_error(c, ZOOM_ERROR_DECODE, addinfo);
4170         do_close(c);
4171     }
4172     if (cret == zoom_complete)
4173         ZOOM_connection_remove_task(c);
4174     if (!strcmp(hres->version, "1.0"))
4175     {
4176         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
4177         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
4178             do_close(c);
4179     }
4180     else 
4181     {
4182         /* HTTP 1.1: only if no close we stay alive .. */
4183         if (connection_head && !strcmp(connection_head, "close"))
4184             do_close(c);
4185     }
4186 }
4187 #endif
4188
4189 static int do_read(ZOOM_connection c)
4190 {
4191     int r, more;
4192     ZOOM_Event event;
4193     
4194     event = ZOOM_Event_create(ZOOM_EVENT_RECV_DATA);
4195     ZOOM_connection_put_event(c, event);
4196     
4197     r = cs_get(c->cs, &c->buf_in, &c->len_in);
4198     more = cs_more(c->cs);
4199     yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
4200     if (r == 1)
4201         return 0;
4202     if (r <= 0)
4203     {
4204         if (!ZOOM_test_reconnect(c))
4205         {
4206             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4207             do_close(c);
4208         }
4209     }
4210     else
4211     {
4212         Z_GDU *gdu;
4213         ZOOM_Event event;
4214
4215         odr_reset(c->odr_in);
4216         odr_setbuf(c->odr_in, c->buf_in, r, 0);
4217         event = ZOOM_Event_create(ZOOM_EVENT_RECV_APDU);
4218         ZOOM_connection_put_event(c, event);
4219
4220         if (!z_GDU(c->odr_in, &gdu, 0, 0))
4221         {
4222             int x;
4223             int err = odr_geterrorx(c->odr_in, &x);
4224             char msg[100];
4225             const char *element = odr_getelement(c->odr_in);
4226             yaz_snprintf(msg, sizeof(msg),
4227                     "ODR code %d:%d element=%s offset=%d",
4228                     err, x, element ? element : "<unknown>",
4229                     odr_offset(c->odr_in));
4230             set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
4231             if (log_api)
4232             {
4233                 FILE *ber_file = yaz_log_file();
4234                 if (ber_file)
4235                     odr_dumpBER(ber_file, c->buf_in, r);
4236             }
4237             do_close(c);
4238         }
4239         else
4240         {
4241             if (c->odr_print)
4242                 z_GDU(c->odr_print, &gdu, 0, 0);
4243             if (gdu->which == Z_GDU_Z3950)
4244                 recv_apdu(c, gdu->u.z3950);
4245             else if (gdu->which == Z_GDU_HTTP_Response)
4246             {
4247 #if YAZ_HAVE_XML2
4248                 handle_http(c, gdu->u.HTTP_Response);
4249 #else
4250                 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
4251                 do_close(c);
4252 #endif
4253             }
4254         }
4255         c->reconnect_ok = 0;
4256     }
4257     return 1;
4258 }
4259
4260 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out)
4261 {
4262     int r;
4263     ZOOM_Event event;
4264     
4265     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
4266     ZOOM_connection_put_event(c, event);
4267
4268     yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
4269     if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
4270     {
4271         yaz_log(log_details, "%p do_write_ex write failed", c);
4272         if (ZOOM_test_reconnect(c))
4273         {
4274             return zoom_pending;
4275         }
4276         if (c->state == STATE_CONNECTING)
4277             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4278         else
4279             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4280         do_close(c);
4281         return zoom_complete;
4282     }
4283     else if (r == 1)
4284     {    
4285         int mask = ZOOM_SELECT_EXCEPT;
4286         if (c->cs->io_pending & CS_WANT_WRITE)
4287             mask += ZOOM_SELECT_WRITE;
4288         if (c->cs->io_pending & CS_WANT_READ)
4289             mask += ZOOM_SELECT_READ;
4290         ZOOM_connection_set_mask(c, mask);
4291         yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
4292                 c, c->mask);
4293     }
4294     else
4295     {
4296         ZOOM_connection_set_mask(c, ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT);
4297         yaz_log(log_details, "%p do_write_ex write complete mask=%d",
4298                 c, c->mask);
4299     }
4300     return zoom_pending;
4301 }
4302
4303 static zoom_ret do_write(ZOOM_connection c)
4304 {
4305     return do_write_ex(c, c->buf_out, c->len_out);
4306 }
4307
4308
4309 ZOOM_API(const char *)
4310     ZOOM_connection_option_get(ZOOM_connection c, const char *key)
4311 {
4312     return ZOOM_options_get(c->options, key);
4313 }
4314
4315 ZOOM_API(const char *)
4316     ZOOM_connection_option_getl(ZOOM_connection c, const char *key, int *lenp)
4317 {
4318     return ZOOM_options_getl(c->options, key, lenp);
4319 }
4320
4321 ZOOM_API(void)
4322     ZOOM_connection_option_set(ZOOM_connection c, const char *key,
4323                                const char *val)
4324 {
4325     ZOOM_options_set(c->options, key, val);
4326 }
4327
4328 ZOOM_API(void)
4329     ZOOM_connection_option_setl(ZOOM_connection c, const char *key,
4330                                 const char *val, int len)
4331 {
4332     ZOOM_options_setl(c->options, key, val, len);
4333 }
4334
4335 ZOOM_API(const char *)
4336     ZOOM_resultset_option_get(ZOOM_resultset r, const char *key)
4337 {
4338     return ZOOM_options_get(r->options, key);
4339 }
4340
4341 ZOOM_API(void)
4342     ZOOM_resultset_option_set(ZOOM_resultset r, const char *key,
4343                               const char *val)
4344 {
4345     ZOOM_options_set(r->options, key, val);
4346 }
4347
4348
4349 ZOOM_API(int)
4350     ZOOM_connection_errcode(ZOOM_connection c)
4351 {
4352     return ZOOM_connection_error(c, 0, 0);
4353 }
4354
4355 ZOOM_API(const char *)
4356     ZOOM_connection_errmsg(ZOOM_connection c)
4357 {
4358     const char *msg;
4359     ZOOM_connection_error(c, &msg, 0);
4360     return msg;
4361 }
4362
4363 ZOOM_API(const char *)
4364     ZOOM_connection_addinfo(ZOOM_connection c)
4365 {
4366     const char *addinfo;
4367     ZOOM_connection_error(c, 0, &addinfo);
4368     return addinfo;
4369 }
4370
4371 ZOOM_API(const char *)
4372     ZOOM_connection_diagset(ZOOM_connection c)
4373 {
4374     const char *diagset;
4375     ZOOM_connection_error_x(c, 0, 0, &diagset);
4376     return diagset;
4377 }
4378
4379 ZOOM_API(const char *)
4380     ZOOM_diag_str(int error)
4381 {
4382     switch (error)
4383     {
4384     case ZOOM_ERROR_NONE:
4385         return "No error";
4386     case ZOOM_ERROR_CONNECT:
4387         return "Connect failed";
4388     case ZOOM_ERROR_MEMORY:
4389         return "Out of memory";
4390     case ZOOM_ERROR_ENCODE:
4391         return "Encoding failed";
4392     case ZOOM_ERROR_DECODE:
4393         return "Decoding failed";
4394     case ZOOM_ERROR_CONNECTION_LOST:
4395         return "Connection lost";
4396     case ZOOM_ERROR_INIT:
4397         return "Init rejected";
4398     case ZOOM_ERROR_INTERNAL:
4399         return "Internal failure";
4400     case ZOOM_ERROR_TIMEOUT:
4401         return "Timeout";
4402     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
4403         return "Unsupported protocol";
4404     case ZOOM_ERROR_UNSUPPORTED_QUERY:
4405         return "Unsupported query type";
4406     case ZOOM_ERROR_INVALID_QUERY:
4407         return "Invalid query";
4408     case ZOOM_ERROR_CQL_PARSE:
4409         return "CQL parsing error";
4410     case ZOOM_ERROR_CQL_TRANSFORM:
4411         return "CQL transformation error";
4412     case ZOOM_ERROR_CCL_CONFIG:
4413         return "CCL configuration error";
4414     case ZOOM_ERROR_CCL_PARSE:
4415         return "CCL parsing error";
4416     default:
4417         return diagbib1_str(error);
4418     }
4419 }
4420
4421 ZOOM_API(int)
4422     ZOOM_connection_error_x(ZOOM_connection c, const char **cp,
4423                             const char **addinfo, const char **diagset)
4424 {
4425     int error = c->error;
4426     if (cp)
4427     {
4428         if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
4429             *cp = ZOOM_diag_str(error);
4430         else if (!strcmp(c->diagset, "HTTP"))
4431             *cp = z_HTTP_errmsg(c->error);
4432         else if (!strcmp(c->diagset, "Bib-1"))
4433             *cp = ZOOM_diag_str(error);
4434         else if (!strcmp(c->diagset, "info:srw/diagnostic/1"))
4435             *cp = yaz_diag_srw_str(c->error);
4436         else
4437             *cp = "Unknown error and diagnostic set";
4438     }
4439     if (addinfo)
4440         *addinfo = c->addinfo ? c->addinfo : "";
4441     if (diagset)
4442         *diagset = c->diagset ? c->diagset : "";
4443     return c->error;
4444 }
4445
4446 ZOOM_API(int)
4447     ZOOM_connection_error(ZOOM_connection c, const char **cp,
4448                           const char **addinfo)
4449 {
4450     return ZOOM_connection_error_x(c, cp, addinfo, 0);
4451 }
4452
4453 static void ZOOM_connection_do_io(ZOOM_connection c, int mask)
4454 {
4455     ZOOM_Event event = 0;
4456     int r = cs_look(c->cs);
4457     yaz_log(log_details, "%p ZOOM_connection_do_io mask=%d cs_look=%d",
4458             c, mask, r);
4459     
4460     if (r == CS_NONE)
4461     {
4462         event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4463         set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4464         do_close(c);
4465         ZOOM_connection_put_event(c, event);
4466     }
4467     else if (r == CS_CONNECT)
4468     {
4469         int ret = ret = cs_rcvconnect(c->cs);
4470         yaz_log(log_details, "%p ZOOM_connection_do_io "
4471                 "cs_rcvconnect returned %d", c, ret);
4472         if (ret == 1)
4473         {
4474             int mask = ZOOM_SELECT_EXCEPT;
4475             if (c->cs->io_pending & CS_WANT_WRITE)
4476                 mask += ZOOM_SELECT_WRITE;
4477             if (c->cs->io_pending & CS_WANT_READ)
4478                 mask += ZOOM_SELECT_READ;
4479             ZOOM_connection_set_mask(c, mask);
4480             event = ZOOM_Event_create(ZOOM_EVENT_NONE);
4481             ZOOM_connection_put_event(c, event);
4482         }
4483         else if (ret == 0)
4484         {
4485             event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4486             ZOOM_connection_put_event(c, event);
4487             get_cert(c);
4488             if (c->proto == PROTO_Z3950)
4489                 ZOOM_connection_send_init(c);
4490             else
4491             {
4492                 /* no init request for SRW .. */
4493                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
4494                 ZOOM_connection_remove_task(c);
4495                 ZOOM_connection_set_mask(c, 0);
4496                 ZOOM_connection_exec_task(c);
4497             }
4498             c->state = STATE_ESTABLISHED;
4499         }
4500         else
4501         {
4502             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4503             do_close(c);
4504         }
4505     }
4506     else
4507     {
4508         if (mask & ZOOM_SELECT_EXCEPT)
4509         {
4510             if (!ZOOM_test_reconnect(c))
4511             {
4512                 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4513                 do_close(c);
4514             }
4515             return;
4516         }
4517         if (mask & ZOOM_SELECT_READ)
4518             do_read(c);
4519         if (c->cs && (mask & ZOOM_SELECT_WRITE))
4520             do_write(c);
4521     }
4522 }
4523
4524 ZOOM_API(int)
4525     ZOOM_connection_last_event(ZOOM_connection cs)
4526 {
4527     if (!cs)
4528         return ZOOM_EVENT_NONE;
4529     return cs->last_event;
4530 }
4531
4532
4533 static void cql2pqf_wrbuf_puts(const char *buf, void *client_data)
4534 {
4535     WRBUF wrbuf = (WRBUF) client_data;
4536     wrbuf_puts(wrbuf, buf);
4537 }
4538
4539 /*
4540  * Returns an xmalloc()d string containing RPN that corresponds to the
4541  * CQL passed in.  On error, sets the Connection object's error state
4542  * and returns a null pointer.
4543  * ### We could cache CQL parser and/or transformer in Connection.
4544  */
4545 static char *cql2pqf(ZOOM_connection c, const char *cql)
4546 {
4547     CQL_parser parser;
4548     int error;
4549     const char *cqlfile;
4550     cql_transform_t trans;
4551     char *result = 0;
4552
4553     parser = cql_parser_create();
4554     if ((error = cql_parser_string(parser, cql)) != 0) {
4555         cql_parser_destroy(parser);
4556         set_ZOOM_error(c, ZOOM_ERROR_CQL_PARSE, cql);
4557         return 0;
4558     }
4559
4560     cqlfile = ZOOM_connection_option_get(c, "cqlfile");
4561     if (cqlfile == 0) 
4562     {
4563         set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, "no CQL transform file");
4564     }
4565     else if ((trans = cql_transform_open_fname(cqlfile)) == 0) 
4566     {
4567         char buf[512];        
4568         sprintf(buf, "can't open CQL transform file '%.200s': %.200s",
4569                 cqlfile, strerror(errno));
4570         set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4571     }
4572     else 
4573     {
4574         WRBUF wrbuf_result = wrbuf_alloc();
4575         error = cql_transform(trans, cql_parser_result(parser),
4576                               cql2pqf_wrbuf_puts, wrbuf_result);
4577         if (error != 0) {
4578             char buf[512];
4579             const char *addinfo;
4580             error = cql_transform_error(trans, &addinfo);
4581             sprintf(buf, "%.200s (addinfo=%.200s)", 
4582                     cql_strerror(error), addinfo);
4583             set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4584         }
4585         else
4586         {
4587             result = xstrdup(wrbuf_cstr(wrbuf_result));
4588         }
4589         cql_transform_close(trans);
4590         wrbuf_destroy(wrbuf_result);
4591     }
4592     cql_parser_destroy(parser);
4593     return result;
4594 }
4595
4596 ZOOM_API(int) ZOOM_connection_fire_event_timeout(ZOOM_connection c)
4597 {
4598     if (c->mask)
4599     {
4600         ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
4601         /* timeout and this connection was waiting */
4602         set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
4603         do_close(c);
4604         ZOOM_connection_put_event(c, event);
4605     }
4606     return 0;
4607 }
4608
4609 ZOOM_API(int)
4610     ZOOM_connection_process(ZOOM_connection c)
4611 {
4612     ZOOM_Event event;
4613     if (!c)
4614         return 0;
4615
4616     event = ZOOM_connection_get_event(c);
4617     if (event)
4618     {
4619         ZOOM_Event_destroy(event);
4620         return 1;
4621     }
4622     ZOOM_connection_exec_task(c);
4623     event = ZOOM_connection_get_event(c);
4624     if (event)
4625     {
4626         ZOOM_Event_destroy(event);
4627         return 1;
4628     }
4629     return 0;
4630 }
4631
4632 ZOOM_API(int)
4633     ZOOM_event_nonblock(int no, ZOOM_connection *cs)
4634 {
4635     int i;
4636
4637     yaz_log(log_details, "ZOOM_process_event(no=%d,cs=%p)", no, cs);
4638     
4639     for (i = 0; i<no; i++)
4640     {
4641         ZOOM_connection c = cs[i];
4642
4643         if (c && ZOOM_connection_process(c))
4644             return i+1;
4645     }
4646     return 0;
4647 }
4648
4649 ZOOM_API(int) ZOOM_connection_fire_event_socket(ZOOM_connection c, int mask)
4650 {
4651     if (c->mask && mask)
4652         ZOOM_connection_do_io(c, mask);
4653     return 0;
4654 }
4655
4656 ZOOM_API(int) ZOOM_connection_get_socket(ZOOM_connection c)
4657 {
4658     if (c->cs)
4659         return cs_fileno(c->cs);
4660     return -1;
4661 }
4662
4663 ZOOM_API(int) ZOOM_connection_set_mask(ZOOM_connection c, int mask)
4664 {
4665     c->mask = mask;
4666     if (!c->cs)
4667         return -1; 
4668     return 0;
4669 }
4670
4671 ZOOM_API(int) ZOOM_connection_get_mask(ZOOM_connection c)
4672 {
4673     if (c->cs)
4674         return c->mask;
4675     return 0;
4676 }
4677
4678 ZOOM_API(int) ZOOM_connection_get_timeout(ZOOM_connection c)
4679 {
4680     return ZOOM_options_get_int(c->options, "timeout", 30);
4681 }
4682
4683 ZOOM_API(void) ZOOM_connection_close(ZOOM_connection c)
4684 {
4685     do_close(c);
4686 }
4687
4688 /*
4689  * Local variables:
4690  * c-basic-offset: 4
4691  * c-file-style: "Stroustrup"
4692  * indent-tabs-mode: nil
4693  * End:
4694  * vim: shiftwidth=4 tabstop=8 expandtab
4695  */
4696