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