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