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