public IEnumerator Exceution(WebAPI webApi) { string sendJson = WebAPIJsonParse.CreateJsonData(this.requestList); WWWResponse response = new WWWResponse(); yield return(webApi.StartCoroutine(GameWebAPI.Instance().StartAPIRequest("API List", sendJson, response))); try { string responseJson = GameWebAPI.Instance().GetResponseJson(response); try { Dictionary <string, string> responseList = WebAPIJsonParse.GetResponseList(this.requestList, responseJson); for (int i = 0; i < this.requestList.Count; i++) { if (responseList.ContainsKey(this.requestList[i].apiId)) { this.requestList[i].ToObject(responseList[this.requestList[i].apiId], false); } } } catch (JsonException ex) { throw new WebAPIException(WWWResponse.LocalErrorStatus.LOCAL_ERROR_JSONPARSE, ex.Message); } } catch (WebAPIException ex2) { throw ex2; } yield break; }
public string GetResponseJson(WWWResponse request_result) { if (request_result.errorStatus != WWWResponse.LocalErrorStatus.NONE) { throw new WebAPIException(request_result.errorStatus, request_result.errorText); } try { this.DEBUG_LOG("==================================== API RESPONCE JSON = " + request_result.responseJson); int @int = WebAPIJsonParse.GetInt(request_result.responseJson, "venus_status"); if (@int == -1) { throw new WebAPIException(WWWResponse.LocalErrorStatus.LOCAL_ERROR_JSONPARSE, "Not Found venus_status"); } switch (@int) { case 1: return(request_result.responseJson); case 2: case 6: case 11: throw new WebAPIException(this.GetResponseError(request_result.responseJson)); } throw new WebAPIException(this.GetResponseError(request_result.responseJson)); } catch (JsonException ex) { throw new WebAPIException(WWWResponse.LocalErrorStatus.LOCAL_ERROR_JSONPARSE, ex.Message); } string result; return(result); }
public IEnumerator StartAPIRequest(string apiId, string json, WWWResponse response) { this.DEBUG_LOG("Request[" + apiId + "] : " + json); yield return(base.StartCoroutine(this.WWWRequest(WebAPIPlatformValue.GetHttpActiveController(), "POST", this.GetDisableVersionCheckCode(apiId), json.Trim(), response))); yield break; }
private static CacheEntry CreateMetaDataCacheEntry(string url, WWWResponse response) { string responseHeader = response.ResponseHeaders["LAST-MODIFIED"]; string entityTag = response.ResponseHeaders["ETAG"]; var cacheEntry = new CacheEntry { EntityTag = entityTag, Modified = responseHeader, Url = url, LastFetched = DateTime.UtcNow }; return(cacheEntry); }
public override WWWResponse ProcessRequest(WWWRequest request) { //GameManager.Instance.adminTools.IsWhiteListEnabled WWWResponse response = null; if (!request.Form.ContainsKey("password") || request.Form["password"] == "") { string loginTemplate = WWW._templates ["loginform"]; if (GameManager.Instance.adminTools.IsWhiteListEnabled()) { string steamButton = WWW._templates["steambutton"]; string hostAndPort = "http://" + request._request.Url.Host + ":" + request._request.Url.Port; string steamLoginUrl = EndPoint_SteamLogin.GetSteamLoginUrl(hostAndPort, hostAndPort + "/steam"); steamButton = steamButton.Replace("{login_url}", steamLoginUrl); loginTemplate = loginTemplate.Replace("{steam_button}", steamButton); loginTemplate = loginTemplate.Replace("{steam_button_title}", "Login with Steam"); } else { loginTemplate = loginTemplate.Replace("{steam_button}", ""); } response = new WWWResponse(loginTemplate); } else { string pw = request.Form["password"]; if (pw == GamePrefs.GetString(EnumGamePrefs.ServerPassword)) { request.User.SetType("user"); response = new WWWResponse("/", 302); } else { if (pw == GamePrefs.GetString(EnumGamePrefs.ControlPanelPassword)) { request.User.SetType("admin"); response = new WWWResponse("/", 302); } else { response = new WWWResponse("/login/?err=InvalidPassword", 302); } } } return(response); }
private void UpdateCache(string url, WWWResponse response) { var added = assetCache.TryAddOrUpdate(GetAssetName(url), response.Bytes); if (added) { AddMetaDataCacheEntry(url, response); } else { Debug.LogWarningFormat("Failed to cache: {0}", url); } }
private void DownloadAsyncResponse(WWWResponse response, IWWWRequest wwwRequest, string originalUrl, Action <WWWResponse> callback) { pendingDownloadRequests.Remove(response.Request); var redirectUrl = GetRedirectUrl(response); if (redirectUrl != null) { DownloadAsync(wwwRequest, originalUrl, redirectUrl, callback); } else { callback(response); } }
private void AddMetaDataCacheEntry(string url, WWWResponse response) { if (!HasValidators(response)) { Debug.LogWarningFormat("ETag and/or Last-Modified missing. Cannot cache url {0}, keys {1}", url, string.Join("\n", response.ResponseHeaders.Keys.ToArray())); } else { var entry = CreateMetaDataCacheEntry(url, response); if (!metaDataCache.TryAddOrUpdate(GetAssetName(url), entry)) { Debug.LogWarningFormat("Failed to add cache metadata for: {0}", url); } } }
public override WWWResponse ProcessRequest(WWWRequest request) { //load the html and send the response WWWResponse response; if (request.User.UserType != "public") { response = new WWWResponse("Welcome, " + request.User.UserType); } else { response = new WWWResponse("Not Allowed"); } return(response); }
public IEnumerator Exceution(WebAPI webApi, WebAPI.RequestStatus requestStatus) { this.param.requestStatus = (int)requestStatus; string sendJson = WebAPIJsonParse.CreateJsonData(this.apiId, this.param); WWWResponse response = new WWWResponse(); yield return webApi.StartCoroutine(webApi.StartAPIRequest(this.apiId, sendJson, response)); try { string responseJson = webApi.GetResponseJson(response); this.ToObject(responseJson, true); } catch (WebAPIException ex) { if (ex != null) { ex.apiId = this.apiId; } throw ex; } yield break; }
public override WWWResponse ProcessRequest(WWWRequest request) { string html = Servers.HTTP.WWW._templates["onlineplayers"]; string itemHtml = Servers.HTTP.WWW._templates["onlineplayersitem"]; string itemList = ""; foreach (EntityPlayer player in PlayerUtils.GetOnlinePlayers()) { string sitem = itemHtml; string steamId = PlayerUtils.GetSteamID(player.entityId.ToString()); sitem = sitem.Replace("{steam_id}", steamId); sitem = sitem.Replace("{display_name}", PlayerUtils.GetDisplayName(player.entityId.ToString())); string playerGroupName = "guest"; string playerAdminLevel = "1000"; if (SDTM.API.Permissions.Users.ContainsKey(steamId)) { playerGroupName = SDTM.API.Permissions.Users [steamId].Group; } playerAdminLevel = GameManager.Instance.adminTools.GetAdminToolsClientInfo(steamId).PermissionLevel.ToString(); sitem = sitem.Replace("{experm_group}", playerGroupName); sitem = sitem.Replace("{admin_level}", playerAdminLevel); string itemTools = ""; itemTools += "<a href=\"/settings/experm/user?user="******"\" title=\"Security\"><i class=\"fa fa-shield\" aria-hidden=\"true\"></i></a>"; //itemTools+=" <a href=\"/settings/player/inventory?player="+steamId+"\" title=\"View Player Inventory\"><i class=\"fa fa-suitcase\" aria-hidden=\"true\"></i></a>"; //itemTools+=" <a href=\"/settings/player/kick?player="+steamId+"\" title=\"Kick/Ban User\"><i class=\"fa fa-ban\" aria-hidden=\"true\"></i></a>"; sitem = sitem.Replace("{tools}", itemTools); itemList += sitem; } html = html.Replace("{player_list}", itemList); WWWResponse response = new WWWResponse(html); return(response); }
private static string GetRedirectUrl(WWWResponse response) { string status = ""; if (response.ResponseHeaders.TryGetValue("STATUS", out status)) { if (status.Contains("302")) { string location = ""; if (response.ResponseHeaders.TryGetValue("LOCATION", out location)) { return(location); } else { Debug.LogErrorFormat("Requested {0} and got a 302, but no location header", response.Url); } } } return(null); }
private void AuthStart(Action onSuccess, Action <WebAPIException> onFailed) { float timeout = GameWebAPI.Instance().GetTimeout(); NpOAuth.Instance.X_AppVer = WebAPIPlatformValue.GetAppVersion(); NpOAuth.Instance.initURL = WebAPIPlatformValue.GetHttpAddressAuth(); NpOAuth.Instance.counsumerKey = WebAPIPlatformValue.GetCounsumerKey(); NpOAuth.Instance.counsumerSecret = WebAPIPlatformValue.GetCounsumerSecret(); NpOAuth.Instance.TimeOut = timeout; NpOAuth.Instance.type = NpOAuthType.Json; Action <NpOAuthErrData> faildAction = delegate(NpOAuthErrData errData) { if (errData.FailedCode != NpOatuhFailedCodeE.ServerFailed) { onFailed(null); } else { WWWResponse request_result = new WWWResponse { responseJson = errData.VenusRespones_.ResJson, errorText = errData.VenusRespones_.Message, errorStatus = WWWResponse.LocalErrorStatus.NONE }; try { GameWebAPI.Instance().GetResponseJson(request_result); } catch (WebAPIException obj) { onFailed(obj); } } }; NpAes aes = new NpAes(); NpOAuth.Instance.Init(this, onSuccess, faildAction, aes); }
public override WWWResponse ProcessRequest(WWWRequest request) { string steamId = ""; string groupName = ""; string displayName = ""; if (request.Form.Count > 0) { steamId = request.Form ["steam_id"]; } else { if (request._request.QueryString ["user"] != null) { steamId = request._request.QueryString ["user"]; } } if (API.Permissions.Users.ContainsKey(steamId)) { groupName = API.Permissions.Users [steamId].Group; displayName = API.Permissions.Users [steamId].DisplayName; } else { groupName = "guest"; //check the online players foreach (EntityPlayer player in PlayerUtils.GetOnlinePlayers()) { if (steamId == PlayerUtils.GetSteamID(player.entityId.ToString())) { displayName = PlayerUtils.GetDisplayName(player.entityId.ToString()); } } if (displayName == "") { //persistent data? } } if (request.Form.Count > 0) { groupName = request.Form ["experm_group"]; API.Permissions.SetUserGroup(steamId, groupName); API.Permissions.Save(); } string html = Servers.HTTP.WWW._templates["expermusereditor"]; string groupOptions = ""; foreach (string expermGroupName in API.Permissions.Groups.Keys) { groupOptions += "<option value=\"" + expermGroupName + "\""; if (expermGroupName == groupName) { groupOptions += " SELECTED"; } groupOptions += ">" + expermGroupName + "</option>"; } string userPermList = ""; PermissionUser pUser = null; if (API.Permissions.Users.ContainsKey(steamId)) { pUser = API.Permissions.Users [steamId]; } if (pUser != null) { string permissionEntryTemplate = Servers.HTTP.WWW._templates ["expermpermissionentry"]; Dictionary <string, bool> permissions = pUser.Permissions.GetAll(); foreach (KeyValuePair <string, bool> perm in permissions) { string permItem = permissionEntryTemplate.Replace("{node_name}", perm.Key); permItem = permItem.Replace("{allowed}", perm.Value.ToString()); string toolList = "<a href=\"/settings/experm/user/removenode?steam_id=" + steamId + "&node=" + perm.Key + "\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i></a>"; permItem = permItem.Replace("{tools}", toolList); userPermList += permItem; } } html = html.Replace("{steam_id}", steamId); html = html.Replace("{display_name}", displayName); html = html.Replace("{experm_groups_options}", groupOptions); html = html.Replace("{user_permissions}", userPermList); WWWResponse response = new WWWResponse(html); return(response); }
public override WWWResponse ProcessRequest(WWWRequest request) { string groupName = ""; int adminLevel = 1000; PermissionGroup pGroup = null; if (request.Form.Count > 0) { groupName = request.Form ["group_name"]; string adminFormStr = request.Form ["admin_level"]; int.TryParse(adminFormStr, out adminLevel); if (API.Permissions.Groups.ContainsKey(groupName)) { pGroup = API.Permissions.Groups [groupName]; pGroup.AdminLevel = adminLevel; API.Permissions.Save(); } } else { if (request._request.QueryString ["group"] != null) { groupName = request._request.QueryString ["group"]; } } if (API.Permissions.Groups.ContainsKey(groupName)) { pGroup = API.Permissions.Groups [groupName]; adminLevel = pGroup.AdminLevel; } string html = Servers.HTTP.WWW._templates["expermgroupeditor"]; html = html.Replace("{group_name}", groupName); html = html.Replace("{admin_level}", adminLevel.ToString()); string groupPermList = ""; if (pGroup != null) { string permissionEntryTemplate = Servers.HTTP.WWW._templates ["expermpermissionentry"]; Dictionary <string, bool> permissions = pGroup.Permissions.GetAll(); foreach (KeyValuePair <string, bool> perm in permissions) { string permItem = permissionEntryTemplate.Replace("{node_name}", perm.Key); permItem = permItem.Replace("{allowed}", perm.Value.ToString()); string toolList = "<a href=\"/settings/experm/group/removenode?group=" + groupName + "&node=" + perm.Key + "\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i></a>"; permItem = permItem.Replace("{tools}", toolList); groupPermList += permItem; } } html = html.Replace("{group_permissions}", groupPermList); WWWResponse response = new WWWResponse(html); return(response); }
public override WWWResponse ProcessRequest(WWWRequest request) { if (request.Form.Count > 0) { bool wasChanged = false; if (request.Form.ContainsKey("tickrate")) { int passedRate = 0; if (int.TryParse(request.Form["tickrate"], out passedRate)) { if (API.Instance.tickRate != passedRate) { API.Instance.tickRate = passedRate; wasChanged = true; } } } if (request.Form.ContainsKey("overridegamepref")) { if (API.OverrideGamePrefs == false) { API.OverrideGamePrefs = true; wasChanged = true; } //see if anything else has been changed foreach (string fieldName in request.Form.Keys) { if (fieldName == "tickrate" || fieldName == "overridegamepref") { continue; } switch (fieldName) { case "world_type": API.Instance.SetConfig("worldtype", request.Form [fieldName], false, true); wasChanged = true; break; case "world_name": API.Instance.SetConfig("worldname", request.Form [fieldName], false, true); wasChanged = true; break; } } } else { if (API.OverrideGamePrefs == true) { API.OverrideGamePrefs = false; wasChanged = true; } } if (request.Form.ContainsKey("webconsole_enabled")) { API.WebConsoleEnabled = true; API.WebConsolePort = request.Form ["webconsole_port"]; wasChanged = true; } else { API.WebConsoleEnabled = false; wasChanged = true; } if (request.Form.ContainsKey("chatcommands_enabled")) { API.ChatCommandsEnabled = true; wasChanged = true; } else { API.ChatCommandsEnabled = false; wasChanged = true; } if (wasChanged) { API.Instance.SaveConfig(); } } string html = Servers.HTTP.WWW._templates["settingsform"]; html = html.Replace("{tickrate}", API.Instance.tickRate.ToString()); html = html.Replace("{chatcommands_enabled}", API.ChatCommandsEnabled.ToString().ToLower()); html = html.Replace("{overridegameprefs}", API.OverrideGamePrefs.ToString().ToLower()); html = html.Replace("{world_type}", GamePrefs.GetString(EnumGamePrefs.GameWorld).ToLower()); html = html.Replace("{world_name}", GamePrefs.GetString(EnumGamePrefs.GameName)); html = html.Replace("{webconsole_enabled}", API.WebConsoleEnabled.ToString().ToLower()); html = html.Replace("{webconsole_port}", API.WebConsolePort); WWWResponse response = new WWWResponse(html); return(response); }
private void HandleDownloadAssetResponse(string url, Action <AssetBundle> onAssetLoaded, Action <Exception> onError, WWWResponse response) { if (!String.IsNullOrEmpty(response.Error)) { Debug.LogWarningFormat("Requesting asset '{0}' failed. Url: {1}. Error: {2}", GetAssetName(url), url, response.Error); onError(new ApplicationException(response.Error)); } else if (response.ResponseHeaders.ContainsKey("STATUS") && response.ResponseHeaders["STATUS"].Contains("304")) { AssetBundle assetBundle; if (assetCache.TryGet(GetAssetName(url), out assetBundle)) { onAssetLoaded(assetBundle); } else { Debug.LogErrorFormat("Failed to load asset '{0}' from cache. Corrupted cache. Please delete the cache folder: '{1}'.", GetAssetName(url), cachePath); onError(new ApplicationException("Cache likely corrupted.")); } } else if (response.AssetBundle != null) { UpdateCache(url, response); onAssetLoaded(response.AssetBundle); } else { string responseHeadersString = ""; foreach (var responseHeader in response.ResponseHeaders) { responseHeadersString += " [" + responseHeader.Key + ": " + responseHeader.Value + "]"; } Debug.LogWarningFormat("Unhandled response for {0}. Downloaded {1} bytes, got the following response headers: {2}", url, response.BytesDownloaded, responseHeadersString); onError(new ApplicationException("Unhandled response.")); } }
private IEnumerator WWWRequest(string url, string method, WebAPI.DisableVersionCheckCode disableVersionCheck, string json, WWWResponse response) { Dictionary <string, object> parameters = new Dictionary <string, object>(); Dictionary <string, string> headers = new Dictionary <string, string>(); WWWForm form = new WWWForm(); int code = (int)disableVersionCheck; if (string.IsNullOrEmpty(this.masterDataVersion)) { code = 1; } else { parameters["dataVersion"] = this.masterDataVersion; form.AddField("dataVersion", this.masterDataVersion); } parameters["activityList"] = json; parameters["disabledVC"] = code.ToString(); parameters["appVersion"] = WebAPIPlatformValue.GetAppVersion(); parameters["assetVersion"] = AssetDataMng.assetVersion.ToString(); headers = NpOAuth.Instance.RequestHeaderDic(method, url, parameters); headers["X-AppVer"] = WebAPIPlatformValue.GetAppVersion(); headers["x-puid"] = PlatformUserID.GetId(); form.AddField("activityList", json); form.AddField("disabledVC", code); form.AddField("appVersion", WebAPIPlatformValue.GetAppVersion()); form.AddField("assetVersion", AssetDataMng.assetVersion.ToString()); WWWHelper www = new WWWHelper(url, form.data, headers, this.timeout); IEnumerator request = www.StartRequest(delegate(string responseText, string errorText, WWWHelper.TimeOut isTimeout) { response.responseJson = responseText; response.errorText = errorText; response.errorStatus = ((isTimeout != WWWHelper.TimeOut.YES) ? ((!string.IsNullOrEmpty(errorText)) ? WWWResponse.LocalErrorStatus.LOCAL_ERROR_WWW : WWWResponse.LocalErrorStatus.NONE) : WWWResponse.LocalErrorStatus.LOCAL_ERROR_TIMEOUT); }); yield return(base.StartCoroutine(request)); yield break; }
public override WWWResponse ProcessRequest(WWWRequest request) { if (request.Form.Count > 0) { bool wasChanged = false; if (request.Form.ContainsKey("tickrate")) { int passedRate = 0; if (int.TryParse(request.Form["tickrate"], out passedRate)) { if (API.Instance.tickRate != passedRate) { API.Instance.tickRate = passedRate; wasChanged = true; } } } if (request.Form.ContainsKey("overridegamepref")) { if (API.OverrideGamePrefs == false) { API.OverrideGamePrefs = true; wasChanged = true; } //see if anything else has been changed foreach (string fieldName in request.Form.Keys) { if (fieldName == "tickrate" || fieldName == "overridegamepref") { continue; } switch (fieldName) { case "world_type": API.Instance.SetConfig("worldtype", request.Form [fieldName], false, true); wasChanged = true; break; case "world_name": API.Instance.SetConfig("worldname", request.Form [fieldName], false, true); wasChanged = true; break; } } } else { if (API.OverrideGamePrefs == true) { API.OverrideGamePrefs = false; wasChanged = true; } } if (wasChanged) { API.Instance.SaveConfig(); } } string groupListTemplate = Servers.HTTP.WWW._templates["expermgrouplist"]; string groupListItemTemplate = Servers.HTTP.WWW._templates["expermgrouplistitem"]; string groupInfoString = ""; foreach (PermissionGroup group in API.Permissions.Groups.Values) { if (group.Name != "_super") { string groupListItem = groupListItemTemplate; groupListItem = groupListItem.Replace("{group_name}", group.Name); if (group.Name != "public") { groupListItem = groupListItem.Replace("{admin_level}", group.AdminLevel.ToString()); string itemTools = ""; itemTools += "<a href=\"/settings/experm/group?group=" + group.Name + "\" title=\"Security\"><i class=\"fa fa-shield\" aria-hidden=\"true\"></i></a>"; groupListItem = groupListItem.Replace("{tools}", itemTools); } else { groupListItem = groupListItem.Replace("{admin_level}", "Web Only"); groupListItem = groupListItem.Replace("{tools}", ""); } groupInfoString += groupListItem; } } groupListTemplate = groupListTemplate.Replace("{group_list_items}", groupInfoString); string userListTemplate = Servers.HTTP.WWW._templates["expermuserlist"]; string userListItemTemplate = Servers.HTTP.WWW._templates["expermuserlistitem"]; string userInfoString = ""; foreach (PermissionUser user in API.Permissions.Users.Values) { string userListItem = userListItemTemplate; userListItem = userListItem.Replace("{steam_id}", user.SteamId); userListItem = userListItem.Replace("{display_name}", user.DisplayName); userListItem = userListItem.Replace("{group_name}", user.Group); userListItem = userListItem.Replace("{admin_level}", GameManager.Instance.adminTools.GetAdminToolsClientInfo(user.SteamId).PermissionLevel.ToString()); string itemTools = ""; itemTools += "<a href=\"/settings/experm/user?user="******"\" title=\"Security\"><i class=\"fa fa-shield\" aria-hidden=\"true\"></i></a>"; //itemTools+=" <a href=\"/settings/player/inventory?player="+user.SteamId+"\" title=\"View Player Inventory\"><i class=\"fa fa-suitcase\" aria-hidden=\"true\"></i></a>"; //itemTools+=" <a href=\"/settings/player/kick?player="+user.SteamId+"\" title=\"Kick/Ban User\"><i class=\"fa fa-ban\" aria-hidden=\"true\"></i></a>"; userListItem = userListItem.Replace("{tools}", itemTools); userInfoString += userListItem; } userListTemplate = userListTemplate.Replace("{user_list_items}", userInfoString); string nodeListTemplate = Servers.HTTP.WWW._templates["expermnodelist"]; string nodeListItemTemplate = Servers.HTTP.WWW._templates["expermnodelistitem"]; string nodeInfoString = ""; foreach (string node in API.Permissions.PermissionNodes) { string nodeListItem = nodeListItemTemplate; nodeListItem = nodeListItem.Replace("{node_name}", node); nodeInfoString += nodeListItem; } nodeListTemplate = nodeListTemplate.Replace("{node_list_items}", nodeInfoString); string html = Servers.HTTP.WWW._templates["expermsettingsmain"]; html = html.Replace("{experm_groups_list}", groupListTemplate); html = html.Replace("{experm_users_list}", userListTemplate); html = html.Replace("{experm_nodes_list}", nodeListTemplate); WWWResponse response = new WWWResponse(html); return(response); }
private static bool HasValidators(WWWResponse response) { return(response.ResponseHeaders.ContainsKey("LAST-MODIFIED") && response.ResponseHeaders.ContainsKey("ETAG")); }
public void Run() { ThreadPool.QueueUserWorkItem((o) => { try { while (_listener.IsListening) { ThreadPool.QueueUserWorkItem((c) => { //bool redirected = false; var ctx = c as HttpListenerContext; try { if (ctx.Request.Url.LocalPath == "/favicon.ico") { ctx.Response.Close(); return; } string localPath = ctx.Request.Url.LocalPath; string fileName = Path.GetFileName(localPath); if (fileName != "" && fileName.IndexOf(".") > 0) { localPath = localPath.Replace(Path.GetFileName(localPath), ""); } else { if (localPath.Substring(localPath.Length - 1, 1) != "/") { localPath += "/"; } } WWWRequest request = new WWWRequest(ctx.Request); WWWUser requestUser = null; string sessionId = ""; if (ctx.Request.Cookies["sessionid"] != null) { sessionId = ctx.Request.Cookies["sessionid"].Value; } if (sessionId != "" && _sessions.ContainsKey(sessionId)) { requestUser = _sessions[sessionId]; } else { requestUser = new WWWUser(); } if (localPath == "/logout/") { _sessions.Remove(sessionId); ctx.Response.Redirect("/login/"); ctx.Response.OutputStream.Close(); return; } ctx.Response.Cookies.Add(new Cookie("sessionid", requestUser.SessionId + "; path=/")); if (!Servers.HTTP.EndPointsList._endPoints.ContainsKey(localPath)) { if (Path.GetExtension(localPath) != "") { localPath = Path.GetDirectoryName(localPath); } } if (Servers.HTTP.EndPointsList._endPoints.ContainsKey(localPath)) { WWWEndpointProvider endpointProvider = (WWWEndpointProvider)Servers.HTTP.EndPointsList._endPoints[localPath]; bool allowed = false; if (requestUser.UserType == "admin") { allowed = true; } else { if (endpointProvider.acl != null) { foreach (string acl in endpointProvider.acl) { if (acl == requestUser.UserType || acl == "public") { allowed = true; break; } } } } if (!allowed) { ctx.Response.Redirect("/login/"); ctx.Response.OutputStream.Close(); return; } else { string postData = GetRequestPostData(ctx.Request); Dictionary <string, string> FormValues = new Dictionary <string, string>(); if (postData != string.Empty && postData.Length > 0) { FormValues = GetFormParameters(postData); } request.Form = FormValues; request.Cookies = ctx.Request.Cookies; request.User = requestUser; WWWResponse userResponse = endpointProvider.ProcessRequest(request); //update session user _sessions[request.User.SessionId] = request.User; foreach (Cookie ck in userResponse.Cookies) { if (ck.Name != "sessionid") { ctx.Response.Cookies.Add(ck); } } if (userResponse.StatusCode == 302) { ctx.Response.Redirect(userResponse.Content); //redirected=true; } else { if (userResponse.StatusCode == -1) //file download { using (FileStream fs = File.OpenRead(userResponse.Content)) { string filename = Path.GetFileName(userResponse.Content); //response is HttpListenerContext.Response... ctx.Response.ContentLength64 = fs.Length; ctx.Response.SendChunked = false; ctx.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet; ctx.Response.AddHeader("Content-disposition", "attachment; filename=" + filename); byte[] buffer = new byte[64 * 1024]; int read; using (BinaryWriter bw = new BinaryWriter(ctx.Response.OutputStream)) { while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, read); bw.Flush(); //seems to have no effect } bw.Close(); } ctx.Response.StatusCode = (int)HttpStatusCode.OK; ctx.Response.StatusDescription = "OK"; ctx.Response.OutputStream.Close(); return; } } else { if (userResponse.StatusCode == -2) // XML Output, no template { byte[] buf = Encoding.UTF8.GetBytes(userResponse.Content); ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/xml"; ctx.Response.ContentLength64 = buf.Length; ctx.Response.OutputStream.Write(buf, 0, buf.Length); } else { if (userResponse.StatusCode == -4) //JSON output, no template { byte[] buf = Encoding.UTF8.GetBytes(userResponse.Content); ctx.Response.StatusCode = 200; ctx.Response.ContentType = "application/json"; ctx.Response.ContentLength64 = buf.Length; ctx.Response.OutputStream.Write(buf, 0, buf.Length); } else { if (userResponse.StatusCode == -5) { using (FileStream fs = File.OpenRead(userResponse.Content)) { string filename = Path.GetFileName(userResponse.Content); //response is HttpListenerContext.Response... ctx.Response.ContentLength64 = fs.Length; ctx.Response.SendChunked = false; ctx.Response.ContentType = "image/png"; ctx.Response.AddHeader("Content-disposition", "attachment; filename=" + filename); byte[] buffer = new byte[64 * 1024]; int read; using (BinaryWriter bw = new BinaryWriter(ctx.Response.OutputStream)) { while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, read); bw.Flush(); //seems to have no effect } bw.Close(); } ctx.Response.StatusCode = (int)HttpStatusCode.OK; ctx.Response.StatusDescription = "OK"; ctx.Response.OutputStream.Close(); return; } } else { string menuString = BuildMenu(request.User, EndPointsList._menu); string rstr = "TEMPLATE NOT FOUND: " + ctx.Request.Url.LocalPath; string[] parts = ctx.Request.Url.LocalPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0 || parts[0] != "settings") { rstr = _templates["main"]; } else { rstr = _templates["settingsmain"]; string settingsMenuStr = BuildSettingsMenu(request.User, EndPointsList._adminMenu); rstr = rstr.Replace("{settings_menu}", settingsMenuStr); } rstr = rstr.Replace("{content}", userResponse.Content).Replace("{title}", userResponse.Title).Replace("{menu}", menuString); byte[] buf = Encoding.UTF8.GetBytes(rstr); ctx.Response.StatusCode = userResponse.StatusCode; ctx.Response.ContentType = "text/html"; ctx.Response.ContentLength64 = buf.Length; ctx.Response.OutputStream.Write(buf, 0, buf.Length); } } } } } } } else { string rstr = "Page not Found"; byte[] buf = Encoding.UTF8.GetBytes(rstr); ctx.Response.StatusCode = 404; ctx.Response.ContentLength64 = buf.Length; ctx.Response.OutputStream.Write(buf, 0, buf.Length); } } catch (Exception err) { Log.Out(err.Message); } // suppress any exceptions finally { // always close the stream ctx.Response.OutputStream.Close(); } }, _listener.GetContext()); } } catch { } // suppress any exceptions }); }