Exemple #1
0
 public WebServiceSettingsBuilder(IServiceProvider serviceProvider,
                                  WebServiceSettingsNode webServiceSettingsNode)
 {
     this.webServiceSettingsNode = webServiceSettingsNode;
     hierarchy          = ServiceHelper.GetCurrentHierarchy(serviceProvider);
     webServiceSettings = new WebServiceSettings();
 }
Exemple #2
0
        protected override ConfigurationSectionInfo GetConfigurationSectionInfo(
            IServiceProvider serviceProvider)
        {
            ConfigurationNode rootNode = ServiceHelper.GetCurrentRootNode(serviceProvider);

            WebServiceSettingsNode node = null;

            if (rootNode != null)
            {
                node = (WebServiceSettingsNode)rootNode.Hierarchy.FindNodeByType(
                    rootNode,
                    typeof(WebServiceSettingsNode));
            }

            WebServiceSettings webServiceSection = null;

            if (node == null)
            {
                webServiceSection = null;
            }
            else
            {
                WebServiceSettingsBuilder builder = new WebServiceSettingsBuilder(serviceProvider, node);
                webServiceSection = builder.Build();
            }

            return(new ConfigurationSectionInfo(node, webServiceSection, WebServiceSettings.SectionName));
        }
        private static bool CheckServiceEnabled(HttpContext context, string apiVersion, string httpMethod)
        {
            bool isEnabled;

            switch (apiVersion)
            {
            case "1":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv1);
                break;

            case "2":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv2);
                break;

            case "file":
                isEnabled = (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileUpload) &&
                             httpMethod.Is("POST")) ||
                            (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileDownload) &&
                             httpMethod.Is("GET"));
                break;

            case "media":
                isEnabled = ((WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaUpload) &&
                              httpMethod.Is("POST")) ||
                             (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaDownload) &&
                              httpMethod.Is("GET")));
                break;

            case "handle":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceHandleDownload);
                break;

            case "script":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting);
                break;

            default:
                isEnabled = false;
                break;
            }

            if (isEnabled)
            {
                return(true);
            }

            const string disabledMessage = "The request could not be completed because the service is disabled.";

            context.Response.StatusCode        = 403;
            context.Response.StatusDescription = disabledMessage;
            PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled.");

            return(false);
        }
        public OgameServiceV1Call(Guid toolId, string toolVersion, Guid?applicationKey, string userName, string password, WebServiceSettings webServiceSettings)
        {
            _toolId             = toolId;
            _toolVersion        = toolVersion;
            _webServiceSettings = webServiceSettings;

            SetWebServiceSettingsUrl();

            _soapHeader                = new AuthHeader();
            _soapHeader.ToolId         = toolId;
            _soapHeader.ApplicationKey = applicationKey;
            _soapHeader.Username       = userName;
            _soapHeader.Password       = password;
            RegisterSoapExtension();
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
        }
        private static HttpClient GetHttpClientForSettings(WebServiceSettings settings, int connectionTimeoutSeconds)
        {
            return(ClientCache.GetOrAdd(settings, (sets) =>
            {
                // Might get called more than once if e.g. many process instances execute at once,
                // but that should not matter much, as only one client will get cached
                var handler = new HttpClientHandler();
                handler.SetHandlerSettingsBasedOnSettings(sets);
                var httpClient = new HttpClient(handler);

                httpClient.DefaultRequestHeaders.ExpectContinue = false;
                httpClient.Timeout = TimeSpan.FromSeconds(Convert.ToDouble(connectionTimeoutSeconds));

                return httpClient;
            }));
        }
        internal WebServiceSettings GetLatestWebServiceSettings(bool throwException)
        {
            WebServiceSettings webServiceSettings    = null;
            WebBrowserClient   webClient             = new WebBrowserClient();
            string             webServiceSettingsUrl = GetCurrenWebServiceSettingsUrl();

            int retries = 1;

TryAgain:
            try
            {
                string webServiceSettingsString = webClient.GetPage(new Uri(webServiceSettingsUrl), "", true);

                if (!string.IsNullOrEmpty(webServiceSettingsString))
                {
                    try
                    {
                        webServiceSettingsString = SerializeDeserializeObject.DeserializeObject <String>(webServiceSettingsString);
                        webServiceSettingsString = Encryption.DecryptString(webServiceSettingsString);
                        webServiceSettings       = SerializeDeserializeObject.DeserializeObject <WebServiceSettings>(webServiceSettingsString);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(Constants.Message.TRY_NEXT_URL);
                    }
                }
                else
                {
                    throw new Exception(Constants.Message.TRY_NEXT_URL);
                }
            }
            catch
            {
                if (retries < GetNumberOfWebServiceSettingsUrl())
                {
                    retries++;
                    webServiceSettingsUrl = GetNextWebServiceSettingsUrl();
                    goto TryAgain;
                }
                else if (throwException)
                {
                    throw new Exception(Constants.Message.WEBSERVICE_SETTINGS_NOT_FOUND);
                }
            }

            return(webServiceSettings);
        }
