private void CheckAccess(IIdentity identity, IServiceRequestInterpreter interpreter, IMapServiceSettings settings) { if (settings?.AccessRules == null || settings.AccessRules.Length == 0) // No Settings -> free service { return; } string userName = identity.UserName; var accessRule = settings .AccessRules .Where(r => r.Username.Equals(userName, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); // if user not found, use rules for anonymous if (accessRule == null) { accessRule = settings .AccessRules .Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); } if (accessRule == null || accessRule.ServiceTypes == null) { throw new TokenRequiredException("forbidden (user:"******")"); } if (!accessRule.ServiceTypes.Contains("_all") && !accessRule.ServiceTypes.Contains("_" + interpreter.IdentityName.ToLower())) { throw new NotAuthorizedException(interpreter.IdentityName + " interface forbidden (user: "******")"); } }
public void Init(int port) { _serverConfig = MapServerConfig.ServerByPort(port); if (_interpreters.Keys.Count == 0) { List <IServiceRequestInterpreter> interpreters = new List <IServiceRequestInterpreter>(); PlugInManager compMan = new PlugInManager(); foreach (XmlNode interpreterNode in compMan.GetPluginNodes(Plugins.Type.IServiceRequestInterpreter)) { IServiceRequestInterpreter interpreter = compMan.CreateInstance(interpreterNode) as IServiceRequestInterpreter; if (interpreter == null) { continue; } interpreters.Add(interpreter); } foreach (IServiceRequestInterpreter interpreter in interpreters) { string guid = PlugInManager.PlugInID(interpreter).ToString().ToLower(); string name = interpreter.IntentityName.ToLower(); if (_interpreters.ContainsKey(guid) || _interpreters.ContainsKey(name)) { continue; } _interpreters.Add(guid, interpreter); if (!String.IsNullOrEmpty(name)) { _interpreters.Add(name, interpreter); } } } }
async public Task CheckAccess(IIdentity identity, IServiceRequestInterpreter interpreter) { if (identity == null) { throw new ArgumentNullException("identity"); } if (interpreter == null) { throw new ArgumentNullException("interpreter"); } await ReloadServiceSettings(); if (!_settings.IsRunningOrIdle()) { throw new Exception("Service not running: " + this.Fullname); } if (_folderSettings != null) { CheckAccess(identity, interpreter, _folderSettings); } CheckAccess(identity, interpreter, _settings); }
public void SetRequestContext(IServiceRequestContext context) { if (context != null) { _mapServer = context.MapServer; _interpreter = context.ServiceRequestInterpreter; _request = context.ServiceRequest; } }
public ServiceRequestContext(IMapServer mapServer, IServiceRequestInterpreter interpreter, ServiceRequest request) { _mapServer = mapServer; _interpreter = interpreter; _request = request; }
public IActionResult OgcRequest(string id, string service = "") { try { IServiceRequestInterpreter interpreter = null; switch (service.ToLower().Split(',')[0]) { case "wms": interpreter = InternetMapServer.GetInterpreter(typeof(WMSRequest)); break; case "wfs": interpreter = InternetMapServer.GetInterpreter(typeof(WFSRequest)); break; case "wmts": interpreter = InternetMapServer.GetInterpreter(typeof(WMTSRequest)); break; default: throw new Exception("Missing or unknow service: " + service); } #region Request string requestString = Request.QueryString.ToString(); if (Request.Method.ToLower() == "post" && Request.Body.CanRead) { MemoryStream ms = new MemoryStream(); byte[] bodyData = new byte[1024]; int bytesRead; while ((bytesRead = Request.Body.Read(bodyData, 0, bodyData.Length)) > 0) { ms.Write(bodyData, 0, bytesRead); } string body = Encoding.UTF8.GetString(ms.ToArray()); if (!String.IsNullOrWhiteSpace(body)) { requestString = body; } } while (requestString.StartsWith("?")) { requestString = requestString.Substring(1); } ServiceRequest serviceRequest = new ServiceRequest(id, requestString); serviceRequest.OnlineResource = InternetMapServer.OnlineResource + "/ogc/" + id; #endregion #region Security Identity identity = Identity.FromFormattedString(String.Empty); identity.HashedPassword = String.Empty; serviceRequest.Identity = identity; #endregion IServiceRequestContext context = new ServiceRequestContext( InternetMapServer.Instance, interpreter, serviceRequest); InternetMapServer.ThreadQueue.AddQueuedThreadSync(interpreter.Request, context); return(Result(serviceRequest.Response, "text/xml")); } catch (Exception ex) { // ToDo: OgcXmlExcpetion return(Result(ex.Message, "text/plain")); } }
static void Main(string[] args) { System.Net.ServicePointManager.DefaultConnectionLimit = 256; //System.Net.ServicePointManager.MaxServicePoints = 256; System.Net.ServicePointManager.CertificatePolicy = new gView.Framework.Web.SimpleHttpsPolicy(); gView.Framework.system.gViewEnvironment.UserInteractive = false; //int x = 0; //x = 1 / x; try { //Thread thread = new Thread(new ThreadStart(StartThread2)); //thread.Start(); //gView.Framework.system.SystemVariables.ApplicationDirectory = gView.Framework.system.SystemVariables.RegistryApplicationDirectory; Logger.Log(loggingMethod.request, "Service EXE started..."); bool console = false; int port = -1; for (int i = 0; i < args.Length; i++) { if (args[i] == "-c") { console = true; } if (args[i] == "-port") { port = int.Parse(args[i + 1]); } } //port = 8001; //console = true; Logger.Log(loggingMethod.request, "Current Directory: " + System.Environment.CurrentDirectory); //Logger.Log(loggingMethod.request, "Check license..."); //myLicense = new License(false); //Logger.Log(loggingMethod.request, "License Info********"); //Logger.Log(loggingMethod.request, "ProductID: " + myLicense.ProductID); //Logger.Log(loggingMethod.request, "InstallationDate: " + SystemVariables.InstallationTime.ToShortDateString() + " " + SystemVariables.InstallationTime.ToLongTimeString()); //Logger.Log(loggingMethod.request, "LicenseFile: " + myLicense.LicenseFile); //Logger.Log(loggingMethod.request, "LicenseFileExists: " + myLicense.LicenseFileExists.ToString()); //if (myLicense.LicenseComponents != null) //{ // Logger.Log(loggingMethod.request, "Components:"); // foreach (string component in myLicense.LicenseComponents) // Logger.Log(loggingMethod.request, " " + component); //} //LicenseTypes licType = IMS.myLicense.ComponentLicenseType("gview.Server;gview.PersonalMapServer"); //if (licType == LicenseTypes.Unknown || // licType == LicenseTypes.Expired) //{ // Logger.Log(loggingMethod.error, "Server is not licensed..."); // return; //} //Logger.Log(loggingMethod.request, "********************"); // Interpreter suchen... Logger.Log(loggingMethod.request, "Register request interpreters..."); mapServer = new MapServer(port); /* * switch (mapServer.LicType) * { * case MapServer.ServerLicType.Unknown: * Logger.Log(loggingMethod.error, "Unkown License"); * if (console) * { * Console.WriteLine("Unkown License..."); #if(DEBUG) * Console.ReadLine(); #endif * } * return; * case MapServer.ServerLicType.Express: * case MapServer.ServerLicType.Private: * System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("gview.mapserver"); * if (procs.Length > 1) * { * Logger.Log(loggingMethod.error, "Your server license type '" + mapServer.LicType.ToString() + "' allows only one server instance!"); * if (console) * { * Console.WriteLine("Your server license type '" + mapServer.LicType.ToString() + "' allows only one server instance!"); #if(DEBUG) * Console.ReadLine(); #endif * } * return; * } * break; * } * */ PlugInManager compMan = new PlugInManager(); foreach (XmlNode interpreterNode in compMan.GetPluginNodes(Plugins.Type.IServiceRequestInterpreter)) { IServiceRequestInterpreter interpreter = compMan.CreateInstance(interpreterNode) as IServiceRequestInterpreter; if (interpreter == null) { continue; } interpreter.OnCreate(mapServer); _interpreters.Add(interpreter); } try { SetConsoleTitle("gView.MapServer.Instance." + port); } catch { } #if (!DEBUG) if (console) { //ImageService service = new ImageService(); //service.Start(args); Console.WriteLine("Server Instance " + port + " starting..."); ServerProcess process = new ServerProcess(port, false); Console.WriteLine("Server Instance is listing on port " + port); Console.ReadLine(); process.Stop(); //service.Stop(); } else { if (port != -1) { Console.WriteLine("Start Server On Port: " + port); ServerProcess process = new ServerProcess(port, true); } else { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ImageService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } } #else port = (port != -1) ? port : 8001; Console.WriteLine("Server Instance " + port + " starting..."); ServerProcess process = new ServerProcess(port, false); Console.WriteLine("Server Instance is listing on port " + port); Console.ReadLine(); Console.WriteLine("Stopping Instance on port " + port); process.Stop(); #endif } catch (Exception ex) { Logger.Log(loggingMethod.error, ex.Message); } }
public Stream TileWmts(string name, string cacheType, string origin, string epsg, string style, string level, string row, string col) { try { if (_serverConfig == null || _serverConfig.Instances.Length == 0) { return(WriteException("ServiceType not initialized!")); } if (IfMatch()) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.StatusCode = HttpStatusCode.NotModified; return(null); } string user, pwd; var request = Request(out user, out pwd); int instanceNr = GetRandom(_serverConfig.Instances.Length /* MapServerConfig.ServerCount*/); MapServerConfig.ServerConfig.InstanceConfig config = _serverConfig.Instances[instanceNr]; InstanceConnection conn = new InstanceConnection("localhost:" + config.Port); IServiceRequestInterpreter requestInterpreter = GetInterpreter("wmts"); string ret = conn.Send(String.Empty, name, cacheType + "/" + origin + "/" + epsg + "/" + style + "/~" + level + "/" + row + "/" + col, PlugInManager.PlugInID(requestInterpreter).ToString(), user, pwd); if (ret.StartsWith("image:")) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "image/png"; ret = ret.Substring(6, ret.Length - 6); return(WriteFile(ret)); } if (ret.StartsWith("{")) { try { var mapServerResponse = gView.Framework.system.MapServerResponse.FromString(ret); OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = mapServerResponse.ContentType; if (mapServerResponse.Expires != null) { AppendEtag((DateTime)mapServerResponse.Expires); } return(WriteBytes(mapServerResponse.Data)); } catch { } } return(WriteValue(ret)); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }
public Stream MapRequestPost(string interpreter, string name, Stream data) { try { if (_serverConfig == null || _serverConfig.Instances.Length == 0) { return(WriteException("ServiceType not initialized!")); } if (IfMatch()) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.StatusCode = HttpStatusCode.NotModified; return(null); } //DateTime td = DateTime.Now; //Console.WriteLine("Start Map Request " + td.ToLongTimeString() + "." + td.Millisecond + " (" + name + ")"); //System.Threading.Thread.Sleep(10000); string user, pwd; var request = Request(out user, out pwd); NameValueCollection queryString = KeysToLower(request.UriTemplateMatch.QueryParameters); string input = (data != null ? new StreamReader(data).ReadToEnd() : String.Empty); if (String.IsNullOrEmpty(input)) { StringBuilder parameters = new StringBuilder(); foreach (string key in queryString.Keys) { if (parameters.Length > 0) { parameters.Append("&"); } parameters.Append(key.ToUpper() + "=" + queryString[key]); } input = parameters.ToString(); } int instanceNr = GetRandom(_serverConfig.Instances.Length /* MapServerConfig.ServerCount*/); MapServerConfig.ServerConfig.InstanceConfig config = _serverConfig.Instances[instanceNr]; InstanceConnection conn = new InstanceConnection("localhost:" + config.Port); string onlineResource = _serverConfig.OnlineResource + "/MapRequest/" + interpreter + "/" + name; IServiceRequestInterpreter requestInterpreter = GetInterpreter(interpreter); string ret = conn.Send(onlineResource, name, input, PlugInManager.PlugInID(requestInterpreter).ToString(), user, pwd, input.Contains("tile:render") ? 3600 : 0); //Console.WriteLine("Finished map Request: " + (DateTime.Now - td).TotalMilliseconds + "ms (" + name + ")"); if (ret.StartsWith("image:")) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "image/png"; ret = ret.Substring(6, ret.Length - 6); return(WriteFile(ret)); } if (ret.StartsWith("{")) { try { var mapServerResponse = gView.Framework.system.MapServerResponse.FromString(ret); OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = mapServerResponse.ContentType; if (mapServerResponse.Expires != null) { AppendEtag((DateTime)mapServerResponse.Expires); } return(WriteBytes(mapServerResponse.Data)); } catch { } } return(WriteValue(ret)); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }
public Stream ServiceCapabilities() { try { string user, pwd; var request = Request(out user, out pwd); NameValueCollection queryString = request.UriTemplateMatch.QueryParameters; string serviceName = queryString["service"]; if (String.IsNullOrEmpty(serviceName)) { return(WriteException("mandatory parameter service missing!")); } string html = LoadHtml("TaskerServiceCapabilities.htm "); #region Capabilities StringBuilder sb = new StringBuilder(); foreach (string key in _interpreters.Keys) { Guid guid; if (Guid.TryParse(key, out guid)) { continue; } IServiceRequestInterpreter si = _interpreters[key]; if (String.IsNullOrEmpty(si.IntentityName)) { continue; } string server = _serverConfig.OnlineResource; string onlineResource = server + "/MapRequest/" + si.IntentityName + "/" + serviceName + "?"; sb.Append("<div class='listbox'><span style='font-weight:bold'>" + si.IntentityName.ToUpper() + "</span>"); InterpreterCapabilities caps = si.Capabilities; if (caps != null && caps.Capabilities != null) { sb.Append("<table width=100%>"); sb.Append("<tr>"); sb.Append("<td><div class='itembox' width=100% style='font-weight:bold'>Version</div></td>"); sb.Append("<td><div class='itembox' width=100% style='font-weight:bold'>Request</div></td>"); sb.Append("<td><div class='itembox' width=100% style='font-weight:bold'>Method</div></td>"); sb.Append("<td><div class='itembox' width=100% style='font-weight:bold'>Example</div></td>"); sb.Append("<td></tr>"); foreach (InterpreterCapabilities.Capability cap in caps.Capabilities) { sb.Append("<tr>"); sb.Append("<td><div class='itembox' width=100%>" + cap.Version + "</div></td>"); sb.Append("<td><div class='itembox' width=100%>" + cap.Name + "</div></td>"); sb.Append("<td><div class='itembox' width=100%>" + cap.Method.ToString() + "</div></td>"); sb.Append("<td><div class='itembox' width=100%>"); if (cap is InterpreterCapabilities.LinkCapability) { string txt = ((InterpreterCapabilities.LinkCapability)cap).RequestLink; txt = txt.Replace("{server}", server).Replace("{onlineresource}", onlineResource).Replace("{service}", serviceName); sb.Append("<a href='" + txt + "'>" + txt + "</a>"); } else if (cap is InterpreterCapabilities.SimpleCapability) { string txt = ((InterpreterCapabilities.SimpleCapability)cap).RequestText; txt = txt.Replace("{server}", server).Replace("{onlineresource}", onlineResource).Replace("{service}", serviceName); sb.Append(txt); } sb.Append("</div></td>"); sb.Append("<tr>"); } } sb.Append("</table>"); sb.Append("</div>"); } html = html.Replace("[CAPABILITIES]", sb.ToString()); #endregion html = html.Replace("[SERVICE]", serviceName); return(HtmlStream(html)); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }
async public Task <IActionResult> MapRequest(string guid, string name, string folder) { try { if (IfMatch()) { return(NotModified()); } #region Security Identity identity = Identity.FromFormattedString(_loginMananger.GetAuthToken(this.Request).Username); #endregion if (!String.IsNullOrWhiteSpace(folder)) { name = folder + "/" + name; } //DateTime td = DateTime.Now; //Console.WriteLine("Start Map Request " + td.ToLongTimeString() + "." + td.Millisecond + " (" + name + ")"); //System.Threading.Thread.Sleep(10000); //string user, pwd; //var request = Request(out user, out pwd); #region Request string input = await GetBody(); if (String.IsNullOrEmpty(input)) { input = this.Request.QueryString.ToString(); } if (input.StartsWith("?")) { input = input.Substring(1); } ServiceRequest serviceRequest = new ServiceRequest(name.ServiceName(), name.FolderName(), input) { OnlineResource = _mapServiceManager.Options.OnlineResource + "/MapRequest/" + guid + "/" + name, OutputUrl = _mapServiceManager.Options.OutputUrl, Identity = identity }; #endregion IServiceRequestInterpreter interpreter = _mapServiceManager.GetInterpreter(new Guid(guid)); #region Queue & Wait IServiceRequestContext context = await ServiceRequestContext.TryCreate( _mapServiceManager.Instance, interpreter, serviceRequest); await _mapServiceManager.TaskQueue.AwaitRequest(interpreter.Request, context); #endregion string ret = serviceRequest.ResponseAsString; return(Result(ret, "text/xml")); } catch (MapServerException mse) { return(WriteError(mse.Message)); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }
public string ServiceRequest2(string OnlineResource, string service, string request, string InterpreterGUID, string usr, string pwd) { //string clientAddress = CallContext.GetData("ClientAddress").ToString(); try { #if (DEBUG) Logger.LogDebug("Start SendRequest"); #endif Identity id = Identity.FromFormattedString(usr); id.HashedPassword = pwd; if (IMS.acl != null && !IMS.acl.HasAccess(id, pwd, service)) { throw new UnauthorizedAccessException(); //return "ERROR: Not Authorized!"; } if (service == "catalog" && IMS.acl != null) { IMS.acl.ReloadXmlDocument(); } if (service == "catalog" && request == "get_used_servers") { StringBuilder sb = new StringBuilder(); sb.Append("<servers>"); foreach (DataRow server in MapServer.GDIServers.Rows) { sb.Append("<server uri='" + (string)server["Server"] + "' port='" + (int)server["Port"] + "' />"); } sb.Append("</servers>"); return(sb.ToString()); } if (service == "catalog" && request == "get_instance_info") { StringBuilder sb = new StringBuilder(); MapServer mapServer = IMS.mapServer; sb.Append("<instance_info>"); if (mapServer != null) { sb.Append("<output url='" + mapServer.OutputUrl + "' />"); } sb.Append("</instance_info>"); return(sb.ToString()); } Guid guid = new Guid(InterpreterGUID); IServiceRequestInterpreter interperter = null; foreach (IServiceRequestInterpreter i in IMS._interpreters) { if (PlugInManager.PlugInID(i) == guid) { interperter = i; break; } } if (interperter == null) { return("FATAL ERROR: Unknown request interpreger..."); } // User berechtigungen überprüfen ServiceRequest serviceRequest = new ServiceRequest(service, request); serviceRequest.OnlineResource = OnlineResource; //serviceRequest.UserName = usr; serviceRequest.Identity = id; IServiceRequestContext context = new ServiceRequestContext( IMS.mapServer, interperter, serviceRequest); //ManualResetEvent resetEvent = new ManualResetEvent(false); //IMS.threadQueue.AddQueuedThread(interperter.Request, context, resetEvent); //resetEvent.WaitOne(); IMS.threadQueue.AddQueuedThreadSync(interperter.Request, context); return(serviceRequest.Response); #if (DEBUG) Logger.LogDebug("SendRequest Finished"); #endif } catch (Exception ex) { //System.Diagnostics.Process.GetCurrentProcess().Kill(); return("FATAL ERROR: " + ex.Message); } }
async public Task <IActionResult> OgcRequest(string id, string service = "") { try { #region Security Identity identity = Identity.FromFormattedString(_loginMananger.GetAuthToken(this.Request).Username); #endregion IServiceRequestInterpreter interpreter = null; switch (service.ToLower().Split(',')[0]) { case "wms": interpreter = _mapServiceMananger.GetInterpreter(typeof(WMSRequest)); break; case "wfs": interpreter = _mapServiceMananger.GetInterpreter(typeof(WFSRequest)); break; case "wmts": interpreter = _mapServiceMananger.GetInterpreter(typeof(WMTSRequest)); break; default: throw new Exception("Missing or unknow service: " + service); } #region Request string requestString = Request.QueryString.ToString(); if (Request.Method.ToLower() == "post" && Request.Body.CanRead) { string body = await GetBody(); if (!String.IsNullOrWhiteSpace(body)) { requestString = body; } } while (requestString.StartsWith("?")) { requestString = requestString.Substring(1); } ServiceRequest serviceRequest = new ServiceRequest(id.ServiceName(), id.FolderName(), requestString) { OnlineResource = _mapServiceMananger.Options.OnlineResource + "/ogc/" + id, OutputUrl = _mapServiceMananger.Options.OutputUrl, Identity = identity }; #endregion IServiceRequestContext context = await ServiceRequestContext.TryCreate( _mapServiceMananger.Instance, interpreter, serviceRequest); await _mapServiceMananger.TaskQueue.AwaitRequest(interpreter.Request, context); var response = serviceRequest.Response; if (response is byte[]) { return(Result((byte[])response, serviceRequest.ResponseContentType)); } return(Result(response?.ToString() ?? String.Empty, serviceRequest.ResponseContentType)); } catch (Exception ex) { // ToDo: OgcXmlExcpetion return(Result(ex.Message, "text/plain")); } }
async static public Task <IServiceRequestContext> TryCreate(IMapServer mapServer, IServiceRequestInterpreter interpreter, ServiceRequest request, bool checkSecurity = true) { var context = new ServiceRequestContext(mapServer, interpreter, request); if (checkSecurity == true) { var mapService = mapServer?.GetMapService(request?.Service, request?.Folder); if (mapService == null) { throw new MapServerException("Unknown service"); } await mapService.CheckAccess(context); } return(context); }
public IActionResult MapRequest(string guid, string id) { try { if (IfMatch()) { return(NotModified()); } //DateTime td = DateTime.Now; //Console.WriteLine("Start Map Request " + td.ToLongTimeString() + "." + td.Millisecond + " (" + name + ")"); //System.Threading.Thread.Sleep(10000); //string user, pwd; //var request = Request(out user, out pwd); #region Request string input = String.Empty; if (Request.Body.CanRead) { MemoryStream ms = new MemoryStream(); byte[] bodyData = new byte[1024]; int bytesRead; while ((bytesRead = Request.Body.Read(bodyData, 0, bodyData.Length)) > 0) { ms.Write(bodyData, 0, bytesRead); } input = Encoding.UTF8.GetString(ms.ToArray()); } if (String.IsNullOrEmpty(input)) { input = this.Request.QueryString.ToString(); } if (input.StartsWith("?")) { input = input.Substring(1); } ServiceRequest serviceRequest = new ServiceRequest(id, input); serviceRequest.OnlineResource = InternetMapServer.OnlineResource + "/MapRequest/" + guid + "/" + id; #endregion IServiceRequestInterpreter interpreter = InternetMapServer.GetInterpreter(new Guid(guid)); #region Security Identity identity = Identity.FromFormattedString(String.Empty); identity.HashedPassword = String.Empty; serviceRequest.Identity = identity; #endregion #region Queue & Wait IServiceRequestContext context = new ServiceRequestContext( InternetMapServer.Instance, interpreter, serviceRequest); InternetMapServer.ThreadQueue.AddQueuedThreadSync(interpreter.Request, context); #endregion string ret = serviceRequest.Response; return(Result(ret, "text/xml")); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }