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