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