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