Exemple #7
0
        private static bool CheckServiceEnabled(HttpContext context, string serviceName)
        {
            var isEnabled = WebServiceSettings.IsEnabled(serviceName);

            if (isEnabled)
            {
                return(true);
            }

            var errorMessage = $"The request could not be completed because the {serviceName} service is disabled.";

            context.Response.StatusCode        = 403;
            context.Response.StatusDescription = errorMessage;
            PowerShellLog.Warn(errorMessage);

            return(false);
        }
Exemple #8
0
        public NameValue[] ExecuteScript(string userName, string password, string script, string returnVariables)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(new NameValue[0]);
            }

            if (!Login(userName, password))
            {
                return(new[]
                {
                    new NameValue()
                    {
                        Name = "login failed", Value = "login failed"
                    }
                });
            }

            PowerShellLog.Info($"Script executed through remoting by user: '******' in disposable session.");

            using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.RemoteAutomation, false))
            {
                scriptSession.ExecuteScriptPart(script);

                var result = new List <NameValue>();

                if (scriptSession.Output.Count > 0)
                {
                    result.Add(new NameValue
                    {
                        Name  = "output",
                        Value =
                            scriptSession.Output.Select(p => p.Terminated ? p.Text + "\n" : p.Text).Aggregate(
                                (current, next) => current + next)
                    });
                }
                result.AddRange(
                    returnVariables.Split('|').Select(variable => new NameValue
                {
                    Name  = variable,
                    Value = (scriptSession.GetVariable(variable) ?? string.Empty).ToString()
                }));
                return(result.ToArray());
            }
        }
Exemple #9
0
        public bool UploadFile(string userName, string password, string filePath, byte[] fileContent, string database,
                               string language)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(false);
            }

            try
            {
                if (!Login(userName, password))
                {
                    return(false);
                }

                PowerShellLog.Info($"File '{filePath}' uploaded through remoting by user: '******'");

                var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/');
                if (!dirName.StartsWith(Constants.MediaLibraryPath))
                {
                    dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName);
                }

                var mco = new MediaCreatorOptions
                {
                    Database    = Factory.GetDatabase(database),
                    Language    = Language.Parse(language),
                    Versioned   = Settings.Media.UploadAsVersionableByDefault,
                    Destination = $"{dirName}/{Path.GetFileNameWithoutExtension(filePath)}"
                };

                var mc = new MediaCreator();
                using (var stream = new MemoryStream(fileContent))
                {
                    mc.CreateFromStream(stream, Path.GetFileName(filePath), mco);
                }
            }
            catch (Exception ex)
            {
                PowerShellLog.Error("Error during uploading file using PowerShell web service", ex);
                return(false);
            }
            return(true);
        }
Exemple #10
0
        public string ExecuteScriptBlockinSite2(string userName, string password, string script, string cliXmlArgs,
                                                string siteName, string sessionId)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(string.Empty);
            }
            if (!Login(userName, password))
            {
                return("<Objs xmlns=\"http://schemas.microsoft.com/powershell/2004/04\"><Obj RefId=\"0\"><S>login failed</S></Obj></Objs>");
            }

            PowerShellLog.Info($"Script executed in session {sessionId} through remoting by user: '******'");

            var scriptSession = ScriptSessionManager.GetSession(sessionId, ApplicationNames.RemoteAutomation, false);

            Sitecore.Context.SetActiveSite(siteName);

            if (!String.IsNullOrEmpty(cliXmlArgs))
            {
                scriptSession.SetVariable("cliXmlArgs", cliXmlArgs);
                scriptSession.ExecuteScriptPart("$params = ConvertFrom-CliXml -InputObject $cliXmlArgs", false, true);
                script = script.TrimEnd(' ', '\t', '\n');
            }
            var outObjects = scriptSession.ExecuteScriptPart(script, false, false, false);

            if (scriptSession.LastErrors != null && scriptSession.LastErrors.Any())
            {
                outObjects.AddRange(scriptSession.LastErrors);
            }
            scriptSession.SetVariable("results", outObjects);
            scriptSession.Output.Clear();
            scriptSession.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results");
            var result = scriptSession.Output.Select(p => p.Text).Aggregate((current, next) => current + next);

            if (String.IsNullOrEmpty(sessionId))
            {
                ScriptSessionManager.RemoveSession(scriptSession);
            }
            return(result);
        }
