2 * $Id: zoom-c.c,v 1.21 2002-01-21 21:50:32 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)
421 /* remove ourselves from the resultsets in connection */
422 ZOOM_resultset *rp = &r->connection->resultsets;
425 assert (*rp); /* we must be in this list!! */
427 { /* OK, we're here - take us out of it */
434 ZOOM_query_destroy (r->search);
435 ZOOM_options_destroy (r->options);
436 odr_destroy (r->odr);
442 size_t ZOOM_resultset_size (ZOOM_resultset r)
447 static void do_close (ZOOM_connection c)
453 c->state = STATE_IDLE;
456 static void ZOOM_resultset_retrieve (ZOOM_resultset r,
457 int force_sync, int start, int count)
467 task = ZOOM_connection_add_task (c, ZOOM_TASK_RETRIEVE);
468 task->u.retrieve.resultset = r;
469 task->u.retrieve.start = start;
470 task->u.retrieve.count = count;
472 ZOOM_resultset_addref (r);
474 if (!r->connection->async || force_sync)
475 while (r->connection && ZOOM_event (1, &r->connection))
479 void ZOOM_resultset_records (ZOOM_resultset r, ZOOM_record *recs,
480 size_t start, size_t count)
482 int force_present = 0;
488 ZOOM_resultset_retrieve (r, force_present, start, count);
492 for (i = 0; i< count; i++)
493 recs[i] = ZOOM_resultset_record_immediate (r, i+start);
497 static int do_connect (ZOOM_connection c)
500 const char *effective_host;
503 effective_host = c->proxy;
505 effective_host = c->host_port;
507 yaz_log (LOG_DEBUG, "do_connect host=%s", effective_host);
510 c->cs = cs_create_host (effective_host, 0, &add);
514 int ret = cs_connect (c->cs, add);
515 yaz_log (LOG_DEBUG, "cs_connect returned %d", ret);
518 c->state = STATE_CONNECTING;
519 c->mask = ZOOM_SELECT_EXCEPT;
520 if (c->cs->io_pending & CS_WANT_WRITE)
521 c->mask += ZOOM_SELECT_WRITE;
522 if (c->cs->io_pending & CS_WANT_READ)
523 c->mask += ZOOM_SELECT_READ;
527 c->state = STATE_IDLE;
528 c->error = ZOOM_ERROR_CONNECT;
532 int z3950_connection_socket(ZOOM_connection c)
535 return cs_fileno(c->cs);
539 int z3950_connection_mask(ZOOM_connection c)
546 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
551 sprintf (str, "send_APDU t=%p type=%d", c, a->which);
554 Z_OtherInformation **oi;
556 yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
558 if (!z_APDU(out, &a, 0, 0))
560 FILE *outf = fopen("/tmp/apdu.txt", "w");
563 ODR odr_pr = odr_createmem(ODR_PRINT);
564 fprintf (outf, "a=%p\n", a);
565 odr_setprint(odr_pr, outf);
566 z_APDU(odr_pr, &a, 0, 0);
570 c->error = ZOOM_ERROR_ENCODE;
578 static int send_APDU (ZOOM_connection c, Z_APDU *a)
582 if (encode_APDU(c, a, c->odr_out))
584 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
585 event = ZOOM_Event_create (ZOOM_EVENT_SEND_APDU);
586 ZOOM_connection_put_event (c, event);
587 odr_reset(c->odr_out);
592 static int ZOOM_connection_send_init (ZOOM_connection c)
595 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
596 Z_InitRequest *ireq = apdu->u.initRequest;
597 Z_IdAuthentication *auth = odr_malloc(c->odr_out, sizeof(*auth));
598 const char *auth_groupId = ZOOM_options_get (c->options, "group");
599 const char *auth_userId = ZOOM_options_get (c->options, "user");
600 const char *auth_password = ZOOM_options_get (c->options, "pass");
602 ODR_MASK_SET(ireq->options, Z_Options_search);
603 ODR_MASK_SET(ireq->options, Z_Options_present);
604 ODR_MASK_SET(ireq->options, Z_Options_scan);
605 ODR_MASK_SET(ireq->options, Z_Options_sort);
606 ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
607 ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
609 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
610 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
611 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
613 impname = ZOOM_options_get (c->options, "implementationName");
614 ireq->implementationName =
615 odr_malloc (c->odr_out, 15 + (impname ? strlen(impname) : 0));
616 strcpy (ireq->implementationName, "");
619 strcat (ireq->implementationName, impname);
620 strcat (ireq->implementationName, "/");
622 strcat (ireq->implementationName, "ZOOM-C/YAZ");
624 *ireq->maximumRecordSize =
625 ZOOM_options_get_int (c->options, "maximumRecordSize", 1024*1024);
626 *ireq->preferredMessageSize =
627 ZOOM_options_get_int (c->options, "preferredMessageSize", 1024*1024);
629 if (auth_groupId || auth_password)
631 Z_IdPass *pass = odr_malloc(c->odr_out, sizeof(*pass));
634 if (auth_groupId && *auth_groupId)
636 pass->groupId = odr_malloc(c->odr_out, strlen(auth_groupId)+1);
637 strcpy(pass->groupId, auth_groupId);
641 if (auth_userId && *auth_userId)
643 pass->userId = odr_malloc(c->odr_out, strlen(auth_userId)+1);
644 strcpy(pass->userId, auth_userId);
648 if (auth_password && *auth_password)
650 pass->password = odr_malloc(c->odr_out, strlen(auth_password)+1);
651 strcpy(pass->password, auth_password);
656 auth->which = Z_IdAuthentication_idPass;
657 auth->u.idPass = pass;
658 ireq->idAuthentication = auth;
661 else if (auth_userId)
663 auth->which = Z_IdAuthentication_open;
664 auth->u.open = odr_malloc(c->odr_out, strlen(auth_userId)+1);
665 strcpy(auth->u.open, auth_userId);
666 ireq->idAuthentication = auth;
669 yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
670 VAL_PROXY, 1, c->host_port);
677 static int ZOOM_connection_send_search (ZOOM_connection c)
680 int lslb, ssub, mspn;
682 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
683 Z_SearchRequest *search_req = apdu->u.searchRequest;
684 const char *elementSetName;
685 const char *smallSetElementSetName;
686 const char *mediumSetElementSetName;
690 assert (c->tasks->which == ZOOM_TASK_SEARCH);
692 r = c->tasks->u.search.resultset;
695 ZOOM_options_get (r->options, "elementSetName");
696 smallSetElementSetName =
697 ZOOM_options_get (r->options, "smallSetElementSetName");
698 mediumSetElementSetName =
699 ZOOM_options_get (r->options, "mediumSetElementSetName");
701 ZOOM_options_get (r->options, "schema");
703 if (!smallSetElementSetName)
704 smallSetElementSetName = elementSetName;
706 if (!mediumSetElementSetName)
707 mediumSetElementSetName = elementSetName;
712 /* prepare query for the search request */
713 search_req->query = r->r_query;
715 search_req->databaseNames =
716 set_DatabaseNames (c, r->options, &search_req->num_databaseNames);
718 /* get syntax (no need to provide unless piggyback is in effect) */
719 syntax = ZOOM_options_get (r->options, "preferredRecordSyntax");
721 lslb = ZOOM_options_get_int (r->options, "largeSetLowerBound", -1);
722 ssub = ZOOM_options_get_int (r->options, "smallSetUpperBound", -1);
723 mspn = ZOOM_options_get_int (r->options, "mediumSetPresentNumber", -1);
724 if (lslb != -1 && ssub != -1 && mspn != -1)
726 /* So're a Z39.50 expert? Let's hope you don't do sort */
727 *search_req->largeSetLowerBound = lslb;
728 *search_req->smallSetUpperBound = ssub;
729 *search_req->mediumSetPresentNumber = mspn;
731 else if (r->start == 0 && r->count > 0
732 && r->piggyback && !r->r_sort_spec && !schema)
734 /* Regular piggyback - do it unless we're going to do sort */
735 *search_req->largeSetLowerBound = 2000000000;
736 *search_req->smallSetUpperBound = r->count;
737 *search_req->mediumSetPresentNumber = r->count;
738 smallSetElementSetName = 0; /* no need to provide this */
742 /* non-piggyback. Need not provide elementsets or syntaxes .. */
743 smallSetElementSetName = 0;
744 mediumSetElementSetName = 0;
747 if (smallSetElementSetName && *smallSetElementSetName)
749 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
751 esn->which = Z_ElementSetNames_generic;
752 esn->u.generic = odr_strdup (c->odr_out, smallSetElementSetName);
753 search_req->smallSetElementSetNames = esn;
755 if (mediumSetElementSetName && *mediumSetElementSetName)
757 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
759 esn->which = Z_ElementSetNames_generic;
760 esn->u.generic = odr_strdup (c->odr_out, mediumSetElementSetName);
761 search_req->mediumSetElementSetNames = esn;
764 search_req->preferredRecordSyntax =
765 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
769 if (c->support_named_resultsets)
773 /* find the lowest unused ordinal so that we re-use
774 result sets on the server. */
775 for (ord = 1; ; ord++)
778 sprintf (setname, "%d", ord);
779 for (rp = c->resultsets; rp; rp = rp->next)
780 if (rp->setname && !strcmp (rp->setname, setname))
785 r->setname = xstrdup (setname);
786 yaz_log (LOG_DEBUG, "allocating %s", r->setname);
789 r->setname = xstrdup ("default");
790 ZOOM_options_set (r->options, "setname", r->setname);
792 search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
793 /* send search request */
799 static void response_diag (ZOOM_connection c, Z_DiagRec *p)
801 Z_DefaultDiagFormat *r;
806 if (p->which != Z_DiagRec_defaultFormat)
808 c->error = ZOOM_ERROR_DECODE;
811 r = p->u.defaultFormat;
814 case Z_DefaultDiagFormat_v2Addinfo:
815 addinfo = r->u.v2Addinfo;
817 case Z_DefaultDiagFormat_v3Addinfo:
818 addinfo = r->u.v3Addinfo;
822 c->addinfo = xstrdup (addinfo);
823 c->error = *r->condition;
826 ZOOM_record ZOOM_record_clone (ZOOM_record srec)
833 odr_enc = odr_createmem(ODR_ENCODE);
834 if (!z_NamePlusRecord (odr_enc, &srec->npr, 0, 0))
836 buf = odr_getbuf (odr_enc, &size, 0);
838 nrec = xmalloc (sizeof(*nrec));
839 nrec->odr = odr_createmem(ODR_DECODE);
840 nrec->wrbuf_marc = 0;
841 odr_setbuf (nrec->odr, buf, size, 0);
842 z_NamePlusRecord (nrec->odr, &nrec->npr, 0, 0);
844 odr_destroy (odr_enc);
848 ZOOM_record ZOOM_resultset_record_immediate (ZOOM_resultset s,size_t pos)
850 return record_cache_lookup (s, pos, 0);
853 ZOOM_record ZOOM_resultset_record (ZOOM_resultset r, size_t pos)
855 ZOOM_resultset_retrieve (r, 1, pos, 1);
856 return ZOOM_resultset_record_immediate (r, pos);
859 void ZOOM_record_destroy (ZOOM_record rec)
864 wrbuf_free (rec->wrbuf_marc, 1);
865 odr_destroy (rec->odr);
869 void *ZOOM_record_get (ZOOM_record rec, const char *type, size_t *len)
871 Z_NamePlusRecord *npr;
877 if (!strcmp (type, "database"))
879 return npr->databaseName;
881 else if (!strcmp (type, "syntax"))
883 if (npr->which == Z_NamePlusRecord_databaseRecord)
885 Z_External *r = (Z_External *) npr->u.databaseRecord;
886 oident *ent = oid_getentbyoid(r->direct_reference);
892 else if (!strcmp (type, "render"))
894 if (npr->which == Z_NamePlusRecord_databaseRecord)
896 Z_External *r = (Z_External *) npr->u.databaseRecord;
897 oident *ent = oid_getentbyoid(r->direct_reference);
899 if (r->which == Z_External_sutrs)
901 *len = r->u.sutrs->len;
902 return r->u.sutrs->buf;
904 else if (r->which == Z_External_octet)
913 case VAL_APPLICATION_XML:
916 if (!rec->wrbuf_marc)
917 rec->wrbuf_marc = wrbuf_alloc();
918 if (marc_display_wrbuf (r->u.octet_aligned->buf,
920 r->u.octet_aligned->len) > 0)
922 *len = wrbuf_len(rec->wrbuf_marc);
923 return wrbuf_buf(rec->wrbuf_marc);
926 *len = r->u.octet_aligned->len;
927 return r->u.octet_aligned->buf;
929 else if (r->which == Z_External_grs1)
937 else if (!strcmp (type, "raw"))
939 if (npr->which == Z_NamePlusRecord_databaseRecord)
941 Z_External *r = (Z_External *) npr->u.databaseRecord;
943 if (r->which == Z_External_sutrs)
945 *len = r->u.sutrs->len;
946 return r->u.sutrs->buf;
948 else if (r->which == Z_External_octet)
950 *len = r->u.octet_aligned->len;
951 return r->u.octet_aligned->buf;
953 else /* grs-1, explain, ... */
956 return (Z_External *) npr->u.databaseRecord;
964 static void record_cache_add (ZOOM_resultset r,
965 Z_NamePlusRecord *npr,
967 const char *elementSetName)
969 ZOOM_record_cache rc;
971 for (rc = r->record_cache; rc; rc = rc->next)
975 if ((!elementSetName && !rc->elementSetName)
976 || (elementSetName && rc->elementSetName &&
977 !strcmp (elementSetName, rc->elementSetName)))
979 /* not destroying rc->npr (it's handled by nmem )*/
981 /* keeping wrbuf_marc too */
987 rc = odr_malloc (r->odr, sizeof(*rc));
990 rc->rec.wrbuf_marc = 0;
992 rc->elementSetName = odr_strdup (r->odr, elementSetName);
994 rc->elementSetName = 0;
996 rc->next = r->record_cache;
997 r->record_cache = rc;
1000 static ZOOM_record record_cache_lookup (ZOOM_resultset r,
1002 const char *elementSetName)
1004 ZOOM_record_cache rc;
1006 for (rc = r->record_cache; rc; rc = rc->next)
1010 if ((!elementSetName && !rc->elementSetName)
1011 || (elementSetName && rc->elementSetName &&
1012 !strcmp (elementSetName, rc->elementSetName)))
1019 static void handle_records (ZOOM_connection c, Z_Records *sr,
1022 ZOOM_resultset resultset;
1026 switch (c->tasks->which)
1028 case ZOOM_TASK_SEARCH:
1029 resultset = c->tasks->u.search.resultset;
1031 case ZOOM_TASK_RETRIEVE:
1032 resultset = c->tasks->u.retrieve.resultset;
1037 if (sr && sr->which == Z_Records_NSD)
1039 Z_DiagRec dr, *dr_p = &dr;
1040 dr.which = Z_DiagRec_defaultFormat;
1041 dr.u.defaultFormat = sr->u.nonSurrogateDiagnostic;
1043 response_diag (c, dr_p);
1045 else if (sr && sr->which == Z_Records_multipleNSD)
1047 if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1048 response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1050 c->error = ZOOM_ERROR_DECODE;
1054 if (resultset->count + resultset->start > resultset->size)
1055 resultset->count = resultset->size - resultset->start;
1056 if (resultset->count < 0)
1057 resultset->count = 0;
1058 if (sr && sr->which == Z_Records_DBOSD)
1061 NMEM nmem = odr_extract_mem (c->odr_in);
1062 Z_NamePlusRecordList *p =
1063 sr->u.databaseOrSurDiagnostics;
1064 for (i = 0; i<p->num_records; i++)
1066 record_cache_add (resultset, p->records[i],
1067 i+ resultset->start, 0);
1069 /* transfer our response to search_nmem .. we need it later */
1070 nmem_transfer (resultset->odr->mem, nmem);
1071 nmem_destroy (nmem);
1072 if (present_phase && p->num_records == 0)
1074 /* present response and we didn't get any records! */
1075 c->error = ZOOM_ERROR_DECODE;
1078 else if (present_phase)
1080 /* present response and we didn't get any records! */
1081 c->error = ZOOM_ERROR_DECODE;
1086 static void handle_present_response (ZOOM_connection c, Z_PresentResponse *pr)
1088 handle_records (c, pr->records, 1);
1091 static void handle_search_response (ZOOM_connection c, Z_SearchResponse *sr)
1093 ZOOM_resultset resultset;
1095 yaz_log (LOG_DEBUG, "got search response");
1097 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1100 resultset = c->tasks->u.search.resultset;
1102 resultset->size = *sr->resultCount;
1103 handle_records (c, sr->records, 0);
1106 static void sort_response (ZOOM_connection c, Z_SortResponse *res)
1108 if (res->diagnostics && res->num_diagnostics > 0)
1109 response_diag (c, res->diagnostics[0]);
1112 static int scan_response (ZOOM_connection c, Z_ScanResponse *res)
1114 NMEM nmem = odr_extract_mem (c->odr_in);
1117 if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1119 scan = c->tasks->u.scan.scan;
1121 if (res->entries && res->entries->nonsurrogateDiagnostics)
1122 response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1123 scan->scan_response = res;
1124 nmem_transfer (scan->odr->mem, nmem);
1126 ZOOM_options_set_int (scan->options, "stepSize", *res->stepSize);
1127 if (res->positionOfTerm)
1128 ZOOM_options_set_int (scan->options, "position", *res->positionOfTerm);
1129 if (res->scanStatus)
1130 ZOOM_options_set_int (scan->options, "scanStatus", *res->scanStatus);
1131 if (res->numberOfEntriesReturned)
1132 ZOOM_options_set_int (scan->options, "number",
1133 *res->numberOfEntriesReturned);
1134 nmem_destroy (nmem);
1138 static int send_sort (ZOOM_connection c)
1140 ZOOM_resultset resultset;
1142 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1145 resultset = c->tasks->u.search.resultset;
1149 resultset->r_sort_spec = 0;
1152 if (resultset->r_sort_spec)
1154 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1155 Z_SortRequest *req = apdu->u.sortRequest;
1157 req->num_inputResultSetNames = 1;
1158 req->inputResultSetNames = (Z_InternationalString **)
1159 odr_malloc (c->odr_out, sizeof(*req->inputResultSetNames));
1160 req->inputResultSetNames[0] =
1161 odr_strdup (c->odr_out, resultset->setname);
1162 req->sortedResultSetName = odr_strdup (c->odr_out, resultset->setname);
1163 req->sortSequence = resultset->r_sort_spec;
1164 resultset->r_sort_spec = 0;
1165 send_APDU (c, apdu);
1171 static int send_present (ZOOM_connection c)
1173 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1174 Z_PresentRequest *req = apdu->u.presentRequest;
1176 const char *syntax =
1177 ZOOM_options_get (c->options, "preferredRecordSyntax");
1178 const char *element =
1179 ZOOM_options_get (c->options, "elementSetName");
1180 const char *schema =
1181 ZOOM_options_get (c->options, "schema");
1182 ZOOM_resultset resultset;
1187 switch (c->tasks->which)
1189 case ZOOM_TASK_SEARCH:
1190 resultset = c->tasks->u.search.resultset;
1192 case ZOOM_TASK_RETRIEVE:
1193 resultset = c->tasks->u.retrieve.resultset;
1194 resultset->start = c->tasks->u.retrieve.start;
1195 resultset->count = c->tasks->u.retrieve.count;
1197 if (resultset->start >= resultset->size)
1199 if (resultset->start + resultset->count > resultset->size)
1200 resultset->count = resultset->size - resultset->start;
1206 if (c->error) /* don't continue on error */
1208 if (resultset->start < 0)
1210 for (i = 0; i<resultset->count; i++)
1213 record_cache_lookup (resultset, i + resultset->start, 0);
1217 if (i == resultset->count)
1220 resultset->start += i;
1221 resultset->count -= i;
1222 *req->resultSetStartPoint = resultset->start + 1;
1223 *req->numberOfRecordsRequested = resultset->count;
1224 assert (*req->numberOfRecordsRequested > 0);
1226 if (syntax && *syntax)
1227 req->preferredRecordSyntax =
1228 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, syntax);
1230 if (schema && *schema)
1232 Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1234 req->recordComposition = compo;
1235 compo->which = Z_RecordComp_complex;
1236 compo->u.complex = (Z_CompSpec *)
1237 odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1238 compo->u.complex->selectAlternativeSyntax = (bool_t *)
1239 odr_malloc(c->odr_out, sizeof(bool_t));
1240 *compo->u.complex->selectAlternativeSyntax = 0;
1242 compo->u.complex->generic = (Z_Specification *)
1243 odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1245 compo->u.complex->generic->schema = (Odr_oid *)
1246 yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, schema);
1248 if (!compo->u.complex->generic->schema)
1250 /* OID wasn't a schema! Try record syntax instead. */
1252 compo->u.complex->generic->schema = (Odr_oid *)
1253 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, schema);
1255 if (element && *element)
1257 compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1258 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1259 compo->u.complex->generic->elementSpec->which =
1260 Z_ElementSpec_elementSetName;
1261 compo->u.complex->generic->elementSpec->u.elementSetName =
1262 odr_strdup (c->odr_out, element);
1265 compo->u.complex->generic->elementSpec = 0;
1266 compo->u.complex->num_dbSpecific = 0;
1267 compo->u.complex->dbSpecific = 0;
1268 compo->u.complex->num_recordSyntax = 0;
1269 compo->u.complex->recordSyntax = 0;
1271 else if (element && *element)
1273 Z_ElementSetNames *esn = odr_malloc (c->odr_out, sizeof(*esn));
1274 Z_RecordComposition *compo = odr_malloc (c->odr_out, sizeof(*compo));
1276 esn->which = Z_ElementSetNames_generic;
1277 esn->u.generic = odr_strdup (c->odr_out, element);
1278 compo->which = Z_RecordComp_simple;
1279 compo->u.simple = esn;
1280 req->recordComposition = compo;
1282 req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1283 send_APDU (c, apdu);
1287 ZOOM_scanset ZOOM_connection_scan (ZOOM_connection c, const char *start)
1289 ZOOM_scanset scan = xmalloc (sizeof(*scan));
1291 scan->connection = c;
1292 scan->odr = odr_createmem (ODR_DECODE);
1293 scan->options = ZOOM_options_create_with_parent (c->options);
1295 scan->scan_response = 0;
1297 if ((scan->termListAndStartPoint =
1298 p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet,
1301 ZOOM_task task = ZOOM_connection_add_task (c, ZOOM_TASK_SCAN);
1302 task->u.scan.scan = scan;
1307 while (ZOOM_event (1, &c))
1314 void ZOOM_scanset_destroy (ZOOM_scanset scan)
1319 if (scan->refcount == 0)
1321 odr_destroy (scan->odr);
1323 ZOOM_options_destroy (scan->options);
1328 int send_scan (ZOOM_connection c)
1331 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
1332 Z_ScanRequest *req = apdu->u.scanRequest;
1335 assert (c->tasks->which == ZOOM_TASK_SCAN);
1336 scan = c->tasks->u.scan.scan;
1338 req->termListAndStartPoint = scan->termListAndStartPoint;
1339 req->attributeSet = scan->attributeSet;
1341 *req->numberOfTermsRequested =
1342 ZOOM_options_get_int(scan->options, "number", 10);
1344 req->preferredPositionInResponse =
1345 odr_intdup (c->odr_out,
1346 ZOOM_options_get_int(scan->options, "position", 1));
1349 odr_intdup (c->odr_out,
1350 ZOOM_options_get_int(scan->options, "stepSize", 0));
1352 req->databaseNames = set_DatabaseNames (c, scan->options,
1353 &req->num_databaseNames);
1355 send_APDU (c, apdu);
1360 size_t ZOOM_scanset_size (ZOOM_scanset scan)
1362 if (!scan || !scan->scan_response || !scan->scan_response->entries)
1364 return scan->scan_response->entries->num_entries;
1367 const char *ZOOM_scanset_term (ZOOM_scanset scan, size_t pos,
1368 int *occ, size_t *len)
1370 const char *term = 0;
1371 size_t noent = ZOOM_scanset_size (scan);
1372 Z_ScanResponse *res = scan->scan_response;
1378 if (res->entries->entries[pos]->which == Z_Entry_termInfo)
1380 Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
1382 if (t->term->which == Z_Term_general)
1384 term = t->term->u.general->buf;
1385 *len = t->term->u.general->len;
1387 *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
1392 const char *ZOOM_scanset_option_get (ZOOM_scanset scan, const char *key)
1394 return ZOOM_options_get (scan->options, key);
1397 void ZOOM_scanset_option_set (ZOOM_scanset scan, const char *key,
1400 ZOOM_options_set (scan->options, key, val);
1403 static int ZOOM_connection_exec_task (ZOOM_connection c)
1405 ZOOM_task task = c->tasks;
1407 yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task");
1410 if (c->error != ZOOM_ERROR_NONE ||
1411 (!c->cs && task->which != ZOOM_TASK_CONNECT))
1413 ZOOM_connection_remove_tasks (c);
1416 yaz_log (LOG_DEBUG, "ZOOM_connection_exec_task type=%d", task->which);
1420 switch (task->which)
1422 case ZOOM_TASK_SEARCH:
1423 /* see if search hasn't been sent yet. */
1424 if (ZOOM_connection_send_search (c))
1427 case ZOOM_TASK_RETRIEVE:
1428 if (send_present (c))
1431 case ZOOM_TASK_CONNECT:
1435 case ZOOM_TASK_SCAN:
1439 ZOOM_connection_remove_task (c);
1443 static int send_sort_present (ZOOM_connection c)
1445 int r = send_sort (c);
1447 r = send_present (c);
1451 static void handle_apdu (ZOOM_connection c, Z_APDU *apdu)
1453 Z_InitResponse *initrs;
1455 yaz_log (LOG_DEBUG, "hande_apdu type=%d", apdu->which);
1459 case Z_APDU_initResponse:
1460 initrs = apdu->u.initResponse;
1461 if (!*initrs->result)
1463 c->error = ZOOM_ERROR_INIT;
1468 yaz_oi_get_string_oidval (&apdu->u.initResponse->otherInfo,
1470 xfree (c->cookie_in);
1473 c->cookie_in = xstrdup(cookie);
1474 if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
1475 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
1476 c->support_named_resultsets = 1;
1479 assert (c->tasks->which == ZOOM_TASK_CONNECT);
1480 ZOOM_connection_remove_task (c);
1482 ZOOM_connection_exec_task (c);
1485 case Z_APDU_searchResponse:
1486 handle_search_response (c, apdu->u.searchResponse);
1487 if (!send_sort_present (c))
1488 ZOOM_connection_remove_task (c);
1490 case Z_APDU_presentResponse:
1491 handle_present_response (c, apdu->u.presentResponse);
1492 if (!send_present (c))
1493 ZOOM_connection_remove_task (c);
1495 case Z_APDU_sortResponse:
1496 sort_response (c, apdu->u.sortResponse);
1497 if (!send_present (c))
1498 ZOOM_connection_remove_task (c);
1500 case Z_APDU_scanResponse:
1501 scan_response (c, apdu->u.scanResponse);
1502 ZOOM_connection_remove_task (c);
1506 static int do_read (ZOOM_connection c)
1512 event = ZOOM_Event_create (ZOOM_EVENT_RECV_DATA);
1513 ZOOM_connection_put_event (c, event);
1515 r = cs_get (c->cs, &c->buf_in, &c->len_in);
1520 c->error= ZOOM_ERROR_CONNECTION_LOST;
1526 odr_reset (c->odr_in);
1527 odr_setbuf (c->odr_in, c->buf_in, r, 0);
1528 event = ZOOM_Event_create (ZOOM_EVENT_RECV_APDU);
1529 ZOOM_connection_put_event (c, event);
1530 if (!z_APDU (c->odr_in, &apdu, 0, 0))
1532 c->error = ZOOM_ERROR_DECODE;
1537 handle_apdu (c, apdu);
1543 static int do_write_ex (ZOOM_connection c, char *buf_out, int len_out)
1548 event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
1549 ZOOM_connection_put_event (c, event);
1551 if ((r=cs_put (c->cs, buf_out, len_out)) < 0)
1553 if (c->state == STATE_CONNECTING)
1554 c->error = ZOOM_ERROR_CONNECT;
1556 c->error = ZOOM_ERROR_CONNECTION_LOST;
1562 c->mask = ZOOM_SELECT_EXCEPT;
1563 if (c->cs->io_pending & CS_WANT_WRITE)
1564 c->mask += ZOOM_SELECT_WRITE;
1565 if (c->cs->io_pending & CS_WANT_READ)
1566 c->mask += ZOOM_SELECT_READ;
1567 yaz_log (LOG_DEBUG, "do_write_ex 1 mask=%d", c->mask);
1571 c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
1572 yaz_log (LOG_DEBUG, "do_write_ex 2 mask=%d", c->mask);
1577 static int do_write(ZOOM_connection c)
1579 return do_write_ex (c, c->buf_out, c->len_out);
1583 const char *ZOOM_connection_option_get (ZOOM_connection c, const char *key)
1585 return ZOOM_options_get (c->options, key);
1588 void ZOOM_connection_option_set (ZOOM_connection c, const char *key,
1591 ZOOM_options_set (c->options, key, val);
1594 const char *ZOOM_resultset_option_get (ZOOM_resultset r, const char *key)
1596 return ZOOM_options_get (r->options, key);
1599 void ZOOM_resultset_option_set (ZOOM_resultset r, const char *key,
1602 ZOOM_options_set (r->options, key, val);
1606 int ZOOM_connection_errcode (ZOOM_connection c)
1608 return ZOOM_connection_error (c, 0, 0);
1611 const char *ZOOM_connection_errmsg (ZOOM_connection c)
1614 ZOOM_connection_error (c, &msg, 0);
1618 const char *ZOOM_connection_addinfo (ZOOM_connection c)
1620 const char *addinfo;
1621 ZOOM_connection_error (c, 0, &addinfo);
1625 int ZOOM_connection_error (ZOOM_connection c, const char **cp,
1626 const char **addinfo)
1628 int error = c->error;
1633 case ZOOM_ERROR_NONE:
1634 *cp = "No error"; break;
1635 case ZOOM_ERROR_CONNECT:
1636 *cp = "Connect failed"; break;
1637 case ZOOM_ERROR_MEMORY:
1638 *cp = "Out of memory"; break;
1639 case ZOOM_ERROR_ENCODE:
1640 *cp = "Encoding failed"; break;
1641 case ZOOM_ERROR_DECODE:
1642 *cp = "Decoding failed"; break;
1643 case ZOOM_ERROR_CONNECTION_LOST:
1644 *cp = "Connection lost"; break;
1645 case ZOOM_ERROR_INIT:
1646 *cp = "Init rejected"; break;
1647 case ZOOM_ERROR_INTERNAL:
1648 *cp = "Internal failure"; break;
1649 case ZOOM_ERROR_TIMEOUT:
1650 *cp = "Timeout"; break;
1652 *cp = diagbib1_str (error);
1658 *addinfo = c->addinfo;
1665 int ZOOM_connection_do_io(ZOOM_connection c, int mask)
1667 ZOOM_Event event = 0;
1668 int r = cs_look(c->cs);
1669 yaz_log (LOG_DEBUG, "ZOOM_connection_do_io c=%p mask=%d cs_look=%d",
1674 event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
1675 c->error = ZOOM_ERROR_CONNECT;
1677 ZOOM_connection_put_event (c, event);
1679 else if (r == CS_CONNECT)
1682 event = ZOOM_Event_create (ZOOM_EVENT_CONNECT);
1684 ret = cs_rcvconnect (c->cs);
1685 yaz_log (LOG_DEBUG, "cs_rcvconnect returned %d", ret);
1688 c->mask = ZOOM_SELECT_EXCEPT;
1689 if (c->cs->io_pending & CS_WANT_WRITE)
1690 c->mask += ZOOM_SELECT_WRITE;
1691 if (c->cs->io_pending & CS_WANT_READ)
1692 c->mask += ZOOM_SELECT_READ;
1693 ZOOM_connection_put_event (c, event);
1697 ZOOM_connection_put_event (c, event);
1698 ZOOM_connection_send_init (c);
1699 c->state = STATE_ESTABLISHED;
1703 c->error = ZOOM_ERROR_CONNECT;
1705 ZOOM_connection_put_event (c, event);
1710 if (mask & ZOOM_SELECT_READ)
1712 if (c->cs && (mask & ZOOM_SELECT_WRITE))
1718 int ZOOM_connection_last_event(ZOOM_connection cs)
1721 return ZOOM_EVENT_NONE;
1722 return cs->last_event;
1725 int ZOOM_event (int no, ZOOM_connection *cs)
1728 struct pollfd pollfds[1024];
1729 ZOOM_connection poll_cs[1024];
1732 fd_set input, output, except;
1737 for (i = 0; i<no; i++)
1739 ZOOM_connection c = cs[i];
1741 if (c && (event = ZOOM_connection_get_event(c)))
1743 ZOOM_Event_destroy (event);
1747 for (i = 0; i<no; i++)
1749 ZOOM_connection c = cs[i];
1751 if (c && ZOOM_connection_exec_task (c))
1753 if ((event = ZOOM_connection_get_event(c)))
1755 ZOOM_Event_destroy (event);
1771 for (i = 0; i<no; i++)
1773 ZOOM_connection c = cs[i];
1778 fd = z3950_connection_socket(c);
1779 mask = z3950_connection_mask(c);
1789 short poll_events = 0;
1791 if (mask & ZOOM_SELECT_READ)
1792 poll_events += POLLIN;
1793 if (mask & ZOOM_SELECT_WRITE)
1794 poll_events += POLLOUT;
1795 if (mask & ZOOM_SELECT_EXCEPT)
1796 poll_events += POLLERR;
1797 pollfds[nfds].fd = fd;
1798 pollfds[nfds].events = poll_events;
1799 pollfds[nfds].revents = 0;
1804 if (mask & ZOOM_SELECT_READ)
1806 FD_SET (fd, &input);
1809 if (mask & ZOOM_SELECT_WRITE)
1811 FD_SET (fd, &output);
1814 if (mask & ZOOM_SELECT_EXCEPT)
1816 FD_SET (fd, &except);
1824 r = poll (pollfds, nfds, 15000);
1825 for (i = 0; i<nfds; i++)
1827 ZOOM_connection c = poll_cs[i];
1831 if (pollfds[i].revents & POLLIN)
1832 mask += ZOOM_SELECT_READ;
1833 if (pollfds[i].revents & POLLOUT)
1834 mask += ZOOM_SELECT_WRITE;
1835 if (pollfds[i].revents & POLLERR)
1836 mask += ZOOM_SELECT_EXCEPT;
1838 ZOOM_connection_do_io(c, mask);
1840 else if (r == 0 && c->mask)
1842 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1843 /* timeout and this connection was waiting */
1844 c->error = ZOOM_ERROR_TIMEOUT;
1846 ZOOM_connection_put_event(c, event);
1850 yaz_log (LOG_DEBUG, "select start");
1851 r = select (max_fd+1, &input, &output, &except, &tv);
1852 yaz_log (LOG_DEBUG, "select stop, returned r=%d", r);
1853 for (i = 0; i<no; i++)
1855 ZOOM_connection c = cs[i];
1860 fd = z3950_connection_socket(c);
1864 /* no timeout and real socket */
1865 if (FD_ISSET(fd, &input))
1866 mask += ZOOM_SELECT_READ;
1867 if (FD_ISSET(fd, &output))
1868 mask += ZOOM_SELECT_WRITE;
1869 if (FD_ISSET(fd, &except))
1870 mask += ZOOM_SELECT_EXCEPT;
1872 ZOOM_connection_do_io(c, mask);
1874 if (r == 0 && c->mask)
1876 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
1877 /* timeout and this connection was waiting */
1878 c->error = ZOOM_ERROR_TIMEOUT;
1880 yaz_log (LOG_DEBUG, "timeout");
1881 ZOOM_connection_put_event(c, event);
1885 for (i = 0; i<no; i++)
1887 ZOOM_connection c = cs[i];
1889 if (c && (event = ZOOM_connection_get_event(c)))
1891 ZOOM_Event_destroy (event);