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