1 /* $Id: pazpar2.c,v 1.62 2007-04-04 21:05:37 marc Exp $ */
8 #include <sys/socket.h>
14 #include <yaz/marcdisp.h>
15 #include <yaz/comstack.h>
16 #include <yaz/tcpip.h>
17 #include <yaz/proto.h>
18 #include <yaz/readconf.h>
19 #include <yaz/pquery.h>
20 #include <yaz/otherinfo.h>
21 #include <yaz/yaz-util.h>
30 #include <yaz/timing.h>
33 #include <netinet/in.h>
38 #include "termlists.h"
40 #include "relevance.h"
47 static void client_fatal(struct client *cl);
48 static void connection_destroy(struct connection *co);
49 static int client_prep_connection(struct client *cl);
50 static void ingest_records(struct client *cl, Z_Records *r);
51 //static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
52 void session_alert_watch(struct session *s, int what);
53 char *session_setting_oneval(struct session *s, struct database *db, const char *name);
55 IOCHAN channel_list = 0; // Master list of connections we're handling events to
57 static struct connection *connection_freelist = 0;
58 static struct client *client_freelist = 0;
60 static char *client_states[] = {
64 "Client_Initializing",
69 "Client_Disconnected",
73 // Note: Some things in this structure will eventually move to configuration
74 struct parameters global_parameters =
84 "Index Data PazPar2 (MasterKey)",
95 static int send_apdu(struct client *c, Z_APDU *a)
97 struct connection *co = c->connection;
101 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
103 odr_perror(global_parameters.odr_out, "Encoding APDU");
106 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
107 r = cs_put(co->link, buf, len);
110 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
115 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
118 odr_reset(global_parameters.odr_out); /* release the APDU structure */
119 co->state = Conn_Waiting;
124 static void send_init(IOCHAN i)
127 struct connection *co = iochan_getdata(i);
128 struct client *cl = co->client;
129 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
131 a->u.initRequest->implementationId = global_parameters.implementationId;
132 a->u.initRequest->implementationName = global_parameters.implementationName;
133 a->u.initRequest->implementationVersion =
134 global_parameters.implementationVersion;
135 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
136 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
137 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
139 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
140 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
141 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
144 /* add virtual host if tunneling through Z39.50 proxy */
146 if (0 < strlen(global_parameters.zproxy_override)
147 && 0 < strlen(cl->database->url))
148 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
149 global_parameters.odr_out, VAL_PROXY,
150 1, cl->database->url);
154 if (send_apdu(cl, a) >= 0)
156 iochan_setflags(i, EVENT_INPUT);
157 cl->state = Client_Initializing;
160 cl->state = Client_Error;
161 odr_reset(global_parameters.odr_out);
164 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
172 pull_terms(nmem, n->u.p[0], termlist, num);
173 pull_terms(nmem, n->u.p[1], termlist, num);
176 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
183 // Extract terms from query into null-terminated termlist
184 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
188 pull_terms(nmem, query, termlist, &num);
192 static void send_search(IOCHAN i)
194 struct connection *co = iochan_getdata(i);
195 struct client *cl = co->client;
196 struct session *se = cl->session;
197 struct database *db = cl->database;
198 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
199 int ndb, cerror, cpos;
202 struct ccl_rpn_node *cn;
203 int ssub = 0, lslb = 100000, mspn = 10;
207 yaz_log(YLOG_DEBUG, "Sending search");
209 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
215 // Initialize relevance structure with query terms
217 extract_terms(se->nmem, cn, p);
218 se->relevance = relevance_create(se->nmem, (const char **) p,
219 se->expected_maxrecs);
222 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
224 zquery->which = Z_Query_type_1;
225 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
228 for (ndb = 0; db->databases[ndb]; ndb++)
230 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
231 for (ndb = 0; db->databases[ndb]; ndb++)
232 databaselist[ndb] = db->databases[ndb];
234 if (!(piggyback = session_setting_oneval(se, db, "pz:piggyback")) || *piggyback == '1')
236 if ((recsyn = session_setting_oneval(se, db, "pz:syntax")))
237 a->u.searchRequest->preferredRecordSyntax =
238 yaz_str_to_z3950oid(global_parameters.odr_out,
239 CLASS_RECSYN, recsyn);
240 a->u.searchRequest->smallSetUpperBound = &ssub;
241 a->u.searchRequest->largeSetLowerBound = &lslb;
242 a->u.searchRequest->mediumSetPresentNumber = &mspn;
244 a->u.searchRequest->resultSetName = "Default";
245 a->u.searchRequest->databaseNames = databaselist;
246 a->u.searchRequest->num_databaseNames = ndb;
248 if (send_apdu(cl, a) >= 0)
250 iochan_setflags(i, EVENT_INPUT);
251 cl->state = Client_Searching;
252 cl->requestid = se->requestid;
255 cl->state = Client_Error;
257 odr_reset(global_parameters.odr_out);
260 static void send_present(IOCHAN i)
262 struct connection *co = iochan_getdata(i);
263 struct client *cl = co->client;
264 struct session *se = cl->session;
265 struct database *db = cl->database;
266 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
268 int start = cl->records + 1;
271 toget = global_parameters.chunk;
272 if (toget > global_parameters.toget - cl->records)
273 toget = global_parameters.toget - cl->records;
274 if (toget > cl->hits - cl->records)
275 toget = cl->hits - cl->records;
277 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
279 a->u.presentRequest->resultSetStartPoint = &start;
280 a->u.presentRequest->numberOfRecordsRequested = &toget;
282 a->u.presentRequest->resultSetId = "Default";
284 if ((recsyn = session_setting_oneval(se, db, "pz:syntax")))
285 a->u.presentRequest->preferredRecordSyntax =
286 yaz_str_to_z3950oid(global_parameters.odr_out,
287 CLASS_RECSYN, recsyn);
289 if (send_apdu(cl, a) >= 0)
291 iochan_setflags(i, EVENT_INPUT);
292 cl->state = Client_Presenting;
295 cl->state = Client_Error;
296 odr_reset(global_parameters.odr_out);
299 static void do_initResponse(IOCHAN i, Z_APDU *a)
301 struct connection *co = iochan_getdata(i);
302 struct client *cl = co->client;
303 Z_InitResponse *r = a->u.initResponse;
305 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->url);
309 cl->state = Client_Idle;
312 cl->state = Client_Failed; // FIXME need to do something to the connection
315 static void do_searchResponse(IOCHAN i, Z_APDU *a)
317 struct connection *co = iochan_getdata(i);
318 struct client *cl = co->client;
319 struct session *se = cl->session;
320 Z_SearchResponse *r = a->u.searchResponse;
322 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
323 cl->database->url, *r->searchStatus);
325 if (*r->searchStatus)
327 cl->hits = *r->resultCount;
328 se->total_hits += cl->hits;
329 if (r->presentStatus && !*r->presentStatus && r->records)
331 yaz_log(YLOG_DEBUG, "Records in search response %s",
333 ingest_records(cl, r->records);
335 cl->state = Client_Idle;
340 cl->state = Client_Error;
342 Z_Records *recs = r->records;
343 if (recs->which == Z_Records_NSD)
346 "Search response: Non-surrogate diagnostic %s",
348 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
349 cl->state = Client_Error;
355 static void do_closeResponse(IOCHAN i, Z_APDU *a)
357 struct connection *co = iochan_getdata(i);
358 struct client *cl = co->client;
359 /* Z_Close *r = a->u.close; */
361 yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
363 cl->state = Client_Failed;
364 connection_destroy(co);
368 char *normalize_mergekey(char *buf, int skiparticle)
370 char *p = buf, *pout = buf;
375 char articles[] = "the den der die des an a "; // must end in space
377 while (*p && !isalnum(*p))
380 while (*p && *p != ' ' && pout - firstword < 62)
381 *(pout++) = tolower(*(p++));
384 if (!strstr(articles, firstword))
391 while (*p && !isalnum(*p))
394 *(pout++) = tolower(*(p++));
397 while (*p && !isalnum(*p))
404 while (pout > buf && *pout == ' ');
409 static void add_facet(struct session *s, const char *type, const char *value)
415 for (i = 0; i < s->num_termlists; i++)
416 if (!strcmp(s->termlists[i].name, type))
418 if (i == s->num_termlists)
420 if (i == SESSION_MAX_TERMLISTS)
422 yaz_log(YLOG_FATAL, "Too many termlists");
425 s->termlists[i].name = nmem_strdup(s->nmem, type);
426 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
427 s->num_termlists = i + 1;
429 termlist_insert(s->termlists[i].termlist, value);
432 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
434 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
435 struct conf_retrievalmap *m;
439 // First normalize to XML
440 if (rprofile->native_syntax == Nativesyn_iso2709)
444 if (rec->which != Z_External_octet)
446 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
449 buf = (char*) rec->u.octet_aligned->buf;
450 len = rec->u.octet_aligned->len;
451 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
453 yaz_log(YLOG_WARN, "Failed to decode MARC");
456 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
457 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
459 yaz_log(YLOG_WARN, "Failed to encode as XML");
462 rdoc = xmlNewDoc((xmlChar *) "1.0");
463 xmlDocSetRootElement(rdoc, res);
467 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
471 if (global_parameters.dump_records)
473 fprintf(stderr, "Input Record (normalized):\n----------------\n");
474 #if LIBXML_VERSION >= 20600
475 xmlDocFormatDump(stderr, rdoc, 1);
477 xmlDocDump(stderr, rdoc);
481 for (m = rprofile->maplist; m; m = m->next)
484 if (m->type != Map_xslt)
486 yaz_log(YLOG_WARN, "Unknown map type");
489 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
491 yaz_log(YLOG_WARN, "XSLT transformation failed");
497 if (global_parameters.dump_records)
499 fprintf(stderr, "Record:\n----------------\n");
500 #if LIBXML_VERSION >= 20600
501 xmlDocFormatDump(stderr, rdoc, 1);
503 xmlDocDump(stderr, rdoc);
509 // Extract what appears to be years from buf, storing highest and
511 static int extract_years(const char *buf, int *first, int *last)
520 while (*buf && !isdigit(*buf))
523 for (e = buf; *e && isdigit(*e); e++)
527 int value = atoi(buf);
528 if (*first < 0 || value < *first)
530 if (*last < 0 || value > *last)
538 static struct record *ingest_record(struct client *cl, Z_External *rec)
540 xmlDoc *xdoc = normalize_record(cl, rec);
543 struct record_cluster *cluster;
544 struct session *se = cl->session;
545 xmlChar *mergekey, *mergekey_norm;
548 struct conf_service *service = global_parameters.server->service;
553 root = xmlDocGetRootElement(xdoc);
554 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
556 yaz_log(YLOG_WARN, "No mergekey found in record");
561 res = nmem_malloc(se->nmem, sizeof(struct record));
564 res->metadata = nmem_malloc(se->nmem,
565 sizeof(struct record_metadata*) * service->num_metadata);
566 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
568 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
570 normalize_mergekey((char *) mergekey_norm, 0);
572 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
574 if (global_parameters.dump_records)
575 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
576 cl->database->url, cl->records);
579 /* no room for record */
583 relevance_newrec(se->relevance, cluster);
585 for (n = root->children; n; n = n->next)
593 if (n->type != XML_ELEMENT_NODE)
595 if (!strcmp((const char *) n->name, "metadata"))
597 struct conf_metadata *md = 0;
598 struct conf_sortkey *sk = 0;
599 struct record_metadata **wheretoput, *newm;
603 type = xmlGetProp(n, (xmlChar *) "type");
604 value = xmlNodeListGetString(xdoc, n->children, 0);
609 // First, find out what field we're looking at
610 for (imeta = 0; imeta < service->num_metadata; imeta++)
611 if (!strcmp((const char *) type, service->metadata[imeta].name))
613 md = &service->metadata[imeta];
614 if (md->sortkey_offset >= 0)
615 sk = &service->sortkeys[md->sortkey_offset];
620 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
624 // Find out where we are putting it
625 if (md->merge == Metadata_merge_no)
626 wheretoput = &res->metadata[imeta];
628 wheretoput = &cluster->metadata[imeta];
631 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
633 if (md->type == Metadata_type_generic)
636 for (p = (char *) value; *p && isspace(*p); p++)
638 for (pe = p + strlen(p) - 1;
639 pe > p && strchr(" ,/.:([", *pe); pe--)
641 newm->data.text = nmem_strdup(se->nmem, p);
644 else if (md->type == Metadata_type_year)
646 if (extract_years((char *) value, &first, &last) < 0)
651 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
654 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
656 yaz_log(YLOG_WARN, "Only range merging supported for years");
659 if (md->merge == Metadata_merge_unique)
661 struct record_metadata *mnode;
662 for (mnode = *wheretoput; mnode; mnode = mnode->next)
663 if (!strcmp((const char *) mnode->data.text, newm->data.text))
667 newm->next = *wheretoput;
671 else if (md->merge == Metadata_merge_longest)
674 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
679 char *s = nmem_strdup(se->nmem, newm->data.text);
680 if (!cluster->sortkeys[md->sortkey_offset])
681 cluster->sortkeys[md->sortkey_offset] =
682 nmem_malloc(se->nmem, sizeof(union data_types));
683 normalize_mergekey(s,
684 (sk->type == Metadata_sortkey_skiparticle));
685 cluster->sortkeys[md->sortkey_offset]->text = s;
689 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
691 newm->next = *wheretoput;
694 else if (md->merge == Metadata_merge_range)
696 assert(md->type == Metadata_type_year);
700 (*wheretoput)->data.number.min = first;
701 (*wheretoput)->data.number.max = last;
703 cluster->sortkeys[md->sortkey_offset] = &newm->data;
707 if (first < (*wheretoput)->data.number.min)
708 (*wheretoput)->data.number.min = first;
709 if (last > (*wheretoput)->data.number.max)
710 (*wheretoput)->data.number.max = last;
715 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
716 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
721 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
724 relevance_countwords(se->relevance, cluster,
725 (char *) value, md->rank);
728 if (md->type == Metadata_type_year)
731 sprintf(year, "%d", last);
732 add_facet(se, (char *) type, year);
735 sprintf(year, "%d", first);
736 add_facet(se, (char *) type, year);
740 add_facet(se, (char *) type, (char *) value);
747 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
756 relevance_donerecord(se->relevance, cluster);
762 // Retrieve first defined value for 'name' for given database.
763 // Will be extended to take into account user associated with session
764 char *session_setting_oneval(struct session *s, struct database *db, const char *name)
766 int offset = settings_offset(name);
770 if (!db->settings[offset])
772 return db->settings[offset]->value;
775 static void ingest_records(struct client *cl, Z_Records *r)
778 yaz_timing_t t = yaz_timing_create();
781 struct session *s = cl->session;
782 Z_NamePlusRecordList *rlist;
785 if (r->which != Z_Records_DBOSD)
787 rlist = r->u.databaseOrSurDiagnostics;
788 for (i = 0; i < rlist->num_records; i++)
790 Z_NamePlusRecord *npr = rlist->records[i];
793 if (npr->which != Z_NamePlusRecord_databaseRecord)
796 "Unexpected record type, probably diagnostic %s",
801 rec = ingest_record(cl, npr->u.databaseRecord);
805 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
806 session_alert_watch(s, SESSION_WATCH_RECORDS);
810 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
811 yaz_timing_get_real(t), yaz_timing_get_user(t),
812 yaz_timing_get_sys(t));
813 yaz_timing_destroy(&t);
817 static void do_presentResponse(IOCHAN i, Z_APDU *a)
819 struct connection *co = iochan_getdata(i);
820 struct client *cl = co->client;
821 Z_PresentResponse *r = a->u.presentResponse;
824 Z_Records *recs = r->records;
825 if (recs->which == Z_Records_NSD)
827 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
829 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
830 cl->state = Client_Error;
834 if (!*r->presentStatus && cl->state != Client_Error)
836 yaz_log(YLOG_DEBUG, "Good Present response %s",
838 ingest_records(cl, r->records);
839 cl->state = Client_Idle;
841 else if (*r->presentStatus)
843 yaz_log(YLOG_WARN, "Bad Present response %s",
845 cl->state = Client_Error;
849 static void handler(IOCHAN i, int event)
851 struct connection *co = iochan_getdata(i);
852 struct client *cl = co->client;
853 struct session *se = 0;
859 yaz_log(YLOG_WARN, "Destroying orphan connection");
860 connection_destroy(co);
864 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
867 socklen_t errlen = sizeof(errcode);
869 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
870 &errlen) < 0 || errcode != 0)
877 yaz_log(YLOG_DEBUG, "Connect OK");
878 co->state = Conn_Open;
880 cl->state = Client_Connected;
884 else if (event & EVENT_INPUT)
886 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
890 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
892 connection_destroy(co);
897 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
898 connection_destroy(co);
901 else if (len > 1) // We discard input if we have no connection
903 co->state = Conn_Open;
905 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
909 odr_reset(global_parameters.odr_in);
910 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
911 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
918 case Z_APDU_initResponse:
919 do_initResponse(i, a);
921 case Z_APDU_searchResponse:
922 do_searchResponse(i, a);
924 case Z_APDU_presentResponse:
925 do_presentResponse(i, a);
928 do_closeResponse(i, a);
932 "Unexpected Z39.50 response from %s",
937 // We aren't expecting staggered output from target
938 // if (cs_more(t->link))
939 // iochan_setevent(i, EVENT_INPUT);
941 else // we throw away response and go to idle mode
943 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
944 cl->state = Client_Idle;
947 /* if len==1 we do nothing but wait for more input */
950 if (cl->state == Client_Connected) {
954 if (cl->state == Client_Idle)
956 if (cl->requestid != se->requestid && *se->query) {
959 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
960 cl->records < cl->hits) {
966 // Disassociate connection from client
967 static void connection_release(struct connection *co)
969 struct client *cl = co->client;
971 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
978 // Close connection and recycle structure
979 static void connection_destroy(struct connection *co)
981 struct host *h = co->host;
983 iochan_destroy(co->iochan);
985 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
986 if (h->connections == co)
987 h->connections = co->next;
990 struct connection *pco;
991 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
994 pco->next = co->next;
1000 if (co->client->state != Client_Idle)
1001 co->client->state = Client_Disconnected;
1002 co->client->connection = 0;
1004 co->next = connection_freelist;
1005 connection_freelist = co;
1008 // Creates a new connection for client, associated with the host of
1009 // client's database
1010 static struct connection *connection_create(struct client *cl)
1012 struct connection *new;
1018 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1020 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1024 if (0 == strlen(global_parameters.zproxy_override)){
1025 /* no Z39.50 proxy needed - direct connect */
1026 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1028 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1030 yaz_log(YLOG_WARN|YLOG_ERRNO,
1031 "Lookup of IP address %s failed",
1032 cl->database->host->ipport);
1037 /* Z39.50 proxy connect */
1038 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1039 cl->database->url, global_parameters.zproxy_override);
1041 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1043 yaz_log(YLOG_WARN|YLOG_ERRNO,
1044 "Lookup of IP address %s failed",
1045 global_parameters.zproxy_override);
1050 res = cs_connect(link, addr);
1053 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1057 if ((new = connection_freelist))
1058 connection_freelist = new->next;
1061 new = xmalloc(sizeof (struct connection));
1065 new->state = Conn_Connecting;
1066 new->host = cl->database->host;
1067 new->next = new->host->connections;
1068 new->host->connections = new;
1070 cl->connection = new;
1073 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1074 iochan_setdata(new->iochan, new);
1075 new->iochan->next = channel_list;
1076 channel_list = new->iochan;
1080 // Close connection and set state to error
1081 static void client_fatal(struct client *cl)
1083 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1084 connection_destroy(cl->connection);
1085 cl->state = Client_Error;
1088 // Ensure that client has a connection associated
1089 static int client_prep_connection(struct client *cl)
1091 struct connection *co;
1092 struct session *se = cl->session;
1093 struct host *host = cl->database->host;
1095 co = cl->connection;
1097 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1101 // See if someone else has an idle connection
1102 // We should look at timestamps here to select the longest-idle connection
1103 for (co = host->connections; co; co = co->next)
1104 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1108 connection_release(co);
1109 cl->connection = co;
1113 co = connection_create(cl);
1117 if (co->state == Conn_Connecting)
1119 cl->state = Client_Connecting;
1120 iochan_setflag(co->iochan, EVENT_OUTPUT);
1122 else if (co->state == Conn_Open)
1124 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1125 cl->state = Client_Idle;
1126 iochan_setflag(co->iochan, EVENT_OUTPUT);
1134 #ifdef GAGA // Moved to database.c
1136 // This function will most likely vanish when a proper target profile mechanism is
1138 void load_simpletargets(const char *fn)
1140 FILE *f = fopen(fn, "r");
1145 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1149 while (fgets(line, 255, f))
1154 struct database *database;
1156 if (strncmp(line, "target ", 7))
1158 line[strlen(line) - 1] = '\0';
1160 if ((name = strchr(line, ';')))
1164 if ((db = strchr(url, '/')))
1169 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1170 for (host = hosts; host; host = host->next)
1171 if (!strcmp((const char *) url, host->hostport))
1175 struct addrinfo *addrinfo, hints;
1178 unsigned char addrbuf[4];
1181 host = xmalloc(sizeof(struct host));
1182 host->hostport = xstrdup(url);
1183 host->connections = 0;
1185 if ((port = strchr(url, ':')))
1191 hints.ai_family = PF_INET;
1192 hints.ai_socktype = SOCK_STREAM;
1193 hints.ai_protocol = IPPROTO_TCP;
1194 hints.ai_addrlen = 0;
1196 hints.ai_canonname = 0;
1198 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1200 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1202 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1203 xfree(host->hostport);
1207 assert(addrinfo->ai_family == PF_INET);
1208 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1209 sprintf(ipport, "%u.%u.%u.%u:%s",
1210 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1211 host->ipport = xstrdup(ipport);
1212 freeaddrinfo(addrinfo);
1216 database = xmalloc(sizeof(struct database));
1217 database->host = host;
1218 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1219 strcpy(database->url, url);
1220 strcat(database->url, "/");
1221 strcat(database->url, db);
1223 database->name = xstrdup(name);
1227 database->databases = xmalloc(2 * sizeof(char *));
1228 database->databases[0] = xstrdup(db);
1229 database->databases[1] = 0;
1230 database->errors = 0;
1231 database->qprofile = 0;
1232 database->rprofile = database_retrieval_profile(database);
1233 database->next = databases;
1234 databases = database;
1242 static struct client *client_create(void)
1245 if (client_freelist)
1247 r = client_freelist;
1248 client_freelist = client_freelist->next;
1251 r = xmalloc(sizeof(struct client));
1260 r->state = Client_Disconnected;
1265 void client_destroy(struct client *c)
1267 struct session *se = c->session;
1268 if (c == se->clients)
1269 se->clients = c->next;
1273 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1279 connection_release(c->connection);
1280 c->next = client_freelist;
1281 client_freelist = c;
1284 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1286 s->watchlist[what].fun = fun;
1287 s->watchlist[what].data = data;
1290 void session_alert_watch(struct session *s, int what)
1292 if (!s->watchlist[what].fun)
1294 (*s->watchlist[what].fun)(s->watchlist[what].data);
1295 s->watchlist[what].fun = 0;
1296 s->watchlist[what].data = 0;
1299 //callback for grep_databases
1300 static void select_targets_callback(void *context, struct database *db)
1302 struct session *se = (struct session*) context;
1303 struct client *cl = client_create();
1306 cl->next = se->clients;
1310 // This should be extended with parameters to control selection criteria
1311 // Associates a set of clients with a session;
1312 int select_targets(struct session *se, struct database_criterion *crit)
1315 client_destroy(se->clients);
1317 return grep_databases(se, crit, select_targets_callback);
1320 int session_active_clients(struct session *s)
1325 for (c = s->clients; c; c = c->next)
1326 if (c->connection && (c->state == Client_Connecting ||
1327 c->state == Client_Initializing ||
1328 c->state == Client_Searching ||
1329 c->state == Client_Presenting))
1335 // parses crit1=val1,crit2=val2|val3,...
1336 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1338 struct database_criterion *res = 0;
1345 nmem_strsplit(m, ",", buf, &values, &num);
1346 for (i = 0; i < num; i++)
1351 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1352 char *eq = strchr(values[i], '=');
1355 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1359 new->name = values[i];
1360 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1362 for (subi = 0; subi < subnum; subi++)
1364 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1365 newv->value = subvalues[subi];
1366 newv->next = new->values;
1375 char *search(struct session *se, char *query, char *filter)
1377 int live_channels = 0;
1379 struct database_criterion *criteria;
1381 yaz_log(YLOG_DEBUG, "Search");
1383 nmem_reset(se->nmem);
1384 criteria = parse_filter(se->nmem, filter);
1385 strcpy(se->query, query);
1387 // Release any existing clients
1388 select_targets(se, criteria);
1389 for (cl = se->clients; cl; cl = cl->next)
1391 if (client_prep_connection(cl))
1396 int maxrecs = live_channels * global_parameters.toget;
1397 se->num_termlists = 0;
1398 se->reclist = reclist_create(se->nmem, maxrecs);
1399 // This will be initialized in send_search()
1401 se->total_records = se->total_hits = se->total_merged = 0;
1402 se->expected_maxrecs = maxrecs;
1410 void destroy_session(struct session *s)
1412 yaz_log(YLOG_LOG, "Destroying session");
1414 client_destroy(s->clients);
1415 nmem_destroy(s->nmem);
1416 wrbuf_destroy(s->wrbuf);
1419 struct session *new_session()
1422 struct session *session = xmalloc(sizeof(*session));
1424 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1426 session->total_hits = 0;
1427 session->total_records = 0;
1428 session->num_termlists = 0;
1429 session->reclist = 0;
1430 session->requestid = -1;
1431 session->clients = 0;
1432 session->expected_maxrecs = 0;
1433 session->query[0] = '\0';
1434 session->nmem = nmem_create();
1435 session->wrbuf = wrbuf_alloc();
1436 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1438 session->watchlist[i].data = 0;
1439 session->watchlist[i].fun = 0;
1445 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1447 static struct hitsbytarget res[1000]; // FIXME MM
1451 for (cl = se->clients; cl; cl = cl->next)
1453 res[*count].id = cl->database->url;
1454 res[*count].name = cl->database->name;
1455 res[*count].hits = cl->hits;
1456 res[*count].records = cl->records;
1457 res[*count].diagnostic = cl->diagnostic;
1458 res[*count].state = client_states[cl->state];
1459 res[*count].connected = cl->connection ? 1 : 0;
1466 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1470 for (i = 0; i < s->num_termlists; i++)
1471 if (!strcmp((const char *) s->termlists[i].name, name))
1472 return termlist_highscore(s->termlists[i].termlist, num);
1476 #ifdef MISSING_HEADERS
1477 void report_nmem_stats(void)
1479 size_t in_use, is_free;
1481 nmem_get_memory_in_use(&in_use);
1482 nmem_get_memory_free(&is_free);
1484 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1485 (long) in_use, (long) is_free);
1489 struct record_cluster *show_single(struct session *s, int id)
1491 struct record_cluster *r;
1493 reclist_rewind(s->reclist);
1494 while ((r = reclist_read_record(s->reclist)))
1500 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1501 int *num, int *total, int *sumhits, NMEM nmem_show)
1503 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1504 * sizeof(struct record_cluster *));
1505 struct reclist_sortparms *spp;
1508 yaz_timing_t t = yaz_timing_create();
1511 for (spp = sp; spp; spp = spp->next)
1512 if (spp->type == Metadata_sortkey_relevance)
1514 relevance_prepare_read(s->relevance, s->reclist);
1517 reclist_sort(s->reclist, sp);
1519 *total = s->reclist->num_records;
1520 *sumhits = s->total_hits;
1522 for (i = 0; i < start; i++)
1523 if (!reclist_read_record(s->reclist))
1530 for (i = 0; i < *num; i++)
1532 struct record_cluster *r = reclist_read_record(s->reclist);
1542 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1543 yaz_timing_get_real(t), yaz_timing_get_user(t),
1544 yaz_timing_get_sys(t));
1545 yaz_timing_destroy(&t);
1550 void statistics(struct session *se, struct statistics *stat)
1555 memset(stat, 0, sizeof(*stat));
1556 for (cl = se->clients; cl; cl = cl->next)
1558 if (!cl->connection)
1559 stat->num_no_connection++;
1562 case Client_Connecting: stat->num_connecting++; break;
1563 case Client_Initializing: stat->num_initializing++; break;
1564 case Client_Searching: stat->num_searching++; break;
1565 case Client_Presenting: stat->num_presenting++; break;
1566 case Client_Idle: stat->num_idle++; break;
1567 case Client_Failed: stat->num_failed++; break;
1568 case Client_Error: stat->num_error++; break;
1573 stat->num_hits = se->total_hits;
1574 stat->num_records = se->total_records;
1576 stat->num_clients = count;
1579 static void start_http_listener(void)
1582 struct conf_server *ser = global_parameters.server;
1584 if (*global_parameters.listener_override)
1585 strcpy(hp, global_parameters.listener_override);
1588 strcpy(hp, ser->host ? ser->host : "");
1593 sprintf(hp + strlen(hp), "%d", ser->port);
1599 // Initialize CCL map for a target
1600 // Note: This approach ignores user-specific CCL maps, for which I
1601 // don't presently see any application.
1602 static void prepare_cclmap(void *context, struct database *db)
1608 db->ccl_map = ccl_qual_mk();
1609 for (s = db->settings[PZ_CCLMAP]; s; s = s->next)
1612 char *p = strchr(s->name + 3, ':');
1615 yaz_log(YLOG_FATAL, "Malformed cclmap name: %s", s->name);
1619 ccl_qual_fitem(db->ccl_map, s->value, p);
1623 // Read settings for each database, and prepare a CCL map for that database
1624 static void prepare_cclmaps(void)
1626 grep_databases(0, 0, prepare_cclmap);
1629 static void start_proxy(void)
1632 struct conf_server *ser = global_parameters.server;
1634 if (*global_parameters.proxy_override)
1635 strcpy(hp, global_parameters.proxy_override);
1636 else if (ser->proxy_host || ser->proxy_port)
1638 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1639 if (ser->proxy_port)
1643 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1649 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1652 static void start_zproxy(void)
1654 struct conf_server *ser = global_parameters.server;
1656 if (*global_parameters.zproxy_override){
1657 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1658 global_parameters.zproxy_override);
1662 else if (ser->zproxy_host || ser->zproxy_port)
1666 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1667 if (ser->zproxy_port)
1674 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1676 strcpy(global_parameters.zproxy_override, hp);
1677 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1678 global_parameters.zproxy_override);
1687 int main(int argc, char **argv)
1692 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1693 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1695 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1697 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1701 if (!read_config(arg))
1705 strcpy(global_parameters.listener_override, arg);
1708 strcpy(global_parameters.proxy_override, arg);
1711 strcpy(global_parameters.zproxy_override, arg);
1714 strcpy(global_parameters.settings_path_override, arg);
1717 load_simpletargets(arg);
1720 global_parameters.dump_records = 1;
1723 fprintf(stderr, "Usage: pazpar2\n"
1725 " -h [host:]port (REST protocol listener)\n"
1727 " -s simpletargetfile\n"
1728 " -p hostname[:portno] (HTTP proxy)\n"
1729 " -z hostname[:portno] (Z39.50 proxy)\n"
1730 " -d (show internal records)\n");
1737 yaz_log(YLOG_FATAL, "Load config with -f");
1740 global_parameters.server = config->servers;
1742 start_http_listener();
1746 if (*global_parameters.settings_path_override)
1747 settings_read(global_parameters.settings_path_override);
1748 else if (global_parameters.server->settings)
1749 settings_read(global_parameters.server->settings);
1751 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may ensue!");
1753 global_parameters.yaz_marc = yaz_marc_create();
1754 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1755 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1756 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1758 event_loop(&channel_list);
1766 * indent-tabs-mode: nil
1768 * vim: shiftwidth=4 tabstop=8 expandtab