Pazpar2 1.4.4-2 for squeeze
[pazpar2-moved-to-github.git] / src / client.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2010 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
55 #define USE_TIMING 0
56 #if USE_TIMING
57 #include <yaz/timing.h>
58 #endif
59
60 #include "ppmutex.h"
61 #include "session.h"
62 #include "parameters.h"
63 #include "client.h"
64 #include "connection.h"
65 #include "settings.h"
66 #include "relevance.h"
67 #include "incref.h"
68
69 /* client counting (1) , disable client counting (0) */
70 #if 1
71 static YAZ_MUTEX g_mutex = 0;
72 static int no_clients = 0;
73
74 static void client_use(int delta)
75 {
76     if (!g_mutex)
77         yaz_mutex_create(&g_mutex);
78     yaz_mutex_enter(g_mutex);
79     no_clients += delta;
80     yaz_mutex_leave(g_mutex);
81     yaz_log(YLOG_DEBUG, "%s clients=%d", delta > 0 ? "INC" : "DEC", no_clients);
82 }
83 #else
84 #define client_use(x)
85 #endif
86
87 /** \brief Represents client state for a connection to one search target */
88 struct client {
89     struct session_database *database;
90     struct connection *connection;
91     struct session *session;
92     char *pquery; // Current search
93     char *cqlquery; // used for SRU targets only
94     Odr_int hits;
95     int record_offset;
96     int maxrecs;
97     int startrecs;
98     int diagnostic;
99     enum client_state state;
100     struct show_raw *show_raw;
101     ZOOM_resultset resultset;
102     YAZ_MUTEX mutex;
103     int ref_count;
104 };
105
106 struct show_raw {
107     int active; // whether this request has been sent to the server
108     int position;
109     int binary;
110     char *syntax;
111     char *esn;
112     void (*error_handler)(void *data, const char *addinfo);
113     void (*record_handler)(void *data, const char *buf, size_t sz);
114     void *data;
115     struct show_raw *next;
116 };
117
118 static const char *client_states[] = {
119     "Client_Connecting",
120     "Client_Idle",
121     "Client_Working",
122     "Client_Error",
123     "Client_Failed",
124     "Client_Disconnected"
125 };
126
127 const char *client_get_state_str(struct client *cl)
128 {
129     return client_states[cl->state];
130 }
131
132 enum client_state client_get_state(struct client *cl)
133 {
134     return cl->state;
135 }
136
137 void client_set_state(struct client *cl, enum client_state st)
138 {
139     int was_active = 0;
140     if (client_is_active(cl))
141         was_active = 1;
142     cl->state = st;
143     /* If client is going from being active to inactive and all clients
144        are now idle we fire a watch for the session . The assumption is
145        that session is not mutex locked if client is already active */
146     if (was_active && !client_is_active(cl) && cl->session)
147     {
148         int no_active = session_active_clients(cl->session);
149         if (no_active == 0)
150             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
151     }
152 }
153
154 static void client_show_raw_error(struct client *cl, const char *addinfo);
155
156 struct connection *client_get_connection(struct client *cl)
157 {
158     return cl->connection;
159 }
160
161 struct session_database *client_get_database(struct client *cl)
162 {
163     return cl->database;
164 }
165
166 struct session *client_get_session(struct client *cl)
167 {
168     return cl->session;
169 }
170
171 const char *client_get_pquery(struct client *cl)
172 {
173     return cl->pquery;
174 }
175
176 static void client_send_raw_present(struct client *cl);
177 static int nativesyntax_to_type(struct session_database *sdb, char *type,
178                                 ZOOM_record rec);
179
180 static void client_show_immediate(
181     ZOOM_resultset resultset, struct session_database *sdb, int position,
182     void *data,
183     void (*error_handler)(void *data, const char *addinfo),
184     void (*record_handler)(void *data, const char *buf, size_t sz),
185     int binary)
186 {
187     ZOOM_record rec = 0;
188     char type[80];
189     const char *buf;
190     int len;
191
192     if (!resultset)
193     {
194         error_handler(data, "no resultset");
195         return;
196     }
197     rec = ZOOM_resultset_record(resultset, position-1);
198     if (!rec)
199     {
200         error_handler(data, "no record");
201         return;
202     }
203     if (binary)
204         strcpy(type, "raw");
205     else
206         nativesyntax_to_type(sdb, type, rec);
207     buf = ZOOM_record_get(rec, type, &len);
208     if (!buf)
209     {
210         error_handler(data, "no record");
211         return;
212     }
213     record_handler(data, buf, len);
214 }
215
216
217 int client_show_raw_begin(struct client *cl, int position,
218                           const char *syntax, const char *esn,
219                           void *data,
220                           void (*error_handler)(void *data, const char *addinfo),
221                           void (*record_handler)(void *data, const char *buf,
222                                                  size_t sz),
223                           int binary)
224 {
225     if (syntax == 0 && esn == 0)
226         client_show_immediate(cl->resultset, client_get_database(cl),
227                               position, data,
228                               error_handler, record_handler,
229                               binary);
230     else
231     {
232         struct show_raw *rr, **rrp;
233
234         if (!cl->connection)
235             return -1;
236     
237
238         rr = xmalloc(sizeof(*rr));
239         rr->position = position;
240         rr->active = 0;
241         rr->data = data;
242         rr->error_handler = error_handler;
243         rr->record_handler = record_handler;
244         rr->binary = binary;
245         if (syntax)
246             rr->syntax = xstrdup(syntax);
247         else
248             rr->syntax = 0;
249         if (esn)
250             rr->esn = xstrdup(esn);
251         else
252             rr->esn = 0;
253         rr->next = 0;
254         
255         for (rrp = &cl->show_raw; *rrp; rrp = &(*rrp)->next)
256             ;
257         *rrp = rr;
258         
259         if (cl->state == Client_Failed)
260         {
261             client_show_raw_error(cl, "client failed");
262         }
263         else if (cl->state == Client_Disconnected)
264         {
265             client_show_raw_error(cl, "client disconnected");
266         }
267         else
268         {
269             client_send_raw_present(cl);
270         }
271     }
272     return 0;
273 }
274
275 static void client_show_raw_delete(struct show_raw *r)
276 {
277     xfree(r->syntax);
278     xfree(r->esn);
279     xfree(r);
280 }
281
282 void client_show_raw_remove(struct client *cl, void *data)
283 {
284     struct show_raw *rr = data;
285     struct show_raw **rrp = &cl->show_raw;
286     while (*rrp != rr)
287         rrp = &(*rrp)->next;
288     if (*rrp)
289     {
290         *rrp = rr->next;
291         client_show_raw_delete(rr);
292     }
293 }
294
295 void client_show_raw_dequeue(struct client *cl)
296 {
297     struct show_raw *rr = cl->show_raw;
298
299     cl->show_raw = rr->next;
300     client_show_raw_delete(rr);
301 }
302
303 static void client_show_raw_error(struct client *cl, const char *addinfo)
304 {
305     while (cl->show_raw)
306     {
307         cl->show_raw->error_handler(cl->show_raw->data, addinfo);
308         client_show_raw_dequeue(cl);
309     }
310 }
311
312 static void client_send_raw_present(struct client *cl)
313 {
314     struct session_database *sdb = client_get_database(cl);
315     struct connection *co = client_get_connection(cl);
316     ZOOM_resultset set = cl->resultset;
317
318     int offset = cl->show_raw->position;
319     const char *syntax = 0;
320     const char *elements = 0;
321
322     assert(cl->show_raw);
323     assert(set);
324
325     yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
326             client_get_url(cl), 1, offset);
327
328     if (cl->show_raw->syntax)
329         syntax = cl->show_raw->syntax;
330     else
331         syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
332     ZOOM_resultset_option_set(set, "preferredRecordSyntax", syntax);
333
334     if (cl->show_raw->esn)
335         elements = cl->show_raw->esn;
336     else
337         elements = session_setting_oneval(sdb, PZ_ELEMENTS);
338     if (elements && *elements)
339         ZOOM_resultset_option_set(set, "elementSetName", elements);
340
341     ZOOM_resultset_records(set, 0, offset-1, 1);
342     cl->show_raw->active = 1;
343
344     connection_continue(co);
345 }
346
347 static int nativesyntax_to_type(struct session_database *sdb, char *type,
348                                 ZOOM_record rec)
349 {
350     const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
351
352     if (s && *s)
353     {
354         if (!strncmp(s, "iso2709", 7))
355         {
356             const char *cp = strchr(s, ';');
357             yaz_snprintf(type, 80, "xml; charset=%s", cp ? cp+1 : "marc-8s");
358         }
359         else if (!strncmp(s, "xml", 3))
360         {
361             strcpy(type, "xml");
362         }
363         else if (!strncmp(s, "txml", 4))
364         {
365             const char *cp = strchr(s, ';');
366             yaz_snprintf(type, 80, "txml; charset=%s", cp ? cp+1 : "marc-8s");
367         }
368         else
369             return -1;
370         return 0;
371     }
372     else  /* attempt to deduce structure */
373     {
374         const char *syntax = ZOOM_record_get(rec, "syntax", NULL);
375         if (syntax)
376         {
377             if (!strcmp(syntax, "XML"))
378             {
379                 strcpy(type, "xml");
380                 return 0;
381             }
382             else if (!strcmp(syntax, "TXML"))
383                 {
384                     strcpy(type, "txml");
385                     return 0;
386                 }
387             else if (!strcmp(syntax, "USmarc") || !strcmp(syntax, "MARC21"))
388             {
389                 strcpy(type, "xml; charset=marc8-s");
390                 return 0;
391             }
392             else return -1;
393         }
394         else return -1;
395     }
396 }
397
398 /**
399  * TODO Consider thread safety!!!
400  *
401  */
402 int client_report_facets(struct client *cl, ZOOM_resultset rs) {
403     int facet_idx;
404     ZOOM_facet_field *facets = ZOOM_resultset_facets(rs);
405     int facet_num;
406     struct session *se = client_get_session(cl);
407     facet_num = ZOOM_resultset_facets_size(rs);
408     yaz_log(YLOG_DEBUG, "client_report_facets: %d", facet_num);
409
410     for (facet_idx = 0; facet_idx < facet_num; facet_idx++) {
411         const char *name = ZOOM_facet_field_name(facets[facet_idx]);
412         size_t term_idx;
413         size_t term_num = ZOOM_facet_field_term_count(facets[facet_idx]);
414         for (term_idx = 0; term_idx < term_num; term_idx++ ) {
415             int freq;
416             const char *term = ZOOM_facet_field_get_term(facets[facet_idx], term_idx, &freq);
417             if (term)
418                 add_facet(se, name, term, freq);
419         }
420     }
421
422     return 0;
423 }
424
425 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
426 {
427     const char *buf;
428     int len;
429     char type[80];
430
431     if (cl->show_raw->binary)
432         strcpy(type, "raw");
433     else
434     {
435         struct session_database *sdb = client_get_database(cl);
436         nativesyntax_to_type(sdb, type, rec);
437     }
438
439     buf = ZOOM_record_get(rec, type, &len);
440     cl->show_raw->record_handler(cl->show_raw->data,  buf, len);
441     client_show_raw_dequeue(cl);
442 }
443
444 void client_search_response(struct client *cl)
445 {
446     struct connection *co = cl->connection;
447     struct session *se = cl->session;
448     ZOOM_connection link = connection_get_link(co);
449     ZOOM_resultset resultset = cl->resultset;
450
451     const char *error, *addinfo = 0;
452     
453     if (ZOOM_connection_error(link, &error, &addinfo))
454     {
455         cl->hits = 0;
456         client_set_state(cl, Client_Error);
457         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
458                 error, addinfo, client_get_url(cl));
459     }
460     else
461     {
462         client_report_facets(cl, resultset);
463         cl->record_offset = cl->startrecs;
464         cl->hits = ZOOM_resultset_size(resultset);
465         if (se)
466             se->total_hits += cl->hits;
467     }
468 }
469
470 void client_got_records(struct client *cl)
471 {
472     struct session *se = cl->session;
473     if (se)
474     {
475         client_unlock(cl);
476         session_alert_watch(se, SESSION_WATCH_SHOW);
477         session_alert_watch(se, SESSION_WATCH_RECORD);
478         client_lock(cl);
479     }
480 }
481
482 void client_record_response(struct client *cl)
483 {
484     struct connection *co = cl->connection;
485     ZOOM_connection link = connection_get_link(co);
486     ZOOM_resultset resultset = cl->resultset;
487     const char *error, *addinfo;
488
489     if (ZOOM_connection_error(link, &error, &addinfo))
490     {
491         client_set_state(cl, Client_Error);
492         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
493             error, addinfo, client_get_url(cl));
494     }
495     else
496     {
497         ZOOM_record rec = 0;
498         const char *msg, *addinfo;
499         
500         if (cl->show_raw && cl->show_raw->active)
501         {
502             if ((rec = ZOOM_resultset_record(resultset,
503                                              cl->show_raw->position-1)))
504             {
505                 cl->show_raw->active = 0;
506                 ingest_raw_record(cl, rec);
507             }
508             else
509             {
510                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
511                         cl->show_raw->position-1);
512             }
513         }
514         else
515         {
516             int offset = cl->record_offset;
517             if ((rec = ZOOM_resultset_record(resultset, offset)))
518             {
519                 cl->record_offset++;
520                 if (cl->session == 0)
521                     ;
522                 else if (ZOOM_record_error(rec, &msg, &addinfo, 0))
523                 {
524                     yaz_log(YLOG_WARN, "Record error %s (%s): %s (rec #%d)",
525                             msg, addinfo, client_get_url(cl),
526                             cl->record_offset);
527                 }
528                 else
529                 {
530                     struct session_database *sdb = client_get_database(cl);
531                     NMEM nmem = nmem_create();
532                     const char *xmlrec;
533                     char type[80];
534
535                     if (nativesyntax_to_type(sdb, type, rec))
536                         yaz_log(YLOG_WARN, "Failed to determine record type");
537                     xmlrec = ZOOM_record_get(rec, type, NULL);
538                     if (!xmlrec)
539                         yaz_log(YLOG_WARN, "ZOOM_record_get failed from %s",
540                                 client_get_url(cl));
541                     else
542                     {
543                         if (ingest_record(cl, xmlrec, cl->record_offset, nmem))
544                             yaz_log(YLOG_WARN, "Failed to ingest from %s",
545                                     client_get_url(cl));
546                     }
547                     nmem_destroy(nmem);
548                 }
549             }
550             else
551             {
552                 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
553                         offset);
554             }
555         }
556     }
557 }
558
559 static int client_set_facets_request(struct client *cl, ZOOM_connection link)
560 {
561     struct session_database *sdb = client_get_database(cl);
562     const char *opt_facet_term_sort  = session_setting_oneval(sdb, PZ_TERMLIST_TERM_SORT);
563     const char *opt_facet_term_count = session_setting_oneval(sdb, PZ_TERMLIST_TERM_COUNT);
564     /* Disable when no count is set */
565     if (opt_facet_term_count && *opt_facet_term_count)
566     {
567         int index = 0;
568         struct session *session = client_get_session(cl);
569         struct conf_service *service = session->service;
570         int num = service->num_metadata;
571         WRBUF wrbuf = wrbuf_alloc();
572         yaz_log(YLOG_DEBUG, "Facet settings, sort: %s count: %s",
573                 opt_facet_term_sort, opt_facet_term_count);
574         for (index = 0; index < num; index++)
575         {
576             struct conf_metadata *conf_meta = &service->metadata[index];
577             if (conf_meta->termlist)
578             {
579                 if (wrbuf_len(wrbuf))
580                     wrbuf_puts(wrbuf, ", ");
581                 wrbuf_printf(wrbuf, "@attr 1=%s", conf_meta->name);
582                 
583                 if (opt_facet_term_sort && *opt_facet_term_sort)
584                     wrbuf_printf(wrbuf, " @attr 2=%s", opt_facet_term_sort);
585                 wrbuf_printf(wrbuf, " @attr 3=%s", opt_facet_term_count);
586             }
587         }
588         if (wrbuf_len(wrbuf))
589         {
590             yaz_log(YLOG_LOG, "Setting ZOOM facets option: %s", wrbuf_cstr(wrbuf));
591             ZOOM_connection_option_set(link, "facets", wrbuf_cstr(wrbuf));
592             return 1;
593         }
594     }
595     return 0;
596 }
597
598 int client_has_facet(struct client *cl, const char *name) {
599     ZOOM_facet_field facet_field;
600     if (!cl || !cl->resultset || !name) {
601         yaz_log(YLOG_DEBUG, "client has facet: Missing %p %p %s", cl, (cl ? cl->resultset: 0), name);
602         return 0;
603     }
604     facet_field = ZOOM_resultset_get_facet_field(cl->resultset, name);
605     if (facet_field) {
606         yaz_log(YLOG_DEBUG, "client: has facets for %s", name);
607         return 1;
608     }
609     yaz_log(YLOG_DEBUG, "client: No facets for %s", name);
610     return 0;
611 }
612
613
614 void client_start_search(struct client *cl)
615 {
616     struct session_database *sdb = client_get_database(cl);
617     struct connection *co = client_get_connection(cl);
618     ZOOM_connection link = connection_get_link(co);
619     ZOOM_resultset rs;
620     char *databaseName = sdb->database->databases[0];
621     const char *opt_piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK);
622     const char *opt_queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING);
623     const char *opt_elements = session_setting_oneval(sdb, PZ_ELEMENTS);
624     const char *opt_requestsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
625     const char *opt_maxrecs = session_setting_oneval(sdb, PZ_MAXRECS);
626     const char *opt_sru = session_setting_oneval(sdb, PZ_SRU);
627     const char *opt_sort = session_setting_oneval(sdb, PZ_SORT);
628     char maxrecs_str[24], startrecs_str[24];
629
630     assert(link);
631
632     cl->hits = -1;
633     cl->record_offset = 0;
634     cl->diagnostic = 0;
635     client_set_state(cl, Client_Working);
636
637     if (*opt_piggyback)
638         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
639     else
640         ZOOM_connection_option_set(link, "piggyback", "1");
641     if (*opt_queryenc)
642         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
643     if (*opt_sru && *opt_elements)
644         ZOOM_connection_option_set(link, "schema", opt_elements);
645     else if (*opt_elements)
646         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
647     if (*opt_requestsyn)
648         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
649
650     if (!*opt_maxrecs)
651     {
652         sprintf(maxrecs_str, "%d", cl->maxrecs);
653         opt_maxrecs = maxrecs_str;
654     }
655     ZOOM_connection_option_set(link, "count", opt_maxrecs);
656
657
658     if (atoi(opt_maxrecs) > 20)
659         ZOOM_connection_option_set(link, "presentChunk", "20");
660     else
661         ZOOM_connection_option_set(link, "presentChunk", opt_maxrecs);
662
663     sprintf(startrecs_str, "%d", cl->startrecs);
664     ZOOM_connection_option_set(link, "start", startrecs_str);
665
666     if (databaseName)
667         ZOOM_connection_option_set(link, "databaseName", databaseName);
668
669     if (cl->cqlquery)
670     {
671         ZOOM_query q = ZOOM_query_create();
672         yaz_log(YLOG_LOG, "Search %s CQL: %s", sdb->database->url, cl->cqlquery);
673         ZOOM_query_cql(q, cl->cqlquery);
674         if (*opt_sort)
675             ZOOM_query_sortby(q, opt_sort);
676         rs = ZOOM_connection_search(link, q);
677         ZOOM_query_destroy(q);
678     }
679     else
680     {
681         client_set_facets_request(cl, link);
682         yaz_log(YLOG_LOG, "Search %s PQF: %s", sdb->database->url, cl->pquery);
683         rs = ZOOM_connection_search_pqf(link, cl->pquery);
684     }
685     ZOOM_resultset_destroy(cl->resultset);
686     cl->resultset = rs;
687     connection_continue(co);
688 }
689
690 struct client *client_create(void)
691 {
692     struct client *r = xmalloc(sizeof(*r));
693     r->maxrecs = 100;
694     r->startrecs = 0;
695     r->pquery = 0;
696     r->cqlquery = 0;
697     r->database = 0;
698     r->connection = 0;
699     r->session = 0;
700     r->hits = 0;
701     r->record_offset = 0;
702     r->diagnostic = 0;
703     r->state = Client_Disconnected;
704     r->show_raw = 0;
705     r->resultset = 0;
706     r->mutex = 0;
707     pazpar2_mutex_create(&r->mutex, "client");
708
709     r->ref_count = 1;
710     client_use(1);
711     
712     return r;
713 }
714
715 void client_lock(struct client *c)
716 {
717     yaz_mutex_enter(c->mutex);
718 }
719
720 void client_unlock(struct client *c)
721 {
722     yaz_mutex_leave(c->mutex);
723 }
724
725 void client_incref(struct client *c)
726 {
727     pazpar2_incref(&c->ref_count, c->mutex);
728     yaz_log(YLOG_DEBUG, "client_incref c=%p %s cnt=%d",
729             c, client_get_url(c), c->ref_count);
730 }
731
732 int client_destroy(struct client *c)
733 {
734     if (c)
735     {
736         yaz_log(YLOG_DEBUG, "client_destroy c=%p %s cnt=%d",
737                 c, client_get_url(c), c->ref_count);
738         if (!pazpar2_decref(&c->ref_count, c->mutex))
739         {
740             xfree(c->pquery);
741             c->pquery = 0;
742             xfree(c->cqlquery);
743             c->cqlquery = 0;
744             assert(!c->connection);
745
746             if (c->resultset)
747             {
748                 ZOOM_resultset_destroy(c->resultset);
749             }
750             yaz_mutex_destroy(&c->mutex);
751             xfree(c);
752             client_use(-1);
753             return 1;
754         }
755     }
756     return 0;
757 }
758
759 void client_set_connection(struct client *cl, struct connection *con)
760 {
761     if (cl->resultset)
762         ZOOM_resultset_release(cl->resultset);
763     if (con)
764     {
765         assert(cl->connection == 0);
766         cl->connection = con;
767         client_incref(cl);
768     }
769     else
770     {
771         cl->connection = con;
772         client_destroy(cl);
773     }
774 }
775
776 void client_disconnect(struct client *cl)
777 {
778     if (cl->state != Client_Idle)
779         client_set_state(cl, Client_Disconnected);
780     client_set_connection(cl, 0);
781 }
782
783 // Extract terms from query into null-terminated termlist
784 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
785 {
786     int num = 0;
787
788     pull_terms(nmem, query, termlist, &num);
789     termlist[num] = 0;
790 }
791
792 // Initialize CCL map for a target
793 static CCL_bibset prepare_cclmap(struct client *cl)
794 {
795     struct session_database *sdb = client_get_database(cl);
796     struct setting *s;
797     CCL_bibset res;
798
799     if (!sdb->settings)
800         return 0;
801     res = ccl_qual_mk();
802     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
803     {
804         char *p = strchr(s->name + 3, ':');
805         if (!p)
806         {
807             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
808             ccl_qual_rm(&res);
809             return 0;
810         }
811         p++;
812         ccl_qual_fitem(res, s->value, p);
813     }
814     return res;
815 }
816
817 // returns a xmalloced CQL query corresponding to the pquery in client
818 static char *make_cqlquery(struct client *cl)
819 {
820     cql_transform_t cqlt = cql_transform_create();
821     Z_RPNQuery *zquery;
822     char *r;
823     WRBUF wrb = wrbuf_alloc();
824     int status;
825     ODR odr_out = odr_createmem(ODR_ENCODE);
826
827     zquery = p_query_rpn(odr_out, cl->pquery);
828     yaz_log(YLOG_LOG, "PQF: %s", cl->pquery);
829     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
830     {
831         yaz_log(YLOG_WARN, "Failed to generate CQL query, code=%d", status);
832         r = 0;
833     }
834     else
835     {
836         r = xstrdup(wrbuf_cstr(wrb));
837     }     
838     wrbuf_destroy(wrb);
839     odr_destroy(odr_out);
840     cql_transform_close(cqlt);
841     return r;
842 }
843
844 // Parse the query given the settings specific to this client
845 int client_parse_query(struct client *cl, const char *query)
846 {
847     struct session *se = client_get_session(cl);
848     struct session_database *sdb = client_get_database(cl);
849     struct ccl_rpn_node *cn;
850     int cerror, cpos;
851     CCL_bibset ccl_map = prepare_cclmap(cl);
852     const char *sru = session_setting_oneval(sdb, PZ_SRU);
853     const char *pqf_prefix = session_setting_oneval(sdb, PZ_PQF_PREFIX);
854     const char *pqf_strftime = session_setting_oneval(sdb, PZ_PQF_STRFTIME);
855
856     if (!ccl_map)
857         return -1;
858
859     cn = ccl_find_str(ccl_map, query, &cerror, &cpos);
860     ccl_qual_rm(&ccl_map);
861     if (!cn)
862     {
863         client_set_state(cl, Client_Error);
864         yaz_log(YLOG_WARN, "Failed to parse CCL query %s for %s",
865                 query,
866                 client_get_database(cl)->database->url);
867         return -1;
868     }
869     wrbuf_rewind(se->wrbuf);
870     if (*pqf_prefix)
871     {
872         wrbuf_puts(se->wrbuf, pqf_prefix);
873         wrbuf_puts(se->wrbuf, " ");
874     }
875     if (!pqf_strftime || !*pqf_strftime)
876         ccl_pquery(se->wrbuf, cn);
877     else
878     {
879         time_t cur_time = time(0);
880         struct tm *tm =  localtime(&cur_time);
881         char tmp_str[300];
882         const char *cp = tmp_str;
883
884         /* see man strftime(3) for things .. In particular %% gets converted
885          to %.. And That's our original query .. */
886         strftime(tmp_str, sizeof(tmp_str)-1, pqf_strftime, tm);
887         for (; *cp; cp++)
888         {
889             if (cp[0] == '%')
890                 ccl_pquery(se->wrbuf, cn);
891             else
892                 wrbuf_putc(se->wrbuf, cp[0]);
893         }
894     }
895     xfree(cl->pquery);
896     cl->pquery = xstrdup(wrbuf_cstr(se->wrbuf));
897
898     xfree(cl->cqlquery);
899     if (*sru)
900     {
901         if (!(cl->cqlquery = make_cqlquery(cl)))
902             return -1;
903     }
904     else
905         cl->cqlquery = 0;
906
907     /* TODO FIX Not thread safe */
908     if (!se->relevance)
909     {
910         // Initialize relevance structure with query terms
911         char *p[512];
912         extract_terms(se->nmem, cn, p);
913         se->relevance = relevance_create(
914             se->service->relevance_pct,
915             se->nmem, (const char **) p);
916     }
917
918     ccl_rpn_delete(cn);
919     return 0;
920 }
921
922 void client_set_session(struct client *cl, struct session *se)
923 {
924     cl->session = se;
925 }
926
927 int client_is_active(struct client *cl)
928 {
929     if (cl->connection && (cl->state == Client_Connecting ||
930                            cl->state == Client_Working))
931         return 1;
932     return 0;
933 }
934
935 Odr_int client_get_hits(struct client *cl)
936 {
937     return cl->hits;
938 }
939
940 int client_get_num_records(struct client *cl)
941 {
942     return cl->record_offset;
943 }
944
945 void client_set_diagnostic(struct client *cl, int diagnostic)
946 {
947     cl->diagnostic = diagnostic;
948 }
949
950 int client_get_diagnostic(struct client *cl)
951 {
952     return cl->diagnostic;
953 }
954
955 void client_set_database(struct client *cl, struct session_database *db)
956 {
957     cl->database = db;
958 }
959
960 struct host *client_get_host(struct client *cl)
961 {
962     return client_get_database(cl)->database->host;
963 }
964
965 const char *client_get_url(struct client *cl)
966 {
967     if (cl->database)
968         return client_get_database(cl)->database->url;
969     else
970         return "NOURL";
971 }
972
973 void client_set_maxrecs(struct client *cl, int v)
974 {
975     cl->maxrecs = v;
976 }
977
978 void client_set_startrecs(struct client *cl, int v)
979 {
980     cl->startrecs = v;
981 }
982
983 /*
984  * Local variables:
985  * c-basic-offset: 4
986  * c-file-style: "Stroustrup"
987  * indent-tabs-mode: nil
988  * End:
989  * vim: shiftwidth=4 tabstop=8 expandtab
990  */
991