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