The pre-init stage honors max-sockets as well.
[yazproxy-moved-to-github.git] / src / yaz-proxy.cpp
1 /* $Id: yaz-proxy.cpp,v 1.78 2008-02-21 09:33:23 adam Exp $
2    Copyright (c) 1998-2008, Index Data.
3
4 This file is part of the yazproxy.
5
6 YAZ proxy 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 YAZ proxy 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 YAZ proxy; 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 #ifdef WIN32
23 #define HAVE_SYS_STAT_H 1
24 #define HAVE_SYS_TYPES_H 1
25 #endif
26
27 #if HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #if HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #if HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #if HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39
40 #include <assert.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include <fcntl.h>
44
45 #include <yaz/srw.h>
46 #include <yaz/marcdisp.h>
47 #include <yaz/yaz-iconv.h>
48 #include <yaz/log.h>
49 #include <yaz/diagbib1.h>
50 #include "proxyp.h"
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/charneg.h>
54 #include <yaz/oid_db.h>
55 #include "msg-thread.h"
56
57 using namespace yazpp_1;
58
59 #ifdef WIN32
60 #define strncasecmp _strnicmp
61 #endif
62
63 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
64 public:
65     int m_ret;
66     IMsg_Thread *handle();
67     void result();
68     Yaz_Proxy *m_proxy;
69     NMEM m_nmem;
70     char *m_apdu_buf;
71     int m_apdu_len;
72     Auth_Msg();
73     virtual ~Auth_Msg();
74 };
75
76 Auth_Msg::Auth_Msg()
77 {
78     m_nmem = nmem_create();
79 }
80
81 Auth_Msg::~Auth_Msg()
82 {
83     nmem_destroy(m_nmem);
84 }
85
86 IMsg_Thread *Auth_Msg::handle()
87 {
88     ODR decode = odr_createmem(ODR_DECODE);
89     Z_APDU *apdu;
90
91     odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
92     int r = z_APDU(decode, &apdu, 0, 0);
93     if (!r)
94     {
95         yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
96     }
97     else
98     {
99         m_ret = m_proxy->handle_authentication(apdu);
100     }
101     odr_destroy(decode);
102     return this;
103 }
104
105 void Auth_Msg::result()
106 {
107     if (m_proxy->dec_ref())
108     {
109         yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
110     }
111     else
112     {
113         odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
114         Z_APDU *apdu = 0;
115         int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
116         if (!r)
117             yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
118         m_proxy->result_authentication(apdu, m_ret);
119     }
120     delete this;
121 }
122
123 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
124 {
125     if (apdu == 0 || ret == 0)
126     {
127         Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
128         *apdu_reject->u.initResponse->result = 0;
129         send_to_client(apdu_reject);
130         dec_ref();
131     }
132     else
133     {
134         if (apdu->which == Z_APDU_initRequest)
135         {
136             Yaz_ProxyConfig *cfg = check_reconfigure();
137             if (cfg)
138                 cfg->target_authentication(m_default_target, odr_encode(), 
139                                            apdu->u.initRequest);
140         }
141         handle_incoming_Z_PDU_2(apdu);
142     }
143 }
144
145 static const char *apdu_name(Z_APDU *apdu)
146 {
147     switch (apdu->which)
148     {
149     case Z_APDU_initRequest:
150         return "initRequest";
151     case Z_APDU_initResponse:
152         return "initResponse";
153     case Z_APDU_searchRequest:
154         return "searchRequest";
155     case Z_APDU_searchResponse:
156         return "searchResponse";
157     case Z_APDU_presentRequest:
158         return "presentRequest";
159     case Z_APDU_presentResponse:
160         return "presentResponse";
161     case Z_APDU_deleteResultSetRequest:
162         return "deleteResultSetRequest";
163     case Z_APDU_deleteResultSetResponse:
164         return "deleteResultSetResponse";
165     case Z_APDU_scanRequest:
166         return "scanRequest";
167     case Z_APDU_scanResponse:
168         return "scanResponse";
169     case Z_APDU_sortRequest:
170         return "sortRequest";
171     case Z_APDU_sortResponse:
172         return "sortResponse";
173     case Z_APDU_extendedServicesRequest:
174         return "extendedServicesRequest";
175     case Z_APDU_extendedServicesResponse:
176         return "extendedServicesResponse";
177     case Z_APDU_close:
178         return "close";
179     }
180     return "other";
181 }
182
183 static const char *gdu_name(Z_GDU *gdu)
184 {
185     switch(gdu->which)
186     {
187     case Z_GDU_Z3950:
188         return apdu_name(gdu->u.z3950);
189     case Z_GDU_HTTP_Request:
190         return "HTTP Request";
191     case Z_GDU_HTTP_Response:
192         return "HTTP Response";
193     }
194     return "Unknown request/response";
195 }
196
197 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
198                      ISocketObservable *the_socket_observable,
199                      Yaz_Proxy *parent)
200     :
201     Z_Assoc(the_PDU_Observable),
202     m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
203 {
204     m_PDU_Observable = the_PDU_Observable;
205     m_socket_observable = the_socket_observable;
206     m_client = 0;
207     m_parent = parent;
208     m_clientPool = 0;
209     m_seqno = 1;
210     m_keepalive_limit_bw = 500000;
211     m_keepalive_limit_pdu = 1000;
212     m_proxyTarget = 0;
213     m_default_target = 0;
214     m_proxy_negotiation_charset = 0;
215     m_proxy_negotiation_lang = 0;
216     m_proxy_negotiation_default_charset = 0;
217     m_charset_converter = new Yaz_CharsetConverter;
218     m_max_clients = 150;
219     m_log_mask = 0;
220     m_seed = time(0);
221     m_client_idletime = 600;
222     m_target_idletime = 600;
223     m_max_sockets = 1024;
224     m_optimize = xstrdup ("1");
225     strcpy(m_session_str, "0 ");
226     m_session_no = 0;
227     m_bytes_sent = 0;
228     m_bytes_recv = 0;
229     m_bw_max = 0;
230     m_pdu_max = 0;
231     m_search_max = 0;
232     m_max_connect = 0;
233     m_max_connect_period = 0;
234     m_limit_connect = 0;
235     m_limit_connect_period = 0;
236     m_timeout_mode = timeout_normal;
237     m_timeout_gdu = 0;
238     m_max_record_retrieve = 0;
239     m_reconfig_flag = 0;
240     m_config_fname = 0;
241     m_request_no = 0;
242     m_flag_invalid_session = 0;
243     m_referenceId = 0;
244     m_referenceId_mem = nmem_create();
245     m_config = 0;
246     m_marcxml_mode = none;
247     m_stylesheet_xsp = 0;
248     m_stylesheet_nprl = 0;
249     m_stylesheet_apdu = 0;
250     m_s2z_stylesheet = 0;
251     m_s2z_database = 0;
252     m_schema = 0;
253     m_backend_type = 0;
254     m_backend_charset = 0;
255     m_frontend_type[0] = -1;
256     m_initRequest_apdu = 0;
257     m_initRequest_mem = 0;
258     m_initRequest_preferredMessageSize = 0;
259     m_initRequest_maximumRecordSize = 0;
260     m_initRequest_options = 0;
261     m_initRequest_version = 0;
262     m_initRequest_oi_negotiation_charsets = 0;
263     m_initRequest_oi_negotiation_num_charsets = 0;
264     m_initRequest_oi_negotiation_langs = 0;
265     m_initRequest_oi_negotiation_num_langs = 0;
266     m_initRequest_oi_negotiation_selected = 0;
267     m_apdu_invalid_session = 0;
268     m_mem_invalid_session = 0;
269     m_s2z_odr_init = 0;
270     m_s2z_odr_search = 0;
271     m_s2z_init_apdu = 0;
272     m_s2z_search_apdu = 0;
273     m_s2z_present_apdu = 0;
274     m_http_keepalive = 0;
275     m_http_version = 0;
276     m_soap_ns = 0;
277     m_s2z_packing = Z_SRW_recordPacking_string;
278 #if HAVE_GETTIMEOFDAY
279     m_time_tv = xmalloc(sizeof(struct timeval));
280     struct timeval *tv = (struct timeval *) m_time_tv;
281     tv->tv_sec = 0;
282     tv->tv_usec = 0;
283 #else
284     m_time_tv = 0;
285 #endif
286     m_usemarcon_ini_stage1 = 0;
287     m_usemarcon_ini_stage2 = 0;
288     m_usemarcon = new Yaz_usemarcon();
289     if (!m_parent)
290         low_socket_open();
291     m_my_thread = 0;
292     m_ref_count = 1;
293     m_main_ptr_dec = false;
294     m_peername = 0;
295     m_num_msg_threads = 0;
296 }
297
298 void Yaz_Proxy::inc_ref()
299 {
300     m_ref_count++;
301 }
302
303 Yaz_Proxy::~Yaz_Proxy()
304 {
305     yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
306             m_bytes_sent, m_bytes_recv);
307     nmem_destroy(m_initRequest_mem);
308     nmem_destroy(m_mem_invalid_session);
309     nmem_destroy(m_referenceId_mem);
310
311     xfree(m_proxyTarget);
312     xfree(m_default_target);
313     xfree(m_proxy_negotiation_charset);
314     xfree(m_proxy_negotiation_lang);
315     xfree(m_proxy_negotiation_default_charset);
316     delete m_charset_converter;
317     xfree(m_optimize);
318
319 #if YAZ_HAVE_XSLT
320     if (m_stylesheet_xsp)
321         xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
322 #endif
323     xfree (m_time_tv);
324
325     xfree (m_peername);
326     xfree (m_schema);
327     xfree (m_backend_type);
328     xfree (m_backend_charset);
329     xfree (m_usemarcon_ini_stage1);
330     xfree (m_usemarcon_ini_stage2);
331     delete m_usemarcon;
332     if (m_s2z_odr_init)
333         odr_destroy(m_s2z_odr_init);
334     if (m_s2z_odr_search)
335         odr_destroy(m_s2z_odr_search);
336     if (!m_parent)
337         low_socket_close();
338     if (!m_parent)
339         delete m_my_thread;
340     delete m_config;
341 }
342
343 void Yaz_Proxy::set_debug_mode(int mode)
344 {
345     m_debug_mode = mode;
346 }
347
348 int Yaz_Proxy::set_config(const char *config)
349 {
350     delete m_config;
351     m_config = new Yaz_ProxyConfig();
352     xfree(m_config_fname);
353     m_config_fname = xstrdup(config);
354     int r = m_config->read_xml(config);
355     if (!r)
356     {
357         int period = 60;
358         m_config->get_generic_info(&m_log_mask, &m_max_clients,
359                                    &m_max_connect, &m_limit_connect, &period,
360                                    &m_num_msg_threads);
361         m_connect.set_period(period);
362     }
363     return r;
364 }
365
366 void Yaz_Proxy::set_default_target(const char *target)
367 {
368     xfree (m_default_target);
369     m_default_target = 0;
370     if (target)
371         m_default_target = (char *) xstrdup (target);
372 }
373
374 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
375                                        const char *default_charset)
376 {
377     yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
378         "default charset to '%s', language to '%s'", m_session_str, 
379         charset?charset:"none",
380         default_charset?default_charset:"none",
381         lang?lang:"none");
382     xfree (m_proxy_negotiation_charset);
383     xfree (m_proxy_negotiation_lang);
384     m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
385     if (charset)
386         m_proxy_negotiation_charset = (char *) xstrdup (charset);
387     if (lang)
388         m_proxy_negotiation_lang = (char *) xstrdup (lang);
389     if (default_charset)
390         m_proxy_negotiation_default_charset =
391             (char *) xstrdup (default_charset);
392 }
393
394 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
395 {
396     if (m_parent)
397         return m_parent->check_reconfigure();
398
399     Yaz_ProxyConfig *cfg = m_config;
400     if (m_reconfig_flag)
401     {
402         yaz_log(YLOG_LOG, "reconfigure");
403         if (m_config_fname && cfg)
404         {
405             yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
406             int r = cfg->read_xml(m_config_fname);
407             if (r)
408                 yaz_log(YLOG_WARN, "reconfigure failed");
409             else
410             {
411                 m_log_mask = 0;
412                 int period = 60;
413                 cfg->get_generic_info(&m_log_mask, &m_max_clients,
414                                       &m_max_connect, &m_limit_connect,
415                                       &period, &m_num_msg_threads);
416                 m_connect.set_period(period);
417             }
418         }
419         else
420             yaz_log(YLOG_LOG, "reconfigure");
421         m_reconfig_flag = 0;
422     }
423     return cfg;
424 }
425
426 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
427                                         *the_PDU_Observable, int fd)
428 {
429     check_reconfigure();
430
431     char session_str[200];
432     const char *peername = the_PDU_Observable->getpeername();
433     if (!peername)
434         peername = "nullpeer";
435
436     if (m_log_mask & PROXY_LOG_IP_CLIENT)
437         sprintf(session_str, "%ld:%d %.80s %d ",
438                 (long) time(0), m_session_no, peername, 0);
439     else
440         sprintf(session_str, "%ld:%d %d ",
441                 (long) time(0), m_session_no, 0);
442     m_session_no++;
443
444     yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
445
446     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
447                                          m_socket_observable, this);
448
449     new_proxy->m_config = 0;
450     new_proxy->m_config_fname = 0;
451     new_proxy->timeout(m_client_idletime);
452     new_proxy->m_target_idletime = m_target_idletime;
453     new_proxy->set_default_target(m_default_target);
454     new_proxy->m_max_clients = m_max_clients;
455     new_proxy->m_log_mask = m_log_mask;
456     new_proxy->m_session_no = m_session_no;
457     new_proxy->m_num_msg_threads = m_num_msg_threads;
458
459 #if 0
460     // in case we want to watch a particular client..
461     if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
462         new_proxy->m_log_mask = 255;
463 #endif
464
465     new_proxy->set_APDU_log(get_APDU_log());
466     if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
467         new_proxy->set_APDU_yazlog(1);
468     else
469         new_proxy->set_APDU_yazlog(0);
470     strcpy(new_proxy->m_session_str, session_str);
471     new_proxy->m_peername = xstrdup(peername);
472     new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
473         m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
474     // create thread object the first time we get an incoming connection
475     if (!m_my_thread && m_num_msg_threads > 0)
476     {
477         yaz_log (YLOG_LOG, "%sStarting message thread management. number=%d",
478                  session_str, m_num_msg_threads);
479         m_my_thread = new Msg_Thread(m_socket_observable, m_num_msg_threads);
480     }
481     new_proxy->m_my_thread = m_my_thread;
482     return new_proxy;
483 }
484
485 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
486 {
487     Z_OtherInformationUnit *oi =
488         update_otherInformation(otherInfo, 0, yaz_oid_userinfo_cookie, 1, 1);
489     
490     if (oi && oi->which == Z_OtherInfo_characterInfo)
491         return oi->information.characterInfo;
492     return 0;
493 }
494
495 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
496 {
497     Z_OtherInformationUnit *oi =
498         update_otherInformation(otherInfo, 0, yaz_oid_userinfo_proxy, 1, 1);
499     
500     if (oi && oi->which == Z_OtherInfo_characterInfo)
501         return oi->information.characterInfo;
502     return 0;
503 }
504 const char *Yaz_Proxy::load_balance(const char **url)
505 {
506     int zurl_in_use[MAX_ZURL_PLEX];
507     int zurl_in_spare[MAX_ZURL_PLEX];
508     Yaz_ProxyClient *c;
509     int i;
510
511     for (i = 0; i<MAX_ZURL_PLEX; i++)
512     {
513         zurl_in_use[i] = 0;
514         zurl_in_spare[i] = 0;
515     }
516     for (c = m_parent->m_clientPool; c; c = c->m_next)
517     {
518         for (i = 0; url[i]; i++)
519             if (!strcmp(url[i], c->get_hostname()))
520             {
521                 zurl_in_use[i]++;
522                 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
523                     zurl_in_spare[i]++;
524             }
525     }
526     int min_use = 100000;
527     int spare_for_min = 0;
528     int max_spare = 0;
529     const char *ret_min = 0;
530     const char *ret_spare = 0;
531     for (i = 0; url[i]; i++)
532     {
533         yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
534                 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
535         if (min_use > zurl_in_use[i])
536         {
537             ret_min = url[i];
538             min_use = zurl_in_use[i];
539             spare_for_min = zurl_in_spare[i];
540         }
541         if (max_spare < zurl_in_spare[i])
542         {
543             ret_spare = url[i];
544             max_spare = zurl_in_spare[i];
545         }
546     }
547     return ret_min;
548 }
549
550 int Yaz_Proxy::get_number_of_connections()
551 {
552     int no_connections = 0;
553     Yaz_ProxyClient *c;
554
555     for (c = m_parent->m_clientPool; c; c = c->m_next)
556     {
557         assert(c->m_prev);
558         assert(*c->m_prev == c);
559         if (!strcmp(m_proxyTarget, c->get_hostname()))
560         {
561             no_connections++;
562         }
563     }
564     yaz_log (YLOG_LOG, "%sExisting %s connections: %d", m_session_str, m_proxyTarget,
565         no_connections);
566     return no_connections;
567 }
568
569 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
570                                        const char *proxy_host, int *http_code)
571 {
572     assert (m_parent);
573     Yaz_Proxy *parent = m_parent;
574     Yaz_ProxyClient *c = m_client;
575
576     if (!m_proxyTarget)
577     {
578         const char *url[MAX_ZURL_PLEX];
579         Yaz_ProxyConfig *cfg = check_reconfigure();
580         if (proxy_host)
581         {
582             if (parent && parent->m_debug_mode)
583             {
584                 // only to be enabled for debugging...
585                 if (!strcmp(proxy_host, "stop"))
586                     exit(0);
587             }
588             xfree(m_default_target);
589             m_default_target = xstrdup(proxy_host);
590         }
591         proxy_host = m_default_target;
592         int client_idletime = -1;
593         const char *cql2rpn_fname = 0;
594         const char *negotiation_charset = 0;
595         const char *negotiation_lang = 0;
596         const char *query_charset = 0;
597         const char *default_client_query_charset = 0;
598         url[0] = m_default_target;
599         url[1] = 0;
600         if (cfg)
601         {
602             int pre_init = 0;
603             cfg->get_target_info(proxy_host, url, &m_bw_max,
604                                  &m_pdu_max, &m_max_record_retrieve,
605                                  &m_search_max,
606                                  &m_target_idletime, &client_idletime,
607                                  &m_max_sockets,
608                                  &parent->m_max_clients,
609                                  &m_keepalive_limit_bw,
610                                  &m_keepalive_limit_pdu,
611                                  &pre_init,
612                                  &cql2rpn_fname,
613                                  &negotiation_charset,
614                                  &negotiation_lang,
615                                  &query_charset,
616                                  &default_client_query_charset);
617         }
618         if (client_idletime != -1)
619         {
620             m_client_idletime = client_idletime;
621             timeout(m_client_idletime);
622         }
623
624         // get those FILE descriptors available 
625         m_parent->low_socket_close();
626         if (cql2rpn_fname)
627             m_cql2rpn.set_pqf_file(cql2rpn_fname);
628         // reserve them again
629         m_parent->low_socket_open();
630         
631         if (negotiation_charset || negotiation_lang || default_client_query_charset)
632         {
633             set_proxy_negotiation(negotiation_charset,
634                 negotiation_lang, default_client_query_charset);
635         }
636         m_charset_converter->set_target_query_charset(query_charset);
637         if (!url[0])
638         {
639             yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
640             return 0;
641         }
642         // we don't handle multiplexing for cookie session, so we just
643         // pick the first one in this case (anonymous users will be able
644         // to use any backend)
645         if (cookie && *cookie)
646             m_proxyTarget = (char*) xstrdup(url[0]);
647         else
648             m_proxyTarget = (char*) xstrdup(load_balance(url));
649     }
650     if (cookie && *cookie)
651     {   // search in sessions with a cookie
652         for (c = parent->m_clientPool; c; c = c->m_next)
653         {
654             assert (c->m_prev);
655             assert (*c->m_prev == c);
656             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
657                 !strcmp(m_proxyTarget, c->get_hostname()))
658             {
659                 // Found it in cache
660                 // The following handles "cancel"
661                 // If connection is busy (waiting for PDU) and
662                 // we have an initRequest we can safely do re-open
663                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
664                 {
665                     yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
666                              c->get_hostname());
667                     c->close();
668                     c->m_init_flag = 0;
669
670                     c->m_last_ok = 0;
671                     c->m_cache.clear();
672                     c->m_last_resultCount = 0;
673                     c->m_sr_transform = 0;
674                     c->m_waiting = 0;
675                     c->m_resultSetStartPoint = 0;
676                     c->m_target_idletime = m_target_idletime;
677                     if (c->client(m_proxyTarget))
678                     {
679                         delete c;
680                         return 0;
681                     }
682                     c->timeout(30);
683                 }
684                 c->m_seqno = parent->m_seqno;
685                 if (c->m_server && c->m_server != this)
686                     c->m_server->m_client = 0;
687                 c->m_server = this;
688                 (parent->m_seqno)++;
689                 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
690                 return c;
691             }
692         }
693     }
694     else if (!c && apdu->which == Z_APDU_initRequest )
695     {
696         // anonymous sessions without cookie.
697         // if authentication is set it is NOT anonymous se we can't share them.
698         // If charset and lang negotiation is use it is NOT anonymous session too.
699         for (c = parent->m_clientPool; c; c = c->m_next)
700         {
701             assert(c->m_prev);
702             assert(*c->m_prev == c);
703             if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0 
704                 && c->compare_idAuthentication(apdu)
705                 && c->compare_charset(apdu)
706                 && !strcmp(m_proxyTarget, c->get_hostname()))
707             {
708                 // found it in cache
709                 yaz_log (YLOG_LOG, "%sREUSE %d %s",
710                          m_session_str, parent->m_seqno, c->get_hostname());
711                 
712                 c->m_seqno = parent->m_seqno;
713                 assert(c->m_server == 0);
714                 c->m_server = this;
715
716                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
717                     c->set_APDU_yazlog(1);
718                 else
719                     c->set_APDU_yazlog(0);
720
721                 (parent->m_seqno)++;
722
723                 parent->pre_init();
724
725                 return c;
726             }
727         }
728     }
729     if (!m_client)
730     {
731         if (apdu->which != Z_APDU_initRequest)
732         {
733             yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
734             *http_code = 500;
735             return 0;
736         }
737
738         int no_in_use = get_number_of_connections();
739         if (no_in_use >= m_max_sockets)
740         {
741             yaz_log (YLOG_LOG, "%smax sockets reached %d", m_session_str,
742                 m_max_sockets);
743             *http_code = 500;
744             return 0;
745         }
746         // go through list of clients - and find the lowest/oldest one.
747         Yaz_ProxyClient *c_min = 0;
748         int min_seq = -1;
749         int no_of_clients = 0;
750         if (parent->m_clientPool)
751             yaz_log (YLOG_DEBUG, "Existing sessions");
752         for (c = parent->m_clientPool; c; c = c->m_next)
753         {
754             yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
755                                c->m_waiting, c->get_hostname(),
756                                c->m_cookie ? c->m_cookie : "");
757             no_of_clients++;
758             if (min_seq < 0 || c->m_seqno < min_seq)
759             {
760                 min_seq = c->m_seqno;
761                 c_min = c;
762             }
763         }
764         if (no_of_clients >= parent->m_max_clients)
765         {
766             c = c_min;
767             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
768             {
769                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
770                          m_session_str, parent->m_max_clients, c->m_seqno);
771                 if (c->m_server && c->m_server != this)
772                     c->m_server->dec_ref();
773             }
774             else
775             {
776                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
777                          m_session_str, parent->m_max_clients,
778                          c->m_seqno, parent->m_seqno, c->get_hostname());
779                 xfree (c->m_cookie);
780                 c->m_cookie = 0;
781                 if (cookie)
782                     c->m_cookie = xstrdup(cookie);
783                 c->m_seqno = parent->m_seqno;
784                 if (c->m_server && c->m_server != this)
785                 {
786                     c->m_server->m_client = 0;
787                     c->m_server->dec_ref();
788                 }
789                 (parent->m_seqno)++;
790                 c->m_target_idletime = m_target_idletime;
791                 c->timeout(m_target_idletime);
792
793                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
794                     c->set_APDU_yazlog(1);
795                 else
796                     c->set_APDU_yazlog(0);
797
798                 return c;
799             }
800         }
801         else
802         {
803
804             yaz_log (YLOG_LOG, "%sNEW %d %s",
805                      m_session_str, parent->m_seqno, m_proxyTarget);
806             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
807             c->m_next = parent->m_clientPool;
808             if (c->m_next)
809                 c->m_next->m_prev = &c->m_next;
810             parent->m_clientPool = c;
811             c->m_prev = &parent->m_clientPool;
812         }
813
814         xfree (c->m_cookie);
815         c->m_cookie = 0;
816         if (cookie)
817             c->m_cookie = xstrdup(cookie);
818
819         c->m_seqno = parent->m_seqno;
820         c->m_init_flag = 0;
821         c->m_last_resultCount = 0;
822         c->m_last_ok = 0;
823         c->m_cache.clear();
824         c->m_sr_transform = 0;
825         c->m_waiting = 0;
826         c->m_resultSetStartPoint = 0;
827         (parent->m_seqno)++;
828         if (c->client(m_proxyTarget))
829         {
830             delete c;
831             return 0;
832         }
833         c->m_target_idletime = m_target_idletime;
834         c->timeout(30);
835
836         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
837             c->set_APDU_yazlog(1);
838         else
839             c->set_APDU_yazlog(0);
840
841         c->set_idAuthentication(apdu);
842     }
843     yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
844     return c;
845 }
846
847 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
848 {
849     int i;
850     for (i = 0; i<num; i++)
851     {
852         Z_DefaultDiagFormat *r;
853         Z_DiagRec *p = pp[i];
854         if (p->which != Z_DiagRec_defaultFormat)
855         {
856             yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
857             return;
858         }
859         else
860             r = p->u.defaultFormat;
861         switch (r->which)
862         {
863         case Z_DefaultDiagFormat_v2Addinfo:
864             yaz_log(YLOG_LOG, "%sError %d %s:%s",
865                     m_session_str,
866                     *r->condition, diagbib1_str(*r->condition),
867                     r->u.v2Addinfo);
868             break;
869         case Z_DefaultDiagFormat_v3Addinfo:
870             yaz_log(YLOG_LOG, "%sError %d %s:%s",
871                     m_session_str,
872                     *r->condition, diagbib1_str(*r->condition),
873                     r->u.v3Addinfo);
874             break;
875         }
876     }
877 }
878
879 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
880 {
881     if (!m_stylesheet_xsp || p->num_records <= 0)
882     {
883         return 0;  /* no XSLT to be done ... */
884     }
885
886     m_stylesheet_offset = 0;
887     m_stylesheet_nprl = p;
888     m_stylesheet_apdu = apdu;
889     m_timeout_mode = timeout_xsl;
890
891     timeout(0);
892     return 1;
893 }
894
895 void Yaz_Proxy::convert_xsl_delay()
896 {
897 #if YAZ_HAVE_XSLT
898     Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
899     if (npr->which == Z_NamePlusRecord_databaseRecord)
900     {
901         Z_External *r = npr->u.databaseRecord;
902         if (r->which == Z_External_octet)
903         {
904 #if 0
905             fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
906 #endif
907             xmlDocPtr res, doc = xmlParseMemory(
908                 (char*) r->u.octet_aligned->buf,
909                 r->u.octet_aligned->len);
910
911
912             yaz_log(YLOG_LOG, "%sXSLT convert %d",
913                     m_session_str, m_stylesheet_offset);
914             res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
915                                       doc, 0);
916
917             if (res)
918             {
919                 xmlChar *out_buf;
920                 int out_len;
921                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
922                 m_stylesheet_nprl->records[m_stylesheet_offset]->
923                     u.databaseRecord =
924                     z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
925                                      (char*) out_buf, out_len);
926                 xmlFree(out_buf);
927                 xmlFreeDoc(res);
928             }
929
930             xmlFreeDoc(doc);
931         }
932     }
933 #endif
934     m_stylesheet_offset++;
935     if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
936     {
937         m_timeout_mode = timeout_normal;
938         m_stylesheet_nprl = 0;
939 #if YAZ_HAVE_XSLT
940         if (m_stylesheet_xsp)
941             xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
942 #endif
943         m_stylesheet_xsp = 0;
944         timeout(m_client_idletime);
945         send_PDU_convert(m_stylesheet_apdu);
946     }
947     else
948         timeout(0);
949 }
950
951 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
952 {
953     if (m_frontend_type[0] != -1)
954     {
955         int i;
956         for (i = 0; i < p->num_records; i++)
957         {
958             Z_NamePlusRecord *npr = p->records[i];
959             if (npr->which == Z_NamePlusRecord_databaseRecord)
960             {
961                 Z_External *r = npr->u.databaseRecord;
962                 if (r->which == Z_External_octet)
963                 {
964 #if HAVE_USEMARCON
965                     if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
966                     {
967                         if (!m_usemarcon->m_stage1)
968                         {
969                             m_usemarcon->m_stage1 = new CDetails();
970                         }
971                         m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
972                         m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
973                         int res = m_usemarcon->m_stage1->Start();
974                         if (res == 0)
975                         {
976                             char *converted;
977                             int convlen;
978                             m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
979                             if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
980                             {
981                                 if (!m_usemarcon->m_stage2)
982                                 {
983                                     m_usemarcon->m_stage2 = new CDetails();
984                                 }
985                                 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
986                                 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
987                                 res = m_usemarcon->m_stage2->Start();
988                                 if (res == 0)
989                                 {
990                                     free(converted);
991                                     m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
992                                 }
993                                 else
994                                 {
995                                     yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
996                                 }
997                             }
998                             npr->u.databaseRecord =
999                                 z_ext_record_oid(odr_encode(),
1000                                                  m_frontend_type,
1001                                                  converted,
1002                                                  strlen(converted));
1003                             free(converted);
1004                         }
1005                         else
1006                         {
1007                             yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
1008                         }
1009                         continue;
1010                     }
1011 #endif
1012 /* HAVE_USEMARCON */
1013                     npr->u.databaseRecord =
1014                         z_ext_record_oid(odr_encode(),
1015                                          m_frontend_type,
1016                                          (char*) r->u.octet_aligned->buf,
1017                                          r->u.octet_aligned->len);
1018                 }
1019             }
1020         }
1021     }
1022 }
1023
1024 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1025                                         const char *backend_charset)
1026 {
1027     int sel =   m_charset_converter->get_client_charset_selected();
1028     const char *client_record_charset =
1029         m_charset_converter->get_client_query_charset();
1030     if (sel && backend_charset && client_record_charset &&
1031         strcmp(backend_charset, client_record_charset))
1032     {
1033         int i;
1034         yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1035                                         backend_charset);
1036         yaz_marc_t mt = yaz_marc_create();
1037         yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1038         yaz_marc_iconv(mt, cd);
1039         for (i = 0; i < p->num_records; i++)
1040         {
1041             Z_NamePlusRecord *npr = p->records[i];
1042             if (npr->which == Z_NamePlusRecord_databaseRecord)
1043             {
1044                 Z_External *r = npr->u.databaseRecord;
1045                 const Odr_oid *oid = r->direct_reference;
1046                 if (!oid)
1047                     continue;
1048
1049                 if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
1050                 {
1051                     WRBUF w = wrbuf_alloc();
1052
1053                     wrbuf_iconv_write(w, cd,  (char*) r->u.octet_aligned->buf,
1054                                       r->u.octet_aligned->len);
1055                     npr->u.databaseRecord =
1056                         z_ext_record_oid(odr_encode(), oid, wrbuf_buf(w),
1057                                          wrbuf_len(w));
1058                     wrbuf_destroy(w);
1059                 }
1060                 else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
1061                 {
1062                     ;
1063                 }
1064                 else if (r->which == Z_External_octet)
1065                 {
1066                     size_t rlen;
1067                     const char *result;
1068                     if (yaz_marc_decode_buf(mt,
1069                                             (char*) r->u.octet_aligned->buf,
1070                                             r->u.octet_aligned->len,
1071                                             &result, &rlen))
1072                     {
1073                         npr->u.databaseRecord =
1074                             z_ext_record_oid(odr_encode(), oid, result, rlen);
1075                         yaz_log(YLOG_LOG, "%sRecoding MARC record",
1076                                 m_session_str);
1077                     }
1078                 }
1079             }
1080         }
1081         if (cd)
1082             yaz_iconv_close(cd);
1083         yaz_marc_destroy(mt);
1084     }
1085 }
1086
1087 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1088                                    const char *backend_charset)
1089 {
1090     int i;
1091     if (!backend_charset)
1092         backend_charset = "MARC-8";
1093     yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1094     yaz_marc_t mt = yaz_marc_create();
1095     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1096     yaz_marc_iconv(mt, cd);
1097     for (i = 0; i < p->num_records; i++)
1098     {
1099         Z_NamePlusRecord *npr = p->records[i];
1100         if (npr->which == Z_NamePlusRecord_databaseRecord)
1101         {
1102             Z_External *r = npr->u.databaseRecord;
1103             if (r->which == Z_External_OPAC)
1104             {
1105                 WRBUF w = wrbuf_alloc();
1106
1107                 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1108                 npr->u.databaseRecord = z_ext_record_oid(
1109                     odr_encode(), yaz_oid_recsyn_xml,
1110                     wrbuf_buf(w), wrbuf_len(w));
1111                 wrbuf_destroy(w);
1112             }
1113             else if (r->which == Z_External_octet)
1114             {
1115                 size_t rlen;
1116                 const char *result;
1117                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1118                                         r->u.octet_aligned->len,
1119                                         &result, &rlen))
1120                 {
1121                     npr->u.databaseRecord =
1122                         z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
1123                                          result, rlen);
1124                 }
1125             }
1126         }
1127     }
1128     if (cd)
1129         yaz_iconv_close(cd);
1130     yaz_marc_destroy(mt);
1131 }
1132
1133 void Yaz_Proxy::logtime()
1134 {
1135 #if HAVE_GETTIMEOFDAY
1136     struct timeval *tv = (struct timeval*) m_time_tv;
1137     if (tv->tv_sec)
1138     {
1139         struct timeval tv1;
1140         gettimeofday(&tv1, 0);
1141         long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1142             (tv1.tv_usec - tv->tv_usec);
1143         if (diff >= 0)
1144             yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1145                     diff/1000000, (diff/1000)%1000);
1146     }
1147     tv->tv_sec = 0;
1148     tv->tv_usec = 0;
1149 #endif
1150 }
1151
1152 int Yaz_Proxy::send_http_response(int code)
1153 {
1154     ODR o = odr_encode();
1155     Z_GDU *gdu = z_get_HTTP_Response(o, code);
1156     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1157     if (m_http_version)
1158         hres->version = odr_strdup(o, m_http_version);
1159     if (m_http_keepalive)
1160         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1161     else
1162         timeout(0);
1163     if (code == 401)
1164         z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", 
1165                           "Basic realm=\"YAZ Proxy\"");
1166
1167
1168     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1169     {
1170         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1171                  gdu_name(gdu));
1172     }
1173     int len;
1174     int r = send_GDU(gdu, &len);
1175     m_bytes_sent += len;
1176     m_bw_stat.add_bytes(len);
1177     logtime();
1178
1179     recv_GDU_more(true);
1180
1181     return r;
1182 }
1183
1184 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1185 {
1186     ODR o = odr_encode();
1187     const char *ctype = "text/xml";
1188     Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1189     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1190     if (m_http_version)
1191         hres->version = odr_strdup(o, m_http_version);
1192     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1193     if (m_http_keepalive)
1194         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1195     else
1196         timeout(0);
1197     if (http_code == 401)
1198         z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1199
1200     static Z_SOAP_Handler soap_handlers[2] = {
1201 #if YAZ_HAVE_XSLT
1202         {"http://www.loc.gov/zing/srw/", 0,
1203          (Z_SOAP_fun) yaz_srw_codec},
1204 #endif
1205         {0, 0, 0}
1206     };
1207
1208     Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1209     soap_package->which = Z_SOAP_generic;
1210     soap_package->u.generic =
1211         (Z_SOAP_Generic *) odr_malloc(o,  sizeof(*soap_package->u.generic));
1212     soap_package->u.generic->no = 0;
1213     soap_package->u.generic->ns = soap_handlers[0].ns;
1214     soap_package->u.generic->p = (void *) srw_pdu;
1215     soap_package->ns = m_soap_ns;
1216     z_soap_codec_enc_xsl(o, &soap_package,
1217                          &hres->content_buf, &hres->content_len,
1218                          soap_handlers, 0, m_s2z_stylesheet);
1219     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1220     {
1221         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1222                  gdu_name(gdu));
1223     }
1224     int len;
1225     int r = send_GDU(gdu, &len);
1226     m_bytes_sent += len;
1227     m_bw_stat.add_bytes(len);
1228     logtime();
1229
1230     recv_GDU_more(true);
1231
1232     return r;
1233 }
1234
1235 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1236 {
1237     ODR o = odr_encode();
1238     Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1239         odr_malloc(o, sizeof(*diagnostic));
1240     int num_diagnostic = 1;
1241     yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1242     return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1243 }
1244
1245 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1246                              Z_DefaultDiagFormat *ddf)
1247 {
1248     int bib1_code = *ddf->condition;
1249     if (bib1_code == 109)
1250         return 404;
1251     srw_res->num_diagnostics = 1;
1252     srw_res->diagnostics = (Z_SRW_diagnostic *)
1253         odr_malloc(o, sizeof(*srw_res->diagnostics));
1254     yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1255                           yaz_diag_bib1_to_srw(*ddf->condition),
1256                           ddf->u.v2Addinfo);
1257     return 0;
1258 }
1259
1260 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1261 {
1262     ODR o = odr_encode();
1263     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1264     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1265
1266     srw_res->numberOfRecords = odr_intdup (o, hits);
1267     if (records && records->which == Z_Records_DBOSD)
1268     {
1269         srw_res->num_records =
1270             records->u.databaseOrSurDiagnostics->num_records;
1271         int i;
1272         srw_res->records = (Z_SRW_record *)
1273             odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1274         for (i = 0; i < srw_res->num_records; i++)
1275         {
1276             Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1277             if (npr->which != Z_NamePlusRecord_databaseRecord)
1278             {
1279                 srw_res->records[i].recordSchema = "diagnostic";
1280                 srw_res->records[i].recordPacking = m_s2z_packing;
1281                 srw_res->records[i].recordData_buf = "67";
1282                 srw_res->records[i].recordData_len = 2;
1283                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1284                 continue;
1285             }
1286             Z_External *r = npr->u.databaseRecord;
1287
1288             if (r->which == Z_External_octet 
1289                 && !oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
1290             {
1291                 srw_res->records[i].recordSchema = m_schema;
1292                 srw_res->records[i].recordPacking = m_s2z_packing;
1293                 srw_res->records[i].recordData_buf = (char*)
1294                     r->u.octet_aligned->buf;
1295                 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1296                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1297             }
1298             else
1299             {
1300                 srw_res->records[i].recordSchema = "diagnostic";
1301                 srw_res->records[i].recordPacking = m_s2z_packing;
1302                 srw_res->records[i].recordData_buf = "67";
1303                 srw_res->records[i].recordData_len = 2;
1304                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1305             }
1306         }
1307     }
1308     if (records && records->which == Z_Records_NSD)
1309     {
1310         int http_code;
1311         http_code = z_to_srw_diag(odr_encode(), srw_res,
1312                                    records->u.nonSurrogateDiagnostic);
1313         if (http_code)
1314             return send_http_response(http_code);
1315     }
1316     return send_srw_response(srw_pdu);
1317
1318 }
1319
1320 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1321                                         int num_diagnostics, int http_code /* = 200 */)
1322 {
1323     ODR o = odr_encode();
1324     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1325     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1326
1327     srw_res->num_diagnostics = num_diagnostics;
1328     srw_res->diagnostics = diagnostics;
1329     return send_srw_response(srw_pdu, http_code);
1330 }
1331
1332 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1333                                         int num_diagnostics)
1334 {
1335     Yaz_ProxyConfig *cfg = check_reconfigure();
1336     if (cfg)
1337     {
1338         int len;
1339         char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1340                                        m_s2z_database, &len);
1341         if (b)
1342         {
1343             Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1344             Z_SRW_explainResponse *er = res->u.explain_response;
1345
1346             er->record.recordData_buf = b;
1347             er->record.recordData_len = len;
1348             er->record.recordPacking = m_s2z_packing;
1349             er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1350
1351             er->diagnostics = diagnostics;
1352             er->num_diagnostics = num_diagnostics;
1353             return send_srw_response(res);
1354         }
1355     }
1356     return send_http_response(404);
1357 }
1358
1359 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1360 {
1361     if (m_http_version)
1362     {
1363         if (apdu->which == Z_APDU_initResponse)
1364         {
1365             Z_InitResponse *res = apdu->u.initResponse;
1366             if (*res->result == 0)
1367             {
1368                 send_to_srw_client_error(3, 0);
1369             }
1370             else if (!m_s2z_search_apdu)
1371             {
1372                 send_srw_explain_response(0, 0);
1373             }
1374             else
1375             {
1376                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1377             }
1378         }
1379         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1380         {
1381             m_s2z_search_apdu = 0;
1382             Z_SearchResponse *res = apdu->u.searchResponse;
1383             m_s2z_hit_count = *res->resultCount;
1384             if (res->records && res->records->which == Z_Records_NSD)
1385             {
1386                 send_to_srw_client_ok(0, res->records, 1);
1387             }
1388             else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1389             {
1390                 // adjust
1391                 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1392
1393                 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1394                 {
1395                     if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1396                         > m_s2z_hit_count)
1397                         *pr->numberOfRecordsRequested =
1398                             1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1399                 }
1400                 handle_incoming_Z_PDU(m_s2z_present_apdu);
1401             }
1402             else
1403             {
1404                 m_s2z_present_apdu = 0;
1405                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1406             }
1407         }
1408         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1409         {
1410             int start =
1411                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1412
1413             m_s2z_present_apdu = 0;
1414             Z_PresentResponse *res = apdu->u.presentResponse;
1415             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1416         }
1417     }
1418     else
1419     {
1420         int len = 0;
1421         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1422             yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1423                      apdu_name(apdu));
1424         int r = send_Z_PDU(apdu, &len);
1425         m_bytes_sent += len;
1426         m_bw_stat.add_bytes(len);
1427         logtime();
1428         return r;
1429     }
1430     return 0;
1431 }
1432
1433 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1434 {
1435     int kill_session = 0;
1436     Z_ReferenceId **new_id = get_referenceIdP(apdu);
1437
1438     if (new_id)
1439         *new_id = m_referenceId;
1440
1441     if (apdu->which == Z_APDU_searchResponse)
1442     {
1443         Z_SearchResponse *sr = apdu->u.searchResponse;
1444         Z_Records *p = sr->records;
1445         if (p && p->which == Z_Records_NSD)
1446         {
1447             Z_DiagRec dr, *dr_p = &dr;
1448             dr.which = Z_DiagRec_defaultFormat;
1449             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1450
1451             *sr->searchStatus = 0;
1452             display_diagrecs(&dr_p, 1);
1453         }
1454         else
1455         {
1456             if (p && p->which == Z_Records_DBOSD)
1457             {
1458                 if (m_backend_type
1459 #if HAVE_USEMARCON
1460                     || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1461 #endif
1462                     )
1463                     convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1464                 if (m_marcxml_mode == marcxml)
1465                     convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1466                                        m_backend_charset);
1467                 else
1468                     convert_records_charset(p->u.databaseOrSurDiagnostics,
1469                                             m_backend_charset);
1470                 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1471                     return 0;
1472
1473             }
1474             if (sr->resultCount)
1475             {
1476                 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1477                         *sr->resultCount);
1478                 if (*sr->resultCount < 0)
1479                 {
1480                     m_flag_invalid_session = 1;
1481                     kill_session = 1;
1482
1483                     *sr->searchStatus = 0;
1484                     sr->records =
1485                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1486                     *sr->resultCount = 0;
1487                 }
1488             }
1489         }
1490     }
1491     else if (apdu->which == Z_APDU_presentResponse)
1492     {
1493         Z_PresentResponse *sr = apdu->u.presentResponse;
1494         Z_Records *p = sr->records;
1495         if (p && p->which == Z_Records_NSD)
1496         {
1497             Z_DiagRec dr, *dr_p = &dr;
1498             dr.which = Z_DiagRec_defaultFormat;
1499             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1500             if (*sr->presentStatus == Z_PresentStatus_success)
1501                 *sr->presentStatus = Z_PresentStatus_failure;
1502             display_diagrecs(&dr_p, 1);
1503         }
1504         if (p && p->which == Z_Records_DBOSD)
1505         {
1506             if (m_backend_type
1507 #if HAVE_USEMARCON
1508                 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1509 #endif
1510                 )
1511                 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1512             if (m_marcxml_mode == marcxml)
1513                 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1514                                    m_backend_charset);
1515             else
1516                 convert_records_charset(p->u.databaseOrSurDiagnostics,
1517                                         m_backend_charset);
1518             if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1519                 return 0;
1520         }
1521     }
1522     else if (apdu->which == Z_APDU_initResponse)
1523     {
1524         //Get and check negotiation record
1525         //from init response.
1526         handle_charset_lang_negotiation(apdu);
1527
1528         if (m_initRequest_options)
1529         {
1530             Z_Options *nopt =
1531                 (Odr_bitmask *)odr_malloc(odr_encode(),
1532                                           sizeof(Odr_bitmask));
1533             ODR_MASK_ZERO(nopt);
1534
1535             int i;
1536             for (i = 0; i<24; i++)
1537                 if (ODR_MASK_GET(m_initRequest_options, i) &&
1538                     ODR_MASK_GET(apdu->u.initResponse->options, i))
1539                     ODR_MASK_SET(nopt, i);
1540             apdu->u.initResponse->options = nopt;
1541         }
1542         if (m_initRequest_version)
1543         {
1544             Z_ProtocolVersion *nopt =
1545                 (Odr_bitmask *)odr_malloc(odr_encode(),
1546                                           sizeof(Odr_bitmask));
1547             ODR_MASK_ZERO(nopt);
1548
1549             int i;
1550             for (i = 0; i<8; i++)
1551                 if (ODR_MASK_GET(m_initRequest_version, i) &&
1552                     ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1553                     ODR_MASK_SET(nopt, i);
1554             apdu->u.initResponse->protocolVersion = nopt;
1555         }
1556         apdu->u.initResponse->preferredMessageSize =
1557             odr_intdup(odr_encode(),
1558                        m_client->m_initResponse_preferredMessageSize >
1559                        m_initRequest_preferredMessageSize ?
1560                        m_initRequest_preferredMessageSize :
1561                        m_client->m_initResponse_preferredMessageSize);
1562         apdu->u.initResponse->maximumRecordSize =
1563             odr_intdup(odr_encode(),
1564                        m_client->m_initResponse_maximumRecordSize >
1565                        m_initRequest_maximumRecordSize ?
1566                        m_initRequest_maximumRecordSize :
1567                        m_client->m_initResponse_maximumRecordSize);
1568     }
1569
1570     int r = send_PDU_convert(apdu);
1571     if (r)
1572         return r;
1573     if (kill_session)
1574     {
1575         delete m_client;
1576         m_client = 0;
1577         m_parent->pre_init();
1578     }
1579     return r;
1580 }
1581
1582 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1583 {
1584     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1585     
1586     odr_reset(m_idAuthentication_odr);
1587     z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1588     m_idAuthentication_ber_buf =
1589         odr_getbuf(m_idAuthentication_odr, 
1590                    &m_idAuthentication_ber_size, 0);
1591 }
1592
1593 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1594 {
1595     return true;
1596 }
1597
1598 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1599 {
1600     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1601     ODR odr = odr_createmem(ODR_ENCODE);
1602
1603     z_IdAuthentication(odr, &t, 1, 0);
1604     int sz;
1605     char *buf = odr_getbuf(odr, &sz, 0);
1606     if (buf && m_idAuthentication_ber_buf
1607         && sz == m_idAuthentication_ber_size
1608         && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1609     {
1610         odr_destroy(odr);
1611         return true;
1612     }
1613     odr_destroy(odr);
1614     if (!buf && !m_idAuthentication_ber_buf)
1615         return true;
1616     return false;
1617 }
1618
1619 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1620 {
1621     int len = 0;
1622     const char *apdu_name_tmp = apdu_name(apdu);
1623     int r = send_Z_PDU(apdu, &len);
1624     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1625         yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1626                  get_session_str(),
1627                  apdu_name_tmp, get_hostname(), len);
1628     m_bytes_sent += len;
1629     return r;
1630 }
1631
1632 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1633 {
1634     if (apdu->which == Z_APDU_presentRequest)
1635     {
1636         Z_PresentRequest *pr = apdu->u.presentRequest;
1637         int toget = *pr->numberOfRecordsRequested;
1638         int start = *pr->resultSetStartPoint;
1639
1640         yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1641                 pr->resultSetId, start, toget);
1642
1643         if (*m_parent->m_optimize == '0')
1644             return apdu;
1645
1646         if (!m_client->m_last_resultSetId)
1647         {
1648             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1649             new_apdu->u.presentResponse->records =
1650                 create_nonSurrogateDiagnostics(
1651                     odr_encode(), 
1652                     YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1653                     pr->resultSetId);
1654             send_to_client(new_apdu);
1655             return 0;
1656         }
1657         if (start < 1 || toget < 0)
1658         {
1659             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1660             new_apdu->u.presentResponse->records =
1661                 create_nonSurrogateDiagnostics(
1662                     odr_encode(), 
1663                     YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 
1664                     0);
1665             send_to_client(new_apdu);
1666             return 0;
1667         }
1668         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1669         {
1670             if (start+toget-1 > m_client->m_last_resultCount)
1671             {
1672                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1673                 new_apdu->u.presentResponse->records =
1674                     create_nonSurrogateDiagnostics(
1675                         odr_encode(), 
1676                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1677                         0);
1678                 send_to_client(new_apdu);
1679                 return 0;
1680             }
1681             Z_NamePlusRecordList *npr;
1682 #if 0
1683             yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1684                     m_session_str, start, toget, yaz_z3950oid_to_str(
1685                         pr->preferredRecordSyntax, &oclass));
1686 #endif
1687             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1688                                           pr->preferredRecordSyntax,
1689                                           pr->recordComposition))
1690             {
1691                 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1692                          m_session_str);
1693                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1694                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1695
1696                 new_apdu->u.presentResponse->numberOfRecordsReturned
1697                     = odr_intdup(odr_encode(), toget);
1698
1699                 new_apdu->u.presentResponse->records = (Z_Records*)
1700                     odr_malloc(odr_encode(), sizeof(Z_Records));
1701                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1702                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1703                 new_apdu->u.presentResponse->nextResultSetPosition =
1704                     odr_intdup(odr_encode(), start+toget);
1705
1706                 send_to_client(new_apdu);
1707                 return 0;
1708             }
1709         }
1710     }
1711
1712     if (apdu->which != Z_APDU_searchRequest)
1713         return apdu;
1714     Z_SearchRequest *sr = apdu->u.searchRequest;
1715     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1716     Yaz_Z_Databases this_databases;
1717
1718     this_databases.set(sr->num_databaseNames, (const char **)
1719                        sr->databaseNames);
1720
1721     this_query->set_Z_Query(sr->query);
1722
1723     // Check for non-negative piggyback params.
1724     if (*sr->smallSetUpperBound < 0
1725         || *sr->largeSetLowerBound < 0
1726         || *sr->mediumSetPresentNumber < 0)
1727     {
1728         Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1729         // Not a present request.. But can't find better diagnostic
1730         new_apdu->u.searchResponse->records =
1731             create_nonSurrogateDiagnostics(
1732                 odr_encode(), 
1733                 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1734         send_to_client(new_apdu);
1735         return 0;
1736     }
1737
1738     char query_str[4096];
1739     this_query->print(query_str, sizeof(query_str)-1);
1740     yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1741
1742     if (*m_parent->m_optimize != '0' &&
1743         m_client->m_last_ok && m_client->m_last_query &&
1744         m_client->m_last_query->match(this_query) &&
1745         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1746         m_client->m_last_databases.match(this_databases))
1747     {
1748         delete this_query;
1749         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1750             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1751         {
1752             Z_NamePlusRecordList *npr;
1753             int toget = *sr->mediumSetPresentNumber;
1754             Z_RecordComposition *comp = 0;
1755
1756             if (toget > m_client->m_last_resultCount)
1757                 toget = m_client->m_last_resultCount;
1758             
1759             if (sr->mediumSetElementSetNames)
1760             {
1761                 comp = (Z_RecordComposition *)
1762                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1763                 comp->which = Z_RecordComp_simple;
1764                 comp->u.simple = sr->mediumSetElementSetNames;
1765             }
1766
1767             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1768                                           sr->preferredRecordSyntax, comp))
1769             {
1770                 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1771                          m_session_str);
1772                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1773                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1774                 new_apdu->u.searchResponse->resultCount =
1775                     &m_client->m_last_resultCount;
1776
1777                 new_apdu->u.searchResponse->numberOfRecordsReturned
1778                     = odr_intdup(odr_encode(), toget);
1779
1780                 new_apdu->u.searchResponse->presentStatus =
1781                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1782                 new_apdu->u.searchResponse->records = (Z_Records*)
1783                     odr_malloc(odr_encode(), sizeof(Z_Records));
1784                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1785                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1786                 new_apdu->u.searchResponse->nextResultSetPosition =
1787                     odr_intdup(odr_encode(), toget+1);
1788                 send_to_client(new_apdu);
1789                 return 0;
1790             }
1791             else
1792             {
1793                 // medium Set
1794                 // send present request (medium size)
1795                 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1796                          m_session_str);
1797
1798                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1799                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1800                 pr->referenceId = sr->referenceId;
1801                 pr->resultSetId = sr->resultSetName;
1802                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1803                 *pr->numberOfRecordsRequested = toget;
1804                 pr->recordComposition = comp;
1805                 m_client->m_sr_transform = 1;
1806                 return new_apdu;
1807             }
1808         }
1809         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1810             m_client->m_last_resultCount <= 0)
1811         {
1812             // large set. Return pseudo-search response immediately
1813             yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1814                      m_session_str);
1815             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1816             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1817             new_apdu->u.searchResponse->resultCount =
1818                 &m_client->m_last_resultCount;
1819             send_to_client(new_apdu);
1820             return 0;
1821         }
1822         else
1823         {
1824             Z_NamePlusRecordList *npr;
1825             int toget = m_client->m_last_resultCount;
1826             Z_RecordComposition *comp = 0;
1827             // small set
1828             // send a present request (small set)
1829
1830             if (sr->smallSetElementSetNames)
1831             {
1832                 comp = (Z_RecordComposition *)
1833                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1834                 comp->which = Z_RecordComp_simple;
1835                 comp->u.simple = sr->smallSetElementSetNames;
1836             }
1837
1838             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1839                                           sr->preferredRecordSyntax, comp))
1840             {
1841                 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1842                          m_session_str);
1843                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1844                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1845                 new_apdu->u.searchResponse->resultCount =
1846                     &m_client->m_last_resultCount;
1847
1848                 new_apdu->u.searchResponse->numberOfRecordsReturned
1849                     = odr_intdup(odr_encode(), toget);
1850
1851                 new_apdu->u.searchResponse->presentStatus =
1852                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1853                 new_apdu->u.searchResponse->records = (Z_Records*)
1854                     odr_malloc(odr_encode(), sizeof(Z_Records));
1855                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1856                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1857                 new_apdu->u.searchResponse->nextResultSetPosition =
1858                     odr_intdup(odr_encode(), toget+1);
1859                 send_to_client(new_apdu);
1860                 return 0;
1861             }
1862             else
1863             {
1864                 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1865                          m_session_str);
1866                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1867                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1868                 pr->referenceId = sr->referenceId;
1869                 pr->resultSetId = sr->resultSetName;
1870                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1871                 *pr->numberOfRecordsRequested = toget;
1872                 pr->recordComposition = comp;
1873                 m_client->m_sr_transform = 1;
1874                 return new_apdu;
1875             }
1876         }
1877     }
1878     else  // query doesn't match
1879     {
1880         delete m_client->m_last_query;
1881         m_client->m_last_query = this_query;
1882         m_client->m_last_ok = 0;
1883         m_client->m_cache.clear();
1884         m_client->m_resultSetStartPoint = 0;
1885
1886         xfree (m_client->m_last_resultSetId);
1887         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1888
1889         m_client->m_last_databases.set(sr->num_databaseNames,
1890                                        (const char **) sr->databaseNames);
1891     }
1892     return apdu;
1893 }
1894
1895
1896 void Yaz_Proxy::inc_request_no()
1897 {
1898     m_request_no++;
1899     char *cp = m_session_str + strlen(m_session_str)-1;
1900     if (*cp == ' ')
1901         cp--;
1902     while (*cp && *cp != ' ')
1903         cp--;
1904     if (*cp)
1905         sprintf(cp+1, "%d ", m_request_no);
1906 }
1907
1908 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1909 {
1910     inc_request_no();
1911
1912     m_bytes_recv += len;
1913
1914     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1915         yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1916                  m_session_str, gdu_name(apdu), len);
1917
1918 #if 0
1919     // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1920     if (apdu->which == Z_GDU_Z3950 
1921         && apdu->u.z3950->which == Z_APDU_searchRequest)
1922     {
1923         Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1924         if (req->query && req->query->which == Z_Query_type_1)
1925         {
1926             Z_RPNQuery *rpnquery = req->query->u.type_1;
1927             if (rpnquery->attributeSetId)
1928             {
1929                 rpnquery->attributeSetId[0] = -2;
1930                 rpnquery->attributeSetId[1] = -1;
1931                 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1932             }
1933         }
1934     }
1935 #endif
1936
1937 #if HAVE_GETTIMEOFDAY
1938     gettimeofday((struct timeval *) m_time_tv, 0);
1939 #endif
1940     m_bw_stat.add_bytes(len);
1941     m_pdu_stat.add_bytes(1);
1942
1943     GDU *gdu = new GDU(apdu);
1944
1945     if (gdu->get() == 0)
1946     {
1947         delete gdu;
1948         yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1949         m_in_queue.clear();
1950         dec_ref();
1951         return;
1952     }
1953     m_in_queue.enqueue(gdu);
1954     recv_GDU_more(false);
1955 }
1956
1957 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1958 {
1959     if (z_gdu->which == Z_GDU_HTTP_Request)
1960     {
1961         Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1962         const char *x_forwarded_for =
1963             z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1964         if (x_forwarded_for)
1965         {
1966             xfree(m_peername);
1967             m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1968             sprintf(m_peername, "tcp:%s", x_forwarded_for);
1969             
1970             yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1971                     m_peername);
1972             if (m_log_mask & PROXY_LOG_IP_CLIENT)
1973                 sprintf(m_session_str, "%ld:%d %.80s %d ",
1974                         (long) time(0), m_session_no, m_peername, m_request_no);
1975             else
1976                 sprintf(m_session_str, "%ld:%d %d ",
1977                         (long) time(0), m_session_no, m_request_no);
1978         }
1979     }
1980 }
1981
1982 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1983 {
1984
1985     m_parent->m_connect.cleanup(false);
1986     m_parent->m_connect.add_connect(m_peername);
1987
1988     int connect_total = m_parent->m_connect.get_total(m_peername);
1989     int max_connect = m_parent->m_max_connect;
1990
1991     if (max_connect && connect_total > max_connect)
1992     {
1993         yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1994                 m_session_str, connect_total, max_connect);
1995         block = true;
1996     }
1997     else 
1998         block = false;
1999     yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
2000             connect_total);
2001     
2002     int limit_connect = m_parent->m_limit_connect;
2003     if (limit_connect)
2004         reduce = connect_total / limit_connect;
2005     else
2006         reduce = 0;
2007 }
2008
2009 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
2010 {
2011     HTTP_Forwarded(gdu->get());
2012
2013     int reduce = 0;
2014     
2015     if (m_request_no == 1)
2016     {
2017         bool block = false;
2018         
2019         connect_stat(block, reduce);
2020
2021         if (block)
2022         {
2023             m_timeout_mode = timeout_busy;
2024             timeout(0);
2025             return;
2026         }
2027     }
2028
2029     int bw_total = m_bw_stat.get_total();
2030     int pdu_total = m_pdu_stat.get_total();
2031     int search_total = m_search_stat.get_total();
2032
2033     assert(m_timeout_mode == timeout_busy);
2034     assert(m_timeout_gdu == 0);
2035
2036     if (m_search_max)
2037         reduce += search_total / m_search_max;
2038     if (m_bw_max)
2039         reduce += (bw_total/m_bw_max);
2040     if (m_pdu_max)
2041     {
2042         if (pdu_total > m_pdu_max)
2043         {
2044             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2045             reduce = (reduce > nreduce) ? reduce : nreduce;
2046         }
2047     }
2048     m_http_version = 0;
2049
2050 #if 0
2051     /* uncomment to force a big reduce */
2052     m_timeout_mode = timeout_reduce;
2053     m_timeout_gdu = gdu;
2054     timeout(3);       // call us reduce seconds later
2055     return;
2056 #endif
2057     if (reduce)
2058     {
2059         yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2060                 m_session_str, reduce, bw_total, pdu_total, search_total,
2061                 m_bw_max, m_pdu_max, m_search_max);
2062
2063         m_timeout_mode = timeout_reduce;
2064         m_timeout_gdu = gdu;
2065         timeout(reduce);       // call us reduce seconds later
2066     }
2067     else
2068         recv_GDU_normal(gdu);
2069 }
2070
2071 void Yaz_Proxy::recv_GDU_more(bool normal)
2072 {
2073     GDU *g;
2074     if (normal && m_timeout_mode == timeout_busy)
2075         m_timeout_mode = timeout_normal;
2076     while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2077     {
2078         m_timeout_mode = timeout_busy;
2079         inc_ref();
2080         recv_GDU_reduce(g);
2081         if (dec_ref())
2082             break;
2083     }
2084 }
2085
2086 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2087 {
2088     Z_GDU *apdu = 0;
2089     gdu->move_away_gdu(odr_decode(), &apdu);
2090     delete gdu;
2091
2092     if (apdu->which == Z_GDU_Z3950)
2093         handle_incoming_Z_PDU(apdu->u.z3950);
2094     else if (apdu->which == Z_GDU_HTTP_Request)
2095         handle_incoming_HTTP(apdu->u.HTTP_Request);
2096 }
2097
2098 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2099 {
2100     if (m_max_record_retrieve)
2101     {
2102         if (apdu->which == Z_APDU_presentRequest)
2103         {
2104             Z_PresentRequest *pr = apdu->u.presentRequest;
2105             if (pr->numberOfRecordsRequested &&
2106                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2107                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2108         }
2109     }
2110 }
2111
2112 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2113 {
2114     if (apdu->which == Z_APDU_initRequest)
2115     {
2116         if (m_initRequest_options &&
2117             !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2118             (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2119         {
2120             // There is no negotiation proposal from
2121             // client's side. OK. The proxy negotiation
2122             // in use, only.
2123             Z_InitRequest *initRequest = apdu->u.initRequest;
2124             Z_OtherInformation **otherInfo;
2125             Z_OtherInformationUnit *oi;
2126             get_otherInfoAPDU(apdu, &otherInfo);
2127             oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2128             if (oi)
2129             {
2130                 ODR_MASK_SET(initRequest->options,
2131                     Z_Options_negotiationModel);
2132                 oi->which = Z_OtherInfo_externallyDefinedInfo;
2133                 oi->information.externallyDefinedInfo =
2134                 yaz_set_proposal_charneg(odr_encode(),
2135                     (const char**)&m_proxy_negotiation_charset,
2136                     m_proxy_negotiation_charset ? 1:0,
2137                     (const char**)&m_proxy_negotiation_lang,
2138                     m_proxy_negotiation_lang ? 1:0,
2139                     1);
2140             }
2141         }
2142         else if (m_initRequest_options &&
2143                  ODR_MASK_GET(m_initRequest_options,
2144                               Z_Options_negotiationModel) &&
2145                  m_charset_converter->get_target_query_charset())
2146         {
2147             yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2148                     m_session_str,
2149                     m_charset_converter->get_target_query_charset());
2150             Z_InitRequest *initRequest = apdu->u.initRequest;
2151             Z_CharSetandLanguageNegotiation *negotiation =
2152                 yaz_get_charneg_record (initRequest->otherInfo);
2153             if (negotiation &&
2154                 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2155             {
2156                 NMEM nmem = nmem_create();
2157                 char **charsets = 0;
2158                 int num_charsets = 0;
2159                 char **langs = 0;
2160                 int num_langs = 0;
2161                 int selected = 0;
2162                 yaz_get_proposal_charneg (nmem, negotiation,
2163                                           &charsets, &num_charsets,
2164                                           &langs, &num_langs, &selected);
2165                 int i;
2166                 for (i = 0; i<num_charsets; i++)
2167                     yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2168                             charsets[i]);
2169                 for (i = 0; i<num_langs; i++)
2170                     yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2171                             langs[i]);
2172
2173                 const char *t_charset =
2174                     m_charset_converter->get_target_query_charset();
2175                 // sweep through charsets and pick the first supported
2176                 // conversion
2177                 for (i = 0; i<num_charsets; i++)
2178                 {
2179                     const char *c_charset = charsets[i];
2180                     if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2181                         break;
2182                 }
2183                 if (i != num_charsets)
2184                 {
2185                     // got one .. set up ODR for reverse direction
2186                     const char *c_charset = charsets[i];
2187                     odr_set_charset(odr_encode(), c_charset, t_charset);
2188                     m_charset_converter->set_client_query_charset(c_charset);
2189                     m_charset_converter->set_client_charset_selected(selected);
2190                 }
2191                 nmem_destroy(nmem);
2192                 ODR_MASK_CLEAR(m_initRequest_options,
2193                                Z_Options_negotiationModel);
2194                 yaz_del_charneg_record(&initRequest->otherInfo);
2195             }
2196             else
2197             {
2198                 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2199                         m_session_str);
2200             }
2201         }
2202         else if (m_charset_converter->get_target_query_charset() &&
2203             m_proxy_negotiation_default_charset)
2204         {
2205             m_charset_converter->
2206                 set_client_query_charset(m_proxy_negotiation_default_charset);
2207         }
2208     }
2209     else if (apdu->which == Z_APDU_initResponse)
2210     {
2211         Z_InitResponse *initResponse = apdu->u.initResponse;
2212         Z_OtherInformation **otherInfo;
2213         get_otherInfoAPDU(apdu, &otherInfo);
2214         
2215         Z_CharSetandLanguageNegotiation *charneg = 0;
2216
2217         if (otherInfo && *otherInfo && 
2218             ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2219             && (charneg = yaz_get_charneg_record(*otherInfo)))
2220         {
2221             char *charset = 0;
2222             char *lang = 0;
2223             int selected = 0;
2224
2225             yaz_get_response_charneg(m_referenceId_mem, charneg,
2226                 &charset, &lang, &selected);
2227
2228             yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2229                 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2230
2231             if (m_initRequest_options &&
2232                 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2233             {
2234                 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2235                     m_session_str);
2236             }
2237             else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2238             {
2239                 // negotiation-charset, negotiation-lang
2240                 // elements of config file in use.
2241
2242                 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2243                     m_session_str);
2244
2245                 // clear negotiation option.
2246                 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2247
2248                 // Delete negotiation (charneg-3) entry.
2249                 yaz_del_charneg_record(otherInfo);
2250             }
2251         }
2252         else
2253         {
2254             if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2255             {
2256                 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2257                         m_session_str);
2258             }
2259             else if (m_charset_converter->get_client_query_charset())
2260             {
2261                 Z_OtherInformation **otherInfo;
2262                 Z_OtherInformationUnit *oi;
2263                 get_otherInfoAPDU(apdu, &otherInfo);
2264                 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2265                 if (oi)
2266                 {
2267                     ODR_MASK_SET(initResponse->options,
2268                                  Z_Options_negotiationModel);
2269                     if (m_initRequest_options)
2270                         ODR_MASK_SET(m_initRequest_options,
2271                                      Z_Options_negotiationModel);
2272                     
2273                     oi->which = Z_OtherInfo_externallyDefinedInfo;    
2274                     oi->information.externallyDefinedInfo =
2275                         yaz_set_response_charneg(
2276                             odr_encode(),
2277                             m_charset_converter->get_client_query_charset(),
2278                             0 /* no lang */,
2279                             m_charset_converter->get_client_charset_selected());
2280                 }
2281             }
2282         }
2283     }
2284 }
2285
2286 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2287                                                      int error,
2288                                                      const char *addinfo)
2289 {
2290     Z_Records *rec = (Z_Records *)
2291         odr_malloc (odr, sizeof(*rec));
2292     int *err = (int *)
2293         odr_malloc (odr, sizeof(*err));
2294     Z_DiagRec *drec = (Z_DiagRec *)
2295         odr_malloc (odr, sizeof(*drec));
2296     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2297         odr_malloc (odr, sizeof(*dr));
2298     *err = error;
2299     rec->which = Z_Records_NSD;
2300     rec->u.nonSurrogateDiagnostic = dr;
2301     dr->diagnosticSetId = odr_oiddup(odr, yaz_oid_diagset_bib_1);
2302     dr->condition = err;
2303     dr->which = Z_DefaultDiagFormat_v2Addinfo;
2304     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2305     return rec;
2306 }
2307
2308 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2309 {
2310     if (apdu->which == Z_APDU_searchRequest &&
2311         apdu->u.searchRequest->query &&
2312         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2313         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2314     {
2315         Z_RPNQuery *rpnquery = 0;
2316         Z_SearchRequest *sr = apdu->u.searchRequest;
2317         char *addinfo = 0;
2318
2319         yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2320                 sr->query->u.type_104->u.cql);
2321
2322         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2323                                           &rpnquery, odr_encode(),
2324                                           &addinfo);
2325         if (r == -3)
2326             yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2327         else if (r)
2328         {
2329             yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2330             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2331
2332             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2333             new_apdu->u.searchResponse->records =
2334                 create_nonSurrogateDiagnostics(odr_encode(),
2335                                                yaz_diag_srw_to_bib1(r),
2336                                                addinfo);
2337             *new_apdu->u.searchResponse->searchStatus = 0;
2338
2339             send_to_client(new_apdu);
2340
2341             return 0;
2342         }
2343         else
2344         {
2345             sr->query->which = Z_Query_type_1;
2346             sr->query->u.type_1 = rpnquery;
2347         }
2348         return apdu;
2349     }
2350     return apdu;
2351 }
2352
2353 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2354 {
2355     if (apdu->which == Z_APDU_searchRequest &&
2356         apdu->u.searchRequest->query)
2357     {
2358         if (apdu->u.searchRequest->query->which == Z_Query_type_1
2359             || apdu->u.searchRequest->query->which == Z_Query_type_101)
2360         {
2361             if (m_http_version)
2362                 m_charset_converter->set_client_query_charset("UTF-8");
2363             Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2364             m_charset_converter->convert_type_1(rpnquery, odr_encode());
2365         }
2366     }
2367     return apdu;
2368 }
2369
2370
2371 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2372 {
2373     if (apdu->which == Z_APDU_searchRequest)
2374     {
2375         Z_SearchRequest *sr = apdu->u.searchRequest;
2376         int err = 0;
2377         char *addinfo = 0;
2378
2379         Yaz_ProxyConfig *cfg = check_reconfigure();
2380         if (cfg)
2381             err = cfg->check_query(odr_encode(), m_default_target,
2382                                    sr->query, &addinfo);
2383         if (err)
2384         {
2385             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2386
2387             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2388             new_apdu->u.searchResponse->records =
2389                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2390             *new_apdu->u.searchResponse->searchStatus = 0;
2391
2392             send_to_client(new_apdu);
2393
2394             return 0;
2395         }
2396     }
2397     return apdu;
2398 }
2399
2400 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2401 {
2402     if (apdu->which != Z_APDU_initRequest)
2403         return 1;  // pass if no init request
2404     Z_InitRequest *req = apdu->u.initRequest;
2405
2406     Yaz_ProxyConfig *cfg = check_reconfigure();
2407     if (!cfg)
2408         return 1;  // pass if no config
2409
2410     int ret;
2411     if (req->idAuthentication == 0)
2412     {
2413         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2414                                          m_peername);
2415     }
2416     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2417     {
2418         ret = cfg->client_authentication(
2419             m_default_target,
2420             req->idAuthentication->u.idPass->userId,
2421             req->idAuthentication->u.idPass->groupId,
2422             req->idAuthentication->u.idPass->password,
2423             m_peername);
2424     }
2425     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2426     {
2427         char user[64], pass[64];
2428         *user = '\0';
2429         *pass = '\0';
2430         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2431         ret = cfg->client_authentication(m_default_target, user, 0, pass,
2432                                          m_peername);
2433     }
2434     else
2435         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2436                                          m_peername);
2437     return ret;
2438 }
2439
2440 int Yaz_Proxy::handle_global_authentication(Z_APDU *apdu)
2441 {
2442     if (apdu->which != Z_APDU_initRequest)
2443         return 1;  // pass if no init request
2444     Z_InitRequest *req = apdu->u.initRequest;
2445
2446     Yaz_ProxyConfig *cfg = check_reconfigure();
2447     if (!cfg)
2448         return 1;  // pass if no config
2449
2450     int ret;
2451     if (req->idAuthentication == 0)
2452     {
2453         ret = cfg->global_client_authentication(0, 0, 0,
2454                                                 m_peername);
2455     }
2456     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2457     {
2458         ret = cfg->global_client_authentication(
2459             req->idAuthentication->u.idPass->userId,
2460             req->idAuthentication->u.idPass->groupId,
2461             req->idAuthentication->u.idPass->password,
2462             m_peername);
2463     }
2464     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2465     {
2466         char user[64], pass[64];
2467         *user = '\0';
2468         *pass = '\0';
2469         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2470         ret = cfg->global_client_authentication(user, 0, pass,
2471                                                 m_peername);
2472     }
2473     else
2474         ret = cfg->global_client_authentication(0, 0, 0, m_peername);
2475     return ret;
2476 }
2477
2478 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2479 {
2480     m_marcxml_mode = none;
2481     if (apdu->which == Z_APDU_searchRequest)
2482     {
2483         Z_SearchRequest *sr = apdu->u.searchRequest;
2484         int err = 0;
2485         char *addinfo = 0;
2486         Yaz_ProxyConfig *cfg = check_reconfigure();
2487
2488         Z_RecordComposition rc_temp, *rc = 0;
2489         if (sr->smallSetElementSetNames)
2490         {
2491             rc_temp.which = Z_RecordComp_simple;
2492             rc_temp.u.simple = sr->smallSetElementSetNames;
2493             rc = &rc_temp;
2494         }
2495
2496         if (sr->preferredRecordSyntax)
2497             oid_oidcpy(m_frontend_type, sr->preferredRecordSyntax);
2498         else
2499             m_frontend_type[0] = -1;
2500
2501         char *stylesheet_name = 0;
2502         if (cfg)
2503             err = cfg->check_syntax(odr_encode(),
2504                                     m_default_target,
2505                                     sr->preferredRecordSyntax, rc,
2506                                     &addinfo, &stylesheet_name, &m_schema,
2507                                     &m_backend_type, &m_backend_charset,
2508                                     &m_usemarcon_ini_stage1,
2509                                     &m_usemarcon_ini_stage2);
2510         if (stylesheet_name)
2511         {
2512             m_parent->low_socket_close();
2513
2514 #if YAZ_HAVE_XSLT
2515             if (m_stylesheet_xsp)
2516                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2517             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2518                                                        stylesheet_name);
2519 #endif
2520             m_stylesheet_offset = 0;
2521             xfree(stylesheet_name);
2522
2523             m_parent->low_socket_open();
2524         }
2525         if (err == -1)
2526         {
2527             sr->smallSetElementSetNames = 0;
2528             sr->mediumSetElementSetNames = 0;
2529             m_marcxml_mode = marcxml;
2530             sr->preferredRecordSyntax =
2531                 yaz_string_to_oid_odr(
2532                     yaz_oid_std(), CLASS_RECSYN,
2533                     m_backend_type ? m_backend_type : "usmarc", 
2534                     odr_encode());
2535         }
2536         else if (err)
2537         {
2538             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2539
2540             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2541             new_apdu->u.searchResponse->records =
2542                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2543             *new_apdu->u.searchResponse->searchStatus = 0;
2544
2545             send_to_client(new_apdu);
2546
2547             return 0;
2548         }
2549         else if (m_backend_type)
2550         {
2551             sr->preferredRecordSyntax =
2552                 yaz_string_to_oid_odr(yaz_oid_std(), CLASS_RECSYN, 
2553                                       m_backend_type, odr_encode());
2554         }
2555     }
2556     else if (apdu->which == Z_APDU_presentRequest)
2557     {
2558         Z_PresentRequest *pr = apdu->u.presentRequest;
2559         int err = 0;
2560         char *addinfo = 0;
2561         Yaz_ProxyConfig *cfg = check_reconfigure();
2562
2563         if (pr->preferredRecordSyntax)
2564             oid_oidcpy(m_frontend_type, pr->preferredRecordSyntax);
2565         else
2566             m_frontend_type[0] = -1;
2567
2568         char *stylesheet_name = 0;
2569         if (cfg)
2570             err = cfg->check_syntax(odr_encode(), m_default_target,
2571                                     pr->preferredRecordSyntax,
2572                                     pr->recordComposition,
2573                                     &addinfo, &stylesheet_name, &m_schema,
2574                                     &m_backend_type, &m_backend_charset,
2575                                     &m_usemarcon_ini_stage1,
2576                                     &m_usemarcon_ini_stage2
2577                                     );
2578         if (stylesheet_name)
2579         {
2580             m_parent->low_socket_close();
2581
2582 #if YAZ_HAVE_XSLT
2583             if (m_stylesheet_xsp)
2584                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2585             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2586                                                        stylesheet_name);
2587 #endif
2588             m_stylesheet_offset = 0;
2589             xfree(stylesheet_name);
2590
2591             m_parent->low_socket_open();
2592         }
2593         if (err == -1)
2594         {
2595             pr->recordComposition = 0;
2596             m_marcxml_mode = marcxml;
2597
2598             pr->preferredRecordSyntax =
2599                 yaz_string_to_oid_odr(
2600                     yaz_oid_std(), CLASS_RECSYN,
2601                     m_backend_type ? m_backend_type : "usmarc", 
2602                     odr_encode());
2603         }
2604         else if (err)
2605         {
2606             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2607
2608             new_apdu->u.presentResponse->referenceId = pr->referenceId;
2609             new_apdu->u.presentResponse->records =
2610                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2611             *new_apdu->u.presentResponse->presentStatus =
2612                 Z_PresentStatus_failure;
2613
2614             send_to_client(new_apdu);
2615
2616             return 0;
2617         }
2618         else if (m_backend_type)
2619         {
2620             pr->preferredRecordSyntax =
2621                 yaz_string_to_oid_odr(yaz_oid_std(),
2622                                       CLASS_RECSYN, m_backend_type, 
2623                                       odr_encode());
2624         }
2625     }
2626     return apdu;
2627 }
2628
2629 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2630 {
2631     if (!schema)
2632         return 0;
2633     Z_ElementSetNames *esn = (Z_ElementSetNames *)
2634         odr_malloc(o, sizeof(Z_ElementSetNames));
2635     esn->which = Z_ElementSetNames_generic;
2636     esn->u.generic = odr_strdup(o, schema);
2637     return esn;
2638 }
2639
2640 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2641 {
2642     const char *t = 0;
2643     Yaz_ProxyConfig *cfg = check_reconfigure();
2644     if (cfg)
2645         t = cfg->get_explain_name(db, backend_db);
2646
2647     if (m_client && m_default_target && t && strcmp(m_default_target, t))
2648     {
2649         releaseClient();
2650     }
2651
2652     if (t)
2653     {
2654         xfree(m_default_target);
2655         m_default_target = xstrdup(t);
2656     }
2657 }
2658
2659 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2660 {
2661     struct stat sbuf;
2662     if (strcmp(hreq->method, "GET"))
2663         return 0;
2664     if (hreq->path[0] != '/')
2665         return 0;
2666     const char *cp = hreq->path;
2667     while (*cp)
2668     {
2669         if (*cp == '/' && strchr("/.", cp[1]))
2670             return 0;
2671         cp++;
2672     }
2673
2674     Yaz_ProxyConfig *cfg = check_reconfigure();
2675
2676     if (!cfg->get_file_access_info(hreq->path+1))
2677         return 0;
2678
2679     const char *fname = hreq->path+1;
2680     if (stat(fname, &sbuf))
2681     {
2682         yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2683                 fname);
2684         return 0;
2685     }
2686     if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2687     {
2688         yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2689         return 0;
2690     }
2691     if (sbuf.st_size > (off_t) 1000000)
2692     {
2693         yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2694                 fname);
2695         return 0;
2696     }
2697
2698     ODR o = odr_encode();
2699
2700     const char *ctype = cfg->check_mime_type(fname);
2701     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2702     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2703     if (m_http_version)
2704         hres->version = odr_strdup(o, m_http_version);
2705     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2706     if (m_http_keepalive)
2707         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2708     else
2709         timeout(0);
2710
2711     hres->content_len = sbuf.st_size;
2712     hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2713     FILE *f = fopen(fname, "rb");
2714     if (f)
2715     {
2716         fread(hres->content_buf, 1, hres->content_len, f);
2717         fclose(f);
2718     }
2719     else
2720     {
2721         return 0;
2722     }
2723     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2724     {
2725         yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2726                  fname);
2727     }
2728     int len;
2729     send_GDU(gdu, &len);
2730     recv_GDU_more(true);
2731     return 1;
2732 }
2733
2734 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2735 {
2736     if (m_s2z_odr_init)
2737     {
2738         odr_destroy(m_s2z_odr_init);
2739         m_s2z_odr_init = 0;
2740     }
2741     if (m_s2z_odr_search)
2742     {
2743         odr_destroy(m_s2z_odr_search);
2744         m_s2z_odr_search = 0;
2745     }
2746
2747     m_http_keepalive = 0;
2748     m_http_version = 0;
2749     if (!strcmp(hreq->version, "1.0"))
2750     {
2751         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2752         if (v && !strcmp(v, "Keep-Alive"))
2753             m_http_keepalive = 1;
2754         else
2755             m_http_keepalive = 0;
2756         m_http_version = "1.0";
2757     }
2758     else
2759     {
2760         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2761         if (v && !strcmp(v, "close"))
2762             m_http_keepalive = 0;
2763         else
2764             m_http_keepalive = 1;
2765         m_http_version = "1.1";
2766     }
2767
2768     const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2769     char authorization_str[255];
2770     *authorization_str = '\0';
2771     if (a && strncasecmp(a, "Basic ", 6) == 0)
2772         base64_decode(a + 6, authorization_str, 254);
2773
2774     Z_SRW_PDU *srw_pdu = 0;
2775     Z_SOAP *soap_package = 0;
2776     char *charset = 0;
2777     Z_SRW_diagnostic *diagnostic = 0;
2778     int num_diagnostic = 0;
2779
2780     yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2781
2782     if (file_access(hreq))
2783     {
2784         return;
2785     }
2786     else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2787                             &charset) == 0
2788              || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2789                                &charset, &diagnostic, &num_diagnostic) == 0)
2790     {
2791         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2792         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2793         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2794         m_s2z_init_apdu = 0;
2795         m_s2z_search_apdu = 0;
2796         m_s2z_present_apdu = 0;
2797
2798         m_s2z_stylesheet = 0;
2799         
2800         Z_IdAuthentication *auth = NULL;
2801         if (srw_pdu->username && srw_pdu->password)
2802         {
2803             yaz_log(YLOG_LOG, "username/password: %s/%s\n",
2804                     srw_pdu->username, srw_pdu->password);
2805             auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2806             auth->which = Z_IdAuthentication_idPass;
2807             auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2808             auth->u.idPass->groupId = NULL;
2809             auth->u.idPass->password = odr_strdup(m_s2z_odr_init, srw_pdu->password);
2810             auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, srw_pdu->username);
2811         }
2812         else
2813         {
2814             if (*authorization_str)
2815             {
2816                 yaz_log(YLOG_LOG, "authorization_str present: %s\n", authorization_str);
2817                 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2818                 auth->which = Z_IdAuthentication_idPass;
2819                 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2820                 auth->u.idPass->groupId = NULL;
2821                 char *p = strchr(authorization_str, ':');
2822                 if (p)
2823                 {
2824                     *p = '\0';
2825                     p++;
2826                     auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2827                 }
2828                 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2829             }
2830             else
2831             {
2832                 // Use _client_ IP as shown in the log entries...!
2833                 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2834                     auth->which = Z_IdAuthentication_idPass;
2835                     auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2836                     auth->u.idPass->groupId  = NULL;
2837                     auth->u.idPass->password = NULL;
2838                     auth->u.idPass->userId   = odr_strdup(m_s2z_odr_init, m_peername);
2839             }
2840         }               
2841         
2842         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2843         {
2844
2845             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2846
2847             const char *backend_db = srw_req->database;
2848             srw_get_client(srw_req->database, &backend_db);
2849
2850             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2851             // recordXPath unsupported.
2852             if (srw_req->recordXPath)
2853             {
2854                 yaz_add_srw_diagnostic(odr_decode(),
2855                                        &diagnostic, &num_diagnostic,
2856                                        72, 0);
2857             }
2858             // sort unsupported
2859             if (srw_req->sort_type != Z_SRW_sort_type_none)
2860             {
2861                 yaz_add_srw_diagnostic(odr_decode(),
2862                                        &diagnostic, &num_diagnostic,
2863                                        80, 0);
2864             }
2865             // save stylesheet
2866             if (srw_req->stylesheet)
2867                 m_s2z_stylesheet =
2868                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2869
2870             // set packing for response records ..
2871             if (srw_req->recordPacking &&
2872                 !strcmp(srw_req->recordPacking, "xml"))
2873                 m_s2z_packing = Z_SRW_recordPacking_XML;
2874             else
2875                 m_s2z_packing = Z_SRW_recordPacking_string;
2876
2877             if (num_diagnostic)
2878             {
2879                 Z_SRW_PDU *srw_pdu =
2880                     yaz_srw_get(odr_encode(),
2881                                 Z_SRW_searchRetrieve_response);
2882                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2883
2884                 srw_res->diagnostics = diagnostic;
2885                 srw_res->num_diagnostics = num_diagnostic;
2886                 send_srw_response(srw_pdu);
2887                 return;
2888             }
2889
2890             // prepare search PDU
2891             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2892                                           Z_APDU_searchRequest);
2893             Z_SearchRequest *z_searchRequest =
2894                 m_s2z_search_apdu->u.searchRequest;
2895
2896             z_searchRequest->num_databaseNames = 1;
2897             z_searchRequest->databaseNames = (char**)
2898                 odr_malloc(m_s2z_odr_search, sizeof(char *));
2899             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2900                                                            backend_db);
2901
2902             // query transformation
2903             Z_Query *query = (Z_Query *)
2904                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2905             z_searchRequest->query = query;
2906
2907             if (srw_req->query_type == Z_SRW_query_type_cql)
2908             {
2909                 Z_External *ext = (Z_External *)
2910                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
2911                 ext->direct_reference =
2912                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2913                 ext->indirect_reference = 0;
2914                 ext->descriptor = 0;
2915                 ext->which = Z_External_CQL;
2916                 ext->u.cql = srw_req->query.cql;
2917
2918                 query->which = Z_Query_type_104;
2919                 query->u.type_104 =  ext;
2920             }
2921             else if (srw_req->query_type == Z_SRW_query_type_pqf)
2922             {
2923                 Z_RPNQuery *RPNquery;
2924                 YAZ_PQF_Parser pqf_parser;
2925
2926                 pqf_parser = yaz_pqf_create ();
2927
2928                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2929                                           srw_req->query.pqf);
2930                 if (!RPNquery)
2931                 {
2932                     const char *pqf_msg;
2933                     size_t off;
2934                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2935                     int ioff = off;
2936                     yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2937                     yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2938
2939                     send_to_srw_client_error(10, 0);
2940                     return;
2941                 }
2942                 query->which = Z_Query_type_1;
2943                 query->u.type_1 =  RPNquery;
2944
2945                 yaz_pqf_destroy (pqf_parser);
2946             }
2947             else
2948             {
2949                 send_to_srw_client_error(7, "query");
2950                 return;
2951             }
2952
2953             // present
2954             m_s2z_present_apdu = 0;
2955             int max = 0;
2956             if (srw_req->maximumRecords)
2957                 max = *srw_req->maximumRecords;
2958             int start = 1;
2959             if (srw_req->startRecord)
2960                 start = *srw_req->startRecord;
2961             if (max > 0)
2962             {
2963                 // Some backend, such as Voyager doesn't honor piggyback
2964                 // So we use present always (0 &&).
2965                 if (0 && start <= 1)  // Z39.50 piggyback
2966                 {
2967                     *z_searchRequest->smallSetUpperBound = max;
2968                     *z_searchRequest->mediumSetPresentNumber = max;
2969                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2970
2971                     z_searchRequest->preferredRecordSyntax =
2972                         odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
2973
2974                     if (srw_req->recordSchema)
2975                     {
2976                         z_searchRequest->smallSetElementSetNames =
2977                             z_searchRequest->mediumSetElementSetNames =
2978                             mk_esn_from_schema(m_s2z_odr_search,
2979                                                srw_req->recordSchema);
2980                     }
2981                 }
2982                 else   // Z39.50 present
2983                 {
2984                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2985                                                    Z_APDU_presentRequest);
2986                     Z_PresentRequest *z_presentRequest =
2987                         m_s2z_present_apdu->u.presentRequest;
2988                     *z_presentRequest->resultSetStartPoint = start;
2989                     *z_presentRequest->numberOfRecordsRequested = max;
2990
2991                     z_presentRequest->preferredRecordSyntax =
2992                         odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
2993                     if (srw_req->recordSchema)
2994                     {
2995                         z_presentRequest->recordComposition =
2996                             (Z_RecordComposition *)
2997                             odr_malloc(m_s2z_odr_search,
2998                                        sizeof(Z_RecordComposition));
2999                         z_presentRequest->recordComposition->which =
3000                             Z_RecordComp_simple;
3001                         z_presentRequest->recordComposition->u.simple =
3002                             mk_esn_from_schema(m_s2z_odr_search,
3003                                                srw_req->recordSchema);
3004                     }
3005                 }
3006             }
3007             if (!m_client)
3008             {
3009                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3010                                             Z_APDU_initRequest);
3011
3012                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3013
3014                 // prevent m_initRequest_apdu memory from being grabbed
3015                 // in Yaz_Proxy::handle_incoming_Z_PDU
3016                 m_initRequest_apdu = m_s2z_init_apdu;
3017                 handle_incoming_Z_PDU(m_s2z_init_apdu);
3018                 return;
3019             }
3020             else
3021             {
3022                 handle_incoming_Z_PDU(m_s2z_search_apdu);
3023                 return;
3024             }
3025         }
3026         else if (srw_pdu->which == Z_SRW_explain_request)
3027         {
3028             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
3029
3030             const char *backend_db = srw_req->database;
3031             srw_get_client(srw_req->database, &backend_db);
3032
3033             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3034
3035             // save stylesheet
3036             if (srw_req->stylesheet)
3037                 m_s2z_stylesheet =
3038                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3039
3040             if (srw_req->recordPacking &&
3041                 !strcmp(srw_req->recordPacking, "xml"))
3042                 m_s2z_packing = Z_SRW_recordPacking_XML;
3043             else
3044                 m_s2z_packing = Z_SRW_recordPacking_string;
3045
3046             if (num_diagnostic)
3047             {
3048                 send_srw_explain_response(diagnostic, num_diagnostic);
3049                 return;
3050             }
3051
3052             if (!m_client)
3053             {
3054                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3055                                             Z_APDU_initRequest);
3056
3057                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3058                 
3059                 // prevent m_initRequest_apdu memory from being grabbed
3060                 // in Yaz_Proxy::handle_incoming_Z_PDU
3061                 m_initRequest_apdu = m_s2z_init_apdu;
3062                 handle_incoming_Z_PDU(m_s2z_init_apdu);
3063             }
3064             else
3065                 send_srw_explain_response(0, 0);
3066             return;
3067         }
3068         else if (srw_pdu->which == Z_SRW_scan_request)
3069         {
3070             m_s2z_database = odr_strdup(m_s2z_odr_init,
3071                                         srw_pdu->u.scan_request->database);
3072
3073             yaz_add_srw_diagnostic(odr_decode(),
3074                                    &diagnostic, &num_diagnostic,
3075                                    4, "scan");
3076             Z_SRW_PDU *srw_pdu =
3077                 yaz_srw_get(odr_encode(),
3078                             Z_SRW_scan_response);
3079             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3080
3081             srw_res->diagnostics = diagnostic;
3082             srw_res->num_diagnostics = num_diagnostic;
3083             send_srw_response(srw_pdu);
3084             return;
3085         }
3086         else
3087         {
3088             m_s2z_database = 0;
3089
3090             send_to_srw_client_error(4, 0);
3091         }
3092     }
3093     send_http_response(400);
3094 }
3095
3096 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3097 {
3098
3099     Z_OtherInformation **oi;
3100     get_otherInfoAPDU(apdu, &oi);
3101
3102     if (apdu->u.initRequest->implementationId)
3103         yaz_log(YLOG_LOG, "%simplementationId: %s",
3104                 m_session_str, apdu->u.initRequest->implementationId);
3105     if (apdu->u.initRequest->implementationName)
3106         yaz_log(YLOG_LOG, "%simplementationName: %s",
3107                 m_session_str, apdu->u.initRequest->implementationName);
3108     if (apdu->u.initRequest->implementationVersion)
3109         yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3110                 m_session_str, apdu->u.initRequest->implementationVersion);
3111     if (m_initRequest_apdu == 0)
3112     {
3113         if (m_initRequest_mem)
3114             nmem_destroy(m_initRequest_mem);
3115
3116         m_initRequest_apdu = apdu;
3117         m_initRequest_mem = odr_extract_mem(odr_decode());
3118
3119         m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3120             preferredMessageSize;
3121         *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3122         m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3123             maximumRecordSize;
3124         *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3125
3126         Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3127             yaz_get_charneg_record(*oi);
3128
3129         // Save proposal charsets and langs.
3130         if (ODR_MASK_GET(apdu->u.initRequest->options,
3131                          Z_Options_negotiationModel)
3132             && charSetandLangRecord)
3133         {
3134
3135             yaz_get_proposal_charneg(m_referenceId_mem,
3136                                      charSetandLangRecord,
3137                                      &m_initRequest_oi_negotiation_charsets,
3138                                      &m_initRequest_oi_negotiation_num_charsets,
3139                                      &m_initRequest_oi_negotiation_langs,
3140                                      &m_initRequest_oi_negotiation_num_langs,
3141                                      &m_initRequest_oi_negotiation_selected);
3142
3143             for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3144             {
3145                 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3146                         m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3147                         m_initRequest_oi_negotiation_charsets[i]:"none");
3148             }
3149             for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3150             {
3151                 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3152                         m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3153                         m_initRequest_oi_negotiation_langs[i]:"none");
3154             }
3155             yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3156                     m_session_str, m_initRequest_oi_negotiation_selected);
3157         }
3158         // save init options for the response..
3159         m_initRequest_options = apdu->u.initRequest->options;
3160
3161         apdu->u.initRequest->options =
3162             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3163                                        sizeof(Odr_bitmask));
3164         ODR_MASK_ZERO(apdu->u.initRequest->options);
3165         int i;
3166         for (i = 0; i<= 24; i++)
3167             ODR_MASK_SET(apdu->u.initRequest->options, i);
3168         // check negotiation option
3169         if (!ODR_MASK_GET(m_initRequest_options,
3170                           Z_Options_negotiationModel))
3171         {
3172             ODR_MASK_CLEAR(apdu->u.initRequest->options,
3173                            Z_Options_negotiationModel);
3174         }
3175         ODR_MASK_CLEAR(apdu->u.initRequest->options,
3176                        Z_Options_concurrentOperations);
3177         // make new version
3178         m_initRequest_version = apdu->u.initRequest->protocolVersion;
3179         apdu->u.initRequest->protocolVersion =
3180             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3181                                        sizeof(Odr_bitmask));
3182         ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3183
3184         for (i = 0; i<= 8; i++)
3185             ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3186     }
3187     handle_charset_lang_negotiation(apdu);
3188     if (m_client->m_init_flag)
3189     {
3190         if (handle_init_response_for_invalid_session(apdu))
3191             return;
3192         if (m_client->m_initResponse)
3193         {
3194             Z_APDU *apdu2 = m_client->m_initResponse;
3195             apdu2->u.initResponse->otherInfo = 0;
3196             if (m_client->m_cookie && *m_client->m_cookie)
3197                 set_otherInformationString(apdu2, yaz_oid_userinfo_cookie, 
3198                                            1, m_client->m_cookie);
3199             apdu2->u.initResponse->referenceId =
3200                 apdu->u.initRequest->referenceId;
3201             apdu2->u.initResponse->options = m_client->m_initResponse_options;
3202             apdu2->u.initResponse->protocolVersion =
3203                 m_client->m_initResponse_version;
3204
3205             handle_charset_lang_negotiation(apdu2);
3206
3207             if (m_timeout_mode == timeout_busy)
3208                 m_timeout_mode = timeout_normal;
3209             send_to_client(apdu2);
3210             return;
3211         }
3212     }
3213     m_client->m_init_flag = 1;
3214
3215     if (m_num_msg_threads && m_my_thread)
3216     {
3217         Auth_Msg *m = new Auth_Msg;
3218         m->m_proxy = this;
3219         z_APDU(odr_encode(), &apdu, 0, "encode");
3220         char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3221         m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3222         memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3223         odr_reset(odr_encode());
3224         
3225         inc_ref();
3226         m_my_thread->put(m);
3227     }
3228     else
3229     {
3230         int ret = handle_authentication(apdu);
3231         result_authentication(apdu, ret);
3232     }
3233 }
3234
3235 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3236 {
3237     Z_ReferenceId **refid = get_referenceIdP(apdu);
3238     nmem_reset(m_referenceId_mem);
3239     if (refid && *refid)
3240     {
3241         m_referenceId = (Z_ReferenceId *)
3242             nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3243         m_referenceId->len = m_referenceId->size = (*refid)->len;
3244         m_referenceId->buf = (unsigned char *)
3245             nmem_malloc(m_referenceId_mem, (*refid)->len);
3246         memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3247     }
3248     else
3249         m_referenceId = 0;
3250
3251     if (!m_client && m_flag_invalid_session)
3252     {
3253         // Got request for a session that is invalid..
3254         m_apdu_invalid_session = apdu; // save package
3255         m_mem_invalid_session = odr_extract_mem(odr_decode());
3256         apdu = m_initRequest_apdu;     // but throw an init to the target
3257     }
3258
3259     if (apdu->which == Z_APDU_searchRequest)
3260         m_search_stat.add_bytes(1);
3261
3262     // Handle global authentication
3263     if (!handle_global_authentication(apdu))
3264     {
3265         if (m_http_version)
3266         {   // HTTP. Send unauthorized
3267             send_http_response(401);
3268             return;
3269         }
3270         else
3271         {
3272             // Z39.50 just shutdown
3273             timeout(0);
3274             return;
3275         }
3276         return;
3277     }
3278
3279     // Determine our client.
3280     Z_OtherInformation **oi;
3281     get_otherInfoAPDU(apdu, &oi);
3282     int http_code = 404;
3283     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi), &http_code);
3284     if (!m_client)
3285     {
3286         if (m_http_version)
3287         {   // HTTP. Send not found
3288             send_http_response(http_code);
3289             return;
3290         }
3291         else
3292         {
3293             // Z39.50 just shutdown
3294             timeout(0);
3295             return;
3296         }
3297     }
3298
3299     m_client->m_server = this;
3300
3301     if (apdu->which == Z_APDU_initRequest)
3302         handle_init(apdu);
3303     else
3304         handle_incoming_Z_PDU_2(apdu);
3305 }
3306
3307 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3308 {
3309     handle_max_record_retrieve(apdu);
3310
3311     if (apdu)
3312         apdu = handle_syntax_validation(apdu);
3313
3314     if (apdu)
3315         apdu = handle_query_transformation(apdu);
3316
3317     if (apdu)
3318         apdu = handle_target_charset_conversion(apdu);
3319
3320     if (apdu)
3321         apdu = handle_query_validation(apdu);
3322
3323     if (apdu)
3324         apdu = result_set_optimize(apdu);
3325
3326     if (!apdu)
3327     {
3328         m_client->timeout(m_target_idletime);  // mark it active even
3329         recv_GDU_more(true);
3330         // though we didn't use it
3331         return;
3332     }
3333
3334     // delete other info construct completely if 0 elements
3335     Z_OtherInformation **oi;
3336     get_otherInfoAPDU(apdu, &oi);
3337     if (oi && *oi && (*oi)->num_elements == 0)
3338         *oi = 0;
3339
3340     if (apdu->which == Z_APDU_presentRequest &&
3341         m_client->m_resultSetStartPoint == 0)
3342     {
3343         Z_PresentRequest *pr = apdu->u.presentRequest;
3344         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3345         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3346     } else {
3347         m_client->m_resultSetStartPoint = 0;
3348     }
3349     if (m_client->send_to_target(apdu) < 0)
3350     {
3351         m_client->shutdown();
3352     }
3353     else
3354         m_client->m_waiting = 1;
3355 }
3356
3357 void Yaz_Proxy::connectNotify()
3358 {
3359 }
3360
3361 void Yaz_Proxy::releaseClient()
3362 {
3363     xfree(m_proxyTarget);
3364     m_proxyTarget = 0;
3365     m_flag_invalid_session = 0;
3366     // only keep if keep_alive flag is set...
3367     if (m_client &&
3368         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3369         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3370         m_client->m_waiting == 0)
3371     {
3372         yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3373                  m_session_str,
3374                  m_client->get_hostname());
3375         yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3376                 m_session_str, m_client->m_pdu_recv,
3377                 m_client->m_bytes_sent + m_client->m_bytes_recv,
3378                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3379         assert (m_client->m_waiting != 2);
3380         // Tell client (if any) that no server connection is there..
3381         m_client->m_server = 0;
3382         m_client = 0;
3383     }
3384     else if (m_client)
3385     {
3386         yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3387                  m_session_str,
3388                  m_client->get_hostname());
3389         assert (m_client->m_waiting != 2);
3390         delete m_client;
3391         m_client = 0;
3392     }
3393     else if (!m_parent)
3394     {
3395         yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3396                  m_session_str);
3397         assert (m_parent);
3398     }
3399     else
3400     {
3401         yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3402                  m_session_str);
3403     }
3404     if (m_parent)
3405         m_parent->pre_init();
3406 }
3407
3408 bool Yaz_Proxy::dec_ref()
3409 {
3410     m_http_keepalive = 0;
3411
3412     --m_ref_count;
3413     if (m_ref_count > 0)
3414         return false;
3415
3416     releaseClient();
3417
3418     delete this;
3419     return true;
3420 }
3421
3422 const char *Yaz_ProxyClient::get_session_str()
3423 {
3424     if (!m_server)
3425         return "0 ";
3426     return m_server->get_session_str();
3427 }
3428
3429 void Yaz_ProxyClient::shutdown()
3430 {
3431     yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3432              get_hostname());
3433
3434     if (m_server)
3435     {
3436         m_waiting = 1;   // ensure it's released from Yaz_Proxy::releaseClient
3437         m_server->dec_ref();
3438     }
3439     else
3440         delete this;
3441 }
3442
3443 void Yaz_Proxy::failNotify()
3444 {
3445     inc_request_no();
3446     yaz_log (YLOG_LOG, "%sConnection closed by client", get_session_str());
3447     dec_ref();
3448 }
3449
3450 void Yaz_Proxy::send_response_fail_client(const char *addr)
3451 {
3452     if (m_http_version)
3453     {
3454         Z_SRW_diagnostic *diagnostic = 0;
3455         int num_diagnostic = 0;
3456         
3457         yaz_add_srw_diagnostic(odr_encode(),
3458                                &diagnostic, &num_diagnostic,
3459                                YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3460         if (m_s2z_search_apdu)
3461             send_srw_search_response(diagnostic, num_diagnostic);
3462         else
3463             send_srw_explain_response(diagnostic, num_diagnostic);
3464     }            
3465 }
3466 void Yaz_ProxyClient::failNotify()
3467 {
3468     if (m_server)
3469         m_server->inc_request_no();
3470     yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3471              get_session_str(), get_hostname());
3472
3473     if (m_server)
3474         m_server->send_response_fail_client(get_hostname());
3475     shutdown();
3476 }
3477
3478 void Yaz_ProxyClient::connectNotify()
3479 {
3480     const char *s = get_session_str();
3481     const char *h = get_hostname();
3482     yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3483              m_target_idletime);
3484     timeout(m_target_idletime);
3485     if (!m_server)
3486         pre_init_client();
3487 }
3488
3489 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3490                                               *the_PDU_Observable, int fd)
3491 {
3492     return new Yaz_ProxyClient(the_PDU_Observable, 0);
3493 }
3494
3495 Yaz_ProxyClient::~Yaz_ProxyClient()
3496 {
3497     if (m_prev)
3498         *m_prev = m_next;
3499     if (m_next)
3500         m_next->m_prev = m_prev;
3501     m_waiting = 2;     // for debugging purposes only.
3502     odr_destroy(m_init_odr);
3503     odr_destroy(m_idAuthentication_odr);
3504     delete m_last_query;
3505     xfree (m_last_resultSetId);
3506     xfree (m_cookie);
3507 }
3508
3509 void Yaz_ProxyClient::pre_init_client()
3510 {
3511     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3512     Z_InitRequest *req = apdu->u.initRequest;
3513
3514     int i;
3515     for (i = 0; i<= 24; i++)
3516         ODR_MASK_SET(req->options, i);
3517     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3518                    Z_Options_negotiationModel);
3519     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3520                    Z_Options_concurrentOperations);
3521     for (i = 0; i<= 10; i++)
3522         ODR_MASK_SET(req->protocolVersion, i);
3523
3524     if (send_to_target(apdu) < 0)
3525     {
3526         delete this;
3527     }
3528     else
3529     {
3530         m_waiting = 1;
3531         m_init_flag = 1;
3532     }
3533 }
3534
3535 void Yaz_Proxy::pre_init()
3536 {
3537     int i;
3538     const char *name = 0;
3539     const char *zurl_in_use[MAX_ZURL_PLEX];
3540     int limit_bw, limit_pdu, limit_req, limit_search;
3541     int target_idletime, client_idletime;
3542     int max_sockets;
3543     int max_clients;
3544     int keepalive_limit_bw, keepalive_limit_pdu;
3545     int pre_init;
3546     const char *cql2rpn = 0;
3547     const char *authentication = 0;
3548     const char *negotiation_charset = 0;
3549     const char *negotiation_lang = 0;
3550
3551     Yaz_ProxyConfig *cfg = check_reconfigure();
3552
3553     zurl_in_use[0] = 0;
3554
3555     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3556         set_APDU_yazlog(1);
3557     else
3558         set_APDU_yazlog(0);
3559
3560     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3561                                           &limit_bw, &limit_pdu, &limit_req,
3562                                           &limit_search,
3563                                           &target_idletime, &client_idletime,
3564                                           &max_sockets,
3565                                           &max_clients,
3566                                           &keepalive_limit_bw,
3567                                           &keepalive_limit_pdu,
3568                                           &pre_init,
3569                                           &cql2rpn,
3570                                           &authentication,
3571                                           &negotiation_charset,
3572                                           &negotiation_lang,
3573                                           0,
3574                                           0) ; i++)
3575     {
3576         if (pre_init)
3577         {
3578             int j;
3579             for (j = 0; zurl_in_use[j]; j++)
3580             {
3581                 Yaz_ProxyClient *c;
3582                 int spare = 0;
3583                 int spare_waiting = 0;
3584                 int in_use = 0;
3585                 int other = 0;
3586                 for (c = m_clientPool; c; c = c->m_next)
3587                 {
3588                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
3589                     {
3590                         if (c->m_cookie == 0)
3591                         {
3592                             if (c->m_server == 0)
3593                                 if (c->m_waiting)
3594                                     spare_waiting++;
3595                                 else
3596                                     spare++;
3597                             else
3598                                 in_use++;
3599                         }
3600                         else
3601                             other++;
3602                     }
3603                 }
3604                 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3605                         "sparew=%d preinit=%d",m_session_str,
3606                         name, zurl_in_use[j], in_use, other,
3607                         spare, spare_waiting, pre_init);
3608                 if (spare + spare_waiting < pre_init
3609                     && in_use + spare + spare_waiting + other < max_sockets)
3610                 {
3611                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3612                     c->m_next = m_clientPool;
3613                     if (c->m_next)
3614                         c->m_next->m_prev = &c->m_next;
3615                     m_clientPool = c;
3616                     c->m_prev = &m_clientPool;
3617
3618                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
3619                         c->set_APDU_yazlog(1);
3620                     else
3621                         c->set_APDU_yazlog(0);
3622
3623                     if (c->client(zurl_in_use[j]))
3624                     {
3625                         timeout(60);
3626                         delete c;
3627                         return;
3628                     }
3629                     c->timeout(30);
3630                     c->m_waiting = 1;
3631                     c->m_target_idletime = target_idletime;
3632                     c->m_seqno = m_seqno++;
3633                 }
3634             }
3635         }
3636     }
3637 }
3638
3639 void Yaz_Proxy::timeoutNotify()
3640 {
3641     if (m_parent)
3642     {
3643         GDU *gdu;
3644         switch(m_timeout_mode)
3645         {
3646         case timeout_normal:
3647         case timeout_busy:
3648             inc_request_no();
3649             m_in_queue.clear();
3650             yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3651             dec_ref();
3652             break;
3653         case timeout_reduce:
3654             timeout(m_client_idletime);
3655             m_timeout_mode = timeout_busy;
3656             gdu = m_timeout_gdu;
3657             m_timeout_gdu = 0;
3658             recv_GDU_normal(gdu);
3659             break;
3660         case timeout_xsl:
3661             assert(m_stylesheet_nprl);
3662             convert_xsl_delay();
3663             recv_GDU_more(true);
3664         }
3665     }
3666     else
3667     {
3668         timeout(600);
3669         pre_init();
3670     }
3671 }
3672
3673 void Yaz_Proxy::markInvalid()
3674 {
3675     m_client = 0;
3676     m_flag_invalid_session = 1;
3677 }
3678
3679 void Yaz_ProxyClient::timeoutNotify()
3680 {
3681     if (m_server)
3682         m_server->inc_request_no();
3683
3684     yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3685              get_hostname());
3686
3687     if (m_server)
3688         m_server->send_response_fail_client(get_hostname());
3689
3690     Yaz_Proxy *proxy_root = m_root;
3691
3692     shutdown();
3693
3694     proxy_root->pre_init();
3695 }
3696
3697 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3698                                  Yaz_Proxy *parent) :
3699     Z_Assoc (the_PDU_Observable)
3700 {
3701     m_cookie = 0;
3702     m_next = 0;
3703     m_prev = 0;
3704     m_init_flag = 0;
3705     m_last_query = 0;
3706     m_last_resultSetId = 0;
3707     m_last_resultCount = 0;
3708     m_last_ok = 0;
3709     m_sr_transform = 0;
3710     m_waiting = 0;
3711     m_init_odr = odr_createmem (ODR_DECODE);
3712     m_initResponse = 0;
3713     m_initResponse_options = 0;
3714     m_initResponse_version = 0;
3715     m_initResponse_preferredMessageSize = 0;
3716     m_initResponse_maximumRecordSize = 0;
3717     m_resultSetStartPoint = 0;
3718     m_bytes_sent = m_bytes_recv = 0;
3719     m_pdu_recv = 0;
3720     m_server = 0;
3721     m_seqno = 0;
3722     m_target_idletime = 600;
3723     m_root = parent;
3724     m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3725     m_idAuthentication_ber_buf = 0;
3726     m_idAuthentication_ber_size = 0;
3727 }
3728
3729 const char *Yaz_Proxy::option(const char *name, const char *value)
3730 {
3731     if (!strcmp (name, "optimize")) {
3732         if (value) {
3733             xfree (m_optimize);
3734             m_optimize = xstrdup (value);
3735         }
3736         return m_optimize;
3737     }
3738     return 0;
3739 }
3740
3741 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3742 {
3743
3744 }
3745
3746 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3747 {
3748     if (apdu->which == Z_GDU_Z3950)
3749         recv_Z_PDU(apdu->u.z3950, len);
3750     else if (apdu->which == Z_GDU_HTTP_Response)
3751         recv_HTTP_response(apdu->u.HTTP_Response, len);
3752     else
3753         shutdown();
3754 }
3755
3756 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3757 {
3758     if (!m_flag_invalid_session)
3759         return 0;
3760     m_flag_invalid_session = 0;
3761     handle_incoming_Z_PDU(m_apdu_invalid_session);
3762     assert (m_mem_invalid_session);
3763     nmem_destroy(m_mem_invalid_session);
3764     m_mem_invalid_session = 0;
3765     return 1;
3766 }
3767
3768 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3769 {
3770     m_bytes_recv += len;
3771
3772     m_pdu_recv++;
3773     m_waiting = 0;
3774     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3775         yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3776                  apdu_name(apdu), get_hostname(), len);
3777     if (apdu->which == Z_APDU_initResponse)
3778     {
3779         if (!m_server)  // if this is a pre init session , check for more
3780             m_root->pre_init();
3781         NMEM nmem = odr_extract_mem (odr_decode());
3782         odr_reset (m_init_odr);
3783         nmem_transfer (m_init_odr->mem, nmem);
3784         m_initResponse = apdu;
3785         m_initResponse_options = apdu->u.initResponse->options;
3786         m_initResponse_version = apdu->u.initResponse->protocolVersion;
3787         m_initResponse_preferredMessageSize =
3788             *apdu->u.initResponse->preferredMessageSize;
3789         m_initResponse_maximumRecordSize =
3790             *apdu->u.initResponse->maximumRecordSize;
3791
3792         Z_InitResponse *ir = apdu->u.initResponse;
3793        
3794         // apply YAZ Proxy version
3795         char *imv0 = ir->implementationVersion;
3796         char *imv1 = (char*)
3797             odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3798         *imv1 = '\0';
3799         if (imv0)
3800             strcat(imv1, imv0);
3801 #ifdef VERSION
3802         strcat(imv1, "/" VERSION);
3803 #endif
3804         ir->implementationVersion = imv1;
3805         
3806         // apply YAZ Proxy implementation name
3807         char *im0 = ir->implementationName;
3808         char *im1 = (char*)
3809             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3810         *im1 = '\0';
3811         if (im0)
3812         {
3813             strcat(im1, im0);
3814             strcat(im1, " ");
3815         }
3816         strcat(im1, "(YAZ Proxy)");
3817         ir->implementationName = im1;
3818
3819         nmem_destroy (nmem);
3820
3821         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3822             return;
3823     }
3824     if (apdu->which == Z_APDU_searchResponse)
3825     {
3826         Z_SearchResponse *sr = apdu->u.searchResponse;
3827         m_last_resultCount = *sr->resultCount;
3828         int status = *sr->searchStatus;
3829         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3830         {
3831             m_last_ok = 1;
3832
3833             if (sr->records && sr->records->which == Z_Records_DBOSD)
3834             {
3835                 m_cache.add(odr_decode(),
3836                             sr->records->u.databaseOrSurDiagnostics, 1,
3837                             *sr->resultCount);
3838             }
3839         }
3840     }
3841     if (apdu->which == Z_APDU_presentResponse)
3842     {
3843         Z_PresentResponse *pr = apdu->u.presentResponse;
3844         if (m_sr_transform)
3845         {
3846             m_sr_transform = 0;
3847             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3848             Z_SearchResponse *sr = new_apdu->u.searchResponse;
3849             sr->referenceId = pr->referenceId;
3850             *sr->resultCount = m_last_resultCount;
3851             sr->records = pr->records;
3852             sr->nextResultSetPosition = pr->nextResultSetPosition;
3853             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3854             apdu = new_apdu;
3855         }
3856         if (pr->records &&
3857             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3858         {
3859             m_cache.add(odr_decode(),
3860                         pr->records->u.databaseOrSurDiagnostics,
3861                         m_resultSetStartPoint, -1);
3862             m_resultSetStartPoint = 0;
3863         }
3864     }
3865     if (m_cookie)
3866         set_otherInformationString(apdu, yaz_oid_userinfo_cookie, 1, m_cookie);
3867
3868     Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3869
3870     if (server)
3871         server->send_to_client(apdu);
3872     if (apdu->which == Z_APDU_close)
3873         shutdown();
3874     else if (server)
3875         server->recv_GDU_more(true);
3876 }
3877
3878 void Yaz_Proxy::low_socket_close()
3879 {
3880 #if WIN32
3881 #else
3882     int i;
3883     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3884         if  (m_lo_fd[i] >= 0)
3885             ::close(m_lo_fd[i]);
3886 #endif
3887 }
3888
3889 void Yaz_Proxy::low_socket_open()
3890 {
3891 #if WIN32
3892 #else
3893     int i;
3894     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3895         m_lo_fd[i] = open("/dev/null", O_RDONLY);
3896 #endif
3897 }
3898
3899 int Yaz_Proxy::server(const char *addr)
3900 {
3901     int r = Z_Assoc::server(addr);
3902     if (!r)
3903     {
3904         yaz_log(YLOG_LOG, "%sStarted proxy "
3905 #ifdef VERSION
3906             VERSION
3907 #endif
3908             " on %s", m_session_str, addr);
3909         timeout(1);
3910     }
3911     return r;
3912 }
3913
3914 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3915 {
3916     const char *base64_chars =
3917         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3918     int len = strlen(base64);
3919     int buf_pos = 0;
3920     int index = 1;
3921
3922     for (int pos = 0; pos <= len; pos++)
3923     {
3924         if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3925             break;
3926
3927         const char *ch_ptr = strchr(base64_chars, base64[pos]);
3928         if (!ch_ptr)
3929             break;
3930         char ch = (char) (ch_ptr - base64_chars);
3931         switch (index)
3932         {
3933             case 1:
3934                 buf[buf_pos] = ch << 2;
3935                 break;
3936             case 2:
3937                 buf[buf_pos++] += (ch & 0x30) >> 4;
3938                 buf[buf_pos] = (ch & 0x0f) << 4;
3939                 break;
3940             case 3:
3941                 buf[buf_pos++] += (ch & 0x3c) >> 2;
3942                 buf[buf_pos] = (ch & 0x03) << 6;
3943                 break;
3944             case 4:
3945                 buf[buf_pos++] += ch;
3946         }
3947         if (index < 4)
3948             index++;
3949         else
3950             index = 1;
3951     }
3952     buf[buf_pos] = '\0';
3953 }
3954
3955 /*
3956  * Local variables:
3957  * c-basic-offset: 4
3958  * indent-tabs-mode: nil
3959  * End:
3960  * vim: shiftwidth=4 tabstop=8 expandtab
3961  */
3962