Exemple #11
0
        public string DisposeScriptSession(string userName, string password, string sessionId)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(string.Empty);
            }

            if (!Login(userName, password))
            {
                return("login failed");
            }

            PowerShellLog.Info($"Session '{sessionId}' disposed by user: '******'");

            if (ScriptSessionManager.GetSessionIfExists(sessionId) is ScriptSession session)
            {
                ScriptSessionManager.RemoveSession(session);
                return("removed");
            }

            return("not found");
        }
        private static async Task <HttpResponseMessage> GetHttpRequestResponseAsync(
            HttpClient httpClient, string method, string url,
            HttpContent content, IDictionary <string, string> headers,
            WebServiceSettings settings, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var request = new HttpRequestMessage(new HttpMethod(method), new Uri(url))
            {
                Content = content,
            };

            // Clear default headers
            content.Headers.Clear();

            foreach (var header in headers)
            {
                var requestHeaderAddedSuccessfully = request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                if (!requestHeaderAddedSuccessfully && request.Content != null)
                {
                    //Could not add to request headers try to add to content headers
                    var contentHeaderAddedSuccessfully = content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    if (!contentHeaderAddedSuccessfully)
                    {
                        Trace.TraceWarning($"Could not add header {header.Key}:{header.Value}");
                    }
                }
            }

            var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);

            if (settings.AllowInvalidResponseContentTypeCharSet && response.Content.Headers?.ContentType != null)
            {
                response.Content.Headers.ContentType.CharSet = null;
            }
            return(response);
        }
        // The method that sends the SOAP messages to OP web service interface
        public static async Task <HttpResponse> CallWebService(string url, string soapMessage, string softwareId, int connectionTimeoutSeconds, CancellationToken cancellationToken)
        {
            var settings = new WebServiceSettings();

            var httpClient = GetHttpClientForSettings(settings, connectionTimeoutSeconds);
            var headers    = GetHeaderDictionary(url, softwareId);

            using (var content = new StringContent(soapMessage, Encoding.GetEncoding(Encoding.UTF8.WebName)))
            {
                var responseMessage = await GetHttpRequestResponseAsync(
                    httpClient,
                    "POST",
                    url,
                    content,
                    headers,
                    settings,
                    cancellationToken)
                                      .ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                var response = new HttpResponse()
                {
                    Body       = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false),
                    StatusCode = (int)responseMessage.StatusCode,
                    Headers    = GetResponseHeaderDictionary(responseMessage.Headers, responseMessage.Content.Headers)
                };

                if (!responseMessage.IsSuccessStatusCode && settings.ThrowExceptionOnErrorResponse)
                {
                    throw new WebException(
                              $"Request to '{url}' failed with status code {(int)responseMessage.StatusCode}. Response body: {response.Body}");
                }

                return(response);
            }
        }
Exemple #14
0
        public byte[] DownloadFile(string userName, string password, string filePath, string database, string language)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(new byte[0]);
            }

            try
            {
                if (!Login(userName, password))
                {
                    return(Encoding.ASCII.GetBytes("login failed"));
                }

                PowerShellLog.Info($"File '{filePath}' downloaded through remoting by user: '******'");

                var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/');
                if (!dirName.StartsWith(Constants.MediaLibraryPath))
                {
                    dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName);
                }
                var itemname = dirName + "/" + Path.GetFileNameWithoutExtension(filePath);
                var db       = Factory.GetDatabase(database);
                var item     = (MediaItem)db.GetItem(itemname);
                using (var stream = item.GetMediaStream())
                {
                    var result = new byte[stream.Length];
                    stream.Read(result, 0, (int)stream.Length);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                PowerShellLog.Error("Error during uploading file using PowerShell web service", ex);
                return(new byte[0]);
            }
        }
 internal void UpdateWebServiceSettings(WebServiceSettings webServiceSettings)
 {
     _webServiceSettings = webServiceSettings;
 }
Exemple #16
0
 public WebServiceSettingsNodeBuilder(IServiceProvider serviceProvider,
                                      WebServiceSettings webServiceSettings)
     : base(serviceProvider)
 {
     this.webServiceSettings = webServiceSettings;
 }
        internal static void SetHandlerSettingsBasedOnSettings(this HttpClientHandler handler, WebServiceSettings settings)
        {
            // Uses Windows Integrated Security
            handler.UseDefaultCredentials = true;
            handler.AllowAutoRedirect     = settings.FollowRedirects;
            // Should this use a proxy?

            //Allow all endpoint types
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
        }
