8edaa8dc8a7e84ea03ebab25d37121ed9acf2b71
[pazpar2-moved-to-github.git] / src / session.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2012 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 session.c
21     \brief high-level logic; mostly user sessions and settings
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <time.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #if HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #if HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #ifdef WIN32
39 #include <windows.h>
40 #endif
41 #include <signal.h>
42 #include <ctype.h>
43 #include <assert.h>
44 #include <math.h>
45
46 #include <yaz/marcdisp.h>
47 #include <yaz/comstack.h>
48 #include <yaz/tcpip.h>
49 #include <yaz/proto.h>
50 #include <yaz/readconf.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/yaz-util.h>
54 #include <yaz/nmem.h>
55 #include <yaz/query-charset.h>
56 #include <yaz/querytowrbuf.h>
57 #include <yaz/oid_db.h>
58 #include <yaz/snprintf.h>
59 #include <yaz/gettimeofday.h>
60
61 #define USE_TIMING 0
62 #if USE_TIMING
63 #include <yaz/timing.h>
64 #endif
65
66 #include "ppmutex.h"
67 #include "parameters.h"
68 #include "session.h"
69 #include "eventl.h"
70 #include "http.h"
71 #include "termlists.h"
72 #include "reclists.h"
73 #include "relevance.h"
74 #include "database.h"
75 #include "client.h"
76 #include "settings.h"
77 #include "normalize7bit.h"
78
79 #include <libxml/tree.h>
80
81 #define TERMLIST_HIGH_SCORE 25
82
83 #define MAX_CHUNK 15
84
85 #define MAX(a,b) ((a)>(b)?(a):(b))
86
87 // Note: Some things in this structure will eventually move to configuration
88 struct parameters global_parameters = 
89 {
90     0,   // dump_records
91     0,   // debug_mode
92     0,   // predictable sessions
93 };
94
95 struct client_list {
96     struct client *client;
97     struct client_list *next;
98 };
99
100 /* session counting (1) , disable client counting (0) */
101 static YAZ_MUTEX g_session_mutex = 0;
102 static int no_sessions = 0;
103 static int no_session_total = 0;
104
105 static int session_use(int delta)
106 {
107     int sessions;
108     if (!g_session_mutex)
109         yaz_mutex_create(&g_session_mutex);
110     yaz_mutex_enter(g_session_mutex);
111     no_sessions += delta;
112     if (delta > 0)
113         no_session_total += delta;
114     sessions = no_sessions;
115     yaz_mutex_leave(g_session_mutex);
116     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
117     return sessions;
118 }
119
120 int sessions_count(void)
121 {
122     return session_use(0);
123 }
124
125 int session_count_total(void)
126 {
127     int total = 0;
128     if (!g_session_mutex)
129         return 0;
130     yaz_mutex_enter(g_session_mutex);
131     total = no_session_total;
132     yaz_mutex_leave(g_session_mutex);
133     return total;
134 }
135
136 static void log_xml_doc(xmlDoc *doc)
137 {
138     FILE *lf = yaz_log_file();
139     xmlChar *result = 0;
140     int len = 0;
141 #if LIBXML_VERSION >= 20600
142     xmlDocDumpFormatMemory(doc, &result, &len, 1);
143 #else
144     xmlDocDumpMemory(doc, &result, &len);
145 #endif
146     if (lf && len)
147     {
148         (void) fwrite(result, 1, len, lf);
149         fprintf(lf, "\n");
150     }
151     xmlFree(result);
152 }
153
154 static void session_enter(struct session *s)
155 {
156     yaz_mutex_enter(s->session_mutex);
157 }
158
159 static void session_leave(struct session *s)
160 {
161     yaz_mutex_leave(s->session_mutex);
162 }
163
164 static void session_normalize_facet(struct session *s, const char *type,
165                                     const char *value,
166                                     WRBUF display_wrbuf,
167                                     WRBUF facet_wrbuf)
168 {
169     struct conf_service *service = s->service;
170     pp2_charset_token_t prt;
171     const char *facet_component;
172     int i;
173     const char *icu_chain_id = 0;
174
175     for (i = 0; i < service->num_metadata; i++)
176         if (!strcmp((service->metadata + i)->name, type))
177             icu_chain_id = (service->metadata + i)->facetrule;
178     if (!icu_chain_id)
179         icu_chain_id = "facet";
180     prt = pp2_charset_token_create(service->charsets, icu_chain_id);
181     if (!prt)
182     {
183         yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
184                 icu_chain_id, type);
185         wrbuf_destroy(facet_wrbuf);
186         wrbuf_destroy(display_wrbuf);
187         return;
188     }
189     pp2_charset_token_first(prt, value, 0);
190     while ((facet_component = pp2_charset_token_next(prt)))
191     {
192         const char *display_component;
193         if (*facet_component)
194         {
195             if (wrbuf_len(facet_wrbuf))
196                 wrbuf_puts(facet_wrbuf, " ");
197             wrbuf_puts(facet_wrbuf, facet_component);
198         }
199         display_component = pp2_get_display(prt);
200         if (display_component)
201         {
202             if (wrbuf_len(display_wrbuf))
203                 wrbuf_puts(display_wrbuf, " ");
204             wrbuf_puts(display_wrbuf, display_component);
205         }
206     }
207     pp2_charset_token_destroy(prt);
208 }
209
210 void add_facet(struct session *s, const char *type, const char *value, int count)
211 {
212     WRBUF facet_wrbuf = wrbuf_alloc();
213     WRBUF display_wrbuf = wrbuf_alloc();
214
215     session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
216  
217     if (wrbuf_len(facet_wrbuf))
218     {
219         int i;
220         for (i = 0; i < s->num_termlists; i++)
221             if (!strcmp(s->termlists[i].name, type))
222                 break;
223         if (i == s->num_termlists)
224         {
225             if (i == SESSION_MAX_TERMLISTS)
226             {
227                 session_log(s, YLOG_FATAL, "Too many termlists");
228                 wrbuf_destroy(facet_wrbuf);
229                 wrbuf_destroy(display_wrbuf);
230                 return;
231             }
232             
233             s->termlists[i].name = nmem_strdup(s->nmem, type);
234             s->termlists[i].termlist 
235                 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
236             s->num_termlists = i + 1;
237         }
238         
239 #if 0
240         session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
241 #endif
242         termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
243                         wrbuf_cstr(facet_wrbuf), count);
244     }
245     wrbuf_destroy(facet_wrbuf);
246     wrbuf_destroy(display_wrbuf);
247 }
248
249 static xmlDoc *record_to_xml(struct session *se,
250                              struct session_database *sdb, const char *rec)
251 {
252     struct database *db = sdb->database;
253     xmlDoc *rdoc = 0;
254
255     rdoc = xmlParseMemory(rec, strlen(rec));
256
257     if (!rdoc)
258     {
259         session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
260                     db->id);
261         return 0;
262     }
263
264     if (global_parameters.dump_records)
265     {
266         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
267         log_xml_doc(rdoc);
268     }
269
270     return rdoc;
271 }
272
273 #define MAX_XSLT_ARGS 16
274
275 // Add static values from session database settings if applicable
276 static void insert_settings_parameters(struct session_database *sdb,
277                                        struct conf_service *service,
278                                        char **parms,
279                                        NMEM nmem)
280 {
281     int i;
282     int nparms = 0;
283     int offset = 0;
284
285     for (i = 0; i < service->num_metadata; i++)
286     {
287         struct conf_metadata *md = &service->metadata[i];
288         int setting;
289
290         if (md->setting == Metadata_setting_parameter &&
291             (setting = settings_lookup_offset(service, md->name)) >= 0)
292         {
293             const char *val = session_setting_oneval(sdb, setting);
294             if (val && nparms < MAX_XSLT_ARGS)
295             {
296                 char *buf;
297                 int len = strlen(val);
298                 buf = nmem_malloc(nmem, len + 3);
299                 buf[0] = '\'';
300                 strcpy(buf + 1, val);
301                 buf[len+1] = '\'';
302                 buf[len+2] = '\0';
303                 parms[offset++] = md->name;
304                 parms[offset++] = buf;
305                 nparms++;
306             }
307         }
308     }
309     parms[offset] = 0;
310 }
311
312 // Add static values from session database settings if applicable
313 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
314     struct conf_service *service)
315 {
316     int i;
317
318     for (i = 0; i < service->num_metadata; i++)
319     {
320         struct conf_metadata *md = &service->metadata[i];
321         int offset;
322
323         if (md->setting == Metadata_setting_postproc &&
324             (offset = settings_lookup_offset(service, md->name)) >= 0)
325         {
326             const char *val = session_setting_oneval(sdb, offset);
327             if (val)
328             {
329                 xmlNode *r = xmlDocGetRootElement(doc);
330                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
331                                              (xmlChar *) val);
332                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
333             }
334         }
335     }
336 }
337
338 static xmlDoc *normalize_record(struct session *se,
339                                 struct session_database *sdb,
340                                 struct conf_service *service,
341                                 const char *rec, NMEM nmem)
342 {
343     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
344
345     if (rdoc)
346     {
347         char *parms[MAX_XSLT_ARGS*2+1];
348         
349         insert_settings_parameters(sdb, service, parms, nmem);
350         
351         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
352         {
353             session_log(se, YLOG_WARN, "Normalize failed from %s",
354                         sdb->database->id);
355         }
356         else
357         {
358             insert_settings_values(sdb, rdoc, service);
359             
360             if (global_parameters.dump_records)
361             {
362                 session_log(se, YLOG_LOG, "Normalized record from %s", 
363                             sdb->database->id);
364                 log_xml_doc(rdoc);
365             }
366         }
367     }
368     return rdoc;
369 }
370
371 void session_settings_dump(struct session *se,
372                            struct session_database *db,
373                            WRBUF w)
374 {
375     if (db->settings)
376     {
377         int i, num = db->num_settings;
378         for (i = 0; i < num; i++)
379         {
380             struct setting *s = db->settings[i];
381             for (;s ; s = s->next)
382             {
383                 wrbuf_puts(w, "<set name=\"");
384                 wrbuf_xmlputs(w, s->name);
385                 wrbuf_puts(w, "\" value=\"");
386                 wrbuf_xmlputs(w, s->value);
387                 wrbuf_puts(w, "\"/>");
388             }
389             if (db->settings[i])
390                 wrbuf_puts(w, "\n");
391         }
392     }
393 }
394
395 // Retrieve first defined value for 'name' for given database.
396 // Will be extended to take into account user associated with session
397 const char *session_setting_oneval(struct session_database *db, int offset)
398 {
399     if (offset >= db->num_settings || !db->settings[offset])
400         return "";
401     return db->settings[offset]->value;
402 }
403
404 // Prepare XSLT stylesheets for record normalization
405 // Structures are allocated on the session_wide nmem to avoid having
406 // to recompute this for every search. This would lead
407 // to leaking if a single session was to repeatedly change the PZ_XSLT
408 // setting. However, this is not a realistic use scenario.
409 static int prepare_map(struct session *se, struct session_database *sdb)
410 {
411     if (sdb->settings && !sdb->map)
412     {
413         const char *s;
414
415         if (sdb->settings[PZ_XSLT] &&
416             (s = session_setting_oneval(sdb, PZ_XSLT)))        
417         {
418             char auto_stylesheet[256];
419             
420             if (!strcmp(s, "auto"))
421             {
422                 const char *request_syntax = session_setting_oneval(
423                     sdb, PZ_REQUESTSYNTAX);
424                 if (request_syntax)
425                 {
426                     char *cp;
427                     yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
428                                  "%s.xsl", request_syntax);
429                     for (cp = auto_stylesheet; *cp; cp++)
430                     {
431                         /* deliberately only consider ASCII */
432                         if (*cp > 32 && *cp < 127)
433                             *cp = tolower(*cp);
434                     }
435                     s = auto_stylesheet;
436                 }
437                 else
438                 {
439                     session_log(se, YLOG_WARN,
440                                 "No pz:requestsyntax for auto stylesheet");
441                 }
442             }
443             sdb->map = normalize_cache_get(se->normalize_cache,
444                                            se->service, s);
445             if (!sdb->map)
446                 return -1;
447         }
448     }
449     return 0;
450 }
451
452 // called if watch should be removed because http_channel is to be destroyed
453 static void session_watch_cancel(void *data, struct http_channel *c,
454                                  void *data2)
455 {
456     struct session_watchentry *ent = data;
457
458     ent->fun = 0;
459     ent->data = 0;
460     ent->obs = 0;
461 }
462
463 // set watch. Returns 0=OK, -1 if watch is already set
464 int session_set_watch(struct session *s, int what, 
465                       session_watchfun fun, void *data,
466                       struct http_channel *chan)
467 {
468     int ret;
469     session_enter(s);
470     if (s->watchlist[what].fun)
471         ret = -1;
472     else
473     {
474         
475         s->watchlist[what].fun = fun;
476         s->watchlist[what].data = data;
477         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
478                                                    session_watch_cancel);
479         ret = 0;
480     }
481     session_leave(s);
482     return ret;
483 }
484
485 void session_alert_watch(struct session *s, int what)
486 {
487     assert(s);
488     session_enter(s);
489     if (s->watchlist[what].fun)
490     {
491         /* our watch is no longer associated with http_channel */
492         void *data;
493         session_watchfun fun;
494
495         http_remove_observer(s->watchlist[what].obs);
496         fun  = s->watchlist[what].fun;
497         data = s->watchlist[what].data;
498
499         /* reset watch before fun is invoked - in case fun wants to set
500            it again */
501         s->watchlist[what].fun = 0;
502         s->watchlist[what].data = 0;
503         s->watchlist[what].obs = 0;
504
505         session_leave(s);
506         session_log(s, YLOG_DEBUG,
507                     "Alert Watch: %d calling function: %p", what, fun);
508         fun(data);
509     }
510     else
511         session_leave(s);
512 }
513
514 //callback for grep_databases
515 static void select_targets_callback(struct session *se,
516                                     struct session_database *db)
517 {
518     struct client *cl;
519     struct client_list *l;
520
521     for (l = se->clients_cached; l; l = l->next)
522         if (client_get_database(l->client) == db)
523             break;
524
525     if (l)
526         cl = l->client;
527     else
528     {
529         cl = client_create(db->database->id);
530         client_set_database(cl, db);
531
532         l = xmalloc(sizeof(*l));
533         l->client = cl;
534         l->next = se->clients_cached;
535         se->clients_cached = l;
536     }
537     /* set session always. If may be 0 if client is not active */
538     client_set_session(cl, se);
539
540     l = xmalloc(sizeof(*l));
541     l->client = cl;
542     l->next = se->clients_active;
543     se->clients_active = l;
544 }
545
546 static void session_reset_active_clients(struct session *se,
547                                          struct client_list *new_list)
548 {
549     struct client_list *l;
550
551     session_enter(se);
552     l = se->clients_active;
553     se->clients_active = new_list;
554     session_leave(se);
555
556     while (l)
557     {
558         struct client_list *l_next = l->next;
559
560         client_lock(l->client); 
561         client_set_session(l->client, 0); /* mark client inactive */
562         client_unlock(l->client);
563
564         xfree(l);
565         l = l_next;
566     }
567 }
568
569 static void session_remove_cached_clients(struct session *se)
570 {
571     struct client_list *l;
572
573     session_reset_active_clients(se, 0);
574
575     session_enter(se);
576     l = se->clients_cached;
577     se->clients_cached = 0;
578     session_leave(se);
579
580     while (l)
581     {
582         struct client_list *l_next = l->next;
583         client_lock(l->client);
584         client_set_session(l->client, 0);
585         client_set_database(l->client, 0);
586         client_unlock(l->client);
587         client_destroy(l->client);
588         xfree(l);
589         l = l_next;
590     }
591 }
592
593 // Associates a set of clients with a session;
594 // Note: Session-databases represent databases with per-session 
595 // setting overrides
596 static int select_targets(struct session *se, const char *filter)
597 {
598     return session_grep_databases(se, filter, select_targets_callback);
599 }
600
601 int session_active_clients(struct session *s)
602 {
603     struct client_list *l;
604     int res = 0;
605
606     for (l = s->clients_active; l; l = l->next)
607         if (client_is_active(l->client))
608             res++;
609
610     return res;
611 }
612
613 int session_is_preferred_clients_ready(struct session *s)
614 {
615     struct client_list *l;
616     int res = 0;
617
618     for (l = s->clients_active; l; l = l->next)
619         if (client_is_active_preferred(l->client))
620             res++;
621     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
622     return res == 0;
623 }
624
625 static void session_clear_set(struct session *se,
626                               const char *sort_field, int increasing)
627 {
628     reclist_destroy(se->reclist);
629     se->reclist = 0;
630     if (nmem_total(se->nmem))
631         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
632                     nmem_total(se->nmem));
633     nmem_reset(se->nmem);
634     se->total_records = se->total_merged = 0;
635     se->num_termlists = 0;
636     
637     /* reset list of sorted results and clear to relevance search */
638     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
639     se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
640     se->sorted_results->increasing = increasing;
641     se->sorted_results->next = 0;
642     
643     se->reclist = reclist_create(se->nmem);
644 }
645
646 void session_sort(struct session *se, const char *field, int increasing,
647                   int clear_set)
648 {
649     struct session_sorted_results *sr;
650     struct client_list *l;
651
652     session_enter(se);
653
654     yaz_log(YLOG_LOG, "session_sort field=%s", field);
655     if (clear_set)
656     {
657         session_clear_set(se, field, increasing);
658     }
659     else
660     {
661         /* see if we already have sorted for this critieria */
662         for (sr = se->sorted_results; sr; sr = sr->next)
663         {
664             if (!strcmp(field, sr->field) && increasing == sr->increasing)
665                 break;
666         }
667         if (sr)
668         {
669             session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d already fetched",
670                         field, increasing);
671             session_leave(se);
672             return;
673         }
674         session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d must fetch",
675                     field, increasing);
676         sr = nmem_malloc(se->nmem, sizeof(*sr));
677         sr->field = nmem_strdup(se->nmem, field);
678         sr->increasing = increasing;
679         sr->next = se->sorted_results;
680         se->sorted_results = sr;
681     }
682         
683     for (l = se->clients_active; l; l = l->next)
684     {
685         struct client *cl = l->client;
686         if (client_get_state(cl) == Client_Connecting ||
687             client_get_state(cl) == Client_Idle ||
688             client_get_state(cl) == Client_Working)
689             client_start_search(cl);
690     }
691     session_leave(se);
692 }
693
694 enum pazpar2_error_code session_search(struct session *se,
695                                        const char *query,
696                                        const char *startrecs,
697                                        const char *maxrecs,
698                                        const char *filter,
699                                        const char *limit,
700                                        const char **addinfo,
701                                        const char *sort_field, int increasing)
702 {
703     int live_channels = 0;
704     int no_working = 0;
705     int no_failed_query = 0;
706     int no_failed_limit = 0;
707     struct client_list *l, *l0;
708     struct timeval tval;
709     facet_limits_t facet_limits;
710
711     session_log(se, YLOG_DEBUG, "Search");
712
713     *addinfo = 0;
714
715     if (se->settings_modified)
716         session_remove_cached_clients(se);
717     else
718         session_reset_active_clients(se, 0);
719     
720     session_enter(se);
721     se->settings_modified = 0;
722     session_clear_set(se, sort_field, increasing);
723     relevance_destroy(&se->relevance);
724
725     live_channels = select_targets(se, filter);
726     if (!live_channels)
727     {
728         session_leave(se);
729         return PAZPAR2_NO_TARGETS;
730     }
731
732     yaz_gettimeofday(&tval);
733     
734     tval.tv_sec += 5;
735
736     facet_limits = facet_limits_create(limit);
737     if (!facet_limits)
738     {
739         *addinfo = "limit";
740         session_leave(se);
741         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
742     }
743
744     l0 = se->clients_active;
745     se->clients_active = 0;
746     session_leave(se);
747
748     for (l = l0; l; l = l->next)
749     {
750         int parse_ret;
751         struct client *cl = l->client;
752
753         if (prepare_map(se, client_get_database(cl)) < 0)
754             continue;
755
756         parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
757                                        maxrecs, se->service->ccl_bibset);
758         if (parse_ret == -1)
759             no_failed_query++;
760         else if (parse_ret == -2)
761             no_failed_limit++;
762         else
763         {
764             int r =
765                 client_prep_connection(cl, se->service->z3950_operation_timeout,
766                                        se->service->z3950_session_timeout,
767                                        se->service->server->iochan_man,
768                                        &tval);
769             if (parse_ret == 1 && r == 2)
770             {
771                 session_log(se, YLOG_LOG, "client %s REUSE result", client_get_id(cl));
772                 client_reingest(cl);
773             }
774             else if (r)
775             {
776                 session_log(se, YLOG_LOG, "client %s NEW search", client_get_id(cl));
777                 client_start_search(cl);
778             }
779             no_working++;
780         }
781     }
782     facet_limits_destroy(facet_limits);
783     session_reset_active_clients(se, l0);
784
785     if (no_working == 0)
786     {
787         if (no_failed_query > 0)
788         {
789             *addinfo = "query";
790             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
791         }
792         else if (no_failed_limit > 0)
793         {
794             *addinfo = "limit";
795             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
796         }
797         else
798             return PAZPAR2_NO_TARGETS;
799     }
800     session_log(se, YLOG_LOG, "session_start_search done");
801     return PAZPAR2_NO_ERROR;
802 }
803
804 // Creates a new session_database object for a database
805 static void session_init_databases_fun(void *context, struct database *db)
806 {
807     struct session *se = (struct session *) context;
808     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
809     int i;
810
811     new->database = db;
812     
813     new->map = 0;
814     assert(db->settings);
815     new->settings = nmem_malloc(se->session_nmem,
816                                 sizeof(struct settings *) * db->num_settings);
817     new->num_settings = db->num_settings;
818     for (i = 0; i < db->num_settings; i++)
819     {
820         struct setting *setting = db->settings[i];
821         new->settings[i] = setting;
822     }
823     new->next = se->databases;
824     se->databases = new;
825 }
826
827 // Doesn't free memory associated with sdb -- nmem takes care of that
828 static void session_database_destroy(struct session_database *sdb)
829 {
830     sdb->map = 0;
831 }
832
833 // Initialize session_database list -- this represents this session's view
834 // of the database list -- subject to modification by the settings ws command
835 void session_init_databases(struct session *se)
836 {
837     se->databases = 0;
838     predef_grep_databases(se, se->service, session_init_databases_fun);
839 }
840
841 // Probably session_init_databases_fun should be refactored instead of
842 // called here.
843 static struct session_database *load_session_database(struct session *se, 
844                                                       char *id)
845 {
846     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
847     session_init_databases_fun((void*) se, db);
848
849     // New sdb is head of se->databases list
850     return se->databases;
851 }
852
853 // Find an existing session database. If not found, load it
854 static struct session_database *find_session_database(struct session *se, 
855                                                       char *id)
856 {
857     struct session_database *sdb;
858
859     for (sdb = se->databases; sdb; sdb = sdb->next)
860         if (!strcmp(sdb->database->id, id))
861             return sdb;
862     return load_session_database(se, id);
863 }
864
865 // Apply a session override to a database
866 void session_apply_setting(struct session *se, char *dbname, char *setting,
867                            char *value)
868 {
869     struct session_database *sdb = find_session_database(se, dbname);
870     struct conf_service *service = se->service;
871     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
872     int offset = settings_create_offset(service, setting);
873
874     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
875                           se->session_nmem);
876     new->precedence = 0;
877     new->target = dbname;
878     new->name = setting;
879     new->value = value;
880     new->next = sdb->settings[offset];
881     sdb->settings[offset] = new;
882
883     se->settings_modified = 1;
884
885     // Force later recompute of settings-driven data structures
886     // (happens when a search starts and client connections are prepared)
887     switch (offset)
888     {
889     case PZ_XSLT:
890         if (sdb->map)
891         {
892             sdb->map = 0;
893         }
894         break;
895     }
896 }
897
898 void session_destroy(struct session *se)
899 {
900     struct session_database *sdb;
901     session_log(se, YLOG_DEBUG, "Destroying");
902     session_use(-1);
903     session_remove_cached_clients(se);
904
905     for (sdb = se->databases; sdb; sdb = sdb->next)
906         session_database_destroy(sdb);
907     normalize_cache_destroy(se->normalize_cache);
908     relevance_destroy(&se->relevance);
909     reclist_destroy(se->reclist);
910     if (nmem_total(se->nmem))
911         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
912     if (nmem_total(se->session_nmem))
913         session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
914     nmem_destroy(se->nmem);
915     service_destroy(se->service);
916     yaz_mutex_destroy(&se->session_mutex);
917 }
918
919 size_t session_get_memory_status(struct session *session) {
920     size_t session_nmem;
921     if (session == 0)
922         return 0;
923     session_enter(session);
924     session_nmem = nmem_total(session->nmem);
925     session_leave(session);
926     return session_nmem;
927 }
928
929
930 struct session *new_session(NMEM nmem, struct conf_service *service,
931                             unsigned session_id)
932 {
933     int i;
934     struct session *session = nmem_malloc(nmem, sizeof(*session));
935
936     char tmp_str[50];
937
938     sprintf(tmp_str, "session#%u", session_id);
939
940     session->session_id = session_id;
941     session_log(session, YLOG_DEBUG, "New");
942     session->service = service;
943     session->relevance = 0;
944     session->total_records = 0;
945     session->number_of_warnings_unknown_elements = 0;
946     session->number_of_warnings_unknown_metadata = 0;
947     session->num_termlists = 0;
948     session->reclist = 0;
949     session->clients_active = 0;
950     session->clients_cached = 0;
951     session->settings_modified = 0;
952     session->session_nmem = nmem;
953     session->nmem = nmem_create();
954     session->databases = 0;
955     for (i = 0; i <= SESSION_WATCH_MAX; i++)
956     {
957         session->watchlist[i].data = 0;
958         session->watchlist[i].fun = 0;
959     }
960     session->normalize_cache = normalize_cache_create();
961     session->session_mutex = 0;
962     pazpar2_mutex_create(&session->session_mutex, tmp_str);
963     session_use(1);
964     return session;
965 }
966
967 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
968
969 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
970                                             int *count, NMEM nmem)
971 {
972     struct hitsbytarget *res = 0;
973     struct client_list *l;
974     size_t sz = 0;
975
976     for (l = se->clients_active; l; l = l->next)
977         sz++;
978
979     res = nmem_malloc(nmem, sizeof(*res) * sz);
980     *count = 0;
981     for (l = se->clients_active; l; l = l->next)
982     {
983         struct client *cl = l->client;
984         WRBUF w = wrbuf_alloc();
985         const char *name = session_setting_oneval(client_get_database(cl),
986                                                   PZ_NAME);
987
988         res[*count].id = client_get_id(cl);
989         res[*count].name = *name ? name : "Unknown";
990         res[*count].hits = client_get_hits(cl);
991         res[*count].approximation = client_get_approximation(cl);
992         res[*count].records = client_get_num_records(cl);
993         res[*count].filtered = client_get_num_records_filtered(cl);
994         res[*count].diagnostic =
995             client_get_diagnostic(cl, &res[*count].addinfo);
996         res[*count].state = client_get_state_str(cl);
997         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
998         session_settings_dump(se, client_get_database(cl), w);
999         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1000         wrbuf_rewind(w);
1001         wrbuf_puts(w, "");
1002         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1003         wrbuf_destroy(w);
1004         (*count)++;
1005     }
1006     return res;
1007 }
1008
1009 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1010 {
1011     struct hitsbytarget *p;
1012     session_enter(se);
1013     p = hitsbytarget_nb(se, count, nmem);
1014     session_leave(se);
1015     return p;
1016 }
1017     
1018 struct termlist_score **get_termlist_score(struct session *se,
1019                                            const char *name, int *num)
1020 {
1021     int i;
1022     struct termlist_score **tl = 0;
1023
1024     session_enter(se);
1025     for (i = 0; i < se->num_termlists; i++)
1026         if (!strcmp((const char *) se->termlists[i].name, name))
1027         {
1028             tl = termlist_highscore(se->termlists[i].termlist, num);
1029             break;
1030         }
1031     session_leave(se);
1032     return tl;
1033 }
1034
1035 // Compares two hitsbytarget nodes by hitcount
1036 static int cmp_ht(const void *p1, const void *p2)
1037 {
1038     const struct hitsbytarget *h1 = p1;
1039     const struct hitsbytarget *h2 = p2;
1040     return h2->hits - h1->hits;
1041 }
1042
1043 // Compares two hitsbytarget nodes by hitcount
1044 static int cmp_ht_approx(const void *p1, const void *p2)
1045 {
1046     const struct hitsbytarget *h1 = p1;
1047     const struct hitsbytarget *h2 = p2;
1048     return h2->approximation - h1->approximation;
1049 }
1050
1051 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1052                                NMEM nmem, int version)
1053 {
1054     struct hitsbytarget *ht;
1055     int count, i;
1056
1057     ht = hitsbytarget_nb(se, &count, nmem);
1058     if (version >= 2)
1059         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1060     else
1061         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1062     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1063     {
1064
1065         // do only print terms which have display names
1066     
1067         wrbuf_puts(wrbuf, "<term>\n");
1068
1069         wrbuf_puts(wrbuf, "<id>");
1070         wrbuf_xmlputs(wrbuf, ht[i].id);
1071         wrbuf_puts(wrbuf, "</id>\n");
1072         
1073         wrbuf_puts(wrbuf, "<name>");
1074         if (!ht[i].name || !ht[i].name[0])
1075             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1076         else
1077             wrbuf_xmlputs(wrbuf, ht[i].name);
1078         wrbuf_puts(wrbuf, "</name>\n");
1079         
1080         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1081                      ht[i].hits);
1082
1083         if (version >= 2) {
1084             // Should not print if we know it isn't a approximation.
1085             wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1086             wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1087             wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1088         }
1089
1090         wrbuf_puts(wrbuf, "<state>");
1091         wrbuf_xmlputs(wrbuf, ht[i].state);
1092         wrbuf_puts(wrbuf, "</state>\n");
1093         
1094         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
1095                      ht[i].diagnostic);
1096         wrbuf_puts(wrbuf, "</term>\n");
1097     }
1098     return count;
1099 }
1100
1101 void perform_termlist(struct http_channel *c, struct session *se,
1102                       const char *name, int num, int version)
1103 {
1104     int i, j;
1105     NMEM nmem_tmp = nmem_create();
1106     char **names;
1107     int num_names = 0;
1108
1109     if (!name)
1110         name = "*";
1111
1112     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1113
1114     session_enter(se);
1115
1116     for (j = 0; j < num_names; j++)
1117     {
1118         const char *tname;
1119         int must_generate_empty = 1; /* bug 5350 */
1120
1121         for (i = 0; i < se->num_termlists; i++)
1122         {
1123             tname = se->termlists[i].name;
1124             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1125             {
1126                 struct termlist_score **p = 0;
1127                 int len;
1128
1129                 wrbuf_puts(c->wrbuf, "<list name=\"");
1130                 wrbuf_xmlputs(c->wrbuf, tname);
1131                 wrbuf_puts(c->wrbuf, "\">\n");
1132                 must_generate_empty = 0;
1133
1134                 p = termlist_highscore(se->termlists[i].termlist, &len);
1135                 if (p)
1136                 {
1137                     int i;
1138                     for (i = 0; i < len && i < num; i++)
1139                     {
1140                         // prevent sending empty term elements
1141                         if (!p[i]->display_term || !p[i]->display_term[0])
1142                             continue;
1143                         
1144                         wrbuf_puts(c->wrbuf, "<term>");
1145                         wrbuf_puts(c->wrbuf, "<name>");
1146                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1147                         wrbuf_puts(c->wrbuf, "</name>");
1148                         
1149                         wrbuf_printf(c->wrbuf, 
1150                                      "<frequency>%d</frequency>", 
1151                                      p[i]->frequency);
1152                         wrbuf_puts(c->wrbuf, "</term>\n");
1153                     }
1154                 }
1155                 wrbuf_puts(c->wrbuf, "</list>\n");
1156             }
1157         }
1158         tname = "xtargets";
1159         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1160         {
1161             wrbuf_puts(c->wrbuf, "<list name=\"");
1162             wrbuf_xmlputs(c->wrbuf, tname);
1163             wrbuf_puts(c->wrbuf, "\">\n");
1164
1165             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1166             wrbuf_puts(c->wrbuf, "</list>\n");
1167             must_generate_empty = 0;
1168         }
1169         if (must_generate_empty)
1170         {
1171             wrbuf_puts(c->wrbuf, "<list name=\"");
1172             wrbuf_xmlputs(c->wrbuf, names[j]);
1173             wrbuf_puts(c->wrbuf, "\"/>\n");
1174         }
1175     }
1176     session_leave(se);
1177     nmem_destroy(nmem_tmp);
1178 }
1179
1180 #ifdef MISSING_HEADERS
1181 void report_nmem_stats(void)
1182 {
1183     size_t in_use, is_free;
1184
1185     nmem_get_memory_in_use(&in_use);
1186     nmem_get_memory_free(&is_free);
1187
1188     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1189             (long) in_use, (long) is_free);
1190 }
1191 #endif
1192
1193 struct record_cluster *show_single_start(struct session *se, const char *id,
1194                                          struct record_cluster **prev_r,
1195                                          struct record_cluster **next_r)
1196 {
1197     struct record_cluster *r = 0;
1198
1199     session_enter(se);
1200     *prev_r = 0;
1201     *next_r = 0;
1202     if (se->reclist)
1203     {
1204         reclist_enter(se->reclist);
1205         while ((r = reclist_read_record(se->reclist)))
1206         {
1207             if (!strcmp(r->recid, id))
1208             {
1209                 *next_r = reclist_read_record(se->reclist);
1210                 break;
1211             }
1212             *prev_r = r;
1213         }
1214         reclist_leave(se->reclist);
1215     }
1216     if (!r)
1217         session_leave(se);
1218     return r;
1219 }
1220
1221 void show_single_stop(struct session *se, struct record_cluster *rec)
1222 {
1223     session_leave(se);
1224 }
1225
1226 struct record_cluster **show_range_start(struct session *se,
1227                                          struct reclist_sortparms *sp, 
1228                                          int start, int *num, int *total, Odr_int *sumhits, Odr_int *approx_hits)
1229 {
1230     struct record_cluster **recs;
1231     struct reclist_sortparms *spp;
1232     int i;
1233 #if USE_TIMING    
1234     yaz_timing_t t = yaz_timing_create();
1235 #endif
1236     session_enter(se);
1237     recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1238     if (!se->relevance)
1239     {
1240         *num = 0;
1241         *total = 0;
1242         *sumhits = 0;        
1243         *approx_hits = 0;
1244         recs = 0;
1245     }
1246     else
1247     {
1248         struct client_list *l;
1249         
1250         for (spp = sp; spp; spp = spp->next)
1251             if (spp->type == Metadata_sortkey_relevance)
1252             {
1253                 relevance_prepare_read(se->relevance, se->reclist);
1254                 break;
1255             }
1256         reclist_sort(se->reclist, sp);
1257         
1258         reclist_enter(se->reclist);
1259         *total = reclist_get_num_records(se->reclist);
1260
1261         *sumhits = 0;
1262         *approx_hits = 0;
1263         for (l = se->clients_active; l; l = l->next) {
1264             *sumhits += client_get_hits(l->client);
1265             *approx_hits += client_get_approximation(l->client);
1266         }
1267         for (i = 0; i < start; i++)
1268             if (!reclist_read_record(se->reclist))
1269             {
1270                 *num = 0;
1271                 recs = 0;
1272                 break;
1273             }
1274         
1275         for (i = 0; i < *num; i++)
1276         {
1277             struct record_cluster *r = reclist_read_record(se->reclist);
1278             if (!r)
1279             {
1280                 *num = i;
1281                 break;
1282             }
1283             recs[i] = r;
1284         }
1285         reclist_leave(se->reclist);
1286     }
1287 #if USE_TIMING
1288     yaz_timing_stop(t);
1289     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1290             yaz_timing_get_real(t), yaz_timing_get_user(t),
1291             yaz_timing_get_sys(t));
1292     yaz_timing_destroy(&t);
1293 #endif
1294     return recs;
1295 }
1296
1297 void show_range_stop(struct session *se, struct record_cluster **recs)
1298 {
1299     session_leave(se);
1300 }
1301
1302 void statistics(struct session *se, struct statistics *stat)
1303 {
1304     struct client_list *l;
1305     int count = 0;
1306
1307     memset(stat, 0, sizeof(*stat));
1308     stat->num_hits = 0;
1309     for (l = se->clients_active; l; l = l->next)
1310     {
1311         struct client *cl = l->client;
1312         if (!client_get_connection(cl))
1313             stat->num_no_connection++;
1314         stat->num_hits += client_get_hits(cl);
1315         switch (client_get_state(cl))
1316         {
1317         case Client_Connecting: stat->num_connecting++; break;
1318         case Client_Working: stat->num_working++; break;
1319         case Client_Idle: stat->num_idle++; break;
1320         case Client_Failed: stat->num_failed++; break;
1321         case Client_Error: stat->num_error++; break;
1322         default: break;
1323         }
1324         count++;
1325     }
1326     stat->num_records = se->total_records;
1327
1328     stat->num_clients = count;
1329 }
1330
1331 static struct record_metadata *record_metadata_init(
1332     NMEM nmem, const char *value, enum conf_metadata_type type,
1333     struct _xmlAttr *attr)
1334 {
1335     struct record_metadata *rec_md = record_metadata_create(nmem);
1336     struct record_metadata_attr **attrp = &rec_md->attributes;
1337     
1338     for (; attr; attr = attr->next)
1339     {
1340         if (attr->children && attr->children->content)
1341         {
1342             if (strcmp((const char *) attr->name, "type"))
1343             {  /* skip the "type" attribute.. Its value is already part of
1344                   the element in output (md-%s) and so repeating it here
1345                   is redundant */
1346                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1347                 (*attrp)->name =
1348                     nmem_strdup(nmem, (const char *) attr->name);
1349                 (*attrp)->value =
1350                     nmem_strdup(nmem, (const char *) attr->children->content);
1351                 attrp = &(*attrp)->next;
1352             }
1353         }
1354     }
1355     *attrp = 0;
1356
1357     if (type == Metadata_type_generic)
1358     {
1359         char *p = nmem_strdup(nmem, value);
1360
1361         p = normalize7bit_generic(p, " ,/.:([");
1362         
1363         rec_md->data.text.disp = p;
1364         rec_md->data.text.sort = 0;
1365     }
1366     else if (type == Metadata_type_year || type == Metadata_type_date)
1367     {
1368         int first, last;
1369         int longdate = 0;
1370
1371         if (type == Metadata_type_date)
1372             longdate = 1;
1373         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1374             return 0;
1375
1376         rec_md->data.number.min = first;
1377         rec_md->data.number.max = last;
1378     }
1379     else
1380         return 0;
1381     return rec_md;
1382 }
1383
1384 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1385                                  struct conf_service *service, WRBUF norm_wr)
1386 {
1387     xmlNode *n;
1388     int no_found = 0;
1389     for (n = root->children; n; n = n->next)
1390     {
1391         if (n->type != XML_ELEMENT_NODE)
1392             continue;
1393         if (!strcmp((const char *) n->name, "metadata"))
1394         {
1395             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1396             if (type == NULL) {
1397                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1398             }
1399             else if (!strcmp(name, (const char *) type))
1400             {
1401                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1402                 if (value)
1403                 {
1404                     const char *norm_str;
1405                     pp2_charset_token_t prt =
1406                         pp2_charset_token_create(service->charsets, "mergekey");
1407                     
1408                     pp2_charset_token_first(prt, (const char *) value, 0);
1409                     if (wrbuf_len(norm_wr) > 0)
1410                         wrbuf_puts(norm_wr, " ");
1411                     wrbuf_puts(norm_wr, name);
1412                     while ((norm_str =
1413                             pp2_charset_token_next(prt)))
1414                     {
1415                         if (*norm_str)
1416                         {
1417                             wrbuf_puts(norm_wr, " ");
1418                             wrbuf_puts(norm_wr, norm_str);
1419                         }
1420                     }
1421                     xmlFree(value);
1422                     pp2_charset_token_destroy(prt);
1423                     no_found++;
1424                 }
1425             }
1426             xmlFree(type);
1427         }
1428     }
1429     return no_found;
1430 }
1431
1432 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1433                                 struct conf_service *service, NMEM nmem)
1434 {
1435     char *mergekey_norm = 0;
1436     xmlNode *root = xmlDocGetRootElement(doc);
1437     WRBUF norm_wr = wrbuf_alloc();
1438
1439     /* consider mergekey from XSL first */
1440     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1441     if (mergekey)
1442     {
1443         const char *norm_str;
1444         pp2_charset_token_t prt =
1445             pp2_charset_token_create(service->charsets, "mergekey");
1446
1447         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1448         while ((norm_str = pp2_charset_token_next(prt)))
1449         {
1450             if (*norm_str)
1451             {
1452                 if (wrbuf_len(norm_wr))
1453                     wrbuf_puts(norm_wr, " ");
1454                 wrbuf_puts(norm_wr, norm_str);
1455             }
1456         }
1457         pp2_charset_token_destroy(prt);
1458         xmlFree(mergekey);
1459     }
1460     else
1461     {
1462         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1463         int field_id;
1464         for (field_id = 0; field_id < service->num_metadata; field_id++)
1465         {
1466             struct conf_metadata *ser_md = &service->metadata[field_id];
1467             if (ser_md->mergekey != Metadata_mergekey_no)
1468             {
1469                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1470                                               service, norm_wr);
1471                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1472                 {
1473                     /* no mergekey on this one and it is required.. 
1474                        Generate unique key instead */
1475                     wrbuf_rewind(norm_wr);
1476                     break;
1477                 }
1478             }
1479         }
1480     }
1481
1482     /* generate unique key if none is not generated already or is empty */
1483     if (wrbuf_len(norm_wr) == 0)
1484     {
1485         wrbuf_printf(norm_wr, "position: %s-%d",
1486                      client_get_id(cl), record_no);
1487     }
1488     else
1489     {
1490         const char *lead = "content: ";
1491         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1492     }
1493     if (wrbuf_len(norm_wr) > 0)
1494         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1495     wrbuf_destroy(norm_wr);
1496     return mergekey_norm;
1497 }
1498
1499 /** \brief see if metadata for pz:recordfilter exists 
1500     \param root xml root element of normalized record
1501     \param sdb session database for client
1502     \retval 0 if there is no metadata for pz:recordfilter
1503     \retval 1 if there is metadata for pz:recordfilter
1504
1505     If there is no pz:recordfilter defined, this function returns 1
1506     as well.
1507 */
1508     
1509 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1510 {
1511     int match = 0;
1512     xmlNode *n;
1513     const char *s;
1514     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1515
1516     if (!s || !*s)
1517         return 1;
1518
1519     for (n = root->children; n; n = n->next)
1520     {
1521         if (n->type != XML_ELEMENT_NODE)
1522             continue;
1523         if (!strcmp((const char *) n->name, "metadata"))
1524         {
1525             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1526             if (type)
1527             {
1528                 size_t len;
1529                 int substring;
1530                 const char *eq;
1531
1532                 if ((eq = strchr(s, '=')))
1533                     substring = 0;
1534                 else if ((eq = strchr(s, '~')))
1535                     substring = 1;
1536                 if (eq)
1537                     len = eq - s;
1538                 else
1539                     len = strlen(s);
1540                 if (len == strlen((const char *)type) &&
1541                     !memcmp((const char *) type, s, len))
1542                 {
1543                     xmlChar *value = xmlNodeGetContent(n);
1544                     if (value && *value)
1545                     {
1546                         if (!eq ||
1547                             (substring && strstr((const char *) value, eq+1)) ||
1548                             (!substring && !strcmp((const char *) value, eq + 1)))
1549                             match = 1;
1550                     }
1551                     xmlFree(value);
1552                 }
1553                 xmlFree(type);
1554             }
1555         }
1556     }
1557     return match;
1558 }
1559
1560
1561 static int ingest_to_cluster(struct client *cl,
1562                              xmlDoc *xdoc,
1563                              xmlNode *root,
1564                              int record_no,
1565                              const char *mergekey_norm);
1566
1567 /** \brief ingest XML record
1568     \param cl client holds the result set for record
1569     \param rec record buffer (0 terminated)
1570     \param record_no record position (1, 2, ..)
1571     \param nmem working NMEM
1572     \retval 0 OK
1573     \retval -1 failure
1574     \retval -2 Filtered
1575 */
1576 int ingest_record(struct client *cl, const char *rec,
1577                   int record_no, NMEM nmem)
1578 {
1579     struct session *se = client_get_session(cl);
1580     int ret = 0;
1581     struct session_database *sdb = client_get_database(cl);
1582     struct conf_service *service = se->service;
1583     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1584     xmlNode *root;
1585     const char *mergekey_norm;
1586     
1587     if (!xdoc)
1588         return -1;
1589     
1590     root = xmlDocGetRootElement(xdoc);
1591     
1592     if (!check_record_filter(root, sdb))
1593     {
1594         session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1595         xmlFreeDoc(xdoc);
1596         return -2;
1597     }
1598     
1599     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1600     if (!mergekey_norm)
1601     {
1602         session_log(se, YLOG_WARN, "Got no mergekey");
1603         xmlFreeDoc(xdoc);
1604         return -1;
1605     }
1606     session_enter(se);
1607     if (client_get_session(cl) == se)
1608         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1609     session_leave(se);
1610     
1611     xmlFreeDoc(xdoc);
1612     return ret;
1613 }
1614
1615 // Skip record on non-zero
1616 static int check_limit_local(struct client *cl,
1617                              struct record *record,
1618                              int record_no)
1619 {
1620     int skip_record = 0;
1621     struct session *se = client_get_session(cl);
1622     struct conf_service *service = se->service;
1623     NMEM nmem_tmp = nmem_create();
1624     struct session_database *sdb = client_get_database(cl);
1625     int l = 0;
1626     while (!skip_record)
1627     {
1628         struct conf_metadata *ser_md = 0;
1629         struct record_metadata *rec_md = 0;
1630         int md_field_id;
1631         char **values = 0;
1632         int i, num_v = 0;
1633         
1634         const char *name = client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v, &values);
1635         if (!name)
1636             break;
1637         
1638         md_field_id = conf_service_metadata_field_id(service, name);
1639         if (md_field_id < 0)
1640         {
1641             skip_record = 1;
1642             break;
1643         }
1644         ser_md = &service->metadata[md_field_id];
1645         rec_md = record->metadata[md_field_id];
1646         yaz_log(YLOG_DEBUG, "check limit local %s", name);
1647         for (i = 0; i < num_v; )
1648         {
1649             if (rec_md)
1650             {
1651                 if (ser_md->type == Metadata_type_year 
1652                     || ser_md->type == Metadata_type_date)
1653                 {
1654                     int y = atoi(values[i]);
1655                     if (y >= rec_md->data.number.min 
1656                         && y <= rec_md->data.number.max)
1657                         break;
1658                 }
1659                 else
1660                 {
1661                     yaz_log(YLOG_DEBUG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1662                     if (!strcmp(rec_md->data.text.disp, values[i]))
1663                     {
1664                         // Value equals, should not be filtered.
1665                         break;
1666                     }
1667                 }
1668                 rec_md = rec_md->next;
1669             }
1670             else
1671             {
1672                 rec_md = record->metadata[md_field_id];
1673                 i++;
1674             }
1675         }
1676         // At end , not match
1677         if (i == num_v)
1678         {
1679             skip_record = 1;
1680             break;
1681         }
1682     }
1683     nmem_destroy(nmem_tmp);
1684     return skip_record;
1685 }
1686                              
1687 static int ingest_to_cluster(struct client *cl,
1688                              xmlDoc *xdoc,
1689                              xmlNode *root,
1690                              int record_no,
1691                              const char *mergekey_norm)
1692 {
1693     xmlNode *n;
1694     xmlChar *type = 0;
1695     xmlChar *value = 0;
1696     struct session *se = client_get_session(cl);
1697     struct conf_service *service = se->service;
1698     int term_factor = 1;
1699     struct record_cluster *cluster;
1700     struct session_database *sdb = client_get_database(cl);
1701     struct record *record = record_create(se->nmem, 
1702                                           service->num_metadata,
1703                                           service->num_sortkeys, cl,
1704                                           record_no);
1705
1706     for (n = root->children; n; n = n->next)
1707     {
1708         if (type)
1709             xmlFree(type);
1710         if (value)
1711             xmlFree(value);
1712         type = value = 0;
1713         
1714         if (n->type != XML_ELEMENT_NODE)
1715             continue;
1716         if (!strcmp((const char *) n->name, "metadata"))
1717         {
1718             struct conf_metadata *ser_md = 0;
1719             struct record_metadata **wheretoput = 0;
1720             struct record_metadata *rec_md = 0;
1721             int md_field_id = -1;
1722             
1723             type = xmlGetProp(n, (xmlChar *) "type");
1724             value = xmlNodeListGetString(xdoc, n->children, 1);
1725             
1726             if (!type || !value || !*value)
1727                 continue;
1728             
1729             md_field_id 
1730                 = conf_service_metadata_field_id(service, (const char *) type);
1731             if (md_field_id < 0)
1732             {
1733                 if (se->number_of_warnings_unknown_metadata == 0)
1734                 {
1735                     session_log(se, YLOG_WARN, 
1736                             "Ignoring unknown metadata element: %s", type);
1737                 }
1738                 se->number_of_warnings_unknown_metadata++;
1739                 continue;
1740             }
1741            
1742             ser_md = &service->metadata[md_field_id];
1743
1744             // non-merged metadata
1745             rec_md = record_metadata_init(se->nmem, (const char *) value,
1746                                           ser_md->type, n->properties);
1747             if (!rec_md)
1748             {
1749                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1750                             "for element '%s'", value, type);
1751                 continue;
1752             }
1753             wheretoput = &record->metadata[md_field_id];
1754             while (*wheretoput)
1755                 wheretoput = &(*wheretoput)->next;
1756             *wheretoput = rec_md;
1757         }
1758     }
1759
1760     if (check_limit_local(cl, record, record_no))
1761     {
1762         session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1763                     record_no, sdb->database->id);
1764         if (type)
1765             xmlFree(type);
1766         if (value)
1767             xmlFree(value);
1768         return -2;
1769     }
1770     cluster = reclist_insert(se->reclist, service, record,
1771                              mergekey_norm, &se->total_merged);
1772     if (!cluster)
1773         return -1;
1774
1775     {
1776         const char *use_term_factor_str =
1777             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1778         if (use_term_factor_str && use_term_factor_str[0] == '1')
1779         {
1780             int maxrecs = client_get_maxrecs(cl);
1781             int hits = (int) client_get_hits(cl);
1782             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1783             assert(term_factor >= 1);
1784             yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1785         }
1786     }
1787
1788     if (global_parameters.dump_records)
1789         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1790                     sdb->database->id, record_no);
1791
1792
1793     relevance_newrec(se->relevance, cluster);
1794     
1795     // now parsing XML record and adding data to cluster or record metadata
1796     for (n = root->children; n; n = n->next)
1797     {
1798         pp2_charset_token_t prt;
1799         if (type)
1800             xmlFree(type);
1801         if (value)
1802             xmlFree(value);
1803         type = value = 0;
1804         
1805         if (n->type != XML_ELEMENT_NODE)
1806             continue;
1807         if (!strcmp((const char *) n->name, "metadata"))
1808         {
1809             struct conf_metadata *ser_md = 0;
1810             struct conf_sortkey *ser_sk = 0;
1811             struct record_metadata **wheretoput = 0;
1812             struct record_metadata *rec_md = 0;
1813             int md_field_id = -1;
1814             int sk_field_id = -1;
1815             const char *rank;
1816             xmlChar *xml_rank;
1817             
1818             type = xmlGetProp(n, (xmlChar *) "type");
1819             value = xmlNodeListGetString(xdoc, n->children, 1);
1820             
1821             if (!type || !value || !*value)
1822                 continue;
1823             
1824             md_field_id 
1825                 = conf_service_metadata_field_id(service, (const char *) type);
1826             if (md_field_id < 0)
1827                 continue;
1828             
1829             ser_md = &service->metadata[md_field_id];
1830
1831             if (ser_md->sortkey_offset >= 0)
1832             {
1833                 sk_field_id = ser_md->sortkey_offset;
1834                 ser_sk = &service->sortkeys[sk_field_id];
1835             }
1836
1837             // merged metadata
1838             rec_md = record_metadata_init(se->nmem, (const char *) value,
1839                                           ser_md->type, 0);
1840             if (!rec_md)
1841                 continue;
1842
1843             xml_rank = xmlGetProp(n, (xmlChar *) "rank");
1844             rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
1845
1846             wheretoput = &cluster->metadata[md_field_id];
1847
1848             // and polulate with data:
1849             // assign cluster or record based on merge action
1850             if (ser_md->merge == Metadata_merge_unique)
1851             {
1852                 while (*wheretoput)
1853                 {
1854                     if (!strcmp((const char *) (*wheretoput)->data.text.disp, 
1855                                 rec_md->data.text.disp))
1856                         break;
1857                     wheretoput = &(*wheretoput)->next;
1858                 }
1859                 if (!*wheretoput)
1860                     *wheretoput = rec_md;
1861             }
1862             else if (ser_md->merge == Metadata_merge_longest)
1863             {
1864                 if (!*wheretoput 
1865                     || strlen(rec_md->data.text.disp) 
1866                     > strlen((*wheretoput)->data.text.disp))
1867                 {
1868                     *wheretoput = rec_md;
1869                     if (ser_sk)
1870                     {
1871                         const char *sort_str = 0;
1872                         int skip_article = 
1873                             ser_sk->type == Metadata_sortkey_skiparticle;
1874
1875                         if (!cluster->sortkeys[sk_field_id])
1876                             cluster->sortkeys[sk_field_id] = 
1877                                 nmem_malloc(se->nmem, 
1878                                             sizeof(union data_types));
1879                          
1880                         prt =
1881                             pp2_charset_token_create(service->charsets, "sort");
1882
1883                         pp2_charset_token_first(prt, rec_md->data.text.disp,
1884                                                 skip_article);
1885
1886                         pp2_charset_token_next(prt);
1887                          
1888                         sort_str = pp2_get_sort(prt);
1889                          
1890                         cluster->sortkeys[sk_field_id]->text.disp = 
1891                             rec_md->data.text.disp;
1892                         if (!sort_str)
1893                         {
1894                             sort_str = rec_md->data.text.disp;
1895                             session_log(se, YLOG_WARN, 
1896                                     "Could not make sortkey. Bug #1858");
1897                         }
1898                         cluster->sortkeys[sk_field_id]->text.sort = 
1899                             nmem_strdup(se->nmem, sort_str);
1900                         pp2_charset_token_destroy(prt);
1901                     }
1902                 }
1903             }
1904             else if (ser_md->merge == Metadata_merge_all)
1905             {
1906                 while (*wheretoput)
1907                     wheretoput = &(*wheretoput)->next;
1908                 *wheretoput = rec_md;
1909             }
1910             else if (ser_md->merge == Metadata_merge_range)
1911             {
1912                 if (!*wheretoput)
1913                 {
1914                     *wheretoput = rec_md;
1915                     if (ser_sk)
1916                         cluster->sortkeys[sk_field_id] 
1917                             = &rec_md->data;
1918                 }
1919                 else
1920                 {
1921                     int this_min = rec_md->data.number.min;
1922                     int this_max = rec_md->data.number.max;
1923                     if (this_min < (*wheretoput)->data.number.min)
1924                         (*wheretoput)->data.number.min = this_min;
1925                     if (this_max > (*wheretoput)->data.number.max)
1926                         (*wheretoput)->data.number.max = this_max;
1927                 }
1928             }
1929
1930             // ranking of _all_ fields enabled ... 
1931             if (rank)
1932             {
1933                 relevance_countwords(se->relevance, cluster, 
1934                                      (char *) value, rank, ser_md->name);
1935             }
1936
1937             // construct facets ... unless the client already has reported them
1938             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1939             {
1940                 if (ser_md->type == Metadata_type_year)
1941                 {
1942                     char year[64];
1943                     sprintf(year, "%d", rec_md->data.number.max);
1944
1945                     add_facet(se, (char *) type, year, term_factor);
1946                     if (rec_md->data.number.max != rec_md->data.number.min)
1947                     {
1948                         sprintf(year, "%d", rec_md->data.number.min);
1949                         add_facet(se, (char *) type, year, term_factor);
1950                     }
1951                 }
1952                 else
1953                     add_facet(se, (char *) type, (char *) value, term_factor);
1954             }
1955
1956             // cleaning up
1957             if (xml_rank)
1958                 xmlFree(xml_rank);
1959             xmlFree(type);
1960             xmlFree(value);
1961             type = value = 0;
1962         }
1963         else
1964         {
1965             if (se->number_of_warnings_unknown_elements == 0)
1966                 session_log(se, YLOG_WARN,
1967                         "Unexpected element in internal record: %s", n->name);
1968             se->number_of_warnings_unknown_elements++;
1969         }
1970     }
1971     if (type)
1972         xmlFree(type);
1973     if (value)
1974         xmlFree(value);
1975
1976     relevance_donerecord(se->relevance, cluster);
1977     se->total_records++;
1978
1979     return 0;
1980 }
1981
1982 void session_log(struct session *s, int level, const char *fmt, ...)
1983 {
1984     char buf[1024];
1985     va_list ap;
1986     va_start(ap, fmt);
1987
1988     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1989     yaz_log(level, "Session %u: %s", s->session_id, buf);
1990
1991     va_end(ap);
1992 }
1993
1994 /*
1995  * Local variables:
1996  * c-basic-offset: 4
1997  * c-file-style: "Stroustrup"
1998  * indent-tabs-mode: nil
1999  * End:
2000  * vim: shiftwidth=4 tabstop=8 expandtab
2001  */
2002