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