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