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