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