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