c73027486aece3b3d3fa73e945ef879ed1d6c8bc
[yaz-moved-to-github.git] / src / zoom-c.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2008 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             if (rc->rec.wrbuf_opac)
1022                 wrbuf_destroy(rc->rec.wrbuf_opac);
1023         }
1024         r->record_hash[i] = 0;
1025     }
1026 }
1027
1028 ZOOM_API(void)
1029     ZOOM_resultset_destroy(ZOOM_resultset r)
1030 {
1031     resultset_destroy(r);
1032 }
1033
1034 static void resultset_destroy(ZOOM_resultset r)
1035 {
1036     if (!r)
1037         return;
1038     (r->refcount)--;
1039     yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
1040             r, r, r->refcount);
1041     if (r->refcount == 0)
1042     {
1043         ZOOM_resultset_cache_reset(r);
1044
1045         if (r->connection)
1046         {
1047             /* remove ourselves from the resultsets in connection */
1048             ZOOM_resultset *rp = &r->connection->resultsets;
1049             while (1)
1050             {
1051                 assert(*rp);   /* we must be in this list!! */
1052                 if (*rp == r)
1053                 {   /* OK, we're here - take us out of it */
1054                     *rp = (*rp)->next;
1055                     break;
1056                 }
1057                 rp = &(*rp)->next;
1058             }
1059         }
1060         ZOOM_query_destroy(r->query);
1061         ZOOM_options_destroy(r->options);
1062         odr_destroy(r->odr);
1063         xfree(r->setname);
1064         xfree(r->schema);
1065         xfree(r);
1066     }
1067 }
1068
1069 ZOOM_API(size_t)
1070     ZOOM_resultset_size(ZOOM_resultset r)
1071 {
1072     yaz_log(log_details, "ZOOM_resultset_size r=%p count=%d",
1073             r, r->size);
1074     return r->size;
1075 }
1076
1077 static void do_close(ZOOM_connection c)
1078 {
1079     if (c->cs)
1080         cs_close(c->cs);
1081     c->cs = 0;
1082     ZOOM_connection_set_mask(c, 0);
1083     c->state = STATE_IDLE;
1084 }
1085
1086 static int ZOOM_test_reconnect(ZOOM_connection c)
1087 {
1088     ZOOM_Event event;
1089
1090     if (!c->reconnect_ok)
1091         return 0;
1092     do_close(c);
1093     c->reconnect_ok = 0;
1094     c->tasks->running = 0;
1095     ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
1096
1097     event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1098     ZOOM_connection_put_event(c, event);
1099
1100     return 1;
1101 }
1102
1103 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
1104                                     int force_sync, int start, int count)
1105 {
1106     ZOOM_task task;
1107     ZOOM_connection c;
1108     const char *cp;
1109     const char *syntax, *elementSetName;
1110
1111     if (!r)
1112         return;
1113     yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1114             " count=%d", r, force_sync, start, count);
1115     c = r->connection;
1116     if (!c)
1117         return;
1118
1119     if (c->host_port && c->proto == PROTO_HTTP)
1120     {
1121         if (!c->cs)
1122         {
1123             yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1124             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1125         }
1126         else
1127         {
1128             yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1129                     "reconnect", r);
1130             c->reconnect_ok = 1;
1131         }
1132     }
1133     task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1134     task->u.retrieve.resultset = r;
1135     task->u.retrieve.start = start;
1136     task->u.retrieve.count = count;
1137
1138     syntax = ZOOM_options_get(r->options, "preferredRecordSyntax"); 
1139     task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1140     elementSetName = ZOOM_options_get(r->options, "elementSetName");
1141     task->u.retrieve.elementSetName = elementSetName 
1142         ? xstrdup(elementSetName) : 0;
1143
1144     cp = ZOOM_options_get(r->options, "schema");
1145     if (cp)
1146     {
1147         if (!r->schema || strcmp(r->schema, cp))
1148         {
1149             xfree(r->schema);
1150             r->schema = xstrdup(cp);
1151         }
1152     }
1153
1154     ZOOM_resultset_addref(r);
1155
1156     if (!r->connection->async || force_sync)
1157         while (r->connection && ZOOM_event(1, &r->connection))
1158             ;
1159 }
1160
1161 ZOOM_API(void)
1162     ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1163                            size_t start, size_t count)
1164 {
1165     int force_present = 0;
1166
1167     if (!r)
1168         return ;
1169     yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1170             r, r, (long) start, (long) count);
1171     if (count && recs)
1172         force_present = 1;
1173     ZOOM_resultset_retrieve(r, force_present, start, count);
1174     if (force_present)
1175     {
1176         size_t i;
1177         for (i = 0; i< count; i++)
1178             recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1179     }
1180 }
1181
1182 static void get_cert(ZOOM_connection c)
1183 {
1184     char *cert_buf;
1185     int cert_len;
1186     
1187     if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1188     {
1189         ZOOM_connection_option_setl(c, "sslPeerCert",
1190                                     cert_buf, cert_len);
1191         xfree(cert_buf);
1192     }
1193 }
1194
1195 static zoom_ret do_connect(ZOOM_connection c)
1196 {
1197     void *add;
1198     const char *effective_host;
1199
1200     if (c->proxy)
1201         effective_host = c->proxy;
1202     else
1203         effective_host = c->host_port;
1204
1205     yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1206
1207     if (c->cs)
1208         cs_close(c->cs);
1209     c->cs = cs_create_host(effective_host, 0, &add);
1210
1211     if (c->cs && c->cs->protocol == PROTO_HTTP)
1212     {
1213 #if YAZ_HAVE_XML2
1214         const char *path = 0;
1215
1216         c->proto = PROTO_HTTP;
1217         cs_get_host_args(c->host_port, &path);
1218         xfree(c->path);
1219         c->path = (char*) xmalloc(strlen(path)+2);
1220         c->path[0] = '/';
1221         strcpy(c->path+1, path);
1222 #else
1223         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1224         do_close(c);
1225         return zoom_complete;
1226 #endif
1227     }
1228     if (c->cs)
1229     {
1230         int ret = cs_connect(c->cs, add);
1231         if (ret == 0)
1232         {
1233             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1234             ZOOM_connection_put_event(c, event);
1235             get_cert(c);
1236             if (c->proto == PROTO_Z3950)
1237                 ZOOM_connection_send_init(c);
1238             else
1239             {
1240                 /* no init request for SRW .. */
1241                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1242                 ZOOM_connection_remove_task(c);
1243                 ZOOM_connection_set_mask(c, 0);
1244                 ZOOM_connection_exec_task(c);
1245             }
1246             c->state = STATE_ESTABLISHED;
1247             return zoom_pending;
1248         }
1249         else if (ret > 0)
1250         {
1251             int mask = ZOOM_SELECT_EXCEPT;
1252             if (c->cs->io_pending & CS_WANT_WRITE)
1253                 mask += ZOOM_SELECT_WRITE;
1254             if (c->cs->io_pending & CS_WANT_READ)
1255                 mask += ZOOM_SELECT_READ;
1256             ZOOM_connection_set_mask(c, mask);
1257             c->state = STATE_CONNECTING; 
1258             return zoom_pending;
1259         }
1260     }
1261     c->state = STATE_IDLE;
1262     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
1263     return zoom_complete;
1264 }
1265
1266 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1267 {
1268     int i;
1269     for (i = 0; i<200; i++)
1270     {
1271         size_t len;
1272         Odr_oid *oid;
1273         Z_OtherInformation **oi;
1274         char buf[80];
1275         const char *val;
1276         const char *cp;
1277
1278         sprintf(buf, "otherInfo%d", i);
1279         val = ZOOM_options_get(c->options, buf);
1280         if (!val)
1281             break;
1282         cp = strchr(val, ':');
1283         if (!cp)
1284             continue;
1285         len = cp - val;
1286         if (len >= sizeof(buf))
1287             len = sizeof(buf)-1;
1288         memcpy(buf, val, len);
1289         buf[len] = '\0';
1290         
1291         oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
1292                                     buf, out);
1293         if (!oid)
1294             continue;
1295         
1296         yaz_oi_APDU(a, &oi);
1297         yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
1298     }
1299 }
1300
1301 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1302 {
1303     assert(a);
1304     if (c->cookie_out)
1305     {
1306         Z_OtherInformation **oi;
1307         yaz_oi_APDU(a, &oi);
1308         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie, 
1309                               1, c->cookie_out);
1310     }
1311     if (c->client_IP)
1312     {
1313         Z_OtherInformation **oi;
1314         yaz_oi_APDU(a, &oi);
1315         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip, 
1316                               1, c->client_IP);
1317     }
1318     otherInfo_attach(c, a, out);
1319     if (!z_APDU(out, &a, 0, 0))
1320     {
1321         FILE *outf = fopen("/tmp/apdu.txt", "a");
1322         if (a && outf)
1323         {
1324             ODR odr_pr = odr_createmem(ODR_PRINT);
1325             fprintf(outf, "a=%p\n", a);
1326             odr_setprint(odr_pr, outf);
1327             z_APDU(odr_pr, &a, 0, 0);
1328             odr_destroy(odr_pr);
1329         }
1330         yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1331         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1332         odr_reset(out);
1333         return -1;
1334     }
1335     if (c->odr_print)
1336         z_APDU(c->odr_print, &a, 0, 0);
1337     yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1338     return 0;
1339 }
1340
1341 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1342 {
1343     ZOOM_Event event;
1344     assert(a);
1345     if (encode_APDU(c, a, c->odr_out))
1346         return zoom_complete;
1347     yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1348     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1349     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1350     ZOOM_connection_put_event(c, event);
1351     odr_reset(c->odr_out);
1352     return do_write(c);
1353 }
1354
1355 /* returns 1 if PDU was sent OK (still pending )
1356    0 if PDU was not sent OK (nothing to wait for) 
1357 */
1358
1359 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1360 {
1361     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1362     Z_InitRequest *ireq = apdu->u.initRequest;
1363     Z_IdAuthentication *auth = (Z_IdAuthentication *)
1364         odr_malloc(c->odr_out, sizeof(*auth));
1365     char *version;
1366
1367     ODR_MASK_SET(ireq->options, Z_Options_search);
1368     ODR_MASK_SET(ireq->options, Z_Options_present);
1369     ODR_MASK_SET(ireq->options, Z_Options_scan);
1370     ODR_MASK_SET(ireq->options, Z_Options_sort);
1371     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1372     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1373     
1374     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1375     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1376     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1377     
1378     ireq->implementationId =
1379         odr_prepend(c->odr_out,
1380                     ZOOM_options_get(c->options, "implementationId"),
1381                     ireq->implementationId);
1382     
1383     ireq->implementationName = 
1384         odr_prepend(c->odr_out,
1385                     ZOOM_options_get(c->options, "implementationName"),
1386                     odr_prepend(c->odr_out, "ZOOM-C",
1387                                 ireq->implementationName));
1388     
1389     ireq->implementationVersion = 
1390         odr_prepend(c->odr_out,
1391                     ZOOM_options_get(c->options, "implementationVersion"),
1392                                 ireq->implementationVersion);
1393     
1394     *ireq->maximumRecordSize = c->maximum_record_size;
1395     *ireq->preferredMessageSize = c->preferred_message_size;
1396     
1397     if (c->group || c->password)
1398     {
1399         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1400         pass->groupId = odr_strdup_null(c->odr_out, c->group);
1401         pass->userId = odr_strdup_null(c->odr_out, c->user);
1402         pass->password = odr_strdup_null(c->odr_out, c->password);
1403         auth->which = Z_IdAuthentication_idPass;
1404         auth->u.idPass = pass;
1405         ireq->idAuthentication = auth;
1406     }
1407     else if (c->user)
1408     {
1409         auth->which = Z_IdAuthentication_open;
1410         auth->u.open = odr_strdup(c->odr_out, c->user);
1411         ireq->idAuthentication = auth;
1412     }
1413     if (c->proxy)
1414     {
1415         yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
1416                               yaz_oid_userinfo_proxy, 1, c->host_port);
1417     }
1418     if (c->charset || c->lang)
1419     {
1420         Z_OtherInformation **oi;
1421         Z_OtherInformationUnit *oi_unit;
1422         
1423         yaz_oi_APDU(apdu, &oi);
1424         
1425         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1426         {
1427             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1428             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1429             oi_unit->information.externallyDefinedInfo =
1430                 yaz_set_proposal_charneg_list(c->odr_out, " ",
1431                                               c->charset, c->lang, 1);
1432         }
1433     }
1434     assert(apdu);
1435     return send_APDU(c, apdu);
1436 }
1437
1438 #if YAZ_HAVE_XML2
1439 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1440 {
1441     Z_GDU *gdu;
1442     ZOOM_Event event;
1443     const char *database =  ZOOM_options_get(c->options, "databaseName");
1444     char *fdatabase = 0;
1445     
1446     if (database)
1447     {
1448         fdatabase = (char *) odr_malloc(c->odr_out, strlen(database)+2);
1449         strcpy(fdatabase, "/");
1450         strcat(fdatabase, database);
1451     }
1452     gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port,
1453                                        fdatabase ? fdatabase : c->path);
1454
1455     if (c->sru_mode == zoom_sru_get)
1456     {
1457         yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1458     }
1459     else if (c->sru_mode == zoom_sru_post)
1460     {
1461         yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1462     }
1463     else if (c->sru_mode == zoom_sru_soap)
1464     {
1465         yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1466     }
1467     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1468         return zoom_complete;
1469     if (c->odr_print)
1470         z_GDU(c->odr_print, &gdu, 0, 0);
1471     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1472         
1473     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1474     ZOOM_connection_put_event(c, event);
1475     odr_reset(c->odr_out);
1476     return do_write(c);
1477 }
1478 #endif
1479
1480 #if YAZ_HAVE_XML2
1481 static Z_SRW_PDU *ZOOM_srw_get_pdu(ZOOM_connection c, int type)
1482 {
1483     Z_SRW_PDU *sr = yaz_srw_get_pdu(c->odr_out, type, c->sru_version);
1484     sr->username = c->user;
1485     sr->password = c->password;
1486     return sr;
1487 }
1488 #endif
1489
1490 #if YAZ_HAVE_XML2
1491 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1492 {
1493     int i;
1494     int *start, *count;
1495     ZOOM_resultset resultset = 0;
1496     Z_SRW_PDU *sr = 0;
1497     const char *option_val = 0;
1498
1499     if (c->error)                  /* don't continue on error */
1500         return zoom_complete;
1501     assert(c->tasks);
1502     switch(c->tasks->which)
1503     {
1504     case ZOOM_TASK_SEARCH:
1505         resultset = c->tasks->u.search.resultset;
1506         if (!resultset->setname)
1507             resultset->setname = xstrdup("default");
1508         ZOOM_options_set(resultset->options, "setname", resultset->setname);
1509         start = &c->tasks->u.search.start;
1510         count = &c->tasks->u.search.count;
1511         break;
1512     case ZOOM_TASK_RETRIEVE:
1513         resultset = c->tasks->u.retrieve.resultset;
1514
1515         start = &c->tasks->u.retrieve.start;
1516         count = &c->tasks->u.retrieve.count;
1517
1518         if (*start >= resultset->size)
1519             return zoom_complete;
1520         if (*start + *count > resultset->size)
1521             *count = resultset->size - *start;
1522
1523         for (i = 0; i < *count; i++)
1524         {
1525             ZOOM_record rec =
1526                 record_cache_lookup(resultset, i + *start,
1527                                     c->tasks->u.retrieve.syntax,
1528                                     c->tasks->u.retrieve.elementSetName);
1529             if (!rec)
1530                 break;
1531             else
1532             {
1533                 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1534                 ZOOM_connection_put_event(c, event);
1535             }
1536         }
1537         *start += i;
1538         *count -= i;
1539
1540         if (*count == 0)
1541             return zoom_complete;
1542         break;
1543     default:
1544         return zoom_complete;
1545     }
1546     assert(resultset->query);
1547         
1548     sr = ZOOM_srw_get_pdu(c, Z_SRW_searchRetrieve_request);
1549     if (resultset->query->z_query->which == Z_Query_type_104
1550         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1551     {
1552         sr->u.request->query_type = Z_SRW_query_type_cql;
1553         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1554     }
1555     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1556              resultset->query->z_query->u.type_1)
1557     {
1558         sr->u.request->query_type = Z_SRW_query_type_pqf;
1559         sr->u.request->query.pqf = resultset->query->query_string;
1560     }
1561     else
1562     {
1563         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1564         return zoom_complete;
1565     }
1566     sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1567     sr->u.request->maximumRecords = odr_intdup(
1568         c->odr_out, (resultset->step > 0 && resultset->step < *count) ? 
1569         resultset->step : *count);
1570     sr->u.request->recordSchema = resultset->schema;
1571     
1572     option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1573     if (option_val)
1574         sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1575
1576     option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1577     yaz_encode_sru_extra(sr, c->odr_out, option_val);
1578     return send_srw(c, sr);
1579 }
1580 #else
1581 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1582 {
1583     return zoom_complete;
1584 }
1585 #endif
1586
1587 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1588 {
1589     ZOOM_resultset r;
1590     int lslb, ssub, mspn;
1591     const char *syntax;
1592     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1593     Z_SearchRequest *search_req = apdu->u.searchRequest;
1594     const char *elementSetName;
1595     const char *smallSetElementSetName;
1596     const char *mediumSetElementSetName;
1597
1598     assert(c->tasks);
1599     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1600
1601     r = c->tasks->u.search.resultset;
1602
1603     yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1604
1605     elementSetName =
1606         ZOOM_options_get(r->options, "elementSetName");
1607     smallSetElementSetName  =
1608         ZOOM_options_get(r->options, "smallSetElementSetName");
1609     mediumSetElementSetName =
1610         ZOOM_options_get(r->options, "mediumSetElementSetName");
1611
1612     if (!smallSetElementSetName)
1613         smallSetElementSetName = elementSetName;
1614
1615     if (!mediumSetElementSetName)
1616         mediumSetElementSetName = elementSetName;
1617
1618     assert(r);
1619     assert(r->query);
1620
1621     /* prepare query for the search request */
1622     search_req->query = r->query->z_query;
1623     if (!search_req->query)
1624     {
1625         set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1626         return zoom_complete;
1627     }
1628     if (r->query->z_query->which == Z_Query_type_1 || 
1629         r->query->z_query->which == Z_Query_type_101)
1630     {
1631         const char *cp = ZOOM_options_get(r->options, "rpnCharset");
1632         if (cp)
1633         {
1634             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
1635             if (cd)
1636             {
1637                 search_req->query = yaz_copy_Z_Query(search_req->query,
1638                                                      c->odr_out);
1639                 
1640                 yaz_query_charset_convert_rpnquery(search_req->query->u.type_1,
1641                                                    c->odr_out, cd);
1642                 yaz_iconv_close(cd);
1643             }
1644         }
1645     }
1646     search_req->databaseNames = r->databaseNames;
1647     search_req->num_databaseNames = r->num_databaseNames;
1648
1649     /* get syntax (no need to provide unless piggyback is in effect) */
1650     syntax = c->tasks->u.search.syntax;
1651
1652     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1653     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1654     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1655     if (lslb != -1 && ssub != -1 && mspn != -1)
1656     {
1657         /* So're a Z39.50 expert? Let's hope you don't do sort */
1658         *search_req->largeSetLowerBound = lslb;
1659         *search_req->smallSetUpperBound = ssub;
1660         *search_req->mediumSetPresentNumber = mspn;
1661     }
1662     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1663              && r->piggyback && !r->r_sort_spec && !r->schema)
1664     {
1665         /* Regular piggyback - do it unless we're going to do sort */
1666         *search_req->largeSetLowerBound = 2000000000;
1667         *search_req->smallSetUpperBound = 1;
1668         *search_req->mediumSetPresentNumber = 
1669             r->step>0 ? r->step : c->tasks->u.search.count;
1670     }
1671     else
1672     {
1673         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1674         smallSetElementSetName = 0;
1675         mediumSetElementSetName = 0;
1676         syntax = 0;
1677     }
1678     if (smallSetElementSetName && *smallSetElementSetName)
1679     {
1680         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1681             odr_malloc(c->odr_out, sizeof(*esn));
1682         
1683         esn->which = Z_ElementSetNames_generic;
1684         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1685         search_req->smallSetElementSetNames = esn;
1686     }
1687     if (mediumSetElementSetName && *mediumSetElementSetName)
1688     {
1689         Z_ElementSetNames *esn =(Z_ElementSetNames *)
1690             odr_malloc(c->odr_out, sizeof(*esn));
1691         
1692         esn->which = Z_ElementSetNames_generic;
1693         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1694         search_req->mediumSetElementSetNames = esn;
1695     }
1696     if (syntax)
1697         search_req->preferredRecordSyntax =
1698             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1699     
1700     if (!r->setname)
1701     {
1702         if (c->support_named_resultsets)
1703         {
1704             char setname[14];
1705             int ord;
1706             /* find the lowest unused ordinal so that we re-use
1707                result sets on the server. */
1708             for (ord = 1; ; ord++)
1709             {
1710                 ZOOM_resultset rp;
1711                 sprintf(setname, "%d", ord);
1712                 for (rp = c->resultsets; rp; rp = rp->next)
1713                     if (rp->setname && !strcmp(rp->setname, setname))
1714                         break;
1715                 if (!rp)
1716                     break;
1717             }
1718             r->setname = xstrdup(setname);
1719             yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1720                     "set %s", c, r->setname);
1721         }
1722         else
1723         {
1724             yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1725                     "default set", c);
1726             r->setname = xstrdup("default");
1727         }
1728         ZOOM_options_set(r->options, "setname", r->setname);
1729     }
1730     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1731     return send_APDU(c, apdu);
1732 }
1733
1734 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1735 {
1736     char oid_name_buf[OID_STR_MAX];
1737     const char *oid_name;
1738     char *addinfo = 0;
1739
1740     oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
1741     switch (r->which)
1742     {
1743     case Z_DefaultDiagFormat_v2Addinfo:
1744         addinfo = r->u.v2Addinfo;
1745         break;
1746     case Z_DefaultDiagFormat_v3Addinfo:
1747         addinfo = r->u.v3Addinfo;
1748         break;
1749     }
1750     xfree(c->addinfo);
1751     c->addinfo = 0;
1752     set_dset_error(c, *r->condition, oid_name, addinfo, 0);
1753 }
1754
1755 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1756 {
1757     if (p->which != Z_DiagRec_defaultFormat)
1758         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1759     else
1760         response_default_diag(c, p->u.defaultFormat);
1761 }
1762
1763 ZOOM_API(ZOOM_record)
1764     ZOOM_record_clone(ZOOM_record srec)
1765 {
1766     char *buf;
1767     int size;
1768     ODR odr_enc;
1769     ZOOM_record nrec;
1770
1771     odr_enc = odr_createmem(ODR_ENCODE);
1772     if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1773         return 0;
1774     buf = odr_getbuf(odr_enc, &size, 0);
1775     
1776     nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1777     nrec->odr = odr_createmem(ODR_DECODE);
1778     nrec->wrbuf_marc = 0;
1779     nrec->wrbuf_iconv = 0;
1780     nrec->wrbuf_opac = 0;
1781     odr_setbuf(nrec->odr, buf, size, 0);
1782     z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1783     
1784     nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1785     nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1786     nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1787     nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1788     nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1789     odr_destroy(odr_enc);
1790     return nrec;
1791 }
1792
1793 ZOOM_API(ZOOM_record)
1794     ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1795 {
1796     const char *syntax =
1797         ZOOM_options_get(s->options, "preferredRecordSyntax"); 
1798     const char *elementSetName =
1799         ZOOM_options_get(s->options, "elementSetName");
1800
1801     return record_cache_lookup(s, pos, syntax, elementSetName);
1802 }
1803
1804 ZOOM_API(ZOOM_record)
1805     ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1806 {
1807     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1808
1809     if (!rec)
1810     {
1811         /*
1812          * MIKE: I think force_sync should always be zero, but I don't
1813          * want to make this change until I get the go-ahead from
1814          * Adam, in case something depends on the old synchronous
1815          * behaviour.
1816          */
1817         int force_sync = 1;
1818         if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1819         ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1820         rec = ZOOM_resultset_record_immediate(r, pos);
1821     }
1822     return rec;
1823 }
1824
1825 ZOOM_API(void)
1826     ZOOM_record_destroy(ZOOM_record rec)
1827 {
1828     if (!rec)
1829         return;
1830     if (rec->wrbuf_marc)
1831         wrbuf_destroy(rec->wrbuf_marc);
1832     if (rec->wrbuf_iconv)
1833         wrbuf_destroy(rec->wrbuf_iconv);
1834     if (rec->wrbuf_opac)
1835         wrbuf_destroy(rec->wrbuf_opac);
1836     odr_destroy(rec->odr);
1837     xfree(rec);
1838 }
1839
1840 static const char *marc_iconv_return(ZOOM_record rec, int marc_type,
1841                                      int *len,
1842                                      const char *buf, int sz,
1843                                      const char *record_charset)
1844 {
1845     char to[40];
1846     char from[40];
1847     yaz_iconv_t cd = 0;
1848     yaz_marc_t mt = yaz_marc_create();
1849
1850     *from = '\0';
1851     strcpy(to, "UTF-8");
1852     if (record_charset && *record_charset)
1853     {
1854         /* Use "from,to" or just "from" */
1855         const char *cp = strchr(record_charset, ',');
1856         int clen = strlen(record_charset);
1857         if (cp && cp[1])
1858         {
1859             strncpy( to, cp+1, sizeof(to)-1);
1860             to[sizeof(to)-1] = '\0';
1861             clen = cp - record_charset;
1862         }
1863         if (clen > sizeof(from)-1)
1864             clen = sizeof(from)-1;
1865         
1866         if (clen)
1867             strncpy(from, record_charset, clen);
1868         from[clen] = '\0';
1869     }
1870
1871     if (*from && *to)
1872     {
1873         cd = yaz_iconv_open(to, from);
1874         yaz_marc_iconv(mt, cd);
1875     }
1876
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         yaz_marc_destroy(mt);
1884         if (cd)
1885             yaz_iconv_close(cd);
1886         if (len)
1887             *len = wrbuf_len(rec->wrbuf_marc);
1888         return wrbuf_cstr(rec->wrbuf_marc);
1889     }
1890     yaz_marc_destroy(mt);
1891     if (cd)
1892         yaz_iconv_close(cd);
1893     return 0;
1894 }
1895
1896 static const char *record_iconv_return(ZOOM_record rec, int *len,
1897                                        const char *buf, int sz,
1898                                        const char *record_charset)
1899 {
1900     char to[40];
1901     char from[40];
1902     yaz_iconv_t cd = 0;
1903
1904     *from = '\0';
1905     strcpy(to, "UTF-8");
1906
1907     if (record_charset && *record_charset)
1908     {
1909         /* Use "from,to" or just "from" */
1910         const char *cp = strchr(record_charset, ',');
1911         int clen = strlen(record_charset);
1912         if (cp && cp[1])
1913         {
1914             strncpy( to, cp+1, sizeof(to)-1);
1915             to[sizeof(to)-1] = '\0';
1916             clen = cp - record_charset;
1917         }
1918         if (clen > sizeof(from)-1)
1919             clen = sizeof(from)-1;
1920         
1921         if (clen)
1922             strncpy(from, record_charset, clen);
1923         from[clen] = '\0';
1924     }
1925
1926     if (*from && *to && (cd = yaz_iconv_open(to, from)))
1927     {
1928         if (!rec->wrbuf_iconv)
1929             rec->wrbuf_iconv = wrbuf_alloc();
1930
1931         wrbuf_rewind(rec->wrbuf_iconv);
1932
1933         wrbuf_iconv_write(rec->wrbuf_iconv, cd, buf, sz);
1934         wrbuf_iconv_reset(rec->wrbuf_iconv, cd);
1935
1936         buf = wrbuf_cstr(rec->wrbuf_iconv);
1937         sz = wrbuf_len(rec->wrbuf_iconv);
1938         yaz_iconv_close(cd);
1939     }
1940     if (len)
1941         *len = sz;
1942     return buf;
1943 }
1944
1945
1946 ZOOM_API(int)
1947     ZOOM_record_error(ZOOM_record rec, const char **cp,
1948                       const char **addinfo, const char **diagset)
1949 {
1950     Z_NamePlusRecord *npr;
1951     
1952     if (!rec)
1953         return 0;
1954
1955     npr = rec->npr;
1956     if (rec->diag_uri)
1957     {
1958         if (cp)
1959             *cp = rec->diag_message;
1960         if (addinfo)
1961             *addinfo = rec->diag_details;
1962         if (diagset)
1963             *diagset = rec->diag_set;
1964         return uri_to_code(rec->diag_uri);
1965     }
1966     if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
1967     {
1968         Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
1969         int error = YAZ_BIB1_UNSPECIFIED_ERROR;
1970         const char *add = 0;
1971
1972         if (diag_rec->which == Z_DiagRec_defaultFormat)
1973         {
1974             Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
1975             oid_class oclass;
1976     
1977             error = *ddf->condition;
1978             switch (ddf->which)
1979             {
1980             case Z_DefaultDiagFormat_v2Addinfo:
1981                 add = ddf->u.v2Addinfo;
1982                 break;
1983             case Z_DefaultDiagFormat_v3Addinfo:
1984                 add = ddf->u.v3Addinfo;
1985                 break;
1986             }
1987             if (diagset)
1988                 *diagset =
1989                     yaz_oid_to_string(yaz_oid_std(),
1990                                       ddf->diagnosticSetId, &oclass);
1991         }
1992         else
1993         {
1994             if (diagset)
1995                 *diagset = "Bib-1";
1996         }
1997         if (addinfo)
1998             *addinfo = add ? add : "";
1999         if (cp)
2000             *cp = diagbib1_str(error);
2001         return error;
2002     }
2003     return 0;
2004 }
2005
2006 ZOOM_API(const char *)
2007     ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2008 {
2009     char type[40];
2010     char charset[40];
2011     char xpath[512];
2012     const char *cp;
2013     int i;
2014     Z_NamePlusRecord *npr;
2015     
2016     if (len)
2017         *len = 0; /* default return */
2018         
2019     if (!rec)
2020         return 0;
2021     npr = rec->npr;
2022     if (!npr)
2023         return 0;
2024
2025     cp = type_spec;
2026     for (i = 0; cp[i] && i < sizeof(type)-1; i++)
2027     {
2028         if (cp[i] == ';' || cp[i] == ' ')
2029             break;
2030         type[i] = cp[i];
2031     }
2032     type[i] = '\0';
2033     charset[0] = '\0';
2034     while (type_spec[i] == ';')
2035     {
2036         i++;
2037         while (type_spec[i] == ' ')
2038             i++;
2039         if (!strncmp(type_spec+i, "charset=", 8))
2040         {
2041             int j = 0;
2042             i = i + 8; /* skip charset= */
2043             for (j = 0; type_spec[i]  && j < sizeof(charset)-1; i++, j++)
2044             {
2045                 if (type_spec[i] == ';' || type_spec[i] == ' ')
2046                     break;
2047                 charset[j] = cp[i];
2048             }
2049             charset[j] = '\0';
2050         }
2051         else if (!strncmp(type_spec+i, "xpath=", 6))
2052         {
2053             int j = 0; 
2054             i = i + 6;
2055             for (j = 0; type_spec[i] && j < sizeof(xpath)-1; i++, j++)
2056                 xpath[j] = cp[i];
2057             xpath[j] = '\0';
2058         } 
2059         while (type_spec[i] == ' ')
2060             i++;
2061     }
2062     if (!strcmp(type, "database"))
2063     {
2064         if (len)
2065             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2066         return npr->databaseName;
2067     }
2068     else if (!strcmp(type, "schema"))
2069     {
2070         if (len)
2071             *len = rec->schema ? strlen(rec->schema) : 0;
2072         return rec->schema;
2073     }
2074     else if (!strcmp(type, "syntax"))
2075     {
2076         const char *desc = 0;   
2077         if (npr->which == Z_NamePlusRecord_databaseRecord)
2078         {
2079             Z_External *r = (Z_External *) npr->u.databaseRecord;
2080             desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2081         }
2082         if (!desc)
2083             desc = "none";
2084         if (len)
2085             *len = strlen(desc);
2086         return desc;
2087     }
2088     if (npr->which != Z_NamePlusRecord_databaseRecord)
2089         return 0;
2090
2091     /* from now on - we have a database record .. */
2092     if (!strcmp(type, "render"))
2093     {
2094         Z_External *r = (Z_External *) npr->u.databaseRecord;
2095         const Odr_oid *oid = r->direct_reference;
2096
2097         /* render bibliographic record .. */
2098         if (r->which == Z_External_OPAC)
2099         {
2100             r = r->u.opac->bibliographicRecord;
2101             if (!r)
2102                 return 0;
2103             oid = r->direct_reference;
2104         }
2105         if (r->which == Z_External_sutrs)
2106             return record_iconv_return(rec, len,
2107                                        (char*) r->u.sutrs->buf,
2108                                        r->u.sutrs->len,
2109                                        charset);
2110         else if (r->which == Z_External_octet)
2111         {
2112             if (yaz_oid_is_iso2709(oid))
2113             {
2114                 const char *ret_buf = marc_iconv_return(
2115                     rec, YAZ_MARC_LINE, len,
2116                     (const char *) r->u.octet_aligned->buf,
2117                     r->u.octet_aligned->len,
2118                     charset);
2119                 if (ret_buf)
2120                     return ret_buf;
2121             }
2122             return record_iconv_return(rec, len,
2123                                        (const char *) r->u.octet_aligned->buf,
2124                                        r->u.octet_aligned->len,
2125                                        charset);
2126         }
2127         else if (r->which == Z_External_grs1)
2128         {
2129             if (!rec->wrbuf_marc)
2130                 rec->wrbuf_marc = wrbuf_alloc();
2131             wrbuf_rewind(rec->wrbuf_marc);
2132             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
2133             return record_iconv_return(rec, len,
2134                                        wrbuf_buf(rec->wrbuf_marc),
2135                                        wrbuf_len(rec->wrbuf_marc),
2136                                        charset);
2137         }
2138         return 0;
2139     }
2140     else if (!strcmp(type, "xml"))
2141     {
2142         Z_External *r = (Z_External *) npr->u.databaseRecord;
2143         const Odr_oid *oid = r->direct_reference;
2144
2145         /* render bibliographic record .. */
2146         if (r->which == Z_External_OPAC)
2147         {
2148             r = r->u.opac->bibliographicRecord;
2149             if (!r)
2150                 return 0;
2151             oid = r->direct_reference;
2152         }
2153         
2154         if (r->which == Z_External_sutrs)
2155             return record_iconv_return(rec, len,
2156                                        (const char *) r->u.sutrs->buf,
2157                                        r->u.sutrs->len,
2158                                        charset);
2159         else if (r->which == Z_External_octet)
2160         {
2161             int marc_decode_type = YAZ_MARC_MARCXML;
2162             if (yaz_oid_is_iso2709(oid))
2163             {
2164                 const char *ret_buf = marc_iconv_return(
2165                     rec, marc_decode_type, len,
2166                     (const char *) r->u.octet_aligned->buf,
2167                     r->u.octet_aligned->len,
2168                     charset);
2169                 if (ret_buf)
2170                     return ret_buf;
2171             }
2172             return record_iconv_return(rec, len,
2173                                        (const char *) r->u.octet_aligned->buf,
2174                                        r->u.octet_aligned->len,
2175                                        charset);
2176         }
2177         else if (r->which == Z_External_grs1)
2178         {
2179             if (len) *len = 5;
2180             return "GRS-1";
2181         }
2182         return 0;
2183     }
2184     else if (!strcmp(type, "raw"))
2185     {
2186         Z_External *r = (Z_External *) npr->u.databaseRecord;
2187         
2188         if (r->which == Z_External_sutrs)
2189         {
2190             if (len) *len = r->u.sutrs->len;
2191             return (const char *) r->u.sutrs->buf;
2192         }
2193         else if (r->which == Z_External_octet)
2194         {
2195             if (len) *len = r->u.octet_aligned->len;
2196             return (const char *) r->u.octet_aligned->buf;
2197         }
2198         else /* grs-1, explain, OPAC, ... */
2199         {
2200             if (len) *len = -1;
2201             return (const char *) npr->u.databaseRecord;
2202         }
2203         return 0;
2204     }
2205     else if (!strcmp (type, "ext"))
2206     {
2207         if (len) *len = -1;
2208         return (const char *) npr->u.databaseRecord;
2209     }
2210     else if (!strcmp (type, "opac"))
2211              
2212     {
2213         Z_External *r = (Z_External *) npr->u.databaseRecord;
2214         if (r->which == Z_External_OPAC)
2215         {
2216             if (!rec->wrbuf_opac)
2217                 rec->wrbuf_opac = wrbuf_alloc();
2218             wrbuf_rewind(rec->wrbuf_opac);
2219             yaz_display_OPAC(rec->wrbuf_opac, r->u.opac, 0);
2220             return record_iconv_return(rec, len,
2221                                        wrbuf_buf(rec->wrbuf_opac),
2222                                        wrbuf_len(rec->wrbuf_opac),
2223                                        charset);
2224         }
2225     }
2226     return 0;
2227 }
2228
2229 static int strcmp_null(const char *v1, const char *v2)
2230 {
2231     if (!v1 && !v2)
2232         return 0;
2233     if (!v1 || !v2)
2234         return -1;
2235     return strcmp(v1, v2);
2236 }
2237
2238 static size_t record_hash(int pos)
2239 {
2240     if (pos < 0)
2241         pos = 0;
2242     return pos % RECORD_HASH_SIZE;
2243 }
2244
2245 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr, 
2246                              int pos,
2247                              const char *syntax, const char *elementSetName,
2248                              const char *schema,
2249                              Z_SRW_diagnostic *diag)
2250 {
2251     ZOOM_record_cache rc = 0;
2252     
2253     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2254     ZOOM_connection_put_event(r->connection, event);
2255
2256     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2257     {
2258         if (pos == rc->pos 
2259             && strcmp_null(r->schema, rc->schema) == 0
2260             && strcmp_null(elementSetName,rc->elementSetName) == 0
2261             && strcmp_null(syntax, rc->syntax) == 0)
2262             break;
2263     }
2264     if (!rc)
2265     {
2266         rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2267         rc->rec.odr = 0;
2268         rc->rec.wrbuf_marc = 0;
2269         rc->rec.wrbuf_iconv = 0;
2270         rc->rec.wrbuf_opac = 0;
2271         rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2272         
2273         rc->syntax = odr_strdup_null(r->odr, syntax);
2274         
2275         rc->schema = odr_strdup_null(r->odr, r->schema);
2276
2277         rc->pos = pos;
2278         rc->next = r->record_hash[record_hash(pos)];
2279         r->record_hash[record_hash(pos)] = rc;
2280     }
2281     rc->rec.npr = npr;
2282     rc->rec.schema = odr_strdup_null(r->odr, schema);
2283     rc->rec.diag_set = 0;
2284     rc->rec.diag_uri = 0;
2285     rc->rec.diag_message = 0;
2286     rc->rec.diag_details = 0;
2287     if (diag)
2288     {
2289         if (diag->uri)
2290         {
2291             char *cp;
2292             rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2293             if ((cp = strrchr(rc->rec.diag_set, '/')))
2294                 *cp = '\0';
2295             rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2296         }
2297         rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);            
2298         rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2299     }
2300 }
2301
2302 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2303                                        const char *syntax,
2304                                        const char *elementSetName)
2305 {
2306     ZOOM_record_cache rc;
2307     
2308     for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2309     {
2310         if (pos == rc->pos)
2311         {
2312             if (strcmp_null(r->schema, rc->schema))
2313                 continue;
2314             if (strcmp_null(elementSetName,rc->elementSetName))
2315                 continue;
2316             if (strcmp_null(syntax, rc->syntax))
2317                 continue;
2318             return &rc->rec;
2319         }
2320     }
2321     return 0;
2322 }
2323                                              
2324 static void handle_records(ZOOM_connection c, Z_Records *sr,
2325                            int present_phase)
2326 {
2327     ZOOM_resultset resultset;
2328     int *start, *count;
2329     const char *syntax = 0, *elementSetName = 0;
2330
2331     if (!c->tasks)
2332         return ;
2333     switch (c->tasks->which)
2334     {
2335     case ZOOM_TASK_SEARCH:
2336         resultset = c->tasks->u.search.resultset;
2337         start = &c->tasks->u.search.start;
2338         count = &c->tasks->u.search.count;
2339         syntax = c->tasks->u.search.syntax;
2340         elementSetName = c->tasks->u.search.elementSetName;
2341         break;
2342     case ZOOM_TASK_RETRIEVE:
2343         resultset = c->tasks->u.retrieve.resultset;        
2344         start = &c->tasks->u.retrieve.start;
2345         count = &c->tasks->u.retrieve.count;
2346         syntax = c->tasks->u.retrieve.syntax;
2347         elementSetName = c->tasks->u.retrieve.elementSetName;
2348         break;
2349     default:
2350         return;
2351     }
2352     if (sr && sr->which == Z_Records_NSD)
2353         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2354     else if (sr && sr->which == Z_Records_multipleNSD)
2355     {
2356         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2357             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2358         else
2359             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2360     }
2361     else 
2362     {
2363         if (*count + *start > resultset->size)
2364             *count = resultset->size - *start;
2365         if (*count < 0)
2366             *count = 0;
2367         if (sr && sr->which == Z_Records_DBOSD)
2368         {
2369             int i;
2370             NMEM nmem = odr_extract_mem(c->odr_in);
2371             Z_NamePlusRecordList *p =
2372                 sr->u.databaseOrSurDiagnostics;
2373             for (i = 0; i<p->num_records; i++)
2374             {
2375                 record_cache_add(resultset, p->records[i], i + *start,
2376                                  syntax, elementSetName,
2377                                  elementSetName, 0);
2378             }
2379             *count -= i;
2380             if (*count < 0)
2381                 *count = 0;
2382             *start += i;
2383             yaz_log(log_details, 
2384                     "handle_records resultset=%p start=%d count=%d",
2385                     resultset, *start, *count);
2386
2387             /* transfer our response to search_nmem .. we need it later */
2388             nmem_transfer(odr_getmem(resultset->odr), nmem);
2389             nmem_destroy(nmem);
2390             if (present_phase && p->num_records == 0)
2391             {
2392                 /* present response and we didn't get any records! */
2393                 Z_NamePlusRecord *myrec = 
2394                     zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2395                 record_cache_add(resultset, myrec, *start,
2396                                  syntax, elementSetName, 0, 0);
2397             }
2398         }
2399         else if (present_phase)
2400         {
2401             /* present response and we didn't get any records! */
2402             Z_NamePlusRecord *myrec = 
2403                 zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2404             record_cache_add(resultset, myrec, *start, syntax, elementSetName,
2405                              0, 0);
2406         }
2407     }
2408 }
2409
2410 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2411 {
2412     handle_records(c, pr->records, 1);
2413 }
2414
2415 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2416                                        Z_Term *term)
2417 {
2418     switch (term->which)
2419     {
2420     case Z_Term_general:
2421         ZOOM_options_setl(opt, name,
2422                           (const char *)(term->u.general->buf), 
2423                           term->u.general->len);
2424         break;
2425     case Z_Term_characterString:
2426         ZOOM_options_set(opt, name, term->u.characterString);
2427         break;
2428     case Z_Term_numeric:
2429         ZOOM_options_set_int(opt, name, *term->u.numeric);
2430         break;
2431     }
2432 }
2433
2434 static void handle_queryExpression(ZOOM_options opt, const char *name,
2435                                    Z_QueryExpression *exp)
2436 {
2437     char opt_name[80];
2438     
2439     switch (exp->which)
2440     {
2441     case Z_QueryExpression_term:
2442         if (exp->u.term && exp->u.term->queryTerm)
2443         {
2444             sprintf(opt_name, "%s.term", name);
2445             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2446         }
2447         break;
2448     case Z_QueryExpression_query:
2449         break;
2450     }
2451 }
2452
2453 static void handle_searchResult(ZOOM_connection c, ZOOM_resultset resultset,
2454                                 Z_OtherInformation *o)
2455 {
2456     int i;
2457     for (i = 0; o && i < o->num_elements; i++)
2458     {
2459         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2460         {
2461             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2462             
2463             if (ext->which == Z_External_searchResult1)
2464             {
2465                 int j;
2466                 Z_SearchInfoReport *sr = ext->u.searchResult1;
2467                 
2468                 if (sr->num)
2469                     ZOOM_options_set_int(
2470                         resultset->options, "searchresult.size", sr->num);
2471
2472                 for (j = 0; j < sr->num; j++)
2473                 {
2474                     Z_SearchInfoReport_s *ent =
2475                         ext->u.searchResult1->elements[j];
2476                     char pref[80];
2477                     
2478                     sprintf(pref, "searchresult.%d", j);
2479
2480                     if (ent->subqueryId)
2481                     {
2482                         char opt_name[80];
2483                         sprintf(opt_name, "%s.id", pref);
2484                         ZOOM_options_set(resultset->options, opt_name,
2485                                          ent->subqueryId);
2486                     }
2487                     if (ent->subqueryExpression)
2488                     {
2489                         char opt_name[80];
2490                         sprintf(opt_name, "%s.subquery", pref);
2491                         handle_queryExpression(resultset->options, opt_name,
2492                                                ent->subqueryExpression);
2493                     }
2494                     if (ent->subqueryInterpretation)
2495                     {
2496                         char opt_name[80];
2497                         sprintf(opt_name, "%s.interpretation", pref);
2498                         handle_queryExpression(resultset->options, opt_name,
2499                                                ent->subqueryInterpretation);
2500                     }
2501                     if (ent->subqueryRecommendation)
2502                     {
2503                         char opt_name[80];
2504                         sprintf(opt_name, "%s.recommendation", pref);
2505                         handle_queryExpression(resultset->options, opt_name,
2506                                                ent->subqueryRecommendation);
2507                     }
2508                     if (ent->subqueryCount)
2509                     {
2510                         char opt_name[80];
2511                         sprintf(opt_name, "%s.count", pref);
2512                         ZOOM_options_set_int(resultset->options, opt_name,
2513                                              *ent->subqueryCount);
2514                     }                                             
2515                 }
2516             }
2517         }
2518     }
2519 }
2520
2521 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2522 {
2523     ZOOM_resultset resultset;
2524     ZOOM_Event event;
2525
2526     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2527         return ;
2528
2529     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2530     ZOOM_connection_put_event(c, event);
2531
2532     resultset = c->tasks->u.search.resultset;
2533
2534     if (sr->resultSetStatus)
2535     {
2536         ZOOM_options_set_int(resultset->options, "resultSetStatus",
2537                              *sr->resultSetStatus);
2538     }
2539     if (sr->presentStatus)
2540     {
2541         ZOOM_options_set_int(resultset->options, "presentStatus",
2542                              *sr->presentStatus);
2543     }
2544     handle_searchResult(c, resultset, sr->additionalSearchInfo);
2545
2546     resultset->size = *sr->resultCount;
2547     handle_records(c, sr->records, 0);
2548 }
2549
2550 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2551 {
2552     if (res->diagnostics && res->num_diagnostics > 0)
2553         response_diag(c, res->diagnostics[0]);
2554 }
2555
2556 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2557 {
2558     NMEM nmem = odr_extract_mem(c->odr_in);
2559     ZOOM_scanset scan;
2560
2561     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2562         return 0;
2563     scan = c->tasks->u.scan.scan;
2564
2565     if (res->entries && res->entries->nonsurrogateDiagnostics)
2566         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2567     scan->scan_response = res;
2568     scan->srw_scan_response = 0;
2569     nmem_transfer(odr_getmem(scan->odr), nmem);
2570     if (res->stepSize)
2571         ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2572     if (res->positionOfTerm)
2573         ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2574     if (res->scanStatus)
2575         ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2576     if (res->numberOfEntriesReturned)
2577         ZOOM_options_set_int(scan->options, "number",
2578                              *res->numberOfEntriesReturned);
2579     nmem_destroy(nmem);
2580     return 1;
2581 }
2582
2583 static zoom_ret send_sort(ZOOM_connection c,
2584                           ZOOM_resultset resultset)
2585 {
2586     if (c->error)
2587         resultset->r_sort_spec = 0;
2588     if (resultset->r_sort_spec)
2589     {
2590         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2591         Z_SortRequest *req = apdu->u.sortRequest;
2592         
2593         req->num_inputResultSetNames = 1;
2594         req->inputResultSetNames = (Z_InternationalString **)
2595             odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2596         req->inputResultSetNames[0] =
2597             odr_strdup(c->odr_out, resultset->setname);
2598         req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2599         req->sortSequence = resultset->r_sort_spec;
2600         resultset->r_sort_spec = 0;
2601         return send_APDU(c, apdu);
2602     }
2603     return zoom_complete;
2604 }
2605
2606 static zoom_ret send_present(ZOOM_connection c)
2607 {
2608     Z_APDU *apdu = 0;
2609     Z_PresentRequest *req = 0;
2610     int i = 0;
2611     const char *syntax = 0;
2612     const char *elementSetName = 0;
2613     ZOOM_resultset  resultset;
2614     int *start, *count;
2615
2616     if (!c->tasks)
2617     {
2618         yaz_log(log_details, "%p send_present no tasks", c);
2619         return zoom_complete;
2620     }
2621     
2622     switch (c->tasks->which)
2623     {
2624     case ZOOM_TASK_SEARCH:
2625         resultset = c->tasks->u.search.resultset;
2626         start = &c->tasks->u.search.start;
2627         count = &c->tasks->u.search.count;
2628         syntax = c->tasks->u.search.syntax;
2629         elementSetName = c->tasks->u.search.elementSetName;
2630         break;
2631     case ZOOM_TASK_RETRIEVE:
2632         resultset = c->tasks->u.retrieve.resultset;
2633         start = &c->tasks->u.retrieve.start;
2634         count = &c->tasks->u.retrieve.count;
2635         syntax = c->tasks->u.retrieve.syntax;
2636         elementSetName = c->tasks->u.retrieve.elementSetName;
2637         break;
2638     default:
2639         return zoom_complete;
2640     }
2641     yaz_log(log_details, "%p send_present start=%d count=%d",
2642             c, *start, *count);
2643
2644     if (*start < 0 || *count < 0 || *start + *count > resultset->size)
2645     {
2646         set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
2647                        "", 0);
2648     }
2649     if (c->error)                  /* don't continue on error */
2650         return zoom_complete;
2651     yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2652             resultset, *start, *count);
2653
2654     for (i = 0; i < *count; i++)
2655     {
2656         ZOOM_record rec =
2657             record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2658         if (!rec)
2659             break;
2660         else
2661         {
2662             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2663             ZOOM_connection_put_event(c, event);
2664         }
2665     }
2666     *start += i;
2667     *count -= i;
2668
2669     if (*count == 0)
2670     {
2671         yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2672         return zoom_complete;
2673     }
2674
2675     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2676     req = apdu->u.presentRequest;
2677
2678     if (i)
2679         yaz_log(log_details, "%p send_present skip=%d", c, i);
2680
2681     *req->resultSetStartPoint = *start + 1;
2682
2683     if (resultset->step > 0 && resultset->step < *count)
2684         *req->numberOfRecordsRequested = resultset->step;
2685     else
2686         *req->numberOfRecordsRequested = *count;
2687     
2688     if (*req->numberOfRecordsRequested + *start > resultset->size)
2689         *req->numberOfRecordsRequested = resultset->size - *start;
2690     assert(*req->numberOfRecordsRequested > 0);
2691
2692     if (syntax && *syntax)
2693         req->preferredRecordSyntax =
2694             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
2695
2696     if (resultset->schema && *resultset->schema)
2697     {
2698         Z_RecordComposition *compo = (Z_RecordComposition *)
2699             odr_malloc(c->odr_out, sizeof(*compo));
2700
2701         req->recordComposition = compo;
2702         compo->which = Z_RecordComp_complex;
2703         compo->u.complex = (Z_CompSpec *)
2704             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2705         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2706             odr_malloc(c->odr_out, sizeof(bool_t));
2707         *compo->u.complex->selectAlternativeSyntax = 0;
2708
2709         compo->u.complex->generic = (Z_Specification *)
2710             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2711
2712         compo->u.complex->generic->which = Z_Schema_oid;
2713         compo->u.complex->generic->schema.oid = (Odr_oid *)
2714             zoom_yaz_str_to_z3950oid (c, CLASS_SCHEMA, resultset->schema);
2715
2716         if (!compo->u.complex->generic->schema.oid)
2717         {
2718             /* OID wasn't a schema! Try record syntax instead. */
2719
2720             compo->u.complex->generic->schema.oid = (Odr_oid *)
2721                 zoom_yaz_str_to_z3950oid (c, CLASS_RECSYN, resultset->schema);
2722         }
2723         if (elementSetName && *elementSetName)
2724         {
2725             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2726                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2727             compo->u.complex->generic->elementSpec->which =
2728                 Z_ElementSpec_elementSetName;
2729             compo->u.complex->generic->elementSpec->u.elementSetName =
2730                 odr_strdup(c->odr_out, elementSetName);
2731         }
2732         else
2733             compo->u.complex->generic->elementSpec = 0;
2734         compo->u.complex->num_dbSpecific = 0;
2735         compo->u.complex->dbSpecific = 0;
2736         compo->u.complex->num_recordSyntax = 0;
2737         compo->u.complex->recordSyntax = 0;
2738     }
2739     else if (elementSetName && *elementSetName)
2740     {
2741         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2742             odr_malloc(c->odr_out, sizeof(*esn));
2743         Z_RecordComposition *compo = (Z_RecordComposition *)
2744             odr_malloc(c->odr_out, sizeof(*compo));
2745         
2746         esn->which = Z_ElementSetNames_generic;
2747         esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2748         compo->which = Z_RecordComp_simple;
2749         compo->u.simple = esn;
2750         req->recordComposition = compo;
2751     }
2752     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2753     return send_APDU(c, apdu);
2754 }
2755
2756 ZOOM_API(ZOOM_scanset)
2757     ZOOM_connection_scan(ZOOM_connection c, const char *start)
2758 {
2759     ZOOM_scanset s;
2760     ZOOM_query q = ZOOM_query_create();
2761
2762     ZOOM_query_prefix(q, start);
2763
2764     s = ZOOM_connection_scan1(c, q);
2765     ZOOM_query_destroy(q);
2766     return s;
2767
2768 }
2769
2770 ZOOM_API(ZOOM_scanset)
2771     ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
2772 {
2773     ZOOM_scanset scan = 0;
2774
2775     if (!q->z_query)
2776         return 0;
2777     scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
2778     scan->connection = c;
2779     scan->odr = odr_createmem(ODR_DECODE);
2780     scan->options = ZOOM_options_create_with_parent(c->options);
2781     scan->refcount = 1;
2782     scan->scan_response = 0;
2783     scan->srw_scan_response = 0;
2784
2785     scan->query = q;
2786     (q->refcount)++;
2787     scan->databaseNames = set_DatabaseNames(c, c->options,
2788                                             &scan->num_databaseNames,
2789                                             scan->odr);
2790
2791     if (1)
2792     {
2793         ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
2794         task->u.scan.scan = scan;
2795         
2796         (scan->refcount)++;
2797         if (!c->async)
2798         {
2799             while (ZOOM_event(1, &c))
2800                 ;
2801         }
2802     }
2803     return scan;
2804 }
2805
2806 ZOOM_API(void)
2807     ZOOM_scanset_destroy(ZOOM_scanset scan)
2808 {
2809     if (!scan)
2810         return;
2811     (scan->refcount)--;
2812     if (scan->refcount == 0)
2813     {
2814         ZOOM_query_destroy(scan->query);
2815
2816         odr_destroy(scan->odr);
2817         
2818         ZOOM_options_destroy(scan->options);
2819         xfree(scan);
2820     }
2821 }
2822
2823 static zoom_ret send_package(ZOOM_connection c)
2824 {
2825     ZOOM_Event event;
2826
2827     yaz_log(log_details, "%p send_package", c);
2828     if (!c->tasks)
2829         return zoom_complete;
2830     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2831     
2832     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
2833     ZOOM_connection_put_event(c, event);
2834     
2835     c->buf_out = c->tasks->u.package->buf_out;
2836     c->len_out = c->tasks->u.package->len_out;
2837
2838     return do_write(c);
2839 }
2840
2841 static zoom_ret ZOOM_connection_send_scan(ZOOM_connection c)
2842 {
2843     ZOOM_scanset scan;
2844     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2845     Z_ScanRequest *req = apdu->u.scanRequest;
2846
2847     yaz_log(log_details, "%p send_scan", c);
2848     if (!c->tasks)
2849         return zoom_complete;
2850     assert (c->tasks->which == ZOOM_TASK_SCAN);
2851     scan = c->tasks->u.scan.scan;
2852
2853     /* Z39.50 scan can only carry RPN */
2854     if (scan->query->z_query->which == Z_Query_type_1 ||
2855         scan->query->z_query->which == Z_Query_type_101)
2856     {
2857         Z_RPNQuery *rpn = scan->query->z_query->u.type_1;
2858         const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
2859         if (cp)
2860         {
2861             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
2862             if (cd)
2863             {
2864                 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
2865
2866                 yaz_query_charset_convert_rpnquery(
2867                     rpn, c->odr_out, cd);
2868                 yaz_iconv_close(cd);
2869             }
2870         }
2871         req->attributeSet = rpn->attributeSetId;
2872         if (!req->attributeSet)
2873             req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
2874         if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
2875             rpn->RPNStructure->u.simple->which == Z_Operand_APT)
2876         {
2877             req->termListAndStartPoint =
2878                 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
2879         }
2880         else
2881         {
2882             set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
2883             return zoom_complete;
2884         }
2885     }
2886     else
2887     {
2888         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
2889         return zoom_complete;
2890     }
2891
2892     *req->numberOfTermsRequested =
2893         ZOOM_options_get_int(scan->options, "number", 10);
2894
2895     req->preferredPositionInResponse =
2896         odr_intdup(c->odr_out,
2897                    ZOOM_options_get_int(scan->options, "position", 1));
2898
2899     req->stepSize =
2900         odr_intdup(c->odr_out,
2901                    ZOOM_options_get_int(scan->options, "stepSize", 0));
2902     
2903     req->databaseNames = scan->databaseNames;
2904     req->num_databaseNames = scan->num_databaseNames;
2905
2906     return send_APDU(c, apdu);
2907 }
2908
2909 #if YAZ_HAVE_XML2
2910 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
2911 {
2912     ZOOM_scanset scan;
2913     Z_SRW_PDU *sr = 0;
2914     const char *option_val = 0;
2915
2916     if (!c->tasks)
2917         return zoom_complete;
2918     assert (c->tasks->which == ZOOM_TASK_SCAN);
2919     scan = c->tasks->u.scan.scan;
2920         
2921     sr = ZOOM_srw_get_pdu(c, Z_SRW_scan_request);
2922
2923     /* SRU scan can only carry CQL and PQF */
2924     if (scan->query->z_query->which == Z_Query_type_104)
2925     {
2926         sr->u.scan_request->query_type = Z_SRW_query_type_cql;
2927         sr->u.scan_request->scanClause.cql = scan->query->query_string;
2928     }
2929     else if (scan->query->z_query->which == Z_Query_type_1
2930              || scan->query->z_query->which == Z_Query_type_101)
2931     {
2932         sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
2933         sr->u.scan_request->scanClause.pqf = scan->query->query_string;
2934     }
2935     else
2936     {
2937         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
2938         return zoom_complete;
2939     }
2940
2941     sr->u.scan_request->maximumTerms = odr_intdup(
2942         c->odr_out, ZOOM_options_get_int(scan->options, "number", 10));
2943     
2944     sr->u.scan_request->responsePosition = odr_intdup(
2945         c->odr_out, ZOOM_options_get_int(scan->options, "position", 1));
2946     
2947     option_val = ZOOM_options_get(scan->options, "extraArgs");
2948     yaz_encode_sru_extra(sr, c->odr_out, option_val);
2949     return send_srw(c, sr);
2950 }
2951 #else
2952 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
2953 {
2954     return zoom_complete;
2955 }
2956 #endif
2957
2958
2959 ZOOM_API(size_t)
2960     ZOOM_scanset_size(ZOOM_scanset scan)
2961 {
2962     if (!scan)
2963         return 0;
2964
2965     if (scan->scan_response && scan->scan_response->entries)
2966         return scan->scan_response->entries->num_entries;
2967     else if (scan->srw_scan_response)
2968         return scan->srw_scan_response->num_terms;
2969     return 0;
2970 }
2971
2972 static void ZOOM_scanset_term_x(ZOOM_scanset scan, size_t pos,
2973                                 int *occ,
2974                                 const char **value_term, size_t *value_len,
2975                                 const char **disp_term, size_t *disp_len)
2976 {
2977     size_t noent = ZOOM_scanset_size(scan);
2978     
2979     *value_term = 0;
2980     *value_len = 0;
2981
2982     *disp_term = 0;
2983     *disp_len = 0;
2984
2985     *occ = 0;
2986     if (pos >= noent || pos < 0)
2987         return;
2988     if (scan->scan_response)
2989     {
2990         Z_ScanResponse *res = scan->scan_response;
2991         if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2992         {
2993             Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2994             
2995             *value_term = (const char *) t->term->u.general->buf;
2996             *value_len = t->term->u.general->len;
2997             if (t->displayTerm)
2998             {
2999                 *disp_term = t->displayTerm;
3000                 *disp_len = strlen(*disp_term);
3001             }
3002             else if (t->term->which == Z_Term_general)
3003             {
3004                 *disp_term = (const char *) t->term->u.general->buf;
3005                 *disp_len = t->term->u.general->len;
3006             }
3007             *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
3008         }
3009     }
3010     if (scan->srw_scan_response)
3011     {
3012         Z_SRW_scanResponse *res = scan->srw_scan_response;
3013         Z_SRW_scanTerm *t = res->terms + pos;
3014         if (t)
3015         {
3016             *value_term = t->value;
3017             *value_len = strlen(*value_term);
3018
3019             if (t->displayTerm)
3020                 *disp_term = t->displayTerm;
3021             else
3022                 *disp_term = t->value;
3023             *disp_len = strlen(*disp_term);
3024             *occ = t->numberOfRecords ? *t->numberOfRecords : 0;
3025         }
3026     }
3027 }
3028
3029 ZOOM_API(const char *)
3030     ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
3031                       int *occ, int *len)
3032 {
3033     const char *value_term = 0;
3034     size_t value_len = 0;
3035     const char *disp_term = 0;
3036     size_t disp_len = 0;
3037
3038     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3039                         &disp_term, &disp_len);
3040     
3041     *len = value_len;
3042     return value_term;
3043 }
3044
3045 ZOOM_API(const char *)
3046     ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
3047                               int *occ, int *len)
3048 {
3049     const char *value_term = 0;
3050     size_t value_len = 0;
3051     const char *disp_term = 0;
3052     size_t disp_len = 0;
3053
3054     ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3055                         &disp_term, &disp_len);
3056     
3057     *len = disp_len;
3058     return disp_term;
3059 }
3060
3061 ZOOM_API(const char *)
3062     ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
3063 {
3064     return ZOOM_options_get(scan->options, key);
3065 }
3066
3067 ZOOM_API(void)
3068     ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
3069                             const char *val)
3070 {
3071     ZOOM_options_set(scan->options, key, val);
3072 }
3073
3074 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
3075 {
3076     const char *str;
3077     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
3078     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3079     
3080     str = ZOOM_options_get(p->options, "package-name");
3081     if (str && *str)
3082         req->packageName = odr_strdup(p->odr_out, str);
3083     
3084     str = ZOOM_options_get(p->options, "user-id");
3085     if (str)
3086         req->userId = odr_strdup_null(p->odr_out, str);
3087     
3088     req->packageType = odr_oiddup(p->odr_out, oid);
3089
3090     str = ZOOM_options_get(p->options, "function");
3091     if (str)
3092     {
3093         if (!strcmp (str, "create"))
3094             *req->function = Z_ExtendedServicesRequest_create;
3095         if (!strcmp (str, "delete"))
3096             *req->function = Z_ExtendedServicesRequest_delete;
3097         if (!strcmp (str, "modify"))
3098             *req->function = Z_ExtendedServicesRequest_modify;
3099     }
3100
3101     str = ZOOM_options_get(p->options, "waitAction");
3102     if (str)
3103     {
3104         if (!strcmp (str, "wait"))
3105             *req->waitAction = Z_ExtendedServicesRequest_wait;
3106         if (!strcmp (str, "waitIfPossible"))
3107             *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
3108         if (!strcmp (str, "dontWait"))
3109             *req->waitAction = Z_ExtendedServicesRequest_dontWait;
3110         if (!strcmp (str, "dontReturnPackage"))
3111             *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
3112     }
3113     return apdu;
3114 }
3115
3116 static const char *ill_array_lookup(void *clientData, const char *idx)
3117 {
3118     ZOOM_package p = (ZOOM_package) clientData;
3119     return ZOOM_options_get(p->options, idx+4);
3120 }
3121
3122 static Z_External *encode_ill_request(ZOOM_package p)
3123 {
3124     ODR out = p->odr_out;
3125     ILL_Request *req;
3126     Z_External *r = 0;
3127     struct ill_get_ctl ctl;
3128         
3129     ctl.odr = p->odr_out;
3130     ctl.clientData = p;
3131     ctl.f = ill_array_lookup;
3132         
3133     req = ill_get_ILLRequest(&ctl, "ill", 0);
3134         
3135     if (!ill_Request(out, &req, 0, 0))
3136     {
3137         int ill_request_size;
3138         char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
3139         if (ill_request_buf)
3140             odr_setbuf(out, ill_request_buf, ill_request_size, 1);
3141         return 0;
3142     }
3143     else
3144     {
3145         int illRequest_size = 0;
3146         char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
3147                 
3148         r = (Z_External *) odr_malloc(out, sizeof(*r));
3149         r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
3150         r->indirect_reference = 0;
3151         r->descriptor = 0;
3152         r->which = Z_External_single;
3153                 
3154         r->u.single_ASN1_type =
3155             odr_create_Odr_oct(out,
3156                                (unsigned char *)illRequest_buf,
3157                                illRequest_size);
3158     }
3159     return r;
3160 }
3161
3162 static Z_ItemOrder *encode_item_order(ZOOM_package p)
3163 {
3164     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
3165     const char *str;
3166     int len;
3167     
3168     req->which = Z_IOItemOrder_esRequest;
3169     req->u.esRequest = (Z_IORequest *) 
3170         odr_malloc(p->odr_out,sizeof(Z_IORequest));
3171
3172     /* to keep part ... */
3173     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
3174         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
3175     req->u.esRequest->toKeep->supplDescription = 0;
3176     req->u.esRequest->toKeep->contact = (Z_IOContact *)
3177         odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
3178         
3179     str = ZOOM_options_get(p->options, "contact-name");
3180     req->u.esRequest->toKeep->contact->name =
3181         odr_strdup_null(p->odr_out, str);
3182         
3183     str = ZOOM_options_get(p->options, "contact-phone");
3184     req->u.esRequest->toKeep->contact->phone =
3185         odr_strdup_null(p->odr_out, str);
3186         
3187     str = ZOOM_options_get(p->options, "contact-email");
3188     req->u.esRequest->toKeep->contact->email =
3189         odr_strdup_null(p->odr_out, str);
3190         
3191     req->u.esRequest->toKeep->addlBilling = 0;
3192         
3193     /* not to keep part ... */
3194     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
3195         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
3196         
3197     str = ZOOM_options_get(p->options, "itemorder-setname");
3198     if (!str)
3199         str = "default";
3200
3201     if (!*str) 
3202         req->u.esRequest->notToKeep->resultSetItem = 0;
3203     else
3204     {
3205         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
3206             odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
3207
3208         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
3209             odr_strdup(p->odr_out, str);
3210         req->u.esRequest->notToKeep->resultSetItem->item =
3211             (int *) odr_malloc(p->odr_out, sizeof(int));
3212         
3213         str = ZOOM_options_get(p->options, "itemorder-item");
3214         *req->u.esRequest->notToKeep->resultSetItem->item =
3215             (str ? atoi(str) : 1);
3216     }
3217
3218     str = ZOOM_options_getl(p->options, "doc", &len);
3219     if (str)
3220     {
3221         req->u.esRequest->notToKeep->itemRequest =
3222             z_ext_record_xml(p->odr_out, str, len);
3223     }
3224     else
3225         req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
3226     
3227     return req;
3228 }
3229
3230 Z_APDU *create_admin_package(ZOOM_package p, int type, 
3231                              Z_ESAdminOriginPartToKeep **toKeepP,
3232                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
3233 {
3234     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
3235     if (apdu)
3236     {
3237         Z_ESAdminOriginPartToKeep  *toKeep;
3238         Z_ESAdminOriginPartNotToKeep  *notToKeep;
3239         Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3240         const char *first_db = "Default";
3241         int num_db;
3242         char **db = set_DatabaseNames(p->connection, p->options, &num_db,
3243                                       p->odr_out);
3244         if (num_db > 0)
3245             first_db = db[0];
3246             
3247         r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
3248         r->descriptor = 0;
3249         r->indirect_reference = 0;
3250         r->which = Z_External_ESAdmin;
3251         
3252         r->u.adminService = (Z_Admin *)
3253             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
3254         r->u.adminService->which = Z_Admin_esRequest;
3255         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
3256             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
3257         
3258         toKeep = r->u.adminService->u.esRequest->toKeep =
3259             (Z_ESAdminOriginPartToKeep *) 
3260             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
3261         toKeep->which = type;
3262         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3263         toKeep->u.create = odr_nullval();
3264         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3265         
3266         r->u.adminService->u.esRequest->notToKeep = notToKeep =
3267             (Z_ESAdminOriginPartNotToKeep *)
3268             odr_malloc(p->odr_out,
3269                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
3270         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
3271         notToKeep->u.recordsWillFollow = odr_nullval();
3272         if (toKeepP)
3273             *toKeepP = toKeep;
3274         if (notToKeepP)
3275             *notToKeepP = notToKeep;
3276     }
3277     return apdu;
3278 }
3279
3280 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
3281 {
3282     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
3283     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3284     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
3285     int len;
3286     const char *doc = ZOOM_options_getl(p->options, "doc", &len);
3287
3288     if (!doc)
3289     {
3290         doc = "";
3291         len = 0;
3292     }
3293
3294     req->taskSpecificParameters = ext;
3295     ext->direct_reference = req->packageType;
3296     ext->descriptor = 0;
3297     ext->indirect_reference = 0;
3298     
3299     ext->which = Z_External_octet;
3300     ext->u.single_ASN1_type =
3301         odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc, len);
3302     return apdu;
3303 }
3304
3305 static Z_APDU *create_update_package(ZOOM_package p)
3306 {
3307     Z_APDU *apdu = 0;
3308     const char *first_db = "Default";
3309     int num_db;
3310     char **db = set_DatabaseNames(p->connection, p->options, &num_db, p->odr_out);
3311     const char *action = ZOOM_options_get(p->options, "action");
3312     int recordIdOpaque_len;
3313     const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
3314         &recordIdOpaque_len);
3315     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
3316     int record_len;
3317     const char *record_buf = ZOOM_options_getl(p->options, "record",
3318         &record_len);
3319     int recordOpaque_len;
3320     const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
3321         &recordOpaque_len);
3322     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
3323     const char *version = ZOOM_options_get(p->options, "updateVersion");
3324
3325     const char *correlationInfo_note =
3326         ZOOM_options_get(p->options, "correlationInfo.note");
3327     const char *correlationInfo_id =
3328         ZOOM_options_get(p->options, "correlationInfo.id");
3329     int action_no = -1;
3330     Odr_oid *syntax_oid = 0;
3331     const Odr_oid *package_oid = yaz_oid_extserv_database_update;
3332
3333     if (!version)
3334         version = "3";
3335     if (!syntax_str)
3336         syntax_str = "xml";
3337     if (!record_buf && !recordOpaque_buf)
3338     {
3339         record_buf = "void";
3340         record_len = 4;
3341         syntax_str = "SUTRS";
3342     }
3343
3344     if (syntax_str)
3345     {
3346         syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
3347                                            CLASS_RECSYN, syntax_str,
3348                                            p->odr_out);
3349     }
3350     if (!syntax_oid)
3351         return 0;
3352
3353     if (num_db > 0)
3354         first_db = db[0];
3355     
3356     switch(*version)
3357     {
3358     case '1':
3359         package_oid = yaz_oid_extserv_database_update_first_version;
3360         /* old update does not support specialUpdate */
3361         if (!action)
3362             action = "recordInsert";
3363         break;
3364     case '2':
3365         if (!action)
3366             action = "specialUpdate";
3367         package_oid = yaz_oid_extserv_database_update_second_version;
3368         break;
3369     case '3':
3370         if (!action)
3371             action = "specialUpdate";
3372         package_oid = yaz_oid_extserv_database_update;
3373         break;
3374     default:
3375         return 0;
3376     }
3377     
3378     if (!strcmp(action, "recordInsert"))
3379         action_no = Z_IUOriginPartToKeep_recordInsert;
3380     else if (!strcmp(action, "recordReplace"))
3381         action_no = Z_IUOriginPartToKeep_recordReplace;
3382     else if (!strcmp(action, "recordDelete"))
3383         action_no = Z_IUOriginPartToKeep_recordDelete;
3384     else if (!strcmp(action, "elementUpdate"))
3385         action_no = Z_IUOriginPartToKeep_elementUpdate;
3386     else if (!strcmp(action, "specialUpdate"))
3387         action_no = Z_IUOriginPartToKeep_specialUpdate;
3388     else
3389         return 0;
3390
3391     apdu = create_es_package(p, package_oid);
3392     if (apdu)
3393     {
3394         Z_IUOriginPartToKeep *toKeep;
3395         Z_IUSuppliedRecords *notToKeep;
3396         Z_External *r = (Z_External *)
3397             odr_malloc(p->odr_out, sizeof(*r));
3398         const char *elementSetName =
3399             ZOOM_options_get(p->options, "elementSetName");
3400         
3401         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3402         
3403         r->direct_reference = odr_oiddup(p->odr_out, package_oid);
3404         r->descriptor = 0;
3405         r->which = Z_External_update;
3406         r->indirect_reference = 0;
3407         r->u.update = (Z_IUUpdate *)
3408             odr_malloc(p->odr_out, sizeof(*r->u.update));
3409         
3410         r->u.update->which = Z_IUUpdate_esRequest;
3411         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3412             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3413         toKeep = r->u.update->u.esRequest->toKeep = 
3414             (Z_IUOriginPartToKeep *)
3415             odr_malloc(p->odr_out, sizeof(*toKeep));
3416         
3417         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3418         toKeep->schema = 0;
3419         
3420         toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
3421             
3422         toKeep->actionQualifier = 0;
3423         toKeep->action = odr_intdup(p->odr_out, action_no);
3424         
3425         notToKeep = r->u.update->u.esRequest->notToKeep = 
3426             (Z_IUSuppliedRecords *)
3427             odr_malloc(p->odr_out, sizeof(*notToKeep));
3428         notToKeep->num = 1;
3429         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3430             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3431         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3432             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3433         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3434         if (recordIdOpaque)
3435         {
3436             notToKeep->elements[0]->u.opaque = 
3437                 odr_create_Odr_oct(p->odr_out,
3438                                    (const unsigned char *) recordIdOpaque,
3439                                    recordIdOpaque_len);
3440         }
3441         else if (recordIdNumber)
3442         {
3443             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3444             
3445             notToKeep->elements[0]->u.number =
3446                 odr_intdup(p->odr_out, atoi(recordIdNumber));
3447         }
3448         else
3449             notToKeep->elements[0]->u.opaque = 0;
3450         notToKeep->elements[0]->supplementalId = 0;
3451         if (correlationInfo_note || correlationInfo_id)
3452         {
3453             Z_IUCorrelationInfo *ci;
3454             ci = notToKeep->elements[0]->correlationInfo =
3455                 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
3456             ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
3457             ci->id = correlationInfo_id ?
3458                 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
3459         }
3460         else
3461             notToKeep->elements[0]->correlationInfo = 0;
3462         if (recordOpaque_buf)
3463         {
3464             notToKeep->elements[0]->record =
3465                 z_ext_record_oid_any(p->odr_out, syntax_oid,
3466                                  recordOpaque_buf, recordOpaque_len);
3467         }
3468         else
3469         {
3470             notToKeep->elements[0]->record =
3471                 z_ext_record_oid(p->odr_out, syntax_oid,
3472                                  record_buf, record_len);
3473         }
3474     }
3475     if (0 && apdu)
3476     {
3477         ODR print = odr_createmem(ODR_PRINT);
3478
3479         z_APDU(print, &apdu, 0, 0);
3480         odr_destroy(print);
3481     }
3482     return apdu;
3483 }
3484
3485 ZOOM_API(void)
3486     ZOOM_package_send(ZOOM_package p, const char *type)
3487 {
3488     Z_APDU *apdu = 0;
3489     ZOOM_connection c;
3490     if (!p)
3491         return;
3492     c = p->connection;
3493     odr_reset(p->odr_out);
3494     xfree(p->buf_out);
3495     p->buf_out = 0;
3496     if (!strcmp(type, "itemorder"))
3497     {
3498         apdu = create_es_package(p, yaz_oid_extserv_item_order);
3499         if (apdu)
3500         {
3501             Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3502             
3503             r->direct_reference = 
3504                 odr_oiddup(p->odr_out, yaz_oid_extserv_item_order);
3505             r->descriptor = 0;
3506             r->which = Z_External_itemOrder;
3507             r->indirect_reference = 0;
3508             r->u.itemOrder = encode_item_order(p);
3509
3510             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3511         }
3512     }
3513     else if (!strcmp(type, "create"))  /* create database */
3514     {
3515         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3516                                     0, 0);
3517     }   
3518     else if (!strcmp(type, "drop"))  /* drop database */
3519     {
3520         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3521                                     0, 0);
3522     }
3523     else if (!strcmp(type, "commit"))  /* commit changes */
3524     {
3525         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3526                                     0, 0);
3527     }
3528     else if (!strcmp(type, "update")) /* update record(s) */
3529     {
3530         apdu = create_update_package(p);
3531     }
3532     else if (!strcmp(type, "xmlupdate"))
3533     {
3534         apdu = create_xmlupdate_package(p);
3535     }
3536     if (apdu)
3537     {
3538         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3539         {
3540             char *buf;
3541
3542             ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
3543             task->u.package = p;
3544             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3545             p->buf_out = (char *) xmalloc(p->len_out);
3546             memcpy(p->buf_out, buf, p->len_out);
3547             
3548             (p->refcount)++;
3549             if (!c->async)
3550             {
3551                 while (ZOOM_event(1, &c))
3552                     ;
3553             }
3554         }
3555     }
3556 }
3557
3558 ZOOM_API(ZOOM_package)
3559     ZOOM_connection_package(ZOOM_connection c, ZOOM_options options)
3560 {
3561     ZOOM_package p = (ZOOM_package) xmalloc(sizeof(*p));
3562
3563     p->connection = c;
3564     p->odr_out = odr_createmem(ODR_ENCODE);
3565     p->options = ZOOM_options_create_with_parent2(options, c->options);
3566     p->refcount = 1;
3567     p->buf_out = 0;
3568     p->len_out = 0;
3569     return p;
3570 }
3571
3572 ZOOM_API(void)
3573     ZOOM_package_destroy(ZOOM_package p)
3574 {
3575     if (!p)
3576         return;
3577     (p->refcount)--;
3578     if (p->refcount == 0)
3579     {
3580         odr_destroy(p->odr_out);
3581         xfree(p->buf_out);
3582         
3583         ZOOM_options_destroy(p->options);
3584         xfree(p);
3585     }
3586 }
3587
3588 ZOOM_API(const char *)
3589     ZOOM_package_option_get(ZOOM_package p, const char *key)
3590 {
3591     return ZOOM_options_get(p->options, key);
3592 }
3593
3594 ZOOM_API(const char *)
3595     ZOOM_package_option_getl(ZOOM_package p, const char *key, int *lenp)
3596 {
3597     return ZOOM_options_getl(p->options, key, lenp);
3598 }
3599
3600 ZOOM_API(void)
3601     ZOOM_package_option_set(ZOOM_package p, const char *key,
3602                             const char *val)
3603 {
3604     ZOOM_options_set(p->options, key, val);
3605 }
3606
3607 ZOOM_API(void)
3608     ZOOM_package_option_setl(ZOOM_package p, const char *key,
3609                              const char *val, int len)
3610 {
3611     ZOOM_options_setl(p->options, key, val, len);
3612 }
3613
3614 static int ZOOM_connection_exec_task(ZOOM_connection c)
3615 {
3616     ZOOM_task task = c->tasks;
3617     zoom_ret ret = zoom_complete;
3618
3619     if (!task)
3620         return 0;
3621     yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3622             c, task->which, task->running);
3623     if (c->error != ZOOM_ERROR_NONE)
3624     {
3625         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3626                 "removing tasks because of error = %d", c, c->error);
3627         ZOOM_connection_remove_tasks(c);
3628         return 0;
3629     }
3630     if (task->running)
3631     {
3632         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3633                 "task already running", c);
3634         return 0;
3635     }
3636     task->running = 1;
3637     ret = zoom_complete;
3638     if (c->cs || task->which == ZOOM_TASK_CONNECT)
3639     {
3640         switch (task->which)
3641         {
3642         case ZOOM_TASK_SEARCH:
3643             if (c->proto == PROTO_HTTP)
3644                 ret = ZOOM_connection_srw_send_search(c);
3645             else
3646                 ret = ZOOM_connection_send_search(c);
3647             break;
3648         case ZOOM_TASK_RETRIEVE:
3649             if (c->proto == PROTO_HTTP)
3650                 ret = ZOOM_connection_srw_send_search(c);
3651             else
3652                 ret = send_present(c);
3653             break;
3654         case ZOOM_TASK_CONNECT:
3655             ret = do_connect(c);
3656             break;
3657         case ZOOM_TASK_SCAN:
3658             if (c->proto == PROTO_HTTP)
3659                 ret = ZOOM_connection_srw_send_scan(c);
3660             else
3661                 ret = ZOOM_connection_send_scan(c);
3662             break;
3663         case ZOOM_TASK_PACKAGE:
3664             ret = send_package(c);
3665             break;
3666         case ZOOM_TASK_SORT:
3667             c->tasks->u.sort.resultset->r_sort_spec = 
3668                 c->tasks->u.sort.q->sort_spec;
3669             ret = send_sort(c, c->tasks->u.sort.resultset);
3670             break;
3671         }
3672     }
3673     else
3674     {
3675         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3676                 "remove tasks because no connection exist", c);
3677         ZOOM_connection_remove_tasks(c);
3678     }
3679     if (ret == zoom_complete)
3680     {
3681         yaz_log(log_details, "%p ZOOM_connection_exec_task "
3682                 "task removed (complete)", c);
3683         ZOOM_connection_remove_task(c);
3684         return 0;
3685     }
3686     yaz_log(log_details, "%p ZOOM_connection_exec_task "
3687             "task pending", c);
3688     return 1;
3689 }
3690
3691 static zoom_ret send_sort_present(ZOOM_connection c)
3692 {
3693     zoom_ret r = zoom_complete;
3694
3695     if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3696         r = send_sort(c, c->tasks->u.search.resultset);
3697     if (r == zoom_complete)
3698         r = send_present(c);
3699     return r;
3700 }
3701
3702 static int es_response_taskpackage_update(ZOOM_connection c,
3703                 Z_IUUpdateTaskPackage *utp)
3704 {
3705         if (utp && utp->targetPart)
3706         {
3707                 Z_IUTargetPart *targetPart = utp->targetPart;
3708                 switch ( *targetPart->updateStatus ) {
3709                         case Z_IUTargetPart_success:
3710                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "success");
3711                                 break;
3712                         case Z_IUTargetPart_partial:
3713                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "partial");
3714                                 break;
3715                         case Z_IUTargetPart_failure:
3716                                 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "failure");
3717                                 if (targetPart->globalDiagnostics && targetPart->num_globalDiagnostics > 0)
3718                                         response_diag(c, targetPart->globalDiagnostics[0]);
3719                                 break;
3720                 }
3721                 // NOTE: Individual record status, surrogate diagnostics, and supplemental diagnostics ARE NOT REPORTED.
3722         }
3723     return 1;
3724 }
3725
3726 static int es_response_taskpackage(ZOOM_connection c,
3727                                    Z_TaskPackage *taskPackage)
3728 {
3729         // targetReference
3730         Odr_oct *id = taskPackage->targetReference;
3731         if (id)
3732                 ZOOM_options_setl(c->tasks->u.package->options,
3733                                                         "targetReference", (char*) id->buf, id->len);
3734         
3735         // taskStatus
3736         switch ( *taskPackage->taskStatus ) {
3737                 case Z_TaskPackage_pending:
3738                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "pending");
3739                         break;
3740                 case Z_TaskPackage_active:
3741                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "active");
3742                         break;
3743                 case Z_TaskPackage_complete:
3744                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "complete");
3745                         break;
3746                 case Z_TaskPackage_aborted:
3747                         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "aborted");
3748                         if ( taskPackage->num_packageDiagnostics && taskPackage->packageDiagnostics )
3749                                 response_diag(c, taskPackage->packageDiagnostics[0]);
3750                         break;
3751         }
3752         
3753         // taskSpecificParameters
3754         // NOTE: Only Update implemented, no others.
3755         if ( taskPackage->taskSpecificParameters->which == Z_External_update ) {
3756                         Z_IUUpdateTaskPackage *utp = taskPackage->taskSpecificParameters->u.update->u.taskPackage;
3757                         es_response_taskpackage_update(c, utp);
3758         }
3759         return 1;
3760 }
3761
3762
3763 static int es_response(ZOOM_connection c,
3764                        Z_ExtendedServicesResponse *res)
3765 {
3766     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3767         return 0;
3768     switch (*res->operationStatus) {
3769         case Z_ExtendedServicesResponse_done:
3770             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "done");
3771             break;
3772         case Z_ExtendedServicesResponse_accepted:
3773             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "accepted");
3774             break;
3775         case Z_ExtendedServicesResponse_failure:
3776             ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "failure");
3777             if (res->diagnostics && res->num_diagnostics > 0)
3778                 response_diag(c, res->diagnostics[0]);
3779             break;
3780     }
3781     if (res->taskPackage &&
3782         res->taskPackage->which == Z_External_extendedService)
3783     {
3784         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
3785         es_response_taskpackage(c, taskPackage);
3786     }
3787     if (res->taskPackage && 
3788         res->taskPackage->which == Z_External_octet)
3789     {
3790         Odr_oct *doc = res->taskPackage->u.octet_aligned;
3791         ZOOM_options_setl(c->tasks->u.package->options,
3792                           "xmlUpdateDoc", (char*) doc->buf, doc->len);
3793     }
3794     return 1;
3795 }
3796
3797 static void interpret_init_diag(ZOOM_connection c,
3798                                 Z_DiagnosticFormat *diag)
3799 {
3800     if (diag->num > 0)
3801     {
3802         Z_DiagnosticFormat_s *ds = diag->elements[0];
3803         if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
3804             response_default_diag(c, ds->u.defaultDiagRec);
3805     }
3806 }
3807
3808
3809 static void interpret_otherinformation_field(ZOOM_connection c,
3810                                              Z_OtherInformation *ui)
3811 {
3812     int i;
3813     for (i = 0; i < ui->num_elements; i++)
3814     {
3815         Z_OtherInformationUnit *unit = ui->list[i];
3816         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
3817             unit->information.externallyDefinedInfo &&
3818             unit->information.externallyDefinedInfo->which ==
3819             Z_External_diag1) 
3820         {
3821             interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
3822         } 
3823     }
3824 }
3825
3826
3827 static void set_init_option(const char *name, void *clientData) {
3828     ZOOM_connection c = (ZOOM_connection) clientData;
3829     char buf[80];
3830
3831     sprintf(buf, "init_opt_%.70s", name);
3832     ZOOM_connection_option_set(c, buf, "1");
3833 }
3834
3835
3836 static void recv_apdu(ZOOM_connection c, Z_APDU *apdu)
3837 {
3838     Z_InitResponse *initrs;
3839     
3840     ZOOM_connection_set_mask(c, 0);
3841     yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
3842     switch(apdu->which)
3843     {
3844     case Z_APDU_initResponse:
3845         yaz_log(log_api, "%p recv_apdu: Received Init response", c);
3846         initrs = apdu->u.initResponse;
3847         ZOOM_connection_option_set(c, "serverImplementationId",
3848                                    initrs->implementationId ?
3849                                    initrs->implementationId : "");
3850         ZOOM_connection_option_set(c, "serverImplementationName",
3851                                    initrs->implementationName ?
3852                                    initrs->implementationName : "");
3853         ZOOM_connection_option_set(c, "serverImplementationVersion",
3854                                    initrs->implementationVersion ?
3855                                    initrs->implementationVersion : "");
3856         /* Set the three old options too, for old applications */
3857         ZOOM_connection_option_set(c, "targetImplementationId",
3858                                    initrs->implementationId ?
3859                                    initrs->implementationId : "");
3860         ZOOM_connection_option_set(c, "targetImplementationName",
3861                                    initrs->implementationName ?
3862                                    initrs->implementationName : "");
3863         ZOOM_connection_option_set(c, "targetImplementationVersion",
3864                                    initrs->implementationVersion ?
3865                                    initrs->implementationVersion : "");
3866
3867         /* Make initrs->options available as ZOOM-level options */
3868         yaz_init_opt_decode(initrs->options, set_init_option, (void*) c);
3869
3870         if (!*initrs->result)
3871         {
3872             Z_External *uif = initrs->userInformationField;
3873
3874             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
3875
3876             if (uif && uif->which == Z_External_userInfo1)
3877                 interpret_otherinformation_field(c, uif->u.userInfo1);
3878         }
3879         else
3880         {
3881             char *cookie =
3882                 yaz_oi_get_string_oid(&apdu->u.initResponse->otherInfo,
3883                                       yaz_oid_userinfo_cookie, 1, 0);
3884             xfree(c->cookie_in);
3885             c->cookie_in = 0;
3886             if (cookie)
3887                 c->cookie_in = xstrdup(cookie);
3888             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
3889                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
3890                 c->support_named_resultsets = 1;
3891             if (c->tasks)
3892             {
3893                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
3894                 ZOOM_connection_remove_task(c);
3895             }
3896             ZOOM_connection_exec_task(c);
3897         }
3898         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
3899         {
3900             NMEM tmpmem = nmem_create();
3901             Z_CharSetandLanguageNegotiation *p =
3902                 yaz_get_charneg_record(initrs->otherInfo);
3903             
3904             if (p)
3905             {
3906                 char *charset = NULL, *lang = NULL;
3907                 int sel;
3908                 
3909                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
3910                 yaz_log(log_details, "%p recv_apdu target accepted: "
3911                         "charset %s, language %s, select %d",
3912                         c,
3913                         charset ? charset : "none", lang ? lang : "none", sel);
3914                 if (charset)
3915                     ZOOM_connection_option_set(c, "negotiation-charset",
3916                                                charset);
3917                 if (lang)
3918                     ZOOM_connection_option_set(c, "negotiation-lang",
3919                                                lang);
3920
3921                 ZOOM_connection_option_set(
3922                     c,  "negotiation-charset-in-effect-for-records",
3923                     (sel != 0) ? "1" : "0");
3924                 nmem_destroy(tmpmem);
3925             }
3926         }       
3927         break;
3928     case Z_APDU_searchResponse:
3929         yaz_log(log_api, "%p recv_apdu Search response", c);
3930         handle_search_response(c, apdu->u.searchResponse);
3931         if (send_sort_present(c) == zoom_complete)
3932             ZOOM_connection_remove_task(c);
3933         break;
3934     case Z_APDU_presentResponse:
3935         yaz_log(log_api, "%p recv_apdu Present response", c);
3936         handle_present_response(c, apdu->u.presentResponse);
3937         if (send_present(c) == zoom_complete)
3938             ZOOM_connection_remove_task(c);
3939         break;
3940     case Z_APDU_sortResponse:
3941         yaz_log(log_api, "%p recv_apdu Sort response", c);
3942         sort_response(c, apdu->u.sortResponse);
3943         if (send_present(c) == zoom_complete)
3944             ZOOM_connection_remove_task(c);
3945         break;
3946     case Z_APDU_scanResponse:
3947         yaz_log(log_api, "%p recv_apdu Scan response", c);
3948         scan_response(c, apdu->u.scanResponse);
3949         ZOOM_connection_remove_task(c);
3950         break;
3951     case Z_APDU_extendedServicesResponse:
3952         yaz_log(log_api, "%p recv_apdu Extended Services response", c);
3953         es_response(c, apdu->u.extendedServicesResponse);
3954         ZOOM_connection_remove_task(c);
3955         break;
3956     case Z_APDU_close:
3957         yaz_log(log_api, "%p recv_apdu Close PDU", c);
3958         if (!ZOOM_test_reconnect(c))
3959         {
3960             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3961             do_close(c);
3962         }
3963         break;
3964     default:
3965         yaz_log(log_api, "%p Received unknown PDU", c);
3966         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3967         do_close(c);
3968     }
3969 }
3970
3971 #if YAZ_HAVE_XML2
3972 static zoom_ret handle_srw_response(ZOOM_connection c,
3973                                     Z_SRW_searchRetrieveResponse *res)
3974 {
3975     ZOOM_resultset resultset = 0;
3976     int i;
3977     NMEM nmem;
3978     ZOOM_Event event;
3979     int *start, *count;
3980     const char *syntax, *elementSetName;
3981
3982     if (!c->tasks)
3983         return zoom_complete;
3984
3985     switch(c->tasks->which)
3986     {
3987     case ZOOM_TASK_SEARCH:
3988         resultset = c->tasks->u.search.resultset;
3989         start = &c->tasks->u.search.start;
3990         count = &c->tasks->u.search.count;
3991         syntax = c->tasks->u.search.syntax;
3992         elementSetName = c->tasks->u.search.elementSetName;        
3993
3994         if (!c->tasks->u.search.recv_search_fired)
3995         {
3996             event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
3997             ZOOM_connection_put_event(c, event);
3998             c->tasks->u.search.recv_search_fired = 1;
3999         }
4000         break;
4001     case ZOOM_TASK_RETRIEVE:
4002         resultset = c->tasks->u.retrieve.resultset;
4003         start = &c->tasks->u.retrieve.start;
4004         count = &c->tasks->u.retrieve.count;
4005         syntax = c->tasks->u.retrieve.syntax;
4006         elementSetName = c->tasks->u.retrieve.elementSetName;
4007         break;
4008     default:
4009         return zoom_complete;
4010     }
4011
4012     resultset->size = 0;
4013
4014     if (res->resultSetId)
4015         ZOOM_resultset_option_set(resultset, "resultSetId", res->resultSetId);
4016
4017     yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
4018
4019     if (res->num_diagnostics > 0)
4020     {
4021         set_SRU_error(c, &res->diagnostics[0]);
4022     }
4023     else
4024     {
4025         if (res->numberOfRecords)
4026             resultset->size = *res->numberOfRecords;
4027         for (i = 0; i<res->num_records; i++)
4028         {
4029             int pos;
4030             Z_SRW_record *sru_rec;
4031             Z_SRW_diagnostic *diag = 0;
4032             int num_diag;
4033             
4034             Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
4035                 odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
4036             
4037             if (res->records[i].recordPosition && 
4038                 *res->records[i].recordPosition > 0)
4039                 pos = *res->records[i].recordPosition - 1;
4040             else
4041                 pos = *start + i;
4042             
4043             sru_rec = &res->records[i];
4044             
4045             npr->databaseName = 0;
4046             npr->which = Z_NamePlusRecord_databaseRecord;
4047             npr->u.databaseRecord = (Z_External *)
4048                 odr_malloc(c->odr_in, sizeof(Z_External));
4049             npr->u.databaseRecord->descriptor = 0;
4050             npr->u.databaseRecord->direct_reference =
4051                 odr_oiddup(c->odr_in, yaz_oid_recsyn_xml);
4052             npr->u.databaseRecord->which = Z_External_octet;
4053             
4054             npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
4055                 odr_malloc(c->odr_in, sizeof(Odr_oct));
4056             npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
4057                 sru_rec->recordData_buf;
4058             npr->u.databaseRecord->u.octet_aligned->len = 
4059                 npr->u.databaseRecord->u.octet_aligned->size = 
4060                 sru_rec->recordData_len;
4061             
4062             if (sru_rec->recordSchema 
4063                 && !strcmp(sru_rec->recordSchema,
4064                            "info:srw/schema/1/diagnostics-v1.1"))
4065             {
4066                 sru_decode_surrogate_diagnostics(sru_rec->recordData_buf,
4067                                                  sru_rec->recordData_len,
4068                                                  &diag, &num_diag,
4069                                                  resultset->odr);
4070             }
4071             record_cache_add(resultset, npr, pos, syntax, elementSetName,
4072                              sru_rec->recordSchema, diag);
4073         }
4074         *count -= i;
4075         *start += i;
4076         if (*count + *start > resultset->size)
4077             *count = resultset->size - *start;
4078         if (*count < 0)
4079             *count = 0;
4080         
4081         nmem = odr_extract_mem(c->odr_in);
4082         nmem_transfer(odr_getmem(resultset->odr), nmem);
4083         nmem_destroy(nmem);
4084
4085         if (*count > 0)
4086             return ZOOM_connection_srw_send_search(c);
4087     }
4088     return zoom_complete;
4089 }
4090 #endif
4091
4092 #if YAZ_HAVE_XML2
4093 static void handle_srw_scan_response(ZOOM_connection c,
4094                                      Z_SRW_scanResponse *res)
4095 {
4096     NMEM nmem = odr_extract_mem(c->odr_in);
4097     ZOOM_scanset scan;
4098
4099     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
4100         return;
4101     scan = c->tasks->u.scan.scan;
4102
4103     if (res->num_diagnostics > 0)
4104         set_SRU_error(c, &res->diagnostics[0]);
4105
4106     scan->scan_response = 0;
4107     scan->srw_scan_response = res;
4108     nmem_transfer(odr_getmem(scan->odr), nmem);
4109
4110     ZOOM_options_set_int(scan->options, "number", res->num_terms);
4111     nmem_destroy(nmem);
4112 }
4113 #endif
4114
4115 #if YAZ_HAVE_XML2
4116 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
4117 {
4118     zoom_ret cret = zoom_complete;
4119     int ret = -1;
4120     const char *addinfo = 0;
4121     const char *connection_head = z_HTTP_header_lookup(hres->headers,
4122                                                        "Connection");
4123     ZOOM_connection_set_mask(c, 0);
4124     yaz_log(log_details, "%p handle_http", c);
4125     
4126     if (!yaz_srw_check_content_type(hres))
4127         addinfo = "content-type";
4128     else
4129     {
4130         Z_SOAP *soap_package = 0;
4131         ODR o = c->odr_in;
4132         Z_SOAP_Handler soap_handlers[2] = {
4133             {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
4134             {0, 0, 0}
4135         };
4136         ret = z_soap_codec(o, &soap_package,
4137                            &hres->content_buf, &hres->content_len,
4138                            soap_handlers);
4139         if (!ret && soap_package->which == Z_SOAP_generic &&
4140             soap_package->u.generic->no == 0)
4141         {
4142             Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
4143
4144             ZOOM_options_set(c->options, "sru_version", sr->srw_version);
4145             if (sr->which == Z_SRW_searchRetrieve_response)
4146                 cret = handle_srw_response(c, sr->u.response);
4147             else if (sr->which == Z_SRW_scan_response)
4148                 handle_srw_scan_response(c, sr->u.scan_response);
4149             else
4150                 ret = -1;
4151         }
4152         else if (!ret && (soap_package->which == Z_SOAP_fault
4153                           || soap_package->which == Z_SOAP_error))
4154         {
4155             set_HTTP_error(c, hres->code,
4156                            soap_package->u.fault->fault_code,
4157                            soap_package->u.fault->fault_string);
4158         }
4159         else
4160             ret = -1;
4161     }
4162     if (ret)
4163     {
4164         if (hres->code != 200)
4165             set_HTTP_error(c, hres->code, 0, 0);
4166         else
4167             set_ZOOM_error(c, ZOOM_ERROR_DECODE, addinfo);
4168         do_close(c);
4169     }
4170     if (cret == zoom_complete)
4171         ZOOM_connection_remove_task(c);
4172     if (!strcmp(hres->version, "1.0"))
4173     {
4174         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
4175         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
4176             do_close(c);
4177     }
4178     else 
4179     {
4180         /* HTTP 1.1: only if no close we stay alive .. */
4181         if (connection_head && !strcmp(connection_head, "close"))
4182             do_close(c);
4183     }
4184 }
4185 #endif
4186
4187 static int do_read(ZOOM_connection c)
4188 {
4189     int r, more;
4190     ZOOM_Event event;
4191     
4192     event = ZOOM_Event_create(ZOOM_EVENT_RECV_DATA);
4193     ZOOM_connection_put_event(c, event);
4194     
4195     r = cs_get(c->cs, &c->buf_in, &c->len_in);
4196     more = cs_more(c->cs);
4197     yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
4198     if (r == 1)
4199         return 0;
4200     if (r <= 0)
4201     {
4202         if (!ZOOM_test_reconnect(c))
4203         {
4204             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4205             do_close(c);
4206         }
4207     }
4208     else
4209     {
4210         Z_GDU *gdu;
4211         ZOOM_Event event;
4212
4213         odr_reset(c->odr_in);
4214         odr_setbuf(c->odr_in, c->buf_in, r, 0);
4215         event = ZOOM_Event_create(ZOOM_EVENT_RECV_APDU);
4216         ZOOM_connection_put_event(c, event);
4217
4218         if (!z_GDU(c->odr_in, &gdu, 0, 0))
4219         {
4220             int x;
4221             int err = odr_geterrorx(c->odr_in, &x);
4222             char msg[100];
4223             const char *element = odr_getelement(c->odr_in);
4224             yaz_snprintf(msg, sizeof(msg),
4225                     "ODR code %d:%d element=%s offset=%d",
4226                     err, x, element ? element : "<unknown>",
4227                     odr_offset(c->odr_in));
4228             set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
4229             if (log_api)
4230             {
4231                 FILE *ber_file = yaz_log_file();
4232                 if (ber_file)
4233                     odr_dumpBER(ber_file, c->buf_in, r);
4234             }
4235             do_close(c);
4236         }
4237         else
4238         {
4239             if (c->odr_print)
4240                 z_GDU(c->odr_print, &gdu, 0, 0);
4241             if (gdu->which == Z_GDU_Z3950)
4242                 recv_apdu(c, gdu->u.z3950);
4243             else if (gdu->which == Z_GDU_HTTP_Response)
4244             {
4245 #if YAZ_HAVE_XML2
4246                 handle_http(c, gdu->u.HTTP_Response);
4247 #else
4248                 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
4249                 do_close(c);
4250 #endif
4251             }
4252         }
4253         c->reconnect_ok = 0;
4254     }
4255     return 1;
4256 }
4257
4258 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out)
4259 {
4260     int r;
4261     ZOOM_Event event;
4262     
4263     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
4264     ZOOM_connection_put_event(c, event);
4265
4266     yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
4267     if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
4268     {
4269         yaz_log(log_details, "%p do_write_ex write failed", c);
4270         if (ZOOM_test_reconnect(c))
4271         {
4272             return zoom_pending;
4273         }
4274         if (c->state == STATE_CONNECTING)
4275             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4276         else
4277             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4278         do_close(c);
4279         return zoom_complete;
4280     }
4281     else if (r == 1)
4282     {    
4283         int mask = ZOOM_SELECT_EXCEPT;
4284         if (c->cs->io_pending & CS_WANT_WRITE)
4285             mask += ZOOM_SELECT_WRITE;
4286         if (c->cs->io_pending & CS_WANT_READ)
4287             mask += ZOOM_SELECT_READ;
4288         ZOOM_connection_set_mask(c, mask);
4289         yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
4290                 c, c->mask);
4291     }
4292     else
4293     {
4294         ZOOM_connection_set_mask(c, ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT);
4295         yaz_log(log_details, "%p do_write_ex write complete mask=%d",
4296                 c, c->mask);
4297     }
4298     return zoom_pending;
4299 }
4300
4301 static zoom_ret do_write(ZOOM_connection c)
4302 {
4303     return do_write_ex(c, c->buf_out, c->len_out);
4304 }
4305
4306
4307 ZOOM_API(const char *)
4308     ZOOM_c