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