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