fbcd94e8b5241a5a92a8e5350105175e1083fd3a
[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     se->reclist = 0;
628     if (nmem_total(se->nmem))
629         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
630                     nmem_total(se->nmem));
631     nmem_reset(se->nmem);
632     se->total_records = se->total_merged = 0;
633     se->num_termlists = 0;
634
635     /* reset list of sorted results and clear to relevance search */
636     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
637     se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
638     se->sorted_results->increasing = sp->increasing;
639     se->sorted_results->type = sp->type;
640     se->sorted_results->next = 0;
641
642     session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
643             sp->name, sp->increasing, sp->type);
644
645     se->reclist = reclist_create(se->nmem);
646 }
647
648 static void session_sort_unlocked(struct session *se, struct reclist_sortparms *sp)
649 {
650     struct reclist_sortparms *sr;
651     struct client_list *l;
652     const char *field = sp->name;
653     int increasing = sp->increasing;
654     int type  = sp->type;
655     int clients_research = 0;
656
657     session_log(se, YLOG_DEBUG, "session_sort field=%s increasing=%d type=%d",
658                 field, increasing, type);
659     /* see if we already have sorted for this criteria */
660     for (sr = se->sorted_results; sr; sr = sr->next)
661     {
662         if (!reclist_sortparms_cmp(sr, sp))
663             break;
664     }
665     if (sr)
666     {
667         session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d already fetched",
668                     field, increasing, type);
669         return;
670     }
671     session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d must fetch",
672                     field, increasing, type);
673
674     // We need to reset reclist on every sort that changes the records, not just for position
675     // So if just one client requires new searching, we need to clear set.
676     // Ask each of the client if sorting requires re-search due to native sort
677     // If it does it will require us to
678     for (l = se->clients_active; l; l = l->next)
679     {
680         struct client *cl = l->client;
681         // Assume no re-search is required.
682         client_parse_init(cl, 1);
683         clients_research += client_parse_sort(cl, sp);
684     }
685     if (clients_research) {
686         session_log(se, YLOG_DEBUG,
687                     "Reset results due to %d clients researching",
688                     clients_research);
689         session_clear_set(se, sp);
690     }
691     else {
692         // A new sorting based on same record set
693         sr = nmem_malloc(se->nmem, sizeof(*sr));
694         sr->name = nmem_strdup(se->nmem, field);
695         sr->increasing = increasing;
696         sr->type = type;
697         sr->next = se->sorted_results;
698         se->sorted_results = sr;
699         session_log(se, YLOG_DEBUG, "No research/ingesting done");
700         return ;
701     }
702     session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
703
704     for (l = se->clients_active; l; l = l->next)
705     {
706         struct client *cl = l->client;
707         if (client_get_state(cl) == Client_Connecting ||
708             client_get_state(cl) == Client_Idle ||
709             client_get_state(cl) == Client_Working) {
710             client_start_search(cl);
711         }
712         else {
713             session_log(se, YLOG_DEBUG,
714                         "Client %s: No re-start/ingest in show. Wrong client state: %d",
715                         client_get_id(cl), client_get_state(cl));
716         }
717
718     }
719 }
720
721 void session_sort(struct session *se, struct reclist_sortparms *sp) {
722     //session_enter(se, "session_sort");
723     session_sort_unlocked(se, sp);
724     //session_leave(se, "session_sort");
725 }
726
727
728 enum pazpar2_error_code session_search(struct session *se,
729                                        const char *query,
730                                        const char *startrecs,
731                                        const char *maxrecs,
732                                        const char *filter,
733                                        const char *limit,
734                                        const char **addinfo,
735                                        struct reclist_sortparms *sp)
736 {
737     int live_channels = 0;
738     int no_working = 0;
739     int no_failed_query = 0;
740     int no_failed_limit = 0;
741     struct client_list *l, *l0;
742
743     session_log(se, YLOG_DEBUG, "Search");
744
745     *addinfo = 0;
746
747     if (se->settings_modified) {
748         session_remove_cached_clients(se);
749     }
750     else
751         session_reset_active_clients(se, 0);
752
753     session_enter(se, "session_search");
754     se->settings_modified = 0;
755
756     session_clear_set(se, sp);
757     relevance_destroy(&se->relevance);
758
759     live_channels = select_targets(se, filter);
760     if (!live_channels)
761     {
762         session_leave(se, "session_search");
763         return PAZPAR2_NO_TARGETS;
764     }
765
766     facet_limits_destroy(se->facet_limits);
767     se->facet_limits = facet_limits_create(limit);
768     if (!se->facet_limits)
769     {
770         *addinfo = "limit";
771         session_leave(se, "session_search");
772         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
773     }
774
775     l0 = se->clients_active;
776     se->clients_active = 0;
777     session_leave(se, "session_search");
778
779     for (l = l0; l; l = l->next)
780     {
781         int parse_ret;
782         struct client *cl = l->client;
783         client_parse_init(cl, 1);
784         if (prepare_map(se, client_get_database(cl)) < 0)
785             continue;
786
787         parse_ret = client_parse_query(cl, query, se->facet_limits);
788         if (parse_ret == -1)
789             no_failed_query++;
790         else if (parse_ret == -2)
791             no_failed_limit++;
792         else if (parse_ret < 0)
793             no_working++; /* other error, such as bad CCL map */
794         else
795         {
796             client_parse_range(cl, startrecs, maxrecs);
797             client_parse_sort(cl, sp);
798             client_start_search(cl);
799             no_working++;
800         }
801     }
802     session_reset_active_clients(se, l0);
803
804     if (no_working == 0)
805     {
806         if (no_failed_query > 0)
807         {
808             *addinfo = "query";
809             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
810         }
811         else if (no_failed_limit > 0)
812         {
813             *addinfo = "limit";
814             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
815         }
816         else
817             return PAZPAR2_NO_TARGETS;
818     }
819     session_log(se, YLOG_LOG, "session_start_search done");
820     return PAZPAR2_NO_ERROR;
821 }
822
823 // Creates a new session_database object for a database
824 static void session_init_databases_fun(void *context, struct database *db)
825 {
826     struct session *se = (struct session *) context;
827     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
828     int i;
829
830     new->database = db;
831
832     new->map = 0;
833     assert(db->settings);
834     new->settings = nmem_malloc(se->session_nmem,
835                                 sizeof(struct settings *) * db->num_settings);
836     new->num_settings = db->num_settings;
837     for (i = 0; i < db->num_settings; i++)
838     {
839         struct setting *setting = db->settings[i];
840         new->settings[i] = setting;
841     }
842     new->next = se->databases;
843     se->databases = new;
844 }
845
846 // Doesn't free memory associated with sdb -- nmem takes care of that
847 static void session_database_destroy(struct session_database *sdb)
848 {
849     sdb->map = 0;
850 }
851
852 // Initialize session_database list -- this represents this session's view
853 // of the database list -- subject to modification by the settings ws command
854 void session_init_databases(struct session *se)
855 {
856     se->databases = 0;
857     predef_grep_databases(se, se->service, session_init_databases_fun);
858 }
859
860 // Probably session_init_databases_fun should be refactored instead of
861 // called here.
862 static struct session_database *load_session_database(struct session *se,
863                                                       char *id)
864 {
865     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
866     session_init_databases_fun((void*) se, db);
867
868     // New sdb is head of se->databases list
869     return se->databases;
870 }
871
872 // Find an existing session database. If not found, load it
873 static struct session_database *find_session_database(struct session *se,
874                                                       char *id)
875 {
876     struct session_database *sdb;
877
878     for (sdb = se->databases; sdb; sdb = sdb->next)
879         if (!strcmp(sdb->database->id, id))
880             return sdb;
881     return load_session_database(se, id);
882 }
883
884 // Apply a session override to a database
885 void session_apply_setting(struct session *se, char *dbname, char *setting,
886                            char *value)
887 {
888     struct session_database *sdb = find_session_database(se, dbname);
889     struct conf_service *service = se->service;
890     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
891     int offset = settings_create_offset(service, setting);
892
893     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
894                           se->session_nmem);
895     new->precedence = 0;
896     new->target = dbname;
897     new->name = setting;
898     new->value = value;
899     new->next = sdb->settings[offset];
900     sdb->settings[offset] = new;
901
902     se->settings_modified = 1;
903
904     // Force later recompute of settings-driven data structures
905     // (happens when a search starts and client connections are prepared)
906     switch (offset)
907     {
908     case PZ_XSLT:
909         if (sdb->map)
910         {
911             sdb->map = 0;
912         }
913         break;
914     }
915 }
916
917 void session_destroy(struct session *se)
918 {
919     struct session_database *sdb;
920     session_log(se, YLOG_DEBUG, "Destroying");
921     session_use(-1);
922     session_remove_cached_clients(se);
923
924     for (sdb = se->databases; sdb; sdb = sdb->next)
925         session_database_destroy(sdb);
926     normalize_cache_destroy(se->normalize_cache);
927     relevance_destroy(&se->relevance);
928     reclist_destroy(se->reclist);
929     if (nmem_total(se->nmem))
930         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
931     if (nmem_total(se->session_nmem))
932         session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
933     facet_limits_destroy(se->facet_limits);
934     nmem_destroy(se->nmem);
935     service_destroy(se->service);
936     yaz_mutex_destroy(&se->session_mutex);
937 }
938
939 size_t session_get_memory_status(struct session *session) {
940     size_t session_nmem;
941     if (session == 0)
942         return 0;
943     session_enter(session, "session_get_memory_status");
944     session_nmem = nmem_total(session->nmem);
945     session_leave(session, "session_get_memory_status");
946     return session_nmem;
947 }
948
949
950 struct session *new_session(NMEM nmem, struct conf_service *service,
951                             unsigned session_id)
952 {
953     int i;
954     struct session *session = nmem_malloc(nmem, sizeof(*session));
955
956     char tmp_str[50];
957
958     sprintf(tmp_str, "session#%u", session_id);
959
960     session->session_id = session_id;
961     session_log(session, YLOG_DEBUG, "New");
962     session->service = service;
963     session->relevance = 0;
964     session->total_records = 0;
965     session->number_of_warnings_unknown_elements = 0;
966     session->number_of_warnings_unknown_metadata = 0;
967     session->num_termlists = 0;
968     session->reclist = 0;
969     session->clients_active = 0;
970     session->clients_cached = 0;
971     session->settings_modified = 0;
972     session->session_nmem = nmem;
973     session->nmem = nmem_create();
974     session->databases = 0;
975     session->sorted_results = 0;
976     session->facet_limits = 0;
977
978     for (i = 0; i <= SESSION_WATCH_MAX; i++)
979     {
980         session->watchlist[i].data = 0;
981         session->watchlist[i].fun = 0;
982     }
983     session->normalize_cache = normalize_cache_create();
984     session->session_mutex = 0;
985     pazpar2_mutex_create(&session->session_mutex, tmp_str);
986     session_use(1);
987     return session;
988 }
989
990 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
991
992 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
993                                             int *count, NMEM nmem)
994 {
995     struct hitsbytarget *res = 0;
996     struct client_list *l;
997     size_t sz = 0;
998
999     for (l = se->clients_active; l; l = l->next)
1000         sz++;
1001
1002     res = nmem_malloc(nmem, sizeof(*res) * sz);
1003     *count = 0;
1004     for (l = se->clients_active; l; l = l->next)
1005     {
1006         struct client *cl = l->client;
1007         WRBUF w = wrbuf_alloc();
1008         const char *name = session_setting_oneval(client_get_database(cl),
1009                                                   PZ_NAME);
1010
1011         res[*count].id = client_get_id(cl);
1012         res[*count].name = *name ? name : "Unknown";
1013         res[*count].hits = client_get_hits(cl);
1014         res[*count].approximation = client_get_approximation(cl);
1015         res[*count].records = client_get_num_records(cl);
1016         res[*count].filtered = client_get_num_records_filtered(cl);
1017         res[*count].diagnostic =
1018             client_get_diagnostic(cl, &res[*count].message,
1019                                   &res[*count].addinfo);
1020         res[*count].state = client_get_state_str(cl);
1021         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
1022         session_settings_dump(se, client_get_database(cl), w);
1023         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1024         wrbuf_rewind(w);
1025         wrbuf_puts(w, "");
1026         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1027         wrbuf_destroy(w);
1028         (*count)++;
1029     }
1030     return res;
1031 }
1032
1033 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1034 {
1035     struct hitsbytarget *p;
1036     session_enter(se, "get_hitsbytarget");
1037     p = hitsbytarget_nb(se, count, nmem);
1038     session_leave(se, "get_hitsbytarget");
1039     return p;
1040 }
1041
1042 // Compares two hitsbytarget nodes by hitcount
1043 static int cmp_ht(const void *p1, const void *p2)
1044 {
1045     const struct hitsbytarget *h1 = p1;
1046     const struct hitsbytarget *h2 = p2;
1047     return h2->hits - h1->hits;
1048 }
1049
1050 // Compares two hitsbytarget nodes by hitcount
1051 static int cmp_ht_approx(const void *p1, const void *p2)
1052 {
1053     const struct hitsbytarget *h1 = p1;
1054     const struct hitsbytarget *h2 = p2;
1055     return h2->approximation - h1->approximation;
1056 }
1057
1058 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1059                                NMEM nmem, int version)
1060 {
1061     struct hitsbytarget *ht;
1062     int count, i;
1063
1064     ht = hitsbytarget_nb(se, &count, nmem);
1065     if (version >= 2)
1066         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1067     else
1068         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1069     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1070     {
1071
1072         // do only print terms which have display names
1073
1074         wrbuf_puts(wrbuf, "<term>\n");
1075
1076         wrbuf_puts(wrbuf, "<id>");
1077         wrbuf_xmlputs(wrbuf, ht[i].id);
1078         wrbuf_puts(wrbuf, "</id>\n");
1079
1080         wrbuf_puts(wrbuf, "<name>");
1081         if (!ht[i].name || !ht[i].name[0])
1082             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1083         else
1084             wrbuf_xmlputs(wrbuf, ht[i].name);
1085         wrbuf_puts(wrbuf, "</name>\n");
1086
1087         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1088                      ht[i].hits);
1089
1090         if (version >= 2) {
1091             // Should not print if we know it isn't a approximation.
1092             wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1093             wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1094             wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1095         }
1096
1097         wrbuf_puts(wrbuf, "<state>");
1098         wrbuf_xmlputs(wrbuf, ht[i].state);
1099         wrbuf_puts(wrbuf, "</state>\n");
1100
1101         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1102                      ht[i].diagnostic);
1103         wrbuf_puts(wrbuf, "</term>\n");
1104     }
1105     return count;
1106 }
1107
1108 void perform_termlist(struct http_channel *c, struct session *se,
1109                       const char *name, int num, int version)
1110 {
1111     int i, j;
1112     NMEM nmem_tmp = nmem_create();
1113     char **names;
1114     int num_names = 0;
1115
1116     if (!name)
1117         name = "*";
1118
1119     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1120
1121     session_enter(se, "perform_termlist");
1122
1123     for (j = 0; j < num_names; j++)
1124     {
1125         const char *tname;
1126         int must_generate_empty = 1; /* bug 5350 */
1127
1128         for (i = 0; i < se->num_termlists; i++)
1129         {
1130             tname = se->termlists[i].name;
1131             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1132             {
1133                 struct termlist_score **p = 0;
1134                 int len;
1135
1136                 wrbuf_puts(c->wrbuf, "<list name=\"");
1137                 wrbuf_xmlputs(c->wrbuf, tname);
1138                 wrbuf_puts(c->wrbuf, "\">\n");
1139                 must_generate_empty = 0;
1140
1141                 p = termlist_highscore(se->termlists[i].termlist, &len,
1142                                        nmem_tmp);
1143                 if (p)
1144                 {
1145                     int i;
1146                     for (i = 0; i < len && i < num; i++)
1147                     {
1148                         // prevent sending empty term elements
1149                         if (!p[i]->display_term || !p[i]->display_term[0])
1150                             continue;
1151
1152                         wrbuf_puts(c->wrbuf, "<term>");
1153                         wrbuf_puts(c->wrbuf, "<name>");
1154                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1155                         wrbuf_puts(c->wrbuf, "</name>");
1156
1157                         wrbuf_printf(c->wrbuf,
1158                                      "<frequency>%d</frequency>",
1159                                      p[i]->frequency);
1160                         wrbuf_puts(c->wrbuf, "</term>\n");
1161                     }
1162                 }
1163                 wrbuf_puts(c->wrbuf, "</list>\n");
1164             }
1165         }
1166         tname = "xtargets";
1167         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1168         {
1169             wrbuf_puts(c->wrbuf, "<list name=\"");
1170             wrbuf_xmlputs(c->wrbuf, tname);
1171             wrbuf_puts(c->wrbuf, "\">\n");
1172
1173             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1174             wrbuf_puts(c->wrbuf, "</list>\n");
1175             must_generate_empty = 0;
1176         }
1177         if (must_generate_empty)
1178         {
1179             wrbuf_puts(c->wrbuf, "<list name=\"");
1180             wrbuf_xmlputs(c->wrbuf, names[j]);
1181             wrbuf_puts(c->wrbuf, "\"/>\n");
1182         }
1183     }
1184     session_leave(se, "perform_termlist");
1185     nmem_destroy(nmem_tmp);
1186 }
1187
1188 #ifdef MISSING_HEADERS
1189 void report_nmem_stats(void)
1190 {
1191     size_t in_use, is_free;
1192
1193     nmem_get_memory_in_use(&in_use);
1194     nmem_get_memory_free(&is_free);
1195
1196     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1197             (long) in_use, (long) is_free);
1198 }
1199 #endif
1200
1201 struct record_cluster *show_single_start(struct session *se, const char *id,
1202                                          struct record_cluster **prev_r,
1203                                          struct record_cluster **next_r)
1204 {
1205     struct record_cluster *r = 0;
1206
1207     session_enter(se, "show_single_start");
1208     *prev_r = 0;
1209     *next_r = 0;
1210     if (se->reclist)
1211     {
1212         reclist_limit(se->reclist, se);
1213
1214         reclist_enter(se->reclist);
1215         while ((r = reclist_read_record(se->reclist)))
1216         {
1217             if (!strcmp(r->recid, id))
1218             {
1219                 *next_r = reclist_read_record(se->reclist);
1220                 break;
1221             }
1222             *prev_r = r;
1223         }
1224         reclist_leave(se->reclist);
1225     }
1226     if (!r)
1227         session_leave(se, "show_single_start");
1228     return r;
1229 }
1230
1231 void show_single_stop(struct session *se, struct record_cluster *rec)
1232 {
1233     session_leave(se, "show_single_stop");
1234 }
1235
1236
1237 int session_fetch_more(struct session *se)
1238 {
1239     struct client_list *l;
1240     int ret = 0;
1241
1242     for (l = se->clients_active; l; l = l->next)
1243     {
1244         struct client *cl = l->client;
1245         if (client_get_state(cl) == Client_Idle)
1246         {
1247             if (client_fetch_more(cl))
1248             {
1249                 session_log(se, YLOG_LOG, "%s: more to fetch",
1250                             client_get_id(cl));
1251                 ret = 1;
1252             }
1253             else
1254             {
1255                 session_log(se, YLOG_LOG, "%s: no more to fetch",
1256                             client_get_id(cl));
1257             }
1258         }
1259         else
1260         {
1261             session_log(se, YLOG_LOG, "%s: no fetch due to state=%s",
1262                         client_get_id(cl), client_get_state_str(cl));
1263         }
1264
1265     }
1266     return ret;
1267 }
1268
1269 struct record_cluster **show_range_start(struct session *se,
1270                                          struct reclist_sortparms *sp,
1271                                          int start, int *num, int *total,
1272                                          Odr_int *sumhits, Odr_int *approx_hits,
1273                                          void (*show_records_ready)(void *data),
1274                                          struct http_channel *chan)
1275 {
1276     struct record_cluster **recs = 0;
1277     struct reclist_sortparms *spp;
1278     struct client_list *l;
1279     int i;
1280 #if USE_TIMING
1281     yaz_timing_t t = yaz_timing_create();
1282 #endif
1283     session_enter(se, "show_range_start");
1284     *sumhits = 0;
1285     *approx_hits = 0;
1286     *total = 0;
1287     reclist_limit(se->reclist, se);
1288     if (se->relevance)
1289     {
1290         for (spp = sp; spp; spp = spp->next)
1291             if (spp->type == Metadata_sortkey_relevance)
1292             {
1293                 relevance_prepare_read(se->relevance, se->reclist);
1294                 break;
1295             }
1296         for (l = se->clients_active; l; l = l->next) {
1297             *sumhits += client_get_hits(l->client);
1298             *approx_hits += client_get_approximation(l->client);
1299         }
1300     }
1301     reclist_sort(se->reclist, sp);
1302
1303     reclist_enter(se->reclist);
1304     *total = reclist_get_num_records(se->reclist);
1305
1306     for (l = se->clients_active; l; l = l->next)
1307         client_update_show_stat(l->client, 0);
1308
1309     for (i = 0; i < start; i++)
1310     {
1311         struct record_cluster *r = reclist_read_record(se->reclist);
1312         if (!r)
1313         {
1314             *num = 0;
1315             break;
1316         }
1317         else
1318         {
1319             struct record *rec = r->records;
1320             for (;rec; rec = rec->next)
1321                 client_update_show_stat(rec->client, 1);
1322         }
1323     }
1324     if (*num > 0)
1325         recs =
1326             nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1327     for (i = 0; i < *num; i++)
1328     {
1329         struct record_cluster *r = reclist_read_record(se->reclist);
1330         if (!r)
1331         {
1332             *num = i;
1333             break;
1334         }
1335         else
1336         {
1337             struct record *rec = r->records;
1338             for (;rec; rec = rec->next)
1339                 client_update_show_stat(rec->client, 1);
1340             recs[i] = r;
1341         }
1342     }
1343     reclist_leave(se->reclist);
1344 #if USE_TIMING
1345     yaz_timing_stop(t);
1346     session_log(se, YLOG_LOG, "show %6.5f %3.2f %3.2f",
1347             yaz_timing_get_real(t), yaz_timing_get_user(t),
1348             yaz_timing_get_sys(t));
1349     yaz_timing_destroy(&t);
1350 #endif
1351
1352     if (!session_fetch_more(se))
1353         session_log(se, YLOG_LOG, "can not fetch more");
1354     else
1355     {
1356         show_range_stop(se, recs);
1357         session_log(se, YLOG_LOG, "fetching more in progress");
1358         if (session_set_watch(se, SESSION_WATCH_SHOW,
1359                               show_records_ready, chan, chan))
1360         {
1361             session_log(se, YLOG_WARN, "Ignoring show block");
1362             session_enter(se, "show_range_start");
1363         }
1364         else
1365         {
1366             session_log(se, YLOG_LOG, "session watch OK");
1367             return 0;
1368         }
1369     }
1370     return recs;
1371 }
1372
1373 void show_range_stop(struct session *se, struct record_cluster **recs)
1374 {
1375     session_leave(se, "show_range_stop");
1376 }
1377
1378 void statistics(struct session *se, struct statistics *stat)
1379 {
1380     struct client_list *l;
1381     int count = 0;
1382
1383     memset(stat, 0, sizeof(*stat));
1384     stat->num_hits = 0;
1385     for (l = se->clients_active; l; l = l->next)
1386     {
1387         struct client *cl = l->client;
1388         if (!client_get_connection(cl))
1389             stat->num_no_connection++;
1390         stat->num_hits += client_get_hits(cl);
1391         switch (client_get_state(cl))
1392         {
1393         case Client_Connecting: stat->num_connecting++; break;
1394         case Client_Working: stat->num_working++; break;
1395         case Client_Idle: stat->num_idle++; break;
1396         case Client_Failed: stat->num_failed++; break;
1397         case Client_Error: stat->num_error++; break;
1398         default: break;
1399         }
1400         count++;
1401     }
1402     stat->num_records = se->total_records;
1403
1404     stat->num_clients = count;
1405 }
1406
1407 static struct record_metadata *record_metadata_init(
1408     NMEM nmem, const char *value, enum conf_metadata_type type,
1409     struct _xmlAttr *attr)
1410 {
1411     struct record_metadata *rec_md = record_metadata_create(nmem);
1412     struct record_metadata_attr **attrp = &rec_md->attributes;
1413
1414     for (; attr; attr = attr->next)
1415     {
1416         if (attr->children && attr->children->content)
1417         {
1418             if (strcmp((const char *) attr->name, "type")
1419                 && strcmp((const char *) attr->name, "empty"))
1420             {  /* skip the "type" + "empty" attribute..
1421                   The "Type" is already part of the element in output
1422                   (md-%s) and so repeating it here is redundant */
1423                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1424                 (*attrp)->name =
1425                     nmem_strdup(nmem, (const char *) attr->name);
1426                 (*attrp)->value =
1427                     nmem_strdup(nmem, (const char *) attr->children->content);
1428                 attrp = &(*attrp)->next;
1429             }
1430         }
1431     }
1432     *attrp = 0;
1433
1434     if (type == Metadata_type_generic)
1435     {
1436         char *p = nmem_strdup(nmem, value);
1437
1438         p = normalize7bit_generic(p, " ,/.:([");
1439
1440         rec_md->data.text.disp = p;
1441         rec_md->data.text.sort = 0;
1442     }
1443     else if (type == Metadata_type_year || type == Metadata_type_date)
1444     {
1445         int first, last;
1446         int longdate = 0;
1447
1448         if (type == Metadata_type_date)
1449             longdate = 1;
1450         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1451             return 0;
1452
1453         rec_md->data.number.min = first;
1454         rec_md->data.number.max = last;
1455     }
1456     else
1457         return 0;
1458     return rec_md;
1459 }
1460
1461 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1462                                  struct conf_service *service, WRBUF norm_wr)
1463 {
1464     xmlNode *n;
1465     int no_found = 0;
1466     for (n = root->children; n; n = n->next)
1467     {
1468         if (n->type != XML_ELEMENT_NODE)
1469             continue;
1470         if (!strcmp((const char *) n->name, "metadata"))
1471         {
1472             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1473             if (type == NULL) {
1474                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1475             }
1476             else if (!strcmp(name, (const char *) type))
1477             {
1478                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1479                 if (value)
1480                 {
1481                     const char *norm_str;
1482                     pp2_charset_token_t prt =
1483                         pp2_charset_token_create(service->charsets, "mergekey");
1484
1485                     pp2_charset_token_first(prt, (const char *) value, 0);
1486                     if (wrbuf_len(norm_wr) > 0)
1487                         wrbuf_puts(norm_wr, " ");
1488                     wrbuf_puts(norm_wr, name);
1489                     while ((norm_str =
1490                             pp2_charset_token_next(prt)))
1491                     {
1492                         if (*norm_str)
1493                         {
1494                             wrbuf_puts(norm_wr, " ");
1495                             wrbuf_puts(norm_wr, norm_str);
1496                         }
1497                     }
1498                     xmlFree(value);
1499                     pp2_charset_token_destroy(prt);
1500                     no_found++;
1501                 }
1502             }
1503             xmlFree(type);
1504         }
1505     }
1506     return no_found;
1507 }
1508
1509 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1510                                 struct conf_service *service, NMEM nmem)
1511 {
1512     char *mergekey_norm = 0;
1513     xmlNode *root = xmlDocGetRootElement(doc);
1514     WRBUF norm_wr = wrbuf_alloc();
1515
1516     /* consider mergekey from XSL first */
1517     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1518     if (mergekey)
1519     {
1520         const char *norm_str;
1521         pp2_charset_token_t prt =
1522             pp2_charset_token_create(service->charsets, "mergekey");
1523
1524         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1525         while ((norm_str = pp2_charset_token_next(prt)))
1526         {
1527             if (*norm_str)
1528             {
1529                 if (wrbuf_len(norm_wr))
1530                     wrbuf_puts(norm_wr, " ");
1531                 wrbuf_puts(norm_wr, norm_str);
1532             }
1533         }
1534         pp2_charset_token_destroy(prt);
1535         xmlFree(mergekey);
1536     }
1537     else
1538     {
1539         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1540         int field_id;
1541         for (field_id = 0; field_id < service->num_metadata; field_id++)
1542         {
1543             struct conf_metadata *ser_md = &service->metadata[field_id];
1544             if (ser_md->mergekey != Metadata_mergekey_no)
1545             {
1546                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1547                                               service, norm_wr);
1548                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1549                 {
1550                     /* no mergekey on this one and it is required..
1551                        Generate unique key instead */
1552                     wrbuf_rewind(norm_wr);
1553                     break;
1554                 }
1555             }
1556         }
1557     }
1558
1559     /* generate unique key if none is not generated already or is empty */
1560     if (wrbuf_len(norm_wr) == 0)
1561     {
1562         wrbuf_printf(norm_wr, "position: %s-%d",
1563                      client_get_id(cl), record_no);
1564     }
1565     else
1566     {
1567         const char *lead = "content: ";
1568         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1569     }
1570     if (wrbuf_len(norm_wr) > 0)
1571         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1572     wrbuf_destroy(norm_wr);
1573     return mergekey_norm;
1574 }
1575
1576 /** \brief see if metadata for pz:recordfilter exists
1577     \param root xml root element of normalized record
1578     \param sdb session database for client
1579     \retval 0 if there is no metadata for pz:recordfilter
1580     \retval 1 if there is metadata for pz:recordfilter
1581
1582     If there is no pz:recordfilter defined, this function returns 1
1583     as well.
1584 */
1585
1586 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1587 {
1588     int match = 0;
1589     xmlNode *n;
1590     const char *s;
1591     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1592
1593     if (!s || !*s)
1594         return 1;
1595
1596     for (n = root->children; n; n = n->next)
1597     {
1598         if (n->type != XML_ELEMENT_NODE)
1599             continue;
1600         if (!strcmp((const char *) n->name, "metadata"))
1601         {
1602             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1603             if (type)
1604             {
1605                 size_t len;
1606                 int substring;
1607                 const char *eq;
1608
1609                 if ((eq = strchr(s, '=')))
1610                     substring = 0;
1611                 else if ((eq = strchr(s, '~')))
1612                     substring = 1;
1613                 if (eq)
1614                     len = eq - s;
1615                 else
1616                     len = strlen(s);
1617                 if (len == strlen((const char *)type) &&
1618                     !memcmp((const char *) type, s, len))
1619                 {
1620                     xmlChar *value = xmlNodeGetContent(n);
1621                     if (value && *value)
1622                     {
1623                         if (!eq ||
1624                             (substring && strstr((const char *) value, eq+1)) ||
1625                             (!substring && !strcmp((const char *) value, eq + 1)))
1626                             match = 1;
1627                     }
1628                     xmlFree(value);
1629                 }
1630                 xmlFree(type);
1631             }
1632         }
1633     }
1634     return match;
1635 }
1636
1637
1638 static int ingest_to_cluster(struct client *cl,
1639                              xmlDoc *xdoc,
1640                              xmlNode *root,
1641                              int record_no,
1642                              const char *mergekey_norm);
1643
1644 /** \brief ingest XML record
1645     \param cl client holds the result set for record
1646     \param rec record buffer (0 terminated)
1647     \param record_no record position (1, 2, ..)
1648     \param nmem working NMEM
1649     \retval 0 OK
1650     \retval -1 failure
1651     \retval -2 Filtered
1652 */
1653 int ingest_record(struct client *cl, const char *rec,
1654                   int record_no, NMEM nmem)
1655 {
1656     struct session *se = client_get_session(cl);
1657     int ret = 0;
1658     struct session_database *sdb = client_get_database(cl);
1659     struct conf_service *service = se->service;
1660     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1661     xmlNode *root;
1662     const char *mergekey_norm;
1663
1664     if (!xdoc)
1665         return -1;
1666
1667     root = xmlDocGetRootElement(xdoc);
1668
1669     if (!check_record_filter(root, sdb))
1670     {
1671         session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1672         xmlFreeDoc(xdoc);
1673         return -2;
1674     }
1675
1676     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1677     if (!mergekey_norm)
1678     {
1679         session_log(se, YLOG_WARN, "Got no mergekey");
1680         xmlFreeDoc(xdoc);
1681         return -1;
1682     }
1683     session_enter(se, "ingest_record");
1684     if (client_get_session(cl) == se)
1685         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1686     session_leave(se, "ingest_record");
1687
1688     xmlFreeDoc(xdoc);
1689     return ret;
1690 }
1691
1692 //    struct conf_metadata *ser_md = &service->metadata[md_field_id];
1693 //    struct record_metadata *rec_md = record->metadata[md_field_id];
1694 static int match_metadata_local(struct conf_metadata *ser_md,
1695                                 struct record_metadata *rec_md0,
1696                                 char **values, int num_v)
1697 {
1698     int i;
1699     struct record_metadata *rec_md = rec_md0;
1700     for (i = 0; i < num_v; )
1701     {
1702         if (rec_md)
1703         {
1704             if (ser_md->type == Metadata_type_year
1705                 || ser_md->type == Metadata_type_date)
1706             {
1707                 int y = atoi(values[i]);
1708                 if (y >= rec_md->data.number.min
1709                     && y <= rec_md->data.number.max)
1710                     break;
1711             }
1712             else
1713             {
1714                 yaz_log(YLOG_DEBUG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1715                 if (!strcmp(rec_md->data.text.disp, values[i]))
1716                 {
1717                     // Value equals, should not be filtered.
1718                     break;
1719                 }
1720             }
1721             rec_md = rec_md->next;
1722         }
1723         else
1724         {
1725             rec_md = rec_md0;
1726             i++;
1727         }
1728     }
1729     return i < num_v ? 1 : 0;
1730 }
1731
1732 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
1733 {
1734     int i;
1735     struct conf_service *service = se->service;
1736     int ret = 1;
1737     const char *name;
1738     const char *value;
1739     NMEM nmem_tmp = nmem_create();
1740
1741     for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
1742     {
1743         int j;
1744         for (j = 0; j < service->num_metadata; j++)
1745         {
1746             struct conf_metadata *md = service->metadata + j;
1747             if (!strcmp(md->name, name) && md->limitcluster)
1748             {
1749                 char **values = 0;
1750                 int num = 0;
1751                 int md_field_id =
1752                     conf_service_metadata_field_id(service,
1753                                                    md->limitcluster);
1754
1755                 if (md_field_id < 0)
1756                 {
1757                     ret = 0;
1758                     break;
1759                 }
1760
1761                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1762                                       &num, 1, '\\', 1);
1763
1764                 if (!match_metadata_local(&service->metadata[md_field_id],
1765                                           rec->metadata[md_field_id],
1766                                           values, num))
1767                 {
1768                     ret = 0;
1769                     break;
1770                 }
1771             }
1772         }
1773     }
1774     nmem_destroy(nmem_tmp);
1775     return ret;
1776 }
1777
1778 // Skip record on non-zero
1779 static int check_limit_local(struct client *cl,
1780                              struct record *record,
1781                              int record_no)
1782 {
1783     int skip_record = 0;
1784     struct session *se = client_get_session(cl);
1785     struct conf_service *service = se->service;
1786     NMEM nmem_tmp = nmem_create();
1787     struct session_database *sdb = client_get_database(cl);
1788     int l = 0;
1789     while (!skip_record)
1790     {
1791         int md_field_id;
1792         char **values = 0;
1793         int num_v = 0;
1794         const char *name =
1795             client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
1796                                          &num_v, &values);
1797         if (!name)
1798             break;
1799
1800         if (!strcmp(name, "*"))
1801         {
1802             for (md_field_id = 0; md_field_id < service->num_metadata;
1803                  md_field_id++)
1804             {
1805                 if (match_metadata_local(
1806                         &service->metadata[md_field_id],
1807                         record->metadata[md_field_id],
1808                         values, num_v))
1809                     break;
1810             }
1811             if (md_field_id == service->num_metadata)
1812                 skip_record = 1;
1813         }
1814         else
1815         {
1816             md_field_id = conf_service_metadata_field_id(service, name);
1817             if (md_field_id < 0)
1818             {
1819                 skip_record = 1;
1820                 break;
1821             }
1822             if (!match_metadata_local(
1823                     &service->metadata[md_field_id],
1824                     record->metadata[md_field_id],
1825                     values, num_v))
1826             {
1827                 skip_record = 1;
1828             }
1829         }
1830     }
1831     nmem_destroy(nmem_tmp);
1832     return skip_record;
1833 }
1834
1835 static int ingest_to_cluster(struct client *cl,
1836                              xmlDoc *xdoc,
1837                              xmlNode *root,
1838                              int record_no,
1839                              const char *mergekey_norm)
1840 {
1841     xmlNode *n;
1842     xmlChar *type = 0;
1843     xmlChar *value = 0;
1844     struct session *se = client_get_session(cl);
1845     struct conf_service *service = se->service;
1846     int term_factor = 1;
1847     struct record_cluster *cluster;
1848     struct record_metadata **metadata0;
1849     struct session_database *sdb = client_get_database(cl);
1850     struct record *record = record_create(se->nmem,
1851                                           service->num_metadata,
1852                                           service->num_sortkeys, cl,
1853                                           record_no);
1854
1855     for (n = root->children; n; n = n->next)
1856     {
1857         if (type)
1858             xmlFree(type);
1859         if (value)
1860             xmlFree(value);
1861         type = value = 0;
1862
1863         if (n->type != XML_ELEMENT_NODE)
1864             continue;
1865         if (!strcmp((const char *) n->name, "metadata"))
1866         {
1867             struct conf_metadata *ser_md = 0;
1868             struct record_metadata **wheretoput = 0;
1869             struct record_metadata *rec_md = 0;
1870             int md_field_id = -1;
1871
1872             type = xmlGetProp(n, (xmlChar *) "type");
1873             value = xmlNodeListGetString(xdoc, n->children, 1);
1874             if (!type)
1875                 continue;
1876             if (!value || !*value)
1877             {
1878                 xmlChar *empty = xmlGetProp(n, (xmlChar *) "empty");
1879                 if (!empty)
1880                     continue;
1881                 if (value)
1882                     xmlFree(value);
1883                 value = empty;
1884             }
1885             md_field_id
1886                 = conf_service_metadata_field_id(service, (const char *) type);
1887             if (md_field_id < 0)
1888             {
1889                 if (se->number_of_warnings_unknown_metadata == 0)
1890                 {
1891                     session_log(se, YLOG_WARN,
1892                             "Ignoring unknown metadata element: %s", type);
1893                 }
1894                 se->number_of_warnings_unknown_metadata++;
1895                 continue;
1896             }
1897
1898             ser_md = &service->metadata[md_field_id];
1899
1900             // non-merged metadata
1901             rec_md = record_metadata_init(se->nmem, (const char *) value,
1902                                           ser_md->type, n->properties);
1903             if (!rec_md)
1904             {
1905                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1906                             "for element '%s'", value, type);
1907                 continue;
1908             }
1909             wheretoput = &record->metadata[md_field_id];
1910             while (*wheretoput)
1911                 wheretoput = &(*wheretoput)->next;
1912             *wheretoput = rec_md;
1913         }
1914     }
1915
1916     if (check_limit_local(cl, record, record_no))
1917     {
1918         session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1919                     record_no, sdb->database->id);
1920         if (type)
1921             xmlFree(type);
1922         if (value)
1923             xmlFree(value);
1924         return -2;
1925     }
1926     cluster = reclist_insert(se->reclist, service, record,
1927                              mergekey_norm, &se->total_merged);
1928     if (!cluster)
1929         return 0; // complete match with existing record
1930
1931     {
1932         const char *use_term_factor_str =
1933             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1934         if (use_term_factor_str && use_term_factor_str[0] == '1')
1935         {
1936             int maxrecs = client_get_maxrecs(cl);
1937             int hits = (int) client_get_hits(cl);
1938             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1939             assert(term_factor >= 1);
1940             session_log(se, YLOG_DEBUG, "Using term factor: %d (%d / %d)",
1941                         term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1942         }
1943     }
1944
1945     if (global_parameters.dump_records)
1946         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1947                     sdb->database->id, record_no);
1948
1949
1950     relevance_newrec(se->relevance, cluster);
1951
1952     // original metadata, to check if first existence of a field
1953     metadata0 = xmalloc(sizeof(*metadata0) * service->num_metadata);
1954     memcpy(metadata0, cluster->metadata,
1955            sizeof(*metadata0) * service->num_metadata);
1956
1957     // now parsing XML record and adding data to cluster or record metadata
1958     for (n = root->children; n; n = n->next)
1959     {
1960         pp2_charset_token_t prt;
1961         if (type)
1962             xmlFree(type);
1963         if (value)
1964             xmlFree(value);
1965         type = value = 0;
1966
1967         if (n->type != XML_ELEMENT_NODE)
1968             continue;
1969         if (!strcmp((const char *) n->name, "metadata"))
1970         {
1971             struct conf_metadata *ser_md = 0;
1972             struct conf_sortkey *ser_sk = 0;
1973             struct record_metadata **wheretoput = 0;
1974             struct record_metadata *rec_md = 0;
1975             int md_field_id = -1;
1976             int sk_field_id = -1;
1977             const char *rank;
1978             xmlChar *xml_rank;
1979
1980             type = xmlGetProp(n, (xmlChar *) "type");
1981             value = xmlNodeListGetString(xdoc, n->children, 1);
1982
1983             if (!type || !value || !*value)
1984                 continue;
1985
1986             md_field_id
1987                 = conf_service_metadata_field_id(service, (const char *) type);
1988             if (md_field_id < 0)
1989                 continue;
1990
1991             ser_md = &service->metadata[md_field_id];
1992
1993             if (ser_md->sortkey_offset >= 0)
1994             {
1995                 sk_field_id = ser_md->sortkey_offset;
1996                 ser_sk = &service->sortkeys[sk_field_id];
1997             }
1998
1999             // merged metadata
2000             rec_md = record_metadata_init(se->nmem, (const char *) value,
2001                                           ser_md->type, 0);
2002
2003             // see if the field was not in cluster already (from beginning)
2004
2005             if (!rec_md)
2006                 continue;
2007
2008             xml_rank = xmlGetProp(n, (xmlChar *) "rank");
2009             rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
2010
2011             wheretoput = &cluster->metadata[md_field_id];
2012
2013             if (ser_md->merge == Metadata_merge_first)
2014             {
2015                 if (!metadata0[md_field_id])
2016                 {
2017                     while (*wheretoput)
2018                         wheretoput = &(*wheretoput)->next;
2019                     *wheretoput = rec_md;
2020                 }
2021             }
2022             else if (ser_md->merge == Metadata_merge_unique)
2023             {
2024                 while (*wheretoput)
2025                 {
2026                     if (!strcmp((const char *) (*wheretoput)->data.text.disp,
2027                                 rec_md->data.text.disp))
2028                         break;
2029                     wheretoput = &(*wheretoput)->next;
2030                 }
2031                 if (!*wheretoput)
2032                     *wheretoput = rec_md;
2033             }
2034             else if (ser_md->merge == Metadata_merge_longest)
2035             {
2036                 if (!*wheretoput
2037                     || strlen(rec_md->data.text.disp)
2038                     > strlen((*wheretoput)->data.text.disp))
2039                 {
2040                     *wheretoput = rec_md;
2041                     if (ser_sk)
2042                     {
2043                         const char *sort_str = 0;
2044                         int skip_article =
2045                             ser_sk->type == Metadata_sortkey_skiparticle;
2046
2047                         if (!cluster->sortkeys[sk_field_id])
2048                             cluster->sortkeys[sk_field_id] =
2049                                 nmem_malloc(se->nmem,
2050                                             sizeof(union data_types));
2051
2052                         prt =
2053                             pp2_charset_token_create(service->charsets, "sort");
2054
2055                         pp2_charset_token_first(prt, rec_md->data.text.disp,
2056                                                 skip_article);
2057
2058                         pp2_charset_token_next(prt);
2059
2060                         sort_str = pp2_get_sort(prt);
2061
2062                         cluster->sortkeys[sk_field_id]->text.disp =
2063                             rec_md->data.text.disp;
2064                         if (!sort_str)
2065                         {
2066                             sort_str = rec_md->data.text.disp;
2067                             session_log(se, YLOG_WARN,
2068                                     "Could not make sortkey. Bug #1858");
2069                         }
2070                         cluster->sortkeys[sk_field_id]->text.sort =
2071                             nmem_strdup(se->nmem, sort_str);
2072                         pp2_charset_token_destroy(prt);
2073                     }
2074                 }
2075             }
2076             else if (ser_md->merge == Metadata_merge_all)
2077             {
2078                 while (*wheretoput)
2079                     wheretoput = &(*wheretoput)->next;
2080                 *wheretoput = rec_md;
2081             }
2082             else if (ser_md->merge == Metadata_merge_range)
2083             {
2084                 if (!*wheretoput)
2085                 {
2086                     *wheretoput = rec_md;
2087                     if (ser_sk)
2088                         cluster->sortkeys[sk_field_id]
2089                             = &rec_md->data;
2090                 }
2091                 else
2092                 {
2093                     int this_min = rec_md->data.number.min;
2094                     int this_max = rec_md->data.number.max;
2095                     if (this_min < (*wheretoput)->data.number.min)
2096                         (*wheretoput)->data.number.min = this_min;
2097                     if (this_max > (*wheretoput)->data.number.max)
2098                         (*wheretoput)->data.number.max = this_max;
2099                 }
2100             }
2101
2102             // ranking of _all_ fields enabled ...
2103             if (rank)
2104             {
2105                 relevance_countwords(se->relevance, cluster,
2106                                      (char *) value, rank, ser_md->name);
2107             }
2108
2109             // construct facets ... unless the client already has reported them
2110             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2111             {
2112                 if (ser_md->type == Metadata_type_year)
2113                 {
2114                     char year[64];
2115                     sprintf(year, "%d", rec_md->data.number.max);
2116
2117                     add_facet(se, (char *) type, year, term_factor);
2118                     if (rec_md->data.number.max != rec_md->data.number.min)
2119                     {
2120                         sprintf(year, "%d", rec_md->data.number.min);
2121                         add_facet(se, (char *) type, year, term_factor);
2122                     }
2123                 }
2124                 else
2125                     add_facet(se, (char *) type, (char *) value, term_factor);
2126             }
2127
2128             // cleaning up
2129             if (xml_rank)
2130                 xmlFree(xml_rank);
2131             xmlFree(type);
2132             xmlFree(value);
2133             type = value = 0;
2134         }
2135         else
2136         {
2137             if (se->number_of_warnings_unknown_elements == 0)
2138                 session_log(se, YLOG_WARN,
2139                         "Unexpected element in internal record: %s", n->name);
2140             se->number_of_warnings_unknown_elements++;
2141         }
2142     }
2143     if (type)
2144         xmlFree(type);
2145     if (value)
2146         xmlFree(value);
2147
2148     xfree(metadata0);
2149     relevance_donerecord(se->relevance, cluster);
2150     se->total_records++;
2151
2152     return 0;
2153 }
2154
2155 void session_log(struct session *s, int level, const char *fmt, ...)
2156 {
2157     char buf[1024];
2158     va_list ap;
2159     va_start(ap, fmt);
2160
2161     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2162     yaz_log(level, "Session %u: %s", s->session_id, buf);
2163
2164     va_end(ap);
2165 }
2166
2167 /*
2168  * Local variables:
2169  * c-basic-offset: 4
2170  * c-file-style: "Stroustrup"
2171  * indent-tabs-mode: nil
2172  * End:
2173  * vim: shiftwidth=4 tabstop=8 expandtab
2174  */
2175