148f462961e107992e7510b392441ce69e9a1a4d
[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 0
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         yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
185                 icu_chain_id, type);
186         wrbuf_destroy(facet_wrbuf);
187         wrbuf_destroy(display_wrbuf);
188         return;
189     }
190     pp2_charset_token_first(prt, value, 0);
191     while ((facet_component = pp2_charset_token_next(prt)))
192     {
193         const char *display_component;
194         if (*facet_component)
195         {
196             if (wrbuf_len(facet_wrbuf))
197                 wrbuf_puts(facet_wrbuf, " ");
198             wrbuf_puts(facet_wrbuf, facet_component);
199         }
200         display_component = pp2_get_display(prt);
201         if (display_component)
202         {
203             if (wrbuf_len(display_wrbuf))
204                 wrbuf_puts(display_wrbuf, " ");
205             wrbuf_puts(display_wrbuf, display_component);
206         }
207     }
208     pp2_charset_token_destroy(prt);
209 }
210
211 void add_facet(struct session *s, const char *type, const char *value, int count)
212 {
213     WRBUF facet_wrbuf = wrbuf_alloc();
214     WRBUF display_wrbuf = wrbuf_alloc();
215
216     session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
217
218     if (wrbuf_len(facet_wrbuf))
219     {
220         int i;
221         for (i = 0; i < s->num_termlists; i++)
222             if (!strcmp(s->termlists[i].name, type))
223                 break;
224         if (i == s->num_termlists)
225         {
226             if (i == SESSION_MAX_TERMLISTS)
227             {
228                 session_log(s, YLOG_FATAL, "Too many termlists");
229                 wrbuf_destroy(facet_wrbuf);
230                 wrbuf_destroy(display_wrbuf);
231                 return;
232             }
233
234             s->termlists[i].name = nmem_strdup(s->nmem, type);
235             s->termlists[i].termlist = termlist_create(s->nmem);
236             s->num_termlists = i + 1;
237         }
238
239 #if 0
240         session_log(s, YLOG_LOG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
241 #endif
242         termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
243                         wrbuf_cstr(facet_wrbuf), count);
244     }
245     wrbuf_destroy(facet_wrbuf);
246     wrbuf_destroy(display_wrbuf);
247 }
248
249 static xmlDoc *record_to_xml(struct session *se,
250                              struct session_database *sdb, const char *rec)
251 {
252     struct database *db = sdb->database;
253     xmlDoc *rdoc = 0;
254
255     rdoc = xmlParseMemory(rec, strlen(rec));
256
257     if (!rdoc)
258     {
259         session_log(se, YLOG_WARN, "Non-wellformed XML");
260         return 0;
261     }
262
263     if (global_parameters.dump_records)
264     {
265         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
266         log_xml_doc(rdoc);
267     }
268
269     return rdoc;
270 }
271
272 #define MAX_XSLT_ARGS 16
273
274 // Add static values from session database settings if applicable
275 static void insert_settings_parameters(struct session_database *sdb,
276                                        struct conf_service *service,
277                                        char **parms,
278                                        NMEM nmem)
279 {
280     int i;
281     int nparms = 0;
282     int offset = 0;
283
284     for (i = 0; i < service->num_metadata; i++)
285     {
286         struct conf_metadata *md = &service->metadata[i];
287         int setting;
288
289         if (md->setting == Metadata_setting_parameter &&
290             (setting = settings_lookup_offset(service, md->name)) >= 0)
291         {
292             const char *val = session_setting_oneval(sdb, setting);
293             if (val && nparms < MAX_XSLT_ARGS)
294             {
295                 char *buf;
296                 int len = strlen(val);
297                 buf = nmem_malloc(nmem, len + 3);
298                 buf[0] = '\'';
299                 strcpy(buf + 1, val);
300                 buf[len+1] = '\'';
301                 buf[len+2] = '\0';
302                 parms[offset++] = md->name;
303                 parms[offset++] = buf;
304                 nparms++;
305             }
306         }
307     }
308     parms[offset] = 0;
309 }
310
311 // Add static values from session database settings if applicable
312 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
313     struct conf_service *service)
314 {
315     int i;
316
317     for (i = 0; i < service->num_metadata; i++)
318     {
319         struct conf_metadata *md = &service->metadata[i];
320         int offset;
321
322         if (md->setting == Metadata_setting_postproc &&
323             (offset = settings_lookup_offset(service, md->name)) >= 0)
324         {
325             const char *val = session_setting_oneval(sdb, offset);
326             if (val)
327             {
328                 xmlNode *r = xmlDocGetRootElement(doc);
329                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
330                                              (xmlChar *) val);
331                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
332             }
333         }
334     }
335 }
336
337 static xmlDoc *normalize_record(struct session *se,
338                                 struct session_database *sdb,
339                                 struct conf_service *service,
340                                 const char *rec, NMEM nmem)
341 {
342     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
343
344     if (rdoc)
345     {
346         char *parms[MAX_XSLT_ARGS*2+1];
347
348         insert_settings_parameters(sdb, service, parms, nmem);
349
350         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
351         {
352             session_log(se, YLOG_WARN, "Normalize failed");
353         }
354         else
355         {
356             insert_settings_values(sdb, rdoc, service);
357
358             if (global_parameters.dump_records)
359             {
360                 session_log(se, YLOG_LOG, "Normalized record from %s",
361                             sdb->database->id);
362                 log_xml_doc(rdoc);
363             }
364         }
365     }
366     return rdoc;
367 }
368
369 void session_settings_dump(struct session *se,
370                            struct session_database *db,
371                            WRBUF w)
372 {
373     if (db->settings)
374     {
375         int i, num = db->num_settings;
376         for (i = 0; i < num; i++)
377         {
378             struct setting *s = db->settings[i];
379             for (;s ; s = s->next)
380             {
381                 wrbuf_puts(w, "<set name=\"");
382                 wrbuf_xmlputs(w, s->name);
383                 wrbuf_puts(w, "\" value=\"");
384                 wrbuf_xmlputs(w, s->value);
385                 wrbuf_puts(w, "\"/>");
386             }
387             if (db->settings[i])
388                 wrbuf_puts(w, "\n");
389         }
390     }
391 }
392
393 // Retrieve first defined value for 'name' for given database.
394 // Will be extended to take into account user associated with session
395 const char *session_setting_oneval(struct session_database *db, int offset)
396 {
397     if (offset >= db->num_settings || !db->settings[offset])
398         return "";
399     return db->settings[offset]->value;
400 }
401
402 // Prepare XSLT stylesheets for record normalization
403 // Structures are allocated on the session_wide nmem to avoid having
404 // to recompute this for every search. This would lead
405 // to leaking if a single session was to repeatedly change the PZ_XSLT
406 // setting. However, this is not a realistic use scenario.
407 static int prepare_map(struct session *se, struct session_database *sdb)
408 {
409     if (sdb->settings && !sdb->map)
410     {
411         const char *s;
412
413         if (sdb->settings[PZ_XSLT] &&
414             (s = session_setting_oneval(sdb, PZ_XSLT)))
415         {
416             char auto_stylesheet[256];
417
418             if (!strcmp(s, "auto"))
419             {
420                 const char *request_syntax = session_setting_oneval(
421                     sdb, PZ_REQUESTSYNTAX);
422                 if (request_syntax)
423                 {
424                     char *cp;
425                     yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
426                                  "%s.xsl", request_syntax);
427                     for (cp = auto_stylesheet; *cp; cp++)
428                     {
429                         /* deliberately only consider ASCII */
430                         if (*cp > 32 && *cp < 127)
431                             *cp = tolower(*cp);
432                     }
433                     s = auto_stylesheet;
434                 }
435                 else
436                 {
437                     session_log(se, YLOG_WARN,
438                                 "No pz:requestsyntax for auto stylesheet");
439                 }
440             }
441             sdb->map = normalize_cache_get(se->normalize_cache,
442                                            se->service, s);
443             if (!sdb->map)
444                 return -1;
445         }
446     }
447     return 0;
448 }
449
450 // called if watch should be removed because http_channel is to be destroyed
451 static void session_watch_cancel(void *data, struct http_channel *c,
452                                  void *data2)
453 {
454     struct session_watchentry *ent = data;
455
456     ent->fun = 0;
457     ent->data = 0;
458     ent->obs = 0;
459 }
460
461 // set watch. Returns 0=OK, -1 if watch is already set
462 int session_set_watch(struct session *s, int what,
463                       session_watchfun fun, void *data,
464                       struct http_channel *chan)
465 {
466     int ret;
467     session_enter(s, "session_set_watch");
468     if (s->watchlist[what].fun)
469         ret = -1;
470     else
471     {
472
473         s->watchlist[what].fun = fun;
474         s->watchlist[what].data = data;
475         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
476                                                    session_watch_cancel);
477         ret = 0;
478     }
479     session_leave(s, "session_set_watch");
480     return ret;
481 }
482
483 void session_alert_watch(struct session *s, int what)
484 {
485     assert(s);
486     session_enter(s, "session_alert_watch");
487     if (s->watchlist[what].fun)
488     {
489         /* our watch is no longer associated with http_channel */
490         void *data;
491         session_watchfun fun;
492
493         http_remove_observer(s->watchlist[what].obs);
494         fun  = s->watchlist[what].fun;
495         data = s->watchlist[what].data;
496
497         /* reset watch before fun is invoked - in case fun wants to set
498            it again */
499         s->watchlist[what].fun = 0;
500         s->watchlist[what].data = 0;
501         s->watchlist[what].obs = 0;
502
503         session_leave(s, "session_alert_watch");
504         session_log(s, YLOG_DEBUG,
505                     "Alert Watch: %d calling function: %p", what, fun);
506         fun(data);
507     }
508     else
509         session_leave(s,"session_alert_watch");
510 }
511
512 //callback for grep_databases
513 static void select_targets_callback(struct session *se,
514                                     struct session_database *db)
515 {
516     struct client *cl;
517     struct client_list *l;
518
519     for (l = se->clients_cached; l; l = l->next)
520         if (client_get_database(l->client) == db)
521             break;
522
523     if (l)
524         cl = l->client;
525     else
526     {
527         cl = client_create(db->database->id);
528         client_set_database(cl, db);
529
530         l = xmalloc(sizeof(*l));
531         l->client = cl;
532         l->next = se->clients_cached;
533         se->clients_cached = l;
534     }
535     /* set session always. If may be 0 if client is not active */
536     client_set_session(cl, se);
537
538     l = xmalloc(sizeof(*l));
539     l->client = cl;
540     l->next = se->clients_active;
541     se->clients_active = l;
542 }
543
544 static void session_reset_active_clients(struct session *se,
545                                          struct client_list *new_list)
546 {
547     struct client_list *l;
548
549     session_enter(se, "session_reset_active_clients");
550     l = se->clients_active;
551     se->clients_active = new_list;
552     session_leave(se, "session_reset_active_clients");
553
554     while (l)
555     {
556         struct client_list *l_next = l->next;
557
558         client_lock(l->client);
559         client_set_session(l->client, 0); /* mark client inactive */
560         client_unlock(l->client);
561
562         xfree(l);
563         l = l_next;
564     }
565 }
566
567 static void session_remove_cached_clients(struct session *se)
568 {
569     struct client_list *l;
570
571     session_reset_active_clients(se, 0);
572
573     session_enter(se, "session_remove_cached_clients");
574     l = se->clients_cached;
575     se->clients_cached = 0;
576     session_leave(se, "session_remove_cached_clients");
577
578     while (l)
579     {
580         struct client_list *l_next = l->next;
581         client_lock(l->client);
582         client_set_session(l->client, 0);
583         client_set_database(l->client, 0);
584         client_unlock(l->client);
585         client_destroy(l->client);
586         xfree(l);
587         l = l_next;
588     }
589 }
590
591 // Associates a set of clients with a session;
592 // Note: Session-databases represent databases with per-session
593 // setting overrides
594 static int select_targets(struct session *se, const char *filter)
595 {
596     return session_grep_databases(se, filter, select_targets_callback);
597 }
598
599 int session_active_clients(struct session *s)
600 {
601     struct client_list *l;
602     int res = 0;
603
604     for (l = s->clients_active; l; l = l->next)
605         if (client_is_active(l->client))
606             res++;
607
608     return res;
609 }
610
611 int session_is_preferred_clients_ready(struct session *s)
612 {
613     struct client_list *l;
614     int res = 0;
615
616     for (l = s->clients_active; l; l = l->next)
617         if (client_is_active_preferred(l->client))
618             res++;
619     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
620     return res == 0;
621 }
622
623 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
624 {
625     reclist_destroy(se->reclist);
626     se->reclist = 0;
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     /* reset list of sorted results and clear to relevance search */
635     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
636     se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
637     se->sorted_results->increasing = sp->increasing;
638     se->sorted_results->type = sp->type;
639     se->sorted_results->next = 0;
640
641     session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
642             sp->name, sp->increasing, sp->type);
643
644     se->reclist = reclist_create(se->nmem);
645 }
646
647 static void session_sort_unlocked(struct session *se, struct reclist_sortparms *sp)
648 {
649     struct reclist_sortparms *sr;
650     struct client_list *l;
651     const char *field = sp->name;
652     int increasing = sp->increasing;
653     int type  = sp->type;
654     int clients_research = 0;
655
656     yaz_log(YLOG_LOG, "session_sort field=%s increasing=%d type=%d", field, increasing, type);
657     /* see if we already have sorted for this criteria */
658     for (sr = se->sorted_results; sr; sr = sr->next)
659     {
660         if (!reclist_sortparms_cmp(sr,sp))
661             break;
662     }
663     if (sr)
664     {
665         session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d already fetched",
666                     field, increasing, type);
667         return;
668     }
669     session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d must fetch",
670                     field, increasing, type);
671
672     // We need to reset reclist on every sort that changes the records, not just for position
673     // So if just one client requires new searching, we need to clear set.
674     // Ask each of the client if sorting requires re-search due to native sort
675     // If it does it will require us to
676     for (l = se->clients_active; l; l = l->next)
677     {
678         struct client *cl = l->client;
679         // Assume no re-search is required.
680         client_parse_init(cl, 1);
681         clients_research += client_parse_sort(cl, sp);
682     }
683     if (clients_research) {
684         yaz_log(YLOG_DEBUG, "Reset results due to %d clients researching", clients_research);
685         session_clear_set(se, sp);
686     }
687     else {
688         // A new sorting based on same record set
689         sr = nmem_malloc(se->nmem, sizeof(*sr));
690         sr->name = nmem_strdup(se->nmem, field);
691         sr->increasing = increasing;
692         sr->type = type;
693         sr->next = se->sorted_results;
694         se->sorted_results = sr;
695         session_log(se, YLOG_DEBUG, "No research/ingesting done");
696         return ;
697     }
698     session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
699
700     for (l = se->clients_active; l; l = l->next)
701     {
702         struct client *cl = l->client;
703         if (client_get_state(cl) == Client_Connecting ||
704             client_get_state(cl) == Client_Idle ||
705             client_get_state(cl) == Client_Working) {
706             client_start_search(cl);
707         }
708         else {
709             yaz_log(YLOG_DEBUG, "Client %s: No re-start/ingest in show. Wrong client state: %d",
710                         client_get_id(cl), client_get_state(cl));
711         }
712
713     }
714 }
715
716 void session_sort(struct session *se, struct reclist_sortparms *sp) {
717     //session_enter(se, "session_sort");
718     session_sort_unlocked(se, sp);
719     //session_leave(se, "session_sort");
720 }
721
722
723 enum pazpar2_error_code session_search(struct session *se,
724                                        const char *query,
725                                        const char *startrecs,
726                                        const char *maxrecs,
727                                        const char *filter,
728                                        const char *limit,
729                                        const char **addinfo,
730                                        struct reclist_sortparms *sp)
731 {
732     int live_channels = 0;
733     int no_working = 0;
734     int no_failed_query = 0;
735     int no_failed_limit = 0;
736     struct client_list *l, *l0;
737     int same_sort_order = 0;
738
739     session_log(se, YLOG_DEBUG, "Search");
740
741     *addinfo = 0;
742
743     if (se->settings_modified) {
744         session_remove_cached_clients(se);
745     }
746     else
747         session_reset_active_clients(se, 0);
748
749     session_enter(se, "session_search");
750     se->settings_modified = 0;
751
752     if (se->sorted_results) {
753         if (!reclist_sortparms_cmp(se->sorted_results, sp))
754             same_sort_order = 1;
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 {
1274     struct record_cluster **recs = 0;
1275     struct reclist_sortparms *spp;
1276     struct client_list *l;
1277     int i;
1278 #if USE_TIMING
1279     yaz_timing_t t = yaz_timing_create();
1280 #endif
1281     session_enter(se, "show_range_start");
1282     *sumhits = 0;
1283     *approx_hits = 0;
1284     *total = 0;
1285     reclist_limit(se->reclist, se);
1286     if (se->relevance)
1287     {
1288         for (spp = sp; spp; spp = spp->next)
1289             if (spp->type == Metadata_sortkey_relevance)
1290             {
1291                 relevance_prepare_read(se->relevance, se->reclist);
1292                 break;
1293             }
1294         for (l = se->clients_active; l; l = l->next) {
1295             *sumhits += client_get_hits(l->client);
1296             *approx_hits += client_get_approximation(l->client);
1297         }
1298     }
1299     reclist_sort(se->reclist, sp);
1300
1301     reclist_enter(se->reclist);
1302     *total = reclist_get_num_records(se->reclist);
1303
1304     for (i = 0; i < start; i++)
1305         if (!reclist_read_record(se->reclist))
1306         {
1307             *num = 0;
1308             break;
1309         }
1310
1311     if (*num > 0)
1312         recs =
1313             nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1314     for (i = 0; i < *num; i++)
1315     {
1316         struct record_cluster *r = reclist_read_record(se->reclist);
1317         if (!r)
1318         {
1319             *num = i;
1320             break;
1321         }
1322         recs[i] = r;
1323     }
1324     reclist_leave(se->reclist);
1325 #if USE_TIMING
1326     yaz_timing_stop(t);
1327     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1328             yaz_timing_get_real(t), yaz_timing_get_user(t),
1329             yaz_timing_get_sys(t));
1330     yaz_timing_destroy(&t);
1331 #endif
1332     return recs;
1333 }
1334
1335 void show_range_stop(struct session *se, struct record_cluster **recs)
1336 {
1337     session_leave(se, "show_range_stop");
1338 }
1339
1340 void statistics(struct session *se, struct statistics *stat)
1341 {
1342     struct client_list *l;
1343     int count = 0;
1344
1345     memset(stat, 0, sizeof(*stat));
1346     stat->num_hits = 0;
1347     for (l = se->clients_active; l; l = l->next)
1348     {
1349         struct client *cl = l->client;
1350         if (!client_get_connection(cl))
1351             stat->num_no_connection++;
1352         stat->num_hits += client_get_hits(cl);
1353         switch (client_get_state(cl))
1354         {
1355         case Client_Connecting: stat->num_connecting++; break;
1356         case Client_Working: stat->num_working++; break;
1357         case Client_Idle: stat->num_idle++; break;
1358         case Client_Failed: stat->num_failed++; break;
1359         case Client_Error: stat->num_error++; break;
1360         default: break;
1361         }
1362         count++;
1363     }
1364     stat->num_records = se->total_records;
1365
1366     stat->num_clients = count;
1367 }
1368
1369 static struct record_metadata *record_metadata_init(
1370     NMEM nmem, const char *value, enum conf_metadata_type type,
1371     struct _xmlAttr *attr)
1372 {
1373     struct record_metadata *rec_md = record_metadata_create(nmem);
1374     struct record_metadata_attr **attrp = &rec_md->attributes;
1375
1376     for (; attr; attr = attr->next)
1377     {
1378         if (attr->children && attr->children->content)
1379         {
1380             if (strcmp((const char *) attr->name, "type"))
1381             {  /* skip the "type" attribute.. Its value is already part of
1382                   the element in output (md-%s) and so repeating it here
1383                   is redundant */
1384                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1385                 (*attrp)->name =
1386                     nmem_strdup(nmem, (const char *) attr->name);
1387                 (*attrp)->value =
1388                     nmem_strdup(nmem, (const char *) attr->children->content);
1389                 attrp = &(*attrp)->next;
1390             }
1391         }
1392     }
1393     *attrp = 0;
1394
1395     if (type == Metadata_type_generic)
1396     {
1397         char *p = nmem_strdup(nmem, value);
1398
1399         p = normalize7bit_generic(p, " ,/.:([");
1400
1401         rec_md->data.text.disp = p;
1402         rec_md->data.text.sort = 0;
1403     }
1404     else if (type == Metadata_type_year || type == Metadata_type_date)
1405     {
1406         int first, last;
1407         int longdate = 0;
1408
1409         if (type == Metadata_type_date)
1410             longdate = 1;
1411         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1412             return 0;
1413
1414         rec_md->data.number.min = first;
1415         rec_md->data.number.max = last;
1416     }
1417     else
1418         return 0;
1419     return rec_md;
1420 }
1421
1422 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1423                                  struct conf_service *service, WRBUF norm_wr)
1424 {
1425     xmlNode *n;
1426     int no_found = 0;
1427     for (n = root->children; n; n = n->next)
1428     {
1429         if (n->type != XML_ELEMENT_NODE)
1430             continue;
1431         if (!strcmp((const char *) n->name, "metadata"))
1432         {
1433             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1434             if (type == NULL) {
1435                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1436             }
1437             else if (!strcmp(name, (const char *) type))
1438             {
1439                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1440                 if (value)
1441                 {
1442                     const char *norm_str;
1443                     pp2_charset_token_t prt =
1444                         pp2_charset_token_create(service->charsets, "mergekey");
1445
1446                     pp2_charset_token_first(prt, (const char *) value, 0);
1447                     if (wrbuf_len(norm_wr) > 0)
1448                         wrbuf_puts(norm_wr, " ");
1449                     wrbuf_puts(norm_wr, name);
1450                     while ((norm_str =
1451                             pp2_charset_token_next(prt)))
1452                     {
1453                         if (*norm_str)
1454                         {
1455                             wrbuf_puts(norm_wr, " ");
1456                             wrbuf_puts(norm_wr, norm_str);
1457                         }
1458                     }
1459                     xmlFree(value);
1460                     pp2_charset_token_destroy(prt);
1461                     no_found++;
1462                 }
1463             }
1464             xmlFree(type);
1465         }
1466     }
1467     return no_found;
1468 }
1469
1470 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1471                                 struct conf_service *service, NMEM nmem)
1472 {
1473     char *mergekey_norm = 0;
1474     xmlNode *root = xmlDocGetRootElement(doc);
1475     WRBUF norm_wr = wrbuf_alloc();
1476
1477     /* consider mergekey from XSL first */
1478     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1479     if (mergekey)
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 *) mergekey, 0);
1486         while ((norm_str = pp2_charset_token_next(prt)))
1487         {
1488             if (*norm_str)
1489             {
1490                 if (wrbuf_len(norm_wr))
1491                     wrbuf_puts(norm_wr, " ");
1492                 wrbuf_puts(norm_wr, norm_str);
1493             }
1494         }
1495         pp2_charset_token_destroy(prt);
1496         xmlFree(mergekey);
1497     }
1498     else
1499     {
1500         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1501         int field_id;
1502         for (field_id = 0; field_id < service->num_metadata; field_id++)
1503         {
1504             struct conf_metadata *ser_md = &service->metadata[field_id];
1505             if (ser_md->mergekey != Metadata_mergekey_no)
1506             {
1507                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1508                                               service, norm_wr);
1509                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1510                 {
1511                     /* no mergekey on this one and it is required..
1512                        Generate unique key instead */
1513                     wrbuf_rewind(norm_wr);
1514                     break;
1515                 }
1516             }
1517         }
1518     }
1519
1520     /* generate unique key if none is not generated already or is empty */
1521     if (wrbuf_len(norm_wr) == 0)
1522     {
1523         wrbuf_printf(norm_wr, "position: %s-%d",
1524                      client_get_id(cl), record_no);
1525     }
1526     else
1527     {
1528         const char *lead = "content: ";
1529         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1530     }
1531     if (wrbuf_len(norm_wr) > 0)
1532         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1533     wrbuf_destroy(norm_wr);
1534     return mergekey_norm;
1535 }
1536
1537 /** \brief see if metadata for pz:recordfilter exists
1538     \param root xml root element of normalized record
1539     \param sdb session database for client
1540     \retval 0 if there is no metadata for pz:recordfilter
1541     \retval 1 if there is metadata for pz:recordfilter
1542
1543     If there is no pz:recordfilter defined, this function returns 1
1544     as well.
1545 */
1546
1547 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1548 {
1549     int match = 0;
1550     xmlNode *n;
1551     const char *s;
1552     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1553
1554     if (!s || !*s)
1555         return 1;
1556
1557     for (n = root->children; n; n = n->next)
1558     {
1559         if (n->type != XML_ELEMENT_NODE)
1560             continue;
1561         if (!strcmp((const char *) n->name, "metadata"))
1562         {
1563             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1564             if (type)
1565             {
1566                 size_t len;
1567                 int substring;
1568                 const char *eq;
1569
1570                 if ((eq = strchr(s, '=')))
1571                     substring = 0;
1572                 else if ((eq = strchr(s, '~')))
1573                     substring = 1;
1574                 if (eq)
1575                     len = eq - s;
1576                 else
1577                     len = strlen(s);
1578                 if (len == strlen((const char *)type) &&
1579                     !memcmp((const char *) type, s, len))
1580                 {
1581                     xmlChar *value = xmlNodeGetContent(n);
1582                     if (value && *value)
1583                     {
1584                         if (!eq ||
1585                             (substring && strstr((const char *) value, eq+1)) ||
1586                             (!substring && !strcmp((const char *) value, eq + 1)))
1587                             match = 1;
1588                     }
1589                     xmlFree(value);
1590                 }
1591                 xmlFree(type);
1592             }
1593         }
1594     }
1595     return match;
1596 }
1597
1598
1599 static int ingest_to_cluster(struct client *cl,
1600                              xmlDoc *xdoc,
1601                              xmlNode *root,
1602                              int record_no,
1603                              const char *mergekey_norm);
1604
1605 /** \brief ingest XML record
1606     \param cl client holds the result set for record
1607     \param rec record buffer (0 terminated)
1608     \param record_no record position (1, 2, ..)
1609     \param nmem working NMEM
1610     \retval 0 OK
1611     \retval -1 failure
1612     \retval -2 Filtered
1613 */
1614 int ingest_record(struct client *cl, const char *rec,
1615                   int record_no, NMEM nmem)
1616 {
1617     struct session *se = client_get_session(cl);
1618     int ret = 0;
1619     struct session_database *sdb = client_get_database(cl);
1620     struct conf_service *service = se->service;
1621     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1622     xmlNode *root;
1623     const char *mergekey_norm;
1624
1625     if (!xdoc)
1626         return -1;
1627
1628     root = xmlDocGetRootElement(xdoc);
1629
1630     if (!check_record_filter(root, sdb))
1631     {
1632         session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1633         xmlFreeDoc(xdoc);
1634         return -2;
1635     }
1636
1637     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1638     if (!mergekey_norm)
1639     {
1640         session_log(se, YLOG_WARN, "Got no mergekey");
1641         xmlFreeDoc(xdoc);
1642         return -1;
1643     }
1644     session_enter(se, "ingest_record");
1645     if (client_get_session(cl) == se)
1646         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1647     session_leave(se, "ingest_record");
1648
1649     xmlFreeDoc(xdoc);
1650     return ret;
1651 }
1652
1653 //    struct conf_metadata *ser_md = &service->metadata[md_field_id];
1654 //    struct record_metadata *rec_md = record->metadata[md_field_id];
1655 static int match_metadata_local(struct conf_metadata *ser_md,
1656                                 struct record_metadata *rec_md0,
1657                                 char **values, int num_v)
1658 {
1659     int i;
1660     struct record_metadata *rec_md = rec_md0;
1661     for (i = 0; i < num_v; )
1662     {
1663         if (rec_md)
1664         {
1665             if (ser_md->type == Metadata_type_year
1666                 || ser_md->type == Metadata_type_date)
1667             {
1668                 int y = atoi(values[i]);
1669                 if (y >= rec_md->data.number.min
1670                     && y <= rec_md->data.number.max)
1671                     break;
1672             }
1673             else
1674             {
1675                 yaz_log(YLOG_DEBUG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1676                 if (!strcmp(rec_md->data.text.disp, values[i]))
1677                 {
1678                     // Value equals, should not be filtered.
1679                     break;
1680                 }
1681             }
1682             rec_md = rec_md->next;
1683         }
1684         else
1685         {
1686             rec_md = rec_md0;
1687             i++;
1688         }
1689     }
1690     return i < num_v ? 1 : 0;
1691 }
1692
1693 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
1694 {
1695     int i;
1696     struct conf_service *service = se->service;
1697     int ret = 1;
1698     const char *name;
1699     const char *value;
1700     NMEM nmem_tmp = nmem_create();
1701
1702     for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
1703     {
1704         int j;
1705         for (j = 0; j < service->num_metadata; j++)
1706         {
1707             struct conf_metadata *md = service->metadata + j;
1708             if (!strcmp(md->name, name) && md->limitcluster)
1709             {
1710                 char **values = 0;
1711                 int num = 0;
1712                 int md_field_id =
1713                     conf_service_metadata_field_id(service,
1714                                                    md->limitcluster);
1715
1716                 if (md_field_id < 0)
1717                 {
1718                     ret = 0;
1719                     break;
1720                 }
1721
1722                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1723                                       &num, 1, '\\', 1);
1724
1725                 if (!match_metadata_local(&service->metadata[md_field_id],
1726                                           rec->metadata[md_field_id],
1727                                           values, num))
1728                 {
1729                     ret = 0;
1730                     break;
1731                 }
1732             }
1733         }
1734     }
1735     nmem_destroy(nmem_tmp);
1736     return ret;
1737 }
1738
1739 // Skip record on non-zero
1740 static int check_limit_local(struct client *cl,
1741                              struct record *record,
1742                              int record_no)
1743 {
1744     int skip_record = 0;
1745     struct session *se = client_get_session(cl);
1746     struct conf_service *service = se->service;
1747     NMEM nmem_tmp = nmem_create();
1748     struct session_database *sdb = client_get_database(cl);
1749     int l = 0;
1750     while (!skip_record)
1751     {
1752         int md_field_id;
1753         char **values = 0;
1754         int num_v = 0;
1755         const char *name =
1756             client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
1757                                          &num_v, &values);
1758         if (!name)
1759             break;
1760
1761         if (!strcmp(name, "*"))
1762         {
1763             for (md_field_id = 0; md_field_id < service->num_metadata;
1764                  md_field_id++)
1765             {
1766                 if (match_metadata_local(
1767                         &service->metadata[md_field_id],
1768                         record->metadata[md_field_id],
1769                         values, num_v))
1770                     break;
1771             }
1772             if (md_field_id == service->num_metadata)
1773                 skip_record = 1;
1774         }
1775         else
1776         {
1777             md_field_id = conf_service_metadata_field_id(service, name);
1778             if (md_field_id < 0)
1779             {
1780                 skip_record = 1;
1781                 break;
1782             }
1783             if (!match_metadata_local(
1784                     &service->metadata[md_field_id],
1785                     record->metadata[md_field_id],
1786                     values, num_v))
1787             {
1788                 skip_record = 1;
1789             }
1790         }
1791     }
1792     nmem_destroy(nmem_tmp);
1793     return skip_record;
1794 }
1795
1796 static int ingest_to_cluster(struct client *cl,
1797                              xmlDoc *xdoc,
1798                              xmlNode *root,
1799                              int record_no,
1800                              const char *mergekey_norm)
1801 {
1802     xmlNode *n;
1803     xmlChar *type = 0;
1804     xmlChar *value = 0;
1805     struct session *se = client_get_session(cl);
1806     struct conf_service *service = se->service;
1807     int term_factor = 1;
1808     struct record_cluster *cluster;
1809     struct record_metadata **metadata0;
1810     struct session_database *sdb = client_get_database(cl);
1811     struct record *record = record_create(se->nmem,
1812                                           service->num_metadata,
1813                                           service->num_sortkeys, cl,
1814                                           record_no);
1815
1816     for (n = root->children; n; n = n->next)
1817     {
1818         if (type)
1819             xmlFree(type);
1820         if (value)
1821             xmlFree(value);
1822         type = value = 0;
1823
1824         if (n->type != XML_ELEMENT_NODE)
1825             continue;
1826         if (!strcmp((const char *) n->name, "metadata"))
1827         {
1828             struct conf_metadata *ser_md = 0;
1829             struct record_metadata **wheretoput = 0;
1830             struct record_metadata *rec_md = 0;
1831             int md_field_id = -1;
1832
1833             type = xmlGetProp(n, (xmlChar *) "type");
1834             value = xmlNodeListGetString(xdoc, n->children, 1);
1835
1836             if (!type || !value || !*value)
1837                 continue;
1838
1839             md_field_id
1840                 = conf_service_metadata_field_id(service, (const char *) type);
1841             if (md_field_id < 0)
1842             {
1843                 if (se->number_of_warnings_unknown_metadata == 0)
1844                 {
1845                     session_log(se, YLOG_WARN,
1846                             "Ignoring unknown metadata element: %s", type);
1847                 }
1848                 se->number_of_warnings_unknown_metadata++;
1849                 continue;
1850             }
1851
1852             ser_md = &service->metadata[md_field_id];
1853
1854             // non-merged metadata
1855             rec_md = record_metadata_init(se->nmem, (const char *) value,
1856                                           ser_md->type, n->properties);
1857             if (!rec_md)
1858             {
1859                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1860                             "for element '%s'", value, type);
1861                 continue;
1862             }
1863             wheretoput = &record->metadata[md_field_id];
1864             while (*wheretoput)
1865                 wheretoput = &(*wheretoput)->next;
1866             *wheretoput = rec_md;
1867         }
1868     }
1869
1870     if (check_limit_local(cl, record, record_no))
1871     {
1872         session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1873                     record_no, sdb->database->id);
1874         if (type)
1875             xmlFree(type);
1876         if (value)
1877             xmlFree(value);
1878         return -2;
1879     }
1880     cluster = reclist_insert(se->reclist, service, record,
1881                              mergekey_norm, &se->total_merged);
1882     if (!cluster)
1883         return -1;
1884
1885     {
1886         const char *use_term_factor_str =
1887             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1888         if (use_term_factor_str && use_term_factor_str[0] == '1')
1889         {
1890             int maxrecs = client_get_maxrecs(cl);
1891             int hits = (int) client_get_hits(cl);
1892             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1893             assert(term_factor >= 1);
1894             yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1895         }
1896     }
1897
1898     if (global_parameters.dump_records)
1899         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1900                     sdb->database->id, record_no);
1901
1902
1903     relevance_newrec(se->relevance, cluster);
1904
1905     // original metadata, to check if first existence of a field
1906     metadata0 = xmalloc(sizeof(*metadata0) * service->num_metadata);
1907     memcpy(metadata0, cluster->metadata,
1908            sizeof(*metadata0) * service->num_metadata);
1909
1910     // now parsing XML record and adding data to cluster or record metadata
1911     for (n = root->children; n; n = n->next)
1912     {
1913         pp2_charset_token_t prt;
1914         if (type)
1915             xmlFree(type);
1916         if (value)
1917             xmlFree(value);
1918         type = value = 0;
1919
1920         if (n->type != XML_ELEMENT_NODE)
1921             continue;
1922         if (!strcmp((const char *) n->name, "metadata"))
1923         {
1924             struct conf_metadata *ser_md = 0;
1925             struct conf_sortkey *ser_sk = 0;
1926             struct record_metadata **wheretoput = 0;
1927             struct record_metadata *rec_md = 0;
1928             int md_field_id = -1;
1929             int sk_field_id = -1;
1930             const char *rank;
1931             xmlChar *xml_rank;
1932
1933             type = xmlGetProp(n, (xmlChar *) "type");
1934             value = xmlNodeListGetString(xdoc, n->children, 1);
1935
1936             if (!type || !value || !*value)
1937                 continue;
1938
1939             md_field_id
1940                 = conf_service_metadata_field_id(service, (const char *) type);
1941             if (md_field_id < 0)
1942                 continue;
1943
1944             ser_md = &service->metadata[md_field_id];
1945
1946             if (ser_md->sortkey_offset >= 0)
1947             {
1948                 sk_field_id = ser_md->sortkey_offset;
1949                 ser_sk = &service->sortkeys[sk_field_id];
1950             }
1951
1952             // merged metadata
1953             rec_md = record_metadata_init(se->nmem, (const char *) value,
1954                                           ser_md->type, 0);
1955
1956             // see if the field was not in cluster already (from beginning)
1957
1958             if (!rec_md)
1959                 continue;
1960
1961             xml_rank = xmlGetProp(n, (xmlChar *) "rank");
1962             rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
1963
1964             wheretoput = &cluster->metadata[md_field_id];
1965
1966             if (ser_md->merge == Metadata_merge_first)
1967             {
1968                 if (!metadata0[md_field_id])
1969                 {
1970                     while (*wheretoput)
1971                         wheretoput = &(*wheretoput)->next;
1972                     *wheretoput = rec_md;
1973                 }
1974             }
1975             else if (ser_md->merge == Metadata_merge_unique)
1976             {
1977                 while (*wheretoput)
1978                 {
1979                     if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1980                                 rec_md->data.text.disp))
1981                         break;
1982                     wheretoput = &(*wheretoput)->next;
1983                 }
1984                 if (!*wheretoput)
1985                     *wheretoput = rec_md;
1986             }
1987             else if (ser_md->merge == Metadata_merge_longest)
1988             {
1989                 if (!*wheretoput
1990                     || strlen(rec_md->data.text.disp)
1991                     > strlen((*wheretoput)->data.text.disp))
1992                 {
1993                     *wheretoput = rec_md;
1994                     if (ser_sk)
1995                     {
1996                         const char *sort_str = 0;
1997                         int skip_article =
1998                             ser_sk->type == Metadata_sortkey_skiparticle;
1999
2000                         if (!cluster->sortkeys[sk_field_id])
2001                             cluster->sortkeys[sk_field_id] =
2002                                 nmem_malloc(se->nmem,
2003                                             sizeof(union data_types));
2004
2005                         prt =
2006                             pp2_charset_token_create(service->charsets, "sort");
2007
2008                         pp2_charset_token_first(prt, rec_md->data.text.disp,
2009                                                 skip_article);
2010
2011                         pp2_charset_token_next(prt);
2012
2013                         sort_str = pp2_get_sort(prt);
2014
2015                         cluster->sortkeys[sk_field_id]->text.disp =
2016                             rec_md->data.text.disp;
2017                         if (!sort_str)
2018                         {
2019                             sort_str = rec_md->data.text.disp;
2020                             session_log(se, YLOG_WARN,
2021                                     "Could not make sortkey. Bug #1858");
2022                         }
2023                         cluster->sortkeys[sk_field_id]->text.sort =
2024                             nmem_strdup(se->nmem, sort_str);
2025                         pp2_charset_token_destroy(prt);
2026                     }
2027                 }
2028             }
2029             else if (ser_md->merge == Metadata_merge_all)
2030             {
2031                 while (*wheretoput)
2032                     wheretoput = &(*wheretoput)->next;
2033                 *wheretoput = rec_md;
2034             }
2035             else if (ser_md->merge == Metadata_merge_range)
2036             {
2037                 if (!*wheretoput)
2038                 {
2039                     *wheretoput = rec_md;
2040                     if (ser_sk)
2041                         cluster->sortkeys[sk_field_id]
2042                             = &rec_md->data;
2043                 }
2044                 else
2045                 {
2046                     int this_min = rec_md->data.number.min;
2047                     int this_max = rec_md->data.number.max;
2048                     if (this_min < (*wheretoput)->data.number.min)
2049                         (*wheretoput)->data.number.min = this_min;
2050                     if (this_max > (*wheretoput)->data.number.max)
2051                         (*wheretoput)->data.number.max = this_max;
2052                 }
2053             }
2054
2055             // ranking of _all_ fields enabled ...
2056             if (rank)
2057             {
2058                 relevance_countwords(se->relevance, cluster,
2059                                      (char *) value, rank, ser_md->name);
2060             }
2061
2062             // construct facets ... unless the client already has reported them
2063             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2064             {
2065                 if (ser_md->type == Metadata_type_year)
2066                 {
2067                     char year[64];
2068                     sprintf(year, "%d", rec_md->data.number.max);
2069
2070                     add_facet(se, (char *) type, year, term_factor);
2071                     if (rec_md->data.number.max != rec_md->data.number.min)
2072                     {
2073                         sprintf(year, "%d", rec_md->data.number.min);
2074                         add_facet(se, (char *) type, year, term_factor);
2075                     }
2076                 }
2077                 else
2078                     add_facet(se, (char *) type, (char *) value, term_factor);
2079             }
2080
2081             // cleaning up
2082             if (xml_rank)
2083                 xmlFree(xml_rank);
2084             xmlFree(type);
2085             xmlFree(value);
2086             type = value = 0;
2087         }
2088         else
2089         {
2090             if (se->number_of_warnings_unknown_elements == 0)
2091                 session_log(se, YLOG_WARN,
2092                         "Unexpected element in internal record: %s", n->name);
2093             se->number_of_warnings_unknown_elements++;
2094         }
2095     }
2096     if (type)
2097         xmlFree(type);
2098     if (value)
2099         xmlFree(value);
2100
2101     xfree(metadata0);
2102     relevance_donerecord(se->relevance, cluster);
2103     se->total_records++;
2104
2105     return 0;
2106 }
2107
2108 void session_log(struct session *s, int level, const char *fmt, ...)
2109 {
2110     char buf[1024];
2111     va_list ap;
2112     va_start(ap, fmt);
2113
2114     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2115     yaz_log(level, "Session %u: %s", s->session_id, buf);
2116
2117     va_end(ap);
2118 }
2119
2120 /*
2121  * Local variables:
2122  * c-basic-offset: 4
2123  * c-file-style: "Stroustrup"
2124  * indent-tabs-mode: nil
2125  * End:
2126  * vim: shiftwidth=4 tabstop=8 expandtab
2127  */
2128