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