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