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