9ddd781b154034f5453b35aabc963bba8c3cefd6
[yaz-moved-to-github.git] / src / zoom-c.c
1 /*
2  * Copyright (c) 2000-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: zoom-c.c,v 1.6 2003-11-25 09:50:35 mike Exp $
6  *
7  * ZOOM layer for C, connections, result sets, queries.
8  */
9 #include <assert.h>
10 #include <string.h>
11 #include "zoom-p.h"
12
13 #include <yaz/yaz-util.h>
14 #include <yaz/xmalloc.h>
15 #include <yaz/otherinfo.h>
16 #include <yaz/log.h>
17 #include <yaz/pquery.h>
18 #include <yaz/marcdisp.h>
19 #include <yaz/diagbib1.h>
20 #include <yaz/charneg.h>
21 #include <yaz/ill.h>
22 #include <yaz/srw.h>
23
24 #if HAVE_SYS_POLL_H
25 #include <sys/poll.h>
26 #endif
27
28 typedef enum {
29     zoom_pending,
30     zoom_complete
31 } zoom_ret;
32
33 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c);
34 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out);
35
36 static ZOOM_Event ZOOM_Event_create (int kind)
37 {
38     ZOOM_Event event = (ZOOM_Event) xmalloc (sizeof(*event));
39     event->kind = kind;
40     event->next = 0;
41     event->prev = 0;
42     return event;
43 }
44
45 static void ZOOM_Event_destroy (ZOOM_Event event)
46 {
47     xfree (event);
48 }
49
50 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
51 {
52     if (c->m_queue_back)
53     {
54         c->m_queue_back->prev = event;
55         assert (c->m_queue_front);
56     }
57     else
58     {
59         assert (!c->m_queue_front);
60         c->m_queue_front = event;
61     }
62     event->next = c->m_queue_back;
63     event->prev = 0;
64     c->m_queue_back = event;
65 }
66
67 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
68 {
69     ZOOM_Event event = c->m_queue_front;
70     if (!event)
71     {
72         c->last_event = ZOOM_EVENT_NONE;
73         return 0;
74     }
75     assert (c->m_queue_back);
76     c->m_queue_front = event->prev;
77     if (c->m_queue_front)
78     {
79         assert (c->m_queue_back);
80         c->m_queue_front->next = 0;
81     }
82     else
83         c->m_queue_back = 0;
84     c->last_event = event->kind;
85     return event;
86 }
87
88
89 static void set_dset_error (ZOOM_connection c, int error,
90                             const char *dset,
91                             const char *addinfo, const char *addinfo2)
92 {
93     xfree (c->addinfo);
94     c->addinfo = 0;
95     c->error = error;
96     c->diagset = dset;
97     if (addinfo && addinfo2)
98     {
99         c->addinfo = xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
100         strcpy(c->addinfo, addinfo);
101         strcat(c->addinfo, addinfo2);
102     }
103     else if (addinfo)
104         c->addinfo = xstrdup(addinfo);
105     if (error)
106         yaz_log(LOG_DEBUG, "Error %s %s:%d %s %s",
107                 c->host_port ? c->host_port : "<>", dset, error,
108                 addinfo ? addinfo : "",
109                 addinfo2 ? addinfo2 : "");
110 }
111
112 #if HAVE_XML2
113 static void set_HTTP_error (ZOOM_connection c, int error,
114                             const char *addinfo, const char *addinfo2)
115 {
116     set_dset_error(c, error, "HTTP", addinfo, addinfo2);
117 }
118 #endif
119
120 static void set_ZOOM_error (ZOOM_connection c, int error,
121                             const char *addinfo)
122 {
123     set_dset_error(c, error, "ZOOM", addinfo, 0);
124 }
125
126 static void clear_error (ZOOM_connection c)
127 {
128
129     switch (c->error)
130     {
131     case ZOOM_ERROR_CONNECT:
132     case ZOOM_ERROR_MEMORY:
133     case ZOOM_ERROR_DECODE:
134     case ZOOM_ERROR_CONNECTION_LOST:
135     case ZOOM_ERROR_INIT:
136     case ZOOM_ERROR_INTERNAL:
137     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
138         break;
139     default:
140         set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
141     }
142 }
143
144 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
145 {
146     ZOOM_task *taskp = &c->tasks;
147     while (*taskp)
148         taskp = &(*taskp)->next;
149     *taskp = (ZOOM_task) xmalloc (sizeof(**taskp));
150     (*taskp)->running = 0;
151     (*taskp)->which = which;
152     (*taskp)->next = 0;
153     clear_error (c);
154     return *taskp;
155 }
156
157 ZOOM_task ZOOM_connection_insert_task (ZOOM_connection c, int which)
158 {
159     ZOOM_task task = (ZOOM_task) xmalloc (sizeof(*task));
160
161     task->next = c->tasks;
162     c->tasks = task;
163
164     task->running = 0;
165     task->which = which;
166     clear_error (c);
167     return task;
168 }
169
170 void ZOOM_connection_remove_task (ZOOM_connection c)
171 {
172     ZOOM_task task = c->tasks;
173
174     if (task)
175     {
176         c->tasks = task->next;
177         switch (task->which)
178         {
179         case ZOOM_TASK_SEARCH:
180
181             ZOOM_resultset_destroy (task->u.search.resultset);
182             break;
183         case ZOOM_TASK_RETRIEVE:
184             ZOOM_resultset_destroy (task->u.retrieve.resultset);
185             break;
186         case ZOOM_TASK_CONNECT:
187             break;
188         case ZOOM_TASK_SCAN:
189             ZOOM_scanset_destroy (task->u.scan.scan);
190             break;
191         case ZOOM_TASK_PACKAGE:
192             ZOOM_package_destroy (task->u.package);
193             break;
194         default:
195             assert (0);
196         }
197         xfree (task);
198     }
199 }
200
201 static int ZOOM_connection_exec_task (ZOOM_connection c);
202
203 void ZOOM_connection_remove_tasks (ZOOM_connection c)
204 {
205     while (c->tasks)
206         ZOOM_connection_remove_task(c);
207 }
208
209 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos);
210
211 ZOOM_API(ZOOM_connection)
212 ZOOM_connection_create (ZOOM_options options)
213 {
214     ZOOM_connection c = (ZOOM_connection) xmalloc (sizeof(*c));
215
216     c->proto = PROTO_Z3950;
217     c->cs = 0;
218     c->mask = 0;
219     c->reconnect_ok = 0;
220     c->state = STATE_IDLE;
221     c->addinfo = 0;
222     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
223     c->buf_in = 0;
224     c->len_in = 0;
225     c->buf_out = 0;
226     c->len_out = 0;
227     c->resultsets = 0;
228
229     c->options = ZOOM_options_create_with_parent(options);
230
231     c->host_port = 0;
232     c->path = 0;
233     c->proxy = 0;
234     
235     c->charset = c->lang = 0;
236
237     c->cookie_out = 0;
238     c->cookie_in = 0;
239     c->client_IP = 0;
240     c->tasks = 0;
241
242     c->odr_in = odr_createmem (ODR_DECODE);
243     c->odr_out = odr_createmem (ODR_ENCODE);
244
245     c->async = 0;
246     c->support_named_resultsets = 0;
247     c->last_event = ZOOM_EVENT_NONE;
248
249     c->m_queue_front = 0;
250     c->m_queue_back = 0;
251     return c;
252 }
253
254 /* set database names. Take local databases (if set); otherwise
255    take databases given in ZURL (if set); otherwise use Default */
256 static char **set_DatabaseNames (ZOOM_connection con, ZOOM_options options,
257                                  int *num)
258 {
259     char **databaseNames;
260     const char *c;
261     int no = 2;
262     const char *cp = ZOOM_options_get (options, "databaseName");
263     
264     if (!cp || !*cp)
265     {
266         if (strncmp (con->host_port, "unix:", 5) == 0)
267             cp = strchr (con->host_port+5, ':');
268         else
269             cp = strchr (con->host_port, '/');
270         if (cp)
271             cp++;
272     }
273     if (cp)
274     {
275         c = cp;
276         while ((c = strchr(c, '+')))
277         {
278             c++;
279             no++;
280         }
281     }
282     else
283         cp = "Default";
284     databaseNames = (char**)
285         odr_malloc (con->odr_out, no * sizeof(*databaseNames));
286     no = 0;
287     while (*cp)
288     {
289         c = strchr (cp, '+');
290         if (!c)
291             c = cp + strlen(cp);
292         else if (c == cp)
293         {
294             cp++;
295             continue;
296         }
297         /* cp ptr to first char of db name, c is char
298            following db name */
299         databaseNames[no] = (char*) odr_malloc (con->odr_out, 1+c-cp);
300         memcpy (databaseNames[no], cp, c-cp);
301         databaseNames[no++][c-cp] = '\0';
302         cp = c;
303         if (*cp)
304             cp++;
305     }
306     databaseNames[no] = NULL;
307     *num = no;
308     return databaseNames;
309 }
310
311 ZOOM_API(ZOOM_connection)
312 ZOOM_connection_new (const char *host, int portnum)
313 {
314     ZOOM_connection c = ZOOM_connection_create (0);
315
316     ZOOM_connection_connect (c, host, portnum);
317     return c;
318 }
319
320 ZOOM_API(void)
321 ZOOM_connection_connect(ZOOM_connection c,
322                         const char *host, int portnum)
323 {
324     const char *val;
325     ZOOM_task task;
326
327     if (c->cs)
328     {
329         yaz_log (LOG_DEBUG, "reconnect");
330         c->reconnect_ok = 1;
331         return;
332     }
333     yaz_log(LOG_DEBUG, "connect");
334     xfree (c->proxy);
335     val = ZOOM_options_get (c->options, "proxy");
336     if (val && *val)
337         c->proxy = xstrdup (val);
338     else
339         c->proxy = 0;
340
341     xfree (c->charset);
342     val = ZOOM_options_get (c->options, "charset");
343     if (val && *val)
344         c->charset = xstrdup (val);
345     else
346         c->charset = 0;
347
348     xfree (c->lang);
349     val = ZOOM_options_get (c->options, "lang");
350     if (val && *val)
351         c->lang = xstrdup (val);
352     else
353         c->lang = 0;
354
355     xfree (c->host_port);
356     if (portnum)
357     {
358         char hostn[128];
359         sprintf (hostn, "%.80s:%d", host, portnum);
360         c->host_port = xstrdup(hostn);
361     }
362     else
363         c->host_port = xstrdup(host);
364
365     ZOOM_options_set(c->options, "host", c->host_port);
366
367     val = ZOOM_options_get (c->options, "cookie");
368     if (val && *val)
369         c->cookie_out = xstrdup (val);
370
371     val = ZOOM_options_get (c->options, "clientIP");
372     if (val && *val)
373         c->client_IP = xstrdup (val);
374
375     c->async = ZOOM_options_get_bool (c->options, "async", 0);
376  
377     set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
378
379     task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
380
381     if (!c->async)
382     {
383         while (ZOOM_event (1, &c))
384             ;
385     }
386 }
387
388 ZOOM_API(ZOOM_query)
389 ZOOM_query_create(void)
390 {
391     ZOOM_query s = (ZOOM_query) xmalloc (sizeof(*s));
392
393     s->refcount = 1;
394     s->z_query = 0;
395     s->sort_spec = 0;
396     s->odr = odr_createmem (ODR_ENCODE);
397     s->query_string = 0;
398
399     return s;
400 }
401
402 ZOOM_API(void)
403 ZOOM_query_destroy(ZOOM_query s)
404 {
405     if (!s)
406         return;
407
408     (s->refcount)--;
409     yaz_log (LOG_DEBUG, "ZOOM_query_destroy count=%d", s->refcount);
410     if (s->refcount == 0)
411     {
412         odr_destroy (s->odr);
413         xfree (s);
414     }
415 }
416
417 ZOOM_API(int)
418 ZOOM_query_prefix(ZOOM_query s, const char *str)
419 {
420     s->query_string = odr_strdup(s->odr, str);
421     s->z_query = (Z_Query *) odr_malloc (s->odr, sizeof(*s->z_query));
422     s->z_query->which = Z_Query_type_1;
423     s->z_query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
424     if (!s->z_query->u.type_1)
425         return -1;
426     return 0;
427 }
428
429 ZOOM_API(int)
430 ZOOM_query_cql(ZOOM_query s, const char *str)
431 {
432     Z_External *ext;
433
434     s->query_string = odr_strdup(s->odr, str);
435
436     ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
437     ext->direct_reference = odr_getoidbystr(s->odr, "1.2.840.10003.16.2");
438     ext->indirect_reference = 0;
439     ext->descriptor = 0;
440     ext->which = Z_External_CQL;
441     ext->u.cql = s->query_string;
442     
443     s->z_query = (Z_Query *) odr_malloc (s->odr, sizeof(*s->z_query));
444     s->z_query->which = Z_Query_type_104;
445     s->z_query->u.type_104 =  ext;
446
447     return 0;
448 }
449
450 ZOOM_API(int)
451 ZOOM_query_sortby(ZOOM_query s, const char *criteria)
452 {
453     s->sort_spec = yaz_sort_spec (s->odr, criteria);
454     if (!s->sort_spec)
455         return -1;
456     return 0;
457 }
458
459 static zoom_ret do_write(ZOOM_connection c);
460
461 ZOOM_API(void)
462 ZOOM_connection_destroy(ZOOM_connection c)
463 {
464     ZOOM_resultset r;
465     if (!c)
466         return;
467     if (c->cs)
468         cs_close (c->cs);
469     for (r = c->resultsets; r; r = r->next)
470         r->connection = 0;
471
472     xfree (c->buf_in);
473     xfree (c->addinfo);
474     odr_destroy (c->odr_in);
475     odr_destroy (c->odr_out);
476     ZOOM_options_destroy (c->options);
477     ZOOM_connection_remove_tasks (c);
478     xfree (c->host_port);
479     xfree (c->path);
480     xfree (c->proxy);
481     xfree (c->charset);
482     xfree (c->lang);
483     xfree (c->cookie_out);
484     xfree (c->cookie_in);
485     xfree (c->client_IP);
486     xfree (c);
487 }
488
489 void ZOOM_resultset_addref (ZOOM_resultset r)
490 {
491     if (r)
492     {
493         (r->refcount)++;
494         yaz_log (LOG_DEBUG, "ZOOM_resultset_addref r=%p count=%d",
495                  r, r->refcount);
496     }
497 }
498 ZOOM_resultset ZOOM_resultset_create ()
499 {
500     ZOOM_resultset r = (ZOOM_resultset) xmalloc (sizeof(*r));
501
502     yaz_log (LOG_DEBUG, "ZOOM_resultset_create r = %p", r);
503     r->refcount = 1;
504     r->size = 0;
505     r->odr = odr_createmem (ODR_ENCODE);
506     r->start = 0;
507     r->piggyback = 1;
508     r->setname = 0;
509     r->schema = 0;
510     r->count = 0;
511     r->step = 0;
512     r->record_cache = 0;
513     r->r_sort_spec = 0;
514     r->query = 0;
515     r->connection = 0;
516     r->next = 0;
517     return r;
518 }
519
520 ZOOM_API(ZOOM_resultset)
521 ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
522 {
523     ZOOM_resultset r;
524     ZOOM_query s = ZOOM_query_create();
525
526     ZOOM_query_prefix (s, q);
527
528     r = ZOOM_connection_search (c, s);
529     ZOOM_query_destroy (s);
530     return r;
531 }
532
533 ZOOM_API(ZOOM_resultset)
534 ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
535 {
536     ZOOM_resultset r = ZOOM_resultset_create ();
537     ZOOM_task task;
538     const char *cp;
539
540     r->r_sort_spec = q->sort_spec;
541     r->query = q;
542
543     r->options = ZOOM_options_create_with_parent(c->options);
544
545     r->start = ZOOM_options_get_int(r->options, "start", 0);
546     r->count = ZOOM_options_get_int(r->options, "count", 0);
547     {
548         /* If "presentChunk" is defined use that; otherwise "step" */
549         const char *cp = ZOOM_options_get (r->options, "presentChunk");
550         r->step = ZOOM_options_get_int(r->options,
551                                        (cp != 0 ? "presentChunk": "step"), 0);
552     }
553     r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
554     cp = ZOOM_options_get (r->options, "setname");
555     if (cp)
556         r->setname = xstrdup(cp);
557     cp = ZOOM_options_get (r->options, "schema");
558     if (cp)
559         r->schema = xstrdup(cp);
560     
561     r->connection = c;
562
563     r->next = c->resultsets;
564     c->resultsets = r;
565
566     if (c->host_port && c->proto == PROTO_HTTP)
567     {
568         if (!c->cs)
569         {
570             yaz_log(LOG_DEBUG, "NO COMSTACK");
571             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
572         }
573         else
574         {
575             yaz_log(LOG_DEBUG, "PREPARE FOR RECONNECT");
576             c->reconnect_ok = 1;
577         }
578     }
579
580     task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
581     task->u.search.resultset = r;
582     ZOOM_resultset_addref (r);  
583
584     (q->refcount)++;
585
586     if (!c->async)
587     {
588         while (ZOOM_event (1, &c))
589             ;
590     }
591     return r;
592 }
593
594 ZOOM_API(void)
595 ZOOM_resultset_destroy(ZOOM_resultset r)
596 {
597     if (!r)
598         return;
599     (r->refcount)--;
600     yaz_log (LOG_DEBUG, "ZOOM_resultset_destroy r = %p count=%d",
601              r, r->refcount);
602     if (r->refcount == 0)
603     {
604         ZOOM_record_cache rc;
605
606         for (rc = r->record_cache; rc; rc = rc->next)
607         {
608             if (rc->rec.wrbuf_marc)
609                 wrbuf_free (rc->rec.wrbuf_marc, 1);
610             if (rc->rec.wrbuf_iconv)
611                 wrbuf_free (rc->rec.wrbuf_iconv, 1);
612             if (rc->rec.wrbuf_opac)
613                 wrbuf_free (rc->rec.wrbuf_opac, 1);
614         }
615         if (r->connection)
616         {
617             /* remove ourselves from the resultsets in connection */
618             ZOOM_resultset *rp = &r->connection->resultsets;
619             while (1)
620             {
621                 assert (*rp);   /* we must be in this list!! */
622                 if (*rp == r)
623                 {   /* OK, we're here - take us out of it */
624                     *rp = (*rp)->next;
625                     break;
626                 }
627                 rp = &(*rp)->next;
628             }
629         }
630         ZOOM_query_destroy (r->query);
631         ZOOM_options_destroy (r->options);
632         odr_destroy (r->odr);
633         xfree (r->setname);
634         xfree (r->schema);
635         xfree (r);
636     }
637 }
638
639 ZOOM_API(size_t)
640 ZOOM_resultset_size (ZOOM_resultset r)
641 {
642     return r->size;
643 }
644
645 static void do_close (ZOOM_connection c)
646 {
647     if (c->cs)
648         cs_close(c->cs);
649     c->cs = 0;
650     c->mask = 0;
651     c->state = STATE_IDLE;
652 }
653
654 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
655                                      int force_sync, int start, int count)
656 {
657     ZOOM_task task;
658     ZOOM_connection c;
659     const char *cp;
660
661     if (!r)
662         return;
663     c = r->connection;
664     if (!c)
665         return;
666
667     if (c->host_port && c->proto == PROTO_HTTP)
668     {
669         if (!c->cs)
670         {
671             yaz_log(LOG_DEBUG, "NO COMSTACK");
672             ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
673         }
674         else
675         {
676             yaz_log(LOG_DEBUG, "PREPARE FOR RECONNECT");
677             c->reconnect_ok = 1;
678         }
679     }
680     task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
681     task->u.retrieve.resultset = r;
682     task->u.retrieve.start = start;
683     task->u.retrieve.count = count;
684
685     cp = ZOOM_options_get (r->options, "schema");
686     if (cp)
687     {
688         if (!r->schema || strcmp(r->schema, cp))
689         {
690             xfree(r->schema);
691             r->schema = xstrdup(cp);
692         }
693     }
694
695     ZOOM_resultset_addref (r);
696
697     if (!r->connection->async || force_sync)
698         while (r->connection && ZOOM_event (1, &r->connection))
699             ;
700 }
701
702 ZOOM_API(void)
703 ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
704                         size_t start, size_t count)
705 {
706     int force_present = 0;
707
708     if (!r)
709         return ;
710     if (count && recs)
711         force_present = 1;
712     ZOOM_resultset_retrieve (r, force_present, start, count);
713     if (force_present)
714     {
715         size_t i;
716         for (i = 0; i< count; i++)
717             recs[i] = ZOOM_resultset_record_immediate (r, i+start);
718     }
719 }
720
721 static zoom_ret do_connect (ZOOM_connection c)
722 {
723     void *add;
724     const char *effective_host;
725
726     if (c->proxy)
727         effective_host = c->proxy;
728     else
729         effective_host = c->host_port;
730
731     yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
732
733     assert (!c->cs);
734     c->cs = cs_create_host (effective_host, 0, &add);
735
736     if (c->cs && c->cs->protocol == PROTO_HTTP)
737     {
738 #if HAVE_XML2
739         const char *path = 0;
740
741         c->proto = PROTO_HTTP;
742         cs_get_host_args(c->host_port, &path);
743         xfree(c->path);
744         c->path = xmalloc(strlen(path)+2);
745         c->path[0] = '/';
746         strcpy (c->path+1, path);
747 #else
748         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
749         do_close(c);
750         return zoom_complete;
751 #endif
752     }
753     if (c->cs)
754     {
755         int ret = cs_connect (c->cs, add);
756         if (ret == 0)
757         {
758             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
759             ZOOM_connection_put_event(c, event);
760             if (c->proto == PROTO_Z3950)
761                 ZOOM_connection_send_init(c);
762             else
763             {
764                 /* no init request for SRW .. */
765                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
766                 ZOOM_connection_remove_task (c);
767                 c->mask = 0;
768                 ZOOM_connection_exec_task (c);
769             }
770             c->state = STATE_ESTABLISHED;
771             return zoom_pending;
772         }
773         else if (ret > 0)
774         {
775             c->state = STATE_CONNECTING; 
776             c->mask = ZOOM_SELECT_EXCEPT;
777             if (c->cs->io_pending & CS_WANT_WRITE)
778                 c->mask += ZOOM_SELECT_WRITE;
779             if (c->cs->io_pending & CS_WANT_READ)
780                 c->mask += ZOOM_SELECT_READ;
781             return zoom_pending;
782         }
783     }
784     c->state = STATE_IDLE;
785     set_ZOOM_error(c, ZOOM_ERROR_CONNECT, effective_host);
786     return zoom_complete;
787 }
788
789 int z3950_connection_socket(ZOOM_connection c)
790 {
791     if (c->cs)
792         return cs_fileno(c->cs);
793     return -1;
794 }
795
796 int z3950_connection_mask(ZOOM_connection c)
797 {
798     if (c->cs)
799         return c->mask;
800     return 0;
801 }
802
803 static void otherInfo_attach (ZOOM_connection c, Z_APDU *a, ODR out)
804 {
805     int i;
806     for (i = 0; i<200; i++)
807     {
808         size_t len;
809         Z_OtherInformation **oi;
810         char buf[80];
811         const char *val;
812         const char *cp;
813         int oidval;
814
815         sprintf (buf, "otherInfo%d", i);
816         val = ZOOM_options_get (c->options, buf);
817         if (!val)
818             break;
819         cp = strchr (val, ':');
820         if (!cp)
821             continue;
822         len = cp - val;
823         if (len >= sizeof(buf))
824             len = sizeof(buf)-1;
825         memcpy (buf, val, len);
826         buf[len] = '\0';
827         oidval = oid_getvalbyname (buf);
828         if (oidval == VAL_NONE)
829             continue;
830         
831         yaz_oi_APDU(a, &oi);
832         yaz_oi_set_string_oidval(oi, out, oidval, 1, cp+1);
833     }
834 }
835
836 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
837 {
838     assert (a);
839     if (c->cookie_out)
840     {
841         Z_OtherInformation **oi;
842         yaz_oi_APDU(a, &oi);
843         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
844     }
845     if (c->client_IP)
846     {
847         Z_OtherInformation **oi;
848         yaz_oi_APDU(a, &oi);
849         yaz_oi_set_string_oidval(oi, out, VAL_CLIENT_IP, 1, c->client_IP);
850     }
851     otherInfo_attach (c, a, out);
852     if (!z_APDU(out, &a, 0, 0))
853     {
854         FILE *outf = fopen("/tmp/apdu.txt", "a");
855         if (a && outf)
856         {
857             ODR odr_pr = odr_createmem(ODR_PRINT);
858             fprintf (outf, "a=%p\n", a);
859             odr_setprint(odr_pr, outf);
860             z_APDU(odr_pr, &a, 0, 0);
861             odr_destroy(odr_pr);
862         }
863         yaz_log (LOG_DEBUG, "encoding failed");
864         set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
865         odr_reset(out);
866         return -1;
867     }
868     
869     return 0;
870 }
871
872 static zoom_ret send_APDU (ZOOM_connection c, Z_APDU *a)
873 {
874     ZOOM_Event event;
875     assert (a);
876     if (encode_APDU(c, a, c->odr_out))
877         return zoom_complete;
878     yaz_log(LOG_DEBUG, "send APDU type=%d", a->which);
879     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
880     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
881     ZOOM_connection_put_event (c, event);
882     odr_reset(c->odr_out);
883     return do_write (c);
884 }
885
886 /* returns 1 if PDU was sent OK (still pending )
887            0 if PDU was not sent OK (nothing to wait for) 
888 */
889
890 static zoom_ret ZOOM_connection_send_init (ZOOM_connection c)
891 {
892     const char *impid, *impname, *impver;
893     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
894     Z_InitRequest *ireq = apdu->u.initRequest;
895     Z_IdAuthentication *auth = (Z_IdAuthentication *)
896         odr_malloc(c->odr_out, sizeof(*auth));
897     const char *auth_groupId = ZOOM_options_get (c->options, "group");
898     const char *auth_userId = ZOOM_options_get (c->options, "user");
899     const char *auth_password = ZOOM_options_get (c->options, "pass");
900     
901     ODR_MASK_SET(ireq->options, Z_Options_search);
902     ODR_MASK_SET(ireq->options, Z_Options_present);
903     ODR_MASK_SET(ireq->options, Z_Options_scan);
904     ODR_MASK_SET(ireq->options, Z_Options_sort);
905     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
906     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
907     
908     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
909     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
910     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
911     
912     impid = ZOOM_options_get (c->options, "implementationId");
913     ireq->implementationId =
914         (char *) odr_malloc (c->odr_out, 15 + (impid ? strlen(impid) : 0));
915     strcpy (ireq->implementationId, "");
916     if (impid)
917     {
918         strcat (ireq->implementationId, impid);
919         strcat (ireq->implementationId, "/");
920     }                                          
921     strcat (ireq->implementationId, "81"); /* Index's implementor ID */
922     
923     impname = ZOOM_options_get (c->options, "implementationName");
924     ireq->implementationName =
925         (char *) odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
926     strcpy (ireq->implementationName, "");
927     if (impname)
928     {
929         strcat (ireq->implementationName, impname);
930         strcat (ireq->implementationName, "/");
931     }                                          
932     strcat (ireq->implementationName, "ZOOM-C/YAZ");
933     
934     impver = ZOOM_options_get (c->options, "implementationVersion");
935     ireq->implementationVersion =
936         (char *) odr_malloc (c->odr_out, strlen("$Revision: 1.6 $") + 2 +
937                              (impver ? strlen(impver) : 0));
938     strcpy (ireq->implementationVersion, "");
939     if (impver)
940     {
941         strcat (ireq->implementationVersion, impver);
942         strcat (ireq->implementationVersion, "/");
943     }                                          
944     strcat (ireq->implementationVersion, "$Revision: 1.6 $");
945
946     *ireq->maximumRecordSize =
947         ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
948     *ireq->preferredMessageSize =
949         ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
950     
951     if (auth_groupId || auth_password)
952     {
953         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
954         int i = 0;
955         pass->groupId = 0;
956         if (auth_groupId && *auth_groupId)
957         {
958             pass->groupId = (char *)
959                 odr_malloc(c->odr_out, strlen(auth_groupId)+1);
960             strcpy(pass->groupId, auth_groupId);
961             i++;
962         }
963         pass->userId = 0;
964         if (auth_userId && *auth_userId)
965         {
966             pass->userId = (char *)
967                 odr_malloc(c->odr_out, strlen(auth_userId)+1);
968             strcpy(pass->userId, auth_userId);
969             i++;
970         }
971         pass->password = 0;
972         if (auth_password && *auth_password)
973         {
974             pass->password = (char *)
975                 odr_malloc(c->odr_out, strlen(auth_password)+1);
976             strcpy(pass->password, auth_password);
977             i++;
978         }
979         if (i)
980         {
981             auth->which = Z_IdAuthentication_idPass;
982             auth->u.idPass = pass;
983             ireq->idAuthentication = auth;
984         }
985     }
986     else if (auth_userId)
987     {
988         auth->which = Z_IdAuthentication_open;
989         auth->u.open = (char *)
990             odr_malloc(c->odr_out, strlen(auth_userId)+1);
991         strcpy(auth->u.open, auth_userId);
992         ireq->idAuthentication = auth;
993     }
994     if (c->proxy)
995         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
996                                  VAL_PROXY, 1, c->host_port);
997     if (c->charset||c->lang)
998     {
999         Z_OtherInformation **oi;
1000         Z_OtherInformationUnit *oi_unit;
1001         
1002         yaz_oi_APDU(apdu, &oi);
1003         
1004         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1005         {
1006             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1007             
1008             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1009             oi_unit->information.externallyDefinedInfo =
1010                 yaz_set_proposal_charneg
1011                 (c->odr_out,
1012                  (const char **)&c->charset, (c->charset) ? 1:0,
1013                  (const char **)&c->lang, (c->lang) ? 1:0, 1);
1014         }
1015     }
1016     assert (apdu);
1017     return send_APDU (c, apdu);
1018 }
1019
1020 #if HAVE_XML2
1021 static zoom_ret send_srw (ZOOM_connection c, Z_SRW_PDU *sr)
1022 {
1023     char ctype[50];
1024     Z_SOAP_Handler h[2] = {
1025         {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1026         {0, 0, 0}
1027     };
1028     ODR o = odr_createmem(ODR_ENCODE);
1029     int ret;
1030     Z_SOAP *p = odr_malloc(o, sizeof(*p));
1031     Z_GDU *gdu;
1032     ZOOM_Event event;
1033
1034     gdu = z_get_HTTP_Request(c->odr_out);
1035     gdu->u.HTTP_Request->path = c->path;
1036
1037     if (c->host_port)
1038     {
1039         const char *cp0 = strstr(c->host_port, "://");
1040         const char *cp1 = 0;
1041         if (cp0)
1042             cp0 = cp0+3;
1043         else
1044             cp0 = c->host_port;
1045
1046         cp1 = strchr(cp0, '/');
1047         if (!cp1)
1048             cp1 = cp0+strlen(cp0);
1049
1050         if (cp0 && cp1)
1051         {
1052             char *h = odr_malloc(c->odr_out, cp1 - cp0 + 1);
1053             memcpy (h, cp0, cp1 - cp0);
1054             h[cp1-cp0] = '\0';
1055             z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers,
1056                               "Host", h);
1057         }
1058     }
1059
1060     strcpy(ctype, "text/xml");
1061     if (c->charset && strlen(c->charset) < 20)
1062     {
1063         strcat(ctype, "; charset=");
1064         strcat(ctype, c->charset);
1065     }
1066     z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers,
1067                       "Content-Type", ctype);
1068     z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers,
1069                       "SOAPAction", "\"\"");
1070     p->which = Z_SOAP_generic;
1071     p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1072     p->u.generic->no = 0;
1073     p->u.generic->ns = 0;
1074     p->u.generic->p = sr;
1075     p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1076
1077     ret = z_soap_codec_enc(o, &p,
1078                            &gdu->u.HTTP_Request->content_buf,
1079                            &gdu->u.HTTP_Request->content_len, h,
1080                            c->charset);
1081
1082     if (!z_GDU(c->odr_out, &gdu, 0, 0))
1083         return zoom_complete;
1084     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1085
1086     odr_destroy(o);
1087
1088     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
1089     ZOOM_connection_put_event (c, event);
1090     odr_reset(c->odr_out);
1091     return do_write (c);
1092 }
1093 #endif
1094
1095 #if HAVE_XML2
1096 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1097 {
1098     int i;
1099     ZOOM_resultset resultset = 0;
1100     Z_SRW_PDU *sr = 0;
1101     const char *recordPacking = 0;
1102
1103     if (c->error)                  /* don't continue on error */
1104         return zoom_complete;
1105     assert (c->tasks);
1106     if (c->tasks->which == ZOOM_TASK_SEARCH)
1107     {
1108         resultset = c->tasks->u.search.resultset;
1109         resultset->setname = xstrdup ("default");
1110         ZOOM_options_set (resultset->options, "setname", resultset->setname);
1111     }
1112     else if(c->tasks->which == ZOOM_TASK_RETRIEVE)
1113     {
1114         resultset = c->tasks->u.retrieve.resultset;
1115
1116         resultset->start = c->tasks->u.retrieve.start;
1117         resultset->count = c->tasks->u.retrieve.count;
1118         
1119         if (resultset->start >= resultset->size)
1120             return zoom_complete;
1121         if (resultset->start + resultset->count > resultset->size)
1122             resultset->count = resultset->size - resultset->start;
1123
1124         for (i = 0; i<resultset->count; i++)
1125         {
1126             ZOOM_record rec =
1127                 record_cache_lookup (resultset, i + resultset->start);
1128             if (!rec)
1129                 break;
1130         }
1131         if (i == resultset->count)
1132             return zoom_complete;
1133     }
1134     assert(resultset->query);
1135         
1136     sr = yaz_srw_get(c->odr_out, Z_SRW_searchRetrieve_request);
1137
1138     if (resultset->query->z_query->which == Z_Query_type_104
1139         && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1140     {
1141
1142         sr->u.request->query_type = Z_SRW_query_type_cql;
1143         sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1144     }
1145     else if (resultset->query->z_query->which == Z_Query_type_1 &&
1146              resultset->query->z_query->u.type_1)
1147     {
1148         sr->u.request->query_type = Z_SRW_query_type_pqf;
1149         sr->u.request->query.pqf = resultset->query->query_string;
1150     }
1151     else
1152     {
1153         set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1154         return zoom_complete;
1155     }
1156     sr->u.request->startRecord = odr_intdup (c->odr_out, resultset->start + 1);
1157     sr->u.request->maximumRecords = odr_intdup (
1158         c->odr_out, resultset->step>0 ? resultset->step : resultset->count);
1159     sr->u.request->recordSchema = resultset->schema;
1160
1161     recordPacking = ZOOM_resultset_option_get (resultset, "recordPacking");
1162
1163     if (recordPacking)
1164         sr->u.request->recordPacking = odr_strdup(c->odr_out, recordPacking);
1165     
1166     return send_srw(c, sr);
1167 }
1168 #else
1169 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1170 {
1171     return zoom_complete;
1172 }
1173 #endif
1174
1175 static zoom_ret ZOOM_connection_send_search (ZOOM_connection c)
1176 {
1177     ZOOM_resultset r;
1178     int lslb, ssub, mspn;
1179     const char *syntax;
1180     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1181     Z_SearchRequest *search_req = apdu->u.searchRequest;
1182     const char *elementSetName;
1183     const char *smallSetElementSetName;
1184     const char *mediumSetElementSetName;
1185
1186     assert (c->tasks);
1187     assert (c->tasks->which == ZOOM_TASK_SEARCH);
1188
1189     r = c->tasks->u.search.resultset;
1190
1191     elementSetName =
1192         ZOOM_options_get (r->options, "elementSetName");
1193     smallSetElementSetName  =
1194         ZOOM_options_get (r->options, "smallSetElementSetName");
1195     mediumSetElementSetName =
1196         ZOOM_options_get (r->options, "mediumSetElementSetName");
1197
1198     if (!smallSetElementSetName)
1199         smallSetElementSetName = elementSetName;
1200
1201     if (!mediumSetElementSetName)
1202         mediumSetElementSetName = elementSetName;
1203
1204     assert (r);
1205     assert (r->query);
1206
1207     /* prepare query for the search request */
1208     search_req->query = r->query->z_query;
1209
1210     search_req->databaseNames =
1211         set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
1212
1213     /* get syntax (no need to provide unless piggyback is in effect) */
1214     syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
1215
1216     lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
1217     ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
1218     mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
1219     if (lslb != -1 && ssub != -1 && mspn != -1)
1220     {
1221         /* So're a Z39.50 expert? Let's hope you don't do sort */
1222         *search_req->largeSetLowerBound = lslb;
1223         *search_req->smallSetUpperBound = ssub;
1224         *search_req->mediumSetPresentNumber = mspn;
1225     }
1226     else if (r->start == 0 && r->count > 0
1227              && r->piggyback && !r->r_sort_spec && !r->schema)
1228     {
1229         /* Regular piggyback - do it unless we're going to do sort */
1230         *search_req->largeSetLowerBound = 2000000000;
1231         *search_req->smallSetUpperBound = 1;
1232         *search_req->mediumSetPresentNumber = r->step>0 ? r->step : r->count;
1233     }
1234     else
1235     {
1236         /* non-piggyback. Need not provide elementsets or syntaxes .. */
1237         smallSetElementSetName = 0;
1238         mediumSetElementSetName = 0;
1239         syntax = 0;
1240     }
1241     if (smallSetElementSetName && *smallSetElementSetName)
1242     {
1243         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1244             odr_malloc (c->odr_out, sizeof(*esn));
1245         
1246         esn->which = Z_ElementSetNames_generic;
1247         esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
1248         search_req->smallSetElementSetNames = esn;
1249     }
1250     if (mediumSetElementSetName && *mediumSetElementSetName)
1251     {
1252         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1253             odr_malloc (c->odr_out, sizeof(*esn));
1254         
1255         esn->which = Z_ElementSetNames_generic;
1256         esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
1257         search_req->mediumSetElementSetNames = esn;
1258     }
1259     if (syntax)
1260         search_req->preferredRecordSyntax =
1261             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1262     
1263     if (!r->setname)
1264     {
1265         if (c->support_named_resultsets)
1266         {
1267             char setname[14];
1268             int ord;
1269             /* find the lowest unused ordinal so that we re-use
1270                result sets on the server. */
1271             for (ord = 1; ; ord++)
1272             {
1273                 ZOOM_resultset rp;
1274                 sprintf (setname, "%d", ord);
1275                 for (rp = c->resultsets; rp; rp = rp->next)
1276                     if (rp->setname && !strcmp (rp->setname, setname))
1277                         break;
1278                 if (!rp)
1279                     break;
1280             }
1281             r->setname = xstrdup (setname);
1282             yaz_log (LOG_DEBUG, "allocating set %s", r->setname);
1283         }
1284         else
1285             r->setname = xstrdup ("default");
1286         ZOOM_options_set (r->options, "setname", r->setname);
1287     }
1288     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1289     /* send search request */
1290     return send_APDU (c, apdu);
1291 }
1292
1293 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
1294 {
1295     int oclass;
1296     Z_DefaultDiagFormat *r;
1297     char *addinfo = 0;
1298     
1299     xfree (c->addinfo);
1300     c->addinfo = 0;
1301     if (p->which != Z_DiagRec_defaultFormat)
1302     {
1303         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1304         return;
1305     }
1306     r = p->u.defaultFormat;
1307     switch (r->which)
1308     {
1309     case Z_DefaultDiagFormat_v2Addinfo:
1310         addinfo = r->u.v2Addinfo;
1311         break;
1312     case Z_DefaultDiagFormat_v3Addinfo:
1313         addinfo = r->u.v3Addinfo;
1314         break;
1315     }
1316     set_dset_error(c, *r->condition,
1317                    yaz_z3950oid_to_str(r->diagnosticSetId, &oclass),
1318                    addinfo, 0);
1319 }
1320
1321 ZOOM_API(ZOOM_record)
1322 ZOOM_record_clone (ZOOM_record srec)
1323 {
1324     char *buf;
1325     int size;
1326     ODR odr_enc;
1327     ZOOM_record nrec;
1328
1329     odr_enc = odr_createmem(ODR_ENCODE);
1330     if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
1331         return 0;
1332     buf = odr_getbuf (odr_enc, &size, 0);
1333     
1334     nrec = (ZOOM_record) xmalloc (sizeof(*nrec));
1335     nrec->odr = odr_createmem(ODR_DECODE);
1336     nrec->wrbuf_marc = 0;
1337     nrec->wrbuf_iconv = 0;
1338     nrec->wrbuf_opac = 0;
1339     odr_setbuf (nrec->odr, buf, size, 0);
1340     z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
1341     
1342     odr_destroy (odr_enc);
1343     return nrec;
1344 }
1345
1346 ZOOM_API(ZOOM_record)
1347 ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
1348 {
1349     return record_cache_lookup (s, pos);
1350 }
1351
1352 ZOOM_API(ZOOM_record)
1353 ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
1354 {
1355     ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1356
1357     if (!rec)
1358     {
1359         ZOOM_resultset_retrieve (r, 1, pos, 1);
1360         rec = ZOOM_resultset_record_immediate (r, pos);
1361     }
1362     return rec;
1363 }
1364
1365 ZOOM_API(void)
1366 ZOOM_record_destroy (ZOOM_record rec)
1367 {
1368     if (!rec)
1369         return;
1370     if (rec->wrbuf_marc)
1371         wrbuf_free (rec->wrbuf_marc, 1);
1372     if (rec->wrbuf_iconv)
1373         wrbuf_free (rec->wrbuf_iconv, 1);
1374     if (rec->wrbuf_opac)
1375         wrbuf_free (rec->wrbuf_opac, 1);
1376     odr_destroy (rec->odr);
1377     xfree (rec);
1378 }
1379
1380 static const char *record_iconv_return(ZOOM_record rec, int *len,
1381                                        const char *buf, int sz,
1382                                        const char *record_charset)
1383 {
1384     char to[40];
1385     char from[40];
1386     yaz_iconv_t cd = 0;
1387
1388     *from = '\0';
1389     strcpy(to, "UTF-8");
1390     if (record_charset && *record_charset)
1391     {
1392         /* Use "from,to" or just "from" */
1393         const char *cp =strchr(record_charset, ',');
1394         int clen = strlen(record_charset);
1395         if (cp && cp[1])
1396         {
1397             strncpy( to, cp+1, sizeof(to)-1);
1398             to[sizeof(to)-1] = '\0';
1399             clen = cp - record_charset;
1400         }
1401         if (clen > sizeof(from)-1)
1402             clen = sizeof(from)-1;
1403         
1404         if (clen)
1405             strncpy(from, record_charset, clen);
1406         from[clen] = '\0';
1407     }
1408
1409     if (*from && *to && (cd = yaz_iconv_open(to, from)))
1410     {
1411         char outbuf[12];
1412         size_t inbytesleft = sz;
1413         const char *inp = buf;
1414         
1415         if (!rec->wrbuf_iconv)
1416             rec->wrbuf_iconv = wrbuf_alloc();
1417
1418         wrbuf_rewind(rec->wrbuf_iconv);
1419
1420         while (inbytesleft)
1421         {
1422             size_t outbytesleft = sizeof(outbuf);
1423             char *outp = outbuf;
1424             size_t r = yaz_iconv (cd, (char**) &inp,
1425                                   &inbytesleft, 
1426                                   &outp, &outbytesleft);
1427             if (r == (size_t) (-1))
1428             {
1429                 int e = yaz_iconv_error(cd);
1430                 if (e != YAZ_ICONV_E2BIG)
1431                     break;
1432             }
1433             wrbuf_write(rec->wrbuf_iconv, outbuf, outp - outbuf);
1434         }
1435         wrbuf_puts(rec->wrbuf_iconv, "");
1436         buf = wrbuf_buf(rec->wrbuf_iconv);
1437         sz = wrbuf_len(rec->wrbuf_iconv);
1438         yaz_iconv_close(cd);
1439     }
1440     if (len)
1441         *len = sz;
1442     return buf;
1443 }
1444
1445 ZOOM_API(const char *)
1446 ZOOM_record_get (ZOOM_record rec, const char *type_spec, int *len)
1447 {
1448     char type[40];
1449     char charset[40];
1450     const char *cp;
1451     int i;
1452     Z_NamePlusRecord *npr;
1453     
1454     if (len)
1455         *len = 0; /* default return */
1456         
1457     if (!rec)
1458         return 0;
1459     npr = rec->npr;
1460     if (!npr)
1461         return 0;
1462
1463     cp = type_spec;
1464     for (i = 0; cp[i] && i < sizeof(type)-1; i++)
1465     {
1466         if (cp[i] == ';' || cp[i] == ' ')
1467             break;
1468         type[i] = cp[i];
1469     }
1470     type[i] = '\0';
1471     charset[0] = '\0';
1472     if (type_spec[i] == ';')
1473     {
1474         i++;
1475         while (type_spec[i] == ' ')
1476             i++;
1477         if (!strncmp(type_spec+i, "charset=", 8))
1478         {
1479             cp = type_spec+i+8;
1480             for (i = 0; cp[i] && i < sizeof(charset)-1; i++)
1481             {
1482                 if (cp[i] == ';' || cp[i] == ' ')
1483                     break;
1484                 charset[i] = cp[i];
1485             }
1486             charset[i] = '\0';
1487         }
1488     }   
1489
1490     if (!strcmp (type, "database"))
1491     {
1492         if (len)
1493             *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
1494         return npr->databaseName;
1495     }
1496     else if (!strcmp (type, "syntax"))
1497     {
1498         const char *desc = 0;   
1499         if (npr->which == Z_NamePlusRecord_databaseRecord)
1500         {
1501             Z_External *r = (Z_External *) npr->u.databaseRecord;
1502             oident *ent = oid_getentbyoid(r->direct_reference);
1503             if (ent)
1504                 desc = ent->desc;
1505         }
1506         if (!desc)
1507             desc = "none";
1508         if (len)
1509             *len = strlen(desc);
1510         return desc;
1511     }
1512     else if (!strcmp (type, "render") && 
1513              npr->which == Z_NamePlusRecord_databaseRecord)
1514     {
1515         Z_External *r = (Z_External *) npr->u.databaseRecord;
1516         oident *ent = oid_getentbyoid(r->direct_reference);
1517
1518         /* render bibliographic record .. */
1519         if (r->which == Z_External_OPAC)
1520         {
1521             r = r->u.opac->bibliographicRecord;
1522             if (!r)
1523                 return 0;
1524             ent = oid_getentbyoid(r->direct_reference);
1525         }
1526         if (r->which == Z_External_sutrs)
1527             return record_iconv_return(rec, len,
1528                                        r->u.sutrs->buf, r->u.sutrs->len,
1529                                        charset);
1530         else if (r->which == Z_External_octet)
1531         {
1532             yaz_marc_t mt;
1533             switch (ent->value)
1534             {
1535             case VAL_SOIF:
1536             case VAL_HTML:
1537             case VAL_SUTRS:
1538                 break;
1539             case VAL_TEXT_XML:
1540             case VAL_APPLICATION_XML:
1541                 break;
1542             default:
1543                 if (!rec->wrbuf_marc)
1544                     rec->wrbuf_marc = wrbuf_alloc();
1545
1546                 mt = yaz_marc_create();
1547                 wrbuf_rewind (rec->wrbuf_marc);
1548                 if (yaz_marc_decode_wrbuf (
1549                         mt, (const char *) r->u.octet_aligned->buf,
1550                         r->u.octet_aligned->len,
1551                         rec->wrbuf_marc) > 0)
1552                 {
1553                     yaz_marc_destroy(mt);
1554                     return record_iconv_return(rec, len,
1555                                                wrbuf_buf(rec->wrbuf_marc),
1556                                                wrbuf_len(rec->wrbuf_marc),
1557                                                charset);
1558                 }
1559                 yaz_marc_destroy(mt);
1560             }
1561             return record_iconv_return(rec, len,
1562                                        (const char *) r->u.octet_aligned->buf,
1563                                        r->u.octet_aligned->len,
1564                                        charset);
1565         }
1566         else if (r->which == Z_External_grs1)
1567         {
1568             if (!rec->wrbuf_marc)
1569                 rec->wrbuf_marc = wrbuf_alloc();
1570             wrbuf_rewind (rec->wrbuf_marc);
1571             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1572             return record_iconv_return(rec, len,
1573                                        wrbuf_buf(rec->wrbuf_marc),
1574                                        wrbuf_len(rec->wrbuf_marc),
1575                                        charset);
1576         }
1577         return 0;
1578     }
1579     else if (npr->which == Z_NamePlusRecord_databaseRecord &&
1580              (!strcmp (type, "xml") || !strcmp(type, "oai")))
1581     {
1582         Z_External *r = (Z_External *) npr->u.databaseRecord;
1583         oident *ent = oid_getentbyoid(r->direct_reference);
1584
1585         /* render bibliographic record .. */
1586         if (r->which == Z_External_OPAC)
1587         {
1588             r = r->u.opac->bibliographicRecord;
1589             if (!r)
1590                 return 0;
1591             ent = oid_getentbyoid(r->direct_reference);
1592         }
1593         
1594         if (r->which == Z_External_sutrs)
1595             return record_iconv_return(rec, len,
1596                                        (const char *) r->u.sutrs->buf,
1597                                        r->u.sutrs->len,
1598                                        charset);
1599         else if (r->which == Z_External_octet)
1600         {
1601             yaz_marc_t mt;
1602             int marc_decode_type = YAZ_MARC_MARCXML;
1603
1604             if (!strcmp(type, "oai"))
1605                 marc_decode_type = YAZ_MARC_OAIMARC;
1606             switch (ent->value)
1607             {
1608             case VAL_SOIF:
1609             case VAL_HTML:
1610             case VAL_SUTRS:
1611                 break;
1612             case VAL_TEXT_XML:
1613             case VAL_APPLICATION_XML:
1614                 break;
1615             default:
1616                 if (!rec->wrbuf_marc)
1617                     rec->wrbuf_marc = wrbuf_alloc();
1618                 wrbuf_rewind (rec->wrbuf_marc);
1619                 mt = yaz_marc_create();
1620
1621                 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1622                 if (yaz_marc_decode_wrbuf (
1623                         mt, (const char *) r->u.octet_aligned->buf,
1624                         r->u.octet_aligned->len,
1625                         rec->wrbuf_marc) > 0)
1626                 {
1627                     yaz_marc_destroy(mt);
1628                     return record_iconv_return(rec, len,
1629                                                wrbuf_buf(rec->wrbuf_marc),
1630                                                wrbuf_len(rec->wrbuf_marc),
1631                                                charset);
1632                 }
1633                 yaz_marc_destroy(mt);
1634             }
1635             return record_iconv_return(rec, len,
1636                                        (const char *) r->u.octet_aligned->buf,
1637                                        r->u.octet_aligned->len,
1638                                        charset);
1639         }
1640         else if (r->which == Z_External_grs1)
1641         {
1642             if (len) *len = 5;
1643             return "GRS-1";
1644         }
1645         return 0;
1646     }
1647     else if (!strcmp (type, "raw"))
1648     {
1649         if (npr->which == Z_NamePlusRecord_databaseRecord)
1650         {
1651             Z_External *r = (Z_External *) npr->u.databaseRecord;
1652             
1653             if (r->which == Z_External_sutrs)
1654             {
1655                 if (len) *len = r->u.sutrs->len;
1656                 return (const char *) r->u.sutrs->buf;
1657             }
1658             else if (r->which == Z_External_octet)
1659             {
1660                 if (len) *len = r->u.octet_aligned->len;
1661                 return (const char *) r->u.octet_aligned->buf;
1662             }
1663             else /* grs-1, explain, OPAC, ... */
1664             {
1665                 if (len) *len = -1;
1666                 return (const char *) npr->u.databaseRecord;
1667             }
1668         }
1669         return 0;
1670     }
1671     else if (!strcmp (type, "ext"))
1672     {
1673         if (npr->which == Z_NamePlusRecord_databaseRecord)
1674             return (const char *) npr->u.databaseRecord;
1675         return 0;
1676     }
1677     else if (npr->which == Z_NamePlusRecord_databaseRecord &&
1678              !strcmp (type, "opac"))
1679              
1680     {
1681         Z_External *r = (Z_External *) npr->u.databaseRecord;
1682         if (r->which == Z_External_OPAC)
1683         {
1684             if (!rec->wrbuf_opac)
1685                 rec->wrbuf_opac = wrbuf_alloc();
1686             wrbuf_rewind (rec->wrbuf_opac);
1687             yaz_display_OPAC(rec->wrbuf_opac, r->u.opac, 0);
1688             return record_iconv_return(rec, len,
1689                                        wrbuf_buf(rec->wrbuf_opac),
1690                                        wrbuf_len(rec->wrbuf_opac),
1691                                        charset);
1692         }
1693     }
1694     return 0;
1695 }
1696
1697 static int strcmp_null(const char *v1, const char *v2)
1698 {
1699     if (!v1 && !v2)
1700         return 0;
1701     if (!v1 || !v2)
1702         return -1;
1703     return strcmp(v1, v2);
1704 }
1705
1706 static void record_cache_add (ZOOM_resultset r, Z_NamePlusRecord *npr, 
1707                               int pos)
1708 {
1709     ZOOM_record_cache rc;
1710     const char *elementSetName =
1711         ZOOM_resultset_option_get (r, "elementSetName");
1712     const char *syntax = 
1713         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1714     
1715     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1716     ZOOM_connection_put_event(r->connection, event);
1717
1718     for (rc = r->record_cache; rc; rc = rc->next)
1719     {
1720         if (pos == rc->pos)
1721         {
1722             if (strcmp_null(r->schema, rc->schema))
1723                 continue;
1724             if (strcmp_null(elementSetName,rc->elementSetName))
1725                 continue;
1726             if (strcmp_null(syntax, rc->syntax))
1727                 continue;
1728             /* not destroying rc->npr (it's handled by nmem )*/
1729             rc->rec.npr = npr;
1730             /* keeping wrbuf_marc too */
1731             return;
1732         }
1733     }
1734     rc = (ZOOM_record_cache) odr_malloc (r->odr, sizeof(*rc));
1735     rc->rec.npr = npr; 
1736     rc->rec.odr = 0;
1737     rc->rec.wrbuf_marc = 0;
1738     rc->rec.wrbuf_iconv = 0;
1739     rc->rec.wrbuf_opac = 0;
1740     if (elementSetName)
1741         rc->elementSetName = odr_strdup (r->odr, elementSetName);
1742     else
1743         rc->elementSetName = 0;
1744
1745     if (syntax)
1746         rc->syntax = odr_strdup (r->odr, syntax);
1747     else
1748         rc->syntax = 0;
1749
1750     if (r->schema)
1751         rc->schema = odr_strdup (r->odr, r->schema);
1752     else
1753         rc->schema = 0;
1754
1755     rc->pos = pos;
1756     rc->next = r->record_cache;
1757     r->record_cache = rc;
1758 }
1759
1760 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos)
1761 {
1762     ZOOM_record_cache rc;
1763     const char *elementSetName =
1764         ZOOM_resultset_option_get (r, "elementSetName");
1765     const char *syntax = 
1766         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1767     
1768     for (rc = r->record_cache; rc; rc = rc->next)
1769     {
1770         if (pos == rc->pos)
1771         {
1772             if (strcmp_null(r->schema, rc->schema))
1773                 continue;
1774             if (strcmp_null(elementSetName,rc->elementSetName))
1775                 continue;
1776             if (strcmp_null(syntax, rc->syntax))
1777                 continue;
1778             return &rc->rec;
1779         }
1780     }
1781     return 0;
1782 }
1783                                              
1784 static void handle_records (ZOOM_connection c, Z_Records *sr,
1785                             int present_phase)
1786 {
1787     ZOOM_resultset resultset;
1788
1789     if (!c->tasks)
1790         return ;
1791     switch (c->tasks->which)
1792     {
1793     case ZOOM_TASK_SEARCH:
1794         resultset = c->tasks->u.search.resultset;
1795         break;
1796     case ZOOM_TASK_RETRIEVE:
1797         resultset = c->tasks->u.retrieve.resultset;        
1798         break;
1799     default:
1800         return;
1801     }
1802     if (sr && sr->which == Z_Records_NSD)
1803     {
1804         Z_DiagRec dr, *dr_p = &dr;
1805         dr.which = Z_DiagRec_defaultFormat;
1806         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1807         
1808         response_diag (c, dr_p);
1809     }
1810     else if (sr && sr->which == Z_Records_multipleNSD)
1811     {
1812         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1813             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1814         else
1815             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1816     }
1817     else 
1818     {
1819         if (resultset->count + resultset->start > resultset->size)
1820             resultset->count = resultset->size - resultset->start;
1821         if (resultset->count < 0)
1822             resultset->count = 0;
1823         if (sr && sr->which == Z_Records_DBOSD)
1824         {
1825             int i;
1826             NMEM nmem = odr_extract_mem (c->odr_in);
1827             Z_NamePlusRecordList *p =
1828                 sr->u.databaseOrSurDiagnostics;
1829             for (i = 0; i<p->num_records; i++)
1830             {
1831                 record_cache_add (resultset, p->records[i],
1832                                   i+ resultset->start);
1833             }
1834             /* transfer our response to search_nmem .. we need it later */
1835             nmem_transfer (resultset->odr->mem, nmem);
1836             nmem_destroy (nmem);
1837             if (present_phase && p->num_records == 0)
1838             {
1839                 /* present response and we didn't get any records! */
1840                 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1841             }
1842         }
1843         else if (present_phase)
1844         {
1845             /* present response and we didn't get any records! */
1846             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1847         }
1848     }
1849 }
1850
1851 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1852 {
1853     handle_records (c, pr->records, 1);
1854 }
1855
1856 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1857 {
1858     ZOOM_resultset resultset;
1859     ZOOM_Event event;
1860     
1861     yaz_log (LOG_DEBUG, "got search response");
1862     
1863     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1864         return ;
1865     
1866     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
1867     ZOOM_connection_put_event(c, event);
1868
1869     resultset = c->tasks->u.search.resultset;
1870
1871     resultset->size = *sr->resultCount;
1872     handle_records (c, sr->records, 0);
1873 }
1874
1875 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1876 {
1877     if (res->diagnostics && res->num_diagnostics > 0)
1878         response_diag (c, res->diagnostics[0]);
1879 }
1880
1881 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1882 {
1883     NMEM nmem = odr_extract_mem (c->odr_in);
1884     ZOOM_scanset scan;
1885
1886     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1887         return 0;
1888     scan = c->tasks->u.scan.scan;
1889
1890     if (res->entries && res->entries->nonsurrogateDiagnostics)
1891         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1892     scan->scan_response = res;
1893     nmem_transfer (scan->odr->mem, nmem);
1894     if (res->stepSize)
1895         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1896     if (res->positionOfTerm)
1897         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1898     if (res->scanStatus)
1899         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1900     if (res->numberOfEntriesReturned)
1901         ZOOM_options_set_int (scan->options, "number",
1902                               *res->numberOfEntriesReturned);
1903     nmem_destroy (nmem);
1904     return 1;
1905 }
1906
1907 static zoom_ret send_sort (ZOOM_connection c)
1908 {
1909     ZOOM_resultset  resultset;
1910
1911     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1912         return zoom_complete;
1913
1914     resultset = c->tasks->u.search.resultset;
1915
1916     if (c->error)
1917     {
1918         resultset->r_sort_spec = 0;
1919         return zoom_complete;
1920     }
1921     if (resultset->r_sort_spec)
1922     {
1923         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1924         Z_SortRequest *req = apdu->u.sortRequest;
1925         
1926         req->num_inputResultSetNames = 1;
1927         req->inputResultSetNames = (Z_InternationalString **)
1928             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1929         req->inputResultSetNames[0] =
1930             odr_strdup (c->odr_out, resultset->setname);
1931         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1932         req->sortSequence = resultset->r_sort_spec;
1933         resultset->r_sort_spec = 0;
1934         return send_APDU (c, apdu);
1935     }
1936     return zoom_complete;
1937 }
1938
1939 static zoom_ret send_present (ZOOM_connection c)
1940 {
1941     Z_APDU *apdu = 0;
1942     Z_PresentRequest *req = 0;
1943     int i = 0;
1944     const char *syntax = 0;
1945     const char *elementSetName = 0;
1946     ZOOM_resultset  resultset;
1947
1948     if (!c->tasks)
1949         return zoom_complete;
1950
1951     switch (c->tasks->which)
1952     {
1953     case ZOOM_TASK_SEARCH:
1954         resultset = c->tasks->u.search.resultset;
1955         break;
1956     case ZOOM_TASK_RETRIEVE:
1957         resultset = c->tasks->u.retrieve.resultset;
1958         resultset->start = c->tasks->u.retrieve.start;
1959         resultset->count = c->tasks->u.retrieve.count;
1960
1961         if (resultset->start >= resultset->size)
1962             return zoom_complete;
1963         if (resultset->start + resultset->count > resultset->size)
1964             resultset->count = resultset->size - resultset->start;
1965         break;
1966     default:
1967         return zoom_complete;
1968     }
1969
1970     syntax = ZOOM_resultset_option_get (resultset, "preferredRecordSyntax");
1971     elementSetName = ZOOM_resultset_option_get (resultset, "elementSetName");
1972
1973     if (c->error)                  /* don't continue on error */
1974         return zoom_complete;
1975     if (resultset->start < 0)
1976         return zoom_complete;
1977     for (i = 0; i<resultset->count; i++)
1978     {
1979         ZOOM_record rec =
1980             record_cache_lookup (resultset, i + resultset->start);
1981         if (!rec)
1982             break;
1983     }
1984     if (i == resultset->count)
1985         return zoom_complete;
1986
1987     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1988     req = apdu->u.presentRequest;
1989
1990     resultset->start += i;
1991     resultset->count -= i;
1992     *req->resultSetStartPoint = resultset->start + 1;
1993     *req->numberOfRecordsRequested = resultset->step>0 ?
1994         resultset->step : resultset->count;
1995     assert (*req->numberOfRecordsRequested > 0);
1996
1997     if (syntax && *syntax)
1998         req->preferredRecordSyntax =
1999             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
2000
2001     if (resultset->schema && *resultset->schema)
2002     {
2003         Z_RecordComposition *compo = (Z_RecordComposition *)
2004             odr_malloc (c->odr_out, sizeof(*compo));
2005
2006         req->recordComposition = compo;
2007         compo->which = Z_RecordComp_complex;
2008         compo->u.complex = (Z_CompSpec *)
2009             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2010         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2011             odr_malloc(c->odr_out, sizeof(bool_t));
2012         *compo->u.complex->selectAlternativeSyntax = 0;
2013
2014         compo->u.complex->generic = (Z_Specification *)
2015             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2016
2017         compo->u.complex->generic->which = Z_Schema_oid;
2018         compo->u.complex->generic->schema.oid = (Odr_oid *)
2019             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, resultset->schema);
2020
2021         if (!compo->u.complex->generic->schema.oid)
2022         {
2023             /* OID wasn't a schema! Try record syntax instead. */
2024
2025             compo->u.complex->generic->schema.oid = (Odr_oid *)
2026                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, resultset->schema);
2027         }
2028         if (elementSetName && *elementSetName)
2029         {
2030             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2031                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2032             compo->u.complex->generic->elementSpec->which =
2033                 Z_ElementSpec_elementSetName;
2034             compo->u.complex->generic->elementSpec->u.elementSetName =
2035                 odr_strdup (c->odr_out, elementSetName);
2036         }
2037         else
2038             compo->u.complex->generic->elementSpec = 0;
2039         compo->u.complex->num_dbSpecific = 0;
2040         compo->u.complex->dbSpecific = 0;
2041         compo->u.complex->num_recordSyntax = 0;
2042         compo->u.complex->recordSyntax = 0;
2043     }
2044     else if (elementSetName && *elementSetName)
2045     {
2046         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2047             odr_malloc (c->odr_out, sizeof(*esn));
2048         Z_RecordComposition *compo = (Z_RecordComposition *)
2049             odr_malloc (c->odr_out, sizeof(*compo));
2050         
2051         esn->which = Z_ElementSetNames_generic;
2052         esn->u.generic = odr_strdup (c->odr_out, elementSetName);
2053         compo->which = Z_RecordComp_simple;
2054         compo->u.simple = esn;
2055         req->recordComposition = compo;
2056     }
2057     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2058     return send_APDU (c, apdu);
2059 }
2060
2061 ZOOM_API(ZOOM_scanset)
2062 ZOOM_connection_scan (ZOOM_connection c, const char *start)
2063 {
2064     ZOOM_scanset scan = (ZOOM_scanset) xmalloc (sizeof(*scan));
2065
2066     scan->connection = c;
2067     scan->odr = odr_createmem (ODR_DECODE);
2068     scan->options = ZOOM_options_create_with_parent (c->options);
2069     scan->refcount = 1;
2070     scan->scan_response = 0;
2071
2072     if ((scan->termListAndStartPoint =
2073          p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
2074                       start)))
2075     {
2076         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
2077         task->u.scan.scan = scan;
2078         
2079         (scan->refcount)++;
2080         if (!c->async)
2081         {
2082             while (ZOOM_event (1, &c))
2083                 ;
2084         }
2085     }
2086     return scan;
2087 }
2088
2089 ZOOM_API(void)
2090 ZOOM_scanset_destroy (ZOOM_scanset scan)
2091 {
2092     if (!scan)
2093         return;
2094     (scan->refcount)--;
2095     if (scan->refcount == 0)
2096     {
2097         odr_destroy (scan->odr);
2098         
2099         ZOOM_options_destroy (scan->options);
2100         xfree (scan);
2101     }
2102 }
2103
2104 static zoom_ret send_package (ZOOM_connection c)
2105 {
2106     ZOOM_Event event;
2107     if (!c->tasks)
2108         return zoom_complete;
2109     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2110     
2111     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
2112     ZOOM_connection_put_event (c, event);
2113     
2114     return do_write_ex (c, c->tasks->u.package->buf_out,
2115                         c->tasks->u.package->len_out);
2116 }
2117
2118 static zoom_ret send_scan (ZOOM_connection c)
2119 {
2120     ZOOM_scanset scan;
2121     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2122     Z_ScanRequest *req = apdu->u.scanRequest;
2123     if (!c->tasks)
2124         return zoom_complete;
2125     assert (c->tasks->which == ZOOM_TASK_SCAN);
2126     scan = c->tasks->u.scan.scan;
2127
2128     req->termListAndStartPoint = scan->termListAndStartPoint;
2129     req->attributeSet = scan->attributeSet;
2130
2131     *req->numberOfTermsRequested =
2132         ZOOM_options_get_int(scan->options, "number", 10);
2133
2134     req->preferredPositionInResponse =
2135         odr_intdup (c->odr_out,
2136                     ZOOM_options_get_int(scan->options, "position", 1));
2137
2138     req->stepSize =
2139         odr_intdup (c->odr_out,
2140                     ZOOM_options_get_int(scan->options, "stepSize", 0));
2141     
2142     req->databaseNames = set_DatabaseNames (c, scan->options, 
2143                                             &req->num_databaseNames);
2144
2145     return send_APDU (c, apdu);
2146 }
2147
2148 ZOOM_API(size_t)
2149 ZOOM_scanset_size (ZOOM_scanset scan)
2150 {
2151     if (!scan || !scan->scan_response || !scan->scan_response->entries)
2152         return 0;
2153     return scan->scan_response->entries->num_entries;
2154 }
2155
2156 ZOOM_API(const char *)
2157 ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
2158                    int *occ, int *len)
2159 {
2160     const char *term = 0;
2161     size_t noent = ZOOM_scanset_size (scan);
2162     Z_ScanResponse *res = scan->scan_response;
2163     
2164     *len = 0;
2165     *occ = 0;
2166     if (pos >= noent)
2167         return 0;
2168     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2169     {
2170         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2171         
2172         if (t->term->which == Z_Term_general)
2173         {
2174             term = (const char *) t->term->u.general->buf;
2175             *len = t->term->u.general->len;
2176         }
2177         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2178     }
2179     return term;
2180 }
2181
2182 ZOOM_API(const char *)
2183 ZOOM_scanset_display_term (ZOOM_scanset scan, size_t pos,
2184                            int *occ, int *len)
2185 {
2186     const char *term = 0;
2187     size_t noent = ZOOM_scanset_size (scan);
2188     Z_ScanResponse *res = scan->scan_response;
2189     
2190     *len = 0;
2191     *occ = 0;
2192     if (pos >= noent)
2193         return 0;
2194     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2195     {
2196         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2197
2198         if (t->displayTerm)
2199         {
2200             term = (const char *) t->term->u.general->buf;
2201             *len = strlen(term);
2202         }
2203         else if (t->term->which == Z_Term_general)
2204         {
2205             term = (const char *) t->term->u.general->buf;
2206             *len = t->term->u.general->len;
2207         }
2208         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2209     }
2210     return term;
2211 }
2212
2213 ZOOM_API(const char *)
2214 ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
2215 {
2216     return ZOOM_options_get (scan->options, key);
2217 }
2218
2219 ZOOM_API(void)
2220 ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
2221                               const char *val)
2222 {
2223     ZOOM_options_set (scan->options, key, val);
2224 }
2225
2226 static Z_APDU *create_es_package (ZOOM_package p, int type)
2227 {
2228     const char *str;
2229     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
2230     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2231     
2232     *req->function = Z_ExtendedServicesRequest_create;
2233     
2234     str = ZOOM_options_get(p->options, "package-name");
2235     if (str && *str)
2236         req->packageName = nmem_strdup (p->odr_out->mem, str);
2237     
2238     str = ZOOM_options_get(p->options, "user-id");
2239     if (str)
2240         req->userId = nmem_strdup (p->odr_out->mem, str);
2241     
2242     req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2243                                               type);
2244
2245     str = ZOOM_options_get(p->options, "function");
2246     if (str)
2247     {
2248         if (!strcmp (str, "create"))
2249             *req->function = 1;
2250         if (!strcmp (str, "delete"))
2251             *req->function = 2;
2252         if (!strcmp (str, "modify"))
2253             *req->function = 3;
2254     }
2255     return apdu;
2256 }
2257
2258 static const char *ill_array_lookup (void *clientData, const char *idx)
2259 {
2260     ZOOM_package p = (ZOOM_package) clientData;
2261     return ZOOM_options_get (p->options, idx+4);
2262 }
2263
2264 static Z_External *encode_ill_request (ZOOM_package p)
2265 {
2266     ODR out = p->odr_out;
2267     ILL_Request *req;
2268     Z_External *r = 0;
2269     struct ill_get_ctl ctl;
2270         
2271     ctl.odr = p->odr_out;
2272     ctl.clientData = p;
2273     ctl.f = ill_array_lookup;
2274         
2275     req = ill_get_ILLRequest(&ctl, "ill", 0);
2276         
2277     if (!ill_Request (out, &req, 0, 0))
2278     {
2279         int ill_request_size;
2280         char *ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2281         if (ill_request_buf)
2282             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2283         return 0;
2284     }
2285     else
2286     {
2287         oident oid;
2288         int illRequest_size = 0;
2289         char *illRequest_buf = odr_getbuf (out, &illRequest_size, 0);
2290                 
2291         oid.proto = PROTO_GENERAL;
2292         oid.oclass = CLASS_GENERAL;
2293         oid.value = VAL_ISO_ILL_1;
2294                 
2295         r = (Z_External *) odr_malloc (out, sizeof(*r));
2296         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
2297         r->indirect_reference = 0;
2298         r->descriptor = 0;
2299         r->which = Z_External_single;
2300                 
2301         r->u.single_ASN1_type = (Odr_oct *)
2302             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
2303         r->u.single_ASN1_type->buf = (unsigned char*)
2304             odr_malloc (out, illRequest_size);
2305         r->u.single_ASN1_type->len = illRequest_size;
2306         r->u.single_ASN1_type->size = illRequest_size;
2307         memcpy (r->u.single_ASN1_type->buf, illRequest_buf, illRequest_size);
2308     }
2309     return r;
2310 }
2311
2312 static Z_ItemOrder *encode_item_order(ZOOM_package p)
2313 {
2314     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc (p->odr_out, sizeof(*req));
2315     const char *str;
2316     
2317     req->which=Z_IOItemOrder_esRequest;
2318     req->u.esRequest = (Z_IORequest *) 
2319         odr_malloc(p->odr_out,sizeof(Z_IORequest));
2320
2321     /* to keep part ... */
2322     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2323         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
2324     req->u.esRequest->toKeep->supplDescription = 0;
2325     req->u.esRequest->toKeep->contact = (Z_IOContact *)
2326         odr_malloc (p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
2327         
2328     str = ZOOM_options_get(p->options, "contact-name");
2329     req->u.esRequest->toKeep->contact->name = str ?
2330         nmem_strdup (p->odr_out->mem, str) : 0;
2331         
2332     str = ZOOM_options_get(p->options, "contact-phone");
2333     req->u.esRequest->toKeep->contact->phone = str ?
2334         nmem_strdup (p->odr_out->mem, str) : 0;
2335         
2336     str = ZOOM_options_get(p->options, "contact-email");
2337     req->u.esRequest->toKeep->contact->email = str ?
2338         nmem_strdup (p->odr_out->mem, str) : 0;
2339         
2340     req->u.esRequest->toKeep->addlBilling = 0;
2341         
2342     /* not to keep part ... */
2343     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2344         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
2345         
2346     str = ZOOM_options_get(p->options, "itemorder-setname");
2347     if (!str)
2348         str = "default";
2349
2350     if (!*str) 
2351         req->u.esRequest->notToKeep->resultSetItem = 0;
2352     else
2353     {
2354         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
2355            odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
2356
2357         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
2358            nmem_strdup (p->odr_out->mem, str);
2359         req->u.esRequest->notToKeep->resultSetItem->item =
2360             (int *) odr_malloc(p->odr_out, sizeof(int));
2361         
2362         str = ZOOM_options_get(p->options, "itemorder-item");
2363         *req->u.esRequest->notToKeep->resultSetItem->item =
2364             (str ? atoi(str) : 1);
2365     }
2366     req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
2367     
2368     return req;
2369 }
2370
2371 ZOOM_API(void)
2372     ZOOM_package_send (ZOOM_package p, const char *type)
2373 {
2374     Z_APDU *apdu = 0;
2375     ZOOM_connection c;
2376     if (!p)
2377         return;
2378     c = p->connection;
2379     odr_reset (p->odr_out);
2380     xfree (p->buf_out);
2381     p->buf_out = 0;
2382     if (!strcmp(type, "itemorder"))
2383     {
2384         Z_External *r;
2385         apdu = create_es_package (p, VAL_ITEMORDER);
2386         if (apdu)
2387         {
2388             r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
2389             
2390             r->direct_reference =
2391                 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2392                                        VAL_ITEMORDER);
2393             r->descriptor = 0;
2394             r->which = Z_External_itemOrder;
2395             r->indirect_reference = 0;
2396             r->u.itemOrder = encode_item_order (p);
2397
2398             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2399         }
2400     }
2401     if (apdu)
2402     {
2403         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
2404         {
2405             char *buf;
2406
2407             ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_PACKAGE);
2408             task->u.package = p;
2409             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
2410             p->buf_out = (char *) xmalloc (p->len_out);
2411             memcpy (p->buf_out, buf, p->len_out);
2412             
2413             (p->refcount)++;
2414             if (!c->async)
2415             {
2416                 while (ZOOM_event (1, &c))
2417                     ;
2418             }
2419         }
2420     }
2421 }
2422
2423 ZOOM_API(ZOOM_package)
2424     ZOOM_connection_package (ZOOM_connection c, ZOOM_options options)
2425 {
2426     ZOOM_package p = (ZOOM_package) xmalloc (sizeof(*p));
2427
2428     p->connection = c;
2429     p->odr_out = odr_createmem (ODR_ENCODE);
2430     p->options = ZOOM_options_create_with_parent2 (options, c->options);
2431     p->refcount = 1;
2432     p->buf_out = 0;
2433     p->len_out = 0;
2434     return p;
2435 }
2436
2437 ZOOM_API(void)
2438     ZOOM_package_destroy(ZOOM_package p)
2439 {
2440     if (!p)
2441         return;
2442     (p->refcount)--;
2443     if (p->refcount == 0)
2444     {
2445         odr_destroy (p->odr_out);
2446         xfree (p->buf_out);
2447         
2448         ZOOM_options_destroy (p->options);
2449         xfree (p);
2450     }
2451 }
2452
2453 ZOOM_API(const char *)
2454 ZOOM_package_option_get (ZOOM_package p, const char *key)
2455 {
2456     return ZOOM_options_get (p->options, key);
2457 }
2458
2459
2460 ZOOM_API(void)
2461 ZOOM_package_option_set (ZOOM_package p, const char *key,
2462                               const char *val)
2463 {
2464     ZOOM_options_set (p->options, key, val);
2465 }
2466
2467 static int ZOOM_connection_exec_task (ZOOM_connection c)
2468 {
2469     ZOOM_task task = c->tasks;
2470     zoom_ret ret = zoom_complete;
2471
2472     if (!task)
2473     {
2474         yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task task=<null>");
2475         return 0;
2476     }
2477     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d run=%d",
2478              task->which, task->running);
2479     if (c->error != ZOOM_ERROR_NONE)
2480     {
2481         yaz_log (LOG_DEBUG, "remove tasks because of error = %d", c->error);
2482         ZOOM_connection_remove_tasks (c);
2483         return 0;
2484     }
2485     if (task->running)
2486     {
2487         yaz_log (LOG_DEBUG, "task already running");
2488         return 0;
2489     }
2490     task->running = 1;
2491     ret = zoom_complete;
2492     if (c->cs || task->which == ZOOM_TASK_CONNECT)
2493     {
2494         switch (task->which)
2495         {
2496         case ZOOM_TASK_SEARCH:
2497             if (c->proto == PROTO_HTTP)
2498                 ret = ZOOM_connection_srw_send_search(c);
2499             else
2500                 ret = ZOOM_connection_send_search(c);
2501             break;
2502         case ZOOM_TASK_RETRIEVE:
2503             if (c->proto == PROTO_HTTP)
2504                 ret = ZOOM_connection_srw_send_search(c);
2505             else
2506                 ret = send_present (c);
2507             break;
2508         case ZOOM_TASK_CONNECT:
2509             ret = do_connect(c);
2510             break;
2511         case ZOOM_TASK_SCAN:
2512             ret = send_scan(c);
2513             break;
2514         case ZOOM_TASK_PACKAGE:
2515             ret = send_package(c);
2516             break;
2517         }
2518     }
2519     else
2520     {
2521         yaz_log (LOG_DEBUG, "remove tasks because no connection exist");
2522         ZOOM_connection_remove_tasks (c);
2523     }
2524     if (ret == zoom_complete)
2525     {
2526         yaz_log (LOG_DEBUG, "task removed (complete)");
2527         ZOOM_connection_remove_task (c);
2528         return 0;
2529     }
2530     yaz_log (LOG_DEBUG, "task pending");
2531     return 1;
2532 }
2533
2534 static zoom_ret send_sort_present (ZOOM_connection c)
2535 {
2536     zoom_ret r = send_sort (c);
2537     if (r == zoom_complete)
2538         r = send_present (c);
2539     return r;
2540 }
2541
2542 static int es_response (ZOOM_connection c,
2543                         Z_ExtendedServicesResponse *res)
2544 {
2545     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
2546         return 0;
2547     if (res->diagnostics && res->num_diagnostics > 0)
2548         response_diag(c, res->diagnostics[0]);
2549     if (res->taskPackage &&
2550         res->taskPackage->which == Z_External_extendedService)
2551     {
2552         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
2553         Odr_oct *id = taskPackage->targetReference;
2554         
2555         if (id)
2556             ZOOM_options_setl (c->tasks->u.package->options,
2557                                "targetReference", (char*) id->buf, id->len);
2558     }
2559     return 1;
2560 }
2561
2562
2563 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
2564 {
2565     Z_InitResponse *initrs;
2566     
2567     c->mask = 0;
2568     yaz_log (LOG_DEBUG, "recv APDU type=%d", apdu->which);
2569     switch(apdu->which)
2570     {
2571     case Z_APDU_initResponse:
2572         initrs = apdu->u.initResponse;
2573         ZOOM_connection_option_set(c, "serverImplementationId",
2574                                    initrs->implementationId ?
2575                                    initrs->implementationId : "");
2576         ZOOM_connection_option_set(c, "serverImplementationName",
2577                                    initrs->implementationName ?
2578                                    initrs->implementationName : "");
2579         ZOOM_connection_option_set(c, "serverImplementationVersion",
2580                                    initrs->implementationVersion ?
2581                                    initrs->implementationVersion : "");
2582         /* Set the three old options too, for old applications */
2583         ZOOM_connection_option_set(c, "targetImplementationId",
2584                                    initrs->implementationId ?
2585                                    initrs->implementationId : "");
2586         ZOOM_connection_option_set(c, "targetImplementationName",
2587                                    initrs->implementationName ?
2588                                    initrs->implementationName : "");
2589         ZOOM_connection_option_set(c, "targetImplementationVersion",
2590                                    initrs->implementationVersion ?
2591                                    initrs->implementationVersion : "");
2592         if (!*initrs->result)
2593         {
2594             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0);
2595         }
2596         else
2597         {
2598             char *cookie =
2599                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
2600                                           VAL_COOKIE, 1, 0);
2601             xfree (c->cookie_in);
2602             c->cookie_in = 0;
2603             if (cookie)
2604                 c->cookie_in = xstrdup(cookie);
2605             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
2606                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
2607                 c->support_named_resultsets = 1;
2608             if (c->tasks)
2609             {
2610                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
2611                 ZOOM_connection_remove_task (c);
2612             }
2613             ZOOM_connection_exec_task (c);
2614         }
2615         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
2616         {
2617             NMEM tmpmem = nmem_create();
2618             Z_CharSetandLanguageNegotiation *p =
2619                 yaz_get_charneg_record(initrs->otherInfo);
2620             
2621             if (p)
2622             {
2623                 char *charset=NULL, *lang=NULL;
2624                 int sel;
2625                 
2626                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
2627                 yaz_log(LOG_DEBUG, "Target accepted: charset %s, "
2628                         "language %s, select %d",
2629                         charset ? charset : "none", lang ? lang : "none", sel);
2630                 if (charset)
2631                     ZOOM_connection_option_set (c, "negotiation-charset",
2632                                                 charset);
2633                 if (lang)
2634                     ZOOM_connection_option_set (c, "negotiation-lang",
2635                                                 lang);
2636                 nmem_destroy(tmpmem);
2637             }
2638         }       
2639         break;
2640     case Z_APDU_searchResponse:
2641         handle_search_response (c, apdu->u.searchResponse);
2642         if (send_sort_present (c) == zoom_complete)
2643             ZOOM_connection_remove_task (c);
2644         break;
2645     case Z_APDU_presentResponse:
2646         handle_present_response (c, apdu->u.presentResponse);
2647         if (send_present (c) == zoom_complete)
2648             ZOOM_connection_remove_task (c);
2649         break;
2650     case Z_APDU_sortResponse:
2651         sort_response (c, apdu->u.sortResponse);
2652         if (send_present (c) == zoom_complete)
2653             ZOOM_connection_remove_task (c);
2654         break;
2655     case Z_APDU_scanResponse:
2656         scan_response (c, apdu->u.scanResponse);
2657         ZOOM_connection_remove_task (c);
2658         break;
2659     case Z_APDU_extendedServicesResponse:
2660         es_response (c, apdu->u.extendedServicesResponse);
2661         ZOOM_connection_remove_task (c);
2662         break;
2663     case Z_APDU_close:
2664         if (c->reconnect_ok)
2665         {
2666             do_close(c);
2667             c->tasks->running = 0;
2668             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2669         }
2670         else
2671         {
2672             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
2673             do_close(c);
2674         }
2675         break;
2676     default:
2677         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2678         do_close(c);
2679     }
2680 }
2681
2682 #if HAVE_XML2
2683 static void handle_srw_response(ZOOM_connection c,
2684                                 Z_SRW_searchRetrieveResponse *res)
2685 {
2686     ZOOM_resultset resultset = 0;
2687     int i;
2688     NMEM nmem;
2689     ZOOM_Event event;
2690
2691     if (!c->tasks)
2692         return;
2693
2694     if (c->tasks->which == ZOOM_TASK_SEARCH)
2695         resultset = c->tasks->u.search.resultset;
2696     else if (c->tasks->which == ZOOM_TASK_RETRIEVE)
2697         resultset = c->tasks->u.retrieve.resultset;
2698     else
2699         return ;
2700
2701     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2702     ZOOM_connection_put_event(c, event);
2703
2704     resultset->size = 0;
2705
2706     yaz_log(LOG_DEBUG, "got SRW response OK");
2707     
2708     if (res->numberOfRecords)
2709         resultset->size = *res->numberOfRecords;
2710
2711     for (i = 0; i<res->num_records; i++)
2712     {
2713         int pos;
2714
2715         Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
2716             odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
2717
2718         if (res->records[i].recordPosition && 
2719             *res->records[i].recordPosition > 0)
2720             pos = *res->records[i].recordPosition - 1;
2721         else
2722             pos = resultset->start + i;
2723         
2724         npr->databaseName = 0;
2725         npr->which = Z_NamePlusRecord_databaseRecord;
2726         npr->u.databaseRecord = (Z_External *)
2727             odr_malloc(c->odr_in, sizeof(Z_External));
2728         npr->u.databaseRecord->descriptor = 0;
2729         npr->u.databaseRecord->direct_reference =
2730             yaz_oidval_to_z3950oid(c->odr_in, CLASS_RECSYN, VAL_TEXT_XML);
2731         npr->u.databaseRecord->which = Z_External_octet;
2732         npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
2733             odr_malloc(c->odr_in, sizeof(Odr_oct));
2734         npr->u.databaseRecord->u.octet_aligned->buf = 
2735             res->records[i].recordData_buf;
2736         npr->u.databaseRecord->u.octet_aligned->len = 
2737             npr->u.databaseRecord->u.octet_aligned->size = 
2738             res->records[i].recordData_len;
2739         record_cache_add (resultset, npr, pos);
2740     }
2741     if (res->num_diagnostics > 0)
2742     {
2743         set_dset_error(c, *res->diagnostics[0].code, "SRW",
2744                        res->diagnostics[0].details, 0);
2745     }
2746     nmem = odr_extract_mem(c->odr_in);
2747     nmem_transfer(resultset->odr->mem, nmem);
2748     nmem_destroy(nmem);
2749 }
2750 #endif
2751
2752 #if HAVE_XML2
2753 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
2754 {
2755     int ret = -1;
2756     const char *content_type = z_HTTP_header_lookup(hres->headers,
2757                                                     "Content-Type");
2758     const char *connection_head = z_HTTP_header_lookup(hres->headers,
2759                                                        "Connection");
2760     c->mask = 0;
2761     yaz_log (LOG_DEBUG, "handle_http");
2762
2763     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2764     {
2765         Z_SOAP *soap_package = 0;
2766         ODR o = odr_createmem(ODR_DECODE);
2767         Z_SOAP_Handler soap_handlers[2] = {
2768             {"http://www.loc.gov/zing/srw/v1.0/", 0,
2769              (Z_SOAP_fun) yaz_srw_codec},
2770             {0, 0, 0}
2771         };
2772         ret = z_soap_codec(o, &soap_package,
2773                            &hres->content_buf, &hres->content_len,
2774                            soap_handlers);
2775         if (!ret && soap_package->which == Z_SOAP_generic &&
2776             soap_package->u.generic->no == 0)
2777         {
2778             Z_SRW_PDU *sr = soap_package->u.generic->p;
2779             if (sr->which == Z_SRW_searchRetrieve_response)
2780                 handle_srw_response(c, sr->u.response);
2781             else
2782                 ret = -1;
2783         }
2784         else if (!ret && (soap_package->which == Z_SOAP_fault
2785                           || soap_package->which == Z_SOAP_error))
2786         {
2787             set_HTTP_error(c, hres->code,
2788                            soap_package->u.fault->fault_code,
2789                            soap_package->u.fault->fault_string);
2790         }
2791         else
2792             ret = -1;
2793         odr_destroy(o);
2794     }
2795     if (ret)
2796     {
2797         if (hres->code != 200)
2798             set_HTTP_error(c, hres->code, 0, 0);
2799         else
2800             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2801         do_close (c);
2802     }
2803     ZOOM_connection_remove_task(c);
2804     if (!strcmp(hres->version, "1.0"))
2805     {
2806         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2807         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2808             do_close(c);
2809     }
2810     else 
2811     {
2812         /* HTTP 1.1: only if no close we stay alive .. */
2813         if (connection_head && !strcmp(connection_head, "close"))
2814             do_close(c);
2815     }
2816 }
2817 #endif
2818
2819 static int do_read (ZOOM_connection c)
2820 {
2821     int r, more;
2822     ZOOM_Event event;
2823     
2824     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
2825     ZOOM_connection_put_event (c, event);
2826     
2827
2828     r = cs_get (c->cs, &c->buf_in, &c->len_in);
2829     more = cs_more(c->cs);
2830     yaz_log (LOG_DEBUG, "do_read len=%d more=%d", r, more);
2831     if (r == 1)
2832         return 0;
2833     if (r <= 0)
2834     {
2835         if (c->reconnect_ok)
2836         {
2837             do_close (c);
2838             c->reconnect_ok = 0;
2839             yaz_log (LOG_DEBUG, "reconnect read");
2840             c->tasks->running = 0;
2841             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2842         }
2843         else
2844         {
2845             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
2846             do_close (c);
2847         }
2848     }
2849     else
2850     {
2851         Z_GDU *gdu;
2852         ZOOM_Event event;
2853
2854         odr_reset (c->odr_in);
2855         odr_setbuf (c->odr_in, c->buf_in, r, 0);
2856         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
2857         ZOOM_connection_put_event (c, event);
2858
2859         if (!z_GDU (c->odr_in, &gdu, 0, 0))
2860         {
2861             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2862             do_close (c);
2863         }
2864         else if (gdu->which == Z_GDU_Z3950)
2865             handle_apdu (c, gdu->u.z3950);
2866         else if (gdu->which == Z_GDU_HTTP_Response)
2867         {
2868 #if HAVE_XML2
2869             handle_http (c, gdu->u.HTTP_Response);
2870 #else
2871             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2872             do_close (c);
2873 #endif
2874         }
2875         c->reconnect_ok = 0;
2876     }
2877     return 1;
2878 }
2879
2880 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
2881 {
2882     int r;
2883     ZOOM_Event event;
2884     
2885     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
2886     ZOOM_connection_put_event (c, event);
2887
2888     yaz_log (LOG_DEBUG, "do_write_ex len=%d", len_out);
2889     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
2890     {
2891         if (c->reconnect_ok)
2892         {
2893             do_close (c);
2894             c->reconnect_ok = 0;
2895             yaz_log (LOG_DEBUG, "reconnect write");
2896             c->tasks->running = 0;
2897             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2898             return zoom_pending;
2899         }
2900         if (c->state == STATE_CONNECTING)
2901             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
2902         else
2903             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
2904         do_close (c);
2905         return zoom_complete;
2906     }
2907     else if (r == 1)
2908     {    
2909         c->mask = ZOOM_SELECT_EXCEPT;
2910         if (c->cs->io_pending & CS_WANT_WRITE)
2911             c->mask += ZOOM_SELECT_WRITE;
2912         if (c->cs->io_pending & CS_WANT_READ)
2913             c->mask += ZOOM_SELECT_READ;
2914         yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
2915     }
2916     else
2917     {
2918         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
2919         yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
2920     }
2921     return zoom_pending;
2922 }
2923
2924 static zoom_ret do_write(ZOOM_connection c)
2925 {
2926     return do_write_ex (c, c->buf_out, c->len_out);
2927 }
2928
2929
2930 ZOOM_API(const char *)
2931 ZOOM_connection_option_get (ZOOM_connection c, const char *key)
2932 {
2933     return ZOOM_options_get (c->options, key);
2934 }
2935
2936 ZOOM_API(void)
2937 ZOOM_connection_option_set (ZOOM_connection c, const char *key,
2938                                   const char *val)
2939 {
2940     ZOOM_options_set (c->options, key, val);
2941 }
2942
2943 ZOOM_API(const char *)
2944 ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
2945 {
2946     return ZOOM_options_get (r->options, key);
2947 }
2948
2949 ZOOM_API(void)
2950 ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
2951                                   const char *val)
2952 {
2953     ZOOM_options_set (r->options, key, val);
2954 }
2955
2956
2957 ZOOM_API(int)
2958 ZOOM_connection_errcode (ZOOM_connection c)
2959 {
2960     return ZOOM_connection_error (c, 0, 0);
2961 }
2962
2963 ZOOM_API(const char *)
2964 ZOOM_connection_errmsg (ZOOM_connection c)
2965 {
2966     const char *msg;
2967     ZOOM_connection_error (c, &msg, 0);
2968     return msg;
2969 }
2970
2971 ZOOM_API(const char *)
2972 ZOOM_connection_addinfo (ZOOM_connection c)
2973 {
2974     const char *addinfo;
2975     ZOOM_connection_error (c, 0, &addinfo);
2976     return addinfo;
2977 }
2978
2979 ZOOM_API(const char *)
2980 ZOOM_diag_str (int error)
2981 {
2982     switch (error)
2983     {
2984     case ZOOM_ERROR_NONE:
2985         return "No error";
2986     case ZOOM_ERROR_CONNECT:
2987         return "Connect failed";
2988     case ZOOM_ERROR_MEMORY:
2989         return "Out of memory";
2990     case ZOOM_ERROR_ENCODE:
2991         return "Encoding failed";
2992     case ZOOM_ERROR_DECODE:
2993         return "Decoding failed";
2994     case ZOOM_ERROR_CONNECTION_LOST:
2995         return "Connection lost";
2996     case ZOOM_ERROR_INIT:
2997         return "Init rejected";
2998     case ZOOM_ERROR_INTERNAL:
2999         return "Internal failure";
3000     case ZOOM_ERROR_TIMEOUT:
3001         return "Timeout";
3002     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
3003         return "Unsupported protocol";
3004     case ZOOM_ERROR_UNSUPPORTED_QUERY:
3005         return "Unsupported query type";
3006     default:
3007         return diagbib1_str (error);
3008     }
3009 }
3010
3011 ZOOM_API(int)
3012 ZOOM_connection_error_x (ZOOM_connection c, const char **cp,
3013                          const char **addinfo, const char **diagset)
3014 {
3015     int error = c->error;
3016     if (cp)
3017     {
3018         if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
3019             *cp = ZOOM_diag_str(error);
3020         else if (!strcmp(c->diagset, "HTTP"))
3021             *cp = z_HTTP_errmsg(c->error);
3022         else if (!strcmp(c->diagset, "Bib-1"))
3023             *cp = ZOOM_diag_str(error);
3024         else if (!strcmp(c->diagset, "SRW"))
3025             *cp = yaz_diag_srw_str(c->error);
3026         else
3027             *cp = "Unknown error and diagnostic set";
3028     }
3029     if (addinfo)
3030         *addinfo = c->addinfo ? c->addinfo : "";
3031     if (diagset)
3032         *diagset = c->diagset ? c->diagset : "";
3033     return c->error;
3034 }
3035
3036 ZOOM_API(int)
3037 ZOOM_connection_error (ZOOM_connection c, const char **cp,
3038                        const char **addinfo)
3039 {
3040     return ZOOM_connection_error_x(c, cp, addinfo, 0);
3041 }
3042
3043 static int ZOOM_connection_do_io(ZOOM_connection c, int mask)
3044 {
3045     ZOOM_Event event = 0;
3046     int r = cs_look(c->cs);
3047     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
3048              c, mask, r);
3049     
3050     if (r == CS_NONE)
3051     {
3052         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
3053         set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
3054         do_close (c);
3055         ZOOM_connection_put_event (c, event);
3056     }
3057     else if (r == CS_CONNECT)
3058     {
3059         int ret;
3060         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
3061
3062         ret = cs_rcvconnect (c->cs);
3063         yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
3064         if (ret == 1)
3065         {
3066             c->mask = ZOOM_SELECT_EXCEPT;
3067             if (c->cs->io_pending & CS_WANT_WRITE)
3068                 c->mask += ZOOM_SELECT_WRITE;
3069             if (c->cs->io_pending & CS_WANT_READ)
3070                 c->mask += ZOOM_SELECT_READ;
3071             ZOOM_connection_put_event (c, event);
3072         }
3073         else if (ret == 0)
3074         {
3075             ZOOM_connection_put_event (c, event);
3076             if (c->proto == PROTO_Z3950)
3077                 ZOOM_connection_send_init(c);
3078             else
3079             {
3080                 /* no init request for SRW .. */
3081                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
3082                 ZOOM_connection_remove_task (c);
3083                 c->mask = 0;
3084                 ZOOM_connection_exec_task (c);
3085             }
3086             c->state = STATE_ESTABLISHED;
3087         }
3088         else
3089         {
3090             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
3091             do_close (c);
3092             ZOOM_connection_put_event (c, event);
3093         }
3094     }
3095     else
3096     {
3097         if (mask & ZOOM_SELECT_READ)
3098             do_read (c);
3099         if (c->cs && (mask & ZOOM_SELECT_WRITE))
3100             do_write (c);
3101     }
3102     return 1;
3103 }
3104
3105 ZOOM_API(int)
3106 ZOOM_connection_last_event(ZOOM_connection cs)
3107 {
3108     if (!cs)
3109         return ZOOM_EVENT_NONE;
3110     return cs->last_event;
3111 }
3112
3113 ZOOM_API(int)
3114 ZOOM_event (int no, ZOOM_connection *cs)
3115 {
3116     int timeout = 5000;
3117 #if HAVE_SYS_POLL_H
3118     struct pollfd pollfds[1024];
3119     ZOOM_connection poll_cs[1024];
3120 #else
3121     struct timeval tv;
3122     fd_set input, output, except;
3123 #endif
3124     int i, r, nfds;
3125     int max_fd = 0;
3126
3127     for (i = 0; i<no; i++)
3128     {
3129         ZOOM_connection c = cs[i];
3130         ZOOM_Event event;
3131         if (c && (event = ZOOM_connection_get_event(c)))
3132         {
3133             ZOOM_Event_destroy (event);
3134             return i+1;
3135         }
3136     }
3137     for (i = 0; i<no; i++)
3138     {
3139         ZOOM_connection c = cs[i];
3140         ZOOM_Event event;
3141         if (c && ZOOM_connection_exec_task (c))
3142         {
3143             if ((event = ZOOM_connection_get_event(c)))
3144             {
3145                 ZOOM_Event_destroy (event);
3146                 return i+1;
3147             }
3148         }
3149     }
3150 #if HAVE_SYS_POLL_H
3151
3152 #else
3153     FD_ZERO (&input);
3154     FD_ZERO (&output);
3155     FD_ZERO (&except);
3156 #endif
3157     nfds = 0;
3158     for (i = 0; i<no; i++)
3159     {
3160         ZOOM_connection c = cs[i];
3161         int fd, mask;
3162         int this_timeout;
3163         
3164         if (!c)
3165             continue;
3166         fd = z3950_connection_socket(c);
3167         mask = z3950_connection_mask(c);
3168
3169         if (fd == -1)
3170             continue;
3171         if (max_fd < fd)
3172             max_fd = fd;
3173
3174         this_timeout = ZOOM_options_get_int (c->options, "timeout", -1);
3175         if (this_timeout != -1 && this_timeout < timeout)
3176             timeout = this_timeout;
3177 #if HAVE_SYS_POLL_H
3178         if (mask)
3179         {
3180             short poll_events = 0;
3181
3182             if (mask & ZOOM_SELECT_READ)
3183                 poll_events += POLLIN;
3184             if (mask & ZOOM_SELECT_WRITE)
3185                 poll_events += POLLOUT;
3186             if (mask & ZOOM_SELECT_EXCEPT)
3187                 poll_events += POLLERR;
3188             pollfds[nfds].fd = fd;
3189             pollfds[nfds].events = poll_events;
3190             pollfds[nfds].revents = 0;
3191             poll_cs[nfds] = c;
3192             nfds++;
3193         }
3194 #else
3195         if (mask & ZOOM_SELECT_READ)
3196         {
3197             FD_SET (fd, &input);
3198             nfds++;
3199         }
3200         if (mask & ZOOM_SELECT_WRITE)
3201         {
3202             FD_SET (fd, &output);
3203             nfds++;
3204         }
3205         if (mask & ZOOM_SELECT_EXCEPT)
3206         {
3207             FD_SET (fd, &except);
3208             nfds++;
3209         }
3210 #endif
3211     }
3212     if (timeout >= 5000)
3213         timeout = 30;
3214
3215     if (!nfds)
3216         return 0;
3217
3218 #if HAVE_SYS_POLL_H
3219     r = poll (pollfds, nfds, timeout * 1000);
3220     for (i = 0; i<nfds; i++)
3221     {
3222         ZOOM_connection c = poll_cs[i];
3223         if (r && c->mask)
3224         {
3225             int mask = 0;
3226             if (pollfds[i].revents & POLLIN)
3227                 mask += ZOOM_SELECT_READ;
3228             if (pollfds[i].revents & POLLOUT)
3229                 mask += ZOOM_SELECT_WRITE;
3230             if (pollfds[i].revents & POLLERR)
3231                 mask += ZOOM_SELECT_EXCEPT;
3232             if (mask)
3233                 ZOOM_connection_do_io(c, mask);
3234         }
3235         else if (r == 0 && c->mask)
3236         {
3237             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
3238             /* timeout and this connection was waiting */
3239             set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
3240             do_close (c);
3241             ZOOM_connection_put_event(c, event);
3242         }
3243     }
3244 #else
3245     tv.tv_sec = timeout;
3246     tv.tv_usec = 0;
3247     yaz_log (LOG_DEBUG, "select start");
3248     r = select (max_fd+1, &input, &output, &except, &tv);
3249     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
3250     for (i = 0; i<no; i++)
3251     {
3252         ZOOM_connection c = cs[i];
3253         int fd, mask;
3254
3255         if (!c)
3256             continue;
3257         fd = z3950_connection_socket(c);
3258         mask = 0;
3259         if (r && c->mask)
3260         {
3261             /* no timeout and real socket */
3262             if (FD_ISSET(fd, &input))
3263                 mask += ZOOM_SELECT_READ;
3264             if (FD_ISSET(fd, &output))
3265                 mask += ZOOM_SELECT_WRITE;
3266             if (FD_ISSET(fd, &except))
3267                 mask += ZOOM_SELECT_EXCEPT;
3268             if (mask)
3269                 ZOOM_connection_do_io(c, mask);
3270         }
3271         if (r == 0 && c->mask)
3272         {
3273             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
3274             /* timeout and this connection was waiting */
3275             set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
3276             do_close (c);
3277             yaz_log (LOG_DEBUG, "timeout");
3278             ZOOM_connection_put_event(c, event);
3279         }
3280     }
3281 #endif
3282     for (i = 0; i<no; i++)
3283     {
3284         ZOOM_connection c = cs[i];
3285         ZOOM_Event event;
3286         if (c && (event = ZOOM_connection_get_event(c)))
3287         {
3288             ZOOM_Event_destroy (event);
3289             return i+1;
3290         }
3291     }
3292     return 0;
3293 }