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