*** empty log message ***
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.39 2007-01-16 23:42:10 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                 add_facet(se, type, value);
671             xmlFree(type);
672             xmlFree(value);
673             type = value = 0;
674         }
675         else
676             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
677     }
678     if (type)
679         xmlFree(type);
680     if (value)
681         xmlFree(value);
682
683     xmlFreeDoc(xdoc);
684
685     relevance_donerecord(se->relevance, cluster);
686     se->total_records++;
687
688     return res;
689 }
690
691 static void ingest_records(struct client *cl, Z_Records *r)
692 {
693 #if USE_TIMING
694     yaz_timing_t t = yaz_timing_create();
695 #endif
696     struct record *rec;
697     struct session *s = cl->session;
698     Z_NamePlusRecordList *rlist;
699     int i;
700
701     if (r->which != Z_Records_DBOSD)
702         return;
703     rlist = r->u.databaseOrSurDiagnostics;
704     for (i = 0; i < rlist->num_records; i++)
705     {
706         Z_NamePlusRecord *npr = rlist->records[i];
707
708         cl->records++;
709         if (npr->which != Z_NamePlusRecord_databaseRecord)
710         {
711             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
712             continue;
713         }
714
715         rec = ingest_record(cl, npr->u.databaseRecord);
716         if (!rec)
717             continue;
718     }
719     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
720         session_alert_watch(s, SESSION_WATCH_RECORDS);
721
722 #if USE_TIMING
723     yaz_timing_stop(t);
724     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
725             yaz_timing_get_real(t), yaz_timing_get_user(t),
726             yaz_timing_get_sys(t));
727     yaz_timing_destroy(&t);
728 #endif
729 }
730
731 static void do_presentResponse(IOCHAN i, Z_APDU *a)
732 {
733     struct connection *co = iochan_getdata(i);
734     struct client *cl = co->client;
735     Z_PresentResponse *r = a->u.presentResponse;
736
737     if (r->records) {
738         Z_Records *recs = r->records;
739         if (recs->which == Z_Records_NSD)
740         {
741             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
742             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
743             cl->state = Client_Error;
744         }
745     }
746
747     if (!*r->presentStatus && cl->state != Client_Error)
748     {
749         yaz_log(YLOG_DEBUG, "Good Present response");
750         ingest_records(cl, r->records);
751         cl->state = Client_Idle;
752     }
753     else if (*r->presentStatus) 
754     {
755         yaz_log(YLOG_WARN, "Bad Present response");
756         cl->state = Client_Error;
757     }
758 }
759
760 static void handler(IOCHAN i, int event)
761 {
762     struct connection *co = iochan_getdata(i);
763     struct client *cl = co->client;
764     struct session *se = 0;
765
766     if (cl)
767         se = cl->session;
768     else
769     {
770         yaz_log(YLOG_WARN, "Destroying orphan connection");
771         connection_destroy(co);
772         return;
773     }
774
775     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
776     {
777         int errcode;
778         socklen_t errlen = sizeof(errcode);
779
780         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
781             &errlen) < 0 || errcode != 0)
782         {
783             client_fatal(cl);
784             return;
785         }
786         else
787         {
788             yaz_log(YLOG_DEBUG, "Connect OK");
789             co->state = Conn_Open;
790             if (cl)
791                 cl->state = Client_Connected;
792         }
793     }
794
795     else if (event & EVENT_INPUT)
796     {
797         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
798
799         if (len < 0)
800         {
801             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
802             connection_destroy(co);
803             return;
804         }
805         else if (len == 0)
806         {
807             yaz_log(YLOG_WARN, "EOF reading from Z server");
808             connection_destroy(co);
809             return;
810         }
811         else if (len > 1) // We discard input if we have no connection
812         {
813             co->state = Conn_Open;
814
815             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
816             {
817                 Z_APDU *a;
818
819                 odr_reset(global_parameters.odr_in);
820                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
821                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
822                 {
823                     client_fatal(cl);
824                     return;
825                 }
826                 switch (a->which)
827                 {
828                     case Z_APDU_initResponse:
829                         do_initResponse(i, a);
830                         break;
831                     case Z_APDU_searchResponse:
832                         do_searchResponse(i, a);
833                         break;
834                     case Z_APDU_presentResponse:
835                         do_presentResponse(i, a);
836                         break;
837                     default:
838                         yaz_log(YLOG_WARN, "Unexpected result from server");
839                         client_fatal(cl);
840                         return;
841                 }
842                 // We aren't expecting staggered output from target
843                 // if (cs_more(t->link))
844                 //    iochan_setevent(i, EVENT_INPUT);
845             }
846             else  // we throw away response and go to idle mode
847             {
848                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
849                 cl->state = Client_Idle;
850             }
851         }
852         /* if len==1 we do nothing but wait for more input */
853     }
854
855     if (cl->state == Client_Connected) {
856         send_init(i);
857     }
858
859     if (cl->state == Client_Idle)
860     {
861         if (cl->requestid != se->requestid && *se->query) {
862             send_search(i);
863         }
864         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
865             cl->records < cl->hits) {
866             send_present(i);
867         }
868     }
869 }
870
871 // Disassociate connection from client
872 static void connection_release(struct connection *co)
873 {
874     struct client *cl = co->client;
875
876     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
877     if (!cl)
878         return;
879     cl->connection = 0;
880     co->client = 0;
881 }
882
883 // Close connection and recycle structure
884 static void connection_destroy(struct connection *co)
885 {
886     struct host *h = co->host;
887     cs_close(co->link);
888     iochan_destroy(co->iochan);
889
890     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
891     if (h->connections == co)
892         h->connections = co->next;
893     else
894     {
895         struct connection *pco;
896         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
897             ;
898         if (pco)
899             pco->next = co->next;
900         else
901             abort();
902     }
903     if (co->client)
904     {
905         if (co->client->state != Client_Idle)
906             co->client->state = Client_Disconnected;
907         co->client->connection = 0;
908     }
909     co->next = connection_freelist;
910     connection_freelist = co;
911 }
912
913 // Creates a new connection for client, associated with the host of 
914 // client's database
915 static struct connection *connection_create(struct client *cl)
916 {
917     struct connection *new;
918     COMSTACK link; 
919     int res;
920     void *addr;
921
922     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
923     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
924     {
925         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
926         exit(1);
927     }
928
929     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
930     {
931         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?", 
932             cl->database->host->ipport);
933         return 0;
934     }
935
936     res = cs_connect(link, addr);
937     if (res < 0)
938     {
939         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
940         return 0;
941     }
942
943     if ((new = connection_freelist))
944         connection_freelist = new->next;
945     else
946     {
947         new = xmalloc(sizeof (struct connection));
948         new->ibuf = 0;
949         new->ibufsize = 0;
950     }
951     new->state = Conn_Connecting;
952     new->host = cl->database->host;
953     new->next = new->host->connections;
954     new->host->connections = new;
955     new->client = cl;
956     cl->connection = new;
957     new->link = link;
958
959     new->iochan = iochan_create(cs_fileno(link), handler, 0);
960     iochan_setdata(new->iochan, new);
961     new->iochan->next = channel_list;
962     channel_list = new->iochan;
963     return new;
964 }
965
966 // Close connection and set state to error
967 static void client_fatal(struct client *cl)
968 {
969     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
970     connection_destroy(cl->connection);
971     cl->state = Client_Error;
972 }
973
974 // Ensure that client has a connection associated
975 static int client_prep_connection(struct client *cl)
976 {
977     struct connection *co;
978     struct session *se = cl->session;
979     struct host *host = cl->database->host;
980
981     co = cl->connection;
982
983     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
984
985     if (!co)
986     {
987         // See if someone else has an idle connection
988         // We should look at timestamps here to select the longest-idle connection
989         for (co = host->connections; co; co = co->next)
990             if (co->state == Conn_Open && (!co->client || co->client->session != se))
991                 break;
992         if (co)
993         {
994             connection_release(co);
995             cl->connection = co;
996             co->client = cl;
997         }
998         else
999             co = connection_create(cl);
1000     }
1001     if (co)
1002     {
1003         if (co->state == Conn_Connecting)
1004         {
1005             cl->state = Client_Connecting;
1006             iochan_setflag(co->iochan, EVENT_OUTPUT);
1007         }
1008         else if (co->state == Conn_Open)
1009         {
1010             if (cl->state == Client_Error || cl->state == Client_Disconnected)
1011                 cl->state = Client_Idle;
1012             iochan_setflag(co->iochan, EVENT_OUTPUT);
1013         }
1014         return 1;
1015     }
1016     else
1017         return 0;
1018 }
1019
1020 // This function will most likely vanish when a proper target profile mechanism is
1021 // introduced.
1022 void load_simpletargets(const char *fn)
1023 {
1024     FILE *f = fopen(fn, "r");
1025     char line[256];
1026
1027     if (!f)
1028     {
1029         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1030         exit(1);
1031     }
1032
1033     while (fgets(line, 255, f))
1034     {
1035         char *url, *db;
1036         struct host *host;
1037         struct database *database;
1038
1039         if (strncmp(line, "target ", 7))
1040             continue;
1041         url = line + 7;
1042         url[strlen(url) - 1] = '\0';
1043         yaz_log(YLOG_DEBUG, "Target: %s", url);
1044         if ((db = strchr(url, '/')))
1045             *(db++) = '\0';
1046         else
1047             db = "Default";
1048
1049         for (host = hosts; host; host = host->next)
1050             if (!strcmp(url, host->hostport))
1051                 break;
1052         if (!host)
1053         {
1054             struct addrinfo *addrinfo, hints;
1055             char *port;
1056             char ipport[128];
1057             unsigned char addrbuf[4];
1058             int res;
1059
1060             host = xmalloc(sizeof(struct host));
1061             host->hostport = xstrdup(url);
1062             host->connections = 0;
1063
1064             if ((port = strchr(url, ':')))
1065                 *(port++) = '\0';
1066             else
1067                 port = "210";
1068
1069             hints.ai_flags = 0;
1070             hints.ai_family = PF_INET;
1071             hints.ai_socktype = SOCK_STREAM;
1072             hints.ai_protocol = IPPROTO_TCP;
1073             hints.ai_addrlen = 0;
1074             hints.ai_addr = 0;
1075             hints.ai_canonname = 0;
1076             hints.ai_next = 0;
1077             // This is not robust code. It assumes that getaddrinfo returns AF_INET
1078             // address.
1079             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1080             {
1081                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1082                 xfree(host->hostport);
1083                 xfree(host);
1084                 continue;
1085             }
1086             assert(addrinfo->ai_family == PF_INET);
1087             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1088             sprintf(ipport, "%u.%u.%u.%u:%s",
1089                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1090             host->ipport = xstrdup(ipport);
1091             freeaddrinfo(addrinfo);
1092             host->next = hosts;
1093             hosts = host;
1094         }
1095         database = xmalloc(sizeof(struct database));
1096         database->host = host;
1097         database->url = xmalloc(strlen(url) + strlen(db) + 2);
1098         strcpy(database->url, url);
1099         strcat(database->url, "/");
1100         strcat(database->url, db);
1101         
1102         database->databases = xmalloc(2 * sizeof(char *));
1103         database->databases[0] = xstrdup(db);
1104         database->databases[1] = 0;
1105         database->errors = 0;
1106         database->qprofile = 0;
1107         database->rprofile = database_retrieval_profile(database);
1108         database->next = databases;
1109         databases = database;
1110
1111     }
1112     fclose(f);
1113 }
1114
1115 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1116 {
1117     switch (n->kind)
1118     {
1119         case CCL_RPN_AND:
1120         case CCL_RPN_OR:
1121         case CCL_RPN_NOT:
1122         case CCL_RPN_PROX:
1123             pull_terms(nmem, n->u.p[0], termlist, num);
1124             pull_terms(nmem, n->u.p[1], termlist, num);
1125             break;
1126         case CCL_RPN_TERM:
1127             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1128             break;
1129         default: // NOOP
1130             break;
1131     }
1132 }
1133
1134 // Extract terms from query into null-terminated termlist
1135 static int extract_terms(NMEM nmem, char *query, char **termlist)
1136 {
1137     int error, pos;
1138     struct ccl_rpn_node *n;
1139     int num = 0;
1140
1141     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1142     if (!n)
1143         return -1;
1144     pull_terms(nmem, n, termlist, &num);
1145     termlist[num] = 0;
1146     ccl_rpn_delete(n);
1147     return 0;
1148 }
1149
1150 static struct client *client_create(void)
1151 {
1152     struct client *r;
1153     if (client_freelist)
1154     {
1155         r = client_freelist;
1156         client_freelist = client_freelist->next;
1157     }
1158     else
1159         r = xmalloc(sizeof(struct client));
1160     r->database = 0;
1161     r->connection = 0;
1162     r->session = 0;
1163     r->hits = 0;
1164     r->records = 0;
1165     r->setno = 0;
1166     r->requestid = -1;
1167     r->diagnostic = 0;
1168     r->state = Client_Disconnected;
1169     r->next = 0;
1170     return r;
1171 }
1172
1173 void client_destroy(struct client *c)
1174 {
1175     struct session *se = c->session;
1176     if (c == se->clients)
1177         se->clients = c->next;
1178     else
1179     {
1180         struct client *cc;
1181         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1182             ;
1183         if (cc)
1184             cc->next = c->next;
1185     }
1186     if (c->connection)
1187         connection_release(c->connection);
1188     c->next = client_freelist;
1189     client_freelist = c;
1190 }
1191
1192 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1193 {
1194     s->watchlist[what].fun = fun;
1195     s->watchlist[what].data = data;
1196 }
1197
1198 void session_alert_watch(struct session *s, int what)
1199 {
1200     if (!s->watchlist[what].fun)
1201         return;
1202     (*s->watchlist[what].fun)(s->watchlist[what].data);
1203     s->watchlist[what].fun = 0;
1204     s->watchlist[what].data = 0;
1205 }
1206
1207 // This needs to be extended with selection criteria
1208 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1209 {
1210     if (!config)
1211     {
1212         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1213         exit(1);
1214     }
1215     if (!config->retrievalprofiles)
1216     {
1217         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1218     }
1219     return config->retrievalprofiles;
1220 }
1221
1222 // This should be extended with parameters to control selection criteria
1223 // Associates a set of clients with a session;
1224 int select_targets(struct session *se)
1225 {
1226     struct database *db;
1227     int c = 0;
1228
1229     while (se->clients)
1230         client_destroy(se->clients);
1231     for (db = databases; db; db = db->next)
1232     {
1233         struct client *cl = client_create();
1234         cl->database = db;
1235         cl->session = se;
1236         cl->next = se->clients;
1237         se->clients = cl;
1238         c++;
1239     }
1240     return c;
1241 }
1242
1243 int session_active_clients(struct session *s)
1244 {
1245     struct client *c;
1246     int res = 0;
1247
1248     for (c = s->clients; c; c = c->next)
1249         if (c->connection && (c->state == Client_Connecting ||
1250                     c->state == Client_Initializing ||
1251                     c->state == Client_Searching ||
1252                     c->state == Client_Presenting))
1253             res++;
1254
1255     return res;
1256 }
1257
1258 char *search(struct session *se, char *query)
1259 {
1260     int live_channels = 0;
1261     struct client *cl;
1262
1263     yaz_log(YLOG_DEBUG, "Search");
1264
1265     strcpy(se->query, query);
1266     se->requestid++;
1267     nmem_reset(se->nmem);
1268     for (cl = se->clients; cl; cl = cl->next)
1269     {
1270         cl->hits = -1;
1271         cl->records = 0;
1272         cl->diagnostic = 0;
1273
1274         if (client_prep_connection(cl))
1275             live_channels++;
1276     }
1277     if (live_channels)
1278     {
1279         char *p[512];
1280         int maxrecs = live_channels * global_parameters.toget;
1281         se->num_termlists = 0;
1282         se->reclist = reclist_create(se->nmem, maxrecs);
1283         extract_terms(se->nmem, query, p);
1284         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1285         se->total_records = se->total_hits = se->total_merged = 0;
1286         se->expected_maxrecs = maxrecs;
1287     }
1288     else
1289         return "NOTARGETS";
1290
1291     return 0;
1292 }
1293
1294 void destroy_session(struct session *s)
1295 {
1296     yaz_log(YLOG_LOG, "Destroying session");
1297     while (s->clients)
1298         client_destroy(s->clients);
1299     nmem_destroy(s->nmem);
1300     wrbuf_free(s->wrbuf, 1);
1301 }
1302
1303 struct session *new_session() 
1304 {
1305     int i;
1306     struct session *session = xmalloc(sizeof(*session));
1307
1308     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1309     
1310     session->total_hits = 0;
1311     session->total_records = 0;
1312     session->num_termlists = 0;
1313     session->reclist = 0;
1314     session->requestid = -1;
1315     session->clients = 0;
1316     session->expected_maxrecs = 0;
1317     session->query[0] = '\0';
1318     session->nmem = nmem_create();
1319     session->wrbuf = wrbuf_alloc();
1320     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1321     {
1322         session->watchlist[i].data = 0;
1323         session->watchlist[i].fun = 0;
1324     }
1325
1326     select_targets(session);
1327
1328     return session;
1329 }
1330
1331 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1332 {
1333     static struct hitsbytarget res[1000]; // FIXME MM
1334     struct client *cl;
1335
1336     *count = 0;
1337     for (cl = se->clients; cl; cl = cl->next)
1338     {
1339         strcpy(res[*count].id, cl->database->host->hostport);
1340         res[*count].hits = cl->hits;
1341         res[*count].records = cl->records;
1342         res[*count].diagnostic = cl->diagnostic;
1343         res[*count].state = client_states[cl->state];
1344         res[*count].connected  = cl->connection ? 1 : 0;
1345         (*count)++;
1346     }
1347
1348     return res;
1349 }
1350
1351 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1352 {
1353     int i;
1354
1355     for (i = 0; i < s->num_termlists; i++)
1356         if (!strcmp(s->termlists[i].name, name))
1357             return termlist_highscore(s->termlists[i].termlist, num);
1358     return 0;
1359 }
1360
1361 #ifdef MISSING_HEADERS
1362 void report_nmem_stats(void)
1363 {
1364     size_t in_use, is_free;
1365
1366     nmem_get_memory_in_use(&in_use);
1367     nmem_get_memory_free(&is_free);
1368
1369     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1370             (long) in_use, (long) is_free);
1371 }
1372 #endif
1373
1374 struct record_cluster *show_single(struct session *s, int id)
1375 {
1376     struct record_cluster *r;
1377
1378     reclist_rewind(s->reclist);
1379     while ((r = reclist_read_record(s->reclist)))
1380         if (r->recid == id)
1381             return r;
1382     return 0;
1383 }
1384
1385 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1386         int *num, int *total, int *sumhits, NMEM nmem_show)
1387 {
1388     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1389                                        * sizeof(struct record_cluster *));
1390     struct reclist_sortparms *spp;
1391     int i;
1392 #if USE_TIMING    
1393     yaz_timing_t t = yaz_timing_create();
1394 #endif
1395
1396     for (spp = sp; spp; spp = spp->next)
1397         if (spp->type == Metadata_sortkey_relevance)
1398         {
1399             relevance_prepare_read(s->relevance, s->reclist);
1400             break;
1401         }
1402     reclist_sort(s->reclist, sp);
1403
1404     *total = s->reclist->num_records;
1405     *sumhits = s->total_hits;
1406
1407     for (i = 0; i < start; i++)
1408         if (!reclist_read_record(s->reclist))
1409         {
1410             *num = 0;
1411             recs = 0;
1412             break;
1413         }
1414
1415     for (i = 0; i < *num; i++)
1416     {
1417         struct record_cluster *r = reclist_read_record(s->reclist);
1418         if (!r)
1419         {
1420             *num = i;
1421             break;
1422         }
1423         recs[i] = r;
1424     }
1425 #if USE_TIMING
1426     yaz_timing_stop(t);
1427     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1428             yaz_timing_get_real(t), yaz_timing_get_user(t),
1429             yaz_timing_get_sys(t));
1430     yaz_timing_destroy(&t);
1431 #endif
1432     return recs;
1433 }
1434
1435 void statistics(struct session *se, struct statistics *stat)
1436 {
1437     struct client *cl;
1438     int count = 0;
1439
1440     memset(stat, 0, sizeof(*stat));
1441     for (cl = se->clients; cl; cl = cl->next)
1442     {
1443         if (!cl->connection)
1444             stat->num_no_connection++;
1445         switch (cl->state)
1446         {
1447             case Client_Connecting: stat->num_connecting++; break;
1448             case Client_Initializing: stat->num_initializing++; break;
1449             case Client_Searching: stat->num_searching++; break;
1450             case Client_Presenting: stat->num_presenting++; break;
1451             case Client_Idle: stat->num_idle++; break;
1452             case Client_Failed: stat->num_failed++; break;
1453             case Client_Error: stat->num_error++; break;
1454             default: break;
1455         }
1456         count++;
1457     }
1458     stat->num_hits = se->total_hits;
1459     stat->num_records = se->total_records;
1460
1461     stat->num_clients = count;
1462 }
1463
1464 static CCL_bibset load_cclfile(const char *fn)
1465 {
1466     CCL_bibset res = ccl_qual_mk();
1467     if (ccl_qual_fname(res, fn) < 0)
1468     {
1469         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1470         exit(1);
1471     }
1472     return res;
1473 }
1474
1475 static void start_http_listener(void)
1476 {
1477     char hp[128] = "";
1478     struct conf_server *ser = global_parameters.server;
1479
1480     if (*global_parameters.listener_override)
1481         strcpy(hp, global_parameters.listener_override);
1482     else
1483     {
1484         strcpy(hp, ser->host ? ser->host : "");
1485         if (ser->port)
1486         {
1487             if (*hp)
1488                 strcat(hp, ":");
1489             sprintf(hp + strlen(hp), "%d", ser->port);
1490         }
1491     }
1492     http_init(hp);
1493 }
1494
1495 static void start_proxy(void)
1496 {
1497     char hp[128] = "";
1498     struct conf_server *ser = global_parameters.server;
1499
1500     if (*global_parameters.proxy_override)
1501         strcpy(hp, global_parameters.proxy_override);
1502     else if (ser->proxy_host || ser->proxy_port)
1503     {
1504         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1505         if (ser->proxy_port)
1506         {
1507             if (*hp)
1508                 strcat(hp, ":");
1509             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1510         }
1511     }
1512     else
1513         return;
1514
1515     http_set_proxyaddr(hp);
1516 }
1517
1518 int main(int argc, char **argv)
1519 {
1520     int ret;
1521     char *arg;
1522
1523     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1524         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1525
1526     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1527
1528     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1529     {
1530         switch (ret) {
1531             case 'f':
1532                 if (!read_config(arg))
1533                     exit(1);
1534                 break;
1535             case 'h':
1536                 strcpy(global_parameters.listener_override, arg);
1537                 break;
1538             case 'C':
1539                 global_parameters.ccl_filter = load_cclfile(arg);
1540                 break;
1541             case 'p':
1542                 strcpy(global_parameters.proxy_override, arg);
1543                 break;
1544             case 's':
1545                 load_simpletargets(arg);
1546                 break;
1547             case 'd':
1548                 global_parameters.dump_records = 1;
1549                 break;
1550             default:
1551                 fprintf(stderr, "Usage: pazpar2\n"
1552                         "    -f configfile\n"
1553                         "    -h [host:]port          (REST protocol listener)\n"
1554                         "    -C cclconfig\n"
1555                         "    -s simpletargetfile\n"
1556                         "    -p hostname[:portno]    (HTTP proxy)\n"
1557                         "    -d                      (show internal records)\n");
1558                 exit(1);
1559         }
1560     }
1561
1562     if (!config)
1563     {
1564         yaz_log(YLOG_FATAL, "Load config with -f");
1565         exit(1);
1566     }
1567     global_parameters.server = config->servers;
1568
1569     start_http_listener();
1570     start_proxy();
1571     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1572     global_parameters.yaz_marc = yaz_marc_create();
1573     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1574     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1575     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1576
1577     event_loop(&channel_list);
1578
1579     return 0;
1580 }
1581
1582 /*
1583  * Local variables:
1584  * c-basic-offset: 4
1585  * indent-tabs-mode: nil
1586  * End:
1587  * vim: shiftwidth=4 tabstop=8 expandtab
1588  */