Merge branch 'master' into bytarget_block
[pazpar2-moved-to-github.git] / src / client.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2011 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 #include <signal.h>
37 #include <assert.h>
38
39 #include <yaz/marcdisp.h>
40 #include <yaz/comstack.h>
41 #include <yaz/tcpip.h>
42 #include <yaz/proto.h>
43 #include <yaz/readconf.h>
44 #include <yaz/pquery.h>
45 #include <yaz/otherinfo.h>
46 #include <yaz/yaz-util.h>
47 #include <yaz/nmem.h>
48 #include <yaz/query-charset.h>
49 #include <yaz/querytowrbuf.h>
50 #include <yaz/oid_db.h>
51 #include <yaz/diagbib1.h>
52 #include <yaz/snprintf.h>
53 #include <yaz/rpn2cql.h>
54 #include <yaz/rpn2solr.h>
55
56 #define USE_TIMING 0
57 #if USE_TIMING
58 #include <yaz/timing.h>
59 #endif
60
61 #include "ppmutex.h"
62 #include "session.h"
63 #include "parameters.h"
64 #include "client.h"
65 #include "connection.h"
66 #include "settings.h"
67 #include "relevance.h"
68 #include "incref.h"
69
70 static YAZ_MUTEX g_mutex = 0;
71 static int no_clients = 0;
72 static int no_clients_total = 0;
73
74 static int client_use(int delta)
75 {
76     int clients;
77     if (!g_mutex)
78         yaz_mutex_create(&g_mutex);
79     yaz_mutex_enter(g_mutex);
80     no_clients += delta;
81     if (delta > 0)
82         no_clients_total += delta;
83     clients = no_clients;
84     yaz_mutex_leave(g_mutex);
85     yaz_log(YLOG_DEBUG, "%s clients=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), clients);
86     return clients;
87 }
88
89 int  clients_count(void) {
90     return client_use(0);
91 }
92
93 int  clients_count_total(void) {
94     int total = 0;
95     if (!g_mutex)
96         return 0;
97     yaz_mutex_enter(g_mutex);
98     total = no_clients_total;
99     yaz_mutex_leave(g_mutex);
100     return total;
101 }
102
103
104 /** \brief Represents client state for a connection to one search target */
105 struct client {
106     struct session_database *database;
107     struct connection *connection;
108     struct session *session;
109     char *pquery; // Current search
110     char *cqlquery; // used for SRU targets only
111     Odr_int hits;
112     int record_offset;
113     int maxrecs;
114     int startrecs;
115     int diagnostic;
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 };
125
126 struct suggestions {
127     NMEM nmem;
128     int num;
129     char **misspelled;
130     char **suggest;
131     char *passthrough;
132 };
133
134 struct show_raw {
135     int active; // whether this request has been sent to the server
136     int position;
137     int binary;
138     char *syntax;
139     char *esn;
140     void (*error_handler)(void *data, const char *addinfo);
141     void (*record_handler)(void *data, const char *buf, size_t sz);
142     void *data;
143     struct show_raw *next;
144 };
145
146 static const char *client_states[] = {
147     "Client_Connecting",
148     "Client_Idle",
149     "Client_Working",
150     "Client_Error",
151     "Client_Failed",
152     "Client_Disconnected"
153 };
154
155 const char *client_get_state_str(struct client *cl)
156 {
157     return client_states[cl->state];
158 }
159
160 enum client_state client_get_state(struct client *cl)
161 {
162     return cl->state;
163 }
164
165 void client_set_state_nb(struct client *cl, enum client_state st)
166 {
167     cl->state = st;
168 }
169
170 void client_set_state(struct client *cl, enum client_state st)
171 {
172     int was_active = 0;
173     if (client_is_active(cl))
174         was_active = 1;
175     cl->state = st;
176     /* If client is going from being active to inactive and all clients
177        are now idle we fire a watch for the session . The assumption is
178        that session is not mutex locked if client is already active */
179     if (was_active && !client_is_active(cl) && cl->session)
180     {
181
182         int no_active = session_active_clients(cl->session);
183         yaz_log(YLOG_DEBUG, "%s: releasing watches on zero active: %d",
184                 client_get_id(cl), no_active);
185         if (no_active == 0) {
186             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
187             session_alert_watch(cl->session, SESSION_WATCH_BYTARGET);
188             session_alert_watch(cl->session, SESSION_WATCH_TERMLIST);
189             session_alert_watch(cl->session, SESSION_WATCH_SHOW_PREF);
190         }
191     }
192 }
193
194 static void client_show_raw_error(struct client *cl, const char *addinfo);
195
196 struct connection *client_get_connection(struct client *cl)
197 {
198     return cl->connection;
199 }
200
201 struct session_database *client_get_database(struct client *cl)
202 {
203     return cl->database;
204 }
205
206 struct session *client_get_session(struct client *cl)
207 {
208     return cl->session;
209 }
210
211 const char *client_get_pquery(struct client *cl)
212 {
213     return cl->pquery;
214 }
215
216 static void client_send_raw_present(struct client *cl);
217 static int nativesyntax_to_type(struct session_database *sdb, char *type,
218                                 ZOOM_record rec);
219
220 static void client_show_immediate(
221     ZOOM_resultset resultset, struct session_database *sdb, int position,
222     void *data,
223     void (*error_handler)(void *data, const char *addinfo),
224     void (*record_handler)(void *data, const char *buf, size_t sz),
225     int binary)
226 {
227     ZOOM_record rec = 0;
228     char type[80];
229     const char *buf;
230     int len;
231
232     if (!resultset)
233     {
234         error_handler(data, "no resultset");
235         return;
236     }
237     rec = ZOOM_resultset_record(resultset, position-1);
238     if (!rec)
239     {
240         error_handler(data, "no record");
241         return;
242     }
243     if (binary)
244         strcpy(type, "raw");
245     else
246         nativesyntax_to_type(sdb, type, rec);
247     buf = ZOOM_record_get(rec, type, &len);
248     if (!buf)
249     {
250         error_handler(data, "no record");
251         return;
252     }
253     record_handler(data, buf, len);
254 }
255
256
257 int client_show_raw_begin(struct client *cl, int position,
258                           const char *syntax, const char *esn,
259                           void *data,
260                           void (*error_handler)(void *data, const char *addinfo),
261                           void (*record_handler)(void *data, const char *buf,
262                                                  size_t sz),
263                           int binary)
264 {
265     if (syntax == 0 && esn == 0)
266         client_show_immediate(cl->resultset, client_get_database(cl),
267                               position, data,
268                               error_handler, record_handler,
269                               binary);
270     else
271     {
272         struct show_raw *rr, **rrp;
273
274         if (!cl->connection)
275             return -1;
276     
277
278         rr = xmalloc(sizeof(*rr));
279         rr->position = position;
280         rr->active = 0;
281         rr->data = data;
282         rr->error_handler = error_handler;
283         rr->record_handler = record_handler;
284         rr->binary = binary;
285         if (syntax)
286             rr->syntax = xstrdup(syntax);
287         else
288             rr->syntax = 0;
289         if (esn)
290             rr->esn = xstrdup(esn);
291         else
292             rr->esn = 0;
293         rr->next = 0;
294         
295         for (rrp = &cl->show_raw; *rrp; rrp = &(*rrp)->next)
296             ;
297         *rrp = rr;
298         
299         if (cl->state == Client_Failed)
300         {
301             client_show_raw_error(cl, "client failed");
302         }
303         else if (cl->state == Client_Disconnected)
304         {
305             client_show_raw_error(cl, "client disconnected");
306         }
307         else
308         {
309             client_send_raw_present(cl);
310         }
311     }
312     return 0;
313 }
314
315 static void client_show_raw_delete(struct show_raw *r)
316 {
317     xfree(r->syntax);
318     xfree(r->esn);
319     xfree(r);
320 }
321
322 void client_show_raw_remove(struct client *cl, void *data)
323 {
324     struct show_raw *rr = data;
325     struct show_raw **rrp = &cl->show_raw;
326     while (*rrp != rr)
327         rrp = &(*rrp)->next;
328     if (*rrp)
329     {
330         *rrp = rr->next;
331         client_show_raw_delete(rr);
332     }
333 }
334
335 void client_show_raw_dequeue(struct client *cl)
336 {
337     struct show_raw *rr = cl->show_raw;
338
339     cl->show_raw = rr->next;
340     client_show_raw_delete(rr);
341 }
342
343 static void client_show_raw_error(struct client *cl, const char *addinfo)
344 {
345     while (cl->show_raw)
346     {
347         cl->show_raw->error_handler(cl->show_raw->data, addinfo);
348         client_show_raw_dequeue(cl);
349     }
350 }
351
352 static void client_send_raw_present(struct client *cl)
353 {
354     struct session_database *sdb = client_get_database(cl);
355     struct connection *co = client_get_connection(cl);
356     ZOOM_resultset set = cl->resultset;
357
358     int offset = cl->show_raw->position;
359     const char *syntax = 0;
360     const char *elements = 0;
361
362     assert(cl->show_raw);
363     assert(set);
364
365     yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
366             client_get_id(cl), 1, offset);
367
368     if (cl->show_raw->syntax)
369         syntax = cl->show_raw->syntax;
370     else
371         syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
372     ZOOM_resultset_option_set(set, "preferredRecordSyntax", syntax);
373
374     if (cl->show_raw->esn)
375         elements = cl->show_raw->esn;
376     else
377         elements = session_setting_oneval(sdb, PZ_ELEMENTS);
378     if (elements && *elements)
379         ZOOM_resultset_option_set(set, "elementSetName", elements);
380
381     ZOOM_resultset_records(set, 0, offset-1, 1);
382     cl->show_raw->active = 1;
383
384     connection_continue(co);
385 }
386
387 static int nativesyntax_to_type(struct session_database *sdb, char *type,
388                                 ZOOM_record rec)
389 {
390     const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
391
392     if (s && *s)
393     {
394         if (!strncmp(s, "iso2709", 7))
395         {
396             const char *cp = strchr(s, ';');
397             yaz_snprintf(type, 80, "xml; charset=%s", cp ? cp+1 : "marc-8s");
398         }
399         else if (!strncmp(s, "xml", 3))
400         {
401             strcpy(type, "xml");
402         }
403         else if (!strncmp(s, "txml", 4))
404         {
405             const char *cp = strchr(s, ';');
406             yaz_snprintf(type, 80, "txml; charset=%s", cp ? cp+1 : "marc-8s");
407         }
408         else
409             return -1;
410         return 0;
411     }
412     else  /* attempt to deduce structure */
413     {
414         const char *syntax = ZOOM_record_get(rec, "syntax", NULL);
415         if (syntax)
416         {
417             if (!strcmp(syntax, "XML"))
418             {
419                 strcpy(type, "xml");
420                 return 0;
421             }
422             else if (!strcmp(syntax, "USmarc") || !strcmp(syntax, "MARC21"))
423             {
424                 strcpy(type, "xml; charset=marc8-s");
425                 return 0;
426             }
427             else return -1;
428         }
429         else return -1;
430     }
431 }
432
433 /**
434  * TODO Consider thread safety!!!
435  *
436  */
437 void client_report_facets(struct client *cl, ZOOM_resultset rs)
438 {
439     struct session_database *sdb = client_get_database(cl);
440     ZOOM_facet_field *facets = ZOOM_resultset_facets(rs);
441
442     if (sdb && facets)
443     {
444         struct session *se = client_get_session(cl);
445         int facet_num = ZOOM_resultset_facets_size(rs);
446         struct setting *s;
447
448         for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
449         {
450             const char *p = strchr(s->name + 3, ':');
451             if (p && p[1] && s->value && s->value[0])
452             {
453                 int facet_idx;
454                 p++; /* p now holds logical facet name */
455                 for (facet_idx = 0; facet_idx < facet_num; facet_idx++)
456                 {
457                     const char *native_name =
458                         ZOOM_facet_field_name(facets[facet_idx]);
459                     if (native_name && !strcmp(s->value, native_name))
460                     {
461                         size_t term_idx;
462                         size_t term_num =
463                             ZOOM_facet_field_term_count(facets[facet_idx]);
464                         for (term_idx = 0; term_idx < term_num; term_idx++ )
465                         {
466                             int freq;
467                             const char *term =
468                                 ZOOM_facet_field_get_term(facets[facet_idx],
469                                                           term_idx, &freq);
470                             if (term)
471                                 add_facet(se, p, term, freq);
472                         }
473                         break;
474                     }
475                 }
476             }
477         }
478     }
479 }
480
481 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
482 {
483     const char *buf;
484     int len;
485     char type[80];
486
487     if (cl->show_raw->binary)
488         strcpy(type, "raw");
489     else
490     {
491         struct session_database *sdb = client_get_database(cl);
492         nativesyntax_to_type(sdb, type, rec);
493     }
494
495     buf = ZOOM_record_get(rec, type, &len);
496     cl->show_raw->record_handler(cl->show_raw->data,  buf, len);
497     client_show_raw_dequeue(cl);
498 }
499
500 void client_check_preferred_watch(struct client *cl)
501 {
502     struct session *se = cl->session;
503     yaz_log(YLOG_DEBUG, "client_check_preferred_watch: %s ", client_get_id(cl));
504     if (se)
505     {
506         client_unlock(cl);
507         /* TODO possible threading issue. Session can have been destroyed */
508         if (session_is_preferred_clients_ready(se)) {
509             session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
510         }
511         else
512             yaz_log(YLOG_DEBUG, "client_check_preferred_watch: Still locked on preferred targets.");
513
514         client_lock(cl);
515     }
516     else
517         yaz_log(YLOG_WARN, "client_check_preferred_watch: %s. No session!", client_get_id(cl));
518
519 }
520
521 struct suggestions* client_suggestions_create(const char* suggestions_string);
522 static void client_suggestions_destroy(struct client *cl);
523
524 void client_search_response(struct client *cl)
525 {
526     struct connection *co = cl->connection;
527     ZOOM_connection link = connection_get_link(co);
528     ZOOM_resultset resultset = cl->resultset;
529
530     const char *error, *addinfo = 0;
531     
532     if (ZOOM_connection_error(link, &error, &addinfo))
533     {
534         cl->hits = 0;
535         client_set_state(cl, Client_Error);
536         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
537                 error, addinfo, client_get_id(cl));
538     }
539     else
540     {
541         yaz_log(YLOG_DEBUG, "client_search_response: hits "
542                 ODR_INT_PRINTF, cl->hits);
543         client_report_facets(cl, resultset);
544         cl->record_offset = cl->startrecs;
545         cl->hits = ZOOM_resultset_size(resultset);
546         if (cl->suggestions)
547             client_suggestions_destroy(cl);
548         cl->suggestions = client_suggestions_create(ZOOM_resultset_option_get(resultset, "suggestions"));
549     }
550 }
551
552 void client_got_records(struct client *cl)
553 {
554     struct session *se = cl->session;
555     if (se)
556     {
557         client_unlock(cl);
558         session_alert_watch(se, SESSION_WATCH_SHOW);
559         session_alert_watch(se, SESSION_WATCH_BYTARGET);
560         session_alert_watch(se, SESSION_WATCH_TERMLIST);
561         session_alert_watch(se, SESSION_WATCH_RECORD);
562         client_lock(cl);
563     }
564 }
565
566 void client_record_response(struct client *cl)
567 {
568     struct connection *co = cl->connection;
569     ZOOM_connection link = connection_get_link(co);
570     ZOOM_resultset resultset = cl->resultset;
571     const char *error, *addinfo;
572
573     if (ZOOM_connection_error(link, &error, &addinfo))
574     {
575         client_set_state(cl, Client_Error);
576         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
577             error, addinfo, client_get_id(cl));
578     }
579     else
580     {
581         ZOOM_record rec = 0;
582         const char *msg, *addinfo;
583         
584         if (cl->show_raw && cl->show_raw->active)
585         {
586             if ((rec = ZOOM_resultset_record(resultset,
587                                              cl->show_raw->position-1)))
588             {
589                 cl->show_raw->active = 0;
590                 ingest_raw_record(cl, rec);
591             }
592             else
593             {
594                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
595                         cl->show_raw->position-1);
596             }
597         }
598         else
599         {
600             int offset = cl->record_offset;
601             if ((rec = ZOOM_resultset_record(resultset, offset)))
602             {
603                 cl->record_offset++;
604                 if (cl->session == 0)
605                     ;
606                 else if (ZOOM_record_error(rec, &msg, &addinfo, 0))
607                 {
608                     yaz_log(YLOG_WARN, "Record error %s (%s): %s (rec #%d)",
609                             msg, addinfo, client_get_id(cl),
610                             cl->record_offset);
611                 }
612                 else
613                 {
614                     struct session_database *sdb = client_get_database(cl);
615                     NMEM nmem = nmem_create();
616                     const char *xmlrec;
617                     char type[80];
618
619                     if (nativesyntax_to_type(sdb, type, rec))
620                         yaz_log(YLOG_WARN, "Failed to determine record type");
621                     xmlrec = ZOOM_record_get(rec, type, NULL);
622                     if (!xmlrec)
623                         yaz_log(YLOG_WARN, "ZOOM_record_get failed from %s",
624                                 client_get_id(cl));
625                     else
626                     {
627                         /* OK = 0, -1 = failure, -2 = Filtered */
628                         if (ingest_record(cl, xmlrec, cl->record_offset, nmem) == -1)
629                             yaz_log(YLOG_WARN, "Failed to ingest from %s", client_get_id(cl));
630                     }
631                     nmem_destroy(nmem);
632                 }
633             }
634             else
635             {
636                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
637                         offset);
638             }
639         }
640     }
641 }
642
643 static void client_set_facets_request(struct client *cl, ZOOM_connection link)
644 {
645     struct session_database *sdb = client_get_database(cl);
646
647     WRBUF w = wrbuf_alloc();
648     
649     struct setting *s;
650
651     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
652     {
653         const char *p = strchr(s->name + 3, ':');
654         if (!p)
655         {
656             yaz_log(YLOG_WARN, "Malformed facetmap name: %s", s->name);
657         }
658         else if (s->value && s->value[0])
659         {
660             wrbuf_puts(w, "@attr 1=");
661             yaz_encode_pqf_term(w, s->value, strlen(s->value));
662             if (s->next)
663                 wrbuf_puts(w, ",");
664         }
665     }
666     yaz_log(YLOG_LOG, "using facets str: %s", wrbuf_cstr(w));
667     ZOOM_connection_option_set(link, "facets",
668                                wrbuf_len(w) ? wrbuf_cstr(w) : 0);
669     wrbuf_destroy(w);
670 }
671
672 int client_has_facet(struct client *cl, const char *name)
673 {
674     struct session_database *sdb = client_get_database(cl);
675     struct setting *s;
676
677     for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
678     {
679         const char *p = strchr(s->name + 3, ':');
680         if (p && !strcmp(name, p + 1))
681             return 1;
682     }
683     return 0;
684 }
685
686 void client_start_search(struct client *cl, const char *sort_strategy_and_spec,
687                          int increasing)
688 {
689     struct session_database *sdb = client_get_database(cl);
690     struct connection *co = client_get_connection(cl);
691     ZOOM_connection link = connection_get_link(co);
692     ZOOM_resultset rs;
693     const char *opt_piggyback   = session_setting_oneval(sdb, PZ_PIGGYBACK);
694     const char *opt_queryenc    = session_setting_oneval(sdb, PZ_QUERYENCODING);
695     const char *opt_elements    = session_setting_oneval(sdb, PZ_ELEMENTS);
696     const char *opt_requestsyn  = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
697     const char *opt_maxrecs     = session_setting_oneval(sdb, PZ_MAXRECS);
698     const char *opt_sru         = session_setting_oneval(sdb, PZ_SRU);
699     const char *opt_sort        = session_setting_oneval(sdb, PZ_SORT);
700     const char *opt_preferred   = session_setting_oneval(sdb, PZ_PREFERRED);
701     const char *extra_args      = session_setting_oneval(sdb, PZ_EXTRA_ARGS);
702     char maxrecs_str[24], startrecs_str[24];
703     ZOOM_query q;
704
705     assert(link);
706
707     cl->record_offset = 0;
708     cl->diagnostic = 0;
709
710     if (extra_args && *extra_args)
711         ZOOM_connection_option_set(link, "extraArgs", extra_args);
712
713     if (opt_preferred) {
714         cl->preferred = atoi(opt_preferred);
715         if (cl->preferred)
716             yaz_log(YLOG_LOG, "Target %s has preferred status: %d",
717                     client_get_id(cl), cl->preferred);
718     }
719     client_set_state(cl, Client_Working);
720
721     if (*opt_piggyback)
722         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
723     else
724         ZOOM_connection_option_set(link, "piggyback", "1");
725     if (*opt_queryenc)
726         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
727     if (*opt_sru && *opt_elements)
728         ZOOM_connection_option_set(link, "schema", opt_elements);
729     else if (*opt_elements)
730         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
731     if (*opt_requestsyn)
732         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
733
734     if (opt_maxrecs && *opt_maxrecs)
735     {
736         cl->maxrecs = atoi(opt_maxrecs);
737     }
738
739     /* convert back to string representation used in ZOOM API */
740     sprintf(maxrecs_str, "%d", cl->maxrecs);
741     ZOOM_connection_option_set(link, "count", maxrecs_str);
742
743     if (cl->maxrecs > 20)
744         ZOOM_connection_option_set(link, "presentChunk", "20");
745     else
746         ZOOM_connection_option_set(link, "presentChunk", maxrecs_str);
747
748     sprintf(startrecs_str, "%d", cl->startrecs);
749     ZOOM_connection_option_set(link, "start", startrecs_str);
750
751     /* TODO Verify does it break something for CQL targets(non-SOLR) ? */
752     /* facets definition is in PQF */
753     client_set_facets_request(cl, link);
754
755     q = ZOOM_query_create();
756     if (cl->cqlquery)
757     {
758         yaz_log(YLOG_LOG, "Search %s CQL: %s", client_get_id(cl),
759                 cl->cqlquery);
760         ZOOM_query_cql(q, cl->cqlquery);
761         if (*opt_sort)
762             ZOOM_query_sortby(q, opt_sort);
763     }
764     else
765     {
766         yaz_log(YLOG_LOG, "Search %s PQF: %s", client_get_id(cl), cl->pquery);
767         
768         ZOOM_query_prefix(q, cl->pquery);
769     }
770     if (sort_strategy_and_spec &&
771         strlen(sort_strategy_and_spec) < 40 /* spec below */)
772     {
773         char spec[50], *p;
774         strcpy(spec, sort_strategy_and_spec);
775         p = strchr(spec, ':');
776         if (p)
777         {
778             *p++ = '\0'; /* cut the string in two */
779             while (*p == ' ')
780                 p++;
781             if (increasing)
782                 strcat(p, " <");
783             else
784                 strcat(p, " >");
785             yaz_log(YLOG_LOG, "applying %s %s", spec, p);
786             ZOOM_query_sortby2(q, spec, p);
787         }
788     }
789     rs = ZOOM_connection_search(link, q);
790     ZOOM_query_destroy(q);
791     ZOOM_resultset_destroy(cl->resultset);
792     cl->resultset = rs;
793     connection_continue(co);
794 }
795
796 struct client *client_create(const char *id)
797 {
798     struct client *cl = xmalloc(sizeof(*cl));
799     cl->maxrecs = 100;
800     cl->startrecs = 0;
801     cl->pquery = 0;
802     cl->cqlquery = 0;
803     cl->database = 0;
804     cl->connection = 0;
805     cl->session = 0;
806     cl->hits = 0;
807     cl->record_offset = 0;
808     cl->diagnostic = 0;
809     cl->state = Client_Disconnected;
810     cl->show_raw = 0;
811     cl->resultset = 0;
812     cl->suggestions = 0;
813     cl->mutex = 0;
814     pazpar2_mutex_create(&cl->mutex, "client");
815     cl->preferred = 0;
816     cl->ref_count = 1;
817     assert(id);
818     cl->id = xstrdup(id);
819     client_use(1);
820     
821     return cl;
822 }
823
824 void client_lock(struct client *c)
825 {
826     yaz_mutex_enter(c->mutex);
827 }
828
829 void client_unlock(struct client *c)
830 {
831     yaz_mutex_leave(c->mutex);
832 }
833
834 void client_incref(struct client *c)
835 {
836     pazpar2_incref(&c->ref_count, c->mutex);
837     yaz_log(YLOG_DEBUG, "client_incref c=%p %s cnt=%d",
838             c, client_get_id(c), c->ref_count);
839 }
840
841 int client_destroy(struct client *c)
842 {
843     if (c)
844     {
845         yaz_log(YLOG_DEBUG, "client_destroy c=%p %s cnt=%d",
846                 c, client_get_id(c), c->ref_count);
847         if (!pazpar2_decref(&c->ref_count, c->mutex))
848         {
849             xfree(c->pquery);
850             c->pquery = 0;
851             xfree(c->cqlquery);
852             c->cqlquery = 0;
853             xfree(c->id);
854             assert(!c->connection);
855
856             if (c->resultset)
857             {
858                 ZOOM_resultset_destroy(c->resultset);
859             }
860             yaz_mutex_destroy(&c->mutex);
861             xfree(c);
862             client_use(-1);
863             return 1;
864         }
865     }
866     return 0;
867 }
868
869 void client_set_connection(struct client *cl, struct connection *con)
870 {
871     if (cl->resultset)
872         ZOOM_resultset_release(cl->resultset);
873     if (con)
874     {
875         assert(cl->connection == 0);
876         cl->connection = con;
877         client_incref(cl);
878     }
879     else
880     {
881         cl->connection = con;
882         client_destroy(cl);
883     }
884 }
885
886 void client_disconnect(struct client *cl)
887 {
888     if (cl->state != Client_Idle)
889         client_set_state(cl, Client_Disconnected);
890     client_set_connection(cl, 0);
891 }
892
893
894 // Initialize CCL map for a target
895 static CCL_bibset prepare_cclmap(struct client *cl)
896 {
897     struct session_database *sdb = client_get_database(cl);
898     struct setting *s;
899     CCL_bibset res;
900
901     if (!sdb->settings)
902         return 0;
903     res = ccl_qual_mk();
904     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
905     {
906         char *p = strchr(s->name + 3, ':');
907         if (!p)
908         {
909             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
910             ccl_qual_rm(&res);
911             return 0;
912         }
913         p++;
914         ccl_qual_fitem(res, s->value, p);
915     }
916     return res;
917 }
918
919 // returns a xmalloced CQL query corresponding to the pquery in client
920 static char *make_cqlquery(struct client *cl)
921 {
922     cql_transform_t cqlt = cql_transform_create();
923     Z_RPNQuery *zquery;
924     char *r;
925     WRBUF wrb = wrbuf_alloc();
926     int status;
927     ODR odr_out = odr_createmem(ODR_ENCODE);
928
929     zquery = p_query_rpn(odr_out, cl->pquery);
930     yaz_log(YLOG_LOG, "PQF: %s", cl->pquery);
931     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
932     {
933         yaz_log(YLOG_WARN, "Failed to generate CQL query, code=%d", status);
934         r = 0;
935     }
936     else
937     {
938         r = xstrdup(wrbuf_cstr(wrb));
939     }     
940     wrbuf_destroy(wrb);
941     odr_destroy(odr_out);
942     cql_transform_close(cqlt);
943     return r;
944 }
945
946 // returns a xmalloced SOLR query corresponding to the pquery in client
947 // TODO Could prob. be merge with the similar make_cqlquery
948 static char *make_solrquery(struct client *cl)
949 {
950     solr_transform_t sqlt = solr_transform_create();
951     Z_RPNQuery *zquery;
952     char *r;
953     WRBUF wrb = wrbuf_alloc();
954     int status;
955     ODR odr_out = odr_createmem(ODR_ENCODE);
956
957     zquery = p_query_rpn(odr_out, cl->pquery);
958     if (zquery == 0) {
959         yaz_log(YLOG_WARN, "Failed to generate RPN from PQF: %s", cl->pquery);
960         return 0;
961     }
962     yaz_log(YLOG_LOG, "PQF: %s", cl->pquery);
963     if ((status = solr_transform_rpn2solr_wrbuf(sqlt, wrb, zquery)))
964     {
965         yaz_log(YLOG_WARN, "Failed to generate SOLR query from PQF %s, code=%d", cl->pquery, status);
966         r = 0;
967     }
968     else
969     {
970         r = xstrdup(wrbuf_cstr(wrb));
971     }
972     wrbuf_destroy(wrb);
973     odr_destroy(odr_out);
974     solr_transform_close(sqlt);
975     return r;
976 }
977
978 static void apply_limit(struct session_database *sdb,
979                         facet_limits_t facet_limits,
980                         WRBUF w_pqf, WRBUF w_ccl)
981 {
982     int i = 0;
983     const char *name;
984     const char *value;
985     NMEM nmem_tmp = nmem_create();
986     for (i = 0; (name = facet_limits_get(facet_limits, i, &value)); i++)
987     {
988         struct setting *s = 0;
989         
990         for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
991         {
992             const char *p = strchr(s->name + 3, ':');
993             if (p && !strcmp(p + 1, name) && s->value)
994             {
995                 char **values = 0;
996                 int i, num = 0;
997                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
998                                       &num, 1, '\\', 1);
999
1000                 if (!strncmp(s->value, "rpn:", 4))
1001                 {
1002                     const char *pqf = s->value + 4;
1003
1004                     wrbuf_puts(w_pqf, "@and ");
1005                     wrbuf_puts(w_pqf, pqf);
1006                     wrbuf_puts(w_pqf, " ");
1007                     for (i = 0; i < num; i++)
1008                     {
1009                         if (i < num - 1)
1010                             wrbuf_puts(w_pqf, "@or ");
1011                         yaz_encode_pqf_term(w_pqf, values[i],
1012                                             strlen(values[i]));
1013                     }
1014                 }
1015                 else if (!strncmp(s->value, "ccl:", 4))
1016                 {
1017                     const char *ccl = s->value + 4;
1018
1019                     wrbuf_puts(w_ccl, " and (");
1020
1021                     for (i = 0; i < num; i++)
1022                     {
1023                         if (i)
1024                             wrbuf_puts(w_ccl, " or ");
1025                         wrbuf_puts(w_ccl, ccl);
1026                         wrbuf_puts(w_ccl, "=\"");
1027                         wrbuf_puts(w_ccl, values[i]);
1028                         wrbuf_puts(w_ccl, "\"");
1029                     }
1030                     wrbuf_puts(w_ccl, ")");
1031
1032                 }
1033                 break;
1034             }
1035         }
1036         nmem_reset(nmem_tmp);
1037         if (!s)
1038         {
1039             yaz_log(YLOG_WARN, "Target %s: limit %s used, but no limitmap defined",
1040                     (sdb->database ? sdb->database->id : "<no id>"), name);
1041         }
1042     }
1043     nmem_destroy(nmem_tmp);
1044 }
1045                         
1046 // Parse the query given the settings specific to this client
1047 int client_parse_query(struct client *cl, const char *query,
1048                        facet_limits_t facet_limits)
1049 {
1050     struct session *se = client_get_session(cl);
1051     struct session_database *sdb = client_get_database(cl);
1052     struct ccl_rpn_node *cn;
1053     int cerror, cpos;
1054     CCL_bibset ccl_map = prepare_cclmap(cl);
1055     const char *sru = session_setting_oneval(sdb, PZ_SRU);
1056     const char *pqf_prefix = session_setting_oneval(sdb, PZ_PQF_PREFIX);
1057     const char *pqf_strftime = session_setting_oneval(sdb, PZ_PQF_STRFTIME);
1058     const char *query_syntax = session_setting_oneval(sdb, PZ_QUERY_SYNTAX);
1059     WRBUF w_ccl, w_pqf;
1060     if (!ccl_map)
1061         return -1;
1062
1063     cl->hits = -1;
1064     w_ccl = wrbuf_alloc();
1065     wrbuf_puts(w_ccl, query);
1066
1067     w_pqf = wrbuf_alloc();
1068     if (*pqf_prefix)
1069     {
1070         wrbuf_puts(w_pqf, pqf_prefix);
1071         wrbuf_puts(w_pqf, " ");
1072     }
1073
1074     apply_limit(sdb, facet_limits, w_pqf, w_ccl);
1075
1076     yaz_log(YLOG_LOG, "CCL query: %s", wrbuf_cstr(w_ccl));
1077     cn = ccl_find_str(ccl_map, wrbuf_cstr(w_ccl), &cerror, &cpos);
1078     ccl_qual_rm(&ccl_map);
1079     if (!cn)
1080     {
1081         client_set_state(cl, Client_Error);
1082         session_log(se, YLOG_WARN, "Failed to parse CCL query '%s' for %s",
1083                     wrbuf_cstr(w_ccl),
1084                     client_get_id(cl));
1085         wrbuf_destroy(w_ccl);
1086         wrbuf_destroy(w_pqf);
1087         return -1;
1088     }
1089     wrbuf_destroy(w_ccl);
1090
1091     if (!pqf_strftime || !*pqf_strftime)
1092         ccl_pquery(w_pqf, cn);
1093     else
1094     {
1095         time_t cur_time = time(0);
1096         struct tm *tm =  localtime(&cur_time);
1097         char tmp_str[300];
1098         const char *cp = tmp_str;
1099
1100         /* see man strftime(3) for things .. In particular %% gets converted
1101          to %.. And That's our original query .. */
1102         strftime(tmp_str, sizeof(tmp_str)-1, pqf_strftime, tm);
1103         for (; *cp; cp++)
1104         {
1105             if (cp[0] == '%')
1106                 ccl_pquery(w_pqf, cn);
1107             else
1108                 wrbuf_putc(w_pqf, cp[0]);
1109         }
1110     }
1111     xfree(cl->pquery);
1112     cl->pquery = xstrdup(wrbuf_cstr(w_pqf));
1113     wrbuf_destroy(w_pqf);
1114
1115     yaz_log(YLOG_LOG, "PQF query: %s", cl->pquery);
1116
1117     xfree(cl->cqlquery);
1118
1119     /* Support for PQF on SRU targets. */
1120     /* TODO Refactor */
1121     yaz_log(YLOG_DEBUG, "Query syntax: %s", query_syntax);
1122     if (strcmp(query_syntax, "pqf") != 0 && *sru)
1123     {
1124         if (!strcmp(sru, "solr")) {
1125             if (!(cl->cqlquery = make_solrquery(cl)))
1126                 return -1;
1127         }
1128         else {
1129             if (!(cl->cqlquery = make_cqlquery(cl)))
1130                 return -1;
1131         }
1132     }
1133     else
1134         cl->cqlquery = 0;
1135
1136     /* TODO FIX Not thread safe */
1137     if (!se->relevance)
1138     {
1139         // Initialize relevance structure with query terms
1140         se->relevance = relevance_create_ccl(
1141             se->service->charsets, se->nmem, cn);
1142     }
1143
1144     ccl_rpn_delete(cn);
1145     return 0;
1146 }
1147
1148 void client_set_session(struct client *cl, struct session *se)
1149 {
1150     cl->session = se;
1151 }
1152
1153 int client_is_active(struct client *cl)
1154 {
1155     if (cl->connection && (cl->state == Client_Connecting ||
1156                            cl->state == Client_Working))
1157         return 1;
1158     return 0;
1159 }
1160
1161 int client_is_active_preferred(struct client *cl)
1162 {
1163     /* only count if this is a preferred target. */
1164     if (!cl->preferred)
1165         return 0;
1166     /* TODO No sure this the condition that Seb wants */
1167     if (cl->connection && (cl->state == Client_Connecting ||
1168                            cl->state == Client_Working))
1169         return 1;
1170     return 0;
1171 }
1172
1173 Odr_int client_get_hits(struct client *cl)
1174 {
1175     return cl->hits;
1176 }
1177
1178 int client_get_num_records(struct client *cl)
1179 {
1180     return cl->record_offset;
1181 }
1182
1183 void client_set_diagnostic(struct client *cl, int diagnostic)
1184 {
1185     cl->diagnostic = diagnostic;
1186 }
1187
1188 int client_get_diagnostic(struct client *cl)
1189 {
1190     return cl->diagnostic;
1191 }
1192
1193 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf)
1194 {
1195     /* int idx; */
1196     struct suggestions *suggestions = cl->suggestions;
1197
1198     if (!suggestions) {
1199         //yaz_log(YLOG_DEBUG, "No suggestions found");
1200         return "";
1201     }
1202     if (suggestions->passthrough) {
1203         yaz_log(YLOG_DEBUG, "Passthrough Suggestions: \n%s\n", suggestions->passthrough);
1204         return suggestions->passthrough;
1205     }
1206     if (suggestions->num == 0) {
1207         return "";
1208     }
1209     /*
1210     for (idx = 0; idx < suggestions->num; idx++) {
1211         wrbuf_printf(wrbuf, "<suggest term=\"%s\"", suggestions->suggest[idx]);
1212         if (suggestions->misspelled[idx] && suggestions->misspelled[idx]) {
1213             wrbuf_puts(wrbuf, suggestions->misspelled[idx]);
1214             wrbuf_puts(wrbuf, "</suggest>\n");
1215         }
1216         else
1217             wrbuf_puts(wrbuf, "/>\n");
1218     }
1219     */
1220     return wrbuf_cstr(wrbuf);
1221 }
1222
1223
1224 void client_set_database(struct client *cl, struct session_database *db)
1225 {
1226     cl->database = db;
1227 }
1228
1229 const char *client_get_id(struct client *cl)
1230 {
1231     return cl->id;
1232 }
1233
1234 void client_set_maxrecs(struct client *cl, int v)
1235 {
1236     cl->maxrecs = v;
1237 }
1238
1239 int client_get_maxrecs(struct client *cl)
1240 {
1241     return cl->maxrecs;
1242 }
1243
1244 void client_set_startrecs(struct client *cl, int v)
1245 {
1246     cl->startrecs = v;
1247 }
1248
1249 void client_set_preferred(struct client *cl, int v)
1250 {
1251     cl->preferred = v;
1252 }
1253
1254
1255 struct suggestions* client_suggestions_create(const char* suggestions_string)
1256 {
1257     int i;
1258     NMEM nmem;
1259     struct suggestions *suggestions;
1260     if (suggestions_string == 0)
1261         return 0;
1262     nmem = nmem_create();
1263     suggestions = nmem_malloc(nmem, sizeof(*suggestions));
1264     yaz_log(YLOG_DEBUG, "client target suggestions: %s", suggestions_string);
1265
1266     suggestions->nmem = nmem;
1267     suggestions->num = 0;
1268     suggestions->misspelled = 0;
1269     suggestions->suggest = 0;
1270     suggestions->passthrough = nmem_strdup_null(nmem, suggestions_string);
1271
1272     if (suggestions_string)
1273         nmem_strsplit_escape2(suggestions->nmem, "\n", suggestions_string, &suggestions->suggest,
1274                               &suggestions->num, 1, '\\', 0);
1275     /* Set up misspelled array */
1276     suggestions->misspelled = (char **) nmem_malloc(nmem, suggestions->num * sizeof(**suggestions->misspelled));
1277     /* replace = with \0 .. for each item */
1278     for (i = 0; i < suggestions->num; i++)
1279     {
1280         char *cp = strchr(suggestions->suggest[i], '=');
1281         if (cp) {
1282             *cp = '\0';
1283             suggestions->misspelled[i] = cp+1;
1284         }
1285     }
1286     return suggestions;
1287 }
1288
1289 static void client_suggestions_destroy(struct client *cl)
1290 {
1291     NMEM nmem = cl->suggestions->nmem;
1292     cl->suggestions = 0;
1293     nmem_destroy(nmem);
1294 }
1295
1296 /*
1297  * Local variables:
1298  * c-basic-offset: 4
1299  * c-file-style: "Stroustrup"
1300  * indent-tabs-mode: nil
1301  * End:
1302  * vim: shiftwidth=4 tabstop=8 expandtab
1303  */
1304