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