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