Now generates CQL queries -- no configuration enabled yet
[pazpar2-moved-to-github.git] / src / client.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2008 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
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #if HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #if HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #if HAVE_NETDB_H
41 #include <netdb.h>
42 #endif
43 #include <signal.h>
44 #include <ctype.h>
45 #include <assert.h>
46
47 #include <yaz/marcdisp.h>
48 #include <yaz/comstack.h>
49 #include <yaz/tcpip.h>
50 #include <yaz/proto.h>
51 #include <yaz/readconf.h>
52 #include <yaz/pquery.h>
53 #include <yaz/otherinfo.h>
54 #include <yaz/yaz-util.h>
55 #include <yaz/nmem.h>
56 #include <yaz/query-charset.h>
57 #include <yaz/querytowrbuf.h>
58 #include <yaz/oid_db.h>
59 #include <yaz/diagbib1.h>
60 #include <yaz/snprintf.h>
61 #include <yaz/rpn2cql.h>
62
63 #define USE_TIMING 0
64 #if USE_TIMING
65 #include <yaz/timing.h>
66 #endif
67
68 #if HAVE_NETINET_IN_H
69 #include <netinet/in.h>
70 #endif
71
72 #include "pazpar2.h"
73
74 #include "client.h"
75 #include "connection.h"
76 #include "settings.h"
77
78 /** \brief Represents client state for a connection to one search target */
79 struct client {
80     struct session_database *database;
81     struct connection *connection;
82     struct session *session;
83     char *pquery; // Current search
84     char *cqlquery; // used for SRU targets only
85     int hits;
86     int records;
87     int setno;
88     int requestid;            // ID of current outstanding request
89     int diagnostic;
90     enum client_state state;
91     struct show_raw *show_raw;
92     struct client *next;     // next client in session or next in free list
93 };
94
95 struct show_raw {
96     int active; // whether this request has been sent to the server
97     int position;
98     int binary;
99     char *syntax;
100     char *esn;
101     void (*error_handler)(void *data, const char *addinfo);
102     void (*record_handler)(void *data, const char *buf, size_t sz);
103     void *data;
104     struct show_raw *next;
105 };
106
107 static const char *client_states[] = {
108     "Client_Connecting",
109     "Client_Connected",
110     "Client_Idle",
111     "Client_Initializing",
112     "Client_Searching",
113     "Client_Presenting",
114     "Client_Error",
115     "Client_Failed",
116     "Client_Disconnected",
117     "Client_Stopped",
118     "Client_Continue"
119 };
120
121 static struct client *client_freelist = 0;
122
123 const char *client_get_state_str(struct client *cl)
124 {
125     return client_states[cl->state];
126 }
127
128 enum client_state client_get_state(struct client *cl)
129 {
130     return cl->state;
131 }
132
133 void client_set_state(struct client *cl, enum client_state st)
134 {
135     cl->state = st;
136     if (cl->session)
137     {
138         int no_active = session_active_clients(cl->session);
139         if (no_active == 0)
140             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
141     }
142 }
143
144 static void client_show_raw_error(struct client *cl, const char *addinfo);
145
146 // Close connection and set state to error
147 void client_fatal(struct client *cl)
148 {
149     //client_show_raw_error(cl, "client connection failure");
150     yaz_log(YLOG_WARN, "Fatal error from %s", client_get_url(cl));
151     connection_destroy(cl->connection);
152     client_set_state(cl, Client_Error);
153 }
154
155 struct connection *client_get_connection(struct client *cl)
156 {
157     return cl->connection;
158 }
159
160 struct session_database *client_get_database(struct client *cl)
161 {
162     return cl->database;
163 }
164
165 struct session *client_get_session(struct client *cl)
166 {
167     return cl->session;
168 }
169
170 const char *client_get_pquery(struct client *cl)
171 {
172     return cl->pquery;
173 }
174
175 void client_set_requestid(struct client *cl, int id)
176 {
177     cl->requestid = id;
178 }
179
180
181 static void client_send_raw_present(struct client *cl);
182
183 int client_show_raw_begin(struct client *cl, int position,
184                           const char *syntax, const char *esn,
185                           void *data,
186                           void (*error_handler)(void *data, const char *addinfo),
187                           void (*record_handler)(void *data, const char *buf,
188                                                  size_t sz),
189                           void **data2,
190                           int binary)
191 {
192     struct show_raw *rr, **rrp;
193     if (!cl->connection)
194     {   /* the client has no connection */
195         return -1;
196     }
197     rr = xmalloc(sizeof(*rr));
198     *data2 = rr;
199     rr->position = position;
200     rr->active = 0;
201     rr->data = data;
202     rr->error_handler = error_handler;
203     rr->record_handler = record_handler;
204     rr->binary = binary;
205     if (syntax)
206         rr->syntax = xstrdup(syntax);
207     else
208         rr->syntax = 0;
209     if (esn)
210         rr->esn = xstrdup(esn);
211     else
212         rr->esn = 0;
213     rr->next = 0;
214     
215     for (rrp = &cl->show_raw; *rrp; rrp = &(*rrp)->next)
216         ;
217     *rrp = rr;
218     
219     if (cl->state == Client_Failed)
220     {
221         client_show_raw_error(cl, "client failed");
222     }
223     else if (cl->state == Client_Disconnected)
224     {
225         client_show_raw_error(cl, "client disconnected");
226     }
227     else
228     {
229         client_send_raw_present(cl);
230     }
231     return 0;
232 }
233
234 void client_show_raw_remove(struct client *cl, void *data)
235 {
236     struct show_raw *rr = data;
237     struct show_raw **rrp = &cl->show_raw;
238     while (*rrp != rr)
239         rrp = &(*rrp)->next;
240     if (*rrp)
241     {
242         *rrp = rr->next;
243         xfree(rr);
244     }
245 }
246
247 void client_show_raw_dequeue(struct client *cl)
248 {
249     struct show_raw *rr = cl->show_raw;
250
251     cl->show_raw = rr->next;
252     xfree(rr);
253 }
254
255 static void client_show_raw_error(struct client *cl, const char *addinfo)
256 {
257     while (cl->show_raw)
258     {
259         cl->show_raw->error_handler(cl->show_raw->data, addinfo);
260         client_show_raw_dequeue(cl);
261     }
262 }
263
264 static void client_send_raw_present(struct client *cl)
265 {
266     struct session_database *sdb = client_get_database(cl);
267     struct connection *co = client_get_connection(cl);
268     ZOOM_resultset set = connection_get_resultset(co);
269
270     int offset = cl->show_raw->position;
271     const char *syntax = 0;
272     const char *elements = 0;
273
274     assert(cl->show_raw);
275     assert(set);
276
277     yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
278             client_get_url(cl), 1, offset);
279
280     if (cl->show_raw->syntax)
281         syntax = cl->show_raw->syntax;
282     else
283         syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
284     ZOOM_resultset_option_set(set, "preferredRecordSyntax", syntax);
285
286     if (cl->show_raw->esn)
287         elements = cl->show_raw->esn;
288     else
289         elements = session_setting_oneval(sdb, PZ_ELEMENTS);
290     if (elements && *elements)
291         ZOOM_resultset_option_set(set, "elementSetName", elements);
292
293     ZOOM_resultset_records(set, 0, offset-1, 1);
294     cl->show_raw->active = 1;
295
296     connection_continue(co);
297 }
298
299 static int nativesyntax_to_type(struct session_database *sdb, char *type)
300 {
301     const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
302
303     if (s && *s)
304     {
305         if (!strncmp(s, "iso2709", 7))
306         {
307             const char *cp = strchr(s, ';');
308             yaz_snprintf(type, 80, "xml; charset=%s", cp ? cp+1 : "marc-8s");
309         }
310         else if (!strncmp(s, "xml", 3))
311         {
312             strcpy(type, "xml");
313         }
314         else
315             return -1;
316         yaz_log(YLOG_LOG, "Returned type %s", type);
317         return 0;
318     }
319     return -1;
320 }
321
322 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
323 {
324     const char *buf;
325     int len;
326     char type[80];
327
328     if (cl->show_raw->binary)
329         strcpy(type, "raw");
330     else
331     {
332         struct session_database *sdb = client_get_database(cl);
333         nativesyntax_to_type(sdb, type);
334     }
335
336     buf = ZOOM_record_get(rec, type, &len);
337     cl->show_raw->record_handler(cl->show_raw->data,  buf, len);
338     client_show_raw_dequeue(cl);
339 }
340
341 void client_search_response(struct client *cl)
342 {
343     struct connection *co = cl->connection;
344     struct session *se = cl->session;
345     ZOOM_connection link = connection_get_link(co);
346     ZOOM_resultset resultset = connection_get_resultset(co);
347     const char *error, *addinfo;
348
349     if (ZOOM_connection_error(link, &error, &addinfo))
350     {
351         cl->hits = 0;
352         cl->state = Client_Error;
353         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
354             error, addinfo, client_get_url(cl));
355     }
356     else
357     {
358         cl->hits = ZOOM_resultset_size(resultset);
359         se->total_hits += cl->hits;
360     }
361 }
362
363
364 void client_record_response(struct client *cl)
365 {
366     struct connection *co = cl->connection;
367     ZOOM_connection link = connection_get_link(co);
368     ZOOM_resultset resultset = connection_get_resultset(co);
369     const char *error, *addinfo;
370
371     yaz_log(YLOG_LOG, "client_record_response");
372     if (ZOOM_connection_error(link, &error, &addinfo))
373     {
374         cl->state = Client_Error;
375         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
376             error, addinfo, client_get_url(cl));
377     }
378     else
379     {
380         ZOOM_record rec = 0;
381         const char *msg, *addinfo;
382         
383         yaz_log(YLOG_LOG, "show_raw=%p show_raw->active=%d",
384                 cl->show_raw, cl->show_raw ? cl->show_raw->active : 0);
385         if (cl->show_raw && cl->show_raw->active)
386         {
387             if ((rec = ZOOM_resultset_record(resultset,
388                                              cl->show_raw->position-1)))
389             {
390                 cl->show_raw->active = 0;
391                 ingest_raw_record(cl, rec);
392             }
393         }
394         else
395         {
396             int offset = cl->records;
397             if ((rec = ZOOM_resultset_record(resultset, offset)))
398             {
399                 yaz_log(YLOG_LOG, "Record with offset %d", offset);
400                 
401                 cl->records++;
402                 if (ZOOM_record_error(rec, &msg, &addinfo, 0))
403                     yaz_log(YLOG_WARN, "Record error %s (%s): %s (rec #%d)",
404                             error, addinfo, client_get_url(cl), cl->records);
405                 else
406                 {
407                     struct session_database *sdb = client_get_database(cl);
408                     const char *xmlrec;
409                     char type[80];
410                     nativesyntax_to_type(sdb, type);
411                     if ((xmlrec = ZOOM_record_get(rec, type, NULL)))
412                     {
413                         if (ingest_record(cl, xmlrec, cl->records))
414                         {
415                             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
416                             session_alert_watch(cl->session, SESSION_WATCH_RECORD);
417                         }
418                         else
419                             yaz_log(YLOG_WARN, "Failed to ingest");
420                     }
421                     else
422                         yaz_log(YLOG_WARN, "Failed to extract ZOOM record");
423                 }
424
425             }
426         }
427         if (!rec)
428             yaz_log(YLOG_WARN, "Expected record, but got NULL");
429     }
430 }
431
432 void client_start_search(struct client *cl)
433 {
434     struct session_database *sdb = client_get_database(cl);
435     struct connection *co = client_get_connection(cl);
436     ZOOM_connection link = connection_get_link(co);
437     ZOOM_resultset rs;
438     char *databaseName = sdb->database->databases[0];
439     const char *opt_piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK);
440     const char *opt_queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING);
441     const char *opt_elements = session_setting_oneval(sdb, PZ_ELEMENTS);
442     const char *opt_requestsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
443     const char *opt_maxrecs = session_setting_oneval(sdb, PZ_MAXRECS);
444     const char *opt_sru = session_setting_oneval(sdb, PZ_SRU);
445
446     assert(link);
447
448     cl->hits = -1;
449     cl->records = 0;
450     cl->diagnostic = 0;
451
452     if (*opt_piggyback)
453         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
454     else
455         ZOOM_connection_option_set(link, "piggyback", "1");
456     if (*opt_queryenc)
457         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
458     if (*opt_sru && *opt_elements)
459         ZOOM_connection_option_set(link, "schema", opt_elements);
460     else if (*opt_elements)
461         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
462     if (*opt_requestsyn)
463         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
464     if (*opt_maxrecs)
465         ZOOM_connection_option_set(link, "count", opt_maxrecs);
466     else
467     {
468         char n[128];
469         sprintf(n, "%d", global_parameters.toget);
470         ZOOM_connection_option_set(link, "count", n);
471     }
472     if (!databaseName || !*databaseName)
473         databaseName = "Default";
474     ZOOM_connection_option_set(link, "databaseName", databaseName);
475
476     ZOOM_connection_option_set(link, "presentChunk", "20");
477
478     if (cl->cqlquery)
479     {
480         ZOOM_query q = ZOOM_query_create();
481         ZOOM_query_cql(q, cl->cqlquery);
482         rs = ZOOM_connection_search(link, q);
483     }
484     else
485         rs = ZOOM_connection_search_pqf(link, cl->pquery);
486     connection_set_resultset(co, rs);
487     connection_continue(co);
488 }
489
490 struct client *client_create(void)
491 {
492     struct client *r;
493     if (client_freelist)
494     {
495         r = client_freelist;
496         client_freelist = client_freelist->next;
497     }
498     else
499         r = xmalloc(sizeof(struct client));
500     r->pquery = 0;
501     r->cqlquery = 0;
502     r->database = 0;
503     r->connection = 0;
504     r->session = 0;
505     r->hits = 0;
506     r->records = 0;
507     r->setno = 0;
508     r->requestid = -1;
509     r->diagnostic = 0;
510     r->state = Client_Disconnected;
511     r->show_raw = 0;
512     r->next = 0;
513     return r;
514 }
515
516 void client_destroy(struct client *c)
517 {
518     struct session *se = c->session;
519     if (c == se->clients)
520         se->clients = c->next;
521     else
522     {
523         struct client *cc;
524         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
525             ;
526         if (cc)
527             cc->next = c->next;
528     }
529     xfree(c->pquery);
530     xfree(c->cqlquery);
531
532     if (c->connection)
533         connection_release(c->connection);
534     c->next = client_freelist;
535     client_freelist = c;
536 }
537
538 void client_set_connection(struct client *cl, struct connection *con)
539 {
540     cl->connection = con;
541 }
542
543 void client_disconnect(struct client *cl)
544 {
545     if (cl->state != Client_Idle)
546         client_set_state(cl, Client_Disconnected);
547     client_set_connection(cl, 0);
548 }
549
550 // Extract terms from query into null-terminated termlist
551 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
552 {
553     int num = 0;
554
555     pull_terms(nmem, query, termlist, &num);
556     termlist[num] = 0;
557 }
558
559 // Initialize CCL map for a target
560 static CCL_bibset prepare_cclmap(struct client *cl)
561 {
562     struct session_database *sdb = client_get_database(cl);
563     struct setting *s;
564     CCL_bibset res;
565
566     if (!sdb->settings)
567         return 0;
568     res = ccl_qual_mk();
569     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
570     {
571         char *p = strchr(s->name + 3, ':');
572         if (!p)
573         {
574             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
575             ccl_qual_rm(&res);
576             return 0;
577         }
578         p++;
579         ccl_qual_fitem(res, s->value, p);
580     }
581     return res;
582 }
583
584 // returns a xmalloced CQL query corresponding to the pquery in client
585 static char *make_cqlquery(struct client *cl)
586 {
587     cql_transform_t cqlt = cql_transform_create();
588     Z_RPNQuery *zquery;
589     char *r;
590     WRBUF wrb = wrbuf_alloc();
591     int status;
592
593     zquery = p_query_rpn(global_parameters.odr_out, cl->pquery);
594     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
595     {
596         yaz_log(YLOG_WARN, "failed to generate CQL query, code=%d", status);
597         return 0;
598     }
599     r = xstrdup(wrbuf_buf(wrb));
600
601     wrbuf_destroy(wrb);
602     odr_reset(global_parameters.odr_out); // releases the zquery
603     cql_transform_close(cqlt);
604     return r;
605 }
606
607 // Parse the query given the settings specific to this client
608 int client_parse_query(struct client *cl, const char *query)
609 {
610     struct session *se = client_get_session(cl);
611     struct session_database *sdb = client_get_database(cl);
612     struct ccl_rpn_node *cn;
613     int cerror, cpos;
614     CCL_bibset ccl_map = prepare_cclmap(cl);
615     const char *sru = session_setting_oneval(sdb, PZ_SRU);
616
617     if (!ccl_map)
618         return -1;
619
620     cn = ccl_find_str(ccl_map, query, &cerror, &cpos);
621     ccl_qual_rm(&ccl_map);
622     if (!cn)
623     {
624         cl->state = Client_Error;
625         yaz_log(YLOG_WARN, "Failed to parse query for %s",
626                          client_get_database(cl)->database->url);
627         return -1;
628     }
629     wrbuf_rewind(se->wrbuf);
630     ccl_pquery(se->wrbuf, cn);
631     xfree(cl->pquery);
632     cl->pquery = xstrdup(wrbuf_cstr(se->wrbuf));
633
634     xfree(cl->cqlquery);
635     if (*sru)
636     {
637         if (!(cl->cqlquery = make_cqlquery(cl)))
638             return -1;
639     }
640     else
641         cl->cqlquery = 0;
642
643     if (!se->relevance)
644     {
645         // Initialize relevance structure with query terms
646         char *p[512];
647         extract_terms(se->nmem, cn, p);
648         se->relevance = relevance_create(
649             global_parameters.server->relevance_pct,
650             se->nmem, (const char **) p,
651             se->expected_maxrecs);
652     }
653
654     ccl_rpn_delete(cn);
655     return 0;
656 }
657
658 void client_set_session(struct client *cl, struct session *se)
659 {
660     cl->session = se;
661     cl->next = se->clients;
662     se->clients = cl;
663 }
664
665 int client_is_active(struct client *cl)
666 {
667     if (cl->connection && (cl->state == Client_Continue ||
668                            cl->state == Client_Connecting ||
669                            cl->state == Client_Working))
670         return 1;
671     return 0;
672 }
673
674 struct client *client_next_in_session(struct client *cl)
675 {
676     if (cl)
677         return cl->next;
678     return 0;
679
680 }
681
682 int client_get_hits(struct client *cl)
683 {
684     return cl->hits;
685 }
686
687 int client_get_num_records(struct client *cl)
688 {
689     return cl->records;
690 }
691
692 int client_get_diagnostic(struct client *cl)
693 {
694     return cl->diagnostic;
695 }
696
697 void client_set_database(struct client *cl, struct session_database *db)
698 {
699     cl->database = db;
700 }
701
702 struct host *client_get_host(struct client *cl)
703 {
704     return client_get_database(cl)->database->host;
705 }
706
707 const char *client_get_url(struct client *cl)
708 {
709     return client_get_database(cl)->database->url;
710 }
711
712 /*
713  * Local variables:
714  * c-basic-offset: 4
715  * indent-tabs-mode: nil
716  * End:
717  * vim: shiftwidth=4 tabstop=8 expandtab
718  */