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