1 /* $Id: pazpar2.c,v 1.70 2007-04-10 08:48:56 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>
49 #include <yaz/timing.h>
52 #include <netinet/in.h>
57 #include "termlists.h"
59 #include "relevance.h"
66 static void client_fatal(struct client *cl);
67 static void connection_destroy(struct connection *co);
68 static int client_prep_connection(struct client *cl);
69 static void ingest_records(struct client *cl, Z_Records *r);
70 void session_alert_watch(struct session *s, int what);
71 char *session_setting_oneval(struct session *s, struct database *db, int offset);
73 IOCHAN channel_list = 0; // Master list of connections we're handling events to
75 static struct connection *connection_freelist = 0;
76 static struct client *client_freelist = 0;
78 static char *client_states[] = {
82 "Client_Initializing",
87 "Client_Disconnected",
91 // Note: Some things in this structure will eventually move to configuration
92 struct parameters global_parameters =
102 "Index Data PazPar2 (MasterKey)",
112 static int send_apdu(struct client *c, Z_APDU *a)
114 struct connection *co = c->connection;
118 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
120 odr_perror(global_parameters.odr_out, "Encoding APDU");
123 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
124 r = cs_put(co->link, buf, len);
127 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
132 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
135 odr_reset(global_parameters.odr_out); /* release the APDU structure */
136 co->state = Conn_Waiting;
140 // Set authentication token in init if one is set for the client
141 // TODO: Extend this to handle other schemes than open (should be simple)
142 static void init_authentication(struct client *cl, Z_InitRequest *req)
144 struct database *db = cl->database;
145 struct session *se = cl->session;
146 char *auth = session_setting_oneval(se, db, PZ_AUTHENTICATION);
150 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
152 idAuth->which = Z_IdAuthentication_open;
153 idAuth->u.open = auth;
154 req->idAuthentication = idAuth;
158 static void send_init(IOCHAN i)
161 struct connection *co = iochan_getdata(i);
162 struct client *cl = co->client;
163 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
165 a->u.initRequest->implementationId = global_parameters.implementationId;
166 a->u.initRequest->implementationName = global_parameters.implementationName;
167 a->u.initRequest->implementationVersion =
168 global_parameters.implementationVersion;
169 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
170 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
171 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
173 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
174 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
175 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
177 init_authentication(cl, a->u.initRequest);
179 /* add virtual host if tunneling through Z39.50 proxy */
181 if (0 < strlen(global_parameters.zproxy_override)
182 && 0 < strlen(cl->database->url))
183 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
184 global_parameters.odr_out, VAL_PROXY,
185 1, cl->database->url);
187 if (send_apdu(cl, a) >= 0)
189 iochan_setflags(i, EVENT_INPUT);
190 cl->state = Client_Initializing;
193 cl->state = Client_Error;
194 odr_reset(global_parameters.odr_out);
197 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
205 pull_terms(nmem, n->u.p[0], termlist, num);
206 pull_terms(nmem, n->u.p[1], termlist, num);
209 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
216 // Extract terms from query into null-terminated termlist
217 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
221 pull_terms(nmem, query, termlist, &num);
225 static void send_search(IOCHAN i)
227 struct connection *co = iochan_getdata(i);
228 struct client *cl = co->client;
229 struct session *se = cl->session;
230 struct database *db = cl->database;
231 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
232 int ndb, cerror, cpos;
235 struct ccl_rpn_node *cn;
236 int ssub = 0, lslb = 100000, mspn = 10;
240 yaz_log(YLOG_DEBUG, "Sending search");
242 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
248 // Initialize relevance structure with query terms
250 extract_terms(se->nmem, cn, p);
251 se->relevance = relevance_create(se->nmem, (const char **) p,
252 se->expected_maxrecs);
255 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
257 zquery->which = Z_Query_type_1;
258 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
261 for (ndb = 0; db->databases[ndb]; ndb++)
263 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
264 for (ndb = 0; db->databases[ndb]; ndb++)
265 databaselist[ndb] = db->databases[ndb];
267 if (!(piggyback = session_setting_oneval(se, db, PZ_PIGGYBACK)) || *piggyback == '1')
269 if ((recsyn = session_setting_oneval(se, db, PZ_REQUESTSYNTAX)))
270 a->u.searchRequest->preferredRecordSyntax =
271 yaz_str_to_z3950oid(global_parameters.odr_out,
272 CLASS_RECSYN, recsyn);
273 a->u.searchRequest->smallSetUpperBound = &ssub;
274 a->u.searchRequest->largeSetLowerBound = &lslb;
275 a->u.searchRequest->mediumSetPresentNumber = &mspn;
277 a->u.searchRequest->resultSetName = "Default";
278 a->u.searchRequest->databaseNames = databaselist;
279 a->u.searchRequest->num_databaseNames = ndb;
281 if (send_apdu(cl, a) >= 0)
283 iochan_setflags(i, EVENT_INPUT);
284 cl->state = Client_Searching;
285 cl->requestid = se->requestid;
288 cl->state = Client_Error;
290 odr_reset(global_parameters.odr_out);
293 static void send_present(IOCHAN i)
295 struct connection *co = iochan_getdata(i);
296 struct client *cl = co->client;
297 struct session *se = cl->session;
298 struct database *db = cl->database;
299 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
301 int start = cl->records + 1;
304 toget = global_parameters.chunk;
305 if (toget > global_parameters.toget - cl->records)
306 toget = global_parameters.toget - cl->records;
307 if (toget > cl->hits - cl->records)
308 toget = cl->hits - cl->records;
310 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
312 a->u.presentRequest->resultSetStartPoint = &start;
313 a->u.presentRequest->numberOfRecordsRequested = &toget;
315 a->u.presentRequest->resultSetId = "Default";
317 if ((recsyn = session_setting_oneval(se, db, PZ_REQUESTSYNTAX)))
318 a->u.presentRequest->preferredRecordSyntax =
319 yaz_str_to_z3950oid(global_parameters.odr_out,
320 CLASS_RECSYN, recsyn);
322 if (send_apdu(cl, a) >= 0)
324 iochan_setflags(i, EVENT_INPUT);
325 cl->state = Client_Presenting;
328 cl->state = Client_Error;
329 odr_reset(global_parameters.odr_out);
332 static void do_initResponse(IOCHAN i, Z_APDU *a)
334 struct connection *co = iochan_getdata(i);
335 struct client *cl = co->client;
336 Z_InitResponse *r = a->u.initResponse;
338 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->url);
342 cl->state = Client_Idle;
345 cl->state = Client_Failed; // FIXME need to do something to the connection
348 static void do_searchResponse(IOCHAN i, Z_APDU *a)
350 struct connection *co = iochan_getdata(i);
351 struct client *cl = co->client;
352 struct session *se = cl->session;
353 Z_SearchResponse *r = a->u.searchResponse;
355 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
356 cl->database->url, *r->searchStatus);
358 if (*r->searchStatus)
360 cl->hits = *r->resultCount;
361 se->total_hits += cl->hits;
362 if (r->presentStatus && !*r->presentStatus && r->records)
364 yaz_log(YLOG_DEBUG, "Records in search response %s",
366 ingest_records(cl, r->records);
368 cl->state = Client_Idle;
373 cl->state = Client_Error;
375 Z_Records *recs = r->records;
376 if (recs->which == Z_Records_NSD)
379 "Search response: Non-surrogate diagnostic %s",
381 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
382 cl->state = Client_Error;
388 static void do_closeResponse(IOCHAN i, Z_APDU *a)
390 struct connection *co = iochan_getdata(i);
391 struct client *cl = co->client;
392 /* Z_Close *r = a->u.close; */
394 yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
396 cl->state = Client_Failed;
397 connection_destroy(co);
401 char *normalize_mergekey(char *buf, int skiparticle)
403 char *p = buf, *pout = buf;
408 char articles[] = "the den der die des an a "; // must end in space
410 while (*p && !isalnum(*p))
413 while (*p && *p != ' ' && pout - firstword < 62)
414 *(pout++) = tolower(*(p++));
417 if (!strstr(articles, firstword))
424 while (*p && !isalnum(*p))
427 *(pout++) = tolower(*(p++));
430 while (*p && !isalnum(*p))
437 while (pout > buf && *pout == ' ');
442 static void add_facet(struct session *s, const char *type, const char *value)
448 for (i = 0; i < s->num_termlists; i++)
449 if (!strcmp(s->termlists[i].name, type))
451 if (i == s->num_termlists)
453 if (i == SESSION_MAX_TERMLISTS)
455 yaz_log(YLOG_FATAL, "Too many termlists");
458 s->termlists[i].name = nmem_strdup(s->nmem, type);
459 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
460 s->num_termlists = i + 1;
462 termlist_insert(s->termlists[i].termlist, value);
465 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
467 struct database_retrievalmap *m;
468 struct database *db = cl->database;
472 // First normalize to XML
477 if (rec->which != Z_External_octet)
479 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
483 buf = (char*) rec->u.octet_aligned->buf;
484 len = rec->u.octet_aligned->len;
485 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
487 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
491 if (yaz_marc_write_xml(db->yaz_marc, &res,
492 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
494 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
498 rdoc = xmlNewDoc((xmlChar *) "1.0");
499 xmlDocSetRootElement(rdoc, res);
503 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
507 if (global_parameters.dump_records)
509 fprintf(stderr, "Input Record (normalized):\n----------------\n");
510 #if LIBXML_VERSION >= 20600
511 xmlDocFormatDump(stderr, rdoc, 1);
513 xmlDocDump(stderr, rdoc);
517 for (m = db->map; m; m = m->next)
520 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
522 yaz_log(YLOG_WARN, "XSLT transformation failed");
528 if (global_parameters.dump_records)
530 fprintf(stderr, "Record:\n----------------\n");
531 #if LIBXML_VERSION >= 20600
532 xmlDocFormatDump(stderr, rdoc, 1);
534 xmlDocDump(stderr, rdoc);
540 // Extract what appears to be years from buf, storing highest and
542 static int extract_years(const char *buf, int *first, int *last)
551 while (*buf && !isdigit(*buf))
554 for (e = buf; *e && isdigit(*e); e++)
558 int value = atoi(buf);
559 if (*first < 0 || value < *first)
561 if (*last < 0 || value > *last)
569 static struct record *ingest_record(struct client *cl, Z_External *rec)
571 xmlDoc *xdoc = normalize_record(cl, rec);
574 struct record_cluster *cluster;
575 struct session *se = cl->session;
576 xmlChar *mergekey, *mergekey_norm;
579 struct conf_service *service = global_parameters.server->service;
584 root = xmlDocGetRootElement(xdoc);
585 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
587 yaz_log(YLOG_WARN, "No mergekey found in record");
592 res = nmem_malloc(se->nmem, sizeof(struct record));
595 res->metadata = nmem_malloc(se->nmem,
596 sizeof(struct record_metadata*) * service->num_metadata);
597 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
599 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
601 normalize_mergekey((char *) mergekey_norm, 0);
603 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
605 if (global_parameters.dump_records)
606 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
607 cl->database->url, cl->records);
610 /* no room for record */
614 relevance_newrec(se->relevance, cluster);
616 for (n = root->children; n; n = n->next)
624 if (n->type != XML_ELEMENT_NODE)
626 if (!strcmp((const char *) n->name, "metadata"))
628 struct conf_metadata *md = 0;
629 struct conf_sortkey *sk = 0;
630 struct record_metadata **wheretoput, *newm;
634 type = xmlGetProp(n, (xmlChar *) "type");
635 value = xmlNodeListGetString(xdoc, n->children, 0);
640 // First, find out what field we're looking at
641 for (imeta = 0; imeta < service->num_metadata; imeta++)
642 if (!strcmp((const char *) type, service->metadata[imeta].name))
644 md = &service->metadata[imeta];
645 if (md->sortkey_offset >= 0)
646 sk = &service->sortkeys[md->sortkey_offset];
651 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
655 // Find out where we are putting it
656 if (md->merge == Metadata_merge_no)
657 wheretoput = &res->metadata[imeta];
659 wheretoput = &cluster->metadata[imeta];
662 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
664 if (md->type == Metadata_type_generic)
667 for (p = (char *) value; *p && isspace(*p); p++)
669 for (pe = p + strlen(p) - 1;
670 pe > p && strchr(" ,/.:([", *pe); pe--)
672 newm->data.text = nmem_strdup(se->nmem, p);
675 else if (md->type == Metadata_type_year)
677 if (extract_years((char *) value, &first, &last) < 0)
682 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
685 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
687 yaz_log(YLOG_WARN, "Only range merging supported for years");
690 if (md->merge == Metadata_merge_unique)
692 struct record_metadata *mnode;
693 for (mnode = *wheretoput; mnode; mnode = mnode->next)
694 if (!strcmp((const char *) mnode->data.text, newm->data.text))
698 newm->next = *wheretoput;
702 else if (md->merge == Metadata_merge_longest)
705 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
710 char *s = nmem_strdup(se->nmem, newm->data.text);
711 if (!cluster->sortkeys[md->sortkey_offset])
712 cluster->sortkeys[md->sortkey_offset] =
713 nmem_malloc(se->nmem, sizeof(union data_types));
714 normalize_mergekey(s,
715 (sk->type == Metadata_sortkey_skiparticle));
716 cluster->sortkeys[md->sortkey_offset]->text = s;
720 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
722 newm->next = *wheretoput;
725 else if (md->merge == Metadata_merge_range)
727 assert(md->type == Metadata_type_year);
731 (*wheretoput)->data.number.min = first;
732 (*wheretoput)->data.number.max = last;
734 cluster->sortkeys[md->sortkey_offset] = &newm->data;
738 if (first < (*wheretoput)->data.number.min)
739 (*wheretoput)->data.number.min = first;
740 if (last > (*wheretoput)->data.number.max)
741 (*wheretoput)->data.number.max = last;
746 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
747 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
752 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
755 relevance_countwords(se->relevance, cluster,
756 (char *) value, md->rank);
759 if (md->type == Metadata_type_year)
762 sprintf(year, "%d", last);
763 add_facet(se, (char *) type, year);
766 sprintf(year, "%d", first);
767 add_facet(se, (char *) type, year);
771 add_facet(se, (char *) type, (char *) value);
778 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
787 relevance_donerecord(se->relevance, cluster);
793 // Retrieve first defined value for 'name' for given database.
794 // Will be extended to take into account user associated with session
795 char *session_setting_oneval(struct session *s, struct database *db, int offset)
797 if (!db->settings[offset])
799 return db->settings[offset]->value;
802 static void ingest_records(struct client *cl, Z_Records *r)
805 yaz_timing_t t = yaz_timing_create();
808 struct session *s = cl->session;
809 Z_NamePlusRecordList *rlist;
812 if (r->which != Z_Records_DBOSD)
814 rlist = r->u.databaseOrSurDiagnostics;
815 for (i = 0; i < rlist->num_records; i++)
817 Z_NamePlusRecord *npr = rlist->records[i];
820 if (npr->which != Z_NamePlusRecord_databaseRecord)
823 "Unexpected record type, probably diagnostic %s",
828 rec = ingest_record(cl, npr->u.databaseRecord);
832 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
833 session_alert_watch(s, SESSION_WATCH_RECORDS);
837 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
838 yaz_timing_get_real(t), yaz_timing_get_user(t),
839 yaz_timing_get_sys(t));
840 yaz_timing_destroy(&t);
844 static void do_presentResponse(IOCHAN i, Z_APDU *a)
846 struct connection *co = iochan_getdata(i);
847 struct client *cl = co->client;
848 Z_PresentResponse *r = a->u.presentResponse;
851 Z_Records *recs = r->records;
852 if (recs->which == Z_Records_NSD)
854 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
856 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
857 cl->state = Client_Error;
861 if (!*r->presentStatus && cl->state != Client_Error)
863 yaz_log(YLOG_DEBUG, "Good Present response %s",
865 ingest_records(cl, r->records);
866 cl->state = Client_Idle;
868 else if (*r->presentStatus)
870 yaz_log(YLOG_WARN, "Bad Present response %s",
872 cl->state = Client_Error;
876 static void handler(IOCHAN i, int event)
878 struct connection *co = iochan_getdata(i);
879 struct client *cl = co->client;
880 struct session *se = 0;
886 yaz_log(YLOG_WARN, "Destroying orphan connection");
887 connection_destroy(co);
891 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
894 socklen_t errlen = sizeof(errcode);
896 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
897 &errlen) < 0 || errcode != 0)
904 yaz_log(YLOG_DEBUG, "Connect OK");
905 co->state = Conn_Open;
907 cl->state = Client_Connected;
911 else if (event & EVENT_INPUT)
913 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
917 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
919 connection_destroy(co);
924 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
925 connection_destroy(co);
928 else if (len > 1) // We discard input if we have no connection
930 co->state = Conn_Open;
932 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
936 odr_reset(global_parameters.odr_in);
937 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
938 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
945 case Z_APDU_initResponse:
946 do_initResponse(i, a);
948 case Z_APDU_searchResponse:
949 do_searchResponse(i, a);
951 case Z_APDU_presentResponse:
952 do_presentResponse(i, a);
955 do_closeResponse(i, a);
959 "Unexpected Z39.50 response from %s",
964 // We aren't expecting staggered output from target
965 // if (cs_more(t->link))
966 // iochan_setevent(i, EVENT_INPUT);
968 else // we throw away response and go to idle mode
970 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
971 cl->state = Client_Idle;
974 /* if len==1 we do nothing but wait for more input */
977 if (cl->state == Client_Connected) {
981 if (cl->state == Client_Idle)
983 if (cl->requestid != se->requestid && *se->query) {
986 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
987 cl->records < cl->hits) {
993 // Disassociate connection from client
994 static void connection_release(struct connection *co)
996 struct client *cl = co->client;
998 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1005 // Close connection and recycle structure
1006 static void connection_destroy(struct connection *co)
1008 struct host *h = co->host;
1010 iochan_destroy(co->iochan);
1012 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1013 if (h->connections == co)
1014 h->connections = co->next;
1017 struct connection *pco;
1018 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1021 pco->next = co->next;
1027 if (co->client->state != Client_Idle)
1028 co->client->state = Client_Disconnected;
1029 co->client->connection = 0;
1031 co->next = connection_freelist;
1032 connection_freelist = co;
1035 // Creates a new connection for client, associated with the host of
1036 // client's database
1037 static struct connection *connection_create(struct client *cl)
1039 struct connection *new;
1045 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1047 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1051 if (0 == strlen(global_parameters.zproxy_override)){
1052 /* no Z39.50 proxy needed - direct connect */
1053 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1055 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1057 yaz_log(YLOG_WARN|YLOG_ERRNO,
1058 "Lookup of IP address %s failed",
1059 cl->database->host->ipport);
1064 /* Z39.50 proxy connect */
1065 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1066 cl->database->url, global_parameters.zproxy_override);
1068 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1070 yaz_log(YLOG_WARN|YLOG_ERRNO,
1071 "Lookup of IP address %s failed",
1072 global_parameters.zproxy_override);
1077 res = cs_connect(link, addr);
1080 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1084 if ((new = connection_freelist))
1085 connection_freelist = new->next;
1088 new = xmalloc(sizeof (struct connection));
1092 new->state = Conn_Connecting;
1093 new->host = cl->database->host;
1094 new->next = new->host->connections;
1095 new->host->connections = new;
1097 cl->connection = new;
1100 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1101 iochan_setdata(new->iochan, new);
1102 new->iochan->next = channel_list;
1103 channel_list = new->iochan;
1107 // Close connection and set state to error
1108 static void client_fatal(struct client *cl)
1110 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1111 connection_destroy(cl->connection);
1112 cl->state = Client_Error;
1115 // Ensure that client has a connection associated
1116 static int client_prep_connection(struct client *cl)
1118 struct connection *co;
1119 struct session *se = cl->session;
1120 struct host *host = cl->database->host;
1122 co = cl->connection;
1124 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1128 // See if someone else has an idle connection
1129 // We should look at timestamps here to select the longest-idle connection
1130 for (co = host->connections; co; co = co->next)
1131 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1135 connection_release(co);
1136 cl->connection = co;
1140 co = connection_create(cl);
1144 if (co->state == Conn_Connecting)
1146 cl->state = Client_Connecting;
1147 iochan_setflag(co->iochan, EVENT_OUTPUT);
1149 else if (co->state == Conn_Open)
1151 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1152 cl->state = Client_Idle;
1153 iochan_setflag(co->iochan, EVENT_OUTPUT);
1161 static struct client *client_create(void)
1164 if (client_freelist)
1166 r = client_freelist;
1167 client_freelist = client_freelist->next;
1170 r = xmalloc(sizeof(struct client));
1179 r->state = Client_Disconnected;
1184 void client_destroy(struct client *c)
1186 struct session *se = c->session;
1187 if (c == se->clients)
1188 se->clients = c->next;
1192 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1198 connection_release(c->connection);
1199 c->next = client_freelist;
1200 client_freelist = c;
1203 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1205 s->watchlist[what].fun = fun;
1206 s->watchlist[what].data = data;
1209 void session_alert_watch(struct session *s, int what)
1211 if (!s->watchlist[what].fun)
1213 (*s->watchlist[what].fun)(s->watchlist[what].data);
1214 s->watchlist[what].fun = 0;
1215 s->watchlist[what].data = 0;
1218 //callback for grep_databases
1219 static void select_targets_callback(void *context, struct database *db)
1221 struct session *se = (struct session*) context;
1222 struct client *cl = client_create();
1225 cl->next = se->clients;
1229 // Associates a set of clients with a session;
1230 int select_targets(struct session *se, struct database_criterion *crit)
1233 client_destroy(se->clients);
1235 return grep_databases(se, crit, select_targets_callback);
1238 int session_active_clients(struct session *s)
1243 for (c = s->clients; c; c = c->next)
1244 if (c->connection && (c->state == Client_Connecting ||
1245 c->state == Client_Initializing ||
1246 c->state == Client_Searching ||
1247 c->state == Client_Presenting))
1253 // parses crit1=val1,crit2=val2|val3,...
1254 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1256 struct database_criterion *res = 0;
1263 nmem_strsplit(m, ",", buf, &values, &num);
1264 for (i = 0; i < num; i++)
1269 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1270 char *eq = strchr(values[i], '=');
1273 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1277 new->name = values[i];
1278 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1280 for (subi = 0; subi < subnum; subi++)
1282 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1283 newv->value = subvalues[subi];
1284 newv->next = new->values;
1293 char *search(struct session *se, char *query, char *filter)
1295 int live_channels = 0;
1297 struct database_criterion *criteria;
1299 yaz_log(YLOG_DEBUG, "Search");
1301 nmem_reset(se->nmem);
1302 criteria = parse_filter(se->nmem, filter);
1303 strcpy(se->query, query);
1305 select_targets(se, criteria);
1306 for (cl = se->clients; cl; cl = cl->next)
1308 if (client_prep_connection(cl))
1313 int maxrecs = live_channels * global_parameters.toget;
1314 se->num_termlists = 0;
1315 se->reclist = reclist_create(se->nmem, maxrecs);
1316 // This will be initialized in send_search()
1318 se->total_records = se->total_hits = se->total_merged = 0;
1319 se->expected_maxrecs = maxrecs;
1327 void destroy_session(struct session *s)
1329 yaz_log(YLOG_LOG, "Destroying session");
1331 client_destroy(s->clients);
1332 nmem_destroy(s->nmem);
1333 wrbuf_destroy(s->wrbuf);
1336 struct session *new_session(NMEM nmem)
1339 struct session *session = nmem_malloc(nmem, sizeof(*session));
1341 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1343 session->total_hits = 0;
1344 session->total_records = 0;
1345 session->num_termlists = 0;
1346 session->reclist = 0;
1347 session->requestid = -1;
1348 session->clients = 0;
1349 session->expected_maxrecs = 0;
1350 session->query[0] = '\0';
1351 session->session_nmem = nmem;
1352 session->nmem = nmem_create();
1353 session->wrbuf = wrbuf_alloc();
1354 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1356 session->watchlist[i].data = 0;
1357 session->watchlist[i].fun = 0;
1363 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1365 static struct hitsbytarget res[1000]; // FIXME MM
1369 for (cl = se->clients; cl; cl = cl->next)
1371 res[*count].id = cl->database->url;
1372 res[*count].name = cl->database->name;
1373 res[*count].hits = cl->hits;
1374 res[*count].records = cl->records;
1375 res[*count].diagnostic = cl->diagnostic;
1376 res[*count].state = client_states[cl->state];
1377 res[*count].connected = cl->connection ? 1 : 0;
1384 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1388 for (i = 0; i < s->num_termlists; i++)
1389 if (!strcmp((const char *) s->termlists[i].name, name))
1390 return termlist_highscore(s->termlists[i].termlist, num);
1394 #ifdef MISSING_HEADERS
1395 void report_nmem_stats(void)
1397 size_t in_use, is_free;
1399 nmem_get_memory_in_use(&in_use);
1400 nmem_get_memory_free(&is_free);
1402 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1403 (long) in_use, (long) is_free);
1407 struct record_cluster *show_single(struct session *s, int id)
1409 struct record_cluster *r;
1411 reclist_rewind(s->reclist);
1412 while ((r = reclist_read_record(s->reclist)))
1418 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1419 int *num, int *total, int *sumhits, NMEM nmem_show)
1421 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1422 * sizeof(struct record_cluster *));
1423 struct reclist_sortparms *spp;
1426 yaz_timing_t t = yaz_timing_create();
1429 for (spp = sp; spp; spp = spp->next)
1430 if (spp->type == Metadata_sortkey_relevance)
1432 relevance_prepare_read(s->relevance, s->reclist);
1435 reclist_sort(s->reclist, sp);
1437 *total = s->reclist->num_records;
1438 *sumhits = s->total_hits;
1440 for (i = 0; i < start; i++)
1441 if (!reclist_read_record(s->reclist))
1448 for (i = 0; i < *num; i++)
1450 struct record_cluster *r = reclist_read_record(s->reclist);
1460 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1461 yaz_timing_get_real(t), yaz_timing_get_user(t),
1462 yaz_timing_get_sys(t));
1463 yaz_timing_destroy(&t);
1468 void statistics(struct session *se, struct statistics *stat)
1473 memset(stat, 0, sizeof(*stat));
1474 for (cl = se->clients; cl; cl = cl->next)
1476 if (!cl->connection)
1477 stat->num_no_connection++;
1480 case Client_Connecting: stat->num_connecting++; break;
1481 case Client_Initializing: stat->num_initializing++; break;
1482 case Client_Searching: stat->num_searching++; break;
1483 case Client_Presenting: stat->num_presenting++; break;
1484 case Client_Idle: stat->num_idle++; break;
1485 case Client_Failed: stat->num_failed++; break;
1486 case Client_Error: stat->num_error++; break;
1491 stat->num_hits = se->total_hits;
1492 stat->num_records = se->total_records;
1494 stat->num_clients = count;
1497 static void start_http_listener(void)
1500 struct conf_server *ser = global_parameters.server;
1502 if (*global_parameters.listener_override)
1503 strcpy(hp, global_parameters.listener_override);
1506 strcpy(hp, ser->host ? ser->host : "");
1511 sprintf(hp + strlen(hp), "%d", ser->port);
1517 static void start_proxy(void)
1520 struct conf_server *ser = global_parameters.server;
1522 if (*global_parameters.proxy_override)
1523 strcpy(hp, global_parameters.proxy_override);
1524 else if (ser->proxy_host || ser->proxy_port)
1526 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1527 if (ser->proxy_port)
1531 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1537 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1540 static void start_zproxy(void)
1542 struct conf_server *ser = global_parameters.server;
1544 if (*global_parameters.zproxy_override){
1545 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1546 global_parameters.zproxy_override);
1550 else if (ser->zproxy_host || ser->zproxy_port)
1554 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1555 if (ser->zproxy_port)
1562 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1564 strcpy(global_parameters.zproxy_override, hp);
1565 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1566 global_parameters.zproxy_override);
1575 int main(int argc, char **argv)
1580 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1581 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1583 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1585 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1589 if (!read_config(arg))
1593 strcpy(global_parameters.listener_override, arg);
1596 strcpy(global_parameters.proxy_override, arg);
1599 strcpy(global_parameters.zproxy_override, arg);
1602 strcpy(global_parameters.settings_path_override, arg);
1605 load_simpletargets(arg);
1608 global_parameters.dump_records = 1;
1611 fprintf(stderr, "Usage: pazpar2\n"
1613 " -h [host:]port (REST protocol listener)\n"
1615 " -s simpletargetfile\n"
1616 " -p hostname[:portno] (HTTP proxy)\n"
1617 " -z hostname[:portno] (Z39.50 proxy)\n"
1618 " -d (show internal records)\n");
1625 yaz_log(YLOG_FATAL, "Load config with -f");
1628 global_parameters.server = config->servers;
1630 start_http_listener();
1634 if (*global_parameters.settings_path_override)
1635 settings_read(global_parameters.settings_path_override);
1636 else if (global_parameters.server->settings)
1637 settings_read(global_parameters.server->settings);
1639 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1640 prepare_databases();
1641 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1642 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1644 event_loop(&channel_list);
1652 * indent-tabs-mode: nil
1654 * vim: shiftwidth=4 tabstop=8 expandtab