2 * Copyright (C) 1995-2006, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: zoom-c.c,v 1.93 2006-10-26 15:34:46 adam Exp $
9 * \brief Implements ZOOM C interface.
17 #include <yaz/yaz-util.h>
18 #include <yaz/xmalloc.h>
19 #include <yaz/otherinfo.h>
21 #include <yaz/pquery.h>
22 #include <yaz/marcdisp.h>
23 #include <yaz/diagbib1.h>
24 #include <yaz/charneg.h>
31 #include <sys/types.h>
40 #include <sys/select.h>
44 #define FD_SETSIZE 512
49 static int log_api = 0;
50 static int log_details = 0;
57 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c);
58 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out);
59 static char *cql2pqf(ZOOM_connection c, const char *cql);
61 static void initlog(void)
63 static int log_level_initialized = 0;
64 if (!log_level_initialized)
66 log_api = yaz_log_module_level("zoom");
67 log_details = yaz_log_module_level("zoomdetails");
68 log_level_initialized = 1;
72 static ZOOM_Event ZOOM_Event_create(int kind)
74 ZOOM_Event event = (ZOOM_Event) xmalloc(sizeof(*event));
78 yaz_log(log_details, "ZOOM_Event_create(kind=%d)", kind);
82 static void ZOOM_Event_destroy(ZOOM_Event event)
87 static void ZOOM_connection_put_event(ZOOM_connection c, ZOOM_Event event)
91 c->m_queue_back->prev = event;
92 assert(c->m_queue_front);
96 assert(!c->m_queue_front);
97 c->m_queue_front = event;
99 event->next = c->m_queue_back;
101 c->m_queue_back = event;
104 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
106 ZOOM_Event event = c->m_queue_front;
109 c->last_event = ZOOM_EVENT_NONE;
112 assert(c->m_queue_back);
113 c->m_queue_front = event->prev;
114 if (c->m_queue_front)
116 assert(c->m_queue_back);
117 c->m_queue_front->next = 0;
121 c->last_event = event->kind;
126 static void set_dset_error(ZOOM_connection c, int error,
128 const char *addinfo, const char *addinfo2)
135 if (!c->diagset || strcmp(dset, c->diagset))
138 c->diagset = xstrdup(dset);
139 /* remove integer part from SRW diagset .. */
140 if ((cp = strrchr(c->diagset, '/')))
143 if (addinfo && addinfo2)
145 c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
146 strcpy(c->addinfo, addinfo);
147 strcat(c->addinfo, addinfo2);
150 c->addinfo = xstrdup(addinfo);
152 yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
153 c, c->host_port ? c->host_port : "<>", dset, error,
154 addinfo ? addinfo : "",
155 addinfo2 ? addinfo2 : "");
159 static void set_HTTP_error(ZOOM_connection c, int error,
160 const char *addinfo, const char *addinfo2)
162 set_dset_error(c, error, "HTTP", addinfo, addinfo2);
166 static void set_ZOOM_error(ZOOM_connection c, int error,
169 set_dset_error(c, error, "ZOOM", addinfo, 0);
172 static void clear_error(ZOOM_connection c)
175 * If an error is tied to an operation then it's ok to clear: for
176 * example, a diagnostic returned from a search is cleared by a
177 * subsequent search. However, problems such as Connection Lost
178 * or Init Refused are not cleared, because they are not
179 * recoverable: doing another search doesn't help.
183 case ZOOM_ERROR_CONNECT:
184 case ZOOM_ERROR_MEMORY:
185 case ZOOM_ERROR_DECODE:
186 case ZOOM_ERROR_CONNECTION_LOST:
187 case ZOOM_ERROR_INIT:
188 case ZOOM_ERROR_INTERNAL:
189 case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
192 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
196 ZOOM_task ZOOM_connection_add_task(ZOOM_connection c, int which)
198 ZOOM_task *taskp = &c->tasks;
200 taskp = &(*taskp)->next;
201 *taskp = (ZOOM_task) xmalloc(sizeof(**taskp));
202 (*taskp)->running = 0;
203 (*taskp)->which = which;
209 ZOOM_API(int) ZOOM_connection_is_idle(ZOOM_connection c)
211 return c->tasks ? 0 : 1;
214 ZOOM_task ZOOM_connection_insert_task(ZOOM_connection c, int which)
216 ZOOM_task task = (ZOOM_task) xmalloc(sizeof(*task));
218 task->next = c->tasks;
227 void ZOOM_connection_remove_task(ZOOM_connection c)
229 ZOOM_task task = c->tasks;
233 c->tasks = task->next;
236 case ZOOM_TASK_SEARCH:
237 ZOOM_resultset_destroy(task->u.search.resultset);
238 xfree(task->u.search.syntax);
239 xfree(task->u.search.elementSetName);
241 case ZOOM_TASK_RETRIEVE:
242 ZOOM_resultset_destroy(task->u.retrieve.resultset);
243 xfree(task->u.retrieve.syntax);
244 xfree(task->u.retrieve.elementSetName);
246 case ZOOM_TASK_CONNECT:
249 ZOOM_scanset_destroy(task->u.scan.scan);
251 case ZOOM_TASK_PACKAGE:
252 ZOOM_package_destroy(task->u.package);
255 ZOOM_resultset_destroy(task->u.sort.resultset);
256 ZOOM_query_destroy(task->u.sort.q);
265 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
266 ZOOM_connection_put_event(c, event);
271 static int ZOOM_connection_exec_task(ZOOM_connection c);
273 void ZOOM_connection_remove_tasks(ZOOM_connection c)
276 ZOOM_connection_remove_task(c);
279 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
281 const char *elementSetName);
283 ZOOM_API(ZOOM_connection)
284 ZOOM_connection_create(ZOOM_options options)
286 ZOOM_connection c = (ZOOM_connection) xmalloc(sizeof(*c));
290 yaz_log(log_api, "%p ZOOM_connection_create", c);
292 c->proto = PROTO_Z3950;
296 c->state = STATE_IDLE;
299 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
306 c->options = ZOOM_options_create_with_parent(options);
312 c->charset = c->lang = 0;
319 c->odr_in = odr_createmem(ODR_DECODE);
320 c->odr_out = odr_createmem(ODR_ENCODE);
323 c->support_named_resultsets = 0;
324 c->last_event = ZOOM_EVENT_NONE;
326 c->m_queue_front = 0;
332 /* set database names. Take local databases (if set); otherwise
333 take databases given in ZURL (if set); otherwise use Default */
334 static char **set_DatabaseNames(ZOOM_connection con, ZOOM_options options,
337 char **databaseNames;
338 const char *cp = ZOOM_options_get(options, "databaseName");
340 if ((!cp || !*cp) && con->host_port)
342 if (strncmp(con->host_port, "unix:", 5) == 0)
343 cp = strchr(con->host_port+5, ':');
345 cp = strchr(con->host_port, '/');
351 nmem_strsplit(con->odr_out->mem, "+", cp, &databaseNames, num);
352 return databaseNames;
355 ZOOM_API(ZOOM_connection)
356 ZOOM_connection_new(const char *host, int portnum)
358 ZOOM_connection c = ZOOM_connection_create(0);
360 ZOOM_connection_connect(c, host, portnum);
364 static zoom_sru_mode get_sru_mode_from_string(const char *s)
367 return zoom_sru_soap;
368 if (!yaz_matchstr(s, "soap"))
369 return zoom_sru_soap;
370 else if (!yaz_matchstr(s, "get"))
372 else if (!yaz_matchstr(s, "post"))
373 return zoom_sru_post;
374 return zoom_sru_error;
378 ZOOM_connection_connect(ZOOM_connection c,
379 const char *host, int portnum)
386 yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
389 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
390 ZOOM_connection_remove_tasks(c);
394 yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
398 yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
400 val = ZOOM_options_get(c->options, "proxy");
403 yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
404 c->proxy = xstrdup(val);
410 val = ZOOM_options_get(c->options, "charset");
413 yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
414 c->charset = xstrdup(val);
420 val = ZOOM_options_get(c->options, "lang");
423 yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
424 c->lang = xstrdup(val);
429 val = ZOOM_options_get(c->options, "sru");
430 c->sru_mode = get_sru_mode_from_string(val);
436 sprintf(hostn, "%.80s:%d", host, portnum);
437 c->host_port = xstrdup(hostn);
440 c->host_port = xstrdup(host);
444 * If the "<scheme>:" part of the host string is preceded by one
445 * or more comma-separated <name>=<value> pairs, these are taken
446 * to be options to be set on the connection object. Among other
447 * applications, this facility can be used to embed authentication
449 * user=admin,password=secret,tcp:localhost:9999
451 char *remainder = c->host_port;
452 char *pcolon = strchr(remainder, ':');
455 while ((pcomma = strchr(remainder, ',')) != 0 &&
456 (pcolon == 0 || pcomma < pcolon)) {
458 if ((pequals = strchr(remainder, '=')) != 0) {
460 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
461 ZOOM_connection_option_set(c, remainder, pequals+1);
463 remainder = pcomma+1;
466 if (remainder != c->host_port) {
468 c->host_port = xstrdup(remainder);
469 /*printf("# reset hp='%s'\n", remainder);*/
473 ZOOM_options_set(c->options, "host", c->host_port);
475 val = ZOOM_options_get(c->options, "cookie");
478 yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
479 c->cookie_out = xstrdup(val);
482 val = ZOOM_options_get(c->options, "clientIP");
485 yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
487 c->client_IP = xstrdup(val);
490 c->async = ZOOM_options_get_bool(c->options, "async", 0);
491 yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
493 task = ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
497 while (ZOOM_event(1, &c))
503 ZOOM_query_create(void)
505 ZOOM_query s = (ZOOM_query) xmalloc(sizeof(*s));
507 yaz_log(log_details, "%p ZOOM_query_create", s);
511 s->odr = odr_createmem(ODR_ENCODE);
518 ZOOM_query_destroy(ZOOM_query s)
524 yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
525 if (s->refcount == 0)
533 ZOOM_query_prefix(ZOOM_query s, const char *str)
535 s->query_string = odr_strdup(s->odr, str);
536 s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
537 s->z_query->which = Z_Query_type_1;
538 s->z_query->u.type_1 = p_query_rpn(s->odr, PROTO_Z3950, str);
539 if (!s->z_query->u.type_1)
541 yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
545 yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
550 ZOOM_query_cql(ZOOM_query s, const char *str)
554 s->query_string = odr_strdup(s->odr, str);
556 ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
557 ext->direct_reference = odr_getoidbystr(s->odr, "1.2.840.10003.16.2");
558 ext->indirect_reference = 0;
560 ext->which = Z_External_CQL;
561 ext->u.cql = s->query_string;
563 s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
564 s->z_query->which = Z_Query_type_104;
565 s->z_query->u.type_104 = ext;
567 yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
573 * Translate the CQL string client-side into RPN which is passed to
574 * the server. This is useful for server's that don't themselves
575 * support CQL, for which ZOOM_query_cql() is useless. `conn' is used
576 * only as a place to stash diagnostics if compilation fails; if this
577 * information is not needed, a null pointer may be used.
580 ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
584 ZOOM_connection freeme = 0;
586 yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
588 conn = freeme = ZOOM_connection_create(0);
590 rpn = cql2pqf(conn, str);
592 ZOOM_connection_destroy(freeme);
596 ret = ZOOM_query_prefix(s, rpn);
602 * Analogous in every way to ZOOM_query_cql2rpn(), except that there
603 * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
604 * to the server, as the YAZ GFS doesn't know how to handle this.
607 ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, const char *config,
608 int *ccl_error, const char **error_string,
612 struct ccl_rpn_node *rpn;
613 CCL_bibset bibset = ccl_qual_mk();
616 ccl_qual_buf(bibset, config);
618 rpn = ccl_find_str(bibset, str, ccl_error, error_pos);
621 *error_string = ccl_err_msg(*ccl_error);
626 WRBUF wr = wrbuf_alloc();
629 ret = ZOOM_query_prefix(s, wrbuf_buf(wr));
632 ccl_qual_rm(&bibset);
637 ZOOM_query_sortby(ZOOM_query s, const char *criteria)
639 s->sort_spec = yaz_sort_spec(s->odr, criteria);
642 yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
646 yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
650 static zoom_ret do_write(ZOOM_connection c);
653 ZOOM_connection_destroy(ZOOM_connection c)
658 yaz_log(log_api, "%p ZOOM_connection_destroy", c);
661 for (r = c->resultsets; r; r = r->next)
667 odr_destroy(c->odr_in);
668 odr_destroy(c->odr_out);
669 ZOOM_options_destroy(c->options);
670 ZOOM_connection_remove_tasks(c);
676 xfree(c->cookie_out);
682 void ZOOM_resultset_addref(ZOOM_resultset r)
687 yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
692 ZOOM_resultset ZOOM_resultset_create(void)
695 ZOOM_resultset r = (ZOOM_resultset) xmalloc(sizeof(*r));
699 yaz_log(log_details, "%p ZOOM_resultset_create", r);
702 r->odr = odr_createmem(ODR_ENCODE);
707 for (i = 0; i<RECORD_HASH_SIZE; i++)
708 r->record_hash[i] = 0;
716 ZOOM_API(ZOOM_resultset)
717 ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
720 ZOOM_query s = ZOOM_query_create();
722 ZOOM_query_prefix(s, q);
724 r = ZOOM_connection_search(c, s);
725 ZOOM_query_destroy(s);
729 ZOOM_API(ZOOM_resultset)
730 ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
732 ZOOM_resultset r = ZOOM_resultset_create();
736 const char *syntax, *elementSetName;
738 yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
739 r->r_sort_spec = q->sort_spec;
742 r->options = ZOOM_options_create_with_parent(c->options);
744 start = ZOOM_options_get_int(r->options, "start", 0);
745 count = ZOOM_options_get_int(r->options, "count", 0);
747 /* If "presentChunk" is defined use that; otherwise "step" */
748 const char *cp = ZOOM_options_get(r->options, "presentChunk");
749 r->step = ZOOM_options_get_int(r->options,
750 (cp != 0 ? "presentChunk": "step"), 0);
752 r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
753 cp = ZOOM_options_get(r->options, "setname");
755 r->setname = xstrdup(cp);
756 cp = ZOOM_options_get(r->options, "schema");
758 r->schema = xstrdup(cp);
762 r->next = c->resultsets;
765 if (c->host_port && c->proto == PROTO_HTTP)
769 yaz_log(log_details, "ZOOM_connection_search: no comstack");
770 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
774 yaz_log(log_details, "ZOOM_connection_search: reconnect");
779 task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
780 task->u.search.resultset = r;
781 task->u.search.start = start;
782 task->u.search.count = count;
784 syntax = ZOOM_options_get(r->options, "preferredRecordSyntax");
785 task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
786 elementSetName = ZOOM_options_get(r->options, "elementSetName");
787 task->u.search.elementSetName = elementSetName
788 ? xstrdup(elementSetName) : 0;
790 ZOOM_resultset_addref(r);
796 while (ZOOM_event(1, &c))
803 * This is the old result-set sorting API, which is maintained only
804 * for the sake of binary compatibility. There is no reason ever to
805 * use this rather than ZOOM_resultset_sort1().
808 ZOOM_resultset_sort(ZOOM_resultset r,
809 const char *sort_type, const char *sort_spec)
811 (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
815 ZOOM_resultset_sort1(ZOOM_resultset r,
816 const char *sort_type, const char *sort_spec)
818 ZOOM_connection c = r->connection;
822 newq = ZOOM_query_create();
823 if (ZOOM_query_sortby(newq, sort_spec) < 0)
826 yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
827 r, r, sort_type, sort_spec);
831 if (c->host_port && c->proto == PROTO_HTTP)
835 yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
836 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
840 yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
846 ZOOM_resultset_cache_reset(r);
847 task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
848 task->u.sort.resultset = r;
849 task->u.sort.q = newq;
851 ZOOM_resultset_addref(r);
855 while (ZOOM_event(1, &c))
863 ZOOM_resultset_cache_reset(ZOOM_resultset r)
866 for (i = 0; i<RECORD_HASH_SIZE; i++)
868 ZOOM_record_cache rc;
869 for (rc = r->record_hash[i]; rc; rc = rc->next)
871 if (rc->rec.wrbuf_marc)
872 wrbuf_free(rc->rec.wrbuf_marc, 1);
873 if (rc->rec.wrbuf_iconv)
874 wrbuf_free(rc->rec.wrbuf_iconv, 1);
875 if (rc->rec.wrbuf_opac)
876 wrbuf_free(rc->rec.wrbuf_opac, 1);
878 r->record_hash[i] = 0;
883 ZOOM_resultset_destroy(ZOOM_resultset r)
888 yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
890 if (r->refcount == 0)
892 ZOOM_resultset_cache_reset(r);
896 /* remove ourselves from the resultsets in connection */
897 ZOOM_resultset *rp = &r->connection->resultsets;
900 assert(*rp); /* we must be in this list!! */
902 { /* OK, we're here - take us out of it */
909 ZOOM_query_destroy(r->query);
910 ZOOM_options_destroy(r->options);
919 ZOOM_resultset_size(ZOOM_resultset r)
924 static void do_close(ZOOM_connection c)
930 c->state = STATE_IDLE;
933 static int ZOOM_test_reconnect(ZOOM_connection c)
935 if (!c->reconnect_ok)
939 c->tasks->running = 0;
940 ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
944 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
945 int force_sync, int start, int count)
950 const char *syntax, *elementSetName;
954 yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
955 " count=%d", r, force_sync, start, count);
960 if (c->host_port && c->proto == PROTO_HTTP)
964 yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
965 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
969 yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
974 task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
975 task->u.retrieve.resultset = r;
976 task->u.retrieve.start = start;
977 task->u.retrieve.count = count;
979 syntax = ZOOM_options_get(r->options, "preferredRecordSyntax");
980 task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
981 elementSetName = ZOOM_options_get(r->options, "elementSetName");
982 task->u.retrieve.elementSetName = elementSetName
983 ? xstrdup(elementSetName) : 0;
985 cp = ZOOM_options_get(r->options, "schema");
988 if (!r->schema || strcmp(r->schema, cp))
991 r->schema = xstrdup(cp);
995 ZOOM_resultset_addref(r);
997 if (!r->connection->async || force_sync)
998 while (r->connection && ZOOM_event(1, &r->connection))
1003 ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1004 size_t start, size_t count)
1006 int force_present = 0;
1010 yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1011 r, r, (long) start, (long) count);
1014 ZOOM_resultset_retrieve(r, force_present, start, count);
1018 for (i = 0; i< count; i++)
1019 recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1023 static void get_cert(ZOOM_connection c)
1028 if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1030 ZOOM_connection_option_setl(c, "sslPeerCert",
1031 cert_buf, cert_len);
1036 static zoom_ret do_connect(ZOOM_connection c)
1039 const char *effective_host;
1042 effective_host = c->proxy;
1044 effective_host = c->host_port;
1046 yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1050 c->cs = cs_create_host(effective_host, 0, &add);
1052 if (c->cs && c->cs->protocol == PROTO_HTTP)
1055 const char *path = 0;
1057 c->proto = PROTO_HTTP;
1058 cs_get_host_args(c->host_port, &path);
1060 c->path = (char*) xmalloc(strlen(path)+2);
1062 strcpy(c->path+1, path);
1064 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1066 return zoom_complete;
1071 int ret = cs_connect(c->cs, add);
1074 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1075 ZOOM_connection_put_event(c, event);
1077 if (c->proto == PROTO_Z3950)
1078 ZOOM_connection_send_init(c);
1081 /* no init request for SRW .. */
1082 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1083 ZOOM_connection_remove_task(c);
1085 ZOOM_connection_exec_task(c);
1087 c->state = STATE_ESTABLISHED;
1088 return zoom_pending;
1092 c->state = STATE_CONNECTING;
1093 c->mask = ZOOM_SELECT_EXCEPT;
1094 if (c->cs->io_pending & CS_WANT_WRITE)
1095 c->mask += ZOOM_SELECT_WRITE;
1096 if (c->cs->io_pending & CS_WANT_READ)
1097 c->mask += ZOOM_SELECT_READ;
1098 return zoom_pending;
1101 c->state = STATE_IDLE;
1102 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
1103 return zoom_complete;
1106 int z3950_connection_socket(ZOOM_connection c)
1109 return cs_fileno(c->cs);
1113 int z3950_connection_mask(ZOOM_connection c)
1120 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1123 for (i = 0; i<200; i++)
1126 Z_OtherInformation **oi;
1132 sprintf(buf, "otherInfo%d", i);
1133 val = ZOOM_options_get(c->options, buf);
1136 cp = strchr(val, ':');
1140 if (len >= sizeof(buf))
1141 len = sizeof(buf)-1;
1142 memcpy(buf, val, len);
1144 oidval = oid_getvalbyname(buf);
1145 if (oidval == VAL_NONE)
1148 yaz_oi_APDU(a, &oi);
1149 yaz_oi_set_string_oidval(oi, out, oidval, 1, cp+1);
1153 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1158 Z_OtherInformation **oi;
1159 yaz_oi_APDU(a, &oi);
1160 yaz_oi_set_string_oidval(oi, out, VAL_COOKIE, 1, c->cookie_out);
1164 Z_OtherInformation **oi;
1165 yaz_oi_APDU(a, &oi);
1166 yaz_oi_set_string_oidval(oi, out, VAL_CLIENT_IP, 1, c->client_IP);
1168 otherInfo_attach(c, a, out);
1169 if (!z_APDU(out, &a, 0, 0))
1171 FILE *outf = fopen("/tmp/apdu.txt", "a");
1174 ODR odr_pr = odr_createmem(ODR_PRINT);
1175 fprintf(outf, "a=%p\n", a);
1176 odr_setprint(odr_pr, outf);
1177 z_APDU(odr_pr, &a, 0, 0);
1178 odr_destroy(odr_pr);
1180 yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1181 set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1185 yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1189 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1193 if (encode_APDU(c, a, c->odr_out))
1194 return zoom_complete;
1195 yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1196 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1197 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1198 ZOOM_connection_put_event(c, event);
1199 odr_reset(c->odr_out);
1203 /* returns 1 if PDU was sent OK (still pending )
1204 0 if PDU was not sent OK (nothing to wait for)
1207 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1209 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1210 Z_InitRequest *ireq = apdu->u.initRequest;
1211 Z_IdAuthentication *auth = (Z_IdAuthentication *)
1212 odr_malloc(c->odr_out, sizeof(*auth));
1213 const char *auth_groupId = ZOOM_options_get(c->options, "group");
1214 const char *auth_userId = ZOOM_options_get(c->options, "user");
1215 const char *auth_password = ZOOM_options_get(c->options, "password");
1218 /* support the pass for backwards compatibility */
1220 auth_password = ZOOM_options_get(c->options, "pass");
1222 ODR_MASK_SET(ireq->options, Z_Options_search);
1223 ODR_MASK_SET(ireq->options, Z_Options_present);
1224 ODR_MASK_SET(ireq->options, Z_Options_scan);
1225 ODR_MASK_SET(ireq->options, Z_Options_sort);
1226 ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1227 ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1229 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1230 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1231 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1233 /* Index Data's Z39.50 Implementor Id is 81 */
1234 ireq->implementationId =
1235 odr_prepend(c->odr_out,
1236 ZOOM_options_get(c->options, "implementationId"),
1237 odr_prepend(c->odr_out, "81", ireq->implementationId));
1239 ireq->implementationName =
1240 odr_prepend(c->odr_out,
1241 ZOOM_options_get(c->options, "implementationName"),
1242 odr_prepend(c->odr_out, "ZOOM-C",
1243 ireq->implementationName));
1245 version = odr_strdup(c->odr_out, "$Revision: 1.93 $");
1246 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1247 version[strlen(version)-2] = '\0';
1248 ireq->implementationVersion =
1249 odr_prepend(c->odr_out,
1250 ZOOM_options_get(c->options, "implementationVersion"),
1251 odr_prepend(c->odr_out, &version[11],
1252 ireq->implementationVersion));
1254 *ireq->maximumRecordSize =
1255 ZOOM_options_get_int(c->options, "maximumRecordSize", 1024*1024);
1256 *ireq->preferredMessageSize =
1257 ZOOM_options_get_int(c->options, "preferredMessageSize", 1024*1024);
1259 if (auth_groupId || auth_password)
1261 Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1264 if (auth_groupId && *auth_groupId)
1266 pass->groupId = (char *)
1267 odr_malloc(c->odr_out, strlen(auth_groupId)+1);
1268 strcpy(pass->groupId, auth_groupId);
1272 if (auth_userId && *auth_userId)
1274 pass->userId = (char *)
1275 odr_malloc(c->odr_out, strlen(auth_userId)+1);
1276 strcpy(pass->userId, auth_userId);
1280 if (auth_password && *auth_password)
1282 pass->password = (char *)
1283 odr_malloc(c->odr_out, strlen(auth_password)+1);
1284 strcpy(pass->password, auth_password);
1289 auth->which = Z_IdAuthentication_idPass;
1290 auth->u.idPass = pass;
1291 ireq->idAuthentication = auth;
1294 else if (auth_userId)
1296 auth->which = Z_IdAuthentication_open;
1297 auth->u.open = (char *)
1298 odr_malloc(c->odr_out, strlen(auth_userId)+1);
1299 strcpy(auth->u.open, auth_userId);
1300 ireq->idAuthentication = auth;
1303 yaz_oi_set_string_oidval(&ireq->otherInfo, c->odr_out,
1304 VAL_PROXY, 1, c->host_port);
1305 if (c->charset || c->lang)
1307 Z_OtherInformation **oi;
1308 Z_OtherInformationUnit *oi_unit;
1310 yaz_oi_APDU(apdu, &oi);
1312 if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1314 ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1315 oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1316 oi_unit->information.externallyDefinedInfo =
1317 yaz_set_proposal_charneg_list(c->odr_out, " ",
1318 c->charset, c->lang, 1);
1322 return send_APDU(c, apdu);
1326 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1331 gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port, c->path);
1333 if (c->sru_mode == zoom_sru_get)
1335 yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1337 else if (c->sru_mode == zoom_sru_post)
1339 yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1341 else if (c->sru_mode == zoom_sru_soap)
1343 yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1345 if (!z_GDU(c->odr_out, &gdu, 0, 0))
1346 return zoom_complete;
1347 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1349 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1350 ZOOM_connection_put_event(c, event);
1351 odr_reset(c->odr_out);
1357 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1361 ZOOM_resultset resultset = 0;
1363 const char *option_val = 0;
1365 if (c->error) /* don't continue on error */
1366 return zoom_complete;
1368 switch(c->tasks->which)
1370 case ZOOM_TASK_SEARCH:
1371 resultset = c->tasks->u.search.resultset;
1372 resultset->setname = xstrdup("default");
1373 ZOOM_options_set(resultset->options, "setname", resultset->setname);
1374 start = &c->tasks->u.search.start;
1375 count = &c->tasks->u.search.count;
1377 case ZOOM_TASK_RETRIEVE:
1378 resultset = c->tasks->u.retrieve.resultset;
1380 start = &c->tasks->u.retrieve.start;
1381 count = &c->tasks->u.retrieve.count;
1383 if (*start >= resultset->size)
1384 return zoom_complete;
1385 if (*start + *count > resultset->size)
1386 *count = resultset->size - *start;
1388 for (i = 0; i < *count; i++)
1391 record_cache_lookup(resultset, i + *start,
1392 c->tasks->u.retrieve.syntax,
1393 c->tasks->u.retrieve.elementSetName);
1398 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1399 ZOOM_connection_put_event(c, event);
1406 return zoom_complete;
1409 return zoom_complete;
1411 assert(resultset->query);
1413 sr = yaz_srw_get(c->odr_out, Z_SRW_searchRetrieve_request);
1415 if (resultset->query->z_query->which == Z_Query_type_104
1416 && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1418 sr->u.request->query_type = Z_SRW_query_type_cql;
1419 sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1421 else if (resultset->query->z_query->which == Z_Query_type_1 &&
1422 resultset->query->z_query->u.type_1)
1424 sr->u.request->query_type = Z_SRW_query_type_pqf;
1425 sr->u.request->query.pqf = resultset->query->query_string;
1429 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1430 return zoom_complete;
1432 sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1433 sr->u.request->maximumRecords = odr_intdup(
1434 c->odr_out, resultset->step>0 ? resultset->step : *count);
1435 sr->u.request->recordSchema = resultset->schema;
1437 option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1439 sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1441 option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1443 sr->extra_args = odr_strdup(c->odr_out, option_val);
1444 return send_srw(c, sr);
1447 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1449 return zoom_complete;
1453 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1456 int lslb, ssub, mspn;
1458 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1459 Z_SearchRequest *search_req = apdu->u.searchRequest;
1460 const char *elementSetName;
1461 const char *smallSetElementSetName;
1462 const char *mediumSetElementSetName;
1465 assert(c->tasks->which == ZOOM_TASK_SEARCH);
1467 r = c->tasks->u.search.resultset;
1469 yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1472 ZOOM_options_get(r->options, "elementSetName");
1473 smallSetElementSetName =
1474 ZOOM_options_get(r->options, "smallSetElementSetName");
1475 mediumSetElementSetName =
1476 ZOOM_options_get(r->options, "mediumSetElementSetName");
1478 if (!smallSetElementSetName)
1479 smallSetElementSetName = elementSetName;
1481 if (!mediumSetElementSetName)
1482 mediumSetElementSetName = elementSetName;
1487 /* prepare query for the search request */
1488 search_req->query = r->query->z_query;
1489 if (!search_req->query)
1491 set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1492 return zoom_complete;
1495 search_req->databaseNames =
1496 set_DatabaseNames(c, r->options, &search_req->num_databaseNames);
1498 /* get syntax (no need to provide unless piggyback is in effect) */
1499 syntax = c->tasks->u.search.syntax;
1501 lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1502 ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1503 mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1504 if (lslb != -1 && ssub != -1 && mspn != -1)
1506 /* So're a Z39.50 expert? Let's hope you don't do sort */
1507 *search_req->largeSetLowerBound = lslb;
1508 *search_req->smallSetUpperBound = ssub;
1509 *search_req->mediumSetPresentNumber = mspn;
1511 else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1512 && r->piggyback && !r->r_sort_spec && !r->schema)
1514 /* Regular piggyback - do it unless we're going to do sort */
1515 *search_req->largeSetLowerBound = 2000000000;
1516 *search_req->smallSetUpperBound = 1;
1517 *search_req->mediumSetPresentNumber =
1518 r->step>0 ? r->step : c->tasks->u.search.count;
1522 /* non-piggyback. Need not provide elementsets or syntaxes .. */
1523 smallSetElementSetName = 0;
1524 mediumSetElementSetName = 0;
1527 if (smallSetElementSetName && *smallSetElementSetName)
1529 Z_ElementSetNames *esn = (Z_ElementSetNames *)
1530 odr_malloc(c->odr_out, sizeof(*esn));
1532 esn->which = Z_ElementSetNames_generic;
1533 esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1534 search_req->smallSetElementSetNames = esn;
1536 if (mediumSetElementSetName && *mediumSetElementSetName)
1538 Z_ElementSetNames *esn =(Z_ElementSetNames *)
1539 odr_malloc(c->odr_out, sizeof(*esn));
1541 esn->which = Z_ElementSetNames_generic;
1542 esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1543 search_req->mediumSetElementSetNames = esn;
1546 search_req->preferredRecordSyntax =
1547 yaz_str_to_z3950oid(c->odr_out, CLASS_RECSYN, syntax);
1551 if (c->support_named_resultsets)
1555 /* find the lowest unused ordinal so that we re-use
1556 result sets on the server. */
1557 for (ord = 1; ; ord++)
1560 sprintf(setname, "%d", ord);
1561 for (rp = c->resultsets; rp; rp = rp->next)
1562 if (rp->setname && !strcmp(rp->setname, setname))
1567 r->setname = xstrdup(setname);
1568 yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1569 "set %s", c, r->setname);
1573 yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1575 r->setname = xstrdup("default");
1577 ZOOM_options_set(r->options, "setname", r->setname);
1579 search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1580 return send_APDU(c, apdu);
1583 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1590 case Z_DefaultDiagFormat_v2Addinfo:
1591 addinfo = r->u.v2Addinfo;
1593 case Z_DefaultDiagFormat_v3Addinfo:
1594 addinfo = r->u.v3Addinfo;
1599 set_dset_error(c, *r->condition,
1600 yaz_z3950oid_to_str(r->diagnosticSetId, &oclass),
1604 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1606 if (p->which != Z_DiagRec_defaultFormat)
1607 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1609 response_default_diag(c, p->u.defaultFormat);
1612 ZOOM_API(ZOOM_record)
1613 ZOOM_record_clone(ZOOM_record srec)
1620 odr_enc = odr_createmem(ODR_ENCODE);
1621 if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1623 buf = odr_getbuf(odr_enc, &size, 0);
1625 nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1626 nrec->odr = odr_createmem(ODR_DECODE);
1627 nrec->wrbuf_marc = 0;
1628 nrec->wrbuf_iconv = 0;
1629 nrec->wrbuf_opac = 0;
1630 odr_setbuf(nrec->odr, buf, size, 0);
1631 z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1633 odr_destroy(odr_enc);
1637 ZOOM_API(ZOOM_record)
1638 ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1640 const char *syntax =
1641 ZOOM_options_get(s->options, "preferredRecordSyntax");
1642 const char *elementSetName =
1643 ZOOM_options_get(s->options, "elementSetName");
1645 return record_cache_lookup(s, pos, syntax, elementSetName);
1648 ZOOM_API(ZOOM_record)
1649 ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1651 ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1656 * MIKE: I think force_sync should always be zero, but I don't
1657 * want to make this change until I get the go-ahead from
1658 * Adam, in case something depends on the old synchronous
1662 if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1663 ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1664 rec = ZOOM_resultset_record_immediate(r, pos);
1670 ZOOM_record_destroy(ZOOM_record rec)
1674 if (rec->wrbuf_marc)
1675 wrbuf_free(rec->wrbuf_marc, 1);
1676 if (rec->wrbuf_iconv)
1677 wrbuf_free(rec->wrbuf_iconv, 1);
1678 if (rec->wrbuf_opac)
1679 wrbuf_free(rec->wrbuf_opac, 1);
1680 odr_destroy(rec->odr);
1684 static const char *marc_iconv_return(ZOOM_record rec, int marc_type,
1686 const char *buf, int sz,
1687 const char *record_charset)
1692 yaz_marc_t mt = yaz_marc_create();
1695 strcpy(to, "UTF-8");
1696 if (record_charset && *record_charset)
1698 /* Use "from,to" or just "from" */
1699 const char *cp = strchr(record_charset, ',');
1700 int clen = strlen(record_charset);
1703 strncpy( to, cp+1, sizeof(to)-1);
1704 to[sizeof(to)-1] = '\0';
1705 clen = cp - record_charset;
1707 if (clen > sizeof(from)-1)
1708 clen = sizeof(from)-1;
1711 strncpy(from, record_charset, clen);
1717 cd = yaz_iconv_open(to, from);
1718 yaz_marc_iconv(mt, cd);
1721 yaz_marc_xml(mt, marc_type);
1722 if (!rec->wrbuf_marc)
1723 rec->wrbuf_marc = wrbuf_alloc();
1724 wrbuf_rewind(rec->wrbuf_marc);
1725 if (yaz_marc_decode_wrbuf(mt, buf, sz, rec->wrbuf_marc) > 0)
1727 yaz_marc_destroy(mt);
1729 yaz_iconv_close(cd);
1731 *len = wrbuf_len(rec->wrbuf_marc);
1732 return wrbuf_buf(rec->wrbuf_marc);
1734 yaz_marc_destroy(mt);
1736 yaz_iconv_close(cd);
1740 static const char *record_iconv_return(ZOOM_record rec, int *len,
1741 const char *buf, int sz,
1742 const char *record_charset)
1749 strcpy(to, "UTF-8");
1750 if (record_charset && *record_charset)
1752 /* Use "from,to" or just "from" */
1753 const char *cp = strchr(record_charset, ',');
1754 int clen = strlen(record_charset);
1757 strncpy( to, cp+1, sizeof(to)-1);
1758 to[sizeof(to)-1] = '\0';
1759 clen = cp - record_charset;
1761 if (clen > sizeof(from)-1)
1762 clen = sizeof(from)-1;
1765 strncpy(from, record_charset, clen);
1769 if (*from && *to && (cd = yaz_iconv_open(to, from)))
1772 size_t inbytesleft = sz;
1773 const char *inp = buf;
1775 if (!rec->wrbuf_iconv)
1776 rec->wrbuf_iconv = wrbuf_alloc();
1778 wrbuf_rewind(rec->wrbuf_iconv);
1782 size_t outbytesleft = sizeof(outbuf);
1783 char *outp = outbuf;
1784 size_t r = yaz_iconv(cd, (char**) &inp,
1786 &outp, &outbytesleft);
1787 if (r == (size_t) (-1))
1789 int e = yaz_iconv_error(cd);
1790 if (e != YAZ_ICONV_E2BIG)
1793 wrbuf_write(rec->wrbuf_iconv, outbuf, outp - outbuf);
1795 wrbuf_puts(rec->wrbuf_iconv, "");
1796 buf = wrbuf_buf(rec->wrbuf_iconv);
1797 sz = wrbuf_len(rec->wrbuf_iconv);
1798 yaz_iconv_close(cd);
1805 ZOOM_API(const char *)
1806 ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
1813 Z_NamePlusRecord *npr;
1816 *len = 0; /* default return */
1825 for (i = 0; cp[i] && i < sizeof(type)-1; i++)
1827 if (cp[i] == ';' || cp[i] == ' ')
1833 while (type_spec[i] == ';')
1836 while (type_spec[i] == ' ')
1838 if (!strncmp(type_spec+i, "charset=", 8))
1841 i = i + 8; /* skip charset= */
1842 for (j = 0; type_spec[i] && j < sizeof(charset)-1; i++, j++)
1844 if (type_spec[i] == ';' || type_spec[i] == ' ')
1850 else if (!strncmp(type_spec+i, "xpath=", 6))
1854 for (j = 0; type_spec[i] && j < sizeof(xpath)-1; i++, j++)
1858 while (type_spec[i] == ' ')
1861 if (!strcmp(type, "database"))
1864 *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
1865 return npr->databaseName;
1867 else if (!strcmp(type, "syntax"))
1869 const char *desc = 0;
1870 if (npr->which == Z_NamePlusRecord_databaseRecord)
1872 Z_External *r = (Z_External *) npr->u.databaseRecord;
1873 oident *ent = oid_getentbyoid(r->direct_reference);
1880 *len = strlen(desc);
1883 if (npr->which != Z_NamePlusRecord_databaseRecord)
1886 /* from now on - we have a database record .. */
1887 if (!strcmp(type, "render"))
1889 Z_External *r = (Z_External *) npr->u.databaseRecord;
1890 oident *ent = oid_getentbyoid(r->direct_reference);
1892 /* render bibliographic record .. */
1893 if (r->which == Z_External_OPAC)
1895 r = r->u.opac->bibliographicRecord;
1898 ent = oid_getentbyoid(r->direct_reference);
1900 if (r->which == Z_External_sutrs)
1901 return record_iconv_return(rec, len,
1902 (char*) r->u.sutrs->buf,
1905 else if (r->which == Z_External_octet)
1907 const char *ret_buf;
1915 case VAL_APPLICATION_XML:
1918 ret_buf = marc_iconv_return(
1919 rec, YAZ_MARC_LINE, len,
1920 (const char *) r->u.octet_aligned->buf,
1921 r->u.octet_aligned->len,
1926 return record_iconv_return(rec, len,
1927 (const char *) r->u.octet_aligned->buf,
1928 r->u.octet_aligned->len,
1931 else if (r->which == Z_External_grs1)
1933 if (!rec->wrbuf_marc)
1934 rec->wrbuf_marc = wrbuf_alloc();
1935 wrbuf_rewind(rec->wrbuf_marc);
1936 yaz_display_grs1(rec->wrbuf_marc, r->u.grs1, 0);
1937 return record_iconv_return(rec, len,
1938 wrbuf_buf(rec->wrbuf_marc),
1939 wrbuf_len(rec->wrbuf_marc),
1944 else if (!strcmp(type, "xml"))
1946 Z_External *r = (Z_External *) npr->u.databaseRecord;
1947 oident *ent = oid_getentbyoid(r->direct_reference);
1949 /* render bibliographic record .. */
1950 if (r->which == Z_External_OPAC)
1952 r = r->u.opac->bibliographicRecord;
1955 ent = oid_getentbyoid(r->direct_reference);
1958 if (r->which == Z_External_sutrs)
1959 return record_iconv_return(rec, len,
1960 (const char *) r->u.sutrs->buf,
1963 else if (r->which == Z_External_octet)
1965 const char *ret_buf;
1966 int marc_decode_type = YAZ_MARC_MARCXML;
1975 case VAL_APPLICATION_XML:
1978 ret_buf = marc_iconv_return(
1979 rec, marc_decode_type, len,
1980 (const char *) r->u.octet_aligned->buf,
1981 r->u.octet_aligned->len,
1986 return record_iconv_return(rec, len,
1987 (const char *) r->u.octet_aligned->buf,
1988 r->u.octet_aligned->len,
1991 else if (r->which == Z_External_grs1)
1998 else if (!strcmp(type, "raw"))
2000 Z_External *r = (Z_External *) npr->u.databaseRecord;
2002 if (r->which == Z_External_sutrs)
2004 if (len) *len = r->u.sutrs->len;
2005 return (const char *) r->u.sutrs->buf;
2007 else if (r->which == Z_External_octet)
2009 if (len) *len = r->u.octet_aligned->len;
2010 return (const char *) r->u.octet_aligned->buf;
2012 else /* grs-1, explain, OPAC, ... */
2015 return (const char *) npr->u.databaseRecord;
2019 else if (!strcmp (type, "ext"))
2022 return (const char *) npr->u.databaseRecord;
2024 else if (!strcmp (type, "opac"))
2027 Z_External *r = (Z_External *) npr->u.databaseRecord;
2028 if (r->which == Z_External_OPAC)
2030 if (!rec->wrbuf_opac)
2031 rec->wrbuf_opac = wrbuf_alloc();
2032 wrbuf_rewind(rec->wrbuf_opac);
2033 yaz_display_OPAC(rec->wrbuf_opac, r->u.opac, 0);
2034 return record_iconv_return(rec, len,
2035 wrbuf_buf(rec->wrbuf_opac),
2036 wrbuf_len(rec->wrbuf_opac),
2043 static int strcmp_null(const char *v1, const char *v2)
2049 return strcmp(v1, v2);
2052 static size_t record_hash(int pos)
2056 return pos % RECORD_HASH_SIZE;
2059 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr,
2061 const char *syntax, const char *elementSetName)
2063 ZOOM_record_cache rc;
2065 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2066 ZOOM_connection_put_event(r->connection, event);
2068 for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2072 if (strcmp_null(r->schema, rc->schema))
2074 if (strcmp_null(elementSetName,rc->elementSetName))
2076 if (strcmp_null(syntax, rc->syntax))
2078 /* not destroying rc->npr (it's handled by nmem )*/
2080 /* keeping wrbuf_marc too */
2084 rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2087 rc->rec.wrbuf_marc = 0;
2088 rc->rec.wrbuf_iconv = 0;
2089 rc->rec.wrbuf_opac = 0;
2091 rc->elementSetName = odr_strdup(r->odr, elementSetName);
2093 rc->elementSetName = 0;
2096 rc->syntax = odr_strdup(r->odr, syntax);
2101 rc->schema = odr_strdup(r->odr, r->schema);
2106 rc->next = r->record_hash[record_hash(pos)];
2107 r->record_hash[record_hash(pos)] = rc;
2110 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2112 const char *elementSetName)
2114 ZOOM_record_cache rc;
2116 for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2120 if (strcmp_null(r->schema, rc->schema))
2122 if (strcmp_null(elementSetName,rc->elementSetName))
2124 if (strcmp_null(syntax, rc->syntax))
2132 static void handle_records(ZOOM_connection c, Z_Records *sr,
2135 ZOOM_resultset resultset;
2137 const char *syntax = 0, *elementSetName = 0;
2141 switch (c->tasks->which)
2143 case ZOOM_TASK_SEARCH:
2144 resultset = c->tasks->u.search.resultset;
2145 start = &c->tasks->u.search.start;
2146 count = &c->tasks->u.search.count;
2147 syntax = c->tasks->u.search.syntax;
2148 elementSetName = c->tasks->u.search.elementSetName;
2150 case ZOOM_TASK_RETRIEVE:
2151 resultset = c->tasks->u.retrieve.resultset;
2152 start = &c->tasks->u.retrieve.start;
2153 count = &c->tasks->u.retrieve.count;
2154 syntax = c->tasks->u.retrieve.syntax;
2155 elementSetName = c->tasks->u.retrieve.elementSetName;
2160 if (sr && sr->which == Z_Records_NSD)
2161 response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2162 else if (sr && sr->which == Z_Records_multipleNSD)
2164 if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2165 response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2167 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2171 if (*count + *start > resultset->size)
2172 *count = resultset->size - *start;
2175 if (sr && sr->which == Z_Records_DBOSD)
2178 NMEM nmem = odr_extract_mem(c->odr_in);
2179 Z_NamePlusRecordList *p =
2180 sr->u.databaseOrSurDiagnostics;
2181 for (i = 0; i<p->num_records; i++)
2183 record_cache_add(resultset, p->records[i], i + *start,
2184 syntax, elementSetName);
2188 yaz_log(log_details,
2189 "handle_records resultset=%p start=%d count=%d",
2190 resultset, *start, *count);
2192 /* transfer our response to search_nmem .. we need it later */
2193 nmem_transfer(resultset->odr->mem, nmem);
2195 if (present_phase && p->num_records == 0)
2197 /* present response and we didn't get any records! */
2198 Z_NamePlusRecord *myrec =
2199 zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2200 record_cache_add(resultset, myrec, *start,
2201 syntax, elementSetName);
2204 else if (present_phase)
2206 /* present response and we didn't get any records! */
2207 Z_NamePlusRecord *myrec =
2208 zget_surrogateDiagRec(resultset->odr, 0, 14, 0);
2209 record_cache_add(resultset, myrec, *start, syntax, elementSetName);
2214 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2216 handle_records(c, pr->records, 1);
2219 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2222 switch (term->which)
2224 case Z_Term_general:
2225 ZOOM_options_setl(opt, name,
2226 (const char *)(term->u.general->buf),
2227 term->u.general->len);
2229 case Z_Term_characterString:
2230 ZOOM_options_set(opt, name, term->u.characterString);
2232 case Z_Term_numeric:
2233 ZOOM_options_set_int(opt, name, *term->u.numeric);
2238 static void handle_queryExpression(ZOOM_options opt, const char *name,
2239 Z_QueryExpression *exp)
2245 case Z_QueryExpression_term:
2246 if (exp->u.term && exp->u.term->queryTerm)
2248 sprintf(opt_name, "%s.term", name);
2249 handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2252 case Z_QueryExpression_query:
2257 static void handle_searchResult(ZOOM_connection c, ZOOM_resultset resultset,
2258 Z_OtherInformation *o)
2261 for (i = 0; o && i < o->num_elements; i++)
2263 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2265 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2267 if (ext->which == Z_External_searchResult1)
2270 Z_SearchInfoReport *sr = ext->u.searchResult1;
2273 ZOOM_options_set_int(
2274 resultset->options, "searchresult.size", sr->num);
2276 for (j = 0; j < sr->num; j++)
2278 Z_SearchInfoReport_s *ent =
2279 ext->u.searchResult1->elements[j];
2282 sprintf(pref, "searchresult.%d", j);
2284 if (ent->subqueryId)
2287 sprintf(opt_name, "%s.id", pref);
2288 ZOOM_options_set(resultset->options, opt_name,
2291 if (ent->subqueryExpression)
2294 sprintf(opt_name, "%s.subquery", pref);
2295 handle_queryExpression(resultset->options, opt_name,
2296 ent->subqueryExpression);
2298 if (ent->subqueryInterpretation)
2301 sprintf(opt_name, "%s.interpretation", pref);
2302 handle_queryExpression(resultset->options, opt_name,
2303 ent->subqueryInterpretation);
2305 if (ent->subqueryRecommendation)
2308 sprintf(opt_name, "%s.recommendation", pref);
2309 handle_queryExpression(resultset->options, opt_name,
2310 ent->subqueryRecommendation);
2312 if (ent->subqueryCount)
2315 sprintf(opt_name, "%s.count", pref);
2316 ZOOM_options_set_int(resultset->options, opt_name,
2317 *ent->subqueryCount);
2325 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2327 ZOOM_resultset resultset;
2330 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2333 event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2334 ZOOM_connection_put_event(c, event);
2336 resultset = c->tasks->u.search.resultset;
2338 handle_searchResult(c, resultset, sr->additionalSearchInfo);
2340 resultset->size = *sr->resultCount;
2341 handle_records(c, sr->records, 0);
2344 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2346 if (res->diagnostics && res->num_diagnostics > 0)
2347 response_diag(c, res->diagnostics[0]);
2350 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2352 NMEM nmem = odr_extract_mem(c->odr_in);
2355 if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2357 scan = c->tasks->u.scan.scan;
2359 if (res->entries && res->entries->nonsurrogateDiagnostics)
2360 response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2361 scan->scan_response = res;
2362 nmem_transfer(scan->odr->mem, nmem);
2364 ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2365 if (res->positionOfTerm)
2366 ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2367 if (res->scanStatus)
2368 ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2369 if (res->numberOfEntriesReturned)
2370 ZOOM_options_set_int(scan->options, "number",
2371 *res->numberOfEntriesReturned);
2376 static zoom_ret send_sort(ZOOM_connection c,
2377 ZOOM_resultset resultset)
2380 resultset->r_sort_spec = 0;
2381 if (resultset->r_sort_spec)
2383 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2384 Z_SortRequest *req = apdu->u.sortRequest;
2386 req->num_inputResultSetNames = 1;
2387 req->inputResultSetNames = (Z_InternationalString **)
2388 odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2389 req->inputResultSetNames[0] =
2390 odr_strdup(c->odr_out, resultset->setname);
2391 req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2392 req->sortSequence = resultset->r_sort_spec;
2393 resultset->r_sort_spec = 0;
2394 return send_APDU(c, apdu);
2396 return zoom_complete;
2399 static zoom_ret send_present(ZOOM_connection c)
2402 Z_PresentRequest *req = 0;
2404 const char *syntax = 0;
2405 const char *elementSetName = 0;
2406 ZOOM_resultset resultset;
2411 yaz_log(log_details, "%p send_present no tasks", c);
2412 return zoom_complete;
2415 switch (c->tasks->which)
2417 case ZOOM_TASK_SEARCH:
2418 resultset = c->tasks->u.search.resultset;
2419 start = &c->tasks->u.search.start;
2420 count = &c->tasks->u.search.count;
2421 syntax = c->tasks->u.search.syntax;
2422 elementSetName = c->tasks->u.search.elementSetName;
2424 case ZOOM_TASK_RETRIEVE:
2425 resultset = c->tasks->u.retrieve.resultset;
2426 start = &c->tasks->u.retrieve.start;
2427 count = &c->tasks->u.retrieve.count;
2428 syntax = c->tasks->u.retrieve.syntax;
2429 elementSetName = c->tasks->u.retrieve.elementSetName;
2431 if (*start >= resultset->size)
2433 yaz_log(log_details, "%p send_present start=%d >= size=%d",
2434 c, *start, resultset->size);
2435 return zoom_complete;
2437 if (*start + *count > resultset->size)
2438 *count = resultset->size - *start;
2441 return zoom_complete;
2443 yaz_log(log_details, "%p send_present start=%d count=%d",
2446 if (c->error) /* don't continue on error */
2447 return zoom_complete;
2449 return zoom_complete;
2450 yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2451 resultset, *start, *count);
2453 for (i = 0; i < *count; i++)
2456 record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2461 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2462 ZOOM_connection_put_event(c, event);
2470 yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2471 return zoom_complete;
2474 apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2475 req = apdu->u.presentRequest;
2478 yaz_log(log_details, "%p send_present skip=%d", c, i);
2480 *req->resultSetStartPoint = *start + 1;
2481 *req->numberOfRecordsRequested = resultset->step>0 ?
2482 resultset->step : *count;
2483 if (*req->numberOfRecordsRequested + *start > resultset->size)
2484 *req->numberOfRecordsRequested = resultset->size - *start;
2485 assert(*req->numberOfRecordsRequested > 0);
2487 if (syntax && *syntax)
2488 req->preferredRecordSyntax =
2489 yaz_str_to_z3950oid(c->odr_out, CLASS_RECSYN, syntax);
2491 if (resultset->schema && *resultset->schema)
2493 Z_RecordComposition *compo = (Z_RecordComposition *)
2494 odr_malloc(c->odr_out, sizeof(*compo));
2496 req->recordComposition = compo;
2497 compo->which = Z_RecordComp_complex;
2498 compo->u.complex = (Z_CompSpec *)
2499 odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2500 compo->u.complex->selectAlternativeSyntax = (bool_t *)
2501 odr_malloc(c->odr_out, sizeof(bool_t));
2502 *compo->u.complex->selectAlternativeSyntax = 0;
2504 compo->u.complex->generic = (Z_Specification *)
2505 odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2507 compo->u.complex->generic->which = Z_Schema_oid;
2508 compo->u.complex->generic->schema.oid = (Odr_oid *)
2509 yaz_str_to_z3950oid (c->odr_out, CLASS_SCHEMA, resultset->schema);
2511 if (!compo->u.complex->generic->schema.oid)
2513 /* OID wasn't a schema! Try record syntax instead. */
2515 compo->u.complex->generic->schema.oid = (Odr_oid *)
2516 yaz_str_to_z3950oid (c->odr_out, CLASS_RECSYN, resultset->schema);
2518 if (elementSetName && *elementSetName)
2520 compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2521 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2522 compo->u.complex->generic->elementSpec->which =
2523 Z_ElementSpec_elementSetName;
2524 compo->u.complex->generic->elementSpec->u.elementSetName =
2525 odr_strdup(c->odr_out, elementSetName);
2528 compo->u.complex->generic->elementSpec = 0;
2529 compo->u.complex->num_dbSpecific = 0;
2530 compo->u.complex->dbSpecific = 0;
2531 compo->u.complex->num_recordSyntax = 0;
2532 compo->u.complex->recordSyntax = 0;
2534 else if (elementSetName && *elementSetName)
2536 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2537 odr_malloc(c->odr_out, sizeof(*esn));
2538 Z_RecordComposition *compo = (Z_RecordComposition *)
2539 odr_malloc(c->odr_out, sizeof(*compo));
2541 esn->which = Z_ElementSetNames_generic;
2542 esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2543 compo->which = Z_RecordComp_simple;
2544 compo->u.simple = esn;
2545 req->recordComposition = compo;
2547 req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2548 return send_APDU(c, apdu);
2551 ZOOM_API(ZOOM_scanset)
2552 ZOOM_connection_scan(ZOOM_connection c, const char *start)
2555 ZOOM_query q = ZOOM_query_create();
2557 ZOOM_query_prefix(q, start);
2559 s = ZOOM_connection_scan1(c, q);
2560 ZOOM_query_destroy(q);
2565 ZOOM_API(ZOOM_scanset)
2566 ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
2570 ZOOM_scanset scan = 0;
2573 * We need to check the query-type, so we can recognise CQL and
2574 * CCL and compile them into a form that we can use here. The
2575 * ZOOM_query structure has no explicit `type' member, but
2576 * inspection of the ZOOM_query_prefix() and ZOOM_query_cql()
2577 * functions shows how the structure is set up in each case.
2581 else if (q->z_query->which == Z_Query_type_1)
2583 yaz_log(log_api, "%p ZOOM_connection_scan1 q=%p PQF '%s'",
2584 c, q, q->query_string);
2585 start = q->query_string;
2587 else if (q->z_query->which == Z_Query_type_104)
2589 yaz_log(log_api, "%p ZOOM_connection_scan1 q=%p CQL '%s'",
2590 c, q, q->query_string);
2591 start = freeme = cql2pqf(c, q->query_string);
2597 yaz_log(YLOG_FATAL, "%p ZOOM_connection_scan1 q=%p unknown type '%s'",
2598 c, q, q->query_string);
2602 scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
2603 scan->connection = c;
2604 scan->odr = odr_createmem(ODR_DECODE);
2605 scan->options = ZOOM_options_create_with_parent(c->options);
2607 scan->scan_response = 0;
2608 scan->termListAndStartPoint =
2609 p_query_scan(scan->odr, PROTO_Z3950, &scan->attributeSet, start);
2611 if (scan->termListAndStartPoint != 0)
2613 ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
2614 task->u.scan.scan = scan;
2619 while (ZOOM_event(1, &c))
2627 ZOOM_scanset_destroy(ZOOM_scanset scan)
2632 if (scan->refcount == 0)
2634 odr_destroy(scan->odr);
2636 ZOOM_options_destroy(scan->options);
2641 static zoom_ret send_package(ZOOM_connection c)
2645 yaz_log(log_details, "%p send_package", c);
2647 return zoom_complete;
2648 assert (c->tasks->which == ZOOM_TASK_PACKAGE);
2650 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
2651 ZOOM_connection_put_event(c, event);
2653 c->buf_out = c->tasks->u.package->buf_out;
2654 c->len_out = c->tasks->u.package->len_out;
2659 static zoom_ret send_scan(ZOOM_connection c)
2662 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
2663 Z_ScanRequest *req = apdu->u.scanRequest;
2665 yaz_log(log_details, "%p send_scan", c);
2667 return zoom_complete;
2668 assert (c->tasks->which == ZOOM_TASK_SCAN);
2669 scan = c->tasks->u.scan.scan;
2671 req->termListAndStartPoint = scan->termListAndStartPoint;
2672 req->attributeSet = scan->attributeSet;
2674 *req->numberOfTermsRequested =
2675 ZOOM_options_get_int(scan->options, "number", 10);
2677 req->preferredPositionInResponse =
2678 odr_intdup(c->odr_out,
2679 ZOOM_options_get_int(scan->options, "position", 1));
2682 odr_intdup(c->odr_out,
2683 ZOOM_options_get_int(scan->options, "stepSize", 0));
2685 req->databaseNames = set_DatabaseNames(c, scan->options,
2686 &req->num_databaseNames);
2688 return send_APDU(c, apdu);
2692 ZOOM_scanset_size(ZOOM_scanset scan)
2694 if (!scan || !scan->scan_response || !scan->scan_response->entries)
2696 return scan->scan_response->entries->num_entries;
2699 ZOOM_API(const char *)
2700 ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
2703 const char *term = 0;
2704 size_t noent = ZOOM_scanset_size(scan);
2705 Z_ScanResponse *res = scan->scan_response;
2711 if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2713 Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2715 if (t->term->which == Z_Term_general)
2717 term = (const char *) t->term->u.general->buf;
2718 *len = t->term->u.general->len;
2720 *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2725 ZOOM_API(const char *)
2726 ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
2729 const char *term = 0;
2730 size_t noent = ZOOM_scanset_size(scan);
2731 Z_ScanResponse *res = scan->scan_response;
2737 if (res->entries->entries[pos]->which == Z_Entry_termInfo)
2739 Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
2743 term = t->displayTerm;
2744 *len = strlen(term);
2746 else if (t->term->which == Z_Term_general)
2748 term = (const char *) t->term->u.general->buf;
2749 *len = t->term->u.general->len;
2751 *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
2756 ZOOM_API(const char *)
2757 ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
2759 return ZOOM_options_get(scan->options, key);
2763 ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
2766 ZOOM_options_set(scan->options, key, val);
2769 static Z_APDU *create_es_package(ZOOM_package p, int type)
2772 Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
2773 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2775 *req->function = Z_ExtendedServicesRequest_create;
2777 str = ZOOM_options_get(p->options, "package-name");
2779 req->packageName = nmem_strdup(p->odr_out->mem, str);
2781 str = ZOOM_options_get(p->options, "user-id");
2783 req->userId = nmem_strdup(p->odr_out->mem, str);
2785 req->packageType = yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2788 str = ZOOM_options_get(p->options, "function");
2791 if (!strcmp (str, "create"))
2793 if (!strcmp (str, "delete"))
2795 if (!strcmp (str, "modify"))
2801 static const char *ill_array_lookup(void *clientData, const char *idx)
2803 ZOOM_package p = (ZOOM_package) clientData;
2804 return ZOOM_options_get(p->options, idx+4);
2807 static Z_External *encode_ill_request(ZOOM_package p)
2809 ODR out = p->odr_out;
2812 struct ill_get_ctl ctl;
2814 ctl.odr = p->odr_out;
2816 ctl.f = ill_array_lookup;
2818 req = ill_get_ILLRequest(&ctl, "ill", 0);
2820 if (!ill_Request(out, &req, 0, 0))
2822 int ill_request_size;
2823 char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
2824 if (ill_request_buf)
2825 odr_setbuf(out, ill_request_buf, ill_request_size, 1);
2831 int illRequest_size = 0;
2832 char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
2834 oid.proto = PROTO_GENERAL;
2835 oid.oclass = CLASS_GENERAL;
2836 oid.value = VAL_ISO_ILL_1;
2838 r = (Z_External *) odr_malloc(out, sizeof(*r));
2839 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
2840 r->indirect_reference = 0;
2842 r->which = Z_External_single;
2844 r->u.single_ASN1_type =
2845 odr_create_Odr_oct(out,
2846 (unsigned char *)illRequest_buf,
2852 static Z_ItemOrder *encode_item_order(ZOOM_package p)
2854 Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
2857 req->which = Z_IOItemOrder_esRequest;
2858 req->u.esRequest = (Z_IORequest *)
2859 odr_malloc(p->odr_out,sizeof(Z_IORequest));
2861 /* to keep part ... */
2862 req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2863 odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
2864 req->u.esRequest->toKeep->supplDescription = 0;
2865 req->u.esRequest->toKeep->contact = (Z_IOContact *)
2866 odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
2868 str = ZOOM_options_get(p->options, "contact-name");
2869 req->u.esRequest->toKeep->contact->name = str ?
2870 nmem_strdup(p->odr_out->mem, str) : 0;
2872 str = ZOOM_options_get(p->options, "contact-phone");
2873 req->u.esRequest->toKeep->contact->phone = str ?
2874 nmem_strdup(p->odr_out->mem, str) : 0;
2876 str = ZOOM_options_get(p->options, "contact-email");
2877 req->u.esRequest->toKeep->contact->email = str ?
2878 nmem_strdup(p->odr_out->mem, str) : 0;
2880 req->u.esRequest->toKeep->addlBilling = 0;
2882 /* not to keep part ... */
2883 req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2884 odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
2886 str = ZOOM_options_get(p->options, "itemorder-setname");
2891 req->u.esRequest->notToKeep->resultSetItem = 0;
2894 req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
2895 odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
2897 req->u.esRequest->notToKeep->resultSetItem->resultSetId =
2898 nmem_strdup(p->odr_out->mem, str);
2899 req->u.esRequest->notToKeep->resultSetItem->item =
2900 (int *) odr_malloc(p->odr_out, sizeof(int));
2902 str = ZOOM_options_get(p->options, "itemorder-item");
2903 *req->u.esRequest->notToKeep->resultSetItem->item =
2904 (str ? atoi(str) : 1);
2906 req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
2911 Z_APDU *create_admin_package(ZOOM_package p, int type,
2912 Z_ESAdminOriginPartToKeep **toKeepP,
2913 Z_ESAdminOriginPartNotToKeep **notToKeepP)
2915 Z_APDU *apdu = create_es_package(p, VAL_ADMINSERVICE);
2918 Z_ESAdminOriginPartToKeep *toKeep;
2919 Z_ESAdminOriginPartNotToKeep *notToKeep;
2920 Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
2921 const char *first_db = "Default";
2923 char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2927 r->direct_reference =
2928 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
2931 r->indirect_reference = 0;
2932 r->which = Z_External_ESAdmin;
2934 r->u.adminService = (Z_Admin *)
2935 odr_malloc(p->odr_out, sizeof(*r->u.adminService));
2936 r->u.adminService->which = Z_Admin_esRequest;
2937 r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
2938 odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
2940 toKeep = r->u.adminService->u.esRequest->toKeep =
2941 (Z_ESAdminOriginPartToKeep *)
2942 odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
2943 toKeep->which = type;
2944 toKeep->databaseName = odr_strdup(p->odr_out, first_db);
2945 toKeep->u.create = odr_nullval();
2946 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
2948 r->u.adminService->u.esRequest->notToKeep = notToKeep =
2949 (Z_ESAdminOriginPartNotToKeep *)
2950 odr_malloc(p->odr_out,
2951 sizeof(*r->u.adminService->u.esRequest->notToKeep));
2952 notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
2953 notToKeep->u.recordsWillFollow = odr_nullval();
2957 *notToKeepP = notToKeep;
2962 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
2964 Z_APDU *apdu = create_es_package(p, VAL_XMLES);
2965 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2966 Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
2967 const char *doc = ZOOM_options_get(p->options, "doc");
2972 req->taskSpecificParameters = ext;
2973 ext->direct_reference = req->packageType;
2974 ext->descriptor = 0;
2975 ext->indirect_reference = 0;
2977 ext->which = Z_External_octet;
2978 ext->u.single_ASN1_type =
2979 odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc,
2984 static Z_APDU *create_update_package(ZOOM_package p)
2987 const char *first_db = "Default";
2989 char **db = set_DatabaseNames(p->connection, p->options, &num_db);
2990 const char *action = ZOOM_options_get(p->options, "action");
2991 const char *recordIdOpaque = ZOOM_options_get(p->options, "recordIdOpaque");
2992 const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
2993 const char *record_buf = ZOOM_options_get(p->options, "record");
2994 const char *syntax_str = ZOOM_options_get(p->options, "syntax");
2995 int syntax_oid = VAL_NONE;
2999 syntax_oid = oid_getvalbyname(syntax_str);
3002 record_buf = "void";
3003 syntax_oid = VAL_SUTRS;
3005 if (syntax_oid == VAL_NONE)
3006 syntax_oid = VAL_TEXT_XML;
3012 action = "specialUpdate";
3014 if (!strcmp(action, "recordInsert"))
3015 action_no = Z_IUOriginPartToKeep_recordInsert;
3016 else if (!strcmp(action, "recordReplace"))
3017 action_no = Z_IUOriginPartToKeep_recordReplace;
3018 else if (!strcmp(action, "recordDelete"))
3019 action_no = Z_IUOriginPartToKeep_recordDelete;
3020 else if (!strcmp(action, "elementUpdate"))
3021 action_no = Z_IUOriginPartToKeep_elementUpdate;
3022 else if (!strcmp(action, "specialUpdate"))
3023 action_no = Z_IUOriginPartToKeep_specialUpdate;
3027 apdu = create_es_package(p, VAL_DBUPDATE);
3030 Z_IUOriginPartToKeep *toKeep;
3031 Z_IUSuppliedRecords *notToKeep;
3032 Z_External *r = (Z_External *)
3033 odr_malloc(p->odr_out, sizeof(*r));
3035 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3037 r->direct_reference =
3038 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
3041 r->which = Z_External_update;
3042 r->indirect_reference = 0;
3043 r->u.update = (Z_IUUpdate *)
3044 odr_malloc(p->odr_out, sizeof(*r->u.update));
3046 r->u.update->which = Z_IUUpdate_esRequest;
3047 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3048 odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3049 toKeep = r->u.update->u.esRequest->toKeep =
3050 (Z_IUOriginPartToKeep *)
3051 odr_malloc(p->odr_out, sizeof(*toKeep));
3053 toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3055 toKeep->elementSetName = 0;
3056 toKeep->actionQualifier = 0;
3057 toKeep->action = odr_intdup(p->odr_out, action_no);
3059 notToKeep = r->u.update->u.esRequest->notToKeep =
3060 (Z_IUSuppliedRecords *)
3061 odr_malloc(p->odr_out, sizeof(*notToKeep));
3063 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3064 odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3065 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3066 odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3067 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3070 notToKeep->elements[0]->u.opaque =
3071 odr_create_Odr_oct(p->odr_out,
3072 (const unsigned char *) recordIdOpaque,
3073 strlen(recordIdOpaque));
3075 else if (recordIdNumber)
3077 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3079 notToKeep->elements[0]->u.number =
3080 odr_intdup(p->odr_out, atoi(recordIdNumber));
3083 notToKeep->elements[0]->u.opaque = 0;
3084 notToKeep->elements[0]->supplementalId = 0;
3085 notToKeep->elements[0]->correlationInfo = 0;
3086 notToKeep->elements[0]->record =
3087 z_ext_record(p->odr_out, syntax_oid,
3088 record_buf, strlen(record_buf));
3092 ODR print = odr_createmem(ODR_PRINT);
3094 z_APDU(print, &apdu, 0, 0);
3101 ZOOM_package_send(ZOOM_package p, const char *type)
3108 odr_reset(p->odr_out);
3111 if (!strcmp(type, "itemorder"))
3113 apdu = create_es_package(p, VAL_ITEMORDER);
3116 Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3118 r->direct_reference =
3119 yaz_oidval_to_z3950oid(p->odr_out, CLASS_EXTSERV,
3122 r->which = Z_External_itemOrder;
3123 r->indirect_reference = 0;
3124 r->u.itemOrder = encode_item_order(p);
3126 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3129 else if (!strcmp(type, "create")) /* create database */
3131 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3134 else if (!strcmp(type, "drop")) /* drop database */
3136 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3139 else if (!strcmp(type, "commit")) /* commit changes */
3141 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3144 else if (!strcmp(type, "update")) /* update record(s) */
3146 apdu = create_update_package(p);
3148 else if (!strcmp(type, "xmlupdate"))
3150 apdu = create_xmlupdate_package(p);
3154 if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3158 ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
3159 task->u.package = p;
3160 buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3161 p->buf_out = (char *) xmalloc(p->len_out);
3162 memcpy(p->buf_out, buf, p->len_out);
3167 while (ZOOM_event(1, &c))
3174 ZOOM_API(ZOOM_package)
3175 ZOOM_connection_package(ZOOM_connection c, ZOOM_options options)
3177 ZOOM_package p = (ZOOM_package) xmalloc(sizeof(*p));
3180 p->odr_out = odr_createmem(ODR_ENCODE);
3181 p->options = ZOOM_options_create_with_parent2(options, c->options);
3189 ZOOM_package_destroy(ZOOM_package p)
3194 if (p->refcount == 0)
3196 odr_destroy(p->odr_out);
3199 ZOOM_options_destroy(p->options);
3204 ZOOM_API(const char *)
3205 ZOOM_package_option_get(ZOOM_package p, const char *key)
3207 return ZOOM_options_get(p->options, key);
3212 ZOOM_package_option_set(ZOOM_package p, const char *key,
3215 ZOOM_options_set(p->options, key, val);
3218 static int ZOOM_connection_exec_task(ZOOM_connection c)
3220 ZOOM_task task = c->tasks;
3221 zoom_ret ret = zoom_complete;
3225 yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3226 c, task->which, task->running);
3227 if (c->error != ZOOM_ERROR_NONE)
3229 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3230 "removing tasks because of error = %d", c, c->error);
3231 ZOOM_connection_remove_tasks(c);
3236 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3237 "task already running", c);
3241 ret = zoom_complete;
3242 if (c->cs || task->which == ZOOM_TASK_CONNECT)
3244 switch (task->which)
3246 case ZOOM_TASK_SEARCH:
3247 if (c->proto == PROTO_HTTP)
3248 ret = ZOOM_connection_srw_send_search(c);
3250 ret = ZOOM_connection_send_search(c);
3252 case ZOOM_TASK_RETRIEVE:
3253 if (c->proto == PROTO_HTTP)
3254 ret = ZOOM_connection_srw_send_search(c);
3256 ret = send_present(c);
3258 case ZOOM_TASK_CONNECT:
3259 ret = do_connect(c);
3261 case ZOOM_TASK_SCAN:
3264 case ZOOM_TASK_PACKAGE:
3265 ret = send_package(c);
3267 case ZOOM_TASK_SORT:
3268 c->tasks->u.sort.resultset->r_sort_spec =
3269 c->tasks->u.sort.q->sort_spec;
3270 ret = send_sort(c, c->tasks->u.sort.resultset);
3276 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3277 "remove tasks because no connection exist", c);
3278 ZOOM_connection_remove_tasks(c);
3280 if (ret == zoom_complete)
3282 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3283 "task removed (complete)", c);
3284 ZOOM_connection_remove_task(c);
3287 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3292 static zoom_ret send_sort_present(ZOOM_connection c)
3294 zoom_ret r = zoom_complete;
3296 if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3297 r = send_sort(c, c->tasks->u.search.resultset);
3298 if (r == zoom_complete)
3299 r = send_present(c);
3303 static int es_response(ZOOM_connection c,
3304 Z_ExtendedServicesResponse *res)
3306 if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3308 if (res->diagnostics && res->num_diagnostics > 0)
3309 response_diag(c, res->diagnostics[0]);
3310 if (res->taskPackage &&
3311 res->taskPackage->which == Z_External_extendedService)
3313 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
3314 Odr_oct *id = taskPackage->targetReference;
3317 ZOOM_options_setl(c->tasks->u.package->options,
3318 "targetReference", (char*) id->buf, id->len);
3320 if (res->taskPackage &&
3321 res->taskPackage->which == Z_External_octet)
3323 Odr_oct *doc = res->taskPackage->u.octet_aligned;
3324 ZOOM_options_setl(c->tasks->u.package->options,
3325 "xmlUpdateDoc", (char*) doc->buf, doc->len);
3330 static void interpret_init_diag(ZOOM_connection c,
3331 Z_DiagnosticFormat *diag)
3335 Z_DiagnosticFormat_s *ds = diag->elements[0];
3336 if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
3337 response_default_diag(c, ds->u.defaultDiagRec);
3342 static void interpret_otherinformation_field(ZOOM_connection c,
3343 Z_OtherInformation *ui)
3346 for (i = 0; i < ui->num_elements; i++)
3348 Z_OtherInformationUnit *unit = ui->list[i];
3349 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
3350 unit->information.externallyDefinedInfo &&
3351 unit->information.externallyDefinedInfo->which ==
3354 interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
3359 static void recv_apdu(ZOOM_connection c, Z_APDU *apdu)
3361 Z_InitResponse *initrs;
3364 yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
3367 case Z_APDU_initResponse:
3368 yaz_log(log_api, "%p recv_apd: Received Init response", c);
3369 initrs = apdu->u.initResponse;
3370 ZOOM_connection_option_set(c, "serverImplementationId",
3371 initrs->implementationId ?
3372 initrs->implementationId : "");
3373 ZOOM_connection_option_set(c, "serverImplementationName",
3374 initrs->implementationName ?
3375 initrs->implementationName : "");
3376 ZOOM_connection_option_set(c, "serverImplementationVersion",
3377 initrs->implementationVersion ?
3378 initrs->implementationVersion : "");
3379 /* Set the three old options too, for old applications */
3380 ZOOM_connection_option_set(c, "targetImplementationId",
3381 initrs->implementationId ?
3382 initrs->implementationId : "");
3383 ZOOM_connection_option_set(c, "targetImplementationName",
3384 initrs->implementationName ?
3385 initrs->implementationName : "");
3386 ZOOM_connection_option_set(c, "targetImplementationVersion",
3387 initrs->implementationVersion ?
3388 initrs->implementationVersion : "");
3389 if (!*initrs->result)
3391 Z_External *uif = initrs->userInformationField;
3393 set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
3395 if (uif && uif->which == Z_External_userInfo1)
3396 interpret_otherinformation_field(c, uif->u.userInfo1);
3401 yaz_oi_get_string_oidval(&apdu->u.initResponse->otherInfo,
3403 xfree(c->cookie_in);
3406 c->cookie_in = xstrdup(cookie);
3407 if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
3408 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
3409 c->support_named_resultsets = 1;
3412 assert(c->tasks->which == ZOOM_TASK_CONNECT);
3413 ZOOM_connection_remove_task(c);
3415 ZOOM_connection_exec_task(c);
3417 if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
3419 NMEM tmpmem = nmem_create();
3420 Z_CharSetandLanguageNegotiation *p =
3421 yaz_get_charneg_record(initrs->otherInfo);
3425 char *charset = NULL, *lang = NULL;
3428 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
3429 yaz_log(log_details, "%p recv_apdu target accepted: "
3430 "charset %s, language %s, select %d",
3432 charset ? charset : "none", lang ? lang : "none", sel);
3434 ZOOM_connection_option_set(c, "negotiation-charset",
3437 ZOOM_connection_option_set(c, "negotiation-lang",
3440 ZOOM_connection_option_set(
3441 c, "negotiation-charset-in-effect-for-records",
3442 (sel != 0) ? "1" : "0");
3443 nmem_destroy(tmpmem);
3447 case Z_APDU_searchResponse:
3448 yaz_log(log_api, "%p recv_apdu Search response", c);
3449 handle_search_response(c, apdu->u.searchResponse);
3450 if (send_sort_present(c) == zoom_complete)
3451 ZOOM_connection_remove_task(c);
3453 case Z_APDU_presentResponse:
3454 yaz_log(log_api, "%p recv_apdu Present response", c);
3455 handle_present_response(c, apdu->u.presentResponse);
3456 if (send_present(c) == zoom_complete)
3457 ZOOM_connection_remove_task(c);
3459 case Z_APDU_sortResponse:
3460 yaz_log(log_api, "%p recv_apdu Sort response", c);
3461 sort_response(c, apdu->u.sortResponse);
3462 if (send_present(c) == zoom_complete)
3463 ZOOM_connection_remove_task(c);
3465 case Z_APDU_scanResponse:
3466 yaz_log(log_api, "%p recv_apdu Scan response", c);
3467 scan_response(c, apdu->u.scanResponse);
3468 ZOOM_connection_remove_task(c);
3470 case Z_APDU_extendedServicesResponse:
3471 yaz_log(log_api, "%p recv_apdu Extended Services response", c);
3472 es_response(c, apdu->u.extendedServicesResponse);
3473 ZOOM_connection_remove_task(c);
3476 yaz_log(log_api, "%p recv_apdu Close PDU", c);
3477 if (!ZOOM_test_reconnect(c))
3479 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3484 yaz_log(log_api, "%p Received unknown PDU", c);
3485 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3491 static void handle_srw_response(ZOOM_connection c,
3492 Z_SRW_searchRetrieveResponse *res)
3494 ZOOM_resultset resultset = 0;
3499 const char *syntax, *elementSetName;
3504 switch(c->tasks->which)
3506 case ZOOM_TASK_SEARCH:
3507 resultset = c->tasks->u.search.resultset;
3508 start = &c->tasks->u.search.start;
3509 syntax = c->tasks->u.search.syntax;
3510 elementSetName = c->tasks->u.search.elementSetName;
3512 case ZOOM_TASK_RETRIEVE:
3513 resultset = c->tasks->u.retrieve.resultset;
3514 start = &c->tasks->u.retrieve.start;
3515 syntax = c->tasks->u.retrieve.syntax;
3516 elementSetName = c->tasks->u.retrieve.elementSetName;
3521 event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
3522 ZOOM_connection_put_event(c, event);
3524 resultset->size = 0;
3526 yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
3528 if (res->numberOfRecords)
3529 resultset->size = *res->numberOfRecords;
3531 for (i = 0; i<res->num_records; i++)
3535 Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
3536 odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
3538 if (res->records[i].recordPosition &&
3539 *res->records[i].recordPosition > 0)
3540 pos = *res->records[i].recordPosition - 1;
3544 npr->databaseName = 0;
3545 npr->which = Z_NamePlusRecord_databaseRecord;
3546 npr->u.databaseRecord = (Z_External *)
3547 odr_malloc(c->odr_in, sizeof(Z_External));
3548 npr->u.databaseRecord->descriptor = 0;
3549 npr->u.databaseRecord->direct_reference =
3550 yaz_oidval_to_z3950oid(c->odr_in, CLASS_RECSYN, VAL_TEXT_XML);
3551 npr->u.databaseRecord->which = Z_External_octet;
3553 npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
3554 odr_malloc(c->odr_in, sizeof(Odr_oct));
3555 npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
3556 res->records[i].recordData_buf;
3557 npr->u.databaseRecord->u.octet_aligned->len =
3558 npr->u.databaseRecord->u.octet_aligned->size =
3559 res->records[i].recordData_len;
3560 record_cache_add(resultset, npr, pos, syntax, elementSetName);
3562 if (res->num_diagnostics > 0)
3564 const char *uri = res->diagnostics[0].uri;
3569 if ((cp = strrchr(uri, '/')))
3571 set_dset_error(c, code, uri,
3572 res->diagnostics[0].details, 0);
3575 nmem = odr_extract_mem(c->odr_in);
3576 nmem_transfer(resultset->odr->mem, nmem);
3582 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
3585 const char *content_type = z_HTTP_header_lookup(hres->headers,
3587 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3590 yaz_log(log_details, "%p handle_http", c);
3592 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3594 Z_SOAP *soap_package = 0;
3596 Z_SOAP_Handler soap_handlers[2] = {
3597 {"http://www.loc.gov/zing/srw/", 0,
3598 (Z_SOAP_fun) yaz_srw_codec},
3601 ret = z_soap_codec(o, &soap_package,
3602 &hres->content_buf, &hres->content_len,
3604 if (!ret && soap_package->which == Z_SOAP_generic &&
3605 soap_package->u.generic->no == 0)
3607 Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
3608 if (sr->which == Z_SRW_searchRetrieve_response)
3609 handle_srw_response(c, sr->u.response);
3613 else if (!ret && (soap_package->which == Z_SOAP_fault
3614 || soap_package->which == Z_SOAP_error))
3616 set_HTTP_error(c, hres->code,
3617 soap_package->u.fault->fault_code,
3618 soap_package->u.fault->fault_string);
3625 if (hres->code != 200)
3626 set_HTTP_error(c, hres->code, 0, 0);
3628 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3631 ZOOM_connection_remove_task(c);
3632 if (!strcmp(hres->version, "1.0"))
3634 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3635 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3640 /* HTTP 1.1: only if no close we stay alive .. */
3641 if (connection_head && !strcmp(connection_head, "close"))
3647 static int do_read(ZOOM_connection c)
3652 event = ZOOM_Event_create(ZOOM_EVENT_RECV_DATA);
3653 ZOOM_connection_put_event(c, event);
3655 r = cs_get(c->cs, &c->buf_in, &c->len_in);
3656 more = cs_more(c->cs);
3657 yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
3662 if (ZOOM_test_reconnect(c))
3664 yaz_log(log_details, "%p do_read reconnect read", c);
3668 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3677 odr_reset(c->odr_in);
3678 odr_setbuf(c->odr_in, c->buf_in, r, 0);
3679 event = ZOOM_Event_create(ZOOM_EVENT_RECV_APDU);
3680 ZOOM_connection_put_event(c, event);
3682 if (!z_GDU(c->odr_in, &gdu, 0, 0))
3685 int err = odr_geterrorx(c->odr_in, &x);
3687 const char *element = odr_getelement(c->odr_in);
3688 sprintf(msg, "ODR code %d:%d element=%-20s",
3689 err, x, element ? element : "<unknown>");
3690 set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
3693 else if (gdu->which == Z_GDU_Z3950)
3694 recv_apdu(c, gdu->u.z3950);
3695 else if (gdu->which == Z_GDU_HTTP_Response)
3698 handle_http(c, gdu->u.HTTP_Response);
3700 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
3704 c->reconnect_ok = 0;
3709 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out)
3714 event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
3715 ZOOM_connection_put_event(c, event);
3717 yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
3718 if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
3720 yaz_log(log_details, "%p do_write_ex write failed", c);
3721 if (ZOOM_test_reconnect(c))
3723 return zoom_pending;
3725 if (c->state == STATE_CONNECTING)
3726 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
3728 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3730 return zoom_complete;
3734 c->mask = ZOOM_SELECT_EXCEPT;
3735 if (c->cs->io_pending & CS_WANT_WRITE)
3736 c->mask += ZOOM_SELECT_WRITE;
3737 if (c->cs->io_pending & CS_WANT_READ)
3738 c->mask += ZOOM_SELECT_READ;
3739 yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
3744 c->mask = ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT;
3745 yaz_log(log_details, "%p do_write_ex write complete mask=%d",
3748 return zoom_pending;
3751 static zoom_ret do_write(ZOOM_connection c)
3753 return do_write_ex(c, c->buf_out, c->len_out);
3757 ZOOM_API(const char *)
3758 ZOOM_connection_option_get(ZOOM_connection c, const char *key)
3760 return ZOOM_options_get(c->options, key);
3763 ZOOM_API(const char *)
3764 ZOOM_connection_option_getl(ZOOM_connection c, const char *key, int *lenp)
3766 return ZOOM_options_getl(c->options, key, lenp);
3770 ZOOM_connection_option_set(ZOOM_connection c, const char *key,
3773 ZOOM_options_set(c->options, key, val);
3777 ZOOM_connection_option_setl(ZOOM_connection c, const char *key,
3778 const char *val, int len)
3780 ZOOM_options_setl(c->options, key, val, len);
3783 ZOOM_API(const char *)
3784 ZOOM_resultset_option_get(ZOOM_resultset r, const char *key)
3786 return ZOOM_options_get(r->options, key);
3790 ZOOM_resultset_option_set(ZOOM_resultset r, const char *key,
3793 ZOOM_options_set(r->options, key, val);
3798 ZOOM_connection_errcode(ZOOM_connection c)
3800 return ZOOM_connection_error(c, 0, 0);
3803 ZOOM_API(const char *)
3804 ZOOM_connection_errmsg(ZOOM_connection c)
3807 ZOOM_connection_error(c, &msg, 0);
3811 ZOOM_API(const char *)
3812 ZOOM_connection_addinfo(ZOOM_connection c)
3814 const char *addinfo;
3815 ZOOM_connection_error(c, 0, &addinfo);
3819 ZOOM_API(const char *)
3820 ZOOM_connection_diagset(ZOOM_connection c)
3822 const char *diagset;
3823 ZOOM_connection_error_x(c, 0, 0, &diagset);
3827 ZOOM_API(const char *)
3828 ZOOM_diag_str(int error)
3832 case ZOOM_ERROR_NONE:
3834 case ZOOM_ERROR_CONNECT:
3835 return "Connect failed";
3836 case ZOOM_ERROR_MEMORY:
3837 return "Out of memory";
3838 case ZOOM_ERROR_ENCODE:
3839 return "Encoding failed";
3840 case ZOOM_ERROR_DECODE:
3841 return "Decoding failed";
3842 case ZOOM_ERROR_CONNECTION_LOST:
3843 return "Connection lost";
3844 case ZOOM_ERROR_INIT:
3845 return "Init rejected";
3846 case ZOOM_ERROR_INTERNAL:
3847 return "Internal failure";
3848 case ZOOM_ERROR_TIMEOUT:
3850 case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
3851 return "Unsupported protocol";
3852 case ZOOM_ERROR_UNSUPPORTED_QUERY:
3853 return "Unsupported query type";
3854 case ZOOM_ERROR_INVALID_QUERY:
3855 return "Invalid query";
3856 case ZOOM_ERROR_CQL_PARSE:
3857 return "CQL parsing error";
3858 case ZOOM_ERROR_CQL_TRANSFORM:
3859 return "CQL transformation error";
3860 case ZOOM_ERROR_CCL_CONFIG:
3861 return "CCL configuration error";
3862 case ZOOM_ERROR_CCL_PARSE:
3863 return "CCL parsing error";
3865 return diagbib1_str(error);
3870 ZOOM_connection_error_x(ZOOM_connection c, const char **cp,
3871 const char **addinfo, const char **diagset)
3873 int error = c->error;
3876 if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
3877 *cp = ZOOM_diag_str(error);
3878 else if (!strcmp(c->diagset, "HTTP"))
3879 *cp = z_HTTP_errmsg(c->error);
3880 else if (!strcmp(c->diagset, "Bib-1"))
3881 *cp = ZOOM_diag_str(error);
3882 else if (!strcmp(c->diagset, "info:srw/diagnostic/1"))
3883 *cp = yaz_diag_srw_str(c->error);
3885 *cp = "Unknown error and diagnostic set";
3888 *addinfo = c->addinfo ? c->addinfo : "";
3890 *diagset = c->diagset ? c->diagset : "";
3895 ZOOM_connection_error(ZOOM_connection c, const char **cp,
3896 const char **addinfo)
3898 return ZOOM_connection_error_x(c, cp, addinfo, 0);
3901 static void ZOOM_connection_do_io(ZOOM_connection c, int mask)
3903 ZOOM_Event event = 0;
3904 int r = cs_look(c->cs);
3905 yaz_log(log_details, "%p ZOOM_connection_do_io mask=%d cs_look=%d",
3910 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
3911 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
3913 ZOOM_connection_put_event(c, event);
3915 else if (r == CS_CONNECT)
3917 int ret = ret = cs_rcvconnect(c->cs);
3918 yaz_log(log_details, "%p ZOOM_connection_do_io "
3919 "cs_rcvconnect returned %d", c, ret);
3922 c->mask = ZOOM_SELECT_EXCEPT;
3923 if (c->cs->io_pending & CS_WANT_WRITE)
3924 c->mask += ZOOM_SELECT_WRITE;
3925 if (c->cs->io_pending & CS_WANT_READ)
3926 c->mask += ZOOM_SELECT_READ;
3930 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
3931 ZOOM_connection_put_event(c, event);
3933 if (c->proto == PROTO_Z3950)
3934 ZOOM_connection_send_init(c);
3937 /* no init request for SRW .. */
3938 assert(c->tasks->which == ZOOM_TASK_CONNECT);
3939 ZOOM_connection_remove_task(c);
3941 ZOOM_connection_exec_task(c);
3943 c->state = STATE_ESTABLISHED;
3947 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
3953 if (mask & ZOOM_SELECT_EXCEPT)
3955 if (ZOOM_test_reconnect(c))
3957 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
3958 ZOOM_connection_put_event(c, event);
3962 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
3967 if (mask & ZOOM_SELECT_READ)
3969 if (c->cs && (mask & ZOOM_SELECT_WRITE))
3975 ZOOM_connection_last_event(ZOOM_connection cs)
3978 return ZOOM_EVENT_NONE;
3979 return cs->last_event;
3983 ZOOM_event(int no, ZOOM_connection *cs)
3985 int timeout = 30; /* default timeout in seconds */
3986 int timeout_set = 0; /* whether it was overriden at all */
3988 struct pollfd pollfds[1024];
3989 ZOOM_connection poll_cs[1024];
3992 fd_set input, output, except;
3997 yaz_log(log_details, "ZOOM_event(no=%d,cs=%p)", no, cs);
3998 for (i = 0; i<no; i++)
4000 ZOOM_connection c = cs[i];
4002 if (c && (event = ZOOM_connection_get_event(c)))
4004 ZOOM_Event_destroy(event);
4008 for (i = 0; i<no; i++)
4010 ZOOM_connection c = cs[i];
4014 ZOOM_connection_exec_task(c);
4015 if ((event = ZOOM_connection_get_event(c)))
4017 ZOOM_Event_destroy(event);
4030 for (i = 0; i<no; i++)
4032 ZOOM_connection c = cs[i];
4038 fd = z3950_connection_socket(c);
4039 mask = z3950_connection_mask(c);
4046 /* -1 is used for indefinite timeout (no timeout), so -2 here. */
4047 this_timeout = ZOOM_options_get_int(c->options, "timeout", -2);
4048 if (this_timeout != -2)
4050 /* ensure the minimum timeout is used */
4052 timeout = this_timeout;
4053 else if (this_timeout != -1 && this_timeout < timeout)
4054 timeout = this_timeout;
4060 short poll_events = 0;
4062 if (mask & ZOOM_SELECT_READ)
4063 poll_events += POLLIN;
4064 if (mask & ZOOM_SELECT_WRITE)
4065 poll_events += POLLOUT;
4066 if (mask & ZOOM_SELECT_EXCEPT)
4067 poll_events += POLLERR;
4068 pollfds[nfds].fd = fd;
4069 pollfds[nfds].events = poll_events;
4070 pollfds[nfds].revents = 0;
4075 if (mask & ZOOM_SELECT_READ)
4080 if (mask & ZOOM_SELECT_WRITE)
4082 FD_SET(fd, &output);
4085 if (mask & ZOOM_SELECT_EXCEPT)
4087 FD_SET(fd, &except);
4096 r = poll(pollfds, nfds, (timeout == -1 ? -1 : timeout * 1000));
4097 for (i = 0; i<nfds; i++)
4099 ZOOM_connection c = poll_cs[i];
4103 if (pollfds[i].revents & POLLIN)
4104 mask += ZOOM_SELECT_READ;
4105 if (pollfds[i].revents & POLLOUT)
4106 mask += ZOOM_SELECT_WRITE;
4107 if (pollfds[i].revents & POLLERR)
4108 mask += ZOOM_SELECT_EXCEPT;
4110 ZOOM_connection_do_io(c, mask);
4112 else if (r == 0 && c->mask)
4114 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
4115 /* timeout and this connection was waiting */
4116 set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
4118 ZOOM_connection_put_event(c, event);
4122 tv.tv_sec = timeout;
4124 r = select(max_fd+1, &input, &output, &except, (timeout == -1 ? 0 : &tv));
4125 for (i = 0; i<no; i++)
4127 ZOOM_connection c = cs[i];
4132 fd = z3950_connection_socket(c);
4136 /* no timeout and real socket */
4137 if (FD_ISSET(fd, &input))
4138 mask += ZOOM_SELECT_READ;
4139 if (FD_ISSET(fd, &output))
4140 mask += ZOOM_SELECT_WRITE;
4141 if (FD_ISSET(fd, &except))
4142 mask += ZOOM_SELECT_EXCEPT;
4144 ZOOM_connection_do_io(c, mask);
4146 if (r == 0 && c->mask)
4148 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
4149 /* timeout and this connection was waiting */
4150 set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
4152 ZOOM_connection_put_event(c, event);
4156 for (i = 0; i<no; i++)
4158 ZOOM_connection c = cs[i];
4160 if (c && (event = ZOOM_connection_get_event(c)))
4162 ZOOM_Event_destroy(event);
4171 * Returns an xmalloc()d string containing RPN that corresponds to the
4172 * CQL passed in. On error, sets the Connection object's error state
4173 * and returns a null pointer.
4174 * ### We could cache CQL parser and/or transformer in Connection.
4176 static char *cql2pqf(ZOOM_connection c, const char *cql)
4180 struct cql_node *node;
4181 const char *cqlfile;
4182 static cql_transform_t trans;
4185 parser = cql_parser_create();
4186 if ((error = cql_parser_string(parser, cql)) != 0) {
4187 cql_parser_destroy(parser);
4188 set_ZOOM_error(c, ZOOM_ERROR_CQL_PARSE, cql);
4192 node = cql_parser_result(parser);
4193 /* ### Do not call cql_parser_destroy() yet: it destroys `node'! */
4195 cqlfile = ZOOM_connection_option_get(c, "cqlfile");
4197 cql_parser_destroy(parser);
4198 cql_node_destroy(node);
4199 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, "no CQL transform file");
4203 if ((trans = cql_transform_open_fname(cqlfile)) == 0) {
4205 cql_parser_destroy(parser);
4206 cql_node_destroy(node);
4207 sprintf(buf, "can't open CQL transform file '%.200s': %.200s",
4208 cqlfile, strerror(errno));
4209 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4213 error = cql_transform_buf(trans, node, pqfbuf, sizeof pqfbuf);
4214 cql_parser_destroy(parser);
4215 cql_node_destroy(node);
4218 const char *addinfo;
4219 error = cql_transform_error(trans, &addinfo);
4220 cql_transform_close(trans);
4221 sprintf(buf, "%.200s (addinfo=%.200s)", cql_strerror(error), addinfo);
4222 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4226 cql_transform_close(trans);
4227 return xstrdup(pqfbuf);
4233 * indent-tabs-mode: nil
4235 * vim: shiftwidth=4 tabstop=8 expandtab