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