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