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