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