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