Implemented named result sets handling for ZOOM.
[yaz-moved-to-github.git] / zoom / zoom-c.c
1 /*
2  * $Id: zoom-c.c,v 1.12 2001-11-22 09:45:31 adam Exp $
3  *
4  * ZOOM layer for C, connections, result sets, queries.
5  */
6 #include <assert.h>
7 #include <yaz/xmalloc.h>
8 #include <yaz/otherinfo.h>
9 #include <yaz/log.h>
10 #include <yaz/pquery.h>
11 #include <yaz/diagbib1.h>
12
13 #include "zoom-p.h"
14
15 #if HAVE_SYS_POLL_H
16 #include <sys/poll.h>
17 #endif
18
19 static ZOOM_Event ZOOM_Event_create (int kind)
20 {
21     ZOOM_Event event = xmalloc (sizeof(*event));
22     event->kind = kind;
23     event->next = 0;
24     event->prev = 0;
25     return event;
26 }
27
28 static void ZOOM_Event_destroy (ZOOM_Event event)
29 {
30     xfree (event);
31 }
32
33 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
34 {
35     // put in back of queue
36     if (c->m_queue_back)
37     {
38         c->m_queue_back->prev = event;
39         assert (c->m_queue_front);
40     }
41     else
42     {
43         assert (!c->m_queue_front);
44         c->m_queue_front = event;
45     }
46     event->next = c->m_queue_back;
47     event->prev = 0;
48     c->m_queue_back = event;
49 }
50
51 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
52 {
53     // get from front of queue
54     ZOOM_Event event = c->m_queue_front;
55     if (!event)
56         return 0;
57     assert (c->m_queue_back);
58     c->m_queue_front = event->prev;
59     if (c->m_queue_front)
60     {
61         assert (c->m_queue_back);
62         c->m_queue_front->next = 0;
63     }
64     else
65         c->m_queue_back = 0;
66     return event;
67 }
68
69 static void clear_error (ZOOM_connection c)
70 {
71     c->error = ZOOM_ERROR_NONE;
72     xfree (c->addinfo);
73     c->addinfo = 0;
74 }
75
76 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
77 {
78     ZOOM_task *taskp = &c->tasks;
79     while (*taskp)
80         taskp = &(*taskp)->next;
81     *taskp = xmalloc (sizeof(**taskp));
82     (*taskp)->running = 0;
83     (*taskp)->which = which;
84     (*taskp)->u.resultset = 0;  /* one null pointer there at least */
85     (*taskp)->next = 0;
86     clear_error (c);
87     return *taskp;
88 }
89
90 void ZOOM_connection_remove_task (ZOOM_connection c)
91 {
92     ZOOM_task task = c->tasks;
93
94     if (task)
95     {
96         c->tasks = task->next;
97         switch (task->which)
98         {
99         case ZOOM_TASK_SEARCH:
100             ZOOM_resultset_destroy (task->u.resultset);
101             break;
102         case ZOOM_TASK_RETRIEVE:
103             ZOOM_resultset_destroy (task->u.resultset);
104             break;
105         case ZOOM_TASK_CONNECT:
106             break;
107         default:
108             assert (0);
109         }
110         xfree (task);
111     }
112 }
113
114 void ZOOM_connection_remove_tasks (ZOOM_connection c)
115 {
116     while (c->tasks)
117         ZOOM_connection_remove_task(c);
118 }
119
120 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
121                                          int pos,
122                                          const char *elementSetName);
123
124 ZOOM_connection ZOOM_connection_create (ZOOM_options options)
125 {
126     ZOOM_connection c = xmalloc (sizeof(*c));
127
128     c->cs = 0;
129     c->mask = 0;
130     c->state = STATE_IDLE;
131     c->error = ZOOM_ERROR_NONE;
132     c->addinfo = 0;
133     c->buf_in = 0;
134     c->len_in = 0;
135     c->buf_out = 0;
136     c->len_out = 0;
137     c->resultsets = 0;
138
139     c->options = ZOOM_options_create_with_parent(options);
140
141     c->host_port = 0;
142     c->proxy = 0;
143
144     c->cookie_out = 0;
145     c->cookie_in = 0;
146     c->tasks = 0;
147
148     c->odr_in = odr_createmem (ODR_DECODE);
149     c->odr_out = odr_createmem (ODR_ENCODE);
150
151     c->async = 0;
152     c->support_named_resultsets = 0;
153
154     c->m_queue_front = 0;
155     c->m_queue_back = 0;
156     return c;
157 }
158
159 /* set database names. Take local databases (if set); otherwise
160    take databases given in ZURL (if set); otherwise use Default */
161 static char **set_DatabaseNames (ZOOM_connection con, int *num)
162 {
163     char **databaseNames;
164     const char *c;
165     int no = 2;
166     const char *cp = ZOOM_options_get (con->options, "databaseName");
167     
168     if (!cp || !*cp)
169     {
170         cp = strchr (con->host_port, '/');
171         if (cp)
172             cp++;
173         }
174     if (cp)
175     {
176         c = cp;
177         while ((c = strchr(c, '+')))
178         {
179             c++;
180             no++;
181         }
182     }
183     else
184         cp = "Default";
185     databaseNames = odr_malloc (con->odr_out, no * sizeof(*databaseNames));
186     no = 0;
187     while (*cp)
188     {
189         c = strchr (cp, '+');
190         if (!c)
191             c = cp + strlen(cp);
192         else if (c == cp)
193         {
194             cp++;
195             continue;
196         }
197         /* cp ptr to first char of db name, c is char
198            following db name */
199         databaseNames[no] = odr_malloc (con->odr_out, 1+c-cp);
200         memcpy (databaseNames[no], cp, c-cp);
201         databaseNames[no++][c-cp] = '\0';
202         cp = c;
203         if (*cp)
204             cp++;
205     }
206     databaseNames[no] = NULL;
207     *num = no;
208     return databaseNames;
209 }
210
211 ZOOM_connection ZOOM_connection_new (const char *host, int portnum)
212 {
213     ZOOM_connection c = ZOOM_connection_create (0);
214
215     ZOOM_connection_connect (c, host, portnum);
216     return c;
217 }
218
219 void ZOOM_connection_connect(ZOOM_connection c,
220                               const char *host, int portnum)
221 {
222     const char *val;
223     ZOOM_task task;
224
225     val = ZOOM_options_get (c->options, "proxy");
226     if (val && *val)
227         c->proxy = xstrdup (val);
228     else
229         c->proxy = 0;
230
231     if (portnum)
232     {
233         char hostn[128];
234         sprintf (hostn, "%.80s:%d", host, portnum);
235         c->host_port = xstrdup(hostn);
236     }
237     else
238         c->host_port = xstrdup(host);
239
240     ZOOM_options_set(c->options, "host", c->host_port);
241
242     c->async = ZOOM_options_get_bool (c->options, "async", 0);
243     
244     task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
245
246     if (!c->async)
247     {
248         while (ZOOM_event (1, &c))
249             ;
250     }
251 }
252
253 ZOOM_query ZOOM_query_create(void)
254 {
255     ZOOM_query s = xmalloc (sizeof(*s));
256
257     s->refcount = 1;
258     s->query = 0;
259     s->sort_spec = 0;
260     s->odr = odr_createmem (ODR_ENCODE);
261
262     return s;
263 }
264
265 void ZOOM_query_destroy(ZOOM_query s)
266 {
267     if (!s)
268         return;
269
270     (s->refcount)--;
271     yaz_log (LOG_DEBUG, "ZOOM_query_destroy count=%d", s->refcount);
272     if (s->refcount == 0)
273     {
274         odr_destroy (s->odr);
275         xfree (s);
276     }
277 }
278
279 int ZOOM_query_prefix(ZOOM_query s, const char *str)
280 {
281     s->query = odr_malloc (s->odr, sizeof(*s->query));
282     s->query->which = Z_Query_type_1;
283     s->query->u.type_1 =  p_query_rpn(s->odr, PROTO_Z3950, str);
284     if (!s->query->u.type_1)
285         return -1;
286     return 0;
287 }
288
289 int ZOOM_query_sortby(ZOOM_query s, const char *criteria)
290 {
291     s->sort_spec = yaz_sort_spec (s->odr, criteria);
292     if (!s->sort_spec)
293         return -1;
294     return 0;
295 }
296
297 static int do_write(ZOOM_connection c);
298
299 void ZOOM_connection_destroy(ZOOM_connection c)
300 {
301     ZOOM_resultset r;
302     if (!c)
303         return;
304     if (c->cs)
305         cs_close (c->cs);
306     for (r = c->resultsets; r; r = r->next)
307         r->connection = 0;
308
309     xfree (c->buf_in);
310     xfree (c->addinfo);
311     odr_destroy (c->odr_in);
312     odr_destroy (c->odr_out);
313     ZOOM_options_destroy (c->options);
314     ZOOM_connection_remove_tasks (c);
315     xfree (c->host_port);
316     xfree (c);
317 }
318
319 void ZOOM_resultset_addref (ZOOM_resultset r)
320 {
321     if (r)
322         (r->refcount)++;
323 }
324 ZOOM_resultset ZOOM_resultset_create ()
325 {
326     ZOOM_resultset r = xmalloc (sizeof(*r));
327
328     r->refcount = 1;
329     r->size = 0;
330     r->odr = odr_createmem (ODR_ENCODE);
331     r->start = 0;
332     r->piggyback = 1;
333     r->setname = 0;
334     r->count = 0;
335     r->record_cache = 0;
336     r->r_sort_spec = 0;
337     r->r_query = 0;
338     r->search = 0;
339     r->connection = 0;
340     r->next = 0;
341     return r;
342 }
343
344 ZOOM_resultset ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
345 {
346     ZOOM_resultset r;
347     ZOOM_query s = ZOOM_query_create();
348
349     ZOOM_query_prefix (s, q);
350
351     r = ZOOM_connection_search (c, s);
352     ZOOM_query_destroy (s);
353     return r;
354 }
355
356 ZOOM_resultset ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
357 {
358     ZOOM_resultset r = ZOOM_resultset_create ();
359     ZOOM_task task;
360     const char *cp;
361
362     r->r_sort_spec = q->sort_spec;
363     r->r_query = q->query;
364     r->search = q;
365
366     r->options = ZOOM_options_create_with_parent(c->options);
367
368     r->start = ZOOM_options_get_int(r->options, "start", 0);
369     r->count = ZOOM_options_get_int(r->options, "count", 0);
370     r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
371     cp = ZOOM_options_get (r->options, "setname");
372     if (cp)
373         r->setname = xstrdup (cp);
374
375     r->connection = c;
376
377     r->next = c->resultsets;
378     c->resultsets = r;
379
380     task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
381     task->u.resultset = r;
382     ZOOM_resultset_addref (r);  
383
384     (q->refcount)++;
385
386     if (!c->async)
387     {
388         while (ZOOM_event (1, &c))
389             ;
390     }
391     return r;
392 }
393
394 void ZOOM_resultset_destroy(ZOOM_resultset r)
395 {
396     if (!r)
397         return;
398     (r->refcount)--;
399     yaz_log (LOG_DEBUG, "destroy r = %p count=%d", r, r->refcount);
400     if (r->refcount == 0)
401     {
402         if (r->connection)
403         {
404             /* remove ourselves from the resultsets in connection */
405             ZOOM_resultset *rp = &r->connection->resultsets;
406             while (1)
407             {
408                 assert (*rp);   /* we must be in this list!! */
409                 if (*rp == r)
410                 {   /* OK, we're here - take us out of it */
411                     *rp = (*rp)->next;
412                     break;
413                 }
414                 rp = &(*rp)->next;
415             }
416         }
417         ZOOM_query_destroy (r->search);
418         ZOOM_options_destroy (r->options);
419         odr_destroy (r->odr);
420         xfree (r->setname);
421         xfree (r);
422     }
423 }
424
425 size_t ZOOM_resultset_size (ZOOM_resultset r)
426 {
427     return r->size;
428 }
429
430 static void do_close (ZOOM_connection c)
431 {
432     if (c->cs)
433         cs_close(c->cs);
434     c->cs = 0;
435     c->mask = 0;
436     c->state = STATE_IDLE;
437 }
438
439 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
440                                       int force_sync, int start, int count)
441 {
442     ZOOM_task task;
443     ZOOM_connection c;
444
445     if (!r)
446         return;
447     c = r->connection;
448     if (!c)
449         return;
450     if (start >= r->size)
451         return;
452
453     if (start + count > r->size)
454         count = r->size - start;
455
456     task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
457     task->u.resultset = r;
458     ZOOM_resultset_addref (r);
459
460     r->start = start;
461     r->count = count;
462
463     if (!r->connection->async || force_sync)
464         while (r->connection && ZOOM_event (1, &r->connection))
465             ;
466 }
467
468 void ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
469                               size_t start, size_t count)
470 {
471     int force_present = 0;
472
473     if (!r)
474         return ;
475     if (count && recs)
476         force_present = 1;
477     ZOOM_resultset_retrieve (r, force_present, start, count);
478     if (force_present)
479     {
480         size_t i;
481         for (i = 0; i< count; i++)
482             recs[i] = ZOOM_resultset_record_immediate (r, i+start);
483     }
484 }
485
486 static int do_connect (ZOOM_connection c)
487 {
488     void *add;
489     const char *effective_host;
490
491     if (c->proxy)
492         effective_host = c->proxy;
493     else
494         effective_host = c->host_port;
495
496     yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
497
498     assert (!c->cs);
499     c->cs = cs_create_host (effective_host, 0, &add);
500
501     if (c->cs)
502     {
503         int ret = cs_connect (c->cs, add);
504         yaz_log (LOG_DEBUG, "cs_connect returned %d", ret);
505         if (ret >= 0)
506         {
507             c->state = STATE_CONNECTING; 
508             c->mask = ZOOM_SELECT_READ | ZOOM_SELECT_WRITE | 
509                 ZOOM_SELECT_EXCEPT;
510             return 1;
511         }
512     }
513     c->state = STATE_IDLE;
514     c->error = ZOOM_ERROR_CONNECT;
515     return 0;
516 }
517
518 int z3950_connection_socket(ZOOM_connection c)
519 {
520     if (c->cs)
521         return cs_fileno(c->cs);
522     return -1;
523 }
524
525 int z3950_connection_mask(ZOOM_connection c)
526 {
527     if (c->cs)
528         return c->mask;
529     return 0;
530 }
531
532 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
533 {
534     char str[120];
535
536     assert (a);
537     sprintf (str, "send_APDU t=%p type=%d", c, a->which);
538     if (c->cookie_out)
539     {
540         Z_OtherInformation **oi;
541         yaz_oi_APDU(a, &oi);
542         yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
543     }
544     if (!z_APDU(out, &a, 0, 0))
545     {
546         FILE *outf = fopen("/tmp/apdu.txt", "w");
547         if (outf)
548         {
549             ODR odr_pr = odr_createmem(ODR_PRINT);
550             fprintf (outf, "a=%p\n", a);
551             odr_setprint(odr_pr, outf);
552             z_APDU(odr_pr, &a, 0, 0);
553             odr_destroy(odr_pr);
554             fclose (outf);
555         }
556         c->error = ZOOM_ERROR_ENCODE;
557         do_close (c);
558         return -1;
559     }
560     return 0;
561 }
562
563 static int send_APDU (ZOOM_connection c, Z_APDU *a)
564 {
565     assert (a);
566     if (encode_APDU(c, a, c->odr_out))
567         return -1;
568     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
569     odr_reset(c->odr_out);
570     do_write (c);
571     return 0;   
572 }
573
574 static int ZOOM_connection_send_init (ZOOM_connection c)
575 {
576     const char *impname;
577     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
578     Z_InitRequest *ireq = apdu->u.initRequest;
579     Z_IdAuthentication *auth = odr_malloc(c->odr_out, sizeof(*auth));
580     const char *auth_groupId = ZOOM_options_get (c->options, "group");
581     const char *auth_userId = ZOOM_options_get (c->options, "user");
582     const char *auth_password = ZOOM_options_get (c->options, "pass");
583     
584     ODR_MASK_SET(ireq->options, Z_Options_search);
585     ODR_MASK_SET(ireq->options, Z_Options_present);
586     ODR_MASK_SET(ireq->options, Z_Options_scan);
587     ODR_MASK_SET(ireq->options, Z_Options_sort);
588     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
589     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
590     
591     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
592     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
593     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
594     
595     impname = ZOOM_options_get (c->options, "implementationName");
596     ireq->implementationName =
597         odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
598     strcpy (ireq->implementationName, "");
599     if (impname)
600     {
601         strcat (ireq->implementationName, impname);
602         strcat (ireq->implementationName, "/");
603     }                                          
604     strcat (ireq->implementationName, "ZOOM-C/YAZ");
605     
606     *ireq->maximumRecordSize =
607         ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
608     *ireq->preferredMessageSize =
609         ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
610     
611     if (auth_groupId || auth_password)
612     {
613         Z_IdPass *pass = odr_malloc(c->odr_out, sizeof(*pass));
614         int i = 0;
615         pass->groupId = 0;
616         if (auth_groupId && *auth_groupId)
617         {
618             pass->groupId = odr_malloc(c->odr_out, strlen(auth_groupId)+1);
619             strcpy(pass->groupId, auth_groupId);
620             i++;
621         }
622         pass->userId = 0;
623         if (auth_userId && *auth_userId)
624         {
625             pass->userId = odr_malloc(c->odr_out, strlen(auth_userId)+1);
626             strcpy(pass->userId, auth_userId);
627             i++;
628         }
629         pass->password = 0;
630         if (auth_password && *auth_password)
631         {
632             pass->password = odr_malloc(c->odr_out, strlen(auth_password)+1);
633             strcpy(pass->password, auth_password);
634             i++;
635         }
636         if (i)
637         {
638             auth->which = Z_IdAuthentication_idPass;
639             auth->u.idPass = pass;
640             ireq->idAuthentication = auth;
641         }
642     }
643     else if (auth_userId)
644     {
645         auth->which = Z_IdAuthentication_open;
646         auth->u.open = odr_malloc(c->odr_out, strlen(auth_userId)+1);
647         strcpy(auth->u.open, auth_userId);
648         ireq->idAuthentication = auth;
649     }
650     if (c->proxy)
651         yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
652                                  VAL_PROXY, 1, c->host_port);
653     assert (apdu);
654     send_APDU (c, apdu);
655     
656     return 0;
657 }
658
659 static int ZOOM_connection_send_search (ZOOM_connection c)
660 {
661     ZOOM_resultset r;
662     int lslb, ssub, mspn;
663     const char *syntax;
664     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
665     Z_SearchRequest *search_req = apdu->u.searchRequest;
666     const char *elementSetName;
667     const char *smallSetElementSetName;
668     const char *mediumSetElementSetName;
669
670     assert (c->tasks);
671     assert (c->tasks->which == ZOOM_TASK_SEARCH);
672
673     r = c->tasks->u.resultset;
674
675     elementSetName =
676         ZOOM_options_get (r->options, "elementSetName");
677     smallSetElementSetName  =
678         ZOOM_options_get (r->options, "smallSetElementSetName");
679     mediumSetElementSetName =
680         ZOOM_options_get (r->options, "mediumSetElementSetName");
681
682     if (!smallSetElementSetName)
683         smallSetElementSetName = elementSetName;
684
685     if (!mediumSetElementSetName)
686         mediumSetElementSetName = elementSetName;
687
688     assert (r);
689     assert (r->r_query);
690
691     /* prepare query for the search request */
692     search_req->query = r->r_query;
693
694     search_req->databaseNames =
695         set_DatabaseNames (c, &search_req->num_databaseNames);
696
697     /* get syntax (no need to provide unless piggyback is in effect) */
698     syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
699
700     lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
701     ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
702     mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
703     if (lslb != -1 && ssub != -1 && mspn != -1)
704     {
705         /* So're a Z39.50 expert? Let's hope you don't do sort */
706         *search_req->largeSetLowerBound = lslb;
707         *search_req->smallSetUpperBound = ssub;
708         *search_req->mediumSetPresentNumber = mspn;
709     }
710     else if (r->start == 0 && r->count > 0
711              && r->piggyback && !r->r_sort_spec)
712     {
713         /* Regular piggyback - do it unless we're going to do sort */
714         *search_req->largeSetLowerBound = 2000000000;
715         *search_req->smallSetUpperBound = r->count;
716         *search_req->mediumSetPresentNumber = r->count;
717         smallSetElementSetName = 0;  /* no need to provide this */
718     }
719     else
720     {
721         /* non-piggyback. Need not provide elementsets or syntaxes .. */
722         smallSetElementSetName = 0;
723         mediumSetElementSetName = 0;
724         syntax = 0;
725     }
726     if (smallSetElementSetName && *smallSetElementSetName)
727     {
728         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
729         
730         esn->which = Z_ElementSetNames_generic;
731         esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
732         search_req->smallSetElementSetNames = esn;
733     }
734     if (mediumSetElementSetName && *mediumSetElementSetName)
735     {
736         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
737         
738         esn->which = Z_ElementSetNames_generic;
739         esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
740         search_req->mediumSetElementSetNames = esn;
741     }
742     if (syntax)
743         search_req->preferredRecordSyntax =
744             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
745     
746     if (!r->setname)
747     {
748         if (c->support_named_resultsets)
749         {
750             char setname[14];
751             int ord;
752             /* find the lowest unused ordinal so that we re-use
753                result sets on the server. */
754             for (ord = 1; ; ord++)
755             {
756                 ZOOM_resultset rp;
757                 sprintf (setname, "%d", ord);
758                 for (rp = c->resultsets; rp; rp = rp->next)
759                     if (rp->setname && !strcmp (rp->setname, setname))
760                         break;
761                 if (!rp)
762                     break;
763             }
764             r->setname = xstrdup (setname);
765             yaz_log (LOG_DEBUG, "allocating %s", r->setname);
766         }
767         else
768             r->setname = xstrdup ("default");
769         ZOOM_options_set (r->options, "setname", r->setname);
770     }
771     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
772     /* send search request */
773     send_APDU (c, apdu);
774     r->r_query = 0;
775     return 1;
776 }
777
778 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
779 {
780     Z_DefaultDiagFormat *r;
781     char *addinfo = 0;
782     
783     xfree (c->addinfo);
784     c->addinfo = 0;
785     if (p->which != Z_DiagRec_defaultFormat)
786     {
787         c->error = ZOOM_ERROR_DECODE;
788         return;
789     }
790     r = p->u.defaultFormat;
791     switch (r->which)
792     {
793     case Z_DefaultDiagFormat_v2Addinfo:
794         addinfo = r->u.v2Addinfo;
795         break;
796     case Z_DefaultDiagFormat_v3Addinfo:
797         addinfo = r->u.v3Addinfo;
798         break;
799     }
800     if (addinfo)
801         c->addinfo = xstrdup (addinfo);
802     c->error = *r->condition;
803 }
804
805 ZOOM_record ZOOM_record_clone (ZOOM_record srec)
806 {
807     char *buf;
808     int size;
809     ODR odr_enc;
810     ZOOM_record nrec;
811
812     odr_enc = odr_createmem(ODR_ENCODE);
813     if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
814         return 0;
815     buf = odr_getbuf (odr_enc, &size, 0);
816     
817     nrec = xmalloc (sizeof(*nrec));
818     nrec->odr = odr_createmem(ODR_DECODE);
819     nrec->wrbuf_marc = 0;
820     odr_setbuf (nrec->odr, buf, size, 0);
821     z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
822     
823     odr_destroy (odr_enc);
824     return nrec;
825 }
826
827 ZOOM_record ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
828 {
829     return record_cache_lookup (s, pos, 0);
830 }
831
832 ZOOM_record ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
833 {
834     ZOOM_resultset_retrieve (r, 1, pos, 1);
835     return ZOOM_resultset_record_immediate (r, pos);
836 }
837
838 void ZOOM_record_destroy (ZOOM_record rec)
839 {
840     if (!rec)
841         return;
842     if (rec->wrbuf_marc)
843         wrbuf_free (rec->wrbuf_marc, 1);
844     odr_destroy (rec->odr);
845     xfree (rec);
846 }
847
848 void *ZOOM_record_get (ZOOM_record rec, const char *type, size_t *len)
849 {
850     Z_NamePlusRecord *npr;
851     if (!rec)
852         return 0;
853     npr = rec->npr;
854     if (!npr)
855         return 0;
856     if (!strcmp (type, "database"))
857     {
858         return npr->databaseName;
859     }
860     else if (!strcmp (type, "syntax"))
861     {
862         if (npr->which == Z_NamePlusRecord_databaseRecord)
863         {
864             Z_External *r = (Z_External *) npr->u.databaseRecord;
865             oident *ent = oid_getentbyoid(r->direct_reference);
866             if (ent)
867                 return ent->desc;
868         }
869         return "none";
870     }
871     else if (!strcmp (type, "render"))
872     {
873         if (npr->which == Z_NamePlusRecord_databaseRecord)
874         {
875             Z_External *r = (Z_External *) npr->u.databaseRecord;
876             oident *ent = oid_getentbyoid(r->direct_reference);
877             
878             if (r->which == Z_External_sutrs)
879             {
880                 *len = r->u.sutrs->len;
881                 return r->u.sutrs->buf;
882             }
883             else if (r->which == Z_External_octet)
884             {
885                 switch (ent->value)
886                 {
887                 case VAL_SOIF:
888                 case VAL_HTML:
889                 case VAL_SUTRS:
890                     break;
891                 case VAL_TEXT_XML:
892                 case VAL_APPLICATION_XML:
893                     break;
894                 default:
895                     if (!rec->wrbuf_marc)
896                         rec->wrbuf_marc = wrbuf_alloc();
897                     if (marc_display_wrbuf (r->u.octet_aligned->buf,
898                                         rec->wrbuf_marc, 0,
899                                             r->u.octet_aligned->len) > 0)
900                     {
901                         *len = wrbuf_len(rec->wrbuf_marc);
902                         return wrbuf_buf(rec->wrbuf_marc);
903                     }
904                 }
905                 *len = r->u.octet_aligned->len;
906                 return r->u.octet_aligned->buf;
907             }
908             else if (r->which == Z_External_grs1)
909             {
910                 *len = 5;
911                 return "GRS-1";
912             }
913         }
914         return 0;
915     }
916     else if (!strcmp (type, "raw"))
917     {
918         if (npr->which == Z_NamePlusRecord_databaseRecord)
919         {
920             *len = -1;
921             return (Z_External *) npr->u.databaseRecord;
922         }
923         return 0;
924     }
925     return 0;
926 }
927
928 static void record_cache_add (ZOOM_resultset r,
929                               Z_NamePlusRecord *npr,
930                               int pos,
931                               const char *elementSetName)
932 {
933     ZOOM_record_cache rc;
934
935     for (rc = r->record_cache; rc; rc = rc->next)
936     {
937         if (pos == rc->pos)
938         {
939             if ((!elementSetName && !rc->elementSetName)
940                 || (elementSetName && rc->elementSetName &&
941                     !strcmp (elementSetName, rc->elementSetName)))
942             {
943                 /* not destroying rc->npr (it's handled by nmem )*/
944                 rc->rec.npr = npr;
945                 /* keeping wrbuf_marc too */
946                 return;
947             }
948         }
949
950     }
951     rc = odr_malloc (r->odr, sizeof(*rc));
952     rc->rec.npr = npr; 
953     rc->rec.odr = 0;
954     rc->rec.wrbuf_marc = 0;
955     if (elementSetName)
956         rc->elementSetName = odr_strdup (r->odr, elementSetName);
957     else
958         rc->elementSetName = 0;
959     rc->pos = pos;
960     rc->next = r->record_cache;
961     r->record_cache = rc;
962 }
963
964 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
965                                          int pos,
966                                          const char *elementSetName)
967 {
968     ZOOM_record_cache rc;
969
970     for (rc = r->record_cache; rc; rc = rc->next)
971     {
972         if (pos == rc->pos)
973         {
974             if ((!elementSetName && !rc->elementSetName)
975                 || (elementSetName && rc->elementSetName &&
976                     !strcmp (elementSetName, rc->elementSetName)))
977                 return &rc->rec;
978         }
979     }
980     return 0;
981 }
982                                              
983 static void handle_records (ZOOM_connection c, Z_Records *sr,
984                             int present_phase)
985 {
986     ZOOM_resultset resultset;
987
988     if (!c->tasks)
989         return ;
990     if (c->tasks->which != ZOOM_TASK_SEARCH &&
991         c->tasks->which != ZOOM_TASK_RETRIEVE)
992         return ;
993     
994     resultset = c->tasks->u.resultset;
995
996     if (sr && sr->which == Z_Records_NSD)
997     {
998         Z_DiagRec dr, *dr_p = &dr;
999         dr.which = Z_DiagRec_defaultFormat;
1000         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1001         
1002         response_diag (c, dr_p);
1003     }
1004     else if (sr && sr->which == Z_Records_multipleNSD)
1005     {
1006         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1007             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1008         else
1009             c->error = ZOOM_ERROR_DECODE;
1010     }
1011     else 
1012     {
1013         if (resultset->count + resultset->start > resultset->size)
1014             resultset->count = resultset->size - resultset->start;
1015         if (resultset->count < 0)
1016             resultset->count = 0;
1017         if (sr && sr->which == Z_Records_DBOSD)
1018         {
1019             int i;
1020             NMEM nmem = odr_extract_mem (c->odr_in);
1021             Z_NamePlusRecordList *p =
1022                 sr->u.databaseOrSurDiagnostics;
1023             for (i = 0; i<p->num_records; i++)
1024             {
1025                 record_cache_add (resultset, p->records[i],
1026                                   i+ resultset->start, 0);
1027             }
1028             /* transfer our response to search_nmem .. we need it later */
1029             nmem_transfer (resultset->odr->mem, nmem);
1030             nmem_destroy (nmem);
1031             if (present_phase && p->num_records == 0)
1032             {
1033                 /* present response and we didn't get any records! */
1034                 c->error = ZOOM_ERROR_DECODE;
1035             }
1036         }
1037         else if (present_phase)
1038         {
1039             /* present response and we didn't get any records! */
1040             c->error = ZOOM_ERROR_DECODE;
1041         }
1042     }
1043 }
1044
1045 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1046 {
1047     handle_records (c, pr->records, 1);
1048 }
1049
1050 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1051 {
1052     ZOOM_resultset resultset;
1053
1054     yaz_log (LOG_DEBUG, "got search response");
1055
1056     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1057         return ;
1058
1059     resultset = c->tasks->u.resultset;
1060
1061     resultset->size = *sr->resultCount;
1062     handle_records (c, sr->records, 0);
1063 }
1064
1065 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1066 {
1067     if (res->diagnostics && res->num_diagnostics > 0)
1068         response_diag (c, res->diagnostics[0]);
1069 }
1070
1071 static int send_sort (ZOOM_connection c)
1072 {
1073     ZOOM_resultset  resultset;
1074
1075     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1076         return 0;
1077
1078     resultset = c->tasks->u.resultset;
1079
1080     if (c->error)
1081     {
1082         resultset->r_sort_spec = 0;
1083         return 0;
1084     }
1085     if (resultset->r_sort_spec)
1086     {
1087         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1088         Z_SortRequest *req = apdu->u.sortRequest;
1089         
1090         req->num_inputResultSetNames = 1;
1091         req->inputResultSetNames = (Z_InternationalString **)
1092             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1093         req->inputResultSetNames[0] =
1094             odr_strdup (c->odr_out, resultset->setname);
1095         req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1096         req->sortSequence = resultset->r_sort_spec;
1097         resultset->r_sort_spec = 0;
1098         send_APDU (c, apdu);
1099         return 1;
1100     }
1101     return 0;
1102 }
1103
1104 static int send_present (ZOOM_connection c)
1105 {
1106     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1107     Z_PresentRequest *req = apdu->u.presentRequest;
1108     int i = 0;
1109     const char *syntax = 
1110         ZOOM_options_get (c->options, "preferredRecordSyntax");
1111     const char *element =
1112         ZOOM_options_get (c->options, "elementSetName");
1113     ZOOM_resultset  resultset;
1114
1115     if (!c->tasks)
1116         return 0;
1117     if (c->tasks->which != ZOOM_TASK_SEARCH && 
1118         c->tasks->which != ZOOM_TASK_RETRIEVE)
1119         return 0;
1120
1121     resultset = c->tasks->u.resultset;
1122     
1123     if (c->error)                  /* don't continue on error */
1124         return 0;
1125     if (resultset->start < 0)
1126         return 0;
1127     for (i = 0; i<resultset->count; i++)
1128     {
1129         ZOOM_record rec =
1130             record_cache_lookup (resultset, i + resultset->start, 0);
1131         if (!rec)
1132             break;
1133     }
1134     if (i == resultset->count)
1135         return 0;
1136
1137     resultset->start += i;
1138     resultset->count -= i;
1139     *req->resultSetStartPoint = resultset->start + 1;
1140     *req->numberOfRecordsRequested = resultset->count;
1141     assert (*req->numberOfRecordsRequested > 0);
1142
1143     if (syntax && *syntax)
1144         req->preferredRecordSyntax =
1145             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1146
1147     if (element && *element)
1148     {
1149         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
1150         Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1151         
1152         esn->which = Z_ElementSetNames_generic;
1153         esn->u.generic = odr_strdup (c->odr_out, element);
1154         compo->which = Z_RecordComp_simple;
1155         compo->u.simple = esn;
1156         req->recordComposition = compo;
1157     }
1158     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1159     send_APDU (c, apdu);
1160     return 1;
1161 }
1162
1163 static int ZOOM_connection_exec_task (ZOOM_connection c)
1164 {
1165     ZOOM_task task = c->tasks;
1166
1167     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task");
1168     if (!task)
1169         return 0;
1170     if (c->error != ZOOM_ERROR_NONE ||
1171         (!c->cs && task->which != ZOOM_TASK_CONNECT))
1172     {
1173         ZOOM_connection_remove_tasks (c);
1174         return 0;
1175     }
1176     yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d", task->which);
1177     if (task->running)
1178         return 0;
1179     task->running = 1;
1180     switch (task->which)
1181     {
1182     case ZOOM_TASK_SEARCH:
1183         /* see if search hasn't been sent yet. */
1184         if (ZOOM_connection_send_search (c))
1185             return 1;
1186         break;
1187     case ZOOM_TASK_RETRIEVE:
1188         if (send_present (c))
1189             return 1;
1190         break;
1191     case ZOOM_TASK_CONNECT:
1192         if (do_connect(c))
1193             return 1;
1194     }
1195     ZOOM_connection_remove_task (c);
1196     return 0;
1197 }
1198
1199 static int send_sort_present (ZOOM_connection c)
1200 {
1201     int r = send_sort (c);
1202     if (!r)
1203         r = send_present (c);
1204     return r;
1205 }
1206
1207 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
1208 {
1209     Z_InitResponse *initrs;
1210     
1211     yaz_log (LOG_DEBUG, "hande_apdu type=%d", apdu->which);
1212     c->mask = 0;
1213     switch(apdu->which)
1214     {
1215     case Z_APDU_initResponse:
1216         initrs = apdu->u.initResponse;
1217         if (!*initrs->result)
1218         {
1219             c->error = ZOOM_ERROR_INIT;
1220         }
1221         else
1222         {
1223             char *cookie =
1224                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
1225                                           VAL_COOKIE, 1, 0);
1226             xfree (c->cookie_in);
1227             c->cookie_in = 0;
1228             if (cookie)
1229                 c->cookie_in = xstrdup(cookie);
1230             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets))
1231                 c->support_named_resultsets = 1;
1232             if (c->tasks)
1233             {
1234                 assert (c->tasks->which == ZOOM_TASK_CONNECT);
1235                 ZOOM_connection_remove_task (c);
1236             }
1237             ZOOM_connection_exec_task (c);
1238         }
1239         break;
1240     case Z_APDU_searchResponse:
1241         handle_search_response (c, apdu->u.searchResponse);
1242         if (!send_sort_present (c))
1243             ZOOM_connection_remove_task (c);
1244         break;
1245     case Z_APDU_presentResponse:
1246         handle_present_response (c, apdu->u.presentResponse);
1247         if (!send_present (c))
1248             ZOOM_connection_remove_task (c);
1249         break;
1250     case Z_APDU_sortResponse:
1251         sort_response (c, apdu->u.sortResponse);
1252         if (!send_present (c))
1253             ZOOM_connection_remove_task (c);
1254     }
1255 }
1256
1257 static int do_read (ZOOM_connection c)
1258 {
1259     int r;
1260     Z_APDU *apdu;
1261     
1262     r = cs_get (c->cs, &c->buf_in, &c->len_in);
1263     if (r == 1)
1264         return 0;
1265     if (r <= 0)
1266     {
1267         c->error= ZOOM_ERROR_CONNECTION_LOST;
1268         do_close (c);
1269     }
1270     else
1271     {
1272         odr_reset (c->odr_in);
1273         odr_setbuf (c->odr_in, c->buf_in, r, 0);
1274         if (!z_APDU (c->odr_in, &apdu, 0, 0))
1275         {
1276             c->error = ZOOM_ERROR_DECODE;
1277             do_close (c);
1278         }
1279         else
1280         {
1281             handle_apdu (c, apdu);
1282         }
1283     }
1284     return 1;
1285 }
1286
1287 static int do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
1288 {
1289     int r;
1290     
1291     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
1292     {
1293         if (c->state == STATE_CONNECTING)
1294             c->error = ZOOM_ERROR_CONNECT;
1295         else
1296             c->error = ZOOM_ERROR_CONNECTION_LOST;
1297         do_close (c);
1298         return 1;
1299     }
1300     else if (r == 1)
1301     {
1302         c->state = STATE_ESTABLISHED;
1303         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_WRITE|ZOOM_SELECT_EXCEPT;
1304     }
1305     else
1306     {
1307         c->state = STATE_ESTABLISHED;
1308         c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
1309     }
1310     return 0;
1311 }
1312
1313 static int do_write(ZOOM_connection c)
1314 {
1315     return do_write_ex (c, c->buf_out, c->len_out);
1316 }
1317
1318
1319 const char *ZOOM_connection_option_get (ZOOM_connection c, const char *key)
1320 {
1321     return ZOOM_options_get (c->options, key);
1322 }
1323
1324 void ZOOM_connection_option_set (ZOOM_connection c, const char *key,
1325                                   const char *val)
1326 {
1327     ZOOM_options_set (c->options, key, val);
1328 }
1329
1330 const char *ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
1331 {
1332     return ZOOM_options_get (r->options, key);
1333 }
1334
1335 void ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
1336                                   const char *val)
1337 {
1338     ZOOM_options_set (r->options, key, val);
1339 }
1340
1341
1342 int ZOOM_connection_errcode (ZOOM_connection c)
1343 {
1344     return ZOOM_connection_error (c, 0, 0);
1345 }
1346
1347 const char *ZOOM_connection_errmsg (ZOOM_connection c)
1348 {
1349     const char *msg;
1350     ZOOM_connection_error (c, &msg, 0);
1351     return msg;
1352 }
1353
1354 const char *ZOOM_connection_addinfo (ZOOM_connection c)
1355 {
1356     const char *addinfo;
1357     ZOOM_connection_error (c, 0, &addinfo);
1358     return addinfo;
1359 }
1360
1361 int ZOOM_connection_error (ZOOM_connection c, const char **cp,
1362                             const char **addinfo)
1363 {
1364     int error = c->error;
1365     if (cp)
1366     {
1367         switch (error)
1368         {
1369         case ZOOM_ERROR_NONE:
1370             *cp = "No error"; break;
1371         case ZOOM_ERROR_CONNECT:
1372             *cp = "Connect failed"; break;
1373         case ZOOM_ERROR_MEMORY:
1374             *cp = "Out of memory"; break;
1375         case ZOOM_ERROR_ENCODE:
1376             *cp = "Encoding failed"; break;
1377         case ZOOM_ERROR_DECODE:
1378             *cp = "Decoding failed"; break;
1379         case ZOOM_ERROR_CONNECTION_LOST:
1380             *cp = "Connection lost"; break;
1381         case ZOOM_ERROR_INIT:
1382             *cp = "Init rejected"; break;
1383         case ZOOM_ERROR_INTERNAL:
1384             *cp = "Internal failure"; break;
1385         case ZOOM_ERROR_TIMEOUT:
1386             *cp = "Timeout"; break;
1387         default:
1388             *cp = diagbib1_str (error);
1389         }
1390     }
1391     if (addinfo)
1392     {
1393         if (c->addinfo)
1394             *addinfo = c->addinfo;
1395         else
1396             *addinfo = "";
1397     }
1398     return c->error;
1399 }
1400
1401 int ZOOM_connection_do_io(ZOOM_connection c, int mask)
1402 {
1403     ZOOM_Event event;
1404 #if 0
1405     int r = cs_look(c->cs);
1406     yaz_log (LOG_LOG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
1407              c, mask, r);
1408     
1409     if (r == CS_NONE)
1410     {
1411         c->error = ZOOM_ERROR_CONNECT;
1412         do_close (c);
1413     }
1414     else if (r == CS_CONNECT)
1415     {
1416         yaz_log (LOG_LOG, "calling rcvconnect");
1417         if (cs_rcvconnect (c->cs) < 0)
1418         {
1419             c->error = ZOOM_ERROR_CONNECT;
1420             do_close (c);
1421         }
1422         else
1423             ZOOM_connection_send_init (c);
1424     }
1425     else
1426     {
1427         if (mask & ZOOM_SELECT_READ)
1428             do_read (c);
1429         if (c->cs && (mask & ZOOM_SELECT_WRITE))
1430             do_write (c);
1431     }   
1432 #else
1433     yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d", c, mask);
1434     if (c->state == STATE_CONNECTING)
1435     {
1436         if (mask & ZOOM_SELECT_WRITE)
1437             ZOOM_connection_send_init (c);
1438         else
1439         {
1440             c->error = ZOOM_ERROR_CONNECT;
1441             do_close (c);
1442         }
1443     }
1444     else if (c->state == STATE_ESTABLISHED)
1445     {
1446         if (mask & ZOOM_SELECT_READ)
1447             do_read (c);
1448         if (c->cs && (mask & ZOOM_SELECT_WRITE))
1449             do_write (c);
1450     }
1451     else
1452     {
1453         c->error = ZOOM_ERROR_INTERNAL;
1454         do_close (c);
1455     }
1456 #endif
1457     event = ZOOM_Event_create (1);
1458     ZOOM_connection_put_event (c, event);
1459     return 1;
1460 }
1461
1462
1463 int ZOOM_event (int no, ZOOM_connection *cs)
1464 {
1465 #if HAVE_SYS_POLL_H
1466     struct pollfd pollfds[1024];
1467     ZOOM_connection poll_cs[1024];
1468 #else
1469     struct timeval tv;
1470     fd_set input, output, except;
1471 #endif
1472     int i, r, nfds;
1473     int max_fd = 0;
1474
1475     for (i = 0; i<no; i++)
1476     {
1477         ZOOM_connection c = cs[i];
1478         ZOOM_Event event;
1479         if (c && (event = ZOOM_connection_get_event(c)))
1480         {
1481             ZOOM_Event_destroy (event);
1482             return i+1;
1483         }
1484     }
1485     for (i = 0; i<no; i++)
1486     {
1487         ZOOM_connection c = cs[i];
1488         if (c && ZOOM_connection_exec_task (c))
1489             return i+1;
1490     }
1491 #if HAVE_SYS_POLL_H
1492
1493 #else
1494     tv.tv_sec = 15;
1495     tv.tv_usec = 0;
1496     
1497     FD_ZERO (&input);
1498     FD_ZERO (&output);
1499     FD_ZERO (&except);
1500 #endif
1501     nfds = 0;
1502     for (i = 0; i<no; i++)
1503     {
1504         ZOOM_connection c = cs[i];
1505         int fd, mask;
1506         
1507         if (!c)
1508             continue;
1509         fd = z3950_connection_socket(c);
1510         mask = z3950_connection_mask(c);
1511
1512         if (fd == -1)
1513             continue;
1514         if (max_fd < fd)
1515             max_fd = fd;
1516
1517 #if HAVE_SYS_POLL_H
1518         if (mask)
1519         {
1520             short poll_events = 0;
1521
1522             if (mask & ZOOM_SELECT_READ)
1523                 poll_events += POLLIN;
1524             if (mask & ZOOM_SELECT_WRITE)
1525                 poll_events += POLLOUT;
1526             if (mask & ZOOM_SELECT_EXCEPT)
1527                 poll_events += POLLERR;
1528             pollfds[nfds].fd = fd;
1529             pollfds[nfds].events = poll_events;
1530             pollfds[nfds].revents = 0;
1531             poll_cs[nfds] = c;
1532             nfds++;
1533         }
1534 #else
1535         if (mask & ZOOM_SELECT_READ)
1536         {
1537             FD_SET (fd, &input);
1538             nfds++;
1539         }
1540         if (mask & ZOOM_SELECT_WRITE)
1541         {
1542             FD_SET (fd, &output);
1543             nfds++;
1544         }
1545         if (mask & ZOOM_SELECT_EXCEPT)
1546         {
1547             FD_SET (fd, &except);
1548             nfds++;
1549         }
1550 #endif
1551     }
1552     if (!nfds)
1553         return 0;
1554 #if HAVE_SYS_POLL_H
1555     yaz_log (LOG_DEBUG, "poll start");
1556     r = poll (pollfds, nfds, 15000);
1557     yaz_log (LOG_DEBUG, "poll stop, returned r=%d", r);
1558     for (i = 0; i<nfds; i++)
1559     {
1560         ZOOM_connection c = poll_cs[i];
1561         if (r && c->mask)
1562         {
1563             int mask = 0;
1564             if (pollfds[i].revents & POLLIN)
1565                 mask += ZOOM_SELECT_READ;
1566             if (pollfds[i].revents & POLLOUT)
1567                 mask += ZOOM_SELECT_WRITE;
1568             if (pollfds[i].revents & POLLERR)
1569                 mask += ZOOM_SELECT_EXCEPT;
1570             if (mask)
1571                 ZOOM_connection_do_io(c, mask);
1572         }
1573         else if (r == 0 && c->mask)
1574         {
1575             ZOOM_Event event = ZOOM_Event_create(0);
1576             /* timeout and this connection was waiting */
1577             c->error = ZOOM_ERROR_TIMEOUT;
1578             do_close (c);
1579             ZOOM_connection_put_event(c, event);
1580         }
1581     }
1582 #else
1583     yaz_log (LOG_DEBUG, "select start");
1584     r = select (max_fd+1, &input, &output, &except, &tv);
1585     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
1586     for (i = 0; i<no; i++)
1587     {
1588         ZOOM_connection c = cs[i];
1589         int fd, mask;
1590
1591         if (!c)
1592             continue;
1593         fd = z3950_connection_socket(c);
1594         mask = 0;
1595         if (r && c->mask)
1596         {
1597             /* no timeout and real socket */
1598             if (FD_ISSET(fd, &input))
1599                 mask += ZOOM_SELECT_READ;
1600             if (FD_ISSET(fd, &output))
1601                 mask += ZOOM_SELECT_WRITE;
1602             if (FD_ISSET(fd, &except))
1603                 mask += ZOOM_SELECT_EXCEPT;
1604             if (mask)
1605                 ZOOM_connection_do_io(c, mask);
1606         }
1607         if (r == 0 && c->mask)
1608         {
1609             ZOOM_Event event = ZOOM_Event_create(0);
1610             /* timeout and this connection was waiting */
1611             c->error = ZOOM_ERROR_TIMEOUT;
1612             do_close (c);
1613             yaz_log (LOG_DEBUG, "timeout");
1614             ZOOM_connection_put_event(c, event);
1615         }
1616     }
1617 #endif
1618     for (i = 0; i<no; i++)
1619     {
1620         ZOOM_connection c = cs[i];
1621         ZOOM_Event event;
1622         if (c && (event = ZOOM_connection_get_event(c)))
1623         {
1624             ZOOM_Event_destroy (event);
1625             return i+1;
1626         }
1627     }
1628     return 0;
1629 }