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