Merge branch 'master' of /home/quinn/proj/pazpar2
[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         return 0;
317     }
318     return -1;
319 }
320
321 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
322 {
323     const char *buf;
324     int len;
325     char type[80];
326
327     if (cl->show_raw->binary)
328         strcpy(type, "raw");
329     else
330     {
331         struct session_database *sdb = client_get_database(cl);
332         nativesyntax_to_type(sdb, type);
333     }
334
335     buf = ZOOM_record_get(rec, type, &len);
336     cl->show_raw->record_handler(cl->show_raw->data,  buf, len);
337     client_show_raw_dequeue(cl);
338 }
339
340 void client_search_response(struct client *cl)
341 {
342     struct connection *co = cl->connection;
343     struct session *se = cl->session;
344     ZOOM_connection link = connection_get_link(co);
345     ZOOM_resultset resultset = connection_get_resultset(co);
346     const char *error, *addinfo;
347
348     if (ZOOM_connection_error(link, &error, &addinfo))
349     {
350         cl->hits = 0;
351         cl->state = Client_Error;
352         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
353             error, addinfo, client_get_url(cl));
354     }
355     else
356     {
357         cl->hits = ZOOM_resultset_size(resultset);
358         se->total_hits += cl->hits;
359     }
360 }
361
362
363 void client_record_response(struct client *cl)
364 {
365     struct connection *co = cl->connection;
366     ZOOM_connection link = connection_get_link(co);
367     ZOOM_resultset resultset = connection_get_resultset(co);
368     const char *error, *addinfo;
369
370     yaz_log(YLOG_LOG, "client_record_response");
371     if (ZOOM_connection_error(link, &error, &addinfo))
372     {
373         cl->state = Client_Error;
374         yaz_log(YLOG_WARN, "Search error %s (%s): %s",
375             error, addinfo, client_get_url(cl));
376     }
377     else
378     {
379         ZOOM_record rec = 0;
380         const char *msg, *addinfo;
381         
382         if (cl->show_raw && cl->show_raw->active)
383         {
384             if ((rec = ZOOM_resultset_record(resultset,
385                                              cl->show_raw->position-1)))
386             {
387                 cl->show_raw->active = 0;
388                 ingest_raw_record(cl, rec);
389             }
390         }
391         else
392         {
393             int offset = cl->records;
394             if ((rec = ZOOM_resultset_record(resultset, offset)))
395             {
396                 yaz_log(YLOG_LOG, "Record with offset %d", offset);
397                 
398                 cl->records++;
399                 if (ZOOM_record_error(rec, &msg, &addinfo, 0))
400                     yaz_log(YLOG_WARN, "Record error %s (%s): %s (rec #%d)",
401                             error, addinfo, client_get_url(cl), cl->records);
402                 else
403                 {
404                     struct session_database *sdb = client_get_database(cl);
405                     const char *xmlrec;
406                     char type[80];
407                     nativesyntax_to_type(sdb, type);
408                     if ((xmlrec = ZOOM_record_get(rec, type, NULL)))
409                     {
410                         if (ingest_record(cl, xmlrec, cl->records))
411                         {
412                             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
413                             session_alert_watch(cl->session, SESSION_WATCH_RECORD);
414                         }
415                         else
416                             yaz_log(YLOG_WARN, "Failed to ingest");
417                     }
418                     else
419                         yaz_log(YLOG_WARN, "Failed to extract ZOOM record");
420                 }
421
422             }
423         }
424         if (!rec)
425             yaz_log(YLOG_WARN, "Expected record, but got NULL");
426     }
427 }
428
429 void client_start_search(struct client *cl)
430 {
431     struct session_database *sdb = client_get_database(cl);
432     struct connection *co = client_get_connection(cl);
433     ZOOM_connection link = connection_get_link(co);
434     ZOOM_resultset rs;
435     char *databaseName = sdb->database->databases[0];
436     const char *opt_piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK);
437     const char *opt_queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING);
438     const char *opt_elements = session_setting_oneval(sdb, PZ_ELEMENTS);
439     const char *opt_requestsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
440     const char *opt_maxrecs = session_setting_oneval(sdb, PZ_MAXRECS);
441     const char *opt_sru = session_setting_oneval(sdb, PZ_SRU);
442
443     assert(link);
444
445     cl->hits = -1;
446     cl->records = 0;
447     cl->diagnostic = 0;
448
449     if (*opt_piggyback)
450         ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
451     else
452         ZOOM_connection_option_set(link, "piggyback", "1");
453     if (*opt_queryenc)
454         ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
455     if (*opt_sru && *opt_elements)
456         ZOOM_connection_option_set(link, "schema", opt_elements);
457     else if (*opt_elements)
458         ZOOM_connection_option_set(link, "elementSetName", opt_elements);
459     if (*opt_requestsyn)
460         ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
461     if (*opt_maxrecs)
462         ZOOM_connection_option_set(link, "count", opt_maxrecs);
463     else
464     {
465         char n[128];
466         sprintf(n, "%d", global_parameters.toget);
467         ZOOM_connection_option_set(link, "count", n);
468     }
469     if (!databaseName || !*databaseName)
470         databaseName = "Default";
471     ZOOM_connection_option_set(link, "databaseName", databaseName);
472
473     ZOOM_connection_option_set(link, "presentChunk", "20");
474
475     if (cl->cqlquery)
476     {
477         ZOOM_query q = ZOOM_query_create();
478         ZOOM_query_cql(q, cl->cqlquery);
479         rs = ZOOM_connection_search(link, q);
480     }
481     else
482         rs = ZOOM_connection_search_pqf(link, cl->pquery);
483     connection_set_resultset(co, rs);
484     connection_continue(co);
485 }
486
487 struct client *client_create(void)
488 {
489     struct client *r;
490     if (client_freelist)
491     {
492         r = client_freelist;
493         client_freelist = client_freelist->next;
494     }
495     else
496         r = xmalloc(sizeof(struct client));
497     r->pquery = 0;
498     r->cqlquery = 0;
499     r->database = 0;
500     r->connection = 0;
501     r->session = 0;
502     r->hits = 0;
503     r->records = 0;
504     r->setno = 0;
505     r->requestid = -1;
506     r->diagnostic = 0;
507     r->state = Client_Disconnected;
508     r->show_raw = 0;
509     r->next = 0;
510     return r;
511 }
512
513 void client_destroy(struct client *c)
514 {
515     struct session *se = c->session;
516     if (c == se->clients)
517         se->clients = c->next;
518     else
519     {
520         struct client *cc;
521         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
522             ;
523         if (cc)
524             cc->next = c->next;
525     }
526     xfree(c->pquery);
527     xfree(c->cqlquery);
528
529     if (c->connection)
530         connection_release(c->connection);
531     c->next = client_freelist;
532     client_freelist = c;
533 }
534
535 void client_set_connection(struct client *cl, struct connection *con)
536 {
537     cl->connection = con;
538 }
539
540 void client_disconnect(struct client *cl)
541 {
542     if (cl->state != Client_Idle)
543         client_set_state(cl, Client_Disconnected);
544     client_set_connection(cl, 0);
545 }
546
547 // Extract terms from query into null-terminated termlist
548 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
549 {
550     int num = 0;
551
552     pull_terms(nmem, query, termlist, &num);
553     termlist[num] = 0;
554 }
555
556 // Initialize CCL map for a target
557 static CCL_bibset prepare_cclmap(struct client *cl)
558 {
559     struct session_database *sdb = client_get_database(cl);
560     struct setting *s;
561     CCL_bibset res;
562
563     if (!sdb->settings)
564         return 0;
565     res = ccl_qual_mk();
566     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
567     {
568         char *p = strchr(s->name + 3, ':');
569         if (!p)
570         {
571             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
572             ccl_qual_rm(&res);
573             return 0;
574         }
575         p++;
576         ccl_qual_fitem(res, s->value, p);
577     }
578     return res;
579 }
580
581 // returns a xmalloced CQL query corresponding to the pquery in client
582 static char *make_cqlquery(struct client *cl)
583 {
584     cql_transform_t cqlt = cql_transform_create();
585     Z_RPNQuery *zquery;
586     char *r;
587     WRBUF wrb = wrbuf_alloc();
588     int status;
589
590     zquery = p_query_rpn(global_parameters.odr_out, cl->pquery);
591     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
592     {
593         yaz_log(YLOG_WARN, "failed to generate CQL query, code=%d", status);
594         return 0;
595     }
596     r = xstrdup(wrbuf_cstr(wrb));
597
598     wrbuf_destroy(wrb);
599     odr_reset(global_parameters.odr_out); // releases the zquery
600     cql_transform_close(cqlt);
601     return r;
602 }
603
604 // Parse the query given the settings specific to this client
605 int client_parse_query(struct client *cl, const char *query)
606 {
607     struct session *se = client_get_session(cl);
608     struct session_database *sdb = client_get_database(cl);
609     struct ccl_rpn_node *cn;
610     int cerror, cpos;
611     CCL_bibset ccl_map = prepare_cclmap(cl);
612     const char *sru = session_setting_oneval(sdb, PZ_SRU);
613
614     if (!ccl_map)
615         return -1;
616
617     cn = ccl_find_str(ccl_map, query, &cerror, &cpos);
618     ccl_qual_rm(&ccl_map);
619     if (!cn)
620     {
621         cl->state = Client_Error;
622         yaz_log(YLOG_WARN, "Failed to parse query for %s",
623                          client_get_database(cl)->database->url);
624         return -1;
625     }
626     wrbuf_rewind(se->wrbuf);
627     ccl_pquery(se->wrbuf, cn);
628     xfree(cl->pquery);
629     cl->pquery = xstrdup(wrbuf_cstr(se->wrbuf));
630
631     xfree(cl->cqlquery);
632     if (*sru)
633     {
634         if (!(cl->cqlquery = make_cqlquery(cl)))
635             return -1;
636     }
637     else
638         cl->cqlquery = 0;
639
640     if (!se->relevance)
641     {
642         // Initialize relevance structure with query terms
643         char *p[512];
644         extract_terms(se->nmem, cn, p);
645         se->relevance = relevance_create(
646             global_parameters.server->relevance_pct,
647             se->nmem, (const char **) p,
648             se->expected_maxrecs);
649     }
650
651     ccl_rpn_delete(cn);
652     return 0;
653 }
654
655 void client_set_session(struct client *cl, struct session *se)
656 {
657     cl->session = se;
658     cl->next = se->clients;
659     se->clients = cl;
660 }
661
662 int client_is_active(struct client *cl)
663 {
664     if (cl->connection && (cl->state == Client_Continue ||
665                            cl->state == Client_Connecting ||
666                            cl->state == Client_Working))
667         return 1;
668     return 0;
669 }
670
671 struct client *client_next_in_session(struct client *cl)
672 {
673     if (cl)
674         return cl->next;
675     return 0;
676
677 }
678
679 int client_get_hits(struct client *cl)
680 {
681     return cl->hits;
682 }
683
684 int client_get_num_records(struct client *cl)
685 {
686     return cl->records;
687 }
688
689 int client_get_diagnostic(struct client *cl)
690 {
691     return cl->diagnostic;
692 }
693
694 void client_set_database(struct client *cl, struct session_database *db)
695 {
696     cl->database = db;
697 }
698
699 struct host *client_get_host(struct client *cl)
700 {
701     return client_get_database(cl)->database->host;
702 }
703
704 const char *client_get_url(struct client *cl)
705 {
706     return client_get_database(cl)->database->url;
707 }
708
709 /*
710  * Local variables:
711  * c-basic-offset: 4
712  * indent-tabs-mode: nil
713  * End:
714  * vim: shiftwidth=4 tabstop=8 expandtab
715  */