public static MimeMap CreateMimeMap(dynamic model, StaticContentSection section) { if (model == null) { throw new ApiArgumentException("model"); } string fileExtension = DynamicHelper.Value(model.file_extension); string mimeType = DynamicHelper.Value(model.mime_type); if (string.IsNullOrEmpty(fileExtension)) { throw new ApiArgumentException("file_extension"); } if (string.IsNullOrEmpty(mimeType)) { throw new ApiArgumentException("mime_type"); } MimeMap mimeMap = section.MimeMaps.CreateElement(); mimeMap.FileExtension = fileExtension.StartsWith(".") ? fileExtension : "." + fileExtension; mimeMap.MimeType = mimeType; return(mimeMap); }
public static HeaderLimit UpdateHeaderLimit(HeaderLimit headerLimit, dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (headerLimit == null) { throw new ApiArgumentException("headerLimit"); } string header = DynamicHelper.Value(model.header); if (header == string.Empty) { throw new ApiArgumentException("header"); } try { headerLimit.Header = DynamicHelper.Value(model.header) ?? headerLimit.Header; headerLimit.SizeLimit = DynamicHelper.To(model.size_limit, 0, uint.MaxValue) ?? headerLimit.SizeLimit; } catch (FileLoadException e) { throw new LockedException(RequestFilteringGlobals.RequestFilteringSectionName, e); } return(headerLimit); }
public static Application CreateApplication(dynamic model, Site site, IFileProvider fileProvider) { // Ensure necessary information provided if (model == null) { throw new ApiArgumentException("model"); } if (String.IsNullOrEmpty(DynamicHelper.Value(model.path))) { throw new ApiArgumentException("path"); } if (string.IsNullOrEmpty(DynamicHelper.Value(model.physical_path))) { throw new ApiArgumentException("physical_path"); } if (site == null) { throw new ArgumentException("site"); } Application app = site.Applications.CreateElement(); // Initialize root virtual directory app.VirtualDirectories.Add("/", string.Empty); // Initialize new application settings SetToDefaults(app); // Set application settings to those provided SetApplication(app, model, fileProvider); return(app); }
public static OutboundRule CreateRule(dynamic model, OutboundRulesSection section) { if (model == null) { throw new ApiArgumentException("model"); } if (string.IsNullOrEmpty(DynamicHelper.Value(model.name))) { throw new ApiArgumentException("name"); } if (string.IsNullOrEmpty(DynamicHelper.Value(model.pattern))) { throw new ApiArgumentException("pattern"); } if (string.IsNullOrEmpty(DynamicHelper.Value(model.match_type))) { throw new ApiArgumentException("match_type"); } var rule = (OutboundRule)section.Rules.CreateElement(); // // Default to rewrite rule rule.Action.Type = OutboundActionType.Rewrite; rule.PatternSyntax = PatternSyntax.ECMAScript; SetRule(model, rule, section); return(rule); }
public static void Initialize(string filePath) { dynamic configObject; using (FileStream fs = new FileStream(filePath, FileMode.Open)) using (StreamReader sr = new StreamReader(fs)) { configObject = JsonConvert.DeserializeObject(sr.ReadToEnd()); } string id = DynamicHelper.Value(configObject.host_id); if (string.IsNullOrEmpty(id)) { Guid guid = Guid.NewGuid(); configObject.host_id = guid.ToString(); using (FileStream fs = new FileStream(filePath, FileMode.Truncate)) using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(JsonConvert.SerializeObject(configObject, Formatting.Indented)); sw.Flush(); } HostId = guid; } else { HostId = Guid.Parse(id); } }
public static JObject GetSite(HttpClient client, string siteName) { List <JObject> sites; if (!(GetSites(client, out sites))) { return(null); } JObject siteRef = sites.FirstOrDefault(s => { string name = DynamicHelper.Value(s["name"]); return(name == null ? false : name.Equals(siteName, StringComparison.OrdinalIgnoreCase)); }); if (siteRef == null) { return(null); } string siteContent; if (client.Get($"{Configuration.TEST_SERVER_URL}{ siteRef["_links"]["self"].Value<string>("href") }", out siteContent)) { return(JsonConvert.DeserializeObject <JObject>(siteContent)); } return(null); }
private static void ExtractModel(dynamic model, out string username, out string password, out string path, out string privateKeyPassword) { if (model == null) { throw new ApiArgumentException("model"); } if (!(model is JObject)) { throw new ApiArgumentException("model", ApiArgumentException.EXPECTED_OBJECT); } dynamic identity = model.identity; if (identity != null && !(identity is JObject)) { throw new ApiArgumentException("identity", ApiArgumentException.EXPECTED_OBJECT); } // // Validate model and extract values path = DynamicHelper.Value(model.path); privateKeyPassword = DynamicHelper.Value(model.private_key_password); username = null; password = null; if (identity != null) { username = DynamicHelper.Value(identity.username); password = DynamicHelper.Value(identity.password); } }
public static void UpdateMapping(dynamic model, Mapping mapping, HandlersSection section) { if (model == null) { throw new ApiArgumentException("model"); } try { string name = DynamicHelper.Value(model.name); if (!string.IsNullOrEmpty(name)) { // Check if trying to change to a different name, if so make sure it doesn't already exist if (section.Mappings.Any(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) && !mapping.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { throw new AlreadyExistsException("mapping.name"); } mapping.Name = name; } SetMapping(model, mapping); } catch (FileLoadException e) { throw new LockedException(section.SectionPath, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } }
public object Post([FromBody] dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (model.handler == null || !(model.handler is JObject)) { throw new ApiArgumentException("handler"); } string handlersUuid = DynamicHelper.Value(model.handler.id); if (handlersUuid == null) { throw new ApiArgumentException("handler.id"); } // Get the feature id HandlersId handlersId = new HandlersId(handlersUuid); Site site = handlersId.SiteId == null ? null : SiteHelper.GetSite(handlersId.SiteId.Value); string configPath = ManagementUnit.ResolveConfigScope(model); HandlersSection section = HandlersHelper.GetHandlersSection(site, handlersId.Path, configPath); Mapping mapping = MappingsHelper.CreateMapping(model, section); MappingsHelper.AddMapping(mapping, section); ManagementUnit.Current.Commit(); dynamic m = MappingsHelper.ToJsonModel(mapping, site, handlersId.Path); return(Created(MappingsHelper.GetLocation(m.id), m)); }
public static File CreateFile(dynamic model, DefaultDocumentSection section) { // Ensure integrity of model if (model == null) { throw new ApiArgumentException("model"); } if (section == null) { throw new ArgumentNullException("section"); } string name = DynamicHelper.Value(model.name); if (String.IsNullOrEmpty(name)) { throw new ApiArgumentException("name"); } File file = section.Files.CreateElement(); file.Name = name; return(file); }
public static UrlRule CreateUrl(dynamic model, RequestFilteringSection section) { if (model == null) { throw new ApiArgumentException("model"); } string urlString = DynamicHelper.Value(model.url); if (string.IsNullOrEmpty(urlString)) { throw new ApiArgumentException("url"); } if (DynamicHelper.To <bool>(model.allow) == null) { throw new ApiArgumentException("allow"); } bool allow = DynamicHelper.To <bool>(model.allow); return(new UrlRule() { Url = urlString, Allow = allow }); }
public async Task <object> Post([FromBody] dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (model.api_key == null || model.api_key.id == null) { throw new ApiArgumentException("api_key"); } string apikeyId = DynamicHelper.Value(model.api_key.id); ApiKey key = _keyProvider.GetKey(apikeyId); if (key == null) { return(NotFound()); } // Renew the token string token = await _keyProvider.RenewToken(key); // // Create response dynamic obj = AccessTokenHelper.ToJsonModel(new ApiToken() { Token = token, Key = key }); return(Created(AccessTokenHelper.GetLocation(key.Id), obj)); }
public static Module CreateManagedModule(dynamic model, ModulesSection section) { if (model == null) { throw new ApiArgumentException("model"); } string name = DynamicHelper.Value(model.name); string type = DynamicHelper.Value(model.type); if (string.IsNullOrEmpty(name)) { throw new ApiArgumentException("name"); } if (string.IsNullOrEmpty(type)) { throw new ApiArgumentException("type"); } Module module = section.Modules.CreateElement(); module.Name = name; module.Type = type; module.PreCondition = DynamicHelper.Value(model.precondition) ?? module.PreCondition; return(module); }
public async Task <object> Post([FromBody] dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (model.expires_on == null) { throw new ApiArgumentException("expires_on"); } string purpose = DynamicHelper.Value(model.purpose) ?? string.Empty; DateTime?expiresOn = DynamicHelper.Value(model.expires_on) != String.Empty ? DynamicHelper.To <DateTime>(model.expires_on) : null; ApiToken token = _keyProvider.GenerateKey(purpose); token.Key.ExpiresOn = expiresOn; await _keyProvider.SaveKey(token.Key); // // Create response dynamic key = ApiKeyHelper.ToJsonModel(token); return(Created(ApiKeyHelper.GetLocation(key.id), key)); }
public static Site ResolveSite(dynamic model = null) { string appUuid = null; if (model != null && model.webapp != null) { if (!(model.webapp is JObject)) { throw new ApiArgumentException("webapp"); } appUuid = DynamicHelper.Value(model.webapp.id); } var context = HttpHelper.Current; if (appUuid == null) { appUuid = context.Request.Query[Defines.IDENTIFIER]; } if (appUuid != null) { var site = SiteHelper.GetSite(new ApplicationId(appUuid).SiteId); if (site == null) { throw new NotFoundException("site"); } return(site); } return(SiteHelper.ResolveSite(model)); }
public static NameValueConfigurationElement Create(dynamic model, HttpProtocolSection section) { if (section == null) { throw new ArgumentException("section"); } if (model == null) { throw new ApiArgumentException("model"); } string name = DynamicHelper.Value(model.name); string value = DynamicHelper.Value(model.value); if (String.IsNullOrEmpty(name)) { throw new ApiArgumentException("name"); } if (value == null) { // We don't check for empty because there is nothing wrong with an empty string header value throw new ApiArgumentException("value"); } var elem = section.CustomHeaders.CreateElement(); elem.Name = name; elem.Value = value; return(elem); }
public static ApplicationPool CreateAppPool(dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } string name = DynamicHelper.Value(model.name); if (String.IsNullOrEmpty(name)) { throw new ApiArgumentException("name"); } if (GetAppPool(name) != null) { throw new AlreadyExistsException("name"); } var sm = ManagementUnit.ServerManager; ApplicationPool appPool = sm.ApplicationPools.CreateElement(); SetToDefaults(appPool, sm.ApplicationPoolDefaults); SetAppPool(appPool, model); return(appPool); }
public static TraceRule UpdateRule(TraceRule rule, dynamic model, Site site, string virtualPath, string configPath = null) { if (model == null) { throw new ApiArgumentException("model"); } if (rule == null) { throw new ArgumentNullException("rule"); } var section = Helper.GetTraceFailedRequestsSection(site, virtualPath, configPath); string path = DynamicHelper.Value(model.path); if (path != null && !path.Equals(rule.Path) && section.TraceRules.Any(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase))) { throw new AlreadyExistsException("path"); } try { SetRule(rule, model, site, virtualPath); } catch (FileLoadException e) { throw new LockedException(section.SectionPath, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } return(rule); }
public static JObject GetAppPool(HttpClient client, string poolName) { List <JObject> pools; if (!(GetAppPools(client, out pools))) { return(null); } JObject poolRef = pools.FirstOrDefault(s => { string name = DynamicHelper.Value(s["name"]); return(name == null ? false : name.Equals(poolName, StringComparison.OrdinalIgnoreCase)); }); if (poolRef == null) { return(null); } string poolContent; if (client.Get($"{ Globals.TEST_SERVER }:{ Globals.TEST_PORT }{ poolRef["_links"]["self"].Value<string>("href") }", out poolContent)) { return(JsonConvert.DeserializeObject <JObject>(poolContent)); } return(null); }
public static void Update(ApiKey key, dynamic model) { if (key == null) { throw new ArgumentNullException(); } if (model == null) { throw new ApiArgumentException("model"); } // // purpose string purpose = DynamicHelper.Value(model.purpose); if (purpose != null) { key.Purpose = purpose; } // // expires_on DateTime?expiresOn = DynamicHelper.To <DateTime>(model.expires_on); if (expiresOn != null) { key.ExpiresOn = expiresOn; } // // Set last modified key.LastModified = DateTime.Now; }
public static NameValueConfigurationElement Create(dynamic model, HttpProtocolSection section) { if (section == null) { throw new ArgumentException("section"); } if (model == null) { throw new ApiArgumentException("model"); } string name = DynamicHelper.Value(model.name); string value = DynamicHelper.Value(model.value); if (String.IsNullOrEmpty(name)) { throw new ApiArgumentException("name"); } if (value == null) { throw new ApiArgumentException("value"); } var elem = section.RedirectHeaders.CreateElement(); elem.Name = name; elem.Value = value; return(elem); }
public static string ResolvePath(dynamic model = null) { string appUuid = null; if (model != null && model.webapp != null) { if (!(model.webapp is JObject)) { throw new ApiArgumentException("webapp"); } appUuid = DynamicHelper.Value(model.webapp.id); } var context = HttpHelper.Current; if (appUuid == null) { appUuid = context.Request.Query[Defines.IDENTIFIER]; } if (appUuid != null) { ApplicationId id = new ApplicationId(appUuid); return(id.Path); } return(SiteHelper.ResolvePath(model)); }
public static void UpdateModule(Module module, dynamic model, Site site) { if (model == null) { throw new ApiArgumentException("model"); } if (module == null) { throw new ArgumentNullException("module"); } if (string.IsNullOrEmpty(module.Name)) { throw new ApiArgumentException("module.Name"); } string type = DynamicHelper.Value(model.type) ?? string.Empty; string precondition = DynamicHelper.Value(model.precondition) ?? module.PreCondition; if (ModuleIsLocked(module) && site != null) { // Can't update the module if it is locked // Unless the scope is at server level throw new InvalidOperationException("Lock violation"); } try { // Locked bool?locked = DynamicHelper.To <bool>(model.locked); if (locked != null) { SetItemLocked(module, locked.Value); } // Precondition if (ConfigurationUtility.ShouldPersist(module.PreCondition, precondition)) { module.PreCondition = precondition; } // Type if (string.IsNullOrEmpty(module.Type) != string.IsNullOrEmpty(type)) { // If the module specified a type, we allow a type name change but not erasure // If the module did not specify a type during creation we don't allow a change throw new ApiArgumentException("type"); } module.Type = type; } catch (FileLoadException e) { throw new LockedException(ModulesGlobals.ModulesSectionName, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } }
public static void UpdateFeatureSettings(dynamic model, Site site, string path, string configPath = null) { if (model == null) { throw new ApiArgumentException("model"); } AllowedServerVariablesSection section = ServerVariablesHelper.GetSection(site, path, configPath); try { if (model.entries != null) { IEnumerable <dynamic> variables = model.entries as IEnumerable <dynamic>; if (variables == null) { throw new ApiArgumentException("entries", ForbiddenArgumentException.EXPECTED_ARRAY); } List <string> variableList = new List <string>(); // Validate all verbs provided foreach (dynamic variable in variables) { string var = DynamicHelper.Value(variable); if (string.IsNullOrEmpty(var)) { throw new ApiArgumentException("entries.item"); } variableList.Add(var); } // Clear configuration's collection section.AllowedServerVariables.Clear(); // Move from temp list to the configuration's collection variableList.ForEach(v => section.AllowedServerVariables.Add(v)); } if (model.metadata != null) { DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => { section.OverrideMode = v; }); } } catch (FileLoadException e) { throw new LockedException(section.SectionPath, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } }
public ILocation CreateLocation(dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } string alias = DynamicHelper.Value(model.alias); string path = DynamicHelper.Value(model.path); IEnumerable <string> claims = null; // // Validate model if (!string.IsNullOrEmpty(alias) && !PathUtil.IsValidFileName(alias)) { throw new ApiArgumentException("alias"); } if (string.IsNullOrEmpty(path) && !PathUtil.IsFullPath(System.Environment.ExpandEnvironmentVariables(path))) { throw new ApiArgumentException("path"); } if (model.claims == null) { throw new ApiArgumentException("claims"); } if (!(model.claims is JArray)) { throw new ApiArgumentException("claims", ApiArgumentException.EXPECTED_ARRAY); } claims = (model.claims as JArray).ToObject <IEnumerable <string> >(); foreach (string claim in claims) { if (!claim.Equals("read", StringComparison.OrdinalIgnoreCase) && !claim.Equals("write", StringComparison.OrdinalIgnoreCase)) { throw new ApiArgumentException("claim"); } } ILocation location = new Location() { Alias = alias ?? string.Empty, Path = path, Claims = claims }; CreateIfNecessary(location); return(location); }
public static Rule SetRule(Rule rule, dynamic model, IPSecuritySection section) { if (rule == null) { throw new ArgumentNullException("rule"); } string subnetMask = DynamicHelper.Value(model.subnet_mask); if (subnetMask != null) { try { // Throw format exception of subnet mask is not in valid format IPAddress.Parse(subnetMask); } catch (FormatException e) { throw new ApiArgumentException("subnet_mask", e); } } string inIp = DynamicHelper.Value(model.ip_address); IPAddress ipAddress = null; if (inIp != null) { try { ipAddress = IPAddress.Parse(inIp); } catch (FormatException e) { throw new ApiArgumentException("ip_address", e); } if (ipAddress != rule.IpAddress && section.IpAddressFilters.Any(r => r.IpAddress.Equals(ipAddress))) { throw new AlreadyExistsException("ip_address"); } } try { rule.IpAddress = ipAddress != null ? ipAddress : rule.IpAddress; rule.Allowed = DynamicHelper.To <bool>(model.allowed) ?? rule.Allowed; rule.SubnetMask = subnetMask ?? rule.SubnetMask; rule.DomainName = DynamicHelper.Value(model.domain_name) ?? rule.DomainName; } catch (FileLoadException e) { throw new LockedException(IPRestrictionsGlobals.IPSecuritySectionName, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } return(rule); }
public void EnsurePostModelValid(dynamic model, out string name, out FileId fileId, out FileId parentId) { if (model == null) { throw new ApiArgumentException("model"); } // // file if (model.file == null) { throw new ApiArgumentException("file"); } if (!(model.file is JObject)) { throw new ApiArgumentException("file", ApiArgumentException.EXPECTED_OBJECT); } string fileUuid = DynamicHelper.Value(model.file.id); if (fileUuid == null) { throw new ApiArgumentException("file.id"); } // // parent if (model.parent == null) { throw new ApiArgumentException("parent"); } if (!(model.parent is JObject)) { throw new ApiArgumentException("parent", ApiArgumentException.EXPECTED_OBJECT); } string parentUuid = DynamicHelper.Value(model.parent.id); if (parentUuid == null) { throw new ApiArgumentException("parent.id"); } // // name name = DynamicHelper.Value(model.name); if (!string.IsNullOrEmpty(name) && !PathUtil.IsValidFileName(name)) { throw new ApiArgumentException("name"); } fileId = FileId.FromUuid(fileUuid); parentId = FileId.FromUuid(parentUuid); }
private static void SetApplication(Application app, dynamic model) { string path = DynamicHelper.Value(model.path); if (!string.IsNullOrEmpty(path)) { // Make sure path starts with '/' if (path[0] != '/') { path = '/' + path; } app.Path = path; } DynamicHelper.If((object)model.enabled_protocols, v => app.EnabledProtocols = v); string physicalPath = DynamicHelper.Value(model.physical_path); if (physicalPath != null) { if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath))) { throw new ApiArgumentException("physical_path", "Directory does not exist."); } var rootVDir = app.VirtualDirectories["/"]; if (rootVDir == null) { throw new ApiArgumentException("application/physical_path", "Root virtual directory does not exist."); } rootVDir.PhysicalPath = physicalPath.Replace('/', '\\'); } if (model.application_pool != null) { // Change application pool if (model.application_pool.id == null) { throw new ApiArgumentException("application_pool.id"); } string poolName = AppPools.AppPoolId.CreateFromUuid(DynamicHelper.Value(model.application_pool.id)).Name; ApplicationPool pool = AppPoolHelper.GetAppPool(poolName); if (pool != null) { app.ApplicationPoolName = pool.Name; } } }
public object Post([FromBody] dynamic model) { File file = null; DefaultDocumentId docId = null; Site site = null; if (model == null) { throw new ApiArgumentException("model"); } if (model.default_document == null) { throw new ApiArgumentException("default_document"); } if (!(model.default_document is JObject)) { throw new ApiArgumentException("default_document"); } // Creating a a file instance requires referencing the target feature string docUuid = DynamicHelper.Value(model.default_document.id); if (docUuid == null) { throw new ApiArgumentException("default_document.id"); } // Get the default document feature id docId = new DefaultDocumentId(docUuid); site = docId.SiteId == null ? null : SiteHelper.GetSite(docId.SiteId.Value); // Get target configuration section for addition of file string configPath = ManagementUnit.ResolveConfigScope(model); DefaultDocumentSection section = DefaultDocumentHelper.GetDefaultDocumentSection(site, docId.Path, configPath); // Create default document file = FilesHelper.CreateFile(model, section); // Add it FilesHelper.AddFile(file, section); // Save ManagementUnit.Current.Commit(); // // Create response dynamic f = FilesHelper.ToJsonModel(file, site, docId.Path); return(Created(FilesHelper.GetLocation(f.id), f)); }
public object Post([FromBody] dynamic model) { Rule rule = null; Site site = null; RequestFilteringId reqId = null; if (model == null) { throw new ApiArgumentException("model"); } // Rule must be created for a specific request filtering section if (model.request_filtering == null) { throw new ApiArgumentException("request_filtering"); } if (!(model.request_filtering is JObject)) { throw new ApiArgumentException(String.Empty, "request_filtering"); } string reqUuid = DynamicHelper.Value(model.request_filtering.id); if (reqUuid == null) { throw new ApiArgumentException("request_filtering.id"); } // Get the feature id reqId = new RequestFilteringId(reqUuid); // Get site the rule is for if applicable site = reqId.SiteId == null ? null : SiteHelper.GetSite(reqId.SiteId.Value); string configPath = ManagementUnit.ResolveConfigScope(model); RequestFilteringSection section = RequestFilteringHelper.GetRequestFilteringSection(site, reqId.Path, configPath); // Create filtering rule rule = RulesHelper.CreateRule(model, section); // Add it RulesHelper.AddRule(rule, section); // Save ManagementUnit.Current.Commit(); // // Create response dynamic r = RulesHelper.ToJsonModel(rule, site, reqId.Path, null, true); return(Created(RulesHelper.GetLocation(r.id), r)); }