6af917e464b3e293377165cfadc8970fd24dbc88
[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.7 2003-11-25 23:18:08 adam 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(YAZ_VERSION) + 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, YAZ_VERSION);
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     if (npr->which != Z_NamePlusRecord_databaseRecord)
1513         return 0;
1514
1515     /* from now on - we have a database record .. */
1516     if (!strcmp (type, "render"))
1517     {
1518         Z_External *r = (Z_External *) npr->u.databaseRecord;
1519         oident *ent = oid_getentbyoid(r->direct_reference);
1520
1521         /* render bibliographic record .. */
1522         if (r->which == Z_External_OPAC)
1523         {
1524             r = r->u.opac->bibliographicRecord;
1525             if (!r)
1526                 return 0;
1527             ent = oid_getentbyoid(r->direct_reference);
1528         }
1529         if (r->which == Z_External_sutrs)
1530             return record_iconv_return(rec, len,
1531                                        r->u.sutrs->buf, r->u.sutrs->len,
1532                                        charset);
1533         else if (r->which == Z_External_octet)
1534         {
1535             yaz_marc_t mt;
1536             switch (ent->value)
1537             {
1538             case VAL_SOIF:
1539             case VAL_HTML:
1540             case VAL_SUTRS:
1541                 break;
1542             case VAL_TEXT_XML:
1543             case VAL_APPLICATION_XML:
1544                 break;
1545             default:
1546                 if (!rec->wrbuf_marc)
1547                     rec->wrbuf_marc = wrbuf_alloc();
1548
1549                 mt = yaz_marc_create();
1550                 wrbuf_rewind (rec->wrbuf_marc);
1551                 if (yaz_marc_decode_wrbuf (
1552                         mt, (const char *) r->u.octet_aligned->buf,
1553                         r->u.octet_aligned->len,
1554                         rec->wrbuf_marc) > 0)
1555                 {
1556                     yaz_marc_destroy(mt);
1557                     return record_iconv_return(rec, len,
1558                                                wrbuf_buf(rec->wrbuf_marc),
1559                                                wrbuf_len(rec->wrbuf_marc),
1560                                                charset);
1561                 }
1562                 yaz_marc_destroy(mt);
1563             }
1564             return record_iconv_return(rec, len,
1565                                        (const char *) r->u.octet_aligned->buf,
1566                                        r->u.octet_aligned->len,
1567                                        charset);
1568         }
1569         else if (r->which == Z_External_grs1)
1570         {
1571             if (!rec->wrbuf_marc)
1572                 rec->wrbuf_marc = wrbuf_alloc();
1573             wrbuf_rewind (rec->wrbuf_marc);
1574             yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1575             return record_iconv_return(rec, len,
1576                                        wrbuf_buf(rec->wrbuf_marc),
1577                                        wrbuf_len(rec->wrbuf_marc),
1578                                        charset);
1579         }
1580         return 0;
1581     }
1582     else if (!strcmp (type, "xml") || !strcmp(type, "oai"))
1583     {
1584         Z_External *r = (Z_External *) npr->u.databaseRecord;
1585         oident *ent = oid_getentbyoid(r->direct_reference);
1586
1587         /* render bibliographic record .. */
1588         if (r->which == Z_External_OPAC)
1589         {
1590             r = r->u.opac->bibliographicRecord;
1591             if (!r)
1592                 return 0;
1593             ent = oid_getentbyoid(r->direct_reference);
1594         }
1595         
1596         if (r->which == Z_External_sutrs)
1597             return record_iconv_return(rec, len,
1598                                        (const char *) r->u.sutrs->buf,
1599                                        r->u.sutrs->len,
1600                                        charset);
1601         else if (r->which == Z_External_octet)
1602         {
1603             yaz_marc_t mt;
1604             int marc_decode_type = YAZ_MARC_MARCXML;
1605
1606             if (!strcmp(type, "oai"))
1607                 marc_decode_type = YAZ_MARC_OAIMARC;
1608             switch (ent->value)
1609             {
1610             case VAL_SOIF:
1611             case VAL_HTML:
1612             case VAL_SUTRS:
1613                 break;
1614             case VAL_TEXT_XML:
1615             case VAL_APPLICATION_XML:
1616                 break;
1617             default:
1618                 if (!rec->wrbuf_marc)
1619                     rec->wrbuf_marc = wrbuf_alloc();
1620                 wrbuf_rewind (rec->wrbuf_marc);
1621                 mt = yaz_marc_create();
1622
1623                 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1624                 if (yaz_marc_decode_wrbuf (
1625                         mt, (const char *) r->u.octet_aligned->buf,
1626                         r->u.octet_aligned->len,
1627                         rec->wrbuf_marc) > 0)
1628                 {
1629                     yaz_marc_destroy(mt);
1630                     return record_iconv_return(rec, len,
1631                                                wrbuf_buf(rec->wrbuf_marc),
1632                                                wrbuf_len(rec->wrbuf_marc),
1633                                                charset);
1634                 }
1635                 yaz_marc_destroy(mt);
1636             }
1637             return record_iconv_return(rec, len,
1638                                        (const char *) r->u.octet_aligned->buf,
1639                                        r->u.octet_aligned->len,
1640                                        charset);
1641         }
1642         else if (r->which == Z_External_grs1)
1643         {
1644             if (len) *len = 5;
1645             return "GRS-1";
1646         }
1647         return 0;
1648     }
1649     else if (!strcmp (type, "raw"))
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         return 0;
1669     }
1670     else if (!strcmp (type, "ext"))
1671     {
1672         if (len) *len = -1;
1673         return (const char *) npr->u.databaseRecord;
1674     }
1675     else if (!strcmp (type, "opac"))
1676              
1677     {
1678         Z_External *r = (Z_External *) npr->u.databaseRecord;
1679         if (r->which == Z_External_OPAC)
1680         {
1681             if (!rec->wrbuf_opac)
1682                 rec->wrbuf_opac = wrbuf_alloc();
1683             wrbuf_rewind (rec->wrbuf_opac);
1684             yaz_display_OPAC(rec->wrbuf_opac, r->u.opac, 0);
1685             return record_iconv_return(rec, len,
1686                                        wrbuf_buf(rec->wrbuf_opac),
1687                                        wrbuf_len(rec->wrbuf_opac),
1688                                        charset);
1689         }
1690     }
1691     return 0;
1692 }
1693
1694 static int strcmp_null(const char *v1, const char *v2)
1695 {
1696     if (!v1 && !v2)
1697         return 0;
1698     if (!v1 || !v2)
1699         return -1;
1700     return strcmp(v1, v2);
1701 }
1702
1703 static void record_cache_add (ZOOM_resultset r, Z_NamePlusRecord *npr, 
1704                               int pos)
1705 {
1706     ZOOM_record_cache rc;
1707     const char *elementSetName =
1708         ZOOM_resultset_option_get (r, "elementSetName");
1709     const char *syntax = 
1710         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1711     
1712     ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1713     ZOOM_connection_put_event(r->connection, event);
1714
1715     for (rc = r->record_cache; rc; rc = rc->next)
1716     {
1717         if (pos == rc->pos)
1718         {
1719             if (strcmp_null(r->schema, rc->schema))
1720                 continue;
1721             if (strcmp_null(elementSetName,rc->elementSetName))
1722                 continue;
1723             if (strcmp_null(syntax, rc->syntax))
1724                 continue;
1725             /* not destroying rc->npr (it's handled by nmem )*/
1726             rc->rec.npr = npr;
1727             /* keeping wrbuf_marc too */
1728             return;
1729         }
1730     }
1731     rc = (ZOOM_record_cache) odr_malloc (r->odr, sizeof(*rc));
1732     rc->rec.npr = npr; 
1733     rc->rec.odr = 0;
1734     rc->rec.wrbuf_marc = 0;
1735     rc->rec.wrbuf_iconv = 0;
1736     rc->rec.wrbuf_opac = 0;
1737     if (elementSetName)
1738         rc->elementSetName = odr_strdup (r->odr, elementSetName);
1739     else
1740         rc->elementSetName = 0;
1741
1742     if (syntax)
1743         rc->syntax = odr_strdup (r->odr, syntax);
1744     else
1745         rc->syntax = 0;
1746
1747     if (r->schema)
1748         rc->schema = odr_strdup (r->odr, r->schema);
1749     else
1750         rc->schema = 0;
1751
1752     rc->pos = pos;
1753     rc->next = r->record_cache;
1754     r->record_cache = rc;
1755 }
1756
1757 static ZOOM_record record_cache_lookup (ZOOM_resultset r, int pos)
1758 {
1759     ZOOM_record_cache rc;
1760     const char *elementSetName =
1761         ZOOM_resultset_option_get (r, "elementSetName");
1762     const char *syntax = 
1763         ZOOM_resultset_option_get (r, "preferredRecordSyntax");
1764     
1765     for (rc = r->record_cache; rc; rc = rc->next)
1766     {
1767         if (pos == rc->pos)
1768         {
1769             if (strcmp_null(r->schema, rc->schema))
1770                 continue;
1771             if (strcmp_null(elementSetName,rc->elementSetName))
1772                 continue;
1773             if (strcmp_null(syntax, rc->syntax))
1774                 continue;
1775             return &rc->rec;
1776         }
1777     }
1778     return 0;
1779 }
1780                                              
1781 static void handle_records (ZOOM_connection c, Z_Records *sr,
1782                             int present_phase)
1783 {
1784     ZOOM_resultset resultset;
1785
1786     if (!c->tasks)
1787         return ;
1788     switch (c->tasks->which)
1789     {
1790     case ZOOM_TASK_SEARCH:
1791         resultset = c->tasks->u.search.resultset;
1792         break;
1793     case ZOOM_TASK_RETRIEVE:
1794         resultset = c->tasks->u.retrieve.resultset;        
1795         break;
1796     default:
1797         return;
1798     }
1799     if (sr && sr->which == Z_Records_NSD)
1800     {
1801         Z_DiagRec dr, *dr_p = &dr;
1802         dr.which = Z_DiagRec_defaultFormat;
1803         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1804         
1805         response_diag (c, dr_p);
1806     }
1807     else if (sr && sr->which == Z_Records_multipleNSD)
1808     {
1809         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1810             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1811         else
1812             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1813     }
1814     else 
1815     {
1816         if (resultset->count + resultset->start > resultset->size)
1817             resultset->count = resultset->size - resultset->start;
1818         if (resultset->count < 0)
1819             resultset->count = 0;
1820         if (sr && sr->which == Z_Records_DBOSD)
1821         {
1822             int i;
1823             NMEM nmem = odr_extract_mem (c->odr_in);
1824             Z_NamePlusRecordList *p =
1825                 sr->u.databaseOrSurDiagnostics;
1826             for (i = 0; i<p->num_records; i++)
1827             {
1828                 record_cache_add (resultset, p->records[i],
1829                                   i+ resultset->start);
1830             }
1831             /* transfer our response to search_nmem .. we need it later */
1832             nmem_transfer (resultset->odr->mem, nmem);
1833             nmem_destroy (nmem);
1834             if (present_phase && p->num_records == 0)
1835             {
1836                 /* present response and we didn't get any records! */
1837                 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1838             }
1839         }
1840         else if (present_phase)
1841         {
1842             /* present response and we didn't get any records! */
1843             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1844         }
1845     }
1846 }
1847
1848 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1849 {
1850     handle_records (c, pr->records, 1);
1851 }
1852
1853 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1854 {
1855     ZOOM_resultset resultset;
1856     ZOOM_Event event;
1857     
1858     yaz_log (LOG_DEBUG, "got search response");
1859     
1860     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1861         return ;
1862     
1863     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
1864     ZOOM_connection_put_event(c, event);
1865
1866     resultset = c->tasks->u.search.resultset;
1867
1868     resultset->size = *sr->resultCount;
1869     handle_records (c, sr->records, 0);
1870 }
1871
1872 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1873 {
1874     if (res->diagnostics && res->num_diagnostics > 0)
1875         response_diag (c, res->diagnostics[0]);
1876 }
1877
1878 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1879 {
1880     NMEM nmem = odr_extract_mem (c->odr_in);
1881     ZOOM_scanset scan;
1882
1883     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1884         return 0;
1885     scan = c->tasks->u.scan.scan;
1886
1887     if (res->entries && res->entries->nonsurrogateDiagnostics)
1888         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1889     scan->scan_response = res;
1890     nmem_transfer (scan->odr->mem, nmem);
1891     if (res->stepSize)
1892         ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1893     if (res->positionOfTerm)
1894         ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1895     if (res->scanStatus)
1896         ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1897     if (res->numberOfEntriesReturned)
1898         ZOOM_options_set_int (scan->options, "number",
1899                               *res->numberOfEntriesReturned);
1900     nmem_destroy (nmem);
1901     return 1;
1902 }
1903
1904 static zoom_ret send_sort (ZOOM_connection c)
1905 {
1906     ZOOM_resultset  resultset;
1907
1908     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1909         return zoom_complete;
1910
1911     resultset = c->tasks->u.search.resultset;
1912
1913     if (c->error)
1914     {
1915         resultset->r_sort_spec = 0;
1916         return zoom_complete;
1917     }
1918     if (resultset->r_sort_spec)
1919     {
1920         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1921         Z_SortRequest *req = apdu->u.sortRequest;
1922         
1923         req->num_inputResultSetNames = 1;
1924         req->inputResultSetNames = (Z_InternationalString **)
1925             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1926         req->inputResultSetNames[0] =
1927             odr_strdup (c->odr_out, resultset->setname);
1928         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1929         req->sortSequence = resultset->r_sort_spec;
1930         resultset->r_sort_spec = 0;
1931         return send_APDU (c, apdu);
1932     }
1933     return zoom_complete;
1934 }
1935
1936 static zoom_ret send_present (ZOOM_connection c)
1937 {
1938     Z_APDU *apdu = 0;
1939     Z_PresentRequest *req = 0;
1940     int i = 0;
1941     const char *syntax = 0;
1942     const char *elementSetName = 0;
1943     ZOOM_resultset  resultset;
1944
1945     if (!c->tasks)
1946         return zoom_complete;
1947
1948     switch (c->tasks->which)
1949     {
1950     case ZOOM_TASK_SEARCH:
1951         resultset = c->tasks->u.search.resultset;
1952         break;
1953     case ZOOM_TASK_RETRIEVE:
1954         resultset = c->tasks->u.retrieve.resultset;
1955         resultset->start = c->tasks->u.retrieve.start;
1956         resultset->count = c->tasks->u.retrieve.count;
1957
1958         if (resultset->start >= resultset->size)
1959             return zoom_complete;
1960         if (resultset->start + resultset->count > resultset->size)
1961             resultset->count = resultset->size - resultset->start;
1962         break;
1963     default:
1964         return zoom_complete;
1965     }
1966
1967     syntax = ZOOM_resultset_option_get (resultset, "preferredRecordSyntax");
1968     elementSetName = ZOOM_resultset_option_get (resultset, "elementSetName");
1969
1970     if (c->error)                  /* don't continue on error */
1971         return zoom_complete;
1972     if (resultset->start < 0)
1973         return zoom_complete;
1974     for (i = 0; i<resultset->count; i++)
1975     {
1976         ZOOM_record rec =
1977             record_cache_lookup (resultset, i + resultset->start);
1978         if (!rec)
1979             break;
1980     }
1981     if (i == resultset->count)
1982         return zoom_complete;
1983
1984     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1985     req = apdu->u.presentRequest;
1986
1987     resultset->start += i;
1988     resultset->count -= i;
1989     *req->resultSetStartPoint = resultset->start + 1;
1990     *req->numberOfRecordsRequested = resultset->step>0 ?
1991         resultset->step : resultset->count;
1992     assert (*req->numberOfRecordsRequested > 0);
1993
1994     if (syntax && *syntax)
1995         req->preferredRecordSyntax =
1996             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1997
1998     if (resultset->schema && *resultset->schema)
1999     {
2000         Z_RecordComposition *compo = (Z_RecordComposition *)
2001             odr_malloc (c->odr_out, sizeof(*compo));
2002
2003         req->recordComposition = compo;
2004         compo->which = Z_RecordComp_complex;
2005         compo->u.complex = (Z_CompSpec *)
2006             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2007         compo->u.complex->selectAlternativeSyntax = (bool_t *) 
2008             odr_malloc(c->odr_out, sizeof(bool_t));
2009         *compo->u.complex->selectAlternativeSyntax = 0;
2010
2011         compo->u.complex->generic = (Z_Specification *)
2012             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2013
2014         compo->u.complex->generic->which = Z_Schema_oid;
2015         compo->u.complex->generic->schema.oid = (Odr_oid *)
2016             yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, resultset->schema);
2017
2018         if (!compo->u.complex->generic->schema.oid)
2019         {
2020             /* OID wasn't a schema! Try record syntax instead. */
2021
2022             compo->u.complex->generic->schema.oid = (Odr_oid *)
2023                 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, resultset->schema);
2024         }
2025         if (elementSetName && *elementSetName)
2026         {
2027             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2028                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2029             compo->u.complex->generic->elementSpec->which =
2030                 Z_ElementSpec_elementSetName;
2031             compo->u.complex->generic->elementSpec->u.elementSetName =
2032                 odr_strdup (c->odr_out, elementSetName);
2033         }
2034         else
2035             compo->u.complex->generic->elementSpec = 0;
2036         compo->u.complex->num_dbSpecific = 0;
2037         compo->u.complex->dbSpecific = 0;
2038         compo->u.complex->num_recordSyntax = 0;
2039         compo->u.complex->recordSyntax = 0;
2040     }
2041     else if (elementSetName && *elementSetName)
2042     {
2043         Z_ElementSetNames *esn = (Z_ElementSetNames *)
2044             odr_malloc (c->odr_out, sizeof(*esn));
2045         Z_RecordComposition *compo = (Z_RecordComposition *)
2046             odr_malloc (c->odr_out, sizeof(*compo));
2047         
2048         esn->which = Z_ElementSetNames_generic;
2049         esn->u.generic = odr_strdup (c->odr_out, elementSetName);
2050         compo->which = Z_RecordComp_simple;
2051         compo->u.simple = esn;
2052         req->recordComposition = compo;
2053     }
2054     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2055     return send_APDU (c, apdu);
2056 }
2057
2058 ZOOM_API(ZOOM_scanset)
2059 ZOOM_connection_scan (ZOOM_connection c, const char *start)
2060 {
2061     ZOOM_scanset scan = (ZOOM_scanset) xmalloc (sizeof(*scan));
2062
2063     scan->connection = c;
2064     scan->odr = odr_createmem (ODR_DECODE);
2065     scan->options = ZOOM_options_create_with_parent (c->options);
2066     scan->refcount = 1;
2067     scan->scan_response = 0;
2068
2069     if ((scan->termListAndStartPoint =
2070          p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
2071                       start)))
2072     {
2073         ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
2074         task->u.scan.scan = scan;
2075         
2076         (scan->refcount)++;
2077         if (!c->async)
2078         {
2079             while (ZOOM_event (1, &c))
2080                 ;
2081         }
2082     }
2083     return scan;
2084 }
2085
2086 ZOOM_API(void)
2087 ZOOM_scanset_destroy (ZOOM_scanset scan)
2088 {
2089     if (!scan)
2090         return;
2091     (scan->refcount)--;
2092     if (scan->refcount == 0)
2093     {
2094         odr_destroy (scan->odr);
2095         
2096         ZOOM_options_destroy (scan->options);
2097         xfree (scan);
2098     }
2099 }
2100
2101 static zoom_ret send_package (ZOOM_connection c)
2102 {
2103     ZOOM_Event event;
2104     if (!c->tasks)
2105         return zoom_complete;
2106     assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2107     
2108     event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
2109     ZOOM_connection_put_event (c, event);
2110     
2111     return do_write_ex (c, c->tasks->u.package->buf_out,
2112                         c->tasks->u.package->len_out);
2113 }
2114
2115 static zoom_ret send_scan (ZOOM_connection c)
2116 {
2117     ZOOM_scanset scan;
2118     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2119     Z_ScanRequest *req = apdu->u.scanRequest;
2120     if (!c->tasks)
2121         return zoom_complete;
2122     assert (c->tasks->which == ZOOM_TASK_SCAN);
2123     scan = c->tasks->u.scan.scan;
2124
2125     req->termListAndStartPoint = scan->termListAndStartPoint;
2126     req->attributeSet = scan->attributeSet;
2127
2128     *req->numberOfTermsRequested =
2129         ZOOM_options_get_int(scan->options, "number", 10);
2130
2131     req->preferredPositionInResponse =
2132         odr_intdup (c->odr_out,
2133                     ZOOM_options_get_int(scan->options, "position", 1));
2134
2135     req->stepSize =
2136         odr_intdup (c->odr_out,
2137                     ZOOM_options_get_int(scan->options, "stepSize", 0));
2138     
2139     req->databaseNames = set_DatabaseNames (c, scan->options, 
2140                                             &req->num_databaseNames);
2141
2142     return send_APDU (c, apdu);
2143 }
2144
2145 ZOOM_API(size_t)
2146 ZOOM_scanset_size (ZOOM_scanset scan)
2147 {
2148     if (!scan || !scan->scan_response || !scan->scan_response->entries)
2149         return 0;
2150     return scan->scan_response->entries->num_entries;
2151 }
2152
2153 ZOOM_API(const char *)
2154 ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
2155                    int *occ, int *len)
2156 {
2157     const char *term = 0;
2158     size_t noent = ZOOM_scanset_size (scan);
2159     Z_ScanResponse *res = scan->scan_response;
2160     
2161     *len = 0;
2162     *occ = 0;
2163     if (pos >= noent)
2164         return 0;
2165     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2166     {
2167         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2168         
2169         if (t->term->which == Z_Term_general)
2170         {
2171             term = (const char *) t->term->u.general->buf;
2172             *len = t->term->u.general->len;
2173         }
2174         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2175     }
2176     return term;
2177 }
2178
2179 ZOOM_API(const char *)
2180 ZOOM_scanset_display_term (ZOOM_scanset scan, size_t pos,
2181                            int *occ, int *len)
2182 {
2183     const char *term = 0;
2184     size_t noent = ZOOM_scanset_size (scan);
2185     Z_ScanResponse *res = scan->scan_response;
2186     
2187     *len = 0;
2188     *occ = 0;
2189     if (pos >= noent)
2190         return 0;
2191     if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2192     {
2193         Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2194
2195         if (t->displayTerm)
2196         {
2197             term = (const char *) t->term->u.general->buf;
2198             *len = strlen(term);
2199         }
2200         else if (t->term->which == Z_Term_general)
2201         {
2202             term = (const char *) t->term->u.general->buf;
2203             *len = t->term->u.general->len;
2204         }
2205         *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2206     }
2207     return term;
2208 }
2209
2210 ZOOM_API(const char *)
2211 ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
2212 {
2213     return ZOOM_options_get (scan->options, key);
2214 }
2215
2216 ZOOM_API(void)
2217 ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
2218                               const char *val)
2219 {
2220     ZOOM_options_set (scan->options, key, val);
2221 }
2222
2223 static Z_APDU *create_es_package (ZOOM_package p, int type)
2224 {
2225     const char *str;
2226     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
2227     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2228     
2229     *req->function = Z_ExtendedServicesRequest_create;
2230     
2231     str = ZOOM_options_get(p->options, "package-name");
2232     if (str && *str)
2233         req->packageName = nmem_strdup (p->odr_out->mem, str);
2234     
2235     str = ZOOM_options_get(p->options, "user-id");
2236     if (str)
2237         req->userId = nmem_strdup (p->odr_out->mem, str);
2238     
2239     req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2240                                               type);
2241
2242     str = ZOOM_options_get(p->options, "function");
2243     if (str)
2244     {
2245         if (!strcmp (str, "create"))
2246             *req->function = 1;
2247         if (!strcmp (str, "delete"))
2248             *req->function = 2;
2249         if (!strcmp (str, "modify"))
2250             *req->function = 3;
2251     }
2252     return apdu;
2253 }
2254
2255 static const char *ill_array_lookup (void *clientData, const char *idx)
2256 {
2257     ZOOM_package p = (ZOOM_package) clientData;
2258     return ZOOM_options_get (p->options, idx+4);
2259 }
2260
2261 static Z_External *encode_ill_request (ZOOM_package p)
2262 {
2263     ODR out = p->odr_out;
2264     ILL_Request *req;
2265     Z_External *r = 0;
2266     struct ill_get_ctl ctl;
2267         
2268     ctl.odr = p->odr_out;
2269     ctl.clientData = p;
2270     ctl.f = ill_array_lookup;
2271         
2272     req = ill_get_ILLRequest(&ctl, "ill", 0);
2273         
2274     if (!ill_Request (out, &req, 0, 0))
2275     {
2276         int ill_request_size;
2277         char *ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2278         if (ill_request_buf)
2279             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2280         return 0;
2281     }
2282     else
2283     {
2284         oident oid;
2285         int illRequest_size = 0;
2286         char *illRequest_buf = odr_getbuf (out, &illRequest_size, 0);
2287                 
2288         oid.proto = PROTO_GENERAL;
2289         oid.oclass = CLASS_GENERAL;
2290         oid.value = VAL_ISO_ILL_1;
2291                 
2292         r = (Z_External *) odr_malloc (out, sizeof(*r));
2293         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
2294         r->indirect_reference = 0;
2295         r->descriptor = 0;
2296         r->which = Z_External_single;
2297                 
2298         r->u.single_ASN1_type = (Odr_oct *)
2299             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
2300         r->u.single_ASN1_type->buf = (unsigned char*)
2301             odr_malloc (out, illRequest_size);
2302         r->u.single_ASN1_type->len = illRequest_size;
2303         r->u.single_ASN1_type->size = illRequest_size;
2304         memcpy (r->u.single_ASN1_type->buf, illRequest_buf, illRequest_size);
2305     }
2306     return r;
2307 }
2308
2309 static Z_ItemOrder *encode_item_order(ZOOM_package p)
2310 {
2311     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc (p->odr_out, sizeof(*req));
2312     const char *str;
2313     
2314     req->which=Z_IOItemOrder_esRequest;
2315     req->u.esRequest = (Z_IORequest *) 
2316         odr_malloc(p->odr_out,sizeof(Z_IORequest));
2317
2318     /* to keep part ... */
2319     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2320         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
2321     req->u.esRequest->toKeep->supplDescription = 0;
2322     req->u.esRequest->toKeep->contact = (Z_IOContact *)
2323         odr_malloc (p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
2324         
2325     str = ZOOM_options_get(p->options, "contact-name");
2326     req->u.esRequest->toKeep->contact->name = str ?
2327         nmem_strdup (p->odr_out->mem, str) : 0;
2328         
2329     str = ZOOM_options_get(p->options, "contact-phone");
2330     req->u.esRequest->toKeep->contact->phone = str ?
2331         nmem_strdup (p->odr_out->mem, str) : 0;
2332         
2333     str = ZOOM_options_get(p->options, "contact-email");
2334     req->u.esRequest->toKeep->contact->email = str ?
2335         nmem_strdup (p->odr_out->mem, str) : 0;
2336         
2337     req->u.esRequest->toKeep->addlBilling = 0;
2338         
2339     /* not to keep part ... */
2340     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2341         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
2342         
2343     str = ZOOM_options_get(p->options, "itemorder-setname");
2344     if (!str)
2345         str = "default";
2346
2347     if (!*str) 
2348         req->u.esRequest->notToKeep->resultSetItem = 0;
2349     else
2350     {
2351         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
2352            odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
2353
2354         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
2355            nmem_strdup (p->odr_out->mem, str);
2356         req->u.esRequest->notToKeep->resultSetItem->item =
2357             (int *) odr_malloc(p->odr_out, sizeof(int));
2358         
2359         str = ZOOM_options_get(p->options, "itemorder-item");
2360         *req->u.esRequest->notToKeep->resultSetItem->item =
2361             (str ? atoi(str) : 1);
2362     }
2363     req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
2364     
2365     return req;
2366 }
2367
2368 Z_APDU *create_admin_package(ZOOM_package p, int type, 
2369                              Z_ESAdminOriginPartToKeep **toKeepP,
2370                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
2371 {
2372     Z_APDU *apdu = create_es_package (p, VAL_ADMINSERVICE);
2373     if (apdu)
2374     {
2375         Z_ESAdminOriginPartToKeep  *toKeep;
2376         Z_ESAdminOriginPartNotToKeep  *notToKeep;
2377         Z_External *r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
2378         const char *first_db = "Default";
2379         int num_db;
2380         char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2381         if (num_db > 0)
2382             first_db = db[0];
2383             
2384         r->direct_reference =
2385             yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2386                                    VAL_ADMINSERVICE);
2387         r->descriptor = 0;
2388         r->indirect_reference = 0;
2389         r->which = Z_External_ESAdmin;
2390         
2391         r->u.adminService = (Z_Admin *)
2392             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
2393         r->u.adminService->which = Z_Admin_esRequest;
2394         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
2395             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
2396         
2397         toKeep = r->u.adminService->u.esRequest->toKeep =
2398             (Z_ESAdminOriginPartToKeep *) 
2399             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
2400         toKeep->which=type;
2401         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
2402         toKeep->u.create=odr_nullval();
2403         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2404         
2405         r->u.adminService->u.esRequest->notToKeep = notToKeep =
2406             (Z_ESAdminOriginPartNotToKeep *)
2407             odr_malloc(p->odr_out,
2408                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
2409         notToKeep->which=Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
2410         notToKeep->u.recordsWillFollow=odr_nullval();
2411         if (toKeepP)
2412             *toKeepP = toKeep;
2413         if (notToKeepP)
2414             *notToKeepP = notToKeep;
2415     }
2416     return apdu;
2417 }
2418
2419 static Z_APDU *create_update_package(ZOOM_package p)
2420 {
2421     Z_APDU *apdu = 0;
2422     const char *first_db = "Default";
2423     int num_db;
2424     char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2425     const char *action = ZOOM_options_get(p->options, "action");
2426     const char *recordId = ZOOM_options_get(p->options, "recordId");
2427     const char *record_buf = ZOOM_options_get(p->options, "record");
2428     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
2429     int syntax_oid = VAL_NONE;
2430     int action_no = -1;
2431     
2432     if (syntax_str)
2433         syntax_oid = oid_getvalbyname(syntax_str);
2434     if (!record_buf)
2435     {
2436         record_buf = "void";
2437         syntax_oid = VAL_SUTRS;
2438     }
2439     if (syntax_oid != VAL_NONE)
2440         syntax_oid = VAL_TEXT_XML;
2441     
2442     if (num_db > 0)
2443         first_db = db[0];
2444     
2445     if (!action)
2446         action = "specialUpdate";
2447     
2448     if (!strcmp(action, "recordInsert"))
2449         action_no = Z_IUOriginPartToKeep_recordInsert;
2450     else if (!strcmp(action, "recordReplace"))
2451         action_no = Z_IUOriginPartToKeep_recordReplace;
2452     else if (!strcmp(action, "recordDelete"))
2453         action_no = Z_IUOriginPartToKeep_recordDelete;
2454     else if (!strcmp(action, "elementUpdate"))
2455         action_no = Z_IUOriginPartToKeep_elementUpdate;
2456     else if (!strcmp(action, "specialUpdate"))
2457         action_no = Z_IUOriginPartToKeep_specialUpdate;
2458     else
2459         return 0;
2460
2461     apdu = create_es_package (p, VAL_DBUPDATE);
2462     if (apdu)
2463     {
2464         Z_IUOriginPartToKeep *toKeep;
2465         Z_IUSuppliedRecords *notToKeep;
2466         Z_External *r = (Z_External *)
2467             odr_malloc (p->odr_out, sizeof(*r));
2468         
2469         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2470         
2471         r->direct_reference =
2472             yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2473                                    VAL_DBUPDATE);
2474         r->descriptor = 0;
2475         r->which = Z_External_update;
2476         r->indirect_reference = 0;
2477         r->u.update = (Z_IUUpdate *)
2478             odr_malloc(p->odr_out, sizeof(*r->u.update));
2479         
2480         r->u.update->which = Z_IUUpdate_esRequest;
2481         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2482             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
2483         toKeep = r->u.update->u.esRequest->toKeep = 
2484             (Z_IUOriginPartToKeep *)
2485             odr_malloc(p->odr_out, sizeof(*toKeep));
2486         
2487         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
2488         toKeep->schema = 0;
2489         toKeep->elementSetName = 0;
2490         toKeep->actionQualifier = 0;
2491         toKeep->action = odr_intdup(p->odr_out, action_no);
2492         
2493         notToKeep = r->u.update->u.esRequest->notToKeep = 
2494             (Z_IUSuppliedRecords *)
2495             odr_malloc(p->odr_out, sizeof(*notToKeep));
2496         notToKeep->num = 1;
2497         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2498             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
2499         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2500             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
2501         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2502         if (recordId)
2503         {
2504             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2505                 odr_malloc (p->odr_out, sizeof(Odr_oct));
2506             notToKeep->elements[0]->u.opaque->size = strlen(recordId);
2507             notToKeep->elements[0]->u.opaque->len = strlen(recordId);
2508             notToKeep->elements[0]->u.opaque->buf =
2509                 odr_strdup(p->odr_out, recordId);
2510         }
2511         else
2512             notToKeep->elements[0]->u.opaque = 0;
2513         notToKeep->elements[0]->supplementalId = 0;
2514         notToKeep->elements[0]->correlationInfo = 0;
2515         notToKeep->elements[0]->record =
2516             z_ext_record(p->odr_out, syntax_oid,
2517                          record_buf, strlen(record_buf));
2518     }
2519     if (0 && apdu)
2520     {
2521        ODR print = odr_createmem(ODR_PRINT);
2522
2523        z_APDU(print, &apdu, 0, 0);
2524        odr_destroy(print);
2525     }
2526     return apdu;
2527 }
2528
2529 ZOOM_API(void)
2530     ZOOM_package_send (ZOOM_package p, const char *type)
2531 {
2532     Z_APDU *apdu = 0;
2533     ZOOM_connection c;
2534     if (!p)
2535         return;
2536     c = p->connection;
2537     odr_reset (p->odr_out);
2538     xfree (p->buf_out);
2539     p->buf_out = 0;
2540     if (!strcmp(type, "itemorder"))
2541     {
2542         apdu = create_es_package (p, VAL_ITEMORDER);
2543         if (apdu)
2544         {
2545             Z_External *r = (Z_External *) odr_malloc (p->odr_out, sizeof(*r));
2546             
2547             r->direct_reference =
2548                 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2549                                        VAL_ITEMORDER);
2550             r->descriptor = 0;
2551             r->which = Z_External_itemOrder;
2552             r->indirect_reference = 0;
2553             r->u.itemOrder = encode_item_order (p);
2554
2555             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2556         }
2557     }
2558     if (!strcmp(type, "create"))  /* create database */
2559     {
2560         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
2561                                     0, 0);
2562     }   
2563     if (!strcmp(type, "drop"))  /* drop database */
2564     {
2565         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
2566                                     0, 0);
2567     }
2568     if (!strcmp(type, "update")) /* update record(s) */
2569     {
2570         apdu = create_update_package(p);
2571     }
2572     if (apdu)
2573     {
2574         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
2575         {
2576             char *buf;
2577
2578             ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_PACKAGE);
2579             task->u.package = p;
2580             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
2581             p->buf_out = (char *) xmalloc (p->len_out);
2582             memcpy (p->buf_out, buf, p->len_out);
2583             
2584             (p->refcount)++;
2585             if (!c->async)
2586             {
2587                 while (ZOOM_event (1, &c))
2588                     ;
2589             }
2590         }
2591     }
2592 }
2593
2594 ZOOM_API(ZOOM_package)
2595     ZOOM_connection_package (ZOOM_connection c, ZOOM_options options)
2596 {
2597     ZOOM_package p = (ZOOM_package) xmalloc (sizeof(*p));
2598
2599     p->connection = c;
2600     p->odr_out = odr_createmem (ODR_ENCODE);
2601     p->options = ZOOM_options_create_with_parent2 (options, c->options);
2602     p->refcount = 1;
2603     p->buf_out = 0;
2604     p->len_out = 0;
2605     return p;
2606 }
2607
2608 ZOOM_API(void)
2609     ZOOM_package_destroy(ZOOM_package p)
2610 {
2611     if (!p)
2612         return;
2613     (p->refcount)--;
2614     if (p->refcount == 0)
2615     {
2616         odr_destroy (p->odr_out);
2617         xfree (p->buf_out);
2618         
2619         ZOOM_options_destroy (p->options);
2620         xfree (p);
2621     }
2622 }
2623
2624 ZOOM_API(const char *)
2625 ZOOM_package_option_get (ZOOM_package p, const char *key)
2626 {
2627     return ZOOM_options_get (p->options, key);
2628 }
2629
2630
2631 ZOOM_API(void)
2632 ZOOM_package_option_set (ZOOM_package p, const char *key,
2633                               const char *val)
2634 {
2635     ZOOM_options_set (p->options, key, val);
2636 }
2637
2638 static int ZOOM_connection_exec_task (ZOOM_connection c)
2639 {
2640     ZOOM_task task = c->tasks;
2641     zoom_ret ret = zoom_complete;
2642
2643     if (!task)
2644     {
2645         yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task task=<null>");
2646         return 0;
2647     }
2648     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d run=%d",
2649              task->which, task->running);
2650     if (c->error != ZOOM_ERROR_NONE)
2651     {
2652         yaz_log (LOG_DEBUG, "remove tasks because of error = %d", c->error);
2653         ZOOM_connection_remove_tasks (c);
2654         return 0;
2655     }
2656     if (task->running)
2657     {
2658         yaz_log (LOG_DEBUG, "task already running");
2659         return 0;
2660     }
2661     task->running = 1;
2662     ret = zoom_complete;
2663     if (c->cs || task->which == ZOOM_TASK_CONNECT)
2664     {
2665         switch (task->which)
2666         {
2667         case ZOOM_TASK_SEARCH:
2668             if (c->proto == PROTO_HTTP)
2669                 ret = ZOOM_connection_srw_send_search(c);
2670             else
2671                 ret = ZOOM_connection_send_search(c);
2672             break;
2673         case ZOOM_TASK_RETRIEVE:
2674             if (c->proto == PROTO_HTTP)
2675                 ret = ZOOM_connection_srw_send_search(c);
2676             else
2677                 ret = send_present (c);
2678             break;
2679         case ZOOM_TASK_CONNECT:
2680             ret = do_connect(c);
2681             break;
2682         case ZOOM_TASK_SCAN:
2683             ret = send_scan(c);
2684             break;
2685         case ZOOM_TASK_PACKAGE:
2686             ret = send_package(c);
2687             break;
2688         }
2689     }
2690     else
2691     {
2692         yaz_log (LOG_DEBUG, "remove tasks because no connection exist");
2693         ZOOM_connection_remove_tasks (c);
2694     }
2695     if (ret == zoom_complete)
2696     {
2697         yaz_log (LOG_DEBUG, "task removed (complete)");
2698         ZOOM_connection_remove_task (c);
2699         return 0;
2700     }
2701     yaz_log (LOG_DEBUG, "task pending");
2702     return 1;
2703 }
2704
2705 static zoom_ret send_sort_present (ZOOM_connection c)
2706 {
2707     zoom_ret r = send_sort (c);
2708     if (r == zoom_complete)
2709         r = send_present (c);
2710     return r;
2711 }
2712
2713 static int es_response (ZOOM_connection c,
2714                         Z_ExtendedServicesResponse *res)
2715 {
2716     if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
2717         return 0;
2718     if (res->diagnostics && res->num_diagnostics > 0)
2719         response_diag(c, res->diagnostics[0]);
2720     if (res->taskPackage &&
2721         res->taskPackage->which == Z_External_extendedService)
2722     {
2723         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
2724         Odr_oct *id = taskPackage->targetReference;
2725         
2726         if (id)
2727             ZOOM_options_setl (c->tasks->u.package->options,
2728                                "targetReference", (char*) id->buf, id->len);
2729     }
2730     return 1;
2731 }
2732
2733
2734 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
2735 {
2736     Z_InitResponse *initrs;
2737     
2738     c->mask = 0;
2739     yaz_log (LOG_DEBUG, "recv APDU type=%d", apdu->which);
2740     switch(apdu->which)
2741     {
2742     case Z_APDU_initResponse:
2743         initrs = apdu->u.initResponse;
2744         ZOOM_connection_option_set(c, "serverImplementationId",
2745                                    initrs->implementationId ?
2746                                    initrs->implementationId : "");
2747         ZOOM_connection_option_set(c, "serverImplementationName",
2748                                    initrs->implementationName ?
2749                                    initrs->implementationName : "");
2750         ZOOM_connection_option_set(c, "serverImplementationVersion",
2751                                    initrs->implementationVersion ?
2752                                    initrs->implementationVersion : "");
2753         /* Set the three old options too, for old applications */
2754         ZOOM_connection_option_set(c, "targetImplementationId",
2755                                    initrs->implementationId ?
2756                                    initrs->implementationId : "");
2757         ZOOM_connection_option_set(c, "targetImplementationName",
2758                                    initrs->implementationName ?
2759                                    initrs->implementationName : "");
2760         ZOOM_connection_option_set(c, "targetImplementationVersion",
2761                                    initrs->implementationVersion ?
2762                                    initrs->implementationVersion : "");
2763         if (!*initrs->result)
2764         {
2765             set_ZOOM_error(c, ZOOM_ERROR_INIT, 0);
2766         }
2767         else
2768         {
2769             char *cookie =
2770                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
2771                                           VAL_COOKIE, 1, 0);
2772             xfree (c->cookie_in);
2773             c->cookie_in = 0;
2774             if (cookie)
2775                 c->cookie_in = xstrdup(cookie);
2776             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
2777                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
2778                 c->support_named_resultsets = 1;
2779             if (c->tasks)
2780             {
2781                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
2782                 ZOOM_connection_remove_task (c);
2783             }
2784             ZOOM_connection_exec_task (c);
2785         }
2786         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
2787         {
2788             NMEM tmpmem = nmem_create();
2789             Z_CharSetandLanguageNegotiation *p =
2790                 yaz_get_charneg_record(initrs->otherInfo);
2791             
2792             if (p)
2793             {
2794                 char *charset=NULL, *lang=NULL;
2795                 int sel;
2796                 
2797                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
2798                 yaz_log(LOG_DEBUG, "Target accepted: charset %s, "
2799                         "language %s, select %d",
2800                         charset ? charset : "none", lang ? lang : "none", sel);
2801                 if (charset)
2802                     ZOOM_connection_option_set (c, "negotiation-charset",
2803                                                 charset);
2804                 if (lang)
2805                     ZOOM_connection_option_set (c, "negotiation-lang",
2806                                                 lang);
2807                 nmem_destroy(tmpmem);
2808             }
2809         }       
2810         break;
2811     case Z_APDU_searchResponse:
2812         handle_search_response (c, apdu->u.searchResponse);
2813         if (send_sort_present (c) == zoom_complete)
2814             ZOOM_connection_remove_task (c);
2815         break;
2816     case Z_APDU_presentResponse:
2817         handle_present_response (c, apdu->u.presentResponse);
2818         if (send_present (c) == zoom_complete)
2819             ZOOM_connection_remove_task (c);
2820         break;
2821     case Z_APDU_sortResponse:
2822         sort_response (c, apdu->u.sortResponse);
2823         if (send_present (c) == zoom_complete)
2824             ZOOM_connection_remove_task (c);
2825         break;
2826     case Z_APDU_scanResponse:
2827         scan_response (c, apdu->u.scanResponse);
2828         ZOOM_connection_remove_task (c);
2829         break;
2830     case Z_APDU_extendedServicesResponse:
2831         es_response (c, apdu->u.extendedServicesResponse);
2832         ZOOM_connection_remove_task (c);
2833         break;
2834     case Z_APDU_close:
2835         if (c->reconnect_ok)
2836         {
2837             do_close(c);
2838             c->tasks->running = 0;
2839             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
2840         }
2841         else
2842         {
2843             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
2844             do_close(c);
2845         }
2846         break;
2847     default:
2848         set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2849         do_close(c);
2850     }
2851 }
2852
2853 #if HAVE_XML2
2854 static void handle_srw_response(ZOOM_connection c,
2855                                 Z_SRW_searchRetrieveResponse *res)
2856 {
2857     ZOOM_resultset resultset = 0;
2858     int i;
2859     NMEM nmem;
2860     ZOOM_Event event;
2861
2862     if (!c->tasks)
2863         return;
2864
2865     if (c->tasks->which == ZOOM_TASK_SEARCH)
2866         resultset = c->tasks->u.search.resultset;
2867     else if (c->tasks->which == ZOOM_TASK_RETRIEVE)
2868         resultset = c->tasks->u.retrieve.resultset;
2869     else
2870         return ;
2871
2872     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2873     ZOOM_connection_put_event(c, event);
2874
2875     resultset->size = 0;
2876
2877     yaz_log(LOG_DEBUG, "got SRW response OK");
2878     
2879     if (res->numberOfRecords)
2880         resultset->size = *res->numberOfRecords;
2881
2882     for (i = 0; i<res->num_records; i++)
2883     {
2884         int pos;
2885
2886         Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
2887             odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
2888
2889         if (res->records[i].recordPosition && 
2890             *res->records[i].recordPosition > 0)
2891             pos = *res->records[i].recordPosition - 1;
2892         else
2893             pos = resultset->start + i;
2894         
2895         npr->databaseName = 0;
2896         npr->which = Z_NamePlusRecord_databaseRecord;
2897         npr->u.databaseRecord = (Z_External *)
2898             odr_malloc(c->odr_in, sizeof(Z_External));
2899         npr->u.databaseRecord->descriptor = 0;
2900         npr->u.databaseRecord->direct_reference =
2901             yaz_oidval_to_z3950oid(c->odr_in, CLASS_RECSYN, VAL_TEXT_XML);
2902         npr->u.databaseRecord->which = Z_External_octet;
2903         npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
2904             odr_malloc(c->odr_in, sizeof(Odr_oct));
2905         npr->u.databaseRecord->u.octet_aligned->buf = 
2906             res->records[i].recordData_buf;
2907         npr->u.databaseRecord->u.octet_aligned->len = 
2908             npr->u.databaseRecord->u.octet_aligned->size = 
2909             res->records[i].recordData_len;
2910         record_cache_add (resultset, npr, pos);
2911     }
2912     if (res->num_diagnostics > 0)
2913     {
2914         set_dset_error(c, *res->diagnostics[0].code, "SRW",
2915                        res->diagnostics[0].details, 0);
2916     }
2917     nmem = odr_extract_mem(c->odr_in);
2918     nmem_transfer(resultset->odr->mem, nmem);
2919     nmem_destroy(nmem);
2920 }
2921 #endif
2922
2923 #if HAVE_XML2
2924 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
2925 {
2926     int ret = -1;
2927     const char *content_type = z_HTTP_header_lookup(hres->headers,
2928                                                     "Content-Type");
2929     const char *connection_head = z_HTTP_header_lookup(hres->headers,
2930                                                        "Connection");
2931     c->mask = 0;
2932     yaz_log (LOG_DEBUG, "handle_http");
2933
2934     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2935     {
2936         Z_SOAP *soap_package = 0;
2937         ODR o = odr_createmem(ODR_DECODE);
2938         Z_SOAP_Handler soap_handlers[2] = {
2939             {"http://www.loc.gov/zing/srw/v1.0/", 0,
2940              (Z_SOAP_fun) yaz_srw_codec},
2941             {0, 0, 0}
2942         };
2943         ret = z_soap_codec(o, &soap_package,
2944                            &hres->content_buf, &hres->content_len,
2945                            soap_handlers);
2946         if (!ret && soap_package->which == Z_SOAP_generic &&
2947             soap_package->u.generic->no == 0)
2948         {
2949             Z_SRW_PDU *sr = soap_package->u.generic->p;
2950             if (sr->which == Z_SRW_searchRetrieve_response)
2951                 handle_srw_response(c, sr->u.response);
2952             else
2953                 ret = -1;
2954         }
2955         else if (!ret && (soap_package->which == Z_SOAP_fault
2956                           || soap_package->which == Z_SOAP_error))
2957         {
2958             set_HTTP_error(c, hres->code,
2959                            soap_package->u.fault->fault_code,
2960                            soap_package->u.fault->fault_string);
2961         }
2962         else
2963             ret = -1;
2964         odr_destroy(o);
2965     }
2966     if (ret)
2967     {
2968         if (hres->code != 200)
2969             set_HTTP_error(c, hres->code, 0, 0);
2970         else
2971             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2972         do_close (c);
2973     }
2974     ZOOM_connection_remove_task(c);
2975     if (!strcmp(hres->version, "1.0"))
2976     {
2977         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2978         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2979             do_close(c);
2980     }
2981     else 
2982     {
2983         /* HTTP 1.1: only if no close we stay alive .. */
2984         if (connection_head && !strcmp(connection_head, "close"))
2985             do_close(c);
2986     }
2987 }
2988 #endif
2989
2990 static int do_read (ZOOM_connection c)
2991 {
2992     int r, more;
2993     ZOOM_Event event;
2994     
2995     event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
2996     ZOOM_connection_put_event (c, event);
2997     
2998     r = cs_get (c->cs, &c->buf_in, &c->len_in);
2999     more = cs_more(c->cs);
3000     yaz_log (LOG_DEBUG, "do_read len=%d more=%d", r, more);
3001     if (r == 1)
3002         return 0;
3003     if (r <= 0)
3004     {
3005         if (c->reconnect_ok)
3006         {
3007             do_close (c);
3008             c->reconnect_ok = 0;
3009             yaz_log (LOG_DEBUG, "reconnect read");
3010             c->tasks->running = 0;
3011             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
3012         }
3013         else
3014         {
3015             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
3016             do_close (c);
3017         }
3018     }
3019     else
3020     {
3021         Z_GDU *gdu;
3022         ZOOM_Event event;
3023
3024         odr_reset (c->odr_in);
3025         odr_setbuf (c->odr_in, c->buf_in, r, 0);
3026         event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
3027         ZOOM_connection_put_event (c, event);
3028
3029         if (!z_GDU (c->odr_in, &gdu, 0, 0))
3030         {
3031             int x;
3032             int err = odr_geterrorx(c->odr_in, &x);
3033             char msg[60];
3034             const char *element = odr_getelement(c->odr_in);
3035             sprintf (msg, "ODR code %d:%d element=%-20s",
3036                      err, x, element ? element : "<unknown>");
3037             set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
3038             do_close (c);
3039         }
3040         else if (gdu->which == Z_GDU_Z3950)
3041             handle_apdu (c, gdu->u.z3950);
3042         else if (gdu->which == Z_GDU_HTTP_Response)
3043         {
3044 #if HAVE_XML2
3045             handle_http (c, gdu->u.HTTP_Response);
3046 #else
3047             set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3048             do_close (c);
3049 #endif
3050         }
3051         c->reconnect_ok = 0;
3052     }
3053     return 1;
3054 }
3055
3056 static zoom_ret do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
3057 {
3058     int r;
3059     ZOOM_Event event;
3060     
3061     event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
3062     ZOOM_connection_put_event (c, event);
3063
3064     yaz_log (LOG_DEBUG, "do_write_ex len=%d", len_out);
3065     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
3066     {
3067         if (c->reconnect_ok)
3068         {
3069             do_close (c);
3070             c->reconnect_ok = 0;
3071             yaz_log (LOG_DEBUG, "reconnect write");
3072             c->tasks->running = 0;
3073             ZOOM_connection_insert_task (c, ZOOM_TASK_CONNECT);
3074             return zoom_pending;
3075         }
3076         if (c->state == STATE_CONNECTING)
3077             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
3078         else
3079             set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, 0);
3080         do_close (c);
3081         return zoom_complete;
3082     }
3083     else if (r == 1)
3084     {    
3085         c->mask = ZOOM_SELECT_EXCEPT;
3086         if (c->cs->io_pending & CS_WANT_WRITE)
3087             c->mask += ZOOM_SELECT_WRITE;
3088         if (c->cs->io_pending & CS_WANT_READ)
3089             c->mask += ZOOM_SELECT_READ;
3090         yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
3091     }
3092     else
3093     {
3094         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
3095         yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
3096     }
3097     return zoom_pending;
3098 }
3099
3100 static zoom_ret do_write(ZOOM_connection c)
3101 {
3102     return do_write_ex (c, c->buf_out, c->len_out);
3103 }
3104
3105
3106 ZOOM_API(const char *)
3107 ZOOM_connection_option_get (ZOOM_connection c, const char *key)
3108 {
3109     return ZOOM_options_get (c->options, key);
3110 }
3111
3112 ZOOM_API(void)
3113 ZOOM_connection_option_set (ZOOM_connection c, const char *key,
3114                                   const char *val)
3115 {
3116     ZOOM_options_set (c->options, key, val);
3117 }
3118
3119 ZOOM_API(const char *)
3120 ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
3121 {
3122     return ZOOM_options_get (r->options, key);
3123 }
3124
3125 ZOOM_API(void)
3126 ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
3127                                   const char *val)
3128 {
3129     ZOOM_options_set (r->options, key, val);
3130 }
3131
3132
3133 ZOOM_API(int)
3134 ZOOM_connection_errcode (ZOOM_connection c)
3135 {
3136     return ZOOM_connection_error (c, 0, 0);
3137 }
3138
3139 ZOOM_API(const char *)
3140 ZOOM_connection_errmsg (ZOOM_connection c)
3141 {
3142     const char *msg;
3143     ZOOM_connection_error (c, &msg, 0);
3144     return msg;
3145 }
3146
3147 ZOOM_API(const char *)
3148 ZOOM_connection_addinfo (ZOOM_connection c)
3149 {
3150     const char *addinfo;
3151     ZOOM_connection_error (c, 0, &addinfo);
3152     return addinfo;
3153 }
3154
3155 ZOOM_API(const char *)
3156 ZOOM_diag_str (int error)
3157 {
3158     switch (error)
3159     {
3160     case ZOOM_ERROR_NONE:
3161         return "No error";
3162     case ZOOM_ERROR_CONNECT:
3163         return "Connect failed";
3164     case ZOOM_ERROR_MEMORY:
3165         return "Out of memory";
3166     case ZOOM_ERROR_ENCODE:
3167         return "Encoding failed";
3168     case ZOOM_ERROR_DECODE:
3169         return "Decoding failed";
3170     case ZOOM_ERROR_CONNECTION_LOST:
3171         return "Connection lost";
3172     case ZOOM_ERROR_INIT:
3173         return "Init rejected";
3174     case ZOOM_ERROR_INTERNAL:
3175         return "Internal failure";
3176     case ZOOM_ERROR_TIMEOUT:
3177         return "Timeout";
3178     case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
3179         return "Unsupported protocol";
3180     case ZOOM_ERROR_UNSUPPORTED_QUERY:
3181         return "Unsupported query type";
3182     default:
3183         return diagbib1_str (error);
3184     }
3185 }
3186
3187 ZOOM_API(int)
3188 ZOOM_connection_error_x (ZOOM_connection c, const char **cp,
3189                          const char **addinfo, const char **diagset)
3190 {
3191     int error = c->error;
3192     if (cp)
3193     {
3194         if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
3195             *cp = ZOOM_diag_str(error);
3196         else if (!strcmp(c->diagset, "HTTP"))
3197             *cp = z_HTTP_errmsg(c->error);
3198         else if (!strcmp(c->diagset, "Bib-1"))
3199             *cp = ZOOM_diag_str(error);
3200         else if (!strcmp(c->diagset, "SRW"))
3201             *cp = yaz_diag_srw_str(c->error);
3202         else
3203             *cp = "Unknown error and diagnostic set";
3204     }
3205     if (addinfo)
3206         *addinfo = c->addinfo ? c->addinfo : "";
3207     if (diagset)
3208         *diagset = c->diagset ? c->diagset : "";
3209     return c->error;
3210 }
3211
3212 ZOOM_API(int)
3213 ZOOM_connection_error (ZOOM_connection c, const char **cp,
3214                        const char **addinfo)
3215 {
3216     return ZOOM_connection_error_x(c, cp, addinfo, 0);
3217 }
3218
3219 static int ZOOM_connection_do_io(ZOOM_connection c, int mask)
3220 {
3221     ZOOM_Event event = 0;
3222     int r = cs_look(c->cs);
3223     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
3224              c, mask, r);
3225     
3226     if (r == CS_NONE)
3227     {
3228         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
3229         set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
3230         do_close (c);
3231         ZOOM_connection_put_event (c, event);
3232     }
3233     else if (r == CS_CONNECT)
3234     {
3235         int ret;
3236         event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
3237
3238         ret = cs_rcvconnect (c->cs);
3239         yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
3240         if (ret == 1)
3241         {
3242             c->mask = ZOOM_SELECT_EXCEPT;
3243             if (c->cs->io_pending & CS_WANT_WRITE)
3244                 c->mask += ZOOM_SELECT_WRITE;
3245             if (c->cs->io_pending & CS_WANT_READ)
3246                 c->mask += ZOOM_SELECT_READ;
3247             ZOOM_connection_put_event (c, event);
3248         }
3249         else if (ret == 0)
3250         {
3251             ZOOM_connection_put_event (c, event);
3252             if (c->proto == PROTO_Z3950)
3253                 ZOOM_connection_send_init(c);
3254             else
3255             {
3256                 /* no init request for SRW .. */
3257                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
3258                 ZOOM_connection_remove_task (c);
3259                 c->mask = 0;
3260                 ZOOM_connection_exec_task (c);
3261             }
3262             c->state = STATE_ESTABLISHED;
3263         }
3264         else
3265         {
3266             set_ZOOM_error(c, ZOOM_ERROR_CONNECT, 0);
3267             do_close (c);
3268             ZOOM_connection_put_event (c, event);
3269         }
3270     }
3271     else
3272     {
3273         if (mask & ZOOM_SELECT_READ)
3274             do_read (c);
3275         if (c->cs && (mask & ZOOM_SELECT_WRITE))
3276             do_write (c);
3277     }
3278     return 1;
3279 }
3280
3281 ZOOM_API(int)
3282 ZOOM_connection_last_event(ZOOM_connection cs)
3283 {
3284     if (!cs)
3285         return ZOOM_EVENT_NONE;
3286     return cs->last_event;
3287 }
3288
3289 ZOOM_API(int)
3290 ZOOM_event (int no, ZOOM_connection *cs)
3291 {
3292     int timeout = 5000;
3293 #if HAVE_SYS_POLL_H
3294     struct pollfd pollfds[1024];
3295     ZOOM_connection poll_cs[1024];
3296 #else
3297     struct timeval tv;
3298     fd_set input, output, except;
3299 #endif
3300     int i, r, nfds;
3301     int max_fd = 0;
3302
3303     for (i = 0; i<no; i++)
3304     {
3305         ZOOM_connection c = cs[i];
3306         ZOOM_Event event;
3307         if (c && (event = ZOOM_connection_get_event(c)))
3308         {
3309             ZOOM_Event_destroy (event);
3310             return i+1;
3311         }
3312     }
3313     for (i = 0; i<no; i++)
3314     {
3315         ZOOM_connection c = cs[i];
3316         ZOOM_Event event;
3317         if (c && ZOOM_connection_exec_task (c))
3318         {
3319             if ((event = ZOOM_connection_get_event(c)))
3320             {
3321                 ZOOM_Event_destroy (event);
3322                 return i+1;
3323             }
3324         }
3325     }
3326 #if HAVE_SYS_POLL_H
3327
3328 #else
3329     FD_ZERO (&input);
3330     FD_ZERO (&output);
3331     FD_ZERO (&except);
3332 #endif
3333     nfds = 0;
3334     for (i = 0; i<no; i++)
3335     {
3336         ZOOM_connection c = cs[i];
3337         int fd, mask;
3338         int this_timeout;
3339         
3340         if (!c)
3341             continue;
3342         fd = z3950_connection_socket(c);
3343         mask = z3950_connection_mask(c);
3344
3345         if (fd == -1)
3346             continue;
3347         if (max_fd < fd)
3348             max_fd = fd;
3349
3350         this_timeout = ZOOM_options_get_int (c->options, "timeout", -1);
3351         if (this_timeout != -1 && this_timeout < timeout)
3352             timeout = this_timeout;
3353 #if HAVE_SYS_POLL_H
3354         if (mask)
3355         {
3356             short poll_events = 0;
3357
3358             if (mask & ZOOM_SELECT_READ)
3359                 poll_events += POLLIN;
3360             if (mask & ZOOM_SELECT_WRITE)
3361                 poll_events += POLLOUT;
3362             if (mask & ZOOM_SELECT_EXCEPT)
3363                 poll_events += POLLERR;
3364             pollfds[nfds].fd = fd;
3365             pollfds[nfds].events = poll_events;
3366             pollfds[nfds].revents = 0;
3367             poll_cs[nfds] = c;
3368             nfds++;
3369         }
3370 #else
3371         if (mask & ZOOM_SELECT_READ)
3372         {
3373             FD_SET (fd, &input);
3374             nfds++;
3375         }
3376         if (mask & ZOOM_SELECT_WRITE)
3377         {
3378             FD_SET (fd, &output);
3379             nfds++;
3380         }
3381         if (mask & ZOOM_SELECT_EXCEPT)
3382         {
3383             FD_SET (fd, &except);
3384             nfds++;
3385         }
3386 #endif
3387     }
3388     if (timeout >= 5000)
3389         timeout = 30;
3390
3391     if (!nfds)
3392         return 0;
3393
3394 #if HAVE_SYS_POLL_H
3395     r = poll (pollfds, nfds, timeout * 1000);
3396     for (i = 0; i<nfds; i++)
3397     {
3398         ZOOM_connection c = poll_cs[i];
3399         if (r && c->mask)
3400         {
3401             int mask = 0;
3402             if (pollfds[i].revents & POLLIN)
3403                 mask += ZOOM_SELECT_READ;
3404             if (pollfds[i].revents & POLLOUT)
3405                 mask += ZOOM_SELECT_WRITE;
3406             if (pollfds[i].revents & POLLERR)
3407                 mask += ZOOM_SELECT_EXCEPT;
3408             if (mask)
3409                 ZOOM_connection_do_io(c, mask);
3410         }
3411         else if (r == 0 && c->mask)
3412         {
3413             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
3414             /* timeout and this connection was waiting */
3415             set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
3416             do_close (c);
3417             ZOOM_connection_put_event(c, event);
3418         }
3419     }
3420 #else
3421     tv.tv_sec = timeout;
3422     tv.tv_usec = 0;
3423     yaz_log (LOG_DEBUG, "select start");
3424     r = select (max_fd+1, &input, &output, &except, &tv);
3425     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
3426     for (i = 0; i<no; i++)
3427     {
3428         ZOOM_connection c = cs[i];
3429         int fd, mask;
3430
3431         if (!c)
3432             continue;
3433         fd = z3950_connection_socket(c);
3434         mask = 0;
3435         if (r && c->mask)
3436         {
3437             /* no timeout and real socket */
3438             if (FD_ISSET(fd, &input))
3439                 mask += ZOOM_SELECT_READ;
3440             if (FD_ISSET(fd, &output))
3441                 mask += ZOOM_SELECT_WRITE;
3442             if (FD_ISSET(fd, &except))
3443                 mask += ZOOM_SELECT_EXCEPT;
3444             if (mask)
3445                 ZOOM_connection_do_io(c, mask);
3446         }
3447         if (r == 0 && c->mask)
3448         {
3449             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
3450             /* timeout and this connection was waiting */
3451             set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
3452             do_close (c);
3453             yaz_log (LOG_DEBUG, "timeout");
3454             ZOOM_connection_put_event(c, event);
3455         }
3456     }
3457 #endif
3458     for (i = 0; i<no; i++)
3459     {
3460         ZOOM_connection c = cs[i];
3461         ZOOM_Event event;
3462         if (c && (event = ZOOM_connection_get_event(c)))
3463         {
3464             ZOOM_Event_destroy (event);
3465             return i+1;
3466         }
3467     }
3468     return 0;
3469 }