3fb79b9c9f084ad68886220187b174841defb5a7
[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     const char *s;
412
413     if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
414         (s = session_setting_oneval(sdb, PZ_XSLT)))        
415     {
416         char auto_stylesheet[256];
417
418         if (!strcmp(s, "auto"))
419         {
420             const char *request_syntax = session_setting_oneval(
421                 sdb, PZ_REQUESTSYNTAX);
422             if (request_syntax)
423             {
424                 char *cp;
425                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
426                              "%s.xsl", request_syntax);
427                 for (cp = auto_stylesheet; *cp; cp++)
428                 {
429                     /* deliberately only consider ASCII */
430                     if (*cp > 32 && *cp < 127)
431                         *cp = tolower(*cp);
432                 }
433                 s = auto_stylesheet;
434             }
435             else
436             {
437                 session_log(se, YLOG_WARN,
438                             "No pz:requestsyntax for auto stylesheet");
439             }
440         }
441         sdb->map = normalize_cache_get(se->normalize_cache,
442                                        se->service, s);
443         if (!sdb->map)
444             return -1;
445     }
446     return 0;
447 }
448
449 // called if watch should be removed because http_channel is to be destroyed
450 static void session_watch_cancel(void *data, struct http_channel *c,
451                                  void *data2)
452 {
453     struct session_watchentry *ent = data;
454
455     ent->fun = 0;
456     ent->data = 0;
457     ent->obs = 0;
458 }
459
460 // set watch. Returns 0=OK, -1 if watch is already set
461 int session_set_watch(struct session *s, int what, 
462                       session_watchfun fun, void *data,
463                       struct http_channel *chan)
464 {
465     int ret;
466     session_enter(s);
467     if (s->watchlist[what].fun)
468         ret = -1;
469     else
470     {
471         
472         s->watchlist[what].fun = fun;
473         s->watchlist[what].data = data;
474         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
475                                                    session_watch_cancel);
476         ret = 0;
477     }
478     session_leave(s);
479     return ret;
480 }
481
482 void session_alert_watch(struct session *s, int what)
483 {
484     assert(s);
485     session_enter(s);
486     if (s->watchlist[what].fun)
487     {
488         /* our watch is no longer associated with http_channel */
489         void *data;
490         session_watchfun fun;
491
492         http_remove_observer(s->watchlist[what].obs);
493         fun  = s->watchlist[what].fun;
494         data = s->watchlist[what].data;
495
496         /* reset watch before fun is invoked - in case fun wants to set
497            it again */
498         s->watchlist[what].fun = 0;
499         s->watchlist[what].data = 0;
500         s->watchlist[what].obs = 0;
501
502         session_leave(s);
503         session_log(s, YLOG_DEBUG,
504                     "Alert Watch: %d calling function: %p", what, fun);
505         fun(data);
506     }
507     else
508         session_leave(s);
509 }
510
511 //callback for grep_databases
512 static void select_targets_callback(struct session *se,
513                                     struct session_database *db)
514 {
515     struct client *cl;
516     struct client_list *l;
517
518     for (l = se->clients_cached; l; l = l->next)
519         if (client_get_database(l->client) == db)
520             break;
521
522     if (l)
523         cl = l->client;
524     else
525     {
526         cl = client_create(db->database->id);
527         client_set_database(cl, db);
528
529         l = xmalloc(sizeof(*l));
530         l->client = cl;
531         l->next = se->clients_cached;
532         se->clients_cached = l;
533     }
534     /* set session always. If may be 0 if client is not active */
535     client_set_session(cl, se);
536
537     l = xmalloc(sizeof(*l));
538     l->client = cl;
539     l->next = se->clients_active;
540     se->clients_active = l;
541 }
542
543 static void session_reset_active_clients(struct session *se,
544                                          struct client_list *new_list)
545 {
546     struct client_list *l;
547
548     session_enter(se);
549     l = se->clients_active;
550     se->clients_active = new_list;
551     session_leave(se);
552
553     while (l)
554     {
555         struct client_list *l_next = l->next;
556
557         client_lock(l->client); 
558         client_set_session(l->client, 0); /* mark client inactive */
559         client_unlock(l->client);
560
561         xfree(l);
562         l = l_next;
563     }
564 }
565
566 static void session_remove_cached_clients(struct session *se)
567 {
568     struct client_list *l;
569
570     session_reset_active_clients(se, 0);
571
572     session_enter(se);
573     l = se->clients_cached;
574     se->clients_cached = 0;
575     session_leave(se);
576
577     while (l)
578     {
579         struct client_list *l_next = l->next;
580         client_lock(l->client);
581         client_set_session(l->client, 0);
582         client_set_database(l->client, 0);
583         client_unlock(l->client);
584         client_destroy(l->client);
585         xfree(l);
586         l = l_next;
587     }
588 }
589
590 // Associates a set of clients with a session;
591 // Note: Session-databases represent databases with per-session 
592 // setting overrides
593 static int select_targets(struct session *se, const char *filter)
594 {
595     return session_grep_databases(se, filter, select_targets_callback);
596 }
597
598 int session_active_clients(struct session *s)
599 {
600     struct client_list *l;
601     int res = 0;
602
603     for (l = s->clients_active; l; l = l->next)
604         if (client_is_active(l->client))
605             res++;
606
607     return res;
608 }
609
610 int session_is_preferred_clients_ready(struct session *s)
611 {
612     struct client_list *l;
613     int res = 0;
614
615     for (l = s->clients_active; l; l = l->next)
616         if (client_is_active_preferred(l->client))
617             res++;
618     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
619     return res == 0;
620 }
621
622 void session_sort(struct session *se, const char *field, int increasing)
623 {
624     struct session_sorted_results *sr;
625     struct client_list *l;
626
627     session_enter(se);
628
629     /* see if we already have sorted for this critieria */
630     for (sr = se->sorted_results; sr; sr = sr->next)
631     {
632         if (!strcmp(field, sr->field) && increasing == sr->increasing)
633             break;
634     }
635     if (sr)
636     {
637         yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
638                 field, increasing);
639         session_leave(se);
640         return;
641     }
642     yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
643             field, increasing);
644     sr = nmem_malloc(se->nmem, sizeof(*sr));
645     sr->field = nmem_strdup(se->nmem, field);
646     sr->increasing = increasing;
647     sr->next = se->sorted_results;
648     se->sorted_results = sr;
649     
650     for (l = se->clients_active; l; l = l->next)
651     {
652         struct client *cl = l->client;
653         if (client_get_state(cl) == Client_Connecting ||
654             client_get_state(cl) == Client_Idle ||
655             client_get_state(cl) == Client_Working)
656             client_start_search(cl);
657     }
658     session_leave(se);
659 }
660
661 enum pazpar2_error_code session_search(struct session *se,
662                                        const char *query,
663                                        const char *startrecs,
664                                        const char *maxrecs,
665                                        const char *filter,
666                                        const char *limit,
667                                        const char **addinfo,
668                                        const char *sort_field, int increasing)
669 {
670     int live_channels = 0;
671     int no_working = 0;
672     int no_failed_query = 0;
673     int no_failed_limit = 0;
674     struct client_list *l, *l0;
675     struct timeval tval;
676     facet_limits_t facet_limits;
677
678     session_log(se, YLOG_DEBUG, "Search");
679
680     *addinfo = 0;
681
682     if (se->settings_modified)
683         session_remove_cached_clients(se);
684     else
685         session_reset_active_clients(se, 0);
686     
687     session_enter(se);
688     reclist_destroy(se->reclist);
689     se->reclist = 0;
690     se->settings_modified = 0;
691     relevance_destroy(&se->relevance);
692     nmem_reset(se->nmem);
693     se->total_records = se->total_merged = 0;
694     se->num_termlists = 0;
695
696     /* reset list of sorted results and clear to relevance search */
697     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
698     se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
699     se->sorted_results->increasing = increasing;
700     se->sorted_results->next = 0;
701     
702     live_channels = select_targets(se, filter);
703     if (!live_channels)
704     {
705         session_leave(se);
706         return PAZPAR2_NO_TARGETS;
707     }
708     se->reclist = reclist_create(se->nmem);
709
710     yaz_gettimeofday(&tval);
711     
712     tval.tv_sec += 5;
713
714     facet_limits = facet_limits_create(limit);
715     if (!facet_limits)
716     {
717         *addinfo = "limit";
718         session_leave(se);
719         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
720     }
721
722     l0 = se->clients_active;
723     se->clients_active = 0;
724     session_leave(se);
725
726     for (l = l0; l; l = l->next)
727     {
728         int parse_ret;
729         struct client *cl = l->client;
730
731         if (prepare_map(se, client_get_database(cl)) < 0)
732             continue;
733
734         parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
735             maxrecs);
736         if (parse_ret == -1)
737             no_failed_query++;
738         else if (parse_ret == -2)
739             no_failed_limit++;
740         else
741         {
742             int r =
743                 client_prep_connection(cl, se->service->z3950_operation_timeout,
744                                        se->service->z3950_session_timeout,
745                                        se->service->server->iochan_man,
746                                        &tval);
747             if (parse_ret == 1 && r == 2)
748             {
749                 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
750                 client_reingest(cl);
751             }
752             else if (r)
753             {
754                 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
755                 client_start_search(cl);
756             }
757             no_working++;
758         }
759     }
760     facet_limits_destroy(facet_limits);
761     session_reset_active_clients(se, l0);
762
763     if (no_working == 0)
764     {
765         if (no_failed_query > 0)
766         {
767             *addinfo = "query";
768             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
769         }
770         else if (no_failed_limit > 0)
771         {
772             *addinfo = "limit";
773             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
774         }
775         else
776             return PAZPAR2_NO_TARGETS;
777     }
778     yaz_log(YLOG_LOG, "session_start_search done");
779     return PAZPAR2_NO_ERROR;
780 }
781
782 // Creates a new session_database object for a database
783 static void session_init_databases_fun(void *context, struct database *db)
784 {
785     struct session *se = (struct session *) context;
786     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
787     int i;
788
789     new->database = db;
790     
791     new->map = 0;
792     assert(db->settings);
793     new->settings = nmem_malloc(se->session_nmem,
794                                 sizeof(struct settings *) * db->num_settings);
795     new->num_settings = db->num_settings;
796     for (i = 0; i < db->num_settings; i++)
797     {
798         struct setting *setting = db->settings[i];
799         new->settings[i] = setting;
800     }
801     new->next = se->databases;
802     se->databases = new;
803 }
804
805 // Doesn't free memory associated with sdb -- nmem takes care of that
806 static void session_database_destroy(struct session_database *sdb)
807 {
808     sdb->map = 0;
809 }
810
811 // Initialize session_database list -- this represents this session's view
812 // of the database list -- subject to modification by the settings ws command
813 void session_init_databases(struct session *se)
814 {
815     se->databases = 0;
816     predef_grep_databases(se, se->service, session_init_databases_fun);
817 }
818
819 // Probably session_init_databases_fun should be refactored instead of
820 // called here.
821 static struct session_database *load_session_database(struct session *se, 
822                                                       char *id)
823 {
824     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
825     session_init_databases_fun((void*) se, db);
826
827     // New sdb is head of se->databases list
828     return se->databases;
829 }
830
831 // Find an existing session database. If not found, load it
832 static struct session_database *find_session_database(struct session *se, 
833                                                       char *id)
834 {
835     struct session_database *sdb;
836
837     for (sdb = se->databases; sdb; sdb = sdb->next)
838         if (!strcmp(sdb->database->id, id))
839             return sdb;
840     return load_session_database(se, id);
841 }
842
843 // Apply a session override to a database
844 void session_apply_setting(struct session *se, char *dbname, char *setting,
845                            char *value)
846 {
847     struct session_database *sdb = find_session_database(se, dbname);
848     struct conf_service *service = se->service;
849     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
850     int offset = settings_create_offset(service, setting);
851
852     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
853                           se->session_nmem);
854     new->precedence = 0;
855     new->target = dbname;
856     new->name = setting;
857     new->value = value;
858     new->next = sdb->settings[offset];
859     sdb->settings[offset] = new;
860
861     se->settings_modified = 1;
862
863     // Force later recompute of settings-driven data structures
864     // (happens when a search starts and client connections are prepared)
865     switch (offset)
866     {
867     case PZ_XSLT:
868         if (sdb->map)
869         {
870             sdb->map = 0;
871         }
872         break;
873     }
874 }
875
876 void session_destroy(struct session *se)
877 {
878     struct session_database *sdb;
879     session_log(se, YLOG_DEBUG, "Destroying");
880     session_use(-1);
881     session_remove_cached_clients(se);
882
883     for (sdb = se->databases; sdb; sdb = sdb->next)
884         session_database_destroy(sdb);
885     normalize_cache_destroy(se->normalize_cache);
886     relevance_destroy(&se->relevance);
887     reclist_destroy(se->reclist);
888     nmem_destroy(se->nmem);
889     service_destroy(se->service);
890     yaz_mutex_destroy(&se->session_mutex);
891 }
892
893 size_t session_get_memory_status(struct session *session) {
894     size_t session_nmem;
895     if (session == 0)
896         return 0;
897     session_enter(session);
898     session_nmem = nmem_total(session->nmem);
899     session_leave(session);
900     return session_nmem;
901 }
902
903
904 struct session *new_session(NMEM nmem, struct conf_service *service,
905                             unsigned session_id)
906 {
907     int i;
908     struct session *session = nmem_malloc(nmem, sizeof(*session));
909
910     char tmp_str[50];
911
912     sprintf(tmp_str, "session#%u", session_id);
913
914     session->session_id = session_id;
915     session_log(session, YLOG_DEBUG, "New");
916     session->service = service;
917     session->relevance = 0;
918     session->total_records = 0;
919     session->number_of_warnings_unknown_elements = 0;
920     session->number_of_warnings_unknown_metadata = 0;
921     session->num_termlists = 0;
922     session->reclist = 0;
923     session->clients_active = 0;
924     session->clients_cached = 0;
925     session->settings_modified = 0;
926     session->session_nmem = nmem;
927     session->nmem = nmem_create();
928     session->databases = 0;
929     for (i = 0; i <= SESSION_WATCH_MAX; i++)
930     {
931         session->watchlist[i].data = 0;
932         session->watchlist[i].fun = 0;
933     }
934     session->normalize_cache = normalize_cache_create();
935     session->session_mutex = 0;
936     pazpar2_mutex_create(&session->session_mutex, tmp_str);
937     session_use(1);
938     return session;
939 }
940
941 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
942
943 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
944                                             int *count, NMEM nmem)
945 {
946     struct hitsbytarget *res = 0;
947     struct client_list *l;
948     size_t sz = 0;
949
950     for (l = se->clients_active; l; l = l->next)
951         sz++;
952
953     res = nmem_malloc(nmem, sizeof(*res) * sz);
954     *count = 0;
955     for (l = se->clients_active; l; l = l->next)
956     {
957         struct client *cl = l->client;
958         WRBUF w = wrbuf_alloc();
959         const char *name = session_setting_oneval(client_get_database(cl),
960                                                   PZ_NAME);
961
962         res[*count].id = client_get_id(cl);
963         res[*count].name = *name ? name : "Unknown";
964         res[*count].hits = client_get_hits(cl);
965         res[*count].approximation = client_get_approximation(cl);
966         res[*count].records = client_get_num_records(cl);
967         res[*count].filtered = client_get_num_records_filtered(cl);
968         res[*count].diagnostic =
969             client_get_diagnostic(cl, &res[*count].addinfo);
970         res[*count].state = client_get_state_str(cl);
971         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
972         session_settings_dump(se, client_get_database(cl), w);
973         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
974         wrbuf_rewind(w);
975         wrbuf_puts(w, "");
976         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
977         wrbuf_destroy(w);
978         (*count)++;
979     }
980     return res;
981 }
982
983 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
984 {
985     struct hitsbytarget *p;
986     session_enter(se);
987     p = hitsbytarget_nb(se, count, nmem);
988     session_leave(se);
989     return p;
990 }
991     
992 struct termlist_score **get_termlist_score(struct session *se,
993                                            const char *name, int *num)
994 {
995     int i;
996     struct termlist_score **tl = 0;
997
998     session_enter(se);
999     for (i = 0; i < se->num_termlists; i++)
1000         if (!strcmp((const char *) se->termlists[i].name, name))
1001         {
1002             tl = termlist_highscore(se->termlists[i].termlist, num);
1003             break;
1004         }
1005     session_leave(se);
1006     return tl;
1007 }
1008
1009 // Compares two hitsbytarget nodes by hitcount
1010 static int cmp_ht(const void *p1, const void *p2)
1011 {
1012     const struct hitsbytarget *h1 = p1;
1013     const struct hitsbytarget *h2 = p2;
1014     return h2->hits - h1->hits;
1015 }
1016
1017 // Compares two hitsbytarget nodes by hitcount
1018 static int cmp_ht_approx(const void *p1, const void *p2)
1019 {
1020     const struct hitsbytarget *h1 = p1;
1021     const struct hitsbytarget *h2 = p2;
1022     return h2->approximation - h1->approximation;
1023 }
1024
1025 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1026                                NMEM nmem, int version)
1027 {
1028     struct hitsbytarget *ht;
1029     int count, i;
1030
1031     ht = hitsbytarget_nb(se, &count, nmem);
1032     if (version >= 2)
1033         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1034     else
1035         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1036     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1037     {
1038
1039         // do only print terms which have display names
1040     
1041         wrbuf_puts(wrbuf, "<term>\n");
1042
1043         wrbuf_puts(wrbuf, "<id>");
1044         wrbuf_xmlputs(wrbuf, ht[i].id);
1045         wrbuf_puts(wrbuf, "</id>\n");
1046         
1047         wrbuf_puts(wrbuf, "<name>");
1048         if (!ht[i].name || !ht[i].name[0])
1049             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1050         else
1051             wrbuf_xmlputs(wrbuf, ht[i].name);
1052         wrbuf_puts(wrbuf, "</name>\n");
1053         
1054         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1055                      ht[i].hits);
1056
1057         if (version >= 2) {
1058             // Should not print if we know it isn't a approximation.
1059             wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1060             wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1061             wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1062         }
1063
1064         wrbuf_puts(wrbuf, "<state>");
1065         wrbuf_xmlputs(wrbuf, ht[i].state);
1066         wrbuf_puts(wrbuf, "</state>\n");
1067         
1068         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
1069                      ht[i].diagnostic);
1070         wrbuf_puts(wrbuf, "</term>\n");
1071     }
1072     return count;
1073 }
1074
1075 void perform_termlist(struct http_channel *c, struct session *se,
1076                       const char *name, int num, int version)
1077 {
1078     int i, j;
1079     NMEM nmem_tmp = nmem_create();
1080     char **names;
1081     int num_names = 0;
1082
1083     if (!name)
1084         name = "*";
1085
1086     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1087
1088     session_enter(se);
1089
1090     for (j = 0; j < num_names; j++)
1091     {
1092         const char *tname;
1093         int must_generate_empty = 1; /* bug 5350 */
1094
1095         for (i = 0; i < se->num_termlists; i++)
1096         {
1097             tname = se->termlists[i].name;
1098             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1099             {
1100                 struct termlist_score **p = 0;
1101                 int len;
1102
1103                 wrbuf_puts(c->wrbuf, "<list name=\"");
1104                 wrbuf_xmlputs(c->wrbuf, tname);
1105                 wrbuf_puts(c->wrbuf, "\">\n");
1106                 must_generate_empty = 0;
1107
1108                 p = termlist_highscore(se->termlists[i].termlist, &len);
1109                 if (p)
1110                 {
1111                     int i;
1112                     for (i = 0; i < len && i < num; i++)
1113                     {
1114                         // prevent sending empty term elements
1115                         if (!p[i]->display_term || !p[i]->display_term[0])
1116                             continue;
1117                         
1118                         wrbuf_puts(c->wrbuf, "<term>");
1119                         wrbuf_puts(c->wrbuf, "<name>");
1120                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1121                         wrbuf_puts(c->wrbuf, "</name>");
1122                         
1123                         wrbuf_printf(c->wrbuf, 
1124                                      "<frequency>%d</frequency>", 
1125                                      p[i]->frequency);
1126                         wrbuf_puts(c->wrbuf, "</term>\n");
1127                     }
1128                 }
1129                 wrbuf_puts(c->wrbuf, "</list>\n");
1130             }
1131         }
1132         tname = "xtargets";
1133         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1134         {
1135             wrbuf_puts(c->wrbuf, "<list name=\"");
1136             wrbuf_xmlputs(c->wrbuf, tname);
1137             wrbuf_puts(c->wrbuf, "\">\n");
1138
1139             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1140             wrbuf_puts(c->wrbuf, "</list>\n");
1141             must_generate_empty = 0;
1142         }
1143         if (must_generate_empty)
1144         {
1145             wrbuf_puts(c->wrbuf, "<list name=\"");
1146             wrbuf_xmlputs(c->wrbuf, names[j]);
1147             wrbuf_puts(c->wrbuf, "\"/>\n");
1148         }
1149     }
1150     session_leave(se);
1151     nmem_destroy(nmem_tmp);
1152 }
1153
1154 #ifdef MISSING_HEADERS
1155 void report_nmem_stats(void)
1156 {
1157     size_t in_use, is_free;
1158
1159     nmem_get_memory_in_use(&in_use);
1160     nmem_get_memory_free(&is_free);
1161
1162     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1163             (long) in_use, (long) is_free);
1164 }
1165 #endif
1166
1167 struct record_cluster *show_single_start(struct session *se, const char *id,
1168                                          struct record_cluster **prev_r,
1169                                          struct record_cluster **next_r)
1170 {
1171     struct record_cluster *r = 0;
1172
1173     session_enter(se);
1174     *prev_r = 0;
1175     *next_r = 0;
1176     if (se->reclist)
1177     {
1178         reclist_enter(se->reclist);
1179         while ((r = reclist_read_record(se->reclist)))
1180         {
1181             if (!strcmp(r->recid, id))
1182             {
1183                 *next_r = reclist_read_record(se->reclist);
1184                 break;
1185             }
1186             *prev_r = r;
1187         }
1188         reclist_leave(se->reclist);
1189     }
1190     if (!r)
1191         session_leave(se);
1192     return r;
1193 }
1194
1195 void show_single_stop(struct session *se, struct record_cluster *rec)
1196 {
1197     session_leave(se);
1198 }
1199
1200 struct record_cluster **show_range_start(struct session *se,
1201                                          struct reclist_sortparms *sp, 
1202                                          int start, int *num, int *total, Odr_int *sumhits, Odr_int *approx_hits)
1203 {
1204     struct record_cluster **recs;
1205     struct reclist_sortparms *spp;
1206     int i;
1207 #if USE_TIMING    
1208     yaz_timing_t t = yaz_timing_create();
1209 #endif
1210     session_enter(se);
1211     recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1212     if (!se->relevance)
1213     {
1214         *num = 0;
1215         *total = 0;
1216         *sumhits = 0;        
1217         *approx_hits = 0;
1218         recs = 0;
1219     }
1220     else
1221     {
1222         struct client_list *l;
1223         
1224         for (spp = sp; spp; spp = spp->next)
1225             if (spp->type == Metadata_sortkey_relevance)
1226             {
1227                 relevance_prepare_read(se->relevance, se->reclist);
1228                 break;
1229             }
1230         reclist_sort(se->reclist, sp);
1231         
1232         reclist_enter(se->reclist);
1233         *total = reclist_get_num_records(se->reclist);
1234
1235         *sumhits = 0;
1236         *approx_hits = 0;
1237         for (l = se->clients_active; l; l = l->next) {
1238             *sumhits += client_get_hits(l->client);
1239             *approx_hits += client_get_approximation(l->client);
1240         }
1241         for (i = 0; i < start; i++)
1242             if (!reclist_read_record(se->reclist))
1243             {
1244                 *num = 0;
1245                 recs = 0;
1246                 break;
1247             }
1248         
1249         for (i = 0; i < *num; i++)
1250         {
1251             struct record_cluster *r = reclist_read_record(se->reclist);
1252             if (!r)
1253             {
1254                 *num = i;
1255                 break;
1256             }
1257             recs[i] = r;
1258         }
1259         reclist_leave(se->reclist);
1260     }
1261 #if USE_TIMING
1262     yaz_timing_stop(t);
1263     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1264             yaz_timing_get_real(t), yaz_timing_get_user(t),
1265             yaz_timing_get_sys(t));
1266     yaz_timing_destroy(&t);
1267 #endif
1268     return recs;
1269 }
1270
1271 void show_range_stop(struct session *se, struct record_cluster **recs)
1272 {
1273     session_leave(se);
1274 }
1275
1276 void statistics(struct session *se, struct statistics *stat)
1277 {
1278     struct client_list *l;
1279     int count = 0;
1280
1281     memset(stat, 0, sizeof(*stat));
1282     stat->num_hits = 0;
1283     for (l = se->clients_active; l; l = l->next)
1284     {
1285         struct client *cl = l->client;
1286         if (!client_get_connection(cl))
1287             stat->num_no_connection++;
1288         stat->num_hits += client_get_hits(cl);
1289         switch (client_get_state(cl))
1290         {
1291         case Client_Connecting: stat->num_connecting++; break;
1292         case Client_Working: stat->num_working++; break;
1293         case Client_Idle: stat->num_idle++; break;
1294         case Client_Failed: stat->num_failed++; break;
1295         case Client_Error: stat->num_error++; break;
1296         default: break;
1297         }
1298         count++;
1299     }
1300     stat->num_records = se->total_records;
1301
1302     stat->num_clients = count;
1303 }
1304
1305 static struct record_metadata *record_metadata_init(
1306     NMEM nmem, const char *value, enum conf_metadata_type type,
1307     struct _xmlAttr *attr)
1308 {
1309     struct record_metadata *rec_md = record_metadata_create(nmem);
1310     struct record_metadata_attr **attrp = &rec_md->attributes;
1311     
1312     for (; attr; attr = attr->next)
1313     {
1314         if (attr->children && attr->children->content)
1315         {
1316             if (strcmp((const char *) attr->name, "type"))
1317             {  /* skip the "type" attribute.. Its value is already part of
1318                   the element in output (md-%s) and so repeating it here
1319                   is redundant */
1320                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1321                 (*attrp)->name =
1322                     nmem_strdup(nmem, (const char *) attr->name);
1323                 (*attrp)->value =
1324                     nmem_strdup(nmem, (const char *) attr->children->content);
1325                 attrp = &(*attrp)->next;
1326             }
1327         }
1328     }
1329     *attrp = 0;
1330
1331     if (type == Metadata_type_generic)
1332     {
1333         char *p = nmem_strdup(nmem, value);
1334
1335         p = normalize7bit_generic(p, " ,/.:([");
1336         
1337         rec_md->data.text.disp = p;
1338         rec_md->data.text.sort = 0;
1339     }
1340     else if (type == Metadata_type_year || type == Metadata_type_date)
1341     {
1342         int first, last;
1343         int longdate = 0;
1344
1345         if (type == Metadata_type_date)
1346             longdate = 1;
1347         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1348             return 0;
1349
1350         rec_md->data.number.min = first;
1351         rec_md->data.number.max = last;
1352     }
1353     else
1354         return 0;
1355     return rec_md;
1356 }
1357
1358 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1359                                  struct conf_service *service, WRBUF norm_wr)
1360 {
1361     xmlNode *n;
1362     int no_found = 0;
1363     for (n = root->children; n; n = n->next)
1364     {
1365         if (n->type != XML_ELEMENT_NODE)
1366             continue;
1367         if (!strcmp((const char *) n->name, "metadata"))
1368         {
1369             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1370             if (type == NULL) {
1371                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1372             }
1373             else if (!strcmp(name, (const char *) type))
1374             {
1375                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1376                 if (value)
1377                 {
1378                     const char *norm_str;
1379                     pp2_charset_token_t prt =
1380                         pp2_charset_token_create(service->charsets, "mergekey");
1381                     
1382                     pp2_charset_token_first(prt, (const char *) value, 0);
1383                     if (wrbuf_len(norm_wr) > 0)
1384                         wrbuf_puts(norm_wr, " ");
1385                     wrbuf_puts(norm_wr, name);
1386                     while ((norm_str =
1387                             pp2_charset_token_next(prt)))
1388                     {
1389                         if (*norm_str)
1390                         {
1391                             wrbuf_puts(norm_wr, " ");
1392                             wrbuf_puts(norm_wr, norm_str);
1393                         }
1394                     }
1395                     xmlFree(value);
1396                     pp2_charset_token_destroy(prt);
1397                     no_found++;
1398                 }
1399             }
1400             xmlFree(type);
1401         }
1402     }
1403     return no_found;
1404 }
1405
1406 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1407                                 struct conf_service *service, NMEM nmem)
1408 {
1409     char *mergekey_norm = 0;
1410     xmlNode *root = xmlDocGetRootElement(doc);
1411     WRBUF norm_wr = wrbuf_alloc();
1412
1413     /* consider mergekey from XSL first */
1414     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1415     if (mergekey)
1416     {
1417         const char *norm_str;
1418         pp2_charset_token_t prt =
1419             pp2_charset_token_create(service->charsets, "mergekey");
1420
1421         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1422         while ((norm_str = pp2_charset_token_next(prt)))
1423         {
1424             if (*norm_str)
1425             {
1426                 if (wrbuf_len(norm_wr))
1427                     wrbuf_puts(norm_wr, " ");
1428                 wrbuf_puts(norm_wr, norm_str);
1429             }
1430         }
1431         pp2_charset_token_destroy(prt);
1432         xmlFree(mergekey);
1433     }
1434     else
1435     {
1436         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1437         int field_id;
1438         for (field_id = 0; field_id < service->num_metadata; field_id++)
1439         {
1440             struct conf_metadata *ser_md = &service->metadata[field_id];
1441             if (ser_md->mergekey != Metadata_mergekey_no)
1442             {
1443                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1444                                               service, norm_wr);
1445                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1446                 {
1447                     /* no mergekey on this one and it is required.. 
1448                        Generate unique key instead */
1449                     wrbuf_rewind(norm_wr);
1450                     break;
1451                 }
1452             }
1453         }
1454     }
1455
1456     /* generate unique key if none is not generated already or is empty */
1457     if (wrbuf_len(norm_wr) == 0)
1458     {
1459         wrbuf_printf(norm_wr, "position: %s-%d",
1460                      client_get_id(cl), record_no);
1461     }
1462     else
1463     {
1464         const char *lead = "content: ";
1465         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1466     }
1467     if (wrbuf_len(norm_wr) > 0)
1468         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1469     wrbuf_destroy(norm_wr);
1470     return mergekey_norm;
1471 }
1472
1473 /** \brief see if metadata for pz:recordfilter exists 
1474     \param root xml root element of normalized record
1475     \param sdb session database for client
1476     \retval 0 if there is no metadata for pz:recordfilter
1477     \retval 1 if there is metadata for pz:recordfilter
1478
1479     If there is no pz:recordfilter defined, this function returns 1
1480     as well.
1481 */
1482     
1483 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1484 {
1485     int match = 0;
1486     xmlNode *n;
1487     const char *s;
1488     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1489
1490     if (!s || !*s)
1491         return 1;
1492
1493     for (n = root->children; n; n = n->next)
1494     {
1495         if (n->type != XML_ELEMENT_NODE)
1496             continue;
1497         if (!strcmp((const char *) n->name, "metadata"))
1498         {
1499             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1500             if (type)
1501             {
1502                 size_t len;
1503                 int substring;
1504                 const char *eq;
1505
1506                 if ((eq = strchr(s, '=')))
1507                     substring = 0;
1508                 else if ((eq = strchr(s, '~')))
1509                     substring = 1;
1510                 if (eq)
1511                     len = eq - s;
1512                 else
1513                     len = strlen(s);
1514                 if (len == strlen((const char *)type) &&
1515                     !memcmp((const char *) type, s, len))
1516                 {
1517                     xmlChar *value = xmlNodeGetContent(n);
1518                     if (value && *value)
1519                     {
1520                         if (!eq ||
1521                             (substring && strstr((const char *) value, eq+1)) ||
1522                             (!substring && !strcmp((const char *) value, eq + 1)))
1523                             match = 1;
1524                     }
1525                     xmlFree(value);
1526                 }
1527                 xmlFree(type);
1528             }
1529         }
1530     }
1531     return match;
1532 }
1533
1534
1535 static int ingest_to_cluster(struct client *cl,
1536                              xmlDoc *xdoc,
1537                              xmlNode *root,
1538                              int record_no,
1539                              const char *mergekey_norm);
1540
1541 /** \brief ingest XML record
1542     \param cl client holds the result set for record
1543     \param rec record buffer (0 terminated)
1544     \param record_no record position (1, 2, ..)
1545     \param nmem working NMEM
1546     \retval 0 OK
1547     \retval -1 failure
1548     \retval -2 Filtered
1549 */
1550 int ingest_record(struct client *cl, const char *rec,
1551                   int record_no, NMEM nmem)
1552 {
1553     struct session *se = client_get_session(cl);
1554     int ret = 0;
1555     struct session_database *sdb = client_get_database(cl);
1556     struct conf_service *service = se->service;
1557     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1558     xmlNode *root;
1559     const char *mergekey_norm;
1560     
1561     if (!xdoc)
1562         return -1;
1563     
1564     root = xmlDocGetRootElement(xdoc);
1565     
1566     if (!check_record_filter(root, sdb))
1567     {
1568         session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1569         xmlFreeDoc(xdoc);
1570         return -2;
1571     }
1572     
1573     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1574     if (!mergekey_norm)
1575     {
1576         session_log(se, YLOG_WARN, "Got no mergekey");
1577         xmlFreeDoc(xdoc);
1578         return -1;
1579     }
1580     session_enter(se);
1581     if (client_get_session(cl) == se)
1582         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1583     session_leave(se);
1584     
1585     xmlFreeDoc(xdoc);
1586     return ret;
1587 }
1588
1589 // Skip record on non-zero
1590 static int check_limit_local(struct client *cl,
1591                              struct record *record,
1592                              int record_no)
1593 {
1594     int skip_record = 0;
1595     struct session *se = client_get_session(cl);
1596     struct conf_service *service = se->service;
1597     NMEM nmem_tmp = nmem_create();
1598     struct session_database *sdb = client_get_database(cl);
1599     int l = 0;
1600     while (!skip_record)
1601     {
1602         struct conf_metadata *ser_md = 0;
1603         struct record_metadata *rec_md = 0;
1604         int md_field_id;
1605         char **values = 0;
1606         int i, num_v = 0;
1607         
1608         const char *name = client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v, &values);
1609         if (!name)
1610             break;
1611         
1612         md_field_id = conf_service_metadata_field_id(service, name);
1613         if (md_field_id < 0)
1614         {
1615             skip_record = 1;
1616             break;
1617         }
1618         ser_md = &service->metadata[md_field_id];
1619         rec_md = record->metadata[md_field_id];
1620         yaz_log(YLOG_LOG, "check limit local %s", name);
1621         for (i = 0; i < num_v; )
1622         {
1623             if (rec_md)
1624             {
1625                 if (ser_md->type == Metadata_type_year 
1626                     || ser_md->type == Metadata_type_date)
1627                 {
1628                     int y = atoi(values[i]);
1629                     if (y >= rec_md->data.number.min 
1630                         && y <= rec_md->data.number.max)
1631                         break;
1632                 }
1633                 else
1634                 {
1635                     yaz_log(YLOG_LOG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1636                     if (!strcmp(rec_md->data.text.disp, values[i]))
1637                     {
1638                         // Value equals, should not be filtered.
1639                         break;
1640                     }
1641                 }
1642                 rec_md = rec_md->next;
1643             }
1644             else
1645             {
1646                 rec_md = record->metadata[md_field_id];
1647                 i++;
1648             }
1649         }
1650         // At end , not match
1651         if (i == num_v)
1652         {
1653             skip_record = 1;
1654             break;
1655         }
1656     }
1657     nmem_destroy(nmem_tmp);
1658     return skip_record;
1659 }
1660                              
1661 static int ingest_to_cluster(struct client *cl,
1662                              xmlDoc *xdoc,
1663                              xmlNode *root,
1664                              int record_no,
1665                              const char *mergekey_norm)
1666 {
1667     xmlNode *n;
1668     xmlChar *type = 0;
1669     xmlChar *value = 0;
1670     struct session *se = client_get_session(cl);
1671     struct conf_service *service = se->service;
1672     int term_factor = 1;
1673     struct record_cluster *cluster;
1674     struct session_database *sdb = client_get_database(cl);
1675     struct record *record = record_create(se->nmem, 
1676                                           service->num_metadata,
1677                                           service->num_sortkeys, cl,
1678                                           record_no);
1679
1680     for (n = root->children; n; n = n->next)
1681     {
1682         if (type)
1683             xmlFree(type);
1684         if (value)
1685             xmlFree(value);
1686         type = value = 0;
1687         
1688         if (n->type != XML_ELEMENT_NODE)
1689             continue;
1690         if (!strcmp((const char *) n->name, "metadata"))
1691         {
1692             struct conf_metadata *ser_md = 0;
1693             struct record_metadata **wheretoput = 0;
1694             struct record_metadata *rec_md = 0;
1695             int md_field_id = -1;
1696             
1697             type = xmlGetProp(n, (xmlChar *) "type");
1698             value = xmlNodeListGetString(xdoc, n->children, 1);
1699             
1700             if (!type || !value || !*value)
1701                 continue;
1702             
1703             md_field_id 
1704                 = conf_service_metadata_field_id(service, (const char *) type);
1705             if (md_field_id < 0)
1706             {
1707                 if (se->number_of_warnings_unknown_metadata == 0)
1708                 {
1709                     session_log(se, YLOG_WARN, 
1710                             "Ignoring unknown metadata element: %s", type);
1711                 }
1712                 se->number_of_warnings_unknown_metadata++;
1713                 continue;
1714             }
1715            
1716             ser_md = &service->metadata[md_field_id];
1717
1718             // non-merged metadata
1719             rec_md = record_metadata_init(se->nmem, (const char *) value,
1720                                           ser_md->type, n->properties);
1721             if (!rec_md)
1722             {
1723                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1724                             "for element '%s'", value, type);
1725                 continue;
1726             }
1727             wheretoput = &record->metadata[md_field_id];
1728             while (*wheretoput)
1729                 wheretoput = &(*wheretoput)->next;
1730             *wheretoput = rec_md;
1731         }
1732     }
1733
1734     if (check_limit_local(cl, record, record_no))
1735     {
1736         session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1737                     record_no, sdb->database->id);
1738         if (type)
1739             xmlFree(type);
1740         if (value)
1741             xmlFree(value);
1742         return -2;
1743     }
1744     cluster = reclist_insert(se->reclist, service, record,
1745                              mergekey_norm, &se->total_merged);
1746     if (!cluster)
1747         return -1;
1748
1749     {
1750         const char *use_term_factor_str =
1751             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1752         if (use_term_factor_str && use_term_factor_str[0] == '1')
1753         {
1754             int maxrecs = client_get_maxrecs(cl);
1755             int hits = (int) client_get_hits(cl);
1756             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1757             assert(term_factor >= 1);
1758             yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1759         }
1760     }
1761
1762     if (global_parameters.dump_records)
1763         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1764                     sdb->database->id, record_no);
1765
1766
1767     relevance_newrec(se->relevance, cluster);
1768     
1769     // now parsing XML record and adding data to cluster or record metadata
1770     for (n = root->children; n; n = n->next)
1771     {
1772         pp2_charset_token_t prt;
1773         if (type)
1774             xmlFree(type);
1775         if (value)
1776             xmlFree(value);
1777         type = value = 0;
1778         
1779         if (n->type != XML_ELEMENT_NODE)
1780             continue;
1781         if (!strcmp((const char *) n->name, "metadata"))
1782         {
1783             struct conf_metadata *ser_md = 0;
1784             struct conf_sortkey *ser_sk = 0;
1785             struct record_metadata **wheretoput = 0;
1786             struct record_metadata *rec_md = 0;
1787             int md_field_id = -1;
1788             int sk_field_id = -1;
1789             
1790             type = xmlGetProp(n, (xmlChar *) "type");
1791             value = xmlNodeListGetString(xdoc, n->children, 1);
1792             
1793             if (!type || !value || !*value)
1794                 continue;
1795             
1796             md_field_id 
1797                 = conf_service_metadata_field_id(service, (const char *) type);
1798             if (md_field_id < 0)
1799                 continue;
1800             
1801             ser_md = &service->metadata[md_field_id];
1802             
1803             if (ser_md->sortkey_offset >= 0)
1804             {
1805                 sk_field_id = ser_md->sortkey_offset;
1806                 ser_sk = &service->sortkeys[sk_field_id];
1807             }
1808
1809             // merged metadata
1810             rec_md = record_metadata_init(se->nmem, (const char *) value,
1811                                           ser_md->type, 0);
1812             if (!rec_md)
1813                 continue;
1814
1815             wheretoput = &cluster->metadata[md_field_id];
1816
1817             // and polulate with data:
1818             // assign cluster or record based on merge action
1819             if (ser_md->merge == Metadata_merge_unique)
1820             {
1821                 while (*wheretoput)
1822                 {
1823                     if (!strcmp((const char *) (*wheretoput)->data.text.disp, 
1824                                 rec_md->data.text.disp))
1825                         break;
1826                     wheretoput = &(*wheretoput)->next;
1827                 }
1828                 if (!*wheretoput)
1829                     *wheretoput = rec_md;
1830             }
1831             else if (ser_md->merge == Metadata_merge_longest)
1832             {
1833                 if (!*wheretoput 
1834                     || strlen(rec_md->data.text.disp) 
1835                     > strlen((*wheretoput)->data.text.disp))
1836                 {
1837                     *wheretoput = rec_md;
1838                     if (ser_sk)
1839                     {
1840                         const char *sort_str = 0;
1841                         int skip_article = 
1842                             ser_sk->type == Metadata_sortkey_skiparticle;
1843
1844                         if (!cluster->sortkeys[sk_field_id])
1845                             cluster->sortkeys[sk_field_id] = 
1846                                 nmem_malloc(se->nmem, 
1847                                             sizeof(union data_types));
1848                          
1849                         prt =
1850                             pp2_charset_token_create(service->charsets, "sort");
1851
1852                         pp2_charset_token_first(prt, rec_md->data.text.disp,
1853                                                 skip_article);
1854
1855                         pp2_charset_token_next(prt);
1856                          
1857                         sort_str = pp2_get_sort(prt);
1858                          
1859                         cluster->sortkeys[sk_field_id]->text.disp = 
1860                             rec_md->data.text.disp;
1861                         if (!sort_str)
1862                         {
1863                             sort_str = rec_md->data.text.disp;
1864                             session_log(se, YLOG_WARN, 
1865                                     "Could not make sortkey. Bug #1858");
1866                         }
1867                         cluster->sortkeys[sk_field_id]->text.sort = 
1868                             nmem_strdup(se->nmem, sort_str);
1869                         pp2_charset_token_destroy(prt);
1870                     }
1871                 }
1872             }
1873             else if (ser_md->merge == Metadata_merge_all)
1874             {
1875                 while (*wheretoput)
1876                     wheretoput = &(*wheretoput)->next;
1877                 *wheretoput = rec_md;
1878             }
1879             else if (ser_md->merge == Metadata_merge_range)
1880             {
1881                 if (!*wheretoput)
1882                 {
1883                     *wheretoput = rec_md;
1884                     if (ser_sk)
1885                         cluster->sortkeys[sk_field_id] 
1886                             = &rec_md->data;
1887                 }
1888                 else
1889                 {
1890                     int this_min = rec_md->data.number.min;
1891                     int this_max = rec_md->data.number.max;
1892                     if (this_min < (*wheretoput)->data.number.min)
1893                         (*wheretoput)->data.number.min = this_min;
1894                     if (this_max > (*wheretoput)->data.number.max)
1895                         (*wheretoput)->data.number.max = this_max;
1896                 }
1897             }
1898
1899
1900             // ranking of _all_ fields enabled ... 
1901             if (ser_md->rank)
1902                 relevance_countwords(se->relevance, cluster, 
1903                                      (char *) value, ser_md->rank,
1904                                      ser_md->name);
1905
1906             // construct facets ... unless the client already has reported them
1907             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1908             {
1909                 if (ser_md->type == Metadata_type_year)
1910                 {
1911                     char year[64];
1912                     sprintf(year, "%d", rec_md->data.number.max);
1913
1914                     add_facet(se, (char *) type, year, term_factor);
1915                     if (rec_md->data.number.max != rec_md->data.number.min)
1916                     {
1917                         sprintf(year, "%d", rec_md->data.number.min);
1918                         add_facet(se, (char *) type, year, term_factor);
1919                     }
1920                 }
1921                 else
1922                     add_facet(se, (char *) type, (char *) value, term_factor);
1923             }
1924
1925             // cleaning up
1926             xmlFree(type);
1927             xmlFree(value);
1928             type = value = 0;
1929         }
1930         else
1931         {
1932             if (se->number_of_warnings_unknown_elements == 0)
1933                 session_log(se, YLOG_WARN,
1934                         "Unexpected element in internal record: %s", n->name);
1935             se->number_of_warnings_unknown_elements++;
1936         }
1937     }
1938     if (type)
1939         xmlFree(type);
1940     if (value)
1941         xmlFree(value);
1942
1943     relevance_donerecord(se->relevance, cluster);
1944     se->total_records++;
1945
1946     return 0;
1947 }
1948
1949 void session_log(struct session *s, int level, const char *fmt, ...)
1950 {
1951     char buf[1024];
1952     va_list ap;
1953     va_start(ap, fmt);
1954
1955     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1956     yaz_log(level, "Session %u: %s", s->session_id, buf);
1957
1958     va_end(ap);
1959 }
1960
1961 /*
1962  * Local variables:
1963  * c-basic-offset: 4
1964  * c-file-style: "Stroustrup"
1965  * indent-tabs-mode: nil
1966  * End:
1967  * vim: shiftwidth=4 tabstop=8 expandtab
1968  */
1969