Deal with targets that return negative hit counts.
[pazpar2-moved-to-github.git] / src / client.c
1 /* $Id: client.c,v 1.22 2007-09-19 13:23:35 adam Exp $
2    Copyright (c) 2006-2007, Index Data.
3
4 This file is part of Pazpar2.
5
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 /** \file client.c
23     \brief Z39.50 client 
24 */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <assert.h>
36
37 #include <yaz/marcdisp.h>
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/proto.h>
41 #include <yaz/readconf.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/nmem.h>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #include <yaz/oid_db.h>
49 #include <yaz/diagbib1.h>
50
51 #if HAVE_CONFIG_H
52 #include "cconfig.h"
53 #endif
54
55 #define USE_TIMING 0
56 #if USE_TIMING
57 #include <yaz/timing.h>
58 #endif
59
60 #include <netinet/in.h>
61
62 #include "pazpar2.h"
63
64 #include "client.h"
65 #include "connection.h"
66 #include "settings.h"
67
68 /** \brief Represents client state for a connection to one search target */
69 struct client {
70     struct session_database *database;
71     struct connection *connection;
72     struct session *session;
73     char *pquery; // Current search
74     int hits;
75     int records;
76     int setno;
77     int requestid;            // ID of current outstanding request
78     int diagnostic;
79     enum client_state state;
80     struct show_raw *show_raw;
81     struct client *next;     // next client in session or next in free list
82 };
83
84 struct show_raw {
85     int active; // whether this request has been sent to the server
86     int position;
87     char *syntax;
88     char *esn;
89     void (*error_handler)(void *data, const char *addinfo);
90     void (*record_handler)(void *data, const char *buf, size_t sz);
91     void *data;
92 };
93
94 static const char *client_states[] = {
95     "Client_Connecting",
96     "Client_Connected",
97     "Client_Idle",
98     "Client_Initializing",
99     "Client_Searching",
100     "Client_Presenting",
101     "Client_Error",
102     "Client_Failed",
103     "Client_Disconnected",
104     "Client_Stopped"
105 };
106
107 static struct client *client_freelist = 0;
108
109 static int send_apdu(struct client *c, Z_APDU *a)
110 {
111     struct session_database *sdb = client_get_database(c);
112     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
113     if (apdulog && *apdulog && *apdulog != '0')
114     {
115         ODR p = odr_createmem(ODR_PRINT);
116         yaz_log(YLOG_LOG, "send APDU %s", client_get_url(c));
117
118         odr_setprint(p, yaz_log_file());
119         z_APDU(p, &a, 0, 0);
120         odr_setprint(p, stderr);
121         odr_destroy(p);
122     }
123     return connection_send_apdu(client_get_connection(c), a);
124 }
125
126
127 const char *client_get_state_str(struct client *cl)
128 {
129     return client_states[cl->state];
130 }
131
132 enum client_state client_get_state(struct client *cl)
133 {
134     return cl->state;
135 }
136
137 void client_set_state(struct client *cl, enum client_state st)
138 {
139     cl->state = st;
140     if (cl->session)
141     {
142         int no_active = session_active_clients(cl->session);
143         if (no_active == 0)
144             session_alert_watch(cl->session, SESSION_WATCH_SHOW);
145     }
146 }
147
148 static void client_show_raw_error(struct client *cl, const char *addinfo);
149
150 // Close connection and set state to error
151 void client_fatal(struct client *cl)
152 {
153     client_show_raw_error(cl, "client connection failure");
154     yaz_log(YLOG_WARN, "Fatal error from %s", client_get_url(cl));
155     connection_destroy(cl->connection);
156     client_set_state(cl, Client_Error);
157 }
158
159
160 static int diag_to_wrbuf(Z_DiagRec **pp, int num, WRBUF w)
161 {
162     int code = 0;
163     int i;
164     for (i = 0; i<num; i++)
165     {
166         Z_DiagRec *p = pp[i];
167         if (i)
168             wrbuf_puts(w, "; ");
169         if (p->which != Z_DiagRec_defaultFormat)
170         {
171             wrbuf_puts(w, "? Not in default format");
172         }
173         else
174         {
175             Z_DefaultDiagFormat *r = p->u.defaultFormat;
176             
177             if (!r->diagnosticSetId)
178                 wrbuf_puts(w, "? Missing diagset");
179             else
180             {
181                 oid_class oclass;
182                 char diag_name_buf[OID_STR_MAX];
183                 const char *diag_name = 0;
184                 diag_name = yaz_oid_to_string_buf
185                     (r->diagnosticSetId, &oclass, diag_name_buf);
186                 wrbuf_puts(w, diag_name);
187             }
188             if (!code)
189                 code = *r->condition;
190             wrbuf_printf(w, " %d %s", *r->condition,
191                          diagbib1_str(*r->condition));
192             switch (r->which)
193             {
194             case Z_DefaultDiagFormat_v2Addinfo:
195                 wrbuf_printf(w, " -- v2 addinfo '%s'", r->u.v2Addinfo);
196                 break;
197             case Z_DefaultDiagFormat_v3Addinfo:
198                 wrbuf_printf(w, " -- v3 addinfo '%s'", r->u.v3Addinfo);
199                 break;
200             }
201         }
202     }
203     return code;
204 }
205
206
207
208 struct connection *client_get_connection(struct client *cl)
209 {
210     return cl->connection;
211 }
212
213 struct session_database *client_get_database(struct client *cl)
214 {
215     return cl->database;
216 }
217
218 struct session *client_get_session(struct client *cl)
219 {
220     return cl->session;
221 }
222
223 const char *client_get_pquery(struct client *cl)
224 {
225     return cl->pquery;
226 }
227
228 void client_set_requestid(struct client *cl, int id)
229 {
230     cl->requestid = id;
231 }
232
233 int client_show_raw_begin(struct client *cl, int position,
234                           const char *syntax, const char *esn,
235                           void *data,
236                           void (*error_handler)(void *data, const char *addinfo),
237                           void (*record_handler)(void *data, const char *buf,
238                                                  size_t sz))
239 {
240     if (cl->show_raw)
241         return -1;
242     cl->show_raw = xmalloc(sizeof(*cl->show_raw));
243     cl->show_raw->position = position;
244     cl->show_raw->active = 0;
245     cl->show_raw->data = data;
246     cl->show_raw->error_handler = error_handler;
247     cl->show_raw->record_handler = record_handler;
248     if (syntax)
249         cl->show_raw->syntax = xstrdup(syntax);
250     else
251         cl->show_raw->syntax = 0;
252     if (esn)
253         cl->show_raw->esn = xstrdup(esn);
254     else
255         cl->show_raw->esn = 0;
256     
257
258     if (cl->state == Client_Failed)
259     {
260         client_show_raw_error(cl, "client failed");
261     }
262     else if (cl->state == Client_Disconnected)
263     {
264         client_show_raw_error(cl, "client disconnected");
265     }
266     else
267     {
268         client_continue(cl);
269     }
270     return 0;
271 }
272
273 void client_show_raw_reset(struct client *cl)
274 {
275     xfree(cl->show_raw);
276     cl->show_raw = 0;
277 }
278
279 static void client_show_raw_error(struct client *cl, const char *addinfo)
280 {
281     if (cl->show_raw)
282     {
283         cl->show_raw->error_handler(cl->show_raw->data, addinfo);
284         client_show_raw_reset(cl);
285     }
286 }
287
288 static void client_show_raw_cancel(struct client *cl)
289 {
290     if (cl->show_raw)
291     {
292         cl->show_raw->error_handler(cl->show_raw->data, "cancel");
293         client_show_raw_reset(cl);
294     }
295 }
296
297 static void client_present_syntax(Z_APDU *a, const char *syntax)
298 {
299     // empty string for syntax OMITS preferredRecordSyntax (OPTIONAL)
300     if (syntax && *syntax)
301         a->u.presentRequest->preferredRecordSyntax =
302             yaz_string_to_oid_odr(yaz_oid_std(),
303                                   CLASS_RECSYN, syntax,
304                                   global_parameters.odr_out);
305 }
306
307 static void client_present_elements(Z_APDU *a, const char *elements)
308 {
309     if (elements && *elements)  // element set is optional
310     {
311         Z_ElementSetNames *elementSetNames =
312             odr_malloc(global_parameters.odr_out, sizeof(*elementSetNames));
313         Z_RecordComposition *compo = 
314             odr_malloc(global_parameters.odr_out, sizeof(*compo));
315         a->u.presentRequest->recordComposition = compo;
316
317         compo->which = Z_RecordComp_simple;
318         compo->u.simple = elementSetNames;
319
320         elementSetNames->which = Z_ElementSetNames_generic;
321         elementSetNames->u.generic = 
322             odr_strdup(global_parameters.odr_out, elements);
323     }
324 }
325
326 void client_send_raw_present(struct client *cl)
327 {
328     struct session_database *sdb = client_get_database(cl);
329     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
330     int toget = 1;
331     int start = cl->show_raw->position;
332     const char *syntax = 0;
333     const char *elements = 0;
334
335     assert(cl->show_raw);
336
337     yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
338             client_get_url(cl), toget, start);
339
340     a->u.presentRequest->resultSetStartPoint = &start;
341     a->u.presentRequest->numberOfRecordsRequested = &toget;
342
343     if (cl->show_raw->syntax)
344         syntax = cl->show_raw->syntax;
345     else
346         syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
347
348     client_present_syntax(a, syntax);
349     if (cl->show_raw->esn)
350         elements = cl->show_raw->esn;
351     else
352         elements = session_setting_oneval(sdb, PZ_ELEMENTS);
353     client_present_elements(a, elements);
354
355     if (send_apdu(cl, a) >= 0)
356     {
357         cl->show_raw->active = 1;
358         cl->state = Client_Presenting;
359     }
360     else
361     {
362         client_show_raw_error(cl, "send_apdu failed");
363         cl->state = Client_Error;
364     }
365     odr_reset(global_parameters.odr_out);
366 }
367
368 void client_send_present(struct client *cl)
369 {
370     struct session_database *sdb = client_get_database(cl);
371     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
372     int toget;
373     int start = cl->records + 1;
374     const char *syntax = 0;
375     const char *elements = 0;
376
377     toget = global_parameters.chunk;
378     if (toget > global_parameters.toget - cl->records)
379         toget = global_parameters.toget - cl->records;
380     if (toget > cl->hits - cl->records)
381         toget = cl->hits - cl->records;
382
383     yaz_log(YLOG_DEBUG, "Trying to present %d record(s) from %d",
384             toget, start);
385
386     a->u.presentRequest->resultSetStartPoint = &start;
387     a->u.presentRequest->numberOfRecordsRequested = &toget;
388
389     syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
390     client_present_syntax(a, syntax);
391
392     elements = session_setting_oneval(sdb, PZ_ELEMENTS);
393     client_present_elements(a, elements);
394
395     if (send_apdu(cl, a) >= 0)
396         cl->state = Client_Presenting;
397     else
398         cl->state = Client_Error;
399     odr_reset(global_parameters.odr_out);
400 }
401
402
403 void client_send_search(struct client *cl)
404 {
405     struct session *se = client_get_session(cl);
406     struct session_database *sdb = client_get_database(cl);
407     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
408     int ndb;
409     char **databaselist;
410     Z_Query *zquery;
411     int ssub = 0, lslb = 100000, mspn = 10;
412     const char *piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK);
413     const char *queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING);
414
415     yaz_log(YLOG_DEBUG, "Sending search to %s", sdb->database->url);
416
417     
418     // constructing RPN query
419     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
420                                                     sizeof(Z_Query));
421     zquery->which = Z_Query_type_1;
422     zquery->u.type_1 = p_query_rpn(global_parameters.odr_out, 
423                                    client_get_pquery(cl));
424
425     // converting to target encoding
426     if (queryenc && *queryenc)
427     {
428         yaz_iconv_t iconv = yaz_iconv_open(queryenc, "UTF-8");
429         if (iconv){
430             yaz_query_charset_convert_rpnquery(zquery->u.type_1, 
431                                                global_parameters.odr_out, 
432                                                iconv);
433             yaz_iconv_close(iconv);
434         } else
435             yaz_log(YLOG_WARN, "Query encoding failed %s %s", 
436                     client_get_database(cl)->database->url, queryenc);
437     }
438
439     for (ndb = 0; sdb->database->databases[ndb]; ndb++)
440         ;
441     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
442     for (ndb = 0; sdb->database->databases[ndb]; ndb++)
443         databaselist[ndb] = sdb->database->databases[ndb];
444
445     if (!piggyback || *piggyback == '1')
446     {
447         const char *elements = session_setting_oneval(sdb, PZ_ELEMENTS);
448         const char *recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
449         if (recsyn && *recsyn)
450         {
451             a->u.searchRequest->preferredRecordSyntax =
452                 yaz_string_to_oid_odr(yaz_oid_std(),
453                                       CLASS_RECSYN, recsyn,
454                                       global_parameters.odr_out);
455         }
456         if (elements && *elements)
457         {
458             Z_ElementSetNames *esn =
459                 odr_malloc(global_parameters.odr_out, sizeof(*esn));
460             esn->which = Z_ElementSetNames_generic;
461             esn->u.generic = odr_strdup(global_parameters.odr_out, elements);
462
463             a->u.searchRequest->smallSetElementSetNames = esn;
464             a->u.searchRequest->mediumSetElementSetNames = esn;
465         }
466         a->u.searchRequest->smallSetUpperBound = &ssub;
467         a->u.searchRequest->largeSetLowerBound = &lslb;
468         a->u.searchRequest->mediumSetPresentNumber = &mspn;
469     }
470     a->u.searchRequest->databaseNames = databaselist;
471     a->u.searchRequest->num_databaseNames = ndb;
472
473     
474     {  //scope for sending and logging queries 
475         WRBUF wbquery = wrbuf_alloc();
476         yaz_query_to_wrbuf(wbquery, a->u.searchRequest->query);
477
478
479         if (send_apdu(cl, a) >= 0)
480         {
481             client_set_state(cl, Client_Searching);
482             client_set_requestid(cl, se->requestid);
483             yaz_log(YLOG_LOG, "SearchRequest %s %s %s", 
484                     client_get_database(cl)->database->url,
485                     queryenc ? queryenc : "UTF-8",
486                     wrbuf_cstr(wbquery));
487         }
488         else {
489             client_set_state(cl, Client_Error);
490             yaz_log(YLOG_WARN, "Failed SearchRequest %s  %s %s", 
491                     client_get_database(cl)->database->url, 
492                     queryenc ? queryenc : "UTF-8",
493                     wrbuf_cstr(wbquery));
494         }
495         
496         wrbuf_destroy(wbquery);
497     }    
498
499     odr_reset(global_parameters.odr_out);
500 }
501
502 void client_init_response(struct client *cl, Z_APDU *a)
503 {
504     Z_InitResponse *r = a->u.initResponse;
505
506     yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
507
508     if (*r->result)
509         cl->state = Client_Idle;
510     else
511         cl->state = Client_Failed; // FIXME need to do something to the connection
512 }
513
514
515 static void ingest_raw_records(struct client *cl, Z_Records *r)
516 {
517     Z_NamePlusRecordList *rlist;
518     Z_NamePlusRecord *npr;
519     xmlDoc *doc;
520     xmlChar *buf_out;
521     int len_out;
522     if (r->which != Z_Records_DBOSD)
523     {
524         client_show_raw_error(cl, "non-surrogate diagnostics");
525         return;
526     }
527
528     rlist = r->u.databaseOrSurDiagnostics;
529     if (rlist->num_records != 1 || !rlist->records || !rlist->records[0])
530     {
531         client_show_raw_error(cl, "no records");
532         return;
533     }
534     npr = rlist->records[0];
535     if (npr->which != Z_NamePlusRecord_databaseRecord)
536     {
537         client_show_raw_error(cl, "surrogate diagnostic");
538         return;
539     }
540
541     doc = record_to_xml(client_get_database(cl), npr->u.databaseRecord);
542     if (!doc)
543     {
544         client_show_raw_error(cl, "unable to convert record to xml");
545         return;
546     }
547
548     xmlDocDumpMemory(doc, &buf_out, &len_out);
549     xmlFreeDoc(doc);
550
551     cl->show_raw->record_handler(cl->show_raw->data,
552                                  (const char *) buf_out, len_out);
553     
554     xmlFree(buf_out);
555     xfree(cl->show_raw);
556     cl->show_raw = 0;
557 }
558
559 static void ingest_records(struct client *cl, Z_Records *r)
560 {
561 #if USE_TIMING
562     yaz_timing_t t = yaz_timing_create();
563 #endif
564     struct record *rec;
565     struct session *s = client_get_session(cl);
566     Z_NamePlusRecordList *rlist;
567     int i;
568
569     if (r->which != Z_Records_DBOSD)
570         return;
571     rlist = r->u.databaseOrSurDiagnostics;
572     for (i = 0; i < rlist->num_records; i++)
573     {
574         Z_NamePlusRecord *npr = rlist->records[i];
575
576         cl->records++;
577         if (npr->which != Z_NamePlusRecord_databaseRecord)
578         {
579             yaz_log(YLOG_WARN, 
580                     "Unexpected record type, probably diagnostic %s",
581                     cl->database->database->url);
582             continue;
583         }
584
585         rec = ingest_record(cl, npr->u.databaseRecord, cl->records);
586         if (!rec)
587             continue;
588     }
589     if (rlist->num_records)
590         session_alert_watch(s, SESSION_WATCH_SHOW);
591     if (rlist->num_records)
592         session_alert_watch(s, SESSION_WATCH_RECORD);
593
594 #if USE_TIMING
595     yaz_timing_stop(t);
596     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
597             yaz_timing_get_real(t), yaz_timing_get_user(t),
598             yaz_timing_get_sys(t));
599     yaz_timing_destroy(&t);
600 #endif
601 }
602
603
604 void client_search_response(struct client *cl, Z_APDU *a)
605 {
606     struct session *se = cl->session;
607     Z_SearchResponse *r = a->u.searchResponse;
608
609     yaz_log(YLOG_DEBUG, "Search response %s (status=%d)", 
610             cl->database->database->url, *r->searchStatus);
611
612     if (*r->searchStatus)
613     {
614         cl->hits = *r->resultCount;
615         if (cl->hits < 0)
616         {
617             yaz_log(YLOG_WARN, "Target %s returns hit count %d",
618                     cl->database->database->url, cl->hits);
619         }
620         else
621             se->total_hits += cl->hits;
622         if (r->presentStatus && !*r->presentStatus && r->records)
623         {
624             yaz_log(YLOG_DEBUG, "Records in search response %s", 
625                     cl->database->database->url);
626             ingest_records(cl, r->records);
627         }
628         cl->state = Client_Idle;
629     }
630     else
631     {          /*"FAILED"*/
632         Z_Records *recs = r->records;
633         cl->hits = 0;
634         cl->state = Client_Error;
635         if (recs && recs->which == Z_Records_NSD)
636         {
637             WRBUF w = wrbuf_alloc();
638
639             Z_DiagRec dr, *dr_p = &dr;
640             dr.which = Z_DiagRec_defaultFormat;
641             dr.u.defaultFormat = recs->u.nonSurrogateDiagnostic;
642             
643             wrbuf_printf(w, "Search response NSD %s: ",
644                          cl->database->database->url);
645             
646             cl->diagnostic = diag_to_wrbuf(&dr_p, 1, w);
647
648             yaz_log(YLOG_WARN, "%s", wrbuf_cstr(w));
649
650             cl->state = Client_Error;
651             wrbuf_destroy(w);
652         }
653         else if (recs && recs->which == Z_Records_multipleNSD)
654         {
655             WRBUF w = wrbuf_alloc();
656
657             wrbuf_printf(w, "Search response multipleNSD %s: ",
658                          cl->database->database->url);
659             cl->diagnostic = 
660                 diag_to_wrbuf(recs->u.multipleNonSurDiagnostics->diagRecs,
661                               recs->u.multipleNonSurDiagnostics->num_diagRecs,
662                               w);
663             yaz_log(YLOG_WARN, "%s", wrbuf_cstr(w));
664             cl->state = Client_Error;
665             wrbuf_destroy(w);
666         }
667     }
668 }
669
670 void client_present_response(struct client *cl, Z_APDU *a)
671 {
672     Z_PresentResponse *r = a->u.presentResponse;
673     Z_Records *recs = r->records;
674         
675     if (recs && recs->which == Z_Records_NSD)
676     {
677         WRBUF w = wrbuf_alloc();
678         
679         Z_DiagRec dr, *dr_p = &dr;
680         dr.which = Z_DiagRec_defaultFormat;
681         dr.u.defaultFormat = recs->u.nonSurrogateDiagnostic;
682         
683         wrbuf_printf(w, "Present response NSD %s: ",
684                      cl->database->database->url);
685         
686         cl->diagnostic = diag_to_wrbuf(&dr_p, 1, w);
687         
688         yaz_log(YLOG_WARN, "%s", wrbuf_cstr(w));
689         
690         cl->state = Client_Error;
691         wrbuf_destroy(w);
692
693         client_show_raw_error(cl, "non surrogate diagnostics");
694     }
695     else if (recs && recs->which == Z_Records_multipleNSD)
696     {
697         WRBUF w = wrbuf_alloc();
698         
699         wrbuf_printf(w, "Present response multipleNSD %s: ",
700                      cl->database->database->url);
701         cl->diagnostic = 
702             diag_to_wrbuf(recs->u.multipleNonSurDiagnostics->diagRecs,
703                           recs->u.multipleNonSurDiagnostics->num_diagRecs,
704                           w);
705         yaz_log(YLOG_WARN, "%s", wrbuf_cstr(w));
706         cl->state = Client_Error;
707         wrbuf_destroy(w);
708     }
709     else if (recs && !*r->presentStatus && cl->state != Client_Error)
710     {
711         yaz_log(YLOG_DEBUG, "Good Present response %s",
712                 cl->database->database->url);
713
714         // we can mix show raw and normal show ..
715         if (cl->show_raw && cl->show_raw->active)
716         {
717             cl->show_raw->active = 0; // no longer active
718             ingest_raw_records(cl, recs);
719         }
720         else
721             ingest_records(cl, recs);
722         cl->state = Client_Idle;
723     }
724     else if (*r->presentStatus) 
725     {
726         yaz_log(YLOG_WARN, "Bad Present response %s",
727                 cl->database->database->url);
728         cl->state = Client_Error;
729         client_show_raw_error(cl, "bad present response");
730     }
731 }
732
733 void client_close_response(struct client *cl, Z_APDU *a)
734 {
735     struct connection *co = cl->connection;
736     /* Z_Close *r = a->u.close; */
737
738     yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
739
740     cl->state = Client_Failed;
741     connection_destroy(co);
742 }
743
744 int client_is_our_response(struct client *cl)
745 {
746     struct session *se = client_get_session(cl);
747
748     if (cl && (cl->requestid == se->requestid || 
749                cl->state == Client_Initializing))
750         return 1;
751     return 0;
752 }
753
754 // Set authentication token in init if one is set for the client
755 // TODO: Extend this to handle other schemes than open (should be simple)
756 static void init_authentication(struct client *cl, Z_InitRequest *req)
757 {
758     struct session_database *sdb = client_get_database(cl);
759     const char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
760
761     if (*auth)
762     {
763         struct connection *co = client_get_connection(cl);
764         struct session *se = client_get_session(cl);
765         Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
766                 sizeof(*idAuth));
767         idAuth->which = Z_IdAuthentication_open;
768         idAuth->u.open = odr_strdup(global_parameters.odr_out, auth);
769         req->idAuthentication = idAuth;
770         connection_set_authentication(co, nmem_strdup(se->session_nmem, auth));
771     }
772 }
773
774 static void init_zproxy(struct client *cl, Z_InitRequest *req)
775 {
776     struct session_database *sdb = client_get_database(cl);
777     char *ztarget = sdb->database->url;
778     //char *ztarget = sdb->url;    
779     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
780     
781     if (*zproxy)
782         yaz_oi_set_string_oid(&req->otherInfo,
783                               global_parameters.odr_out,
784                               yaz_oid_userinfo_proxy,
785                               1, ztarget);
786 }
787
788
789 static void client_init_request(struct client *cl)
790 {
791     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
792
793     a->u.initRequest->implementationId = global_parameters.implementationId;
794     a->u.initRequest->implementationName = global_parameters.implementationName;
795     a->u.initRequest->implementationVersion =
796         global_parameters.implementationVersion;
797     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
798     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
799     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
800
801     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
802     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
803     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
804
805     init_authentication(cl, a->u.initRequest);
806     init_zproxy(cl, a->u.initRequest);
807
808     if (send_apdu(cl, a) >= 0)
809         client_set_state(cl, Client_Initializing);
810     else
811         client_set_state(cl, Client_Error);
812     odr_reset(global_parameters.odr_out);
813 }
814
815 void client_continue(struct client *cl)
816 {
817     if (cl->state == Client_Connected) {
818         client_init_request(cl);
819     }
820     if (cl->state == Client_Idle)
821     {
822         struct session *se = client_get_session(cl);
823         if (cl->requestid != se->requestid && cl->pquery) {
824             // we'll have to abort this because result set is to be deleted
825             client_show_raw_cancel(cl);   
826             client_send_search(cl);
827         }
828         else if (cl->show_raw)
829         {
830             client_send_raw_present(cl);
831         }
832         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
833             cl->records < cl->hits) {
834             client_send_present(cl);
835         }
836     }
837 }
838
839 struct client *client_create(void)
840 {
841     struct client *r;
842     if (client_freelist)
843     {
844         r = client_freelist;
845         client_freelist = client_freelist->next;
846     }
847     else
848         r = xmalloc(sizeof(struct client));
849     r->pquery = 0;
850     r->database = 0;
851     r->connection = 0;
852     r->session = 0;
853     r->hits = 0;
854     r->records = 0;
855     r->setno = 0;
856     r->requestid = -1;
857     r->diagnostic = 0;
858     r->state = Client_Disconnected;
859     r->show_raw = 0;
860     r->next = 0;
861     return r;
862 }
863
864 void client_destroy(struct client *c)
865 {
866     struct session *se = c->session;
867     if (c == se->clients)
868         se->clients = c->next;
869     else
870     {
871         struct client *cc;
872         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
873             ;
874         if (cc)
875             cc->next = c->next;
876     }
877     xfree(c->pquery);
878
879     if (c->connection)
880         connection_release(c->connection);
881     c->next = client_freelist;
882     client_freelist = c;
883 }
884
885 void client_set_connection(struct client *cl, struct connection *con)
886 {
887     cl->connection = con;
888 }
889
890 void client_disconnect(struct client *cl)
891 {
892     if (cl->state != Client_Idle)
893         cl->state = Client_Disconnected;
894     client_set_connection(cl, 0);
895 }
896
897 // Extract terms from query into null-terminated termlist
898 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
899 {
900     int num = 0;
901
902     pull_terms(nmem, query, termlist, &num);
903     termlist[num] = 0;
904 }
905
906 // Initialize CCL map for a target
907 static CCL_bibset prepare_cclmap(struct client *cl)
908 {
909     struct session_database *sdb = client_get_database(cl);
910     struct setting *s;
911     CCL_bibset res;
912
913     if (!sdb->settings)
914         return 0;
915     res = ccl_qual_mk();
916     for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
917     {
918         char *p = strchr(s->name + 3, ':');
919         if (!p)
920         {
921             yaz_log(YLOG_WARN, "Malformed cclmap name: %s", s->name);
922             ccl_qual_rm(&res);
923             return 0;
924         }
925         p++;
926         ccl_qual_fitem(res, s->value, p);
927     }
928     return res;
929 }
930
931 // Parse the query given the settings specific to this client
932 int client_parse_query(struct client *cl, const char *query)
933 {
934     struct session *se = client_get_session(cl);
935     struct ccl_rpn_node *cn;
936     int cerror, cpos;
937     CCL_bibset ccl_map = prepare_cclmap(cl);
938
939     if (!ccl_map)
940         return -1;
941
942     cn = ccl_find_str(ccl_map, query, &cerror, &cpos);
943     ccl_qual_rm(&ccl_map);
944     if (!cn)
945     {
946         cl->state = Client_Error;
947         yaz_log(YLOG_WARN, "Failed to parse query for %s",
948                          client_get_database(cl)->database->url);
949         return -1;
950     }
951     wrbuf_rewind(se->wrbuf);
952     ccl_pquery(se->wrbuf, cn);
953     xfree(cl->pquery);
954     cl->pquery = xstrdup(wrbuf_cstr(se->wrbuf));
955
956     if (!se->relevance)
957     {
958         // Initialize relevance structure with query terms
959         char *p[512];
960         extract_terms(se->nmem, cn, p);
961         se->relevance = relevance_create(
962             global_parameters.server->relevance_pct,
963             se->nmem, (const char **) p,
964             se->expected_maxrecs);
965     }
966
967     ccl_rpn_delete(cn);
968     return 0;
969 }
970
971 void client_set_session(struct client *cl, struct session *se)
972 {
973     cl->session = se;
974     cl->next = se->clients;
975     se->clients = cl;
976 }
977
978 int client_is_active(struct client *cl)
979 {
980     if (cl->connection && (cl->state == Client_Connecting ||
981                            cl->state == Client_Initializing ||
982                            cl->state == Client_Searching ||
983                            cl->state == Client_Presenting))
984         return 1;
985     return 0;
986 }
987
988 struct client *client_next_in_session(struct client *cl)
989 {
990     if (cl)
991         return cl->next;
992     return 0;
993
994 }
995
996 int client_get_hits(struct client *cl)
997 {
998     return cl->hits;
999 }
1000
1001 int client_get_num_records(struct client *cl)
1002 {
1003     return cl->records;
1004 }
1005
1006 int client_get_diagnostic(struct client *cl)
1007 {
1008     return cl->diagnostic;
1009 }
1010
1011 void client_set_database(struct client *cl, struct session_database *db)
1012 {
1013     cl->database = db;
1014 }
1015
1016 struct host *client_get_host(struct client *cl)
1017 {
1018     return client_get_database(cl)->database->host;
1019 }
1020
1021 const char *client_get_url(struct client *cl)
1022 {
1023     return client_get_database(cl)->database->url;
1024 }
1025
1026 /*
1027  * Local variables:
1028  * c-basic-offset: 4
1029  * indent-tabs-mode: nil
1030  * End:
1031  * vim: shiftwidth=4 tabstop=8 expandtab
1032  */