- if (r->records) {
- Z_Records *recs = r->records;
- if (recs->which == Z_Records_NSD)
- {
- yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
- cl->database->database->url);
- cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
- cl->state = Client_Error;
- }
- }
-
- if (!*r->presentStatus && cl->state != Client_Error)
- {
- yaz_log(YLOG_DEBUG, "Good Present response %s",
- cl->database->database->url);
- ingest_records(cl, r->records);
- cl->state = Client_Idle;
- }
- else if (*r->presentStatus)
- {
- yaz_log(YLOG_WARN, "Bad Present response %s",
- cl->database->database->url);
- cl->state = Client_Error;
- }
-}
-
-static void handler(IOCHAN i, int event)
-{
- struct connection *co = iochan_getdata(i);
- struct client *cl = co->client;
- struct session *se = 0;
-
- if (cl)
- se = cl->session;
- else
- {
- yaz_log(YLOG_WARN, "Destroying orphan connection");
- connection_destroy(co);
- return;
- }
-
- if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
- {
- int errcode;
- socklen_t errlen = sizeof(errcode);
-
- if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
- &errlen) < 0 || errcode != 0)
- {
- client_fatal(cl);
- return;
- }
- else
- {
- yaz_log(YLOG_DEBUG, "Connect OK");
- co->state = Conn_Open;
- if (cl)
- cl->state = Client_Connected;
- }
- }
-
- else if (event & EVENT_INPUT)
- {
- int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
-
- if (len < 0)
- {
- yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
- cl->database->database->url);
- connection_destroy(co);
- return;
- }
- else if (len == 0)
- {
- yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
- connection_destroy(co);
- return;
- }
- else if (len > 1) // We discard input if we have no connection
- {
- co->state = Conn_Open;
-
- if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
- {
- Z_APDU *a;
-
- odr_reset(global_parameters.odr_in);
- odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
- if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
- {
- client_fatal(cl);
- return;
- }
- switch (a->which)
- {
- case Z_APDU_initResponse:
- do_initResponse(i, a);
- break;
- case Z_APDU_searchResponse:
- do_searchResponse(i, a);
- break;
- case Z_APDU_presentResponse:
- do_presentResponse(i, a);
- break;
- case Z_APDU_close:
- do_closeResponse(i, a);
- break;
- default:
- yaz_log(YLOG_WARN,
- "Unexpected Z39.50 response from %s",
- cl->database->database->url);
- client_fatal(cl);
- return;
- }
- // We aren't expecting staggered output from target
- // if (cs_more(t->link))
- // iochan_setevent(i, EVENT_INPUT);
- }
- else // we throw away response and go to idle mode
- {
- yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
- cl->state = Client_Idle;
- }
- }
- /* if len==1 we do nothing but wait for more input */
- }
-
- if (cl->state == Client_Connected) {
- send_init(i);
- }
-
- if (cl->state == Client_Idle)
- {
- if (cl->requestid != se->requestid && *se->query) {
- send_search(i);
- }
- else if (cl->hits > 0 && cl->records < global_parameters.toget &&
- cl->records < cl->hits) {
- send_present(i);
- }
- }
-}
-
-// Disassociate connection from client
-static void connection_release(struct connection *co)
-{
- struct client *cl = co->client;
-
- yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
- if (!cl)
- return;
- cl->connection = 0;
- co->client = 0;
-}
-
-// Close connection and recycle structure
-static void connection_destroy(struct connection *co)
-{
- struct host *h = co->host;
- cs_close(co->link);
- iochan_destroy(co->iochan);
-
- yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
- if (h->connections == co)
- h->connections = co->next;
- else
- {
- struct connection *pco;
- for (pco = h->connections; pco && pco->next != co; pco = pco->next)
- ;
- if (pco)
- pco->next = co->next;
- else
- abort();
- }
- if (co->client)
- {
- if (co->client->state != Client_Idle)
- co->client->state = Client_Disconnected;
- co->client->connection = 0;
- }
- co->next = connection_freelist;
- connection_freelist = co;
-}
-
-// Creates a new connection for client, associated with the host of
-// client's database
-static struct connection *connection_create(struct client *cl)
-{
- struct connection *new;
- COMSTACK link;
- int res;
- void *addr;
-
-
- if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
- {
- yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
- exit(1);
- }
-
- if (0 == strlen(global_parameters.zproxy_override)){
- /* no Z39.50 proxy needed - direct connect */
- yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
-
- if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
- {
- yaz_log(YLOG_WARN|YLOG_ERRNO,
- "Lookup of IP address %s failed",
- cl->database->database->host->ipport);
- return 0;
- }
-
- } else {
- /* Z39.50 proxy connect */
- yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
- cl->database->database->url, global_parameters.zproxy_override);
-
- if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
- {
- yaz_log(YLOG_WARN|YLOG_ERRNO,
- "Lookup of IP address %s failed",
- global_parameters.zproxy_override);
- return 0;
- }
- }
-
- res = cs_connect(link, addr);
- if (res < 0)
- {
- yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
- return 0;
- }
-
- if ((new = connection_freelist))
- connection_freelist = new->next;
- else
- {
- new = xmalloc(sizeof (struct connection));
- new->ibuf = 0;
- new->ibufsize = 0;
- }
- new->state = Conn_Connecting;
- new->host = cl->database->database->host;
- new->next = new->host->connections;
- new->host->connections = new;
- new->client = cl;
- cl->connection = new;
- new->link = link;
-
- new->iochan = iochan_create(cs_fileno(link), handler, 0);
- iochan_setdata(new->iochan, new);
- new->iochan->next = channel_list;
- channel_list = new->iochan;
- return new;
-}
-
-// Close connection and set state to error
-static void client_fatal(struct client *cl)
-{
- yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
- connection_destroy(cl->connection);
- cl->state = Client_Error;
-}
-
-// Ensure that client has a connection associated
-static int client_prep_connection(struct client *cl)
-{
- struct connection *co;
- struct session *se = cl->session;
- struct host *host = cl->database->database->host;
-
- co = cl->connection;
-
- yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
-
- if (!co)
- {
- // See if someone else has an idle connection
- // We should look at timestamps here to select the longest-idle connection
- for (co = host->connections; co; co = co->next)
- if (co->state == Conn_Open && (!co->client || co->client->session != se))
- break;
- if (co)
- {
- connection_release(co);
- cl->connection = co;
- co->client = cl;
- }
- else
- co = connection_create(cl);
- }
- if (co)
- {
- if (co->state == Conn_Connecting)
- {
- cl->state = Client_Connecting;
- iochan_setflag(co->iochan, EVENT_OUTPUT);
- }
- else if (co->state == Conn_Open)
- {
- if (cl->state == Client_Error || cl->state == Client_Disconnected)
- cl->state = Client_Idle;
- iochan_setflag(co->iochan, EVENT_OUTPUT);
- }
- return 1;
- }
- else
- return 0;
-}
-
-static struct client *client_create(void)
-{
- struct client *r;
- if (client_freelist)
- {
- r = client_freelist;
- client_freelist = client_freelist->next;
- }
- else
- r = xmalloc(sizeof(struct client));
- r->database = 0;
- r->connection = 0;
- r->session = 0;
- r->hits = 0;
- r->records = 0;
- r->setno = 0;
- r->requestid = -1;
- r->diagnostic = 0;
- r->state = Client_Disconnected;
- r->next = 0;
- return r;
-}
-
-void client_destroy(struct client *c)
-{
- struct session *se = c->session;
- if (c == se->clients)
- se->clients = c->next;
- else
- {
- struct client *cc;
- for (cc = se->clients; cc && cc->next != c; cc = cc->next)
- ;
- if (cc)
- cc->next = c->next;
- }
- if (c->connection)
- connection_release(c->connection);
- c->next = client_freelist;
- client_freelist = c;
-}
-
-void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
-{
- s->watchlist[what].fun = fun;
- s->watchlist[what].data = data;
-}
-
-void session_alert_watch(struct session *s, int what)
-{
- if (!s->watchlist[what].fun)
- return;
- (*s->watchlist[what].fun)(s->watchlist[what].data);
- s->watchlist[what].fun = 0;
- s->watchlist[what].data = 0;
-}
-
-//callback for grep_databases
-static void select_targets_callback(void *context, struct session_database *db)
-{
- struct session *se = (struct session*) context;
- struct client *cl = client_create();
- cl->database = db;
- cl->session = se;
- cl->next = se->clients;
- se->clients = cl;
-}
-
-// Associates a set of clients with a session;
-// Note: Session-databases represent databases with per-session setting overrides
-int select_targets(struct session *se, struct database_criterion *crit)
-{
- while (se->clients)
- client_destroy(se->clients);
-
- return session_grep_databases(se, crit, select_targets_callback);
-}
-
-int session_active_clients(struct session *s)
-{
- struct client *c;
- int res = 0;
-
- for (c = s->clients; c; c = c->next)
- if (c->connection && (c->state == Client_Connecting ||
- c->state == Client_Initializing ||
- c->state == Client_Searching ||
- c->state == Client_Presenting))
- res++;
-
- return res;
-}
-
-// parses crit1=val1,crit2=val2|val3,...
-static struct database_criterion *parse_filter(NMEM m, const char *buf)
-{
- struct database_criterion *res = 0;
- char **values;
- int num;
- int i;
-
- if (!buf || !*buf)
- return 0;
- nmem_strsplit(m, ",", buf, &values, &num);
- for (i = 0; i < num; i++)
- {
- char **subvalues;
- int subnum;
- int subi;
- struct database_criterion *new = nmem_malloc(m, sizeof(*new));
- char *eq = strchr(values[i], '=');
- if (!eq)
- {
- yaz_log(YLOG_WARN, "Missing equal-sign in filter");
- return 0;
- }
- *(eq++) = '\0';
- new->name = values[i];
- nmem_strsplit(m, "|", eq, &subvalues, &subnum);
- new->values = 0;
- for (subi = 0; subi < subnum; subi++)
- {
- struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
- newv->value = subvalues[subi];
- newv->next = new->values;
- new->values = newv;
- }
- new->next = res;
- res = new;
- }
- return res;
-}
-
-char *search(struct session *se, char *query, char *filter)
-{
- int live_channels = 0;
- struct client *cl;
- struct database_criterion *criteria;
-
- yaz_log(YLOG_DEBUG, "Search");
-
- nmem_reset(se->nmem);
- criteria = parse_filter(se->nmem, filter);
- strcpy(se->query, query);
- se->requestid++;
- select_targets(se, criteria);
- for (cl = se->clients; cl; cl = cl->next)
- {
- if (client_prep_connection(cl))
- live_channels++;
- }
- if (live_channels)
- {
- int maxrecs = live_channels * global_parameters.toget;
- se->num_termlists = 0;
- se->reclist = reclist_create(se->nmem, maxrecs);
- // This will be initialized in send_search()
- se->relevance = 0;
- se->total_records = se->total_hits = se->total_merged = 0;
- se->expected_maxrecs = maxrecs;
- }
- else
- return "NOTARGETS";
-
- return 0;
-}
-
-// Apply a session override to a database
-void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
-{
- struct session_database *sdb;
-
- for (sdb = se->databases; sdb; sdb = sdb->next)
- if (!strcmp(dbname, sdb->database->url))
- {
- struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
- int offset = settings_offset(setting);
-
- if (offset < 0)
- {
- yaz_log(YLOG_WARN, "Unknown setting %s", setting);
- return;
- }
- new->precedence = 0;
- new->target = dbname;
- new->name = setting;
- new->value = value;
- new->next = sdb->settings[offset];
- sdb->settings[offset] = new;
- break;
- }
- if (!sdb)
- yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
-}
-
-void session_init_databases_fun(void *context, struct database *db)
-{
- struct session *se = (struct session *) context;
- struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
- int num = settings_num();
- int i;
-
- new->database = db;
- new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
- for (i = 0; i < num; i++)
- new->settings[i] = db->settings[i];
- new->next = se->databases;
- se->databases = new;
-}
-
-// Initialize session_database list -- this represents this session's view
-// of the database list -- subject to modification by the settings ws command
-void session_init_databases(struct session *se)
-{
- se->databases = 0;
- grep_databases(se, 0, session_init_databases_fun);
-}
-
-void destroy_session(struct session *s)
-{
- yaz_log(YLOG_LOG, "Destroying session");
- while (s->clients)
- client_destroy(s->clients);
- nmem_destroy(s->nmem);
- wrbuf_destroy(s->wrbuf);
-}
-
-struct session *new_session(NMEM nmem)
-{
- int i;
- struct session *session = nmem_malloc(nmem, sizeof(*session));
-
- yaz_log(YLOG_DEBUG, "New Pazpar2 session");
-
- session->total_hits = 0;
- session->total_records = 0;
- session->num_termlists = 0;
- session->reclist = 0;
- session->requestid = -1;
- session->clients = 0;
- session->expected_maxrecs = 0;
- session->query[0] = '\0';
- session->session_nmem = nmem;
- session->nmem = nmem_create();
- session->wrbuf = wrbuf_alloc();
- session_init_databases(session);
- for (i = 0; i <= SESSION_WATCH_MAX; i++)
- {
- session->watchlist[i].data = 0;
- session->watchlist[i].fun = 0;
- }
-
- return session;
-}
-
-struct hitsbytarget *hitsbytarget(struct session *se, int *count)
-{
- static struct hitsbytarget res[1000]; // FIXME MM
- struct client *cl;
-
- *count = 0;
- for (cl = se->clients; cl; cl = cl->next)
- {
- char *name = session_setting_oneval(cl->database, PZ_NAME);
-
- res[*count].id = cl->database->database->url;
- res[*count].name = *name ? name : "Unknown";
- res[*count].hits = cl->hits;
- res[*count].records = cl->records;
- res[*count].diagnostic = cl->diagnostic;
- res[*count].state = client_states[cl->state];
- res[*count].connected = cl->connection ? 1 : 0;
- (*count)++;
- }
-
- return res;
-}
-
-struct termlist_score **termlist(struct session *s, const char *name, int *num)
-{
- int i;
-
- for (i = 0; i < s->num_termlists; i++)
- if (!strcmp((const char *) s->termlists[i].name, name))
- return termlist_highscore(s->termlists[i].termlist, num);
- return 0;
-}
-
-#ifdef MISSING_HEADERS
-void report_nmem_stats(void)
-{
- size_t in_use, is_free;
-
- nmem_get_memory_in_use(&in_use);
- nmem_get_memory_free(&is_free);
-
- yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
- (long) in_use, (long) is_free);
-}
-#endif
-
-struct record_cluster *show_single(struct session *s, int id)
-{
- struct record_cluster *r;
-
- reclist_rewind(s->reclist);
- while ((r = reclist_read_record(s->reclist)))
- if (r->recid == id)
- return r;
- return 0;
-}
-
-struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
- int *num, int *total, int *sumhits, NMEM nmem_show)
-{
- struct record_cluster **recs = nmem_malloc(nmem_show, *num
- * sizeof(struct record_cluster *));
- struct reclist_sortparms *spp;
- int i;
-#if USE_TIMING
- yaz_timing_t t = yaz_timing_create();
-#endif
-
- for (spp = sp; spp; spp = spp->next)
- if (spp->type == Metadata_sortkey_relevance)
- {
- relevance_prepare_read(s->relevance, s->reclist);
- break;
- }
- reclist_sort(s->reclist, sp);
-
- *total = s->reclist->num_records;
- *sumhits = s->total_hits;
-
- for (i = 0; i < start; i++)
- if (!reclist_read_record(s->reclist))
- {
- *num = 0;
- recs = 0;
- break;
- }
-
- for (i = 0; i < *num; i++)
- {
- struct record_cluster *r = reclist_read_record(s->reclist);
- if (!r)
- {
- *num = i;
- break;
- }
- recs[i] = r;
- }
-#if USE_TIMING
- yaz_timing_stop(t);
- yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
- yaz_timing_get_real(t), yaz_timing_get_user(t),
- yaz_timing_get_sys(t));
- yaz_timing_destroy(&t);
-#endif
- return recs;
-}
-
-void statistics(struct session *se, struct statistics *stat)
-{
- struct client *cl;
- int count = 0;
-
- memset(stat, 0, sizeof(*stat));
- for (cl = se->clients; cl; cl = cl->next)
- {
- if (!cl->connection)
- stat->num_no_connection++;
- switch (cl->state)
- {
- case Client_Connecting: stat->num_connecting++; break;
- case Client_Initializing: stat->num_initializing++; break;
- case Client_Searching: stat->num_searching++; break;
- case Client_Presenting: stat->num_presenting++; break;
- case Client_Idle: stat->num_idle++; break;
- case Client_Failed: stat->num_failed++; break;
- case Client_Error: stat->num_error++; break;
- default: break;
- }
- count++;
- }
- stat->num_hits = se->total_hits;
- stat->num_records = se->total_records;
-
- stat->num_clients = count;
-}
-
-static void start_http_listener(void)
-{
- char hp[128] = "";
- struct conf_server *ser = global_parameters.server;
-
- if (*global_parameters.listener_override)
- strcpy(hp, global_parameters.listener_override);
- else
- {
- strcpy(hp, ser->host ? ser->host : "");
- if (ser->port)
- {
- if (*hp)
- strcat(hp, ":");
- sprintf(hp + strlen(hp), "%d", ser->port);
- }
- }
- http_init(hp);
-}
-
-static void start_proxy(void)
-{
- char hp[128] = "";
- struct conf_server *ser = global_parameters.server;
-
- if (*global_parameters.proxy_override)
- strcpy(hp, global_parameters.proxy_override);
- else if (ser->proxy_host || ser->proxy_port)
- {
- strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
- if (ser->proxy_port)
- {
- if (*hp)
- strcat(hp, ":");
- sprintf(hp + strlen(hp), "%d", ser->proxy_port);
- }
- }
- else
- return;
-
- http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
-}
-
-static void start_zproxy(void)
-{
- struct conf_server *ser = global_parameters.server;
-
- if (*global_parameters.zproxy_override){
- yaz_log(YLOG_LOG, "Z39.50 proxy %s",
- global_parameters.zproxy_override);
- return;
- }
-
- else if (ser->zproxy_host || ser->zproxy_port)
- {
- char hp[128] = "";
-
- strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
- if (ser->zproxy_port)
- {
- if (*hp)
- strcat(hp, ":");
- else
- strcat(hp, "@:");
-
- sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
- }
- strcpy(global_parameters.zproxy_override, hp);
- yaz_log(YLOG_LOG, "Z39.50 proxy %s",
- global_parameters.zproxy_override);
-
- }
- else
- return;
-}
-
-
-
-int main(int argc, char **argv)
-{
- int ret;
- char *arg;
-
- if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
- yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
-
- yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
-
- while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
- {
- switch (ret) {
- case 'f':
- if (!read_config(arg))
- exit(1);
- break;
- case 'h':
- strcpy(global_parameters.listener_override, arg);
- break;
- case 'p':
- strcpy(global_parameters.proxy_override, arg);
- break;
- case 'z':
- strcpy(global_parameters.zproxy_override, arg);
- break;
- case 't':
- strcpy(global_parameters.settings_path_override, arg);
- break;
- case 's':
- load_simpletargets(arg);
- break;
- case 'd':
- global_parameters.dump_records = 1;
- break;
- default:
- fprintf(stderr, "Usage: pazpar2\n"
- " -f configfile\n"
- " -h [host:]port (REST protocol listener)\n"
- " -C cclconfig\n"
- " -s simpletargetfile\n"
- " -p hostname[:portno] (HTTP proxy)\n"
- " -z hostname[:portno] (Z39.50 proxy)\n"
- " -d (show internal records)\n");
- exit(1);
- }
- }
-
- if (!config)
- {
- yaz_log(YLOG_FATAL, "Load config with -f");
- exit(1);
- }
- global_parameters.server = config->servers;
-
- start_http_listener();
- start_proxy();
- start_zproxy();
-
- if (*global_parameters.settings_path_override)
- settings_read(global_parameters.settings_path_override);
- else if (global_parameters.server->settings)
- settings_read(global_parameters.server->settings);
- else
- yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
- prepare_databases();
- global_parameters.odr_in = odr_createmem(ODR_DECODE);
- global_parameters.odr_out = odr_createmem(ODR_ENCODE);
-
- event_loop(&channel_list);
-
- return 0;
-}
-
-/*
- * Local variables:
- * c-basic-offset: 4
- * indent-tabs-mode: nil
- * End:
- * vim: shiftwidth=4 tabstop=8 expandtab
- */