xdoc caching in client
[pazpar2-moved-to-github.git] / src / client.c
1 /* This file is part of Pazpar2.
2    Copyright (C) Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 /** \file client.c
21     \brief Z39.50 client
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #if HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef WIN32
37 #include <windows.h>
38 #endif
39 #include <signal.h>
40 #include <assert.h>
41
42 #include <yaz/marcdisp.h>
43 #include <yaz/comstack.h>
44 #include <yaz/tcpip.h>
45 #include <yaz/proto.h>
46 #include <yaz/readconf.h>
47 #include <yaz/pquery.h>
48 #include <yaz/otherinfo.h>
49 #include <yaz/yaz-util.h>
50 #include <yaz/nmem.h>
51 #include <yaz/query-charset.h>
52 #include <yaz/querytowrbuf.h>
53 #include <yaz/oid_db.h>
54 #include <yaz/diagbib1.h>
55 #include <yaz/snprintf.h>
56 #include <yaz/rpn2cql.h>
57 #include <yaz/rpn2solr.h>
58 #include <yaz/gettimeofday.h>
59
60 #define USE_TIMING 0
61 #if USE_TIMING
62 #include <yaz/timing.h>
63 #endif
64
65 #include "ppmutex.h"
66 #include "session.h"
67 #include "parameters.h"
68 #include "client.h"
69 #include "connection.h"
70 #include "settings.h"
71 #include "relevance.h"
72 #include "incref.h"
73
74 #define XDOC_CACHE_SIZE 100
75
76 static YAZ_MUTEX g_mutex = 0;
77 static int no_clients = 0;
78
79 static int client_use(int delta)
80 {
81     int clients;
82     if (!g_mutex)
83         yaz_mutex_create(&g_mutex);
84     yaz_mutex_enter(g_mutex);
85     no_clients += delta;
86     clients = no_clients;
87     yaz_mutex_leave(g_mutex);
88     yaz_log(YLOG_DEBUG, "%s clients=%d",
89             delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), clients);
90     return clients;
91 }
92
93 int clients_count(void)
94 {
95     return client_use(0);
96 }
97
98 /** \brief Represents client state for a connection to one search target */
99 struct client {
100     struct session_database *database;
101     struct connection *connection;
102     struct session *session;
103     char *pquery; // Current search
104     char *cqlquery; // used for SRU targets only
105     char *addinfo; // diagnostic info for most resent error
106     Odr_int hits;
107     int record_offset;
108     int show_stat_no;
109     int filtered; // When using local:, this will count the number of filtered records.
110     int maxrecs;
111     int startrecs;
112     int diagnostic;
113     char *message;
114     int preferred;
115     struct suggestions *suggestions;
116     enum client_state state;
117     struct show_raw *show_raw;
118     ZOOM_resultset resultset;
119     YAZ_MUTEX mutex;
120     int ref_count;
121     char *id;
122     facet_limits_t facet_limits;
123     int same_search;
124     char *sort_strategy;
125     char *sort_criteria;
126     xmlDoc **xdoc;
127 };
128
129 struct suggestions {
130     NMEM nmem;
131     int num;
132     char **misspelled;
133     char **suggest;
134     char *passthrough;
135 };
136
137 struct show_raw {
138     int active; // whether this request has been sent to the server
139     int position;
140     int binary;
141     char *syntax;
142     char *esn;
143     char *nativesyntax;
144     void (*error_handler)(void *data, const char *addinfo);
145     void (*record_handler)(void *data, const char *buf, size_t sz);
146     void *data;
147     struct show_raw *next;
148 };
149
150 static const char *client_states[] = {
151     "Client_Connecting",
152     "Client_Idle",
153     "Client_Working",
154     "Client_Error",
155     "Client_Failed",
156     "Client_Disconnected"
157 };
158
159 const char *client_get_state_str(struct client *cl)
160 {
161     return client_states[cl->state];
162 }
163
164 enum client_state client_get_state(struct client *cl)
165 {
166     return cl->state;
167 }
168
169 void client_set_state_nb(struct client *cl, enum client_state st)
170 {
171     cl->state = st;
172 }
173
174 void client_set_state(struct client *cl, enum client_state st)
175 {
176     int was_active = 0;
177     if (client_is_active(cl))
178         was_active = 1;
179     cl->state = st;
180     /* If client is going from being active to inactive and all clients
181        are now idle we fire a watch for the session . The assumption is
182        that session is not mutex locked if client is already active */
183     if (was_active && !client_is_active(cl) && cl->session)
184     {
185
186         int no_active = session_active_clients(cl->session);
187         yaz_log(YLOG_DEBUG, "%s: releasing watches on zero active: %d",
188                 client_get_id(cl), no_active);
189         if (no_active == 0) {
190             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
191             session_alert_watch(cl->session, SESSION_WATCH_BYTARGET);
192             session_alert_watch(cl->session, SESSION_WATCH_TERMLIST);
193             session_alert_watch(cl->session, SESSION_WATCH_SHOW_PREF);
194         }
195     }
196 }
197
198 static void client_init_xdoc(struct client *cl)
199 {
200     int i;
201
202     cl->xdoc = xmalloc(sizeof(*cl->xdoc) * XDOC_CACHE_SIZE);
203     for (i = 0; i < XDOC_CACHE_SIZE; i++)
204         cl->xdoc[i] = 0;
205 }
206
207 static void client_destroy_xdoc(struct client *cl)
208 {
209     int i;
210
211     assert(cl->xdoc);
212     for (i = 0; i < XDOC_CACHE_SIZE; i++)
213         if (cl->xdoc[i])
214             xmlFreeDoc(cl->xdoc[i]);
215     xfree(cl->xdoc);
216 }
217
218 xmlDoc *client_get_xdoc(struct client *cl, int record_no)
219 {
220     assert(cl->xdoc);
221     if (record_no >= 0 && record_no < XDOC_CACHE_SIZE)
222         return cl->xdoc[record_no];
223     return 0;
224 }
225
226 void client_store_xdoc(struct client *cl, int record_no, xmlDoc *xdoc)
227 {
228     assert(cl->xdoc);
229     if (record_no >= 0 && record_no < XDOC_CACHE_SIZE)
230     {
231         if (cl->xdoc[record_no])
232             xmlFreeDoc(cl->xdoc[record_no]);
233         cl->xdoc[record_no] = xdoc;
234     }
235     else
236     {
237         xmlFreeDoc(xdoc);
238     }
239 }
240
241
242 static void client_show_raw_error(struct client *cl, const char *addinfo);
243
244 struct connection *client_get_connection(struct client *cl)
245 {
246     return cl->connection;
247 }
248
249 struct session_database *client_get_database(struct client *cl)
250 {
251     return cl->database;
252 }
253
254 struct session *client_get_session(struct client *cl)
255 {
256     return cl->session;
257 }
258
259 static void client_send_raw_present(struct client *cl);
260 static int nativesyntax_to_type(const char *s, char *type, ZOOM_record rec);
261
262 static void client_show_immediate(
263     ZOOM_resultset resultset, struct session_database *sdb, int position,
264     void *data,
265     void (*error_handler)(void *data, const char *addinfo),
266     void (*record_handler)(void *data, const char *buf, size_t sz),
267     int binary,
268     const char *nativesyntax)
269 {
270     ZOOM_record rec = 0;
271     char type[80];
272     const char *buf;
273     int len;
274
275     if (!resultset)
276     {
277         error_handler(data, "no resultset");
278         return;
279     }
280     rec = ZOOM_resultset_record_immediate(resultset, position-1);
281     if (!rec)
282     {
283         error_handler(data, "no record");
284         return;
285     }
286     nativesyntax_to_type(nativesyntax, type, rec);
287     buf = ZOOM_record_get(rec, type, &len);
288     if (!buf)
289     {
290         error_handler(data, "no record");
291         return;
292     }
293     record_handler(data, buf, len);
294 }
295
296
297 int client_show_raw_begin(struct client *cl, int position,
298                           const char *syntax, const char *esn,
299                           void *data,
300                           void (*error_handler)(void *data, const char *addinfo),
301                           void (*record_handler)(void *data, const char *buf,
302                                                  size_t sz),
303                           int binary,
304                           const char *nativesyntax)
305 {
306     if (!nativesyntax)
307     {
308         if (binary)
309             nativesyntax = "raw";
310         else
311         {
312             struct session_database *sdb = client_get_database(cl);
313             nativesyntax = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
314         }
315     }
316
317     if (syntax == 0 && esn == 0)
318         client_show_immediate(cl->resultset, client_get_database(cl),
319                               position, data,
320                               error_handler, record_handler,
321                               binary, nativesyntax);
322     else
323     {
324         struct show_raw *rr, **rrp;
325
326         if (!cl->connection)
327             return -1;
328
329
330         rr = xmalloc(sizeof(*rr));
331         rr->position = position;
332         rr->active = 0;
333         rr->data = data;
334         rr->error_handler = error_handler;
335         rr->record_handler = record_handler;
336         rr->binary = binary;
337         if (syntax)
338             rr->syntax = xstrdup(syntax);
339         else
340             rr->syntax = 0;
341         if (esn)
342             rr->esn = xstrdup(esn);
343         else
344             rr->esn = 0;
345
346         assert(nativesyntax);
347         rr->nativesyntax = xstrdup(nativesyntax);
348
349         rr->next = 0;
350
351         for (rrp = &cl->show_raw; *rrp; rrp = &(*rrp)->next)
352             ;
353         *rrp = rr;
354
355         if (cl->state == Client_Failed)
356         {
357             client_show_raw_error(cl, "client failed");
358         }
359         else if (cl->state == Client_Disconnected)
360         {
361             client_show_raw_error(cl, "client disconnected");
362         }
363         else
364         {
365             client_send_raw_present(cl);
366         }
367     }
368     return 0;
369 }
370
371 static void client_show_raw_delete(struct show_raw *r)
372 {
373     xfree(r->syntax);
374     xfree(r->esn);
375     xfree(r->nativesyntax);
376     xfree(r);
377 }
378
379 void client_show_raw_remove(struct client *cl, void *data)
380 {
381     struct show_raw *rr = data;
382     struct show_raw **rrp = &cl->show_raw;
383     while (*rrp != rr)
384         rrp = &(*rrp)->next;
385     if (*rrp)
386     {
387         *rrp = rr->next;
388         client_show_raw_delete(rr);
389     }
390 }
391
392 static void client_show_raw_dequeue(struct client *cl)
393 {
394     struct show_raw *rr = cl->show_raw;
395
396     cl->show_raw = rr->next;
397     client_show_raw_delete(rr);
398 }
399
400 static void client_show_raw_error(struct client *cl, const char *addinfo)
401 {
402     while (cl->show_raw)
403     {
404         cl->show_raw->error_handler(cl->show_raw->data, addinfo);
405         client_show_raw_dequeue(cl);
406     }
407 }
408
409 static void client_send_raw_present(struct client *cl)
410 {
411     struct session_database *sdb = client_get_database(cl);
412     struct connection *co = client_get_connection(cl);
413     ZOOM_resultset set = cl->resultset;
414
415     int offset = cl->show_raw->position;
416     const char *syntax = 0;
417     const char *elements = 0;
418
419     assert(cl->show_raw);
420     assert(set);
421
422     yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
423             client_get_id(cl), 1, offset);
424
425     if (cl->show_raw->syntax)
426         syntax = cl->show_raw->syntax;
427     else
428         syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
429     ZOOM_resultset_option_set(set, "preferredRecordSyntax", syntax);
430
431     if (cl->show_raw->esn)
432         elements = cl->show_raw->esn;
433     else
434         elements = session_setting_oneval(sdb, PZ_ELEMENTS);
435     if (elements && *elements)
436         ZOOM_resultset_option_set(set, "elementSetName", elements);
437
438     ZOOM_resultset_records(set, 0, offset-1, 1);
439     cl->show_raw->active = 1;
440
441     connection_continue(co);
442 }
443
444 static int nativesyntax_to_type(const char *s, char *type,
445                                 ZOOM_record rec)
446 {
447     if (s && *s)
448     {
449         if (!strncmp(s, "iso2709", 7))
450         {
451             const char *cp = strchr(s, ';');
452             yaz_snprintf(type, 80, "xml; charset=%s", cp ? cp+1 : "marc-8s");
453         }
454         else if (!strncmp(s, "txml", 4))
455         {
456             const char *cp = strchr(s, ';');
457             yaz_snprintf(type, 80, "txml; charset=%s", cp ? cp+1 : "marc-8s");
458         }
459         else /* pass verbatim to ZOOM - including "xml" */
460             strcpy(type, s);
461         return 0;
462     }
463     else  /* attempt to deduce structure */
464     {
465         const char *syntax = ZOOM_record_get(rec, "syntax", NULL);
466         if (syntax)
467         {
468             if (!strcmp(syntax, "XML"))
469             {
470                 strcpy(type, "xml");
471                 return 0;
472             }
473             else if (!strcmp(syntax, "USmarc") || !strcmp(syntax, "MARC21"))
474             {
475                 strcpy(type, "xml; charset=marc8-s");
476                 return 0;
477             }
478             else return -1;
479         }
480         else return -1;
481     }
482 }
483
484 /**
485  * TODO Consider thread safety!!!
486  *
487  */
488 static void client_report_facets(struct client *cl, ZOOM_resultset rs)
489 {
490     struct session_database *sdb = client_get_database(cl);
491     ZOOM_facet_field *facets = ZOOM_resultset_facets(rs);
492
493     if (sdb && facets)
494     {
495         struct session *se = client_get_session(cl);
496         int facet_num = ZOOM_resultset_facets_size(rs);
497         struct setting *s;
498
499         for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
500         {
501             const char *p = strchr(s->name + 3, ':');
502             if (p && p[1] && s->value && s->value[0])
503             {
504                 int facet_idx;
505                 p++; /* p now holds logical facet name */
506                 for (facet_idx = 0; facet_idx < facet_num; facet_idx++)
507                 {
508                     const char *native_name =
509                         ZOOM_facet_field_name(facets[facet_idx]);
510                     if (native_name && !strcmp(s->value, native_name))
511                     {
512                         size_t term_idx;
513                         size_t term_num =
514                             ZOOM_facet_field_term_count(facets[facet_idx]);
515                         for (term_idx = 0; term_idx < term_num; term_idx++ )
516                         {
517                             int freq;
518                             const char *term =
519                                 ZOOM_facet_field_get_term(facets[facet_idx],
520                                                           term_idx, &freq);
521                             if (term)
522                                 add_facet(se, p, term, freq);
523                         }
524                         break;
525                     }
526                 }
527             }
528         }
529     }
530 }
531
532 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
533 {
534     const char *buf;
535     int len;
536     char type[80];
537
538     nativesyntax_to_type(cl->show_raw->nativesyntax, type, rec);
539     buf = ZOOM_record_get(rec, type, &len);
540     cl->show_raw->record_handler(cl->show_raw->data,  buf, len);
541     client_show_raw_dequeue(cl);
542 }
543
544 void client_check_preferred_watch(struct client *cl)
545 {
546     struct session *se = cl->session;
547     yaz_log(YLOG_DEBUG, "client_check_preferred_watch: %s ", client_get_id(cl));
548     if (se)
549     {
550         client_unlock(cl);
551         /* TODO possible threading issue. Session can have been destroyed */
552         if (session_is_preferred_clients_ready(se)) {
553             session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
554         }
555         else
556             yaz_log(YLOG_DEBUG, "client_check_preferred_watch: Still locked on preferred targets.");
557
558         client_lock(cl);
559     }
560     else
561         yaz_log(YLOG_WARN, "client_check_preferred_watch: %s. No session!", client_get_id(cl));
562
563 }
564
565 struct suggestions* client_suggestions_create(const char* suggestions_string);
566 static void client_suggestions_destroy(struct client *cl);
567
568 void client_search_response(struct client *cl)
569 {
570     struct connection *co = cl->connection;
571     ZOOM_connection link = connection_get_link(co);
572     ZOOM_resultset resultset = cl->resultset;
573
574     const char *error, *addinfo = 0;
575
576     if (ZOOM_connection_error(link, &error, &addinfo))
577     {
578         cl->hits = 0;
579         client_set_state(cl, Client_Error);
580         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
581                 error, addinfo, client_get_id(cl));
582     }
583     else
584     {
585         client_report_facets(cl, resultset);
586         cl->record_offset = cl->startrecs;
587         cl->hits = ZOOM_resultset_size(resultset);
588         yaz_log(YLOG_DEBUG, "client_search_response: hits " ODR_INT_PRINTF,
589                 cl->hits);
590         if (cl->suggestions)
591             client_suggestions_destroy(cl);
592         cl->suggestions =
593             client_suggestions_create(ZOOM_resultset_option_get(
594                                           resultset, "suggestions"));
595     }
596 }
597
598 void client_got_records(struct client *cl)
599 {
600     struct session *se = cl->session;
601     if (se)
602     {
603         if (reclist_get_num_records(se->reclist) > 0)
604         {
605             client_unlock(cl);
606             session_alert_watch(se, SESSION_WATCH_SHOW);
607             session_alert_watch(se, SESSION_WATCH_BYTARGET);
608             session_alert_watch(se, SESSION_WATCH_TERMLIST);
609             session_alert_watch(se, SESSION_WATCH_RECORD);
610             client_lock(cl);
611         }
612     }
613 }
614
615 static void client_record_ingest(struct client *cl)
616 {
617     const char *msg, *addinfo;
618     ZOOM_record rec = 0;
619     ZOOM_resultset resultset = cl->resultset;
620     struct session *se = client_get_session(cl);
621     xmlDoc *xdoc;
622
623     xdoc = client_get_xdoc(cl, cl->record_offset + 1);
624     if (xdoc)
625     {
626         int offset = cl->record_offset++;
627         if (cl->session)
628         {
629             NMEM nmem = nmem_create();
630             int rc = ingest_xml_record(cl, xdoc, offset, nmem);
631             if (rc == -1)
632                 session_log(se, YLOG_WARN,
633                             "Failed to ingest xdoc from %s #%d",
634                             client_get_id(cl), offset);
635             else if (rc == -2)
636                 cl->filtered++;
637             nmem_destroy(nmem);
638         }
639     }
640     else if ((rec = ZOOM_resultset_record_immediate(resultset,
641                                                     cl->record_offset)))
642     {
643         int offset = ++cl->record_offset;
644         if (cl->session == 0)
645             ;  /* no operation */
646         else if (ZOOM_record_error(rec, &msg, &addinfo, 0))
647         {
648             session_log(se, YLOG_WARN, "Record error %s (%s): %s #%d",
649                         msg, addinfo, client_get_id(cl), offset);
650         }
651         else
652         {
653             struct session_database *sdb = client_get_database(cl);
654             NMEM nmem = nmem_create();
655             const char *xmlrec;
656             char type[80];
657
658             const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
659             if (nativesyntax_to_type(s, type, rec))
660                 session_log(se, YLOG_WARN, "Failed to determine record type");
661             xmlrec = ZOOM_record_get(rec, type, NULL);
662             if (!xmlrec)
663             {
664                 const char *rec_syn =  ZOOM_record_get(rec, "syntax", NULL);
665                 session_log(se, YLOG_WARN, "ZOOM_record_get failed from %s #%d",
666                             client_get_id(cl), offset);
667                 session_log(se, YLOG_LOG, "pz:nativesyntax=%s . "
668                             "ZOOM record type=%s . Actual record syntax=%s",
669                             s ? s : "null", type,
670                             rec_syn ? rec_syn : "null");
671             }
672             else
673             {
674                 /* OK = 0, -1 = failure, -2 = Filtered */
675                 int rc = ingest_record(cl, xmlrec, cl->record_offset, nmem);
676                 if (rc == -1)
677                 {
678                     const char *rec_syn =  ZOOM_record_get(rec, "syntax", NULL);
679                     session_log(se, YLOG_WARN,
680                                 "Failed to ingest record from %s #%d",
681                                 client_get_id(cl), offset);
682                     session_log(se, YLOG_LOG, "pz:nativesyntax=%s . "
683                                 "ZOOM record type=%s . Actual record syntax=%s",
684                                 s ? s : "null", type,
685                                 rec_syn ? rec_syn : "null");
686                 }
687                 if (rc == -2)
688                     cl->filtered += 1;
689             }
690             nmem_destroy(nmem);
691         }
692     }
693     else
694     {
695         session_log(se, YLOG_WARN, "Got NULL record from %s #%d",
696                     client_get_id(cl), cl->record_offset);
697     }
698 }
699
700 void client_record_response(struct client *cl, int *got_records)
701 {
702     struct connection *co = cl->connection;
703     ZOOM_connection link = connection_get_link(co);
704     ZOOM_resultset resultset = cl->resultset;
705     const char *error, *addinfo;
706
707     if (ZOOM_connection_error(link, &error, &addinfo))
708     {
709         client_set_state(cl, Client_Error);
710         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
711             error, addinfo, client_get_id(cl));
712     }
713     else
714     {
715         if (cl->show_raw && cl->show_raw->active)
716         {
717             ZOOM_record rec = 0;
718             if ((rec = ZOOM_resultset_record_immediate(
719                      resultset, cl->show_raw->position-1)))
720             {
721                 cl->show_raw->active = 0;
722                 ingest_raw_record(cl, rec);
723             }
724             else
725             {
726                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
727                         cl->show_raw->position-1);
728             }
729         }
730         else
731         {
732             client_record_ingest(cl);
733             *got_records = 1;
734         }
735     }
736 }
737
738 int client_reingest(struct client *cl)
739 {
740     int i = cl->startrecs;
741     int to = cl->record_offset;
742     cl->filtered = 0;
743
744     cl->record_offset = i;
745     for (; i < to; i++)
746         client_record_ingest(cl);
747     return 0;
748 }
749
750 static void client_set_facets_request(struct client *cl, ZOOM_connection link)
751 {
752     struct session_database *sdb = client_get_database(cl);
753
754     WRBUF w = wrbuf_alloc();
755
756     struct setting *s;
757
758     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
759     {
760         const char *p = strchr(s->name + 3, ':');
761         if (!p)
762         {
763             yaz_log(YLOG_WARN, "Malformed facetmap name: %s", s->name);
764         }
765         else if (s->value && s->value[0])
766         {
767             wrbuf_puts(w, "@attr 1=");
768             yaz_encode_pqf_term(w, s->value, strlen(s->value));
769             if (s->next)
770                 wrbuf_puts(w, ",");
771         }
772     }
773     yaz_log(YLOG_DEBUG, "using facets str: %s", wrbuf_cstr(w));
774     ZOOM_connection_option_set(link, "facets",
775                                wrbuf_len(w) ? wrbuf_cstr(w) : 0);
776     wrbuf_destroy(w);
777 }
778
779 int client_has_facet(struct client *cl, const char *name)
780 {
781     struct session_database *sdb = client_get_database(cl);
782     struct setting *s;
783
784     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
785     {
786         const char *p = strchr(s->name + 3, ':');
787         if (p && !strcmp(name, p + 1))
788             return 1;
789     }
790     return 0;
791 }
792
793 static const char *get_strategy_plus_sort(struct client *l, const char *field)
794 {
795     struct session_database *sdb = client_get_database(l);
796     struct setting *s;
797
798     const char *strategy_plus_sort = 0;
799
800     for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
801     {
802         char *p = strchr(s->name + 3, ':');
803         if (!p)
804         {
805             yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
806             continue;
807         }
808         p++;
809         if (!strcmp(p, field))
810         {
811             strategy_plus_sort = s->value;
812             break;
813         }
814     }
815     return strategy_plus_sort;
816 }
817
818 void client_update_show_stat(struct client *cl, int cmd)
819 {
820     if (cmd == 0)
821         cl->show_stat_no = 0;
822     else if (cmd == 1)
823         cl->show_stat_no++;
824 }
825
826 int client_fetch_more(struct client *cl)
827 {
828     struct session_database *sdb = client_get_database(cl);
829     const char *str;
830     int extend_recs = 0;
831     int number = cl->hits - cl->record_offset;
832
833     str = session_setting_oneval(sdb, PZ_EXTENDRECS);
834     if (!str || !*str)
835         return 0;
836
837     extend_recs = atoi(str);
838
839     yaz_log(YLOG_LOG, "cl=%s show_stat_no=%d got=%d",
840             client_get_id(cl), cl->show_stat_no, cl->record_offset);
841     if (cl->show_stat_no < cl->record_offset)
842         return 0;
843     yaz_log(YLOG_LOG, "cl=%s Trying to fetch more", client_get_id(cl));
844
845     if (number > extend_recs)
846         number = extend_recs;
847     if (number > 0)
848     {
849         ZOOM_resultset set = cl->resultset;
850         struct connection *co = client_get_connection(cl);
851
852         str = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
853         ZOOM_resultset_option_set(set, "preferredRecordSyntax", str);
854         str = session_setting_oneval(sdb, PZ_ELEMENTS);
855         if (str && *str)
856             ZOOM_resultset_option_set(set, "elementSetName", str);
857
858         ZOOM_resultset_records(set, 0, cl->record_offset, number);
859         client_set_state(cl, Client_Working);
860         connection_continue(co);
861         return 1;
862     }
863     else
864     {
865         yaz_log(YLOG_LOG, "cl=%s. OK no more in total set", client_get_id(cl));
866     }
867     return 0;
868 }
869
870 int client_parse_init(struct client *cl, int same_search)
871 {
872     cl->same_search = same_search;
873     return 0;
874 }
875
876 /*
877  * TODO consider how to extend the range
878  * */
879 int client_parse_range(struct client *cl, const char *startrecs,
880                        const char *maxrecs)
881 {
882     if (maxrecs && atoi(maxrecs) != cl->maxrecs)
883     {
884         cl->same_search = 0;
885         cl->maxrecs = atoi(maxrecs);
886     }
887
888     if (startrecs && atoi(startrecs) != cl->startrecs)
889     {
890         cl->same_search = 0;
891         cl->startrecs = atoi(startrecs);
892     }
893
894     return 0;
895 }
896
897 int client_start_search(struct client *cl)
898 {
899     struct session_database *sdb = client_get_database(cl);
900     struct connection *co = 0;
901     ZOOM_connection link = 0;
902     struct session *se = client_get_session(cl);
903     ZOOM_resultset rs;
904     const char *opt_piggyback   = session_setting_oneval(sdb, PZ_PIGGYBACK);
905     const char *opt_queryenc    = session_setting_oneval(sdb, PZ_QUERYENCODING);
906     const char *opt_elements    = session_setting_oneval(sdb, PZ_ELEMENTS);
907     const char *opt_requestsyn  = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
908     const char *opt_maxrecs     = session_setting_oneval(sdb, PZ_MAXRECS);
909     const char *opt_sru         = session_setting_oneval(sdb, PZ_SRU);
910     const char *opt_sort        = session_setting_oneval(sdb, PZ_SORT);
911     const char *opt_preferred   = session_setting_oneval(sdb, PZ_PREFERRED);
912     const char *extra_args      = session_setting_oneval(sdb, PZ_EXTRA_ARGS);
913     const char *opt_present_chunk = session_setting_oneval(sdb, PZ_PRESENT_CHUNK);
914     ZOOM_query query;
915     char maxrecs_str[24], startrecs_str[24], present_chunk_str[24];
916     struct timeval tval;
917     int present_chunk = 20; // Default chunk size
918     int rc_prep_connection;
919
920
921     yaz_gettimeofday(&tval);
922     tval.tv_sec += 5;
923
924     if (opt_present_chunk && strcmp(opt_present_chunk,"")) {
925         present_chunk = atoi(opt_present_chunk);
926         yaz_log(YLOG_DEBUG, "Present chunk set to %d", present_chunk);
927     }
928     rc_prep_connection =
929         client_prep_connection(cl, se->service->z3950_operation_timeout,
930                                se->service->z3950_session_timeout,
931                                se->service->server->iochan_man,
932                                &tval);
933     /* Nothing has changed and we already have a result */
934     if (cl->same_search == 1 && rc_prep_connection == 2)
935     {
936         session_log(se, YLOG_LOG, "client %s resuse result", client_get_id(cl));
937         client_report_facets(cl, cl->resultset);
938         return client_reingest(cl);
939     }
940     else if (!rc_prep_connection)
941     {
942         session_log(se, YLOG_LOG, "client %s postponing search: No connection",
943                     client_get_id(cl));
944         client_set_state_nb(cl, Client_Working);
945         return -1;
946     }
947     co = client_get_connection(cl);
948     assert(cl);
949     link = connection_get_link(co);
950     assert(link);
951
952     session_log(se, YLOG_LOG, "client %s new search", client_get_id(cl));
953
954     cl->diagnostic = 0;
955     cl->filtered = 0;
956
957     client_destroy_xdoc(cl);
958     client_init_xdoc(cl);
959
960     if (extra_args && *extra_args)
961         ZOOM_connection_option_set(link, "extraArgs", extra_args);
962
963     if (opt_preferred) {
964         cl->preferred = atoi(opt_preferred);
965         if (cl->preferred)
966             yaz_log(YLOG_LOG, "Target %s has preferred status: %d",
967                     client_get_id(cl), cl->preferred);
968     }
969
970     if (*opt_piggyback)
971         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
972     else
973         ZOOM_connection_option_set(link, "piggyback", "1");
974     if (*opt_queryenc)
975         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
976     if (*opt_sru && *opt_elements)
977         ZOOM_connection_option_set(link, "schema", opt_elements);
978     else if (*opt_elements)
979         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
980     if (*opt_requestsyn)
981         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
982
983     if (opt_maxrecs && *opt_maxrecs)
984     {
985         cl->maxrecs = atoi(opt_maxrecs);
986     }
987
988     /* convert back to string representation used in ZOOM API */
989     sprintf(maxrecs_str, "%d", cl->maxrecs);
990     ZOOM_connection_option_set(link, "count", maxrecs_str);
991
992     /* A present_chunk less than 1 will disable chunking. */
993     if (present_chunk > 0 && cl->maxrecs > present_chunk) {
994         sprintf(present_chunk_str, "%d", present_chunk);
995         ZOOM_connection_option_set(link, "presentChunk", present_chunk_str);
996         yaz_log(YLOG_DEBUG, "Present chunk set to %s", present_chunk_str);
997     }
998     else {
999         ZOOM_connection_option_set(link, "presentChunk", maxrecs_str);
1000         yaz_log(YLOG_DEBUG, "Present chunk set to %s (maxrecs)", maxrecs_str);
1001     }
1002     sprintf(startrecs_str, "%d", cl->startrecs);
1003     ZOOM_connection_option_set(link, "start", startrecs_str);
1004
1005     /* TODO Verify does it break something for CQL targets(non-SOLR) ? */
1006     /* facets definition is in PQF */
1007     client_set_facets_request(cl, link);
1008
1009     query = ZOOM_query_create();
1010     if (cl->cqlquery)
1011     {
1012         yaz_log(YLOG_LOG, "Client %s: Search CQL: %s", client_get_id(cl),
1013                 cl->cqlquery);
1014         ZOOM_query_cql(query, cl->cqlquery);
1015         if (*opt_sort)
1016             ZOOM_query_sortby(query, opt_sort);
1017     }
1018     else
1019     {
1020         yaz_log(YLOG_LOG, "Client %s: Search PQF: %s", client_get_id(cl),
1021                 cl->pquery);
1022
1023         ZOOM_query_prefix(query, cl->pquery);
1024     }
1025     if (cl->sort_strategy && cl->sort_criteria) {
1026         yaz_log(YLOG_LOG, "Client %s: "
1027                 "Set ZOOM sort strategy and criteria: %s %s",
1028                 client_get_id(cl), cl->sort_strategy, cl->sort_criteria);
1029         ZOOM_query_sortby2(query, cl->sort_strategy, cl->sort_criteria);
1030     }
1031
1032     yaz_log(YLOG_DEBUG,"Client %s: Starting search", client_get_id(cl));
1033     client_set_state(cl, Client_Working);
1034     cl->hits = 0;
1035     cl->record_offset = 0;
1036     rs = ZOOM_connection_search(link, query);
1037     ZOOM_query_destroy(query);
1038     ZOOM_resultset_destroy(cl->resultset);
1039     cl->resultset = rs;
1040     connection_continue(co);
1041     return 0;
1042 }
1043
1044 struct client *client_create(const char *id)
1045 {
1046     struct client *cl = xmalloc(sizeof(*cl));
1047     cl->maxrecs = 100;
1048     cl->startrecs = 0;
1049     cl->pquery = 0;
1050     cl->cqlquery = 0;
1051     cl->addinfo = 0;
1052     cl->message = 0;
1053     cl->database = 0;
1054     cl->connection = 0;
1055     cl->session = 0;
1056     cl->hits = 0;
1057     cl->record_offset = 0;
1058     cl->filtered = 0;
1059     cl->diagnostic = 0;
1060     cl->state = Client_Disconnected;
1061     cl->show_raw = 0;
1062     cl->resultset = 0;
1063     cl->suggestions = 0;
1064     cl->mutex = 0;
1065     pazpar2_mutex_create(&cl->mutex, "client");
1066     cl->preferred = 0;
1067     cl->ref_count = 1;
1068     cl->facet_limits = 0;
1069     cl->sort_strategy = 0;
1070     cl->sort_criteria = 0;
1071     assert(id);
1072     cl->id = xstrdup(id);
1073     client_init_xdoc(cl);
1074     client_use(1);
1075
1076     yaz_log(YLOG_DEBUG, "client_create c=%p %s", cl, id);
1077     return cl;
1078 }
1079
1080 void client_lock(struct client *c)
1081 {
1082     yaz_mutex_enter(c->mutex);
1083 }
1084
1085 void client_unlock(struct client *c)
1086 {
1087     yaz_mutex_leave(c->mutex);
1088 }
1089
1090 void client_incref(struct client *c)
1091 {
1092     pazpar2_incref(&c->ref_count, c->mutex);
1093     yaz_log(YLOG_DEBUG, "client_incref c=%p %s cnt=%d",
1094             c, client_get_id(c), c->ref_count);
1095 }
1096
1097 int client_destroy(struct client *c)
1098 {
1099     if (c)
1100     {
1101         yaz_log(YLOG_DEBUG, "client_destroy c=%p %s cnt=%d",
1102                 c, client_get_id(c), c->ref_count);
1103         if (!pazpar2_decref(&c->ref_count, c->mutex))
1104         {
1105             xfree(c->pquery);
1106             c->pquery = 0;
1107             xfree(c->cqlquery);
1108             c->cqlquery = 0;
1109             xfree(c->addinfo);
1110             c->addinfo = 0;
1111             xfree(c->message);
1112             c->message = 0;
1113             xfree(c->id);
1114             xfree(c->sort_strategy);
1115             xfree(c->sort_criteria);
1116             assert(!c->connection);
1117             facet_limits_destroy(c->facet_limits);
1118
1119             client_destroy_xdoc(c);
1120             if (c->resultset)
1121             {
1122                 ZOOM_resultset_destroy(c->resultset);
1123             }
1124             yaz_mutex_destroy(&c->mutex);
1125             xfree(c);
1126             client_use(-1);
1127             return 1;
1128         }
1129     }
1130     return 0;
1131 }
1132
1133 void client_set_connection(struct client *cl, struct connection *con)
1134 {
1135     if (cl->resultset)
1136         ZOOM_resultset_release(cl->resultset);
1137     if (con)
1138     {
1139         assert(cl->connection == 0);
1140         cl->connection = con;
1141         client_incref(cl);
1142     }
1143     else
1144     {
1145         cl->connection = con;
1146         client_destroy(cl);
1147     }
1148 }
1149
1150 void client_disconnect(struct client *cl)
1151 {
1152     if (cl->state != Client_Idle)
1153         client_set_state(cl, Client_Disconnected);
1154     client_set_connection(cl, 0);
1155 }
1156
1157 // Initialize CCL map for a target
1158 static CCL_bibset prepare_cclmap(struct client *cl, CCL_bibset base_bibset)
1159 {
1160     struct session_database *sdb = client_get_database(cl);
1161     struct setting *s;
1162     CCL_bibset res;
1163
1164     if (!sdb->settings)
1165         return 0;
1166     if (base_bibset)
1167         res = ccl_qual_dup(base_bibset);
1168     else
1169         res = ccl_qual_mk();
1170     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
1171     {
1172         const char *addinfo = 0;
1173         char *p = strchr(s->name + 3, ':');
1174         if (!p)
1175         {
1176             WRBUF w = wrbuf_alloc();
1177             wrbuf_printf(w, "Malformed cclmap. name=%s", s->name);
1178             yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1179             client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1180                                   ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1181                                   wrbuf_cstr(w));
1182             client_set_state_nb(cl, Client_Error);
1183             ccl_qual_rm(&res);
1184             wrbuf_destroy(w);
1185             return 0;
1186         }
1187         p++;
1188         if (ccl_qual_fitem2(res, s->value, p, &addinfo))
1189         {
1190             WRBUF w = wrbuf_alloc();
1191
1192             wrbuf_printf(w, "Malformed cclmap. name=%s: value=%s (%s)",
1193                          s->name, p, addinfo);
1194             yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1195             client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1196                                   ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1197                                   wrbuf_cstr(w));
1198             client_set_state_nb(cl, Client_Error);
1199             ccl_qual_rm(&res);
1200             wrbuf_destroy(w);
1201             return 0;
1202         }
1203     }
1204     return res;
1205 }
1206
1207 // returns a xmalloced CQL query corresponding to the pquery in client
1208 static char *make_cqlquery(struct client *cl, Z_RPNQuery *zquery)
1209 {
1210     cql_transform_t cqlt = cql_transform_create();
1211     char *r = 0;
1212     WRBUF wrb = wrbuf_alloc();
1213     int status;
1214
1215     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
1216     {
1217         yaz_log(YLOG_WARN, "Failed to generate CQL query, code=%d", status);
1218     }
1219     else
1220     {
1221         r = xstrdup(wrbuf_cstr(wrb));
1222     }
1223     wrbuf_destroy(wrb);
1224     cql_transform_close(cqlt);
1225     return r;
1226 }
1227
1228 // returns a xmalloced SOLR query corresponding to the pquery in client
1229 // TODO Could prob. be merge with the similar make_cqlquery
1230 static char *make_solrquery(struct client *cl, Z_RPNQuery *zquery)
1231 {
1232     solr_transform_t sqlt = solr_transform_create();
1233     char *r = 0;
1234     WRBUF wrb = wrbuf_alloc();
1235     int status;
1236
1237     if ((status = solr_transform_rpn2solr_wrbuf(sqlt, wrb, zquery)))
1238     {
1239         yaz_log(YLOG_WARN, "Failed to generate SOLR query, code=%d", status);
1240     }
1241     else
1242     {
1243         r = xstrdup(wrbuf_cstr(wrb));
1244     }
1245     wrbuf_destroy(wrb);
1246     solr_transform_close(sqlt);
1247     return r;
1248 }
1249
1250 const char *client_get_facet_limit_local(struct client *cl,
1251                                          struct session_database *sdb,
1252                                          int *l,
1253                                          NMEM nmem, int *num, char ***values)
1254 {
1255     const char *name = 0;
1256     const char *value = 0;
1257     for (; (name = facet_limits_get(cl->facet_limits, *l, &value)); (*l)++)
1258     {
1259         struct setting *s = 0;
1260
1261         for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1262         {
1263             const char *p = strchr(s->name + 3, ':');
1264             if (p && !strcmp(p + 1, name) && s->value)
1265             {
1266                 int j, cnum;
1267                 char **cvalues;
1268                 nmem_strsplit_escape2(nmem, ",", s->value, &cvalues,
1269                                       &cnum, 1, '\\', 1);
1270                 for (j = 0; j < cnum; j++)
1271                 {
1272                     const char *cvalue = cvalues[j];
1273                     while (*cvalue == ' ')
1274                         cvalue++;
1275                     if (!strncmp(cvalue, "local:", 6))
1276                     {
1277                         const char *cp = cvalue + 6;
1278                         while (*cp == ' ')
1279                             cp++;
1280                         nmem_strsplit_escape2(nmem, "|", value, values,
1281                                               num, 1, '\\', 1);
1282                         (*l)++;
1283                         return *cp ? cp : name;
1284                     }
1285                 }
1286             }
1287         }
1288     }
1289     return 0;
1290 }
1291
1292 static int apply_limit(struct session_database *sdb,
1293                        facet_limits_t facet_limits,
1294                        WRBUF w_pqf, CCL_bibset ccl_map,
1295                        struct conf_service *service)
1296 {
1297     int ret = 0;
1298     int i = 0;
1299     const char *name;
1300     const char *value;
1301
1302     NMEM nmem_tmp = nmem_create();
1303     for (i = 0; (name = facet_limits_get(facet_limits, i, &value)); i++)
1304     {
1305         struct setting *s = 0;
1306         nmem_reset(nmem_tmp);
1307         /* name="pz:limitmap:author" value="rpn:@attr 1=4|local:other" */
1308         for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1309         {
1310             const char *p = strchr(s->name + 3, ':');
1311             if (p && !strcmp(p + 1, name) && s->value)
1312             {
1313                 char **values = 0;
1314                 int i, num = 0;
1315                 char **cvalues = 0;
1316                 int j, cnum = 0;
1317                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1318                                       &num, 1, '\\', 1);
1319
1320                 nmem_strsplit_escape2(nmem_tmp, ",", s->value, &cvalues,
1321                                       &cnum, 1, '\\', 1);
1322
1323                 for (j = 0; ret == 0 && j < cnum; j++)
1324                 {
1325                     const char *cvalue = cvalues[j];
1326                     while (*cvalue == ' ')
1327                         cvalue++;
1328                     if (!strncmp(cvalue, "rpn:", 4))
1329                     {
1330                         const char *pqf = cvalue + 4;
1331                         wrbuf_puts(w_pqf, "@and ");
1332                         wrbuf_puts(w_pqf, pqf);
1333                         wrbuf_puts(w_pqf, " ");
1334                         for (i = 0; i < num; i++)
1335                         {
1336                             if (i < num - 1)
1337                                 wrbuf_puts(w_pqf, "@or ");
1338                             yaz_encode_pqf_term(w_pqf, values[i],
1339                                                 strlen(values[i]));
1340                         }
1341                     }
1342                     else if (!strncmp(cvalue, "ccl:", 4))
1343                     {
1344                         const char *ccl = cvalue + 4;
1345                         WRBUF ccl_w = wrbuf_alloc();
1346                         for (i = 0; i < num; i++)
1347                         {
1348                             int cerror, cpos;
1349                             struct ccl_rpn_node *cn;
1350                             wrbuf_rewind(ccl_w);
1351                             wrbuf_puts(ccl_w, ccl);
1352                             wrbuf_puts(ccl_w, "=\"");
1353                             wrbuf_puts(ccl_w, values[i]);
1354                             wrbuf_puts(ccl_w, "\"");
1355
1356                             cn = ccl_find_str(ccl_map, wrbuf_cstr(ccl_w),
1357                                               &cerror, &cpos);
1358                             if (cn)
1359                             {
1360                                 if (i == 0)
1361                                     wrbuf_printf(w_pqf, "@and ");
1362
1363                                 /* or multiple values.. could be bad if last
1364                                    CCL parse fails, but this is unlikely to
1365                                    happen */
1366                                 if (i < num - 1)
1367                                     wrbuf_printf(w_pqf, "@or ");
1368                                 ccl_pquery(w_pqf, cn);
1369                                 ccl_rpn_delete(cn);
1370                             }
1371                         }
1372                         wrbuf_destroy(ccl_w);
1373                     }
1374                     else if (!strncmp(cvalue, "local:", 6)) {
1375                         /* no operation */
1376                     }
1377                     else
1378                     {
1379                         yaz_log(YLOG_WARN, "Target %s: Bad limitmap '%s'",
1380                                 sdb->database->id, cvalue);
1381                         ret = -1; /* bad limitmap */
1382                     }
1383                 }
1384                 break;
1385             }
1386         }
1387         if (!s)
1388         {
1389             int i;
1390             for (i = 0; i < service->num_metadata; i++)
1391             {
1392                 struct conf_metadata *md = service->metadata + i;
1393                 if (!strcmp(md->name, name) && md->limitcluster)
1394                 {
1395                     yaz_log(YLOG_LOG, "limitcluster in use for %s",
1396                             md->name);
1397                     break;
1398                 }
1399             }
1400             if (i == service->num_metadata)
1401             {
1402                 yaz_log(YLOG_WARN, "Target %s: limit %s used, but no limitmap defined",
1403                         (sdb->database ? sdb->database->id : "<no id>"), name);
1404             }
1405         }
1406     }
1407     nmem_destroy(nmem_tmp);
1408     return ret;
1409 }
1410
1411 // Parse the query given the settings specific to this client
1412 // client variable same_search is set as below as well as returned:
1413 // 0 if query is OK but different from before
1414 // 1 if query is OK but same as before
1415 // return -1 on query error
1416 // return -2 on limit error
1417 int client_parse_query(struct client *cl, const char *query,
1418                        facet_limits_t facet_limits, const char **error_msg)
1419 {
1420     struct session *se = client_get_session(cl);
1421     struct conf_service *service = se->service;
1422     struct session_database *sdb = client_get_database(cl);
1423     struct ccl_rpn_node *cn;
1424     int cerror, cpos;
1425     ODR odr_out;
1426     CCL_bibset ccl_map = prepare_cclmap(cl, service->ccl_bibset);
1427     const char *sru = session_setting_oneval(sdb, PZ_SRU);
1428     const char *pqf_prefix = session_setting_oneval(sdb, PZ_PQF_PREFIX);
1429     const char *pqf_strftime = session_setting_oneval(sdb, PZ_PQF_STRFTIME);
1430     const char *query_syntax = session_setting_oneval(sdb, PZ_QUERY_SYNTAX);
1431     WRBUF w_ccl, w_pqf;
1432     int ret_value = 1;
1433     Z_RPNQuery *zquery;
1434
1435     if (!ccl_map)
1436         return -3;
1437
1438     w_ccl = wrbuf_alloc();
1439     wrbuf_puts(w_ccl, query);
1440
1441     w_pqf = wrbuf_alloc();
1442     if (*pqf_prefix)
1443     {
1444         wrbuf_puts(w_pqf, pqf_prefix);
1445         wrbuf_puts(w_pqf, " ");
1446     }
1447
1448     if (apply_limit(sdb, facet_limits, w_pqf, ccl_map, service))
1449     {
1450         ccl_qual_rm(&ccl_map);
1451         return -2;
1452     }
1453
1454     facet_limits_destroy(cl->facet_limits);
1455     cl->facet_limits = facet_limits_dup(facet_limits);
1456
1457     yaz_log(YLOG_LOG, "Client %s: CCL query: %s limit: %s",
1458             client_get_id(cl), wrbuf_cstr(w_ccl), wrbuf_cstr(w_pqf));
1459     cn = ccl_find_str(ccl_map, wrbuf_cstr(w_ccl), &cerror, &cpos);
1460     ccl_qual_rm(&ccl_map);
1461     if (!cn)
1462     {
1463         if (error_msg)
1464             *error_msg = ccl_err_msg(cerror);
1465         client_set_state(cl, Client_Error);
1466         session_log(se, YLOG_WARN, "Client %s: Failed to parse CCL query '%s'",
1467                     client_get_id(cl),
1468                     wrbuf_cstr(w_ccl));
1469         wrbuf_destroy(w_ccl);
1470         wrbuf_destroy(w_pqf);
1471         return -1;
1472     }
1473     wrbuf_destroy(w_ccl);
1474
1475     if (!pqf_strftime || !*pqf_strftime)
1476         ccl_pquery(w_pqf, cn);
1477     else
1478     {
1479         time_t cur_time = time(0);
1480         struct tm *tm =  localtime(&cur_time);
1481         char tmp_str[300];
1482         const char *cp = tmp_str;
1483
1484         /* see man strftime(3) for things .. In particular %% gets converted
1485          to %.. And That's our original query .. */
1486         strftime(tmp_str, sizeof(tmp_str)-1, pqf_strftime, tm);
1487         for (; *cp; cp++)
1488         {
1489             if (cp[0] == '%')
1490                 ccl_pquery(w_pqf, cn);
1491             else
1492                 wrbuf_putc(w_pqf, cp[0]);
1493         }
1494     }
1495
1496     /* Compares query and limit with old one. If different we need to research */
1497     if (!cl->pquery || strcmp(cl->pquery, wrbuf_cstr(w_pqf)))
1498     {
1499         if (cl->pquery)
1500             session_log(se, YLOG_LOG, "Client %s: "
1501                         "Re-search due query/limit change: %s to %s", 
1502                         client_get_id(cl), cl->pquery, wrbuf_cstr(w_pqf));
1503         xfree(cl->pquery);
1504         cl->pquery = xstrdup(wrbuf_cstr(w_pqf));
1505         // return value is no longer used.
1506         ret_value = 0;
1507         // Need to (re)search
1508         cl->same_search= 0;
1509     }
1510     wrbuf_destroy(w_pqf);
1511
1512     xfree(cl->cqlquery);
1513     cl->cqlquery = 0;
1514
1515     odr_out = odr_createmem(ODR_ENCODE);
1516     zquery = p_query_rpn(odr_out, cl->pquery);
1517     if (!zquery)
1518     {
1519
1520         session_log(se, YLOG_WARN, "Invalid PQF query for Client %s: %s",
1521                     client_get_id(cl), cl->pquery);
1522         ret_value = -1;
1523         *error_msg = "Invalid PQF after CCL to PQF conversion";
1524     }
1525     else
1526     {
1527         session_log(se, YLOG_LOG, "PQF for Client %s: %s",
1528                     client_get_id(cl), cl->pquery);
1529
1530         /* Support for PQF on SRU targets. */
1531         if (strcmp(query_syntax, "pqf") != 0 && *sru)
1532         {
1533             if (!strcmp(sru, "solr"))
1534                 cl->cqlquery = make_solrquery(cl, zquery);
1535             else
1536                 cl->cqlquery = make_cqlquery(cl, zquery);
1537             if (!cl->cqlquery)
1538             {
1539                 *error_msg = "Cannot convert PQF to Solr/CQL";
1540                 ret_value = -1;
1541             }
1542             else
1543                 session_log(se, YLOG_LOG, "Client %s native query: %s (%s)",
1544                             client_get_id(cl), cl->cqlquery, sru);
1545         }
1546     }
1547     odr_destroy(odr_out);
1548
1549     /* TODO FIX Not thread safe */
1550     if (!se->relevance)
1551     {
1552         // Initialize relevance structure with query terms
1553         se->relevance = relevance_create_ccl(se->service->charsets, cn,
1554                                              se->service->rank_cluster,
1555                                              se->service->rank_follow,
1556                                              se->service->rank_lead,
1557                                              se->service->rank_length);
1558     }
1559     ccl_rpn_delete(cn);
1560     return ret_value;
1561 }
1562
1563 int client_parse_sort(struct client *cl, struct reclist_sortparms *sp)
1564 {
1565     if (sp)
1566     {
1567         const char *sort_strategy_and_spec =
1568             get_strategy_plus_sort(cl, sp->name);
1569         int increasing = sp->increasing;
1570         if (!strcmp(sp->name, "relevance"))
1571             increasing = 1;
1572         if (sort_strategy_and_spec && strlen(sort_strategy_and_spec) < 40)
1573         {
1574             char strategy[50], *p;
1575             strcpy(strategy, sort_strategy_and_spec);
1576             p = strchr(strategy, ':');
1577             if (p)
1578             {
1579                 // Split the string in two
1580                 *p++ = 0;
1581                 while (*p == ' ')
1582                     p++;
1583                 if (increasing)
1584                     strcat(p, " <");
1585                 else
1586                     strcat(p, " >");
1587                 yaz_log(YLOG_LOG, "Client %s: "
1588                         "applying sorting %s %s", client_get_id(cl),
1589                         strategy, p);
1590                 if (!cl->sort_strategy || strcmp(cl->sort_strategy, strategy))
1591                     cl->same_search = 0;
1592                 if (!cl->sort_criteria || strcmp(cl->sort_criteria, p))
1593                     cl->same_search = 0;
1594                 if (cl->same_search == 0) {
1595                     xfree(cl->sort_strategy);
1596                     cl->sort_strategy = xstrdup(strategy);
1597                     xfree(cl->sort_criteria);
1598                     cl->sort_criteria = xstrdup(p);
1599                 }
1600             }
1601             else {
1602                 yaz_log(YLOG_LOG, "Client %s: "
1603                         "Invalid sort strategy and spec found %s",
1604                         client_get_id(cl), sort_strategy_and_spec);
1605                 xfree(cl->sort_strategy);
1606                 cl->sort_strategy  = 0;
1607                 xfree(cl->sort_criteria);
1608                 cl->sort_criteria = 0;
1609             }
1610         }
1611         else
1612         {
1613             yaz_log(YLOG_DEBUG, "Client %s: "
1614                     "No sort strategy and spec found.", client_get_id(cl));
1615             xfree(cl->sort_strategy);
1616             cl->sort_strategy  = 0;
1617             xfree(cl->sort_criteria);
1618             cl->sort_criteria = 0;
1619         }
1620
1621     }
1622     return !cl->same_search;
1623 }
1624
1625 void client_set_session(struct client *cl, struct session *se)
1626 {
1627     cl->session = se;
1628 }
1629
1630 int client_is_active(struct client *cl)
1631 {
1632     if (cl->connection && (cl->state == Client_Connecting ||
1633                            cl->state == Client_Working))
1634         return 1;
1635     return 0;
1636 }
1637
1638 int client_is_active_preferred(struct client *cl)
1639 {
1640     /* only count if this is a preferred target. */
1641     if (!cl->preferred)
1642         return 0;
1643     /* TODO No sure this the condition that Seb wants */
1644     if (cl->connection && (cl->state == Client_Connecting ||
1645                            cl->state == Client_Working))
1646         return 1;
1647     return 0;
1648 }
1649
1650 Odr_int client_get_hits(struct client *cl)
1651 {
1652     return cl->hits;
1653 }
1654
1655 Odr_int client_get_approximation(struct client *cl)
1656 {
1657     if (cl->record_offset > 0)
1658     {
1659         Odr_int approx = ((10 * cl->hits * (cl->record_offset - cl->filtered))
1660                           / cl->record_offset + 5) /10;
1661         yaz_log(YLOG_DEBUG, "%s: Approx: %lld * %d / %d = %lld ",
1662                 client_get_id(cl), cl->hits,
1663                 cl->record_offset - cl->filtered, cl->record_offset, approx);
1664         return approx;
1665     }
1666     return cl->hits;
1667 }
1668
1669 int client_get_num_records(struct client *cl)
1670 {
1671     return cl->record_offset;
1672 }
1673
1674 int client_get_num_records_filtered(struct client *cl)
1675 {
1676     return cl->filtered;
1677 }
1678
1679 void client_set_diagnostic(struct client *cl, int diagnostic,
1680                            const char *message, const char *addinfo)
1681 {
1682     cl->diagnostic = diagnostic;
1683     xfree(cl->message);
1684     cl->message = xstrdup(message);
1685     xfree(cl->addinfo);
1686     cl->addinfo = 0;
1687     if (addinfo)
1688         cl->addinfo = xstrdup(addinfo);
1689 }
1690
1691 int client_get_diagnostic(struct client *cl, const char **message,
1692                           const char **addinfo)
1693 {
1694     if (message)
1695         *message = cl->message;
1696     if (addinfo)
1697         *addinfo = cl->addinfo;
1698     return cl->diagnostic;
1699 }
1700
1701 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf)
1702 {
1703     /* int idx; */
1704     struct suggestions *suggestions = cl->suggestions;
1705
1706     if (!suggestions) 
1707         return "";
1708     if (suggestions->passthrough)
1709     {
1710         yaz_log(YLOG_DEBUG, "Passthrough Suggestions: \n%s\n",
1711                 suggestions->passthrough);
1712         return suggestions->passthrough;
1713     }
1714     if (suggestions->num == 0)
1715         return "";
1716     /*
1717     for (idx = 0; idx < suggestions->num; idx++) {
1718         wrbuf_printf(wrbuf, "<suggest term=\"%s\"", suggestions->suggest[idx]);
1719         if (suggestions->misspelled[idx] && suggestions->misspelled[idx]) {
1720             wrbuf_puts(wrbuf, suggestions->misspelled[idx]);
1721             wrbuf_puts(wrbuf, "</suggest>\n");
1722         }
1723         else
1724             wrbuf_puts(wrbuf, "/>\n");
1725     }
1726     */
1727     return wrbuf_cstr(wrbuf);
1728 }
1729
1730
1731 void client_set_database(struct client *cl, struct session_database *db)
1732 {
1733     cl->database = db;
1734 }
1735
1736 const char *client_get_id(struct client *cl)
1737 {
1738     return cl->id;
1739 }
1740
1741 int client_get_maxrecs(struct client *cl)
1742 {
1743     return cl->maxrecs;
1744 }
1745
1746 void client_set_preferred(struct client *cl, int v)
1747 {
1748     cl->preferred = v;
1749 }
1750
1751
1752 struct suggestions* client_suggestions_create(const char* suggestions_string)
1753 {
1754     int i;
1755     NMEM nmem;
1756     struct suggestions *suggestions;
1757     if (suggestions_string == 0 || suggestions_string[0] == 0 )
1758         return 0;
1759     nmem = nmem_create();
1760     suggestions = nmem_malloc(nmem, sizeof(*suggestions));
1761     yaz_log(YLOG_DEBUG, "client target suggestions: %s.", suggestions_string);
1762
1763     suggestions->nmem = nmem;
1764     suggestions->num = 0;
1765     suggestions->misspelled = 0;
1766     suggestions->suggest = 0;
1767     suggestions->passthrough = nmem_strdup_null(nmem, suggestions_string);
1768
1769     if (suggestions_string)
1770         nmem_strsplit_escape2(suggestions->nmem, "\n", suggestions_string, &suggestions->suggest,
1771                               &suggestions->num, 1, '\\', 0);
1772     /* Set up misspelled array */
1773     suggestions->misspelled = (char **)
1774         nmem_malloc(nmem, suggestions->num * sizeof(*suggestions->misspelled));
1775     /* replace = with \0 .. for each item */
1776     for (i = 0; i < suggestions->num; i++)
1777     {
1778         char *cp = strchr(suggestions->suggest[i], '=');
1779         if (cp) {
1780             *cp = '\0';
1781             suggestions->misspelled[i] = cp+1;
1782         }
1783     }
1784     return suggestions;
1785 }
1786
1787 static void client_suggestions_destroy(struct client *cl)
1788 {
1789     NMEM nmem = cl->suggestions->nmem;
1790     cl->suggestions = 0;
1791     nmem_destroy(nmem);
1792 }
1793
1794 /*
1795  * Local variables:
1796  * c-basic-offset: 4
1797  * c-file-style: "Stroustrup"
1798  * indent-tabs-mode: nil
1799  * End:
1800  * vim: shiftwidth=4 tabstop=8 expandtab
1801  */
1802