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