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