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