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