1 /* $Id: pazpar2.c,v 1.61 2007-04-03 04:05:01 quinn 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, "Received init response");
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, "Searchresponse (status=%d)", *r->searchStatus);
324 if (*r->searchStatus)
326 cl->hits = *r->resultCount;
327 se->total_hits += cl->hits;
328 if (r->presentStatus && !*r->presentStatus && r->records)
330 yaz_log(YLOG_DEBUG, "Records in search response");
331 ingest_records(cl, r->records);
333 cl->state = Client_Idle;
338 cl->state = Client_Error;
340 Z_Records *recs = r->records;
341 if (recs->which == Z_Records_NSD)
343 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
344 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
345 cl->state = Client_Error;
351 char *normalize_mergekey(char *buf, int skiparticle)
353 char *p = buf, *pout = buf;
358 char articles[] = "the den der die des an a "; // must end in space
360 while (*p && !isalnum(*p))
363 while (*p && *p != ' ' && pout - firstword < 62)
364 *(pout++) = tolower(*(p++));
367 if (!strstr(articles, firstword))
374 while (*p && !isalnum(*p))
377 *(pout++) = tolower(*(p++));
380 while (*p && !isalnum(*p))
387 while (pout > buf && *pout == ' ');
392 static void add_facet(struct session *s, const char *type, const char *value)
398 for (i = 0; i < s->num_termlists; i++)
399 if (!strcmp(s->termlists[i].name, type))
401 if (i == s->num_termlists)
403 if (i == SESSION_MAX_TERMLISTS)
405 yaz_log(YLOG_FATAL, "Too many termlists");
408 s->termlists[i].name = nmem_strdup(s->nmem, type);
409 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
410 s->num_termlists = i + 1;
412 termlist_insert(s->termlists[i].termlist, value);
415 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
417 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
418 struct conf_retrievalmap *m;
422 // First normalize to XML
423 if (rprofile->native_syntax == Nativesyn_iso2709)
427 if (rec->which != Z_External_octet)
429 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
432 buf = (char*) rec->u.octet_aligned->buf;
433 len = rec->u.octet_aligned->len;
434 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
436 yaz_log(YLOG_WARN, "Failed to decode MARC");
439 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
440 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
442 yaz_log(YLOG_WARN, "Failed to encode as XML");
445 rdoc = xmlNewDoc((xmlChar *) "1.0");
446 xmlDocSetRootElement(rdoc, res);
450 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
454 if (global_parameters.dump_records)
456 fprintf(stderr, "Input Record (normalized):\n----------------\n");
457 #if LIBXML_VERSION >= 20600
458 xmlDocFormatDump(stderr, rdoc, 1);
460 xmlDocDump(stderr, rdoc);
464 for (m = rprofile->maplist; m; m = m->next)
467 if (m->type != Map_xslt)
469 yaz_log(YLOG_WARN, "Unknown map type");
472 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
474 yaz_log(YLOG_WARN, "XSLT transformation failed");
480 if (global_parameters.dump_records)
482 fprintf(stderr, "Record:\n----------------\n");
483 #if LIBXML_VERSION >= 20600
484 xmlDocFormatDump(stderr, rdoc, 1);
486 xmlDocDump(stderr, rdoc);
492 // Extract what appears to be years from buf, storing highest and
494 static int extract_years(const char *buf, int *first, int *last)
503 while (*buf && !isdigit(*buf))
506 for (e = buf; *e && isdigit(*e); e++)
510 int value = atoi(buf);
511 if (*first < 0 || value < *first)
513 if (*last < 0 || value > *last)
521 static struct record *ingest_record(struct client *cl, Z_External *rec)
523 xmlDoc *xdoc = normalize_record(cl, rec);
526 struct record_cluster *cluster;
527 struct session *se = cl->session;
528 xmlChar *mergekey, *mergekey_norm;
531 struct conf_service *service = global_parameters.server->service;
536 root = xmlDocGetRootElement(xdoc);
537 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
539 yaz_log(YLOG_WARN, "No mergekey found in record");
544 res = nmem_malloc(se->nmem, sizeof(struct record));
547 res->metadata = nmem_malloc(se->nmem,
548 sizeof(struct record_metadata*) * service->num_metadata);
549 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
551 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
553 normalize_mergekey((char *) mergekey_norm, 0);
555 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
557 if (global_parameters.dump_records)
558 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
559 cl->database->url, cl->records);
562 /* no room for record */
566 relevance_newrec(se->relevance, cluster);
568 for (n = root->children; n; n = n->next)
576 if (n->type != XML_ELEMENT_NODE)
578 if (!strcmp((const char *) n->name, "metadata"))
580 struct conf_metadata *md = 0;
581 struct conf_sortkey *sk = 0;
582 struct record_metadata **wheretoput, *newm;
586 type = xmlGetProp(n, (xmlChar *) "type");
587 value = xmlNodeListGetString(xdoc, n->children, 0);
592 // First, find out what field we're looking at
593 for (imeta = 0; imeta < service->num_metadata; imeta++)
594 if (!strcmp((const char *) type, service->metadata[imeta].name))
596 md = &service->metadata[imeta];
597 if (md->sortkey_offset >= 0)
598 sk = &service->sortkeys[md->sortkey_offset];
603 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
607 // Find out where we are putting it
608 if (md->merge == Metadata_merge_no)
609 wheretoput = &res->metadata[imeta];
611 wheretoput = &cluster->metadata[imeta];
614 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
616 if (md->type == Metadata_type_generic)
619 for (p = (char *) value; *p && isspace(*p); p++)
621 for (pe = p + strlen(p) - 1;
622 pe > p && strchr(" ,/.:([", *pe); pe--)
624 newm->data.text = nmem_strdup(se->nmem, p);
627 else if (md->type == Metadata_type_year)
629 if (extract_years((char *) value, &first, &last) < 0)
634 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
637 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
639 yaz_log(YLOG_WARN, "Only range merging supported for years");
642 if (md->merge == Metadata_merge_unique)
644 struct record_metadata *mnode;
645 for (mnode = *wheretoput; mnode; mnode = mnode->next)
646 if (!strcmp((const char *) mnode->data.text, newm->data.text))
650 newm->next = *wheretoput;
654 else if (md->merge == Metadata_merge_longest)
657 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
662 char *s = nmem_strdup(se->nmem, newm->data.text);
663 if (!cluster->sortkeys[md->sortkey_offset])
664 cluster->sortkeys[md->sortkey_offset] =
665 nmem_malloc(se->nmem, sizeof(union data_types));
666 normalize_mergekey(s,
667 (sk->type == Metadata_sortkey_skiparticle));
668 cluster->sortkeys[md->sortkey_offset]->text = s;
672 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
674 newm->next = *wheretoput;
677 else if (md->merge == Metadata_merge_range)
679 assert(md->type == Metadata_type_year);
683 (*wheretoput)->data.number.min = first;
684 (*wheretoput)->data.number.max = last;
686 cluster->sortkeys[md->sortkey_offset] = &newm->data;
690 if (first < (*wheretoput)->data.number.min)
691 (*wheretoput)->data.number.min = first;
692 if (last > (*wheretoput)->data.number.max)
693 (*wheretoput)->data.number.max = last;
698 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
699 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
704 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
707 relevance_countwords(se->relevance, cluster,
708 (char *) value, md->rank);
711 if (md->type == Metadata_type_year)
714 sprintf(year, "%d", last);
715 add_facet(se, (char *) type, year);
718 sprintf(year, "%d", first);
719 add_facet(se, (char *) type, year);
723 add_facet(se, (char *) type, (char *) value);
730 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
739 relevance_donerecord(se->relevance, cluster);
745 // Retrieve first defined value for 'name' for given database.
746 // Will be extended to take into account user associated with session
747 char *session_setting_oneval(struct session *s, struct database *db, const char *name)
749 int offset = settings_offset(name);
753 if (!db->settings[offset])
755 return db->settings[offset]->value;
758 static void ingest_records(struct client *cl, Z_Records *r)
761 yaz_timing_t t = yaz_timing_create();
764 struct session *s = cl->session;
765 Z_NamePlusRecordList *rlist;
768 if (r->which != Z_Records_DBOSD)
770 rlist = r->u.databaseOrSurDiagnostics;
771 for (i = 0; i < rlist->num_records; i++)
773 Z_NamePlusRecord *npr = rlist->records[i];
776 if (npr->which != Z_NamePlusRecord_databaseRecord)
778 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
782 rec = ingest_record(cl, npr->u.databaseRecord);
786 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
787 session_alert_watch(s, SESSION_WATCH_RECORDS);
791 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
792 yaz_timing_get_real(t), yaz_timing_get_user(t),
793 yaz_timing_get_sys(t));
794 yaz_timing_destroy(&t);
798 static void do_presentResponse(IOCHAN i, Z_APDU *a)
800 struct connection *co = iochan_getdata(i);
801 struct client *cl = co->client;
802 Z_PresentResponse *r = a->u.presentResponse;
805 Z_Records *recs = r->records;
806 if (recs->which == Z_Records_NSD)
808 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
809 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
810 cl->state = Client_Error;
814 if (!*r->presentStatus && cl->state != Client_Error)
816 yaz_log(YLOG_DEBUG, "Good Present response");
817 ingest_records(cl, r->records);
818 cl->state = Client_Idle;
820 else if (*r->presentStatus)
822 yaz_log(YLOG_WARN, "Bad Present response");
823 cl->state = Client_Error;
827 static void handler(IOCHAN i, int event)
829 struct connection *co = iochan_getdata(i);
830 struct client *cl = co->client;
831 struct session *se = 0;
837 yaz_log(YLOG_WARN, "Destroying orphan connection");
838 connection_destroy(co);
842 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
845 socklen_t errlen = sizeof(errcode);
847 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
848 &errlen) < 0 || errcode != 0)
855 yaz_log(YLOG_DEBUG, "Connect OK");
856 co->state = Conn_Open;
858 cl->state = Client_Connected;
862 else if (event & EVENT_INPUT)
864 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
868 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
869 connection_destroy(co);
874 yaz_log(YLOG_WARN, "EOF reading from Z server");
875 connection_destroy(co);
878 else if (len > 1) // We discard input if we have no connection
880 co->state = Conn_Open;
882 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
886 odr_reset(global_parameters.odr_in);
887 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
888 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
895 case Z_APDU_initResponse:
896 do_initResponse(i, a);
898 case Z_APDU_searchResponse:
899 do_searchResponse(i, a);
901 case Z_APDU_presentResponse:
902 do_presentResponse(i, a);
905 yaz_log(YLOG_WARN, "Unexpected result from server");
909 // We aren't expecting staggered output from target
910 // if (cs_more(t->link))
911 // iochan_setevent(i, EVENT_INPUT);
913 else // we throw away response and go to idle mode
915 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
916 cl->state = Client_Idle;
919 /* if len==1 we do nothing but wait for more input */
922 if (cl->state == Client_Connected) {
926 if (cl->state == Client_Idle)
928 if (cl->requestid != se->requestid && *se->query) {
931 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
932 cl->records < cl->hits) {
938 // Disassociate connection from client
939 static void connection_release(struct connection *co)
941 struct client *cl = co->client;
943 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
950 // Close connection and recycle structure
951 static void connection_destroy(struct connection *co)
953 struct host *h = co->host;
955 iochan_destroy(co->iochan);
957 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
958 if (h->connections == co)
959 h->connections = co->next;
962 struct connection *pco;
963 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
966 pco->next = co->next;
972 if (co->client->state != Client_Idle)
973 co->client->state = Client_Disconnected;
974 co->client->connection = 0;
976 co->next = connection_freelist;
977 connection_freelist = co;
980 // Creates a new connection for client, associated with the host of
982 static struct connection *connection_create(struct client *cl)
984 struct connection *new;
990 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
992 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
996 if (0 == strlen(global_parameters.zproxy_override)){
997 /* no Z39.50 proxy needed - direct connect */
998 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1000 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1002 yaz_log(YLOG_WARN|YLOG_ERRNO,
1003 "Lookup of IP address %s failed",
1004 cl->database->host->ipport);
1009 /* Z39.50 proxy connect */
1010 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1011 cl->database->url, global_parameters.zproxy_override);
1013 yaz_log(YLOG_LOG, "Connection cs_create_host %s proxy %s",
1014 cl->database->url, global_parameters.zproxy_override);
1016 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1018 yaz_log(YLOG_WARN|YLOG_ERRNO,
1019 "Lookup of IP address %s failed",
1020 global_parameters.zproxy_override);
1025 res = cs_connect(link, addr);
1028 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1032 if ((new = connection_freelist))
1033 connection_freelist = new->next;
1036 new = xmalloc(sizeof (struct connection));
1040 new->state = Conn_Connecting;
1041 new->host = cl->database->host;
1042 new->next = new->host->connections;
1043 new->host->connections = new;
1045 cl->connection = new;
1048 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1049 iochan_setdata(new->iochan, new);
1050 new->iochan->next = channel_list;
1051 channel_list = new->iochan;
1055 // Close connection and set state to error
1056 static void client_fatal(struct client *cl)
1058 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1059 connection_destroy(cl->connection);
1060 cl->state = Client_Error;
1063 // Ensure that client has a connection associated
1064 static int client_prep_connection(struct client *cl)
1066 struct connection *co;
1067 struct session *se = cl->session;
1068 struct host *host = cl->database->host;
1070 co = cl->connection;
1072 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1076 // See if someone else has an idle connection
1077 // We should look at timestamps here to select the longest-idle connection
1078 for (co = host->connections; co; co = co->next)
1079 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1083 connection_release(co);
1084 cl->connection = co;
1088 co = connection_create(cl);
1092 if (co->state == Conn_Connecting)
1094 cl->state = Client_Connecting;
1095 iochan_setflag(co->iochan, EVENT_OUTPUT);
1097 else if (co->state == Conn_Open)
1099 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1100 cl->state = Client_Idle;
1101 iochan_setflag(co->iochan, EVENT_OUTPUT);
1109 #ifdef GAGA // Moved to database.c
1111 // This function will most likely vanish when a proper target profile mechanism is
1113 void load_simpletargets(const char *fn)
1115 FILE *f = fopen(fn, "r");
1120 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1124 while (fgets(line, 255, f))
1129 struct database *database;
1131 if (strncmp(line, "target ", 7))
1133 line[strlen(line) - 1] = '\0';
1135 if ((name = strchr(line, ';')))
1139 if ((db = strchr(url, '/')))
1144 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1145 for (host = hosts; host; host = host->next)
1146 if (!strcmp((const char *) url, host->hostport))
1150 struct addrinfo *addrinfo, hints;
1153 unsigned char addrbuf[4];
1156 host = xmalloc(sizeof(struct host));
1157 host->hostport = xstrdup(url);
1158 host->connections = 0;
1160 if ((port = strchr(url, ':')))
1166 hints.ai_family = PF_INET;
1167 hints.ai_socktype = SOCK_STREAM;
1168 hints.ai_protocol = IPPROTO_TCP;
1169 hints.ai_addrlen = 0;
1171 hints.ai_canonname = 0;
1173 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1175 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1177 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1178 xfree(host->hostport);
1182 assert(addrinfo->ai_family == PF_INET);
1183 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1184 sprintf(ipport, "%u.%u.%u.%u:%s",
1185 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1186 host->ipport = xstrdup(ipport);
1187 freeaddrinfo(addrinfo);
1191 database = xmalloc(sizeof(struct database));
1192 database->host = host;
1193 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1194 strcpy(database->url, url);
1195 strcat(database->url, "/");
1196 strcat(database->url, db);
1198 database->name = xstrdup(name);
1202 database->databases = xmalloc(2 * sizeof(char *));
1203 database->databases[0] = xstrdup(db);
1204 database->databases[1] = 0;
1205 database->errors = 0;
1206 database->qprofile = 0;
1207 database->rprofile = database_retrieval_profile(database);
1208 database->next = databases;
1209 databases = database;
1217 static struct client *client_create(void)
1220 if (client_freelist)
1222 r = client_freelist;
1223 client_freelist = client_freelist->next;
1226 r = xmalloc(sizeof(struct client));
1235 r->state = Client_Disconnected;
1240 void client_destroy(struct client *c)
1242 struct session *se = c->session;
1243 if (c == se->clients)
1244 se->clients = c->next;
1248 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1254 connection_release(c->connection);
1255 c->next = client_freelist;
1256 client_freelist = c;
1259 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1261 s->watchlist[what].fun = fun;
1262 s->watchlist[what].data = data;
1265 void session_alert_watch(struct session *s, int what)
1267 if (!s->watchlist[what].fun)
1269 (*s->watchlist[what].fun)(s->watchlist[what].data);
1270 s->watchlist[what].fun = 0;
1271 s->watchlist[what].data = 0;
1274 //callback for grep_databases
1275 static void select_targets_callback(void *context, struct database *db)
1277 struct session *se = (struct session*) context;
1278 struct client *cl = client_create();
1281 cl->next = se->clients;
1285 // This should be extended with parameters to control selection criteria
1286 // Associates a set of clients with a session;
1287 int select_targets(struct session *se, struct database_criterion *crit)
1290 client_destroy(se->clients);
1292 return grep_databases(se, crit, select_targets_callback);
1295 int session_active_clients(struct session *s)
1300 for (c = s->clients; c; c = c->next)
1301 if (c->connection && (c->state == Client_Connecting ||
1302 c->state == Client_Initializing ||
1303 c->state == Client_Searching ||
1304 c->state == Client_Presenting))
1310 // parses crit1=val1,crit2=val2|val3,...
1311 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1313 struct database_criterion *res = 0;
1320 nmem_strsplit(m, ",", buf, &values, &num);
1321 for (i = 0; i < num; i++)
1326 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1327 char *eq = strchr(values[i], '=');
1330 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1334 new->name = values[i];
1335 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1337 for (subi = 0; subi < subnum; subi++)
1339 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1340 newv->value = subvalues[subi];
1341 newv->next = new->values;
1350 char *search(struct session *se, char *query, char *filter)
1352 int live_channels = 0;
1354 struct database_criterion *criteria;
1356 yaz_log(YLOG_DEBUG, "Search");
1358 nmem_reset(se->nmem);
1359 criteria = parse_filter(se->nmem, filter);
1360 strcpy(se->query, query);
1362 // Release any existing clients
1363 select_targets(se, criteria);
1364 for (cl = se->clients; cl; cl = cl->next)
1366 if (client_prep_connection(cl))
1371 int maxrecs = live_channels * global_parameters.toget;
1372 se->num_termlists = 0;
1373 se->reclist = reclist_create(se->nmem, maxrecs);
1374 // This will be initialized in send_search()
1376 se->total_records = se->total_hits = se->total_merged = 0;
1377 se->expected_maxrecs = maxrecs;
1385 void destroy_session(struct session *s)
1387 yaz_log(YLOG_LOG, "Destroying session");
1389 client_destroy(s->clients);
1390 nmem_destroy(s->nmem);
1391 wrbuf_destroy(s->wrbuf);
1394 struct session *new_session()
1397 struct session *session = xmalloc(sizeof(*session));
1399 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1401 session->total_hits = 0;
1402 session->total_records = 0;
1403 session->num_termlists = 0;
1404 session->reclist = 0;
1405 session->requestid = -1;
1406 session->clients = 0;
1407 session->expected_maxrecs = 0;
1408 session->query[0] = '\0';
1409 session->nmem = nmem_create();
1410 session->wrbuf = wrbuf_alloc();
1411 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1413 session->watchlist[i].data = 0;
1414 session->watchlist[i].fun = 0;
1420 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1422 static struct hitsbytarget res[1000]; // FIXME MM
1426 for (cl = se->clients; cl; cl = cl->next)
1428 res[*count].id = cl->database->url;
1429 res[*count].name = cl->database->name;
1430 res[*count].hits = cl->hits;
1431 res[*count].records = cl->records;
1432 res[*count].diagnostic = cl->diagnostic;
1433 res[*count].state = client_states[cl->state];
1434 res[*count].connected = cl->connection ? 1 : 0;
1441 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1445 for (i = 0; i < s->num_termlists; i++)
1446 if (!strcmp((const char *) s->termlists[i].name, name))
1447 return termlist_highscore(s->termlists[i].termlist, num);
1451 #ifdef MISSING_HEADERS
1452 void report_nmem_stats(void)
1454 size_t in_use, is_free;
1456 nmem_get_memory_in_use(&in_use);
1457 nmem_get_memory_free(&is_free);
1459 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1460 (long) in_use, (long) is_free);
1464 struct record_cluster *show_single(struct session *s, int id)
1466 struct record_cluster *r;
1468 reclist_rewind(s->reclist);
1469 while ((r = reclist_read_record(s->reclist)))
1475 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1476 int *num, int *total, int *sumhits, NMEM nmem_show)
1478 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1479 * sizeof(struct record_cluster *));
1480 struct reclist_sortparms *spp;
1483 yaz_timing_t t = yaz_timing_create();
1486 for (spp = sp; spp; spp = spp->next)
1487 if (spp->type == Metadata_sortkey_relevance)
1489 relevance_prepare_read(s->relevance, s->reclist);
1492 reclist_sort(s->reclist, sp);
1494 *total = s->reclist->num_records;
1495 *sumhits = s->total_hits;
1497 for (i = 0; i < start; i++)
1498 if (!reclist_read_record(s->reclist))
1505 for (i = 0; i < *num; i++)
1507 struct record_cluster *r = reclist_read_record(s->reclist);
1517 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1518 yaz_timing_get_real(t), yaz_timing_get_user(t),
1519 yaz_timing_get_sys(t));
1520 yaz_timing_destroy(&t);
1525 void statistics(struct session *se, struct statistics *stat)
1530 memset(stat, 0, sizeof(*stat));
1531 for (cl = se->clients; cl; cl = cl->next)
1533 if (!cl->connection)
1534 stat->num_no_connection++;
1537 case Client_Connecting: stat->num_connecting++; break;
1538 case Client_Initializing: stat->num_initializing++; break;
1539 case Client_Searching: stat->num_searching++; break;
1540 case Client_Presenting: stat->num_presenting++; break;
1541 case Client_Idle: stat->num_idle++; break;
1542 case Client_Failed: stat->num_failed++; break;
1543 case Client_Error: stat->num_error++; break;
1548 stat->num_hits = se->total_hits;
1549 stat->num_records = se->total_records;
1551 stat->num_clients = count;
1554 static void start_http_listener(void)
1557 struct conf_server *ser = global_parameters.server;
1559 if (*global_parameters.listener_override)
1560 strcpy(hp, global_parameters.listener_override);
1563 strcpy(hp, ser->host ? ser->host : "");
1568 sprintf(hp + strlen(hp), "%d", ser->port);
1574 // Initialize CCL map for a target
1575 // Note: This approach ignores user-specific CCL maps, for which I
1576 // don't presently see any application.
1577 static void prepare_cclmap(void *context, struct database *db)
1583 db->ccl_map = ccl_qual_mk();
1584 for (s = db->settings[PZ_CCLMAP]; s; s = s->next)
1587 char *p = strchr(s->name + 3, ':');
1590 yaz_log(YLOG_FATAL, "Malformed cclmap name: %s", s->name);
1594 ccl_qual_fitem(db->ccl_map, s->value, p);
1598 // Read settings for each database, and prepare a CCL map for that database
1599 static void prepare_cclmaps(void)
1601 grep_databases(0, 0, prepare_cclmap);
1604 static void start_proxy(void)
1607 struct conf_server *ser = global_parameters.server;
1609 if (*global_parameters.proxy_override)
1610 strcpy(hp, global_parameters.proxy_override);
1611 else if (ser->proxy_host || ser->proxy_port)
1613 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1614 if (ser->proxy_port)
1618 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1624 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1627 static void start_zproxy(void)
1629 struct conf_server *ser = global_parameters.server;
1631 if (*global_parameters.zproxy_override){
1632 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1633 global_parameters.zproxy_override);
1637 else if (ser->zproxy_host || ser->zproxy_port)
1641 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1642 if (ser->zproxy_port)
1649 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1651 strcpy(global_parameters.zproxy_override, hp);
1652 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1653 global_parameters.zproxy_override);
1662 int main(int argc, char **argv)
1667 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1668 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1670 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1672 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1676 if (!read_config(arg))
1680 strcpy(global_parameters.listener_override, arg);
1683 strcpy(global_parameters.proxy_override, arg);
1686 strcpy(global_parameters.zproxy_override, arg);
1689 strcpy(global_parameters.settings_path_override, arg);
1692 load_simpletargets(arg);
1695 global_parameters.dump_records = 1;
1698 fprintf(stderr, "Usage: pazpar2\n"
1700 " -h [host:]port (REST protocol listener)\n"
1702 " -s simpletargetfile\n"
1703 " -p hostname[:portno] (HTTP proxy)\n"
1704 " -z hostname[:portno] (Z39.50 proxy)\n"
1705 " -d (show internal records)\n");
1712 yaz_log(YLOG_FATAL, "Load config with -f");
1715 global_parameters.server = config->servers;
1717 start_http_listener();
1721 if (*global_parameters.settings_path_override)
1722 settings_read(global_parameters.settings_path_override);
1723 else if (global_parameters.server->settings)
1724 settings_read(global_parameters.server->settings);
1726 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may ensue!");
1728 global_parameters.yaz_marc = yaz_marc_create();
1729 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1730 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1731 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1733 event_loop(&channel_list);
1741 * indent-tabs-mode: nil
1743 * vim: shiftwidth=4 tabstop=8 expandtab