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