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