Correctly set recsyn in search
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.46 2007-01-26 19:30:51 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.searchRequest->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 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
389 {
390     struct conf_retrievalprofile *rprofile = cl->database->rprofile;
391     struct conf_retrievalmap *m;
392     xmlNode *res;
393     xmlDoc *rdoc;
394
395     // First normalize to XML
396     if (rprofile->native_syntax == Nativesyn_iso2709)
397     {
398         char *buf;
399         int len;
400         if (rec->which != Z_External_octet)
401         {
402             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
403             return 0;
404         }
405         buf = (char*) rec->u.octet_aligned->buf;
406         len = rec->u.octet_aligned->len;
407         if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
408         {
409             yaz_log(YLOG_WARN, "Failed to decode MARC");
410             return 0;
411         }
412         if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
413                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
414         {
415             yaz_log(YLOG_WARN, "Failed to encode as XML");
416             return 0;
417         }
418         rdoc = xmlNewDoc("1.0");
419         xmlDocSetRootElement(rdoc, res);
420     }
421     else
422     {
423         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
424         exit(1);
425     }
426
427     if (global_parameters.dump_records)
428     {
429         fprintf(stderr, "Input Record (normalized):\n----------------\n");
430 #if LIBXML_VERSION >= 20600
431         xmlDocFormatDump(stderr, rdoc, 1);
432 #else
433         xmlDocDump(stderr, rdoc);
434 #endif
435     }
436
437     for (m = rprofile->maplist; m; m = m->next)
438     {
439         xmlDoc *new;
440         if (m->type != Map_xslt)
441         {
442             yaz_log(YLOG_WARN, "Unknown map type");
443             return 0;
444         }
445         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
446         {
447             yaz_log(YLOG_WARN, "XSLT transformation failed");
448             return 0;
449         }
450         xmlFreeDoc(rdoc);
451         rdoc = new;
452     }
453     if (global_parameters.dump_records)
454     {
455         fprintf(stderr, "Record:\n----------------\n");
456 #if LIBXML_VERSION >= 20600
457         xmlDocFormatDump(stderr, rdoc, 1);
458 #else
459         xmlDocDump(stderr, rdoc);
460 #endif
461     }
462     return rdoc;
463 }
464
465 // Extract what appears to be years from buf, storing highest and
466 // lowest values.
467 static int extract_years(const char *buf, int *first, int *last)
468 {
469     *first = -1;
470     *last = -1;
471     while (*buf)
472     {
473         const char *e;
474         int len;
475
476         while (*buf && !isdigit(*buf))
477             buf++;
478         len = 0;
479         for (e = buf; *e && isdigit(*e); e++)
480             len++;
481         if (len == 4)
482         {
483             int value = atoi(buf);
484             if (*first < 0 || value < *first)
485                 *first = value;
486             if (*last < 0 || value > *last)
487                 *last = value;
488         }
489         buf = e;
490     }
491     return *first;
492 }
493
494 static struct record *ingest_record(struct client *cl, Z_External *rec)
495 {
496     xmlDoc *xdoc = normalize_record(cl, rec);
497     xmlNode *root, *n;
498     struct record *res;
499     struct record_cluster *cluster;
500     struct session *se = cl->session;
501     xmlChar *mergekey, *mergekey_norm;
502     xmlChar *type = 0;
503     xmlChar *value = 0;
504     struct conf_service *service = global_parameters.server->service;
505
506     if (!xdoc)
507         return 0;
508
509     root = xmlDocGetRootElement(xdoc);
510     if (!(mergekey = xmlGetProp(root, "mergekey")))
511     {
512         yaz_log(YLOG_WARN, "No mergekey found in record");
513         xmlFreeDoc(xdoc);
514         return 0;
515     }
516
517     res = nmem_malloc(se->nmem, sizeof(struct record));
518     res->next = 0;
519     res->client = cl;
520     res->metadata = nmem_malloc(se->nmem,
521             sizeof(struct record_metadata*) * service->num_metadata);
522     memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
523
524     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
525     xmlFree(mergekey);
526     normalize_mergekey(mergekey_norm, 0);
527
528     cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
529     if (global_parameters.dump_records)
530         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
531                 cl->database->url, cl->records);
532     if (!cluster)
533     {
534         /* no room for record */
535         xmlFreeDoc(xdoc);
536         return 0;
537     }
538     relevance_newrec(se->relevance, cluster);
539
540     for (n = root->children; n; n = n->next)
541     {
542         if (type)
543             xmlFree(type);
544         if (value)
545             xmlFree(value);
546         type = value = 0;
547
548         if (n->type != XML_ELEMENT_NODE)
549             continue;
550         if (!strcmp(n->name, "metadata"))
551         {
552             struct conf_metadata *md = 0;
553             struct conf_sortkey *sk = 0;
554             struct record_metadata **wheretoput, *newm;
555             int imeta;
556             int first, last;
557
558             type = xmlGetProp(n, "type");
559             value = xmlNodeListGetString(xdoc, n->children, 0);
560
561             if (!type || !value)
562                 continue;
563
564             // First, find out what field we're looking at
565             for (imeta = 0; imeta < service->num_metadata; imeta++)
566                 if (!strcmp(type, service->metadata[imeta].name))
567                 {
568                     md = &service->metadata[imeta];
569                     if (md->sortkey_offset >= 0)
570                         sk = &service->sortkeys[md->sortkey_offset];
571                     break;
572                 }
573             if (!md)
574             {
575                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
576                 continue;
577             }
578
579             // Find out where we are putting it
580             if (md->merge == Metadata_merge_no)
581                 wheretoput = &res->metadata[imeta];
582             else
583                 wheretoput = &cluster->metadata[imeta];
584             
585             // Put it there
586             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
587             newm->next = 0;
588             if (md->type == Metadata_type_generic)
589             {
590                 char *p, *pe;
591                 for (p = value; *p && isspace(*p); p++)
592                     ;
593                 for (pe = p + strlen(p) - 1;
594                         pe > p && strchr(" ,/.:([", *pe); pe--)
595                     *pe = '\0';
596                 newm->data.text = nmem_strdup(se->nmem, p);
597
598             }
599             else if (md->type == Metadata_type_year)
600             {
601                 if (extract_years(value, &first, &last) < 0)
602                     continue;
603             }
604             else
605             {
606                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
607                 continue;
608             }
609             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
610             {
611                 yaz_log(YLOG_WARN, "Only range merging supported for years");
612                 continue;
613             }
614             if (md->merge == Metadata_merge_unique)
615             {
616                 struct record_metadata *mnode;
617                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
618                     if (!strcmp(mnode->data.text, newm->data.text))
619                         break;
620                 if (!mnode)
621                 {
622                     newm->next = *wheretoput;
623                     *wheretoput = newm;
624                 }
625             }
626             else if (md->merge == Metadata_merge_longest)
627             {
628                 if (!*wheretoput ||
629                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
630                 {
631                     *wheretoput = newm;
632                     if (sk)
633                     {
634                         char *s = nmem_strdup(se->nmem, newm->data.text);
635                         if (!cluster->sortkeys[md->sortkey_offset])
636                             cluster->sortkeys[md->sortkey_offset] = 
637                                 nmem_malloc(se->nmem, sizeof(union data_types));
638                         normalize_mergekey(s,
639                                 (sk->type == Metadata_sortkey_skiparticle));
640                         cluster->sortkeys[md->sortkey_offset]->text = s;
641                     }
642                 }
643             }
644             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
645             {
646                 newm->next = *wheretoput;
647                 *wheretoput = newm;
648             }
649             else if (md->merge == Metadata_merge_range)
650             {
651                 assert(md->type == Metadata_type_year);
652                 if (!*wheretoput)
653                 {
654                     *wheretoput = newm;
655                     (*wheretoput)->data.number.min = first;
656                     (*wheretoput)->data.number.max = last;
657                     if (sk)
658                         cluster->sortkeys[md->sortkey_offset] = &newm->data;
659                 }
660                 else
661                 {
662                     if (first < (*wheretoput)->data.number.min)
663                         (*wheretoput)->data.number.min = first;
664                     if (last > (*wheretoput)->data.number.max)
665                         (*wheretoput)->data.number.max = last;
666                 }
667 #ifdef GAGA
668                 if (sk)
669                 {
670                     union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
671                     yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
672                 }
673 #endif
674             }
675             else
676                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
677
678             if (md->rank)
679                 relevance_countwords(se->relevance, cluster, value, md->rank);
680             if (md->termlist)
681             {
682                 if (md->type == Metadata_type_year)
683                 {
684                     char year[64];
685                     sprintf(year, "%d", last);
686                     add_facet(se, type, year);
687                     if (first != last)
688                     {
689                         sprintf(year, "%d", first);
690                         add_facet(se, type, year);
691                     }
692                 }
693                 else
694                     add_facet(se, type, value);
695             }
696             xmlFree(type);
697             xmlFree(value);
698             type = value = 0;
699         }
700         else
701             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
702     }
703     if (type)
704         xmlFree(type);
705     if (value)
706         xmlFree(value);
707
708     xmlFreeDoc(xdoc);
709
710     relevance_donerecord(se->relevance, cluster);
711     se->total_records++;
712
713     return res;
714 }
715
716 static void ingest_records(struct client *cl, Z_Records *r)
717 {
718 #if USE_TIMING
719     yaz_timing_t t = yaz_timing_create();
720 #endif
721     struct record *rec;
722     struct session *s = cl->session;
723     Z_NamePlusRecordList *rlist;
724     int i;
725
726     if (r->which != Z_Records_DBOSD)
727         return;
728     rlist = r->u.databaseOrSurDiagnostics;
729     for (i = 0; i < rlist->num_records; i++)
730     {
731         Z_NamePlusRecord *npr = rlist->records[i];
732
733         cl->records++;
734         if (npr->which != Z_NamePlusRecord_databaseRecord)
735         {
736             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
737             continue;
738         }
739
740         rec = ingest_record(cl, npr->u.databaseRecord);
741         if (!rec)
742             continue;
743     }
744     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
745         session_alert_watch(s, SESSION_WATCH_RECORDS);
746
747 #if USE_TIMING
748     yaz_timing_stop(t);
749     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
750             yaz_timing_get_real(t), yaz_timing_get_user(t),
751             yaz_timing_get_sys(t));
752     yaz_timing_destroy(&t);
753 #endif
754 }
755
756 static void do_presentResponse(IOCHAN i, Z_APDU *a)
757 {
758     struct connection *co = iochan_getdata(i);
759     struct client *cl = co->client;
760     Z_PresentResponse *r = a->u.presentResponse;
761
762     if (r->records) {
763         Z_Records *recs = r->records;
764         if (recs->which == Z_Records_NSD)
765         {
766             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
767             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
768             cl->state = Client_Error;
769         }
770     }
771
772     if (!*r->presentStatus && cl->state != Client_Error)
773     {
774         yaz_log(YLOG_DEBUG, "Good Present response");
775         ingest_records(cl, r->records);
776         cl->state = Client_Idle;
777     }
778     else if (*r->presentStatus) 
779     {
780         yaz_log(YLOG_WARN, "Bad Present response");
781         cl->state = Client_Error;
782     }
783 }
784
785 static void handler(IOCHAN i, int event)
786 {
787     struct connection *co = iochan_getdata(i);
788     struct client *cl = co->client;
789     struct session *se = 0;
790
791     if (cl)
792         se = cl->session;
793     else
794     {
795         yaz_log(YLOG_WARN, "Destroying orphan connection");
796         connection_destroy(co);
797         return;
798     }
799
800     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
801     {
802         int errcode;
803         socklen_t errlen = sizeof(errcode);
804
805         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
806             &errlen) < 0 || errcode != 0)
807         {
808             client_fatal(cl);
809             return;
810         }
811         else
812         {
813             yaz_log(YLOG_DEBUG, "Connect OK");
814             co->state = Conn_Open;
815             if (cl)
816                 cl->state = Client_Connected;
817         }
818     }
819
820     else if (event & EVENT_INPUT)
821     {
822         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
823
824         if (len < 0)
825         {
826             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
827             connection_destroy(co);
828             return;
829         }
830         else if (len == 0)
831         {
832             yaz_log(YLOG_WARN, "EOF reading from Z server");
833             connection_destroy(co);
834             return;
835         }
836         else if (len > 1) // We discard input if we have no connection
837         {
838             co->state = Conn_Open;
839
840             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
841             {
842                 Z_APDU *a;
843
844                 odr_reset(global_parameters.odr_in);
845                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
846                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
847                 {
848                     client_fatal(cl);
849                     return;
850                 }
851                 switch (a->which)
852                 {
853                     case Z_APDU_initResponse:
854                         do_initResponse(i, a);
855                         break;
856                     case Z_APDU_searchResponse:
857                         do_searchResponse(i, a);
858                         break;
859                     case Z_APDU_presentResponse:
860                         do_presentResponse(i, a);
861                         break;
862                     default:
863                         yaz_log(YLOG_WARN, "Unexpected result from server");
864                         client_fatal(cl);
865                         return;
866                 }
867                 // We aren't expecting staggered output from target
868                 // if (cs_more(t->link))
869                 //    iochan_setevent(i, EVENT_INPUT);
870             }
871             else  // we throw away response and go to idle mode
872             {
873                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
874                 cl->state = Client_Idle;
875             }
876         }
877         /* if len==1 we do nothing but wait for more input */
878     }
879
880     if (cl->state == Client_Connected) {
881         send_init(i);
882     }
883
884     if (cl->state == Client_Idle)
885     {
886         if (cl->requestid != se->requestid && *se->query) {
887             send_search(i);
888         }
889         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
890             cl->records < cl->hits) {
891             send_present(i);
892         }
893     }
894 }
895
896 // Disassociate connection from client
897 static void connection_release(struct connection *co)
898 {
899     struct client *cl = co->client;
900
901     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
902     if (!cl)
903         return;
904     cl->connection = 0;
905     co->client = 0;
906 }
907
908 // Close connection and recycle structure
909 static void connection_destroy(struct connection *co)
910 {
911     struct host *h = co->host;
912     cs_close(co->link);
913     iochan_destroy(co->iochan);
914
915     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
916     if (h->connections == co)
917         h->connections = co->next;
918     else
919     {
920         struct connection *pco;
921         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
922             ;
923         if (pco)
924             pco->next = co->next;
925         else
926             abort();
927     }
928     if (co->client)
929     {
930         if (co->client->state != Client_Idle)
931             co->client->state = Client_Disconnected;
932         co->client->connection = 0;
933     }
934     co->next = connection_freelist;
935     connection_freelist = co;
936 }
937
938 // Creates a new connection for client, associated with the host of 
939 // client's database
940 static struct connection *connection_create(struct client *cl)
941 {
942     struct connection *new;
943     COMSTACK link; 
944     int res;
945     void *addr;
946
947     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
948     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
949     {
950         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
951         exit(1);
952     }
953
954     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
955     {
956         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?", 
957             cl->database->host->ipport);
958         return 0;
959     }
960
961     res = cs_connect(link, addr);
962     if (res < 0)
963     {
964         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
965         return 0;
966     }
967
968     if ((new = connection_freelist))
969         connection_freelist = new->next;
970     else
971     {
972         new = xmalloc(sizeof (struct connection));
973         new->ibuf = 0;
974         new->ibufsize = 0;
975     }
976     new->state = Conn_Connecting;
977     new->host = cl->database->host;
978     new->next = new->host->connections;
979     new->host->connections = new;
980     new->client = cl;
981     cl->connection = new;
982     new->link = link;
983
984     new->iochan = iochan_create(cs_fileno(link), handler, 0);
985     iochan_setdata(new->iochan, new);
986     new->iochan->next = channel_list;
987     channel_list = new->iochan;
988     return new;
989 }
990
991 // Close connection and set state to error
992 static void client_fatal(struct client *cl)
993 {
994     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
995     connection_destroy(cl->connection);
996     cl->state = Client_Error;
997 }
998
999 // Ensure that client has a connection associated
1000 static int client_prep_connection(struct client *cl)
1001 {
1002     struct connection *co;
1003     struct session *se = cl->session;
1004     struct host *host = cl->database->host;
1005
1006     co = cl->connection;
1007
1008     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1009
1010     if (!co)
1011     {
1012         // See if someone else has an idle connection
1013         // We should look at timestamps here to select the longest-idle connection
1014         for (co = host->connections; co; co = co->next)
1015             if (co->state == Conn_Open && (!co->client || co->client->session != se))
1016                 break;
1017         if (co)
1018         {
1019             connection_release(co);
1020             cl->connection = co;
1021             co->client = cl;
1022         }
1023         else
1024             co = connection_create(cl);
1025     }
1026     if (co)
1027     {
1028         if (co->state == Conn_Connecting)
1029         {
1030             cl->state = Client_Connecting;
1031             iochan_setflag(co->iochan, EVENT_OUTPUT);
1032         }
1033         else if (co->state == Conn_Open)
1034         {
1035             if (cl->state == Client_Error || cl->state == Client_Disconnected)
1036                 cl->state = Client_Idle;
1037             iochan_setflag(co->iochan, EVENT_OUTPUT);
1038         }
1039         return 1;
1040     }
1041     else
1042         return 0;
1043 }
1044
1045 // This function will most likely vanish when a proper target profile mechanism is
1046 // introduced.
1047 void load_simpletargets(const char *fn)
1048 {
1049     FILE *f = fopen(fn, "r");
1050     char line[256];
1051
1052     if (!f)
1053     {
1054         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1055         exit(1);
1056     }
1057
1058     while (fgets(line, 255, f))
1059     {
1060         char *url, *db;
1061         char *name;
1062         struct host *host;
1063         struct database *database;
1064
1065         if (strncmp(line, "target ", 7))
1066             continue;
1067         line[strlen(line) - 1] = '\0';
1068
1069         if ((name = strchr(line, ';')))
1070             *(name++) = '\0';
1071
1072         url = line + 7;
1073         if ((db = strchr(url, '/')))
1074             *(db++) = '\0';
1075         else
1076             db = "Default";
1077
1078         yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1079         for (host = hosts; host; host = host->next)
1080             if (!strcmp(url, host->hostport))
1081                 break;
1082         if (!host)
1083         {
1084             struct addrinfo *addrinfo, hints;
1085             char *port;
1086             char ipport[128];
1087             unsigned char addrbuf[4];
1088             int res;
1089
1090             host = xmalloc(sizeof(struct host));
1091             host->hostport = xstrdup(url);
1092             host->connections = 0;
1093
1094             if ((port = strchr(url, ':')))
1095                 *(port++) = '\0';
1096             else
1097                 port = "210";
1098
1099             hints.ai_flags = 0;
1100             hints.ai_family = PF_INET;
1101             hints.ai_socktype = SOCK_STREAM;
1102             hints.ai_protocol = IPPROTO_TCP;
1103             hints.ai_addrlen = 0;
1104             hints.ai_addr = 0;
1105             hints.ai_canonname = 0;
1106             hints.ai_next = 0;
1107             // This is not robust code. It assumes that getaddrinfo returns AF_INET
1108             // address.
1109             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1110             {
1111                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1112                 xfree(host->hostport);
1113                 xfree(host);
1114                 continue;
1115             }
1116             assert(addrinfo->ai_family == PF_INET);
1117             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1118             sprintf(ipport, "%u.%u.%u.%u:%s",
1119                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1120             host->ipport = xstrdup(ipport);
1121             freeaddrinfo(addrinfo);
1122             host->next = hosts;
1123             hosts = host;
1124         }
1125         database = xmalloc(sizeof(struct database));
1126         database->host = host;
1127         database->url = xmalloc(strlen(url) + strlen(db) + 2);
1128         strcpy(database->url, url);
1129         strcat(database->url, "/");
1130         strcat(database->url, db);
1131         if (name)
1132             database->name = xstrdup(name);
1133         else
1134             database->name = 0;
1135         
1136         database->databases = xmalloc(2 * sizeof(char *));
1137         database->databases[0] = xstrdup(db);
1138         database->databases[1] = 0;
1139         database->errors = 0;
1140         database->qprofile = 0;
1141         database->rprofile = database_retrieval_profile(database);
1142         database->next = databases;
1143         databases = database;
1144
1145     }
1146     fclose(f);
1147 }
1148
1149 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1150 {
1151     switch (n->kind)
1152     {
1153         case CCL_RPN_AND:
1154         case CCL_RPN_OR:
1155         case CCL_RPN_NOT:
1156         case CCL_RPN_PROX:
1157             pull_terms(nmem, n->u.p[0], termlist, num);
1158             pull_terms(nmem, n->u.p[1], termlist, num);
1159             break;
1160         case CCL_RPN_TERM:
1161             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1162             break;
1163         default: // NOOP
1164             break;
1165     }
1166 }
1167
1168 // Extract terms from query into null-terminated termlist
1169 static int extract_terms(NMEM nmem, char *query, char **termlist)
1170 {
1171     int error, pos;
1172     struct ccl_rpn_node *n;
1173     int num = 0;
1174
1175     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1176     if (!n)
1177         return -1;
1178     pull_terms(nmem, n, termlist, &num);
1179     termlist[num] = 0;
1180     ccl_rpn_delete(n);
1181     return 0;
1182 }
1183
1184 static struct client *client_create(void)
1185 {
1186     struct client *r;
1187     if (client_freelist)
1188     {
1189         r = client_freelist;
1190         client_freelist = client_freelist->next;
1191     }
1192     else
1193         r = xmalloc(sizeof(struct client));
1194     r->database = 0;
1195     r->connection = 0;
1196     r->session = 0;
1197     r->hits = 0;
1198     r->records = 0;
1199     r->setno = 0;
1200     r->requestid = -1;
1201     r->diagnostic = 0;
1202     r->state = Client_Disconnected;
1203     r->next = 0;
1204     return r;
1205 }
1206
1207 void client_destroy(struct client *c)
1208 {
1209     struct session *se = c->session;
1210     if (c == se->clients)
1211         se->clients = c->next;
1212     else
1213     {
1214         struct client *cc;
1215         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1216             ;
1217         if (cc)
1218             cc->next = c->next;
1219     }
1220     if (c->connection)
1221         connection_release(c->connection);
1222     c->next = client_freelist;
1223     client_freelist = c;
1224 }
1225
1226 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1227 {
1228     s->watchlist[what].fun = fun;
1229     s->watchlist[what].data = data;
1230 }
1231
1232 void session_alert_watch(struct session *s, int what)
1233 {
1234     if (!s->watchlist[what].fun)
1235         return;
1236     (*s->watchlist[what].fun)(s->watchlist[what].data);
1237     s->watchlist[what].fun = 0;
1238     s->watchlist[what].data = 0;
1239 }
1240
1241 // This needs to be extended with selection criteria
1242 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1243 {
1244     if (!config)
1245     {
1246         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1247         exit(1);
1248     }
1249     if (!config->retrievalprofiles)
1250     {
1251         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1252     }
1253     return config->retrievalprofiles;
1254 }
1255
1256 // This should be extended with parameters to control selection criteria
1257 // Associates a set of clients with a session;
1258 int select_targets(struct session *se)
1259 {
1260     struct database *db;
1261     int c = 0;
1262
1263     while (se->clients)
1264         client_destroy(se->clients);
1265     for (db = databases; db; db = db->next)
1266     {
1267         struct client *cl = client_create();
1268         cl->database = db;
1269         cl->session = se;
1270         cl->next = se->clients;
1271         se->clients = cl;
1272         c++;
1273     }
1274     return c;
1275 }
1276
1277 int session_active_clients(struct session *s)
1278 {
1279     struct client *c;
1280     int res = 0;
1281
1282     for (c = s->clients; c; c = c->next)
1283         if (c->connection && (c->state == Client_Connecting ||
1284                     c->state == Client_Initializing ||
1285                     c->state == Client_Searching ||
1286                     c->state == Client_Presenting))
1287             res++;
1288
1289     return res;
1290 }
1291
1292 char *search(struct session *se, char *query)
1293 {
1294     int live_channels = 0;
1295     struct client *cl;
1296
1297     yaz_log(YLOG_DEBUG, "Search");
1298
1299     strcpy(se->query, query);
1300     se->requestid++;
1301     nmem_reset(se->nmem);
1302     for (cl = se->clients; cl; cl = cl->next)
1303     {
1304         cl->hits = -1;
1305         cl->records = 0;
1306         cl->diagnostic = 0;
1307
1308         if (client_prep_connection(cl))
1309             live_channels++;
1310     }
1311     if (live_channels)
1312     {
1313         char *p[512];
1314         int maxrecs = live_channels * global_parameters.toget;
1315         se->num_termlists = 0;
1316         se->reclist = reclist_create(se->nmem, maxrecs);
1317         extract_terms(se->nmem, query, p);
1318         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1319         se->total_records = se->total_hits = se->total_merged = 0;
1320         se->expected_maxrecs = maxrecs;
1321     }
1322     else
1323         return "NOTARGETS";
1324
1325     return 0;
1326 }
1327
1328 void destroy_session(struct session *s)
1329 {
1330     yaz_log(YLOG_LOG, "Destroying session");
1331     while (s->clients)
1332         client_destroy(s->clients);
1333     nmem_destroy(s->nmem);
1334     wrbuf_free(s->wrbuf, 1);
1335 }
1336
1337 struct session *new_session() 
1338 {
1339     int i;
1340     struct session *session = xmalloc(sizeof(*session));
1341
1342     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1343     
1344     session->total_hits = 0;
1345     session->total_records = 0;
1346     session->num_termlists = 0;
1347     session->reclist = 0;
1348     session->requestid = -1;
1349     session->clients = 0;
1350     session->expected_maxrecs = 0;
1351     session->query[0] = '\0';
1352     session->nmem = nmem_create();
1353     session->wrbuf = wrbuf_alloc();
1354     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1355     {
1356         session->watchlist[i].data = 0;
1357         session->watchlist[i].fun = 0;
1358     }
1359
1360     select_targets(session);
1361
1362     return session;
1363 }
1364
1365 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1366 {
1367     static struct hitsbytarget res[1000]; // FIXME MM
1368     struct client *cl;
1369
1370     *count = 0;
1371     for (cl = se->clients; cl; cl = cl->next)
1372     {
1373         res[*count].id = cl->database->url;
1374         res[*count].name = cl->database->name;
1375         res[*count].hits = cl->hits;
1376         res[*count].records = cl->records;
1377         res[*count].diagnostic = cl->diagnostic;
1378         res[*count].state = client_states[cl->state];
1379         res[*count].connected  = cl->connection ? 1 : 0;
1380         (*count)++;
1381     }
1382
1383     return res;
1384 }
1385
1386 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1387 {
1388     int i;
1389
1390     for (i = 0; i < s->num_termlists; i++)
1391         if (!strcmp(s->termlists[i].name, name))
1392             return termlist_highscore(s->termlists[i].termlist, num);
1393     return 0;
1394 }
1395
1396 #ifdef MISSING_HEADERS
1397 void report_nmem_stats(void)
1398 {
1399     size_t in_use, is_free;
1400
1401     nmem_get_memory_in_use(&in_use);
1402     nmem_get_memory_free(&is_free);
1403
1404     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1405             (long) in_use, (long) is_free);
1406 }
1407 #endif
1408
1409 struct record_cluster *show_single(struct session *s, int id)
1410 {
1411     struct record_cluster *r;
1412
1413     reclist_rewind(s->reclist);
1414     while ((r = reclist_read_record(s->reclist)))
1415         if (r->recid == id)
1416             return r;
1417     return 0;
1418 }
1419
1420 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1421         int *num, int *total, int *sumhits, NMEM nmem_show)
1422 {
1423     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1424                                        * sizeof(struct record_cluster *));
1425     struct reclist_sortparms *spp;
1426     int i;
1427 #if USE_TIMING    
1428     yaz_timing_t t = yaz_timing_create();
1429 #endif
1430
1431     for (spp = sp; spp; spp = spp->next)
1432         if (spp->type == Metadata_sortkey_relevance)
1433         {
1434             relevance_prepare_read(s->relevance, s->reclist);
1435             break;
1436         }
1437     reclist_sort(s->reclist, sp);
1438
1439     *total = s->reclist->num_records;
1440     *sumhits = s->total_hits;
1441
1442     for (i = 0; i < start; i++)
1443         if (!reclist_read_record(s->reclist))
1444         {
1445             *num = 0;
1446             recs = 0;
1447             break;
1448         }
1449
1450     for (i = 0; i < *num; i++)
1451     {
1452         struct record_cluster *r = reclist_read_record(s->reclist);
1453         if (!r)
1454         {
1455             *num = i;
1456             break;
1457         }
1458         recs[i] = r;
1459     }
1460 #if USE_TIMING
1461     yaz_timing_stop(t);
1462     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1463             yaz_timing_get_real(t), yaz_timing_get_user(t),
1464             yaz_timing_get_sys(t));
1465     yaz_timing_destroy(&t);
1466 #endif
1467     return recs;
1468 }
1469
1470 void statistics(struct session *se, struct statistics *stat)
1471 {
1472     struct client *cl;
1473     int count = 0;
1474
1475     memset(stat, 0, sizeof(*stat));
1476     for (cl = se->clients; cl; cl = cl->next)
1477     {
1478         if (!cl->connection)
1479             stat->num_no_connection++;
1480         switch (cl->state)
1481         {
1482             case Client_Connecting: stat->num_connecting++; break;
1483             case Client_Initializing: stat->num_initializing++; break;
1484             case Client_Searching: stat->num_searching++; break;
1485             case Client_Presenting: stat->num_presenting++; break;
1486             case Client_Idle: stat->num_idle++; break;
1487             case Client_Failed: stat->num_failed++; break;
1488             case Client_Error: stat->num_error++; break;
1489             default: break;
1490         }
1491         count++;
1492     }
1493     stat->num_hits = se->total_hits;
1494     stat->num_records = se->total_records;
1495
1496     stat->num_clients = count;
1497 }
1498
1499 static CCL_bibset load_cclfile(const char *fn)
1500 {
1501     CCL_bibset res = ccl_qual_mk();
1502     if (ccl_qual_fname(res, fn) < 0)
1503     {
1504         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1505         exit(1);
1506     }
1507     return res;
1508 }
1509
1510 static void start_http_listener(void)
1511 {
1512     char hp[128] = "";
1513     struct conf_server *ser = global_parameters.server;
1514
1515     if (*global_parameters.listener_override)
1516         strcpy(hp, global_parameters.listener_override);
1517     else
1518     {
1519         strcpy(hp, ser->host ? ser->host : "");
1520         if (ser->port)
1521         {
1522             if (*hp)
1523                 strcat(hp, ":");
1524             sprintf(hp + strlen(hp), "%d", ser->port);
1525         }
1526     }
1527     http_init(hp);
1528 }
1529
1530 static void start_proxy(void)
1531 {
1532     char hp[128] = "";
1533     struct conf_server *ser = global_parameters.server;
1534
1535     if (*global_parameters.proxy_override)
1536         strcpy(hp, global_parameters.proxy_override);
1537     else if (ser->proxy_host || ser->proxy_port)
1538     {
1539         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1540         if (ser->proxy_port)
1541         {
1542             if (*hp)
1543                 strcat(hp, ":");
1544             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1545         }
1546     }
1547     else
1548         return;
1549
1550     http_set_proxyaddr(hp);
1551 }
1552
1553 int main(int argc, char **argv)
1554 {
1555     int ret;
1556     char *arg;
1557
1558     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1559         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1560
1561     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1562
1563     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1564     {
1565         switch (ret) {
1566             case 'f':
1567                 if (!read_config(arg))
1568                     exit(1);
1569                 break;
1570             case 'h':
1571                 strcpy(global_parameters.listener_override, arg);
1572                 break;
1573             case 'C':
1574                 global_parameters.ccl_filter = load_cclfile(arg);
1575                 break;
1576             case 'p':
1577                 strcpy(global_parameters.proxy_override, arg);
1578                 break;
1579             case 's':
1580                 load_simpletargets(arg);
1581                 break;
1582             case 'd':
1583                 global_parameters.dump_records = 1;
1584                 break;
1585             default:
1586                 fprintf(stderr, "Usage: pazpar2\n"
1587                         "    -f configfile\n"
1588                         "    -h [host:]port          (REST protocol listener)\n"
1589                         "    -C cclconfig\n"
1590                         "    -s simpletargetfile\n"
1591                         "    -p hostname[:portno]    (HTTP proxy)\n"
1592                         "    -d                      (show internal records)\n");
1593                 exit(1);
1594         }
1595     }
1596
1597     if (!config)
1598     {
1599         yaz_log(YLOG_FATAL, "Load config with -f");
1600         exit(1);
1601     }
1602     global_parameters.server = config->servers;
1603
1604     start_http_listener();
1605     start_proxy();
1606     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1607     global_parameters.yaz_marc = yaz_marc_create();
1608     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1609     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1610     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1611
1612     event_loop(&channel_list);
1613
1614     return 0;
1615 }
1616
1617 /*
1618  * Local variables:
1619  * c-basic-offset: 4
1620  * indent-tabs-mode: nil
1621  * End:
1622  * vim: shiftwidth=4 tabstop=8 expandtab
1623  */