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