2 * $Id: zoom-c.c,v 1.22 2002-01-24 19:33:09 adam Exp $
4 * ZOOM layer for C, connections, result sets, queries.
7 #include <yaz/xmalloc.h>
8 #include <yaz/otherinfo.h>
10 #include <yaz/pquery.h>
11 #include <yaz/diagbib1.h>
19 static ZOOM_Event ZOOM_Event_create (int kind)
21 ZOOM_Event event = xmalloc (sizeof(*event));
28 static void ZOOM_Event_destroy (ZOOM_Event event)
33 static void ZOOM_connection_put_event (ZOOM_connection c, ZOOM_Event event)
37 c->m_queue_back->prev = event;
38 assert (c->m_queue_front);
42 assert (!c->m_queue_front);
43 c->m_queue_front = event;
45 event->next = c->m_queue_back;
47 c->m_queue_back = event;
50 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
52 ZOOM_Event event = c->m_queue_front;
55 assert (c->m_queue_back);
56 c->m_queue_front = event->prev;
59 assert (c->m_queue_back);
60 c->m_queue_front->next = 0;
64 c->last_event = event->kind;
68 static void clear_error (ZOOM_connection c)
73 case ZOOM_ERROR_CONNECT:
74 case ZOOM_ERROR_MEMORY:
75 case ZOOM_ERROR_DECODE:
76 case ZOOM_ERROR_CONNECTION_LOST:
78 case ZOOM_ERROR_INTERNAL:
81 c->error = ZOOM_ERROR_NONE;
87 ZOOM_task ZOOM_connection_add_task (ZOOM_connection c, int which)
89 ZOOM_task *taskp = &c->tasks;
91 taskp = &(*taskp)->next;
92 *taskp = xmalloc (sizeof(**taskp));
93 (*taskp)->running = 0;
94 (*taskp)->which = which;
100 void ZOOM_connection_remove_task (ZOOM_connection c)
102 ZOOM_task task = c->tasks;
106 c->tasks = task->next;
109 case ZOOM_TASK_SEARCH:
110 ZOOM_resultset_destroy (task->u.search.resultset);
112 case ZOOM_TASK_RETRIEVE:
113 ZOOM_resultset_destroy (task->u.retrieve.resultset);
115 case ZOOM_TASK_CONNECT:
118 ZOOM_scanset_destroy (task->u.scan.scan);
127 void ZOOM_connection_remove_tasks (ZOOM_connection c)
130 ZOOM_connection_remove_task(c);
133 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
135 const char *elementSetName);
137 ZOOM_connection ZOOM_connection_create (ZOOM_options options)
139 ZOOM_connection c = xmalloc (sizeof(*c));
143 c->state = STATE_IDLE;
144 c->error = ZOOM_ERROR_NONE;
152 c->options = ZOOM_options_create_with_parent(options);
161 c->odr_in = odr_createmem (ODR_DECODE);
162 c->odr_out = odr_createmem (ODR_ENCODE);
165 c->support_named_resultsets = 0;
166 c->last_event = ZOOM_EVENT_NONE;
168 c->m_queue_front = 0;
173 /* set database names. Take local databases (if set); otherwise
174 take databases given in ZURL (if set); otherwise use Default */
175 static char **set_DatabaseNames (ZOOM_connection con, ZOOM_options options,
178 char **databaseNames;
181 const char *cp = ZOOM_options_get (options, "databaseName");
185 cp = strchr (con->host_port, '/');
192 while ((c = strchr(c, '+')))
200 databaseNames = odr_malloc (con->odr_out, no * sizeof(*databaseNames));
204 c = strchr (cp, '+');
212 /* cp ptr to first char of db name, c is char
214 databaseNames[no] = odr_malloc (con->odr_out, 1+c-cp);
215 memcpy (databaseNames[no], cp, c-cp);
216 databaseNames[no++][c-cp] = '\0';
221 databaseNames[no] = NULL;
223 return databaseNames;
226 ZOOM_connection ZOOM_connection_new (const char *host, int portnum)
228 ZOOM_connection c = ZOOM_connection_create (0);
230 ZOOM_connection_connect (c, host, portnum);
234 void ZOOM_connection_connect(ZOOM_connection c,
235 const char *host, int portnum)
240 val = ZOOM_options_get (c->options, "proxy");
242 c->proxy = xstrdup (val);
249 sprintf (hostn, "%.80s:%d", host, portnum);
250 c->host_port = xstrdup(hostn);
253 c->host_port = xstrdup(host);
255 ZOOM_options_set(c->options, "host", c->host_port);
257 c->async = ZOOM_options_get_bool (c->options, "async", 0);
259 c->error = ZOOM_ERROR_NONE;
261 task = ZOOM_connection_add_task (c, ZOOM_TASK_CONNECT);
265 while (ZOOM_event (1, &c))
270 ZOOM_query ZOOM_query_create(void)
272 ZOOM_query s = xmalloc (sizeof(*s));
277 s->odr = odr_createmem (ODR_ENCODE);
282 void ZOOM_query_destroy(ZOOM_query s)
288 yaz_log (LOG_DEBUG, "ZOOM_query_destroy count=%d", s->refcount);
289 if (s->refcount == 0)
291 odr_destroy (s->odr);
296 int ZOOM_query_prefix(ZOOM_query s, const char *str)
298 s->query = odr_malloc (s->odr, sizeof(*s->query));
299 s->query->which = Z_Query_type_1;
300 s->query->u.type_1 = p_query_rpn(s->odr, PROTO_Z3950, str);
301 if (!s->query->u.type_1)
306 int ZOOM_query_sortby(ZOOM_query s, const char *criteria)
308 s->sort_spec = yaz_sort_spec (s->odr, criteria);
314 static int do_write(ZOOM_connection c);
316 void ZOOM_connection_destroy(ZOOM_connection c)
323 for (r = c->resultsets; r; r = r->next)
328 odr_destroy (c->odr_in);
329 odr_destroy (c->odr_out);
330 ZOOM_options_destroy (c->options);
331 ZOOM_connection_remove_tasks (c);
332 xfree (c->host_port);
336 void ZOOM_resultset_addref (ZOOM_resultset r)
341 ZOOM_resultset ZOOM_resultset_create ()
343 ZOOM_resultset r = xmalloc (sizeof(*r));
347 r->odr = odr_createmem (ODR_ENCODE);
361 ZOOM_resultset ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
364 ZOOM_query s = ZOOM_query_create();
366 ZOOM_query_prefix (s, q);
368 r = ZOOM_connection_search (c, s);
369 ZOOM_query_destroy (s);
373 ZOOM_resultset ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
375 ZOOM_resultset r = ZOOM_resultset_create ();
379 r->r_sort_spec = q->sort_spec;
380 r->r_query = q->query;
383 r->options = ZOOM_options_create_with_parent(c->options);
385 r->start = ZOOM_options_get_int(r->options, "start", 0);
386 r->count = ZOOM_options_get_int(r->options, "count", 0);
387 r->piggyback = ZOOM_options_get_bool (r->options, "piggyback", 1);
388 cp = ZOOM_options_get (r->options, "setname");
390 r->setname = xstrdup (cp);
394 r->next = c->resultsets;
397 task = ZOOM_connection_add_task (c, ZOOM_TASK_SEARCH);
398 task->u.search.resultset = r;
399 ZOOM_resultset_addref (r);
405 while (ZOOM_event (1, &c))
411 void ZOOM_resultset_destroy(ZOOM_resultset r)
416 yaz_log (LOG_DEBUG, "destroy r = %p count=%d", r, r->refcount);
417 if (r->refcount == 0)
419 ZOOM_record_cache rc;
421 for (rc = r->record_cache; rc; rc = rc->next)
422 if (rc->rec.wrbuf_marc)
423 wrbuf_free (rc->rec.wrbuf_marc, 1);
426 /* remove ourselves from the resultsets in connection */
427 ZOOM_resultset *rp = &r->connection->resultsets;
430 assert (*rp); /* we must be in this list!! */
432 { /* OK, we're here - take us out of it */
439 ZOOM_query_destroy (r->search);
440 ZOOM_options_destroy (r->options);
441 odr_destroy (r->odr);
447 size_t ZOOM_resultset_size (ZOOM_resultset r)
452 static void do_close (ZOOM_connection c)
458 c->state = STATE_IDLE;
461 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
462 int force_sync, int start, int count)
472 task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
473 task->u.retrieve.resultset = r;
474 task->u.retrieve.start = start;
475 task->u.retrieve.count = count;
477 ZOOM_resultset_addref (r);
479 if (!r->connection->async || force_sync)
480 while (r->connection && ZOOM_event (1, &r->connection))
484 void ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
485 size_t start, size_t count)
487 int force_present = 0;
493 ZOOM_resultset_retrieve (r, force_present, start, count);
497 for (i = 0; i< count; i++)
498 recs[i] = ZOOM_resultset_record_immediate (r, i+start);
502 static int do_connect (ZOOM_connection c)
505 const char *effective_host;
508 effective_host = c->proxy;
510 effective_host = c->host_port;
512 yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
515 c->cs = cs_create_host (effective_host, 0, &add);
519 int ret = cs_connect (c->cs, add);
520 yaz_log (LOG_DEBUG, "cs_connect returned %d", ret);
523 c->state = STATE_CONNECTING;
524 c->mask = ZOOM_SELECT_EXCEPT;
525 if (c->cs->io_pending & CS_WANT_WRITE)
526 c->mask += ZOOM_SELECT_WRITE;
527 if (c->cs->io_pending & CS_WANT_READ)
528 c->mask += ZOOM_SELECT_READ;
532 c->state = STATE_IDLE;
533 c->error = ZOOM_ERROR_CONNECT;
537 int z3950_connection_socket(ZOOM_connection c)
540 return cs_fileno(c->cs);
544 int z3950_connection_mask(ZOOM_connection c)
551 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
556 sprintf (str, "send_APDU t=%p type=%d", c, a->which);
559 Z_OtherInformation **oi;
561 yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
563 if (!z_APDU(out, &a, 0, 0))
565 FILE *outf = fopen("/tmp/apdu.txt", "w");
568 ODR odr_pr = odr_createmem(ODR_PRINT);
569 fprintf (outf, "a=%p\n", a);
570 odr_setprint(odr_pr, outf);
571 z_APDU(odr_pr, &a, 0, 0);
575 c->error = ZOOM_ERROR_ENCODE;
583 static int send_APDU (ZOOM_connection c, Z_APDU *a)
587 if (encode_APDU(c, a, c->odr_out))
589 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
590 event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
591 ZOOM_connection_put_event (c, event);
592 odr_reset(c->odr_out);
597 static int ZOOM_connection_send_init (ZOOM_connection c)
600 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
601 Z_InitRequest *ireq = apdu->u.initRequest;
602 Z_IdAuthentication *auth = odr_malloc(c->odr_out, sizeof(*auth));
603 const char *auth_groupId = ZOOM_options_get (c->options, "group");
604 const char *auth_userId = ZOOM_options_get (c->options, "user");
605 const char *auth_password = ZOOM_options_get (c->options, "pass");
607 ODR_MASK_SET(ireq->options, Z_Options_search);
608 ODR_MASK_SET(ireq->options, Z_Options_present);
609 ODR_MASK_SET(ireq->options, Z_Options_scan);
610 ODR_MASK_SET(ireq->options, Z_Options_sort);
611 ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
612 ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
614 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
615 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
616 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
618 impname = ZOOM_options_get (c->options, "implementationName");
619 ireq->implementationName =
620 odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
621 strcpy (ireq->implementationName, "");
624 strcat (ireq->implementationName, impname);
625 strcat (ireq->implementationName, "/");
627 strcat (ireq->implementationName, "ZOOM-C/YAZ");
629 *ireq->maximumRecordSize =
630 ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
631 *ireq->preferredMessageSize =
632 ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
634 if (auth_groupId || auth_password)
636 Z_IdPass *pass = odr_malloc(c->odr_out, sizeof(*pass));
639 if (auth_groupId && *auth_groupId)
641 pass->groupId = odr_malloc(c->odr_out, strlen(auth_groupId)+1);
642 strcpy(pass->groupId, auth_groupId);
646 if (auth_userId && *auth_userId)
648 pass->userId = odr_malloc(c->odr_out, strlen(auth_userId)+1);
649 strcpy(pass->userId, auth_userId);
653 if (auth_password && *auth_password)
655 pass->password = odr_malloc(c->odr_out, strlen(auth_password)+1);
656 strcpy(pass->password, auth_password);
661 auth->which = Z_IdAuthentication_idPass;
662 auth->u.idPass = pass;
663 ireq->idAuthentication = auth;
666 else if (auth_userId)
668 auth->which = Z_IdAuthentication_open;
669 auth->u.open = odr_malloc(c->odr_out, strlen(auth_userId)+1);
670 strcpy(auth->u.open, auth_userId);
671 ireq->idAuthentication = auth;
674 yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
675 VAL_PROXY, 1, c->host_port);
682 static int ZOOM_connection_send_search (ZOOM_connection c)
685 int lslb, ssub, mspn;
687 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
688 Z_SearchRequest *search_req = apdu->u.searchRequest;
689 const char *elementSetName;
690 const char *smallSetElementSetName;
691 const char *mediumSetElementSetName;
695 assert (c->tasks->which == ZOOM_TASK_SEARCH);
697 r = c->tasks->u.search.resultset;
700 ZOOM_options_get (r->options, "elementSetName");
701 smallSetElementSetName =
702 ZOOM_options_get (r->options, "smallSetElementSetName");
703 mediumSetElementSetName =
704 ZOOM_options_get (r->options, "mediumSetElementSetName");
706 ZOOM_options_get (r->options, "schema");
708 if (!smallSetElementSetName)
709 smallSetElementSetName = elementSetName;
711 if (!mediumSetElementSetName)
712 mediumSetElementSetName = elementSetName;
717 /* prepare query for the search request */
718 search_req->query = r->r_query;
720 search_req->databaseNames =
721 set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
723 /* get syntax (no need to provide unless piggyback is in effect) */
724 syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
726 lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
727 ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
728 mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
729 if (lslb != -1 && ssub != -1 && mspn != -1)
731 /* So're a Z39.50 expert? Let's hope you don't do sort */
732 *search_req->largeSetLowerBound = lslb;
733 *search_req->smallSetUpperBound = ssub;
734 *search_req->mediumSetPresentNumber = mspn;
736 else if (r->start == 0 && r->count > 0
737 && r->piggyback && !r->r_sort_spec && !schema)
739 /* Regular piggyback - do it unless we're going to do sort */
740 *search_req->largeSetLowerBound = 2000000000;
741 *search_req->smallSetUpperBound = r->count;
742 *search_req->mediumSetPresentNumber = r->count;
743 smallSetElementSetName = 0; /* no need to provide this */
747 /* non-piggyback. Need not provide elementsets or syntaxes .. */
748 smallSetElementSetName = 0;
749 mediumSetElementSetName = 0;
752 if (smallSetElementSetName && *smallSetElementSetName)
754 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
756 esn->which = Z_ElementSetNames_generic;
757 esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
758 search_req->smallSetElementSetNames = esn;
760 if (mediumSetElementSetName && *mediumSetElementSetName)
762 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
764 esn->which = Z_ElementSetNames_generic;
765 esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
766 search_req->mediumSetElementSetNames = esn;
769 search_req->preferredRecordSyntax =
770 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
774 if (c->support_named_resultsets)
778 /* find the lowest unused ordinal so that we re-use
779 result sets on the server. */
780 for (ord = 1; ; ord++)
783 sprintf (setname, "%d", ord);
784 for (rp = c->resultsets; rp; rp = rp->next)
785 if (rp->setname && !strcmp (rp->setname, setname))
790 r->setname = xstrdup (setname);
791 yaz_log (LOG_DEBUG, "allocating %s", r->setname);
794 r->setname = xstrdup ("default");
795 ZOOM_options_set (r->options, "setname", r->setname);
797 search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
798 /* send search request */
804 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
806 Z_DefaultDiagFormat *r;
811 if (p->which != Z_DiagRec_defaultFormat)
813 c->error = ZOOM_ERROR_DECODE;
816 r = p->u.defaultFormat;
819 case Z_DefaultDiagFormat_v2Addinfo:
820 addinfo = r->u.v2Addinfo;
822 case Z_DefaultDiagFormat_v3Addinfo:
823 addinfo = r->u.v3Addinfo;
827 c->addinfo = xstrdup (addinfo);
828 c->error = *r->condition;
831 ZOOM_record ZOOM_record_clone (ZOOM_record srec)
838 odr_enc = odr_createmem(ODR_ENCODE);
839 if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
841 buf = odr_getbuf (odr_enc, &size, 0);
843 nrec = xmalloc (sizeof(*nrec));
844 nrec->odr = odr_createmem(ODR_DECODE);
845 nrec->wrbuf_marc = 0;
846 odr_setbuf (nrec->odr, buf, size, 0);
847 z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
849 odr_destroy (odr_enc);
853 ZOOM_record ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
855 return record_cache_lookup (s, pos, 0);
858 ZOOM_record ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
860 ZOOM_resultset_retrieve (r, 1, pos, 1);
861 return ZOOM_resultset_record_immediate (r, pos);
864 void ZOOM_record_destroy (ZOOM_record rec)
869 wrbuf_free (rec->wrbuf_marc, 1);
870 odr_destroy (rec->odr);
874 void *ZOOM_record_get (ZOOM_record rec, const char *type, size_t *len)
876 Z_NamePlusRecord *npr;
882 if (!strcmp (type, "database"))
884 return npr->databaseName;
886 else if (!strcmp (type, "syntax"))
888 if (npr->which == Z_NamePlusRecord_databaseRecord)
890 Z_External *r = (Z_External *) npr->u.databaseRecord;
891 oident *ent = oid_getentbyoid(r->direct_reference);
897 else if (!strcmp (type, "render"))
899 if (npr->which == Z_NamePlusRecord_databaseRecord)
901 Z_External *r = (Z_External *) npr->u.databaseRecord;
902 oident *ent = oid_getentbyoid(r->direct_reference);
904 if (r->which == Z_External_sutrs)
906 *len = r->u.sutrs->len;
907 return r->u.sutrs->buf;
909 else if (r->which == Z_External_octet)
918 case VAL_APPLICATION_XML:
921 if (!rec->wrbuf_marc)
922 rec->wrbuf_marc = wrbuf_alloc();
923 wrbuf_rewind (rec->wrbuf_marc);
924 if (marc_display_wrbuf (r->u.octet_aligned->buf,
926 r->u.octet_aligned->len) > 0)
928 *len = wrbuf_len(rec->wrbuf_marc);
929 return wrbuf_buf(rec->wrbuf_marc);
932 *len = r->u.octet_aligned->len;
933 return r->u.octet_aligned->buf;
935 else if (r->which == Z_External_grs1)
943 else if (!strcmp (type, "raw"))
945 if (npr->which == Z_NamePlusRecord_databaseRecord)
947 Z_External *r = (Z_External *) npr->u.databaseRecord;
949 if (r->which == Z_External_sutrs)
951 *len = r->u.sutrs->len;
952 return r->u.sutrs->buf;
954 else if (r->which == Z_External_octet)
956 *len = r->u.octet_aligned->len;
957 return r->u.octet_aligned->buf;
959 else /* grs-1, explain, ... */
962 return (Z_External *) npr->u.databaseRecord;
970 static void record_cache_add (ZOOM_resultset r,
971 Z_NamePlusRecord *npr,
973 const char *elementSetName)
975 ZOOM_record_cache rc;
977 for (rc = r->record_cache; rc; rc = rc->next)
981 if ((!elementSetName && !rc->elementSetName)
982 || (elementSetName && rc->elementSetName &&
983 !strcmp (elementSetName, rc->elementSetName)))
985 /* not destroying rc->npr (it's handled by nmem )*/
987 /* keeping wrbuf_marc too */
992 rc = odr_malloc (r->odr, sizeof(*rc));
995 rc->rec.wrbuf_marc = 0;
997 rc->elementSetName = odr_strdup (r->odr, elementSetName);
999 rc->elementSetName = 0;
1001 rc->next = r->record_cache;
1002 r->record_cache = rc;
1005 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
1007 const char *elementSetName)
1009 ZOOM_record_cache rc;
1011 for (rc = r->record_cache; rc; rc = rc->next)
1015 if ((!elementSetName && !rc->elementSetName)
1016 || (elementSetName && rc->elementSetName &&
1017 !strcmp (elementSetName, rc->elementSetName)))
1024 static void handle_records (ZOOM_connection c, Z_Records *sr,
1027 ZOOM_resultset resultset;
1031 switch (c->tasks->which)
1033 case ZOOM_TASK_SEARCH:
1034 resultset = c->tasks->u.search.resultset;
1036 case ZOOM_TASK_RETRIEVE:
1037 resultset = c->tasks->u.retrieve.resultset;
1042 if (sr && sr->which == Z_Records_NSD)
1044 Z_DiagRec dr, *dr_p = &dr;
1045 dr.which = Z_DiagRec_defaultFormat;
1046 dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1048 response_diag (c, dr_p);
1050 else if (sr && sr->which == Z_Records_multipleNSD)
1052 if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1053 response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1055 c->error = ZOOM_ERROR_DECODE;
1059 if (resultset->count + resultset->start > resultset->size)
1060 resultset->count = resultset->size - resultset->start;
1061 if (resultset->count < 0)
1062 resultset->count = 0;
1063 if (sr && sr->which == Z_Records_DBOSD)
1066 NMEM nmem = odr_extract_mem (c->odr_in);
1067 Z_NamePlusRecordList *p =
1068 sr->u.databaseOrSurDiagnostics;
1069 for (i = 0; i<p->num_records; i++)
1071 record_cache_add (resultset, p->records[i],
1072 i+ resultset->start, 0);
1074 /* transfer our response to search_nmem .. we need it later */
1075 nmem_transfer (resultset->odr->mem, nmem);
1076 nmem_destroy (nmem);
1077 if (present_phase && p->num_records == 0)
1079 /* present response and we didn't get any records! */
1080 c->error = ZOOM_ERROR_DECODE;
1083 else if (present_phase)
1085 /* present response and we didn't get any records! */
1086 c->error = ZOOM_ERROR_DECODE;
1091 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1093 handle_records (c, pr->records, 1);
1096 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1098 ZOOM_resultset resultset;
1100 yaz_log (LOG_DEBUG, "got search response");
1102 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1105 resultset = c->tasks->u.search.resultset;
1107 resultset->size = *sr->resultCount;
1108 handle_records (c, sr->records, 0);
1111 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1113 if (res->diagnostics && res->num_diagnostics > 0)
1114 response_diag (c, res->diagnostics[0]);
1117 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1119 NMEM nmem = odr_extract_mem (c->odr_in);
1122 if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1124 scan = c->tasks->u.scan.scan;
1126 if (res->entries && res->entries->nonsurrogateDiagnostics)
1127 response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1128 scan->scan_response = res;
1129 nmem_transfer (scan->odr->mem, nmem);
1131 ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1132 if (res->positionOfTerm)
1133 ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1134 if (res->scanStatus)
1135 ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1136 if (res->numberOfEntriesReturned)
1137 ZOOM_options_set_int (scan->options, "number",
1138 *res->numberOfEntriesReturned);
1139 nmem_destroy (nmem);
1143 static int send_sort (ZOOM_connection c)
1145 ZOOM_resultset resultset;
1147 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1150 resultset = c->tasks->u.search.resultset;
1154 resultset->r_sort_spec = 0;
1157 if (resultset->r_sort_spec)
1159 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1160 Z_SortRequest *req = apdu->u.sortRequest;
1162 req->num_inputResultSetNames = 1;
1163 req->inputResultSetNames = (Z_InternationalString **)
1164 odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1165 req->inputResultSetNames[0] =
1166 odr_strdup (c->odr_out, resultset->setname);
1167 req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1168 req->sortSequence = resultset->r_sort_spec;
1169 resultset->r_sort_spec = 0;
1170 send_APDU (c, apdu);
1176 static int send_present (ZOOM_connection c)
1178 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1179 Z_PresentRequest *req = apdu->u.presentRequest;
1181 const char *syntax =
1182 ZOOM_options_get (c->options, "preferredRecordSyntax");
1183 const char *element =
1184 ZOOM_options_get (c->options, "elementSetName");
1185 const char *schema =
1186 ZOOM_options_get (c->options, "schema");
1187 ZOOM_resultset resultset;
1192 switch (c->tasks->which)
1194 case ZOOM_TASK_SEARCH:
1195 resultset = c->tasks->u.search.resultset;
1197 case ZOOM_TASK_RETRIEVE:
1198 resultset = c->tasks->u.retrieve.resultset;
1199 resultset->start = c->tasks->u.retrieve.start;
1200 resultset->count = c->tasks->u.retrieve.count;
1202 if (resultset->start >= resultset->size)
1204 if (resultset->start + resultset->count > resultset->size)
1205 resultset->count = resultset->size - resultset->start;
1211 if (c->error) /* don't continue on error */
1213 if (resultset->start < 0)
1215 for (i = 0; i<resultset->count; i++)
1218 record_cache_lookup (resultset, i + resultset->start, 0);
1222 if (i == resultset->count)
1225 resultset->start += i;
1226 resultset->count -= i;
1227 *req->resultSetStartPoint = resultset->start + 1;
1228 *req->numberOfRecordsRequested = resultset->count;
1229 assert (*req->numberOfRecordsRequested > 0);
1231 if (syntax && *syntax)
1232 req->preferredRecordSyntax =
1233 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1235 if (schema && *schema)
1237 Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1239 req->recordComposition = compo;
1240 compo->which = Z_RecordComp_complex;
1241 compo->u.complex = (Z_CompSpec *)
1242 odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1243 compo->u.complex->selectAlternativeSyntax = (bool_t *)
1244 odr_malloc(c->odr_out, sizeof(bool_t));
1245 *compo->u.complex->selectAlternativeSyntax = 0;
1247 compo->u.complex->generic = (Z_Specification *)
1248 odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1250 compo->u.complex->generic->schema = (Odr_oid *)
1251 yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, schema);
1253 if (!compo->u.complex->generic->schema)
1255 /* OID wasn't a schema! Try record syntax instead. */
1257 compo->u.complex->generic->schema = (Odr_oid *)
1258 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, schema);
1260 if (element && *element)
1262 compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1263 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1264 compo->u.complex->generic->elementSpec->which =
1265 Z_ElementSpec_elementSetName;
1266 compo->u.complex->generic->elementSpec->u.elementSetName =
1267 odr_strdup (c->odr_out, element);
1270 compo->u.complex->generic->elementSpec = 0;
1271 compo->u.complex->num_dbSpecific = 0;
1272 compo->u.complex->dbSpecific = 0;
1273 compo->u.complex->num_recordSyntax = 0;
1274 compo->u.complex->recordSyntax = 0;
1276 else if (element && *element)
1278 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
1279 Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1281 esn->which = Z_ElementSetNames_generic;
1282 esn->u.generic = odr_strdup (c->odr_out, element);
1283 compo->which = Z_RecordComp_simple;
1284 compo->u.simple = esn;
1285 req->recordComposition = compo;
1287 req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1288 send_APDU (c, apdu);
1292 ZOOM_scanset ZOOM_connection_scan (ZOOM_connection c, const char *start)
1294 ZOOM_scanset scan = xmalloc (sizeof(*scan));
1296 scan->connection = c;
1297 scan->odr = odr_createmem (ODR_DECODE);
1298 scan->options = ZOOM_options_create_with_parent (c->options);
1300 scan->scan_response = 0;
1302 if ((scan->termListAndStartPoint =
1303 p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
1306 ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
1307 task->u.scan.scan = scan;
1312 while (ZOOM_event (1, &c))
1319 void ZOOM_scanset_destroy (ZOOM_scanset scan)
1324 if (scan->refcount == 0)
1326 odr_destroy (scan->odr);
1328 ZOOM_options_destroy (scan->options);
1333 int send_scan (ZOOM_connection c)
1336 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
1337 Z_ScanRequest *req = apdu->u.scanRequest;
1340 assert (c->tasks->which == ZOOM_TASK_SCAN);
1341 scan = c->tasks->u.scan.scan;
1343 req->termListAndStartPoint = scan->termListAndStartPoint;
1344 req->attributeSet = scan->attributeSet;
1346 *req->numberOfTermsRequested =
1347 ZOOM_options_get_int(scan->options, "number", 10);
1349 req->preferredPositionInResponse =
1350 odr_intdup (c->odr_out,
1351 ZOOM_options_get_int(scan->options, "position", 1));
1354 odr_intdup (c->odr_out,
1355 ZOOM_options_get_int(scan->options, "stepSize", 0));
1357 req->databaseNames = set_DatabaseNames (c, scan->options,
1358 &req->num_databaseNames);
1360 send_APDU (c, apdu);
1365 size_t ZOOM_scanset_size (ZOOM_scanset scan)
1367 if (!scan || !scan->scan_response || !scan->scan_response->entries)
1369 return scan->scan_response->entries->num_entries;
1372 const char *ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
1373 int *occ, size_t *len)
1375 const char *term = 0;
1376 size_t noent = ZOOM_scanset_size (scan);
1377 Z_ScanResponse *res = scan->scan_response;
1383 if (res->entries->entries[pos]->which == Z_Entry_termInfo)
1385 Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
1387 if (t->term->which == Z_Term_general)
1389 term = t->term->u.general->buf;
1390 *len = t->term->u.general->len;
1392 *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
1397 const char *ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
1399 return ZOOM_options_get (scan->options, key);
1402 void ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
1405 ZOOM_options_set (scan->options, key, val);
1408 static int ZOOM_connection_exec_task (ZOOM_connection c)
1410 ZOOM_task task = c->tasks;
1412 yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task");
1415 if (c->error != ZOOM_ERROR_NONE ||
1416 (!c->cs && task->which != ZOOM_TASK_CONNECT))
1418 ZOOM_connection_remove_tasks (c);
1421 yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d", task->which);
1425 switch (task->which)
1427 case ZOOM_TASK_SEARCH:
1428 /* see if search hasn't been sent yet. */
1429 if (ZOOM_connection_send_search (c))
1432 case ZOOM_TASK_RETRIEVE:
1433 if (send_present (c))
1436 case ZOOM_TASK_CONNECT:
1440 case ZOOM_TASK_SCAN:
1444 ZOOM_connection_remove_task (c);
1448 static int send_sort_present (ZOOM_connection c)
1450 int r = send_sort (c);
1452 r = send_present (c);
1456 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
1458 Z_InitResponse *initrs;
1460 yaz_log (LOG_DEBUG, "hande_apdu type=%d", apdu->which);
1464 case Z_APDU_initResponse:
1465 initrs = apdu->u.initResponse;
1466 if (!*initrs->result)
1468 c->error = ZOOM_ERROR_INIT;
1473 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
1475 xfree (c->cookie_in);
1478 c->cookie_in = xstrdup(cookie);
1479 if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
1480 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
1481 c->support_named_resultsets = 1;
1484 assert (c->tasks->which == ZOOM_TASK_CONNECT);
1485 ZOOM_connection_remove_task (c);
1487 ZOOM_connection_exec_task (c);
1490 case Z_APDU_searchResponse:
1491 handle_search_response (c, apdu->u.searchResponse);
1492 if (!send_sort_present (c))
1493 ZOOM_connection_remove_task (c);
1495 case Z_APDU_presentResponse:
1496 handle_present_response (c, apdu->u.presentResponse);
1497 if (!send_present (c))
1498 ZOOM_connection_remove_task (c);
1500 case Z_APDU_sortResponse:
1501 sort_response (c, apdu->u.sortResponse);
1502 if (!send_present (c))
1503 ZOOM_connection_remove_task (c);
1505 case Z_APDU_scanResponse:
1506 scan_response (c, apdu->u.scanResponse);
1507 ZOOM_connection_remove_task (c);
1511 static int do_read (ZOOM_connection c)
1517 event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
1518 ZOOM_connection_put_event (c, event);
1520 r = cs_get (c->cs, &c->buf_in, &c->len_in);
1525 c->error= ZOOM_ERROR_CONNECTION_LOST;
1531 odr_reset (c->odr_in);
1532 odr_setbuf (c->odr_in, c->buf_in, r, 0);
1533 event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
1534 ZOOM_connection_put_event (c, event);
1535 if (!z_APDU (c->odr_in, &apdu, 0, 0))
1537 c->error = ZOOM_ERROR_DECODE;
1542 handle_apdu (c, apdu);
1548 static int do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
1553 event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
1554 ZOOM_connection_put_event (c, event);
1556 if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
1558 if (c->state == STATE_CONNECTING)
1559 c->error = ZOOM_ERROR_CONNECT;
1561 c->error = ZOOM_ERROR_CONNECTION_LOST;
1567 c->mask = ZOOM_SELECT_EXCEPT;
1568 if (c->cs->io_pending & CS_WANT_WRITE)
1569 c->mask += ZOOM_SELECT_WRITE;
1570 if (c->cs->io_pending & CS_WANT_READ)
1571 c->mask += ZOOM_SELECT_READ;
1572 yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
1576 c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
1577 yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
1582 static int do_write(ZOOM_connection c)
1584 return do_write_ex (c, c->buf_out, c->len_out);
1588 const char *ZOOM_connection_option_get (ZOOM_connection c, const char *key)
1590 return ZOOM_options_get (c->options, key);
1593 void ZOOM_connection_option_set (ZOOM_connection c, const char *key,
1596 ZOOM_options_set (c->options, key, val);
1599 const char *ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
1601 return ZOOM_options_get (r->options, key);
1604 void ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
1607 ZOOM_options_set (r->options, key, val);
1611 int ZOOM_connection_errcode (ZOOM_connection c)
1613 return ZOOM_connection_error (c, 0, 0);
1616 const char *ZOOM_connection_errmsg (ZOOM_connection c)
1619 ZOOM_connection_error (c, &msg, 0);
1623 const char *ZOOM_connection_addinfo (ZOOM_connection c)
1625 const char *addinfo;
1626 ZOOM_connection_error (c, 0, &addinfo);
1630 int ZOOM_connection_error (ZOOM_connection c, const char **cp,
1631 const char **addinfo)
1633 int error = c->error;
1638 case ZOOM_ERROR_NONE:
1639 *cp = "No error"; break;
1640 case ZOOM_ERROR_CONNECT:
1641 *cp = "Connect failed"; break;
1642 case ZOOM_ERROR_MEMORY:
1643 *cp = "Out of memory"; break;
1644 case ZOOM_ERROR_ENCODE:
1645 *cp = "Encoding failed"; break;
1646 case ZOOM_ERROR_DECODE:
1647 *cp = "Decoding failed"; break;
1648 case ZOOM_ERROR_CONNECTION_LOST:
1649 *cp = "Connection lost"; break;
1650 case ZOOM_ERROR_INIT:
1651 *cp = "Init rejected"; break;
1652 case ZOOM_ERROR_INTERNAL:
1653 *cp = "Internal failure"; break;
1654 case ZOOM_ERROR_TIMEOUT:
1655 *cp = "Timeout"; break;
1657 *cp = diagbib1_str (error);
1663 *addinfo = c->addinfo;
1670 int ZOOM_connection_do_io(ZOOM_connection c, int mask)
1672 ZOOM_Event event = 0;
1673 int r = cs_look(c->cs);
1674 yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
1679 event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
1680 c->error = ZOOM_ERROR_CONNECT;
1682 ZOOM_connection_put_event (c, event);
1684 else if (r == CS_CONNECT)
1687 event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
1689 ret = cs_rcvconnect (c->cs);
1690 yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
1693 c->mask = ZOOM_SELECT_EXCEPT;
1694 if (c->cs->io_pending & CS_WANT_WRITE)
1695 c->mask += ZOOM_SELECT_WRITE;
1696 if (c->cs->io_pending & CS_WANT_READ)
1697 c->mask += ZOOM_SELECT_READ;
1698 ZOOM_connection_put_event (c, event);
1702 ZOOM_connection_put_event (c, event);
1703 ZOOM_connection_send_init (c);
1704 c->state = STATE_ESTABLISHED;
1708 c->error = ZOOM_ERROR_CONNECT;
1710 ZOOM_connection_put_event (c, event);
1715 if (mask & ZOOM_SELECT_READ)
1717 if (c->cs && (mask & ZOOM_SELECT_WRITE))
1723 int ZOOM_connection_last_event(ZOOM_connection cs)
1726 return ZOOM_EVENT_NONE;
1727 return cs->last_event;
1730 int ZOOM_event (int no, ZOOM_connection *cs)
1733 struct pollfd pollfds[1024];
1734 ZOOM_connection poll_cs[1024];
1737 fd_set input, output, except;
1742 for (i = 0; i<no; i++)
1744 ZOOM_connection c = cs[i];
1746 if (c && (event = ZOOM_connection_get_event(c)))
1748 ZOOM_Event_destroy (event);
1752 for (i = 0; i<no; i++)
1754 ZOOM_connection c = cs[i];
1756 if (c && ZOOM_connection_exec_task (c))
1758 if ((event = ZOOM_connection_get_event(c)))
1760 ZOOM_Event_destroy (event);
1776 for (i = 0; i<no; i++)
1778 ZOOM_connection c = cs[i];
1783 fd = z3950_connection_socket(c);
1784 mask = z3950_connection_mask(c);
1794 short poll_events = 0;
1796 if (mask & ZOOM_SELECT_READ)
1797 poll_events += POLLIN;
1798 if (mask & ZOOM_SELECT_WRITE)
1799 poll_events += POLLOUT;
1800 if (mask & ZOOM_SELECT_EXCEPT)
1801 poll_events += POLLERR;
1802 pollfds[nfds].fd = fd;
1803 pollfds[nfds].events = poll_events;
1804 pollfds[nfds].revents = 0;
1809 if (mask & ZOOM_SELECT_READ)
1811 FD_SET (fd, &input);
1814 if (mask & ZOOM_SELECT_WRITE)
1816 FD_SET (fd, &output);
1819 if (mask & ZOOM_SELECT_EXCEPT)
1821 FD_SET (fd, &except);
1829 r = poll (pollfds, nfds, 15000);
1830 for (i = 0; i<nfds; i++)
1832 ZOOM_connection c = poll_cs[i];
1836 if (pollfds[i].revents & POLLIN)
1837 mask += ZOOM_SELECT_READ;
1838 if (pollfds[i].revents & POLLOUT)
1839 mask += ZOOM_SELECT_WRITE;
1840 if (pollfds[i].revents & POLLERR)
1841 mask += ZOOM_SELECT_EXCEPT;
1843 ZOOM_connection_do_io(c, mask);
1845 else if (r == 0 && c->mask)
1847 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1848 /* timeout and this connection was waiting */
1849 c->error = ZOOM_ERROR_TIMEOUT;
1851 ZOOM_connection_put_event(c, event);
1855 yaz_log (LOG_DEBUG, "select start");
1856 r = select (max_fd+1, &input, &output, &except, &tv);
1857 yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
1858 for (i = 0; i<no; i++)
1860 ZOOM_connection c = cs[i];
1865 fd = z3950_connection_socket(c);
1869 /* no timeout and real socket */
1870 if (FD_ISSET(fd, &input))
1871 mask += ZOOM_SELECT_READ;
1872 if (FD_ISSET(fd, &output))
1873 mask += ZOOM_SELECT_WRITE;
1874 if (FD_ISSET(fd, &except))
1875 mask += ZOOM_SELECT_EXCEPT;
1877 ZOOM_connection_do_io(c, mask);
1879 if (r == 0 && c->mask)
1881 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1882 /* timeout and this connection was waiting */
1883 c->error = ZOOM_ERROR_TIMEOUT;
1885 yaz_log (LOG_DEBUG, "timeout");
1886 ZOOM_connection_put_event(c, event);
1890 for (i = 0; i<no; i++)
1892 ZOOM_connection c = cs[i];
1894 if (c && (event = ZOOM_connection_get_event(c)))
1896 ZOOM_Event_destroy (event);