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