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