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