Merge branch 'master' into paz-927
[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; /* 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);
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 void client_check_preferred_watch(struct client *cl)
547 {
548     struct session *se = cl->session;
549     yaz_log(YLOG_DEBUG, "client_check_preferred_watch: %s ", client_get_id(cl));
550     if (se)
551     {
552         client_unlock(cl);
553         /* TODO possible threading issue. Session can have been destroyed */
554         if (session_is_preferred_clients_ready(se)) {
555             session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
556         }
557         else
558             yaz_log(YLOG_DEBUG, "client_check_preferred_watch: Still locked on preferred targets.");
559
560         client_lock(cl);
561     }
562     else
563         yaz_log(YLOG_WARN, "client_check_preferred_watch: %s. No session!", client_get_id(cl));
564
565 }
566
567 struct suggestions* client_suggestions_create(const char* suggestions_string);
568 static void client_suggestions_destroy(struct client *cl);
569
570 void client_search_response(struct client *cl)
571 {
572     struct connection *co = cl->connection;
573     ZOOM_connection link = connection_get_link(co);
574     ZOOM_resultset resultset = cl->resultset;
575     struct session *se = client_get_session(cl);
576
577     const char *error, *addinfo = 0;
578
579     if (ZOOM_connection_error(link, &error, &addinfo))
580     {
581         cl->hits = 0;
582         session_log(se, YLOG_WARN, "%s: Error %s (%s)",
583                     client_get_id(cl), error, addinfo);
584         client_set_state(cl, Client_Error);
585     }
586     else
587     {
588         client_report_facets(cl, resultset);
589         cl->record_offset = cl->startrecs;
590         cl->hits = ZOOM_resultset_size(resultset);
591         session_log(se, YLOG_LOG, "%s: hits: " ODR_INT_PRINTF,
592                     client_get_id(cl), cl->hits);
593         if (cl->suggestions)
594             client_suggestions_destroy(cl);
595         cl->suggestions =
596             client_suggestions_create(ZOOM_resultset_option_get(
597                                           resultset, "suggestions"));
598     }
599 }
600
601 void client_got_records(struct client *cl)
602 {
603     struct session *se = cl->session;
604     if (se)
605     {
606         if (reclist_get_num_records(se->reclist) > 0)
607         {
608             client_unlock(cl);
609             session_alert_watch(se, SESSION_WATCH_SHOW);
610             session_alert_watch(se, SESSION_WATCH_BYTARGET);
611             session_alert_watch(se, SESSION_WATCH_TERMLIST);
612             session_alert_watch(se, SESSION_WATCH_RECORD);
613             client_lock(cl);
614         }
615     }
616 }
617
618 static void client_record_ingest(struct client *cl)
619 {
620     const char *msg, *addinfo;
621     ZOOM_record rec = 0;
622     ZOOM_resultset resultset = cl->resultset;
623     struct session *se = client_get_session(cl);
624     xmlDoc *xdoc;
625     int offset = cl->record_offset + 1; /* 0 versus 1 numbered offsets */
626
627     xdoc = client_get_xdoc(cl, offset);
628     if (xdoc)
629     {
630         if (cl->session)
631         {
632             NMEM nmem = nmem_create();
633             int rc = ingest_xml_record(cl, xdoc, offset, nmem, 1);
634             if (rc == -1)
635             {
636                 session_log(se, YLOG_WARN,
637                             "%s: #%d: failed to ingest xdoc",
638                             client_get_id(cl), offset);
639                 cl->ingest_failures++;
640             }
641             else if (rc == -2)
642                 cl->filtered++;
643             nmem_destroy(nmem);
644         }
645     }
646     else if ((rec = ZOOM_resultset_record_immediate(resultset,
647                                                     cl->record_offset)))
648     {
649         if (cl->session == 0)
650             ;  /* no operation */
651         else if (ZOOM_record_error(rec, &msg, &addinfo, 0))
652         {
653             session_log(se, YLOG_WARN, "Record error %s (%s): %s #%d",
654                         msg, addinfo, client_get_id(cl), offset);
655             cl->record_failures++;
656         }
657         else
658         {
659             struct session_database *sdb = client_get_database(cl);
660             NMEM nmem = nmem_create();
661             const char *xmlrec;
662             char type[80];
663
664             const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
665             if (nativesyntax_to_type(s, type, rec))
666                 session_log(se, YLOG_WARN, "Failed to determine record type");
667             xmlrec = ZOOM_record_get(rec, type, NULL);
668             if (!xmlrec)
669             {
670                 const char *rec_syn =  ZOOM_record_get(rec, "syntax", NULL);
671                 session_log(se, YLOG_WARN, "%s: #%d: ZOOM_record_get failed",
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
680             {
681                 /* OK = 0, -1 = failure, -2 = Filtered */
682                 int rc = ingest_record(cl, xmlrec, offset, nmem);
683                 if (rc == -1)
684                 {
685                     const char *rec_syn =  ZOOM_record_get(rec, "syntax", NULL);
686                     session_log(se, YLOG_WARN,
687                                 "%s: #%d: failed to ingest record",
688                                 client_get_id(cl), offset);
689                     session_log(se, YLOG_LOG, "pz:nativesyntax=%s . "
690                                 "ZOOM record type=%s . Actual record syntax=%s",
691                                 s ? s : "null", type,
692                                 rec_syn ? rec_syn : "null");
693                     cl->ingest_failures++;
694                 }
695                 else if (rc == -2)
696                     cl->filtered++;
697             }
698             nmem_destroy(nmem);
699         }
700     }
701     else
702     {
703         session_log(se, YLOG_WARN, "Got NULL record from %s #%d",
704                     client_get_id(cl), offset);
705     }
706     cl->record_offset++;
707 }
708
709 void client_record_response(struct client *cl, int *got_records)
710 {
711     struct connection *co = cl->connection;
712     ZOOM_connection link = connection_get_link(co);
713     ZOOM_resultset resultset = cl->resultset;
714     const char *error, *addinfo;
715
716     if (ZOOM_connection_error(link, &error, &addinfo))
717     {
718         struct session *se = client_get_session(cl);
719         session_log(se, YLOG_WARN, "%s: Error %s (%s)",
720                     client_get_id(cl), error, addinfo);
721         client_set_state(cl, Client_Error);
722     }
723     else
724     {
725         if (cl->show_raw && cl->show_raw->active)
726         {
727             ZOOM_record rec = 0;
728             if ((rec = ZOOM_resultset_record_immediate(
729                      resultset, cl->show_raw->position-1)))
730             {
731                 cl->show_raw->active = 0;
732                 ingest_raw_record(cl, rec);
733             }
734             else
735             {
736                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
737                         cl->show_raw->position-1);
738             }
739         }
740         else
741         {
742             client_record_ingest(cl);
743             *got_records = 1;
744         }
745     }
746 }
747
748 int client_reingest(struct client *cl)
749 {
750     int i = cl->startrecs;
751     int to = cl->record_offset;
752     cl->record_failures = cl->ingest_failures = cl->filtered = 0;
753
754     cl->record_offset = i;
755     for (; i < to; i++)
756         client_record_ingest(cl);
757     return 0;
758 }
759
760 static void client_set_facets_request(struct client *cl, ZOOM_connection link)
761 {
762     struct session_database *sdb = client_get_database(cl);
763
764     WRBUF w = wrbuf_alloc();
765
766     struct setting *s;
767
768     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
769     {
770         const char *p = strchr(s->name + 3, ':');
771         if (!p)
772         {
773             yaz_log(YLOG_WARN, "Malformed facetmap name: %s", s->name);
774         }
775         else if (s->value && s->value[0])
776         {
777             wrbuf_puts(w, "@attr 1=");
778             yaz_encode_pqf_term(w, s->value, strlen(s->value));
779             if (s->next)
780                 wrbuf_puts(w, ",");
781         }
782     }
783     yaz_log(YLOG_DEBUG, "using facets str: %s", wrbuf_cstr(w));
784     ZOOM_connection_option_set(link, "facets",
785                                wrbuf_len(w) ? wrbuf_cstr(w) : 0);
786     wrbuf_destroy(w);
787 }
788
789 int client_has_facet(struct client *cl, const char *name)
790 {
791     struct session_database *sdb = client_get_database(cl);
792     struct setting *s;
793
794     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
795     {
796         const char *p = strchr(s->name + 3, ':');
797         if (p && !strcmp(name, p + 1))
798             return 1;
799     }
800     return 0;
801 }
802
803 static const char *get_strategy_plus_sort(struct client *l, const char *field)
804 {
805     struct session_database *sdb = client_get_database(l);
806     struct setting *s;
807
808     const char *strategy_plus_sort = 0;
809
810     for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
811     {
812         char *p = strchr(s->name + 3, ':');
813         if (!p)
814         {
815             yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
816             continue;
817         }
818         p++;
819         if (!strcmp(p, field))
820         {
821             strategy_plus_sort = s->value;
822             break;
823         }
824     }
825     return strategy_plus_sort;
826 }
827
828 void client_update_show_stat(struct client *cl, int cmd)
829 {
830     if (cmd == 0)
831         cl->show_stat_no = 0;
832     else if (cmd == 1)
833         cl->show_stat_no++;
834 }
835
836 int client_fetch_more(struct client *cl)
837 {
838     struct session_database *sdb = client_get_database(cl);
839     const char *str;
840     int extend_recs = 0;
841     int number = cl->hits - cl->record_offset;
842
843     str = session_setting_oneval(sdb, PZ_EXTENDRECS);
844     if (!str || !*str)
845         return 0;
846
847     extend_recs = atoi(str);
848
849     yaz_log(YLOG_LOG, "cl=%s show_stat_no=%d got=%d",
850             client_get_id(cl), cl->show_stat_no, cl->record_offset);
851     if (cl->show_stat_no < cl->record_offset)
852         return 0;
853     yaz_log(YLOG_LOG, "cl=%s Trying to fetch more", client_get_id(cl));
854
855     if (number > extend_recs)
856         number = extend_recs;
857     if (number > 0)
858     {
859         ZOOM_resultset set = cl->resultset;
860         struct connection *co = client_get_connection(cl);
861
862         str = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
863         ZOOM_resultset_option_set(set, "preferredRecordSyntax", str);
864         str = session_setting_oneval(sdb, PZ_ELEMENTS);
865         if (str && *str)
866             ZOOM_resultset_option_set(set, "elementSetName", str);
867
868         ZOOM_resultset_records(set, 0, cl->record_offset, number);
869         client_set_state(cl, Client_Working);
870         connection_continue(co);
871         return 1;
872     }
873     else
874     {
875         yaz_log(YLOG_LOG, "cl=%s. OK no more in total set", client_get_id(cl));
876     }
877     return 0;
878 }
879
880 int client_parse_init(struct client *cl, int same_search)
881 {
882     cl->same_search = same_search;
883     return 0;
884 }
885
886 /*
887  * TODO consider how to extend the range
888  * */
889 int client_parse_range(struct client *cl, const char *startrecs,
890                        const char *maxrecs)
891 {
892     if (maxrecs && atoi(maxrecs) != cl->maxrecs)
893     {
894         cl->same_search = 0;
895         cl->maxrecs = atoi(maxrecs);
896     }
897
898     if (startrecs && atoi(startrecs) != cl->startrecs)
899     {
900         cl->same_search = 0;
901         cl->startrecs = atoi(startrecs);
902     }
903
904     return 0;
905 }
906
907 int client_start_search(struct client *cl)
908 {
909     struct session_database *sdb = client_get_database(cl);
910     struct connection *co = 0;
911     ZOOM_connection link = 0;
912     struct session *se = client_get_session(cl);
913     ZOOM_resultset rs;
914     const char *opt_piggyback   = session_setting_oneval(sdb, PZ_PIGGYBACK);
915     const char *opt_queryenc    = session_setting_oneval(sdb, PZ_QUERYENCODING);
916     const char *opt_elements    = session_setting_oneval(sdb, PZ_ELEMENTS);
917     const char *opt_requestsyn  = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
918     const char *opt_maxrecs     = session_setting_oneval(sdb, PZ_MAXRECS);
919     const char *opt_sru         = session_setting_oneval(sdb, PZ_SRU);
920     const char *opt_sort        = session_setting_oneval(sdb, PZ_SORT);
921     const char *opt_preferred   = session_setting_oneval(sdb, PZ_PREFERRED);
922     const char *extra_args      = session_setting_oneval(sdb, PZ_EXTRA_ARGS);
923     const char *opt_present_chunk = session_setting_oneval(sdb, PZ_PRESENT_CHUNK);
924     ZOOM_query query;
925     char maxrecs_str[24], startrecs_str[24], present_chunk_str[24];
926     struct timeval tval;
927     int present_chunk = 20; // Default chunk size
928     int rc_prep_connection;
929
930     cl->diagnostic = 0;
931     cl->record_failures = cl->ingest_failures = cl->filtered = 0;
932
933     yaz_gettimeofday(&tval);
934     tval.tv_sec += 5;
935
936     if (opt_present_chunk && strcmp(opt_present_chunk,"")) {
937         present_chunk = atoi(opt_present_chunk);
938         yaz_log(YLOG_DEBUG, "Present chunk set to %d", present_chunk);
939     }
940     rc_prep_connection =
941         client_prep_connection(cl, se->service->z3950_operation_timeout,
942                                se->service->z3950_session_timeout,
943                                se->service->server->iochan_man,
944                                &tval);
945     /* Nothing has changed and we already have a result */
946     if (cl->same_search == 1 && rc_prep_connection == 2)
947     {
948         session_log(se, YLOG_LOG, "%s: reuse result", client_get_id(cl));
949         client_report_facets(cl, cl->resultset);
950         return client_reingest(cl);
951     }
952     else if (!rc_prep_connection)
953     {
954         session_log(se, YLOG_LOG, "%s: postponing search: No connection",
955                     client_get_id(cl));
956         client_set_state_nb(cl, Client_Working);
957         return -1;
958     }
959     co = client_get_connection(cl);
960     assert(cl);
961     link = connection_get_link(co);
962     assert(link);
963
964     session_log(se, YLOG_LOG, "%s: new search", client_get_id(cl));
965
966     client_destroy_xdoc(cl);
967     client_init_xdoc(cl);
968
969     if (extra_args && *extra_args)
970         ZOOM_connection_option_set(link, "extraArgs", extra_args);
971
972     if (opt_preferred) {
973         cl->preferred = atoi(opt_preferred);
974         if (cl->preferred)
975             yaz_log(YLOG_LOG, "Target %s has preferred status: %d",
976                     client_get_id(cl), cl->preferred);
977     }
978
979     if (*opt_piggyback)
980         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
981     else
982         ZOOM_connection_option_set(link, "piggyback", "1");
983     if (*opt_queryenc)
984         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
985     if (*opt_sru && *opt_elements)
986         ZOOM_connection_option_set(link, "schema", opt_elements);
987     else if (*opt_elements)
988         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
989     if (*opt_requestsyn)
990         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
991
992     if (opt_maxrecs && *opt_maxrecs)
993     {
994         cl->maxrecs = atoi(opt_maxrecs);
995     }
996
997     /* convert back to string representation used in ZOOM API */
998     sprintf(maxrecs_str, "%d", cl->maxrecs);
999     ZOOM_connection_option_set(link, "count", maxrecs_str);
1000
1001     /* A present_chunk less than 1 will disable chunking. */
1002     if (present_chunk > 0 && cl->maxrecs > present_chunk) {
1003         sprintf(present_chunk_str, "%d", present_chunk);
1004         ZOOM_connection_option_set(link, "presentChunk", present_chunk_str);
1005         yaz_log(YLOG_DEBUG, "Present chunk set to %s", present_chunk_str);
1006     }
1007     else {
1008         ZOOM_connection_option_set(link, "presentChunk", maxrecs_str);
1009         yaz_log(YLOG_DEBUG, "Present chunk set to %s (maxrecs)", maxrecs_str);
1010     }
1011     sprintf(startrecs_str, "%d", cl->startrecs);
1012     ZOOM_connection_option_set(link, "start", startrecs_str);
1013
1014     /* TODO Verify does it break something for CQL targets(non-SOLR) ? */
1015     /* facets definition is in PQF */
1016     client_set_facets_request(cl, link);
1017
1018     query = ZOOM_query_create();
1019     if (cl->cqlquery)
1020     {
1021         session_log(se, YLOG_LOG, "%s: Search CQL: %s", client_get_id(cl),
1022                     cl->cqlquery);
1023         ZOOM_query_cql(query, cl->cqlquery);
1024         if (*opt_sort)
1025             ZOOM_query_sortby(query, opt_sort);
1026     }
1027     else
1028     {
1029         session_log(se, YLOG_LOG, "%s: Search PQF: %s", client_get_id(cl),
1030                     cl->pquery);
1031         ZOOM_query_prefix(query, cl->pquery);
1032     }
1033     if (cl->sort_strategy && cl->sort_criteria) {
1034         yaz_log(YLOG_LOG, "Client %s: "
1035                 "Set ZOOM sort strategy and criteria: %s %s",
1036                 client_get_id(cl), cl->sort_strategy, cl->sort_criteria);
1037         ZOOM_query_sortby2(query, cl->sort_strategy, cl->sort_criteria);
1038     }
1039
1040     yaz_log(YLOG_DEBUG,"Client %s: Starting search", client_get_id(cl));
1041     client_set_state(cl, Client_Working);
1042     cl->hits = 0;
1043     cl->record_offset = 0;
1044     rs = ZOOM_connection_search(link, query);
1045     ZOOM_query_destroy(query);
1046     ZOOM_resultset_destroy(cl->resultset);
1047     cl->resultset = rs;
1048     connection_continue(co);
1049     return 0;
1050 }
1051
1052 struct client *client_create(const char *id)
1053 {
1054     struct client *cl = xmalloc(sizeof(*cl));
1055     cl->maxrecs = 100;
1056     cl->startrecs = 0;
1057     cl->pquery = 0;
1058     cl->cqlquery = 0;
1059     cl->addinfo = 0;
1060     cl->message = 0;
1061     cl->database = 0;
1062     cl->connection = 0;
1063     cl->session = 0;
1064     cl->hits = 0;
1065     cl->record_offset = 0;
1066     cl->filtered = 0;
1067     cl->diagnostic = 0;
1068     cl->state = Client_Disconnected;
1069     cl->show_raw = 0;
1070     cl->resultset = 0;
1071     cl->suggestions = 0;
1072     cl->mutex = 0;
1073     pazpar2_mutex_create(&cl->mutex, "client");
1074     cl->preferred = 0;
1075     cl->ref_count = 1;
1076     cl->facet_limits = 0;
1077     cl->sort_strategy = 0;
1078     cl->sort_criteria = 0;
1079     assert(id);
1080     cl->id = xstrdup(id);
1081     client_init_xdoc(cl);
1082     client_use(1);
1083
1084     yaz_log(YLOG_DEBUG, "client_create c=%p %s", cl, id);
1085     return cl;
1086 }
1087
1088 void client_lock(struct client *c)
1089 {
1090     yaz_mutex_enter(c->mutex);
1091 }
1092
1093 void client_unlock(struct client *c)
1094 {
1095     yaz_mutex_leave(c->mutex);
1096 }
1097
1098 void client_incref(struct client *c)
1099 {
1100     pazpar2_incref(&c->ref_count, c->mutex);
1101     yaz_log(YLOG_DEBUG, "client_incref c=%p %s cnt=%d",
1102             c, client_get_id(c), c->ref_count);
1103 }
1104
1105 int client_destroy(struct client *c)
1106 {
1107     if (c)
1108     {
1109         yaz_log(YLOG_DEBUG, "client_destroy c=%p %s cnt=%d",
1110                 c, client_get_id(c), c->ref_count);
1111         if (!pazpar2_decref(&c->ref_count, c->mutex))
1112         {
1113             xfree(c->pquery);
1114             c->pquery = 0;
1115             xfree(c->cqlquery);
1116             c->cqlquery = 0;
1117             xfree(c->addinfo);
1118             c->addinfo = 0;
1119             xfree(c->message);
1120             c->message = 0;
1121             xfree(c->id);
1122             xfree(c->sort_strategy);
1123             xfree(c->sort_criteria);
1124             assert(!c->connection);
1125             facet_limits_destroy(c->facet_limits);
1126
1127             client_destroy_xdoc(c);
1128             if (c->resultset)
1129             {
1130                 ZOOM_resultset_destroy(c->resultset);
1131             }
1132             yaz_mutex_destroy(&c->mutex);
1133             xfree(c);
1134             client_use(-1);
1135             return 1;
1136         }
1137     }
1138     return 0;
1139 }
1140
1141 void client_set_connection(struct client *cl, struct connection *con)
1142 {
1143     if (cl->resultset)
1144         ZOOM_resultset_release(cl->resultset);
1145     if (con)
1146     {
1147         assert(cl->connection == 0);
1148         cl->connection = con;
1149         client_incref(cl);
1150     }
1151     else
1152     {
1153         client_lock(cl);
1154         cl->connection = con;
1155         client_unlock(cl);
1156         client_destroy(cl);
1157     }
1158 }
1159
1160 void client_disconnect(struct client *cl)
1161 {
1162     if (cl->state != Client_Idle)
1163         client_set_state(cl, Client_Disconnected);
1164     client_set_connection(cl, 0);
1165 }
1166
1167 void client_mark_dead(struct client *cl)
1168 {
1169     if (cl->connection)
1170         connection_mark_dead(cl->connection);
1171 }
1172
1173 void client_stop(struct client *cl)
1174 {
1175     client_lock(cl);
1176     if (cl->state == Client_Working || cl->state == Client_Connecting)
1177     {
1178         yaz_log(YLOG_LOG, "client_stop: %s release", client_get_id(cl));
1179         if (cl->connection)
1180         {
1181             connection_release2(cl->connection);
1182             assert(cl->ref_count > 1);
1183             cl->ref_count--;
1184             cl->connection = 0;
1185         }
1186         cl->state = Client_Disconnected;
1187     }
1188     else
1189         yaz_log(YLOG_LOG, "client_stop: %s ignore", client_get_id(cl));
1190     client_unlock(cl);
1191 }
1192
1193 // Initialize CCL map for a target
1194 static CCL_bibset prepare_cclmap(struct client *cl, CCL_bibset base_bibset)
1195 {
1196     struct session_database *sdb = client_get_database(cl);
1197     struct setting *s;
1198     CCL_bibset res;
1199
1200     if (!sdb->settings)
1201         return 0;
1202     if (base_bibset)
1203         res = ccl_qual_dup(base_bibset);
1204     else
1205         res = ccl_qual_mk();
1206     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
1207     {
1208         const char *addinfo = 0;
1209         char *p = strchr(s->name + 3, ':');
1210         if (!p)
1211         {
1212             WRBUF w = wrbuf_alloc();
1213             wrbuf_printf(w, "Malformed cclmap. name=%s", s->name);
1214             yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1215             client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1216                                   ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1217                                   wrbuf_cstr(w));
1218             client_set_state_nb(cl, Client_Error);
1219             ccl_qual_rm(&res);
1220             wrbuf_destroy(w);
1221             return 0;
1222         }
1223         p++;
1224         if (ccl_qual_fitem2(res, s->value, p, &addinfo))
1225         {
1226             WRBUF w = wrbuf_alloc();
1227
1228             wrbuf_printf(w, "Malformed cclmap. name=%s: value=%s (%s)",
1229                          s->name, p, addinfo);
1230             yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1231             client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1232                                   ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1233                                   wrbuf_cstr(w));
1234             client_set_state_nb(cl, Client_Error);
1235             ccl_qual_rm(&res);
1236             wrbuf_destroy(w);
1237             return 0;
1238         }
1239     }
1240     return res;
1241 }
1242
1243 // returns a xmalloced CQL query corresponding to the pquery in client
1244 static char *make_cqlquery(struct client *cl, Z_RPNQuery *zquery)
1245 {
1246     cql_transform_t cqlt = cql_transform_create();
1247     char *r = 0;
1248     WRBUF wrb = wrbuf_alloc();
1249     int status;
1250
1251     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
1252     {
1253         yaz_log(YLOG_WARN, "Failed to generate CQL query, code=%d", status);
1254     }
1255     else
1256     {
1257         r = xstrdup(wrbuf_cstr(wrb));
1258     }
1259     wrbuf_destroy(wrb);
1260     cql_transform_close(cqlt);
1261     return r;
1262 }
1263
1264 // returns a xmalloced SOLR query corresponding to the pquery in client
1265 // TODO Could prob. be merge with the similar make_cqlquery
1266 static char *make_solrquery(struct client *cl, Z_RPNQuery *zquery)
1267 {
1268     solr_transform_t sqlt = solr_transform_create();
1269     char *r = 0;
1270     WRBUF wrb = wrbuf_alloc();
1271     int status;
1272
1273     if ((status = solr_transform_rpn2solr_wrbuf(sqlt, wrb, zquery)))
1274     {
1275         yaz_log(YLOG_WARN, "Failed to generate SOLR query, code=%d", status);
1276     }
1277     else
1278     {
1279         r = xstrdup(wrbuf_cstr(wrb));
1280     }
1281     wrbuf_destroy(wrb);
1282     solr_transform_close(sqlt);
1283     return r;
1284 }
1285
1286 const char *client_get_facet_limit_local(struct client *cl,
1287                                          struct session_database *sdb,
1288                                          int *l,
1289                                          NMEM nmem, int *num, char ***values)
1290 {
1291     const char *name = 0;
1292     const char *value = 0;
1293     for (; (name = facet_limits_get(cl->facet_limits, *l, &value)); (*l)++)
1294     {
1295         struct setting *s = 0;
1296
1297         for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1298         {
1299             const char *p = strchr(s->name + 3, ':');
1300             if (p && !strcmp(p + 1, name) && s->value)
1301             {
1302                 int j, cnum;
1303                 char **cvalues;
1304                 nmem_strsplit_escape2(nmem, ",", s->value, &cvalues,
1305                                       &cnum, 1, '\\', 1);
1306                 for (j = 0; j < cnum; j++)
1307                 {
1308                     const char *cvalue = cvalues[j];
1309                     while (*cvalue == ' ')
1310                         cvalue++;
1311                     if (!strncmp(cvalue, "local:", 6))
1312                     {
1313                         const char *cp = cvalue + 6;
1314                         while (*cp == ' ')
1315                             cp++;
1316                         nmem_strsplit_escape2(nmem, "|", value, values,
1317                                               num, 1, '\\', 1);
1318                         (*l)++;
1319                         return *cp ? cp : name;
1320                     }
1321                 }
1322             }
1323         }
1324     }
1325     return 0;
1326 }
1327
1328 static int apply_limit(struct session_database *sdb,
1329                        facet_limits_t facet_limits,
1330                        WRBUF w_pqf, CCL_bibset ccl_map,
1331                        struct conf_service *service)
1332 {
1333     int ret = 0;
1334     int i = 0;
1335     const char *name;
1336     const char *value;
1337
1338     NMEM nmem_tmp = nmem_create();
1339     for (i = 0; (name = facet_limits_get(facet_limits, i, &value)); i++)
1340     {
1341         struct setting *s = 0;
1342         nmem_reset(nmem_tmp);
1343         /* name="pz:limitmap:author" value="rpn:@attr 1=4|local:other" */
1344         for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1345         {
1346             const char *p = strchr(s->name + 3, ':');
1347             if (p && !strcmp(p + 1, name) && s->value)
1348             {
1349                 char **values = 0;
1350                 int i, num = 0;
1351                 char **cvalues = 0;
1352                 int j, cnum = 0;
1353                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1354                                       &num, 1, '\\', 1);
1355
1356                 nmem_strsplit_escape2(nmem_tmp, ",", s->value, &cvalues,
1357                                       &cnum, 1, '\\', 1);
1358
1359                 for (j = 0; ret == 0 && j < cnum; j++)
1360                 {
1361                     const char *cvalue = cvalues[j];
1362                     while (*cvalue == ' ')
1363                         cvalue++;
1364                     if (!strncmp(cvalue, "rpn:", 4))
1365                     {
1366                         const char *pqf = cvalue + 4;
1367                         wrbuf_puts(w_pqf, "@and ");
1368                         wrbuf_puts(w_pqf, pqf);
1369                         wrbuf_puts(w_pqf, " ");
1370                         for (i = 0; i < num; i++)
1371                         {
1372                             if (i < num - 1)
1373                                 wrbuf_puts(w_pqf, "@or ");
1374                             yaz_encode_pqf_term(w_pqf, values[i],
1375                                                 strlen(values[i]));
1376                         }
1377                     }
1378                     else if (!strncmp(cvalue, "ccl:", 4))
1379                     {
1380                         const char *ccl = cvalue + 4;
1381                         WRBUF ccl_w = wrbuf_alloc();
1382                         for (i = 0; i < num; i++)
1383                         {
1384                             int cerror, cpos;
1385                             struct ccl_rpn_node *cn;
1386                             wrbuf_rewind(ccl_w);
1387                             wrbuf_puts(ccl_w, ccl);
1388                             wrbuf_puts(ccl_w, "=\"");
1389                             wrbuf_puts(ccl_w, values[i]);
1390                             wrbuf_puts(ccl_w, "\"");
1391
1392                             cn = ccl_find_str(ccl_map, wrbuf_cstr(ccl_w),
1393                                               &cerror, &cpos);
1394                             if (cn)
1395                             {
1396                                 if (i == 0)
1397                                     wrbuf_printf(w_pqf, "@and ");
1398
1399                                 /* or multiple values.. could be bad if last
1400                                    CCL parse fails, but this is unlikely to
1401                                    happen */
1402                                 if (i < num - 1)
1403                                     wrbuf_printf(w_pqf, "@or ");
1404                                 ccl_pquery(w_pqf, cn);
1405                                 ccl_rpn_delete(cn);
1406                             }
1407                         }
1408                         wrbuf_destroy(ccl_w);
1409                     }
1410                     else if (!strncmp(cvalue, "local:", 6)) {
1411                         /* no operation */
1412                     }
1413                     else
1414                     {
1415                         yaz_log(YLOG_WARN, "Target %s: Bad limitmap '%s'",
1416                                 sdb->database->id, cvalue);
1417                         ret = -1; /* bad limitmap */
1418                     }
1419                 }
1420                 break;
1421             }
1422         }
1423         if (!s)
1424         {
1425             int i;
1426             for (i = 0; i < service->num_metadata; i++)
1427             {
1428                 struct conf_metadata *md = service->metadata + i;
1429                 if (!strcmp(md->name, name) && md->limitcluster)
1430                 {
1431                     yaz_log(YLOG_LOG, "limitcluster in use for %s",
1432                             md->name);
1433                     break;
1434                 }
1435             }
1436             if (i == service->num_metadata)
1437             {
1438                 yaz_log(YLOG_WARN, "Target %s: limit %s used, but no limitmap defined",
1439                         (sdb->database ? sdb->database->id : "<no id>"), name);
1440             }
1441         }
1442     }
1443     nmem_destroy(nmem_tmp);
1444     return ret;
1445 }
1446
1447 // Parse the query given the settings specific to this client
1448 // client variable same_search is set as below as well as returned:
1449 // 0 if query is OK but different from before
1450 // 1 if query is OK but same as before
1451 // return -1 on query error
1452 // return -2 on limit error
1453 int client_parse_query(struct client *cl, const char *query,
1454                        facet_limits_t facet_limits, const char **error_msg)
1455 {
1456     struct session *se = client_get_session(cl);
1457     struct conf_service *service = se->service;
1458     struct session_database *sdb = client_get_database(cl);
1459     struct ccl_rpn_node *cn;
1460     int cerror, cpos;
1461     ODR odr_out;
1462     CCL_bibset ccl_map = prepare_cclmap(cl, service->ccl_bibset);
1463     const char *sru = session_setting_oneval(sdb, PZ_SRU);
1464     const char *pqf_prefix = session_setting_oneval(sdb, PZ_PQF_PREFIX);
1465     const char *pqf_strftime = session_setting_oneval(sdb, PZ_PQF_STRFTIME);
1466     const char *query_syntax = session_setting_oneval(sdb, PZ_QUERY_SYNTAX);
1467     WRBUF w_ccl, w_pqf;
1468     int ret_value = 1;
1469     Z_RPNQuery *zquery;
1470
1471     if (!ccl_map)
1472         return -3;
1473
1474     w_ccl = wrbuf_alloc();
1475     wrbuf_puts(w_ccl, query);
1476
1477     w_pqf = wrbuf_alloc();
1478     if (*pqf_prefix)
1479     {
1480         wrbuf_puts(w_pqf, pqf_prefix);
1481         wrbuf_puts(w_pqf, " ");
1482     }
1483
1484     if (apply_limit(sdb, facet_limits, w_pqf, ccl_map, service))
1485     {
1486         ccl_qual_rm(&ccl_map);
1487         return -2;
1488     }
1489
1490     facet_limits_destroy(cl->facet_limits);
1491     cl->facet_limits = facet_limits_dup(facet_limits);
1492
1493     yaz_log(YLOG_LOG, "Client %s: CCL query: %s limit: %s",
1494             client_get_id(cl), wrbuf_cstr(w_ccl), wrbuf_cstr(w_pqf));
1495     cn = ccl_find_str(ccl_map, wrbuf_cstr(w_ccl), &cerror, &cpos);
1496     ccl_qual_rm(&ccl_map);
1497     if (!cn)
1498     {
1499         if (error_msg)
1500             *error_msg = ccl_err_msg(cerror);
1501         client_set_state(cl, Client_Error);
1502         session_log(se, YLOG_WARN, "Client %s: Failed to parse CCL query '%s'",
1503                     client_get_id(cl),
1504                     wrbuf_cstr(w_ccl));
1505         wrbuf_destroy(w_ccl);
1506         wrbuf_destroy(w_pqf);
1507         return -1;
1508     }
1509     wrbuf_destroy(w_ccl);
1510
1511     if (!pqf_strftime || !*pqf_strftime)
1512         ccl_pquery(w_pqf, cn);
1513     else
1514     {
1515         time_t cur_time = time(0);
1516         struct tm *tm =  localtime(&cur_time);
1517         char tmp_str[300];
1518         const char *cp = tmp_str;
1519
1520         /* see man strftime(3) for things .. In particular %% gets converted
1521          to %.. And That's our original query .. */
1522         strftime(tmp_str, sizeof(tmp_str)-1, pqf_strftime, tm);
1523         for (; *cp; cp++)
1524         {
1525             if (cp[0] == '%')
1526                 ccl_pquery(w_pqf, cn);
1527             else
1528                 wrbuf_putc(w_pqf, cp[0]);
1529         }
1530     }
1531
1532     /* Compares query and limit with old one. If different we need to research */
1533     if (!cl->pquery || strcmp(cl->pquery, wrbuf_cstr(w_pqf)))
1534     {
1535         if (cl->pquery)
1536             session_log(se, YLOG_LOG, "Client %s: "
1537                         "Re-search due query/limit change: %s to %s", 
1538                         client_get_id(cl), cl->pquery, wrbuf_cstr(w_pqf));
1539         xfree(cl->pquery);
1540         cl->pquery = xstrdup(wrbuf_cstr(w_pqf));
1541         // return value is no longer used.
1542         ret_value = 0;
1543         // Need to (re)search
1544         cl->same_search= 0;
1545     }
1546     wrbuf_destroy(w_pqf);
1547
1548     xfree(cl->cqlquery);
1549     cl->cqlquery = 0;
1550
1551     odr_out = odr_createmem(ODR_ENCODE);
1552     zquery = p_query_rpn(odr_out, cl->pquery);
1553     if (!zquery)
1554     {
1555
1556         session_log(se, YLOG_WARN, "Invalid PQF query for Client %s: %s",
1557                     client_get_id(cl), cl->pquery);
1558         ret_value = -1;
1559         *error_msg = "Invalid PQF after CCL to PQF conversion";
1560     }
1561     else
1562     {
1563         session_log(se, YLOG_LOG, "PQF for Client %s: %s",
1564                     client_get_id(cl), cl->pquery);
1565
1566         /* Support for PQF on SRU targets. */
1567         if (strcmp(query_syntax, "pqf") != 0 && *sru)
1568         {
1569             if (!strcmp(sru, "solr"))
1570                 cl->cqlquery = make_solrquery(cl, zquery);
1571             else
1572                 cl->cqlquery = make_cqlquery(cl, zquery);
1573             if (!cl->cqlquery)
1574             {
1575                 *error_msg = "Cannot convert PQF to Solr/CQL";
1576                 ret_value = -1;
1577             }
1578             else
1579                 session_log(se, YLOG_LOG, "Client %s native query: %s (%s)",
1580                             client_get_id(cl), cl->cqlquery, sru);
1581         }
1582     }
1583     odr_destroy(odr_out);
1584
1585     /* TODO FIX Not thread safe */
1586     if (!se->relevance)
1587     {
1588         // Initialize relevance structure with query terms
1589         se->relevance = relevance_create_ccl(se->service->charsets, cn,
1590                                              se->service->rank_cluster,
1591                                              se->service->rank_follow,
1592                                              se->service->rank_lead,
1593                                              se->service->rank_length);
1594     }
1595     ccl_rpn_delete(cn);
1596     return ret_value;
1597 }
1598
1599 int client_parse_sort(struct client *cl, struct reclist_sortparms *sp)
1600 {
1601     if (sp)
1602     {
1603         const char *sort_strategy_and_spec =
1604             get_strategy_plus_sort(cl, sp->name);
1605         int increasing = sp->increasing;
1606         if (!strcmp(sp->name, "relevance"))
1607             increasing = 1;
1608         if (sort_strategy_and_spec && strlen(sort_strategy_and_spec) < 40)
1609         {
1610             char strategy[50], *p;
1611             strcpy(strategy, sort_strategy_and_spec);
1612             p = strchr(strategy, ':');
1613             if (p)
1614             {
1615                 // Split the string in two
1616                 *p++ = 0;
1617                 while (*p == ' ')
1618                     p++;
1619                 if (increasing)
1620                     strcat(p, " <");
1621                 else
1622                     strcat(p, " >");
1623                 yaz_log(YLOG_LOG, "Client %s: "
1624                         "applying sorting %s %s", client_get_id(cl),
1625                         strategy, p);
1626                 if (!cl->sort_strategy || strcmp(cl->sort_strategy, strategy))
1627                     cl->same_search = 0;
1628                 if (!cl->sort_criteria || strcmp(cl->sort_criteria, p))
1629                     cl->same_search = 0;
1630                 if (cl->same_search == 0) {
1631                     xfree(cl->sort_strategy);
1632                     cl->sort_strategy = xstrdup(strategy);
1633                     xfree(cl->sort_criteria);
1634                     cl->sort_criteria = xstrdup(p);
1635                 }
1636             }
1637             else {
1638                 yaz_log(YLOG_LOG, "Client %s: "
1639                         "Invalid sort strategy and spec found %s",
1640                         client_get_id(cl), sort_strategy_and_spec);
1641                 xfree(cl->sort_strategy);
1642                 cl->sort_strategy  = 0;
1643                 xfree(cl->sort_criteria);
1644                 cl->sort_criteria = 0;
1645             }
1646         }
1647         else
1648         {
1649             yaz_log(YLOG_DEBUG, "Client %s: "
1650                     "No sort strategy and spec found.", client_get_id(cl));
1651             xfree(cl->sort_strategy);
1652             cl->sort_strategy  = 0;
1653             xfree(cl->sort_criteria);
1654             cl->sort_criteria = 0;
1655         }
1656
1657     }
1658     return !cl->same_search;
1659 }
1660
1661 void client_set_session(struct client *cl, struct session *se)
1662 {
1663     cl->session = se;
1664 }
1665
1666 int client_is_active(struct client *cl)
1667 {
1668     if (cl->connection && (cl->state == Client_Connecting ||
1669                            cl->state == Client_Working))
1670         return 1;
1671     return 0;
1672 }
1673
1674 int client_is_active_preferred(struct client *cl)
1675 {
1676     /* only count if this is a preferred target. */
1677     if (!cl->preferred)
1678         return 0;
1679     /* TODO No sure this the condition that Seb wants */
1680     if (cl->connection && (cl->state == Client_Connecting ||
1681                            cl->state == Client_Working))
1682         return 1;
1683     return 0;
1684 }
1685
1686 Odr_int client_get_hits(struct client *cl)
1687 {
1688     return cl->hits;
1689 }
1690
1691 Odr_int client_get_approximation(struct client *cl)
1692 {
1693     if (cl->record_offset > 0)
1694     {
1695         Odr_int approx = ((10 * cl->hits * (cl->record_offset - cl->filtered))
1696                           / cl->record_offset + 5) /10;
1697         yaz_log(YLOG_DEBUG, "%s: Approx: %lld * %d / %d = %lld ",
1698                 client_get_id(cl), cl->hits,
1699                 cl->record_offset - cl->filtered, cl->record_offset, approx);
1700         return approx;
1701     }
1702     return cl->hits;
1703 }
1704
1705 int client_get_num_records(struct client *cl, int *filtered, int *ingest,
1706                            int *failed)
1707 {
1708     if (filtered)
1709         *filtered = cl->filtered;
1710     if (ingest)
1711         *ingest = cl->ingest_failures;
1712     if (failed)
1713         *failed = cl->record_failures;
1714     return cl->record_offset;
1715 }
1716
1717 void client_set_diagnostic(struct client *cl, int diagnostic,
1718                            const char *message, const char *addinfo)
1719 {
1720     cl->diagnostic = diagnostic;
1721     xfree(cl->message);
1722     cl->message = xstrdup(message);
1723     xfree(cl->addinfo);
1724     cl->addinfo = 0;
1725     if (addinfo)
1726         cl->addinfo = xstrdup(addinfo);
1727 }
1728
1729 int client_get_diagnostic(struct client *cl, const char **message,
1730                           const char **addinfo)
1731 {
1732     if (message)
1733         *message = cl->message;
1734     if (addinfo)
1735         *addinfo = cl->addinfo;
1736     return cl->diagnostic;
1737 }
1738
1739 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf)
1740 {
1741     /* int idx; */
1742     struct suggestions *suggestions = cl->suggestions;
1743
1744     if (!suggestions) 
1745         return "";
1746     if (suggestions->passthrough)
1747     {
1748         yaz_log(YLOG_DEBUG, "Passthrough Suggestions: \n%s\n",
1749                 suggestions->passthrough);
1750         return suggestions->passthrough;
1751     }
1752     if (suggestions->num == 0)
1753         return "";
1754     /*
1755     for (idx = 0; idx < suggestions->num; idx++) {
1756         wrbuf_printf(wrbuf, "<suggest term=\"%s\"", suggestions->suggest[idx]);
1757         if (suggestions->misspelled[idx] && suggestions->misspelled[idx]) {
1758             wrbuf_puts(wrbuf, suggestions->misspelled[idx]);
1759             wrbuf_puts(wrbuf, "</suggest>\n");
1760         }
1761         else
1762             wrbuf_puts(wrbuf, "/>\n");
1763     }
1764     */
1765     return wrbuf_cstr(wrbuf);
1766 }
1767
1768
1769 void client_set_database(struct client *cl, struct session_database *db)
1770 {
1771     cl->database = db;
1772 }
1773
1774 const char *client_get_id(struct client *cl)
1775 {
1776     return cl->id;
1777 }
1778
1779 int client_get_maxrecs(struct client *cl)
1780 {
1781     return cl->maxrecs;
1782 }
1783
1784 void client_set_preferred(struct client *cl, int v)
1785 {
1786     cl->preferred = v;
1787 }
1788
1789
1790 struct suggestions* client_suggestions_create(const char* suggestions_string)
1791 {
1792     int i;
1793     NMEM nmem;
1794     struct suggestions *suggestions;
1795     if (suggestions_string == 0 || suggestions_string[0] == 0 )
1796         return 0;
1797     nmem = nmem_create();
1798     suggestions = nmem_malloc(nmem, sizeof(*suggestions));
1799     yaz_log(YLOG_DEBUG, "client target suggestions: %s.", suggestions_string);
1800
1801     suggestions->nmem = nmem;
1802     suggestions->num = 0;
1803     suggestions->misspelled = 0;
1804     suggestions->suggest = 0;
1805     suggestions->passthrough = nmem_strdup_null(nmem, suggestions_string);
1806
1807     if (suggestions_string)
1808         nmem_strsplit_escape2(suggestions->nmem, "\n", suggestions_string, &suggestions->suggest,
1809                               &suggestions->num, 1, '\\', 0);
1810     /* Set up misspelled array */
1811     suggestions->misspelled = (char **)
1812         nmem_malloc(nmem, suggestions->num * sizeof(*suggestions->misspelled));
1813     /* replace = with \0 .. for each item */
1814     for (i = 0; i < suggestions->num; i++)
1815     {
1816         char *cp = strchr(suggestions->suggest[i], '=');
1817         if (cp) {
1818             *cp = '\0';
1819             suggestions->misspelled[i] = cp+1;
1820         }
1821     }
1822     return suggestions;
1823 }
1824
1825 static void client_suggestions_destroy(struct client *cl)
1826 {
1827     NMEM nmem = cl->suggestions->nmem;
1828     cl->suggestions = 0;
1829     nmem_destroy(nmem);
1830 }
1831
1832 /*
1833  * Local variables:
1834  * c-basic-offset: 4
1835  * c-file-style: "Stroustrup"
1836  * indent-tabs-mode: nil
1837  * End:
1838  * vim: shiftwidth=4 tabstop=8 expandtab
1839  */
1840