Z39.50 session/connect timeout in parameters
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.56 2007-07-25 11:41:32 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 /** \file logic.c
23     \brief high-level logic; mostly user sessions and settings
24 */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <assert.h>
36
37 #include <yaz/marcdisp.h>
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/proto.h>
41 #include <yaz/readconf.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/nmem.h>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #include <yaz/oid_db.h>
49 #include <yaz/snprintf.h>
50
51 #if HAVE_CONFIG_H
52 #include "cconfig.h"
53 #endif
54
55 #define USE_TIMING 0
56 #if USE_TIMING
57 #include <yaz/timing.h>
58 #endif
59
60 #include <netinet/in.h>
61
62 #include "pazpar2.h"
63 #include "eventl.h"
64 #include "http.h"
65 #include "termlists.h"
66 #include "reclists.h"
67 #include "relevance.h"
68 #include "config.h"
69 #include "database.h"
70 #include "client.h"
71 #include "settings.h"
72 #include "normalize7bit.h"
73
74 #define TERMLIST_HIGH_SCORE 25
75
76 #define MAX_CHUNK 15
77
78 // Note: Some things in this structure will eventually move to configuration
79 struct parameters global_parameters = 
80 {
81     "",
82     "",
83     "", 
84     0,
85     0, /* dump_records */
86     0, /* debug_mode */
87     30,
88     "81",
89     "Index Data PazPar2",
90     VERSION,
91     600, // 10 minutes
92     60,
93     100,
94     MAX_CHUNK,
95     0,
96     0,
97     180,
98     30
99 };
100
101 // Recursively traverse query structure to extract terms.
102 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
103 {
104     char **words;
105     int numwords;
106     int i;
107
108     switch (n->kind)
109     {
110         case CCL_RPN_AND:
111         case CCL_RPN_OR:
112         case CCL_RPN_NOT:
113         case CCL_RPN_PROX:
114             pull_terms(nmem, n->u.p[0], termlist, num);
115             pull_terms(nmem, n->u.p[1], termlist, num);
116             break;
117         case CCL_RPN_TERM:
118             nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
119             for (i = 0; i < numwords; i++)
120                 termlist[(*num)++] = words[i];
121             break;
122         default: // NOOP
123             break;
124     }
125 }
126
127
128
129 static void add_facet(struct session *s, const char *type, const char *value)
130 {
131     int i;
132
133     if (!*value)
134         return;
135     for (i = 0; i < s->num_termlists; i++)
136         if (!strcmp(s->termlists[i].name, type))
137             break;
138     if (i == s->num_termlists)
139     {
140         if (i == SESSION_MAX_TERMLISTS)
141         {
142             yaz_log(YLOG_FATAL, "Too many termlists");
143             return;
144         }
145
146         s->termlists[i].name = nmem_strdup(s->nmem, type);
147         s->termlists[i].termlist 
148             = termlist_create(s->nmem, s->expected_maxrecs,
149                               TERMLIST_HIGH_SCORE);
150         s->num_termlists = i + 1;
151     }
152     termlist_insert(s->termlists[i].termlist, value);
153 }
154
155 xmlDoc *record_to_xml(struct session_database *sdb, Z_External *rec)
156 {
157     struct database *db = sdb->database;
158     xmlDoc *rdoc = 0;
159     const Odr_oid *oid = rec->direct_reference;
160
161     /* convert response record to XML somehow */
162     if (rec->which == Z_External_octet && oid
163         && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
164     {
165         /* xml already */
166         rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
167                               rec->u.octet_aligned->len);
168         if (!rdoc)
169         {
170             yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
171                     db->url);
172             return 0;
173         }
174     }
175     else if (rec->which == Z_External_OPAC)
176     {
177         if (!sdb->yaz_marc)
178         {
179             yaz_log(YLOG_WARN, "MARC decoding not configured");
180             return 0;
181         }
182         else
183         {
184             /* OPAC gets converted to XML too */
185             WRBUF wrbuf_opac = wrbuf_alloc();
186             /* MARCXML inside the OPAC XML. Charset is in effect because we
187                use the yaz_marc handle */
188             yaz_marc_xml(sdb->yaz_marc, YAZ_MARC_MARCXML);
189             yaz_opac_decode_wrbuf(sdb->yaz_marc, rec->u.opac, wrbuf_opac);
190             
191             rdoc = xmlParseMemory((char*) wrbuf_buf(wrbuf_opac),
192                                   wrbuf_len(wrbuf_opac));
193             if (!rdoc)
194                 yaz_log(YLOG_WARN, "Unable to parse OPAC XML");
195             wrbuf_destroy(wrbuf_opac);
196         }
197     }
198     else if (oid && yaz_oid_is_iso2709(oid))
199     {
200         /* ISO2709 gets converted to MARCXML */
201         if (!sdb->yaz_marc)
202         {
203             yaz_log(YLOG_WARN, "MARC decoding not configured");
204             return 0;
205         }
206         else
207         {
208             xmlNode *res;
209             char *buf;
210             int len;
211             
212             if (rec->which != Z_External_octet)
213             {
214                 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
215                         db->url);
216                 return 0;
217             }
218             buf = (char*) rec->u.octet_aligned->buf;
219             len = rec->u.octet_aligned->len;
220             if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
221             {
222                 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
223                 return 0;
224             }
225             
226             yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
227             if (yaz_marc_write_xml(sdb->yaz_marc, &res,
228                                    "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
229             {
230                 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
231                         db->url);
232                 return 0;
233             }
234             rdoc = xmlNewDoc((xmlChar *) "1.0");
235             xmlDocSetRootElement(rdoc, res);
236         }
237     }
238     else
239     {
240         char oid_name_buf[OID_STR_MAX];
241         const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
242         yaz_log(YLOG_FATAL, 
243                 "Unable to handle record of type %s from %s", 
244                 oid_name, db->url);
245         return 0;
246     }
247     
248     if (global_parameters.dump_records)
249     {
250         FILE *lf = yaz_log_file();
251         if (lf)
252         {
253             yaz_log(YLOG_LOG, "Un-normalized record from %s", db->url);
254 #if LIBXML_VERSION >= 20600
255             xmlDocFormatDump(lf, rdoc, 1);
256 #else
257             xmlDocDump(lf, rdoc);
258 #endif
259             fprintf(lf, "\n");
260         }
261     }
262     return rdoc;
263 }
264
265 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
266 {
267     struct database_retrievalmap *m;
268     xmlDoc *rdoc = record_to_xml(sdb, rec);
269     if (rdoc)
270     {
271         for (m = sdb->map; m; m = m->next){
272             xmlDoc *new = 0;
273             
274             {
275                 xmlNodePtr root = 0;
276                 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
277                 root= xmlDocGetRootElement(new);
278                 if (!new || !root || !(root->children))
279                 {
280                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
281                             sdb->database->url);
282                     xmlFreeDoc(new);
283                     xmlFreeDoc(rdoc);
284                     return 0;
285                 }
286             }
287             
288             xmlFreeDoc(rdoc);
289             rdoc = new;
290         }
291         if (global_parameters.dump_records)
292         {
293             FILE *lf = yaz_log_file();
294             
295             if (lf)
296             {
297                 yaz_log(YLOG_LOG, "Normalized record from %s", 
298                         sdb->database->url);
299 #if LIBXML_VERSION >= 20600
300                 xmlDocFormatDump(lf, rdoc, 1);
301 #else
302                 xmlDocDump(lf, rdoc);
303 #endif
304                 fprintf(lf, "\n");
305             }
306         }
307     }
308     return rdoc;
309 }
310
311 // Retrieve first defined value for 'name' for given database.
312 // Will be extended to take into account user associated with session
313 char *session_setting_oneval(struct session_database *db, int offset)
314 {
315     if (!db->settings[offset])
316         return "";
317     return db->settings[offset]->value;
318 }
319
320
321
322 // Initialize YAZ Map structures for MARC-based targets
323 static int prepare_yazmarc(struct session_database *sdb)
324 {
325     char *s;
326
327     if (!sdb->settings)
328     {
329         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
330         return -1;
331     }
332     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
333         && !strncmp(s, "iso2709", 7))
334     {
335         char *encoding = "marc-8s", *e;
336         yaz_iconv_t cm;
337
338         // See if a native encoding is specified
339         if ((e = strchr(s, ';')))
340             encoding = e + 1;
341
342         sdb->yaz_marc = yaz_marc_create();
343         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
344         
345         cm = yaz_iconv_open("utf-8", encoding);
346         if (!cm)
347         {
348             yaz_log(YLOG_FATAL, 
349                     "Unable to map from %s to UTF-8 for target %s", 
350                     encoding, sdb->database->url);
351             return -1;
352         }
353         yaz_marc_iconv(sdb->yaz_marc, cm);
354     }
355     return 0;
356 }
357
358 // Prepare XSLT stylesheets for record normalization
359 // Structures are allocated on the session_wide nmem to avoid having
360 // to recompute this for every search. This would lead
361 // to leaking if a single session was to repeatedly change the PZ_XSLT
362 // setting. However, this is not a realistic use scenario.
363 static int prepare_map(struct session *se, struct session_database *sdb)
364 {
365    char *s;
366
367     if (!sdb->settings)
368     {
369         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
370         return -1;
371     }
372     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
373     {
374         char **stylesheets;
375         struct database_retrievalmap **m = &sdb->map;
376         int num, i;
377         char auto_stylesheet[256];
378
379         if (!strcmp(s, "auto"))
380         {
381             char *request_syntax = session_setting_oneval(sdb,
382                                                           PZ_REQUESTSYNTAX);
383             if (request_syntax)
384             {
385                 char *cp;
386                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
387                              "%s.xsl", request_syntax);
388                 for (cp = auto_stylesheet; *cp; cp++)
389                 {
390                     /* deliberately only consider ASCII */
391                     if (*cp > 32 && *cp < 127)
392                         *cp = tolower(*cp);
393                 }
394                 s = auto_stylesheet;
395             }
396             else
397             {
398                 yaz_log(YLOG_WARN, "No pz:requestsyntax for auto stylesheet");
399             }
400         }
401         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
402         for (i = 0; i < num; i++)
403         {
404             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
405             (*m)->next = 0;
406             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
407             {
408                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
409                         stylesheets[i]);
410                 return -1;
411             }
412             m = &(*m)->next;
413         }
414     }
415     if (!sdb->map)
416         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
417                 sdb->database->url);
418     return 0;
419 }
420
421 // This analyzes settings and recomputes any supporting data structures
422 // if necessary.
423 static int prepare_session_database(struct session *se, 
424                                     struct session_database *sdb)
425 {
426     if (!sdb->settings)
427     {
428         yaz_log(YLOG_WARN, 
429                 "No settings associated with %s", sdb->database->url);
430         return -1;
431     }
432     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
433     {
434         if (prepare_yazmarc(sdb) < 0)
435             return -1;
436     }
437     if (sdb->settings[PZ_XSLT] && !sdb->map)
438     {
439         if (prepare_map(se, sdb) < 0)
440             return -1;
441     }
442     return 0;
443 }
444
445 // called if watch should be removed because http_channel is to be destroyed
446 static void session_watch_cancel(void *data, struct http_channel *c)
447 {
448     struct session_watchentry *ent = data;
449
450     ent->fun = 0;
451     ent->data = 0;
452     ent->obs = 0;
453 }
454
455 // set watch. Returns 0=OK, -1 if watch is already set
456 int session_set_watch(struct session *s, int what, 
457                       session_watchfun fun, void *data,
458                       struct http_channel *chan)
459 {
460     if (s->watchlist[what].fun)
461         return -1;
462     s->watchlist[what].fun = fun;
463     s->watchlist[what].data = data;
464     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
465                                                session_watch_cancel);
466     return 0;
467 }
468
469 void session_alert_watch(struct session *s, int what)
470 {
471     if (!s->watchlist[what].fun)
472         return;
473     http_remove_observer(s->watchlist[what].obs);
474     (*s->watchlist[what].fun)(s->watchlist[what].data);
475     s->watchlist[what].fun = 0;
476     s->watchlist[what].data = 0;
477     s->watchlist[what].obs = 0;
478 }
479
480 //callback for grep_databases
481 static void select_targets_callback(void *context, struct session_database *db)
482 {
483     struct session *se = (struct session*) context;
484     struct client *cl = client_create();
485     client_set_database(cl, db);
486     client_set_session(cl, se);
487 }
488
489 // Associates a set of clients with a session;
490 // Note: Session-databases represent databases with per-session 
491 // setting overrides
492 int select_targets(struct session *se, struct database_criterion *crit)
493 {
494     while (se->clients)
495         client_destroy(se->clients);
496
497     return session_grep_databases(se, crit, select_targets_callback);
498 }
499
500 int session_active_clients(struct session *s)
501 {
502     struct client *c;
503     int res = 0;
504
505     for (c = s->clients; c; c = client_next_in_session(c))
506         if (client_is_active(c))
507             res++;
508
509     return res;
510 }
511
512 // parses crit1=val1,crit2=val2|val3,...
513 static struct database_criterion *parse_filter(NMEM m, const char *buf)
514 {
515     struct database_criterion *res = 0;
516     char **values;
517     int num;
518     int i;
519
520     if (!buf || !*buf)
521         return 0;
522     nmem_strsplit(m, ",", buf,  &values, &num);
523     for (i = 0; i < num; i++)
524     {
525         char **subvalues;
526         int subnum;
527         int subi;
528         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
529         char *eq = strchr(values[i], '=');
530         if (!eq)
531         {
532             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
533             return 0;
534         }
535         *(eq++) = '\0';
536         new->name = values[i];
537         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
538         new->values = 0;
539         for (subi = 0; subi < subnum; subi++)
540         {
541             struct database_criterion_value *newv
542                 = nmem_malloc(m, sizeof(*newv));
543             newv->value = subvalues[subi];
544             newv->next = new->values;
545             new->values = newv;
546         }
547         new->next = res;
548         res = new;
549     }
550     return res;
551 }
552
553 enum pazpar2_error_code search(struct session *se,
554                                char *query, char *filter,
555                                const char **addinfo)
556 {
557     int live_channels = 0;
558     int no_working = 0;
559     int no_failed = 0;
560     struct client *cl;
561     struct database_criterion *criteria;
562
563     yaz_log(YLOG_DEBUG, "Search");
564
565     *addinfo = 0;
566     nmem_reset(se->nmem);
567     criteria = parse_filter(se->nmem, filter);
568     se->requestid++;
569     live_channels = select_targets(se, criteria);
570     if (live_channels)
571     {
572         int maxrecs = live_channels * global_parameters.toget;
573         se->num_termlists = 0;
574         se->reclist = reclist_create(se->nmem, maxrecs);
575         // This will be initialized in send_search()
576         se->total_records = se->total_hits = se->total_merged = 0;
577         se->expected_maxrecs = maxrecs;
578     }
579     else
580         return PAZPAR2_NO_TARGETS;
581
582     se->relevance = 0;
583
584     for (cl = se->clients; cl; cl = client_next_in_session(cl))
585     {
586         if (prepare_session_database(se, client_get_database(cl)) < 0)
587         {
588             *addinfo = client_get_database(cl)->database->url;
589             return PAZPAR2_CONFIG_TARGET;
590         }
591         // Parse query for target
592         if (client_parse_query(cl, query) < 0)
593             no_failed++;
594         else
595         {
596             no_working++;
597             client_prep_connection(cl);
598         }
599     }
600
601     // If no queries could be mapped, we signal an error
602     if (no_working == 0)
603     {
604         *addinfo = "query";
605         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
606     }
607     return PAZPAR2_NO_ERROR;
608 }
609
610 // Creates a new session_database object for a database
611 static void session_init_databases_fun(void *context, struct database *db)
612 {
613     struct session *se = (struct session *) context;
614     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
615     int num = settings_num();
616     int i;
617
618     new->database = db;
619     new->yaz_marc = 0;
620     
621 #ifdef HAVE_ICU
622     if (global_parameters.server && global_parameters.server->icu_chn)
623         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
624     else
625         new->pct = pp2_charset_create(0);
626 #else // HAVE_ICU
627     new->pct = pp2_charset_create(0);
628 #endif // HAVE_ICU
629
630     new->map = 0;
631     new->settings 
632         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
633     memset(new->settings, 0, sizeof(struct settings*) * num);
634
635     if (db->settings)
636     {
637         for (i = 0; i < num; i++)
638             new->settings[i] = db->settings[i];
639     }
640     new->next = se->databases;
641     se->databases = new;
642 }
643
644 // Doesn't free memory associated with sdb -- nmem takes care of that
645 static void session_database_destroy(struct session_database *sdb)
646 {
647     struct database_retrievalmap *m;
648
649     for (m = sdb->map; m; m = m->next)
650         xsltFreeStylesheet(m->stylesheet);
651     if (sdb->yaz_marc)
652         yaz_marc_destroy(sdb->yaz_marc);
653     if (sdb->pct)
654         pp2_charset_destroy(sdb->pct);
655 }
656
657 // Initialize session_database list -- this represents this session's view
658 // of the database list -- subject to modification by the settings ws command
659 void session_init_databases(struct session *se)
660 {
661     se->databases = 0;
662     predef_grep_databases(se, 0, session_init_databases_fun);
663 }
664
665 // Probably session_init_databases_fun should be refactored instead of
666 // called here.
667 static struct session_database *load_session_database(struct session *se, 
668                                                       char *id)
669 {
670     struct database *db = find_database(id, 0);
671
672     session_init_databases_fun((void*) se, db);
673     // New sdb is head of se->databases list
674     return se->databases;
675 }
676
677 // Find an existing session database. If not found, load it
678 static struct session_database *find_session_database(struct session *se, 
679                                                       char *id)
680 {
681     struct session_database *sdb;
682
683     for (sdb = se->databases; sdb; sdb = sdb->next)
684         if (!strcmp(sdb->database->url, id))
685             return sdb;
686     return load_session_database(se, id);
687 }
688
689 // Apply a session override to a database
690 void session_apply_setting(struct session *se, char *dbname, char *setting,
691                            char *value)
692 {
693     struct session_database *sdb = find_session_database(se, dbname);
694     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
695     int offset = settings_offset_cprefix(setting);
696
697     if (offset < 0)
698     {
699         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
700         return;
701     }
702     // Jakub: This breaks the filter setting.
703     /*if (offset == PZ_ID)
704     {
705         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
706         return;
707     }*/
708     new->precedence = 0;
709     new->target = dbname;
710     new->name = setting;
711     new->value = value;
712     new->next = sdb->settings[offset];
713     sdb->settings[offset] = new;
714
715     // Force later recompute of settings-driven data structures
716     // (happens when a search starts and client connections are prepared)
717     switch (offset)
718     {
719         case PZ_NATIVESYNTAX:
720             if (sdb->yaz_marc)
721             {
722                 yaz_marc_destroy(sdb->yaz_marc);
723                 sdb->yaz_marc = 0;
724             }
725             break;
726         case PZ_XSLT:
727             if (sdb->map)
728             {
729                 struct database_retrievalmap *m;
730                 // We don't worry about the map structure -- it's in nmem
731                 for (m = sdb->map; m; m = m->next)
732                     xsltFreeStylesheet(m->stylesheet);
733                 sdb->map = 0;
734             }
735             break;
736     }
737 }
738
739 void destroy_session(struct session *s)
740 {
741     struct session_database *sdb;
742
743     while (s->clients)
744         client_destroy(s->clients);
745     for (sdb = s->databases; sdb; sdb = sdb->next)
746         session_database_destroy(sdb);
747     nmem_destroy(s->nmem);
748     wrbuf_destroy(s->wrbuf);
749 }
750
751 struct session *new_session(NMEM nmem) 
752 {
753     int i;
754     struct session *session = nmem_malloc(nmem, sizeof(*session));
755
756     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
757     
758     session->relevance = 0;
759     session->total_hits = 0;
760     session->total_records = 0;
761     session->num_termlists = 0;
762     session->reclist = 0;
763     session->requestid = -1;
764     session->clients = 0;
765     session->expected_maxrecs = 0;
766     session->session_nmem = nmem;
767     session->nmem = nmem_create();
768     session->wrbuf = wrbuf_alloc();
769     session->databases = 0;
770     for (i = 0; i <= SESSION_WATCH_MAX; i++)
771     {
772         session->watchlist[i].data = 0;
773         session->watchlist[i].fun = 0;
774     }
775
776     return session;
777 }
778
779 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
780 {
781     static struct hitsbytarget res[1000]; // FIXME MM
782     struct client *cl;
783
784     *count = 0;
785     for (cl = se->clients; cl; cl = client_next_in_session(cl))
786     {
787         char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
788
789         res[*count].id = client_get_database(cl)->database->url;
790         res[*count].name = *name ? name : "Unknown";
791         res[*count].hits = client_get_hits(cl);
792         res[*count].records = client_get_num_records(cl);
793         res[*count].diagnostic = client_get_diagnostic(cl);
794         res[*count].state = client_get_state_str(cl);
795         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
796         (*count)++;
797     }
798
799     return res;
800 }
801
802 struct termlist_score **termlist(struct session *s, const char *name, int *num)
803 {
804     int i;
805
806     for (i = 0; i < s->num_termlists; i++)
807         if (!strcmp((const char *) s->termlists[i].name, name))
808             return termlist_highscore(s->termlists[i].termlist, num);
809     return 0;
810 }
811
812 #ifdef MISSING_HEADERS
813 void report_nmem_stats(void)
814 {
815     size_t in_use, is_free;
816
817     nmem_get_memory_in_use(&in_use);
818     nmem_get_memory_free(&is_free);
819
820     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
821             (long) in_use, (long) is_free);
822 }
823 #endif
824
825 struct record_cluster *show_single(struct session *s, const char *id)
826 {
827     struct record_cluster *r;
828
829     reclist_rewind(s->reclist);
830     while ((r = reclist_read_record(s->reclist)))
831         if (!strcmp(r->recid, id))
832             return r;
833     return 0;
834 }
835
836 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
837                              int start, int *num, int *total, int *sumhits, 
838                              NMEM nmem_show)
839 {
840     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
841                                        * sizeof(struct record_cluster *));
842     struct reclist_sortparms *spp;
843     int i;
844 #if USE_TIMING    
845     yaz_timing_t t = yaz_timing_create();
846 #endif
847
848     if (!s->relevance)
849     {
850         *num = 0;
851         *total = 0;
852         *sumhits = 0;
853         recs = 0;
854     }
855     else
856     {
857         for (spp = sp; spp; spp = spp->next)
858             if (spp->type == Metadata_sortkey_relevance)
859             {
860                 relevance_prepare_read(s->relevance, s->reclist);
861                 break;
862             }
863         reclist_sort(s->reclist, sp);
864         
865         *total = s->reclist->num_records;
866         *sumhits = s->total_hits;
867         
868         for (i = 0; i < start; i++)
869             if (!reclist_read_record(s->reclist))
870             {
871                 *num = 0;
872                 recs = 0;
873                 break;
874             }
875         
876         for (i = 0; i < *num; i++)
877         {
878             struct record_cluster *r = reclist_read_record(s->reclist);
879             if (!r)
880             {
881                 *num = i;
882                 break;
883             }
884             recs[i] = r;
885         }
886     }
887 #if USE_TIMING
888     yaz_timing_stop(t);
889     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
890             yaz_timing_get_real(t), yaz_timing_get_user(t),
891             yaz_timing_get_sys(t));
892     yaz_timing_destroy(&t);
893 #endif
894     return recs;
895 }
896
897 void statistics(struct session *se, struct statistics *stat)
898 {
899     struct client *cl;
900     int count = 0;
901
902     memset(stat, 0, sizeof(*stat));
903     for (cl = se->clients; cl; cl = client_next_in_session(cl))
904     {
905         if (!client_get_connection(cl))
906             stat->num_no_connection++;
907         switch (client_get_state(cl))
908         {
909             case Client_Connecting: stat->num_connecting++; break;
910             case Client_Initializing: stat->num_initializing++; break;
911             case Client_Searching: stat->num_searching++; break;
912             case Client_Presenting: stat->num_presenting++; break;
913             case Client_Idle: stat->num_idle++; break;
914             case Client_Failed: stat->num_failed++; break;
915             case Client_Error: stat->num_error++; break;
916             default: break;
917         }
918         count++;
919     }
920     stat->num_hits = se->total_hits;
921     stat->num_records = se->total_records;
922
923     stat->num_clients = count;
924 }
925
926 void start_http_listener(void)
927 {
928     char hp[128] = "";
929     struct conf_server *ser = global_parameters.server;
930
931     if (*global_parameters.listener_override)
932         strcpy(hp, global_parameters.listener_override);
933     else
934     {
935         strcpy(hp, ser->host ? ser->host : "");
936         if (ser->port)
937         {
938             if (*hp)
939                 strcat(hp, ":");
940             sprintf(hp + strlen(hp), "%d", ser->port);
941         }
942     }
943     http_init(hp);
944 }
945
946 void start_proxy(void)
947 {
948     char hp[128] = "";
949     struct conf_server *ser = global_parameters.server;
950
951     if (*global_parameters.proxy_override)
952         strcpy(hp, global_parameters.proxy_override);
953     else if (ser->proxy_host || ser->proxy_port)
954     {
955         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
956         if (ser->proxy_port)
957         {
958             if (*hp)
959                 strcat(hp, ":");
960             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
961         }
962     }
963     else
964         return;
965
966     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
967 }
968
969
970 // Master list of connections we're handling events to
971 static IOCHAN channel_list = 0; 
972 void pazpar2_add_channel(IOCHAN chan)
973 {
974     chan->next = channel_list;
975     channel_list = chan;
976 }
977
978 void pazpar2_event_loop()
979 {
980     event_loop(&channel_list);
981 }
982
983 static struct record_metadata *record_metadata_init(
984     NMEM nmem, char *value, enum conf_metadata_type type)
985 {
986     struct record_metadata *rec_md = record_metadata_create(nmem);
987     if (type == Metadata_type_generic)
988     {
989         char * p = value;
990         p = normalize7bit_generic(p, " ,/.:([");
991         
992         rec_md->data.text = nmem_strdup(nmem, p);
993     }
994     else if (type == Metadata_type_year)
995     {
996         int first, last;
997         if (extract7bit_years((char *) value, &first, &last) < 0)
998             return 0;
999         rec_md->data.number.min = first;
1000         rec_md->data.number.max = last;
1001     }
1002     else
1003         return 0;
1004     return rec_md;
1005 }
1006
1007 struct record *ingest_record(struct client *cl, Z_External *rec,
1008                              int record_no)
1009 {
1010     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
1011     xmlNode *root, *n;
1012     struct record *record;
1013     struct record_cluster *cluster;
1014     struct session *se = client_get_session(cl);
1015     xmlChar *mergekey, *mergekey_norm;
1016     xmlChar *type = 0;
1017     xmlChar *value = 0;
1018     struct conf_service *service = global_parameters.server->service;
1019
1020     if (!xdoc)
1021         return 0;
1022
1023     root = xmlDocGetRootElement(xdoc);
1024     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
1025     {
1026         yaz_log(YLOG_WARN, "No mergekey found in record");
1027         xmlFreeDoc(xdoc);
1028         return 0;
1029     }
1030
1031     record = record_create(se->nmem, 
1032                            service->num_metadata, service->num_sortkeys, cl,
1033                            record_no);
1034
1035     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
1036     xmlFree(mergekey);
1037     normalize7bit_mergekey((char *) mergekey_norm, 0);
1038
1039     cluster = reclist_insert(se->reclist, 
1040                              global_parameters.server->service, 
1041                              record, (char *) mergekey_norm, 
1042                              &se->total_merged);
1043     if (global_parameters.dump_records)
1044         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1045                 client_get_database(cl)->database->url, record_no);
1046     if (!cluster)
1047     {
1048         /* no room for record */
1049         xmlFreeDoc(xdoc);
1050         return 0;
1051     }
1052     relevance_newrec(se->relevance, cluster);
1053
1054
1055     // now parsing XML record and adding data to cluster or record metadata
1056     for (n = root->children; n; n = n->next)
1057     {
1058         if (type)
1059             xmlFree(type);
1060         if (value)
1061             xmlFree(value);
1062         type = value = 0;
1063
1064         if (n->type != XML_ELEMENT_NODE)
1065             continue;
1066         if (!strcmp((const char *) n->name, "metadata"))
1067         {
1068             struct conf_metadata *ser_md = 0;
1069             struct conf_sortkey *ser_sk = 0;
1070             struct record_metadata **wheretoput = 0;
1071             struct record_metadata *rec_md = 0;
1072             int md_field_id = -1;
1073             int sk_field_id = -1;
1074
1075             type = xmlGetProp(n, (xmlChar *) "type");
1076             value = xmlNodeListGetString(xdoc, n->children, 1);
1077
1078             if (!type || !value)
1079                 continue;
1080
1081             md_field_id 
1082                 = conf_service_metadata_field_id(service, (const char *) type);
1083             if (md_field_id < 0)
1084             {
1085                 yaz_log(YLOG_WARN, 
1086                         "Ignoring unknown metadata element: %s", type);
1087                 continue;
1088             }
1089
1090             ser_md = &service->metadata[md_field_id];
1091
1092             if (ser_md->sortkey_offset >= 0){
1093                 sk_field_id = ser_md->sortkey_offset;
1094                 ser_sk = &service->sortkeys[sk_field_id];
1095             }
1096
1097             // non-merged metadata
1098             rec_md = record_metadata_init(se->nmem, (char *) value,
1099                                           ser_md->type);
1100             if (!rec_md)
1101             {
1102                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1103                         value, type);
1104                 continue;
1105             }
1106             rec_md->next = record->metadata[md_field_id];
1107             record->metadata[md_field_id] = rec_md;
1108
1109             // merged metadata
1110             rec_md = record_metadata_init(se->nmem, (char *) value,
1111                                           ser_md->type);
1112             wheretoput = &cluster->metadata[md_field_id];
1113
1114             // and polulate with data:
1115             // assign cluster or record based on merge action
1116             if (ser_md->merge == Metadata_merge_unique)
1117             {
1118                 struct record_metadata *mnode;
1119                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1120                     if (!strcmp((const char *) mnode->data.text, 
1121                                 rec_md->data.text))
1122                         break;
1123                 if (!mnode)
1124                 {
1125                     rec_md->next = *wheretoput;
1126                     *wheretoput = rec_md;
1127                 }
1128             }
1129             else if (ser_md->merge == Metadata_merge_longest)
1130             {
1131                 if (!*wheretoput 
1132                     || strlen(rec_md->data.text) 
1133                        > strlen((*wheretoput)->data.text))
1134                 {
1135                     *wheretoput = rec_md;
1136                     if (ser_sk)
1137                     {
1138                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1139                         if (!cluster->sortkeys[sk_field_id])
1140                             cluster->sortkeys[sk_field_id] = 
1141                                 nmem_malloc(se->nmem, 
1142                                             sizeof(union data_types));
1143                         normalize7bit_mergekey(s,
1144                              (ser_sk->type == Metadata_sortkey_skiparticle));
1145                         cluster->sortkeys[sk_field_id]->text = s;
1146                     }
1147                 }
1148             }
1149             else if (ser_md->merge == Metadata_merge_all)
1150             {
1151                 rec_md->next = *wheretoput;
1152                 *wheretoput = rec_md;
1153             }
1154             else if (ser_md->merge == Metadata_merge_range)
1155             {
1156                 if (!*wheretoput)
1157                 {
1158                     *wheretoput = rec_md;
1159                     if (ser_sk)
1160                         cluster->sortkeys[sk_field_id] 
1161                             = &rec_md->data;
1162                 }
1163                 else
1164                 {
1165                     int this_min = rec_md->data.number.min;
1166                     int this_max = rec_md->data.number.max;
1167                     if (this_min < (*wheretoput)->data.number.min)
1168                         (*wheretoput)->data.number.min = this_min;
1169                     if (this_max > (*wheretoput)->data.number.max)
1170                         (*wheretoput)->data.number.max = this_max;
1171                 }
1172 #ifdef GAGA
1173                 if (ser_sk)
1174                 {
1175                     union data_types *sdata 
1176                         = cluster->sortkeys[sk_field_id];
1177                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1178                             sdata->number.min, sdata->number.max);
1179                 }
1180 #endif
1181             }
1182
1183
1184             // ranking of _all_ fields enabled ... 
1185             if (ser_md->rank)
1186                 relevance_countwords(se->relevance, cluster, 
1187                                      (char *) value, ser_md->rank);
1188
1189             // construct facets ... 
1190             if (ser_md->termlist)
1191             {
1192                 if (ser_md->type == Metadata_type_year)
1193                 {
1194                     char year[64];
1195                     sprintf(year, "%d", rec_md->data.number.max);
1196                     add_facet(se, (char *) type, year);
1197                     if (rec_md->data.number.max != rec_md->data.number.min)
1198                     {
1199                         sprintf(year, "%d", rec_md->data.number.min);
1200                         add_facet(se, (char *) type, year);
1201                     }
1202                 }
1203                 else
1204                     add_facet(se, (char *) type, (char *) value);
1205             }
1206
1207             // cleaning up
1208             xmlFree(type);
1209             xmlFree(value);
1210             type = value = 0;
1211         }
1212         else
1213             yaz_log(YLOG_WARN,
1214                     "Unexpected element %s in internal record", n->name);
1215     }
1216     if (type)
1217         xmlFree(type);
1218     if (value)
1219         xmlFree(value);
1220
1221     xmlFreeDoc(xdoc);
1222
1223     relevance_donerecord(se->relevance, cluster);
1224     se->total_records++;
1225
1226     return record;
1227 }
1228
1229
1230
1231 /*
1232  * Local variables:
1233  * c-basic-offset: 4
1234  * indent-tabs-mode: nil
1235  * End:
1236  * vim: shiftwidth=4 tabstop=8 expandtab
1237  */