Fixed bug related to ranking, introduced by 'metadata' update.
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.20 2007-01-08 19:39:12 quinn Exp $ */;
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/time.h>
7 #include <unistd.h>
8 #include <sys/socket.h>
9 #include <netdb.h>
10 #include <signal.h>
11 #include <ctype.h>
12 #include <assert.h>
13
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/yaz-util.h>
21 #include <yaz/nmem.h>
22
23 #if HAVE_CONFIG_H
24 #include "cconfig.h"
25 #endif
26
27 #define USE_TIMING 0
28 #if USE_TIMING
29 #include <yaz/timing.h>
30 #endif
31
32 #include "pazpar2.h"
33 #include "eventl.h"
34 #include "http.h"
35 #include "termlists.h"
36 #include "reclists.h"
37 #include "relevance.h"
38 #include "config.h"
39
40 #define MAX_CHUNK 15
41
42 static void client_fatal(struct client *cl);
43 static void connection_destroy(struct connection *co);
44 static int client_prep_connection(struct client *cl);
45 static void ingest_records(struct client *cl, Z_Records *r);
46 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
47 void session_alert_watch(struct session *s, int what);
48
49 IOCHAN channel_list = 0;  // Master list of connections we're handling events to
50
51 static struct connection *connection_freelist = 0;
52 static struct client *client_freelist = 0;
53
54 static struct host *hosts = 0;  // The hosts we know about 
55 static struct database *databases = 0; // The databases we know about
56
57 static char *client_states[] = {
58     "Client_Connecting",
59     "Client_Connected",
60     "Client_Idle",
61     "Client_Initializing",
62     "Client_Searching",
63     "Client_Presenting",
64     "Client_Error",
65     "Client_Failed",
66     "Client_Disconnected",
67     "Client_Stopped"
68 };
69
70 // Note: Some things in this structure will eventually move to configuration
71 struct parameters global_parameters = 
72 {
73     0,
74     0,
75     30,
76     "81",
77     "Index Data PazPar2 (MasterKey)",
78     VERSION,
79     600, // 10 minutes
80     60,
81     100,
82     MAX_CHUNK,
83     0,
84     0,
85     0,
86     0
87 };
88
89 static int send_apdu(struct client *c, Z_APDU *a)
90 {
91     struct connection *co = c->connection;
92     char *buf;
93     int len, r;
94
95     if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
96     {
97         odr_perror(global_parameters.odr_out, "Encoding APDU");
98         abort();
99     }
100     buf = odr_getbuf(global_parameters.odr_out, &len, 0);
101     r = cs_put(co->link, buf, len);
102     if (r < 0)
103     {
104         yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
105         return -1;
106     }
107     else if (r == 1)
108     {
109         fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
110         exit(1);
111     }
112     odr_reset(global_parameters.odr_out); /* release the APDU structure  */
113     co->state = Conn_Waiting;
114     return 0;
115 }
116
117
118 static void send_init(IOCHAN i)
119 {
120     struct connection *co = iochan_getdata(i);
121     struct client *cl = co->client;
122     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
123
124     a->u.initRequest->implementationId = global_parameters.implementationId;
125     a->u.initRequest->implementationName = global_parameters.implementationName;
126     a->u.initRequest->implementationVersion =
127         global_parameters.implementationVersion;
128     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
129     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
130     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
131
132     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
133     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
134     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
135     if (send_apdu(cl, a) >= 0)
136     {
137         iochan_setflags(i, EVENT_INPUT);
138         cl->state = Client_Initializing;
139     }
140     else
141         cl->state = Client_Error;
142     odr_reset(global_parameters.odr_out);
143 }
144
145 static void send_search(IOCHAN i)
146 {
147     struct connection *co = iochan_getdata(i);
148     struct client *cl = co->client; 
149     struct session *se = cl->session;
150     struct database *db = cl->database;
151     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
152     int ndb, cerror, cpos;
153     char **databaselist;
154     Z_Query *zquery;
155     struct ccl_rpn_node *cn;
156     int ssub = 0, lslb = 100000, mspn = 10;
157
158     yaz_log(YLOG_DEBUG, "Sending search");
159
160     cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
161     if (!cn)
162         return;
163     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
164             sizeof(Z_Query));
165     zquery->which = Z_Query_type_1;
166     zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
167     ccl_rpn_delete(cn);
168
169     for (ndb = 0; db->databases[ndb]; ndb++)
170         ;
171     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
172     for (ndb = 0; db->databases[ndb]; ndb++)
173         databaselist[ndb] = db->databases[ndb];
174
175     a->u.presentRequest->preferredRecordSyntax =
176             yaz_oidval_to_z3950oid(global_parameters.odr_out,
177             CLASS_RECSYN, VAL_USMARC);
178     a->u.searchRequest->smallSetUpperBound = &ssub;
179     a->u.searchRequest->largeSetLowerBound = &lslb;
180     a->u.searchRequest->mediumSetPresentNumber = &mspn;
181     a->u.searchRequest->resultSetName = "Default";
182     a->u.searchRequest->databaseNames = databaselist;
183     a->u.searchRequest->num_databaseNames = ndb;
184
185     if (send_apdu(cl, a) >= 0)
186     {
187         iochan_setflags(i, EVENT_INPUT);
188         cl->state = Client_Searching;
189         cl->requestid = se->requestid;
190     }
191     else
192         cl->state = Client_Error;
193
194     odr_reset(global_parameters.odr_out);
195 }
196
197 static void send_present(IOCHAN i)
198 {
199     struct connection *co = iochan_getdata(i);
200     struct client *cl = co->client; 
201     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
202     int toget;
203     int start = cl->records + 1;
204
205     toget = global_parameters.chunk;
206     if (toget > global_parameters.toget - cl->records)
207         toget = global_parameters.toget - cl->records;
208     if (toget > cl->hits - cl->records)
209         toget = cl->hits - cl->records;
210
211     yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
212
213     a->u.presentRequest->resultSetStartPoint = &start;
214     a->u.presentRequest->numberOfRecordsRequested = &toget;
215
216     a->u.presentRequest->resultSetId = "Default";
217
218     a->u.presentRequest->preferredRecordSyntax =
219             yaz_oidval_to_z3950oid(global_parameters.odr_out,
220             CLASS_RECSYN, VAL_USMARC);
221
222     if (send_apdu(cl, a) >= 0)
223     {
224         iochan_setflags(i, EVENT_INPUT);
225         cl->state = Client_Presenting;
226     }
227     else
228         cl->state = Client_Error;
229     odr_reset(global_parameters.odr_out);
230 }
231
232 static void do_initResponse(IOCHAN i, Z_APDU *a)
233 {
234     struct connection *co = iochan_getdata(i);
235     struct client *cl = co->client;
236     Z_InitResponse *r = a->u.initResponse;
237
238     yaz_log(YLOG_DEBUG, "Received init response");
239
240     if (*r->result)
241     {
242         cl->state = Client_Idle;
243     }
244     else
245         cl->state = Client_Failed; // FIXME need to do something to the connection
246 }
247
248 static void do_searchResponse(IOCHAN i, Z_APDU *a)
249 {
250     struct connection *co = iochan_getdata(i);
251     struct client *cl = co->client;
252     struct session *se = cl->session;
253     Z_SearchResponse *r = a->u.searchResponse;
254
255     yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
256
257     if (*r->searchStatus)
258     {
259         cl->hits = *r->resultCount;
260         se->total_hits += cl->hits;
261         if (r->presentStatus && !*r->presentStatus && r->records)
262         {
263             yaz_log(YLOG_DEBUG, "Records in search response");
264             cl->records += *r->numberOfRecordsReturned;
265             ingest_records(cl, r->records);
266         }
267         cl->state = Client_Idle;
268     }
269     else
270     {          /*"FAILED"*/
271         cl->hits = 0;
272         cl->state = Client_Error;
273         if (r->records) {
274             Z_Records *recs = r->records;
275             if (recs->which == Z_Records_NSD)
276             {
277                 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
278                 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
279                 cl->state = Client_Error;
280             }
281         }
282     }
283 }
284
285 char *normalize_mergekey(char *buf)
286 {
287     char *p = buf, *pout = buf;
288
289     while (*p)
290     {
291         while (*p && !isalnum(*p))
292             p++;
293         while (isalnum(*p))
294             *(pout++) = tolower(*(p++));
295         if (*p)
296             *(pout++) = ' ';
297         while (*p && !isalnum(*p))
298             p++;
299     }
300     if (buf != pout)
301         *pout = '\0';
302
303     return buf;
304 }
305
306
307 #ifdef GAGA
308 // FIXME needs to be generalized. Should flexibly generate X lists per search
309 static void extract_subject(struct session *s, const char *rec)
310 {
311     const char *field, *subfield;
312
313     while ((field = find_field(rec, "650")))
314     {
315         rec = field; 
316         if ((subfield = find_subfield(field, 'a')))
317         {
318             char *e, *ef;
319             char buf[1024];
320             int len;
321
322             ef = index(subfield, '\n');
323             if (!ef)
324                 return;
325             if ((e = index(subfield, '\t')) && e < ef)
326                 ef = e;
327             while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
328                 ef--;
329             len = ef - subfield;
330             assert(len < 1023);
331             memcpy(buf, subfield, len);
332             buf[len] = '\0';
333 #ifdef FIXME
334             if (*buf)
335                 termlist_insert(s->termlist, buf);
336 #endif
337         }
338     }
339 }
340 #endif
341
342 static void add_facet(struct session *s, const char *type, const char *value)
343 {
344     int i;
345
346     for (i = 0; i < s->num_termlists; i++)
347         if (!strcmp(s->termlists[i].name, type))
348             break;
349     if (i == s->num_termlists)
350     {
351         if (i == SESSION_MAX_TERMLISTS)
352         {
353             yaz_log(YLOG_FATAL, "Too many termlists");
354             exit(1);
355         }
356         s->termlists[i].name = nmem_strdup(s->nmem, type);
357         s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
358         s->num_termlists = i + 1;
359     }
360     termlist_insert(s->termlists[i].termlist, value);
361 }
362
363 int yaz_marc_write_xml();
364
365 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
366 {
367     struct conf_retrievalprofile *rprofile = cl->database->rprofile;
368     struct conf_retrievalmap *m;
369     xmlNode *res;
370     xmlDoc *rdoc;
371
372     // First normalize to XML
373     if (rprofile->native_syntax == Nativesyn_iso2709)
374     {
375         char *buf;
376         int len;
377         if (rec->which != Z_External_octet)
378         {
379             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
380             return 0;
381         }
382         buf = (char*) rec->u.octet_aligned->buf;
383         len = rec->u.octet_aligned->len;
384         if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
385         {
386             yaz_log(YLOG_WARN, "Failed to decode MARC");
387             return 0;
388         }
389         if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
390                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
391         {
392             yaz_log(YLOG_WARN, "Failed to encode as XML");
393             return 0;
394         }
395         rdoc = xmlNewDoc("1.0");
396         xmlDocSetRootElement(rdoc, res);
397     }
398     else
399     {
400         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
401         exit(1);
402     }
403     for (m = rprofile->maplist; m; m = m->next)
404     {
405         xmlDoc *new;
406         if (m->type != Map_xslt)
407         {
408             yaz_log(YLOG_WARN, "Unknown map type");
409             return 0;
410         }
411         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
412         {
413             yaz_log(YLOG_WARN, "XSLT transformation failed");
414             return 0;
415         }
416         xmlFreeDoc(rdoc);
417         rdoc = new;
418     }
419     if (global_parameters.dump_records)
420     {
421         fprintf(stderr, "Record:\n----------------\n");
422         xmlDocFormatDump(stderr, rdoc, 1);
423     }
424     return rdoc;
425 }
426
427 static struct record *ingest_record(struct client *cl, Z_External *rec)
428 {
429     xmlDoc *xdoc = normalize_record(cl, rec);
430     xmlNode *root, *n;
431     struct record *res;
432     struct record_cluster *cluster;
433     struct session *se = cl->session;
434     xmlChar *mergekey, *mergekey_norm;
435     xmlChar *type;
436     xmlChar *value;
437     struct conf_service *service = global_parameters.server->service;
438
439     if (!xdoc)
440         return 0;
441
442     root = xmlDocGetRootElement(xdoc);
443     if (!(mergekey = xmlGetProp(root, "mergekey")))
444     {
445         yaz_log(YLOG_WARN, "No mergekey found in record");
446         xmlFreeDoc(xdoc);
447         return 0;
448     }
449
450     res = nmem_malloc(se->nmem, sizeof(struct record));
451     res->next = 0;
452     res->target_offset = -1;
453     res->term_frequency_vec = 0;
454     res->metadata = nmem_malloc(se->nmem,
455             sizeof(struct record_metadata*) * service->num_metadata);
456     bzero(res->metadata, sizeof(struct record_metadata*) * service->num_metadata);
457     res->relevance = 0;
458
459     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
460     xmlFree(mergekey);
461     normalize_mergekey(mergekey_norm);
462
463     cluster = reclist_insert(se->reclist, res, mergekey_norm);
464     if (!cluster)
465     {
466         /* no room for record */
467         xmlFreeDoc(xdoc);
468         return 0;
469     }
470     relevance_newrec(se->relevance, cluster);
471
472     type = value = 0;
473     for (n = root->children; n; n = n->next)
474     {
475         if (type)
476             xmlFree(type);
477         if (value)
478             xmlFree(value);
479         type = value = 0;
480
481         if (n->type != XML_ELEMENT_NODE)
482             continue;
483         if (!strcmp(n->name, "metadata"))
484         {
485             type = xmlGetProp(n, "type");
486             value = xmlNodeListGetString(xdoc, n->children, 0);
487             struct conf_metadata *md = 0;
488             struct record_metadata **wheretoput, *newm;
489             int imeta;
490
491             // First, find out what field we're looking at
492             for (imeta = 0; imeta < service->num_metadata; imeta++)
493                 if (!strcmp(type, service->metadata[imeta].name))
494                 {
495                     md = &service->metadata[imeta];
496                     break;
497                 }
498             if (!md)
499             {
500                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
501                 continue;
502             }
503
504             // Find out where we are putting it
505             if (md->merge == Metadata_merge_no)
506                 wheretoput = &res->metadata[imeta];
507             else
508                 wheretoput = &cluster->metadata[imeta];
509             
510             // Put it there
511             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
512             newm->next = 0;
513             if (md->type == Metadata_type_generic)
514             {
515                 newm->data.text = nmem_strdup(se->nmem, value);
516             }
517             else
518             {
519                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
520                 continue;
521             }
522             if (md->merge == Metadata_merge_unique)
523             {
524                 struct record_metadata *mnode;
525                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
526                     if (!strcmp(mnode->data.text, mnode->data.text))
527                         break;
528                 if (!mnode)
529                 {
530                     newm->next = *wheretoput;
531                     *wheretoput = newm;
532                 }
533             }
534             else if (md->merge == Metadata_merge_longest)
535             {
536                 if (!*wheretoput ||
537                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
538                 *wheretoput = newm;
539             }
540             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
541             {
542                 newm->next = *wheretoput;
543                 *wheretoput = newm;
544             }
545             else
546                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
547
548             if (md->rank)
549                 relevance_countwords(se->relevance, cluster, value, md->rank);
550             if (md->termlist)
551                 add_facet(se, type, value);
552             xmlFree(type);
553             xmlFree(value);
554             type = value = 0;
555         }
556         else
557             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
558     }
559
560     xmlFreeDoc(xdoc);
561
562     relevance_donerecord(se->relevance, cluster);
563     se->total_records++;
564
565     return res;
566 }
567
568 static void ingest_records(struct client *cl, Z_Records *r)
569 {
570 #if USE_TIMING
571     yaz_timing_t t = yaz_timing_create();
572 #endif
573     struct record *rec;
574     struct session *s = cl->session;
575     Z_NamePlusRecordList *rlist;
576     int i;
577
578     if (r->which != Z_Records_DBOSD)
579         return;
580     rlist = r->u.databaseOrSurDiagnostics;
581     for (i = 0; i < rlist->num_records; i++)
582     {
583         Z_NamePlusRecord *npr = rlist->records[i];
584
585         if (npr->which != Z_NamePlusRecord_databaseRecord)
586         {
587             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
588             continue;
589         }
590
591         rec = ingest_record(cl, npr->u.databaseRecord);
592         if (!rec)
593             continue;
594     }
595     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
596         session_alert_watch(s, SESSION_WATCH_RECORDS);
597
598 #if USE_TIMING
599     yaz_timing_stop(t);
600     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
601             yaz_timing_get_real(t), yaz_timing_get_user(t),
602             yaz_timing_get_sys(t));
603     yaz_timing_destroy(&t);
604 #endif
605 }
606
607 static void do_presentResponse(IOCHAN i, Z_APDU *a)
608 {
609     struct connection *co = iochan_getdata(i);
610     struct client *cl = co->client;
611     Z_PresentResponse *r = a->u.presentResponse;
612
613     if (r->records) {
614         Z_Records *recs = r->records;
615         if (recs->which == Z_Records_NSD)
616         {
617             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
618             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
619             cl->state = Client_Error;
620         }
621     }
622
623     if (!*r->presentStatus && cl->state != Client_Error)
624     {
625         yaz_log(YLOG_DEBUG, "Good Present response");
626         cl->records += *r->numberOfRecordsReturned;
627         ingest_records(cl, r->records);
628         cl->state = Client_Idle;
629     }
630     else if (*r->presentStatus) 
631     {
632         yaz_log(YLOG_WARN, "Bad Present response");
633         cl->state = Client_Error;
634     }
635 }
636
637 static void handler(IOCHAN i, int event)
638 {
639     struct connection *co = iochan_getdata(i);
640     struct client *cl = co->client;
641     struct session *se = 0;
642
643     if (cl)
644         se = cl->session;
645     else
646     {
647         yaz_log(YLOG_WARN, "Destroying orphan connection");
648         connection_destroy(co);
649         return;
650     }
651
652     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
653     {
654         int errcode;
655         socklen_t errlen = sizeof(errcode);
656
657         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
658             &errlen) < 0 || errcode != 0)
659         {
660             client_fatal(cl);
661             return;
662         }
663         else
664         {
665             yaz_log(YLOG_DEBUG, "Connect OK");
666             co->state = Conn_Open;
667             if (cl)
668                 cl->state = Client_Connected;
669         }
670     }
671
672     else if (event & EVENT_INPUT)
673     {
674         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
675
676         if (len < 0)
677         {
678             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
679             connection_destroy(co);
680             return;
681         }
682         else if (len == 0)
683         {
684             yaz_log(YLOG_WARN, "EOF reading from Z server");
685             connection_destroy(co);
686             return;
687         }
688         else if (len > 1) // We discard input if we have no connection
689         {
690             co->state = Conn_Open;
691
692             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
693             {
694                 Z_APDU *a;
695
696                 odr_reset(global_parameters.odr_in);
697                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
698                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
699                 {
700                     client_fatal(cl);
701                     return;
702                 }
703                 switch (a->which)
704                 {
705                     case Z_APDU_initResponse:
706                         do_initResponse(i, a);
707                         break;
708                     case Z_APDU_searchResponse:
709                         do_searchResponse(i, a);
710                         break;
711                     case Z_APDU_presentResponse:
712                         do_presentResponse(i, a);
713                         break;
714                     default:
715                         yaz_log(YLOG_WARN, "Unexpected result from server");
716                         client_fatal(cl);
717                         return;
718                 }
719                 // We aren't expecting staggered output from target
720                 // if (cs_more(t->link))
721                 //    iochan_setevent(i, EVENT_INPUT);
722             }
723             else  // we throw away response and go to idle mode
724             {
725                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
726                 cl->state = Client_Idle;
727             }
728         }
729         /* if len==1 we do nothing but wait for more input */
730     }
731
732     if (cl->state == Client_Connected) {
733         send_init(i);
734     }
735
736     if (cl->state == Client_Idle)
737     {
738         if (cl->requestid != se->requestid && *se->query) {
739             send_search(i);
740         }
741         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
742             cl->records < cl->hits) {
743             send_present(i);
744         }
745     }
746 }
747
748 // Disassociate connection from client
749 static void connection_release(struct connection *co)
750 {
751     struct client *cl = co->client;
752
753     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
754     if (!cl)
755         return;
756     cl->connection = 0;
757     co->client = 0;
758 }
759
760 // Close connection and recycle structure
761 static void connection_destroy(struct connection *co)
762 {
763     struct host *h = co->host;
764     cs_close(co->link);
765     iochan_destroy(co->iochan);
766
767     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
768     if (h->connections == co)
769         h->connections = co->next;
770     else
771     {
772         struct connection *pco;
773         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
774             ;
775         if (pco)
776             pco->next = co->next;
777         else
778             abort();
779     }
780     if (co->client)
781     {
782         if (co->client->state != Client_Idle)
783             co->client->state = Client_Disconnected;
784         co->client->connection = 0;
785     }
786     co->next = connection_freelist;
787     connection_freelist = co;
788 }
789
790 // Creates a new connection for client, associated with the host of 
791 // client's database
792 static struct connection *connection_create(struct client *cl)
793 {
794     struct connection *new;
795     COMSTACK link; 
796     int res;
797     void *addr;
798
799     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
800     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
801     {
802         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
803         exit(1);
804     }
805
806     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
807     {
808         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
809         return 0;
810     }
811
812     res = cs_connect(link, addr);
813     if (res < 0)
814     {
815         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
816         return 0;
817     }
818
819     if ((new = connection_freelist))
820         connection_freelist = new->next;
821     else
822     {
823         new = xmalloc(sizeof (struct connection));
824         new->ibuf = 0;
825         new->ibufsize = 0;
826     }
827     new->state = Conn_Connecting;
828     new->host = cl->database->host;
829     new->next = new->host->connections;
830     new->host->connections = new;
831     new->client = cl;
832     cl->connection = new;
833     new->link = link;
834
835     new->iochan = iochan_create(cs_fileno(link), handler, 0);
836     iochan_setdata(new->iochan, new);
837     new->iochan->next = channel_list;
838     channel_list = new->iochan;
839     return new;
840 }
841
842 // Close connection and set state to error
843 static void client_fatal(struct client *cl)
844 {
845     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
846     connection_destroy(cl->connection);
847     cl->state = Client_Error;
848 }
849
850 // Ensure that client has a connection associated
851 static int client_prep_connection(struct client *cl)
852 {
853     struct connection *co;
854     struct session *se = cl->session;
855     struct host *host = cl->database->host;
856
857     co = cl->connection;
858
859     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
860
861     if (!co)
862     {
863         // See if someone else has an idle connection
864         // We should look at timestamps here to select the longest-idle connection
865         for (co = host->connections; co; co = co->next)
866             if (co->state == Conn_Open && (!co->client || co->client->session != se))
867                 break;
868         if (co)
869         {
870             connection_release(co);
871             cl->connection = co;
872             co->client = cl;
873         }
874         else
875             co = connection_create(cl);
876     }
877     if (co)
878     {
879         if (co->state == Conn_Connecting)
880         {
881             cl->state = Client_Connecting;
882             iochan_setflag(co->iochan, EVENT_OUTPUT);
883         }
884         else if (co->state == Conn_Open)
885         {
886             if (cl->state == Client_Error || cl->state == Client_Disconnected)
887                 cl->state = Client_Idle;
888             iochan_setflag(co->iochan, EVENT_OUTPUT);
889         }
890         return 1;
891     }
892     else
893         return 0;
894 }
895
896 // This function will most likely vanish when a proper target profile mechanism is
897 // introduced.
898 void load_simpletargets(const char *fn)
899 {
900     FILE *f = fopen(fn, "r");
901     char line[256];
902
903     if (!f)
904     {
905         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
906         exit(1);
907     }
908
909     while (fgets(line, 255, f))
910     {
911         char *url, *db;
912         struct host *host;
913         struct database *database;
914
915         if (strncmp(line, "target ", 7))
916             continue;
917         url = line + 7;
918         url[strlen(url) - 1] = '\0';
919         yaz_log(YLOG_DEBUG, "Target: %s", url);
920         if ((db = strchr(url, '/')))
921             *(db++) = '\0';
922         else
923             db = "Default";
924
925         for (host = hosts; host; host = host->next)
926             if (!strcmp(url, host->hostport))
927                 break;
928         if (!host)
929         {
930             struct addrinfo *addrinfo, hints;
931             char *port;
932             char ipport[128];
933             unsigned char addrbuf[4];
934             int res;
935
936             host = xmalloc(sizeof(struct host));
937             host->hostport = xstrdup(url);
938             host->connections = 0;
939
940             if ((port = strchr(url, ':')))
941                 *(port++) = '\0';
942             else
943                 port = "210";
944
945             hints.ai_flags = 0;
946             hints.ai_family = PF_INET;
947             hints.ai_socktype = SOCK_STREAM;
948             hints.ai_protocol = IPPROTO_TCP;
949             hints.ai_addrlen = 0;
950             hints.ai_addr = 0;
951             hints.ai_canonname = 0;
952             hints.ai_next = 0;
953             // This is not robust code. It assumes that getaddrinfo returns AF_INET
954             // address.
955             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
956             {
957                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
958                 xfree(host->hostport);
959                 xfree(host);
960                 continue;
961             }
962             assert(addrinfo->ai_family == PF_INET);
963             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
964             sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
965                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
966             host->ipport = xstrdup(ipport);
967             freeaddrinfo(addrinfo);
968             host->next = hosts;
969             hosts = host;
970         }
971         database = xmalloc(sizeof(struct database));
972         database->host = host;
973         database->url = xmalloc(strlen(url) + strlen(db) + 2);
974         strcpy(database->url, url);
975         strcat(database->url, "/");
976         strcat(database->url, db);
977         
978         database->databases = xmalloc(2 * sizeof(char *));
979         database->databases[0] = xstrdup(db);
980         database->databases[1] = 0;
981         database->errors = 0;
982         database->qprofile = 0;
983         database->rprofile = database_retrieval_profile(database);
984         database->next = databases;
985         databases = database;
986
987     }
988     fclose(f);
989 }
990
991 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
992 {
993     switch (n->kind)
994     {
995         case CCL_RPN_AND:
996         case CCL_RPN_OR:
997         case CCL_RPN_NOT:
998         case CCL_RPN_PROX:
999             pull_terms(nmem, n->u.p[0], termlist, num);
1000             pull_terms(nmem, n->u.p[1], termlist, num);
1001             break;
1002         case CCL_RPN_TERM:
1003             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1004             break;
1005         default: // NOOP
1006             break;
1007     }
1008 }
1009
1010 // Extract terms from query into null-terminated termlist
1011 static int extract_terms(NMEM nmem, char *query, char **termlist)
1012 {
1013     int error, pos;
1014     struct ccl_rpn_node *n;
1015     int num = 0;
1016
1017     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1018     if (!n)
1019         return -1;
1020     pull_terms(nmem, n, termlist, &num);
1021     termlist[num] = 0;
1022     ccl_rpn_delete(n);
1023     return 0;
1024 }
1025
1026 static struct client *client_create(void)
1027 {
1028     struct client *r;
1029     if (client_freelist)
1030     {
1031         r = client_freelist;
1032         client_freelist = client_freelist->next;
1033     }
1034     else
1035         r = xmalloc(sizeof(struct client));
1036     r->database = 0;
1037     r->connection = 0;
1038     r->session = 0;
1039     r->hits = 0;
1040     r->records = 0;
1041     r->setno = 0;
1042     r->requestid = -1;
1043     r->diagnostic = 0;
1044     r->state = Client_Disconnected;
1045     r->next = 0;
1046     return r;
1047 }
1048
1049 void client_destroy(struct client *c)
1050 {
1051     struct session *se = c->session;
1052     if (c == se->clients)
1053         se->clients = c->next;
1054     else
1055     {
1056         struct client *cc;
1057         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1058             ;
1059         if (cc)
1060             cc->next = c->next;
1061     }
1062     if (c->connection)
1063         connection_release(c->connection);
1064     c->next = client_freelist;
1065     client_freelist = c;
1066 }
1067
1068 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1069 {
1070     s->watchlist[what].fun = fun;
1071     s->watchlist[what].data = data;
1072 }
1073
1074 void session_alert_watch(struct session *s, int what)
1075 {
1076     if (!s->watchlist[what].fun)
1077         return;
1078     (*s->watchlist[what].fun)(s->watchlist[what].data);
1079     s->watchlist[what].fun = 0;
1080     s->watchlist[what].data = 0;
1081 }
1082
1083 // This needs to be extended with selection criteria
1084 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1085 {
1086     if (!config)
1087     {
1088         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1089         exit(1);
1090     }
1091     if (!config->retrievalprofiles)
1092     {
1093         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1094     }
1095     return config->retrievalprofiles;
1096 }
1097
1098 // This should be extended with parameters to control selection criteria
1099 // Associates a set of clients with a session;
1100 int select_targets(struct session *se)
1101 {
1102     struct database *db;
1103     int c = 0;
1104
1105     while (se->clients)
1106         client_destroy(se->clients);
1107     for (db = databases; db; db = db->next)
1108     {
1109         struct client *cl = client_create();
1110         cl->database = db;
1111         cl->session = se;
1112         cl->next = se->clients;
1113         se->clients = cl;
1114         c++;
1115     }
1116     return c;
1117 }
1118
1119 int session_active_clients(struct session *s)
1120 {
1121     struct client *c;
1122     int res = 0;
1123
1124     for (c = s->clients; c; c = c->next)
1125         if (c->connection && (c->state == Client_Connecting ||
1126                     c->state == Client_Initializing ||
1127                     c->state == Client_Searching ||
1128                     c->state == Client_Presenting))
1129             res++;
1130
1131     return res;
1132 }
1133
1134 char *search(struct session *se, char *query)
1135 {
1136     int live_channels = 0;
1137     struct client *cl;
1138
1139     yaz_log(YLOG_DEBUG, "Search");
1140
1141     strcpy(se->query, query);
1142     se->requestid++;
1143     nmem_reset(se->nmem);
1144     for (cl = se->clients; cl; cl = cl->next)
1145     {
1146         cl->hits = -1;
1147         cl->records = 0;
1148         cl->diagnostic = 0;
1149
1150         if (client_prep_connection(cl))
1151             live_channels++;
1152     }
1153     if (live_channels)
1154     {
1155         char *p[512];
1156         int maxrecs = live_channels * global_parameters.toget;
1157         se->num_termlists = 0;
1158         se->reclist = reclist_create(se->nmem, maxrecs);
1159         extract_terms(se->nmem, query, p);
1160         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1161         se->total_records = se->total_hits = 0;
1162         se->expected_maxrecs = maxrecs;
1163     }
1164     else
1165         return "NOTARGETS";
1166
1167     return 0;
1168 }
1169
1170 void destroy_session(struct session *s)
1171 {
1172     yaz_log(YLOG_LOG, "Destroying session");
1173     while (s->clients)
1174         client_destroy(s->clients);
1175     nmem_destroy(s->nmem);
1176     wrbuf_free(s->wrbuf, 1);
1177 }
1178
1179 struct session *new_session() 
1180 {
1181     int i;
1182     struct session *session = xmalloc(sizeof(*session));
1183
1184     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1185     
1186     session->total_hits = 0;
1187     session->total_records = 0;
1188     session->num_termlists = 0;
1189     session->reclist = 0;
1190     session->requestid = -1;
1191     session->clients = 0;
1192     session->expected_maxrecs = 0;
1193     session->query[0] = '\0';
1194     session->nmem = nmem_create();
1195     session->wrbuf = wrbuf_alloc();
1196     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1197     {
1198         session->watchlist[i].data = 0;
1199         session->watchlist[i].fun = 0;
1200     }
1201
1202     select_targets(session);
1203
1204     return session;
1205 }
1206
1207 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1208 {
1209     static struct hitsbytarget res[1000]; // FIXME MM
1210     struct client *cl;
1211
1212     *count = 0;
1213     for (cl = se->clients; cl; cl = cl->next)
1214     {
1215         strcpy(res[*count].id, cl->database->host->hostport);
1216         res[*count].hits = cl->hits;
1217         res[*count].records = cl->records;
1218         res[*count].diagnostic = cl->diagnostic;
1219         res[*count].state = client_states[cl->state];
1220         res[*count].connected  = cl->connection ? 1 : 0;
1221         (*count)++;
1222     }
1223
1224     return res;
1225 }
1226
1227 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1228 {
1229     int i;
1230
1231     for (i = 0; i < s->num_termlists; i++)
1232         if (!strcmp(s->termlists[i].name, name))
1233             return termlist_highscore(s->termlists[i].termlist, num);
1234     return 0;
1235 }
1236
1237 #ifdef MISSING_HEADERS
1238 void report_nmem_stats(void)
1239 {
1240     size_t in_use, is_free;
1241
1242     nmem_get_memory_in_use(&in_use);
1243     nmem_get_memory_free(&is_free);
1244
1245     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1246             (long) in_use, (long) is_free);
1247 }
1248 #endif
1249
1250 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1251                      int *sumhits, NMEM nmem_show)
1252 {
1253     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1254                                        * sizeof(struct record_cluster *));
1255     int i;
1256 #if USE_TIMING    
1257     yaz_timing_t t = yaz_timing_create();
1258 #endif
1259     relevance_prepare_read(s->relevance, s->reclist);
1260
1261     *total = s->reclist->num_records;
1262     *sumhits = s->total_hits;
1263
1264     for (i = 0; i < start; i++)
1265         if (!reclist_read_record(s->reclist))
1266         {
1267             *num = 0;
1268             recs = 0;
1269             break;
1270         }
1271
1272     for (i = 0; i < *num; i++)
1273     {
1274         struct record_cluster *r = reclist_read_record(s->reclist);
1275         if (!r)
1276         {
1277             *num = i;
1278             break;
1279         }
1280         recs[i] = r;
1281     }
1282 #if USE_TIMING
1283     yaz_timing_stop(t);
1284     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1285             yaz_timing_get_real(t), yaz_timing_get_user(t),
1286             yaz_timing_get_sys(t));
1287     yaz_timing_destroy(&t);
1288 #endif
1289     return recs;
1290 }
1291
1292 void statistics(struct session *se, struct statistics *stat)
1293 {
1294     struct client *cl;
1295     int count = 0;
1296
1297     bzero(stat, sizeof(*stat));
1298     for (cl = se->clients; cl; cl = cl->next)
1299     {
1300         if (!cl->connection)
1301             stat->num_no_connection++;
1302         switch (cl->state)
1303         {
1304             case Client_Connecting: stat->num_connecting++; break;
1305             case Client_Initializing: stat->num_initializing++; break;
1306             case Client_Searching: stat->num_searching++; break;
1307             case Client_Presenting: stat->num_presenting++; break;
1308             case Client_Idle: stat->num_idle++; break;
1309             case Client_Failed: stat->num_failed++; break;
1310             case Client_Error: stat->num_error++; break;
1311             default: break;
1312         }
1313         count++;
1314     }
1315     stat->num_hits = se->total_hits;
1316     stat->num_records = se->total_records;
1317
1318     stat->num_clients = count;
1319 }
1320
1321 static CCL_bibset load_cclfile(const char *fn)
1322 {
1323     CCL_bibset res = ccl_qual_mk();
1324     if (ccl_qual_fname(res, fn) < 0)
1325     {
1326         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1327         exit(1);
1328     }
1329     return res;
1330 }
1331
1332 int main(int argc, char **argv)
1333 {
1334     int ret;
1335     char *arg;
1336     int setport = 0;
1337
1338     if (signal(SIGPIPE, SIG_IGN) < 0)
1339         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1340
1341     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1342
1343     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1344     {
1345         switch (ret) {
1346             case 'f':
1347                 if (!read_config(arg))
1348                     exit(1);
1349                 break;
1350             case 'h':
1351                 http_init(arg);
1352                 setport++;
1353                 break;
1354             case 'C':
1355                 global_parameters.ccl_filter = load_cclfile(arg);
1356                 break;
1357             case 'p':
1358                 http_set_proxyaddr(arg);
1359                 break;
1360             case 's':
1361                 load_simpletargets(arg);
1362                 break;
1363             case 'd':
1364                 global_parameters.dump_records = 1;
1365                 break;
1366             default:
1367                 fprintf(stderr, "Usage: pazpar2\n"
1368                         "    -f configfile\n"
1369                         "    -h [host:]port          (REST protocol listener)\n"
1370                         "    -C cclconfig\n"
1371                         "    -s simpletargetfile\n"
1372                         "    -p hostname[:portno]    (HTTP proxy)\n");
1373                 exit(1);
1374         }
1375     }
1376
1377     if (!config)
1378     {
1379         yaz_log(YLOG_FATAL, "Load config with -f");
1380         exit(1);
1381     }
1382     global_parameters.server = config->servers;
1383
1384     if (!setport)
1385     {
1386         fprintf(stderr, "Set command port with -h\n");
1387         exit(1);
1388     }
1389
1390     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1391     global_parameters.yaz_marc = yaz_marc_create();
1392     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1393     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1394     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1395
1396     event_loop(&channel_list);
1397
1398     return 0;
1399 }
1400
1401 /*
1402  * Local variables:
1403  * c-basic-offset: 4
1404  * indent-tabs-mode: nil
1405  * End:
1406  * vim: shiftwidth=4 tabstop=8 expandtab
1407  */