ZOOM: record objects "owned" by result sets.
[yaz-moved-to-github.git] / zoom / zoom-c.c
1 /*
2  * $Id: zoom-c.c,v 1.6 2001-11-15 08:58:29 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 size_t 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 (const 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     return record_cache_lookup (s, pos, 0);
795 }
796
797 Z3950_record Z3950_resultset_record (Z3950_resultset r, size_t pos)
798 {
799     Z3950_resultset_retrieve (r, 1, pos, 1);
800     return Z3950_resultset_record_immediate (r, pos);
801 }
802
803 void Z3950_record_destroy (Z3950_record rec)
804 {
805     if (!rec)
806         return;
807     if (rec->wrbuf_marc)
808         wrbuf_free (rec->wrbuf_marc, 1);
809     odr_destroy (rec->odr);
810     xfree (rec);
811 }
812
813 void *Z3950_record_get (Z3950_record rec, const char *type, size_t *len)
814 {
815     Z_NamePlusRecord *npr;
816     if (!rec)
817         return 0;
818     npr = rec->npr;
819     if (!npr)
820         return 0;
821     if (!strcmp (type, "database"))
822     {
823         return npr->databaseName;
824     }
825     else if (!strcmp (type, "syntax"))
826     {
827         if (npr->which == Z_NamePlusRecord_databaseRecord)
828         {
829             Z_External *r = (Z_External *) npr->u.databaseRecord;
830             oident *ent = oid_getentbyoid(r->direct_reference);
831             if (ent)
832                 return ent->desc;
833         }
834         return "none";
835     }
836     else if (!strcmp (type, "render"))
837     {
838         if (npr->which == Z_NamePlusRecord_databaseRecord)
839         {
840             Z_External *r = (Z_External *) npr->u.databaseRecord;
841             oident *ent = oid_getentbyoid(r->direct_reference);
842             
843             if (r->which == Z_External_sutrs)
844             {
845                 *len = r->u.sutrs->len;
846                 return r->u.sutrs->buf;
847             }
848             else if (r->which == Z_External_octet)
849             {
850                 switch (ent->value)
851                 {
852                 case VAL_SOIF:
853                 case VAL_HTML:
854                 case VAL_SUTRS:
855                     break;
856                 case VAL_TEXT_XML:
857                 case VAL_APPLICATION_XML:
858                     break;
859                 default:
860                     if (!rec->wrbuf_marc)
861                         rec->wrbuf_marc = wrbuf_alloc();
862                     if (marc_display_wrbuf (r->u.octet_aligned->buf,
863                                         rec->wrbuf_marc, 0,
864                                             r->u.octet_aligned->len) > 0)
865                     {
866                         *len = wrbuf_len(rec->wrbuf_marc);
867                         return wrbuf_buf(rec->wrbuf_marc);
868                     }
869                 }
870                 *len = r->u.octet_aligned->len;
871                 return r->u.octet_aligned->buf;
872             }
873             else if (r->which == Z_External_grs1)
874             {
875                 *len = 5;
876                 return "GRS-1";
877             }
878         }
879         return 0;
880     }
881     else if (!strcmp (type, "raw"))
882     {
883         if (npr->which == Z_NamePlusRecord_databaseRecord)
884         {
885             *len = -1;
886             return (Z_External *) npr->u.databaseRecord;
887         }
888         return 0;
889     }
890     return 0;
891 }
892
893 static void record_cache_add (Z3950_resultset r,
894                               Z_NamePlusRecord *npr,
895                               int pos,
896                               const char *elementSetName)
897 {
898     Z3950_record_cache rc;
899
900     for (rc = r->record_cache; rc; rc = rc->next)
901     {
902         if (pos == rc->pos)
903         {
904             if ((!elementSetName && !rc->elementSetName)
905                 || (elementSetName && rc->elementSetName &&
906                     !strcmp (elementSetName, rc->elementSetName)))
907             {
908                 /* not destroying rc->npr (it's handled by nmem )*/
909                 rc->rec.npr = npr;
910                 /* keeping wrbuf_marc too */
911                 return;
912             }
913         }
914
915     }
916     rc = odr_malloc (r->odr, sizeof(*rc));
917     rc->rec.npr = npr; 
918     rc->rec.odr = 0;
919     rc->rec.wrbuf_marc = 0;
920     if (elementSetName)
921         rc->elementSetName = odr_strdup (r->odr, elementSetName);
922     else
923         rc->elementSetName = 0;
924     rc->pos = pos;
925     rc->next = r->record_cache;
926     r->record_cache = rc;
927 }
928
929 static Z3950_record record_cache_lookup (Z3950_resultset r,
930                                          int pos,
931                                          const char *elementSetName)
932 {
933     Z3950_record_cache rc;
934
935     for (rc = r->record_cache; rc; rc = rc->next)
936     {
937         if (pos == rc->pos)
938         {
939             if ((!elementSetName && !rc->elementSetName)
940                 || (elementSetName && rc->elementSetName &&
941                     !strcmp (elementSetName, rc->elementSetName)))
942                 return &rc->rec;
943         }
944     }
945     return 0;
946 }
947                                              
948 static void handle_records (Z3950_connection c, Z_Records *sr,
949                             int present_phase)
950 {
951     Z3950_resultset resultset;
952
953     if (!c->tasks)
954         return ;
955     if (c->tasks->which != Z3950_TASK_SEARCH &&
956         c->tasks->which != Z3950_TASK_RETRIEVE)
957         return ;
958     
959     resultset = c->tasks->u.resultset;
960
961     if (sr && sr->which == Z_Records_NSD)
962     {
963         Z_DiagRec dr, *dr_p = &dr;
964         dr.which = Z_DiagRec_defaultFormat;
965         dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
966         
967         response_diag (c, dr_p);
968     }
969     else if (sr && sr->which == Z_Records_multipleNSD)
970     {
971         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
972             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
973         else
974             c->error = Z3950_ERROR_DECODE;
975     }
976     else 
977     {
978         if (resultset->count + resultset->start > resultset->size)
979             resultset->count = resultset->size - resultset->start;
980         if (resultset->count < 0)
981             resultset->count = 0;
982         if (sr && sr->which == Z_Records_DBOSD)
983         {
984             int i;
985             NMEM nmem = odr_extract_mem (c->odr_in);
986             Z_NamePlusRecordList *p =
987                 sr->u.databaseOrSurDiagnostics;
988             for (i = 0; i<p->num_records; i++)
989             {
990                 record_cache_add (resultset, p->records[i],
991                                   i+ resultset->start, 0);
992             }
993             /* transfer our response to search_nmem .. we need it later */
994             nmem_transfer (resultset->odr->mem, nmem);
995             nmem_destroy (nmem);
996             if (present_phase && p->num_records == 0)
997             {
998                 /* present response and we didn't get any records! */
999                 c->error = Z3950_ERROR_DECODE;
1000             }
1001         }
1002         else if (present_phase)
1003         {
1004             /* present response and we didn't get any records! */
1005             c->error = Z3950_ERROR_DECODE;
1006         }
1007     }
1008 }
1009
1010 static void handle_present_response (Z3950_connection c, Z_PresentResponse *pr)
1011 {
1012     handle_records (c, pr->records, 1);
1013 }
1014
1015 static void handle_search_response (Z3950_connection c, Z_SearchResponse *sr)
1016 {
1017     Z3950_resultset resultset;
1018
1019     yaz_log (LOG_DEBUG, "got search response");
1020
1021     if (!c->tasks || c->tasks->which != Z3950_TASK_SEARCH)
1022         return ;
1023
1024     resultset = c->tasks->u.resultset;
1025
1026     resultset->size = *sr->resultCount;
1027     handle_records (c, sr->records, 0);
1028 }
1029
1030 static void sort_response (Z3950_connection c, Z_SortResponse *res)
1031 {
1032     if (res->diagnostics && res->num_diagnostics > 0)
1033         response_diag (c, res->diagnostics[0]);
1034 }
1035
1036 static int send_sort (Z3950_connection c)
1037 {
1038     Z3950_resultset  resultset;
1039
1040     if (!c->tasks || c->tasks->which != Z3950_TASK_SEARCH)
1041         return 0;
1042
1043     resultset = c->tasks->u.resultset;
1044
1045     if (c->error)
1046     {
1047         resultset->r_sort_spec = 0;
1048         return 0;
1049     }
1050     if (resultset->r_sort_spec)
1051     {
1052         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1053         Z_SortRequest *req = apdu->u.sortRequest;
1054         
1055         req->num_inputResultSetNames = 1;
1056         req->inputResultSetNames = (Z_InternationalString **)
1057             odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1058         req->inputResultSetNames[0] = odr_strdup (c->odr_out, "default");
1059         req->sortedResultSetName = odr_strdup (c->odr_out, "default");
1060         req->sortSequence = resultset->r_sort_spec;
1061         resultset->r_sort_spec = 0;
1062         send_APDU (c, apdu);
1063         return 1;
1064     }
1065     return 0;
1066 }
1067
1068 static int send_present (Z3950_connection c)
1069 {
1070     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1071     Z_PresentRequest *req = apdu->u.presentRequest;
1072     int i = 0;
1073     const char *syntax = 
1074         Z3950_options_get (c->options, "preferredRecordSyntax");
1075     const char *element =
1076         Z3950_options_get (c->options, "elementSetName");
1077     Z3950_resultset  resultset;
1078
1079     if (!c->tasks)
1080         return 0;
1081     if (c->tasks->which != Z3950_TASK_SEARCH && 
1082         c->tasks->which != Z3950_TASK_RETRIEVE)
1083         return 0;
1084
1085     resultset = c->tasks->u.resultset;
1086     
1087     if (c->error)                  /* don't continue on error */
1088         return 0;
1089     if (resultset->start < 0)
1090         return 0;
1091     for (i = 0; i<resultset->count; i++)
1092     {
1093         Z3950_record rec =
1094             record_cache_lookup (resultset, i + resultset->start, 0);
1095         if (!rec)
1096             break;
1097     }
1098     if (i == resultset->count)
1099         return 0;
1100
1101     resultset->start += i;
1102     resultset->count -= i;
1103     *req->resultSetStartPoint = resultset->start + 1;
1104     *req->numberOfRecordsRequested = resultset->count;
1105     assert (*req->numberOfRecordsRequested > 0);
1106
1107     if (syntax && *syntax)
1108         req->preferredRecordSyntax =
1109             yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1110
1111     if (element && *element)
1112     {
1113         Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
1114         Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1115         
1116         esn->which = Z_ElementSetNames_generic;
1117         esn->u.generic = odr_strdup (c->odr_out, element);
1118         compo->which = Z_RecordComp_simple;
1119         compo->u.simple = esn;
1120         req->recordComposition = compo;
1121     }
1122     send_APDU (c, apdu);
1123     return 1;
1124 }
1125
1126 static int Z3950_connection_exec_task (Z3950_connection c)
1127 {
1128     Z3950_task task = c->tasks;
1129
1130     yaz_log (LOG_LOG, "Z3950_connection_exec_task");
1131     if (!task)
1132         return 0;
1133     if (c->error != Z3950_ERROR_NONE ||
1134         (!c->cs && task->which != Z3950_TASK_CONNECT))
1135     {
1136         Z3950_connection_remove_tasks (c);
1137         return 0;
1138     }
1139     yaz_log (LOG_DEBUG, "Z3950_connection_exec_task type=%d", task->which);
1140     if (task->running)
1141         return 0;
1142     task->running = 1;
1143     switch (task->which)
1144     {
1145     case Z3950_TASK_SEARCH:
1146         /* see if search hasn't been sent yet. */
1147         if (Z3950_connection_send_search (c))
1148             return 1;
1149         break;
1150     case Z3950_TASK_RETRIEVE:
1151         if (send_present (c))
1152             return 1;
1153         break;
1154     case Z3950_TASK_CONNECT:
1155         if (do_connect(c))
1156             return 1;
1157     }
1158     Z3950_connection_remove_task (c);
1159     return 0;
1160 }
1161
1162 static int send_sort_present (Z3950_connection c)
1163 {
1164     int r = send_sort (c);
1165     if (!r)
1166         r = send_present (c);
1167     return r;
1168 }
1169
1170 static void handle_apdu (Z3950_connection c, Z_APDU *apdu)
1171 {
1172     Z_InitResponse *initrs;
1173     
1174     yaz_log (LOG_DEBUG, "hande_apdu type=%d", apdu->which);
1175     c->mask = 0;
1176     switch(apdu->which)
1177     {
1178     case Z_APDU_initResponse:
1179         initrs = apdu->u.initResponse;
1180         if (!*initrs->result)
1181         {
1182             c->error = Z3950_ERROR_INIT;
1183         }
1184         else
1185         {
1186             char *cookie =
1187                 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
1188                                           VAL_COOKIE, 1, 0);
1189             xfree (c->cookie_in);
1190             c->cookie_in = 0;
1191             if (cookie)
1192                 c->cookie_in = xstrdup(cookie);
1193             if (c->tasks)
1194             {
1195                 assert (c->tasks->which == Z3950_TASK_CONNECT);
1196                 Z3950_connection_remove_task (c);
1197             }
1198             Z3950_connection_exec_task (c);
1199         }
1200         break;
1201     case Z_APDU_searchResponse:
1202         handle_search_response (c, apdu->u.searchResponse);
1203         if (!send_sort_present (c))
1204             Z3950_connection_remove_task (c);
1205         break;
1206     case Z_APDU_presentResponse:
1207         handle_present_response (c, apdu->u.presentResponse);
1208         if (!send_present (c))
1209             Z3950_connection_remove_task (c);
1210         break;
1211     case Z_APDU_sortResponse:
1212         sort_response (c, apdu->u.sortResponse);
1213         if (!send_present (c))
1214             Z3950_connection_remove_task (c);
1215     }
1216 }
1217
1218 static int do_read (Z3950_connection c)
1219 {
1220     int r;
1221     Z_APDU *apdu;
1222     
1223     r = cs_get (c->cs, &c->buf_in, &c->len_in);
1224     if (r == 1)
1225         return 0;
1226     if (r <= 0)
1227     {
1228         c->error= Z3950_ERROR_CONNECTION_LOST;
1229         do_close (c);
1230     }
1231     else
1232     {
1233         odr_reset (c->odr_in);
1234         odr_setbuf (c->odr_in, c->buf_in, r, 0);
1235         if (!z_APDU (c->odr_in, &apdu, 0, 0))
1236         {
1237             c->error = Z3950_ERROR_DECODE;
1238             do_close (c);
1239         }
1240         else
1241         {
1242             handle_apdu (c, apdu);
1243         }
1244     }
1245     return 1;
1246 }
1247
1248 static int do_write_ex (Z3950_connection c, char *buf_out, int len_out)
1249 {
1250     int r;
1251     
1252     if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
1253     {
1254         if (c->state == STATE_CONNECTING)
1255             c->error = Z3950_ERROR_CONNECT;
1256         else
1257             c->error = Z3950_ERROR_CONNECTION_LOST;
1258         do_close (c);
1259         return 1;
1260     }
1261     else if (r == 1)
1262     {
1263         c->state = STATE_ESTABLISHED;
1264         c->mask = Z3950_SELECT_READ|Z3950_SELECT_WRITE|Z3950_SELECT_EXCEPT;
1265     }
1266     else
1267     {
1268         c->state = STATE_ESTABLISHED;
1269         c->mask = Z3950_SELECT_READ|Z3950_SELECT_EXCEPT;
1270     }
1271     return 0;
1272 }
1273
1274 static int do_write(Z3950_connection c)
1275 {
1276     return do_write_ex (c, c->buf_out, c->len_out);
1277 }
1278
1279 const char *Z3950_connection_option (Z3950_connection c, const char *key,
1280                                      const char *val)
1281 {
1282     if (val)
1283     {
1284         Z3950_options_set (c->options, key, val);
1285         return val;
1286     }
1287     return Z3950_options_get (c->options, key);
1288 }
1289
1290 const char *Z3950_resultset_option (Z3950_resultset r, const char *key,
1291                                     const char *val)
1292 {
1293     if (val)
1294     {
1295         Z3950_options_set (r->options, key, val);
1296         return val;
1297     }
1298     return Z3950_options_get (r->options, key);
1299 }
1300
1301
1302 int Z3950_connection_errcode (Z3950_connection c)
1303 {
1304     return Z3950_connection_error (c, 0, 0);
1305 }
1306
1307 const char *Z3950_connection_errmsg (Z3950_connection c)
1308 {
1309     const char *msg;
1310     Z3950_connection_error (c, &msg, 0);
1311     return msg;
1312 }
1313
1314 const char *Z3950_connection_addinfo (Z3950_connection c)
1315 {
1316     const char *addinfo;
1317     Z3950_connection_error (c, 0, &addinfo);
1318     return addinfo;
1319 }
1320
1321 int Z3950_connection_error (Z3950_connection c, const char **cp,
1322                             const char **addinfo)
1323 {
1324     int error = c->error;
1325     if (cp)
1326     {
1327         switch (error)
1328         {
1329         case Z3950_ERROR_NONE:
1330             *cp = "No error"; break;
1331         case Z3950_ERROR_CONNECT:
1332             *cp = "Connect failed"; break;
1333         case Z3950_ERROR_MEMORY:
1334             *cp = "Out of memory"; break;
1335         case Z3950_ERROR_ENCODE:
1336             *cp = "Encoding failed"; break;
1337         case Z3950_ERROR_DECODE:
1338             *cp = "Decoding failed"; break;
1339         case Z3950_ERROR_CONNECTION_LOST:
1340             *cp = "Connection lost"; break;
1341         case Z3950_ERROR_INIT:
1342             *cp = "Init rejected"; break;
1343         case Z3950_ERROR_INTERNAL:
1344             *cp = "Internal failure"; break;
1345         case Z3950_ERROR_TIMEOUT:
1346             *cp = "Timeout"; break;
1347         default:
1348             *cp = diagbib1_str (error);
1349         }
1350     }
1351     if (addinfo)
1352     {
1353         if (c->addinfo)
1354             *addinfo = c->addinfo;
1355         else
1356             *addinfo = "";
1357     }
1358     return c->error;
1359 }
1360
1361 int Z3950_connection_do_io(Z3950_connection c, int mask)
1362 {
1363     Z3950_Event event;
1364 #if 0
1365     int r = cs_look(c->cs);
1366     yaz_log (LOG_LOG, "Z3950_connection_do_io c=%p mask=%d cs_look=%d",
1367              c, mask, r);
1368     
1369     if (r == CS_NONE)
1370     {
1371         c->error = Z3950_ERROR_CONNECT;
1372         do_close (c);
1373     }
1374     else if (r == CS_CONNECT)
1375     {
1376         yaz_log (LOG_LOG, "calling rcvconnect");
1377         if (cs_rcvconnect (c->cs) < 0)
1378         {
1379             c->error = Z3950_ERROR_CONNECT;
1380             do_close (c);
1381         }
1382         else
1383             Z3950_connection_send_init (c);
1384     }
1385     else
1386     {
1387         if (mask & Z3950_SELECT_READ)
1388             do_read (c);
1389         if (c->cs && (mask & Z3950_SELECT_WRITE))
1390             do_write (c);
1391     }   
1392 #else
1393     yaz_log (LOG_DEBUG, "Z3950_connection_do_io c=%p mask=%d", c, mask);
1394     if (c->state == STATE_CONNECTING)
1395     {
1396         if (mask & Z3950_SELECT_WRITE)
1397             Z3950_connection_send_init (c);
1398         else
1399         {
1400             c->error = Z3950_ERROR_CONNECT;
1401             do_close (c);
1402         }
1403     }
1404     else if (c->state == STATE_ESTABLISHED)
1405     {
1406         if (mask & Z3950_SELECT_READ)
1407             do_read (c);
1408         if (c->cs && (mask & Z3950_SELECT_WRITE))
1409             do_write (c);
1410     }
1411     else
1412     {
1413         c->error = Z3950_ERROR_INTERNAL;
1414         do_close (c);
1415     }
1416 #endif
1417     event = Z3950_Event_create (1);
1418     Z3950_connection_put_event (c, event);
1419     return 1;
1420 }
1421
1422
1423 int Z3950_event (int no, Z3950_connection *cs)
1424 {
1425 #if HAVE_SYS_POLL_H
1426     struct pollfd pollfds[1024];
1427     Z3950_connection poll_cs[1024];
1428 #else
1429     struct timeval tv;
1430     fd_set input, output, except;
1431 #endif
1432     int i, r, nfds;
1433     int max_fd = 0;
1434
1435     for (i = 0; i<no; i++)
1436     {
1437         Z3950_connection c = cs[i];
1438         Z3950_Event event;
1439         if (c && (event = Z3950_connection_get_event(c)))
1440         {
1441             Z3950_Event_destroy (event);
1442             return i+1;
1443         }
1444     }
1445     for (i = 0; i<no; i++)
1446     {
1447         Z3950_connection c = cs[i];
1448         if (c && Z3950_connection_exec_task (c))
1449             return i+1;
1450     }
1451 #if HAVE_SYS_POLL_H
1452
1453 #else
1454     tv.tv_sec = 15;
1455     tv.tv_usec = 0;
1456     
1457     FD_ZERO (&input);
1458     FD_ZERO (&output);
1459     FD_ZERO (&except);
1460 #endif
1461     nfds = 0;
1462     for (i = 0; i<no; i++)
1463     {
1464         Z3950_connection c = cs[i];
1465         int fd, mask;
1466         
1467         if (!c)
1468             continue;
1469         fd = z3950_connection_socket(c);
1470         mask = z3950_connection_mask(c);
1471
1472         if (fd == -1)
1473             continue;
1474         if (max_fd < fd)
1475             max_fd = fd;
1476
1477 #if HAVE_SYS_POLL_H
1478         if (mask)
1479         {
1480             short poll_events = 0;
1481
1482             if (mask & Z3950_SELECT_READ)
1483                 poll_events += POLLIN;
1484             if (mask & Z3950_SELECT_WRITE)
1485                 poll_events += POLLOUT;
1486             if (mask & Z3950_SELECT_EXCEPT)
1487                 poll_events += POLLERR;
1488             pollfds[nfds].fd = fd;
1489             pollfds[nfds].events = poll_events;
1490             pollfds[nfds].revents = 0;
1491             poll_cs[nfds] = c;
1492             nfds++;
1493         }
1494 #else
1495         if (mask & Z3950_SELECT_READ)
1496         {
1497             FD_SET (fd, &input);
1498             nfds++;
1499         }
1500         if (mask & Z3950_SELECT_WRITE)
1501         {
1502             FD_SET (fd, &output);
1503             nfds++;
1504         }
1505         if (mask & Z3950_SELECT_EXCEPT)
1506         {
1507             FD_SET (fd, &except);
1508             nfds++;
1509         }
1510 #endif
1511     }
1512     if (!nfds)
1513         return 0;
1514 #if HAVE_SYS_POLL_H
1515     yaz_log (LOG_LOG, "poll start");
1516     r = poll (pollfds, nfds, 15000);
1517     yaz_log (LOG_LOG, "poll stop, returned r=%d", r);
1518     for (i = 0; i<nfds; i++)
1519     {
1520         Z3950_connection c = poll_cs[i];
1521         if (r && c->mask)
1522         {
1523             int mask = 0;
1524             if (pollfds[i].revents & POLLIN)
1525                 mask += Z3950_SELECT_READ;
1526             if (pollfds[i].revents & POLLOUT)
1527                 mask += Z3950_SELECT_WRITE;
1528             if (pollfds[i].revents & POLLERR)
1529                 mask += Z3950_SELECT_EXCEPT;
1530             if (mask)
1531                 Z3950_connection_do_io(c, mask);
1532         }
1533         else if (r == 0 && c->mask)
1534         {
1535             Z3950_Event event = Z3950_Event_create(0);
1536             /* timeout and this connection was waiting */
1537             c->error = Z3950_ERROR_TIMEOUT;
1538             do_close (c);
1539             Z3950_connection_put_event(c, event);
1540         }
1541     }
1542 #else
1543     yaz_log (LOG_DEBUG, "select start");
1544     r = select (max_fd+1, &input, &output, &except, &tv);
1545     yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
1546     for (i = 0; i<no; i++)
1547     {
1548         Z3950_connection c = cs[i];
1549         int fd, mask;
1550
1551         if (!c)
1552             continue;
1553         fd = z3950_connection_socket(c);
1554         mask = 0;
1555         if (r && c->mask)
1556         {
1557             /* no timeout and real socket */
1558             if (FD_ISSET(fd, &input))
1559                 mask += Z3950_SELECT_READ;
1560             if (FD_ISSET(fd, &output))
1561                 mask += Z3950_SELECT_WRITE;
1562             if (FD_ISSET(fd, &except))
1563                 mask += Z3950_SELECT_EXCEPT;
1564             if (mask)
1565                 Z3950_connection_do_io(c, mask);
1566         }
1567         if (r == 0 && c->mask)
1568         {
1569             Z3950_Event event = Z3950_Event_create(0);
1570             /* timeout and this connection was waiting */
1571             c->error = Z3950_ERROR_TIMEOUT;
1572             do_close (c);
1573             yaz_log (LOG_LOG, "timeout");
1574             Z3950_connection_put_event(c, event);
1575         }
1576     }
1577 #endif
1578     for (i = 0; i<no; i++)
1579     {
1580         Z3950_connection c = cs[i];
1581         Z3950_Event event;
1582         if (c && (event = Z3950_connection_get_event(c)))
1583         {
1584             Z3950_Event_destroy (event);
1585             return i+1;
1586         }
1587     }
1588     return 0;
1589 }