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