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