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