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