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