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