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