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