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