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