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