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