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