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