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