Exemple #18
0
 public TransloadWS(IOptions <WebServiceSettings> config, ILogger <TransloadWS> logger)
 {
     settings = config.Value;
     _logger  = logger;
 }
        private void GetValidWebServiceUrl(bool throwException)
        {
            lock (_lock)
            {
                bool             updateWebServiceSettingsWhenAllServicesAreDown = true;
                WebBrowserClient webClient     = new WebBrowserClient();
                WebServiceUrl    webServiceUrl = GetCurrentWebServiceUrl();

                if (_currentWebServiceUrl != null && (DateTime.Now - _lastPingDateTime).TotalSeconds <= 15)
                {
                    return;
                }

                int retries = 1;
TryAgain:
                try
                {
                    if (webServiceUrl != null && PingWebService(webServiceUrl.Url, false))
                    {
                        _lastPingDateTime     = DateTime.Now;
                        _currentWebServiceUrl = webServiceUrl;
                    }
                    else
                    {
                        throw new Exception(Constants.Message.TRY_NEXT_URL);
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message.Equals(Constants.Message.TRY_NEXT_URL))
                    {
                        if (retries < GetNumberOfWebServiceUrl())
                        {
                            retries++;
                            webServiceUrl = GetNextWebServiceUrl();
                            goto TryAgain;
                        }
                        else if (updateWebServiceSettingsWhenAllServicesAreDown)
                        {
                            updateWebServiceSettingsWhenAllServicesAreDown = false;
                            WebServiceSettings tempWebServiceSettings = GetLatestWebServiceSettings(false);
                            if (tempWebServiceSettings != null && _webServiceSettings.SettingId != tempWebServiceSettings.SettingId)
                            {
                                _webServiceSettings.SettingId         = tempWebServiceSettings.SettingId;
                                _webServiceSettings.WebServiceUrlList = tempWebServiceSettings.WebServiceUrlList;
                                _currentWebServiceUrlIndex            = 0;
                                webServiceUrl = GetCurrentWebServiceUrl();
                                retries       = 1;
                                goto TryAgain;
                            }
                        }
                        if (throwException)
                        {
                            throw new Exception(Constants.Message.WEBSERVICES_ARE_DOWN);
                        }
                    }
                    else if (throwException)
                    {
                        throw ex;
                    }
                }
            }
        }
 public IdentityWebEndpoint(ILogger logger, WebServiceSettings webServiceSettings) :
     base(logger, webServiceSettings)
 {
 }
        private static bool CheckServiceEnabled(string apiVersion, string httpMethod)
        {
            var          isEnabled       = true;
            const string disabledMessage = "The request could not be completed because the service is disabled.";

            switch (apiVersion)
            {
            case "1":
                if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv1))
                {
                    HttpContext.Current.Response.StatusCode        = 403;
                    HttpContext.Current.Response.StatusDescription = disabledMessage;
                    isEnabled = false;
                }
                break;

            case "2":
                if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv2))
                {
                    HttpContext.Current.Response.StatusCode        = 403;
                    HttpContext.Current.Response.StatusDescription = disabledMessage;
                    isEnabled = false;
                }
                break;

            case "file":
                if ((WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileUpload) && httpMethod.Is("POST")) ||
                    (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileDownload) && httpMethod.Is("GET")))
                {
                    break;
                }
                HttpContext.Current.Response.StatusCode        = 403;
                HttpContext.Current.Response.StatusDescription = disabledMessage;
                isEnabled = false;
                break;

            case "media":
                if ((WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaUpload) && httpMethod.Is("POST")) ||
                    (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaDownload) && httpMethod.Is("GET")))
                {
                    break;
                }
                HttpContext.Current.Response.StatusCode        = 403;
                HttpContext.Current.Response.StatusDescription = disabledMessage;
                isEnabled = false;
                break;

            case "handle":
                if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceHandleDownload))
                {
                    HttpContext.Current.Response.StatusCode        = 403;
                    HttpContext.Current.Response.StatusDescription = disabledMessage;
                    isEnabled = false;
                }
                break;

            default:
                HttpContext.Current.Response.StatusCode        = 403;
                HttpContext.Current.Response.StatusDescription = disabledMessage;
                isEnabled = false;
                break;
            }

            return(isEnabled);
        }