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