Added support for settings-derived data elements in post-normalization record
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.57 2007-07-30 11:52:08 quinn 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 // Add static values from session database settings if applicable
266 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc)
267 {
268     struct conf_service *service = global_parameters.server->service;
269     int i;
270
271     for (i = 0; i < service->num_metadata; i++)
272     {
273         struct conf_metadata *md = &service->metadata[i];
274         int offset;
275
276         if (md->setting == Metadata_setting_postproc &&
277                 (offset = settings_offset(md->name)) > 0)
278         {
279             char *val = session_setting_oneval(sdb, offset);
280             if (val)
281             {
282                 xmlNode *r = xmlDocGetRootElement(doc);
283                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
284                         (xmlChar *) val);
285                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
286             }
287         }
288     }
289 }
290
291 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
292 {
293     struct database_retrievalmap *m;
294     xmlDoc *rdoc = record_to_xml(sdb, rec);
295     if (rdoc)
296     {
297         for (m = sdb->map; m; m = m->next)
298         {
299             xmlDoc *new = 0;
300             
301             {
302                 xmlNodePtr root = 0;
303                 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
304                 root= xmlDocGetRootElement(new);
305                 if (!new || !root || !(root->children))
306                 {
307                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
308                             sdb->database->url);
309                     xmlFreeDoc(new);
310                     xmlFreeDoc(rdoc);
311                     return 0;
312                 }
313             }
314             
315             xmlFreeDoc(rdoc);
316             rdoc = new;
317         }
318
319         insert_settings_values(sdb, rdoc);
320
321         if (global_parameters.dump_records)
322         {
323             FILE *lf = yaz_log_file();
324             
325             if (lf)
326             {
327                 yaz_log(YLOG_LOG, "Normalized record from %s", 
328                         sdb->database->url);
329 #if LIBXML_VERSION >= 20600
330                 xmlDocFormatDump(lf, rdoc, 1);
331 #else
332                 xmlDocDump(lf, rdoc);
333 #endif
334                 fprintf(lf, "\n");
335             }
336         }
337     }
338     return rdoc;
339 }
340
341 // Retrieve first defined value for 'name' for given database.
342 // Will be extended to take into account user associated with session
343 char *session_setting_oneval(struct session_database *db, int offset)
344 {
345     if (!db->settings[offset])
346         return "";
347     return db->settings[offset]->value;
348 }
349
350
351
352 // Initialize YAZ Map structures for MARC-based targets
353 static int prepare_yazmarc(struct session_database *sdb)
354 {
355     char *s;
356
357     if (!sdb->settings)
358     {
359         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
360         return -1;
361     }
362     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
363         && !strncmp(s, "iso2709", 7))
364     {
365         char *encoding = "marc-8s", *e;
366         yaz_iconv_t cm;
367
368         // See if a native encoding is specified
369         if ((e = strchr(s, ';')))
370             encoding = e + 1;
371
372         sdb->yaz_marc = yaz_marc_create();
373         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
374         
375         cm = yaz_iconv_open("utf-8", encoding);
376         if (!cm)
377         {
378             yaz_log(YLOG_FATAL, 
379                     "Unable to map from %s to UTF-8 for target %s", 
380                     encoding, sdb->database->url);
381             return -1;
382         }
383         yaz_marc_iconv(sdb->yaz_marc, cm);
384     }
385     return 0;
386 }
387
388 // Prepare XSLT stylesheets for record normalization
389 // Structures are allocated on the session_wide nmem to avoid having
390 // to recompute this for every search. This would lead
391 // to leaking if a single session was to repeatedly change the PZ_XSLT
392 // setting. However, this is not a realistic use scenario.
393 static int prepare_map(struct session *se, struct session_database *sdb)
394 {
395    char *s;
396
397     if (!sdb->settings)
398     {
399         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
400         return -1;
401     }
402     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
403     {
404         char **stylesheets;
405         struct database_retrievalmap **m = &sdb->map;
406         int num, i;
407         char auto_stylesheet[256];
408
409         if (!strcmp(s, "auto"))
410         {
411             char *request_syntax = session_setting_oneval(sdb,
412                                                           PZ_REQUESTSYNTAX);
413             if (request_syntax)
414             {
415                 char *cp;
416                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
417                              "%s.xsl", request_syntax);
418                 for (cp = auto_stylesheet; *cp; cp++)
419                 {
420                     /* deliberately only consider ASCII */
421                     if (*cp > 32 && *cp < 127)
422                         *cp = tolower(*cp);
423                 }
424                 s = auto_stylesheet;
425             }
426             else
427             {
428                 yaz_log(YLOG_WARN, "No pz:requestsyntax for auto stylesheet");
429             }
430         }
431         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
432         for (i = 0; i < num; i++)
433         {
434             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
435             (*m)->next = 0;
436             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
437             {
438                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
439                         stylesheets[i]);
440                 return -1;
441             }
442             m = &(*m)->next;
443         }
444     }
445     if (!sdb->map)
446         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
447                 sdb->database->url);
448     return 0;
449 }
450
451 // This analyzes settings and recomputes any supporting data structures
452 // if necessary.
453 static int prepare_session_database(struct session *se, 
454                                     struct session_database *sdb)
455 {
456     if (!sdb->settings)
457     {
458         yaz_log(YLOG_WARN, 
459                 "No settings associated with %s", sdb->database->url);
460         return -1;
461     }
462     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
463     {
464         if (prepare_yazmarc(sdb) < 0)
465             return -1;
466     }
467     if (sdb->settings[PZ_XSLT] && !sdb->map)
468     {
469         if (prepare_map(se, sdb) < 0)
470             return -1;
471     }
472     return 0;
473 }
474
475 // called if watch should be removed because http_channel is to be destroyed
476 static void session_watch_cancel(void *data, struct http_channel *c)
477 {
478     struct session_watchentry *ent = data;
479
480     ent->fun = 0;
481     ent->data = 0;
482     ent->obs = 0;
483 }
484
485 // set watch. Returns 0=OK, -1 if watch is already set
486 int session_set_watch(struct session *s, int what, 
487                       session_watchfun fun, void *data,
488                       struct http_channel *chan)
489 {
490     if (s->watchlist[what].fun)
491         return -1;
492     s->watchlist[what].fun = fun;
493     s->watchlist[what].data = data;
494     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
495                                                session_watch_cancel);
496     return 0;
497 }
498
499 void session_alert_watch(struct session *s, int what)
500 {
501     if (!s->watchlist[what].fun)
502         return;
503     http_remove_observer(s->watchlist[what].obs);
504     (*s->watchlist[what].fun)(s->watchlist[what].data);
505     s->watchlist[what].fun = 0;
506     s->watchlist[what].data = 0;
507     s->watchlist[what].obs = 0;
508 }
509
510 //callback for grep_databases
511 static void select_targets_callback(void *context, struct session_database *db)
512 {
513     struct session *se = (struct session*) context;
514     struct client *cl = client_create();
515     client_set_database(cl, db);
516     client_set_session(cl, se);
517 }
518
519 // Associates a set of clients with a session;
520 // Note: Session-databases represent databases with per-session 
521 // setting overrides
522 int select_targets(struct session *se, struct database_criterion *crit)
523 {
524     while (se->clients)
525         client_destroy(se->clients);
526
527     return session_grep_databases(se, crit, select_targets_callback);
528 }
529
530 int session_active_clients(struct session *s)
531 {
532     struct client *c;
533     int res = 0;
534
535     for (c = s->clients; c; c = client_next_in_session(c))
536         if (client_is_active(c))
537             res++;
538
539     return res;
540 }
541
542 // parses crit1=val1,crit2=val2|val3,...
543 static struct database_criterion *parse_filter(NMEM m, const char *buf)
544 {
545     struct database_criterion *res = 0;
546     char **values;
547     int num;
548     int i;
549
550     if (!buf || !*buf)
551         return 0;
552     nmem_strsplit(m, ",", buf,  &values, &num);
553     for (i = 0; i < num; i++)
554     {
555         char **subvalues;
556         int subnum;
557         int subi;
558         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
559         char *eq = strchr(values[i], '=');
560         if (!eq)
561         {
562             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
563             return 0;
564         }
565         *(eq++) = '\0';
566         new->name = values[i];
567         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
568         new->values = 0;
569         for (subi = 0; subi < subnum; subi++)
570         {
571             struct database_criterion_value *newv
572                 = nmem_malloc(m, sizeof(*newv));
573             newv->value = subvalues[subi];
574             newv->next = new->values;
575             new->values = newv;
576         }
577         new->next = res;
578         res = new;
579     }
580     return res;
581 }
582
583 enum pazpar2_error_code search(struct session *se,
584                                char *query, char *filter,
585                                const char **addinfo)
586 {
587     int live_channels = 0;
588     int no_working = 0;
589     int no_failed = 0;
590     struct client *cl;
591     struct database_criterion *criteria;
592
593     yaz_log(YLOG_DEBUG, "Search");
594
595     *addinfo = 0;
596     nmem_reset(se->nmem);
597     criteria = parse_filter(se->nmem, filter);
598     se->requestid++;
599     live_channels = select_targets(se, criteria);
600     if (live_channels)
601     {
602         int maxrecs = live_channels * global_parameters.toget;
603         se->num_termlists = 0;
604         se->reclist = reclist_create(se->nmem, maxrecs);
605         // This will be initialized in send_search()
606         se->total_records = se->total_hits = se->total_merged = 0;
607         se->expected_maxrecs = maxrecs;
608     }
609     else
610         return PAZPAR2_NO_TARGETS;
611
612     se->relevance = 0;
613
614     for (cl = se->clients; cl; cl = client_next_in_session(cl))
615     {
616         if (prepare_session_database(se, client_get_database(cl)) < 0)
617         {
618             *addinfo = client_get_database(cl)->database->url;
619             return PAZPAR2_CONFIG_TARGET;
620         }
621         // Parse query for target
622         if (client_parse_query(cl, query) < 0)
623             no_failed++;
624         else
625         {
626             no_working++;
627             client_prep_connection(cl);
628         }
629     }
630
631     // If no queries could be mapped, we signal an error
632     if (no_working == 0)
633     {
634         *addinfo = "query";
635         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
636     }
637     return PAZPAR2_NO_ERROR;
638 }
639
640 // Creates a new session_database object for a database
641 static void session_init_databases_fun(void *context, struct database *db)
642 {
643     struct session *se = (struct session *) context;
644     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
645     int num = settings_num();
646     int i;
647
648     new->database = db;
649     new->yaz_marc = 0;
650     
651 #ifdef HAVE_ICU
652     if (global_parameters.server && global_parameters.server->icu_chn)
653         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
654     else
655         new->pct = pp2_charset_create(0);
656 #else // HAVE_ICU
657     new->pct = pp2_charset_create(0);
658 #endif // HAVE_ICU
659
660     new->map = 0;
661     new->settings 
662         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
663     memset(new->settings, 0, sizeof(struct settings*) * num);
664
665     if (db->settings)
666     {
667         for (i = 0; i < num; i++)
668             new->settings[i] = db->settings[i];
669     }
670     new->next = se->databases;
671     se->databases = new;
672 }
673
674 // Doesn't free memory associated with sdb -- nmem takes care of that
675 static void session_database_destroy(struct session_database *sdb)
676 {
677     struct database_retrievalmap *m;
678
679     for (m = sdb->map; m; m = m->next)
680         xsltFreeStylesheet(m->stylesheet);
681     if (sdb->yaz_marc)
682         yaz_marc_destroy(sdb->yaz_marc);
683     if (sdb->pct)
684         pp2_charset_destroy(sdb->pct);
685 }
686
687 // Initialize session_database list -- this represents this session's view
688 // of the database list -- subject to modification by the settings ws command
689 void session_init_databases(struct session *se)
690 {
691     se->databases = 0;
692     predef_grep_databases(se, 0, session_init_databases_fun);
693 }
694
695 // Probably session_init_databases_fun should be refactored instead of
696 // called here.
697 static struct session_database *load_session_database(struct session *se, 
698                                                       char *id)
699 {
700     struct database *db = find_database(id, 0);
701
702     session_init_databases_fun((void*) se, db);
703     // New sdb is head of se->databases list
704     return se->databases;
705 }
706
707 // Find an existing session database. If not found, load it
708 static struct session_database *find_session_database(struct session *se, 
709                                                       char *id)
710 {
711     struct session_database *sdb;
712
713     for (sdb = se->databases; sdb; sdb = sdb->next)
714         if (!strcmp(sdb->database->url, id))
715             return sdb;
716     return load_session_database(se, id);
717 }
718
719 // Apply a session override to a database
720 void session_apply_setting(struct session *se, char *dbname, char *setting,
721                            char *value)
722 {
723     struct session_database *sdb = find_session_database(se, dbname);
724     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
725     int offset = settings_offset_cprefix(setting);
726
727     if (offset < 0)
728     {
729         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
730         return;
731     }
732     // Jakub: This breaks the filter setting.
733     /*if (offset == PZ_ID)
734     {
735         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
736         return;
737     }*/
738     new->precedence = 0;
739     new->target = dbname;
740     new->name = setting;
741     new->value = value;
742     new->next = sdb->settings[offset];
743     sdb->settings[offset] = new;
744
745     // Force later recompute of settings-driven data structures
746     // (happens when a search starts and client connections are prepared)
747     switch (offset)
748     {
749         case PZ_NATIVESYNTAX:
750             if (sdb->yaz_marc)
751             {
752                 yaz_marc_destroy(sdb->yaz_marc);
753                 sdb->yaz_marc = 0;
754             }
755             break;
756         case PZ_XSLT:
757             if (sdb->map)
758             {
759                 struct database_retrievalmap *m;
760                 // We don't worry about the map structure -- it's in nmem
761                 for (m = sdb->map; m; m = m->next)
762                     xsltFreeStylesheet(m->stylesheet);
763                 sdb->map = 0;
764             }
765             break;
766     }
767 }
768
769 void destroy_session(struct session *s)
770 {
771     struct session_database *sdb;
772
773     while (s->clients)
774         client_destroy(s->clients);
775     for (sdb = s->databases; sdb; sdb = sdb->next)
776         session_database_destroy(sdb);
777     nmem_destroy(s->nmem);
778     wrbuf_destroy(s->wrbuf);
779 }
780
781 struct session *new_session(NMEM nmem) 
782 {
783     int i;
784     struct session *session = nmem_malloc(nmem, sizeof(*session));
785
786     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
787     
788     session->relevance = 0;
789     session->total_hits = 0;
790     session->total_records = 0;
791     session->num_termlists = 0;
792     session->reclist = 0;
793     session->requestid = -1;
794     session->clients = 0;
795     session->expected_maxrecs = 0;
796     session->session_nmem = nmem;
797     session->nmem = nmem_create();
798     session->wrbuf = wrbuf_alloc();
799     session->databases = 0;
800     for (i = 0; i <= SESSION_WATCH_MAX; i++)
801     {
802         session->watchlist[i].data = 0;
803         session->watchlist[i].fun = 0;
804     }
805
806     return session;
807 }
808
809 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
810 {
811     static struct hitsbytarget res[1000]; // FIXME MM
812     struct client *cl;
813
814     *count = 0;
815     for (cl = se->clients; cl; cl = client_next_in_session(cl))
816     {
817         char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
818
819         res[*count].id = client_get_database(cl)->database->url;
820         res[*count].name = *name ? name : "Unknown";
821         res[*count].hits = client_get_hits(cl);
822         res[*count].records = client_get_num_records(cl);
823         res[*count].diagnostic = client_get_diagnostic(cl);
824         res[*count].state = client_get_state_str(cl);
825         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
826         (*count)++;
827     }
828
829     return res;
830 }
831
832 struct termlist_score **termlist(struct session *s, const char *name, int *num)
833 {
834     int i;
835
836     for (i = 0; i < s->num_termlists; i++)
837         if (!strcmp((const char *) s->termlists[i].name, name))
838             return termlist_highscore(s->termlists[i].termlist, num);
839     return 0;
840 }
841
842 #ifdef MISSING_HEADERS
843 void report_nmem_stats(void)
844 {
845     size_t in_use, is_free;
846
847     nmem_get_memory_in_use(&in_use);
848     nmem_get_memory_free(&is_free);
849
850     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
851             (long) in_use, (long) is_free);
852 }
853 #endif
854
855 struct record_cluster *show_single(struct session *s, const char *id)
856 {
857     struct record_cluster *r;
858
859     reclist_rewind(s->reclist);
860     while ((r = reclist_read_record(s->reclist)))
861         if (!strcmp(r->recid, id))
862             return r;
863     return 0;
864 }
865
866 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
867                              int start, int *num, int *total, int *sumhits, 
868                              NMEM nmem_show)
869 {
870     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
871                                        * sizeof(struct record_cluster *));
872     struct reclist_sortparms *spp;
873     int i;
874 #if USE_TIMING    
875     yaz_timing_t t = yaz_timing_create();
876 #endif
877
878     if (!s->relevance)
879     {
880         *num = 0;
881         *total = 0;
882         *sumhits = 0;
883         recs = 0;
884     }
885     else
886     {
887         for (spp = sp; spp; spp = spp->next)
888             if (spp->type == Metadata_sortkey_relevance)
889             {
890                 relevance_prepare_read(s->relevance, s->reclist);
891                 break;
892             }
893         reclist_sort(s->reclist, sp);
894         
895         *total = s->reclist->num_records;
896         *sumhits = s->total_hits;
897         
898         for (i = 0; i < start; i++)
899             if (!reclist_read_record(s->reclist))
900             {
901                 *num = 0;
902                 recs = 0;
903                 break;
904             }
905         
906         for (i = 0; i < *num; i++)
907         {
908             struct record_cluster *r = reclist_read_record(s->reclist);
909             if (!r)
910             {
911                 *num = i;
912                 break;
913             }
914             recs[i] = r;
915         }
916     }
917 #if USE_TIMING
918     yaz_timing_stop(t);
919     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
920             yaz_timing_get_real(t), yaz_timing_get_user(t),
921             yaz_timing_get_sys(t));
922     yaz_timing_destroy(&t);
923 #endif
924     return recs;
925 }
926
927 void statistics(struct session *se, struct statistics *stat)
928 {
929     struct client *cl;
930     int count = 0;
931
932     memset(stat, 0, sizeof(*stat));
933     for (cl = se->clients; cl; cl = client_next_in_session(cl))
934     {
935         if (!client_get_connection(cl))
936             stat->num_no_connection++;
937         switch (client_get_state(cl))
938         {
939             case Client_Connecting: stat->num_connecting++; break;
940             case Client_Initializing: stat->num_initializing++; break;
941             case Client_Searching: stat->num_searching++; break;
942             case Client_Presenting: stat->num_presenting++; break;
943             case Client_Idle: stat->num_idle++; break;
944             case Client_Failed: stat->num_failed++; break;
945             case Client_Error: stat->num_error++; break;
946             default: break;
947         }
948         count++;
949     }
950     stat->num_hits = se->total_hits;
951     stat->num_records = se->total_records;
952
953     stat->num_clients = count;
954 }
955
956 void start_http_listener(void)
957 {
958     char hp[128] = "";
959     struct conf_server *ser = global_parameters.server;
960
961     if (*global_parameters.listener_override)
962         strcpy(hp, global_parameters.listener_override);
963     else
964     {
965         strcpy(hp, ser->host ? ser->host : "");
966         if (ser->port)
967         {
968             if (*hp)
969                 strcat(hp, ":");
970             sprintf(hp + strlen(hp), "%d", ser->port);
971         }
972     }
973     http_init(hp);
974 }
975
976 void start_proxy(void)
977 {
978     char hp[128] = "";
979     struct conf_server *ser = global_parameters.server;
980
981     if (*global_parameters.proxy_override)
982         strcpy(hp, global_parameters.proxy_override);
983     else if (ser->proxy_host || ser->proxy_port)
984     {
985         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
986         if (ser->proxy_port)
987         {
988             if (*hp)
989                 strcat(hp, ":");
990             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
991         }
992     }
993     else
994         return;
995
996     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
997 }
998
999
1000 // Master list of connections we're handling events to
1001 static IOCHAN channel_list = 0; 
1002 void pazpar2_add_channel(IOCHAN chan)
1003 {
1004     chan->next = channel_list;
1005     channel_list = chan;
1006 }
1007
1008 void pazpar2_event_loop()
1009 {
1010     event_loop(&channel_list);
1011 }
1012
1013 static struct record_metadata *record_metadata_init(
1014     NMEM nmem, char *value, enum conf_metadata_type type)
1015 {
1016     struct record_metadata *rec_md = record_metadata_create(nmem);
1017     if (type == Metadata_type_generic)
1018     {
1019         char * p = value;
1020         p = normalize7bit_generic(p, " ,/.:([");
1021         
1022         rec_md->data.text = nmem_strdup(nmem, p);
1023     }
1024     else if (type == Metadata_type_year)
1025     {
1026         int first, last;
1027         if (extract7bit_years((char *) value, &first, &last) < 0)
1028             return 0;
1029         rec_md->data.number.min = first;
1030         rec_md->data.number.max = last;
1031     }
1032     else
1033         return 0;
1034     return rec_md;
1035 }
1036
1037 struct record *ingest_record(struct client *cl, Z_External *rec,
1038                              int record_no)
1039 {
1040     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
1041     xmlNode *root, *n;
1042     struct record *record;
1043     struct record_cluster *cluster;
1044     struct session *se = client_get_session(cl);
1045     xmlChar *mergekey, *mergekey_norm;
1046     xmlChar *type = 0;
1047     xmlChar *value = 0;
1048     struct conf_service *service = global_parameters.server->service;
1049
1050     if (!xdoc)
1051         return 0;
1052
1053     root = xmlDocGetRootElement(xdoc);
1054     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
1055     {
1056         yaz_log(YLOG_WARN, "No mergekey found in record");
1057         xmlFreeDoc(xdoc);
1058         return 0;
1059     }
1060
1061     record = record_create(se->nmem, 
1062                            service->num_metadata, service->num_sortkeys, cl,
1063                            record_no);
1064
1065     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
1066     xmlFree(mergekey);
1067     normalize7bit_mergekey((char *) mergekey_norm, 0);
1068
1069     cluster = reclist_insert(se->reclist, 
1070                              global_parameters.server->service, 
1071                              record, (char *) mergekey_norm, 
1072                              &se->total_merged);
1073     if (global_parameters.dump_records)
1074         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1075                 client_get_database(cl)->database->url, record_no);
1076     if (!cluster)
1077     {
1078         /* no room for record */
1079         xmlFreeDoc(xdoc);
1080         return 0;
1081     }
1082     relevance_newrec(se->relevance, cluster);
1083
1084
1085     // now parsing XML record and adding data to cluster or record metadata
1086     for (n = root->children; n; n = n->next)
1087     {
1088         if (type)
1089             xmlFree(type);
1090         if (value)
1091             xmlFree(value);
1092         type = value = 0;
1093
1094         if (n->type != XML_ELEMENT_NODE)
1095             continue;
1096         if (!strcmp((const char *) n->name, "metadata"))
1097         {
1098             struct conf_metadata *ser_md = 0;
1099             struct conf_sortkey *ser_sk = 0;
1100             struct record_metadata **wheretoput = 0;
1101             struct record_metadata *rec_md = 0;
1102             int md_field_id = -1;
1103             int sk_field_id = -1;
1104
1105             type = xmlGetProp(n, (xmlChar *) "type");
1106             value = xmlNodeListGetString(xdoc, n->children, 1);
1107
1108             if (!type || !value)
1109                 continue;
1110
1111             md_field_id 
1112                 = conf_service_metadata_field_id(service, (const char *) type);
1113             if (md_field_id < 0)
1114             {
1115                 yaz_log(YLOG_WARN, 
1116                         "Ignoring unknown metadata element: %s", type);
1117                 continue;
1118             }
1119
1120             ser_md = &service->metadata[md_field_id];
1121
1122             if (ser_md->sortkey_offset >= 0){
1123                 sk_field_id = ser_md->sortkey_offset;
1124                 ser_sk = &service->sortkeys[sk_field_id];
1125             }
1126
1127             // non-merged metadata
1128             rec_md = record_metadata_init(se->nmem, (char *) value,
1129                                           ser_md->type);
1130             if (!rec_md)
1131             {
1132                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1133                         value, type);
1134                 continue;
1135             }
1136             rec_md->next = record->metadata[md_field_id];
1137             record->metadata[md_field_id] = rec_md;
1138
1139             // merged metadata
1140             rec_md = record_metadata_init(se->nmem, (char *) value,
1141                                           ser_md->type);
1142             wheretoput = &cluster->metadata[md_field_id];
1143
1144             // and polulate with data:
1145             // assign cluster or record based on merge action
1146             if (ser_md->merge == Metadata_merge_unique)
1147             {
1148                 struct record_metadata *mnode;
1149                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1150                     if (!strcmp((const char *) mnode->data.text, 
1151                                 rec_md->data.text))
1152                         break;
1153                 if (!mnode)
1154                 {
1155                     rec_md->next = *wheretoput;
1156                     *wheretoput = rec_md;
1157                 }
1158             }
1159             else if (ser_md->merge == Metadata_merge_longest)
1160             {
1161                 if (!*wheretoput 
1162                     || strlen(rec_md->data.text) 
1163                        > strlen((*wheretoput)->data.text))
1164                 {
1165                     *wheretoput = rec_md;
1166                     if (ser_sk)
1167                     {
1168                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1169                         if (!cluster->sortkeys[sk_field_id])
1170                             cluster->sortkeys[sk_field_id] = 
1171                                 nmem_malloc(se->nmem, 
1172                                             sizeof(union data_types));
1173                         normalize7bit_mergekey(s,
1174                              (ser_sk->type == Metadata_sortkey_skiparticle));
1175                         cluster->sortkeys[sk_field_id]->text = s;
1176                     }
1177                 }
1178             }
1179             else if (ser_md->merge == Metadata_merge_all)
1180             {
1181                 rec_md->next = *wheretoput;
1182                 *wheretoput = rec_md;
1183             }
1184             else if (ser_md->merge == Metadata_merge_range)
1185             {
1186                 if (!*wheretoput)
1187                 {
1188                     *wheretoput = rec_md;
1189                     if (ser_sk)
1190                         cluster->sortkeys[sk_field_id] 
1191                             = &rec_md->data;
1192                 }
1193                 else
1194                 {
1195                     int this_min = rec_md->data.number.min;
1196                     int this_max = rec_md->data.number.max;
1197                     if (this_min < (*wheretoput)->data.number.min)
1198                         (*wheretoput)->data.number.min = this_min;
1199                     if (this_max > (*wheretoput)->data.number.max)
1200                         (*wheretoput)->data.number.max = this_max;
1201                 }
1202 #ifdef GAGA
1203                 if (ser_sk)
1204                 {
1205                     union data_types *sdata 
1206                         = cluster->sortkeys[sk_field_id];
1207                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1208                             sdata->number.min, sdata->number.max);
1209                 }
1210 #endif
1211             }
1212
1213
1214             // ranking of _all_ fields enabled ... 
1215             if (ser_md->rank)
1216                 relevance_countwords(se->relevance, cluster, 
1217                                      (char *) value, ser_md->rank);
1218
1219             // construct facets ... 
1220             if (ser_md->termlist)
1221             {
1222                 if (ser_md->type == Metadata_type_year)
1223                 {
1224                     char year[64];
1225                     sprintf(year, "%d", rec_md->data.number.max);
1226                     add_facet(se, (char *) type, year);
1227                     if (rec_md->data.number.max != rec_md->data.number.min)
1228                     {
1229                         sprintf(year, "%d", rec_md->data.number.min);
1230                         add_facet(se, (char *) type, year);
1231                     }
1232                 }
1233                 else
1234                     add_facet(se, (char *) type, (char *) value);
1235             }
1236
1237             // cleaning up
1238             xmlFree(type);
1239             xmlFree(value);
1240             type = value = 0;
1241         }
1242         else
1243             yaz_log(YLOG_WARN,
1244                     "Unexpected element %s in internal record", n->name);
1245     }
1246     if (type)
1247         xmlFree(type);
1248     if (value)
1249         xmlFree(value);
1250
1251     xmlFreeDoc(xdoc);
1252
1253     relevance_donerecord(se->relevance, cluster);
1254     se->total_records++;
1255
1256     return record;
1257 }
1258
1259
1260
1261 /*
1262  * Local variables:
1263  * c-basic-offset: 4
1264  * indent-tabs-mode: nil
1265  * End:
1266  * vim: shiftwidth=4 tabstop=8 expandtab
1267  */