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