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