ConnettoreBaseHTTP.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.pdd.core.connettori;

  21. import java.io.ByteArrayOutputStream;
  22. import java.net.HttpCookie;
  23. import java.util.ArrayList;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;

  27. import javax.net.ssl.SSLSocketFactory;

  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  30. import org.openspcoop2.core.config.constants.RuoloContesto;
  31. import org.openspcoop2.core.constants.CostantiConnettori;
  32. import org.openspcoop2.message.OpenSPCoop2Message;
  33. import org.openspcoop2.message.constants.ServiceBinding;
  34. import org.openspcoop2.message.rest.RestUtilities;
  35. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  36. import org.openspcoop2.pdd.config.CostantiProprieta;
  37. import org.openspcoop2.pdd.config.ForwardProxy;
  38. import org.openspcoop2.pdd.config.ForwardProxyConfigurazione;
  39. import org.openspcoop2.pdd.config.UrlInvocazioneAPI;
  40. import org.openspcoop2.pdd.core.CostantiPdD;
  41. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  42. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  43. import org.openspcoop2.pdd.core.keystore.GestoreKeystoreCaching;
  44. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  45. import org.openspcoop2.pdd.mdb.ConsegnaContenutiApplicativi;
  46. import org.openspcoop2.utils.CopyStream;
  47. import org.openspcoop2.utils.UtilsException;
  48. import org.openspcoop2.utils.io.Base64Utilities;
  49. import org.openspcoop2.utils.resources.Charset;
  50. import org.openspcoop2.utils.transport.TransportUtils;
  51. import org.openspcoop2.utils.transport.http.HttpConstants;
  52. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  53. import org.openspcoop2.utils.transport.http.HttpUtilities;
  54. import org.openspcoop2.utils.transport.http.RFC2047Encoding;
  55. import org.openspcoop2.utils.transport.http.RFC2047Utilities;
  56. import org.openspcoop2.utils.transport.http.SSLConfig;

  57. /**
  58.  * ConnettoreBaseHTTP
  59.  *
  60.  *
  61.  * @author Poli Andrea (apoli@link.it)
  62.  * @author $Author$
  63.  * @version $Rev$, $Date$
  64.  */

  65. public abstract class ConnettoreBaseHTTP extends ConnettoreBaseWithResponse {
  66.    
  67.     @Override
  68.     public String getProtocollo() {
  69.         return "HTTP";
  70.     }
  71.    
  72.     /** httpMethod */
  73.     private HttpRequestMethod forceHttpMethod = null;
  74.     public void setForceHttpMethod(HttpRequestMethod forceHttpMethod) {
  75.         this.forceHttpMethod = forceHttpMethod;
  76.     }

  77.     protected HttpRequestMethod httpMethod = null;
  78.     public HttpRequestMethod getHttpMethod() {
  79.         return this.httpMethod;
  80.     }
  81.     public void setHttpMethod(OpenSPCoop2Message msg) throws ConnettoreException {
  82.         // HttpMethod
  83.         if(this.forceHttpMethod!=null) {
  84.             this.httpMethod = this.forceHttpMethod;
  85.         }
  86.         else {
  87.             if(ServiceBinding.SOAP.equals(msg.getServiceBinding())){
  88.                 this.httpMethod = HttpRequestMethod.POST;
  89.             }
  90.             else{
  91.                 if(msg.getTransportRequestContext()==null || msg.getTransportRequestContext().getRequestType()==null){
  92.                     throw new ConnettoreException("HttpRequestMethod non definito");
  93.                 }
  94.                 this.httpMethod = HttpRequestMethod.valueOf(msg.getTransportRequestContext().getRequestType().toUpperCase());
  95.                 if(this.httpMethod==null){
  96.                     throw new ConnettoreException("HttpRequestMethod sconosciuto ("+this.httpMethod+")");
  97.                 }
  98.             }
  99.         }
  100.     }
  101.    
  102.     /** SSL Configuration */
  103.     protected boolean connettoreHttps = false;
  104.     protected SSLConfig sslContextProperties;
  105.    
  106.     /** InputStream Risposta */
  107.     protected String resultHTTPMessage;

  108.     /** RFC 2047 */
  109.     boolean encodingRFC2047 = false;
  110.     Charset charsetRFC2047 = null;
  111.     RFC2047Encoding encodingAlgorithmRFC2047 = null;
  112.     boolean validazioneHeaderRFC2047 = false;
  113.    
  114.    
  115.     /** Proxy Pass Reverse */
  116.     protected boolean proxyPassReverseEnabled = false;
  117.     protected boolean proxyPassReverse_location = false;
  118.     protected boolean proxyPassReverse_setCookie_path = false;
  119.     protected boolean proxyPassReverse_setCookie_domain = false;
  120.     protected boolean proxyPassReverse_usePrefixProtocol = false;
  121.     protected List<String> proxyPassReverse_headers = null;
  122.     protected List<String> proxyPassReverse_setCookie_headers = null;
  123.     private boolean forceDisable_proxyPassReverse = false;
  124.     public void setForceDisable_proxyPassReverse(boolean forceDisable_proxyPassReverse) {
  125.         this.forceDisable_proxyPassReverse = forceDisable_proxyPassReverse;
  126.     }

  127.     /** ForwardProxy */
  128.     protected ForwardProxy forwardProxy;
  129.     protected String forwardProxy_headerName;
  130.     protected String forwardProxy_headerValue;
  131.    
  132.     @Override
  133.     protected boolean initialize(ConnettoreMsg request, boolean connectorPropertiesRequired, ResponseCachingConfigurazione responseCachingConfig){
  134.         boolean init = super.initialize(request, connectorPropertiesRequired, responseCachingConfig);
  135.        
  136.         updateForwardProxy(request.getForwardProxy());
  137.        
  138.         // Location
  139.         if(this.properties.get(CostantiConnettori.CONNETTORE_LOCATION)==null){
  140.             this.errore = "Proprieta' '"+CostantiConnettori.CONNETTORE_LOCATION+"' non fornita e richiesta da questo tipo di connettore ["+request.getTipoConnettore()+"]";
  141.             return false;
  142.         }
  143.        
  144.         if(this.idModulo!=null){
  145.             if(ConsegnaContenutiApplicativi.ID_MODULO.equals(this.idModulo)){
  146.                 this.encodingRFC2047 = this.openspcoopProperties.isEnabledEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  147.                 this.charsetRFC2047 = this.openspcoopProperties.getCharsetEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  148.                 this.encodingAlgorithmRFC2047 = this.openspcoopProperties.getEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  149.                 this.validazioneHeaderRFC2047 = this.openspcoopProperties.isEnabledValidazioneRFC2047HeaderNameValueConsegnaContenutiApplicativi();
  150.             }else{
  151.                 this.encodingRFC2047 = this.openspcoopProperties.isEnabledEncodingRFC2047HeaderValueInoltroBuste();
  152.                 this.charsetRFC2047 = this.openspcoopProperties.getCharsetEncodingRFC2047HeaderValueInoltroBuste();
  153.                 this.encodingAlgorithmRFC2047 = this.openspcoopProperties.getEncodingRFC2047HeaderValueInoltroBuste();
  154.                 this.validazioneHeaderRFC2047 = this.openspcoopProperties.isEnabledValidazioneRFC2047HeaderNameValueInoltroBuste();
  155.             }
  156.            
  157.             this.encodingRFC2047 = CostantiProprieta.isConnettoriHeaderValueEncodingRFC2047RequestEnabled(this.proprietaPorta, this.encodingRFC2047);
  158.             this.charsetRFC2047 = CostantiProprieta.getConnettoriHeaderValueEncodingRFC2047RequestCharset(this.proprietaPorta, this.charsetRFC2047);
  159.             this.encodingAlgorithmRFC2047 = CostantiProprieta.getConnettoriHeaderValueEncodingRFC2047RequestType(this.proprietaPorta, this.encodingAlgorithmRFC2047);
  160.             this.validazioneHeaderRFC2047 = CostantiProprieta.isConnettoriHeaderValidationRequestEnabled(this.proprietaPorta, this.validazioneHeaderRFC2047);
  161.         }
  162.        
  163.         if(!this.forceDisable_proxyPassReverse) {
  164.            
  165.             if(this.isRest) {
  166.                 if(ConsegnaContenutiApplicativi.ID_MODULO.equals(this.idModulo)){
  167.                     this.proxyPassReverse_location = this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse();
  168.                     this.proxyPassReverse_setCookie_path = this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie() && this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_path();
  169.                     this.proxyPassReverse_setCookie_domain = this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie() && this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_domain();
  170.                     this.proxyPassReverse_usePrefixProtocol = this.openspcoopProperties.isRESTServices_consegnaContenutiApplicativi_proxyPassReverse_useProtocolPrefix();
  171.                     try {
  172.                         this.proxyPassReverse_headers = this.openspcoopProperties.getRESTServices_consegnaContenutiApplicativi_proxyPassReverse_headers();
  173.                         this.proxyPassReverse_setCookie_headers = this.openspcoopProperties.getRESTServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_headers();
  174.                     }catch(Exception e) {
  175.                         this.errore = e.getMessage();
  176.                         return false;
  177.                     }
  178.                 }
  179.                 else{
  180.                     // InoltroBuste e InoltroRisposte
  181.                     this.proxyPassReverse_location = this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse();
  182.                     this.proxyPassReverse_setCookie_path = this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse_setCookie() && this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse_setCookie_path();
  183.                     this.proxyPassReverse_setCookie_domain = this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse_setCookie() && this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse_setCookie_domain();
  184.                     this.proxyPassReverse_usePrefixProtocol = this.openspcoopProperties.isRESTServices_inoltroBuste_proxyPassReverse_useProtocolPrefix();
  185.                     try {
  186.                         this.proxyPassReverse_headers = this.openspcoopProperties.getRESTServices_inoltroBuste_proxyPassReverse_headers();
  187.                         this.proxyPassReverse_setCookie_headers = this.openspcoopProperties.getRESTServices_inoltroBuste_proxyPassReverse_setCookie_headers();
  188.                     }catch(Exception e) {
  189.                         this.errore = e.getMessage();
  190.                         return false;
  191.                     }
  192.                 }
  193.             }else {
  194.                 if(ConsegnaContenutiApplicativi.ID_MODULO.equals(this.idModulo)){
  195.                     this.proxyPassReverse_location = this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse();
  196.                     this.proxyPassReverse_setCookie_path = this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie() && this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_path();
  197.                     this.proxyPassReverse_setCookie_domain = this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie() && this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_domain();
  198.                     this.proxyPassReverse_usePrefixProtocol = this.openspcoopProperties.isSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_useProtocolPrefix();
  199.                     try {
  200.                         this.proxyPassReverse_headers = this.openspcoopProperties.getSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_headers();
  201.                         this.proxyPassReverse_setCookie_headers = this.openspcoopProperties.getSOAPServices_consegnaContenutiApplicativi_proxyPassReverse_setCookie_headers();
  202.                     }catch(Exception e) {
  203.                         this.errore = e.getMessage();
  204.                         return false;
  205.                     }
  206.                 }
  207.                 else{
  208.                     // InoltroBuste e InoltroRisposte
  209.                     this.proxyPassReverse_location = this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse();
  210.                     this.proxyPassReverse_setCookie_path = this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse_setCookie() && this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse_setCookie_path();
  211.                     this.proxyPassReverse_setCookie_domain = this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse_setCookie() && this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse_setCookie_domain();
  212.                     this.proxyPassReverse_usePrefixProtocol = this.openspcoopProperties.isSOAPServices_inoltroBuste_proxyPassReverse_useProtocolPrefix();
  213.                     try {
  214.                         this.proxyPassReverse_headers = this.openspcoopProperties.getSOAPServices_inoltroBuste_proxyPassReverse_headers();
  215.                         this.proxyPassReverse_setCookie_headers = this.openspcoopProperties.getSOAPServices_inoltroBuste_proxyPassReverse_setCookie_headers();
  216.                     }catch(Exception e) {
  217.                         this.errore = e.getMessage();
  218.                         return false;
  219.                     }
  220.                 }
  221.             }
  222.            
  223.             // check proprieta' specifiche
  224.             if(this.proprietaPorta!=null && !this.proprietaPorta.isEmpty()) {
  225.                 try {
  226.                     this.proxyPassReverse_location = CostantiProprieta.isConnettoriProxyPassReverseEnabled(this.proprietaPorta, this.proxyPassReverse_location);
  227.                     if(this.proxyPassReverse_location) {
  228.                         this.proxyPassReverse_headers = CostantiProprieta.getConnettoriProxyPassReverseHeaders(this.proprietaPorta, this.proxyPassReverse_headers);
  229.                     }
  230.                    
  231.                     this.proxyPassReverse_setCookie_path = CostantiProprieta.isConnettoriProxyPassReverseSetCookiePathEnabled(this.proprietaPorta, this.proxyPassReverse_setCookie_path);
  232.                     this.proxyPassReverse_setCookie_domain = CostantiProprieta.isConnettoriProxyPassReverseSetCookieDomainEnabled(this.proprietaPorta, this.proxyPassReverse_setCookie_domain);
  233.                     if(this.proxyPassReverse_setCookie_path || this.proxyPassReverse_setCookie_domain) {
  234.                         this.proxyPassReverse_setCookie_headers = CostantiProprieta.getConnettoriProxyPassReverseHeaders(this.proprietaPorta, this.proxyPassReverse_setCookie_headers);
  235.                     }
  236.                    
  237.                     if(this.proxyPassReverse_location || this.proxyPassReverse_setCookie_path || this.proxyPassReverse_setCookie_domain) {
  238.                         this.proxyPassReverse_usePrefixProtocol = CostantiProprieta.isConnettoriProxyPassReverseUseProtocolPrefix(this.proprietaPorta, this.proxyPassReverse_usePrefixProtocol);
  239.                     }
  240.                 }catch(Exception e) {
  241.                     this.errore = e.getMessage();
  242.                     return false;
  243.                 }
  244.             }
  245.            
  246.             if(this.proxyPassReverse_location) {
  247.                 this.proxyPassReverse_location = (this.proxyPassReverse_headers!=null && !this.proxyPassReverse_headers.isEmpty());
  248.             }
  249.             if(this.proxyPassReverse_setCookie_path) {
  250.                 this.proxyPassReverse_setCookie_path = (this.proxyPassReverse_setCookie_headers!=null && !this.proxyPassReverse_setCookie_headers.isEmpty());
  251.             }
  252.             if(this.proxyPassReverse_setCookie_domain) {
  253.                 this.proxyPassReverse_setCookie_domain = (this.proxyPassReverse_setCookie_headers!=null && !this.proxyPassReverse_setCookie_headers.isEmpty());
  254.             }

  255.             this.proxyPassReverseEnabled = this.proxyPassReverse_location || this.proxyPassReverse_setCookie_path || this.proxyPassReverse_setCookie_domain;
  256.         }
  257.        
  258.         return init;
  259.     }
  260.    
  261.     protected void setSSLContext() throws ConnettoreException{
  262.         if(this.connettoreHttps){
  263.             this.sslContextProperties = ConnettoreHTTPSProperties.readProperties(this.properties);
  264.         }
  265.         else {
  266.             String location = this.properties.get(CostantiConnettori.CONNETTORE_LOCATION);
  267.             if(!location.trim().startsWith("https")){
  268.                 if(this.debug){
  269.                     this.logger.debug("Location non richiede gestione https ["+location.trim()+"]");
  270.                 }
  271.                 return;
  272.             }
  273.            
  274.             boolean urlHttpsOverrideJvmConfiguration = ConnettoreHTTPUrlHttpsKeystoreRepository.isEnabled(this.idModulo, this.proprietaPorta);
  275.             if(!urlHttpsOverrideJvmConfiguration) {
  276.                 if(this.debug){
  277.                     this.logger.debug("Location https ["+location.trim()+"]; gestione personalizzata dei keystore disabilitata");
  278.                 }
  279.                 return;
  280.             }
  281.            
  282.             ConnettoreHTTPUrlHttpsKeystoreRepository utils = new ConnettoreHTTPUrlHttpsKeystoreRepository(this.debug, this.logger, this.idModulo);
  283.             utils.init(this.proprietaPorta, this.busta, this.dynamicMap, this.getPddContext());
  284.             this.sslContextProperties = utils.readSSLContext(this.requestInfo);
  285.         }
  286.        
  287.         this.setSecureRandomSSLContext();
  288.     }
  289.     private void setSecureRandomSSLContext() throws ConnettoreException{
  290.         if(this.sslContextProperties!=null &&
  291.                 !this.sslContextProperties.isSecureRandomSet() &&
  292.                 this.openspcoopProperties.isConnettoreHttps_useSecureRandom()
  293.                 ) {
  294.                 this.sslContextProperties.setSecureRandom(true);
  295.                 if(this.openspcoopProperties.getConnettoreHttps_secureRandomAlgo()!=null) {
  296.                     this.sslContextProperties.setSecureRandomAlgorithm(this.openspcoopProperties.getConnettoreHttps_secureRandomAlgo());
  297.                 }
  298.             }
  299.     }
  300.    
  301.     protected SSLSocketFactory buildSSLContextFactory() throws UtilsException {
  302.         // Gestione https
  303.         if(this.sslContextProperties!=null){
  304.            
  305.             StringBuilder sbError = null;
  306.             StringBuilder sbDebug = null;
  307.             try {
  308.                 sbError = new StringBuilder();
  309.                 this.sslContextProperties.setSbError(sbError);
  310.                 if(this.debug) {
  311.                     sbDebug = new StringBuilder();
  312.                     this.sslContextProperties.setSbDebug(sbDebug);
  313.                 }
  314.                 this.sslContextProperties.setLogger(this.logger.getLogger());
  315.                 Map<String,Object> dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(this.busta, this.requestInfo, this.getPddContext(),
  316.                         this.logger!=null ? this.logger.getLogger() : null);
  317.                 this.sslContextProperties.setDynamicMap(dynamicMap);
  318.                 return GestoreKeystoreCaching.getSSLSocketFactory(this.requestInfo, this.sslContextProperties).getSslSocketFactory(this.requestInfo);
  319.             }catch(Exception e) {
  320.                 if(this.logger!=null) {
  321.                     this.logger.error("Lettura SSLSocketFactory '"+this.sslContextProperties.toString()+"' dalla cache fallita: "+e.getMessage(),e);
  322.                 }
  323.                 throw new UtilsException(e.getMessage(),e);
  324.             }finally {
  325.                 if(sbError!=null && sbError.length()>0 &&
  326.                         this.logger!=null) {
  327.                     this.logger.error(sbError.toString());
  328.                 }
  329.                 if(sbDebug!=null && sbDebug.length()>0 &&
  330.                         this.logger!=null) {
  331.                     this.logger.info(sbDebug.toString(), false);
  332.                 }
  333.             }
  334.            
  335.         }
  336.         return null;
  337.     }
  338.    
  339.        
  340.     protected void updateForwardProxy(ForwardProxy forwardProxy) {
  341.         if(this.forwardProxy==null) {
  342.             this.forwardProxy = forwardProxy;
  343.         }
  344.     }
  345.     protected boolean updateLocation_forwardProxy(String location) throws ConnettoreException {
  346.        
  347.         if(this.forwardProxy!=null && this.forwardProxy.isEnabled()) {
  348.                    
  349.             ForwardProxyConfigurazione config = this.forwardProxy.getConfig();
  350.            
  351.             String base64Location = null;
  352.             if(config.getHeader()!=null) {
  353.                 this.forwardProxy_headerName = config.getHeader();
  354.                
  355.                 if(config.isHeaderBase64()) {
  356.                     base64Location = Base64Utilities.encodeAsString(location.getBytes());
  357.                     this.forwardProxy_headerValue = base64Location;
  358.                 }
  359.                 else {
  360.                     this.forwardProxy_headerValue = location;
  361.                     if(this.encodingRFC2047){
  362.                         try {
  363.                             if(RFC2047Utilities.isAllCharactersInCharset(this.forwardProxy_headerValue, this.charsetRFC2047)==false){
  364.                                 String encoded = RFC2047Utilities.encode(new String(this.forwardProxy_headerValue), this.charsetRFC2047, this.encodingAlgorithmRFC2047);
  365.                                 //System.out.println("@@@@ CODIFICA ["+value+"] in ["+encoded+"]");
  366.                                 if(this.debug)
  367.                                     this.logger.info("RFC2047 Encoded value ["+this.forwardProxy_headerValue+"] in ["+encoded+"] (charset:"+this.charsetRFC2047+" encoding-algorithm:"+this.encodingAlgorithmRFC2047+")",false);
  368.                                 this.forwardProxy_headerValue = encoded;
  369.                             }
  370.                         }catch(Exception e) {
  371.                             throw new ConnettoreException(e.getMessage(),e);
  372.                         }
  373.                     }
  374.                 }
  375.             }
  376.            
  377.             Map<String, List<String>> queryParameters = new HashMap<>();
  378.             if(config.getQuery()!=null) {
  379.                 if(config.isQueryBase64()) {
  380.                     if(base64Location==null) {
  381.                         base64Location = Base64Utilities.encodeAsString(location.getBytes());
  382.                     }
  383.                     TransportUtils.addParameter(queryParameters,config.getQuery(), base64Location);
  384.                 }
  385.                 else {
  386.                     TransportUtils.addParameter(queryParameters,config.getQuery(), location);
  387.                 }
  388.             }
  389.            
  390.             String newUrl = this.forwardProxy.getUrl();
  391.             if(this.dynamicMap!=null) {
  392.                 try {
  393.                     newUrl = DynamicUtils.convertDynamicPropertyValue("forwardProxyUrl", newUrl, this.dynamicMap, this.getPddContext(), false);
  394.                 }catch(Exception e){
  395.                     this.logger.error("Errore durante la costruzione della url per la funzionalità di 'forwardProxy' (dynamic): "+e.getMessage(),e);
  396.                 }
  397.             }
  398.            
  399.             boolean encodeBaseLocation = true; // la base location può contenere dei parametri
  400.             this.location = TransportUtils.buildUrlWithParameters(queryParameters, newUrl, encodeBaseLocation, this.logger!=null ? this.logger.getLogger() : OpenSPCoop2Logger.getLoggerOpenSPCoopCore());
  401.            
  402.             return true;
  403.         }
  404.        
  405.         return false;
  406.        
  407.     }
  408.    
  409.     @Override
  410.     protected boolean dumpResponse(Map<String, List<String>> trasporto) throws Exception{
  411.        
  412.         if(this.isRest){
  413.             if(this.proxyPassReverseEnabled) {
  414.                 checkProxyPassReverse();
  415.             }
  416.         }
  417.         else {
  418.             /*
  419.              * Se il messaggio e' un html di errore me ne esco
  420.              */    
  421.             if(!checkSoapHtmlResponse()) {
  422.                 return false;
  423.             }
  424.            
  425.             if(this.proxyPassReverseEnabled) {
  426.                 checkProxyPassReverse();
  427.             }
  428.         }
  429.        
  430.         return super.dumpResponse(trasporto);
  431.     }
  432.    
  433.     @Override
  434.     protected boolean doSoapResponse() throws Exception{

  435.         // gestione ordinaria via WS/SOAP
  436.        
  437.         if(this.debug)
  438.             this.logger.debug("gestione WS/SOAP in corso (check HTML) ...");
  439.        
  440.         /*
  441.          * Se il messaggio e' un html di errore me ne esco
  442.          */    
  443.         if(!checkSoapHtmlResponse()) {
  444.             return false;
  445.         }
  446.        
  447.         if(this.proxyPassReverseEnabled) {
  448.             checkProxyPassReverse();
  449.         }
  450.        
  451.         return super.doSoapResponse();
  452.     }
  453.    
  454.     private boolean checkSoapHtmlResponse() throws Exception {
  455.         /*
  456.          * Se il messaggio e' un html di errore me ne esco
  457.          */        
  458.         if(this.codice>=400 &&
  459.                 (
  460.                     (this.tipoRisposta!=null && this.tipoRisposta.contains(HttpConstants.CONTENT_TYPE_HTML))
  461.                     ||
  462.                     (this.tipoRisposta==null || StringUtils.isEmpty(this.tipoRisposta)) // fix per casi in cui viene ritornata una pagina html senza content-type
  463.                 )
  464.             ){
  465.             String tmpResultHTTPMessage=this.resultHTTPMessage;
  466.             if(tmpResultHTTPMessage==null) {
  467.                 // provo a tradurlo
  468.                 tmpResultHTTPMessage = HttpUtilities.getHttpReason(this.codice);
  469.             }
  470.             String tipoLetturaRisposta = "("+this.codice+") " +  tmpResultHTTPMessage;
  471.            
  472.             // Registro HTML ricevuto.
  473.             String htmlRicevuto = null;
  474.             if(this.isResponse!=null){
  475.                
  476.                 this.emitDiagnosticResponseRead(this.isResponse);
  477.                
  478.                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  479. //              byte [] readB = new byte[Utilities.DIMENSIONE_BUFFER];
  480. //              int readByte = 0;
  481. //              while((readByte = this.isResponse.read(readB))!= -1){
  482. //                  bout.write(readB,0,readByte);
  483. //              }
  484.                 CopyStream.copy(this.isResponse, bout);
  485.                 this.isResponse.close();
  486.                 bout.flush();
  487.                 bout.close();
  488.                 htmlRicevuto = bout.toString();
  489.             }
  490.            
  491.             if(htmlRicevuto!=null && !"".equals(htmlRicevuto))
  492.                 this.errore = tipoLetturaRisposta +"\nhttp response: "+htmlRicevuto;
  493.             else
  494.                 this.errore = tipoLetturaRisposta;
  495.             return false;
  496.         }
  497.        
  498.         return true;
  499.     }
  500.    
  501.     @Override
  502.     protected boolean doRestResponse() throws Exception{
  503.        
  504.         if(this.proxyPassReverseEnabled) {
  505.             checkProxyPassReverse();
  506.         }
  507.        
  508.         return super.doRestResponse();
  509.     }

  510.     private boolean proxyPassReverseDone = false;
  511.     private void checkProxyPassReverse() throws Exception {
  512.         if(!this.proxyPassReverseDone) {
  513.             try {
  514.                 if(this.debug)
  515.                     this.logger.debug("gestione (rest:"+this.isRest+") - proxyPassReverse:"+this.proxyPassReverseEnabled+
  516.                             " (location:"+this.proxyPassReverse_location+" setCookie-path:"+this.proxyPassReverse_setCookie_path+" setCookie-domain:"+this.proxyPassReverse_setCookie_domain+") ...");
  517.            
  518.                 if(this.proxyPassReverseEnabled) {
  519.                    
  520.                     // Raccolgo informazioni
  521.                     String baseUrl = null;
  522.                     String prefixGatewayUrl = null;
  523.                     String contesto = null;
  524.                     try {
  525.                         baseUrl = this.properties.get(CostantiConnettori.CONNETTORE_LOCATION);
  526.                         if(baseUrl==null) {
  527.                             throw new Exception("BaseURL undefined");
  528.                         }
  529.                         if(this.debug)
  530.                             this.logger.debug("Base URL: ["+baseUrl+"] ...");
  531.                          
  532.                         String interfaceName = null;
  533.                         if(this.requestMsg!=null) {
  534.                             Object porta = this.requestMsg.getContextProperty(CostantiPdD.NOME_PORTA_INVOCATA);
  535.                             if(porta!=null && porta instanceof String) {
  536.                                 interfaceName = (String) porta;
  537.                             }
  538.                             if(interfaceName==null) {
  539.                                 if(this.requestMsg.getTransportRequestContext()!=null) {
  540.                                     interfaceName = this.requestMsg.getTransportRequestContext().getInterfaceName();
  541.                                 }
  542.                             }
  543.                             if(interfaceName==null) {
  544.                                 if(this.pa!=null) {
  545.                                     interfaceName = this.pa.getNome();
  546.                                 }
  547.                                 else if(this.pd!=null) {
  548.                                     interfaceName = this.pd.getNome();
  549.                                 }
  550.                             }
  551.                         }
  552.                          
  553.                         if(this.proxyPassReverse_usePrefixProtocol) {
  554.                             UrlInvocazioneAPI urlInvocazioneApi = ConfigurazionePdDManager.getInstance().getConfigurazioneUrlInvocazione(this.getProtocolFactory(),
  555.                                     ConsegnaContenutiApplicativi.ID_MODULO.equals(this.idModulo) ? RuoloContesto.PORTA_APPLICATIVA : RuoloContesto.PORTA_DELEGATA,
  556.                                     this.requestMsg!=null ? this.requestMsg.getServiceBinding() : null,
  557.                                     interfaceName,
  558.                                     this.requestInfo!=null ? this.requestInfo.getIdentitaPdD() : null,
  559.                                     this.getIdAccordo(),
  560.                                     this.requestInfo);      
  561.                             prefixGatewayUrl = urlInvocazioneApi.getBaseUrl();
  562.                             contesto = urlInvocazioneApi.getContext();
  563.                         }
  564.                          
  565.                     }catch(Exception e) {
  566.                         throw new Exception("Errore durante la raccolta delle informazioni necessarie alla funzione di proxy pass reverse: "+e.getMessage(),e);
  567.                     }
  568.    
  569.                     if(this.proxyPassReverse_location) {
  570.                      
  571.                         for (String header : this.proxyPassReverse_headers) {
  572.                             String redirectLocation = TransportUtils.getFirstValue(this.propertiesTrasportoRisposta, header);
  573.                             if(redirectLocation!=null) {
  574.                                 if(this.debug)
  575.                                     this.logger.debug("Trovato Header '"+header+"':["+redirectLocation+"] ...");
  576.                                
  577.                                 try {
  578.                                     String newRedirectLocation = RestUtilities.buildPassReverseUrl(this.requestMsg.getTransportRequestContext(), baseUrl, redirectLocation, prefixGatewayUrl, contesto);
  579.                                     if(this.debug)
  580.                                         this.logger.debug("Nuovo Header '"+header+"':["+newRedirectLocation+"] ...");
  581.                                
  582.                                     if(!redirectLocation.equals(newRedirectLocation)) {
  583.                                         TransportUtils.removeObject(this.propertiesTrasportoRisposta, header);
  584.                                         TransportUtils.addHeader(this.propertiesTrasportoRisposta,header, newRedirectLocation);
  585.                                     }
  586.                                 }catch(Exception e) {
  587.                                     throw new Exception("Errore durante l'aggiornamento dell'header '"+header+
  588.                                             "' attraverso la funzione di proxy pass reverse: "+e.getMessage(),e);
  589.                                 }
  590.                             }
  591.                         }
  592.                     }
  593.                
  594.                     if(this.proxyPassReverse_setCookie_path || this.proxyPassReverse_setCookie_domain) {
  595.                      
  596.                         for (String header : this.proxyPassReverse_setCookie_headers) {
  597.                             List<String> cookieValues = TransportUtils.getValues(this.propertiesTrasportoRisposta, header);
  598.                             List<String> newCookieValues = null;
  599.                             boolean modify = false;
  600.                             if(cookieValues!=null && !cookieValues.isEmpty()) {
  601.                                
  602.                                 newCookieValues = new ArrayList<>();
  603.                                
  604.                                 for (String cookieValue : cookieValues) {
  605.                                     if(cookieValue!=null) {
  606.                                         if(this.debug)
  607.                                             this.logger.debug("Trovato CookieHeader '"+header+"':["+cookieValue+"] ...");
  608.                                            
  609.                                         List<String> cookieNames = new ArrayList<>();
  610.                                         List<String> cookiePaths = new ArrayList<>();
  611.                                         List<String> cookieDomains = new ArrayList<>();
  612.                                         try {
  613.                                             List<HttpCookie> l = java.net.HttpCookie.parse(cookieValue);
  614.                                             for (HttpCookie httpCookie : l) {
  615.                                                 //System.out.println("cookie ["+httpCookie.getName()+"] ["+httpCookie.getPath()+"]");
  616.                                                 if(httpCookie.getPath()!=null) {
  617.                                                     cookieNames.add(httpCookie.getName());
  618.                                                     cookiePaths.add(httpCookie.getPath());
  619.                                                     cookieDomains.add(httpCookie.getDomain());
  620.                                                 }
  621.                                             }
  622.                                         }catch(Throwable e) {
  623.                                             this.logger.error("Errore durante il parsing del valore dell'header '"+header+"' (gestione cookie): "+e.getMessage(),e);
  624.                                         }
  625.                                        
  626.                                         if(!cookieNames.isEmpty()) {
  627.                                             for (int i = 0; i < cookieNames.size(); i++) {
  628.                                                 String cName = cookieNames.get(i);
  629.                                                 String cPath = cookiePaths.get(i);
  630.                                                 String cDomain = cookieDomains.get(i);
  631.                                                
  632.                                                 String newValue = cookieValue;
  633.                                                
  634.                                                 if(this.proxyPassReverse_setCookie_path) {
  635.                                                     try {
  636.                                                         if(cPath!=null) {
  637.                                                             String newPath = RestUtilities.buildCookiePassReversePath(this.requestMsg.getTransportRequestContext(), baseUrl, cPath, prefixGatewayUrl, contesto);
  638.                                                             if(this.debug)
  639.                                                                 this.logger.debug("Nuovo Path '"+cName+"' (header:"+header+"):["+newPath+"] ...");
  640.                                                        
  641.                                                             if(!cPath.equals(newPath)) {
  642.                                                                 newValue = newValue.replace(cPath, newPath);
  643.                                                                 /*
  644.                                                                 String newValue = newValue.replace("path="+cPath, "path="+newPath);
  645.                                                                 newValue = newValue.replace("path ="+cPath, "path ="+newPath);
  646.                                                                 newValue = newValue.replace("path= "+cPath, "path= "+newPath);
  647.                                                                 newValue = newValue.replace("path = "+cPath, "path = "+newPath);
  648.                                                                
  649.                                                                 newValue = newValue.replace("Path="+cPath, "Path="+newPath);
  650.                                                                 newValue = newValue.replace("Path ="+cPath, "Path ="+newPath);
  651.                                                                 newValue = newValue.replace("Path= "+cPath, "Path= "+newPath);
  652.                                                                 newValue = newValue.replace("Path = "+cPath, "Path = "+newPath);
  653.                                                                
  654.                                                                 newValue = newValue.replace("PATH="+cPath, "PATH="+newPath);
  655.                                                                 newValue = newValue.replace("PATH ="+cPath, "PATH ="+newPath);
  656.                                                                 newValue = newValue.replace("PATH= "+cPath, "PATH= "+newPath);
  657.                                                                 newValue = newValue.replace("PATH = "+cPath, "PATH = "+newPath);
  658.                                                                
  659.                                                                 newValue + newValue.replace("path=\""+cPath, "path=\""+newPath);
  660.                                                                 newValue = newValue.replace("path =\""+cPath, "path =\""+newPath);
  661.                                                                 newValue = newValue.replace("path= \""+cPath, "path= \""+newPath);
  662.                                                                 newValue = newValue.replace("path = \""+cPath, "path = \""+newPath);
  663.                                                                
  664.                                                                 newValue = newValue.replace("Path=\""+cPath, "Path=\""+newPath);
  665.                                                                 newValue = newValue.replace("Path =\""+cPath, "Path =\""+newPath);
  666.                                                                 newValue = newValue.replace("Path= \""+cPath, "Path= \""+newPath);
  667.                                                                 newValue = newValue.replace("Path = \""+cPath, "Path = \""+newPath);
  668.                                                                
  669.                                                                 newValue = newValue.replace("PATH=\""+cPath, "PATH=\""+newPath);
  670.                                                                 newValue = newValue.replace("PATH =\""+cPath, "PATH =\""+newPath);
  671.                                                                 newValue = newValue.replace("PATH= \""+cPath, "PATH= \""+newPath);
  672.                                                                 newValue = newValue.replace("PATH = \""+cPath, "PATH = \""+newPath);*/
  673.                                                                
  674.                                                                 modify=true;
  675.                                                             }
  676.                                                         }
  677.                                                     }catch(Exception e) {
  678.                                                         throw new Exception("Errore durante l'aggiornamento del cookie '"+cName+
  679.                                                                 "' (header:"+header+") attraverso la funzione di proxy pass reverse: "+e.getMessage(),e);
  680.                                                     }  
  681.                                                 }
  682.                                                
  683.                                                 if(this.proxyPassReverse_setCookie_domain) {
  684.                                                     try {
  685.                                                         if(cDomain!=null) {
  686.                                                             String newDomain = RestUtilities.buildCookiePassReverseDomain(this.requestMsg.getTransportRequestContext(), baseUrl, cDomain, prefixGatewayUrl);
  687.                                                             if(this.debug)
  688.                                                                 this.logger.debug("Nuovo Domain '"+cDomain+"' (header:"+header+"):["+newDomain+"] ...");
  689.                                                        
  690.                                                             if(!cDomain.equals(newDomain)) {
  691.                                                                 newValue = newValue.replace(cDomain, newDomain);
  692.                                                                 /*
  693.                                                                 String newValue = newValue.replace("domain="+cDomain, "domain="+newDomain);
  694.                                                                 newValue = newValue.replace("domain ="+cDomain, "domain ="+newDomain);
  695.                                                                 newValue = newValue.replace("domain= "+cDomain, "domain= "+newDomain);
  696.                                                                 newValue = newValue.replace("domain = "+cDomain, "domain = "+newDomain);
  697.                                                                
  698.                                                                 newValue = newValue.replace("Domain="+cDomain, "Domain="+newDomain);
  699.                                                                 newValue = newValue.replace("Domain ="+cDomain, "Domain ="+newDomain);
  700.                                                                 newValue = newValue.replace("Domain= "+cDomain, "Domain= "+newDomain);
  701.                                                                 newValue = newValue.replace("Domain = "+cDomain, "Domain = "+newDomain);
  702.                                                                
  703.                                                                 newValue = newValue.replace("DOMAIN="+cDomain, "DOMAIN="+newDomain);
  704.                                                                 newValue = newValue.replace("DOMAIN ="+cDomain, "DOMAIN ="+newDomain);
  705.                                                                 newValue = newValue.replace("DOMAIN= "+cDomain, "DOMAIN= "+newDomain);
  706.                                                                 newValue = newValue.replace("DOMAIN = "+cDomain, "DOMAIN = "+newDomain);
  707.                                                                
  708.                                                                 newValue + newValue.replace("domain=\""+cDomain, "domain=\""+newDomain);
  709.                                                                 newValue = newValue.replace("domain =\""+cDomain, "domain =\""+newDomain);
  710.                                                                 newValue = newValue.replace("domain= \""+cDomain, "domain= \""+newDomain);
  711.                                                                 newValue = newValue.replace("domain = \""+cDomain, "domain = \""+newDomain);
  712.                                                                
  713.                                                                 newValue = newValue.replace("Domain=\""+cDomain, "Domain=\""+newDomain);
  714.                                                                 newValue = newValue.replace("Domain =\""+cDomain, "Domain =\""+newDomain);
  715.                                                                 newValue = newValue.replace("Domain= \""+cDomain, "Domain= \""+newDomain);
  716.                                                                 newValue = newValue.replace("Domain = \""+cDomain, "Domain = \""+newDomain);
  717.                                                                
  718.                                                                 newValue = newValue.replace("DOMAIN=\""+cDomain, "DOMAIN=\""+newDomain);
  719.                                                                 newValue = newValue.replace("DOMAIN =\""+cDomain, "DOMAIN =\""+newDomain);
  720.                                                                 newValue = newValue.replace("DOMAIN= \""+cDomain, "DOMAIN= \""+newDomain);
  721.                                                                 newValue = newValue.replace("DOMAIN = \""+cDomain, "DOMAIN = \""+newDomain);*/
  722.                                                                
  723.                                                                 modify=true;
  724.                                                             }
  725.                                                         }
  726.                                                     }catch(Exception e) {
  727.                                                         throw new Exception("Errore durante l'aggiornamento del cookie '"+cName+
  728.                                                                 "' (header:"+header+") attraverso la funzione di proxy pass reverse: "+e.getMessage(),e);
  729.                                                     }
  730.                                                 }
  731.                                                
  732.                                                 newCookieValues.add(newValue);
  733.                                            
  734.                                             } // end for (int i = 0; i < cookieNames.size(); i++) {
  735.                                         } // end !cookieNames.isEmpty()
  736.                                     } // end cookieValue!=null
  737.                                 } // end for (String cookieValue : cookieValues) {
  738.                             } //end if(cookieValues!=null && !cookieValues.isEmpty()) {
  739.                            
  740.                             if(modify) {
  741.                                 TransportUtils.removeObject(this.propertiesTrasportoRisposta, header);
  742.                                 this.propertiesTrasportoRisposta.put(header, newCookieValues);
  743.                             }
  744.                         }
  745.                     }
  746.                  
  747.                 }
  748.                
  749.             }finally {
  750.                 this.proxyPassReverseDone = true;
  751.             }
  752.          }
  753.     }
  754. }