e61d8118a48ae8d4e44c32e73e5e5425e58a2b10
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.41 2007-06-13 08:04:03 adam Exp $
2    Copyright (c) 2006-2007, Index Data.
3
4 This file is part of Pazpar2.
5
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 /** \file logic.c
23     \brief high-level logic; mostly user sessions and settings
24 */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <assert.h>
36
37 #include <yaz/marcdisp.h>
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/proto.h>
41 #include <yaz/readconf.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/nmem.h>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #if YAZ_VERSIONL >= 0x020163
49 #include <yaz/oid_db.h>
50 #endif
51
52 #if HAVE_CONFIG_H
53 #include "cconfig.h"
54 #endif
55
56 #define USE_TIMING 0
57 #if USE_TIMING
58 #include <yaz/timing.h>
59 #endif
60
61 #include <netinet/in.h>
62
63 #include "pazpar2.h"
64 #include "eventl.h"
65 #include "http.h"
66 #include "termlists.h"
67 #include "reclists.h"
68 #include "relevance.h"
69 #include "config.h"
70 #include "database.h"
71 #include "client.h"
72 #include "settings.h"
73 #include "normalize7bit.h"
74
75 #define TERMLIST_HIGH_SCORE 25
76
77 #define MAX_CHUNK 15
78
79 // Note: Some things in this structure will eventually move to configuration
80 struct parameters global_parameters = 
81 {
82     "",
83     "",
84     "", 
85     0,
86     0, /* dump_records */
87     0, /* debug_mode */
88     30,
89     "81",
90     "Index Data PazPar2",
91     VERSION,
92     600, // 10 minutes
93     60,
94     100,
95     MAX_CHUNK,
96     0,
97     0
98 };
99
100
101 // Recursively traverse query structure to extract terms.
102 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
103 {
104     char **words;
105     int numwords;
106     int i;
107
108     switch (n->kind)
109     {
110         case CCL_RPN_AND:
111         case CCL_RPN_OR:
112         case CCL_RPN_NOT:
113         case CCL_RPN_PROX:
114             pull_terms(nmem, n->u.p[0], termlist, num);
115             pull_terms(nmem, n->u.p[1], termlist, num);
116             break;
117         case CCL_RPN_TERM:
118             nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
119             for (i = 0; i < numwords; i++)
120                 termlist[(*num)++] = words[i];
121             break;
122         default: // NOOP
123             break;
124     }
125 }
126
127
128
129 static void add_facet(struct session *s, const char *type, const char *value)
130 {
131     int i;
132
133     if (!*value)
134         return;
135     for (i = 0; i < s->num_termlists; i++)
136         if (!strcmp(s->termlists[i].name, type))
137             break;
138     if (i == s->num_termlists)
139     {
140         if (i == SESSION_MAX_TERMLISTS)
141         {
142             yaz_log(YLOG_FATAL, "Too many termlists");
143             return;
144         }
145
146         s->termlists[i].name = nmem_strdup(s->nmem, type);
147         s->termlists[i].termlist 
148             = termlist_create(s->nmem, s->expected_maxrecs,
149                               TERMLIST_HIGH_SCORE);
150         s->num_termlists = i + 1;
151     }
152     termlist_insert(s->termlists[i].termlist, value);
153 }
154
155 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
156 {
157     struct database_retrievalmap *m;
158     struct database *db = sdb->database;
159     xmlDoc *rdoc = 0;
160     const Odr_oid *oid = rec->direct_reference;
161
162     /* convert response record to XML somehow */
163     if (rec->which == Z_External_octet && oid
164         && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
165     {
166         /* xml already */
167         rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
168                               rec->u.octet_aligned->len);
169         if (!rdoc)
170         {
171             yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
172                     db->url);
173             return 0;
174         }
175     }
176     else if (oid && yaz_oid_is_iso2709(oid))
177     {
178         /* ISO2709 gets converted to MARCXML */
179         if (!sdb->yaz_marc)
180         {
181             yaz_log(YLOG_FATAL, "Unable to handle ISO2709 record");
182             return 0;
183         }
184         else
185         {
186             xmlNode *res;
187             char *buf;
188             int len;
189             
190             if (rec->which != Z_External_octet)
191             {
192                 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
193                         db->url);
194                 return 0;
195             }
196             buf = (char*) rec->u.octet_aligned->buf;
197             len = rec->u.octet_aligned->len;
198             if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
199             {
200                 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
201                 return 0;
202             }
203             
204             yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
205             if (yaz_marc_write_xml(sdb->yaz_marc, &res,
206                                    "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
207             {
208                 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
209                         db->url);
210                 return 0;
211             }
212             rdoc = xmlNewDoc((xmlChar *) "1.0");
213             xmlDocSetRootElement(rdoc, res);
214         }
215     }
216     else
217     {
218         char oid_name_buf[OID_STR_MAX];
219         const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
220         yaz_log(YLOG_FATAL, 
221                 "Unable to handle record of type %s from %s", 
222                 oid_name, db->url);
223         return 0;
224     }
225     
226     if (global_parameters.dump_records){
227         fprintf(stderr, 
228                 "Input Record (normalized) from %s\n----------------\n",
229                 db->url);
230 #if LIBXML_VERSION >= 20600
231         xmlDocFormatDump(stderr, rdoc, 1);
232 #else
233         xmlDocDump(stderr, rdoc);
234 #endif
235     }
236
237     for (m = sdb->map; m; m = m->next){
238         xmlDoc *new = 0;
239
240         {
241             xmlNodePtr root = 0;
242             new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
243             root= xmlDocGetRootElement(new);
244         if (!new || !root || !(root->children))
245         {
246             yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
247                     sdb->database->url);
248             xmlFreeDoc(new);
249             xmlFreeDoc(rdoc);
250             return 0;
251         }
252         }
253    
254         xmlFreeDoc(rdoc);
255         rdoc = new;
256     }
257     if (global_parameters.dump_records)
258     {
259         fprintf(stderr, "Record from %s\n----------------\n", 
260                 sdb->database->url);
261 #if LIBXML_VERSION >= 20600
262         xmlDocFormatDump(stderr, rdoc, 1);
263 #else
264         xmlDocDump(stderr, rdoc);
265 #endif
266     }
267     return rdoc;
268 }
269
270 // Retrieve first defined value for 'name' for given database.
271 // Will be extended to take into account user associated with session
272 char *session_setting_oneval(struct session_database *db, int offset)
273 {
274     if (!db->settings[offset])
275         return "";
276     return db->settings[offset]->value;
277 }
278
279
280
281 // Initialize YAZ Map structures for MARC-based targets
282 static int prepare_yazmarc(struct session_database *sdb)
283 {
284     char *s;
285
286     if (!sdb->settings)
287     {
288         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
289         return -1;
290     }
291     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
292         && !strncmp(s, "iso2709", 7))
293     {
294         char *encoding = "marc-8s", *e;
295         yaz_iconv_t cm;
296
297         // See if a native encoding is specified
298         if ((e = strchr(s, ';')))
299             encoding = e + 1;
300
301         sdb->yaz_marc = yaz_marc_create();
302         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
303         
304         cm = yaz_iconv_open("utf-8", encoding);
305         if (!cm)
306         {
307             yaz_log(YLOG_FATAL, 
308                     "Unable to map from %s to UTF-8 for target %s", 
309                     encoding, sdb->database->url);
310             return -1;
311         }
312         yaz_marc_iconv(sdb->yaz_marc, cm);
313     }
314     return 0;
315 }
316
317 // Prepare XSLT stylesheets for record normalization
318 // Structures are allocated on the session_wide nmem to avoid having
319 // to recompute this for every search. This would lead
320 // to leaking if a single session was to repeatedly change the PZ_XSLT
321 // setting. However, this is not a realistic use scenario.
322 static int prepare_map(struct session *se, struct session_database *sdb)
323 {
324    char *s;
325
326     if (!sdb->settings)
327     {
328         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
329         return -1;
330     }
331     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
332     {
333         char **stylesheets;
334         struct database_retrievalmap **m = &sdb->map;
335         int num, i;
336
337         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
338         for (i = 0; i < num; i++)
339         {
340             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
341             (*m)->next = 0;
342             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
343             {
344                 yaz_log(YLOG_FATAL, "Unable to load stylesheet: %s",
345                         stylesheets[i]);
346                 return -1;
347             }
348             m = &(*m)->next;
349         }
350     }
351     if (!sdb->map)
352         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
353                 sdb->database->url);
354     return 0;
355 }
356
357 // This analyzes settings and recomputes any supporting data structures
358 // if necessary.
359 static int prepare_session_database(struct session *se, 
360                                     struct session_database *sdb)
361 {
362     if (!sdb->settings)
363     {
364         yaz_log(YLOG_WARN, 
365                 "No settings associated with %s", sdb->database->url);
366         return -1;
367     }
368     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
369     {
370         if (prepare_yazmarc(sdb) < 0)
371             return -1;
372     }
373     if (sdb->settings[PZ_XSLT] && !sdb->map)
374     {
375         if (prepare_map(se, sdb) < 0)
376             return -1;
377     }
378     return 0;
379 }
380
381
382 void session_set_watch(struct session *s, int what, 
383                        session_watchfun fun, void *data)
384 {
385     s->watchlist[what].fun = fun;
386     s->watchlist[what].data = data;
387 }
388
389 void session_alert_watch(struct session *s, int what)
390 {
391     if (!s->watchlist[what].fun)
392         return;
393     (*s->watchlist[what].fun)(s->watchlist[what].data);
394     s->watchlist[what].fun = 0;
395     s->watchlist[what].data = 0;
396 }
397
398 //callback for grep_databases
399 static void select_targets_callback(void *context, struct session_database *db)
400 {
401     struct session *se = (struct session*) context;
402     struct client *cl = client_create();
403     client_set_database(cl, db);
404     client_set_session(cl, se);
405 }
406
407 // Associates a set of clients with a session;
408 // Note: Session-databases represent databases with per-session 
409 // setting overrides
410 int select_targets(struct session *se, struct database_criterion *crit)
411 {
412     while (se->clients)
413         client_destroy(se->clients);
414
415     return session_grep_databases(se, crit, select_targets_callback);
416 }
417
418 int session_active_clients(struct session *s)
419 {
420     struct client *c;
421     int res = 0;
422
423     for (c = s->clients; c; c = client_next_in_session(c))
424         if (client_is_active(c))
425             res++;
426
427     return res;
428 }
429
430 // parses crit1=val1,crit2=val2|val3,...
431 static struct database_criterion *parse_filter(NMEM m, const char *buf)
432 {
433     struct database_criterion *res = 0;
434     char **values;
435     int num;
436     int i;
437
438     if (!buf || !*buf)
439         return 0;
440     nmem_strsplit(m, ",", buf,  &values, &num);
441     for (i = 0; i < num; i++)
442     {
443         char **subvalues;
444         int subnum;
445         int subi;
446         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
447         char *eq = strchr(values[i], '=');
448         if (!eq)
449         {
450             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
451             return 0;
452         }
453         *(eq++) = '\0';
454         new->name = values[i];
455         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
456         new->values = 0;
457         for (subi = 0; subi < subnum; subi++)
458         {
459             struct database_criterion_value *newv
460                 = nmem_malloc(m, sizeof(*newv));
461             newv->value = subvalues[subi];
462             newv->next = new->values;
463             new->values = newv;
464         }
465         new->next = res;
466         res = new;
467     }
468     return res;
469 }
470
471 enum pazpar2_error_code search(struct session *se,
472                                char *query, char *filter,
473                                const char **addinfo)
474 {
475     int live_channels = 0;
476     struct client *cl;
477     struct database_criterion *criteria;
478
479     yaz_log(YLOG_DEBUG, "Search");
480
481     *addinfo = 0;
482     nmem_reset(se->nmem);
483     criteria = parse_filter(se->nmem, filter);
484     se->requestid++;
485     live_channels = select_targets(se, criteria);
486     if (live_channels)
487     {
488         int maxrecs = live_channels * global_parameters.toget;
489         se->num_termlists = 0;
490         se->reclist = reclist_create(se->nmem, maxrecs);
491         // This will be initialized in send_search()
492         se->total_records = se->total_hits = se->total_merged = 0;
493         se->expected_maxrecs = maxrecs;
494     }
495     else
496         return PAZPAR2_NO_TARGETS;
497
498     se->relevance = 0;
499
500     for (cl = se->clients; cl; cl = client_next_in_session(cl))
501     {
502         if (prepare_session_database(se, client_get_database(cl)) < 0)
503         {
504             *addinfo = client_get_database(cl)->database->url;
505             return PAZPAR2_CONFIG_TARGET;
506         }
507         // Query must parse for all targets
508         if (client_parse_query(cl, query) < 0)
509         {
510             *addinfo = "query";
511             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
512         }
513     }
514
515     for (cl = se->clients; cl; cl = client_next_in_session(cl))
516         client_prep_connection(cl);
517
518     return PAZPAR2_NO_ERROR;
519 }
520
521 // Creates a new session_database object for a database
522 static void session_init_databases_fun(void *context, struct database *db)
523 {
524     struct session *se = (struct session *) context;
525     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
526     int num = settings_num();
527     int i;
528
529     new->database = db;
530     new->yaz_marc = 0;
531     
532 #ifdef HAVE_ICU
533     if (global_parameters.server && global_parameters.server->icu_chn)
534         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
535     else
536         new->pct = pp2_charset_create(0);
537 #else // HAVE_ICU
538     new->pct = pp2_charset_create(0);
539 #endif // HAVE_ICU
540
541     new->map = 0;
542     new->settings 
543         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
544     memset(new->settings, 0, sizeof(struct settings*) * num);
545
546     if (db->settings)
547     {
548         for (i = 0; i < num; i++)
549             new->settings[i] = db->settings[i];
550     }
551     new->next = se->databases;
552     se->databases = new;
553 }
554
555 // Doesn't free memory associated with sdb -- nmem takes care of that
556 static void session_database_destroy(struct session_database *sdb)
557 {
558     struct database_retrievalmap *m;
559
560     for (m = sdb->map; m; m = m->next)
561         xsltFreeStylesheet(m->stylesheet);
562     if (sdb->yaz_marc)
563         yaz_marc_destroy(sdb->yaz_marc);
564     if (sdb->pct)
565         pp2_charset_destroy(sdb->pct);
566 }
567
568 // Initialize session_database list -- this represents this session's view
569 // of the database list -- subject to modification by the settings ws command
570 void session_init_databases(struct session *se)
571 {
572     se->databases = 0;
573     grep_databases(se, 0, session_init_databases_fun);
574 }
575
576 // Probably session_init_databases_fun should be refactored instead of
577 // called here.
578 static struct session_database *load_session_database(struct session *se, 
579                                                       char *id)
580 {
581     struct database *db = find_database(id, 0);
582
583     session_init_databases_fun((void*) se, db);
584     // New sdb is head of se->databases list
585     return se->databases;
586 }
587
588 // Find an existing session database. If not found, load it
589 static struct session_database *find_session_database(struct session *se, 
590                                                       char *id)
591 {
592     struct session_database *sdb;
593
594     for (sdb = se->databases; sdb; sdb = sdb->next)
595         if (!strcmp(sdb->database->url, id))
596             return sdb;
597     return load_session_database(se, id);
598 }
599
600 // Apply a session override to a database
601 void session_apply_setting(struct session *se, char *dbname, char *setting,
602                            char *value)
603 {
604     struct session_database *sdb = find_session_database(se, dbname);
605     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
606     int offset = settings_offset_cprefix(setting);
607
608     if (offset < 0)
609     {
610         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
611         return;
612     }
613     // Jakub: This breaks the filter setting.
614     /*if (offset == PZ_ID)
615     {
616         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
617         return;
618     }*/
619     new->precedence = 0;
620     new->target = dbname;
621     new->name = setting;
622     new->value = value;
623     new->next = sdb->settings[offset];
624     sdb->settings[offset] = new;
625
626     // Force later recompute of settings-driven data structures
627     // (happens when a search starts and client connections are prepared)
628     switch (offset)
629     {
630         case PZ_NATIVESYNTAX:
631             if (sdb->yaz_marc)
632             {
633                 yaz_marc_destroy(sdb->yaz_marc);
634                 sdb->yaz_marc = 0;
635             }
636             break;
637         case PZ_XSLT:
638             if (sdb->map)
639             {
640                 struct database_retrievalmap *m;
641                 // We don't worry about the map structure -- it's in nmem
642                 for (m = sdb->map; m; m = m->next)
643                     xsltFreeStylesheet(m->stylesheet);
644                 sdb->map = 0;
645             }
646             break;
647     }
648 }
649
650 void destroy_session(struct session *s)
651 {
652     struct session_database *sdb;
653
654     yaz_log(YLOG_LOG, "Destroying session");
655     while (s->clients)
656         client_destroy(s->clients);
657     for (sdb = s->databases; sdb; sdb = sdb->next)
658         session_database_destroy(sdb);
659     nmem_destroy(s->nmem);
660     wrbuf_destroy(s->wrbuf);
661 }
662
663 struct session *new_session(NMEM nmem) 
664 {
665     int i;
666     struct session *session = nmem_malloc(nmem, sizeof(*session));
667
668     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
669     
670     session->total_hits = 0;
671     session->total_records = 0;
672     session->num_termlists = 0;
673     session->reclist = 0;
674     session->requestid = -1;
675     session->clients = 0;
676     session->expected_maxrecs = 0;
677     session->session_nmem = nmem;
678     session->nmem = nmem_create();
679     session->wrbuf = wrbuf_alloc();
680     session_init_databases(session);
681     for (i = 0; i <= SESSION_WATCH_MAX; i++)
682     {
683         session->watchlist[i].data = 0;
684         session->watchlist[i].fun = 0;
685     }
686
687     return session;
688 }
689
690 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
691 {
692     static struct hitsbytarget res[1000]; // FIXME MM
693     struct client *cl;
694
695     *count = 0;
696     for (cl = se->clients; cl; cl = client_next_in_session(cl))
697     {
698         char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
699
700         res[*count].id = client_get_database(cl)->database->url;
701         res[*count].name = *name ? name : "Unknown";
702         res[*count].hits = client_get_hits(cl);
703         res[*count].records = client_get_num_records(cl);
704         res[*count].diagnostic = client_get_diagnostic(cl);
705         res[*count].state = client_get_state_str(cl);
706         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
707         (*count)++;
708     }
709
710     return res;
711 }
712
713 struct termlist_score **termlist(struct session *s, const char *name, int *num)
714 {
715     int i;
716
717     for (i = 0; i < s->num_termlists; i++)
718         if (!strcmp((const char *) s->termlists[i].name, name))
719             return termlist_highscore(s->termlists[i].termlist, num);
720     return 0;
721 }
722
723 #ifdef MISSING_HEADERS
724 void report_nmem_stats(void)
725 {
726     size_t in_use, is_free;
727
728     nmem_get_memory_in_use(&in_use);
729     nmem_get_memory_free(&is_free);
730
731     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
732             (long) in_use, (long) is_free);
733 }
734 #endif
735
736 struct record_cluster *show_single(struct session *s, int id)
737 {
738     struct record_cluster *r;
739
740     reclist_rewind(s->reclist);
741     while ((r = reclist_read_record(s->reclist)))
742         if (r->recid == id)
743             return r;
744     return 0;
745 }
746
747 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
748                              int start, int *num, int *total, int *sumhits, 
749                              NMEM nmem_show)
750 {
751     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
752                                        * sizeof(struct record_cluster *));
753     struct reclist_sortparms *spp;
754     int i;
755 #if USE_TIMING    
756     yaz_timing_t t = yaz_timing_create();
757 #endif
758
759     for (spp = sp; spp; spp = spp->next)
760         if (spp->type == Metadata_sortkey_relevance)
761         {
762             relevance_prepare_read(s->relevance, s->reclist);
763             break;
764         }
765     reclist_sort(s->reclist, sp);
766
767     *total = s->reclist->num_records;
768     *sumhits = s->total_hits;
769
770     for (i = 0; i < start; i++)
771         if (!reclist_read_record(s->reclist))
772         {
773             *num = 0;
774             recs = 0;
775             break;
776         }
777
778     for (i = 0; i < *num; i++)
779     {
780         struct record_cluster *r = reclist_read_record(s->reclist);
781         if (!r)
782         {
783             *num = i;
784             break;
785         }
786         recs[i] = r;
787     }
788 #if USE_TIMING
789     yaz_timing_stop(t);
790     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
791             yaz_timing_get_real(t), yaz_timing_get_user(t),
792             yaz_timing_get_sys(t));
793     yaz_timing_destroy(&t);
794 #endif
795     return recs;
796 }
797
798 void statistics(struct session *se, struct statistics *stat)
799 {
800     struct client *cl;
801     int count = 0;
802
803     memset(stat, 0, sizeof(*stat));
804     for (cl = se->clients; cl; cl = client_next_in_session(cl))
805     {
806         if (!client_get_connection(cl))
807             stat->num_no_connection++;
808         switch (client_get_state(cl))
809         {
810             case Client_Connecting: stat->num_connecting++; break;
811             case Client_Initializing: stat->num_initializing++; break;
812             case Client_Searching: stat->num_searching++; break;
813             case Client_Presenting: stat->num_presenting++; break;
814             case Client_Idle: stat->num_idle++; break;
815             case Client_Failed: stat->num_failed++; break;
816             case Client_Error: stat->num_error++; break;
817             default: break;
818         }
819         count++;
820     }
821     stat->num_hits = se->total_hits;
822     stat->num_records = se->total_records;
823
824     stat->num_clients = count;
825 }
826
827 void start_http_listener(void)
828 {
829     char hp[128] = "";
830     struct conf_server *ser = global_parameters.server;
831
832     if (*global_parameters.listener_override)
833         strcpy(hp, global_parameters.listener_override);
834     else
835     {
836         strcpy(hp, ser->host ? ser->host : "");
837         if (ser->port)
838         {
839             if (*hp)
840                 strcat(hp, ":");
841             sprintf(hp + strlen(hp), "%d", ser->port);
842         }
843     }
844     http_init(hp);
845 }
846
847 void start_proxy(void)
848 {
849     char hp[128] = "";
850     struct conf_server *ser = global_parameters.server;
851
852     if (*global_parameters.proxy_override)
853         strcpy(hp, global_parameters.proxy_override);
854     else if (ser->proxy_host || ser->proxy_port)
855     {
856         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
857         if (ser->proxy_port)
858         {
859             if (*hp)
860                 strcat(hp, ":");
861             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
862         }
863     }
864     else
865         return;
866
867     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
868 }
869
870
871 // Master list of connections we're handling events to
872 static IOCHAN channel_list = 0; 
873 void pazpar2_add_channel(IOCHAN chan)
874 {
875     chan->next = channel_list;
876     channel_list = chan;
877 }
878
879 void pazpar2_event_loop()
880 {
881     event_loop(&channel_list);
882 }
883
884 struct record *ingest_record(struct client *cl, Z_External *rec,
885                              int record_no)
886 {
887     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
888     xmlNode *root, *n;
889     struct record *record;
890     struct record_cluster *cluster;
891     struct session *se = client_get_session(cl);
892     xmlChar *mergekey, *mergekey_norm;
893     xmlChar *type = 0;
894     xmlChar *value = 0;
895     struct conf_service *service = global_parameters.server->service;
896
897     if (!xdoc)
898         return 0;
899
900     root = xmlDocGetRootElement(xdoc);
901     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
902     {
903         yaz_log(YLOG_WARN, "No mergekey found in record");
904         xmlFreeDoc(xdoc);
905         return 0;
906     }
907
908     record = record_create(se->nmem, 
909                            service->num_metadata, service->num_sortkeys, cl);
910
911     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
912     xmlFree(mergekey);
913     normalize7bit_mergekey((char *) mergekey_norm, 0);
914
915     cluster = reclist_insert(se->reclist, 
916                              global_parameters.server->service, 
917                              record, (char *) mergekey_norm, 
918                              &se->total_merged);
919     if (global_parameters.dump_records)
920         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
921                 client_get_database(cl)->database->url, record_no);
922     if (!cluster)
923     {
924         /* no room for record */
925         xmlFreeDoc(xdoc);
926         return 0;
927     }
928     relevance_newrec(se->relevance, cluster);
929
930
931     // now parsing XML record and adding data to cluster or record metadata
932     for (n = root->children; n; n = n->next)
933     {
934         if (type)
935             xmlFree(type);
936         if (value)
937             xmlFree(value);
938         type = value = 0;
939
940         if (n->type != XML_ELEMENT_NODE)
941             continue;
942         if (!strcmp((const char *) n->name, "metadata"))
943         {
944             struct conf_metadata *ser_md = 0;
945             struct conf_sortkey *ser_sk = 0;
946             struct record_metadata **wheretoput = 0;
947             struct record_metadata *rec_md = 0;
948             int md_field_id = -1;
949             int sk_field_id = -1;
950             int first, last;
951
952             type = xmlGetProp(n, (xmlChar *) "type");
953             value = xmlNodeListGetString(xdoc, n->children, 1);
954
955             if (!type || !value)
956                 continue;
957
958             md_field_id 
959                 = conf_service_metadata_field_id(service, (const char *) type);
960             if (md_field_id < 0)
961             {
962                 yaz_log(YLOG_WARN, 
963                         "Ignoring unknown metadata element: %s", type);
964                 continue;
965             }
966
967             ser_md = &service->metadata[md_field_id];
968
969             if (ser_md->sortkey_offset >= 0){
970                 sk_field_id = ser_md->sortkey_offset;
971                 ser_sk = &service->sortkeys[sk_field_id];
972             }
973
974             // Find out where we are putting it - based on merge or not
975             if (ser_md->merge == Metadata_merge_no)
976                 wheretoput = &record->metadata[md_field_id];
977             else
978                 wheretoput = &cluster->metadata[md_field_id];
979             
980             // create new record_metadata
981             rec_md = record_metadata_create(se->nmem);
982
983             // and polulate with data:
984             // type based charmapping decisions follow here
985             if (ser_md->type == Metadata_type_generic)
986             {
987
988                 char * p = (char *) value;
989                 p = normalize7bit_generic(p, " ,/.:([");
990                 
991                 rec_md->data.text = nmem_strdup(se->nmem, p);
992
993             }
994             else if (ser_md->type == Metadata_type_year)
995             {
996                 if (extract7bit_years((char *) value, &first, &last) < 0)
997                     continue;
998             }
999             else
1000             {
1001                 yaz_log(YLOG_WARN, 
1002                         "Unknown type in metadata element %s", type);
1003                 continue;
1004             }
1005
1006             // and polulate with data:
1007             // assign cluster or record based on merge action
1008             if (ser_md->merge == Metadata_merge_unique)
1009             {
1010                 struct record_metadata *mnode;
1011                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1012                     if (!strcmp((const char *) mnode->data.text, 
1013                                 rec_md->data.text))
1014                         break;
1015                 if (!mnode)
1016                 {
1017                     rec_md->next = *wheretoput;
1018                     *wheretoput = rec_md;
1019                 }
1020             }
1021             else if (ser_md->merge == Metadata_merge_longest)
1022             {
1023                 if (!*wheretoput 
1024                     || strlen(rec_md->data.text) 
1025                        > strlen((*wheretoput)->data.text))
1026                 {
1027                     *wheretoput = rec_md;
1028                     if (ser_sk)
1029                     {
1030                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1031                         if (!cluster->sortkeys[sk_field_id])
1032                             cluster->sortkeys[sk_field_id] = 
1033                                 nmem_malloc(se->nmem, 
1034                                             sizeof(union data_types));
1035                         normalize7bit_mergekey(s,
1036                              (ser_sk->type == Metadata_sortkey_skiparticle));
1037                         cluster->sortkeys[sk_field_id]->text = s;
1038                     }
1039                 }
1040             }
1041             else if (ser_md->merge == Metadata_merge_all 
1042                      || ser_md->merge == Metadata_merge_no)
1043             {
1044                 rec_md->next = *wheretoput;
1045                 *wheretoput = rec_md;
1046             }
1047             else if (ser_md->merge == Metadata_merge_range)
1048             {
1049                 if (!*wheretoput)
1050                 {
1051                     *wheretoput = rec_md;
1052                     (*wheretoput)->data.number.min = first;
1053                     (*wheretoput)->data.number.max = last;
1054                     if (ser_sk)
1055                         cluster->sortkeys[sk_field_id] 
1056                             = &rec_md->data;
1057                 }
1058                 else
1059                 {
1060                     if (first < (*wheretoput)->data.number.min)
1061                         (*wheretoput)->data.number.min = first;
1062                     if (last > (*wheretoput)->data.number.max)
1063                         (*wheretoput)->data.number.max = last;
1064                 }
1065 #ifdef GAGA
1066                 if (ser_sk)
1067                 {
1068                     union data_types *sdata 
1069                         = cluster->sortkeys[sk_field_id];
1070                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1071                             sdata->number.min, sdata->number.max);
1072                 }
1073 #endif
1074             }
1075
1076
1077             // ranking of _all_ fields enabled ... 
1078             if (ser_md->rank)
1079                 relevance_countwords(se->relevance, cluster, 
1080                                      (char *) value, ser_md->rank);
1081
1082             // construct facets ... 
1083             if (ser_md->termlist)
1084             {
1085                 if (ser_md->type == Metadata_type_year)
1086                 {
1087                     char year[64];
1088                     sprintf(year, "%d", last);
1089                     add_facet(se, (char *) type, year);
1090                     if (first != last)
1091                     {
1092                         sprintf(year, "%d", first);
1093                         add_facet(se, (char *) type, year);
1094                     }
1095                 }
1096                 else
1097                     add_facet(se, (char *) type, (char *) value);
1098             }
1099
1100             // cleaning up
1101             xmlFree(type);
1102             xmlFree(value);
1103             type = value = 0;
1104         }
1105         else
1106             yaz_log(YLOG_WARN,
1107                     "Unexpected element %s in internal record", n->name);
1108     }
1109     if (type)
1110         xmlFree(type);
1111     if (value)
1112         xmlFree(value);
1113
1114     xmlFreeDoc(xdoc);
1115
1116     relevance_donerecord(se->relevance, cluster);
1117     se->total_records++;
1118
1119     return record;
1120 }
1121
1122
1123
1124 /*
1125  * Local variables:
1126  * c-basic-offset: 4
1127  * indent-tabs-mode: nil
1128  * End:
1129  * vim: shiftwidth=4 tabstop=8 expandtab
1130  */