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