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