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