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