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