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