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