1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements ZOOM C interface.
15 #include <yaz/yaz-util.h>
16 #include <yaz/xmalloc.h>
17 #include <yaz/otherinfo.h>
19 #include <yaz/pquery.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/charneg.h>
27 #include <yaz/query-charset.h>
28 #include <yaz/copy_types.h>
29 #include <yaz/snprintf.h>
30 #include <yaz/facet.h>
32 #include <yaz/shptr.h>
38 static int log_api = 0;
39 static int log_details = 0;
46 static void resultset_destroy(ZOOM_resultset r);
47 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c);
48 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out);
49 static char *cql2pqf(ZOOM_connection c, const char *cql);
51 ZOOM_API(const char *) ZOOM_get_event_str(int event)
53 static const char *ar[] = {
70 * This wrapper is just for logging failed lookups. It would be nicer
71 * if it could cause failure when a lookup fails, but that's hard.
73 static Odr_oid *zoom_yaz_str_to_z3950oid(ZOOM_connection c,
74 oid_class oid_class, const char *str) {
75 Odr_oid *res = yaz_string_to_oid_odr(yaz_oid_std(), oid_class, str,
78 yaz_log(YLOG_WARN, "%p OID lookup (%d, '%s') failed",
79 c, (int) oid_class, str);
84 static void initlog(void)
86 static int log_level_initialized = 0;
87 if (!log_level_initialized)
89 log_api = yaz_log_module_level("zoom");
90 log_details = yaz_log_module_level("zoomdetails");
91 log_level_initialized = 1;
95 static ZOOM_Event ZOOM_Event_create(int kind)
97 ZOOM_Event event = (ZOOM_Event) xmalloc(sizeof(*event));
101 yaz_log(log_details, "ZOOM_Event_create(kind=%d)", kind);
105 static void ZOOM_Event_destroy(ZOOM_Event event)
110 static void ZOOM_connection_put_event(ZOOM_connection c, ZOOM_Event event)
114 c->m_queue_back->prev = event;
115 assert(c->m_queue_front);
119 assert(!c->m_queue_front);
120 c->m_queue_front = event;
122 event->next = c->m_queue_back;
124 c->m_queue_back = event;
127 static ZOOM_Event ZOOM_connection_get_event(ZOOM_connection c)
129 ZOOM_Event event = c->m_queue_front;
132 c->last_event = ZOOM_EVENT_NONE;
135 assert(c->m_queue_back);
136 c->m_queue_front = event->prev;
137 if (c->m_queue_front)
139 assert(c->m_queue_back);
140 c->m_queue_front->next = 0;
144 c->last_event = event->kind;
148 static void ZOOM_connection_remove_events(ZOOM_connection c)
151 while ((event = ZOOM_connection_get_event(c)))
152 ZOOM_Event_destroy(event);
155 ZOOM_API(int) ZOOM_connection_peek_event(ZOOM_connection c)
157 ZOOM_Event event = c->m_queue_front;
159 return event ? event->kind : ZOOM_EVENT_NONE;
162 void ZOOM_connection_remove_tasks(ZOOM_connection c);
164 static void set_dset_error(ZOOM_connection c, int error,
166 const char *addinfo, const char *addinfo2)
173 if (!c->diagset || strcmp(dset, c->diagset))
176 c->diagset = xstrdup(dset);
177 /* remove integer part from SRW diagset .. */
178 if ((cp = strrchr(c->diagset, '/')))
181 if (addinfo && addinfo2)
183 c->addinfo = (char*) xmalloc(strlen(addinfo) + strlen(addinfo2) + 2);
184 strcpy(c->addinfo, addinfo);
185 strcat(c->addinfo, addinfo2);
188 c->addinfo = xstrdup(addinfo);
189 if (error != ZOOM_ERROR_NONE)
191 yaz_log(log_api, "%p set_dset_error %s %s:%d %s %s",
192 c, c->host_port ? c->host_port : "<>", dset, error,
193 addinfo ? addinfo : "",
194 addinfo2 ? addinfo2 : "");
195 ZOOM_connection_remove_tasks(c);
199 static int uri_to_code(const char *uri)
203 if ((cp = strrchr(uri, '/')))
209 static void set_HTTP_error(ZOOM_connection c, int error,
210 const char *addinfo, const char *addinfo2)
212 set_dset_error(c, error, "HTTP", addinfo, addinfo2);
215 static void set_SRU_error(ZOOM_connection c, Z_SRW_diagnostic *d)
217 const char *uri = d->uri;
219 set_dset_error(c, uri_to_code(uri), uri, d->details, 0);
225 static void set_ZOOM_error(ZOOM_connection c, int error,
228 set_dset_error(c, error, "ZOOM", addinfo, 0);
231 static void clear_error(ZOOM_connection c)
234 * If an error is tied to an operation then it's ok to clear: for
235 * example, a diagnostic returned from a search is cleared by a
236 * subsequent search. However, problems such as Connection Lost
237 * or Init Refused are not cleared, because they are not
238 * recoverable: doing another search doesn't help.
241 ZOOM_connection_remove_events(c);
244 case ZOOM_ERROR_CONNECT:
245 case ZOOM_ERROR_MEMORY:
246 case ZOOM_ERROR_DECODE:
247 case ZOOM_ERROR_CONNECTION_LOST:
248 case ZOOM_ERROR_INIT:
249 case ZOOM_ERROR_INTERNAL:
250 case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
253 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
257 void ZOOM_connection_show_task(ZOOM_task task)
261 case ZOOM_TASK_SEARCH:
262 yaz_log(YLOG_LOG, "search p=%p", task);
264 case ZOOM_TASK_RETRIEVE:
265 yaz_log(YLOG_LOG, "retrieve p=%p", task);
267 case ZOOM_TASK_CONNECT:
268 yaz_log(YLOG_LOG, "connect p=%p", task);
271 yaz_log(YLOG_LOG, "scan p=%p", task);
276 void ZOOM_connection_show_tasks(ZOOM_connection c)
279 yaz_log(YLOG_LOG, "connection p=%p tasks", c);
280 for (task = c->tasks; task; task = task->next)
281 ZOOM_connection_show_task(task);
284 ZOOM_task ZOOM_connection_add_task(ZOOM_connection c, int which)
286 ZOOM_task *taskp = &c->tasks;
288 taskp = &(*taskp)->next;
289 *taskp = (ZOOM_task) xmalloc(sizeof(**taskp));
290 (*taskp)->running = 0;
291 (*taskp)->which = which;
297 ZOOM_API(int) ZOOM_connection_is_idle(ZOOM_connection c)
299 return c->tasks ? 0 : 1;
302 ZOOM_task ZOOM_connection_insert_task(ZOOM_connection c, int which)
304 ZOOM_task task = (ZOOM_task) xmalloc(sizeof(*task));
306 task->next = c->tasks;
315 void ZOOM_connection_remove_task(ZOOM_connection c)
317 ZOOM_task task = c->tasks;
321 c->tasks = task->next;
324 case ZOOM_TASK_SEARCH:
325 resultset_destroy(task->u.search.resultset);
326 xfree(task->u.search.syntax);
327 xfree(task->u.search.elementSetName);
329 case ZOOM_TASK_RETRIEVE:
330 resultset_destroy(task->u.retrieve.resultset);
331 xfree(task->u.retrieve.syntax);
332 xfree(task->u.retrieve.elementSetName);
334 case ZOOM_TASK_CONNECT:
337 ZOOM_scanset_destroy(task->u.scan.scan);
339 case ZOOM_TASK_PACKAGE:
340 ZOOM_package_destroy(task->u.package);
343 resultset_destroy(task->u.sort.resultset);
344 ZOOM_query_destroy(task->u.sort.q);
353 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_END);
354 ZOOM_connection_put_event(c, event);
359 void ZOOM_connection_remove_tasks(ZOOM_connection c)
362 ZOOM_connection_remove_task(c);
365 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
367 const char *elementSetName);
369 ZOOM_API(ZOOM_connection)
370 ZOOM_connection_create(ZOOM_options options)
372 ZOOM_connection c = (ZOOM_connection) xmalloc(sizeof(*c));
376 yaz_log(log_api, "%p ZOOM_connection_create", c);
378 c->proto = PROTO_Z3950;
380 ZOOM_connection_set_mask(c, 0);
382 c->state = STATE_IDLE;
385 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
392 c->options = ZOOM_options_create_with_parent(options);
398 c->charset = c->lang = 0;
409 c->maximum_record_size = 0;
410 c->preferred_message_size = 0;
412 c->odr_in = odr_createmem(ODR_DECODE);
413 c->odr_out = odr_createmem(ODR_ENCODE);
417 c->support_named_resultsets = 0;
418 c->last_event = ZOOM_EVENT_NONE;
420 c->m_queue_front = 0;
429 /* set database names. Take local databases (if set); otherwise
430 take databases given in ZURL (if set); otherwise use Default */
431 static char **set_DatabaseNames(ZOOM_connection con, ZOOM_options options,
434 char **databaseNames;
435 const char *cp = ZOOM_options_get(options, "databaseName");
437 if ((!cp || !*cp) && con->host_port)
439 if (strncmp(con->host_port, "unix:", 5) == 0)
440 cp = strchr(con->host_port+5, ':');
442 cp = strchr(con->host_port, '/');
448 nmem_strsplit(odr_getmem(odr), "+", cp, &databaseNames, num);
449 return databaseNames;
452 ZOOM_API(ZOOM_connection)
453 ZOOM_connection_new(const char *host, int portnum)
455 ZOOM_connection c = ZOOM_connection_create(0);
457 ZOOM_connection_connect(c, host, portnum);
461 static zoom_sru_mode get_sru_mode_from_string(const char *s)
464 return zoom_sru_soap;
465 if (!yaz_matchstr(s, "soap"))
466 return zoom_sru_soap;
467 else if (!yaz_matchstr(s, "get"))
469 else if (!yaz_matchstr(s, "post"))
470 return zoom_sru_post;
471 return zoom_sru_error;
475 ZOOM_connection_connect(ZOOM_connection c,
476 const char *host, int portnum)
483 yaz_log(log_api, "%p ZOOM_connection_connect host=%s portnum=%d",
484 c, host ? host : "null", portnum);
486 set_ZOOM_error(c, ZOOM_ERROR_NONE, 0);
487 ZOOM_connection_remove_tasks(c);
491 odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
492 odr_destroy(c->odr_print);
494 if (ZOOM_options_get_bool(c->options, "apdulog", 0))
496 c->odr_print = odr_createmem(ODR_PRINT);
497 odr_setprint(c->odr_print, yaz_log_file());
504 yaz_log(log_details, "%p ZOOM_connection_connect reconnect ok", c);
508 yaz_log(log_details, "%p ZOOM_connection_connect connect", c);
511 val = ZOOM_options_get(c->options, "proxy");
514 yaz_log(log_details, "%p ZOOM_connection_connect proxy=%s", c, val);
515 c->proxy = xstrdup(val);
520 val = ZOOM_options_get(c->options, "charset");
523 yaz_log(log_details, "%p ZOOM_connection_connect charset=%s", c, val);
524 c->charset = xstrdup(val);
528 val = ZOOM_options_get(c->options, "lang");
531 yaz_log(log_details, "%p ZOOM_connection_connect lang=%s", c, val);
532 c->lang = xstrdup(val);
543 sprintf(hostn, "%.80s:%d", host, portnum);
544 c->host_port = xstrdup(hostn);
547 c->host_port = xstrdup(host);
552 * If the "<scheme>:" part of the host string is preceded by one
553 * or more comma-separated <name>=<value> pairs, these are taken
554 * to be options to be set on the connection object. Among other
555 * applications, this facility can be used to embed authentication
557 * user=admin,password=secret,tcp:localhost:9999
559 char *remainder = c->host_port;
560 char *pcolon = strchr(remainder, ':');
563 while ((pcomma = strchr(remainder, ',')) != 0 &&
564 (pcolon == 0 || pcomma < pcolon)) {
566 if ((pequals = strchr(remainder, '=')) != 0) {
568 /*printf("# setting '%s'='%s'\n", remainder, pequals+1);*/
569 ZOOM_connection_option_set(c, remainder, pequals+1);
571 remainder = pcomma+1;
574 if (remainder != c->host_port) {
576 c->host_port = xstrdup(remainder);
577 /*printf("# reset hp='%s'\n", remainder);*/
581 val = ZOOM_options_get(c->options, "sru");
582 c->sru_mode = get_sru_mode_from_string(val);
584 xfree(c->sru_version);
585 val = ZOOM_options_get(c->options, "sru_version");
586 c->sru_version = xstrdup(val ? val : "1.2");
588 ZOOM_options_set(c->options, "host", c->host_port);
590 xfree(c->cookie_out);
592 val = ZOOM_options_get(c->options, "cookie");
595 yaz_log(log_details, "%p ZOOM_connection_connect cookie=%s", c, val);
596 c->cookie_out = xstrdup(val);
601 val = ZOOM_options_get(c->options, "clientIP");
604 yaz_log(log_details, "%p ZOOM_connection_connect clientIP=%s",
606 c->client_IP = xstrdup(val);
611 val = ZOOM_options_get(c->options, "group");
613 c->group = xstrdup(val);
617 val = ZOOM_options_get(c->options, "user");
619 c->user = xstrdup(val);
623 val = ZOOM_options_get(c->options, "password");
625 val = ZOOM_options_get(c->options, "pass");
628 c->password = xstrdup(val);
630 c->maximum_record_size =
631 ZOOM_options_get_int(c->options, "maximumRecordSize", 1024*1024);
632 c->preferred_message_size =
633 ZOOM_options_get_int(c->options, "preferredMessageSize", 1024*1024);
635 c->async = ZOOM_options_get_bool(c->options, "async", 0);
636 yaz_log(log_details, "%p ZOOM_connection_connect async=%d", c, c->async);
638 task = ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
642 while (ZOOM_event(1, &c))
648 ZOOM_query_create(void)
650 ZOOM_query s = (ZOOM_query) xmalloc(sizeof(*s));
652 yaz_log(log_details, "%p ZOOM_query_create", s);
656 s->odr = odr_createmem(ODR_ENCODE);
663 ZOOM_query_destroy(ZOOM_query s)
669 yaz_log(log_details, "%p ZOOM_query_destroy count=%d", s, s->refcount);
670 if (s->refcount == 0)
678 ZOOM_query_prefix(ZOOM_query s, const char *str)
680 s->query_string = odr_strdup(s->odr, str);
681 s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
682 s->z_query->which = Z_Query_type_1;
683 s->z_query->u.type_1 = p_query_rpn(s->odr, str);
684 if (!s->z_query->u.type_1)
686 yaz_log(log_details, "%p ZOOM_query_prefix str=%s failed", s, str);
690 yaz_log(log_details, "%p ZOOM_query_prefix str=%s", s, str);
695 ZOOM_query_cql(ZOOM_query s, const char *str)
699 s->query_string = odr_strdup(s->odr, str);
701 ext = (Z_External *) odr_malloc(s->odr, sizeof(*ext));
702 ext->direct_reference = odr_oiddup(s->odr, yaz_oid_userinfo_cql);
703 ext->indirect_reference = 0;
705 ext->which = Z_External_CQL;
706 ext->u.cql = s->query_string;
708 s->z_query = (Z_Query *) odr_malloc(s->odr, sizeof(*s->z_query));
709 s->z_query->which = Z_Query_type_104;
710 s->z_query->u.type_104 = ext;
712 yaz_log(log_details, "%p ZOOM_query_cql str=%s", s, str);
718 * Translate the CQL string client-side into RPN which is passed to
719 * the server. This is useful for server's that don't themselves
720 * support CQL, for which ZOOM_query_cql() is useless. `conn' is used
721 * only as a place to stash diagnostics if compilation fails; if this
722 * information is not needed, a null pointer may be used.
725 ZOOM_query_cql2rpn(ZOOM_query s, const char *str, ZOOM_connection conn)
729 ZOOM_connection freeme = 0;
731 yaz_log(log_details, "%p ZOOM_query_cql2rpn str=%s conn=%p", s, str, conn);
733 conn = freeme = ZOOM_connection_create(0);
735 rpn = cql2pqf(conn, str);
737 ZOOM_connection_destroy(freeme);
741 ret = ZOOM_query_prefix(s, rpn);
747 * Analogous in every way to ZOOM_query_cql2rpn(), except that there
748 * is no analogous ZOOM_query_ccl() that just sends uninterpreted CCL
749 * to the server, as the YAZ GFS doesn't know how to handle this.
752 ZOOM_query_ccl2rpn(ZOOM_query s, const char *str, const char *config,
753 int *ccl_error, const char **error_string,
757 struct ccl_rpn_node *rpn;
758 CCL_bibset bibset = ccl_qual_mk();
761 ccl_qual_buf(bibset, config);
763 rpn = ccl_find_str(bibset, str, ccl_error, error_pos);
766 *error_string = ccl_err_msg(*ccl_error);
771 WRBUF wr = wrbuf_alloc();
774 ret = ZOOM_query_prefix(s, wrbuf_cstr(wr));
777 ccl_qual_rm(&bibset);
782 ZOOM_query_sortby(ZOOM_query s, const char *criteria)
784 s->sort_spec = yaz_sort_spec(s->odr, criteria);
787 yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s failed",
791 yaz_log(log_details, "%p ZOOM_query_sortby criteria=%s", s, criteria);
795 static zoom_ret do_write(ZOOM_connection c);
797 ZOOM_API(void) ZOOM_resultset_release(ZOOM_resultset r)
799 #if ZOOM_RESULT_LISTS
803 /* remove ourselves from the resultsets in connection */
804 ZOOM_resultset *rp = &r->connection->resultsets;
807 assert(*rp); /* we must be in this list!! */
809 { /* OK, we're here - take us out of it */
821 ZOOM_connection_destroy(ZOOM_connection c)
823 #if ZOOM_RESULT_LISTS
824 ZOOM_resultsets list;
830 yaz_log(log_api, "%p ZOOM_connection_destroy", c);
834 #if ZOOM_RESULT_LISTS
835 // Remove the connection's usage of resultsets
836 list = c->resultsets;
838 ZOOM_resultsets removed = list;
839 ZOOM_resultset_destroy(list->resultset);
844 for (r = c->resultsets; r; r = r->next)
851 odr_destroy(c->odr_in);
852 odr_destroy(c->odr_out);
855 odr_setprint(c->odr_print, 0); /* prevent destroy from fclose'ing */
856 odr_destroy(c->odr_print);
858 ZOOM_options_destroy(c->options);
859 ZOOM_connection_remove_tasks(c);
860 ZOOM_connection_remove_events(c);
866 xfree(c->cookie_out);
872 xfree(c->sru_version);
876 void ZOOM_resultset_addref(ZOOM_resultset r)
880 yaz_mutex_enter(r->mutex);
882 yaz_log(log_details, "%p ZOOM_resultset_addref count=%d",
884 yaz_mutex_leave(r->mutex);
888 ZOOM_resultset ZOOM_resultset_create(void)
891 ZOOM_resultset r = (ZOOM_resultset) xmalloc(sizeof(*r));
895 yaz_log(log_details, "%p ZOOM_resultset_create", r);
898 r->odr = odr_createmem(ODR_ENCODE);
903 for (i = 0; i<RECORD_HASH_SIZE; i++)
904 r->record_hash[i] = 0;
908 r->databaseNames = 0;
909 r->num_databaseNames = 0;
914 yaz_mutex_create(&r->mutex);
917 WRBUF w = wrbuf_alloc();
918 YAZ_SHPTR_INIT(r->record_wrbuf, w);
924 ZOOM_API(ZOOM_resultset)
925 ZOOM_connection_search_pqf(ZOOM_connection c, const char *q)
928 ZOOM_query s = ZOOM_query_create();
930 ZOOM_query_prefix(s, q);
932 r = ZOOM_connection_search(c, s);
933 ZOOM_query_destroy(s);
937 ZOOM_API(ZOOM_resultset)
938 ZOOM_connection_search(ZOOM_connection c, ZOOM_query q)
940 ZOOM_resultset r = ZOOM_resultset_create();
944 const char *syntax, *elementSetName;
945 #if ZOOM_RESULT_LISTS
949 yaz_log(log_api, "%p ZOOM_connection_search set %p query %p", c, r, q);
950 r->r_sort_spec = q->sort_spec;
953 r->options = ZOOM_options_create_with_parent(c->options);
955 start = ZOOM_options_get_int(r->options, "start", 0);
956 count = ZOOM_options_get_int(r->options, "count", 0);
958 /* If "presentChunk" is defined use that; otherwise "step" */
959 const char *cp = ZOOM_options_get(r->options, "presentChunk");
960 r->step = ZOOM_options_get_int(r->options,
961 (cp != 0 ? "presentChunk": "step"), 0);
963 r->piggyback = ZOOM_options_get_bool(r->options, "piggyback", 1);
964 cp = ZOOM_options_get(r->options, "setname");
966 r->setname = xstrdup(cp);
967 cp = ZOOM_options_get(r->options, "schema");
969 r->schema = xstrdup(cp);
971 r->databaseNames = set_DatabaseNames(c, c->options, &r->num_databaseNames,
976 #if ZOOM_RESULT_LISTS
977 yaz_log(log_details, "%p ZOOM_connection_search: Adding new resultset (%p) to resultsets (%p) ", c, r, c->resultsets);
978 set = xmalloc(sizeof(*set));
979 ZOOM_resultset_addref(r);
981 set->next = c->resultsets;
984 r->next = c->resultsets;
987 if (c->host_port && c->proto == PROTO_HTTP)
991 yaz_log(log_details, "ZOOM_connection_search: no comstack");
992 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
996 yaz_log(log_details, "ZOOM_connection_search: reconnect");
1001 task = ZOOM_connection_add_task(c, ZOOM_TASK_SEARCH);
1002 task->u.search.resultset = r;
1003 task->u.search.start = start;
1004 task->u.search.count = count;
1005 task->u.search.recv_search_fired = 0;
1007 syntax = ZOOM_options_get(r->options, "preferredRecordSyntax");
1008 task->u.search.syntax = syntax ? xstrdup(syntax) : 0;
1009 elementSetName = ZOOM_options_get(r->options, "elementSetName");
1010 task->u.search.elementSetName = elementSetName
1011 ? xstrdup(elementSetName) : 0;
1013 ZOOM_resultset_addref(r);
1019 while (ZOOM_event(1, &c))
1026 ZOOM_resultset_sort(ZOOM_resultset r,
1027 const char *sort_type, const char *sort_spec)
1029 (void) ZOOM_resultset_sort1(r, sort_type, sort_spec);
1033 ZOOM_resultset_sort1(ZOOM_resultset r,
1034 const char *sort_type, const char *sort_spec)
1036 ZOOM_connection c = r->connection;
1040 newq = ZOOM_query_create();
1041 if (ZOOM_query_sortby(newq, sort_spec) < 0)
1044 yaz_log(log_api, "%p ZOOM_resultset_sort r=%p sort_type=%s sort_spec=%s",
1045 r, r, sort_type, sort_spec);
1049 if (c->host_port && c->proto == PROTO_HTTP)
1053 yaz_log(log_details, "%p ZOOM_resultset_sort: no comstack", r);
1054 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1058 yaz_log(log_details, "%p ZOOM_resultset_sort: prepare reconnect",
1060 c->reconnect_ok = 1;
1064 ZOOM_resultset_cache_reset(r);
1065 task = ZOOM_connection_add_task(c, ZOOM_TASK_SORT);
1066 task->u.sort.resultset = r;
1067 task->u.sort.q = newq;
1069 ZOOM_resultset_addref(r);
1073 while (ZOOM_event(1, &c))
1080 static void ZOOM_record_release(ZOOM_record rec)
1086 if (rec->record_wrbuf)
1087 YAZ_SHPTR_DEC(rec->record_wrbuf, wrbuf_destroy);
1090 wrbuf_destroy(rec->wrbuf);
1094 odr_destroy(rec->odr);
1098 ZOOM_resultset_cache_reset(ZOOM_resultset r)
1101 for (i = 0; i<RECORD_HASH_SIZE; i++)
1103 ZOOM_record_cache rc;
1104 for (rc = r->record_hash[i]; rc; rc = rc->next)
1106 ZOOM_record_release(&rc->rec);
1108 r->record_hash[i] = 0;
1113 ZOOM_resultset_destroy(ZOOM_resultset r)
1115 resultset_destroy(r);
1118 static void resultset_destroy(ZOOM_resultset r)
1122 yaz_mutex_enter(r->mutex);
1124 yaz_log(log_details, "%p ZOOM_resultset_destroy r=%p count=%d",
1126 if (r->refcount == 0)
1128 yaz_mutex_leave(r->mutex);
1130 yaz_log(log_details, "%p ZOOM_connection resultset_destroy: Deleting resultset (%p) ", r->connection, r);
1131 ZOOM_resultset_cache_reset(r);
1132 ZOOM_resultset_release(r);
1133 ZOOM_query_destroy(r->query);
1134 ZOOM_options_destroy(r->options);
1135 odr_destroy(r->odr);
1138 yaz_mutex_destroy(&r->mutex);
1140 YAZ_SHPTR_DEC(r->record_wrbuf, wrbuf_destroy);
1145 yaz_mutex_leave(r->mutex);
1149 ZOOM_resultset_size(ZOOM_resultset r)
1151 yaz_log(log_details, "ZOOM_resultset_size r=%p count=" ODR_INT_PRINTF,
1156 static void do_close(ZOOM_connection c)
1161 ZOOM_connection_set_mask(c, 0);
1162 c->state = STATE_IDLE;
1165 static int ZOOM_test_reconnect(ZOOM_connection c)
1169 if (!c->reconnect_ok)
1172 c->reconnect_ok = 0;
1173 c->tasks->running = 0;
1174 ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
1176 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1177 ZOOM_connection_put_event(c, event);
1182 static void ZOOM_resultset_retrieve(ZOOM_resultset r,
1183 int force_sync, int start, int count)
1188 const char *syntax, *elementSetName;
1192 yaz_log(log_details, "%p ZOOM_resultset_retrieve force_sync=%d start=%d"
1193 " count=%d", r, force_sync, start, count);
1198 if (c->host_port && c->proto == PROTO_HTTP)
1202 yaz_log(log_details, "%p ZOOM_resultset_retrieve: no comstack", r);
1203 ZOOM_connection_add_task(c, ZOOM_TASK_CONNECT);
1207 yaz_log(log_details, "%p ZOOM_resultset_retrieve: prepare "
1209 c->reconnect_ok = 1;
1212 task = ZOOM_connection_add_task(c, ZOOM_TASK_RETRIEVE);
1213 task->u.retrieve.resultset = r;
1214 task->u.retrieve.start = start;
1215 task->u.retrieve.count = count;
1217 syntax = ZOOM_options_get(r->options, "preferredRecordSyntax");
1218 task->u.retrieve.syntax = syntax ? xstrdup(syntax) : 0;
1219 elementSetName = ZOOM_options_get(r->options, "elementSetName");
1220 task->u.retrieve.elementSetName = elementSetName
1221 ? xstrdup(elementSetName) : 0;
1223 cp = ZOOM_options_get(r->options, "schema");
1226 if (!r->schema || strcmp(r->schema, cp))
1229 r->schema = xstrdup(cp);
1233 ZOOM_resultset_addref(r);
1235 if (!r->connection->async || force_sync)
1236 while (r->connection && ZOOM_event(1, &r->connection))
1241 ZOOM_resultset_records(ZOOM_resultset r, ZOOM_record *recs,
1242 size_t start, size_t count)
1244 int force_present = 0;
1248 yaz_log(log_api, "%p ZOOM_resultset_records r=%p start=%ld count=%ld",
1249 r, r, (long) start, (long) count);
1252 ZOOM_resultset_retrieve(r, force_present, start, count);
1256 for (i = 0; i< count; i++)
1257 recs[i] = ZOOM_resultset_record_immediate(r, i+start);
1262 ZOOM_resultset_facets_size(ZOOM_resultset r) {
1263 return r->num_facets;
1266 ZOOM_API(ZOOM_facet_field)
1267 ZOOM_resultset_get_facet_field(ZOOM_resultset r, const char *name) {
1268 int num = r->num_facets;
1269 ZOOM_facet_field *facets = r->facets;
1271 for (index = 0; index < num; index++) {
1272 if (!strcmp(facets[index]->facet_name, name)) {
1273 return facets[index];
1280 ZOOM_API(ZOOM_facet_field *)
1281 ZOOM_resultset_facets(ZOOM_resultset r)
1286 ZOOM_API(const char**)
1287 ZOOM_resultset_facet_names(ZOOM_resultset r)
1289 return (const char **) r->facets_names;
1292 ZOOM_API(const char*)
1293 ZOOM_facet_field_name(ZOOM_facet_field field)
1295 return field->facet_name;
1299 ZOOM_facet_field_term_count(ZOOM_facet_field field)
1301 return field->num_terms;
1304 ZOOM_API(const char*)
1305 ZOOM_facet_field_get_term(ZOOM_facet_field field, size_t idx, int *freq) {
1306 *freq = field->facet_terms[idx].frequency;
1307 return field->facet_terms[idx].term;
1311 static void get_cert(ZOOM_connection c)
1316 if (cs_get_peer_certificate_x509(c->cs, &cert_buf, &cert_len))
1318 ZOOM_connection_option_setl(c, "sslPeerCert",
1319 cert_buf, cert_len);
1324 static zoom_ret do_connect_host(ZOOM_connection c,
1325 const char *effective_host,
1326 const char *logical_url);
1328 static zoom_ret do_connect(ZOOM_connection c)
1330 const char *effective_host;
1333 effective_host = c->proxy;
1335 effective_host = c->host_port;
1336 return do_connect_host(c, effective_host, c->host_port);
1339 static zoom_ret do_connect_host(ZOOM_connection c, const char *effective_host,
1340 const char *logical_url)
1344 yaz_log(log_details, "%p do_connect effective_host=%s", c, effective_host);
1348 c->cs = cs_create_host(effective_host, 0, &add);
1350 if (c->cs && c->cs->protocol == PROTO_HTTP)
1357 c->proto = PROTO_HTTP;
1358 cs_get_host_args(logical_url, &db);
1361 c->path = xmalloc(strlen(db) * 3 + 2);
1362 yaz_encode_sru_dbpath_buf(c->path, db);
1365 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_PROTOCOL, "SRW");
1367 return zoom_complete;
1372 int ret = cs_connect(c->cs, add);
1375 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
1376 ZOOM_connection_put_event(c, event);
1378 if (c->proto == PROTO_Z3950)
1379 ZOOM_connection_send_init(c);
1382 /* no init request for SRW .. */
1383 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1384 ZOOM_connection_remove_task(c);
1385 ZOOM_connection_set_mask(c, 0);
1386 ZOOM_connection_exec_task(c);
1388 c->state = STATE_ESTABLISHED;
1389 return zoom_pending;
1393 int mask = ZOOM_SELECT_EXCEPT;
1394 if (c->cs->io_pending & CS_WANT_WRITE)
1395 mask += ZOOM_SELECT_WRITE;
1396 if (c->cs->io_pending & CS_WANT_READ)
1397 mask += ZOOM_SELECT_READ;
1398 ZOOM_connection_set_mask(c, mask);
1399 c->state = STATE_CONNECTING;
1400 return zoom_pending;
1403 c->state = STATE_IDLE;
1404 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, logical_url);
1405 return zoom_complete;
1408 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
1411 for (i = 0; i<200; i++)
1415 Z_OtherInformation **oi;
1420 sprintf(buf, "otherInfo%d", i);
1421 val = ZOOM_options_get(c->options, buf);
1424 cp = strchr(val, ':');
1428 if (len >= sizeof(buf))
1429 len = sizeof(buf)-1;
1430 memcpy(buf, val, len);
1433 oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
1438 yaz_oi_APDU(a, &oi);
1439 yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
1443 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
1448 Z_OtherInformation **oi;
1449 yaz_oi_APDU(a, &oi);
1450 yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie,
1455 Z_OtherInformation **oi;
1456 yaz_oi_APDU(a, &oi);
1457 yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip,
1460 otherInfo_attach(c, a, out);
1461 if (!z_APDU(out, &a, 0, 0))
1463 FILE *outf = fopen("/tmp/apdu.txt", "a");
1466 ODR odr_pr = odr_createmem(ODR_PRINT);
1467 fprintf(outf, "a=%p\n", a);
1468 odr_setprint(odr_pr, outf);
1469 z_APDU(odr_pr, &a, 0, 0);
1470 odr_destroy(odr_pr);
1472 yaz_log(log_api, "%p encoding_APDU: encoding failed", c);
1473 set_ZOOM_error(c, ZOOM_ERROR_ENCODE, 0);
1478 z_APDU(c->odr_print, &a, 0, 0);
1479 yaz_log(log_details, "%p encoding_APDU encoding OK", c);
1483 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
1487 if (encode_APDU(c, a, c->odr_out))
1488 return zoom_complete;
1489 yaz_log(log_details, "%p send APDU type=%d", c, a->which);
1490 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1491 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1492 ZOOM_connection_put_event(c, event);
1493 odr_reset(c->odr_out);
1497 /* returns 1 if PDU was sent OK (still pending )
1498 0 if PDU was not sent OK (nothing to wait for)
1501 static zoom_ret ZOOM_connection_send_init(ZOOM_connection c)
1503 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
1504 Z_InitRequest *ireq = apdu->u.initRequest;
1505 Z_IdAuthentication *auth = (Z_IdAuthentication *)
1506 odr_malloc(c->odr_out, sizeof(*auth));
1508 ODR_MASK_SET(ireq->options, Z_Options_search);
1509 ODR_MASK_SET(ireq->options, Z_Options_present);
1510 ODR_MASK_SET(ireq->options, Z_Options_scan);
1511 ODR_MASK_SET(ireq->options, Z_Options_sort);
1512 ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
1513 ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
1515 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
1516 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
1517 ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
1519 ireq->implementationId =
1520 odr_prepend(c->odr_out,
1521 ZOOM_options_get(c->options, "implementationId"),
1522 ireq->implementationId);
1524 ireq->implementationName =
1525 odr_prepend(c->odr_out,
1526 ZOOM_options_get(c->options, "implementationName"),
1527 odr_prepend(c->odr_out, "ZOOM-C",
1528 ireq->implementationName));
1530 ireq->implementationVersion =
1531 odr_prepend(c->odr_out,
1532 ZOOM_options_get(c->options, "implementationVersion"),
1533 ireq->implementationVersion);
1535 *ireq->maximumRecordSize = c->maximum_record_size;
1536 *ireq->preferredMessageSize = c->preferred_message_size;
1538 if (c->group || c->password)
1540 Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
1541 pass->groupId = odr_strdup_null(c->odr_out, c->group);
1542 pass->userId = odr_strdup_null(c->odr_out, c->user);
1543 pass->password = odr_strdup_null(c->odr_out, c->password);
1544 auth->which = Z_IdAuthentication_idPass;
1545 auth->u.idPass = pass;
1546 ireq->idAuthentication = auth;
1550 auth->which = Z_IdAuthentication_open;
1551 auth->u.open = odr_strdup(c->odr_out, c->user);
1552 ireq->idAuthentication = auth;
1556 yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
1557 yaz_oid_userinfo_proxy, 1, c->host_port);
1559 if (c->charset || c->lang)
1561 Z_OtherInformation **oi;
1562 Z_OtherInformationUnit *oi_unit;
1564 yaz_oi_APDU(apdu, &oi);
1566 if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
1568 ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
1569 oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
1570 oi_unit->information.externallyDefinedInfo =
1571 yaz_set_proposal_charneg_list(c->odr_out, " ",
1572 c->charset, c->lang, 1);
1576 return send_APDU(c, apdu);
1580 static zoom_ret send_srw(ZOOM_connection c, Z_SRW_PDU *sr)
1584 const char *database = ZOOM_options_get(c->options, "databaseName");
1585 char *fdatabase = 0;
1588 fdatabase = yaz_encode_sru_dbpath_odr(c->odr_out, database);
1589 gdu = z_get_HTTP_Request_host_path(c->odr_out, c->host_port,
1590 fdatabase ? fdatabase : c->path);
1592 if (c->sru_mode == zoom_sru_get)
1594 yaz_sru_get_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1596 else if (c->sru_mode == zoom_sru_post)
1598 yaz_sru_post_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1600 else if (c->sru_mode == zoom_sru_soap)
1602 yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, c->odr_out, c->charset);
1604 if (!z_GDU(c->odr_out, &gdu, 0, 0))
1605 return zoom_complete;
1607 z_GDU(c->odr_print, &gdu, 0, 0);
1608 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
1610 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
1611 ZOOM_connection_put_event(c, event);
1612 odr_reset(c->odr_out);
1618 static Z_SRW_PDU *ZOOM_srw_get_pdu(ZOOM_connection c, int type)
1620 Z_SRW_PDU *sr = yaz_srw_get_pdu(c->odr_out, type, c->sru_version);
1621 sr->username = c->user;
1622 sr->password = c->password;
1628 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1632 ZOOM_resultset resultset = 0;
1634 const char *option_val = 0;
1636 if (c->error) /* don't continue on error */
1637 return zoom_complete;
1639 switch(c->tasks->which)
1641 case ZOOM_TASK_SEARCH:
1642 resultset = c->tasks->u.search.resultset;
1643 if (!resultset->setname)
1644 resultset->setname = xstrdup("default");
1645 ZOOM_options_set(resultset->options, "setname", resultset->setname);
1646 start = &c->tasks->u.search.start;
1647 count = &c->tasks->u.search.count;
1649 case ZOOM_TASK_RETRIEVE:
1650 resultset = c->tasks->u.retrieve.resultset;
1652 start = &c->tasks->u.retrieve.start;
1653 count = &c->tasks->u.retrieve.count;
1655 if (*start >= resultset->size)
1656 return zoom_complete;
1657 if (*start + *count > resultset->size)
1658 *count = resultset->size - *start;
1660 for (i = 0; i < *count; i++)
1663 record_cache_lookup(resultset, i + *start,
1664 c->tasks->u.retrieve.syntax,
1665 c->tasks->u.retrieve.elementSetName);
1670 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1671 ZOOM_connection_put_event(c, event);
1678 return zoom_complete;
1681 return zoom_complete;
1683 assert(resultset->query);
1685 sr = ZOOM_srw_get_pdu(c, Z_SRW_searchRetrieve_request);
1686 if (resultset->query->z_query->which == Z_Query_type_104
1687 && resultset->query->z_query->u.type_104->which == Z_External_CQL)
1689 sr->u.request->query_type = Z_SRW_query_type_cql;
1690 sr->u.request->query.cql =resultset->query->z_query->u.type_104->u.cql;
1692 else if (resultset->query->z_query->which == Z_Query_type_1 &&
1693 resultset->query->z_query->u.type_1)
1695 sr->u.request->query_type = Z_SRW_query_type_pqf;
1696 sr->u.request->query.pqf = resultset->query->query_string;
1700 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
1701 return zoom_complete;
1703 sr->u.request->startRecord = odr_intdup(c->odr_out, *start + 1);
1704 sr->u.request->maximumRecords = odr_intdup(
1705 c->odr_out, (resultset->step > 0 && resultset->step < *count) ?
1706 resultset->step : *count);
1707 sr->u.request->recordSchema = resultset->schema;
1709 option_val = ZOOM_resultset_option_get(resultset, "recordPacking");
1711 sr->u.request->recordPacking = odr_strdup(c->odr_out, option_val);
1713 option_val = ZOOM_resultset_option_get(resultset, "extraArgs");
1714 yaz_encode_sru_extra(sr, c->odr_out, option_val);
1715 return send_srw(c, sr);
1718 static zoom_ret ZOOM_connection_srw_send_search(ZOOM_connection c)
1720 return zoom_complete;
1724 static zoom_ret ZOOM_connection_send_search(ZOOM_connection c)
1727 int lslb, ssub, mspn;
1729 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
1730 Z_SearchRequest *search_req = apdu->u.searchRequest;
1731 const char *elementSetName;
1732 const char *smallSetElementSetName;
1733 const char *mediumSetElementSetName;
1737 assert(c->tasks->which == ZOOM_TASK_SEARCH);
1739 r = c->tasks->u.search.resultset;
1741 yaz_log(log_details, "%p ZOOM_connection_send_search set=%p", c, r);
1744 ZOOM_options_get(r->options, "elementSetName");
1745 smallSetElementSetName =
1746 ZOOM_options_get(r->options, "smallSetElementSetName");
1747 mediumSetElementSetName =
1748 ZOOM_options_get(r->options, "mediumSetElementSetName");
1750 if (!smallSetElementSetName)
1751 smallSetElementSetName = elementSetName;
1753 if (!mediumSetElementSetName)
1754 mediumSetElementSetName = elementSetName;
1756 facets = ZOOM_options_get(r->options, "facets");
1758 Z_FacetList *facet_list = yaz_pqf_parse_facet_list(c->odr_out, facets);
1760 Z_OtherInformation **oi;
1761 yaz_oi_APDU(apdu, &oi);
1763 yaz_oi_set_facetlist(oi, c->odr_out, facet_list);
1771 /* prepare query for the search request */
1772 search_req->query = r->query->z_query;
1773 if (!search_req->query)
1775 set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1776 return zoom_complete;
1778 if (r->query->z_query->which == Z_Query_type_1 ||
1779 r->query->z_query->which == Z_Query_type_101)
1781 const char *cp = ZOOM_options_get(r->options, "rpnCharset");
1784 yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
1788 search_req->query = yaz_copy_Z_Query(search_req->query,
1791 r = yaz_query_charset_convert_rpnquery_check(
1792 search_req->query->u.type_1,
1794 yaz_iconv_close(cd);
1796 { /* query could not be char converted */
1797 set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
1798 return zoom_complete;
1803 search_req->databaseNames = r->databaseNames;
1804 search_req->num_databaseNames = r->num_databaseNames;
1806 /* get syntax (no need to provide unless piggyback is in effect) */
1807 syntax = c->tasks->u.search.syntax;
1809 lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
1810 ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
1811 mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
1812 if (lslb != -1 && ssub != -1 && mspn != -1)
1814 /* So're a Z39.50 expert? Let's hope you don't do sort */
1815 *search_req->largeSetLowerBound = lslb;
1816 *search_req->smallSetUpperBound = ssub;
1817 *search_req->mediumSetPresentNumber = mspn;
1819 else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
1820 && r->piggyback && !r->r_sort_spec && !r->schema)
1822 /* Regular piggyback - do it unless we're going to do sort */
1823 *search_req->largeSetLowerBound = 2000000000;
1824 *search_req->smallSetUpperBound = 1;
1825 *search_req->mediumSetPresentNumber =
1826 r->step>0 ? r->step : c->tasks->u.search.count;
1830 /* non-piggyback. Need not provide elementsets or syntaxes .. */
1831 smallSetElementSetName = 0;
1832 mediumSetElementSetName = 0;
1835 if (smallSetElementSetName && *smallSetElementSetName)
1837 Z_ElementSetNames *esn = (Z_ElementSetNames *)
1838 odr_malloc(c->odr_out, sizeof(*esn));
1840 esn->which = Z_ElementSetNames_generic;
1841 esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
1842 search_req->smallSetElementSetNames = esn;
1844 if (mediumSetElementSetName && *mediumSetElementSetName)
1846 Z_ElementSetNames *esn =(Z_ElementSetNames *)
1847 odr_malloc(c->odr_out, sizeof(*esn));
1849 esn->which = Z_ElementSetNames_generic;
1850 esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
1851 search_req->mediumSetElementSetNames = esn;
1854 search_req->preferredRecordSyntax =
1855 zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1859 if (c->support_named_resultsets)
1863 /* find the lowest unused ordinal so that we re-use
1864 result sets on the server. */
1865 for (ord = 1; ; ord++)
1867 #if ZOOM_RESULT_LISTS
1868 ZOOM_resultsets rsp;
1869 sprintf(setname, "%d", ord);
1870 for (rsp = c->resultsets; rsp; rsp = rsp->next)
1871 if (rsp->resultset->setname && !strcmp(rsp->resultset->setname, setname))
1877 sprintf(setname, "%d", ord);
1878 for (rp = c->resultsets; rp; rp = rp->next)
1879 if (rp->setname && !strcmp(rp->setname, setname))
1886 r->setname = xstrdup(setname);
1887 yaz_log(log_details, "%p ZOOM_connection_send_search: allocating "
1888 "set %s", c, r->setname);
1892 yaz_log(log_details, "%p ZOOM_connection_send_search: using "
1894 r->setname = xstrdup("default");
1896 ZOOM_options_set(r->options, "setname", r->setname);
1898 search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
1899 return send_APDU(c, apdu);
1902 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
1904 char oid_name_buf[OID_STR_MAX];
1905 const char *oid_name;
1908 oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
1911 case Z_DefaultDiagFormat_v2Addinfo:
1912 addinfo = r->u.v2Addinfo;
1914 case Z_DefaultDiagFormat_v3Addinfo:
1915 addinfo = r->u.v3Addinfo;
1920 set_dset_error(c, *r->condition, oid_name, addinfo, 0);
1923 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
1925 if (p->which != Z_DiagRec_defaultFormat)
1926 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
1928 response_default_diag(c, p->u.defaultFormat);
1931 ZOOM_API(ZOOM_record)
1932 ZOOM_record_clone(ZOOM_record srec)
1939 odr_enc = odr_createmem(ODR_ENCODE);
1940 if (!z_NamePlusRecord(odr_enc, &srec->npr, 0, 0))
1942 buf = odr_getbuf(odr_enc, &size, 0);
1944 nrec = (ZOOM_record) xmalloc(sizeof(*nrec));
1945 yaz_log(log_details, "ZOOM_record create");
1946 nrec->odr = odr_createmem(ODR_DECODE);
1948 nrec->record_wrbuf = 0;
1952 odr_setbuf(nrec->odr, buf, size, 0);
1953 z_NamePlusRecord(nrec->odr, &nrec->npr, 0, 0);
1955 nrec->schema = odr_strdup_null(nrec->odr, srec->schema);
1956 nrec->diag_uri = odr_strdup_null(nrec->odr, srec->diag_uri);
1957 nrec->diag_message = odr_strdup_null(nrec->odr, srec->diag_message);
1958 nrec->diag_details = odr_strdup_null(nrec->odr, srec->diag_details);
1959 nrec->diag_set = odr_strdup_null(nrec->odr, srec->diag_set);
1960 odr_destroy(odr_enc);
1964 ZOOM_API(ZOOM_record)
1965 ZOOM_resultset_record_immediate(ZOOM_resultset s,size_t pos)
1967 const char *syntax =
1968 ZOOM_options_get(s->options, "preferredRecordSyntax");
1969 const char *elementSetName =
1970 ZOOM_options_get(s->options, "elementSetName");
1972 return record_cache_lookup(s, pos, syntax, elementSetName);
1975 ZOOM_API(ZOOM_record)
1976 ZOOM_resultset_record(ZOOM_resultset r, size_t pos)
1978 ZOOM_record rec = ZOOM_resultset_record_immediate(r, pos);
1983 * MIKE: I think force_sync should always be zero, but I don't
1984 * want to make this change until I get the go-ahead from
1985 * Adam, in case something depends on the old synchronous
1989 if (getenv("ZOOM_RECORD_NO_FORCE_SYNC")) force_sync = 0;
1990 ZOOM_resultset_retrieve(r, force_sync, pos, 1);
1991 rec = ZOOM_resultset_record_immediate(r, pos);
1997 ZOOM_record_destroy(ZOOM_record rec)
1999 ZOOM_record_release(rec);
2000 yaz_log(log_details, "ZOOM_record destroy");
2005 static yaz_iconv_t iconv_create_charset(const char *record_charset)
2012 strcpy(to, "UTF-8");
2013 if (record_charset && *record_charset)
2015 /* Use "from,to" or just "from" */
2016 const char *cp = strchr(record_charset, ',');
2017 size_t clen = strlen(record_charset);
2020 strncpy( to, cp+1, sizeof(to)-1);
2021 to[sizeof(to)-1] = '\0';
2022 clen = cp - record_charset;
2024 if (clen > sizeof(from)-1)
2025 clen = sizeof(from)-1;
2028 strncpy(from, record_charset, clen);
2032 cd = yaz_iconv_open(to, from);
2036 static const char *return_marc_record(WRBUF wrbuf,
2039 const char *buf, int sz,
2040 const char *record_charset)
2042 yaz_iconv_t cd = iconv_create_charset(record_charset);
2043 yaz_marc_t mt = yaz_marc_create();
2044 const char *ret_string = 0;
2047 yaz_marc_iconv(mt, cd);
2048 yaz_marc_xml(mt, marc_type);
2049 if (yaz_marc_decode_wrbuf(mt, buf, sz, wrbuf) > 0)
2052 *len = wrbuf_len(wrbuf);
2053 ret_string = wrbuf_cstr(wrbuf);
2055 yaz_marc_destroy(mt);
2057 yaz_iconv_close(cd);
2061 static const char *return_opac_record(WRBUF wrbuf,
2064 Z_OPACRecord *opac_rec,
2065 const char *record_charset)
2067 yaz_iconv_t cd = iconv_create_charset(record_charset);
2068 yaz_marc_t mt = yaz_marc_create();
2071 yaz_marc_iconv(mt, cd);
2072 yaz_marc_xml(mt, marc_type);
2074 yaz_opac_decode_wrbuf(mt, opac_rec, wrbuf);
2075 yaz_marc_destroy(mt);
2078 yaz_iconv_close(cd);
2080 *len = wrbuf_len(wrbuf);
2081 return wrbuf_cstr(wrbuf);
2084 static const char *return_string_record(WRBUF wrbuf,
2086 const char *buf, int sz,
2087 const char *record_charset)
2089 yaz_iconv_t cd = iconv_create_charset(record_charset);
2093 wrbuf_iconv_write(wrbuf, cd, buf, sz);
2094 wrbuf_iconv_reset(wrbuf, cd);
2096 buf = wrbuf_cstr(wrbuf);
2097 sz = wrbuf_len(wrbuf);
2098 yaz_iconv_close(cd);
2105 static const char *return_record_wrbuf(WRBUF wrbuf, int *len,
2106 Z_NamePlusRecord *npr,
2107 int marctype, const char *charset)
2109 Z_External *r = (Z_External *) npr->u.databaseRecord;
2110 const Odr_oid *oid = r->direct_reference;
2112 wrbuf_rewind(wrbuf);
2113 /* render bibliographic record .. */
2114 if (r->which == Z_External_OPAC)
2116 return return_opac_record(wrbuf, marctype, len,
2117 r->u.opac, charset);
2119 if (r->which == Z_External_sutrs)
2120 return return_string_record(wrbuf, len,
2121 (char*) r->u.sutrs->buf,
2124 else if (r->which == Z_External_octet)
2126 if (yaz_oid_is_iso2709(oid))
2128 const char *ret_buf = return_marc_record(
2129 wrbuf, marctype, len,
2130 (const char *) r->u.octet_aligned->buf,
2131 r->u.octet_aligned->len,
2135 /* bad ISO2709. Return fail unless raw (ISO2709) is wanted */
2136 if (marctype != YAZ_MARC_ISO2709)
2139 return return_string_record(wrbuf, len,
2140 (const char *) r->u.octet_aligned->buf,
2141 r->u.octet_aligned->len,
2144 else if (r->which == Z_External_grs1)
2146 yaz_display_grs1(wrbuf, r->u.grs1, 0);
2147 return return_string_record(wrbuf, len,
2156 ZOOM_record_error(ZOOM_record rec, const char **cp,
2157 const char **addinfo, const char **diagset)
2159 Z_NamePlusRecord *npr;
2168 *cp = rec->diag_message;
2170 *addinfo = rec->diag_details;
2172 *diagset = rec->diag_set;
2173 return uri_to_code(rec->diag_uri);
2175 if (npr && npr->which == Z_NamePlusRecord_surrogateDiagnostic)
2177 Z_DiagRec *diag_rec = npr->u.surrogateDiagnostic;
2178 int error = YAZ_BIB1_UNSPECIFIED_ERROR;
2179 const char *add = 0;
2181 if (diag_rec->which == Z_DiagRec_defaultFormat)
2183 Z_DefaultDiagFormat *ddf = diag_rec->u.defaultFormat;
2186 error = *ddf->condition;
2189 case Z_DefaultDiagFormat_v2Addinfo:
2190 add = ddf->u.v2Addinfo;
2192 case Z_DefaultDiagFormat_v3Addinfo:
2193 add = ddf->u.v3Addinfo;
2198 yaz_oid_to_string(yaz_oid_std(),
2199 ddf->diagnosticSetId, &oclass);
2207 *addinfo = add ? add : "";
2209 *cp = diagbib1_str(error);
2215 static const char *get_record_format(WRBUF wrbuf, int *len,
2216 Z_NamePlusRecord *npr,
2217 int marctype, const char *charset,
2220 const char *res = return_record_wrbuf(wrbuf, len, npr, marctype, charset);
2222 if (*format == '1' && len)
2224 /* try to XML format res */
2226 xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
2227 doc = xmlParseMemory(res, *len);
2232 xmlDocDumpFormatMemory(doc, &xml_mem, &xml_size, 1);
2233 wrbuf_rewind(wrbuf);
2234 wrbuf_write(wrbuf, (const char *) xml_mem, xml_size);
2237 res = wrbuf_cstr(wrbuf);
2238 *len = wrbuf_len(wrbuf);
2246 static const char *npr_format(Z_NamePlusRecord *npr, const char *schema,
2248 const char *type_spec, int *len)
2254 const char *cp = type_spec;
2256 for (i = 0; cp[i] && cp[i] != ';' && cp[i] != ' ' && i < sizeof(type)-1;
2264 while (cp[i] == ' ')
2269 while (cp[i] == ' ')
2271 if (!strncmp(cp + i, "charset=", 8))
2274 i = i + 8; /* skip charset= */
2275 for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2277 if (j < sizeof(charset)-1)
2278 charset[j++] = cp[i];
2282 else if (!strncmp(cp + i, "format=", 7))
2286 for (j = 0; cp[i] && cp[i] != ';' && cp[i] != ' '; i++)
2288 if (j < sizeof(format)-1)
2289 format[j++] = cp[i];
2294 if (!strcmp(type, "database"))
2297 *len = (npr->databaseName ? strlen(npr->databaseName) : 0);
2298 return npr->databaseName;
2300 else if (!strcmp(type, "schema"))
2303 *len = schema ? strlen(schema) : 0;
2306 else if (!strcmp(type, "syntax"))
2308 const char *desc = 0;
2309 if (npr->which == Z_NamePlusRecord_databaseRecord)
2311 Z_External *r = (Z_External *) npr->u.databaseRecord;
2312 desc = yaz_oid_to_string(yaz_oid_std(), r->direct_reference, 0);
2317 *len = strlen(desc);
2320 if (npr->which != Z_NamePlusRecord_databaseRecord)
2323 /* from now on - we have a database record .. */
2324 if (!strcmp(type, "render"))
2326 return get_record_format(wrbuf, len, npr, YAZ_MARC_LINE, charset, format);
2328 else if (!strcmp(type, "xml"))
2330 return get_record_format(wrbuf, len, npr, YAZ_MARC_MARCXML, charset,
2333 else if (!strcmp(type, "txml"))
2335 return get_record_format(wrbuf, len, npr, YAZ_MARC_TURBOMARC, charset,
2338 else if (!strcmp(type, "raw"))
2340 return get_record_format(wrbuf, len, npr, YAZ_MARC_ISO2709, charset,
2343 else if (!strcmp(type, "ext"))
2346 return (const char *) npr->u.databaseRecord;
2348 else if (!strcmp(type, "opac"))
2350 if (npr->u.databaseRecord->which == Z_External_OPAC)
2351 return get_record_format(wrbuf, len, npr, YAZ_MARC_MARCXML, charset,
2357 ZOOM_API(const char *)
2358 ZOOM_record_get(ZOOM_record rec, const char *type_spec, int *len)
2363 *len = 0; /* default return */
2365 if (!rec || !rec->npr)
2369 if (!rec->record_wrbuf)
2371 WRBUF w = wrbuf_alloc();
2372 YAZ_SHPTR_INIT(rec->record_wrbuf, w);
2374 wrbuf = rec->record_wrbuf->ptr;
2377 rec->wrbuf = wrbuf_alloc();
2380 return npr_format(rec->npr, rec->schema, wrbuf, type_spec, len);
2383 static int strcmp_null(const char *v1, const char *v2)
2389 return strcmp(v1, v2);
2392 static size_t record_hash(int pos)
2396 return pos % RECORD_HASH_SIZE;
2399 static void record_cache_add(ZOOM_resultset r, Z_NamePlusRecord *npr,
2401 const char *syntax, const char *elementSetName,
2403 Z_SRW_diagnostic *diag)
2405 ZOOM_record_cache rc = 0;
2407 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2408 ZOOM_connection_put_event(r->connection, event);
2410 for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2413 && strcmp_null(r->schema, rc->schema) == 0
2414 && strcmp_null(elementSetName,rc->elementSetName) == 0
2415 && strcmp_null(syntax, rc->syntax) == 0)
2420 rc = (ZOOM_record_cache) odr_malloc(r->odr, sizeof(*rc));
2423 YAZ_SHPTR_INC(r->record_wrbuf);
2424 rc->rec.record_wrbuf = r->record_wrbuf;
2428 rc->elementSetName = odr_strdup_null(r->odr, elementSetName);
2430 rc->syntax = odr_strdup_null(r->odr, syntax);
2432 rc->schema = odr_strdup_null(r->odr, r->schema);
2435 rc->next = r->record_hash[record_hash(pos)];
2436 r->record_hash[record_hash(pos)] = rc;
2439 rc->rec.schema = odr_strdup_null(r->odr, schema);
2440 rc->rec.diag_set = 0;
2441 rc->rec.diag_uri = 0;
2442 rc->rec.diag_message = 0;
2443 rc->rec.diag_details = 0;
2449 rc->rec.diag_set = odr_strdup(r->odr, diag->uri);
2450 if ((cp = strrchr(rc->rec.diag_set, '/')))
2452 rc->rec.diag_uri = odr_strdup(r->odr, diag->uri);
2454 rc->rec.diag_message = odr_strdup_null(r->odr, diag->message);
2455 rc->rec.diag_details = odr_strdup_null(r->odr, diag->details);
2459 static ZOOM_record record_cache_lookup(ZOOM_resultset r, int pos,
2461 const char *elementSetName)
2463 ZOOM_record_cache rc;
2465 for (rc = r->record_hash[record_hash(pos)]; rc; rc = rc->next)
2469 if (strcmp_null(r->schema, rc->schema))
2471 if (strcmp_null(elementSetName,rc->elementSetName))
2473 if (strcmp_null(syntax, rc->syntax))
2481 static void handle_records(ZOOM_connection c, Z_Records *sr,
2484 ZOOM_resultset resultset;
2486 const char *syntax = 0, *elementSetName = 0;
2490 switch (c->tasks->which)
2492 case ZOOM_TASK_SEARCH:
2493 resultset = c->tasks->u.search.resultset;
2494 start = &c->tasks->u.search.start;
2495 count = &c->tasks->u.search.count;
2496 syntax = c->tasks->u.search.syntax;
2497 elementSetName = c->tasks->u.search.elementSetName;
2499 case ZOOM_TASK_RETRIEVE:
2500 resultset = c->tasks->u.retrieve.resultset;
2501 start = &c->tasks->u.retrieve.start;
2502 count = &c->tasks->u.retrieve.count;
2503 syntax = c->tasks->u.retrieve.syntax;
2504 elementSetName = c->tasks->u.retrieve.elementSetName;
2509 if (sr && sr->which == Z_Records_NSD)
2510 response_default_diag(c, sr->u.nonSurrogateDiagnostic);
2511 else if (sr && sr->which == Z_Records_multipleNSD)
2513 if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
2514 response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
2516 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
2520 if (*count + *start > resultset->size)
2521 *count = resultset->size - *start;
2524 if (sr && sr->which == Z_Records_DBOSD)
2527 NMEM nmem = odr_extract_mem(c->odr_in);
2528 Z_NamePlusRecordList *p =
2529 sr->u.databaseOrSurDiagnostics;
2530 for (i = 0; i<p->num_records; i++)
2532 record_cache_add(resultset, p->records[i], i + *start,
2533 syntax, elementSetName,
2540 yaz_log(log_details,
2541 "handle_records resultset=%p start=%d count=%d",
2542 resultset, *start, *count);
2544 /* transfer our response to search_nmem .. we need it later */
2545 nmem_transfer(odr_getmem(resultset->odr), nmem);
2547 if (present_phase && p->num_records == 0)
2549 /* present response and we didn't get any records! */
2550 Z_NamePlusRecord *myrec =
2551 zget_surrogateDiagRec(
2553 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2554 "ZOOM C generated. Present phase and no records");
2555 record_cache_add(resultset, myrec, *start,
2556 syntax, elementSetName, 0, 0);
2559 else if (present_phase)
2561 /* present response and we didn't get any records! */
2562 Z_NamePlusRecord *myrec =
2563 zget_surrogateDiagRec(
2565 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
2566 "ZOOM C generated: Present response and no records");
2567 record_cache_add(resultset, myrec, *start, syntax, elementSetName,
2573 static void handle_present_response(ZOOM_connection c, Z_PresentResponse *pr)
2575 handle_records(c, pr->records, 1);
2578 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
2581 switch (term->which)
2583 case Z_Term_general:
2584 ZOOM_options_setl(opt, name,
2585 (const char *)(term->u.general->buf),
2586 term->u.general->len);
2588 case Z_Term_characterString:
2589 ZOOM_options_set(opt, name, term->u.characterString);
2591 case Z_Term_numeric:
2592 ZOOM_options_set_int(opt, name, *term->u.numeric);
2597 static void handle_queryExpression(ZOOM_options opt, const char *name,
2598 Z_QueryExpression *exp)
2604 case Z_QueryExpression_term:
2605 if (exp->u.term && exp->u.term->queryTerm)
2607 sprintf(opt_name, "%s.term", name);
2608 handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
2611 case Z_QueryExpression_query:
2616 static void handle_search_result(ZOOM_connection c, ZOOM_resultset resultset,
2617 Z_OtherInformation *o)
2620 for (i = 0; o && i < o->num_elements; i++)
2622 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2624 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2626 if (ext->which == Z_External_searchResult1)
2629 Z_SearchInfoReport *sr = ext->u.searchResult1;
2632 ZOOM_options_set_int(
2633 resultset->options, "searchresult.size", sr->num);
2635 for (j = 0; j < sr->num; j++)
2637 Z_SearchInfoReport_s *ent =
2638 ext->u.searchResult1->elements[j];
2641 sprintf(pref, "searchresult.%d", j);
2643 if (ent->subqueryId)
2646 sprintf(opt_name, "%s.id", pref);
2647 ZOOM_options_set(resultset->options, opt_name,
2650 if (ent->subqueryExpression)
2653 sprintf(opt_name, "%s.subquery", pref);
2654 handle_queryExpression(resultset->options, opt_name,
2655 ent->subqueryExpression);
2657 if (ent->subqueryInterpretation)
2660 sprintf(opt_name, "%s.interpretation", pref);
2661 handle_queryExpression(resultset->options, opt_name,
2662 ent->subqueryInterpretation);
2664 if (ent->subqueryRecommendation)
2667 sprintf(opt_name, "%s.recommendation", pref);
2668 handle_queryExpression(resultset->options, opt_name,
2669 ent->subqueryRecommendation);
2671 if (ent->subqueryCount)
2674 sprintf(opt_name, "%s.count", pref);
2675 ZOOM_options_set_int(resultset->options, opt_name,
2676 *ent->subqueryCount);
2684 static char *get_term_cstr(ODR odr, Z_Term *term) {
2686 switch (term->which) {
2687 case Z_Term_general:
2688 return odr_strdupn(odr, (const char *) term->u.general->buf, (size_t) term->u.general->len);
2690 case Z_Term_characterString:
2691 return odr_strdup(odr, term->u.characterString);
2696 static ZOOM_facet_field get_zoom_facet_field(ODR odr, Z_FacetField *facet) {
2698 struct yaz_facet_attr attr_values;
2699 ZOOM_facet_field facet_field = odr_malloc(odr, sizeof(*facet_field));
2700 yaz_facet_attr_init(&attr_values);
2701 yaz_facet_attr_get_z_attributes(facet->attributes, &attr_values);
2702 facet_field->facet_name = odr_strdup(odr, attr_values.useattr);
2703 facet_field->num_terms = facet->num_terms;
2704 yaz_log(YLOG_DEBUG, "ZOOM_facet_field %s %d terms %d", attr_values.useattr, attr_values.limit, facet->num_terms);
2705 facet_field->facet_terms = odr_malloc(odr, facet_field->num_terms * sizeof(*facet_field->facet_terms));
2706 for (term_index = 0 ; term_index < facet->num_terms; term_index++) {
2707 Z_FacetTerm *facetTerm = facet->terms[term_index];
2708 facet_field->facet_terms[term_index].frequency = *facetTerm->count;
2709 facet_field->facet_terms[term_index].term = get_term_cstr(odr, facetTerm->term);
2710 yaz_log(YLOG_DEBUG, " term[%d] %s %d",
2711 term_index, facet_field->facet_terms[term_index].term, facet_field->facet_terms[term_index].frequency);
2716 static void handle_facet_result(ZOOM_connection c, ZOOM_resultset r,
2717 Z_OtherInformation *o)
2720 for (i = 0; o && i < o->num_elements; i++)
2722 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
2724 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
2725 if (ext->which == Z_External_userFacets)
2728 Z_FacetList *fl = ext->u.facetList;
2729 r->num_facets = fl->num;
2730 yaz_log(YLOG_DEBUG, "Facets found: %d", fl->num);
2731 r->facets = odr_malloc(r->odr, r->num_facets * sizeof(*r->facets));
2732 r->facets_names = odr_malloc(r->odr, r->num_facets * sizeof(*r->facets_names));
2733 for (j = 0; j < fl->num; j++)
2735 r->facets[j] = get_zoom_facet_field(r->odr, fl->elements[j]);
2737 yaz_log(YLOG_DEBUG, "Facet field missing on index %d !", j);
2738 r->facets_names[j] = (char *) ZOOM_facet_field_name(r->facets[j]);
2746 static void handle_search_response(ZOOM_connection c, Z_SearchResponse *sr)
2748 ZOOM_resultset resultset;
2751 if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
2754 event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
2755 ZOOM_connection_put_event(c, event);
2757 resultset = c->tasks->u.search.resultset;
2759 if (sr->resultSetStatus)
2761 ZOOM_options_set_int(resultset->options, "resultSetStatus",
2762 *sr->resultSetStatus);
2764 if (sr->presentStatus)
2766 ZOOM_options_set_int(resultset->options, "presentStatus",
2767 *sr->presentStatus);
2769 handle_search_result(c, resultset, sr->additionalSearchInfo);
2771 handle_facet_result(c, resultset, sr->additionalSearchInfo);
2773 resultset->size = *sr->resultCount;
2774 handle_records(c, sr->records, 0);
2777 static void sort_response(ZOOM_connection c, Z_SortResponse *res)
2779 if (res->diagnostics && res->num_diagnostics > 0)
2780 response_diag(c, res->diagnostics[0]);
2783 static int scan_response(ZOOM_connection c, Z_ScanResponse *res)
2785 NMEM nmem = odr_extract_mem(c->odr_in);
2788 if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
2790 scan = c->tasks->u.scan.scan;
2792 if (res->entries && res->entries->nonsurrogateDiagnostics)
2793 response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
2794 scan->scan_response = res;
2795 scan->srw_scan_response = 0;
2796 nmem_transfer(odr_getmem(scan->odr), nmem);
2798 ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
2799 if (res->positionOfTerm)
2800 ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
2801 if (res->scanStatus)
2802 ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
2803 if (res->numberOfEntriesReturned)
2804 ZOOM_options_set_int(scan->options, "number",
2805 *res->numberOfEntriesReturned);
2810 static zoom_ret send_sort(ZOOM_connection c,
2811 ZOOM_resultset resultset)
2814 resultset->r_sort_spec = 0;
2815 if (resultset->r_sort_spec)
2817 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
2818 Z_SortRequest *req = apdu->u.sortRequest;
2820 req->num_inputResultSetNames = 1;
2821 req->inputResultSetNames = (Z_InternationalString **)
2822 odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
2823 req->inputResultSetNames[0] =
2824 odr_strdup(c->odr_out, resultset->setname);
2825 req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
2826 req->sortSequence = resultset->r_sort_spec;
2827 resultset->r_sort_spec = 0;
2828 return send_APDU(c, apdu);
2830 return zoom_complete;
2833 static zoom_ret send_present(ZOOM_connection c)
2836 Z_PresentRequest *req = 0;
2838 const char *syntax = 0;
2839 const char *elementSetName = 0;
2840 ZOOM_resultset resultset;
2845 yaz_log(log_details, "%p send_present no tasks", c);
2846 return zoom_complete;
2849 switch (c->tasks->which)
2851 case ZOOM_TASK_SEARCH:
2852 resultset = c->tasks->u.search.resultset;
2853 start = &c->tasks->u.search.start;
2854 count = &c->tasks->u.search.count;
2855 syntax = c->tasks->u.search.syntax;
2856 elementSetName = c->tasks->u.search.elementSetName;
2858 case ZOOM_TASK_RETRIEVE:
2859 resultset = c->tasks->u.retrieve.resultset;
2860 start = &c->tasks->u.retrieve.start;
2861 count = &c->tasks->u.retrieve.count;
2862 syntax = c->tasks->u.retrieve.syntax;
2863 elementSetName = c->tasks->u.retrieve.elementSetName;
2866 return zoom_complete;
2868 yaz_log(log_details, "%p send_present start=%d count=%d",
2871 if (*start < 0 || *count < 0 || *start + *count > resultset->size)
2873 set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
2876 if (c->error) /* don't continue on error */
2877 return zoom_complete;
2878 yaz_log(log_details, "send_present resultset=%p start=%d count=%d",
2879 resultset, *start, *count);
2881 for (i = 0; i < *count; i++)
2884 record_cache_lookup(resultset, i + *start, syntax, elementSetName);
2889 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
2890 ZOOM_connection_put_event(c, event);
2898 yaz_log(log_details, "%p send_present skip=%d no more to fetch", c, i);
2899 return zoom_complete;
2902 apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
2903 req = apdu->u.presentRequest;
2906 yaz_log(log_details, "%p send_present skip=%d", c, i);
2908 *req->resultSetStartPoint = *start + 1;
2910 if (resultset->step > 0 && resultset->step < *count)
2911 *req->numberOfRecordsRequested = resultset->step;
2913 *req->numberOfRecordsRequested = *count;
2915 if (*req->numberOfRecordsRequested + *start > resultset->size)
2916 *req->numberOfRecordsRequested = resultset->size - *start;
2917 assert(*req->numberOfRecordsRequested > 0);
2919 if (syntax && *syntax)
2920 req->preferredRecordSyntax =
2921 zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
2923 if (resultset->schema && *resultset->schema)
2925 Z_RecordComposition *compo = (Z_RecordComposition *)
2926 odr_malloc(c->odr_out, sizeof(*compo));
2928 req->recordComposition = compo;
2929 compo->which = Z_RecordComp_complex;
2930 compo->u.complex = (Z_CompSpec *)
2931 odr_malloc(c->odr_out, sizeof(*compo->u.complex));
2932 compo->u.complex->selectAlternativeSyntax = (bool_t *)
2933 odr_malloc(c->odr_out, sizeof(bool_t));
2934 *compo->u.complex->selectAlternativeSyntax = 0;
2936 compo->u.complex->generic = (Z_Specification *)
2937 odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
2939 compo->u.complex->generic->which = Z_Schema_oid;
2940 compo->u.complex->generic->schema.oid = (Odr_oid *)
2941 zoom_yaz_str_to_z3950oid (c, CLASS_SCHEMA, resultset->schema);
2943 if (!compo->u.complex->generic->schema.oid)
2945 /* OID wasn't a schema! Try record syntax instead. */
2947 compo->u.complex->generic->schema.oid = (Odr_oid *)
2948 zoom_yaz_str_to_z3950oid (c, CLASS_RECSYN, resultset->schema);
2950 if (elementSetName && *elementSetName)
2952 compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
2953 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
2954 compo->u.complex->generic->elementSpec->which =
2955 Z_ElementSpec_elementSetName;
2956 compo->u.complex->generic->elementSpec->u.elementSetName =
2957 odr_strdup(c->odr_out, elementSetName);
2960 compo->u.complex->generic->elementSpec = 0;
2961 compo->u.complex->num_dbSpecific = 0;
2962 compo->u.complex->dbSpecific = 0;
2963 compo->u.complex->num_recordSyntax = 0;
2964 compo->u.complex->recordSyntax = 0;
2966 else if (elementSetName && *elementSetName)
2968 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2969 odr_malloc(c->odr_out, sizeof(*esn));
2970 Z_RecordComposition *compo = (Z_RecordComposition *)
2971 odr_malloc(c->odr_out, sizeof(*compo));
2973 esn->which = Z_ElementSetNames_generic;
2974 esn->u.generic = odr_strdup(c->odr_out, elementSetName);
2975 compo->which = Z_RecordComp_simple;
2976 compo->u.simple = esn;
2977 req->recordComposition = compo;
2979 req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
2980 return send_APDU(c, apdu);
2983 ZOOM_API(ZOOM_scanset)
2984 ZOOM_connection_scan(ZOOM_connection c, const char *start)
2987 ZOOM_query q = ZOOM_query_create();
2989 ZOOM_query_prefix(q, start);
2991 s = ZOOM_connection_scan1(c, q);
2992 ZOOM_query_destroy(q);
2997 ZOOM_API(ZOOM_scanset)
2998 ZOOM_connection_scan1(ZOOM_connection c, ZOOM_query q)
3000 ZOOM_scanset scan = 0;
3004 scan = (ZOOM_scanset) xmalloc(sizeof(*scan));
3005 scan->connection = c;
3006 scan->odr = odr_createmem(ODR_DECODE);
3007 scan->options = ZOOM_options_create_with_parent(c->options);
3009 scan->scan_response = 0;
3010 scan->srw_scan_response = 0;
3014 scan->databaseNames = set_DatabaseNames(c, c->options,
3015 &scan->num_databaseNames,
3020 ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_SCAN);
3021 task->u.scan.scan = scan;
3026 while (ZOOM_event(1, &c))
3034 ZOOM_scanset_destroy(ZOOM_scanset scan)
3039 if (scan->refcount == 0)
3041 ZOOM_query_destroy(scan->query);
3043 odr_destroy(scan->odr);
3045 ZOOM_options_destroy(scan->options);
3050 static zoom_ret send_package(ZOOM_connection c)
3054 yaz_log(log_details, "%p send_package", c);
3056 return zoom_complete;
3057 assert (c->tasks->which == ZOOM_TASK_PACKAGE);
3059 event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
3060 ZOOM_connection_put_event(c, event);
3062 c->buf_out = c->tasks->u.package->buf_out;
3063 c->len_out = c->tasks->u.package->len_out;
3068 static zoom_ret ZOOM_connection_send_scan(ZOOM_connection c)
3071 Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
3072 Z_ScanRequest *req = apdu->u.scanRequest;
3074 yaz_log(log_details, "%p send_scan", c);
3076 return zoom_complete;
3077 assert (c->tasks->which == ZOOM_TASK_SCAN);
3078 scan = c->tasks->u.scan.scan;
3080 /* Z39.50 scan can only carry RPN */
3081 if (scan->query->z_query->which == Z_Query_type_1 ||
3082 scan->query->z_query->which == Z_Query_type_101)
3084 Z_RPNQuery *rpn = scan->query->z_query->u.type_1;
3085 const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
3088 yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
3091 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
3093 yaz_query_charset_convert_rpnquery(
3094 rpn, c->odr_out, cd);
3095 yaz_iconv_close(cd);
3098 req->attributeSet = rpn->attributeSetId;
3099 if (!req->attributeSet)
3100 req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
3101 if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
3102 rpn->RPNStructure->u.simple->which == Z_Operand_APT)
3104 req->termListAndStartPoint =
3105 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
3109 set_ZOOM_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
3110 return zoom_complete;
3115 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
3116 return zoom_complete;
3119 *req->numberOfTermsRequested =
3120 ZOOM_options_get_int(scan->options, "number", 20);
3122 req->preferredPositionInResponse =
3123 odr_intdup(c->odr_out,
3124 ZOOM_options_get_int(scan->options, "position", 1));
3127 odr_intdup(c->odr_out,
3128 ZOOM_options_get_int(scan->options, "stepSize", 0));
3130 req->databaseNames = scan->databaseNames;
3131 req->num_databaseNames = scan->num_databaseNames;
3133 return send_APDU(c, apdu);
3137 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3141 const char *option_val = 0;
3144 return zoom_complete;
3145 assert (c->tasks->which == ZOOM_TASK_SCAN);
3146 scan = c->tasks->u.scan.scan;
3148 sr = ZOOM_srw_get_pdu(c, Z_SRW_scan_request);
3150 /* SRU scan can only carry CQL and PQF */
3151 if (scan->query->z_query->which == Z_Query_type_104)
3153 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
3154 sr->u.scan_request->scanClause.cql = scan->query->query_string;
3156 else if (scan->query->z_query->which == Z_Query_type_1
3157 || scan->query->z_query->which == Z_Query_type_101)
3159 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
3160 sr->u.scan_request->scanClause.pqf = scan->query->query_string;
3164 set_ZOOM_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
3165 return zoom_complete;
3168 sr->u.scan_request->maximumTerms = odr_intdup(
3169 c->odr_out, ZOOM_options_get_int(scan->options, "number", 10));
3171 sr->u.scan_request->responsePosition = odr_intdup(
3172 c->odr_out, ZOOM_options_get_int(scan->options, "position", 1));
3174 option_val = ZOOM_options_get(scan->options, "extraArgs");
3175 yaz_encode_sru_extra(sr, c->odr_out, option_val);
3176 return send_srw(c, sr);
3179 static zoom_ret ZOOM_connection_srw_send_scan(ZOOM_connection c)
3181 return zoom_complete;
3187 ZOOM_scanset_size(ZOOM_scanset scan)
3192 if (scan->scan_response && scan->scan_response->entries)
3193 return scan->scan_response->entries->num_entries;
3194 else if (scan->srw_scan_response)
3195 return scan->srw_scan_response->num_terms;
3199 static void ZOOM_scanset_term_x(ZOOM_scanset scan, size_t pos,
3201 const char **value_term, size_t *value_len,
3202 const char **disp_term, size_t *disp_len)
3204 size_t noent = ZOOM_scanset_size(scan);
3215 if (scan->scan_response)
3217 Z_ScanResponse *res = scan->scan_response;
3218 if (res->entries->entries[pos]->which == Z_Entry_termInfo)
3220 Z_TermInfo *t = res->entries->entries[pos]->u.termInfo;
3222 *value_term = (const char *) t->term->u.general->buf;
3223 *value_len = t->term->u.general->len;
3226 *disp_term = t->displayTerm;
3227 *disp_len = strlen(*disp_term);
3229 else if (t->term->which == Z_Term_general)
3231 *disp_term = (const char *) t->term->u.general->buf;
3232 *disp_len = t->term->u.general->len;
3234 *occ = t->globalOccurrences ? *t->globalOccurrences : 0;
3237 if (scan->srw_scan_response)
3239 Z_SRW_scanResponse *res = scan->srw_scan_response;
3240 Z_SRW_scanTerm *t = res->terms + pos;
3243 *value_term = t->value;
3244 *value_len = strlen(*value_term);
3247 *disp_term = t->displayTerm;
3249 *disp_term = t->value;
3250 *disp_len = strlen(*disp_term);
3251 *occ = t->numberOfRecords ? *t->numberOfRecords : 0;
3256 ZOOM_API(const char *)
3257 ZOOM_scanset_term(ZOOM_scanset scan, size_t pos,
3258 size_t *occ, size_t *len)
3260 const char *value_term = 0;
3261 size_t value_len = 0;
3262 const char *disp_term = 0;
3263 size_t disp_len = 0;
3265 ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3266 &disp_term, &disp_len);
3272 ZOOM_API(const char *)
3273 ZOOM_scanset_display_term(ZOOM_scanset scan, size_t pos,
3274 size_t *occ, size_t *len)
3276 const char *value_term = 0;
3277 size_t value_len = 0;
3278 const char *disp_term = 0;
3279 size_t disp_len = 0;
3281 ZOOM_scanset_term_x(scan, pos, occ, &value_term, &value_len,
3282 &disp_term, &disp_len);
3288 ZOOM_API(const char *)
3289 ZOOM_scanset_option_get(ZOOM_scanset scan, const char *key)
3291 return ZOOM_options_get(scan->options, key);
3295 ZOOM_scanset_option_set(ZOOM_scanset scan, const char *key,
3298 ZOOM_options_set(scan->options, key, val);
3301 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
3304 Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
3305 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3307 str = ZOOM_options_get(p->options, "package-name");
3309 req->packageName = odr_strdup(p->odr_out, str);
3311 str = ZOOM_options_get(p->options, "user-id");
3313 req->userId = odr_strdup_null(p->odr_out, str);
3315 req->packageType = odr_oiddup(p->odr_out, oid);
3317 str = ZOOM_options_get(p->options, "function");
3320 if (!strcmp (str, "create"))
3321 *req->function = Z_ExtendedServicesRequest_create;
3322 if (!strcmp (str, "delete"))
3323 *req->function = Z_ExtendedServicesRequest_delete;
3324 if (!strcmp (str, "modify"))
3325 *req->function = Z_ExtendedServicesRequest_modify;
3328 str = ZOOM_options_get(p->options, "waitAction");
3331 if (!strcmp (str, "wait"))
3332 *req->waitAction = Z_ExtendedServicesRequest_wait;
3333 if (!strcmp (str, "waitIfPossible"))
3334 *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
3335 if (!strcmp (str, "dontWait"))
3336 *req->waitAction = Z_ExtendedServicesRequest_dontWait;
3337 if (!strcmp (str, "dontReturnPackage"))
3338 *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
3343 static const char *ill_array_lookup(void *clientData, const char *idx)
3345 ZOOM_package p = (ZOOM_package) clientData;
3346 return ZOOM_options_get(p->options, idx+4);
3349 static Z_External *encode_ill_request(ZOOM_package p)
3351 ODR out = p->odr_out;
3354 struct ill_get_ctl ctl;
3356 ctl.odr = p->odr_out;
3358 ctl.f = ill_array_lookup;
3360 req = ill_get_ILLRequest(&ctl, "ill", 0);
3362 if (!ill_Request(out, &req, 0, 0))
3364 int ill_request_size;
3365 char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
3366 if (ill_request_buf)
3367 odr_setbuf(out, ill_request_buf, ill_request_size, 1);
3372 int illRequest_size = 0;
3373 char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
3375 r = (Z_External *) odr_malloc(out, sizeof(*r));
3376 r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
3377 r->indirect_reference = 0;
3379 r->which = Z_External_single;
3381 r->u.single_ASN1_type =
3382 odr_create_Odr_oct(out,
3383 (unsigned char *)illRequest_buf,
3389 static Z_ItemOrder *encode_item_order(ZOOM_package p)
3391 Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
3395 req->which = Z_IOItemOrder_esRequest;
3396 req->u.esRequest = (Z_IORequest *)
3397 odr_malloc(p->odr_out,sizeof(Z_IORequest));
3399 /* to keep part ... */
3400 req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
3401 odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
3402 req->u.esRequest->toKeep->supplDescription = 0;
3403 req->u.esRequest->toKeep->contact = (Z_IOContact *)
3404 odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
3406 str = ZOOM_options_get(p->options, "contact-name");
3407 req->u.esRequest->toKeep->contact->name =
3408 odr_strdup_null(p->odr_out, str);
3410 str = ZOOM_options_get(p->options, "contact-phone");
3411 req->u.esRequest->toKeep->contact->phone =
3412 odr_strdup_null(p->odr_out, str);
3414 str = ZOOM_options_get(p->options, "contact-email");
3415 req->u.esRequest->toKeep->contact->email =
3416 odr_strdup_null(p->odr_out, str);
3418 req->u.esRequest->toKeep->addlBilling = 0;
3420 /* not to keep part ... */
3421 req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
3422 odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
3424 str = ZOOM_options_get(p->options, "itemorder-setname");
3429 req->u.esRequest->notToKeep->resultSetItem = 0;
3432 req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
3433 odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
3435 req->u.esRequest->notToKeep->resultSetItem->resultSetId =
3436 odr_strdup(p->odr_out, str);
3437 req->u.esRequest->notToKeep->resultSetItem->item =
3438 odr_intdup(p->odr_out, 0);
3440 str = ZOOM_options_get(p->options, "itemorder-item");
3441 *req->u.esRequest->notToKeep->resultSetItem->item =
3442 (str ? atoi(str) : 1);
3445 str = ZOOM_options_getl(p->options, "doc", &len);
3448 req->u.esRequest->notToKeep->itemRequest =
3449 z_ext_record_xml(p->odr_out, str, len);
3452 req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
3457 Z_APDU *create_admin_package(ZOOM_package p, int type,
3458 Z_ESAdminOriginPartToKeep **toKeepP,
3459 Z_ESAdminOriginPartNotToKeep **notToKeepP)
3461 Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
3464 Z_ESAdminOriginPartToKeep *toKeep;
3465 Z_ESAdminOriginPartNotToKeep *notToKeep;
3466 Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3467 const char *first_db = "Default";
3469 char **db = set_DatabaseNames(p->connection, p->options, &num_db,
3474 r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
3476 r->indirect_reference = 0;
3477 r->which = Z_External_ESAdmin;
3479 r->u.adminService = (Z_Admin *)
3480 odr_malloc(p->odr_out, sizeof(*r->u.adminService));
3481 r->u.adminService->which = Z_Admin_esRequest;
3482 r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
3483 odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
3485 toKeep = r->u.adminService->u.esRequest->toKeep =
3486 (Z_ESAdminOriginPartToKeep *)
3487 odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
3488 toKeep->which = type;
3489 toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3490 toKeep->u.create = odr_nullval();
3491 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3493 r->u.adminService->u.esRequest->notToKeep = notToKeep =
3494 (Z_ESAdminOriginPartNotToKeep *)
3495 odr_malloc(p->odr_out,
3496 sizeof(*r->u.adminService->u.esRequest->notToKeep));
3497 notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
3498 notToKeep->u.recordsWillFollow = odr_nullval();
3502 *notToKeepP = notToKeep;
3507 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
3509 Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
3510 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
3511 Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
3513 const char *doc = ZOOM_options_getl(p->options, "doc", &len);
3521 req->taskSpecificParameters = ext;
3522 ext->direct_reference = req->packageType;
3523 ext->descriptor = 0;
3524 ext->indirect_reference = 0;
3526 ext->which = Z_External_octet;
3527 ext->u.single_ASN1_type =
3528 odr_create_Odr_oct(p->odr_out, (const unsigned char *) doc, len);
3532 static Z_APDU *create_update_package(ZOOM_package p)
3535 const char *first_db = "Default";
3537 char **db = set_DatabaseNames(p->connection, p->options, &num_db, p->odr_out);
3538 const char *action = ZOOM_options_get(p->options, "action");
3539 int recordIdOpaque_len;
3540 const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
3541 &recordIdOpaque_len);
3542 const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
3544 const char *record_buf = ZOOM_options_getl(p->options, "record",
3546 int recordOpaque_len;
3547 const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
3549 const char *syntax_str = ZOOM_options_get(p->options, "syntax");
3550 const char *version = ZOOM_options_get(p->options, "updateVersion");
3552 const char *correlationInfo_note =
3553 ZOOM_options_get(p->options, "correlationInfo.note");
3554 const char *correlationInfo_id =
3555 ZOOM_options_get(p->options, "correlationInfo.id");
3557 Odr_oid *syntax_oid = 0;
3558 const Odr_oid *package_oid = yaz_oid_extserv_database_update;
3564 if (!record_buf && !recordOpaque_buf)
3566 record_buf = "void";
3568 syntax_str = "SUTRS";
3573 syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
3574 CLASS_RECSYN, syntax_str,
3586 package_oid = yaz_oid_extserv_database_update_first_version;
3587 /* old update does not support specialUpdate */
3589 action = "recordInsert";
3593 action = "specialUpdate";
3594 package_oid = yaz_oid_extserv_database_update_second_version;
3598 action = "specialUpdate";
3599 package_oid = yaz_oid_extserv_database_update;
3605 if (!strcmp(action, "recordInsert"))
3606 action_no = Z_IUOriginPartToKeep_recordInsert;
3607 else if (!strcmp(action, "recordReplace"))
3608 action_no = Z_IUOriginPartToKeep_recordReplace;
3609 else if (!strcmp(action, "recordDelete"))
3610 action_no = Z_IUOriginPartToKeep_recordDelete;
3611 else if (!strcmp(action, "elementUpdate"))
3612 action_no = Z_IUOriginPartToKeep_elementUpdate;
3613 else if (!strcmp(action, "specialUpdate"))
3614 action_no = Z_IUOriginPartToKeep_specialUpdate;
3618 apdu = create_es_package(p, package_oid);
3621 Z_IUOriginPartToKeep *toKeep;
3622 Z_IUSuppliedRecords *notToKeep;
3623 Z_External *r = (Z_External *)
3624 odr_malloc(p->odr_out, sizeof(*r));
3625 const char *elementSetName =
3626 ZOOM_options_get(p->options, "elementSetName");
3628 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3630 r->direct_reference = odr_oiddup(p->odr_out, package_oid);
3632 r->which = Z_External_update;
3633 r->indirect_reference = 0;
3634 r->u.update = (Z_IUUpdate *)
3635 odr_malloc(p->odr_out, sizeof(*r->u.update));
3637 r->u.update->which = Z_IUUpdate_esRequest;
3638 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
3639 odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
3640 toKeep = r->u.update->u.esRequest->toKeep =
3641 (Z_IUOriginPartToKeep *)
3642 odr_malloc(p->odr_out, sizeof(*toKeep));
3644 toKeep->databaseName = odr_strdup(p->odr_out, first_db);
3647 toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
3649 toKeep->actionQualifier = 0;
3650 toKeep->action = odr_intdup(p->odr_out, action_no);
3652 notToKeep = r->u.update->u.esRequest->notToKeep =
3653 (Z_IUSuppliedRecords *)
3654 odr_malloc(p->odr_out, sizeof(*notToKeep));
3656 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
3657 odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
3658 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
3659 odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
3660 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
3663 notToKeep->elements[0]->u.opaque =
3664 odr_create_Odr_oct(p->odr_out,
3665 (const unsigned char *) recordIdOpaque,
3666 recordIdOpaque_len);
3668 else if (recordIdNumber)
3670 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
3672 notToKeep->elements[0]->u.number =
3673 odr_intdup(p->odr_out, atoi(recordIdNumber));
3676 notToKeep->elements[0]->u.opaque = 0;
3677 notToKeep->elements[0]->supplementalId = 0;
3678 if (correlationInfo_note || correlationInfo_id)
3680 Z_IUCorrelationInfo *ci;
3681 ci = notToKeep->elements[0]->correlationInfo =
3682 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
3683 ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
3684 ci->id = correlationInfo_id ?
3685 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
3688 notToKeep->elements[0]->correlationInfo = 0;
3689 if (recordOpaque_buf)
3691 notToKeep->elements[0]->record =
3692 z_ext_record_oid_any(p->odr_out, syntax_oid,
3693 recordOpaque_buf, recordOpaque_len);
3697 notToKeep->elements[0]->record =
3698 z_ext_record_oid(p->odr_out, syntax_oid,
3699 record_buf, record_len);
3704 ODR print = odr_createmem(ODR_PRINT);
3706 z_APDU(print, &apdu, 0, 0);
3713 ZOOM_package_send(ZOOM_package p, const char *type)
3720 odr_reset(p->odr_out);
3723 if (!strcmp(type, "itemorder"))
3725 apdu = create_es_package(p, yaz_oid_extserv_item_order);
3728 Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
3730 r->direct_reference =
3731 odr_oiddup(p->odr_out, yaz_oid_extserv_item_order);
3733 r->which = Z_External_itemOrder;
3734 r->indirect_reference = 0;
3735 r->u.itemOrder = encode_item_order(p);
3737 apdu->u.extendedServicesRequest->taskSpecificParameters = r;
3740 else if (!strcmp(type, "create")) /* create database */
3742 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
3745 else if (!strcmp(type, "drop")) /* drop database */
3747 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
3750 else if (!strcmp(type, "commit")) /* commit changes */
3752 apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
3755 else if (!strcmp(type, "update")) /* update record(s) */
3757 apdu = create_update_package(p);
3759 else if (!strcmp(type, "xmlupdate"))
3761 apdu = create_xmlupdate_package(p);
3765 if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
3769 ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
3770 task->u.package = p;
3771 buf = odr_getbuf(p->odr_out, &p->len_out, 0);
3772 p->buf_out = (char *) xmalloc(p->len_out);
3773 memcpy(p->buf_out, buf, p->len_out);
3778 while (ZOOM_event(1, &c))
3785 ZOOM_API(ZOOM_package)
3786 ZOOM_connection_package(ZOOM_connection c, ZOOM_options options)
3788 ZOOM_package p = (ZOOM_package) xmalloc(sizeof(*p));
3791 p->odr_out = odr_createmem(ODR_ENCODE);
3792 p->options = ZOOM_options_create_with_parent2(options, c->options);
3800 ZOOM_package_destroy(ZOOM_package p)
3805 if (p->refcount == 0)
3807 odr_destroy(p->odr_out);
3810 ZOOM_options_destroy(p->options);
3815 ZOOM_API(const char *)
3816 ZOOM_package_option_get(ZOOM_package p, const char *key)
3818 return ZOOM_options_get(p->options, key);
3821 ZOOM_API(const char *)
3822 ZOOM_package_option_getl(ZOOM_package p, const char *key, int *lenp)
3824 return ZOOM_options_getl(p->options, key, lenp);
3828 ZOOM_package_option_set(ZOOM_package p, const char *key,
3831 ZOOM_options_set(p->options, key, val);
3835 ZOOM_package_option_setl(ZOOM_package p, const char *key,
3836 const char *val, int len)
3838 ZOOM_options_setl(p->options, key, val, len);
3842 ZOOM_connection_exec_task(ZOOM_connection c)
3844 ZOOM_task task = c->tasks;
3845 zoom_ret ret = zoom_complete;
3849 yaz_log(log_details, "%p ZOOM_connection_exec_task type=%d run=%d",
3850 c, task->which, task->running);
3851 if (c->error != ZOOM_ERROR_NONE)
3853 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3854 "removing tasks because of error = %d", c, c->error);
3855 ZOOM_connection_remove_tasks(c);
3860 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3861 "task already running", c);
3865 ret = zoom_complete;
3866 if (c->cs || task->which == ZOOM_TASK_CONNECT)
3868 switch (task->which)
3870 case ZOOM_TASK_SEARCH:
3871 if (c->proto == PROTO_HTTP)
3872 ret = ZOOM_connection_srw_send_search(c);
3874 ret = ZOOM_connection_send_search(c);
3876 case ZOOM_TASK_RETRIEVE:
3877 if (c->proto == PROTO_HTTP)
3878 ret = ZOOM_connection_srw_send_search(c);
3880 ret = send_present(c);
3882 case ZOOM_TASK_CONNECT:
3883 ret = do_connect(c);
3885 case ZOOM_TASK_SCAN:
3886 if (c->proto == PROTO_HTTP)
3887 ret = ZOOM_connection_srw_send_scan(c);
3889 ret = ZOOM_connection_send_scan(c);
3891 case ZOOM_TASK_PACKAGE:
3892 ret = send_package(c);
3894 case ZOOM_TASK_SORT:
3895 c->tasks->u.sort.resultset->r_sort_spec =
3896 c->tasks->u.sort.q->sort_spec;
3897 ret = send_sort(c, c->tasks->u.sort.resultset);
3903 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3904 "remove tasks because no connection exist", c);
3905 ZOOM_connection_remove_tasks(c);
3907 if (ret == zoom_complete)
3909 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3910 "task removed (complete)", c);
3911 ZOOM_connection_remove_task(c);
3914 yaz_log(log_details, "%p ZOOM_connection_exec_task "
3919 static zoom_ret send_sort_present(ZOOM_connection c)
3921 zoom_ret r = zoom_complete;
3923 if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
3924 r = send_sort(c, c->tasks->u.search.resultset);
3925 if (r == zoom_complete)
3926 r = send_present(c);
3930 static int es_response_taskpackage_update(ZOOM_connection c,
3931 Z_IUUpdateTaskPackage *utp)
3933 if (utp && utp->targetPart)
3935 Z_IUTargetPart *targetPart = utp->targetPart;
3936 switch ( *targetPart->updateStatus ) {
3937 case Z_IUTargetPart_success:
3938 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "success");
3940 case Z_IUTargetPart_partial:
3941 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "partial");
3943 case Z_IUTargetPart_failure:
3944 ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "failure");
3945 if (targetPart->globalDiagnostics && targetPart->num_globalDiagnostics > 0)
3946 response_diag(c, targetPart->globalDiagnostics[0]);
3949 // NOTE: Individual record status, surrogate diagnostics, and supplemental diagnostics ARE NOT REPORTED.
3954 static int es_response_taskpackage(ZOOM_connection c,
3955 Z_TaskPackage *taskPackage)
3958 Odr_oct *id = taskPackage->targetReference;
3960 ZOOM_options_setl(c->tasks->u.package->options,
3961 "targetReference", (char*) id->buf, id->len);
3964 switch ( *taskPackage->taskStatus ) {
3965 case Z_TaskPackage_pending:
3966 ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "pending");
3968 case Z_TaskPackage_active:
3969 ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "active");
3971 case Z_TaskPackage_complete:
3972 ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "complete");
3974 case Z_TaskPackage_aborted:
3975 ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "aborted");
3976 if ( taskPackage->num_packageDiagnostics && taskPackage->packageDiagnostics )
3977 response_diag(c, taskPackage->packageDiagnostics[0]);
3981 // taskSpecificParameters
3982 // NOTE: Only Update implemented, no others.
3983 if ( taskPackage->taskSpecificParameters->which == Z_External_update ) {
3984 Z_IUUpdateTaskPackage *utp = taskPackage->taskSpecificParameters->u.update->u.taskPackage;
3985 es_response_taskpackage_update(c, utp);
3991 static int es_response(ZOOM_connection c,
3992 Z_ExtendedServicesResponse *res)
3994 if (!c->tasks || c->tasks->which != ZOOM_TASK_PACKAGE)
3996 switch (*res->operationStatus) {
3997 case Z_ExtendedServicesResponse_done:
3998 ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "done");
4000 case Z_ExtendedServicesResponse_accepted:
4001 ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "accepted");
4003 case Z_ExtendedServicesResponse_failure:
4004 ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "failure");
4005 if (res->diagnostics && res->num_diagnostics > 0)
4006 response_diag(c, res->diagnostics[0]);
4009 if (res->taskPackage &&
4010 res->taskPackage->which == Z_External_extendedService)
4012 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
4013 es_response_taskpackage(c, taskPackage);
4015 if (res->taskPackage &&
4016 res->taskPackage->which == Z_External_octet)
4018 Odr_oct *doc = res->taskPackage->u.octet_aligned;
4019 ZOOM_options_setl(c->tasks->u.package->options,
4020 "xmlUpdateDoc", (char*) doc->buf, doc->len);
4025 static void interpret_init_diag(ZOOM_connection c,
4026 Z_DiagnosticFormat *diag)
4030 Z_DiagnosticFormat_s *ds = diag->elements[0];
4031 if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
4032 response_default_diag(c, ds->u.defaultDiagRec);
4037 static void interpret_otherinformation_field(ZOOM_connection c,
4038 Z_OtherInformation *ui)
4041 for (i = 0; i < ui->num_elements; i++)
4043 Z_OtherInformationUnit *unit = ui->list[i];
4044 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
4045 unit->information.externallyDefinedInfo &&
4046 unit->information.externallyDefinedInfo->which ==
4049 interpret_init_diag(c, unit->information.externallyDefinedInfo->u.diag1);
4055 static void set_init_option(const char *name, void *clientData) {
4056 ZOOM_connection c = (ZOOM_connection) clientData;
4059 sprintf(buf, "init_opt_%.70s", name);
4060 ZOOM_connection_option_set(c, buf, "1");
4064 static void recv_apdu(ZOOM_connection c, Z_APDU *apdu)
4066 Z_InitResponse *initrs;
4068 ZOOM_connection_set_mask(c, 0);
4069 yaz_log(log_details, "%p recv_apdu apdu->which=%d", c, apdu->which);
4072 case Z_APDU_initResponse:
4073 yaz_log(log_api, "%p recv_apdu: Received Init response", c);
4074 initrs = apdu->u.initResponse;
4075 ZOOM_connection_option_set(c, "serverImplementationId",
4076 initrs->implementationId ?
4077 initrs->implementationId : "");
4078 ZOOM_connection_option_set(c, "serverImplementationName",
4079 initrs->implementationName ?
4080 initrs->implementationName : "");
4081 ZOOM_connection_option_set(c, "serverImplementationVersion",
4082 initrs->implementationVersion ?
4083 initrs->implementationVersion : "");
4084 /* Set the three old options too, for old applications */
4085 ZOOM_connection_option_set(c, "targetImplementationId",
4086 initrs->implementationId ?
4087 initrs->implementationId : "");
4088 ZOOM_connection_option_set(c, "targetImplementationName",
4089 initrs->implementationName ?
4090 initrs->implementationName : "");
4091 ZOOM_connection_option_set(c, "targetImplementationVersion",
4092 initrs->implementationVersion ?
4093 initrs->implementationVersion : "");
4095 /* Make initrs->options available as ZOOM-level options */
4096 yaz_init_opt_decode(initrs->options, set_init_option, (void*) c);
4098 if (!*initrs->result)
4100 Z_External *uif = initrs->userInformationField;
4102 set_ZOOM_error(c, ZOOM_ERROR_INIT, 0); /* default error */
4104 if (uif && uif->which == Z_External_userInfo1)
4105 interpret_otherinformation_field(c, uif->u.userInfo1);
4110 yaz_oi_get_string_oid(&apdu->u.initResponse->otherInfo,
4111 yaz_oid_userinfo_cookie, 1, 0);
4112 xfree(c->cookie_in);
4115 c->cookie_in = xstrdup(cookie);
4116 if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
4117 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
4118 c->support_named_resultsets = 1;
4121 assert(c->tasks->which == ZOOM_TASK_CONNECT);
4122 ZOOM_connection_remove_task(c);
4124 ZOOM_connection_exec_task(c);
4126 if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
4128 NMEM tmpmem = nmem_create();
4129 Z_CharSetandLanguageNegotiation *p =
4130 yaz_get_charneg_record(initrs->otherInfo);
4134 char *charset = NULL, *lang = NULL;
4137 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
4138 yaz_log(log_details, "%p recv_apdu target accepted: "
4139 "charset %s, language %s, select %d",
4141 charset ? charset : "none", lang ? lang : "none", sel);
4143 ZOOM_connection_option_set(c, "negotiation-charset",
4146 ZOOM_connection_option_set(c, "negotiation-lang",
4149 ZOOM_connection_option_set(
4150 c, "negotiation-charset-in-effect-for-records",
4151 (sel != 0) ? "1" : "0");
4152 nmem_destroy(tmpmem);
4156 case Z_APDU_searchResponse:
4157 yaz_log(log_api, "%p recv_apdu Search response", c);
4158 handle_search_response(c, apdu->u.searchResponse);
4159 if (send_sort_present(c) == zoom_complete)
4160 ZOOM_connection_remove_task(c);
4162 case Z_APDU_presentResponse:
4163 yaz_log(log_api, "%p recv_apdu Present response", c);
4164 handle_present_response(c, apdu->u.presentResponse);
4165 if (send_present(c) == zoom_complete)
4166 ZOOM_connection_remove_task(c);
4168 case Z_APDU_sortResponse:
4169 yaz_log(log_api, "%p recv_apdu Sort response", c);
4170 sort_response(c, apdu->u.sortResponse);
4171 if (send_present(c) == zoom_complete)
4172 ZOOM_connection_remove_task(c);
4174 case Z_APDU_scanResponse:
4175 yaz_log(log_api, "%p recv_apdu Scan response", c);
4176 scan_response(c, apdu->u.scanResponse);
4177 ZOOM_connection_remove_task(c);
4179 case Z_APDU_extendedServicesResponse:
4180 yaz_log(log_api, "%p recv_apdu Extended Services response", c);
4181 es_response(c, apdu->u.extendedServicesResponse);
4182 ZOOM_connection_remove_task(c);
4185 yaz_log(log_api, "%p recv_apdu Close PDU", c);
4186 if (!ZOOM_test_reconnect(c))
4188 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4193 yaz_log(log_api, "%p Received unknown PDU", c);
4194 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
4200 static zoom_ret handle_srw_response(ZOOM_connection c,
4201 Z_SRW_searchRetrieveResponse *res)
4203 ZOOM_resultset resultset = 0;
4208 const char *syntax, *elementSetName;
4211 return zoom_complete;
4213 switch(c->tasks->which)
4215 case ZOOM_TASK_SEARCH:
4216 resultset = c->tasks->u.search.resultset;
4217 start = &c->tasks->u.search.start;
4218 count = &c->tasks->u.search.count;
4219 syntax = c->tasks->u.search.syntax;
4220 elementSetName = c->tasks->u.search.elementSetName;
4222 if (!c->tasks->u.search.recv_search_fired)
4224 event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
4225 ZOOM_connection_put_event(c, event);
4226 c->tasks->u.search.recv_search_fired = 1;
4229 case ZOOM_TASK_RETRIEVE:
4230 resultset = c->tasks->u.retrieve.resultset;
4231 start = &c->tasks->u.retrieve.start;
4232 count = &c->tasks->u.retrieve.count;
4233 syntax = c->tasks->u.retrieve.syntax;
4234 elementSetName = c->tasks->u.retrieve.elementSetName;
4237 return zoom_complete;
4240 resultset->size = 0;
4242 if (res->resultSetId)
4243 ZOOM_resultset_option_set(resultset, "resultSetId", res->resultSetId);
4245 yaz_log(log_details, "%p handle_srw_response got SRW response OK", c);
4247 if (res->num_diagnostics > 0)
4249 set_SRU_error(c, &res->diagnostics[0]);
4253 if (res->numberOfRecords)
4254 resultset->size = *res->numberOfRecords;
4255 for (i = 0; i<res->num_records; i++)
4258 Z_SRW_record *sru_rec;
4259 Z_SRW_diagnostic *diag = 0;
4262 Z_NamePlusRecord *npr = (Z_NamePlusRecord *)
4263 odr_malloc(c->odr_in, sizeof(Z_NamePlusRecord));
4265 if (res->records[i].recordPosition &&
4266 *res->records[i].recordPosition > 0)
4267 pos = *res->records[i].recordPosition - 1;
4271 sru_rec = &res->records[i];
4273 npr->databaseName = 0;
4274 npr->which = Z_NamePlusRecord_databaseRecord;
4275 npr->u.databaseRecord = (Z_External *)
4276 odr_malloc(c->odr_in, sizeof(Z_External));
4277 npr->u.databaseRecord->descriptor = 0;
4278 npr->u.databaseRecord->direct_reference =
4279 odr_oiddup(c->odr_in, yaz_oid_recsyn_xml);
4280 npr->u.databaseRecord->which = Z_External_octet;
4282 npr->u.databaseRecord->u.octet_aligned = (Odr_oct *)
4283 odr_malloc(c->odr_in, sizeof(Odr_oct));
4284 npr->u.databaseRecord->u.octet_aligned->buf = (unsigned char*)
4285 sru_rec->recordData_buf;
4286 npr->u.databaseRecord->u.octet_aligned->len =
4287 npr->u.databaseRecord->u.octet_aligned->size =
4288 sru_rec->recordData_len;
4290 if (sru_rec->recordSchema
4291 && !strcmp(sru_rec->recordSchema,
4292 "info:srw/schema/1/diagnostics-v1.1"))
4294 sru_decode_surrogate_diagnostics(sru_rec->recordData_buf,
4295 sru_rec->recordData_len,
4299 record_cache_add(resultset, npr, pos, syntax, elementSetName,
4300 sru_rec->recordSchema, diag);
4304 if (*count + *start > resultset->size)
4305 *count = resultset->size - *start;
4309 nmem = odr_extract_mem(c->odr_in);
4310 nmem_transfer(odr_getmem(resultset->odr), nmem);
4314 return ZOOM_connection_srw_send_search(c);
4316 return zoom_complete;
4321 static void handle_srw_scan_response(ZOOM_connection c,
4322 Z_SRW_scanResponse *res)
4324 NMEM nmem = odr_extract_mem(c->odr_in);
4327 if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
4329 scan = c->tasks->u.scan.scan;
4331 if (res->num_diagnostics > 0)
4332 set_SRU_error(c, &res->diagnostics[0]);
4334 scan->scan_response = 0;
4335 scan->srw_scan_response = res;
4336 nmem_transfer(odr_getmem(scan->odr), nmem);
4338 ZOOM_options_set_int(scan->options, "number", res->num_terms);
4344 static Z_GDU *get_HTTP_Request_url(ODR odr, const char *url)
4346 Z_GDU *p = z_get_HTTP_Request(odr);
4347 const char *host = url;
4348 const char *cp0 = strstr(host, "://");
4349 const char *cp1 = 0;
4355 cp1 = strchr(cp0, '/');
4357 cp1 = cp0 + strlen(cp0);
4361 char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
4362 memcpy (h, cp0, cp1 - cp0);
4364 z_HTTP_header_add(odr, &p->u.HTTP_Request->headers, "Host", h);
4366 p->u.HTTP_Request->path = odr_strdup(odr, *cp1 ? cp1 : "/");
4370 static zoom_ret send_SRW_redirect(ZOOM_connection c, const char *uri,
4371 Z_HTTP_Response *cookie_hres)
4373 struct Z_HTTP_Header *h;
4374 Z_GDU *gdu = get_HTTP_Request_url(c->odr_out, uri);
4375 char *combined_cookies;
4376 int combined_cookies_len = 0;
4378 gdu->u.HTTP_Request->method = odr_strdup(c->odr_out, "GET");
4379 z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers, "Accept",
4382 for (h = cookie_hres->headers; h; h = h->next)
4384 if (!strcmp(h->name, "Set-Cookie"))
4388 if (!(cp = strchr(h->value, ';')))
4389 cp = h->value + strlen(h->value);
4390 if (cp - h->value >= 1) {
4391 combined_cookies = xrealloc(combined_cookies, combined_cookies_len + cp - h->value + 3);
4392 memcpy(combined_cookies+combined_cookies_len, h->value, cp - h->value);
4393 combined_cookies[combined_cookies_len + cp - h->value] = '\0';
4394 strcat(combined_cookies,"; ");
4395 combined_cookies_len = strlen(combined_cookies);
4400 if (combined_cookies_len)
4402 z_HTTP_header_add(c->odr_out, &gdu->u.HTTP_Request->headers,
4403 "Cookie", combined_cookies);
4404 xfree(combined_cookies);
4407 if (c->user && c->password)
4409 z_HTTP_header_add_basic_auth(c->odr_out, &gdu->u.HTTP_Request->headers,
4410 c->user, c->password);
4412 if (!z_GDU(c->odr_out, &gdu, 0, 0))
4413 return zoom_complete;
4415 z_GDU(c->odr_print, &gdu, 0, 0);
4416 c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
4418 odr_reset(c->odr_out);
4422 static void handle_http(ZOOM_connection c, Z_HTTP_Response *hres)
4424 zoom_ret cret = zoom_complete;
4426 const char *addinfo = 0;
4427 const char *connection_head = z_HTTP_header_lookup(hres->headers,
4429 const char *location;
4431 ZOOM_connection_set_mask(c, 0);
4432 yaz_log(log_details, "%p handle_http", c);
4434 if ((hres->code == 301 || hres->code == 302) && c->sru_mode == zoom_sru_get
4435 && (location = z_HTTP_header_lookup(hres->headers, "Location")))
4438 if (c->no_redirects > 10)
4440 set_HTTP_error(c, hres->code, 0, 0);
4441 c->no_redirects = 0;
4446 /* since redirect may change host we just reconnect. A smarter
4447 implementation might check whether it's the same server */
4448 do_connect_host(c, location, 0);
4449 send_SRW_redirect(c, location, hres);
4450 /* we're OK for now. Operation is not really complete */
4452 cret = zoom_pending;
4456 { /* not redirect (normal response) */
4457 if (!yaz_srw_check_content_type(hres))
4458 addinfo = "content-type";
4461 Z_SOAP *soap_package = 0;
4463 Z_SOAP_Handler soap_handlers[2] = {
4464 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
4467 ret = z_soap_codec(o, &soap_package,
4468 &hres->content_buf, &hres->content_len,
4470 if (!ret && soap_package->which == Z_SOAP_generic &&
4471 soap_package->u.generic->no == 0)
4473 Z_SRW_PDU *sr = (Z_SRW_PDU*) soap_package->u.generic->p;
4475 ZOOM_options_set(c->options, "sru_version", sr->srw_version);
4476 ZOOM_options_setl(c->options, "sru_extra_response_data",
4477 sr->extraResponseData_buf, sr->extraResponseData_len);
4478 if (sr->which == Z_SRW_searchRetrieve_response)
4479 cret = handle_srw_response(c, sr->u.response);
4480 else if (sr->which == Z_SRW_scan_response)
4481 handle_srw_scan_response(c, sr->u.scan_response);
4485 else if (!ret && (soap_package->which == Z_SOAP_fault
4486 || soap_package->which == Z_SOAP_error))
4488 set_HTTP_error(c, hres->code,
4489 soap_package->u.fault->fault_code,
4490 soap_package->u.fault->fault_string);
4497 if (c->no_redirects) /* end of redirect. change hosts again */
4500 c->no_redirects = 0;
4504 if (hres->code != 200)
4505 set_HTTP_error(c, hres->code, 0, 0);
4507 set_ZOOM_error(c, ZOOM_ERROR_DECODE, addinfo);
4510 if (cret == zoom_complete)
4512 yaz_log(YLOG_LOG, "removing tasks in handle_http");
4513 ZOOM_connection_remove_task(c);
4517 if (!strcmp(hres->version, "1.0"))
4519 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
4520 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
4525 /* HTTP 1.1: only if no close we stay alive.. */
4526 if (connection_head && !strcmp(connection_head, "close"))
4534 c->tasks->running = 0;
4535 ZOOM_connection_insert_task(c, ZOOM_TASK_CONNECT);
4536 c->reconnect_ok = 0;
4543 static int do_read(ZOOM_connection c)
4548 event = ZOOM_Event_create(ZOOM_EVENT_RECV_DATA);
4549 ZOOM_connection_put_event(c, event);
4551 r = cs_get(c->cs, &c->buf_in, &c->len_in);
4552 more = cs_more(c->cs);
4553 yaz_log(log_details, "%p do_read len=%d more=%d", c, r, more);
4558 if (!ZOOM_test_reconnect(c))
4560 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4569 odr_reset(c->odr_in);
4570 odr_setbuf(c->odr_in, c->buf_in, r, 0);
4571 event = ZOOM_Event_create(ZOOM_EVENT_RECV_APDU);
4572 ZOOM_connection_put_event(c, event);
4574 if (!z_GDU(c->odr_in, &gdu, 0, 0))
4577 int err = odr_geterrorx(c->odr_in, &x);
4579 const char *element = odr_getelement(c->odr_in);
4580 yaz_snprintf(msg, sizeof(msg),
4581 "ODR code %d:%d element=%s offset=%d",
4582 err, x, element ? element : "<unknown>",
4583 odr_offset(c->odr_in));
4584 set_ZOOM_error(c, ZOOM_ERROR_DECODE, msg);
4587 FILE *ber_file = yaz_log_file();
4589 odr_dumpBER(ber_file, c->buf_in, r);
4596 z_GDU(c->odr_print, &gdu, 0, 0);
4597 if (gdu->which == Z_GDU_Z3950)
4598 recv_apdu(c, gdu->u.z3950);
4599 else if (gdu->which == Z_GDU_HTTP_Response)
4602 handle_http(c, gdu->u.HTTP_Response);
4604 set_ZOOM_error(c, ZOOM_ERROR_DECODE, 0);
4609 c->reconnect_ok = 0;
4614 static zoom_ret do_write_ex(ZOOM_connection c, char *buf_out, int len_out)
4619 event = ZOOM_Event_create(ZOOM_EVENT_SEND_DATA);
4620 ZOOM_connection_put_event(c, event);
4622 yaz_log(log_details, "%p do_write_ex len=%d", c, len_out);
4623 if ((r = cs_put(c->cs, buf_out, len_out)) < 0)
4625 yaz_log(log_details, "%p do_write_ex write failed", c);
4626 if (ZOOM_test_reconnect(c))
4628 return zoom_pending;
4630 if (c->state == STATE_CONNECTING)
4631 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4633 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4635 return zoom_complete;
4639 int mask = ZOOM_SELECT_EXCEPT;
4640 if (c->cs->io_pending & CS_WANT_WRITE)
4641 mask += ZOOM_SELECT_WRITE;
4642 if (c->cs->io_pending & CS_WANT_READ)
4643 mask += ZOOM_SELECT_READ;
4644 ZOOM_connection_set_mask(c, mask);
4645 yaz_log(log_details, "%p do_write_ex write incomplete mask=%d",
4650 ZOOM_connection_set_mask(c, ZOOM_SELECT_READ|ZOOM_SELECT_EXCEPT);
4651 yaz_log(log_details, "%p do_write_ex write complete mask=%d",
4654 return zoom_pending;
4657 static zoom_ret do_write(ZOOM_connection c)
4659 return do_write_ex(c, c->buf_out, c->len_out);
4663 ZOOM_API(const char *)
4664 ZOOM_connection_option_get(ZOOM_connection c, const char *key)
4666 return ZOOM_options_get(c->options, key);
4669 ZOOM_API(const char *)
4670 ZOOM_connection_option_getl(ZOOM_connection c, const char *key, int *lenp)
4672 return ZOOM_options_getl(c->options, key, lenp);
4676 ZOOM_connection_option_set(ZOOM_connection c, const char *key,
4679 ZOOM_options_set(c->options, key, val);
4683 ZOOM_connection_option_setl(ZOOM_connection c, const char *key,
4684 const char *val, int len)
4686 ZOOM_options_setl(c->options, key, val, len);
4689 ZOOM_API(const char *)
4690 ZOOM_resultset_option_get(ZOOM_resultset r, const char *key)
4692 return ZOOM_options_get(r->options, key);
4696 ZOOM_resultset_option_set(ZOOM_resultset r, const char *key,
4699 ZOOM_options_set(r->options, key, val);
4704 ZOOM_connection_errcode(ZOOM_connection c)
4706 return ZOOM_connection_error(c, 0, 0);
4709 ZOOM_API(const char *)
4710 ZOOM_connection_errmsg(ZOOM_connection c)
4713 ZOOM_connection_error(c, &msg, 0);
4717 ZOOM_API(const char *)
4718 ZOOM_connection_addinfo(ZOOM_connection c)
4720 const char *addinfo;
4721 ZOOM_connection_error(c, 0, &addinfo);
4725 ZOOM_API(const char *)
4726 ZOOM_connection_diagset(ZOOM_connection c)
4728 const char *diagset;
4729 ZOOM_connection_error_x(c, 0, 0, &diagset);
4733 ZOOM_API(const char *)
4734 ZOOM_diag_str(int error)
4738 case ZOOM_ERROR_NONE:
4740 case ZOOM_ERROR_CONNECT:
4741 return "Connect failed";
4742 case ZOOM_ERROR_MEMORY:
4743 return "Out of memory";
4744 case ZOOM_ERROR_ENCODE:
4745 return "Encoding failed";
4746 case ZOOM_ERROR_DECODE:
4747 return "Decoding failed";
4748 case ZOOM_ERROR_CONNECTION_LOST:
4749 return "Connection lost";
4750 case ZOOM_ERROR_INIT:
4751 return "Init rejected";
4752 case ZOOM_ERROR_INTERNAL:
4753 return "Internal failure";
4754 case ZOOM_ERROR_TIMEOUT:
4756 case ZOOM_ERROR_UNSUPPORTED_PROTOCOL:
4757 return "Unsupported protocol";
4758 case ZOOM_ERROR_UNSUPPORTED_QUERY:
4759 return "Unsupported query type";
4760 case ZOOM_ERROR_INVALID_QUERY:
4761 return "Invalid query";
4762 case ZOOM_ERROR_CQL_PARSE:
4763 return "CQL parsing error";
4764 case ZOOM_ERROR_CQL_TRANSFORM:
4765 return "CQL transformation error";
4766 case ZOOM_ERROR_CCL_CONFIG:
4767 return "CCL configuration error";
4768 case ZOOM_ERROR_CCL_PARSE:
4769 return "CCL parsing error";
4771 return diagbib1_str(error);
4776 ZOOM_connection_error_x(ZOOM_connection c, const char **cp,
4777 const char **addinfo, const char **diagset)
4779 int error = c->error;
4782 if (!c->diagset || !strcmp(c->diagset, "ZOOM"))
4783 *cp = ZOOM_diag_str(error);
4784 else if (!strcmp(c->diagset, "HTTP"))
4785 *cp = z_HTTP_errmsg(c->error);
4786 else if (!strcmp(c->diagset, "Bib-1"))
4787 *cp = ZOOM_diag_str(error);
4788 else if (!strcmp(c->diagset, "info:srw/diagnostic/1"))
4789 *cp = yaz_diag_srw_str(c->error);
4791 *cp = "Unknown error and diagnostic set";
4794 *addinfo = c->addinfo ? c->addinfo : "";
4796 *diagset = c->diagset ? c->diagset : "";
4801 ZOOM_connection_error(ZOOM_connection c, const char **cp,
4802 const char **addinfo)
4804 return ZOOM_connection_error_x(c, cp, addinfo, 0);
4807 static void ZOOM_connection_do_io(ZOOM_connection c, int mask)
4809 ZOOM_Event event = 0;
4810 int r = cs_look(c->cs);
4811 yaz_log(log_details, "%p ZOOM_connection_do_io mask=%d cs_look=%d",
4816 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4817 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4819 ZOOM_connection_put_event(c, event);
4821 else if (r == CS_CONNECT)
4823 int ret = ret = cs_rcvconnect(c->cs);
4824 yaz_log(log_details, "%p ZOOM_connection_do_io "
4825 "cs_rcvconnect returned %d", c, ret);
4828 int mask = ZOOM_SELECT_EXCEPT;
4829 if (c->cs->io_pending & CS_WANT_WRITE)
4830 mask += ZOOM_SELECT_WRITE;
4831 if (c->cs->io_pending & CS_WANT_READ)
4832 mask += ZOOM_SELECT_READ;
4833 ZOOM_connection_set_mask(c, mask);
4834 event = ZOOM_Event_create(ZOOM_EVENT_NONE);
4835 ZOOM_connection_put_event(c, event);
4839 event = ZOOM_Event_create(ZOOM_EVENT_CONNECT);
4840 ZOOM_connection_put_event(c, event);
4842 if (c->proto == PROTO_Z3950)
4843 ZOOM_connection_send_init(c);
4846 /* no init request for SRW .. */
4847 assert(c->tasks->which == ZOOM_TASK_CONNECT);
4848 ZOOM_connection_remove_task(c);
4849 ZOOM_connection_set_mask(c, 0);
4850 ZOOM_connection_exec_task(c);
4852 c->state = STATE_ESTABLISHED;
4856 set_ZOOM_error(c, ZOOM_ERROR_CONNECT, c->host_port);
4862 if (mask & ZOOM_SELECT_EXCEPT)
4864 if (!ZOOM_test_reconnect(c))
4866 set_ZOOM_error(c, ZOOM_ERROR_CONNECTION_LOST, c->host_port);
4871 if (mask & ZOOM_SELECT_READ)
4873 if (c->cs && (mask & ZOOM_SELECT_WRITE))
4879 ZOOM_connection_last_event(ZOOM_connection cs)
4882 return ZOOM_EVENT_NONE;
4883 return cs->last_event;
4887 static void cql2pqf_wrbuf_puts(const char *buf, void *client_data)
4889 WRBUF wrbuf = (WRBUF) client_data;
4890 wrbuf_puts(wrbuf, buf);
4894 * Returns an xmalloc()d string containing RPN that corresponds to the
4895 * CQL passed in. On error, sets the Connection object's error state
4896 * and returns a null pointer.
4897 * ### We could cache CQL parser and/or transformer in Connection.
4899 static char *cql2pqf(ZOOM_connection c, const char *cql)
4903 const char *cqlfile;
4904 cql_transform_t trans;
4907 parser = cql_parser_create();
4908 if ((error = cql_parser_string(parser, cql)) != 0) {
4909 cql_parser_destroy(parser);
4910 set_ZOOM_error(c, ZOOM_ERROR_CQL_PARSE, cql);
4914 cqlfile = ZOOM_connection_option_get(c, "cqlfile");
4917 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, "no CQL transform file");
4919 else if ((trans = cql_transform_open_fname(cqlfile)) == 0)
4922 sprintf(buf, "can't open CQL transform file '%.200s': %.200s",
4923 cqlfile, strerror(errno));
4924 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4928 WRBUF wrbuf_result = wrbuf_alloc();
4929 error = cql_transform(trans, cql_parser_result(parser),
4930 cql2pqf_wrbuf_puts, wrbuf_result);
4933 const char *addinfo;
4934 error = cql_transform_error(trans, &addinfo);
4935 sprintf(buf, "%.200s (addinfo=%.200s)",
4936 cql_strerror(error), addinfo);
4937 set_ZOOM_error(c, ZOOM_ERROR_CQL_TRANSFORM, buf);
4941 result = xstrdup(wrbuf_cstr(wrbuf_result));
4943 cql_transform_close(trans);
4944 wrbuf_destroy(wrbuf_result);
4946 cql_parser_destroy(parser);
4950 ZOOM_API(int) ZOOM_connection_fire_event_timeout(ZOOM_connection c)
4954 ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_TIMEOUT);
4955 /* timeout and this connection was waiting */
4956 set_ZOOM_error(c, ZOOM_ERROR_TIMEOUT, 0);
4958 ZOOM_connection_put_event(c, event);
4964 ZOOM_connection_process(ZOOM_connection c)
4970 event = ZOOM_connection_get_event(c);
4973 ZOOM_Event_destroy(event);
4976 ZOOM_connection_exec_task(c);
4977 event = ZOOM_connection_get_event(c);
4980 ZOOM_Event_destroy(event);
4987 ZOOM_event_nonblock(int no, ZOOM_connection *cs)
4991 yaz_log(log_details, "ZOOM_process_event(no=%d,cs=%p)", no, cs);
4993 for (i = 0; i<no; i++)
4995 ZOOM_connection c = cs[i];
4997 if (c && ZOOM_connection_process(c))
5003 ZOOM_API(int) ZOOM_connection_fire_event_socket(ZOOM_connection c, int mask)
5005 if (c->mask && mask)
5006 ZOOM_connection_do_io(c, mask);
5010 ZOOM_API(int) ZOOM_connection_get_socket(ZOOM_connection c)
5013 return cs_fileno(c->cs);
5017 ZOOM_API(int) ZOOM_connection_set_mask(ZOOM_connection c, int mask)
5025 ZOOM_API(int) ZOOM_connection_get_mask(ZOOM_connection c)
5032 ZOOM_API(int) ZOOM_connection_get_timeout(ZOOM_connection c)
5034 return ZOOM_options_get_int(c->options, "timeout", 30);
5037 ZOOM_API(void) ZOOM_connection_close(ZOOM_connection c)
5045 * c-file-style: "Stroustrup"
5046 * indent-tabs-mode: nil
5048 * vim: shiftwidth=4 tabstop=8 expandtab