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