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