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