Using yaz_daemon rather than own code. Fixed bug #2060.
[yazproxy-moved-to-github.git] / src / yaz-proxy.cpp
1 /* $Id: yaz-proxy.cpp,v 1.78 2008-02-21 09:33:23 adam Exp $
2    Copyright (c) 1998-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         if (m_config_fname && cfg)
403         {
404             yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
405             int r = cfg->read_xml(m_config_fname);
406             if (r)
407                 yaz_log(YLOG_WARN, "reconfigure failed");
408             else
409             {
410                 m_log_mask = 0;
411                 int period = 60;
412                 cfg->get_generic_info(&m_log_mask, &m_max_clients,
413                                       &m_max_connect, &m_limit_connect,
414                                       &period, &m_num_msg_threads);
415                 m_connect.set_period(period);
416             }
417         }
418         else
419             yaz_log(YLOG_LOG, "reconfigure");
420         m_reconfig_flag = 0;
421     }
422     return cfg;
423 }
424
425 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
426                                         *the_PDU_Observable, int fd)
427 {
428     check_reconfigure();
429
430     char session_str[200];
431     const char *peername = the_PDU_Observable->getpeername();
432     if (!peername)
433         peername = "nullpeer";
434
435     if (m_log_mask & PROXY_LOG_IP_CLIENT)
436         sprintf(session_str, "%ld:%d %.80s %d ",
437                 (long) time(0), m_session_no, peername, 0);
438     else
439         sprintf(session_str, "%ld:%d %d ",
440                 (long) time(0), m_session_no, 0);
441     m_session_no++;
442
443     yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
444
445     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
446                                          m_socket_observable, this);
447
448     new_proxy->m_config = 0;
449     new_proxy->m_config_fname = 0;
450     new_proxy->timeout(m_client_idletime);
451     new_proxy->m_target_idletime = m_target_idletime;
452     new_proxy->set_default_target(m_default_target);
453     new_proxy->m_max_clients = m_max_clients;
454     new_proxy->m_log_mask = m_log_mask;
455     new_proxy->m_session_no = m_session_no;
456     new_proxy->m_num_msg_threads = m_num_msg_threads;
457
458 #if 0
459     // in case we want to watch a particular client..
460     if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
461         new_proxy->m_log_mask = 255;
462 #endif
463
464     new_proxy->set_APDU_log(get_APDU_log());
465     if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
466         new_proxy->set_APDU_yazlog(1);
467     else
468         new_proxy->set_APDU_yazlog(0);
469     strcpy(new_proxy->m_session_str, session_str);
470     new_proxy->m_peername = xstrdup(peername);
471     new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
472         m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
473     // create thread object the first time we get an incoming connection
474     if (!m_my_thread && m_num_msg_threads > 0)
475     {
476         yaz_log (YLOG_LOG, "%sStarting message thread management. number=%d",
477                  session_str, m_num_msg_threads);
478         m_my_thread = new Msg_Thread(m_socket_observable, m_num_msg_threads);
479     }
480     new_proxy->m_my_thread = m_my_thread;
481     return new_proxy;
482 }
483
484 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
485 {
486     Z_OtherInformationUnit *oi =
487         update_otherInformation(otherInfo, 0, yaz_oid_userinfo_cookie, 1, 1);
488     
489     if (oi && oi->which == Z_OtherInfo_characterInfo)
490         return oi->information.characterInfo;
491     return 0;
492 }
493
494 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
495 {
496     Z_OtherInformationUnit *oi =
497         update_otherInformation(otherInfo, 0, yaz_oid_userinfo_proxy, 1, 1);
498     
499     if (oi && oi->which == Z_OtherInfo_characterInfo)
500         return oi->information.characterInfo;
501     return 0;
502 }
503 const char *Yaz_Proxy::load_balance(const char **url)
504 {
505     int zurl_in_use[MAX_ZURL_PLEX];
506     int zurl_in_spare[MAX_ZURL_PLEX];
507     Yaz_ProxyClient *c;
508     int i;
509
510     for (i = 0; i<MAX_ZURL_PLEX; i++)
511     {
512         zurl_in_use[i] = 0;
513         zurl_in_spare[i] = 0;
514     }
515     for (c = m_parent->m_clientPool; c; c = c->m_next)
516     {
517         for (i = 0; url[i]; i++)
518             if (!strcmp(url[i], c->get_hostname()))
519             {
520                 zurl_in_use[i]++;
521                 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
522                     zurl_in_spare[i]++;
523             }
524     }
525     int min_use = 100000;
526     int spare_for_min = 0;
527     int max_spare = 0;
528     const char *ret_min = 0;
529     const char *ret_spare = 0;
530     for (i = 0; url[i]; i++)
531     {
532         yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
533                 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
534         if (min_use > zurl_in_use[i])
535         {
536             ret_min = url[i];
537             min_use = zurl_in_use[i];
538             spare_for_min = zurl_in_spare[i];
539         }
540         if (max_spare < zurl_in_spare[i])
541         {
542             ret_spare = url[i];
543             max_spare = zurl_in_spare[i];
544         }
545     }
546     return ret_min;
547 }
548
549 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
550                                        const char *proxy_host)
551 {
552     assert (m_parent);
553     Yaz_Proxy *parent = m_parent;
554     Yaz_ProxyClient *c = m_client;
555
556     if (!m_proxyTarget)
557     {
558         const char *url[MAX_ZURL_PLEX];
559         Yaz_ProxyConfig *cfg = check_reconfigure();
560         if (proxy_host)
561         {
562             if (parent && parent->m_debug_mode)
563             {
564                 // only to be enabled for debugging...
565                 if (!strcmp(proxy_host, "stop"))
566                     exit(0);
567             }
568             xfree(m_default_target);
569             m_default_target = xstrdup(proxy_host);
570         }
571         proxy_host = m_default_target;
572         int client_idletime = -1;
573         const char *cql2rpn_fname = 0;
574         const char *negotiation_charset = 0;
575         const char *negotiation_lang = 0;
576         const char *query_charset = 0;
577         const char *default_client_query_charset = 0;
578         url[0] = m_default_target;
579         url[1] = 0;
580         if (cfg)
581         {
582             int pre_init = 0;
583             cfg->get_target_info(proxy_host, url, &m_bw_max,
584                                  &m_pdu_max, &m_max_record_retrieve,
585                                  &m_search_max,
586                                  &m_target_idletime, &client_idletime,
587                                  &parent->m_max_clients,
588                                  &m_keepalive_limit_bw,
589                                  &m_keepalive_limit_pdu,
590                                  &pre_init,
591                                  &cql2rpn_fname,
592                                  &negotiation_charset,
593                                  &negotiation_lang,
594                                  &query_charset,
595                                  &default_client_query_charset);
596         }
597         if (client_idletime != -1)
598         {
599             m_client_idletime = client_idletime;
600             timeout(m_client_idletime);
601         }
602
603         // get those FILE descriptors available 
604         m_parent->low_socket_close();
605         if (cql2rpn_fname)
606             m_cql2rpn.set_pqf_file(cql2rpn_fname);
607         // reserve them again
608         m_parent->low_socket_open();
609         
610         if (negotiation_charset || negotiation_lang || default_client_query_charset)
611         {
612             set_proxy_negotiation(negotiation_charset,
613                 negotiation_lang, default_client_query_charset);
614         }
615         m_charset_converter->set_target_query_charset(query_charset);
616         if (!url[0])
617         {
618             yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
619             return 0;
620         }
621         // we don't handle multiplexing for cookie session, so we just
622         // pick the first one in this case (anonymous users will be able
623         // to use any backend)
624         if (cookie && *cookie)
625             m_proxyTarget = (char*) xstrdup(url[0]);
626         else
627             m_proxyTarget = (char*) xstrdup(load_balance(url));
628     }
629     if (cookie && *cookie)
630     {   // search in sessions with a cookie
631         for (c = parent->m_clientPool; c; c = c->m_next)
632         {
633             assert (c->m_prev);
634             assert (*c->m_prev == c);
635             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
636                 !strcmp(m_proxyTarget, c->get_hostname()))
637             {
638                 // Found it in cache
639                 // The following handles "cancel"
640                 // If connection is busy (waiting for PDU) and
641                 // we have an initRequest we can safely do re-open
642                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
643                 {
644                     yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
645                              c->get_hostname());
646                     c->close();
647                     c->m_init_flag = 0;
648
649                     c->m_last_ok = 0;
650                     c->m_cache.clear();
651                     c->m_last_resultCount = 0;
652                     c->m_sr_transform = 0;
653                     c->m_waiting = 0;
654                     c->m_resultSetStartPoint = 0;
655                     c->m_target_idletime = m_target_idletime;
656                     if (c->client(m_proxyTarget))
657                     {
658                         delete c;
659                         return 0;
660                     }
661                     c->timeout(30);
662                 }
663                 c->m_seqno = parent->m_seqno;
664                 if (c->m_server && c->m_server != this)
665                     c->m_server->m_client = 0;
666                 c->m_server = this;
667                 (parent->m_seqno)++;
668                 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
669                 return c;
670             }
671         }
672     }
673     else if (!c && apdu->which == Z_APDU_initRequest )
674     {
675         // anonymous sessions without cookie.
676         // if authentication is set it is NOT anonymous se we can't share them.
677         // If charset and lang negotiation is use it is NOT anonymous session too.
678         for (c = parent->m_clientPool; c; c = c->m_next)
679         {
680             assert(c->m_prev);
681             assert(*c->m_prev == c);
682             if (c->m_server == 0 && c->m_cookie == 0 &&  c->m_waiting == 0 
683                 && c->compare_idAuthentication(apdu)
684                 && c->compare_charset(apdu)
685                 && !strcmp(m_proxyTarget, c->get_hostname()))
686             {
687                 // found it in cache
688                 yaz_log (YLOG_LOG, "%sREUSE %d %s",
689                          m_session_str, parent->m_seqno, c->get_hostname());
690                 
691                 c->m_seqno = parent->m_seqno;
692                 assert(c->m_server == 0);
693                 c->m_server = this;
694
695                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
696                     c->set_APDU_yazlog(1);
697                 else
698                     c->set_APDU_yazlog(0);
699
700                 (parent->m_seqno)++;
701
702                 parent->pre_init();
703
704                 return c;
705             }
706         }
707     }
708     if (!m_client)
709     {
710         if (apdu->which != Z_APDU_initRequest)
711         {
712             yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
713             return 0;
714         }
715         // go through list of clients - and find the lowest/oldest one.
716         Yaz_ProxyClient *c_min = 0;
717         int min_seq = -1;
718         int no_of_clients = 0;
719         if (parent->m_clientPool)
720             yaz_log (YLOG_DEBUG, "Existing sessions");
721         for (c = parent->m_clientPool; c; c = c->m_next)
722         {
723             yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
724                                c->m_waiting, c->get_hostname(),
725                                c->m_cookie ? c->m_cookie : "");
726             no_of_clients++;
727             if (min_seq < 0 || c->m_seqno < min_seq)
728             {
729                 min_seq = c->m_seqno;
730                 c_min = c;
731             }
732         }
733         if (no_of_clients >= parent->m_max_clients)
734         {
735             c = c_min;
736             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
737             {
738                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
739                          m_session_str, parent->m_max_clients, c->m_seqno);
740                 if (c->m_server && c->m_server != this)
741                     c->m_server->dec_ref();
742             }
743             else
744             {
745                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
746                          m_session_str, parent->m_max_clients,
747                          c->m_seqno, parent->m_seqno, c->get_hostname());
748                 xfree (c->m_cookie);
749                 c->m_cookie = 0;
750                 if (cookie)
751                     c->m_cookie = xstrdup(cookie);
752                 c->m_seqno = parent->m_seqno;
753                 if (c->m_server && c->m_server != this)
754                 {
755                     c->m_server->m_client = 0;
756                     c->m_server->dec_ref();
757                 }
758                 (parent->m_seqno)++;
759                 c->m_target_idletime = m_target_idletime;
760                 c->timeout(m_target_idletime);
761
762                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
763                     c->set_APDU_yazlog(1);
764                 else
765                     c->set_APDU_yazlog(0);
766
767                 return c;
768             }
769         }
770         else
771         {
772             yaz_log (YLOG_LOG, "%sNEW %d %s",
773                      m_session_str, parent->m_seqno, m_proxyTarget);
774             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
775             c->m_next = parent->m_clientPool;
776             if (c->m_next)
777                 c->m_next->m_prev = &c->m_next;
778             parent->m_clientPool = c;
779             c->m_prev = &parent->m_clientPool;
780         }
781
782         xfree (c->m_cookie);
783         c->m_cookie = 0;
784         if (cookie)
785             c->m_cookie = xstrdup(cookie);
786
787         c->m_seqno = parent->m_seqno;
788         c->m_init_flag = 0;
789         c->m_last_resultCount = 0;
790         c->m_last_ok = 0;
791         c->m_cache.clear();
792         c->m_sr_transform = 0;
793         c->m_waiting = 0;
794         c->m_resultSetStartPoint = 0;
795         (parent->m_seqno)++;
796         if (c->client(m_proxyTarget))
797         {
798             delete c;
799             return 0;
800         }
801         c->m_target_idletime = m_target_idletime;
802         c->timeout(30);
803
804         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
805             c->set_APDU_yazlog(1);
806         else
807             c->set_APDU_yazlog(0);
808
809         c->set_idAuthentication(apdu);
810     }
811     yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
812     return c;
813 }
814
815 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
816 {
817     int i;
818     for (i = 0; i<num; i++)
819     {
820         Z_DefaultDiagFormat *r;
821         Z_DiagRec *p = pp[i];
822         if (p->which != Z_DiagRec_defaultFormat)
823         {
824             yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
825             return;
826         }
827         else
828             r = p->u.defaultFormat;
829         switch (r->which)
830         {
831         case Z_DefaultDiagFormat_v2Addinfo:
832             yaz_log(YLOG_LOG, "%sError %d %s:%s",
833                     m_session_str,
834                     *r->condition, diagbib1_str(*r->condition),
835                     r->u.v2Addinfo);
836             break;
837         case Z_DefaultDiagFormat_v3Addinfo:
838             yaz_log(YLOG_LOG, "%sError %d %s:%s",
839                     m_session_str,
840                     *r->condition, diagbib1_str(*r->condition),
841                     r->u.v3Addinfo);
842             break;
843         }
844     }
845 }
846
847 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
848 {
849     if (!m_stylesheet_xsp || p->num_records <= 0)
850     {
851         return 0;  /* no XSLT to be done ... */
852     }
853
854     m_stylesheet_offset = 0;
855     m_stylesheet_nprl = p;
856     m_stylesheet_apdu = apdu;
857     m_timeout_mode = timeout_xsl;
858
859     timeout(0);
860     return 1;
861 }
862
863 void Yaz_Proxy::convert_xsl_delay()
864 {
865 #if YAZ_HAVE_XSLT
866     Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
867     if (npr->which == Z_NamePlusRecord_databaseRecord)
868     {
869         Z_External *r = npr->u.databaseRecord;
870         if (r->which == Z_External_octet)
871         {
872 #if 0
873             fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
874 #endif
875             xmlDocPtr res, doc = xmlParseMemory(
876                 (char*) r->u.octet_aligned->buf,
877                 r->u.octet_aligned->len);
878
879
880             yaz_log(YLOG_LOG, "%sXSLT convert %d",
881                     m_session_str, m_stylesheet_offset);
882             res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
883                                       doc, 0);
884
885             if (res)
886             {
887                 xmlChar *out_buf;
888                 int out_len;
889                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
890                 m_stylesheet_nprl->records[m_stylesheet_offset]->
891                     u.databaseRecord =
892                     z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
893                                      (char*) out_buf, out_len);
894                 xmlFree(out_buf);
895                 xmlFreeDoc(res);
896             }
897
898             xmlFreeDoc(doc);
899         }
900     }
901 #endif
902     m_stylesheet_offset++;
903     if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
904     {
905         m_timeout_mode = timeout_normal;
906         m_stylesheet_nprl = 0;
907 #if YAZ_HAVE_XSLT
908         if (m_stylesheet_xsp)
909             xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
910 #endif
911         m_stylesheet_xsp = 0;
912         timeout(m_client_idletime);
913         send_PDU_convert(m_stylesheet_apdu);
914     }
915     else
916         timeout(0);
917 }
918
919 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
920 {
921     if (m_frontend_type[0] != -1)
922     {
923         int i;
924         for (i = 0; i < p->num_records; i++)
925         {
926             Z_NamePlusRecord *npr = p->records[i];
927             if (npr->which == Z_NamePlusRecord_databaseRecord)
928             {
929                 Z_External *r = npr->u.databaseRecord;
930                 if (r->which == Z_External_octet)
931                 {
932 #if HAVE_USEMARCON
933                     if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
934                     {
935                         if (!m_usemarcon->m_stage1)
936                         {
937                             m_usemarcon->m_stage1 = new CDetails();
938                         }
939                         m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
940                         m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
941                         int res = m_usemarcon->m_stage1->Start();
942                         if (res == 0)
943                         {
944                             char *converted;
945                             int convlen;
946                             m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
947                             if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
948                             {
949                                 if (!m_usemarcon->m_stage2)
950                                 {
951                                     m_usemarcon->m_stage2 = new CDetails();
952                                 }
953                                 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
954                                 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
955                                 res = m_usemarcon->m_stage2->Start();
956                                 if (res == 0)
957                                 {
958                                     free(converted);
959                                     m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
960                                 }
961                                 else
962                                 {
963                                     yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
964                                 }
965                             }
966                             npr->u.databaseRecord =
967                                 z_ext_record_oid(odr_encode(),
968                                                  m_frontend_type,
969                                                  converted,
970                                                  strlen(converted));
971                             free(converted);
972                         }
973                         else
974                         {
975                             yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
976                         }
977                         continue;
978                     }
979 #endif
980 /* HAVE_USEMARCON */
981                     npr->u.databaseRecord =
982                         z_ext_record_oid(odr_encode(),
983                                          m_frontend_type,
984                                          (char*) r->u.octet_aligned->buf,
985                                          r->u.octet_aligned->len);
986                 }
987             }
988         }
989     }
990 }
991
992 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
993                                         const char *backend_charset)
994 {
995     int sel =   m_charset_converter->get_client_charset_selected();
996     const char *client_record_charset =
997         m_charset_converter->get_client_query_charset();
998     if (sel && backend_charset && client_record_charset &&
999         strcmp(backend_charset, client_record_charset))
1000     {
1001         int i;
1002         yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1003                                         backend_charset);
1004         yaz_marc_t mt = yaz_marc_create();
1005         yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1006         yaz_marc_iconv(mt, cd);
1007         for (i = 0; i < p->num_records; i++)
1008         {
1009             Z_NamePlusRecord *npr = p->records[i];
1010             if (npr->which == Z_NamePlusRecord_databaseRecord)
1011             {
1012                 Z_External *r = npr->u.databaseRecord;
1013                 const Odr_oid *oid = r->direct_reference;
1014                 if (!oid)
1015                     continue;
1016
1017                 if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
1018                 {
1019                     WRBUF w = wrbuf_alloc();
1020
1021                     wrbuf_iconv_write(w, cd,  (char*) r->u.octet_aligned->buf,
1022                                       r->u.octet_aligned->len);
1023                     npr->u.databaseRecord =
1024                         z_ext_record_oid(odr_encode(), oid, wrbuf_buf(w),
1025                                          wrbuf_len(w));
1026                     wrbuf_destroy(w);
1027                 }
1028                 else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
1029                 {
1030                     ;
1031                 }
1032                 else if (r->which == Z_External_octet)
1033                 {
1034                     size_t rlen;
1035                     const char *result;
1036                     if (yaz_marc_decode_buf(mt,
1037                                             (char*) r->u.octet_aligned->buf,
1038                                             r->u.octet_aligned->len,
1039                                             &result, &rlen))
1040                     {
1041                         npr->u.databaseRecord =
1042                             z_ext_record_oid(odr_encode(), oid, result, rlen);
1043                         yaz_log(YLOG_LOG, "%sRecoding MARC record",
1044                                 m_session_str);
1045                     }
1046                 }
1047             }
1048         }
1049         if (cd)
1050             yaz_iconv_close(cd);
1051         yaz_marc_destroy(mt);
1052     }
1053 }
1054
1055 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1056                                    const char *backend_charset)
1057 {
1058     int i;
1059     if (!backend_charset)
1060         backend_charset = "MARC-8";
1061     yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1062     yaz_marc_t mt = yaz_marc_create();
1063     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1064     yaz_marc_iconv(mt, cd);
1065     for (i = 0; i < p->num_records; i++)
1066     {
1067         Z_NamePlusRecord *npr = p->records[i];
1068         if (npr->which == Z_NamePlusRecord_databaseRecord)
1069         {
1070             Z_External *r = npr->u.databaseRecord;
1071             if (r->which == Z_External_OPAC)
1072             {
1073                 WRBUF w = wrbuf_alloc();
1074
1075                 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1076                 npr->u.databaseRecord = z_ext_record_oid(
1077                     odr_encode(), yaz_oid_recsyn_xml,
1078                     wrbuf_buf(w), wrbuf_len(w));
1079                 wrbuf_destroy(w);
1080             }
1081             else if (r->which == Z_External_octet)
1082             {
1083                 size_t rlen;
1084                 const char *result;
1085                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1086                                         r->u.octet_aligned->len,
1087                                         &result, &rlen))
1088                 {
1089                     npr->u.databaseRecord =
1090                         z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
1091                                          result, rlen);
1092                 }
1093             }
1094         }
1095     }
1096     if (cd)
1097         yaz_iconv_close(cd);
1098     yaz_marc_destroy(mt);
1099 }
1100
1101 void Yaz_Proxy::logtime()
1102 {
1103 #if HAVE_GETTIMEOFDAY
1104     struct timeval *tv = (struct timeval*) m_time_tv;
1105     if (tv->tv_sec)
1106     {
1107         struct timeval tv1;
1108         gettimeofday(&tv1, 0);
1109         long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1110             (tv1.tv_usec - tv->tv_usec);
1111         if (diff >= 0)
1112             yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1113                     diff/1000000, (diff/1000)%1000);
1114     }
1115     tv->tv_sec = 0;
1116     tv->tv_usec = 0;
1117 #endif
1118 }
1119
1120 int Yaz_Proxy::send_http_response(int code)
1121 {
1122     ODR o = odr_encode();
1123     Z_GDU *gdu = z_get_HTTP_Response(o, code);
1124     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1125     if (m_http_version)
1126         hres->version = odr_strdup(o, m_http_version);
1127     if (m_http_keepalive)
1128         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1129     else
1130         timeout(0);
1131     if (code == 401)
1132         z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", 
1133                           "Basic realm=\"YAZ Proxy\"");
1134
1135
1136     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1137     {
1138         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1139                  gdu_name(gdu));
1140     }
1141     int len;
1142     int r = send_GDU(gdu, &len);
1143     m_bytes_sent += len;
1144     m_bw_stat.add_bytes(len);
1145     logtime();
1146
1147     recv_GDU_more(true);
1148
1149     return r;
1150 }
1151
1152 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1153 {
1154     ODR o = odr_encode();
1155     const char *ctype = "text/xml";
1156     Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1157     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1158     if (m_http_version)
1159         hres->version = odr_strdup(o, m_http_version);
1160     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1161     if (m_http_keepalive)
1162         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1163     else
1164         timeout(0);
1165     if (http_code == 401)
1166         z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1167
1168     static Z_SOAP_Handler soap_handlers[2] = {
1169 #if YAZ_HAVE_XSLT
1170         {"http://www.loc.gov/zing/srw/", 0,
1171          (Z_SOAP_fun) yaz_srw_codec},
1172 #endif
1173         {0, 0, 0}
1174     };
1175
1176     Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1177     soap_package->which = Z_SOAP_generic;
1178     soap_package->u.generic =
1179         (Z_SOAP_Generic *) odr_malloc(o,  sizeof(*soap_package->u.generic));
1180     soap_package->u.generic->no = 0;
1181     soap_package->u.generic->ns = soap_handlers[0].ns;
1182     soap_package->u.generic->p = (void *) srw_pdu;
1183     soap_package->ns = m_soap_ns;
1184     z_soap_codec_enc_xsl(o, &soap_package,
1185                          &hres->content_buf, &hres->content_len,
1186                          soap_handlers, 0, m_s2z_stylesheet);
1187     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1188     {
1189         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1190                  gdu_name(gdu));
1191     }
1192     int len;
1193     int r = send_GDU(gdu, &len);
1194     m_bytes_sent += len;
1195     m_bw_stat.add_bytes(len);
1196     logtime();
1197
1198     recv_GDU_more(true);
1199
1200     return r;
1201 }
1202
1203 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1204 {
1205     ODR o = odr_encode();
1206     Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1207         odr_malloc(o, sizeof(*diagnostic));
1208     int num_diagnostic = 1;
1209     yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1210     return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1211 }
1212
1213 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1214                              Z_DefaultDiagFormat *ddf)
1215 {
1216     int bib1_code = *ddf->condition;
1217     if (bib1_code == 109)
1218         return 404;
1219     srw_res->num_diagnostics = 1;
1220     srw_res->diagnostics = (Z_SRW_diagnostic *)
1221         odr_malloc(o, sizeof(*srw_res->diagnostics));
1222     yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1223                           yaz_diag_bib1_to_srw(*ddf->condition),
1224                           ddf->u.v2Addinfo);
1225     return 0;
1226 }
1227
1228 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1229 {
1230     ODR o = odr_encode();
1231     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1232     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1233
1234     srw_res->numberOfRecords = odr_intdup (o, hits);
1235     if (records && records->which == Z_Records_DBOSD)
1236     {
1237         srw_res->num_records =
1238             records->u.databaseOrSurDiagnostics->num_records;
1239         int i;
1240         srw_res->records = (Z_SRW_record *)
1241             odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1242         for (i = 0; i < srw_res->num_records; i++)
1243         {
1244             Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1245             if (npr->which != Z_NamePlusRecord_databaseRecord)
1246             {
1247                 srw_res->records[i].recordSchema = "diagnostic";
1248                 srw_res->records[i].recordPacking = m_s2z_packing;
1249                 srw_res->records[i].recordData_buf = "67";
1250                 srw_res->records[i].recordData_len = 2;
1251                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1252                 continue;
1253             }
1254             Z_External *r = npr->u.databaseRecord;
1255
1256             if (r->which == Z_External_octet 
1257                 && !oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
1258             {
1259                 srw_res->records[i].recordSchema = m_schema;
1260                 srw_res->records[i].recordPacking = m_s2z_packing;
1261                 srw_res->records[i].recordData_buf = (char*)
1262                     r->u.octet_aligned->buf;
1263                 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1264                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1265             }
1266             else
1267             {
1268                 srw_res->records[i].recordSchema = "diagnostic";
1269                 srw_res->records[i].recordPacking = m_s2z_packing;
1270                 srw_res->records[i].recordData_buf = "67";
1271                 srw_res->records[i].recordData_len = 2;
1272                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1273             }
1274         }
1275     }
1276     if (records && records->which == Z_Records_NSD)
1277     {
1278         int http_code;
1279         http_code = z_to_srw_diag(odr_encode(), srw_res,
1280                                    records->u.nonSurrogateDiagnostic);
1281         if (http_code)
1282             return send_http_response(http_code);
1283     }
1284     return send_srw_response(srw_pdu);
1285
1286 }
1287
1288 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1289                                         int num_diagnostics, int http_code /* = 200 */)
1290 {
1291     ODR o = odr_encode();
1292     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1293     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1294
1295     srw_res->num_diagnostics = num_diagnostics;
1296     srw_res->diagnostics = diagnostics;
1297     return send_srw_response(srw_pdu, http_code);
1298 }
1299
1300 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1301                                         int num_diagnostics)
1302 {
1303     Yaz_ProxyConfig *cfg = check_reconfigure();
1304     if (cfg)
1305     {
1306         int len;
1307         char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1308                                        m_s2z_database, &len);
1309         if (b)
1310         {
1311             Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1312             Z_SRW_explainResponse *er = res->u.explain_response;
1313
1314             er->record.recordData_buf = b;
1315             er->record.recordData_len = len;
1316             er->record.recordPacking = m_s2z_packing;
1317             er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1318
1319             er->diagnostics = diagnostics;
1320             er->num_diagnostics = num_diagnostics;
1321             return send_srw_response(res);
1322         }
1323     }
1324     return send_http_response(404);
1325 }
1326
1327 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1328 {
1329     if (m_http_version)
1330     {
1331         if (apdu->which == Z_APDU_initResponse)
1332         {
1333             Z_InitResponse *res = apdu->u.initResponse;
1334             if (*res->result == 0)
1335             {
1336                 send_to_srw_client_error(3, 0);
1337             }
1338             else if (!m_s2z_search_apdu)
1339             {
1340                 send_srw_explain_response(0, 0);
1341             }
1342             else
1343             {
1344                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1345             }
1346         }
1347         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1348         {
1349             m_s2z_search_apdu = 0;
1350             Z_SearchResponse *res = apdu->u.searchResponse;
1351             m_s2z_hit_count = *res->resultCount;
1352             if (res->records && res->records->which == Z_Records_NSD)
1353             {
1354                 send_to_srw_client_ok(0, res->records, 1);
1355             }
1356             else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1357             {
1358                 // adjust
1359                 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1360
1361                 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1362                 {
1363                     if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1364                         > m_s2z_hit_count)
1365                         *pr->numberOfRecordsRequested =
1366                             1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1367                 }
1368                 handle_incoming_Z_PDU(m_s2z_present_apdu);
1369             }
1370             else
1371             {
1372                 m_s2z_present_apdu = 0;
1373                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1374             }
1375         }
1376         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1377         {
1378             int start =
1379                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1380
1381             m_s2z_present_apdu = 0;
1382             Z_PresentResponse *res = apdu->u.presentResponse;
1383             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1384         }
1385     }
1386     else
1387     {
1388         int len = 0;
1389         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1390             yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1391                      apdu_name(apdu));
1392         int r = send_Z_PDU(apdu, &len);
1393         m_bytes_sent += len;
1394         m_bw_stat.add_bytes(len);
1395         logtime();
1396         return r;
1397     }
1398     return 0;
1399 }
1400
1401 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1402 {
1403     int kill_session = 0;
1404     Z_ReferenceId **new_id = get_referenceIdP(apdu);
1405
1406     if (new_id)
1407         *new_id = m_referenceId;
1408
1409     if (apdu->which == Z_APDU_searchResponse)
1410     {
1411         Z_SearchResponse *sr = apdu->u.searchResponse;
1412         Z_Records *p = sr->records;
1413         if (p && p->which == Z_Records_NSD)
1414         {
1415             Z_DiagRec dr, *dr_p = &dr;
1416             dr.which = Z_DiagRec_defaultFormat;
1417             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1418
1419             *sr->searchStatus = 0;
1420             display_diagrecs(&dr_p, 1);
1421         }
1422         else
1423         {
1424             if (p && p->which == Z_Records_DBOSD)
1425             {
1426                 if (m_backend_type
1427 #if HAVE_USEMARCON
1428                     || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1429 #endif
1430                     )
1431                     convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1432                 if (m_marcxml_mode == marcxml)
1433                     convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1434                                        m_backend_charset);
1435                 else
1436                     convert_records_charset(p->u.databaseOrSurDiagnostics,
1437                                             m_backend_charset);
1438                 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1439                     return 0;
1440
1441             }
1442             if (sr->resultCount)
1443             {
1444                 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1445                         *sr->resultCount);
1446                 if (*sr->resultCount < 0)
1447                 {
1448                     m_flag_invalid_session = 1;
1449                     kill_session = 1;
1450
1451                     *sr->searchStatus = 0;
1452                     sr->records =
1453                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1454                     *sr->resultCount = 0;
1455                 }
1456             }
1457         }
1458     }
1459     else if (apdu->which == Z_APDU_presentResponse)
1460     {
1461         Z_PresentResponse *sr = apdu->u.presentResponse;
1462         Z_Records *p = sr->records;
1463         if (p && p->which == Z_Records_NSD)
1464         {
1465             Z_DiagRec dr, *dr_p = &dr;
1466             dr.which = Z_DiagRec_defaultFormat;
1467             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1468             if (*sr->presentStatus == Z_PresentStatus_success)
1469                 *sr->presentStatus = Z_PresentStatus_failure;
1470             display_diagrecs(&dr_p, 1);
1471         }
1472         if (p && p->which == Z_Records_DBOSD)
1473         {
1474             if (m_backend_type
1475 #if HAVE_USEMARCON
1476                 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1477 #endif
1478                 )
1479                 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1480             if (m_marcxml_mode == marcxml)
1481                 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1482                                    m_backend_charset);
1483             else
1484                 convert_records_charset(p->u.databaseOrSurDiagnostics,
1485                                         m_backend_charset);
1486             if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1487                 return 0;
1488         }
1489     }
1490     else if (apdu->which == Z_APDU_initResponse)
1491     {
1492         //Get and check negotiation record
1493         //from init response.
1494         handle_charset_lang_negotiation(apdu);
1495
1496         if (m_initRequest_options)
1497         {
1498             Z_Options *nopt =
1499                 (Odr_bitmask *)odr_malloc(odr_encode(),
1500                                           sizeof(Odr_bitmask));
1501             ODR_MASK_ZERO(nopt);
1502
1503             int i;
1504             for (i = 0; i<24; i++)
1505                 if (ODR_MASK_GET(m_initRequest_options, i) &&
1506                     ODR_MASK_GET(apdu->u.initResponse->options, i))
1507                     ODR_MASK_SET(nopt, i);
1508             apdu->u.initResponse->options = nopt;
1509         }
1510         if (m_initRequest_version)
1511         {
1512             Z_ProtocolVersion *nopt =
1513                 (Odr_bitmask *)odr_malloc(odr_encode(),
1514                                           sizeof(Odr_bitmask));
1515             ODR_MASK_ZERO(nopt);
1516
1517             int i;
1518             for (i = 0; i<8; i++)
1519                 if (ODR_MASK_GET(m_initRequest_version, i) &&
1520                     ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1521                     ODR_MASK_SET(nopt, i);
1522             apdu->u.initResponse->protocolVersion = nopt;
1523         }
1524         apdu->u.initResponse->preferredMessageSize =
1525             odr_intdup(odr_encode(),
1526                        m_client->m_initResponse_preferredMessageSize >
1527                        m_initRequest_preferredMessageSize ?
1528                        m_initRequest_preferredMessageSize :
1529                        m_client->m_initResponse_preferredMessageSize);
1530         apdu->u.initResponse->maximumRecordSize =
1531             odr_intdup(odr_encode(),
1532                        m_client->m_initResponse_maximumRecordSize >
1533                        m_initRequest_maximumRecordSize ?
1534                        m_initRequest_maximumRecordSize :
1535                        m_client->m_initResponse_maximumRecordSize);
1536     }
1537
1538     int r = send_PDU_convert(apdu);
1539     if (r)
1540         return r;
1541     if (kill_session)
1542     {
1543         delete m_client;
1544         m_client = 0;
1545         m_parent->pre_init();
1546     }
1547     return r;
1548 }
1549
1550 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1551 {
1552     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1553     
1554     odr_reset(m_idAuthentication_odr);
1555     z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1556     m_idAuthentication_ber_buf =
1557         odr_getbuf(m_idAuthentication_odr, 
1558                    &m_idAuthentication_ber_size, 0);
1559 }
1560
1561 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1562 {
1563     return true;
1564 }
1565
1566 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1567 {
1568     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1569     ODR odr = odr_createmem(ODR_ENCODE);
1570
1571     z_IdAuthentication(odr, &t, 1, 0);
1572     int sz;
1573     char *buf = odr_getbuf(odr, &sz, 0);
1574     if (buf && m_idAuthentication_ber_buf
1575         && sz == m_idAuthentication_ber_size
1576         && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1577     {
1578         odr_destroy(odr);
1579         return true;
1580     }
1581     odr_destroy(odr);
1582     if (!buf && !m_idAuthentication_ber_buf)
1583         return true;
1584     return false;
1585 }
1586
1587 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1588 {
1589     int len = 0;
1590     const char *apdu_name_tmp = apdu_name(apdu);
1591     int r = send_Z_PDU(apdu, &len);
1592     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1593         yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1594                  get_session_str(),
1595                  apdu_name_tmp, get_hostname(), len);
1596     m_bytes_sent += len;
1597     return r;
1598 }
1599
1600 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1601 {
1602     if (apdu->which == Z_APDU_presentRequest)
1603     {
1604         Z_PresentRequest *pr = apdu->u.presentRequest;
1605         int toget = *pr->numberOfRecordsRequested;
1606         int start = *pr->resultSetStartPoint;
1607
1608         yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1609                 pr->resultSetId, start, toget);
1610
1611         if (*m_parent->m_optimize == '0')
1612             return apdu;
1613
1614         if (!m_client->m_last_resultSetId)
1615         {
1616             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1617             new_apdu->u.presentResponse->records =
1618                 create_nonSurrogateDiagnostics(
1619                     odr_encode(), 
1620                     YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1621                     pr->resultSetId);
1622             send_to_client(new_apdu);
1623             return 0;
1624         }
1625         if (start < 1 || toget < 0)
1626         {
1627             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1628             new_apdu->u.presentResponse->records =
1629                 create_nonSurrogateDiagnostics(
1630                     odr_encode(), 
1631                     YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 
1632                     0);
1633             send_to_client(new_apdu);
1634             return 0;
1635         }
1636         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1637         {
1638             if (start+toget-1 > m_client->m_last_resultCount)
1639             {
1640                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1641                 new_apdu->u.presentResponse->records =
1642                     create_nonSurrogateDiagnostics(
1643                         odr_encode(), 
1644                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1645                         0);
1646                 send_to_client(new_apdu);
1647                 return 0;
1648             }
1649             Z_NamePlusRecordList *npr;
1650 #if 0
1651             yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1652                     m_session_str, start, toget, yaz_z3950oid_to_str(
1653                         pr->preferredRecordSyntax, &oclass));
1654 #endif
1655             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1656                                           pr->preferredRecordSyntax,
1657                                           pr->recordComposition))
1658             {
1659                 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1660                          m_session_str);
1661                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1662                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1663
1664                 new_apdu->u.presentResponse->numberOfRecordsReturned
1665                     = odr_intdup(odr_encode(), toget);
1666
1667                 new_apdu->u.presentResponse->records = (Z_Records*)
1668                     odr_malloc(odr_encode(), sizeof(Z_Records));
1669                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1670                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1671                 new_apdu->u.presentResponse->nextResultSetPosition =
1672                     odr_intdup(odr_encode(), start+toget);
1673
1674                 send_to_client(new_apdu);
1675                 return 0;
1676             }
1677         }
1678     }
1679
1680     if (apdu->which != Z_APDU_searchRequest)
1681         return apdu;
1682     Z_SearchRequest *sr = apdu->u.searchRequest;
1683     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1684     Yaz_Z_Databases this_databases;
1685
1686     this_databases.set(sr->num_databaseNames, (const char **)
1687                        sr->databaseNames);
1688
1689     this_query->set_Z_Query(sr->query);
1690
1691     // Check for non-negative piggyback params.
1692     if (*sr->smallSetUpperBound < 0
1693         || *sr->largeSetLowerBound < 0
1694         || *sr->mediumSetPresentNumber < 0)
1695     {
1696         Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1697         // Not a present request.. But can't find better diagnostic
1698         new_apdu->u.searchResponse->records =
1699             create_nonSurrogateDiagnostics(
1700                 odr_encode(), 
1701                 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1702         send_to_client(new_apdu);
1703         return 0;
1704     }
1705
1706     char query_str[4096];
1707     this_query->print(query_str, sizeof(query_str)-1);
1708     yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1709
1710     if (*m_parent->m_optimize != '0' &&
1711         m_client->m_last_ok && m_client->m_last_query &&
1712         m_client->m_last_query->match(this_query) &&
1713         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1714         m_client->m_last_databases.match(this_databases))
1715     {
1716         delete this_query;
1717         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1718             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1719         {
1720             Z_NamePlusRecordList *npr;
1721             int toget = *sr->mediumSetPresentNumber;
1722             Z_RecordComposition *comp = 0;
1723
1724             if (toget > m_client->m_last_resultCount)
1725                 toget = m_client->m_last_resultCount;
1726             
1727             if (sr->mediumSetElementSetNames)
1728             {
1729                 comp = (Z_RecordComposition *)
1730                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1731                 comp->which = Z_RecordComp_simple;
1732                 comp->u.simple = sr->mediumSetElementSetNames;
1733             }
1734
1735             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1736                                           sr->preferredRecordSyntax, comp))
1737             {
1738                 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1739                          m_session_str);
1740                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1741                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1742                 new_apdu->u.searchResponse->resultCount =
1743                     &m_client->m_last_resultCount;
1744
1745                 new_apdu->u.searchResponse->numberOfRecordsReturned
1746                     = odr_intdup(odr_encode(), toget);
1747
1748                 new_apdu->u.searchResponse->presentStatus =
1749                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1750                 new_apdu->u.searchResponse->records = (Z_Records*)
1751                     odr_malloc(odr_encode(), sizeof(Z_Records));
1752                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1753                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1754                 new_apdu->u.searchResponse->nextResultSetPosition =
1755                     odr_intdup(odr_encode(), toget+1);
1756                 send_to_client(new_apdu);
1757                 return 0;
1758             }
1759             else
1760             {
1761                 // medium Set
1762                 // send present request (medium size)
1763                 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1764                          m_session_str);
1765
1766                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1767                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1768                 pr->referenceId = sr->referenceId;
1769                 pr->resultSetId = sr->resultSetName;
1770                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1771                 *pr->numberOfRecordsRequested = toget;
1772                 pr->recordComposition = comp;
1773                 m_client->m_sr_transform = 1;
1774                 return new_apdu;
1775             }
1776         }
1777         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1778             m_client->m_last_resultCount <= 0)
1779         {
1780             // large set. Return pseudo-search response immediately
1781             yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1782                      m_session_str);
1783             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1784             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1785             new_apdu->u.searchResponse->resultCount =
1786                 &m_client->m_last_resultCount;
1787             send_to_client(new_apdu);
1788             return 0;
1789         }
1790         else
1791         {
1792             Z_NamePlusRecordList *npr;
1793             int toget = m_client->m_last_resultCount;
1794             Z_RecordComposition *comp = 0;
1795             // small set
1796             // send a present request (small set)
1797
1798             if (sr->smallSetElementSetNames)
1799             {
1800                 comp = (Z_RecordComposition *)
1801                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1802                 comp->which = Z_RecordComp_simple;
1803                 comp->u.simple = sr->smallSetElementSetNames;
1804             }
1805
1806             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1807                                           sr->preferredRecordSyntax, comp))
1808             {
1809                 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1810                          m_session_str);
1811                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1812                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1813                 new_apdu->u.searchResponse->resultCount =
1814                     &m_client->m_last_resultCount;
1815
1816                 new_apdu->u.searchResponse->numberOfRecordsReturned
1817                     = odr_intdup(odr_encode(), toget);
1818
1819                 new_apdu->u.searchResponse->presentStatus =
1820                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1821                 new_apdu->u.searchResponse->records = (Z_Records*)
1822                     odr_malloc(odr_encode(), sizeof(Z_Records));
1823                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1824                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1825                 new_apdu->u.searchResponse->nextResultSetPosition =
1826                     odr_intdup(odr_encode(), toget+1);
1827                 send_to_client(new_apdu);
1828                 return 0;
1829             }
1830             else
1831             {
1832                 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1833                          m_session_str);
1834                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1835                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1836                 pr->referenceId = sr->referenceId;
1837                 pr->resultSetId = sr->resultSetName;
1838                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1839                 *pr->numberOfRecordsRequested = toget;
1840                 pr->recordComposition = comp;
1841                 m_client->m_sr_transform = 1;
1842                 return new_apdu;
1843             }
1844         }
1845     }
1846     else  // query doesn't match
1847     {
1848         delete m_client->m_last_query;
1849         m_client->m_last_query = this_query;
1850         m_client->m_last_ok = 0;
1851         m_client->m_cache.clear();
1852         m_client->m_resultSetStartPoint = 0;
1853
1854         xfree (m_client->m_last_resultSetId);
1855         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1856
1857         m_client->m_last_databases.set(sr->num_databaseNames,
1858                                        (const char **) sr->databaseNames);
1859     }
1860     return apdu;
1861 }
1862
1863
1864 void Yaz_Proxy::inc_request_no()
1865 {
1866     m_request_no++;
1867     char *cp = m_session_str + strlen(m_session_str)-1;
1868     if (*cp == ' ')
1869         cp--;
1870     while (*cp && *cp != ' ')
1871         cp--;
1872     if (*cp)
1873         sprintf(cp+1, "%d ", m_request_no);
1874 }
1875
1876 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1877 {
1878     inc_request_no();
1879
1880     m_bytes_recv += len;
1881
1882     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1883         yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1884                  m_session_str, gdu_name(apdu), len);
1885
1886 #if 0
1887     // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1888     if (apdu->which == Z_GDU_Z3950 
1889         && apdu->u.z3950->which == Z_APDU_searchRequest)
1890     {
1891         Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1892         if (req->query && req->query->which == Z_Query_type_1)
1893         {
1894             Z_RPNQuery *rpnquery = req->query->u.type_1;
1895             if (rpnquery->attributeSetId)
1896             {
1897                 rpnquery->attributeSetId[0] = -2;
1898                 rpnquery->attributeSetId[1] = -1;
1899                 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1900             }
1901         }
1902     }
1903 #endif
1904
1905 #if HAVE_GETTIMEOFDAY
1906     gettimeofday((struct timeval *) m_time_tv, 0);
1907 #endif
1908     m_bw_stat.add_bytes(len);
1909     m_pdu_stat.add_bytes(1);
1910
1911     GDU *gdu = new GDU(apdu);
1912
1913     if (gdu->get() == 0)
1914     {
1915         delete gdu;
1916         yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1917         m_in_queue.clear();
1918         dec_ref();
1919         return;
1920     }
1921     m_in_queue.enqueue(gdu);
1922     recv_GDU_more(false);
1923 }
1924
1925 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1926 {
1927     if (z_gdu->which == Z_GDU_HTTP_Request)
1928     {
1929         Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1930         const char *x_forwarded_for =
1931             z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1932         if (x_forwarded_for)
1933         {
1934             xfree(m_peername);
1935             m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1936             sprintf(m_peername, "tcp:%s", x_forwarded_for);
1937             
1938             yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1939                     m_peername);
1940             if (m_log_mask & PROXY_LOG_IP_CLIENT)
1941                 sprintf(m_session_str, "%ld:%d %.80s %d ",
1942                         (long) time(0), m_session_no, m_peername, m_request_no);
1943             else
1944                 sprintf(m_session_str, "%ld:%d %d ",
1945                         (long) time(0), m_session_no, m_request_no);
1946         }
1947     }
1948 }
1949
1950 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1951 {
1952
1953     m_parent->m_connect.cleanup(false);
1954     m_parent->m_connect.add_connect(m_peername);
1955
1956     int connect_total = m_parent->m_connect.get_total(m_peername);
1957     int max_connect = m_parent->m_max_connect;
1958
1959     if (max_connect && connect_total > max_connect)
1960     {
1961         yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1962                 m_session_str, connect_total, max_connect);
1963         block = true;
1964     }
1965     else 
1966         block = false;
1967     yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
1968             connect_total);
1969     
1970     int limit_connect = m_parent->m_limit_connect;
1971     if (limit_connect)
1972         reduce = connect_total / limit_connect;
1973     else
1974         reduce = 0;
1975 }
1976
1977 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1978 {
1979     HTTP_Forwarded(gdu->get());
1980
1981     int reduce = 0;
1982     
1983     if (m_request_no == 1)
1984     {
1985         bool block = false;
1986         
1987         connect_stat(block, reduce);
1988
1989         if (block)
1990         {
1991             m_timeout_mode = timeout_busy;
1992             timeout(0);
1993             return;
1994         }
1995     }
1996
1997     int bw_total = m_bw_stat.get_total();
1998     int pdu_total = m_pdu_stat.get_total();
1999     int search_total = m_search_stat.get_total();
2000
2001     assert(m_timeout_mode == timeout_busy);
2002     assert(m_timeout_gdu == 0);
2003
2004     if (m_search_max)
2005         reduce += search_total / m_search_max;
2006     if (m_bw_max)
2007         reduce += (bw_total/m_bw_max);
2008     if (m_pdu_max)
2009     {
2010         if (pdu_total > m_pdu_max)
2011         {
2012             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2013             reduce = (reduce > nreduce) ? reduce : nreduce;
2014         }
2015     }
2016     m_http_version = 0;
2017
2018 #if 0
2019     /* uncomment to force a big reduce */
2020     m_timeout_mode = timeout_reduce;
2021     m_timeout_gdu = gdu;
2022     timeout(3);       // call us reduce seconds later
2023     return;
2024 #endif
2025     if (reduce)
2026     {
2027         yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2028                 m_session_str, reduce, bw_total, pdu_total, search_total,
2029                 m_bw_max, m_pdu_max, m_search_max);
2030
2031         m_timeout_mode = timeout_reduce;
2032         m_timeout_gdu = gdu;
2033         timeout(reduce);       // call us reduce seconds later
2034     }
2035     else
2036         recv_GDU_normal(gdu);
2037 }
2038
2039 void Yaz_Proxy::recv_GDU_more(bool normal)
2040 {
2041     GDU *g;
2042     if (normal && m_timeout_mode == timeout_busy)
2043         m_timeout_mode = timeout_normal;
2044     while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2045     {
2046         m_timeout_mode = timeout_busy;
2047         inc_ref();
2048         recv_GDU_reduce(g);
2049         if (dec_ref())
2050             break;
2051     }
2052 }
2053
2054 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2055 {
2056     Z_GDU *apdu = 0;
2057     gdu->move_away_gdu(odr_decode(), &apdu);
2058     delete gdu;
2059
2060     if (apdu->which == Z_GDU_Z3950)
2061         handle_incoming_Z_PDU(apdu->u.z3950);
2062     else if (apdu->which == Z_GDU_HTTP_Request)
2063         handle_incoming_HTTP(apdu->u.HTTP_Request);
2064 }
2065
2066 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2067 {
2068     if (m_max_record_retrieve)
2069     {
2070         if (apdu->which == Z_APDU_presentRequest)
2071         {
2072             Z_PresentRequest *pr = apdu->u.presentRequest;
2073             if (pr->numberOfRecordsRequested &&
2074                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2075                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2076         }
2077     }
2078 }
2079
2080 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2081 {
2082     if (apdu->which == Z_APDU_initRequest)
2083     {
2084         if (m_initRequest_options &&
2085             !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2086             (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2087         {
2088             // There is no negotiation proposal from
2089             // client's side. OK. The proxy negotiation
2090             // in use, only.
2091             Z_InitRequest *initRequest = apdu->u.initRequest;
2092             Z_OtherInformation **otherInfo;
2093             Z_OtherInformationUnit *oi;
2094             get_otherInfoAPDU(apdu, &otherInfo);
2095             oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2096             if (oi)
2097             {
2098                 ODR_MASK_SET(initRequest->options,
2099                     Z_Options_negotiationModel);
2100                 oi->which = Z_OtherInfo_externallyDefinedInfo;
2101                 oi->information.externallyDefinedInfo =
2102                 yaz_set_proposal_charneg(odr_encode(),
2103                     (const char**)&m_proxy_negotiation_charset,
2104                     m_proxy_negotiation_charset ? 1:0,
2105                     (const char**)&m_proxy_negotiation_lang,
2106                     m_proxy_negotiation_lang ? 1:0,
2107                     1);
2108             }
2109         }
2110         else if (m_initRequest_options &&
2111                  ODR_MASK_GET(m_initRequest_options,
2112                               Z_Options_negotiationModel) &&
2113                  m_charset_converter->get_target_query_charset())
2114         {
2115             yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2116                     m_session_str,
2117                     m_charset_converter->get_target_query_charset());
2118             Z_InitRequest *initRequest = apdu->u.initRequest;
2119             Z_CharSetandLanguageNegotiation *negotiation =
2120                 yaz_get_charneg_record (initRequest->otherInfo);
2121             if (negotiation &&
2122                 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2123             {
2124                 NMEM nmem = nmem_create();
2125                 char **charsets = 0;
2126                 int num_charsets = 0;
2127                 char **langs = 0;
2128                 int num_langs = 0;
2129                 int selected = 0;
2130                 yaz_get_proposal_charneg (nmem, negotiation,
2131                                           &charsets, &num_charsets,
2132                                           &langs, &num_langs, &selected);
2133                 int i;
2134                 for (i = 0; i<num_charsets; i++)
2135                     yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2136                             charsets[i]);
2137                 for (i = 0; i<num_langs; i++)
2138                     yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2139                             langs[i]);
2140
2141                 const char *t_charset =
2142                     m_charset_converter->get_target_query_charset();
2143                 // sweep through charsets and pick the first supported
2144                 // conversion
2145                 for (i = 0; i<num_charsets; i++)
2146                 {
2147                     const char *c_charset = charsets[i];
2148                     if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2149                         break;
2150                 }
2151                 if (i != num_charsets)
2152                 {
2153                     // got one .. set up ODR for reverse direction
2154                     const char *c_charset = charsets[i];
2155                     odr_set_charset(odr_encode(), c_charset, t_charset);
2156                     m_charset_converter->set_client_query_charset(c_charset);
2157                     m_charset_converter->set_client_charset_selected(selected);
2158                 }
2159                 nmem_destroy(nmem);
2160                 ODR_MASK_CLEAR(m_initRequest_options,
2161                                Z_Options_negotiationModel);
2162                 yaz_del_charneg_record(&initRequest->otherInfo);
2163             }
2164             else
2165             {
2166                 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2167                         m_session_str);
2168             }
2169         }
2170         else if (m_charset_converter->get_target_query_charset() &&
2171             m_proxy_negotiation_default_charset)
2172         {
2173             m_charset_converter->
2174                 set_client_query_charset(m_proxy_negotiation_default_charset);
2175         }
2176     }
2177     else if (apdu->which == Z_APDU_initResponse)
2178     {
2179         Z_InitResponse *initResponse = apdu->u.initResponse;
2180         Z_OtherInformation **otherInfo;
2181         get_otherInfoAPDU(apdu, &otherInfo);
2182         
2183         Z_CharSetandLanguageNegotiation *charneg = 0;
2184
2185         if (otherInfo && *otherInfo && 
2186             ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2187             && (charneg = yaz_get_charneg_record(*otherInfo)))
2188         {
2189             char *charset = 0;
2190             char *lang = 0;
2191             int selected = 0;
2192
2193             yaz_get_response_charneg(m_referenceId_mem, charneg,
2194                 &charset, &lang, &selected);
2195
2196             yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2197                 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2198
2199             if (m_initRequest_options &&
2200                 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2201             {
2202                 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2203                     m_session_str);
2204             }
2205             else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2206             {
2207                 // negotiation-charset, negotiation-lang
2208                 // elements of config file in use.
2209
2210                 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2211                     m_session_str);
2212
2213                 // clear negotiation option.
2214                 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2215
2216                 // Delete negotiation (charneg-3) entry.
2217                 yaz_del_charneg_record(otherInfo);
2218             }
2219         }
2220         else
2221         {
2222             if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2223             {
2224                 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2225                         m_session_str);
2226             }
2227             else if (m_charset_converter->get_client_query_charset())
2228             {
2229                 Z_OtherInformation **otherInfo;
2230                 Z_OtherInformationUnit *oi;
2231                 get_otherInfoAPDU(apdu, &otherInfo);
2232                 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2233                 if (oi)
2234                 {
2235                     ODR_MASK_SET(initResponse->options,
2236                                  Z_Options_negotiationModel);
2237                     if (m_initRequest_options)
2238                         ODR_MASK_SET(m_initRequest_options,
2239                                      Z_Options_negotiationModel);
2240                     
2241                     oi->which = Z_OtherInfo_externallyDefinedInfo;    
2242                     oi->information.externallyDefinedInfo =
2243                         yaz_set_response_charneg(
2244                             odr_encode(),
2245                             m_charset_converter->get_client_query_charset(),
2246                             0 /* no lang */,
2247                             m_charset_converter->get_client_charset_selected());
2248                 }
2249             }
2250         }
2251     }
2252 }
2253
2254 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2255                                                      int error,
2256                                                      const char *addinfo)
2257 {
2258     Z_Records *rec = (Z_Records *)
2259         odr_malloc (odr, sizeof(*rec));
2260     int *err = (int *)
2261         odr_malloc (odr, sizeof(*err));
2262     Z_DiagRec *drec = (Z_DiagRec *)
2263         odr_malloc (odr, sizeof(*drec));
2264     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2265         odr_malloc (odr, sizeof(*dr));
2266     *err = error;
2267     rec->which = Z_Records_NSD;
2268     rec->u.nonSurrogateDiagnostic = dr;
2269     dr->diagnosticSetId = odr_oiddup(odr, yaz_oid_diagset_bib_1);
2270     dr->condition = err;
2271     dr->which = Z_DefaultDiagFormat_v2Addinfo;
2272     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2273     return rec;
2274 }
2275
2276 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2277 {
2278     if (apdu->which == Z_APDU_searchRequest &&
2279         apdu->u.searchRequest->query &&
2280         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2281         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2282     {
2283         Z_RPNQuery *rpnquery = 0;
2284         Z_SearchRequest *sr = apdu->u.searchRequest;
2285         char *addinfo = 0;
2286
2287         yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2288                 sr->query->u.type_104->u.cql);
2289
2290         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2291                                           &rpnquery, odr_encode(),
2292                                           &addinfo);
2293         if (r == -3)
2294             yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2295         else if (r)
2296         {
2297             yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2298             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2299
2300             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2301             new_apdu->u.searchResponse->records =
2302                 create_nonSurrogateDiagnostics(odr_encode(),
2303                                                yaz_diag_srw_to_bib1(r),
2304                                                addinfo);
2305             *new_apdu->u.searchResponse->searchStatus = 0;
2306
2307             send_to_client(new_apdu);
2308
2309             return 0;
2310         }
2311         else
2312         {
2313             sr->query->which = Z_Query_type_1;
2314             sr->query->u.type_1 = rpnquery;
2315         }
2316         return apdu;
2317     }
2318     return apdu;
2319 }
2320
2321 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2322 {
2323     if (apdu->which == Z_APDU_searchRequest &&
2324         apdu->u.searchRequest->query)
2325     {
2326         if (apdu->u.searchRequest->query->which == Z_Query_type_1
2327             || apdu->u.searchRequest->query->which == Z_Query_type_101)
2328         {
2329             if (m_http_version)
2330                 m_charset_converter->set_client_query_charset("UTF-8");
2331             Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2332             m_charset_converter->convert_type_1(rpnquery, odr_encode());
2333         }
2334     }
2335     return apdu;
2336 }
2337
2338
2339 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2340 {
2341     if (apdu->which == Z_APDU_searchRequest)
2342     {
2343         Z_SearchRequest *sr = apdu->u.searchRequest;
2344         int err = 0;
2345         char *addinfo = 0;
2346
2347         Yaz_ProxyConfig *cfg = check_reconfigure();
2348         if (cfg)
2349             err = cfg->check_query(odr_encode(), m_default_target,
2350                                    sr->query, &addinfo);
2351         if (err)
2352         {
2353             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2354
2355             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2356             new_apdu->u.searchResponse->records =
2357                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2358             *new_apdu->u.searchResponse->searchStatus = 0;
2359
2360             send_to_client(new_apdu);
2361
2362             return 0;
2363         }
2364     }
2365     return apdu;
2366 }
2367
2368 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2369 {
2370     if (apdu->which != Z_APDU_initRequest)
2371         return 1;  // pass if no init request
2372     Z_InitRequest *req = apdu->u.initRequest;
2373
2374     Yaz_ProxyConfig *cfg = check_reconfigure();
2375     if (!cfg)
2376         return 1;  // pass if no config
2377
2378     int ret;
2379     if (req->idAuthentication == 0)
2380     {
2381         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2382                                          m_peername);
2383     }
2384     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2385     {
2386         ret = cfg->client_authentication(
2387             m_default_target,
2388             req->idAuthentication->u.idPass->userId,
2389             req->idAuthentication->u.idPass->groupId,
2390             req->idAuthentication->u.idPass->password,
2391             m_peername);
2392     }
2393     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2394     {
2395         char user[64], pass[64];
2396         *user = '\0';
2397         *pass = '\0';
2398         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2399         ret = cfg->client_authentication(m_default_target, user, 0, pass,
2400                                          m_peername);
2401     }
2402     else
2403         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2404                                          m_peername);
2405     return ret;
2406 }
2407
2408 int Yaz_Proxy::handle_global_authentication(Z_APDU *apdu)
2409 {
2410     if (apdu->which != Z_APDU_initRequest)
2411         return 1;  // pass if no init request
2412     Z_InitRequest *req = apdu->u.initRequest;
2413
2414     Yaz_ProxyConfig *cfg = check_reconfigure();
2415     if (!cfg)
2416         return 1;  // pass if no config
2417
2418     int ret;
2419     if (req->idAuthentication == 0)
2420     {
2421         ret = cfg->global_client_authentication(0, 0, 0,
2422                                                 m_peername);
2423     }
2424     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2425     {
2426         ret = cfg->global_client_authentication(
2427             req->idAuthentication->u.idPass->userId,
2428             req->idAuthentication->u.idPass->groupId,
2429             req->idAuthentication->u.idPass->password,
2430             m_peername);
2431     }
2432     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2433     {
2434         char user[64], pass[64];
2435         *user = '\0';
2436         *pass = '\0';
2437         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2438         ret = cfg->global_client_authentication(user, 0, pass,
2439                                                 m_peername);
2440     }
2441     else
2442         ret = cfg->global_client_authentication(0, 0, 0, m_peername);
2443     return ret;
2444 }
2445
2446 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2447 {
2448     m_marcxml_mode = none;
2449     if (apdu->which == Z_APDU_searchRequest)
2450     {
2451         Z_SearchRequest *sr = apdu->u.searchRequest;
2452         int err = 0;
2453         char *addinfo = 0;
2454         Yaz_ProxyConfig *cfg = check_reconfigure();
2455
2456         Z_RecordComposition rc_temp, *rc = 0;
2457         if (sr->smallSetElementSetNames)
2458         {
2459             rc_temp.which = Z_RecordComp_simple;
2460             rc_temp.u.simple = sr->smallSetElementSetNames;
2461             rc = &rc_temp;
2462         }
2463
2464         if (sr->preferredRecordSyntax)
2465             oid_oidcpy(m_frontend_type, sr->preferredRecordSyntax);
2466         else
2467             m_frontend_type[0] = -1;
2468
2469         char *stylesheet_name = 0;
2470         if (cfg)
2471             err = cfg->check_syntax(odr_encode(),
2472                                     m_default_target,
2473                                     sr->preferredRecordSyntax, rc,
2474                                     &addinfo, &stylesheet_name, &m_schema,
2475                                     &m_backend_type, &m_backend_charset,
2476                                     &m_usemarcon_ini_stage1,
2477                                     &m_usemarcon_ini_stage2);
2478         if (stylesheet_name)
2479         {
2480             m_parent->low_socket_close();
2481
2482 #if YAZ_HAVE_XSLT
2483             if (m_stylesheet_xsp)
2484                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2485             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2486                                                        stylesheet_name);
2487 #endif
2488             m_stylesheet_offset = 0;
2489             xfree(stylesheet_name);
2490
2491             m_parent->low_socket_open();
2492         }
2493         if (err == -1)
2494         {
2495             sr->smallSetElementSetNames = 0;
2496             sr->mediumSetElementSetNames = 0;
2497             m_marcxml_mode = marcxml;
2498             sr->preferredRecordSyntax =
2499                 yaz_string_to_oid_odr(
2500                     yaz_oid_std(), CLASS_RECSYN,
2501                     m_backend_type ? m_backend_type : "usmarc", 
2502                     odr_encode());
2503         }
2504         else if (err)
2505         {
2506             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2507
2508             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2509             new_apdu->u.searchResponse->records =
2510                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2511             *new_apdu->u.searchResponse->searchStatus = 0;
2512
2513             send_to_client(new_apdu);
2514
2515             return 0;
2516         }
2517         else if (m_backend_type)
2518         {
2519             sr->preferredRecordSyntax =
2520                 yaz_string_to_oid_odr(yaz_oid_std(), CLASS_RECSYN, 
2521                                       m_backend_type, odr_encode());
2522         }
2523     }
2524     else if (apdu->which == Z_APDU_presentRequest)
2525     {
2526         Z_PresentRequest *pr = apdu->u.presentRequest;
2527         int err = 0;
2528         char *addinfo = 0;
2529         Yaz_ProxyConfig *cfg = check_reconfigure();
2530
2531         if (pr->preferredRecordSyntax)
2532             oid_oidcpy(m_frontend_type, pr->preferredRecordSyntax);
2533         else
2534             m_frontend_type[0] = -1;
2535
2536         char *stylesheet_name = 0;
2537         if (cfg)
2538             err = cfg->check_syntax(odr_encode(), m_default_target,
2539                                     pr->preferredRecordSyntax,
2540                                     pr->recordComposition,
2541                                     &addinfo, &stylesheet_name, &m_schema,
2542                                     &m_backend_type, &m_backend_charset,
2543                                     &m_usemarcon_ini_stage1,
2544                                     &m_usemarcon_ini_stage2
2545                                     );
2546         if (stylesheet_name)
2547         {
2548             m_parent->low_socket_close();
2549
2550 #if YAZ_HAVE_XSLT
2551             if (m_stylesheet_xsp)
2552                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2553             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2554                                                        stylesheet_name);
2555 #endif
2556             m_stylesheet_offset = 0;
2557             xfree(stylesheet_name);
2558
2559             m_parent->low_socket_open();
2560         }
2561         if (err == -1)
2562         {
2563             pr->recordComposition = 0;
2564             m_marcxml_mode = marcxml;
2565
2566             pr->preferredRecordSyntax =
2567                 yaz_string_to_oid_odr(
2568                     yaz_oid_std(), CLASS_RECSYN,
2569                     m_backend_type ? m_backend_type : "usmarc", 
2570                     odr_encode());
2571         }
2572         else if (err)
2573         {
2574             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2575
2576             new_apdu->u.presentResponse->referenceId = pr->referenceId;
2577             new_apdu->u.presentResponse->records =
2578                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2579             *new_apdu->u.presentResponse->presentStatus =
2580                 Z_PresentStatus_failure;
2581
2582             send_to_client(new_apdu);
2583
2584             return 0;
2585         }
2586         else if (m_backend_type)
2587         {
2588             pr->preferredRecordSyntax =
2589                 yaz_string_to_oid_odr(yaz_oid_std(),
2590                                       CLASS_RECSYN, m_backend_type, 
2591                                       odr_encode());
2592         }
2593     }
2594     return apdu;
2595 }
2596
2597 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2598 {
2599     if (!schema)
2600         return 0;
2601     Z_ElementSetNames *esn = (Z_ElementSetNames *)
2602         odr_malloc(o, sizeof(Z_ElementSetNames));
2603     esn->which = Z_ElementSetNames_generic;
2604     esn->u.generic = odr_strdup(o, schema);
2605     return esn;
2606 }
2607
2608 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2609 {
2610     const char *t = 0;
2611     Yaz_ProxyConfig *cfg = check_reconfigure();
2612     if (cfg)
2613         t = cfg->get_explain_name(db, backend_db);
2614
2615     if (m_client && m_default_target && t && strcmp(m_default_target, t))
2616     {
2617         releaseClient();
2618     }
2619
2620     if (t)
2621     {
2622         xfree(m_default_target);
2623         m_default_target = xstrdup(t);
2624     }
2625 }
2626
2627 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2628 {
2629     struct stat sbuf;
2630     if (strcmp(hreq->method, "GET"))
2631         return 0;
2632     if (hreq->path[0] != '/')
2633         return 0;
2634     const char *cp = hreq->path;
2635     while (*cp)
2636     {
2637         if (*cp == '/' && strchr("/.", cp[1]))
2638             return 0;
2639         cp++;
2640     }
2641
2642     Yaz_ProxyConfig *cfg = check_reconfigure();
2643
2644     if (!cfg->get_file_access_info(hreq->path+1))
2645         return 0;
2646
2647     const char *fname = hreq->path+1;
2648     if (stat(fname, &sbuf))
2649     {
2650         yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2651                 fname);
2652         return 0;
2653     }
2654     if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2655     {
2656         yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2657         return 0;
2658     }
2659     if (sbuf.st_size > (off_t) 1000000)
2660     {
2661         yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2662                 fname);
2663         return 0;
2664     }
2665
2666     ODR o = odr_encode();
2667
2668     const char *ctype = cfg->check_mime_type(fname);
2669     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2670     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2671     if (m_http_version)
2672         hres->version = odr_strdup(o, m_http_version);
2673     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2674     if (m_http_keepalive)
2675         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2676     else
2677         timeout(0);
2678
2679     hres->content_len = sbuf.st_size;
2680     hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2681     FILE *f = fopen(fname, "rb");
2682     if (f)
2683     {
2684         fread(hres->content_buf, 1, hres->content_len, f);
2685         fclose(f);
2686     }
2687     else
2688     {
2689         return 0;
2690     }
2691     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2692     {
2693         yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2694                  fname);
2695     }
2696     int len;
2697     send_GDU(gdu, &len);
2698     recv_GDU_more(true);
2699     return 1;
2700 }
2701
2702 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2703 {
2704     if (m_s2z_odr_init)
2705     {
2706         odr_destroy(m_s2z_odr_init);
2707         m_s2z_odr_init = 0;
2708     }
2709     if (m_s2z_odr_search)
2710     {
2711         odr_destroy(m_s2z_odr_search);
2712         m_s2z_odr_search = 0;
2713     }
2714
2715     m_http_keepalive = 0;
2716     m_http_version = 0;
2717     if (!strcmp(hreq->version, "1.0"))
2718     {
2719         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2720         if (v && !strcmp(v, "Keep-Alive"))
2721             m_http_keepalive = 1;
2722         else
2723             m_http_keepalive = 0;
2724         m_http_version = "1.0";
2725     }
2726     else
2727     {
2728         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2729         if (v && !strcmp(v, "close"))
2730             m_http_keepalive = 0;
2731         else
2732             m_http_keepalive = 1;
2733         m_http_version = "1.1";
2734     }
2735
2736     const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2737     char authorization_str[255];
2738     *authorization_str = '\0';
2739     if (a && strncasecmp(a, "Basic ", 6) == 0)
2740         base64_decode(a + 6, authorization_str, 254);
2741
2742     Z_SRW_PDU *srw_pdu = 0;
2743     Z_SOAP *soap_package = 0;
2744     char *charset = 0;
2745     Z_SRW_diagnostic *diagnostic = 0;
2746     int num_diagnostic = 0;
2747
2748     yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2749
2750     if (file_access(hreq))
2751     {
2752         return;
2753     }
2754     else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2755                             &charset) == 0
2756              || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2757                                &charset, &diagnostic, &num_diagnostic) == 0)
2758     {
2759         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2760         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2761         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2762         m_s2z_init_apdu = 0;
2763         m_s2z_search_apdu = 0;
2764         m_s2z_present_apdu = 0;
2765
2766         m_s2z_stylesheet = 0;
2767         
2768         Z_IdAuthentication *auth = NULL;
2769         if (srw_pdu->username && srw_pdu->password)
2770         {
2771             yaz_log(YLOG_LOG, "username/password: %s/%s\n",
2772                     srw_pdu->username, srw_pdu->password);
2773             auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2774             auth->which = Z_IdAuthentication_idPass;
2775             auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2776             auth->u.idPass->groupId = NULL;
2777             auth->u.idPass->password = odr_strdup(m_s2z_odr_init, srw_pdu->password);
2778             auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, srw_pdu->username);
2779         }
2780         else
2781         {
2782             if (*authorization_str)
2783             {
2784                 yaz_log(YLOG_LOG, "authorization_str present: %s\n", authorization_str);
2785                 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2786                 auth->which = Z_IdAuthentication_idPass;
2787                 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2788                 auth->u.idPass->groupId = NULL;
2789                 char *p = strchr(authorization_str, ':');
2790                 if (p)
2791                 {
2792                     *p = '\0';
2793                     p++;
2794                     auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2795                 }
2796                 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2797             }
2798             else
2799             {
2800                 // Use _client_ IP as shown in the log entries...!
2801                 yaz_log(YLOG_LOG, "No authorization_str present: use client IP: %s\n", m_peername);
2802                 
2803                 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2804                     auth->which = Z_IdAuthentication_idPass;
2805                     auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2806                     auth->u.idPass->groupId  = NULL;
2807                     auth->u.idPass->password = NULL;
2808                     auth->u.idPass->userId   = odr_strdup(m_s2z_odr_init, m_peername);
2809             }
2810         }               
2811         
2812         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2813         {
2814
2815             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2816
2817             const char *backend_db = srw_req->database;
2818             srw_get_client(srw_req->database, &backend_db);
2819
2820             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2821             // recordXPath unsupported.
2822             if (srw_req->recordXPath)
2823             {
2824                 yaz_add_srw_diagnostic(odr_decode(),
2825                                        &diagnostic, &num_diagnostic,
2826                                        72, 0);
2827             }
2828             // sort unsupported
2829             if (srw_req->sort_type != Z_SRW_sort_type_none)
2830             {
2831                 yaz_add_srw_diagnostic(odr_decode(),
2832                                        &diagnostic, &num_diagnostic,
2833                                        80, 0);
2834             }
2835             // save stylesheet
2836             if (srw_req->stylesheet)
2837                 m_s2z_stylesheet =
2838                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2839
2840             // set packing for response records ..
2841             if (srw_req->recordPacking &&
2842                 !strcmp(srw_req->recordPacking, "xml"))
2843                 m_s2z_packing = Z_SRW_recordPacking_XML;
2844             else
2845                 m_s2z_packing = Z_SRW_recordPacking_string;
2846
2847             if (num_diagnostic)
2848             {
2849                 Z_SRW_PDU *srw_pdu =
2850                     yaz_srw_get(odr_encode(),
2851                                 Z_SRW_searchRetrieve_response);
2852                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2853
2854                 srw_res->diagnostics = diagnostic;
2855                 srw_res->num_diagnostics = num_diagnostic;
2856                 send_srw_response(srw_pdu);
2857                 return;
2858             }
2859
2860             // prepare search PDU
2861             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2862                                           Z_APDU_searchRequest);
2863             Z_SearchRequest *z_searchRequest =
2864                 m_s2z_search_apdu->u.searchRequest;
2865
2866             z_searchRequest->num_databaseNames = 1;
2867             z_searchRequest->databaseNames = (char**)
2868                 odr_malloc(m_s2z_odr_search, sizeof(char *));
2869             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2870                                                            backend_db);
2871
2872             // query transformation
2873             Z_Query *query = (Z_Query *)
2874                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2875             z_searchRequest->query = query;
2876
2877             if (srw_req->query_type == Z_SRW_query_type_cql)
2878             {
2879                 Z_External *ext = (Z_External *)
2880                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
2881                 ext->direct_reference =
2882                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2883                 ext->indirect_reference = 0;
2884                 ext->descriptor = 0;
2885                 ext->which = Z_External_CQL;
2886                 ext->u.cql = srw_req->query.cql;
2887
2888                 query->which = Z_Query_type_104;
2889                 query->u.type_104 =  ext;
2890             }
2891             else if (srw_req->query_type == Z_SRW_query_type_pqf)
2892             {
2893                 Z_RPNQuery *RPNquery;
2894                 YAZ_PQF_Parser pqf_parser;
2895
2896                 pqf_parser = yaz_pqf_create ();
2897
2898                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2899                                           srw_req->query.pqf);
2900                 if (!RPNquery)
2901                 {
2902                     const char *pqf_msg;
2903                     size_t off;
2904                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2905                     int ioff = off;
2906                     yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2907                     yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2908
2909                     send_to_srw_client_error(10, 0);
2910                     return;
2911                 }
2912                 query->which = Z_Query_type_1;
2913                 query->u.type_1 =  RPNquery;
2914
2915                 yaz_pqf_destroy (pqf_parser);
2916             }
2917             else
2918             {
2919                 send_to_srw_client_error(7, "query");
2920                 return;
2921             }
2922
2923             // present
2924             m_s2z_present_apdu = 0;
2925             int max = 0;
2926             if (srw_req->maximumRecords)
2927                 max = *srw_req->maximumRecords;
2928             int start = 1;
2929             if (srw_req->startRecord)
2930                 start = *srw_req->startRecord;
2931             if (max > 0)
2932             {
2933                 // Some backend, such as Voyager doesn't honor piggyback
2934                 // So we use present always (0 &&).
2935                 if (0 && start <= 1)  // Z39.50 piggyback
2936                 {
2937                     *z_searchRequest->smallSetUpperBound = max;
2938                     *z_searchRequest->mediumSetPresentNumber = max;
2939                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2940
2941                     z_searchRequest->preferredRecordSyntax =
2942                         odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
2943
2944                     if (srw_req->recordSchema)
2945                     {
2946                         z_searchRequest->smallSetElementSetNames =
2947                             z_searchRequest->mediumSetElementSetNames =
2948                             mk_esn_from_schema(m_s2z_odr_search,
2949                                                srw_req->recordSchema);
2950                     }
2951                 }
2952                 else   // Z39.50 present
2953                 {
2954                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2955                                                    Z_APDU_presentRequest);
2956                     Z_PresentRequest *z_presentRequest =
2957                         m_s2z_present_apdu->u.presentRequest;
2958                     *z_presentRequest->resultSetStartPoint = start;
2959                     *z_presentRequest->numberOfRecordsRequested = max;
2960
2961                     z_presentRequest->preferredRecordSyntax =
2962                         odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
2963                     if (srw_req->recordSchema)
2964                     {
2965                         z_presentRequest->recordComposition =
2966                             (Z_RecordComposition *)
2967                             odr_malloc(m_s2z_odr_search,
2968                                        sizeof(Z_RecordComposition));
2969                         z_presentRequest->recordComposition->which =
2970                             Z_RecordComp_simple;
2971                         z_presentRequest->recordComposition->u.simple =
2972                             mk_esn_from_schema(m_s2z_odr_search,
2973                                                srw_req->recordSchema);
2974                     }
2975                 }
2976             }
2977             if (!m_client)
2978             {
2979                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2980                                             Z_APDU_initRequest);
2981
2982                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2983
2984                 // prevent m_initRequest_apdu memory from being grabbed
2985                 // in Yaz_Proxy::handle_incoming_Z_PDU
2986                 m_initRequest_apdu = m_s2z_init_apdu;
2987                 handle_incoming_Z_PDU(m_s2z_init_apdu);
2988                 return;
2989             }
2990             else
2991             {
2992                 handle_incoming_Z_PDU(m_s2z_search_apdu);
2993                 return;
2994             }
2995         }
2996         else if (srw_pdu->which == Z_SRW_explain_request)
2997         {
2998             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2999
3000             const char *backend_db = srw_req->database;
3001             srw_get_client(srw_req->database, &backend_db);
3002
3003             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3004
3005             // save stylesheet
3006             if (srw_req->stylesheet)
3007                 m_s2z_stylesheet =
3008                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3009
3010             if (srw_req->recordPacking &&
3011                 !strcmp(srw_req->recordPacking, "xml"))
3012                 m_s2z_packing = Z_SRW_recordPacking_XML;
3013             else
3014                 m_s2z_packing = Z_SRW_recordPacking_string;
3015
3016             if (num_diagnostic)
3017             {
3018                 send_srw_explain_response(diagnostic, num_diagnostic);
3019                 return;
3020             }
3021
3022             if (!m_client)
3023             {
3024                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3025                                             Z_APDU_initRequest);
3026
3027                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3028                 
3029                 // prevent m_initRequest_apdu memory from being grabbed
3030                 // in Yaz_Proxy::handle_incoming_Z_PDU
3031                 m_initRequest_apdu = m_s2z_init_apdu;
3032                 handle_incoming_Z_PDU(m_s2z_init_apdu);
3033             }
3034             else
3035                 send_srw_explain_response(0, 0);
3036             return;
3037         }
3038         else if (srw_pdu->which == Z_SRW_scan_request)
3039         {
3040             m_s2z_database = odr_strdup(m_s2z_odr_init,
3041                                         srw_pdu->u.scan_request->database);
3042
3043             yaz_add_srw_diagnostic(odr_decode(),
3044                                    &diagnostic, &num_diagnostic,
3045                                    4, "scan");
3046             Z_SRW_PDU *srw_pdu =
3047                 yaz_srw_get(odr_encode(),
3048                             Z_SRW_scan_response);
3049             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3050
3051             srw_res->diagnostics = diagnostic;
3052             srw_res->num_diagnostics = num_diagnostic;
3053             send_srw_response(srw_pdu);
3054             return;
3055         }
3056         else
3057         {
3058             m_s2z_database = 0;
3059
3060             send_to_srw_client_error(4, 0);
3061         }
3062     }
3063     send_http_response(400);
3064 }
3065
3066 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3067 {
3068
3069     Z_OtherInformation **oi;
3070     get_otherInfoAPDU(apdu, &oi);
3071
3072     if (apdu->u.initRequest->implementationId)
3073         yaz_log(YLOG_LOG, "%simplementationId: %s",
3074                 m_session_str, apdu->u.initRequest->implementationId);
3075     if (apdu->u.initRequest->implementationName)
3076         yaz_log(YLOG_LOG, "%simplementationName: %s",
3077                 m_session_str, apdu->u.initRequest->implementationName);
3078     if (apdu->u.initRequest->implementationVersion)
3079         yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3080                 m_session_str, apdu->u.initRequest->implementationVersion);
3081     if (m_initRequest_apdu == 0)
3082     {
3083         if (m_initRequest_mem)
3084             nmem_destroy(m_initRequest_mem);
3085
3086         m_initRequest_apdu = apdu;
3087         m_initRequest_mem = odr_extract_mem(odr_decode());
3088
3089         m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3090             preferredMessageSize;
3091         *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3092         m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3093             maximumRecordSize;
3094         *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3095
3096         Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3097             yaz_get_charneg_record(*oi);
3098
3099         // Save proposal charsets and langs.
3100         if (ODR_MASK_GET(apdu->u.initRequest->options,
3101                          Z_Options_negotiationModel)
3102             && charSetandLangRecord)
3103         {
3104
3105             yaz_get_proposal_charneg(m_referenceId_mem,
3106                                      charSetandLangRecord,
3107                                      &m_initRequest_oi_negotiation_charsets,
3108                                      &m_initRequest_oi_negotiation_num_charsets,
3109                                      &m_initRequest_oi_negotiation_langs,
3110                                      &m_initRequest_oi_negotiation_num_langs,
3111                                      &m_initRequest_oi_negotiation_selected);
3112
3113             for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3114             {
3115                 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3116                         m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3117                         m_initRequest_oi_negotiation_charsets[i]:"none");
3118             }
3119             for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3120             {
3121                 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3122                         m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3123                         m_initRequest_oi_negotiation_langs[i]:"none");
3124             }
3125             yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3126                     m_session_str, m_initRequest_oi_negotiation_selected);
3127         }
3128         // save init options for the response..
3129         m_initRequest_options = apdu->u.initRequest->options;
3130
3131         apdu->u.initRequest->options =
3132             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3133                                        sizeof(Odr_bitmask));
3134         ODR_MASK_ZERO(apdu->u.initRequest->options);
3135         int i;
3136         for (i = 0; i<= 24; i++)
3137             ODR_MASK_SET(apdu->u.initRequest->options, i);
3138         // check negotiation option
3139         if (!ODR_MASK_GET(m_initRequest_options,
3140                           Z_Options_negotiationModel))
3141         {
3142             ODR_MASK_CLEAR(apdu->u.initRequest->options,
3143                            Z_Options_negotiationModel);
3144         }
3145         ODR_MASK_CLEAR(apdu->u.initRequest->options,
3146                        Z_Options_concurrentOperations);
3147         // make new version
3148         m_initRequest_version = apdu->u.initRequest->protocolVersion;
3149         apdu->u.initRequest->protocolVersion =
3150             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3151                                        sizeof(Odr_bitmask));
3152         ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3153
3154         for (i = 0; i<= 8; i++)
3155             ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3156     }
3157     handle_charset_lang_negotiation(apdu);
3158     if (m_client->m_init_flag)
3159     {
3160         if (handle_init_response_for_invalid_session(apdu))
3161             return;
3162         if (m_client->m_initResponse)
3163         {
3164             Z_APDU *apdu2 = m_client->m_initResponse;
3165             apdu2->u.initResponse->otherInfo = 0;
3166             if (m_client->m_cookie && *m_client->m_cookie)
3167                 set_otherInformationString(apdu2, yaz_oid_userinfo_cookie, 
3168                                            1, m_client->m_cookie);
3169             apdu2->u.initResponse->referenceId =
3170                 apdu->u.initRequest->referenceId;
3171             apdu2->u.initResponse->options = m_client->m_initResponse_options;
3172             apdu2->u.initResponse->protocolVersion =
3173                 m_client->m_initResponse_version;
3174
3175             handle_charset_lang_negotiation(apdu2);
3176
3177             if (m_timeout_mode == timeout_busy)
3178                 m_timeout_mode = timeout_normal;
3179             send_to_client(apdu2);
3180             return;
3181         }
3182     }
3183     m_client->m_init_flag = 1;
3184
3185     if (m_num_msg_threads && m_my_thread)
3186     {
3187         Auth_Msg *m = new Auth_Msg;
3188         m->m_proxy = this;
3189         z_APDU(odr_encode(), &apdu, 0, "encode");
3190         char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3191         m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3192         memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3193         odr_reset(odr_encode());
3194         
3195         inc_ref();
3196         m_my_thread->put(m);
3197     }
3198     else
3199     {
3200         int ret = handle_authentication(apdu);
3201         result_authentication(apdu, ret);
3202     }
3203 }
3204
3205 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3206 {
3207     Z_ReferenceId **refid = get_referenceIdP(apdu);
3208     nmem_reset(m_referenceId_mem);
3209     if (refid && *refid)
3210     {
3211         m_referenceId = (Z_ReferenceId *)
3212             nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3213         m_referenceId->len = m_referenceId->size = (*refid)->len;
3214         m_referenceId->buf = (unsigned char *)
3215             nmem_malloc(m_referenceId_mem, (*refid)->len);
3216         memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3217     }
3218     else
3219         m_referenceId = 0;
3220
3221     if (!m_client && m_flag_invalid_session)
3222     {
3223         // Got request for a session that is invalid..
3224         m_apdu_invalid_session = apdu; // save package
3225         m_mem_invalid_session = odr_extract_mem(odr_decode());
3226         apdu = m_initRequest_apdu;     // but throw an init to the target
3227     }
3228
3229     if (apdu->which == Z_APDU_searchRequest)
3230         m_search_stat.add_bytes(1);
3231
3232     // Handle global authentication
3233     if (!handle_global_authentication(apdu))
3234     {
3235         if (m_http_version)
3236         {   // HTTP. Send unauthorized
3237             send_http_response(401);
3238             return;
3239         }
3240         else
3241         {
3242             // Z39.50 just shutdown
3243             timeout(0);
3244             return;
3245         }
3246         return;
3247     }
3248
3249     // Determine our client.
3250     Z_OtherInformation **oi;
3251     get_otherInfoAPDU(apdu, &oi);
3252     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3253     if (!m_client)
3254     {
3255         if (m_http_version)
3256         {   // HTTP. Send not found
3257             send_http_response(404);
3258             return;
3259         }
3260         else
3261         {
3262             // Z39.50 just shutdown
3263             timeout(0);
3264             return;
3265         }
3266     }
3267
3268     m_client->m_server = this;
3269
3270     if (apdu->which == Z_APDU_initRequest)
3271         handle_init(apdu);
3272     else
3273         handle_incoming_Z_PDU_2(apdu);
3274 }
3275
3276 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3277 {
3278     handle_max_record_retrieve(apdu);
3279
3280     if (apdu)
3281         apdu = handle_syntax_validation(apdu);
3282
3283     if (apdu)
3284         apdu = handle_query_transformation(apdu);
3285
3286     if (apdu)
3287         apdu = handle_target_charset_conversion(apdu);
3288
3289     if (apdu)
3290         apdu = handle_query_validation(apdu);
3291
3292     if (apdu)
3293         apdu = result_set_optimize(apdu);
3294
3295     if (!apdu)
3296     {
3297         m_client->timeout(m_target_idletime);  // mark it active even
3298         recv_GDU_more(true);
3299         // though we didn't use it
3300         return;
3301     }
3302
3303     // delete other info construct completely if 0 elements
3304     Z_OtherInformation **oi;
3305     get_otherInfoAPDU(apdu, &oi);
3306     if (oi && *oi && (*oi)->num_elements == 0)
3307         *oi = 0;
3308
3309     if (apdu->which == Z_APDU_presentRequest &&
3310         m_client->m_resultSetStartPoint == 0)
3311     {
3312         Z_PresentRequest *pr = apdu->u.presentRequest;
3313         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3314         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3315     } else {
3316         m_client->m_resultSetStartPoint = 0;
3317     }
3318     if (m_client->send_to_target(apdu) < 0)
3319     {
3320         m_client->shutdown();
3321     }
3322     else
3323         m_client->m_waiting = 1;
3324 }
3325
3326 void Yaz_Proxy::connectNotify()
3327 {
3328 }
3329
3330 void Yaz_Proxy::releaseClient()
3331 {
3332     xfree(m_proxyTarget);
3333     m_proxyTarget = 0;
3334     m_flag_invalid_session = 0;
3335     // only keep if keep_alive flag is set...
3336     if (m_client &&
3337         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3338         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3339         m_client->m_waiting == 0)
3340     {
3341         yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3342                  m_session_str,
3343                  m_client->get_hostname());
3344         yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3345                 m_session_str, m_client->m_pdu_recv,
3346                 m_client->m_bytes_sent + m_client->m_bytes_recv,
3347                 m_keepalive_limit_bw, m_keepalive_limit_