1 /* $Id: pazpar2.c,v 1.77 2007-04-12 13:46:28 adam Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
27 #include <sys/socket.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/comstack.h>
35 #include <yaz/tcpip.h>
36 #include <yaz/proto.h>
37 #include <yaz/readconf.h>
38 #include <yaz/pquery.h>
39 #include <yaz/otherinfo.h>
40 #include <yaz/yaz-util.h>
42 #include <yaz/querytowrbuf.h>
43 #if YAZ_VERSIONL >= 0x020163
44 #include <yaz/oid_db.h>
53 #include <yaz/timing.h>
56 #include <netinet/in.h>
61 #include "termlists.h"
63 #include "relevance.h"
70 static void client_fatal(struct client *cl);
71 static void connection_destroy(struct connection *co);
72 static int client_prep_connection(struct client *cl);
73 static void ingest_records(struct client *cl, Z_Records *r);
74 void session_alert_watch(struct session *s, int what);
76 IOCHAN channel_list = 0; // Master list of connections we're handling events to
78 static struct connection *connection_freelist = 0;
79 static struct client *client_freelist = 0;
81 static char *client_states[] = {
85 "Client_Initializing",
90 "Client_Disconnected",
94 // Note: Some things in this structure will eventually move to configuration
95 struct parameters global_parameters =
105 "Index Data PazPar2 (MasterKey)",
115 static int send_apdu(struct client *c, Z_APDU *a)
117 struct connection *co = c->connection;
121 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
123 odr_perror(global_parameters.odr_out, "Encoding APDU");
126 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
127 r = cs_put(co->link, buf, len);
130 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
135 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
138 odr_reset(global_parameters.odr_out); /* release the APDU structure */
139 co->state = Conn_Waiting;
143 // Set authentication token in init if one is set for the client
144 // TODO: Extend this to handle other schemes than open (should be simple)
145 static void init_authentication(struct client *cl, Z_InitRequest *req)
147 struct session_database *sdb = cl->database;
148 char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
152 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
154 idAuth->which = Z_IdAuthentication_open;
155 idAuth->u.open = auth;
156 req->idAuthentication = idAuth;
160 static void send_init(IOCHAN i)
163 struct connection *co = iochan_getdata(i);
164 struct client *cl = co->client;
165 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
167 a->u.initRequest->implementationId = global_parameters.implementationId;
168 a->u.initRequest->implementationName = global_parameters.implementationName;
169 a->u.initRequest->implementationVersion =
170 global_parameters.implementationVersion;
171 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
172 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
173 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
175 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
176 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
177 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
179 init_authentication(cl, a->u.initRequest);
181 /* add virtual host if tunneling through Z39.50 proxy */
183 if (0 < strlen(global_parameters.zproxy_override)
184 && 0 < strlen(cl->database->database->url))
186 #if YAZ_VERSIONL >= 0x020163
187 const int *oid_proxy = yaz_string_to_oid(yaz_oid_std(),
188 CLASS_USERINFO, OID_STR_PROXY);
189 yaz_oi_set_string_oid(&a->u.initRequest->otherInfo,
190 global_parameters.odr_out, oid_proxy,
191 1, cl->database->database->url);
193 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
194 global_parameters.odr_out, VAL_PROXY,
195 1, cl->database->database->url);
199 if (send_apdu(cl, a) >= 0)
201 iochan_setflags(i, EVENT_INPUT);
202 cl->state = Client_Initializing;
205 cl->state = Client_Error;
206 odr_reset(global_parameters.odr_out);
209 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
217 pull_terms(nmem, n->u.p[0], termlist, num);
218 pull_terms(nmem, n->u.p[1], termlist, num);
221 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
228 // Extract terms from query into null-terminated termlist
229 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
233 pull_terms(nmem, query, termlist, &num);
237 static void send_search(IOCHAN i)
239 struct connection *co = iochan_getdata(i);
240 struct client *cl = co->client;
241 struct session *se = cl->session;
242 struct session_database *sdb = cl->database;
243 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
244 int ndb, cerror, cpos;
247 struct ccl_rpn_node *cn;
248 int ssub = 0, lslb = 100000, mspn = 10;
252 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
254 cn = ccl_find_str(sdb->database->ccl_map, se->query, &cerror, &cpos);
260 // Initialize relevance structure with query terms
262 extract_terms(se->nmem, cn, p);
263 se->relevance = relevance_create(se->nmem, (const char **) p,
264 se->expected_maxrecs);
267 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
269 zquery->which = Z_Query_type_1;
270 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
273 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
275 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
276 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
277 databaselist[ndb] = sdb->database->databases[ndb];
279 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
281 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
283 #if YAZ_VERSIONL >= 0x020163
284 a->u.searchRequest->preferredRecordSyntax =
285 yaz_string_to_oid_odr(yaz_oid_std(),
286 CLASS_RECSYN, recsyn,
287 global_parameters.odr_out);
289 a->u.searchRequest->preferredRecordSyntax =
290 yaz_str_to_z3950oid(global_parameters.odr_out,
291 CLASS_RECSYN, recsyn);
294 a->u.searchRequest->smallSetUpperBound = &ssub;
295 a->u.searchRequest->largeSetLowerBound = &lslb;
296 a->u.searchRequest->mediumSetPresentNumber = &mspn;
298 a->u.searchRequest->resultSetName = "Default";
299 a->u.searchRequest->databaseNames = databaselist;
300 a->u.searchRequest->num_databaseNames = ndb;
303 { //scope for sending and logging queries
304 WRBUF wbquery = wrbuf_alloc();
305 yaz_query_to_wrbuf(wbquery, zquery);
307 if (send_apdu(cl, a) >= 0)
309 iochan_setflags(i, EVENT_INPUT);
310 cl->state = Client_Searching;
311 cl->requestid = se->requestid;
312 yaz_log(YLOG_LOG, "SearchRequest %s %s",
313 cl->database->database->url, wrbuf_cstr(wbquery));
316 cl->state = Client_Error;
317 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s",
318 cl->database->database->url, wrbuf_cstr(wbquery));
321 wrbuf_destroy(wbquery);
324 odr_reset(global_parameters.odr_out);
327 static void send_present(IOCHAN i)
329 struct connection *co = iochan_getdata(i);
330 struct client *cl = co->client;
331 struct session_database *sdb = cl->database;
332 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
334 int start = cl->records + 1;
337 toget = global_parameters.chunk;
338 if (toget > global_parameters.toget - cl->records)
339 toget = global_parameters.toget - cl->records;
340 if (toget > cl->hits - cl->records)
341 toget = cl->hits - cl->records;
343 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
345 a->u.presentRequest->resultSetStartPoint = &start;
346 a->u.presentRequest->numberOfRecordsRequested = &toget;
348 a->u.presentRequest->resultSetId = "Default";
350 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
352 #if YAZ_VERSIONL >= 0x020163
353 a->u.presentRequest->preferredRecordSyntax =
354 yaz_string_to_oid_odr(yaz_oid_std(),
355 CLASS_RECSYN, recsyn,
356 global_parameters.odr_out);
358 a->u.presentRequest->preferredRecordSyntax =
359 yaz_str_to_z3950oid(global_parameters.odr_out,
360 CLASS_RECSYN, recsyn);
364 if (send_apdu(cl, a) >= 0)
366 iochan_setflags(i, EVENT_INPUT);
367 cl->state = Client_Presenting;
370 cl->state = Client_Error;
371 odr_reset(global_parameters.odr_out);
374 static void do_initResponse(IOCHAN i, Z_APDU *a)
376 struct connection *co = iochan_getdata(i);
377 struct client *cl = co->client;
378 Z_InitResponse *r = a->u.initResponse;
380 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
384 cl->state = Client_Idle;
387 cl->state = Client_Failed; // FIXME need to do something to the connection
390 static void do_searchResponse(IOCHAN i, Z_APDU *a)
392 struct connection *co = iochan_getdata(i);
393 struct client *cl = co->client;
394 struct session *se = cl->session;
395 Z_SearchResponse *r = a->u.searchResponse;
397 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
398 cl->database->database->url, *r->searchStatus);
400 if (*r->searchStatus)
402 cl->hits = *r->resultCount;
403 se->total_hits += cl->hits;
404 if (r->presentStatus && !*r->presentStatus && r->records)
406 yaz_log(YLOG_DEBUG, "Records in search response %s",
407 cl->database->database->url);
408 ingest_records(cl, r->records);
410 cl->state = Client_Idle;
415 cl->state = Client_Error;
417 Z_Records *recs = r->records;
418 if (recs->which == Z_Records_NSD)
421 "Search response: Non-surrogate diagnostic %s",
422 cl->database->database->url);
423 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
424 cl->state = Client_Error;
430 static void do_closeResponse(IOCHAN i, Z_APDU *a)
432 struct connection *co = iochan_getdata(i);
433 struct client *cl = co->client;
434 /* Z_Close *r = a->u.close; */
436 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
438 cl->state = Client_Failed;
439 connection_destroy(co);
443 char *normalize_mergekey(char *buf, int skiparticle)
445 char *p = buf, *pout = buf;
450 char articles[] = "the den der die des an a "; // must end in space
452 while (*p && !isalnum(*p))
455 while (*p && *p != ' ' && pout - firstword < 62)
456 *(pout++) = tolower(*(p++));
459 if (!strstr(articles, firstword))
466 while (*p && !isalnum(*p))
469 *(pout++) = tolower(*(p++));
472 while (*p && !isalnum(*p))
479 while (pout > buf && *pout == ' ');
484 static void add_facet(struct session *s, const char *type, const char *value)
490 for (i = 0; i < s->num_termlists; i++)
491 if (!strcmp(s->termlists[i].name, type))
493 if (i == s->num_termlists)
495 if (i == SESSION_MAX_TERMLISTS)
497 yaz_log(YLOG_FATAL, "Too many termlists");
500 s->termlists[i].name = nmem_strdup(s->nmem, type);
501 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
502 s->num_termlists = i + 1;
504 termlist_insert(s->termlists[i].termlist, value);
507 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
509 struct database_retrievalmap *m;
510 struct database *db = cl->database->database;
514 // First normalize to XML
519 if (rec->which != Z_External_octet)
521 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
522 cl->database->database->url);
525 buf = (char*) rec->u.octet_aligned->buf;
526 len = rec->u.octet_aligned->len;
527 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
529 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
530 cl->database->database->url);
534 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
535 if (yaz_marc_write_xml(db->yaz_marc, &res,
536 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
538 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
539 cl->database->database->url);
542 rdoc = xmlNewDoc((xmlChar *) "1.0");
543 xmlDocSetRootElement(rdoc, res);
549 "Unknown native_syntax in normalize_record from %s",
550 cl->database->database->url);
554 if (global_parameters.dump_records){
556 "Input Record (normalized) from %s\n----------------\n",
557 cl->database->database->url);
558 #if LIBXML_VERSION >= 20600
559 xmlDocFormatDump(stderr, rdoc, 1);
561 xmlDocDump(stderr, rdoc);
565 for (m = db->map; m; m = m->next){
571 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
572 root= xmlDocGetRootElement(new);
573 if (!new || !root || !(root->children))
575 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
576 cl->database->database->url);
585 // do it another way to detect transformation errors right now
586 // but does not seem to work either!
588 xsltTransformContextPtr ctxt;
589 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
590 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
591 if ((ctxt->state == XSLT_STATE_ERROR) ||
592 (ctxt->state == XSLT_STATE_STOPPED)){
593 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
594 cl->database->database->url);
605 if (global_parameters.dump_records)
607 fprintf(stderr, "Record from %s\n----------------\n",
608 cl->database->database->url);
609 #if LIBXML_VERSION >= 20600
610 xmlDocFormatDump(stderr, rdoc, 1);
612 xmlDocDump(stderr, rdoc);
618 // Extract what appears to be years from buf, storing highest and
620 static int extract_years(const char *buf, int *first, int *last)
629 while (*buf && !isdigit(*buf))
632 for (e = buf; *e && isdigit(*e); e++)
636 int value = atoi(buf);
637 if (*first < 0 || value < *first)
639 if (*last < 0 || value > *last)
647 static struct record *ingest_record(struct client *cl, Z_External *rec)
649 xmlDoc *xdoc = normalize_record(cl, rec);
652 struct record_cluster *cluster;
653 struct session *se = cl->session;
654 xmlChar *mergekey, *mergekey_norm;
657 struct conf_service *service = global_parameters.server->service;
662 root = xmlDocGetRootElement(xdoc);
663 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
665 yaz_log(YLOG_WARN, "No mergekey found in record");
670 res = nmem_malloc(se->nmem, sizeof(struct record));
673 res->metadata = nmem_malloc(se->nmem,
674 sizeof(struct record_metadata*) * service->num_metadata);
675 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
677 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
679 normalize_mergekey((char *) mergekey_norm, 0);
681 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
683 if (global_parameters.dump_records)
684 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
685 cl->database->database->url, cl->records);
688 /* no room for record */
692 relevance_newrec(se->relevance, cluster);
694 for (n = root->children; n; n = n->next)
702 if (n->type != XML_ELEMENT_NODE)
704 if (!strcmp((const char *) n->name, "metadata"))
706 struct conf_metadata *md = 0;
707 struct conf_sortkey *sk = 0;
708 struct record_metadata **wheretoput, *newm;
712 type = xmlGetProp(n, (xmlChar *) "type");
713 value = xmlNodeListGetString(xdoc, n->children, 0);
718 // First, find out what field we're looking at
719 for (imeta = 0; imeta < service->num_metadata; imeta++)
720 if (!strcmp((const char *) type, service->metadata[imeta].name))
722 md = &service->metadata[imeta];
723 if (md->sortkey_offset >= 0)
724 sk = &service->sortkeys[md->sortkey_offset];
729 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
733 // Find out where we are putting it
734 if (md->merge == Metadata_merge_no)
735 wheretoput = &res->metadata[imeta];
737 wheretoput = &cluster->metadata[imeta];
740 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
742 if (md->type == Metadata_type_generic)
745 for (p = (char *) value; *p && isspace(*p); p++)
747 for (pe = p + strlen(p) - 1;
748 pe > p && strchr(" ,/.:([", *pe); pe--)
750 newm->data.text = nmem_strdup(se->nmem, p);
753 else if (md->type == Metadata_type_year)
755 if (extract_years((char *) value, &first, &last) < 0)
760 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
763 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
765 yaz_log(YLOG_WARN, "Only range merging supported for years");
768 if (md->merge == Metadata_merge_unique)
770 struct record_metadata *mnode;
771 for (mnode = *wheretoput; mnode; mnode = mnode->next)
772 if (!strcmp((const char *) mnode->data.text, newm->data.text))
776 newm->next = *wheretoput;
780 else if (md->merge == Metadata_merge_longest)
783 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
788 char *s = nmem_strdup(se->nmem, newm->data.text);
789 if (!cluster->sortkeys[md->sortkey_offset])
790 cluster->sortkeys[md->sortkey_offset] =
791 nmem_malloc(se->nmem, sizeof(union data_types));
792 normalize_mergekey(s,
793 (sk->type == Metadata_sortkey_skiparticle));
794 cluster->sortkeys[md->sortkey_offset]->text = s;
798 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
800 newm->next = *wheretoput;
803 else if (md->merge == Metadata_merge_range)
805 assert(md->type == Metadata_type_year);
809 (*wheretoput)->data.number.min = first;
810 (*wheretoput)->data.number.max = last;
812 cluster->sortkeys[md->sortkey_offset] = &newm->data;
816 if (first < (*wheretoput)->data.number.min)
817 (*wheretoput)->data.number.min = first;
818 if (last > (*wheretoput)->data.number.max)
819 (*wheretoput)->data.number.max = last;
824 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
825 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
830 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
833 relevance_countwords(se->relevance, cluster,
834 (char *) value, md->rank);
837 if (md->type == Metadata_type_year)
840 sprintf(year, "%d", last);
841 add_facet(se, (char *) type, year);
844 sprintf(year, "%d", first);
845 add_facet(se, (char *) type, year);
849 add_facet(se, (char *) type, (char *) value);
856 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
865 relevance_donerecord(se->relevance, cluster);
871 // Retrieve first defined value for 'name' for given database.
872 // Will be extended to take into account user associated with session
873 char *session_setting_oneval(struct session_database *db, int offset)
875 if (!db->settings[offset])
877 return db->settings[offset]->value;
880 static void ingest_records(struct client *cl, Z_Records *r)
883 yaz_timing_t t = yaz_timing_create();
886 struct session *s = cl->session;
887 Z_NamePlusRecordList *rlist;
890 if (r->which != Z_Records_DBOSD)
892 rlist = r->u.databaseOrSurDiagnostics;
893 for (i = 0; i < rlist->num_records; i++)
895 Z_NamePlusRecord *npr = rlist->records[i];
898 if (npr->which != Z_NamePlusRecord_databaseRecord)
901 "Unexpected record type, probably diagnostic %s",
902 cl->database->database->url);
906 rec = ingest_record(cl, npr->u.databaseRecord);
910 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
911 session_alert_watch(s, SESSION_WATCH_RECORDS);
915 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
916 yaz_timing_get_real(t), yaz_timing_get_user(t),
917 yaz_timing_get_sys(t));
918 yaz_timing_destroy(&t);
922 static void do_presentResponse(IOCHAN i, Z_APDU *a)
924 struct connection *co = iochan_getdata(i);
925 struct client *cl = co->client;
926 Z_PresentResponse *r = a->u.presentResponse;
929 Z_Records *recs = r->records;
930 if (recs->which == Z_Records_NSD)
932 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
933 cl->database->database->url);
934 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
935 cl->state = Client_Error;
939 if (!*r->presentStatus && cl->state != Client_Error)
941 yaz_log(YLOG_DEBUG, "Good Present response %s",
942 cl->database->database->url);
943 ingest_records(cl, r->records);
944 cl->state = Client_Idle;
946 else if (*r->presentStatus)
948 yaz_log(YLOG_WARN, "Bad Present response %s",
949 cl->database->database->url);
950 cl->state = Client_Error;
954 static void handler(IOCHAN i, int event)
956 struct connection *co = iochan_getdata(i);
957 struct client *cl = co->client;
958 struct session *se = 0;
964 yaz_log(YLOG_WARN, "Destroying orphan connection");
965 connection_destroy(co);
969 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
972 socklen_t errlen = sizeof(errcode);
974 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
975 &errlen) < 0 || errcode != 0)
982 yaz_log(YLOG_DEBUG, "Connect OK");
983 co->state = Conn_Open;
985 cl->state = Client_Connected;
989 else if (event & EVENT_INPUT)
991 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
995 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
996 cl->database->database->url);
997 connection_destroy(co);
1002 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1003 connection_destroy(co);
1006 else if (len > 1) // We discard input if we have no connection
1008 co->state = Conn_Open;
1010 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1014 odr_reset(global_parameters.odr_in);
1015 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1016 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1023 case Z_APDU_initResponse:
1024 do_initResponse(i, a);
1026 case Z_APDU_searchResponse:
1027 do_searchResponse(i, a);
1029 case Z_APDU_presentResponse:
1030 do_presentResponse(i, a);
1033 do_closeResponse(i, a);
1037 "Unexpected Z39.50 response from %s",
1038 cl->database->database->url);
1042 // We aren't expecting staggered output from target
1043 // if (cs_more(t->link))
1044 // iochan_setevent(i, EVENT_INPUT);
1046 else // we throw away response and go to idle mode
1048 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1049 cl->state = Client_Idle;
1052 /* if len==1 we do nothing but wait for more input */
1055 if (cl->state == Client_Connected) {
1059 if (cl->state == Client_Idle)
1061 if (cl->requestid != se->requestid && *se->query) {
1064 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1065 cl->records < cl->hits) {
1071 // Disassociate connection from client
1072 static void connection_release(struct connection *co)
1074 struct client *cl = co->client;
1076 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1083 // Close connection and recycle structure
1084 static void connection_destroy(struct connection *co)
1086 struct host *h = co->host;
1088 iochan_destroy(co->iochan);
1090 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1091 if (h->connections == co)
1092 h->connections = co->next;
1095 struct connection *pco;
1096 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1099 pco->next = co->next;
1105 if (co->client->state != Client_Idle)
1106 co->client->state = Client_Disconnected;
1107 co->client->connection = 0;
1109 co->next = connection_freelist;
1110 connection_freelist = co;
1113 // Creates a new connection for client, associated with the host of
1114 // client's database
1115 static struct connection *connection_create(struct client *cl)
1117 struct connection *new;
1123 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1125 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1129 if (0 == strlen(global_parameters.zproxy_override)){
1130 /* no Z39.50 proxy needed - direct connect */
1131 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1133 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1135 yaz_log(YLOG_WARN|YLOG_ERRNO,
1136 "Lookup of IP address %s failed",
1137 cl->database->database->host->ipport);
1142 /* Z39.50 proxy connect */
1143 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1144 cl->database->database->url, global_parameters.zproxy_override);
1146 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1148 yaz_log(YLOG_WARN|YLOG_ERRNO,
1149 "Lookup of IP address %s failed",
1150 global_parameters.zproxy_override);
1155 res = cs_connect(link, addr);
1158 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1162 if ((new = connection_freelist))
1163 connection_freelist = new->next;
1166 new = xmalloc(sizeof (struct connection));
1170 new->state = Conn_Connecting;
1171 new->host = cl->database->database->host;
1172 new->next = new->host->connections;
1173 new->host->connections = new;
1175 cl->connection = new;
1178 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1179 iochan_setdata(new->iochan, new);
1180 new->iochan->next = channel_list;
1181 channel_list = new->iochan;
1185 // Close connection and set state to error
1186 static void client_fatal(struct client *cl)
1188 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1189 connection_destroy(cl->connection);
1190 cl->state = Client_Error;
1193 // Ensure that client has a connection associated
1194 static int client_prep_connection(struct client *cl)
1196 struct connection *co;
1197 struct session *se = cl->session;
1198 struct host *host = cl->database->database->host;
1200 co = cl->connection;
1202 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1206 // See if someone else has an idle connection
1207 // We should look at timestamps here to select the longest-idle connection
1208 for (co = host->connections; co; co = co->next)
1209 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1213 connection_release(co);
1214 cl->connection = co;
1218 co = connection_create(cl);
1222 if (co->state == Conn_Connecting)
1224 cl->state = Client_Connecting;
1225 iochan_setflag(co->iochan, EVENT_OUTPUT);
1227 else if (co->state == Conn_Open)
1229 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1230 cl->state = Client_Idle;
1231 iochan_setflag(co->iochan, EVENT_OUTPUT);
1239 static struct client *client_create(void)
1242 if (client_freelist)
1244 r = client_freelist;
1245 client_freelist = client_freelist->next;
1248 r = xmalloc(sizeof(struct client));
1257 r->state = Client_Disconnected;
1262 void client_destroy(struct client *c)
1264 struct session *se = c->session;
1265 if (c == se->clients)
1266 se->clients = c->next;
1270 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1276 connection_release(c->connection);
1277 c->next = client_freelist;
1278 client_freelist = c;
1281 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1283 s->watchlist[what].fun = fun;
1284 s->watchlist[what].data = data;
1287 void session_alert_watch(struct session *s, int what)
1289 if (!s->watchlist[what].fun)
1291 (*s->watchlist[what].fun)(s->watchlist[what].data);
1292 s->watchlist[what].fun = 0;
1293 s->watchlist[what].data = 0;
1296 //callback for grep_databases
1297 static void select_targets_callback(void *context, struct session_database *db)
1299 struct session *se = (struct session*) context;
1300 struct client *cl = client_create();
1303 cl->next = se->clients;
1307 // Associates a set of clients with a session;
1308 // Note: Session-databases represent databases with per-session setting overrides
1309 int select_targets(struct session *se, struct database_criterion *crit)
1312 client_destroy(se->clients);
1314 return session_grep_databases(se, crit, select_targets_callback);
1317 int session_active_clients(struct session *s)
1322 for (c = s->clients; c; c = c->next)
1323 if (c->connection && (c->state == Client_Connecting ||
1324 c->state == Client_Initializing ||
1325 c->state == Client_Searching ||
1326 c->state == Client_Presenting))
1332 // parses crit1=val1,crit2=val2|val3,...
1333 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1335 struct database_criterion *res = 0;
1342 nmem_strsplit(m, ",", buf, &values, &num);
1343 for (i = 0; i < num; i++)
1348 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1349 char *eq = strchr(values[i], '=');
1352 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1356 new->name = values[i];
1357 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1359 for (subi = 0; subi < subnum; subi++)
1361 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1362 newv->value = subvalues[subi];
1363 newv->next = new->values;
1372 char *search(struct session *se, char *query, char *filter)
1374 int live_channels = 0;
1376 struct database_criterion *criteria;
1378 yaz_log(YLOG_DEBUG, "Search");
1380 nmem_reset(se->nmem);
1381 criteria = parse_filter(se->nmem, filter);
1382 strcpy(se->query, query);
1384 select_targets(se, criteria);
1385 for (cl = se->clients; cl; cl = cl->next)
1387 if (client_prep_connection(cl))
1392 int maxrecs = live_channels * global_parameters.toget;
1393 se->num_termlists = 0;
1394 se->reclist = reclist_create(se->nmem, maxrecs);
1395 // This will be initialized in send_search()
1397 se->total_records = se->total_hits = se->total_merged = 0;
1398 se->expected_maxrecs = maxrecs;
1406 // Apply a session override to a database
1407 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1409 struct session_database *sdb;
1411 for (sdb = se->databases; sdb; sdb = sdb->next)
1412 if (!strcmp(dbname, sdb->database->url))
1414 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1415 int offset = settings_offset(setting);
1419 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1422 new->precedence = 0;
1423 new->target = dbname;
1424 new->name = setting;
1426 new->next = sdb->settings[offset];
1427 sdb->settings[offset] = new;
1431 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1434 void session_init_databases_fun(void *context, struct database *db)
1436 struct session *se = (struct session *) context;
1437 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1438 int num = settings_num();
1442 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1443 for (i = 0; i < num; i++)
1444 new->settings[i] = db->settings[i];
1445 new->next = se->databases;
1446 se->databases = new;
1449 // Initialize session_database list -- this represents this session's view
1450 // of the database list -- subject to modification by the settings ws command
1451 void session_init_databases(struct session *se)
1454 grep_databases(se, 0, session_init_databases_fun);
1457 void destroy_session(struct session *s)
1459 yaz_log(YLOG_LOG, "Destroying session");
1461 client_destroy(s->clients);
1462 nmem_destroy(s->nmem);
1463 wrbuf_destroy(s->wrbuf);
1466 struct session *new_session(NMEM nmem)
1469 struct session *session = nmem_malloc(nmem, sizeof(*session));
1471 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1473 session->total_hits = 0;
1474 session->total_records = 0;
1475 session->num_termlists = 0;
1476 session->reclist = 0;
1477 session->requestid = -1;
1478 session->clients = 0;
1479 session->expected_maxrecs = 0;
1480 session->query[0] = '\0';
1481 session->session_nmem = nmem;
1482 session->nmem = nmem_create();
1483 session->wrbuf = wrbuf_alloc();
1484 session_init_databases(session);
1485 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1487 session->watchlist[i].data = 0;
1488 session->watchlist[i].fun = 0;
1494 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1496 static struct hitsbytarget res[1000]; // FIXME MM
1500 for (cl = se->clients; cl; cl = cl->next)
1502 char *name = session_setting_oneval(cl->database, PZ_NAME);
1504 res[*count].id = cl->database->database->url;
1505 res[*count].name = *name ? name : "Unknown";
1506 res[*count].hits = cl->hits;
1507 res[*count].records = cl->records;
1508 res[*count].diagnostic = cl->diagnostic;
1509 res[*count].state = client_states[cl->state];
1510 res[*count].connected = cl->connection ? 1 : 0;
1517 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1521 for (i = 0; i < s->num_termlists; i++)
1522 if (!strcmp((const char *) s->termlists[i].name, name))
1523 return termlist_highscore(s->termlists[i].termlist, num);
1527 #ifdef MISSING_HEADERS
1528 void report_nmem_stats(void)
1530 size_t in_use, is_free;
1532 nmem_get_memory_in_use(&in_use);
1533 nmem_get_memory_free(&is_free);
1535 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1536 (long) in_use, (long) is_free);
1540 struct record_cluster *show_single(struct session *s, int id)
1542 struct record_cluster *r;
1544 reclist_rewind(s->reclist);
1545 while ((r = reclist_read_record(s->reclist)))
1551 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1552 int *num, int *total, int *sumhits, NMEM nmem_show)
1554 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1555 * sizeof(struct record_cluster *));
1556 struct reclist_sortparms *spp;
1559 yaz_timing_t t = yaz_timing_create();
1562 for (spp = sp; spp; spp = spp->next)
1563 if (spp->type == Metadata_sortkey_relevance)
1565 relevance_prepare_read(s->relevance, s->reclist);
1568 reclist_sort(s->reclist, sp);
1570 *total = s->reclist->num_records;
1571 *sumhits = s->total_hits;
1573 for (i = 0; i < start; i++)
1574 if (!reclist_read_record(s->reclist))
1581 for (i = 0; i < *num; i++)
1583 struct record_cluster *r = reclist_read_record(s->reclist);
1593 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1594 yaz_timing_get_real(t), yaz_timing_get_user(t),
1595 yaz_timing_get_sys(t));
1596 yaz_timing_destroy(&t);
1601 void statistics(struct session *se, struct statistics *stat)
1606 memset(stat, 0, sizeof(*stat));
1607 for (cl = se->clients; cl; cl = cl->next)
1609 if (!cl->connection)
1610 stat->num_no_connection++;
1613 case Client_Connecting: stat->num_connecting++; break;
1614 case Client_Initializing: stat->num_initializing++; break;
1615 case Client_Searching: stat->num_searching++; break;
1616 case Client_Presenting: stat->num_presenting++; break;
1617 case Client_Idle: stat->num_idle++; break;
1618 case Client_Failed: stat->num_failed++; break;
1619 case Client_Error: stat->num_error++; break;
1624 stat->num_hits = se->total_hits;
1625 stat->num_records = se->total_records;
1627 stat->num_clients = count;
1630 static void start_http_listener(void)
1633 struct conf_server *ser = global_parameters.server;
1635 if (*global_parameters.listener_override)
1636 strcpy(hp, global_parameters.listener_override);
1639 strcpy(hp, ser->host ? ser->host : "");
1644 sprintf(hp + strlen(hp), "%d", ser->port);
1650 static void start_proxy(void)
1653 struct conf_server *ser = global_parameters.server;
1655 if (*global_parameters.proxy_override)
1656 strcpy(hp, global_parameters.proxy_override);
1657 else if (ser->proxy_host || ser->proxy_port)
1659 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1660 if (ser->proxy_port)
1664 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1670 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1673 static void start_zproxy(void)
1675 struct conf_server *ser = global_parameters.server;
1677 if (*global_parameters.zproxy_override){
1678 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1679 global_parameters.zproxy_override);
1683 else if (ser->zproxy_host || ser->zproxy_port)
1687 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1688 if (ser->zproxy_port)
1695 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1697 strcpy(global_parameters.zproxy_override, hp);
1698 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1699 global_parameters.zproxy_override);
1708 int main(int argc, char **argv)
1713 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1714 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1716 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1718 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1722 if (!read_config(arg))
1726 strcpy(global_parameters.listener_override, arg);
1729 strcpy(global_parameters.proxy_override, arg);
1732 strcpy(global_parameters.zproxy_override, arg);
1735 strcpy(global_parameters.settings_path_override, arg);
1738 load_simpletargets(arg);
1741 global_parameters.dump_records = 1;
1744 fprintf(stderr, "Usage: pazpar2\n"
1746 " -h [host:]port (REST protocol listener)\n"
1748 " -s simpletargetfile\n"
1749 " -p hostname[:portno] (HTTP proxy)\n"
1750 " -z hostname[:portno] (Z39.50 proxy)\n"
1751 " -d (show internal records)\n");
1758 yaz_log(YLOG_FATAL, "Load config with -f");
1761 global_parameters.server = config->servers;
1763 start_http_listener();
1767 if (*global_parameters.settings_path_override)
1768 settings_read(global_parameters.settings_path_override);
1769 else if (global_parameters.server->settings)
1770 settings_read(global_parameters.server->settings);
1772 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1773 prepare_databases();
1774 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1775 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1777 event_loop(&channel_list);
1785 * indent-tabs-mode: nil
1787 * vim: shiftwidth=4 tabstop=8 expandtab