Fixes for URL path not being propagated for SRU requests
[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)
470         ZOOM_connection_option_set(link, "databaseName", databaseName);
471
472     ZOOM_connection_option_set(link, "presentChunk", "20");
473
474     if (cl->cqlquery)
475     {
476         ZOOM_query q = ZOOM_query_create();
477         ZOOM_query_cql(q, cl->cqlquery);
478         rs = ZOOM_connection_search(link, q);
479     }
480     else
481         rs = ZOOM_connection_search_pqf(link, cl->pquery);
482     connection_set_resultset(co, rs);
483     connection_continue(co);
484 }
485
486 struct client *client_create(void)
487 {
488     struct client *r;
489     if (client_freelist)
490     {
491         r = client_freelist;
492         client_freelist = client_freelist->next;
493     }
494     else
495         r = xmalloc(sizeof(struct client));
496     r->pquery = 0;
497     r->cqlquery = 0;
498     r->database = 0;
499     r->connection = 0;
500     r->session = 0;
501     r->hits = 0;
502     r->records = 0;
503     r->setno = 0;
504     r->requestid = -1;
505     r->diagnostic = 0;
506     r->state = Client_Disconnected;
507     r->show_raw = 0;
508     r->next = 0;
509     return r;
510 }
511
512 void client_destroy(struct client *c)
513 {
514     struct session *se = c->session;
515     if (c == se->clients)
516         se->clients = c->next;
517     else
518     {
519         struct client *cc;
520         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
521             ;
522         if (cc)
523             cc->next = c->next;
524     }
525     xfree(c->pquery);
526     xfree(c->cqlquery);
527
528     if (c->connection)
529         connection_release(c->connection);
530     c->next = client_freelist;
531     client_freelist = c;
532 }
533
534 void client_set_connection(struct client *cl, struct connection *con)
535 {
536     cl->connection = con;
537 }
538
539 void client_disconnect(struct client *cl)
540 {
541     if (cl->state != Client_Idle)
542         client_set_state(cl, Client_Disconnected);
543     client_set_connection(cl, 0);
544 }
545
546 // Extract terms from query into null-terminated termlist
547 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
548 {
549     int num = 0;
550
551     pull_terms(nmem, query, termlist, &num);
552     termlist[num] = 0;
553 }
554
555 // Initialize CCL map for a target
556 static CCL_bibset prepare_cclmap(struct client *cl)
557 {
558     struct session_database *sdb = client_get_database(cl);
559     struct setting *s;
560     CCL_bibset res;
561
562     if (!sdb->settings)
563         return 0;
564     res = ccl_qual_mk();
565     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
566     {
567         char *p = strchr(s->name + 3, ':');
568         if (!p)
569         {
570             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
571             ccl_qual_rm(&res);
572             return 0;
573         }
574         p++;
575         ccl_qual_fitem(res, s->value, p);
576     }
577     return res;
578 }
579
580 // returns a xmalloced CQL query corresponding to the pquery in client
581 static char *make_cqlquery(struct client *cl)
582 {
583     cql_transform_t cqlt = cql_transform_create();
584     Z_RPNQuery *zquery;
585     char *r;
586     WRBUF wrb = wrbuf_alloc();
587     int status;
588
589     zquery = p_query_rpn(global_parameters.odr_out, cl->pquery);
590     if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
591     {
592         yaz_log(YLOG_WARN, "failed to generate CQL query, code=%d", status);
593         return 0;
594     }
595     r = xstrdup(wrbuf_cstr(wrb));
596
597     wrbuf_destroy(wrb);
598     odr_reset(global_parameters.odr_out); // releases the zquery
599     cql_transform_close(cqlt);
600     return r;
601 }
602
603 // Parse the query given the settings specific to this client
604 int client_parse_query(struct client *cl, const char *query)
605 {
606     struct session *se = client_get_session(cl);
607     struct session_database *sdb = client_get_database(cl);
608     struct ccl_rpn_node *cn;
609     int cerror, cpos;
610     CCL_bibset ccl_map = prepare_cclmap(cl);
611     const char *sru = session_setting_oneval(sdb, PZ_SRU);
612
613     if (!ccl_map)
614         return -1;
615
616     cn = ccl_find_str(ccl_map, query, &cerror, &cpos);
617     ccl_qual_rm(&ccl_map);
618     if (!cn)
619     {
620         cl->state = Client_Error;
621         yaz_log(YLOG_WARN, "Failed to parse query for %s",
622                          client_get_database(cl)->database->url);
623         return -1;
624     }
625     wrbuf_rewind(se->wrbuf);
626     ccl_pquery(se->wrbuf, cn);
627     xfree(cl->pquery);
628     cl->pquery = xstrdup(wrbuf_cstr(se->wrbuf));
629
630     xfree(cl->cqlquery);
631     if (*sru)
632     {
633         if (!(cl->cqlquery = make_cqlquery(cl)))
634             return -1;
635     }
636     else
637         cl->cqlquery = 0;
638
639     if (!se->relevance)
640     {
641         // Initialize relevance structure with query terms
642         char *p[512];
643         extract_terms(se->nmem, cn, p);
644         se->relevance = relevance_create(
645             global_parameters.server->relevance_pct,
646             se->nmem, (const char **) p,
647             se->expected_maxrecs);
648     }
649
650     ccl_rpn_delete(cn);
651     return 0;
652 }
653
654 void client_set_session(struct client *cl, struct session *se)
655 {
656     cl->session = se;
657     cl->next = se->clients;
658     se->clients = cl;
659 }
660
661 int client_is_active(struct client *cl)
662 {
663     if (cl->connection && (cl->state == Client_Continue ||
664                            cl->state == Client_Connecting ||
665                            cl->state == Client_Working))
666         return 1;
667     return 0;
668 }
669
670 struct client *client_next_in_session(struct client *cl)
671 {
672     if (cl)
673         return cl->next;
674     return 0;
675
676 }
677
678 int client_get_hits(struct client *cl)
679 {
680     return cl->hits;
681 }
682
683 int client_get_num_records(struct client *cl)
684 {
685     return cl->records;
686 }
687
688 int client_get_diagnostic(struct client *cl)
689 {
690     return cl->diagnostic;
691 }
692
693 void client_set_database(struct client *cl, struct session_database *db)
694 {
695     cl->database = db;
696 }
697
698 struct host *client_get_host(struct client *cl)
699 {
700     return client_get_database(cl)->database->host;
701 }
702
703 const char *client_get_url(struct client *cl)
704 {
705     return client_get_database(cl)->database->url;
706 }
707
708 /*
709  * Local variables:
710  * c-basic-offset: 4
711  * indent-tabs-mode: nil
712  * End:
713  * vim: shiftwidth=4 tabstop=8 expandtab
714  */