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