From 54ccca1e2cb8af5d0fdc420f64574a7d7b13c94b Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Tue, 31 Mar 2009 02:00:33 +0000 Subject: Update svn properties, add copyright header, formatting cleanup. --- .../Rest/Inventory/RestHandler.cs | 2 +- .../Framework/Communications/Cache/AssetCache.cs | 4 +- .../Framework/Communications/IAuthentication.cs | 51 +- .../Communications/Services/GridInfoService.cs | 344 +- .../Communications/Services/LoginResponse.cs | 1624 +-- .../Communications/Services/LoginService.cs | 2186 +-- .../UserServer.Modules/UserLoginAuthService.cs | 448 +- .../Avatar/InstantMessage/OfflineMessageModule.cs | 2 +- .../Hypergrid/HGStandaloneInventoryModule.cs | 330 +- .../Hypergrid/HGStandaloneLoginModule.cs | 506 +- .../DynamicTexture/DynamicTextureModule.cs | 64 +- .../Shared/Api/Implementation/LSL_Api.cs | 56 +- .../Shared/Api/Implementation/Plugins/Timer.cs | 1 - bin/HttpServer_OpenSim.xml | 14038 +++++++++---------- bin/OpenSim.ini.example | 40 +- 15 files changed, 9858 insertions(+), 9838 deletions(-) diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/RestHandler.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/RestHandler.cs index 5ff9da3..180d6f4 100644 --- a/OpenSim/ApplicationPlugins/Rest/Inventory/RestHandler.cs +++ b/OpenSim/ApplicationPlugins/Rest/Inventory/RestHandler.cs @@ -227,7 +227,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory // them easy to reach from anywhere in the assembly. Rest.main = openSim; - if(Rest.main == null) + if (Rest.main == null) throw new Exception("OpenSim base pointer is null"); Rest.Plugin = this; diff --git a/OpenSim/Framework/Communications/Cache/AssetCache.cs b/OpenSim/Framework/Communications/Cache/AssetCache.cs index d79645e..73aa6ba 100644 --- a/OpenSim/Framework/Communications/Cache/AssetCache.cs +++ b/OpenSim/Framework/Communications/Cache/AssetCache.cs @@ -503,7 +503,7 @@ namespace OpenSim.Framework.Communications.Cache req.Params = transferRequest.TransferInfo.Params; req.AssetInf = new AssetInfo(asset); req.NumPackets = CalculateNumPackets(asset.Data); - lock(AssetRequests) AssetRequests.Add(req); + lock (AssetRequests) AssetRequests.Add(req); } /// @@ -526,7 +526,7 @@ namespace OpenSim.Framework.Communications.Cache for (int i = 0; i < num; i++) { - lock(AssetRequests) + lock (AssetRequests) { req = AssetRequests[0]; AssetRequests.RemoveAt(0); diff --git a/OpenSim/Framework/Communications/IAuthentication.cs b/OpenSim/Framework/Communications/IAuthentication.cs index 5d6d5f2..0f62569 100644 --- a/OpenSim/Framework/Communications/IAuthentication.cs +++ b/OpenSim/Framework/Communications/IAuthentication.cs @@ -1,13 +1,38 @@ -using System; - -using OpenMetaverse; - - -namespace OpenSim.Framework.Communications -{ - public interface IAuthentication - { - string GetNewKey(string url, UUID userID, UUID authToken); - bool VerifyKey(UUID userID, string key); - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using OpenMetaverse; + +namespace OpenSim.Framework.Communications +{ + public interface IAuthentication + { + string GetNewKey(string url, UUID userID, UUID authToken); + bool VerifyKey(UUID userID, string key); + } +} diff --git a/OpenSim/Framework/Communications/Services/GridInfoService.cs b/OpenSim/Framework/Communications/Services/GridInfoService.cs index 96fe0d8..030ea61 100644 --- a/OpenSim/Framework/Communications/Services/GridInfoService.cs +++ b/OpenSim/Framework/Communications/Services/GridInfoService.cs @@ -1,172 +1,172 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.IO; -using System.Reflection; -using System.Text; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework.Servers; - -namespace OpenSim.Framework.Communications.Services -{ - public class GridInfoService - { - private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Hashtable _info = new Hashtable(); - - /// - /// Instantiate a GridInfoService object. - /// - /// path to config path containing - /// grid information - /// - /// GridInfoService uses the [GridInfo] section of the - /// standard OpenSim.ini file --- which is not optimal, but - /// anything else requires a general redesign of the config - /// system. - /// - public GridInfoService(IConfigSource configSource) - { - loadGridInfo(configSource); - } - - /// - /// Default constructor, uses OpenSim.ini. - /// - public GridInfoService() - { - try - { - IConfigSource configSource = new IniConfigSource(Path.Combine(Util.configDir(), "OpenSim.ini")); - loadGridInfo(configSource); - } - catch (FileNotFoundException) - { - _log.Warn("[GridInfoService] no OpenSim.ini file found --- GridInfoServices WILL NOT BE AVAILABLE to your users"); - } - } - - private void loadGridInfo(IConfigSource configSource) - { - _info["platform"] = "OpenSim"; - try - { - IConfig startupCfg = configSource.Configs["Startup"]; - IConfig gridCfg = configSource.Configs["GridInfo"]; - IConfig netCfg = configSource.Configs["Network"]; - - bool grid = startupCfg.GetBoolean("gridmode", false); - - if (grid) - _info["mode"] = "grid"; - else - _info["mode"] = "standalone"; - - - if (null != gridCfg) - { - foreach (string k in gridCfg.GetKeys()) - { - _info[k] = gridCfg.GetString(k); - } - } - else if (null != netCfg) - { - if (grid) - _info["login"] - = netCfg.GetString( - "user_server_url", "http://127.0.0.1:" + UserConfig.DefaultHttpPort.ToString()); - else - _info["login"] - = String.Format( - "http://127.0.0.1:{0}/", - netCfg.GetString( - "http_listener_port", NetworkServersInfo.DefaultHttpListenerPort.ToString())); - - IssueWarning(); - } - else - { - _info["login"] = "http://127.0.0.1:9000/"; - IssueWarning(); - } - } - catch (Exception) - { - _log.Debug("[GridInfoService] cannot get grid info from config source, using minimal defaults"); - } - _log.InfoFormat("[GridInfoService] Grid info service initialized with {0} keys", _info.Count); - - } - - private void IssueWarning() - { - _log.Warn("[GridInfoService] found no [GridInfo] section in your OpenSim.ini"); - _log.Warn("[GridInfoService] trying to guess sensible defaults, you might want to provide better ones:"); - foreach (string k in _info.Keys) - { - _log.WarnFormat("[GridInfoService] {0}: {1}", k, _info[k]); - } - } - - public XmlRpcResponse XmlRpcGridInfoMethod(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - _log.Info("[GridInfo]: Request for grid info"); - - foreach (string k in _info.Keys) - { - responseData[k] = _info[k]; - } - response.Value = responseData; - - return response; - } - - public string RestGetGridInfoMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - StringBuilder sb = new StringBuilder(); - - sb.Append("\n"); - foreach (string k in _info.Keys) - { - sb.AppendFormat("<{0}>{1}\n", k, _info[k]); - } - sb.Append("\n"); - - return sb.ToString(); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.IO; +using System.Reflection; +using System.Text; +using log4net; +using Nini.Config; +using Nwc.XmlRpc; +using OpenSim.Framework.Servers; + +namespace OpenSim.Framework.Communications.Services +{ + public class GridInfoService + { + private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Hashtable _info = new Hashtable(); + + /// + /// Instantiate a GridInfoService object. + /// + /// path to config path containing + /// grid information + /// + /// GridInfoService uses the [GridInfo] section of the + /// standard OpenSim.ini file --- which is not optimal, but + /// anything else requires a general redesign of the config + /// system. + /// + public GridInfoService(IConfigSource configSource) + { + loadGridInfo(configSource); + } + + /// + /// Default constructor, uses OpenSim.ini. + /// + public GridInfoService() + { + try + { + IConfigSource configSource = new IniConfigSource(Path.Combine(Util.configDir(), "OpenSim.ini")); + loadGridInfo(configSource); + } + catch (FileNotFoundException) + { + _log.Warn("[GridInfoService] no OpenSim.ini file found --- GridInfoServices WILL NOT BE AVAILABLE to your users"); + } + } + + private void loadGridInfo(IConfigSource configSource) + { + _info["platform"] = "OpenSim"; + try + { + IConfig startupCfg = configSource.Configs["Startup"]; + IConfig gridCfg = configSource.Configs["GridInfo"]; + IConfig netCfg = configSource.Configs["Network"]; + + bool grid = startupCfg.GetBoolean("gridmode", false); + + if (grid) + _info["mode"] = "grid"; + else + _info["mode"] = "standalone"; + + + if (null != gridCfg) + { + foreach (string k in gridCfg.GetKeys()) + { + _info[k] = gridCfg.GetString(k); + } + } + else if (null != netCfg) + { + if (grid) + _info["login"] + = netCfg.GetString( + "user_server_url", "http://127.0.0.1:" + UserConfig.DefaultHttpPort.ToString()); + else + _info["login"] + = String.Format( + "http://127.0.0.1:{0}/", + netCfg.GetString( + "http_listener_port", NetworkServersInfo.DefaultHttpListenerPort.ToString())); + + IssueWarning(); + } + else + { + _info["login"] = "http://127.0.0.1:9000/"; + IssueWarning(); + } + } + catch (Exception) + { + _log.Debug("[GridInfoService] cannot get grid info from config source, using minimal defaults"); + } + _log.InfoFormat("[GridInfoService] Grid info service initialized with {0} keys", _info.Count); + + } + + private void IssueWarning() + { + _log.Warn("[GridInfoService] found no [GridInfo] section in your OpenSim.ini"); + _log.Warn("[GridInfoService] trying to guess sensible defaults, you might want to provide better ones:"); + foreach (string k in _info.Keys) + { + _log.WarnFormat("[GridInfoService] {0}: {1}", k, _info[k]); + } + } + + public XmlRpcResponse XmlRpcGridInfoMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + + _log.Info("[GridInfo]: Request for grid info"); + + foreach (string k in _info.Keys) + { + responseData[k] = _info[k]; + } + response.Value = responseData; + + return response; + } + + public string RestGetGridInfoMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + StringBuilder sb = new StringBuilder(); + + sb.Append("\n"); + foreach (string k in _info.Keys) + { + sb.AppendFormat("<{0}>{1}\n", k, _info[k]); + } + sb.Append("\n"); + + return sb.ToString(); + } + } +} diff --git a/OpenSim/Framework/Communications/Services/LoginResponse.cs b/OpenSim/Framework/Communications/Services/LoginResponse.cs index 82515e0..db208a4 100644 --- a/OpenSim/Framework/Communications/Services/LoginResponse.cs +++ b/OpenSim/Framework/Communications/Services/LoginResponse.cs @@ -1,812 +1,812 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenMetaverse.StructuredData; - -namespace OpenSim.Framework.Communications.Services -{ - /// - /// A temp class to handle login response. - /// Should make use of UserProfileManager where possible. - /// - public class LoginResponse - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Hashtable loginFlagsHash; - private Hashtable globalTexturesHash; - private Hashtable loginError; - private Hashtable uiConfigHash; - - private ArrayList loginFlags; - private ArrayList globalTextures; - private ArrayList eventCategories; - private ArrayList uiConfig; - private ArrayList classifiedCategories; - private ArrayList inventoryRoot; - private ArrayList initialOutfit; - private ArrayList agentInventory; - private ArrayList inventoryLibraryOwner; - private ArrayList inventoryLibRoot; - private ArrayList inventoryLibrary; - private ArrayList activeGestures; - - private UserInfo userProfile; - - private UUID agentID; - private UUID sessionID; - private UUID secureSessionID; - - // Login Flags - private string dst; - private string stipendSinceLogin; - private string gendered; - private string everLoggedIn; - private string login; - private uint simPort; - private uint simHttpPort; - private string simAddress; - private string agentAccess; - private Int32 circuitCode; - private uint regionX; - private uint regionY; - - // Login - private string firstname; - private string lastname; - - // Global Textures - private string sunTexture; - private string cloudTexture; - private string moonTexture; - - // Error Flags - private string errorReason; - private string errorMessage; - - // Response - private XmlRpcResponse xmlRpcResponse; - // private XmlRpcResponse defaultXmlRpcResponse; - - private string welcomeMessage; - private string startLocation; - private string allowFirstLife; - private string home; - private string seedCapability; - private string lookAt; - - private BuddyList m_buddyList = null; - - public LoginResponse() - { - loginFlags = new ArrayList(); - globalTextures = new ArrayList(); - eventCategories = new ArrayList(); - uiConfig = new ArrayList(); - classifiedCategories = new ArrayList(); - - loginError = new Hashtable(); - uiConfigHash = new Hashtable(); - - // defaultXmlRpcResponse = new XmlRpcResponse(); - userProfile = new UserInfo(); - inventoryRoot = new ArrayList(); - initialOutfit = new ArrayList(); - agentInventory = new ArrayList(); - inventoryLibrary = new ArrayList(); - inventoryLibraryOwner = new ArrayList(); - activeGestures = new ArrayList(); - - xmlRpcResponse = new XmlRpcResponse(); - // defaultXmlRpcResponse = new XmlRpcResponse(); - - SetDefaultValues(); - } - - private void SetDefaultValues() - { - DST = "N"; - StipendSinceLogin = "N"; - Gendered = "Y"; - EverLoggedIn = "Y"; - login = "false"; - firstname = "Test"; - lastname = "User"; - agentAccess = "M"; - startLocation = "last"; - allowFirstLife = "Y"; - - SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271"; - CloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621"; - MoonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621"; - - ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock."; - ErrorReason = "key"; - welcomeMessage = "Welcome to OpenSim!"; - seedCapability = String.Empty; - home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" + - userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" + - userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" + - userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}"; - lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]"; - RegionX = (uint) 255232; - RegionY = (uint) 254976; - - // Classifieds; - AddClassifiedCategory((Int32) 1, "Shopping"); - AddClassifiedCategory((Int32) 2, "Land Rental"); - AddClassifiedCategory((Int32) 3, "Property Rental"); - AddClassifiedCategory((Int32) 4, "Special Attraction"); - AddClassifiedCategory((Int32) 5, "New Products"); - AddClassifiedCategory((Int32) 6, "Employment"); - AddClassifiedCategory((Int32) 7, "Wanted"); - AddClassifiedCategory((Int32) 8, "Service"); - AddClassifiedCategory((Int32) 9, "Personal"); - - SessionID = UUID.Random(); - SecureSessionID = UUID.Random(); - AgentID = UUID.Random(); - - Hashtable InitialOutfitHash = new Hashtable(); - InitialOutfitHash["folder_name"] = "Nightclub Female"; - InitialOutfitHash["gender"] = "female"; - initialOutfit.Add(InitialOutfitHash); - } - - #region Login Failure Methods - - public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login) - { - // Overwrite any default values; - xmlRpcResponse = new XmlRpcResponse(); - - // Ensure Login Failed message/reason; - ErrorMessage = message; - ErrorReason = reason; - - loginError["reason"] = ErrorReason; - loginError["message"] = ErrorMessage; - loginError["login"] = login; - xmlRpcResponse.Value = loginError; - return (xmlRpcResponse); - } - - public OSD GenerateFailureResponseLLSD(string reason, string message, string login) - { - OSDMap map = new OSDMap(); - - // Ensure Login Failed message/reason; - ErrorMessage = message; - ErrorReason = reason; - - map["reason"] = OSD.FromString(ErrorReason); - map["message"] = OSD.FromString(ErrorMessage); - map["login"] = OSD.FromString(login); - - return map; - } - - public XmlRpcResponse CreateFailedResponse() - { - return (CreateLoginFailedResponse()); - } - - public OSD CreateFailedResponseLLSD() - { - return CreateLoginFailedResponseLLSD(); - } - - public XmlRpcResponse CreateLoginFailedResponse() - { - return - (GenerateFailureResponse("key", - "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", - "false")); - } - - public OSD CreateLoginFailedResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", - "false"); - } - - /// - /// Response to indicate that login failed because the agent's inventory was not available. - /// - /// - public XmlRpcResponse CreateLoginInventoryFailedResponse() - { - return GenerateFailureResponse( - "key", - "The avatar inventory service is not responding. Please notify your login region operator.", - "false"); - } - - public XmlRpcResponse CreateAlreadyLoggedInResponse() - { - return - (GenerateFailureResponse("presence", - "You appear to be already logged in. " + - "If this is not the case please wait for your session to timeout. " + - "If this takes longer than a few minutes please contact the grid owner. " + - "Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.", - "false")); - } - - public OSD CreateAlreadyLoggedInResponseLLSD() - { - return GenerateFailureResponseLLSD( - "presence", - "You appear to be already logged in. " + - "If this is not the case please wait for your session to timeout. " + - "If this takes longer than a few minutes please contact the grid owner", - "false"); - } - - public XmlRpcResponse CreateLoginBlockedResponse() - { - return - (GenerateFailureResponse("presence", - "Logins are currently restricted. Please try again later", - "false")); - } - - public OSD CreateLoginBlockedResponseLLSD() - { - return GenerateFailureResponseLLSD( - "presence", - "Logins are currently restricted. Please try again later", - "false"); - } - - public XmlRpcResponse CreateDeadRegionResponse() - { - return - (GenerateFailureResponse("key", - "The region you are attempting to log into is not responding. Please select another region and try again.", - "false")); - } - - public OSD CreateDeadRegionResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "The region you are attempting to log into is not responding. Please select another region and try again.", - "false"); - } - - public XmlRpcResponse CreateGridErrorResponse() - { - return - (GenerateFailureResponse("key", - "Error connecting to grid. Could not percieve credentials from login XML.", - "false")); - } - - public OSD CreateGridErrorResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "Error connecting to grid. Could not percieve credentials from login XML.", - "false"); - } - - #endregion - - public virtual XmlRpcResponse ToXmlRpcResponse() - { - try - { - Hashtable responseData = new Hashtable(); - - loginFlagsHash = new Hashtable(); - loginFlagsHash["daylight_savings"] = DST; - loginFlagsHash["stipend_since_login"] = StipendSinceLogin; - loginFlagsHash["gendered"] = Gendered; - loginFlagsHash["ever_logged_in"] = EverLoggedIn; - loginFlags.Add(loginFlagsHash); - - responseData["first_name"] = Firstname; - responseData["last_name"] = Lastname; - responseData["agent_access"] = agentAccess; - - globalTexturesHash = new Hashtable(); - globalTexturesHash["sun_texture_id"] = SunTexture; - globalTexturesHash["cloud_texture_id"] = CloudTexture; - globalTexturesHash["moon_texture_id"] = MoonTexture; - globalTextures.Add(globalTexturesHash); - // this.eventCategories.Add(this.eventCategoriesHash); - - AddToUIConfig("allow_first_life", allowFirstLife); - uiConfig.Add(uiConfigHash); - - responseData["sim_port"] = (Int32) SimPort; - responseData["sim_ip"] = SimAddress; - responseData["http_port"] = (Int32)SimHttpPort; - - responseData["agent_id"] = AgentID.ToString(); - responseData["session_id"] = SessionID.ToString(); - responseData["secure_session_id"] = SecureSessionID.ToString(); - responseData["circuit_code"] = CircuitCode; - responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; - responseData["login-flags"] = loginFlags; - responseData["global-textures"] = globalTextures; - responseData["seed_capability"] = seedCapability; - - responseData["event_categories"] = eventCategories; - responseData["event_notifications"] = new ArrayList(); // todo - responseData["classified_categories"] = classifiedCategories; - responseData["ui-config"] = uiConfig; - - responseData["inventory-skeleton"] = agentInventory; - responseData["inventory-skel-lib"] = inventoryLibrary; - responseData["inventory-root"] = inventoryRoot; - responseData["inventory-lib-root"] = inventoryLibRoot; - responseData["gestures"] = activeGestures; - responseData["inventory-lib-owner"] = inventoryLibraryOwner; - responseData["initial-outfit"] = initialOutfit; - responseData["start_location"] = startLocation; - responseData["seed_capability"] = seedCapability; - responseData["home"] = home; - responseData["look_at"] = lookAt; - responseData["message"] = welcomeMessage; - responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize); - responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize); - - //responseData["inventory-lib-root"] = new ArrayList(); // todo - - if (m_buddyList != null) - { - responseData["buddy-list"] = m_buddyList.ToArray(); - } - - responseData["login"] = "true"; - xmlRpcResponse.Value = responseData; - - return (xmlRpcResponse); - } - catch (Exception e) - { - m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message); - - return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false")); - } - } - - public OSD ToLLSDResponse() - { - try - { - OSDMap map = new OSDMap(); - - map["first_name"] = OSD.FromString(Firstname); - map["last_name"] = OSD.FromString(Lastname); - map["agent_access"] = OSD.FromString(agentAccess); - - map["sim_port"] = OSD.FromInteger(SimPort); - map["sim_ip"] = OSD.FromString(SimAddress); - - map["agent_id"] = OSD.FromUUID(AgentID); - map["session_id"] = OSD.FromUUID(SessionID); - map["secure_session_id"] = OSD.FromUUID(SecureSessionID); - map["circuit_code"] = OSD.FromInteger(CircuitCode); - map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds); - - #region Login Flags - - OSDMap loginFlagsLLSD = new OSDMap(); - loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST); - loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin); - loginFlagsLLSD["gendered"] = OSD.FromString(Gendered); - loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn); - map["login-flags"] = WrapOSDMap(loginFlagsLLSD); - - #endregion Login Flags - - #region Global Textures - - OSDMap globalTexturesLLSD = new OSDMap(); - globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture); - globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture); - globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture); - - map["global-textures"] = WrapOSDMap(globalTexturesLLSD); - - #endregion Global Textures - - map["seed_capability"] = OSD.FromString(seedCapability); - - map["event_categories"] = ArrayListToOSDArray(eventCategories); - //map["event_notifications"] = new OSDArray(); // todo - map["classified_categories"] = ArrayListToOSDArray(classifiedCategories); - - #region UI Config - - OSDMap uiConfigLLSD = new OSDMap(); - uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife); - map["ui-config"] = WrapOSDMap(uiConfigLLSD); - - #endregion UI Config - - #region Inventory - - map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory); - - map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary); - map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ; - map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot); - map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner); - - #endregion Inventory - - map["gestures"] = ArrayListToOSDArray(activeGestures); - - map["initial-outfit"] = ArrayListToOSDArray(initialOutfit); - map["start_location"] = OSD.FromString(startLocation); - - map["seed_capability"] = OSD.FromString(seedCapability); - map["home"] = OSD.FromString(home); - map["look_at"] = OSD.FromString(lookAt); - map["message"] = OSD.FromString(welcomeMessage); - map["region_x"] = OSD.FromInteger(RegionX * Constants.RegionSize); - map["region_y"] = OSD.FromInteger(RegionY * Constants.RegionSize); - - if (m_buddyList != null) - { - map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray()); - } - - map["login"] = OSD.FromString("true"); - - return map; - } - catch (Exception e) - { - m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message); - - return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false"); - } - } - - public OSDArray ArrayListToOSDArray(ArrayList arrlst) - { - OSDArray llsdBack = new OSDArray(); - foreach (Hashtable ht in arrlst) - { - OSDMap mp = new OSDMap(); - foreach (DictionaryEntry deHt in ht) - { - mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value)); - } - llsdBack.Add(mp); - } - return llsdBack; - } - - private static OSDArray WrapOSDMap(OSDMap wrapMe) - { - OSDArray array = new OSDArray(); - array.Add(wrapMe); - return array; - } - - public void SetEventCategories(string category, string value) - { - // this.eventCategoriesHash[category] = value; - //TODO - } - - public void AddToUIConfig(string itemName, string item) - { - uiConfigHash[itemName] = item; - } - - public void AddClassifiedCategory(Int32 ID, string categoryName) - { - Hashtable hash = new Hashtable(); - hash["category_name"] = categoryName; - hash["category_id"] = ID; - classifiedCategories.Add(hash); - // this.classifiedCategoriesHash.Clear(); - } - - #region Properties - - public string Login - { - get { return login; } - set { login = value; } - } - - public string DST - { - get { return dst; } - set { dst = value; } - } - - public string StipendSinceLogin - { - get { return stipendSinceLogin; } - set { stipendSinceLogin = value; } - } - - public string Gendered - { - get { return gendered; } - set { gendered = value; } - } - - public string EverLoggedIn - { - get { return everLoggedIn; } - set { everLoggedIn = value; } - } - - public uint SimPort - { - get { return simPort; } - set { simPort = value; } - } - - public uint SimHttpPort - { - get { return simHttpPort; } - set { simHttpPort = value; } - } - - public string SimAddress - { - get { return simAddress; } - set { simAddress = value; } - } - - public UUID AgentID - { - get { return agentID; } - set { agentID = value; } - } - - public UUID SessionID - { - get { return sessionID; } - set { sessionID = value; } - } - - public UUID SecureSessionID - { - get { return secureSessionID; } - set { secureSessionID = value; } - } - - public Int32 CircuitCode - { - get { return circuitCode; } - set { circuitCode = value; } - } - - public uint RegionX - { - get { return regionX; } - set { regionX = value; } - } - - public uint RegionY - { - get { return regionY; } - set { regionY = value; } - } - - public string SunTexture - { - get { return sunTexture; } - set { sunTexture = value; } - } - - public string CloudTexture - { - get { return cloudTexture; } - set { cloudTexture = value; } - } - - public string MoonTexture - { - get { return moonTexture; } - set { moonTexture = value; } - } - - public string Firstname - { - get { return firstname; } - set { firstname = value; } - } - - public string Lastname - { - get { return lastname; } - set { lastname = value; } - } - - public string AgentAccess - { - get { return agentAccess; } - set { agentAccess = value; } - } - - public string StartLocation - { - get { return startLocation; } - set { startLocation = value; } - } - - public string LookAt - { - get { return lookAt; } - set { lookAt = value; } - } - - public string SeedCapability - { - get { return seedCapability; } - set { seedCapability = value; } - } - - public string ErrorReason - { - get { return errorReason; } - set { errorReason = value; } - } - - public string ErrorMessage - { - get { return errorMessage; } - set { errorMessage = value; } - } - - public ArrayList InventoryRoot - { - get { return inventoryRoot; } - set { inventoryRoot = value; } - } - - public ArrayList InventorySkeleton - { - get { return agentInventory; } - set { agentInventory = value; } - } - - public ArrayList InventoryLibrary - { - get { return inventoryLibrary; } - set { inventoryLibrary = value; } - } - - public ArrayList InventoryLibraryOwner - { - get { return inventoryLibraryOwner; } - set { inventoryLibraryOwner = value; } - } - - public ArrayList InventoryLibRoot - { - get { return inventoryLibRoot; } - set { inventoryLibRoot = value; } - } - - public ArrayList ActiveGestures - { - get { return activeGestures; } - set { activeGestures = value; } - } - - public string Home - { - get { return home; } - set { home = value; } - } - - public string Message - { - get { return welcomeMessage; } - set { welcomeMessage = value; } - } - - public BuddyList BuddList - { - get { return m_buddyList; } - set { m_buddyList = value; } - } - - #endregion - - public class UserInfo - { - public string firstname; - public string lastname; - public ulong homeregionhandle; - public Vector3 homepos; - public Vector3 homelookat; - } - - public class BuddyList - { - public List Buddies = new List(); - - public void AddNewBuddy(BuddyInfo buddy) - { - if (!Buddies.Contains(buddy)) - { - Buddies.Add(buddy); - } - } - - public ArrayList ToArray() - { - ArrayList buddyArray = new ArrayList(); - foreach (BuddyInfo buddy in Buddies) - { - buddyArray.Add(buddy.ToHashTable()); - } - return buddyArray; - } - - public class BuddyInfo - { - public int BuddyRightsHave = 1; - public int BuddyRightsGiven = 1; - public UUID BuddyID; - - public BuddyInfo(string buddyID) - { - BuddyID = new UUID(buddyID); - } - - public BuddyInfo(UUID buddyID) - { - BuddyID = buddyID; - } - - public Hashtable ToHashTable() - { - Hashtable hTable = new Hashtable(); - hTable["buddy_rights_has"] = BuddyRightsHave; - hTable["buddy_rights_given"] = BuddyRightsGiven; - hTable["buddy_id"] = BuddyID.ToString(); - return hTable; - } - } - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenMetaverse.StructuredData; + +namespace OpenSim.Framework.Communications.Services +{ + /// + /// A temp class to handle login response. + /// Should make use of UserProfileManager where possible. + /// + public class LoginResponse + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Hashtable loginFlagsHash; + private Hashtable globalTexturesHash; + private Hashtable loginError; + private Hashtable uiConfigHash; + + private ArrayList loginFlags; + private ArrayList globalTextures; + private ArrayList eventCategories; + private ArrayList uiConfig; + private ArrayList classifiedCategories; + private ArrayList inventoryRoot; + private ArrayList initialOutfit; + private ArrayList agentInventory; + private ArrayList inventoryLibraryOwner; + private ArrayList inventoryLibRoot; + private ArrayList inventoryLibrary; + private ArrayList activeGestures; + + private UserInfo userProfile; + + private UUID agentID; + private UUID sessionID; + private UUID secureSessionID; + + // Login Flags + private string dst; + private string stipendSinceLogin; + private string gendered; + private string everLoggedIn; + private string login; + private uint simPort; + private uint simHttpPort; + private string simAddress; + private string agentAccess; + private Int32 circuitCode; + private uint regionX; + private uint regionY; + + // Login + private string firstname; + private string lastname; + + // Global Textures + private string sunTexture; + private string cloudTexture; + private string moonTexture; + + // Error Flags + private string errorReason; + private string errorMessage; + + // Response + private XmlRpcResponse xmlRpcResponse; + // private XmlRpcResponse defaultXmlRpcResponse; + + private string welcomeMessage; + private string startLocation; + private string allowFirstLife; + private string home; + private string seedCapability; + private string lookAt; + + private BuddyList m_buddyList = null; + + public LoginResponse() + { + loginFlags = new ArrayList(); + globalTextures = new ArrayList(); + eventCategories = new ArrayList(); + uiConfig = new ArrayList(); + classifiedCategories = new ArrayList(); + + loginError = new Hashtable(); + uiConfigHash = new Hashtable(); + + // defaultXmlRpcResponse = new XmlRpcResponse(); + userProfile = new UserInfo(); + inventoryRoot = new ArrayList(); + initialOutfit = new ArrayList(); + agentInventory = new ArrayList(); + inventoryLibrary = new ArrayList(); + inventoryLibraryOwner = new ArrayList(); + activeGestures = new ArrayList(); + + xmlRpcResponse = new XmlRpcResponse(); + // defaultXmlRpcResponse = new XmlRpcResponse(); + + SetDefaultValues(); + } + + private void SetDefaultValues() + { + DST = "N"; + StipendSinceLogin = "N"; + Gendered = "Y"; + EverLoggedIn = "Y"; + login = "false"; + firstname = "Test"; + lastname = "User"; + agentAccess = "M"; + startLocation = "last"; + allowFirstLife = "Y"; + + SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271"; + CloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621"; + MoonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621"; + + ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock."; + ErrorReason = "key"; + welcomeMessage = "Welcome to OpenSim!"; + seedCapability = String.Empty; + home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" + + userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" + + userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" + + userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}"; + lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]"; + RegionX = (uint) 255232; + RegionY = (uint) 254976; + + // Classifieds; + AddClassifiedCategory((Int32) 1, "Shopping"); + AddClassifiedCategory((Int32) 2, "Land Rental"); + AddClassifiedCategory((Int32) 3, "Property Rental"); + AddClassifiedCategory((Int32) 4, "Special Attraction"); + AddClassifiedCategory((Int32) 5, "New Products"); + AddClassifiedCategory((Int32) 6, "Employment"); + AddClassifiedCategory((Int32) 7, "Wanted"); + AddClassifiedCategory((Int32) 8, "Service"); + AddClassifiedCategory((Int32) 9, "Personal"); + + SessionID = UUID.Random(); + SecureSessionID = UUID.Random(); + AgentID = UUID.Random(); + + Hashtable InitialOutfitHash = new Hashtable(); + InitialOutfitHash["folder_name"] = "Nightclub Female"; + InitialOutfitHash["gender"] = "female"; + initialOutfit.Add(InitialOutfitHash); + } + + #region Login Failure Methods + + public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login) + { + // Overwrite any default values; + xmlRpcResponse = new XmlRpcResponse(); + + // Ensure Login Failed message/reason; + ErrorMessage = message; + ErrorReason = reason; + + loginError["reason"] = ErrorReason; + loginError["message"] = ErrorMessage; + loginError["login"] = login; + xmlRpcResponse.Value = loginError; + return (xmlRpcResponse); + } + + public OSD GenerateFailureResponseLLSD(string reason, string message, string login) + { + OSDMap map = new OSDMap(); + + // Ensure Login Failed message/reason; + ErrorMessage = message; + ErrorReason = reason; + + map["reason"] = OSD.FromString(ErrorReason); + map["message"] = OSD.FromString(ErrorMessage); + map["login"] = OSD.FromString(login); + + return map; + } + + public XmlRpcResponse CreateFailedResponse() + { + return (CreateLoginFailedResponse()); + } + + public OSD CreateFailedResponseLLSD() + { + return CreateLoginFailedResponseLLSD(); + } + + public XmlRpcResponse CreateLoginFailedResponse() + { + return + (GenerateFailureResponse("key", + "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", + "false")); + } + + public OSD CreateLoginFailedResponseLLSD() + { + return GenerateFailureResponseLLSD( + "key", + "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", + "false"); + } + + /// + /// Response to indicate that login failed because the agent's inventory was not available. + /// + /// + public XmlRpcResponse CreateLoginInventoryFailedResponse() + { + return GenerateFailureResponse( + "key", + "The avatar inventory service is not responding. Please notify your login region operator.", + "false"); + } + + public XmlRpcResponse CreateAlreadyLoggedInResponse() + { + return + (GenerateFailureResponse("presence", + "You appear to be already logged in. " + + "If this is not the case please wait for your session to timeout. " + + "If this takes longer than a few minutes please contact the grid owner. " + + "Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.", + "false")); + } + + public OSD CreateAlreadyLoggedInResponseLLSD() + { + return GenerateFailureResponseLLSD( + "presence", + "You appear to be already logged in. " + + "If this is not the case please wait for your session to timeout. " + + "If this takes longer than a few minutes please contact the grid owner", + "false"); + } + + public XmlRpcResponse CreateLoginBlockedResponse() + { + return + (GenerateFailureResponse("presence", + "Logins are currently restricted. Please try again later", + "false")); + } + + public OSD CreateLoginBlockedResponseLLSD() + { + return GenerateFailureResponseLLSD( + "presence", + "Logins are currently restricted. Please try again later", + "false"); + } + + public XmlRpcResponse CreateDeadRegionResponse() + { + return + (GenerateFailureResponse("key", + "The region you are attempting to log into is not responding. Please select another region and try again.", + "false")); + } + + public OSD CreateDeadRegionResponseLLSD() + { + return GenerateFailureResponseLLSD( + "key", + "The region you are attempting to log into is not responding. Please select another region and try again.", + "false"); + } + + public XmlRpcResponse CreateGridErrorResponse() + { + return + (GenerateFailureResponse("key", + "Error connecting to grid. Could not percieve credentials from login XML.", + "false")); + } + + public OSD CreateGridErrorResponseLLSD() + { + return GenerateFailureResponseLLSD( + "key", + "Error connecting to grid. Could not percieve credentials from login XML.", + "false"); + } + + #endregion + + public virtual XmlRpcResponse ToXmlRpcResponse() + { + try + { + Hashtable responseData = new Hashtable(); + + loginFlagsHash = new Hashtable(); + loginFlagsHash["daylight_savings"] = DST; + loginFlagsHash["stipend_since_login"] = StipendSinceLogin; + loginFlagsHash["gendered"] = Gendered; + loginFlagsHash["ever_logged_in"] = EverLoggedIn; + loginFlags.Add(loginFlagsHash); + + responseData["first_name"] = Firstname; + responseData["last_name"] = Lastname; + responseData["agent_access"] = agentAccess; + + globalTexturesHash = new Hashtable(); + globalTexturesHash["sun_texture_id"] = SunTexture; + globalTexturesHash["cloud_texture_id"] = CloudTexture; + globalTexturesHash["moon_texture_id"] = MoonTexture; + globalTextures.Add(globalTexturesHash); + // this.eventCategories.Add(this.eventCategoriesHash); + + AddToUIConfig("allow_first_life", allowFirstLife); + uiConfig.Add(uiConfigHash); + + responseData["sim_port"] = (Int32) SimPort; + responseData["sim_ip"] = SimAddress; + responseData["http_port"] = (Int32)SimHttpPort; + + responseData["agent_id"] = AgentID.ToString(); + responseData["session_id"] = SessionID.ToString(); + responseData["secure_session_id"] = SecureSessionID.ToString(); + responseData["circuit_code"] = CircuitCode; + responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + responseData["login-flags"] = loginFlags; + responseData["global-textures"] = globalTextures; + responseData["seed_capability"] = seedCapability; + + responseData["event_categories"] = eventCategories; + responseData["event_notifications"] = new ArrayList(); // todo + responseData["classified_categories"] = classifiedCategories; + responseData["ui-config"] = uiConfig; + + responseData["inventory-skeleton"] = agentInventory; + responseData["inventory-skel-lib"] = inventoryLibrary; + responseData["inventory-root"] = inventoryRoot; + responseData["inventory-lib-root"] = inventoryLibRoot; + responseData["gestures"] = activeGestures; + responseData["inventory-lib-owner"] = inventoryLibraryOwner; + responseData["initial-outfit"] = initialOutfit; + responseData["start_location"] = startLocation; + responseData["seed_capability"] = seedCapability; + responseData["home"] = home; + responseData["look_at"] = lookAt; + responseData["message"] = welcomeMessage; + responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize); + responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize); + + //responseData["inventory-lib-root"] = new ArrayList(); // todo + + if (m_buddyList != null) + { + responseData["buddy-list"] = m_buddyList.ToArray(); + } + + responseData["login"] = "true"; + xmlRpcResponse.Value = responseData; + + return (xmlRpcResponse); + } + catch (Exception e) + { + m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message); + + return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false")); + } + } + + public OSD ToLLSDResponse() + { + try + { + OSDMap map = new OSDMap(); + + map["first_name"] = OSD.FromString(Firstname); + map["last_name"] = OSD.FromString(Lastname); + map["agent_access"] = OSD.FromString(agentAccess); + + map["sim_port"] = OSD.FromInteger(SimPort); + map["sim_ip"] = OSD.FromString(SimAddress); + + map["agent_id"] = OSD.FromUUID(AgentID); + map["session_id"] = OSD.FromUUID(SessionID); + map["secure_session_id"] = OSD.FromUUID(SecureSessionID); + map["circuit_code"] = OSD.FromInteger(CircuitCode); + map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds); + + #region Login Flags + + OSDMap loginFlagsLLSD = new OSDMap(); + loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST); + loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin); + loginFlagsLLSD["gendered"] = OSD.FromString(Gendered); + loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn); + map["login-flags"] = WrapOSDMap(loginFlagsLLSD); + + #endregion Login Flags + + #region Global Textures + + OSDMap globalTexturesLLSD = new OSDMap(); + globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture); + globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture); + globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture); + + map["global-textures"] = WrapOSDMap(globalTexturesLLSD); + + #endregion Global Textures + + map["seed_capability"] = OSD.FromString(seedCapability); + + map["event_categories"] = ArrayListToOSDArray(eventCategories); + //map["event_notifications"] = new OSDArray(); // todo + map["classified_categories"] = ArrayListToOSDArray(classifiedCategories); + + #region UI Config + + OSDMap uiConfigLLSD = new OSDMap(); + uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife); + map["ui-config"] = WrapOSDMap(uiConfigLLSD); + + #endregion UI Config + + #region Inventory + + map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory); + + map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary); + map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ; + map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot); + map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner); + + #endregion Inventory + + map["gestures"] = ArrayListToOSDArray(activeGestures); + + map["initial-outfit"] = ArrayListToOSDArray(initialOutfit); + map["start_location"] = OSD.FromString(startLocation); + + map["seed_capability"] = OSD.FromString(seedCapability); + map["home"] = OSD.FromString(home); + map["look_at"] = OSD.FromString(lookAt); + map["message"] = OSD.FromString(welcomeMessage); + map["region_x"] = OSD.FromInteger(RegionX * Constants.RegionSize); + map["region_y"] = OSD.FromInteger(RegionY * Constants.RegionSize); + + if (m_buddyList != null) + { + map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray()); + } + + map["login"] = OSD.FromString("true"); + + return map; + } + catch (Exception e) + { + m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message); + + return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false"); + } + } + + public OSDArray ArrayListToOSDArray(ArrayList arrlst) + { + OSDArray llsdBack = new OSDArray(); + foreach (Hashtable ht in arrlst) + { + OSDMap mp = new OSDMap(); + foreach (DictionaryEntry deHt in ht) + { + mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value)); + } + llsdBack.Add(mp); + } + return llsdBack; + } + + private static OSDArray WrapOSDMap(OSDMap wrapMe) + { + OSDArray array = new OSDArray(); + array.Add(wrapMe); + return array; + } + + public void SetEventCategories(string category, string value) + { + // this.eventCategoriesHash[category] = value; + //TODO + } + + public void AddToUIConfig(string itemName, string item) + { + uiConfigHash[itemName] = item; + } + + public void AddClassifiedCategory(Int32 ID, string categoryName) + { + Hashtable hash = new Hashtable(); + hash["category_name"] = categoryName; + hash["category_id"] = ID; + classifiedCategories.Add(hash); + // this.classifiedCategoriesHash.Clear(); + } + + #region Properties + + public string Login + { + get { return login; } + set { login = value; } + } + + public string DST + { + get { return dst; } + set { dst = value; } + } + + public string StipendSinceLogin + { + get { return stipendSinceLogin; } + set { stipendSinceLogin = value; } + } + + public string Gendered + { + get { return gendered; } + set { gendered = value; } + } + + public string EverLoggedIn + { + get { return everLoggedIn; } + set { everLoggedIn = value; } + } + + public uint SimPort + { + get { return simPort; } + set { simPort = value; } + } + + public uint SimHttpPort + { + get { return simHttpPort; } + set { simHttpPort = value; } + } + + public string SimAddress + { + get { return simAddress; } + set { simAddress = value; } + } + + public UUID AgentID + { + get { return agentID; } + set { agentID = value; } + } + + public UUID SessionID + { + get { return sessionID; } + set { sessionID = value; } + } + + public UUID SecureSessionID + { + get { return secureSessionID; } + set { secureSessionID = value; } + } + + public Int32 CircuitCode + { + get { return circuitCode; } + set { circuitCode = value; } + } + + public uint RegionX + { + get { return regionX; } + set { regionX = value; } + } + + public uint RegionY + { + get { return regionY; } + set { regionY = value; } + } + + public string SunTexture + { + get { return sunTexture; } + set { sunTexture = value; } + } + + public string CloudTexture + { + get { return cloudTexture; } + set { cloudTexture = value; } + } + + public string MoonTexture + { + get { return moonTexture; } + set { moonTexture = value; } + } + + public string Firstname + { + get { return firstname; } + set { firstname = value; } + } + + public string Lastname + { + get { return lastname; } + set { lastname = value; } + } + + public string AgentAccess + { + get { return agentAccess; } + set { agentAccess = value; } + } + + public string StartLocation + { + get { return startLocation; } + set { startLocation = value; } + } + + public string LookAt + { + get { return lookAt; } + set { lookAt = value; } + } + + public string SeedCapability + { + get { return seedCapability; } + set { seedCapability = value; } + } + + public string ErrorReason + { + get { return errorReason; } + set { errorReason = value; } + } + + public string ErrorMessage + { + get { return errorMessage; } + set { errorMessage = value; } + } + + public ArrayList InventoryRoot + { + get { return inventoryRoot; } + set { inventoryRoot = value; } + } + + public ArrayList InventorySkeleton + { + get { return agentInventory; } + set { agentInventory = value; } + } + + public ArrayList InventoryLibrary + { + get { return inventoryLibrary; } + set { inventoryLibrary = value; } + } + + public ArrayList InventoryLibraryOwner + { + get { return inventoryLibraryOwner; } + set { inventoryLibraryOwner = value; } + } + + public ArrayList InventoryLibRoot + { + get { return inventoryLibRoot; } + set { inventoryLibRoot = value; } + } + + public ArrayList ActiveGestures + { + get { return activeGestures; } + set { activeGestures = value; } + } + + public string Home + { + get { return home; } + set { home = value; } + } + + public string Message + { + get { return welcomeMessage; } + set { welcomeMessage = value; } + } + + public BuddyList BuddList + { + get { return m_buddyList; } + set { m_buddyList = value; } + } + + #endregion + + public class UserInfo + { + public string firstname; + public string lastname; + public ulong homeregionhandle; + public Vector3 homepos; + public Vector3 homelookat; + } + + public class BuddyList + { + public List Buddies = new List(); + + public void AddNewBuddy(BuddyInfo buddy) + { + if (!Buddies.Contains(buddy)) + { + Buddies.Add(buddy); + } + } + + public ArrayList ToArray() + { + ArrayList buddyArray = new ArrayList(); + foreach (BuddyInfo buddy in Buddies) + { + buddyArray.Add(buddy.ToHashTable()); + } + return buddyArray; + } + + public class BuddyInfo + { + public int BuddyRightsHave = 1; + public int BuddyRightsGiven = 1; + public UUID BuddyID; + + public BuddyInfo(string buddyID) + { + BuddyID = new UUID(buddyID); + } + + public BuddyInfo(UUID buddyID) + { + BuddyID = buddyID; + } + + public Hashtable ToHashTable() + { + Hashtable hTable = new Hashtable(); + hTable["buddy_rights_has"] = BuddyRightsHave; + hTable["buddy_rights_given"] = BuddyRightsGiven; + hTable["buddy_id"] = BuddyID.ToString(); + return hTable; + } + } + } + } +} diff --git a/OpenSim/Framework/Communications/Services/LoginService.cs b/OpenSim/Framework/Communications/Services/LoginService.cs index 51158c9..1b6520d 100644 --- a/OpenSim/Framework/Communications/Services/LoginService.cs +++ b/OpenSim/Framework/Communications/Services/LoginService.cs @@ -1,1093 +1,1093 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenMetaverse.StructuredData; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Statistics; - -namespace OpenSim.Framework.Communications.Services -{ - public abstract class LoginService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected string m_welcomeMessage = "Welcome to OpenSim"; - protected int m_minLoginLevel = 0; - protected UserManagerBase m_userManager = null; - protected Mutex m_loginMutex = new Mutex(false); - - /// - /// Used during login to send the skeleton of the OpenSim Library to the client. - /// - protected LibraryRootFolder m_libraryRootFolder; - - protected uint m_defaultHomeX; - protected uint m_defaultHomeY; - - /// - /// Used by the login service to make requests to the inventory service. - /// - protected IInterServiceInventoryServices m_inventoryService; - - /// - /// Constructor - /// - /// - /// - /// - public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder, - string welcomeMess) - { - m_userManager = userManager; - m_libraryRootFolder = libraryRootFolder; - - if (welcomeMess != String.Empty) - { - m_welcomeMessage = welcomeMess; - } - } - - /// - /// If the user is already logged in, try to notify the region that the user they've got is dead. - /// - /// - public virtual void LogOffUser(UserProfileData theUser, string message) - { - } - - - /// - /// Called when we receive the client's initial XMLRPC login_to_simulator request message - /// - /// The XMLRPC request - /// The response to send - public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) - { - // Temporary fix - m_loginMutex.WaitOne(); - - try - { - //CFK: CustomizeResponse contains sufficient strings to alleviate the need for this. - //CKF: m_log.Info("[LOGIN]: Attempting login now..."); - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - - SniffLoginKey((Uri)request.Params[2], requestData); - - bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && - (requestData.Contains("passwd") || requestData.Contains("web_login_key"))); - - string startLocationRequest = "last"; - - UserProfileData userProfile; - LoginResponse logResponse = new LoginResponse(); - - string firstname; - string lastname; - - if (GoodXML) - { - if (requestData.Contains("start")) - { - startLocationRequest = (string)requestData["start"]; - } - - firstname = (string)requestData["first"]; - lastname = (string)requestData["last"]; - - m_log.InfoFormat( - "[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'", - firstname, lastname); - - string clientVersion = "Unknown"; - - if (requestData.Contains("version")) - { - clientVersion = (string)requestData["version"]; - } - - m_log.DebugFormat( - "[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest); - - if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile)) - { - return logResponse.CreateLoginFailedResponse(); - } - } - else - { - m_log.Info( - "[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data"); - - return logResponse.CreateGridErrorResponse(); - } - - if (userProfile.GodLevel < m_minLoginLevel) - { - return logResponse.CreateLoginBlockedResponse(); - } - else - { - // If we already have a session... - if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) - { - //TODO: The following statements can cause trouble: - // If agentOnline could not turn from true back to false normally - // because of some problem, for instance, the crashment of server or client, - // the user cannot log in any longer. - userProfile.CurrentAgent.AgentOnline = false; - - m_userManager.CommitAgent(ref userProfile); - - // try to tell the region that their user is dead. - LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location"); - - // Reject the login - - m_log.InfoFormat( - "[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in", - firstname, lastname); - - return logResponse.CreateAlreadyLoggedInResponse(); - } - - // Otherwise... - // Create a new agent session - - m_userManager.ResetAttachments(userProfile.ID); - - CreateAgent(userProfile, request); - - try - { - UUID agentID = userProfile.ID; - InventoryData inventData; - - try - { - inventData = GetInventorySkeleton(agentID); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}", - agentID, e); - - return logResponse.CreateLoginInventoryFailedResponse(); - } - - ArrayList AgentInventoryArray = inventData.InventoryArray; - - Hashtable InventoryRootHash = new Hashtable(); - InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); - ArrayList InventoryRoot = new ArrayList(); - InventoryRoot.Add(InventoryRootHash); - userProfile.RootInventoryFolderID = inventData.RootFolderID; - - // Inventory Library Section - Hashtable InventoryLibRootHash = new Hashtable(); - InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; - ArrayList InventoryLibRoot = new ArrayList(); - InventoryLibRoot.Add(InventoryLibRootHash); - - logResponse.InventoryLibRoot = InventoryLibRoot; - logResponse.InventoryLibraryOwner = GetLibraryOwner(); - logResponse.InventoryRoot = InventoryRoot; - logResponse.InventorySkeleton = AgentInventoryArray; - logResponse.InventoryLibrary = GetInventoryLibrary(); - - logResponse.CircuitCode = Util.RandomClass.Next(); - logResponse.Lastname = userProfile.SurName; - logResponse.Firstname = userProfile.FirstName; - logResponse.AgentID = agentID; - logResponse.SessionID = userProfile.CurrentAgent.SessionID; - logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; - logResponse.Message = GetMessage(); - logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); - logResponse.StartLocation = startLocationRequest; - - if (CustomiseResponse(logResponse, userProfile, startLocationRequest)) - { - userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; - CommitAgent(ref userProfile); - - // If we reach this point, then the login has successfully logged onto the grid - if (StatsManager.UserStats != null) - StatsManager.UserStats.AddSuccessfulLogin(); - - m_log.DebugFormat( - "[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.", - firstname, lastname); - - return logResponse.ToXmlRpcResponse(); - } - else - { - m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname); - return logResponse.CreateDeadRegionResponse(); - } - } - catch (Exception e) - { - m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e); - m_log.Error(e.StackTrace); - } - } - - m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response"); - return response; - } - finally - { - m_loginMutex.ReleaseMutex(); - } - } - - protected virtual bool TryAuthenticateXmlRpcLogin(XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile) - { - Hashtable requestData = (Hashtable)request.Params[0]; - - bool GoodLogin = false; - - userProfile = GetTheUser(firstname, lastname); - if (userProfile == null) - { - m_log.Info("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname); - } - else - { - if (requestData.Contains("passwd")) - { - string passwd = (string)requestData["passwd"]; - GoodLogin = AuthenticateUser(userProfile, passwd); - } - if (!GoodLogin && (requestData.Contains("web_login_key"))) - { - try - { - UUID webloginkey = new UUID((string)requestData["web_login_key"]); - GoodLogin = AuthenticateUser(userProfile, webloginkey); - } - catch (Exception e) - { - m_log.InfoFormat( - "[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}", - requestData["web_login_key"], firstname, lastname, e); - } - } - } - - return GoodLogin; - } - - protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile) - { - bool GoodLogin = false; - userProfile = GetTheUser(firstname, lastname); - if (userProfile == null) - { - m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname); - - return false; - } - - GoodLogin = AuthenticateUser(userProfile, passwd); - return GoodLogin; - } - - /// - /// Called when we receive the client's initial LLSD login_to_simulator request message - /// - /// The LLSD request - /// The response to send - public OSD LLSDLoginMethod(OSD request) - { - // Temporary fix - m_loginMutex.WaitOne(); - - try - { - // bool GoodLogin = false; - - string startLocationRequest = "last"; - - UserProfileData userProfile = null; - LoginResponse logResponse = new LoginResponse(); - - if (request.Type == OSDType.Map) - { - OSDMap map = (OSDMap)request; - - if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) - { - string firstname = map["first"].AsString(); - string lastname = map["last"].AsString(); - string passwd = map["passwd"].AsString(); - - if (map.ContainsKey("start")) - { - m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString()); - startLocationRequest = map["start"].AsString(); - } - m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd); - - if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile)) - { - return logResponse.CreateLoginFailedResponseLLSD(); - } - } - else - return logResponse.CreateLoginFailedResponseLLSD(); - } - else - return logResponse.CreateLoginFailedResponseLLSD(); - - - if (userProfile.GodLevel < m_minLoginLevel) - { - return logResponse.CreateLoginBlockedResponseLLSD(); - } - else - { - // If we already have a session... - if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) - { - userProfile.CurrentAgent.AgentOnline = false; - - m_userManager.CommitAgent(ref userProfile); - // try to tell the region that their user is dead. - LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location"); - - // Reject the login - - m_log.InfoFormat( - "[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in", - userProfile.FirstName, userProfile.SurName); - - userProfile.CurrentAgent = null; - return logResponse.CreateAlreadyLoggedInResponseLLSD(); - } - - // Otherwise... - // Create a new agent session - - m_userManager.ResetAttachments(userProfile.ID); - - CreateAgent(userProfile, request); - - try - { - UUID agentID = userProfile.ID; - - //InventoryData inventData = GetInventorySkeleton(agentID); - InventoryData inventData = null; - - try - { - inventData = GetInventorySkeleton(agentID); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}", - agentID, e.GetType(), e.Message); - - return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD (); - } - - - ArrayList AgentInventoryArray = inventData.InventoryArray; - - Hashtable InventoryRootHash = new Hashtable(); - InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); - ArrayList InventoryRoot = new ArrayList(); - InventoryRoot.Add(InventoryRootHash); - userProfile.RootInventoryFolderID = inventData.RootFolderID; - - - // Inventory Library Section - Hashtable InventoryLibRootHash = new Hashtable(); - InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; - ArrayList InventoryLibRoot = new ArrayList(); - InventoryLibRoot.Add(InventoryLibRootHash); - - logResponse.InventoryLibRoot = InventoryLibRoot; - logResponse.InventoryLibraryOwner = GetLibraryOwner(); - logResponse.InventoryRoot = InventoryRoot; - logResponse.InventorySkeleton = AgentInventoryArray; - logResponse.InventoryLibrary = GetInventoryLibrary(); - - logResponse.CircuitCode = (Int32)Util.RandomClass.Next(); - logResponse.Lastname = userProfile.SurName; - logResponse.Firstname = userProfile.FirstName; - logResponse.AgentID = agentID; - logResponse.SessionID = userProfile.CurrentAgent.SessionID; - logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; - logResponse.Message = GetMessage(); - logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); - logResponse.StartLocation = startLocationRequest; - - try - { - CustomiseResponse(logResponse, userProfile, startLocationRequest); - } - catch (Exception ex) - { - m_log.Info("[LOGIN]: LLSD " + ex.ToString()); - return logResponse.CreateDeadRegionResponseLLSD(); - } - - userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; - CommitAgent(ref userProfile); - - // If we reach this point, then the login has successfully logged onto the grid - if (StatsManager.UserStats != null) - StatsManager.UserStats.AddSuccessfulLogin(); - - m_log.DebugFormat( - "[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.", - userProfile.FirstName, userProfile.SurName); - - return logResponse.ToLLSDResponse(); - } - catch (Exception ex) - { - m_log.Info("[LOGIN]: LLSD " + ex.ToString()); - return logResponse.CreateFailedResponseLLSD(); - } - } - } - finally - { - m_loginMutex.ReleaseMutex(); - } - } - - public Hashtable ProcessHTMLLogin(Hashtable keysvals) - { - // Matches all unspecified characters - // Currently specified,; lowercase letters, upper case letters, numbers, underline - // period, space, parens, and dash. - - Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]"); - - Hashtable returnactions = new Hashtable(); - int statuscode = 200; - - string firstname = String.Empty; - string lastname = String.Empty; - string location = String.Empty; - string region = String.Empty; - string grid = String.Empty; - string channel = String.Empty; - string version = String.Empty; - string lang = String.Empty; - string password = String.Empty; - string errormessages = String.Empty; - - // the client requires the HTML form field be named 'username' - // however, the data it sends when it loads the first time is 'firstname' - // another one of those little nuances. - - if (keysvals.Contains("firstname")) - firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999); - - if (keysvals.Contains("username")) - firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999); - - if (keysvals.Contains("lastname")) - lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999); - - if (keysvals.Contains("location")) - location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999); - - if (keysvals.Contains("region")) - region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999); - - if (keysvals.Contains("grid")) - grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999); - - if (keysvals.Contains("channel")) - channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999); - - if (keysvals.Contains("version")) - version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999); - - if (keysvals.Contains("lang")) - lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999); - - if (keysvals.Contains("password")) - password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999); - - // load our login form. - string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); - - if (keysvals.ContainsKey("show_login_form")) - { - UserProfileData user = GetTheUser(firstname, lastname); - bool goodweblogin = false; - - if (user != null) - goodweblogin = AuthenticateUser(user, password); - - if (goodweblogin) - { - UUID webloginkey = UUID.Random(); - m_userManager.StoreWebLoginKey(user.ID, webloginkey); - //statuscode = 301; - - // string redirectURL = "about:blank?redirect-http-hack=" + - // HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" + - // lastname + - // "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString()); - //m_log.Info("[WEB]: R:" + redirectURL); - returnactions["int_response_code"] = statuscode; - //returnactions["str_redirect_location"] = redirectURL; - //returnactions["str_response_string"] = "GoodLogin"; - returnactions["str_response_string"] = webloginkey.ToString(); - } - else - { - errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again"; - - loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); - returnactions["int_response_code"] = statuscode; - returnactions["str_response_string"] = loginform; - } - } - else - { - returnactions["int_response_code"] = statuscode; - returnactions["str_response_string"] = loginform; - } - return returnactions; - } - - public string GetLoginForm(string firstname, string lastname, string location, string region, - string grid, string channel, string version, string lang, - string password, string errormessages) - { - // inject our values in the form at the markers - - string loginform = String.Empty; - string file = Path.Combine(Util.configDir(), "http_loginform.html"); - if (!File.Exists(file)) - { - loginform = GetDefaultLoginForm(); - } - else - { - StreamReader sr = File.OpenText(file); - loginform = sr.ReadToEnd(); - sr.Close(); - } - - loginform = loginform.Replace("[$firstname]", firstname); - loginform = loginform.Replace("[$lastname]", lastname); - loginform = loginform.Replace("[$location]", location); - loginform = loginform.Replace("[$region]", region); - loginform = loginform.Replace("[$grid]", grid); - loginform = loginform.Replace("[$channel]", channel); - loginform = loginform.Replace("[$version]", version); - loginform = loginform.Replace("[$lang]", lang); - loginform = loginform.Replace("[$password]", password); - loginform = loginform.Replace("[$errors]", errormessages); - - return loginform; - } - - public string GetDefaultLoginForm() - { - string responseString = - ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "OpenSim Login"; - responseString += "
"; - responseString += "
"; - - responseString += "
"; - - responseString += "
[$errors]
"; - responseString += "
"; - responseString += "First Name:"; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += "Last Name:"; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += "Password:"; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "
"; - responseString += ""; - responseString += "
"; - responseString += "
Connecting...
"; - - responseString += "
"; - - responseString += "
[$channel] | [$version]=[$lang]
"; - responseString += "
"; - responseString += ""; - responseString += "
"; - responseString += ""; - responseString += ""; - responseString += ""; - - return responseString; - } - - /// - /// Saves a target agent to the database - /// - /// The users profile - /// Successful? - public bool CommitAgent(ref UserProfileData profile) - { - return m_userManager.CommitAgent(ref profile); - } - - /// - /// Checks a user against it's password hash - /// - /// The users profile - /// The supplied password - /// Authenticated? - public virtual bool AuthenticateUser(UserProfileData profile, string password) - { - bool passwordSuccess = false; - //m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); - - // Web Login method seems to also occasionally send the hashed password itself - - // we do this to get our hash in a form that the server password code can consume - // when the web-login-form submits the password in the clear (supposed to be over SSL!) - if (!password.StartsWith("$1$")) - password = "$1$" + Util.Md5Hash(password); - - password = password.Remove(0, 3); //remove $1$ - - string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); - // Testing... - //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash); - //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password); - - passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) - || profile.PasswordHash.Equals(password, StringComparison.InvariantCultureIgnoreCase)); - - return passwordSuccess; - } - - public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey) - { - bool passwordSuccess = false; - m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); - - // Match web login key unless it's the default weblogin key UUID.Zero - passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero); - - return passwordSuccess; - } - - /// - /// - /// - /// - /// - public void CreateAgent(UserProfileData profile, XmlRpcRequest request) - { - m_userManager.CreateAgent(profile, request); - } - - public void CreateAgent(UserProfileData profile, OSD request) - { - m_userManager.CreateAgent(profile, request); - } - - /// - /// - /// - /// - /// - /// - public virtual UserProfileData GetTheUser(string firstname, string lastname) - { - return m_userManager.GetUserProfile(firstname, lastname); - } - - /// - /// - /// - /// - public virtual string GetMessage() - { - return m_welcomeMessage; - } - - private static LoginResponse.BuddyList ConvertFriendListItem(List LFL) - { - LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList(); - foreach (FriendListItem fl in LFL) - { - LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend); - buddyitem.BuddyID = fl.Friend; - buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms; - buddyitem.BuddyRightsGiven = (int)fl.FriendPerms; - buddylistreturn.AddNewBuddy(buddyitem); - } - return buddylistreturn; - } - - /// - /// Converts the inventory library skeleton into the form required by the rpc request. - /// - /// - protected virtual ArrayList GetInventoryLibrary() - { - Dictionary rootFolders - = m_libraryRootFolder.RequestSelfAndDescendentFolders(); - ArrayList folderHashes = new ArrayList(); - - foreach (InventoryFolderBase folder in rootFolders.Values) - { - Hashtable TempHash = new Hashtable(); - TempHash["name"] = folder.Name; - TempHash["parent_id"] = folder.ParentID.ToString(); - TempHash["version"] = (Int32)folder.Version; - TempHash["type_default"] = (Int32)folder.Type; - TempHash["folder_id"] = folder.ID.ToString(); - folderHashes.Add(TempHash); - } - - return folderHashes; - } - - /// - /// - /// - /// - protected virtual ArrayList GetLibraryOwner() - { - //for now create random inventory library owner - Hashtable TempHash = new Hashtable(); - TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; - ArrayList inventoryLibOwner = new ArrayList(); - inventoryLibOwner.Add(TempHash); - return inventoryLibOwner; - } - - public class InventoryData - { - public ArrayList InventoryArray = null; - public UUID RootFolderID = UUID.Zero; - - public InventoryData(ArrayList invList, UUID rootID) - { - InventoryArray = invList; - RootFolderID = rootID; - } - } - - protected void SniffLoginKey(Uri uri, Hashtable requestData) - { - string uri_str = uri.ToString(); - string[] parts = uri_str.Split(new char[] { '=' }); - if (parts.Length > 1) - { - string web_login_key = parts[1]; - requestData.Add("web_login_key", web_login_key); - m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key); - } - } - - /// - /// Customises the login response and fills in missing values. This method also tells the login region to - /// expect a client connection. - /// - /// The existing response - /// The user profile - /// The requested start location - /// true on success, false if the region was not successfully told to expect a user connection - public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) - { - // add active gestures to login-response - AddActiveGestures(response, theUser); - - // HomeLocation - RegionInfo homeInfo = null; - - // use the homeRegionID if it is stored already. If not, use the regionHandle as before - UUID homeRegionId = theUser.HomeRegionID; - ulong homeRegionHandle = theUser.HomeRegion; - if (homeRegionId != UUID.Zero) - { - homeInfo = GetRegionInfo(homeRegionId); - } - else - { - homeInfo = GetRegionInfo(homeRegionHandle); - } - - if (homeInfo != null) - { - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - (homeInfo.RegionLocX * Constants.RegionSize), - (homeInfo.RegionLocY * Constants.RegionSize), - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - } - else - { - m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY); - // Emergency mode: Home-region isn't available, so we can't request the region info. - // Use the stored home regionHandle instead. - // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again - ulong regionX = homeRegionHandle >> 32; - ulong regionY = homeRegionHandle & 0xffffffff; - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - regionX, regionY, - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - - m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", - theUser.FirstName, theUser.SurName, - regionX, regionY); - } - - // StartLocation - RegionInfo regionInfo = null; - if (startLocationRequest == "home") - { - regionInfo = homeInfo; - theUser.CurrentAgent.Position = theUser.HomeLocation; - response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; - } - else if (startLocationRequest == "last") - { - UUID lastRegion = theUser.CurrentAgent.Region; - regionInfo = GetRegionInfo(lastRegion); - response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + theUser.CurrentAgent.LookAt.Z.ToString() + "]"; - } - else - { - Regex reURI = new Regex(@"^uri:(?[^&]+)&(?\d+)&(?\d+)&(?\d+)$"); - Match uriMatch = reURI.Match(startLocationRequest); - if (uriMatch == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest); - } - else - { - string region = uriMatch.Groups["region"].ToString(); - regionInfo = RequestClosestRegion(region); - if (regionInfo == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region); - } - else - { - theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), - float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); - } - } - response.LookAt = "[r0,r1,r0]"; - // can be: last, home, safe, url - response.StartLocation = "url"; - } - - if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response))) - { - return true; - } - - // StartLocation not available, send him to a nearby region instead - // regionInfo = m_gridService.RequestClosestRegion(""); - //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); - - // Send him to default region instead - ulong defaultHandle = (((ulong)m_defaultHomeX * Constants.RegionSize) << 32) | - ((ulong)m_defaultHomeY * Constants.RegionSize); - - if ((regionInfo != null) && (defaultHandle == regionInfo.RegionHandle)) - { - m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); - return false; - } - - m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); - regionInfo = GetRegionInfo(defaultHandle); - - if (regionInfo == null) - { - m_log.ErrorFormat("[LOGIN]: No default region available. Aborting."); - return false; - } - - theUser.CurrentAgent.Position = new Vector3(128, 128, 0); - response.StartLocation = "safe"; - - return PrepareLoginToRegion(regionInfo, theUser, response); - } - - protected abstract RegionInfo RequestClosestRegion(string region); - protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle); - protected abstract RegionInfo GetRegionInfo(UUID homeRegionId); - protected abstract bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response); - - /// - /// Add active gestures of the user to the login response. - /// - /// - /// A - /// - /// - /// A - /// - protected void AddActiveGestures(LoginResponse response, UserProfileData theUser) - { - List gestures = m_inventoryService.GetActiveGestures(theUser.ID); - //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); - ArrayList list = new ArrayList(); - if (gestures != null) - { - foreach (InventoryItemBase gesture in gestures) - { - Hashtable item = new Hashtable(); - item["item_id"] = gesture.ID.ToString(); - item["asset_id"] = gesture.AssetID.ToString(); - list.Add(item); - } - } - response.ActiveGestures = list; - } - - /// - /// Get the initial login inventory skeleton (in other words, the folder structure) for the given user. - /// - /// - /// - /// This will be thrown if there is a problem with the inventory service - protected InventoryData GetInventorySkeleton(UUID userID) - { - List folders = m_inventoryService.GetInventorySkeleton(userID); - - // If we have user auth but no inventory folders for some reason, create a new set of folders. - if (folders == null || folders.Count == 0) - { - m_log.InfoFormat( - "[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID); - - // Although the create user function creates a new agent inventory along with a new user profile, some - // tools are creating the user profile directly in the database without creating the inventory. At - // this time we'll accomodate them by lazily creating the user inventory now if it doesn't already - // exist. - if (!m_inventoryService.CreateNewUserInventory(userID)) - { - throw new Exception( - String.Format( - "The inventory creation request for user {0} did not succeed." - + " Please contact your inventory service provider for more information.", - userID)); - } - - m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); - - folders = m_inventoryService.GetInventorySkeleton(userID); - - if (folders == null || folders.Count == 0) - { - throw new Exception( - String.Format( - "A root inventory folder for user {0} could not be retrieved from the inventory service", - userID)); - } - } - - UUID rootID = UUID.Zero; - ArrayList AgentInventoryArray = new ArrayList(); - Hashtable TempHash; - foreach (InventoryFolderBase InvFolder in folders) - { - if (InvFolder.ParentID == UUID.Zero) - { - rootID = InvFolder.ID; - } - TempHash = new Hashtable(); - TempHash["name"] = InvFolder.Name; - TempHash["parent_id"] = InvFolder.ParentID.ToString(); - TempHash["version"] = (Int32)InvFolder.Version; - TempHash["type_default"] = (Int32)InvFolder.Type; - TempHash["folder_id"] = InvFolder.ID.ToString(); - AgentInventoryArray.Add(TempHash); - } - - return new InventoryData(AgentInventoryArray, rootID); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Threading; +using System.Web; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenMetaverse.StructuredData; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Statistics; + +namespace OpenSim.Framework.Communications.Services +{ + public abstract class LoginService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected string m_welcomeMessage = "Welcome to OpenSim"; + protected int m_minLoginLevel = 0; + protected UserManagerBase m_userManager = null; + protected Mutex m_loginMutex = new Mutex(false); + + /// + /// Used during login to send the skeleton of the OpenSim Library to the client. + /// + protected LibraryRootFolder m_libraryRootFolder; + + protected uint m_defaultHomeX; + protected uint m_defaultHomeY; + + /// + /// Used by the login service to make requests to the inventory service. + /// + protected IInterServiceInventoryServices m_inventoryService; + + /// + /// Constructor + /// + /// + /// + /// + public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder, + string welcomeMess) + { + m_userManager = userManager; + m_libraryRootFolder = libraryRootFolder; + + if (welcomeMess != String.Empty) + { + m_welcomeMessage = welcomeMess; + } + } + + /// + /// If the user is already logged in, try to notify the region that the user they've got is dead. + /// + /// + public virtual void LogOffUser(UserProfileData theUser, string message) + { + } + + + /// + /// Called when we receive the client's initial XMLRPC login_to_simulator request message + /// + /// The XMLRPC request + /// The response to send + public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) + { + // Temporary fix + m_loginMutex.WaitOne(); + + try + { + //CFK: CustomizeResponse contains sufficient strings to alleviate the need for this. + //CKF: m_log.Info("[LOGIN]: Attempting login now..."); + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + + SniffLoginKey((Uri)request.Params[2], requestData); + + bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && + (requestData.Contains("passwd") || requestData.Contains("web_login_key"))); + + string startLocationRequest = "last"; + + UserProfileData userProfile; + LoginResponse logResponse = new LoginResponse(); + + string firstname; + string lastname; + + if (GoodXML) + { + if (requestData.Contains("start")) + { + startLocationRequest = (string)requestData["start"]; + } + + firstname = (string)requestData["first"]; + lastname = (string)requestData["last"]; + + m_log.InfoFormat( + "[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'", + firstname, lastname); + + string clientVersion = "Unknown"; + + if (requestData.Contains("version")) + { + clientVersion = (string)requestData["version"]; + } + + m_log.DebugFormat( + "[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest); + + if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile)) + { + return logResponse.CreateLoginFailedResponse(); + } + } + else + { + m_log.Info( + "[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data"); + + return logResponse.CreateGridErrorResponse(); + } + + if (userProfile.GodLevel < m_minLoginLevel) + { + return logResponse.CreateLoginBlockedResponse(); + } + else + { + // If we already have a session... + if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) + { + //TODO: The following statements can cause trouble: + // If agentOnline could not turn from true back to false normally + // because of some problem, for instance, the crashment of server or client, + // the user cannot log in any longer. + userProfile.CurrentAgent.AgentOnline = false; + + m_userManager.CommitAgent(ref userProfile); + + // try to tell the region that their user is dead. + LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location"); + + // Reject the login + + m_log.InfoFormat( + "[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in", + firstname, lastname); + + return logResponse.CreateAlreadyLoggedInResponse(); + } + + // Otherwise... + // Create a new agent session + + m_userManager.ResetAttachments(userProfile.ID); + + CreateAgent(userProfile, request); + + try + { + UUID agentID = userProfile.ID; + InventoryData inventData; + + try + { + inventData = GetInventorySkeleton(agentID); + } + catch (Exception e) + { + m_log.ErrorFormat( + "[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}", + agentID, e); + + return logResponse.CreateLoginInventoryFailedResponse(); + } + + ArrayList AgentInventoryArray = inventData.InventoryArray; + + Hashtable InventoryRootHash = new Hashtable(); + InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); + ArrayList InventoryRoot = new ArrayList(); + InventoryRoot.Add(InventoryRootHash); + userProfile.RootInventoryFolderID = inventData.RootFolderID; + + // Inventory Library Section + Hashtable InventoryLibRootHash = new Hashtable(); + InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; + ArrayList InventoryLibRoot = new ArrayList(); + InventoryLibRoot.Add(InventoryLibRootHash); + + logResponse.InventoryLibRoot = InventoryLibRoot; + logResponse.InventoryLibraryOwner = GetLibraryOwner(); + logResponse.InventoryRoot = InventoryRoot; + logResponse.InventorySkeleton = AgentInventoryArray; + logResponse.InventoryLibrary = GetInventoryLibrary(); + + logResponse.CircuitCode = Util.RandomClass.Next(); + logResponse.Lastname = userProfile.SurName; + logResponse.Firstname = userProfile.FirstName; + logResponse.AgentID = agentID; + logResponse.SessionID = userProfile.CurrentAgent.SessionID; + logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; + logResponse.Message = GetMessage(); + logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); + logResponse.StartLocation = startLocationRequest; + + if (CustomiseResponse(logResponse, userProfile, startLocationRequest)) + { + userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; + CommitAgent(ref userProfile); + + // If we reach this point, then the login has successfully logged onto the grid + if (StatsManager.UserStats != null) + StatsManager.UserStats.AddSuccessfulLogin(); + + m_log.DebugFormat( + "[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.", + firstname, lastname); + + return logResponse.ToXmlRpcResponse(); + } + else + { + m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname); + return logResponse.CreateDeadRegionResponse(); + } + } + catch (Exception e) + { + m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e); + m_log.Error(e.StackTrace); + } + } + + m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response"); + return response; + } + finally + { + m_loginMutex.ReleaseMutex(); + } + } + + protected virtual bool TryAuthenticateXmlRpcLogin(XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + bool GoodLogin = false; + + userProfile = GetTheUser(firstname, lastname); + if (userProfile == null) + { + m_log.Info("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname); + } + else + { + if (requestData.Contains("passwd")) + { + string passwd = (string)requestData["passwd"]; + GoodLogin = AuthenticateUser(userProfile, passwd); + } + if (!GoodLogin && (requestData.Contains("web_login_key"))) + { + try + { + UUID webloginkey = new UUID((string)requestData["web_login_key"]); + GoodLogin = AuthenticateUser(userProfile, webloginkey); + } + catch (Exception e) + { + m_log.InfoFormat( + "[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}", + requestData["web_login_key"], firstname, lastname, e); + } + } + } + + return GoodLogin; + } + + protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile) + { + bool GoodLogin = false; + userProfile = GetTheUser(firstname, lastname); + if (userProfile == null) + { + m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname); + + return false; + } + + GoodLogin = AuthenticateUser(userProfile, passwd); + return GoodLogin; + } + + /// + /// Called when we receive the client's initial LLSD login_to_simulator request message + /// + /// The LLSD request + /// The response to send + public OSD LLSDLoginMethod(OSD request) + { + // Temporary fix + m_loginMutex.WaitOne(); + + try + { + // bool GoodLogin = false; + + string startLocationRequest = "last"; + + UserProfileData userProfile = null; + LoginResponse logResponse = new LoginResponse(); + + if (request.Type == OSDType.Map) + { + OSDMap map = (OSDMap)request; + + if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) + { + string firstname = map["first"].AsString(); + string lastname = map["last"].AsString(); + string passwd = map["passwd"].AsString(); + + if (map.ContainsKey("start")) + { + m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString()); + startLocationRequest = map["start"].AsString(); + } + m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd); + + if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile)) + { + return logResponse.CreateLoginFailedResponseLLSD(); + } + } + else + return logResponse.CreateLoginFailedResponseLLSD(); + } + else + return logResponse.CreateLoginFailedResponseLLSD(); + + + if (userProfile.GodLevel < m_minLoginLevel) + { + return logResponse.CreateLoginBlockedResponseLLSD(); + } + else + { + // If we already have a session... + if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) + { + userProfile.CurrentAgent.AgentOnline = false; + + m_userManager.CommitAgent(ref userProfile); + // try to tell the region that their user is dead. + LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location"); + + // Reject the login + + m_log.InfoFormat( + "[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in", + userProfile.FirstName, userProfile.SurName); + + userProfile.CurrentAgent = null; + return logResponse.CreateAlreadyLoggedInResponseLLSD(); + } + + // Otherwise... + // Create a new agent session + + m_userManager.ResetAttachments(userProfile.ID); + + CreateAgent(userProfile, request); + + try + { + UUID agentID = userProfile.ID; + + //InventoryData inventData = GetInventorySkeleton(agentID); + InventoryData inventData = null; + + try + { + inventData = GetInventorySkeleton(agentID); + } + catch (Exception e) + { + m_log.ErrorFormat( + "[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}", + agentID, e.GetType(), e.Message); + + return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD (); + } + + + ArrayList AgentInventoryArray = inventData.InventoryArray; + + Hashtable InventoryRootHash = new Hashtable(); + InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); + ArrayList InventoryRoot = new ArrayList(); + InventoryRoot.Add(InventoryRootHash); + userProfile.RootInventoryFolderID = inventData.RootFolderID; + + + // Inventory Library Section + Hashtable InventoryLibRootHash = new Hashtable(); + InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; + ArrayList InventoryLibRoot = new ArrayList(); + InventoryLibRoot.Add(InventoryLibRootHash); + + logResponse.InventoryLibRoot = InventoryLibRoot; + logResponse.InventoryLibraryOwner = GetLibraryOwner(); + logResponse.InventoryRoot = InventoryRoot; + logResponse.InventorySkeleton = AgentInventoryArray; + logResponse.InventoryLibrary = GetInventoryLibrary(); + + logResponse.CircuitCode = (Int32)Util.RandomClass.Next(); + logResponse.Lastname = userProfile.SurName; + logResponse.Firstname = userProfile.FirstName; + logResponse.AgentID = agentID; + logResponse.SessionID = userProfile.CurrentAgent.SessionID; + logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; + logResponse.Message = GetMessage(); + logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); + logResponse.StartLocation = startLocationRequest; + + try + { + CustomiseResponse(logResponse, userProfile, startLocationRequest); + } + catch (Exception ex) + { + m_log.Info("[LOGIN]: LLSD " + ex.ToString()); + return logResponse.CreateDeadRegionResponseLLSD(); + } + + userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; + CommitAgent(ref userProfile); + + // If we reach this point, then the login has successfully logged onto the grid + if (StatsManager.UserStats != null) + StatsManager.UserStats.AddSuccessfulLogin(); + + m_log.DebugFormat( + "[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.", + userProfile.FirstName, userProfile.SurName); + + return logResponse.ToLLSDResponse(); + } + catch (Exception ex) + { + m_log.Info("[LOGIN]: LLSD " + ex.ToString()); + return logResponse.CreateFailedResponseLLSD(); + } + } + } + finally + { + m_loginMutex.ReleaseMutex(); + } + } + + public Hashtable ProcessHTMLLogin(Hashtable keysvals) + { + // Matches all unspecified characters + // Currently specified,; lowercase letters, upper case letters, numbers, underline + // period, space, parens, and dash. + + Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]"); + + Hashtable returnactions = new Hashtable(); + int statuscode = 200; + + string firstname = String.Empty; + string lastname = String.Empty; + string location = String.Empty; + string region = String.Empty; + string grid = String.Empty; + string channel = String.Empty; + string version = String.Empty; + string lang = String.Empty; + string password = String.Empty; + string errormessages = String.Empty; + + // the client requires the HTML form field be named 'username' + // however, the data it sends when it loads the first time is 'firstname' + // another one of those little nuances. + + if (keysvals.Contains("firstname")) + firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999); + + if (keysvals.Contains("username")) + firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999); + + if (keysvals.Contains("lastname")) + lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999); + + if (keysvals.Contains("location")) + location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999); + + if (keysvals.Contains("region")) + region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999); + + if (keysvals.Contains("grid")) + grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999); + + if (keysvals.Contains("channel")) + channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999); + + if (keysvals.Contains("version")) + version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999); + + if (keysvals.Contains("lang")) + lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999); + + if (keysvals.Contains("password")) + password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999); + + // load our login form. + string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); + + if (keysvals.ContainsKey("show_login_form")) + { + UserProfileData user = GetTheUser(firstname, lastname); + bool goodweblogin = false; + + if (user != null) + goodweblogin = AuthenticateUser(user, password); + + if (goodweblogin) + { + UUID webloginkey = UUID.Random(); + m_userManager.StoreWebLoginKey(user.ID, webloginkey); + //statuscode = 301; + + // string redirectURL = "about:blank?redirect-http-hack=" + + // HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" + + // lastname + + // "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString()); + //m_log.Info("[WEB]: R:" + redirectURL); + returnactions["int_response_code"] = statuscode; + //returnactions["str_redirect_location"] = redirectURL; + //returnactions["str_response_string"] = "GoodLogin"; + returnactions["str_response_string"] = webloginkey.ToString(); + } + else + { + errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again"; + + loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); + returnactions["int_response_code"] = statuscode; + returnactions["str_response_string"] = loginform; + } + } + else + { + returnactions["int_response_code"] = statuscode; + returnactions["str_response_string"] = loginform; + } + return returnactions; + } + + public string GetLoginForm(string firstname, string lastname, string location, string region, + string grid, string channel, string version, string lang, + string password, string errormessages) + { + // inject our values in the form at the markers + + string loginform = String.Empty; + string file = Path.Combine(Util.configDir(), "http_loginform.html"); + if (!File.Exists(file)) + { + loginform = GetDefaultLoginForm(); + } + else + { + StreamReader sr = File.OpenText(file); + loginform = sr.ReadToEnd(); + sr.Close(); + } + + loginform = loginform.Replace("[$firstname]", firstname); + loginform = loginform.Replace("[$lastname]", lastname); + loginform = loginform.Replace("[$location]", location); + loginform = loginform.Replace("[$region]", region); + loginform = loginform.Replace("[$grid]", grid); + loginform = loginform.Replace("[$channel]", channel); + loginform = loginform.Replace("[$version]", version); + loginform = loginform.Replace("[$lang]", lang); + loginform = loginform.Replace("[$password]", password); + loginform = loginform.Replace("[$errors]", errormessages); + + return loginform; + } + + public string GetDefaultLoginForm() + { + string responseString = + ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += "OpenSim Login"; + responseString += "
"; + responseString += "
"; + + responseString += "
"; + + responseString += "
[$errors]
"; + responseString += "
"; + responseString += "First Name:"; + responseString += ""; + responseString += "
"; + responseString += "
"; + responseString += "Last Name:"; + responseString += ""; + responseString += "
"; + responseString += "
"; + responseString += "Password:"; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += "
"; + responseString += "
"; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += ""; + responseString += "
"; + responseString += ""; + responseString += "
"; + responseString += "
Connecting...
"; + + responseString += "
"; + + responseString += "
[$channel] | [$version]=[$lang]
"; + responseString += "
"; + responseString += ""; + responseString += "
"; + responseString += ""; + responseString += ""; + responseString += ""; + + return responseString; + } + + /// + /// Saves a target agent to the database + /// + /// The users profile + /// Successful? + public bool CommitAgent(ref UserProfileData profile) + { + return m_userManager.CommitAgent(ref profile); + } + + /// + /// Checks a user against it's password hash + /// + /// The users profile + /// The supplied password + /// Authenticated? + public virtual bool AuthenticateUser(UserProfileData profile, string password) + { + bool passwordSuccess = false; + //m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); + + // Web Login method seems to also occasionally send the hashed password itself + + // we do this to get our hash in a form that the server password code can consume + // when the web-login-form submits the password in the clear (supposed to be over SSL!) + if (!password.StartsWith("$1$")) + password = "$1$" + Util.Md5Hash(password); + + password = password.Remove(0, 3); //remove $1$ + + string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); + // Testing... + //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash); + //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password); + + passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) + || profile.PasswordHash.Equals(password, StringComparison.InvariantCultureIgnoreCase)); + + return passwordSuccess; + } + + public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey) + { + bool passwordSuccess = false; + m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); + + // Match web login key unless it's the default weblogin key UUID.Zero + passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero); + + return passwordSuccess; + } + + /// + /// + /// + /// + /// + public void CreateAgent(UserProfileData profile, XmlRpcRequest request) + { + m_userManager.CreateAgent(profile, request); + } + + public void CreateAgent(UserProfileData profile, OSD request) + { + m_userManager.CreateAgent(profile, request); + } + + /// + /// + /// + /// + /// + /// + public virtual UserProfileData GetTheUser(string firstname, string lastname) + { + return m_userManager.GetUserProfile(firstname, lastname); + } + + /// + /// + /// + /// + public virtual string GetMessage() + { + return m_welcomeMessage; + } + + private static LoginResponse.BuddyList ConvertFriendListItem(List LFL) + { + LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList(); + foreach (FriendListItem fl in LFL) + { + LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend); + buddyitem.BuddyID = fl.Friend; + buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms; + buddyitem.BuddyRightsGiven = (int)fl.FriendPerms; + buddylistreturn.AddNewBuddy(buddyitem); + } + return buddylistreturn; + } + + /// + /// Converts the inventory library skeleton into the form required by the rpc request. + /// + /// + protected virtual ArrayList GetInventoryLibrary() + { + Dictionary rootFolders + = m_libraryRootFolder.RequestSelfAndDescendentFolders(); + ArrayList folderHashes = new ArrayList(); + + foreach (InventoryFolderBase folder in rootFolders.Values) + { + Hashtable TempHash = new Hashtable(); + TempHash["name"] = folder.Name; + TempHash["parent_id"] = folder.ParentID.ToString(); + TempHash["version"] = (Int32)folder.Version; + TempHash["type_default"] = (Int32)folder.Type; + TempHash["folder_id"] = folder.ID.ToString(); + folderHashes.Add(TempHash); + } + + return folderHashes; + } + + /// + /// + /// + /// + protected virtual ArrayList GetLibraryOwner() + { + //for now create random inventory library owner + Hashtable TempHash = new Hashtable(); + TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; + ArrayList inventoryLibOwner = new ArrayList(); + inventoryLibOwner.Add(TempHash); + return inventoryLibOwner; + } + + public class InventoryData + { + public ArrayList InventoryArray = null; + public UUID RootFolderID = UUID.Zero; + + public InventoryData(ArrayList invList, UUID rootID) + { + InventoryArray = invList; + RootFolderID = rootID; + } + } + + protected void SniffLoginKey(Uri uri, Hashtable requestData) + { + string uri_str = uri.ToString(); + string[] parts = uri_str.Split(new char[] { '=' }); + if (parts.Length > 1) + { + string web_login_key = parts[1]; + requestData.Add("web_login_key", web_login_key); + m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key); + } + } + + /// + /// Customises the login response and fills in missing values. This method also tells the login region to + /// expect a client connection. + /// + /// The existing response + /// The user profile + /// The requested start location + /// true on success, false if the region was not successfully told to expect a user connection + public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) + { + // add active gestures to login-response + AddActiveGestures(response, theUser); + + // HomeLocation + RegionInfo homeInfo = null; + + // use the homeRegionID if it is stored already. If not, use the regionHandle as before + UUID homeRegionId = theUser.HomeRegionID; + ulong homeRegionHandle = theUser.HomeRegion; + if (homeRegionId != UUID.Zero) + { + homeInfo = GetRegionInfo(homeRegionId); + } + else + { + homeInfo = GetRegionInfo(homeRegionHandle); + } + + if (homeInfo != null) + { + response.Home = + string.Format( + "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", + (homeInfo.RegionLocX * Constants.RegionSize), + (homeInfo.RegionLocY * Constants.RegionSize), + theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + } + else + { + m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY); + // Emergency mode: Home-region isn't available, so we can't request the region info. + // Use the stored home regionHandle instead. + // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again + ulong regionX = homeRegionHandle >> 32; + ulong regionY = homeRegionHandle & 0xffffffff; + response.Home = + string.Format( + "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", + regionX, regionY, + theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + + m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", + theUser.FirstName, theUser.SurName, + regionX, regionY); + } + + // StartLocation + RegionInfo regionInfo = null; + if (startLocationRequest == "home") + { + regionInfo = homeInfo; + theUser.CurrentAgent.Position = theUser.HomeLocation; + response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; + } + else if (startLocationRequest == "last") + { + UUID lastRegion = theUser.CurrentAgent.Region; + regionInfo = GetRegionInfo(lastRegion); + response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + theUser.CurrentAgent.LookAt.Z.ToString() + "]"; + } + else + { + Regex reURI = new Regex(@"^uri:(?[^&]+)&(?\d+)&(?\d+)&(?\d+)$"); + Match uriMatch = reURI.Match(startLocationRequest); + if (uriMatch == null) + { + m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest); + } + else + { + string region = uriMatch.Groups["region"].ToString(); + regionInfo = RequestClosestRegion(region); + if (regionInfo == null) + { + m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region); + } + else + { + theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), + float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); + } + } + response.LookAt = "[r0,r1,r0]"; + // can be: last, home, safe, url + response.StartLocation = "url"; + } + + if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response))) + { + return true; + } + + // StartLocation not available, send him to a nearby region instead + // regionInfo = m_gridService.RequestClosestRegion(""); + //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); + + // Send him to default region instead + ulong defaultHandle = (((ulong)m_defaultHomeX * Constants.RegionSize) << 32) | + ((ulong)m_defaultHomeY * Constants.RegionSize); + + if ((regionInfo != null) && (defaultHandle == regionInfo.RegionHandle)) + { + m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); + return false; + } + + m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); + regionInfo = GetRegionInfo(defaultHandle); + + if (regionInfo == null) + { + m_log.ErrorFormat("[LOGIN]: No default region available. Aborting."); + return false; + } + + theUser.CurrentAgent.Position = new Vector3(128, 128, 0); + response.StartLocation = "safe"; + + return PrepareLoginToRegion(regionInfo, theUser, response); + } + + protected abstract RegionInfo RequestClosestRegion(string region); + protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle); + protected abstract RegionInfo GetRegionInfo(UUID homeRegionId); + protected abstract bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response); + + /// + /// Add active gestures of the user to the login response. + /// + /// + /// A + /// + /// + /// A + /// + protected void AddActiveGestures(LoginResponse response, UserProfileData theUser) + { + List gestures = m_inventoryService.GetActiveGestures(theUser.ID); + //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); + ArrayList list = new ArrayList(); + if (gestures != null) + { + foreach (InventoryItemBase gesture in gestures) + { + Hashtable item = new Hashtable(); + item["item_id"] = gesture.ID.ToString(); + item["asset_id"] = gesture.AssetID.ToString(); + list.Add(item); + } + } + response.ActiveGestures = list; + } + + /// + /// Get the initial login inventory skeleton (in other words, the folder structure) for the given user. + /// + /// + /// + /// This will be thrown if there is a problem with the inventory service + protected InventoryData GetInventorySkeleton(UUID userID) + { + List folders = m_inventoryService.GetInventorySkeleton(userID); + + // If we have user auth but no inventory folders for some reason, create a new set of folders. + if (folders == null || folders.Count == 0) + { + m_log.InfoFormat( + "[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID); + + // Although the create user function creates a new agent inventory along with a new user profile, some + // tools are creating the user profile directly in the database without creating the inventory. At + // this time we'll accomodate them by lazily creating the user inventory now if it doesn't already + // exist. + if (!m_inventoryService.CreateNewUserInventory(userID)) + { + throw new Exception( + String.Format( + "The inventory creation request for user {0} did not succeed." + + " Please contact your inventory service provider for more information.", + userID)); + } + + m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); + + folders = m_inventoryService.GetInventorySkeleton(userID); + + if (folders == null || folders.Count == 0) + { + throw new Exception( + String.Format( + "A root inventory folder for user {0} could not be retrieved from the inventory service", + userID)); + } + } + + UUID rootID = UUID.Zero; + ArrayList AgentInventoryArray = new ArrayList(); + Hashtable TempHash; + foreach (InventoryFolderBase InvFolder in folders) + { + if (InvFolder.ParentID == UUID.Zero) + { + rootID = InvFolder.ID; + } + TempHash = new Hashtable(); + TempHash["name"] = InvFolder.Name; + TempHash["parent_id"] = InvFolder.ParentID.ToString(); + TempHash["version"] = (Int32)InvFolder.Version; + TempHash["type_default"] = (Int32)InvFolder.Type; + TempHash["folder_id"] = InvFolder.ID.ToString(); + AgentInventoryArray.Add(TempHash); + } + + return new InventoryData(AgentInventoryArray, rootID); + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserLoginAuthService.cs b/OpenSim/Grid/UserServer.Modules/UserLoginAuthService.cs index a910136..4811434 100644 --- a/OpenSim/Grid/UserServer.Modules/UserLoginAuthService.cs +++ b/OpenSim/Grid/UserServer.Modules/UserLoginAuthService.cs @@ -1,224 +1,224 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text.RegularExpressions; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Services; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - - /// - /// Hypergrid login service used in grid mode. - /// - public class UserLoginAuthService : HGLoginAuthService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public UserConfig m_config; - private readonly IRegionProfileRouter m_regionProfileService; - - protected BaseHttpServer m_httpServer; - - public UserLoginAuthService( - UserManagerBase userManager, IInterServiceInventoryServices inventoryService, - LibraryRootFolder libraryRootFolder, - UserConfig config, string welcomeMess, IRegionProfileRouter regionProfileService) - : base(userManager, welcomeMess, inventoryService, null, true, libraryRootFolder, null) - { - m_config = config; - m_defaultHomeX = m_config.DefaultX; - m_defaultHomeY = m_config.DefaultY; - m_inventoryService = inventoryService; - m_regionProfileService = regionProfileService; - - NetworkServersInfo serversinfo = new NetworkServersInfo(1000, 1000); - serversinfo.GridRecvKey = m_config.GridRecvKey; - serversinfo.GridSendKey = m_config.GridSendKey; - serversinfo.GridURL = m_config.GridServerURL.ToString(); - serversinfo.InventoryURL = m_config.InventoryUrl.ToString(); - serversinfo.UserURL = m_config.AuthUrl.ToString(); - SetServersInfo(serversinfo); - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - httpServer.AddXmlRPCHandler("hg_login", XmlRpcLoginMethod); - httpServer.AddXmlRPCHandler("hg_new_auth_key", XmlRpcGenerateKeyMethod); - httpServer.AddXmlRPCHandler("hg_verify_auth_key", XmlRpcVerifyKeyMethod); - } - - - public override void LogOffUser(UserProfileData theUser, string message) - { - RegionProfileData SimInfo; - try - { - SimInfo = m_regionProfileService.RequestSimProfileData( - theUser.CurrentAgent.Handle, m_config.GridServerURL, - m_config.GridSendKey, m_config.GridRecvKey); - - if (SimInfo == null) - { - m_log.Error("[GRID]: Region user was in isn't currently logged in"); - return; - } - } - catch (Exception) - { - m_log.Error("[GRID]: Unable to look up region to log user off"); - return; - } - - // Prepare notification - Hashtable SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); - SimParams["region_secret2"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - ArrayList SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - - // Prepare notification - SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - //base.LogOffUser(theUser); - } - - protected override RegionInfo RequestClosestRegion(string region) - { - RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(region, - m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); - - if (profileData != null) - { - return profileData.ToRegionInfo(); - } - else - { - return null; - } - } - - protected override RegionInfo GetRegionInfo(ulong homeRegionHandle) - { - RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionHandle, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - if (profileData != null) - { - return profileData.ToRegionInfo(); - } - else - { - return null; - } - } - - protected override RegionInfo GetRegionInfo(UUID homeRegionId) - { - RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionId, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - if (profileData != null) - { - return profileData.ToRegionInfo(); - } - else - { - return null; - } - } - - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text.RegularExpressions; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Services; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Capabilities; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + + /// + /// Hypergrid login service used in grid mode. + /// + public class UserLoginAuthService : HGLoginAuthService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public UserConfig m_config; + private readonly IRegionProfileRouter m_regionProfileService; + + protected BaseHttpServer m_httpServer; + + public UserLoginAuthService( + UserManagerBase userManager, IInterServiceInventoryServices inventoryService, + LibraryRootFolder libraryRootFolder, + UserConfig config, string welcomeMess, IRegionProfileRouter regionProfileService) + : base(userManager, welcomeMess, inventoryService, null, true, libraryRootFolder, null) + { + m_config = config; + m_defaultHomeX = m_config.DefaultX; + m_defaultHomeY = m_config.DefaultY; + m_inventoryService = inventoryService; + m_regionProfileService = regionProfileService; + + NetworkServersInfo serversinfo = new NetworkServersInfo(1000, 1000); + serversinfo.GridRecvKey = m_config.GridRecvKey; + serversinfo.GridSendKey = m_config.GridSendKey; + serversinfo.GridURL = m_config.GridServerURL.ToString(); + serversinfo.InventoryURL = m_config.InventoryUrl.ToString(); + serversinfo.UserURL = m_config.AuthUrl.ToString(); + SetServersInfo(serversinfo); + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + httpServer.AddXmlRPCHandler("hg_login", XmlRpcLoginMethod); + httpServer.AddXmlRPCHandler("hg_new_auth_key", XmlRpcGenerateKeyMethod); + httpServer.AddXmlRPCHandler("hg_verify_auth_key", XmlRpcVerifyKeyMethod); + } + + + public override void LogOffUser(UserProfileData theUser, string message) + { + RegionProfileData SimInfo; + try + { + SimInfo = m_regionProfileService.RequestSimProfileData( + theUser.CurrentAgent.Handle, m_config.GridServerURL, + m_config.GridSendKey, m_config.GridRecvKey); + + if (SimInfo == null) + { + m_log.Error("[GRID]: Region user was in isn't currently logged in"); + return; + } + } + catch (Exception) + { + m_log.Error("[GRID]: Unable to look up region to log user off"); + return; + } + + // Prepare notification + Hashtable SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); + SimParams["region_secret2"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + ArrayList SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + + // Prepare notification + SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + //base.LogOffUser(theUser); + } + + protected override RegionInfo RequestClosestRegion(string region) + { + RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(region, + m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); + + if (profileData != null) + { + return profileData.ToRegionInfo(); + } + else + { + return null; + } + } + + protected override RegionInfo GetRegionInfo(ulong homeRegionHandle) + { + RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionHandle, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + if (profileData != null) + { + return profileData.ToRegionInfo(); + } + else + { + return null; + } + } + + protected override RegionInfo GetRegionInfo(UUID homeRegionId) + { + RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionId, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + if (profileData != null) + { + return profileData.ToRegionInfo(); + } + else + { + return null; + } + } + + } +} diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs index 56eb508..a521ead 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs @@ -184,7 +184,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage bool success = SynchronousRestObjectPoster.BeginPostObject( "POST", m_RestURL+"/SaveMessage/", im); - if(im.dialog == (byte)InstantMessageDialog.MessageFromAgent) + if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent) { IClientAPI client = FindClient(new UUID(im.fromAgentID)); if (client == null) diff --git a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneInventoryModule.cs b/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneInventoryModule.cs index 525dda7..a1306cd 100644 --- a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneInventoryModule.cs +++ b/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneInventoryModule.cs @@ -1,165 +1,165 @@ -/** - * Copyright (c) 2008, Contributors. All rights reserved. - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * * Neither the name of the Organizations nor the names of Individual - * Contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Services; -using Caps = OpenSim.Framework.Communications.Capabilities.Caps; -using LLSDHelpers = OpenSim.Framework.Communications.Capabilities.LLSDHelpers; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Servers.Interfaces; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Region.CoreModules.Communications.REST; - -using OpenMetaverse.StructuredData; - -namespace OpenSim.Region.CoreModules.Hypergrid -{ - public class HGStandaloneInventoryModule : IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private static bool initialized = false; - private static bool enabled = false; - - private bool m_doLookup = false; - Scene m_scene; - HGInventoryService m_inventoryService; - InventoryServiceBase m_inventoryBase; - - public bool DoLookup - { - get { return m_doLookup; } - set { m_doLookup = value; } - } - - #region IRegionModule interface - - public void Initialise(Scene scene, IConfigSource config) - { - if (!initialized) - { - initialized = true; - m_scene = scene; - - // This module is only on for standalones - enabled = !config.Configs["Startup"].GetBoolean("gridmode", true) && config.Configs["Startup"].GetBoolean("hypergrid", false); - } - } - - public void PostInitialise() - { - if (enabled) - { - m_log.Info("[HGStandaloneInvModule]: Starting..."); - //m_inventoryService = new InventoryService(m_scene); - m_inventoryBase = (InventoryServiceBase)m_scene.CommsManager.SecureInventoryService; - - m_inventoryService = new HGInventoryService(m_inventoryBase, - ((AssetServerBase)m_scene.CommsManager.AssetCache.AssetServer).AssetProviderPlugin, - (UserManagerBase)m_scene.CommsManager.UserService, m_scene.CommsManager.HttpServer, - m_scene.CommsManager.NetworkServersInfo.InventoryURL); - - AddHttpHandlers(m_scene.CommsManager.HttpServer); - m_inventoryService.AddHttpHandlers(); - } - } - - public void Close() - { - } - - public string Name - { - get { return "HGStandaloneInventoryModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - public virtual void AddHttpHandlers(IHttpServer httpServer) - { - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/GetInventory/", m_inventoryService.GetUserInventory, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/NewFolder/", m_inventoryBase.AddFolder, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/UpdateFolder/", m_inventoryBase.UpdateFolder, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/MoveFolder/", m_inventoryBase.MoveFolder, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/PurgeFolder/", m_inventoryBase.PurgeFolder, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/NewItem/", m_inventoryBase.AddItem, CheckAuthSession)); - - httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/DeleteItem/", m_inventoryBase.DeleteItem, CheckAuthSession)); - - } - - /// - /// Check that the source of an inventory request for a particular agent is a current session belonging to - /// that agent. - /// - /// - /// - /// - public bool CheckAuthSession(string session_id, string avatar_id) - { - return true; - } - - } - -} +/** + * Copyright (c) 2008, Contributors. All rights reserved. + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the Organizations nor the names of Individual + * Contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Services; +using Caps = OpenSim.Framework.Communications.Capabilities.Caps; +using LLSDHelpers = OpenSim.Framework.Communications.Capabilities.LLSDHelpers; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Servers.Interfaces; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.CoreModules.Communications.REST; + +using OpenMetaverse.StructuredData; + +namespace OpenSim.Region.CoreModules.Hypergrid +{ + public class HGStandaloneInventoryModule : IRegionModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static bool initialized = false; + private static bool enabled = false; + + private bool m_doLookup = false; + Scene m_scene; + HGInventoryService m_inventoryService; + InventoryServiceBase m_inventoryBase; + + public bool DoLookup + { + get { return m_doLookup; } + set { m_doLookup = value; } + } + + #region IRegionModule interface + + public void Initialise(Scene scene, IConfigSource config) + { + if (!initialized) + { + initialized = true; + m_scene = scene; + + // This module is only on for standalones + enabled = !config.Configs["Startup"].GetBoolean("gridmode", true) && config.Configs["Startup"].GetBoolean("hypergrid", false); + } + } + + public void PostInitialise() + { + if (enabled) + { + m_log.Info("[HGStandaloneInvModule]: Starting..."); + //m_inventoryService = new InventoryService(m_scene); + m_inventoryBase = (InventoryServiceBase)m_scene.CommsManager.SecureInventoryService; + + m_inventoryService = new HGInventoryService(m_inventoryBase, + ((AssetServerBase)m_scene.CommsManager.AssetCache.AssetServer).AssetProviderPlugin, + (UserManagerBase)m_scene.CommsManager.UserService, m_scene.CommsManager.HttpServer, + m_scene.CommsManager.NetworkServersInfo.InventoryURL); + + AddHttpHandlers(m_scene.CommsManager.HttpServer); + m_inventoryService.AddHttpHandlers(); + } + } + + public void Close() + { + } + + public string Name + { + get { return "HGStandaloneInventoryModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + + public virtual void AddHttpHandlers(IHttpServer httpServer) + { + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/GetInventory/", m_inventoryService.GetUserInventory, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/NewFolder/", m_inventoryBase.AddFolder, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/UpdateFolder/", m_inventoryBase.UpdateFolder, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/MoveFolder/", m_inventoryBase.MoveFolder, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/PurgeFolder/", m_inventoryBase.PurgeFolder, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/NewItem/", m_inventoryBase.AddItem, CheckAuthSession)); + + httpServer.AddStreamHandler( + new RestDeserialiseSecureHandler( + "POST", "/DeleteItem/", m_inventoryBase.DeleteItem, CheckAuthSession)); + + } + + /// + /// Check that the source of an inventory request for a particular agent is a current session belonging to + /// that agent. + /// + /// + /// + /// + public bool CheckAuthSession(string session_id, string avatar_id) + { + return true; + } + + } + +} diff --git a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs b/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs index 9e134be..f0e957b 100644 --- a/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs +++ b/OpenSim/Region/CoreModules/Hypergrid/HGStandaloneLoginModule.cs @@ -1,253 +1,253 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Text.RegularExpressions; -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Services; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Region.Framework.Interfaces; - -namespace OpenSim.Region.CoreModules.Hypergrid -{ - public class HGStandaloneLoginModule : IRegionModule, ILoginServiceToRegionsConnector - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected List m_scenes = new List(); - protected Scene m_firstScene; - - protected bool m_enabled = false; // Module is only enabled if running in standalone mode - - - public bool RegionLoginsEnabled - { - get - { - if (m_firstScene != null) - { - return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; - } - else - { - return false; - } - } - } - - protected HGLoginAuthService m_loginService; - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource source) - { - if (m_firstScene == null) - { - m_firstScene = scene; - - IConfig startupConfig = source.Configs["Startup"]; - if (startupConfig != null) - { - m_enabled = !startupConfig.GetBoolean("gridmode", false); - } - - if (m_enabled) - { - m_log.Debug("[HGLogin] HGlogin module enabled"); - bool authenticate = true; - string welcomeMessage = "Welcome to OpenSim"; - IConfig standaloneConfig = source.Configs["StandAlone"]; - if (standaloneConfig != null) - { - authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true); - welcomeMessage = standaloneConfig.GetString("welcome_message"); - } - - //TODO: fix casting. - LibraryRootFolder rootFolder = m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder; - - IHttpServer httpServer = m_firstScene.CommsManager.HttpServer; - - //TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference - m_loginService = new HGLoginAuthService((UserManagerBase)m_firstScene.CommsManager.UserService, welcomeMessage, m_firstScene.CommsManager.InterServiceInventoryService, m_firstScene.CommsManager.NetworkServersInfo, authenticate, rootFolder, this); - - httpServer.AddXmlRPCHandler("hg_login", m_loginService.XmlRpcLoginMethod); - httpServer.AddXmlRPCHandler("hg_new_auth_key", m_loginService.XmlRpcGenerateKeyMethod); - httpServer.AddXmlRPCHandler("hg_verify_auth_key", m_loginService.XmlRpcVerifyKeyMethod); - - } - } - - if (m_enabled) - { - AddScene(scene); - } - } - - public void PostInitialise() - { - - } - - public void Close() - { - - } - - public string Name - { - get { return "HGStandaloneLoginModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - protected void AddScene(Scene scene) - { - lock (m_scenes) - { - if (!m_scenes.Contains(scene)) - { - m_scenes.Add(scene); - } - } - } - - public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent) - { - return true; - } - - public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message) - { - Scene scene; - if (TryGetRegion(regionHandle, out scene)) - { - scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message); - } - } - - public RegionInfo RequestNeighbourInfo(ulong regionhandle) - { - Scene scene; - if (TryGetRegion(regionhandle, out scene)) - { - return scene.RegionInfo; - } - return null; - } - - public RegionInfo RequestClosestRegion(string region) - { - Scene scene; - if (TryGetRegion(region, out scene)) - { - return scene.RegionInfo; - } - return null; - } - - public RegionInfo RequestNeighbourInfo(UUID regionID) - { - Scene scene; - if (TryGetRegion(regionID, out scene)) - { - return scene.RegionInfo; - } - return null; - } - - protected bool TryGetRegion(ulong regionHandle, out Scene scene) - { - lock (m_scenes) - { - foreach (Scene nextScene in m_scenes) - { - if (nextScene.RegionInfo.RegionHandle == regionHandle) - { - scene = nextScene; - return true; - } - } - } - - scene = null; - return false; - } - - protected bool TryGetRegion(UUID regionID, out Scene scene) - { - lock (m_scenes) - { - foreach (Scene nextScene in m_scenes) - { - if (nextScene.RegionInfo.RegionID == regionID) - { - scene = nextScene; - return true; - } - } - } - - scene = null; - return false; - } - - protected bool TryGetRegion(string regionName, out Scene scene) - { - lock (m_scenes) - { - foreach (Scene nextScene in m_scenes) - { - if (nextScene.RegionInfo.RegionName == regionName) - { - scene = nextScene; - return true; - } - } - } - - scene = null; - return false; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Text.RegularExpressions; +using log4net; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Services; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Capabilities; +using OpenSim.Framework.Servers.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Interfaces; + +namespace OpenSim.Region.CoreModules.Hypergrid +{ + public class HGStandaloneLoginModule : IRegionModule, ILoginServiceToRegionsConnector + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected List m_scenes = new List(); + protected Scene m_firstScene; + + protected bool m_enabled = false; // Module is only enabled if running in standalone mode + + + public bool RegionLoginsEnabled + { + get + { + if (m_firstScene != null) + { + return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; + } + else + { + return false; + } + } + } + + protected HGLoginAuthService m_loginService; + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) + { + if (m_firstScene == null) + { + m_firstScene = scene; + + IConfig startupConfig = source.Configs["Startup"]; + if (startupConfig != null) + { + m_enabled = !startupConfig.GetBoolean("gridmode", false); + } + + if (m_enabled) + { + m_log.Debug("[HGLogin] HGlogin module enabled"); + bool authenticate = true; + string welcomeMessage = "Welcome to OpenSim"; + IConfig standaloneConfig = source.Configs["StandAlone"]; + if (standaloneConfig != null) + { + authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true); + welcomeMessage = standaloneConfig.GetString("welcome_message"); + } + + //TODO: fix casting. + LibraryRootFolder rootFolder = m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder; + + IHttpServer httpServer = m_firstScene.CommsManager.HttpServer; + + //TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference + m_loginService = new HGLoginAuthService((UserManagerBase)m_firstScene.CommsManager.UserService, welcomeMessage, m_firstScene.CommsManager.InterServiceInventoryService, m_firstScene.CommsManager.NetworkServersInfo, authenticate, rootFolder, this); + + httpServer.AddXmlRPCHandler("hg_login", m_loginService.XmlRpcLoginMethod); + httpServer.AddXmlRPCHandler("hg_new_auth_key", m_loginService.XmlRpcGenerateKeyMethod); + httpServer.AddXmlRPCHandler("hg_verify_auth_key", m_loginService.XmlRpcVerifyKeyMethod); + + } + } + + if (m_enabled) + { + AddScene(scene); + } + } + + public void PostInitialise() + { + + } + + public void Close() + { + + } + + public string Name + { + get { return "HGStandaloneLoginModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + + protected void AddScene(Scene scene) + { + lock (m_scenes) + { + if (!m_scenes.Contains(scene)) + { + m_scenes.Add(scene); + } + } + } + + public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent) + { + return true; + } + + public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message) + { + Scene scene; + if (TryGetRegion(regionHandle, out scene)) + { + scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message); + } + } + + public RegionInfo RequestNeighbourInfo(ulong regionhandle) + { + Scene scene; + if (TryGetRegion(regionhandle, out scene)) + { + return scene.RegionInfo; + } + return null; + } + + public RegionInfo RequestClosestRegion(string region) + { + Scene scene; + if (TryGetRegion(region, out scene)) + { + return scene.RegionInfo; + } + return null; + } + + public RegionInfo RequestNeighbourInfo(UUID regionID) + { + Scene scene; + if (TryGetRegion(regionID, out scene)) + { + return scene.RegionInfo; + } + return null; + } + + protected bool TryGetRegion(ulong regionHandle, out Scene scene) + { + lock (m_scenes) + { + foreach (Scene nextScene in m_scenes) + { + if (nextScene.RegionInfo.RegionHandle == regionHandle) + { + scene = nextScene; + return true; + } + } + } + + scene = null; + return false; + } + + protected bool TryGetRegion(UUID regionID, out Scene scene) + { + lock (m_scenes) + { + foreach (Scene nextScene in m_scenes) + { + if (nextScene.RegionInfo.RegionID == regionID) + { + scene = nextScene; + return true; + } + } + } + + scene = null; + return false; + } + + protected bool TryGetRegion(string regionName, out Scene scene) + { + lock (m_scenes) + { + foreach (Scene nextScene in m_scenes) + { + if (nextScene.RegionInfo.RegionName == regionName) + { + scene = nextScene; + return true; + } + } + } + + scene = null; + return false; + } + } +} diff --git a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs index dedd37f..f9059e0 100644 --- a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs +++ b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs @@ -66,18 +66,17 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture /// public void ReturnData(UUID id, byte[] data) { + DynamicTextureUpdater updater = null; - DynamicTextureUpdater updater = null; - - lock(Updaters) + lock (Updaters) { - if (Updaters.ContainsKey(id)) - { - updater = Updaters[id]; + if (Updaters.ContainsKey(id)) + { + updater = Updaters[id]; } } - if(updater != null) + if (updater != null) { if (RegisteredScenes.ContainsKey(updater.SimUUID)) { @@ -86,27 +85,26 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture } } - if(updater.UpdateTimer == 0) - { - lock(Updaters) - { - if (!Updaters.ContainsKey(updater.UpdaterID)) - { - Updaters.Remove(updater.UpdaterID); - } - } - } - + if (updater.UpdateTimer == 0) + { + lock (Updaters) + { + if (!Updaters.ContainsKey(updater.UpdaterID)) + { + Updaters.Remove(updater.UpdaterID); + } + } + } } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, - string extraParams, int updateTimer) + string extraParams, int updateTimer) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, - string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) + string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { if (RenderPlugins.ContainsKey(contentType)) { @@ -123,12 +121,12 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; - lock(Updaters) + lock (Updaters) { - if (!Updaters.ContainsKey(updater.UpdaterID)) - { - Updaters.Add(updater.UpdaterID, updater); - } + if (!Updaters.ContainsKey(updater.UpdaterID)) + { + Updaters.Add(updater.UpdaterID, updater); + } } RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); @@ -138,13 +136,13 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, - string extraParams, int updateTimer) + string extraParams, int updateTimer) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, - string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) + string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { if (RenderPlugins.ContainsKey(contentType)) { @@ -159,12 +157,12 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; - lock(Updaters) + lock (Updaters) { - if (!Updaters.ContainsKey(updater.UpdaterID)) - { - Updaters.Add(updater.UpdaterID, updater); - } + if (!Updaters.ContainsKey(updater.UpdaterID)) + { + Updaters.Add(updater.UpdaterID, updater); + } } RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); @@ -173,7 +171,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture return UUID.Zero; } - public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize, out double xSize, out double ySize) { @@ -307,7 +304,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture part.ScheduleFullUpdate(); scene.CommsManager.AssetCache.ExpireAsset(oldID); - } private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 3c1b87f..e32f1b4 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -4998,29 +4998,29 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (dir.x == 0) { - if (dir.y == 0) - { - // Direction vector is 0,0 so return - // false since we're staying in the sim - return 0; - } - else - { - // Y is the only valid direction - edge.y = dir.y / Math.Abs(dir.y); - } + if (dir.y == 0) + { + // Direction vector is 0,0 so return + // false since we're staying in the sim + return 0; + } + else + { + // Y is the only valid direction + edge.y = dir.y / Math.Abs(dir.y); + } } else { LSL_Float mag; - if (dir.x > 0) - { + if (dir.x > 0) + { mag = (Constants.RegionSize - pos.x) / dir.x; - } - else - { + } + else + { mag = (pos.x/dir.x); - } + } mag = Math.Abs(mag); @@ -5028,7 +5028,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (edge.y > Constants.RegionSize || edge.y < 0) { - // Y goes out of bounds first + // Y goes out of bounds first edge.y = dir.y / Math.Abs(dir.y); } else @@ -5039,18 +5039,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } } - List neighbors = World.CommsManager.GridService.RequestNeighbours(World.RegionInfo.RegionLocX, World.RegionInfo.RegionLocY); + List neighbors = World.CommsManager.GridService.RequestNeighbours(World.RegionInfo.RegionLocX, World.RegionInfo.RegionLocY); - uint neighborX = World.RegionInfo.RegionLocX + (uint)dir.x; - uint neighborY = World.RegionInfo.RegionLocY + (uint)dir.y; - - foreach (SimpleRegionInfo sri in neighbors) - { - if (sri.RegionLocX == neighborX && sri.RegionLocY == neighborY) - return 0; - } + uint neighborX = World.RegionInfo.RegionLocX + (uint)dir.x; + uint neighborY = World.RegionInfo.RegionLocY + (uint)dir.y; + + foreach (SimpleRegionInfo sri in neighbors) + { + if (sri.RegionLocX == neighborX && sri.RegionLocY == neighborY) + return 0; + } - return 1; + return 1; } /// diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/Timer.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/Timer.cs index 09351fd..5353fc9 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/Timer.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/Timer.cs @@ -49,7 +49,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins { return localID.ToString() + itemID.ToString(); } - private class TimerClass { diff --git a/bin/HttpServer_OpenSim.xml b/bin/HttpServer_OpenSim.xml index a9ac538..747f35d 100644 --- a/bin/HttpServer_OpenSim.xml +++ b/bin/HttpServer_OpenSim.xml @@ -1,7019 +1,7019 @@ - - - - HttpServer_OpenSim - - - - - Cookies that should be set. - - - - - Adds a cookie in the collection. - - cookie to add - cookie is null - - - - Copy a request cookie - - - When the cookie should expire - - - - Gets a collection enumerator on the cookie list. - - collection enumerator - - - - Remove all cookies - - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Gets the count of cookies in the collection. - - - - - Gets the cookie of a given identifier (null if not existing). - - - - - Generates C#/HTML from HAML code. - - HAML documentation: http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html - - - - A code generator is used to convert template code to something that we can - work with, as HTML or c# code. - - - - - - Generate C# code from the template. - - A that the generated code will be written to. - If the template have not been parsed first. - If template is incorrect - - - - Parse a file and convert into to our own template object code. - - Path and filename to a template - If something is incorrect in the template. - - - - - - - - - Parse a file and convert into to our own template object code. - - A containing our template - If something is incorrect in the template. - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - The log writer. - - - - Check and validate indentation - - line to check - number of white spaces - number of indentations (2 white spaces = 1 intend, 1 tab = 1 intend) - - - - Check indentation - - fills line with intend info - - - - check if current line is a multi line - - previous line - current line - - - - Generate HTML code from the template. - Code is encapsulated in <% and <%= - - A that the generated code will be written to. - If the template have not been parsed first. - If template is incorrect - - - - Get the first word (letters and digits only) from the specified offset. - - - - - - - - Check indentation / node placement - - - - - Parse a node - todo: improve doc - - - - - - - - - PreParse goes through the text add handles indentation - and all multi line cases. - - Reader containing the text - - - - print the entire document - - - - - Print line information to the console - - - - - - Read next line from file - - true if line could be read; false if EOF. - - - - Generates a string with spaces. - - number of spaces. - string of spaces. - - - - Parse a file and convert into to our own template object code. - - Path and filename to a template - If something is incorrect in the template. - - - - - - - - - - Parse a file and convert into to our own template object code. - - A containing our template - If something is incorrect in the template. - - - - Generate C# code from the template. - - A that the generated code will be written to. - If the template have not been parsed first. - If template is incorrect - - - - Property to retrieve the root node for the latest parsed document - - - - - Class to make dynamic binding of redirects. Instead of having to specify a number of similar redirect rules - a regular expression can be used to identify redirect urls and thier targets. - - - [a-z0-9]+)", "/users/${target}?find=true", RegexOptions.IgnoreCase) - ]]> - - - - - redirects from one url to another. - - - - - Rules are used to perform operations before a request is being handled. - Rules can be used to create routing etc. - - - - - Process the incoming request. - - incoming http request - outgoing http response - true if response should be sent to the browser directly (no other rules or modules will be processed). - - returning true means that no modules will get the request. Returning true is typically being done - for redirects. - - If request or response is null. - - - - Initializes a new instance of the class. - - Absolute path (no servername) - Absolute path (no servername) - - server.Add(new RedirectRule("/", "/user/index")); - - - - - Initializes a new instance of the class. - - Absolute path (no servername) - Absolute path (no servername) - true if request should be redirected, false if the request uri should be replaced. - - server.Add(new RedirectRule("/", "/user/index")); - - - - - Process the incoming request. - - incoming http request - outgoing http response - true if response should be sent to the browser directly (no other rules or modules will be processed). - - returning true means that no modules will get the request. Returning true is typically being done - for redirects. - - - - - string to match request url with. - - Is compared to request.Uri.AbsolutePath - - - - Where to redirect. - - - - - true if we should redirect. - - - false means that the rule will replace - the current request uri with the new one from this class. - - - - - Initializes a new instance of the class. - - Expression to match url - Expression to generate url - - [a-zA-Z0-9]+)", "/user/${first}")); - Result of ie. /employee1 will then be /user/employee1 - ]]> - - - - - Initializes a new instance of the class. - - Expression to match url - Expression to generate url - Regular expression options to use, can be null - - [a-zA-Z0-9]+)", "/user/{first}", RegexOptions.IgnoreCase)); - Result of ie. /employee1 will then be /user/employee1 - ]]> - - - - - Initializes a new instance of the class. - - Expression to match url - Expression to generate url - Regular expression options to apply - true if request should be redirected, false if the request uri should be replaced. - - [a-zA-Z0-9]+)", "/user/${first}", RegexOptions.None)); - Result of ie. /employee1 will then be /user/employee1 - ]]> - - - - - Process the incoming request. - - incoming http request - outgoing http response - true if response should be sent to the browser directly (no other rules or modules will be processed). - - returning true means that no modules will get the request. Returning true is typically being done - for redirects. - - If request or response is null - - - - Interface used to load templates from different sources. - - - - - Load a template into a and return it. - - Relative path (and filename) to template. - a if file was found; otherwise null. - - - - Fetch all files from the resource that matches the specified arguments. - - Where the file should reside. - Files to check - a list of files if found; or an empty array if no files are found. - - - - Check's whether a template should be reloaded or not. - - template information - true if template is OK; false if it do not exist or are old. - - - - Returns whether or not the loader has an instance of the file requested - - The name of the template/file - True if the loader can provide the file - - - - Webhelper provides helpers for common tasks in HTML. - - - - - Used to let the website use different javascript libraries. - Default is - - - - - Creates a link that invokes through ajax. - - url to fetch - link title - - optional options in format "key, value, key, value". - Javascript options starts with ':'. - - a link tag - - WebHelper.AjaxRequest("/users/add/", "Add user", "method:", "post", "onclick", "validate('this');"); - - - - - Builds a link that updates an element with the fetched ajax content. - - Url to fetch content from - link title - html element to update with the results of the ajax request. - optional options in format "key, value, key, value" - A link tag. - - - - A link that pop ups a Dialog (overlay div) - - url to contents of dialog - link title - name/value of html attributes. - A "a"-tag that popups a dialog when clicked - - WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); - - - - - Create/Open a dialog box using ajax - - - - - - - - - Close a javascript dialog window/div. - - javascript for closing a dialog. - - - - - Create a <form> tag. - - name of form - action to invoke on submit - form should be posted as ajax - html code - - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); - - - - - Create a link tag. - - url to go to - link title (text that is displayed) - html attributes, name, value, name, value - html code - - WebHelper.Link("/user/show/1", "Show user", "id", "showUser", "onclick", "return confirm('Are you shure?');"); - - - - - Build a link - - url to go to. - title of link (displayed text) - extra html attributes. - a complete link - - - - Build a link - - url to go to. - title of link (displayed text) - extra html attributes. - a complete link - more options - - - - Obsolete - - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - - - - Obsolete - - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - - - - Render errors into a UL with class "errors" - - class used by UL-tag. - items to list - an unordered html list. - - - - Render errors into a UL with class "errors" - - class used by UL-tag. - items to list - an unordered html list. - - - - Render errors into a UL with class "errors" - - - - - - - Generates a list with html attributes. - - StringBuilder that the options should be added to. - attributes set by user. - attributes set by any of the helper classes. - - - - Generates a list with html attributes. - - StringBuilder that the options should be added to. - - - - - Purpose of this class is to create a javascript toolkit independent javascript helper. - - - - - Generates a list with JS options. - - StringBuilder that the options should be added to. - the javascript options. name, value pairs. each string value should be escaped by YOU! - true if we should start with a comma. - - - - Removes any javascript parameters from an array of parameters - - The array of parameters to remove javascript params from - An array of html parameters - - - - javascript action that should be added to the "onsubmit" event in the form tag. - - - All javascript option names should end with colon. - - - JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); - - - - - - Requests a url through ajax - - url to fetch - optional options in format "key, value, key, value", used in JS request object. - a link tag - All javascript option names should end with colon. - - - JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); - - - - - - Ajax requests that updates an element with - the fetched content - - Url to fetch content from - element to update - optional options in format "key, value, key, value", used in JS updater object. - A link tag. - All javascript option names should end with colon. - - - JSHelper.AjaxUpdater("/user/show/1", "userInfo", "onsuccess:", "alert('Successful!');"); - - - - - - A link that pop ups a Dialog (overlay div) - - url to contents of dialog - link title - A "a"-tag that popups a dialog when clicked - name/value of html attributes - - WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); - - - - - Close a javascript dialog window/div. - - javascript for closing a dialog. - - - - - Creates a new modal dialog window - - url to open in window. - window title (may not be supported by all js implementations) - - - - - - Contains a connection to a browser/client. - - - - - Contains a connection to a browser/client. - - - - - Disconnect from client - - error to report in the delegate. - - - - Send a response. - - Either HttpHelper.HTTP10 or HttpHelper.HTTP11 - http status code - reason for the status code. - html body contents, can be null or empty. - If httpVersion is invalid. - - - - Send a response. - - Either HttpHelper.HTTP10 or HttpHelper.HTTP11 - http status code - reason for the status code. - - - - Send a response. - - - - - - send a whole buffer - - buffer to send - - - - - Send data using the stream - - Contains data to send - Start position in buffer - number of bytes to send - - - - - - Using SSL or other encryption method. - - - - - Buffersize determines how large the HTTP header can be. - - - - - Initializes a new instance of the class. - - true if the connection is secured (SSL/TLS) - client that connected. - delegate handling incoming requests. - delegate being called when a client disconnectes - Stream used for communication - If beginreceive fails - delegate used to write log entries - - - - - - Initializes a new instance of the class. - - true if the connection is secured (SSL/TLS) - delegate handling incoming requests. - client that connected - Stream used for communication - If beginreceive fails - - - - - - Disconnect from client - - error to report in the delegate. - - - - This method checks the request if a responde to 100-continue should be sent. - - - 100 continue is a value in the Expect header. - It's used to let the webserver determine if a request can be handled. The client - waits for a reply before sending the body. - - - - - Send a response. - - Either HttpHelper.HTTP10 or HttpHelper.HTTP11 - http status code - reason for the status code. - html body contents, can be null or empty. - If httpVersion is invalid. - - - - Send a response. - - Either HttpHelper.HTTP10 or HttpHelper.HTTP11 - http status code - reason for the status code. - - - - Send a response. - - - - - - send a whole buffer - - buffer to send - - - - - Send data using the stream - - Contains data to send - Start position in buffer - number of bytes to send - - - - - - Using SSL or other encryption method. - - - - - Client have been disconnected. - - Client that was disconnected. - Reason - - - - - Invoked when a client context have received a new HTTP request - - Client that received the request. - Request that was received. - - - - - A controller module is a part of the ModelViewController design pattern. - It gives you a way to create user friendly URLs. - - - The controller module uses the flyweight pattern which means that - the memory usage will continue to increase until the module have - enough objects in memory to serve all concurrent requests. The objects - are reused and will not be freed. - - - - ControllerModule module = new ControllerModule(); - module.Add(new UserController()); - module.Add(new SearchController()); - myWebsite.Add(module); - - - - - - A HttpModule can be used to serve urls. The module itself - decides if it should serve a url or not. In this way, you can - get a very flexible http app since you can let multiple modules - serve almost similiar urls. - - - Throw UnauthorizedException if you are using a AuthenticationModule and want to prompt for username/password. - - - - - Method that process the url - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - true if this module handled the request. - - - - Set the log writer to use. - - logwriter to use. - - - - Log something. - - importance of log message - message - - - - If true specifies that the module doesn't consume the processing of a request so that subsequent modules - can continue processing afterwards. Default is false. - - - - - The controller module uses the prototype design pattern - to be able to create new controller objects for requests - if the stack is empty. - - A prototype which will be cloned for each request - - If a controller with that name have been added already. - - - - Method that process the incoming request. - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - - - - Get a prototype - - in lowercase, without "Controller" - The controller if found; otherwise null. - - - //fetches the class UserController - RequestController userController = controllerModule["user"]; - - - - - - Initializes a new instance of the class. - - A controller used to handle certain URLs. Will be cloned for each parallel request. - - - - Retrieve a previously created controller (or a new one if none exist). - - - - - - Add a controller - - - - - - Prototype controller used for cloning. - - The prototype. - - - - Will contain helper functions for javascript. - - - - - Requests a url through ajax - - url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. - optional options in format "key, value, key, value", used in JS request object. All keys should end with colon. - a link tag - onclick attribute is used by this method. - - - // plain text - JSHelper.AjaxRequest("'/user/show/1'"); - - // ajax request using this.href - string link = "<a href=\"/user/call/1\" onclick=\"" + JSHelper.AjaxRequest("this.href") + "/<call user</a>"; - - - - - - Ajax requests that updates an element with - the fetched content - - url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. - element to update - options in format "key, value, key, value". All keys should end with colon. - A link tag. - - - JSHelper.AjaxUpdater("'/user/show/1'", "user", "onsuccess:", "alert('hello');", "asynchronous:", "true"); - - - - - - Opens contents in a dialog window. - - url to contents of dialog - link title - name, value, name, value, all parameter names should end with colon. - - - - Close a javascript dialog window/div. - - javascript for closing a dialog. - - - - - Delegate used by to populate select options. - - current object (for instance a User). - Text that should be displayed in the value part of a <optiongt;-tag. - Text shown in the select list. - - // Class that is going to be used in a SELECT-tag. - public class User - { - private readonly string _realName; - private readonly int _id; - public User(int id, string realName) - { - _id = id; - _realName = realName; - } - public string RealName - { - get { return _realName; } - } - - public int Id - { - get { return _id; } - } - } - - // Using an inline delegate to generate the select list - public void UserInlineDelegate() - { - List<User> items = new List<User>(); - items.Add(new User(1, "adam")); - items.Add(new User(2, "bertial")); - items.Add(new User(3, "david")); - string htmlSelect = Select("users", "users", items, delegate(object o, out object id, out object value) - { - User user = (User)o; - id = user.Id; - value = user.RealName; - }, 2, true); - } - - // Using an method as delegate to generate the select list. - public void UseExternalDelegate() - { - List<User> items = new List<User>(); - items.Add(new User(1, "adam")); - items.Add(new User(2, "bertial")); - items.Add(new User(3, "david")); - string htmlSelect = Select("users", "users", items, UserOptions, 1, true); - } - - // delegate returning id and title - public static void UserOptions(object o, out object id, out object title) - { - User user = (User)o; - id = user.Id; - value = user.RealName; - } /// - - - - Methods marked with BeforeFilter will be invoked before each request. - - - BeforeFilters should take no arguments and return false - if controller method should not be invoked. - - - - - - Initializes a new instance of the class. - - - BeforeFilters should take no arguments and return false - if controller method should not be invoked. - - - - - Initializes a new instance of the class. - - Specify if the filter should be invoked among the first filters, in between or among the last. - - BeforeFilters should take no arguments and return false - if controller method should not be invoked. - - - - - Filters position in before filter queue - - - - - Determins when a before filter is executed. - - - - - - Filter will be invoked first (unless another filter is added after this one with the First position) - - - - - Invoke after all first filters, and before the last filters. - - - - - Filter will be invoked last (unless another filter is added after this one with the Last position) - - - - - The "basic" authentication scheme is based on the model that the - client must authenticate itself with a user-ID and a password for - each realm. The realm value should be considered an opaque string - which can only be compared for equality with other realms on that - server. The server will service the request only if it can validate - the user-ID and password for the protection space of the Request-URI. - There are no optional authentication parameters. - - - - - Authentication modules are used to implement different - kind of http authentication. - - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - Delegate used to determine if authentication is required (may be null). - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - - - - Create a response that can be sent in the WWW-Authenticate header. - - Realm that the user should authenticate in - Array with optional options. - A correct auth request. - If realm is empty or null. - - - - An authentication response have been received from the web browser. - Check if it's correct - - Contents from the Authorization header - Realm that should be authenticated - GET/POST/PUT/DELETE etc. - options to specific implementations - Authentication object that is stored for the request. A user class or something like that. - if authenticationHeader is invalid - If any of the paramters is empty or null. - - - - Used to invoke the auth delegate that is used to lookup the username/realm. - - Realm (domain) that user want to authenticate in - Username - Password used for validation. Some implementations got password in clear text, they are then sent to client. - object that will be stored in the request to help you identify the user if authentication was successful. - true if authentication was successful - - - - Determines if authentication is required. - - Http request from browser - true if user should be authenticated. - throw ForbiddenException from your delegate if no more attempts are allowed. - If no more attempts are allowed - - - - name used in http request. - - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - Delegate used to determine if authentication is required (may be null). - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - - - - Create a response that can be sent in the WWW-Authenticate header. - - Realm that the user should authenticate in - Not used in basic auth - A correct auth request. - - - - An authentication response have been received from the web browser. - Check if it's correct - - Contents from the Authorization header - Realm that should be authenticated - GET/POST/PUT/DELETE etc. - Not used in basic auth - Authentication object that is stored for the request. A user class or something like that. - if authenticationHeader is invalid - If any of the paramters is empty or null. - - - - name used in http request. - - - - - The follow node allows users to display code in a haml document - - - #main Welcome =user.FirstName - - - - - Child nodes may not be the first node on a line - - - - - A node represents a controller code and contents. For example a html tag, an attribute list or something else. - - - - - Add a new node - - parent node. - - - - Modifiers are used to modify the first node on the line. - Typical modifiers are attribute lists, class names and IDs. - - Modifier node - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - First node on line, used since some nodes cannot exist on their own on a line. - - - - Generate HTML code (with ASP tags) - - - - - - Converts the node to c# code - - true if we are inside the internal stringbuilder - c# code - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - c# code - - - - Generate C# code of the node - - true if we are inside the internal stringbuilder - code is small enough to fit on one row. - smallEnough is a default value, recalc it - c# code - - - - Get intendation level for this node. - - - - - - Returns true if the node is applicable after another node as text instead of being applied as a modifier - - - - - Count our children and our childrens children and so on... - - - - - All child nodes for this node. - - - - - Should only be set for each parent. - - - - - Modifiers are used to modify the first node on the line. - Typical modifiers are attribute lists, class names and IDs. - - - - - Last modifier for this node - - - - - - Number of modifiers for this line. - - - - - Parent node. - - - - - Child nodes may not be the first node on a line - - parent node - - - - Creates a DIV node and add's the specified node to it. - - Contains all prototypes for each control char. used to instanciate new nodes. - parent node - current line information - node to add to the DIV node - current node - - - - Get endposition for this modifier. - - where to start searching - contents of the current line - char that tells us that this is the end position - index on the current line - - - - Get endposition for this modifier. - - where to start searching - contents of the current line - index on the current line - - - - This is a plain text node - - - - - Contains C# code that will be rendered into the view. - - Parent node - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line - - - - Generate HTML for this node (with asp tags for code) - - - - - - = is placed at the end of a tag definition, after class, id, and attribute declarations. - It’s just a shortcut for inserting Ruby code into an element. It works the same as = without a tag: - it inserts the result of the Ruby code into the template. - However, if the result is short enough, it is displayed entirely on one line. - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - Determines if this is a textnode (containg plain text) - - - - - Contains HTML attributes. - - - - - Create a new node - - parent node - collection of attributes - - - - create an attribute node - - parent node - - - - Get an attribute - - name of the attribute (case sensitive) - attribute if found; otherwise null. - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - html attributes - - - - - A attribute - - - - - value is a simple word or quoted text - - - - - Name of the attribute - - - - - Value, can be a statement, variable or quoted text. - - - - - Arguments being used in a template. - - - - - - - Holds the arguments connected to their names for quick access. - (since the ArgumentContainer also holds the name for the argument the mapping with strings is somewhat redundant - but since the data do 'belong' to the ArgumentContainer this solution was chosen to speed up access) - - - - - Initializes the class without any set arguments. - - - - - Initializes the class with all the arguments of the parameter class. - - Cannot be null - If arguments is null - - - - Initializes the class with the objects in the parameterlist. - Note that each object that is null must be followed by a type. - - Should contain ordered pairs/truples of string, object and type where type is optional if the object isn´t null - new TemplateArguments("Dir", "\", "Users", null, typeof(User)); - If optional type differs from type of object (if object != null) or argument name is duplicate - If the order of objects is incorrect - If any argument name or type is null - - - - A function that merges two argument holders updating and adding values - - - If arguments is null - - - - Clears added arguments - - - - - Adds an argument. - (Will throw ArgumentException on duplicates since adding an argument twice points to incorrect code, for ways around - this - - Cannot be null - Cannot be null - If argumentName or argumentObject is null - If an argument named argumentName already exists - - - - Adds an argument. Allows for argumentObject to be null - (Will throw ArgumentException - - Cannot be null - - Cannot be null - If argumentName or argumentType is null - If an argument named argumentName already exists or argumentObject != null and typeof(argumentObject) differs from argumentType - - - - Updates an already added argument - - Cannot be null - Cannot be null - If no argument named argumentName exists - If argumentName or argumentObject is null - - - - Updates an already added argument, allows for argumentObject to be null - - Cannot be null - - Cannot be null - If argumentName or argumentType is null - If an argument named argumentName doesn´t exists or argumentObject != null and typeof(argumentObject) differs from argumentType - - - - Clears all added arguments - - - - - Retrieves the arguments - (Does so now by copying the values to a new array, could be optimized?) - - An array containing arguments with name, object and type - - - - Returns a individual hashcode built upon the specified types the class is holding - - The hashcode is made by joining the typenames of all held arguments and making a string hashcode from them - - - - - Retrieves a concated typename ie DictinaryInt32String - - The type to retrieve the name for - - - - Checks whether a specific argument is specified or not. - - Argument name - true if argument is specified; otherwise false. - - - - Function to make it possible to index out known arguments - - The name of an added argument - Null if no ArgumentContainer by name was found - - - - A container class grouping mapping name, argument type and the argument object - - - - - Contains the name mapped to the argument - - - - - Contains the type of the argument, this must be valid if _argumentObject is null - - - - - Holds the actual object - - - - - Constructor to initiate an ArgumentContainer, will set the ArgumentType to the value of the argumentObject's type - - Cannot be null - Cannot be null - If argumentName or argumentObject is null - - - - Alternative constructor allowing argumentObject parameter to be null - - Cannot be null - - Cannot be null - If argumentName or argumentType is null - If argumentObject != null and argumentType != typeof(argumentObject) - - - - Sets the object and type of the argument, equal to ArgumentContainer.Object = ... - - Cannot be null - If argumentObject is null - - - - Sets the argument object and type. Type of the object and argumentType must correspond. - - - Cannot be null - If argumentType is null - If typeof(argumentObject) differs from argumentType and object != null - - - - Attribute for retrieving the name. The name cannot be set however because an argument is defined by its name - changing the name would be changing the arguments meaning, thus an argument needing a name change should rather - be recreated - - - - - Returns the type of the argument object. The property cannot be set since the type depends on and must correspond to - the type of the object - - - - - Returns or changes the argument object. If the object is to be changed to null the type must be passed aswell, - in that case - - If set value is null - - - - A partial is a HAML template that is inserted into other HAML templates. - - - - - Contains the page/controller target for the partial. - The PartialNode should be written as follows: - ex. - - _"requestedpage"{parametername="parametervalue",parametername2=parameter2,parametername3=parameter3:typeof(parameter3type)} - - - - - create a new partial node. - - parent node - - - - Determines if this node can handle the line (by checking the first word); - - Controller char (word) - True if text belongs to this node type - First node on line. - - - - Parse node contents add return a fresh node. - - Node that this is a subnode to. Can be null - A list with node types - Line to parse - Where to start the parsing. Will be set to where the next node should start parsing - A node corresponding to the bla bla; null if parsing failed. - - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - Helper function to retrieve the code for the partial request - - A string representing the code for invocating a render of the partial - - - - Throw an exception with predefined information - - why the exception was thrown - - - - This is a plain text node - - - - - Returns the page/controller target for the node - - - - - Loads templates from embedded resources. - - - - - Loads templates from a namespace in the given assembly to an uri - - The uri to map the resources to - The assembly in which the resources reside - The namespace from which to load the resources - - resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); - - will make ie the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ - - - - - Load a template into a and return it. - - Relative path (and filename) to template. - - a if file was found; otherwise null. - - - - - Fetch all files from the resource that matches the specified arguments. - - Where the file should reside. - Files to check - - a list of files if found; or an empty array if no files are found. - - - - - Always returns true since a resource won't be updated during execution - - - - - - - Returns whether or not the loader has an instance of the file requested - - The name of the template/file - True if the loader can provide the file - - - - Priority for log entries - - - - - - Very detailed logs to be able to follow the flow of the program. - - - - - Logs to help debug errors in the application - - - - - Information to be able to keep track of state changes etc. - - - - - Something did not go as we expected, but it's no problem. - - - - - Something that should not fail failed, but we can still keep - on going. - - - - - Something failed, and we cannot handle it properly. - - - - - Interface used to write to log files. - - - - - Write an entry to the log file. - - object that is writing to the log - importance of the log message - the message - - - - This class writes to the console. It colors the output depending on the logprio and includes a 3-level stacktrace (in debug mode) - - - - - - The actual instance of this class. - - - - - Logwriters the specified source. - - object that wrote the logentry. - Importance of the log message - The message. - - - - Get color for the specified logprio - - prio for the log entry - A for the prio - - - - Default log writer, writes everything to null (nowhere). - - - - - - The logging instance. - - - - - Writes everything to null - - object that wrote the logentry. - Importance of the log message - The message. - - - - Contains some kind of input from the browser/client. - can be QueryString, form data or any other request body content. - - - - - Base class for request data containers - - - - - Adds a parameter mapped to the presented name - - The name to map the parameter to - The parameter value - - - - Returns true if the container contains the requested parameter - - Parameter id - True if parameter exists - - - - Returns a request parameter - - The name associated with the parameter - - - - Representation of a non-initialized class instance - - - Variable telling the class that it is non-initialized - - - - Initializes a new instance of the class. - - form name. - - - - Initializes a new instance of the class. - - form name. - if set to true all changes will be ignored. - this constructor should only be used by Empty - - - Creates a deep copy of the HttpInput class - The object to copy - The function makes a deep copy of quite a lot which can be slow - - - - Add a new element. Form array elements are parsed - and added in a correct hierachy. - - Name is converted to lower case. - - - - - Returns true if the class contains a HttpInput value with the corresponding name - - The field/querystring name - True if the value exists - - - - Parses an item and returns it. - This function is primarly used to parse array items as in user[name]. - - - - - - - Outputs the instance representing all its values joined together - - - - Returns all items as an unescaped query string. - - - - - Extracts one parameter from an array - - Containing the string array - All but the first value - - string test1 = ExtractOne("system[user][extension][id]"); - string test2 = ExtractOne(test1); - string test3 = ExtractOne(test2); - // test1 = user[extension][id] - // test2 = extension[id] - // test3 = id - - - - Resets all data contained by class - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Returns an enumerator that iterates through a collection. - - - - An object that can be used to iterate through the collection. - - 2 - - - - Form name as lower case - - - - - Get a form item. - - - Returns HttpInputItem.Empty if item was not found. - - - - Returns item either from a form or a query string (checks them in that order) - - - - Representation of a non-initialized HttpParam - - - Initialises the class to hold a value either from a post request or a querystring request - - - - The add method is not availible for HttpParam - since HttpParam checks both Request.Form and Request.QueryString - - name identifying the value - value to add - - - - - Checks whether the form or querystring has the specified value - - Name, case sensitive - true if found; otherwise false. - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Returns an enumerator that iterates through a collection. - - - - An object that can be used to iterate through the collection. - - 2 - - - - Fetch an item from the form or querystring (in that order). - - - Item if found; otherwise HttpInputItem.EmptyLanguageNode - - - - Container class for posted files - - - - - Creates a container for a posted file - - The identifier of the post field - The file path - The content type of the file - The name of the file uploaded - If any parameter is null or empty - - - - Creates a container for a posted file - - If any parameter is null or empty - - - Destructor disposing the file - - - - Deletes the temporary file - - True if manual dispose - - - - Disposing interface, cleans up managed resources (the temporary file) and suppresses finalization - - - - - The name/id of the file - - - - - The full file path - - - - - The name of the uploaded file - - - - - The type of file - - - - - The object form class takes an object and creates form items for it. - - - - - Initializes a new instance of the class. - - - form name *and* id. - action to do when form is posted. - - - - - Initializes a new instance of the class. - - form name *and* id. - action to do when form is posted. - object to get values from - - - - Initializes a new instance of the class. - - form action. - object to get values from. - - - - write out the FORM-tag. - - generated html code - - - - Writeout the form tag - - form should be posted through ajax. - generated html code - - - - Generates a text box. - - - - generated html code - - - - password box - - - - generated html code - - - - Hiddens the specified property name. - - Name of the property. - The options. - generated html code - - - - Labels the specified property name. - - property in object. - caption - generated html code - - - - Generate a checkbox - - property in object - checkbox value - additional html attributes. - generated html code - - - - Write a html select tag - - object property. - id column - The title column. - The options. - - - - - Selects the specified property name. - - Name of the property. - The items. - The id column. - The title column. - The options. - - - - - Write a submit tag. - - button caption - html submit tag - - - - html end form tag - - html - - - - This provider is used to let us implement any type of form decoding we want without - having to rewrite anything else in the server. - - - - - - - Should contain boundary and type, as in: multipart/form-data; boundary=---------------------------230051238959 - Stream containg form data. - Encoding used when decoding the stream - HttpInput.EmptyLanguageNode if no parser was found. Must always return something (HttpInput.Empty instead of null) - If stream is null or not readable. - If stream contents cannot be decoded properly. - - - - Add a decoder. - - - - - - - Number of added decoders. - - - - - Use with care. - - - - - Decoder used for unknown content types. - - - - - Contains an (html) attribute list. - - - - - Rules are used during preparse - - - - - Determines if this node spans over multiple lines. - - contains line information (and text) - true if rule have previously inited a multiline. - true if this line continues onto the next./// - - - - Determines if this node spans over multiple lines. - - contains line information (and text) - true if the previous line was continued. - true if this line continues onto the next. - - - - A text only node. - - - - - - - parent node - plain text - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - true if this is the first node on the line. - - - - Generate HTML for this node. - - - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - todo: add description - c# code - - - - The text. - - - - - Is this a text node (containing plain text)? - - - - - Serves files that are stored in embedded resources. - - - - - Initializes a new instance of the class. - Runs to make sure the basic mime types are available, they can be cleared later - through the use of if desired. - - - - - Mimtypes that this class can handle per default - - - - - Loads resources from a namespace in the given assembly to an uri - - The uri to map the resources to - The assembly in which the resources reside - The namespace from which to load the resources - - resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); - - will make ie the resource MyLib.Models.User.Views.stylesheet.css accessible via /user/stylesheet.css - - - - - Returns true if the module can handle the request - - - - - Method that process the url - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - true if this module handled the request. - - - - List with all mime-type that are allowed. - - All other mime types will result in a Forbidden http status code. - - - - This decoder converts XML documents to form items. - Each element becomes a subitem in the form, and each attribute becomes an item. - - - // xml: somethingdata - // result: - // form["hello"].Value = "something" - // form["hello"]["id"].Value = 1 - // form["hello"]["world]["id"].Value = 1 - // form["hello"]["world"].Value = "data" - - - The original xml document is stored in form["__xml__"].Value. - - - - - Interface for form content decoders. - - - - - - - Stream containing the content - Content type (with any additional info like boundry). Content type is always supplied in lower case - Stream enconding - A http form, or null if content could not be parsed. - If contents in the stream is not valid input data. - - - - Checks if the decoder can handle the mime type - - Content type (with any additional info like boundry). Content type is always supplied in lower case. - True if the decoder can parse the specified content type - - - - - - Stream containing the content - Content type (with any additional info like boundry). Content type is always supplied in lower case - Stream encoding - Note: contentType and encoding are not used? - A http form, or null if content could not be parsed. - - - - - Recursive function that will go through an xml element and store it's content - to the form item. - - (parent) Item in form that content should be added to. - Node that should be parsed. - - - - Checks if the decoder can handle the mime type - - Content type (with any additional info like boundry). Content type is always supplied in lower case. - True if the decoder can parse the specified content type - - - - This attribute can be used to map a controller to a specific url without using - the class name. - - - - - Maps a controller to a url without using the controller name. - - - Per default the class name is used to determine which url to handle. - For instance, "class UserController" or "class User" tells the framework that - the urls that starts with "/user" should be handled by that controller. - This attribute can be used to circumvent that. - - The name. - - - - The name that the controller should use - - - - - A session store is used to store and load sessions on a media. - The default implementation () saves/retrieves sessions from memory. - - - - - Creates a new http session with a generated id. - - A object - - - - Creates a new http session with a specific id - - Id used to identify the new cookie.. - A object. - - Id should be generated by the store implementation if it's null or . - - - - - Load an existing session. - - Session id (usually retrieved from a client side cookie). - A session if found; otherwise null. - - - - Save an updated session to the store. - - Session id (usually retrieved from a client side cookie). - If Id property have not been specified. - - - - We use the flyweight pattern which reuses small objects - instead of creating new each time. - - Unused session that should be reused next time Create is called. - - - - Remove expired sessions - - - - - Remove a session - - id of the session. - - - - Load a session from the store - - - null if session is not found. - - - - Number of minutes before a session expires. - - Default time is 20 minutes. - - - - HTTP Listener waits for HTTP connections and provide us with s using the - delegate. - - - - - Listen for regular HTTP connections - - IP Address to accept connections on - TCP Port to listen on, default HTTP port is 80. - - - - Launch HttpListener in SSL mode - - IP Address to accept connections on - TCP Port to listen on, default HTTPS port is 443 - Certificate to use - - - - Launch HttpListener in SSL mode - - IP Address to accept connections on - TCP Port to listen on, default HTTPS port is 443 - Certificate to use - which HTTPS protocol to use, default is TLS. - - - - Start listen for new connections - - Number of connections that can stand in a queue to be accepted. - - - - Stop the listener - - - - - - A client have been accepted, but not handled, by the listener. - - - - - Invoked when a client disconnects - - - - - Gives you a change to receive log entries for all internals of the HTTP library. - - - You may not switch log writer after starting the listener. - - - - - This handler will be invoked each time a new connection is accepted. - - - - - True if we should turn on trace logs. - - - - - Let's to receive unhandled exceptions from the threads. - - - Exceptions will be thrown during debug mode if this event is not used, - exceptions will be printed to console and suppressed during release mode. - - - - - PrototypeJS implementation of the javascript functions. - - - - - Requests a url through ajax - - url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. - optional options in format "key, value, key, value", used in JS request object. All keys should end with colon. - a link tag - onclick attribute is used by this method. - - - // plain text - JSHelper.AjaxRequest("'/user/show/1'"); - - // ajax request using this.href - string link = "<a href=\"/user/call/1\" onclick=\"" + JSHelper.AjaxRequest("this.href") + "/<call user</a>"; - - - - - - Determins if a list of strings contains a specific value - - options to check in - value to find - true if value was found - case insensitive - - - - Ajax requests that updates an element with - the fetched content - - url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. - element to update - options in format "key, value, key, value". All keys should end with colon. - A link tag. - - - JSHelper.AjaxUpdater("'/user/show/1'", "user", "onsuccess:", "alert('hello');", "asynchronous:", "true"); - - - - - - A link that pop ups a Dialog (overlay div) - - url to contents of dialog - link title - name, value, name, value - - A "a"-tag that popups a dialog when clicked - - Requires Control.Modal found here: http://livepipe.net/projects/control_modal/ - And the following javascript (load it in application.js): - - Event.observe(window, 'load', - function() { - document.getElementsByClassName('modal').each(function(link){ new Control.Modal(link); }); - } - ); - - - - WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); - - - - - create a modal dialog (usually using DIVs) - - url to fetch - dialog title - javascript/html attributes. javascript options ends with colon ':'. - - - - - Close a javascript dialog window/div. - - javascript for closing a dialog. - - - - - javascript action that should be added to the "onsubmit" event in the form tag. - - remember to encapsulate strings in '' - - All javascript option names should end with colon. - - - JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); - - - - - - The requested resource was not found in the web server. - - - - - All HTTP based exceptions will derive this class. - - - - - Create a new HttpException - - http status code (sent in the response) - error description - - - - Create a new HttpException - - http status code (sent in the response) - error description - inner exception - - - - status code to use in the response. - - - - - Create a new exception - - message describing the error - inner exception - - - - Create a new exception - - message describing the error - - - - A controller in the Model-View-Controller pattern. - Derive this class and add method with one of the following signatures: - "public string MethodName()" or "public void MyMethod()". - - The first should return a string with the response, the latter - should use SendHeader and SendBody methods to handle the response. - - - Last segment of the path is always broken into the properties Id and RequestedType - Alhtough note that the RequestedType can also be empty if no file extension have - been specified. A typical use of file extensions in controllers is to specify which type of - format to return. - - - public class MyController : RequestController - { - public string Hello() - { - if (RequestedType == "xml") - return "<hello>World<hello>"; - else - return "Hello " + Request.QueryString["user"].Value + ", welcome to my world"; - } - - public void File() - { - Response.Headers.ContentType = "text/xml"; - Response.SendHeader(); - } - } - - - - - - - - create a new request controller - - prototype to copy information from - - - - create a new controller - - - - - Method that determines if an url should be handled or not by the module - - Url requested by the client. - true if module should handle the url. - - - - Determines which method to use. - - Requested resource - - - - Call all before filters - - true if a before filter wants to abort the processing. - - - - Override this method to be able to process result - returned by controller method. - - - - - Override this method if you want to be able to - handle unhanded exceptions - - thrown exception - Don't "eat" exceptions derived from HttpException since - they are handled by the framework,unless your are sure of what you are - doing.. - - - - This method goes through all methods in the controller and - add's them to a dictionary. They are later used to invoke - the correct method depending on the url - - - - - Method that process the url - - Uses Uri and QueryString to determine method. - Relays response object to invoked method. - Relays session object to invoked method. - - - - Will assign all variables that are unique for each session - - - - - - - - Make a clone of this controller - - a new controller with the same base information as this one. - - - - object that was attached during http authentication process. - - - You can also assign this tag yourself if you are using regular - http page login. - - - - - - Name of this controller (class name without the "Controller" part) - - - - - Specifies the method to use if no action have been specified. - - If specified method do not exist. - - - - Id is the third part of the uri path. - - - Is extracted as in: /controllername/methodname/id/ - - string.Empty if not specified. - - - - - - Method currently being invoked. - Always in lower case. - - - - - Request information (like Url, form, querystring etc) - - - - - Extension if a filename was specified. - - - - - Response information (that is going to be sent back to the browser/client) - - - - - Session information, is stored between requests as long as the session cookie is valid. - - - - - Marks methods to let framework know that the method is protected - - - - - - - Initializes a new instance of the class. - - - - - - - - Level is a value defined by you. It should be used to determine the users - that can access the method tagged with the AuthRequired attribute. - - - = level; - } - } - ]]> - - - - - Level is a value defined by you. It should be used to determine the users - that can access the method tagged with the AuthRequired attribute. - - - - - A session stored in memory. - - - - - Interface for sessions - - - - - Remove everything from the session - - - - - Remove everything from the session - - True if the session is cleared due to expiration - - - - Session id - - - - - Should - - Name of the session variable - null if it's not set - If the object cant be serialized. - - - - When the session was last accessed. - This property is touched by the http server each time the - session is requested. - - - - - Number of session variables. - - - - - Event triggered upon clearing the session - - - - - - - A unique id used by the sessions store to identify the session - - - - Id - - - - - - Remove everything from the session - - - - - Clears the specified expire. - - True if the session is cleared due to expiration - - - - Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - - 2 - - - - Session id - - - - - Should - - Name of the session variable - null if it's not set - - - - when the session was last accessed. - - - Used to determine when the session should be removed. - - - - - Number of values in the session - - - - - Flag to indicate that the session have been changed - and should be saved into the session store. - - - - - Event triggered upon clearing the session - - - - - IRule that says that something :) - - - - - Determines if this node spans over multiple lines. - - contains line information (and text) - true if the previous line was continued. - true if this line continues onto the next. - - - - Represents a HTML tag. - - - - - Create a new HTML tag node. - - parent node - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line. - - - - Parse node contents add return a fresh node. - - Node that this is a subnode to. Can be null - A list with node types - Line to parse - Where to start the parsing. Will be set to where the next node should start parsing - A node corresponding to the bla bla; null if parsing failed. - - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - This is a plain text node - - - - - tag name - - - - - Thrown when a template cannot be compiled. - - - - - Initializes a new instance of the class. - - Template that failed compilation. - Exception thrown by the compiler. - - - - Creates and returns a string representation of the current exception. - - - A string representation of the current exception. - - - - - - - - Gets a message that describes the current exception. - - - - The error message that explains the reason for the exception, or an empty string(""). - - - - - Contains all HTTP Methods (according to the HTTP 1.1 specification) - - See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - - - - - - The DELETE method requests that the origin server delete the resource identified by the Request-URI. - - - - This method MAY be overridden by human intervention (or other means) on the origin server. - The client cannot be guaranteed that the operation has been carried out, even if the status code - returned from the origin server indicates that the action has been completed successfully. - - - However, the server SHOULD NOT indicate success unless, at the time the response is given, - it intends to delete the resource or move it to an inaccessible location. - - - A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, - 202 (Accepted) if the action has not yet been enacted, - or 204 (No Content) if the action has been enacted but the response does not include an entity. - - - If the request passes through a cache and the Request-URI identifies one or more currently cached entities, - those entries SHOULD be treated as stale. Responses to this method are not cacheable. - - - - - - The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. - - - - If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the - entity in the response and not the source text of the process, unless that text happens to be the output of the process. - - - The semantics of the GET method change to a "conditional GET" if the request message includes an - If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. - A conditional GET method requests that the entity be transferred only under the circumstances described - by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network - usage by allowing cached entities to be refreshed without requiring multiple requests or transferring - data already held by the client. - - - - - - The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. - - - The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the - information sent in response to a GET request. This method can be used for obtaining metainformation about - the entity implied by the request without transferring the entity-body itself. - - This method is often used for testing hypertext links for validity, accessibility, and recent modification. - - - - - The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. - - - This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. - - - - - The POST method is used to request that the origin server accept the entity enclosed - in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. - - - POST is designed to allow a uniform method to cover the following functions: - - - Annotation of existing resources; - - Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; - - Providing a block of data, such as the result of submitting a form, to a data-handling process; - - Extending a database through an append operation. - - - - If a resource has been created on the origin server, the response SHOULD be 201 (Created) and - contain an entity which describes the status of the request and refers to the new resource, and a - Location header (see section 14.30). - - - The action performed by the POST method might not result in a resource that can be identified by a URI. - In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on - whether or not the response includes an entity that describes the result. - - Responses to this method are not cacheable, unless the response includes appropriate Cache-Control - or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent - to retrieve a cacheable resource. - - - - - - The PUT method requests that the enclosed entity be stored under the supplied Request-URI. - - - - - If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a - modified version of the one residing on the origin server. - - If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new - resource by the requesting user agent, the origin server can create the resource with that URI. - - If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. - - If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to - indicate successful completion of the request. - - If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be - given that reflects the nature of the problem. - - - - The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not - understand or implement and MUST return a 501 (Not Implemented) response in such cases. - - - - - - The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - - - - - Contains all HTTP Methods (according to the HTTP 1.1 specification) - - See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - - - - - - The DELETE method requests that the origin server delete the resource identified by the Request-URI. - - - - This method MAY be overridden by human intervention (or other means) on the origin server. - The client cannot be guaranteed that the operation has been carried out, even if the status code - returned from the origin server indicates that the action has been completed successfully. - - - However, the server SHOULD NOT indicate success unless, at the time the response is given, - it intends to delete the resource or move it to an inaccessible location. - - - A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, - 202 (Accepted) if the action has not yet been enacted, - or 204 (No Content) if the action has been enacted but the response does not include an entity. - - - If the request passes through a cache and the Request-URI identifies one or more currently cached entities, - those entries SHOULD be treated as stale. Responses to this method are not cacheable. - - - - - - The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. - - - - If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the - entity in the response and not the source text of the process, unless that text happens to be the output of the process. - - - The semantics of the GET method change to a "conditional GET" if the request message includes an - If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. - A conditional GET method requests that the entity be transferred only under the circumstances described - by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network - usage by allowing cached entities to be refreshed without requiring multiple requests or transferring - data already held by the client. - - - - - - The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. - - - The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the - information sent in response to a GET request. This method can be used for obtaining metainformation about - the entity implied by the request without transferring the entity-body itself. - - This method is often used for testing hypertext links for validity, accessibility, and recent modification. - - - - - The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. - - - This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. - - - - - The POST method is used to request that the origin server accept the entity enclosed - in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. - - - POST is designed to allow a uniform method to cover the following functions: - - - Annotation of existing resources; - - Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; - - Providing a block of data, such as the result of submitting a form, to a data-handling process; - - Extending a database through an append operation. - - - - If a resource has been created on the origin server, the response SHOULD be 201 (Created) and - contain an entity which describes the status of the request and refers to the new resource, and a - Location header (see section 14.30). - - - The action performed by the POST method might not result in a resource that can be identified by a URI. - In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on - whether or not the response includes an entity that describes the result. - - Responses to this method are not cacheable, unless the response includes appropriate Cache-Control - or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent - to retrieve a cacheable resource. - - - - - - The PUT method requests that the enclosed entity be stored under the supplied Request-URI. - - - - - If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a - modified version of the one residing on the origin server. - - If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new - resource by the requesting user agent, the origin server can create the resource with that URI. - - If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. - - If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to - indicate successful completion of the request. - - If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be - given that reflects the nature of the problem. - - - - The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not - understand or implement and MUST return a 501 (Not Implemented) response in such cases. - - - - - - The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - - - - - Contains serverside http request information. - - - - - Decode body into a form. - - A list with form decoders. - If body contents is not valid for the chosen decoder. - If body is still being transferred. - - - - Sets the cookies. - - The cookies. - - - - Called during parsing of a IHttpRequest. - - Name of the header, should not be url encoded - Value of the header, should not be url encoded - If a header is incorrect. - - - - Add bytes to the body - - buffer to read bytes from - where to start read - number of bytes to read - Number of bytes actually read (same as length unless we got all body bytes). - - If body is not writable - - - - Clear everything in the request - - - - - Have all body content bytes been received? - - - - - Kind of types accepted by the client. - - - - - Submitted body contents - - - - - Kind of connection used for the session. - - - - - Number of bytes in the body - - - - - Headers sent by the client. All names are in lower case. - - - - - Version of http. - Probably HttpHelper.HTTP10 or HttpHelper.HTTP11 - - - - - - Requested method, always upper case. - - - - - - Variables sent in the query string - - - - - Requested URI (url) - - - - - Uri absolute path splitted into parts. - - - // uri is: http://gauffin.com/code/tiny/ - Console.WriteLine(request.UriParts[0]); // result: code - Console.WriteLine(request.UriParts[1]); // result: tiny - - - If you're using controllers than the first part is controller name, - the second part is method name and the third part is Id property. - - - - - - Check's both QueryString and Form after the parameter. - - - - - Form parameters. - - - - Returns true if the request was made by Ajax (Asyncronous Javascript) - - - Returns set cookies for the request - - - - Parses a HTTP request directly from a stream - - - - - Create a new request parser - - delegate called when a complete request have been generated - delegate receiving log entries. - - - - Add a number of bytes to the body - - - - - - - - - Remove all state information for the request. - - - - - Parse request line - - - If line is incorrect - Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF" - - - - We've parsed a new header. - - Name in lower case - Value, unmodified. - If content length cannot be parsed. - - - - Parse a message - - - where in buffer that parsing should start - number of bytes to parse - Unparsed bytes left in buffer. - - - - Current state in parser. - - - - - Invoked when a request have been completed. - - - - - - Current state in the parsing. - - - - - Should parse the request line - - - - - Searching for a complete header name - - - - - Searching for colon after header name (ignoring white spaces) - - - - - Searching for start of header value (ignoring white spaces) - - - - - Searching for a complete header value (can span over multiple lines, as long as they are prefixed with one/more whitespaces) - - - - - Adding bytes to body - - - - - Contains serverside http request information. - - - - - Chars used to split an url path into multiple parts. - - - - - Assign a form. - - - - - - Creates a new object that is a copy of the current instance. - - - - A new object that is a copy of this instance. - - 2 - - - - Decode body into a form. - - A list with form decoders. - If body contents is not valid for the chosen decoder. - If body is still being transferred. - - - - Cookies - - the cookies - - - - Called during parsing of a IHttpRequest. - - Name of the header, should not be url encoded - Value of the header, should not be url encoded - If a header is incorrect. - - - - Add bytes to the body - - buffer to read bytes from - where to start read - number of bytes to read - Number of bytes actually read (same as length unless we got all body bytes). - - If body is not writable - - - - Clear everything in the request - - - - - Have all body content bytes been received? - - - - - Kind of types accepted by the client. - - - - - Submitted body contents - - - - - Kind of connection used for the session. - - - - - Number of bytes in the body - - - - - Headers sent by the client. All names are in lower case. - - - - - Version of http. - Probably HttpHelper.HTTP10 or HttpHelper.HTTP11 - - - - - - Requested method, always upper case. - - - - - - Variables sent in the query string - - - - - Requested URI (url) - - - - - - Uri absolute path splitted into parts. - - - // uri is: http://gauffin.com/code/tiny/ - Console.WriteLine(request.UriParts[0]); // result: code - Console.WriteLine(request.UriParts[1]); // result: tiny - - - If you're using controllers than the first part is controller name, - the second part is method name and the third part is Id property. - - - - - - Path and query (will be merged with the host header) and put in Uri - - - - - - Check's both QueryString and Form after the parameter. - - - - - Form parameters. - - - - Returns true if the request was made by Ajax (Asyncronous Javascript) - - - Returns set cookies for the request - - - - Current request is sent over secure protocol - - - - - The website module let's you handle multiple websites in the same server. - It uses the "Host" header to check which site you want. - - It's recommended that you do not - add any other modules to HttpServer if you are using the website module. Instead, - add all wanted modules to each website. - - - - - - domain name that should be handled. - - - - - Method that process the url - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - - - - Name of site. - - - - - Helpers making it easier to work with forms. - - - - - - Used to let the website use different javascript libraries. - Default is - - - - - Create a <form> tag. - - name of form - action to invoke on submit - form should be posted as ajax - html code - - - // without options - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); - - // with options - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax, "style", "display:inline", "class", "greenForm"); - - - html attributes or javscript options. - Method will ALWAYS be POST. - - - - Creates a select list with the values in a collection. - - Name of the SELECT-tag - collection used to generate options. - delegate used to return id and title from objects. - value that should be marked as selected. - First row should contain an empty value. - string containtain a SELECT-tag. - - - - - Creates a select list with the values in a collection. - - Name of the SELECT-tag - Id of the SELECT-tag - collection used to generate options. - delegate used to return id and title from objects. - value that should be marked as selected. - First row should contain an empty value. - string containtain a SELECT-tag. - - - - // Class that is going to be used in a SELECT-tag. - public class User - { - private readonly string _realName; - private readonly int _id; - public User(int id, string realName) - { - _id = id; - _realName = realName; - } - public string RealName - { - get { return _realName; } - } - - public int Id - { - get { return _id; } - } - } - - // Using an inline delegate to generate the select list - public void UserInlineDelegate() - { - List<User> items = new List<User>(); - items.Add(new User(1, "adam")); - items.Add(new User(2, "bertial")); - items.Add(new User(3, "david")); - string htmlSelect = Select("users", "users", items, delegate(object o, out object id, out object value) - { - User user = (User)o; - id = user.Id; - value = user.RealName; - }, 2, true); - } - - // Using an method as delegate to generate the select list. - public void UseExternalDelegate() - { - List<User> items = new List<User>(); - items.Add(new User(1, "adam")); - items.Add(new User(2, "bertial")); - items.Add(new User(3, "david")); - string htmlSelect = Select("users", "users", items, UserOptions, 1, true); - } - - // delegate returning id and title - public static void UserOptions(object o, out object id, out object title) - { - User user = (User)o; - id = user.Id; - value = user.RealName; - } - - - - - - Creates a select list with the values in a collection. - - Name of the SELECT-tag - Id of the SELECT-tag - collection used to generate options. - delegate used to return id and title from objects. - value that should be marked as selected. - First row should contain an empty value. - name, value collection of extra html attributes. - string containtain a SELECT-tag. - - - - - Generate a list of HTML options - - collection used to generate options. - delegate used to return id and title from objects. - value that should be marked as selected. - First row should contain an empty value. - - - - - Creates a checkbox. - - element name - element value - determines if the check box is selected or not. This is done diffrently depending on the - type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if - the box is checked or not. - a list with additional attributes (name, value, name, value). - a generated radio button - - - - Creates a checkbox. - - element name - element id - element value - determines if the check box is selected or not. This is done diffrently depending on the - type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if - the box is checked or not. - a list with additional attributes (name, value, name, value). - a generated radio button - - value in your business object. (check box will be selected if it matches the element value) - - - - - Creates a checkbox. - - element name - element id - determines if the check box is selected or not. This is done diffrently depending on the - type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if - the box is checked or not. - a list with additional attributes (name, value, name, value). - a generated radio button - will set value to "1". - - - - Creates a RadioButton. - - element name - element value - determines if the radio button is selected or not. This is done diffrently depending on the - type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if - the box is checked or not. - a list with additional attributes (name, value, name, value). - a generated radio button - - - - Creates a RadioButton. - - element name - element id - element value - determines if the radio button is selected or not. This is done diffrently depending on the - type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if - the box is checked or not. - a list with additional attributes (name, value, name, value). - a generated radio button - - - - form close tag - - - - - - The request could not be understood by the server due to malformed syntax. - The client SHOULD NOT repeat the request without modifications. - - Text taken from: http://www.submissionchamber.com/help-guides/error-codes.php - - - - - Create a new bad request exception. - - reason to why the request was bad. - - - - Create a new bad request exception. - - reason to why the request was bad. - inner exception - - - - Implements HTTP Digest authentication. It's more secure than Basic auth since password is - encrypted with a "key" from the server. - - - Keep in mind that the password is encrypted with MD5. Use a combination of SSL and digest auth to be secure. - - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - Delegate used to determine if authentication is required (may be null). - - - - Initializes a new instance of the class. - - Delegate used to provide information used during authentication. - - - - Used by test classes to be able to use hardcoded values - - - - - An authentication response have been received from the web browser. - Check if it's correct - - Contents from the Authorization header - Realm that should be authenticated - GET/POST/PUT/DELETE etc. - First option: true if username/password is correct but not cnonce - - Authentication object that is stored for the request. A user class or something like that. - - if authenticationHeader is invalid - If any of the paramters is empty or null. - - - - Encrypts parameters into a Digest string - - Realm that the user want's to log into. - User logging in - Users password. - HTTP metod. - Uri/domain that generated the login prompt. - The qop. - The nonce. - The nc. - The cnonce. - Digest enrypted string - - - - Create a response that can be sent in the WWW-Authenticate header. - - Realm that the user should authenticate in - First options specifies if true if username/password is correct but not cnonce. - A correct auth request. - If realm is empty or null. - - - - Decodes authorization header value - - header value - Encoding that the buffer is in - All headers and their values if successful; otherwise null - - NameValueCollection header = DigestAuthentication.Decode("response=\"6629fae49393a05397450978507c4ef1\",\r\nc=00001", Encoding.ASCII); - - Can handle lots of whitespaces and new lines without failing. - - - - Gets the current nonce. - - - - - - Gets the Md5 hash bin hex2. - - To be hashed. - - - - - determines if the nonce is valid or has expired. - - nonce value (check wikipedia for info) - true if the nonce has not expired. - - - - name used in http request. - - - - - Session store using memory for each session. - - - - - Initializes the class setting the expirationtimer to clean the session every minute - - - - - Delegate for the cleanup timer - - - - - Creates a new http session - - - - - - Creates a new http session with a specific id - - Id used to identify the new cookie.. - A object. - - Id should be generated by the store implementation if it's null or . - - - - - Load an existing session. - - - - - - - Save an updated session to the store. - - - - - - We use the flyweight pattern which reuses small objects - instead of creating new each time. - - EmptyLanguageNode (unused) session that should be reused next time Create is called. - - - - Remove expired sessions - - - - - Remove a session - - id of the session. - - - - Load a session from the store - - - null if session is not found. - - - - Number of minutes before a session expires. - Default is 20 minutes. - - - - - Keeps information about templates, so we know when to regenerate it. - - - - - When the template was compiled. - - Use this date to determine if the template is old and needs to be recompiled. - - - - Template file name. - - - - - The actual template. - - - - - Validator is used to validate all input items in a form. - - - - - Initializes a new instance of the class. - - collection to be filled with errors - - - - Initializes a new instance of the class. - - collection to be filled with errors - Translation used to translate the "name" parameters in all validation methods. - - - - Initializes a new instance of the class. - - Translation used to translate the "name" parameters in all validation methods. - - - - - - form that validation should be made on. - - - - - - collection that all validation errors are added to. - form that validation should be made on. - - - - - - collection that all validation errors are added to. - form that validation should be made on. - Language category used to translate field names. - - - - Switch to a new http input. - - form to use validation for now - - - - Switch to a new http input. - - form to use validation for now - language for the validation - - - - Check if a value is digits only - - Field name. - true if field is required (may not be empty) - string if validated, otherwise string.Empty - - - - Check if a value is digits only - - Field name. - extra characters that is allowed. - true if field is required (may not be empty) - string if validated, otherwise string.Empty - - - - Check whether the specified form item is an integer. - - Form parameter to validate - value if parameter is an int; 0 if not. - - - - Check whether the specified form item is an integer. - - Form parameter to validate - Paramater is required (adds an error if it's not specified) - value if parameter is an int; 0 if not. - - - - Check whether the specified value is a double. - - Name of the parameter - Paramater is required (adds an error if it's not specified) - value if parameter is a double; 0 if not. - - - - Check whether the specified value is a currency amount. - - Name of the parameter - Paramater is required (adds an error if it's not specified) - value if parameter is a currency amount; 0 if not. - - - - Validates a string to hex - - The name of the field to validate - If the field must be set - The value if validated otherwise string.Empty - - - - Validate that a string only contains letters or digits. - - Name of form parameter to validate. - Value is required. - value if valid; otherwise string.EmptyLanguageNode. - - - - Validate that a string only contains letters or digits. - - Form parameter name. - vaue if found; otherwise string.Empty - - - - Validate that a string only contains letters, digits or the specified characters - - Form parameter name. - may not be null or empty if true. - any other allowed characters. - value if valid; otherwise string.Empty - - - - Validate that a string consists of only letters (including special letters) - - - If a value must be passed - - - - - Validate that a string consists of only letters (a-z and A-Z) - - - If a value must be passed - A string of extra character to test against, dont forget language specific characters and spaces if wished for - - - - - Check whether the specified value is an integer. - - Name of the parameter - value if parameter contains valid characters; string.Empty if not. - - - - Check whether the specified value is an integer. - - Name of the parameter - Paramater is required (adds an error if it's not specified) - value if parameter contains valid characters; string.Empty if not. - - - - Validate that a string only contains letters or digits or any of the . - - Name of form parameter to validate. - Value is required. - value if valid; otherwise string.Empty. - - - - Validate that a string only contains letters or digits or any of the . - - Form parameter name. - vaue if found; otherwise string.Empty - - - - Check's weather a parameter is null or not. - - Parameter in form - true if value is not null; otherwise false. - - - - Validate a string value - - Name of form parameter to validate. - Value is required. - value if valid; otherwise string.Empty. - - - - Validate a string parameter in the form - - Form parameter name. - vaue if found; otherwise string.Empty - - - - validates email address using a regexp. - - field name - field is required (may not be null or empty). - value if validation is ok; otherwise string.Empty. - - - - Check whether the specified value is an character. - - Name of the parameter - Paramater is required (adds an error if it's not specified) - value if parameter is an int; char.MinValue if not. - - - - Check whether the specified value is an character. - - Name of the parameter - value if parameter is an int; char.MinValue if not. - - - - Checks whether a field is true (can also be in native language). - - field name - field is required (may not be null or empty). - true if value is true; false if value is false or if validation failed. - Check validation errors to see if error ocurred. - - - - Checks whether a field is true (can also be in native language). - - field name - true if value is true; false if value is false or if validation failed. - Check validation errors to see if error ocurred. - - - - Class to handle loading of resource files - - - - - ]]> - - - - Parses a filename and sets it to the extensionless name in lowercase. The extension is cut out without the dot. - - - - - string ext; - string filename = "/uSeR/teSt.haMl"; - ParseName(ref filename, out ext); - Console.WriteLine("File: " + filename); - Console.WriteLine("Ext: " + ext); - -> user/test - -> haml - - - - - Add a resource to a specified uri without extension, ie user/test - - The uri to add the resource to - The instance describing the resource - - - - Loads resources from a namespace in the given assembly to an uri - - The uri to map the resources to - The assembly in which the resources reside - The namespace from which to load the resources - - resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); - - will make ie the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ - - - - - Retrieves a stream for the specified resource path if loaded otherwise null - - Path to the resource to retrieve a stream for - A stream or null if the resource couldn't be found - - - - Fetch all files from the resource that matches the specified arguments. - - The path to the resource to extract - - a list of files if found; or an empty array if no files are found. - - - - - Fetch all files from the resource that matches the specified arguments. - - Where the file should reside. - Files to check - - a list of files if found; or an empty array if no files are found. - - - - - Returns whether or not the loader has an instance of the file requested - - The name of the template/file - True if the loader can provide the file - - - - We dont want to let the server to die due to exceptions thrown in worker threads. - therefore we use this delegate to give you a change to handle uncaught exceptions. - - Class that the exception was thrown in. - Exception - - Server will throw a InternalServerException in release version if you dont - handle this delegate. - - - - - Method marked with this attribute determines if authentication is required. - - - - - - - The method should take one parameter (int level), return a bool and be protected/private. - You should throw UnauthorizedException if you are using HTTP authentication. - - - = level; - } - } - ]]> - - - - - This class is created as a wrapper, since there are two different cookie types in .Net (Cookie and HttpCookie). - The framework might switch class in the future and we dont want to have to replace all instances - - - - - Let's copy all the cookies. - - value from cookie header. - - - - Adds a cookie in the collection. - - cookie to add - cookie is null - - - - Gets a collection enumerator on the cookie list. - - collection enumerator - - - - Remove all cookies. - - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Gets the count of cookies in the collection. - - - - - Gets the cookie of a given identifier (null if not existing). - - - - - Delegate used to find a realm/domain. - - - - - Realms are used during HTTP Authentication - - - - - - - A complete HTTP server, you need to add a module to it to be able to handle incoming requests. - - - - // this small example will add two web site modules, thus handling - // two different sites. In reality you should add Controller modules or something - // two the website modules to be able to handle different requests. - HttpServer server = new HttpServer(); - server.Add(new WebSiteModule("www.gauffin.com", "Gauffin Telecom AB")); - server.Add(new WebSiteModule("www.vapadi.se", "Remote PBX")); - - // start regular http - server.Start(IPAddress.Any, 80); - - // start https - server.Start(IPAddress.Any, 443, myCertificate); - - - - - - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - Form decoders are used to convert different types of posted data to the object types. - - - - - - Initializes a new instance of the class. - - A session store is used to save and retrieve sessions - - - - - Initializes a new instance of the class. - - The log writer. - - - - - Initializes a new instance of the class. - - Form decoders are used to convert different types of posted data to the object types. - The log writer. - - - - - - - Initializes a new instance of the class. - - Form decoders are used to convert different types of posted data to the object types. - A session store is used to save and retrieve sessions - The log writer. - - - - - - - - Adds the specified rule. - - The rule. - - - - Add a to the server. - - mode to add - - - - Decodes the request body. - - The request. - - - - Generate a HTTP error page (that will be added to the response body). - response status code is also set. - - Response that the page will be generated in. - . - response body contents. - - - - Generate a HTTP error page (that will be added to the response body). - response status code is also set. - - Response that the page will be generated in. - exception. - - - - Realms are used by the s. - - HTTP request - domain/realm. - - - - Process an incoming request. - - connection to client - request information - response that should be filled - session information - - - - Can be overloaded to implement stuff when a client have been connected. - - - Default implementation does nothing. - - client that disconnected - disconnect reason - - - - Handle authentication - - - - - true if request can be handled; false if not. - - - - Will request authentication. - - - Sends respond to client, nothing else can be done with the response after this. - - - - - - - - Start the web server using regular HTTP. - - IP Address to listen on, use IpAddress.Any to accept connections on all ip addresses/network cards. - Port to listen on. 80 can be a good idea =) - - - - Accept secure connections. - - IP Address to listen on, use IpAddress.Any to accept connections on all ipaddresses/network cards. - Port to listen on. 80 can be a good idea =) - Certificate to use - - - - shut down the server and listeners - - - - - write an entry to the log file - - importance of the message - log message - - - - write an entry to the log file - - object that wrote the message - importance of the message - log message - - - - Modules used for authentication. The module that is is added first is used as - the default authentication module. - - Use the corresponding property - in the WebSiteModule if you are using multiple websites. - - - - Form decoder providers are used to decode request body (which normally contains form data). - - - - - Server name sent in HTTP responses. - - - Do NOT include version in name, since it makes it - easier for hackers. - - - - - Name of cookie where session id is stored. - - - - - Specified where logging should go. - - - - - - - - Number of connections that can wait to be accepted by the server. - - Default is 10. - - - - Realms are used during HTTP authentication. - Default realm is same as server name. - - - - - Let's to receive unhandled exceptions from the threads. - - - Exceptions will be thrown during debug mode if this event is not used, - exceptions will be printed to console and suppressed during release mode. - - - - - The request requires user authentication. The response MUST include a - WWW-Authenticate header field (section 14.47) containing a challenge - applicable to the requested resource. - - The client MAY repeat the request with a suitable Authorization header - field (section 14.8). If the request already included Authorization - credentials, then the 401 response indicates that authorization has been - refused for those credentials. If the 401 response contains the same challenge - as the prior response, and the user agent has already attempted authentication - at least once, then the user SHOULD be presented the entity that was given in the response, - since that entity might include relevant diagnostic information. - - HTTP access authentication is explained in rfc2617: - http://www.ietf.org/rfc/rfc2617.txt - - (description is taken from - http://www.submissionchamber.com/help-guides/error-codes.php#sec10.4.2) - - - - - Create a new unauhtorized exception. - - - - - - Create a new unauhtorized exception. - - reason to why the request was unauthorized. - inner exception - - - - Create a new unauhtorized exception. - - reason to why the request was unauthorized. - - - - Generates C# rendering object using ASP similiar tags in the HTML code. - - - - - Generate C# code from the template. - - A textwriter that the generated code will be written to. - If the template have not been parsed first. - If template is incorrect - - - - Parse a file and convert into to our own template object code. - - Path and filename to a template - If something is incorrect in the template. - - - - - - - - - Parse a file and convert into to our own template object code. - - A textreader containing our template - If something is incorrect in the template. - - - - Purpose if this class is to take template objects and keep them in - memory. It will also take a filename and the code generator to use - if when the template have been changed on disk. - - - - - Initializes a new instance of the class. - - - Template loaders used to load templates from any source. - The loaders will be invoked in the order they are given, that is the first loader will always be asked to give a template - first. - - - - - Initializes a new instance of the class. - - Uses the file template loader. - - - - Add a template generator - - File extension without the dot. - Generator to handle the extension - If the generator already exists. - If file extension is incorrect - If generator is not specified. - - - cache.Add("haml", new HamlGenerator()); - - - - - - This type should be included, so it may be called from the scripts (name space and assembly). - - - - - - Checks the template. - - Template information, filename must be set. - true if template exists and have been compiled. - - - - Compiles the specified code. - - Name of template. - c# code generated from a template. - Arguments as in name, value, name, value, name, value - - An id to specify the exact instance of a template. Made from joining the 'TemplateClass' with the hashcode of the filename - and the hashcode of the supplied arguments - - Template - If compilation fails - - - - Will generate code from the template. - Next step is to compile the code. - - Path and filename to template. - - If no template generator exists for the specified extension. - If parsing/compiling fails - - - - - Find a template using wildcards in filename. - - Full path (including wildcards in filename) to where we should find a template. - First found generator if an extension was matched; otherwise null. - method is not thread safe - - - - Render a partial - - Path and filename - Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents. - Arguments passed from parent template - - - - - - - - Generate HTML from a template. - - Path and filename - Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents. - - - - - - string html = cache.Generate("views\\users\\view.haml", new TemplateArguments("user", dbUser, "isAdmin", dbUser.IsAdmin), null); - - - - - - Keeps information about templates, so we know when to regenerate it. - - - - - Container to bind resource names to assemblies - - - - - Instantiates an instance of - - The full name/path of the resource - The assembly the resource exists in - - - - Retrieves a stream to the resouce - - Null if the resource couldn't be located somehow - - - - Retrieves the assembly the resource resides in - - - - - Retrieves the full name/path of the assembly - - - - - Retrieves the extension of the resource - - - - - This template loader loads all templates from a folder on the hard drive. - - - - - Initializes a new instance of the class. - - A prefix that is prepended to all requested files. - - - - - Initializes a new instance of the class. - - - - - Load a template into a and return it. - - Relative path (and filename) to template. - - a if file was found; otherwise null. - - - - - Fetch all files from the resource that matches the specified arguments. - - Where the file should reside. - Files to check - - a list of files if found; or an empty array if no files are found. - - - - - Returns whether or not the loader has an instance of the file requested - - The name of the template/file - True if the loader can provide the file - - - - Check's whether a template should be reloaded or not. - - template information - - true if template is OK; false if it do not exist or are old. - - - - - A prefix that is prepended to all requested files. - - - - \\templateName.*" - mgr.PathPrefix = "views\\"; - ]]> - - - PathPrefix may not be null, only string.Empty - - - - - Helpers to make XML handling easier - - - - - Serializes object to XML. - - object to serialize. - xml - - Removes namespaces and adds intendation - - - - - Response that is sent back to the web browser / client. - - A response can be sent if different ways. The easiest one is - to just fill the Body stream with content, everything else - will then be taken care of by the framework. The default content-type - is text/html, you should change it if you send anything else. - - The second and slighty more complex way is to send the response - as parts. Start with sending the header using the SendHeaders method and - then you can send the body using SendBody method, but do not forget - to set ContentType and ContentLength before doing so. - - - public void MyHandler(IHttpRequest request, IHttpResponse response) - { - - } - - - - - Add another header to the document. - - Name of the header, case sensitive, use lower cases. - Header values can span over multiple lines as long as each line starts with a white space. New line chars should be \r\n - If headers already been sent. - If value conditions have not been met. - Adding any header will override the default ones and those specified by properties. - - - - Send headers and body to the browser. - - If content have already been sent. - - - - Make sure that you have specified ContentLength and sent the headers first. - - - If headers have not been sent. - - offest of first byte to send - number of bytes to send. - - - This method can be used if you want to send body contents without caching them first. This - is recommended for larger files to keep the memory usage low. - - - - Make sure that you have specified ContentLength and sent the headers first. - - - If headers have not been sent. - - - - This method can be used if you want to send body contents without caching them first. This - is recommended for larger files to keep the memory usage low. - - - - Send headers to the client. - - If headers already been sent. - - - - - - - Redirect client to somewhere else using the 302 status code. - - Destination of the redirect - If headers already been sent. - You can not do anything more with the request when a redirect have been done. This should be your last - action. - - - - redirect to somewhere - - where the redirect should go - - No body are allowed when doing redirects. - - - - - The body stream is used to cache the body contents - before sending everything to the client. It's the simplest - way to serve documents. - - - - - The chunked encoding modifies the body of a message in order to - transfer it as a series of chunks, each with its own size indicator, - followed by an OPTIONAL trailer containing entity-header fields. This - allows dynamically produced content to be transferred along with the - information necessary for the recipient to verify that it has - received the full message. - - - - - Kind of connection - - - - - Encoding to use when sending stuff to the client. - - Default is UTF8 - - - - Number of seconds to keep connection alive - - Only used if Connection property is set to ConnectionType.KeepAlive - - - - Status code that is sent to the client. - - Default is HttpStatusCode.Ok - - - - Information about why a specific status code was used. - - - - - Size of the body. MUST be specified before sending the header, - unless property Chunked is set to true. - - - - - Kind of content in the body - - Default is text/html - - - - Headers have been sent to the client- - - You can not send any additional headers if they have already been sent. - - - - The whole response have been sent. - - - - - Cookies that should be created/changed. - - - - - Type of HTTP connection - - - - - Connection is closed after each request-response - - - - - Connection is kept alive for X seconds (unless another request have been made) - - - - - represents a http input item. Each item can have multiple sub items, a sub item - is made in a html form by using square brackets - - - // becomes: - Console.WriteLine("Value: {0}", form["user"]["FirstName"].Value); - - - All names in a form SHOULD be in lowercase. - - - - Representation of a non-initialized HttpInputItem - - - - Initializes an input item setting its name/identifier and value - - Parameter name/id - Parameter value - - - Creates a deep copy of the item specified - The item to copy - The function makes a deep copy of quite a lot which can be slow - - - - Add another value to this item - - - - - - checks if a subitem exists (and has a value). - - name in lower case - true if the subitem exists and has a value; otherwise false. - - - Returns a formatted representation of the instance with the values of all contained parameters - - - - Outputs the string in a formatted manner - - A prefix to append, used internally - produce a query string - - - - Add a sub item - - Can contain array formatting, the item is then parsed and added in multiple levels - - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Returns an enumerator that iterates through a collection. - - - - An object that can be used to iterate through the collection. - - 2 - - - - Outputs the string in a formatted manner - - A prefix to append, used internally - - - - - Number of values - - - - - Get a sub item - - name in lower case. - HttpInputItem.Empty if no item was found. - - - - Name of item (in lower case). - - - - - Returns the first value, or null if no value exist. - - - - - Returns the last value, or null if no value exist. - - - - - Returns the list with values. - todo: Return a readonly collection - - - - - - - name in lower case - - - - - Can handle application/x-www-form-urlencoded - - - - - - Stream containing the content - Content type (with any additional info like boundry). Content type is always supplied in lower case - Stream enconding - - A http form, or null if content could not be parsed. - - If contents in the stream is not valid input data. - - - - Checks if the decoder can handle the mime type - - Content type (with any additional info like boundry). Content type is always supplied in lower case. - True if the decoder can parse the specified content type - - - - Used to simply testing of controls. - - - - - Fake host name, default is "http://localhost" - - - - - Session used if null have been specified as argument to one of the class methods. - - - - - Send a GET request to a controller. - - Controller receiving the post request. - Uri visited. - Response from the controller. - Session used during the test. null = is used. - body posted by the response object - - - void MyTest() - { - ControllerTester tester = new ControllerTester(); - - MyController controller = new MyController(); - IHttpResponse response; - string text = Get(controller, "/my/hello/1?hello=world", out response, null); - Assert.Equal("world|1", text); - } - - - - - - Send a POST request to a controller. - - Controller receiving the post request. - Uri visited. - Form being processed by controller. - Response from the controller. - Session used during the test. null = is used. - body posted by the response object - - - void MyTest() - { - // Create a controller. - MyController controller = new MyController(); - - // build up a form that is used by the controller. - HttpForm form = new HttpForm(); - form.Add("user[firstName]", "Jonas"); - - // Invoke the request - ControllerTester tester = new ControllerTester(); - IHttpResponse response; - string text = tester.Get(controller, "/user/create/", form, out response, null); - - // validate response back from controller. - Assert.Equal("User 'Jonas' has been created.", text); - } - - - - - - Invoked when a client have been accepted by the - - - Can be used to revoke incoming connections - - - - - Initializes a new instance of the class. - - The socket. - - - - Client may not be handled. - - - - - Accepted socket. - - - - - Client should be revoked. - - - - - cookie being sent back to the browser. - - - - - - cookie sent by the client/browser - - - - - - Constructor. - - cookie identifier - cookie content - id or content is null - id is empty - - - - Gets the cookie HTML representation. - - cookie string - - - - Gets the cookie identifier. - - - - - Cookie value. Set to null to remove cookie. - - - - - Constructor. - - cookie identifier - cookie content - cookie expiration date. Use DateTime.MinValue for session cookie. - id or content is null - id is empty - - - - Create a new cookie - - name identifying the cookie - cookie value - when the cookie expires. Setting DateTime.MinValue will delete the cookie when the session is closed. - Path to where the cookie is valid - Domain that the cookie is valid for. - - - - Create a new cookie - - Name and value will be used - when the cookie expires. - - - - Gets the cookie HTML representation. - - cookie string - - - - When the cookie expires. - DateTime.MinValue means that the cookie expires when the session do so. - - - - - Cookie is only valid under this path. - - - - - Interface for dynamically generated templates. - - - - - - Run the template to generate HTML code. - - arguments passed to the template - template manager (a manager is used to generate templates) - HTML code. - - - - Contains information on where in the template the error occurred, and what the error was. - - - - - Initializes a new instance of the class. - - Line that the error appeared on. - error description. - - - - Initializes a new instance of the class. - - Line that the error appeared on. - error description. - line contents. - - - - Returns the actual line where the error originated - - - - - Line number in template - - - - - The ’-’ character makes the text following it into “silent” code: C# code that is evaluated, but not output. - It is not recommended that you use this widely; almost all processing code and logic should be restricted to the Controller, Helpers, or partials. - - For example - - - string foo = "hello" - - foo += " there" - - foo += " you!" - %p= foo - - - Is compiled to - -

- hello there you! -

-
-
-
- - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - The compiler is responsible of creating a render object which can be - cached and used over and over again. - - - - - - - Base c# code for a template object. - - - - - Create a new template compiler - - - - - Adds the specified type. - - The type. - - - - Compiles the specified args. - - Arguments, should contain "name, value, name, value" etc. - c# code that will be included in the generated template class - Id of the template class - Tiny template if successful; otherwise null. - If compilation fails - If args are incorrect - - - - Response that is sent back to the web browser / client. - - A response can be sent if different ways. The easiest one is - to just fill the Body stream with content, everything else - will then be taken care of by the framework. The default content-type - is text/html, you should change it if you send anything else. - - The second and slighty more complex way is to send the response - as parts. Start with sending the header using the SendHeaders method and - then you can send the body using SendBody method, but do not forget - to set ContentType and ContentLength before doing so. - - - public void MyHandler(IHttpRequest request, IHttpResponse response) - { - - } - - todo: add two examples, using SendHeaders/SendBody and just the Body stream. - - - - Initializes a new instance of the class. - - The context. - The request. - - - - Add another header to the document. - - Name of the header, case sensitive, use lower cases. - Header values can span over multiple lines as long as each line starts with a white space. New line chars should be \r\n - If headers already been sent. - If value conditions have not been met. - Adding any header will override the default ones and those specified by properties. - - - - Send headers and body to the browser. - - If content have already been sent. - - - - Make sure that you have specified ContentLength and sent the headers first. - - - If headers have not been sent. - - offest of first byte to send - number of bytes to send. - - - This method can be used if you want to send body contents without caching them first. This - is recommended for larger files to keep the memory usage low. - - - - Make sure that you have specified ContentLength and sent the headers first. - - - If headers have not been sent. - - - - This method can be used if you want to send body contents without caching them first. This - is recommended for larger files to keep the memory usage low. - - - - Send headers to the client. - - If headers already been sent. - - - - - - - Redirect client to somewhere else using the 302 status code. - - Destination of the redirect - If headers already been sent. - You can not do anything more with the request when a redirect have been done. This should be your last - action. - - - - redirect to somewhere - - where the redirect should go - - No body are allowed when doing redirects. - - - - - The body stream is used to cache the body contents - before sending everything to the client. It's the simplest - way to serve documents. - - - - - The chunked encoding modifies the body of a message in order to - transfer it as a series of chunks, each with its own size indicator, - followed by an OPTIONAL trailer containing entity-header fields. This - allows dynamically produced content to be transferred along with the - information necessary for the recipient to verify that it has - received the full message. - - - - - Kind of connection - - - - - Encoding to use when sending stuff to the client. - - Default is UTF8 - - - - Number of seconds to keep connection alive - - Only used if Connection property is set to ConnectionType.KeepAlive - - - - Status code that is sent to the client. - - Default is HttpStatusCode.Ok - - - - Information about why a specific status code was used. - - - - - Size of the body. MUST be specified before sending the header, - unless property Chunked is set to true. - - - - - Kind of content in the body - - Default is text/html - - - - Headers have been sent to the client- - - You can not send any additional headers if they have already been sent. - - - - The whole response have been sent. - - - - - Cookies that should be created/changed. - - - - - A reverse proxy are used to act as a bridge between local (protected/hidden) websites - and public clients. - - A typical usage is to allow web servers on non standard ports to still be available - to the public clients, or allow web servers on private ips to be available. - - - - - - - Base url requested from browser - Base url on private web server - - // this will return contents from http://192.168.1.128/view/jonas when client requests http://www.gauffin.com/user/view/jonas - _server.Add(new ReverseProxyModule("http://www.gauffin.com/user/", "http://192.168.1.128/"); - - - - - Method that determines if an url should be handled or not by the module - - Url requested by the client. - true if module should handle the url. - - - - Method that process the url - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - - - Container for posted form data - - - Instance to help mark a non-initialized form - - - Initializes a form container with the specified name - - - - Makes a deep copy of the input - - The input to copy - - - - Adds a file to the collection of posted files - - The file to add - If the file is already added - If file is null - If the instance is HttpForm.EmptyForm which cannot be modified - - - - Checks if the form contains a specified file - - Field name of the file parameter - True if the file exists - If the instance is HttpForm.EmptyForm which cannot be modified - - - - Retrieves a file held by by the form - - The identifier of the file - The requested file or null if the file was not found - If name is null or empty - If the instance is HttpForm.EmptyForm which cannot be modified - - - Disposes all held HttpFile's and resets values - - - - The server encountered an unexpected condition which prevented it from fulfilling the request. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - error message. - - - - Initializes a new instance of the class. - - error message. - inner exception. - - - - This attribute tells the controller that the method - uses SendHeader and/or SendBody to handle the request. - - - - - Contains line text and state information about a line in a HAML template. - - - - - Initializes a new instance of the class. - - The line number. - The unparsed data (line contents). - - - - Will check that all rule conditions have been met. - Will also remove the rules if they are done. - - - - - - - Append another line - - - - - - Parsed line contents (without whitespaces in the beginning) - - text contents - - - - Set intendation info to previously added line text. - - - - - - - Assign line text - - - - - - - - - - - If extra lines have been added. - - - - If the next line should be appended to us (multi line) - - - - - Do NOT add yourself using the Add methods of the linkedList. - Parent property will add node. - - - - - Untouched line text - - - - - Has one or more children (intented more that this one) - - - - - Number of intends (two spaces = 1, one tab = 1) - - - - - Line number - - - - - Parent node (one level up in intendation) - - - - - All line data generated on one line - - - - - IRule have not got all needed information yet, - keep appending lines to this LineInfo until rule says that it's done. - - - - - Number of whitespaces before actual entry beings. - - - - - True if node is selfclosed (i.e. <br />) - - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - First node on line, used since some nodes cannot exist on their own on a line. - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - Text nodes should be added as child. - - - - - Used to inform http server that - - - - - Eventarguments used when an exception is thrown by a module - - the exception - - - - Exception thrown in a module - - - - - View controllers integrates the templates, by adding - Render methods. - - - - - Create a new . - - - - - Create a new . - - prototype to copy information from. - - - - Render template for the currently invoked method. - - arguments/parameters used in template - template generated content - calls RenderActionWithErrors - - - - Render contents into a template. - - method/template to generate - arguments/parameters used in template - template generated content - calls RenderActionWithErrors. - - - - Merge arguments array and Arguments property. - - Arguments array to merge - arguments/parameters that can be used in the template. - Will add Request/Response/Session arguments - - - - Renders errors from the property into the - current method template, or as a JavaScript alert if the request is Ajax. - - name of the currently invoked method. - arguments used in the method template. - generated string - Creates a JavaScript Alert box if request is Ajax. - - - - Renders errors from the property into the - current method template, or as a JavaScript alert if the request is Ajax. - - A collection of errors. - name of the currently invoked method. - arguments used in the method template. - generated string - Creates a JavaScript Alert box if request is Ajax. - - - - Switches content-type to "text/JavaScript" and returns content. - - JavaScript to send to the client. - JavaScript - - - - Creates a JavaScript "alert" filled with all errors. - - - a - - - - renders one of the layouts - - layout to render (should be found in the "views\\layouts" folder). - contents will be put in the template variable called "text". - generated text/HTML. - - - - Render a template. - - Merges the Arguments property with the args parameter and pass those to the template. - controller name are used as a folder name when looking for the template. - method are used as filename when looking for the template. - arguments that should be passed to the template. - - - - - Invoked each time a new request is about to be invoked. - - Can be used to clear old data. - - - - - - - Arguments that are being used in the templates. - - - - - A set of errors that occurred during request processing. - Key should be argument name (if argument error, otherwise ), value should be - the error message. - - Errors can be rendered into templates using the method. - - - - - True if we always should render contents inside page layouts when request is Ajax. - - default is false. - - - - Which page layout to use (without file extension) - - - - Page layouts should be places in the Views\Layouts folder. - - - default is "Application" - - - - - - Page title (are added as a parameter to the layout template, use it in <title> HTML tag. - - - - - Arguments sent when a is cleared - - - - - Instantiates the arguments for the event - - True if the session is cleared due to expiration - - - - Returns true if the session is cleared due to expiration - - - - - Delegate for when a IHttpSession is cleared - - this is being cleared. - Arguments for the clearing - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - A list of prototype nodes. - - - - - Creates the node. - - node identifier. - parent node. - created node if identifier was found; otherwise null. - - - - - - - first node on line - - - - - Add a prototype - - prototype node - - - - The purpose of this module is to serve files. - - - - - Initializes a new instance of the class. - - Uri to serve, for instance "/files/" - Path on hard drive where we should start looking for files - If true a Last-Modifed header will be sent upon requests urging webbrowser to cache files - - - - Initializes a new instance of the class. - - Uri to serve, for instance "/files/" - Path on hard drive where we should start looking for files - - - - Mimtypes that this class can handle per default - - - - - Determines if the request should be handled by this module. - Invoked by the HttpServer - - - true if this module should handle it. - - - - check if source contains any of the chars. - - - - - - - - Method that process the url - - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - - - - return a file extension from an absolute uri path (or plain filename) - - - - - - - List with all mime-type that are allowed. - - All other mime types will result in a Forbidden http status code. - - - - characters that may not exist in a path. - - - fileMod.ForbiddenChars = new string[]{ "\\", "..", ":" }; - - - - - Generic helper functions for Http - - - - - Version string for HTTP v1.0 - - - - - Version string for HTTP v1.1 - - - - - An empty url - - - - - Parses a querystring. - - Querystring (url decoded) - A HttpInput object if successful; otherwise HttpInput.Empty - - - - The server understood the request, but is refusing to fulfill it. - Authorization will not help and the request SHOULD NOT be repeated. - If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, - it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information - available to the client, the status code 404 (Not Found) can be used instead. - - Text taken from: http://www.submissionchamber.com/help-guides/error-codes.php - - - - - Initializes a new instance of the class. - - error message - - - - Delegate used to let authentication modules authenticate the username and password. - - Realm that the user want to authenticate in - Username specified by client - Password supplied by the delagete - object that will be stored in a session variable called if authentication was successful. - throw forbidden exception if too many attempts have been made. - - - - Let's you decide on a system level if authentication is requried. - You can also decide if authentication is required in each HttpModule. - - Http request from client - true if user should be authenticated. - throw ForbiddenException if no more attempts are allowed. - If no more attempts are allowed - - - - Represents a html class node. - - - - - Parse node contents add return a fresh node. - - List containing all node types - Node that this is a subnode to. Can be null - Line to parse - Where to start the parsing. Should be set to where the next node should start parsing. - A node corresponding to the bla bla; null if parsing failed. - - - - - determines if this node can handle the line (by checking the first word); - - Controller char (word) - true if text belongs to this node type - first node on line - - - - Convert node to HTML (with ASP-tags) - - HTML string - - - - Convert the node to c# code - - True if we are inside the internal stringbuilder - true if all subnodes fit on one line - smallEnough is a default value, recalc it - c# code - - - - - - - http://www.faqs.org/rfcs/rfc1867.html - - - - - multipart/form-data - - - - - form-data - - - - - - - Stream containing the content - Content type (with any additional info like boundry). Content type is always supplied in lower case - Stream enconding - A http form, or null if content could not be parsed. - If contents in the stream is not valid input data. - If any parameter is null - - - - Checks if the decoder can handle the mime type - - Content type (with any additional info like boundry). Content type is always supplied in lower case. - True if the decoder can parse the specified content type - - - - - - - - - - - Represents a field in a multipart form - - - - Lists content type mime types. - - - - - text/plain - - - - - text/haml - - - - - content type for javascript documents = application/javascript - - - - RFC 4329 states that text/javascript have been superseeded by - application/javascript. You might still want to check browser versions - since older ones do not support application/javascript. - - Browser support: http://krijnhoetmer.nl/stuff/javascript/mime-types/ - - - - - text/xml - - - - - A list of content types - - - - - - - Semicolon separated content types. - - - - Returns an enumerator that iterates through a collection. - - - An object that can be used to iterate through the collection. - - - - - Searches for the specified type - - Can also be a part of a type (searching for "xml" would return true for "application/xml"). - true if type was found. - - - - Get this first content type. - - - - - Fetch a content type - - Part of type ("xml" would return "application/xml") - - All content types are in lower case. - -
-
+ + + + HttpServer_OpenSim + + + + + Cookies that should be set. + + + + + Adds a cookie in the collection. + + cookie to add + cookie is null + + + + Copy a request cookie + + + When the cookie should expire + + + + Gets a collection enumerator on the cookie list. + + collection enumerator + + + + Remove all cookies + + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Gets the count of cookies in the collection. + + + + + Gets the cookie of a given identifier (null if not existing). + + + + + Generates C#/HTML from HAML code. + + HAML documentation: http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html + + + + A code generator is used to convert template code to something that we can + work with, as HTML or c# code. + + + + + + Generate C# code from the template. + + A that the generated code will be written to. + If the template have not been parsed first. + If template is incorrect + + + + Parse a file and convert into to our own template object code. + + Path and filename to a template + If something is incorrect in the template. + + + + + + + + + Parse a file and convert into to our own template object code. + + A containing our template + If something is incorrect in the template. + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + The log writer. + + + + Check and validate indentation + + line to check + number of white spaces + number of indentations (2 white spaces = 1 intend, 1 tab = 1 intend) + + + + Check indentation + + fills line with intend info + + + + check if current line is a multi line + + previous line + current line + + + + Generate HTML code from the template. + Code is encapsulated in <% and <%= + + A that the generated code will be written to. + If the template have not been parsed first. + If template is incorrect + + + + Get the first word (letters and digits only) from the specified offset. + + + + + + + + Check indentation / node placement + + + + + Parse a node + todo: improve doc + + + + + + + + + PreParse goes through the text add handles indentation + and all multi line cases. + + Reader containing the text + + + + print the entire document + + + + + Print line information to the console + + + + + + Read next line from file + + true if line could be read; false if EOF. + + + + Generates a string with spaces. + + number of spaces. + string of spaces. + + + + Parse a file and convert into to our own template object code. + + Path and filename to a template + If something is incorrect in the template. + + + + + + + + + + Parse a file and convert into to our own template object code. + + A containing our template + If something is incorrect in the template. + + + + Generate C# code from the template. + + A that the generated code will be written to. + If the template have not been parsed first. + If template is incorrect + + + + Property to retrieve the root node for the latest parsed document + + + + + Class to make dynamic binding of redirects. Instead of having to specify a number of similar redirect rules + a regular expression can be used to identify redirect urls and thier targets. + + + [a-z0-9]+)", "/users/${target}?find=true", RegexOptions.IgnoreCase) + ]]> + + + + + redirects from one url to another. + + + + + Rules are used to perform operations before a request is being handled. + Rules can be used to create routing etc. + + + + + Process the incoming request. + + incoming http request + outgoing http response + true if response should be sent to the browser directly (no other rules or modules will be processed). + + returning true means that no modules will get the request. Returning true is typically being done + for redirects. + + If request or response is null. + + + + Initializes a new instance of the class. + + Absolute path (no servername) + Absolute path (no servername) + + server.Add(new RedirectRule("/", "/user/index")); + + + + + Initializes a new instance of the class. + + Absolute path (no servername) + Absolute path (no servername) + true if request should be redirected, false if the request uri should be replaced. + + server.Add(new RedirectRule("/", "/user/index")); + + + + + Process the incoming request. + + incoming http request + outgoing http response + true if response should be sent to the browser directly (no other rules or modules will be processed). + + returning true means that no modules will get the request. Returning true is typically being done + for redirects. + + + + + string to match request url with. + + Is compared to request.Uri.AbsolutePath + + + + Where to redirect. + + + + + true if we should redirect. + + + false means that the rule will replace + the current request uri with the new one from this class. + + + + + Initializes a new instance of the class. + + Expression to match url + Expression to generate url + + [a-zA-Z0-9]+)", "/user/${first}")); + Result of ie. /employee1 will then be /user/employee1 + ]]> + + + + + Initializes a new instance of the class. + + Expression to match url + Expression to generate url + Regular expression options to use, can be null + + [a-zA-Z0-9]+)", "/user/{first}", RegexOptions.IgnoreCase)); + Result of ie. /employee1 will then be /user/employee1 + ]]> + + + + + Initializes a new instance of the class. + + Expression to match url + Expression to generate url + Regular expression options to apply + true if request should be redirected, false if the request uri should be replaced. + + [a-zA-Z0-9]+)", "/user/${first}", RegexOptions.None)); + Result of ie. /employee1 will then be /user/employee1 + ]]> + + + + + Process the incoming request. + + incoming http request + outgoing http response + true if response should be sent to the browser directly (no other rules or modules will be processed). + + returning true means that no modules will get the request. Returning true is typically being done + for redirects. + + If request or response is null + + + + Interface used to load templates from different sources. + + + + + Load a template into a and return it. + + Relative path (and filename) to template. + a if file was found; otherwise null. + + + + Fetch all files from the resource that matches the specified arguments. + + Where the file should reside. + Files to check + a list of files if found; or an empty array if no files are found. + + + + Check's whether a template should be reloaded or not. + + template information + true if template is OK; false if it do not exist or are old. + + + + Returns whether or not the loader has an instance of the file requested + + The name of the template/file + True if the loader can provide the file + + + + Webhelper provides helpers for common tasks in HTML. + + + + + Used to let the website use different javascript libraries. + Default is + + + + + Creates a link that invokes through ajax. + + url to fetch + link title + + optional options in format "key, value, key, value". + Javascript options starts with ':'. + + a link tag + + WebHelper.AjaxRequest("/users/add/", "Add user", "method:", "post", "onclick", "validate('this');"); + + + + + Builds a link that updates an element with the fetched ajax content. + + Url to fetch content from + link title + html element to update with the results of the ajax request. + optional options in format "key, value, key, value" + A link tag. + + + + A link that pop ups a Dialog (overlay div) + + url to contents of dialog + link title + name/value of html attributes. + A "a"-tag that popups a dialog when clicked + + WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); + + + + + Create/Open a dialog box using ajax + + + + + + + + + Close a javascript dialog window/div. + + javascript for closing a dialog. + + + + + Create a <form> tag. + + name of form + action to invoke on submit + form should be posted as ajax + html code + + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); + + + + + Create a link tag. + + url to go to + link title (text that is displayed) + html attributes, name, value, name, value + html code + + WebHelper.Link("/user/show/1", "Show user", "id", "showUser", "onclick", "return confirm('Are you shure?');"); + + + + + Build a link + + url to go to. + title of link (displayed text) + extra html attributes. + a complete link + + + + Build a link + + url to go to. + title of link (displayed text) + extra html attributes. + a complete link + more options + + + + Obsolete + + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + + + + Obsolete + + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + + + + Render errors into a UL with class "errors" + + class used by UL-tag. + items to list + an unordered html list. + + + + Render errors into a UL with class "errors" + + class used by UL-tag. + items to list + an unordered html list. + + + + Render errors into a UL with class "errors" + + + + + + + Generates a list with html attributes. + + StringBuilder that the options should be added to. + attributes set by user. + attributes set by any of the helper classes. + + + + Generates a list with html attributes. + + StringBuilder that the options should be added to. + + + + + Purpose of this class is to create a javascript toolkit independent javascript helper. + + + + + Generates a list with JS options. + + StringBuilder that the options should be added to. + the javascript options. name, value pairs. each string value should be escaped by YOU! + true if we should start with a comma. + + + + Removes any javascript parameters from an array of parameters + + The array of parameters to remove javascript params from + An array of html parameters + + + + javascript action that should be added to the "onsubmit" event in the form tag. + + + All javascript option names should end with colon. + + + JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); + + + + + + Requests a url through ajax + + url to fetch + optional options in format "key, value, key, value", used in JS request object. + a link tag + All javascript option names should end with colon. + + + JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); + + + + + + Ajax requests that updates an element with + the fetched content + + Url to fetch content from + element to update + optional options in format "key, value, key, value", used in JS updater object. + A link tag. + All javascript option names should end with colon. + + + JSHelper.AjaxUpdater("/user/show/1", "userInfo", "onsuccess:", "alert('Successful!');"); + + + + + + A link that pop ups a Dialog (overlay div) + + url to contents of dialog + link title + A "a"-tag that popups a dialog when clicked + name/value of html attributes + + WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); + + + + + Close a javascript dialog window/div. + + javascript for closing a dialog. + + + + + Creates a new modal dialog window + + url to open in window. + window title (may not be supported by all js implementations) + + + + + + Contains a connection to a browser/client. + + + + + Contains a connection to a browser/client. + + + + + Disconnect from client + + error to report in the delegate. + + + + Send a response. + + Either HttpHelper.HTTP10 or HttpHelper.HTTP11 + http status code + reason for the status code. + html body contents, can be null or empty. + If httpVersion is invalid. + + + + Send a response. + + Either HttpHelper.HTTP10 or HttpHelper.HTTP11 + http status code + reason for the status code. + + + + Send a response. + + + + + + send a whole buffer + + buffer to send + + + + + Send data using the stream + + Contains data to send + Start position in buffer + number of bytes to send + + + + + + Using SSL or other encryption method. + + + + + Buffersize determines how large the HTTP header can be. + + + + + Initializes a new instance of the class. + + true if the connection is secured (SSL/TLS) + client that connected. + delegate handling incoming requests. + delegate being called when a client disconnectes + Stream used for communication + If beginreceive fails + delegate used to write log entries + + + + + + Initializes a new instance of the class. + + true if the connection is secured (SSL/TLS) + delegate handling incoming requests. + client that connected + Stream used for communication + If beginreceive fails + + + + + + Disconnect from client + + error to report in the delegate. + + + + This method checks the request if a responde to 100-continue should be sent. + + + 100 continue is a value in the Expect header. + It's used to let the webserver determine if a request can be handled. The client + waits for a reply before sending the body. + + + + + Send a response. + + Either HttpHelper.HTTP10 or HttpHelper.HTTP11 + http status code + reason for the status code. + html body contents, can be null or empty. + If httpVersion is invalid. + + + + Send a response. + + Either HttpHelper.HTTP10 or HttpHelper.HTTP11 + http status code + reason for the status code. + + + + Send a response. + + + + + + send a whole buffer + + buffer to send + + + + + Send data using the stream + + Contains data to send + Start position in buffer + number of bytes to send + + + + + + Using SSL or other encryption method. + + + + + Client have been disconnected. + + Client that was disconnected. + Reason + + + + + Invoked when a client context have received a new HTTP request + + Client that received the request. + Request that was received. + + + + + A controller module is a part of the ModelViewController design pattern. + It gives you a way to create user friendly URLs. + + + The controller module uses the flyweight pattern which means that + the memory usage will continue to increase until the module have + enough objects in memory to serve all concurrent requests. The objects + are reused and will not be freed. + + + + ControllerModule module = new ControllerModule(); + module.Add(new UserController()); + module.Add(new SearchController()); + myWebsite.Add(module); + + + + + + A HttpModule can be used to serve urls. The module itself + decides if it should serve a url or not. In this way, you can + get a very flexible http app since you can let multiple modules + serve almost similiar urls. + + + Throw UnauthorizedException if you are using a AuthenticationModule and want to prompt for username/password. + + + + + Method that process the url + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + true if this module handled the request. + + + + Set the log writer to use. + + logwriter to use. + + + + Log something. + + importance of log message + message + + + + If true specifies that the module doesn't consume the processing of a request so that subsequent modules + can continue processing afterwards. Default is false. + + + + + The controller module uses the prototype design pattern + to be able to create new controller objects for requests + if the stack is empty. + + A prototype which will be cloned for each request + + If a controller with that name have been added already. + + + + Method that process the incoming request. + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + + + + Get a prototype + + in lowercase, without "Controller" + The controller if found; otherwise null. + + + //fetches the class UserController + RequestController userController = controllerModule["user"]; + + + + + + Initializes a new instance of the class. + + A controller used to handle certain URLs. Will be cloned for each parallel request. + + + + Retrieve a previously created controller (or a new one if none exist). + + + + + + Add a controller + + + + + + Prototype controller used for cloning. + + The prototype. + + + + Will contain helper functions for javascript. + + + + + Requests a url through ajax + + url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. + optional options in format "key, value, key, value", used in JS request object. All keys should end with colon. + a link tag + onclick attribute is used by this method. + + + // plain text + JSHelper.AjaxRequest("'/user/show/1'"); + + // ajax request using this.href + string link = "<a href=\"/user/call/1\" onclick=\"" + JSHelper.AjaxRequest("this.href") + "/<call user</a>"; + + + + + + Ajax requests that updates an element with + the fetched content + + url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. + element to update + options in format "key, value, key, value". All keys should end with colon. + A link tag. + + + JSHelper.AjaxUpdater("'/user/show/1'", "user", "onsuccess:", "alert('hello');", "asynchronous:", "true"); + + + + + + Opens contents in a dialog window. + + url to contents of dialog + link title + name, value, name, value, all parameter names should end with colon. + + + + Close a javascript dialog window/div. + + javascript for closing a dialog. + + + + + Delegate used by to populate select options. + + current object (for instance a User). + Text that should be displayed in the value part of a <optiongt;-tag. + Text shown in the select list. + + // Class that is going to be used in a SELECT-tag. + public class User + { + private readonly string _realName; + private readonly int _id; + public User(int id, string realName) + { + _id = id; + _realName = realName; + } + public string RealName + { + get { return _realName; } + } + + public int Id + { + get { return _id; } + } + } + + // Using an inline delegate to generate the select list + public void UserInlineDelegate() + { + List<User> items = new List<User>(); + items.Add(new User(1, "adam")); + items.Add(new User(2, "bertial")); + items.Add(new User(3, "david")); + string htmlSelect = Select("users", "users", items, delegate(object o, out object id, out object value) + { + User user = (User)o; + id = user.Id; + value = user.RealName; + }, 2, true); + } + + // Using an method as delegate to generate the select list. + public void UseExternalDelegate() + { + List<User> items = new List<User>(); + items.Add(new User(1, "adam")); + items.Add(new User(2, "bertial")); + items.Add(new User(3, "david")); + string htmlSelect = Select("users", "users", items, UserOptions, 1, true); + } + + // delegate returning id and title + public static void UserOptions(object o, out object id, out object title) + { + User user = (User)o; + id = user.Id; + value = user.RealName; + } /// + + + + Methods marked with BeforeFilter will be invoked before each request. + + + BeforeFilters should take no arguments and return false + if controller method should not be invoked. + + + + + + Initializes a new instance of the class. + + + BeforeFilters should take no arguments and return false + if controller method should not be invoked. + + + + + Initializes a new instance of the class. + + Specify if the filter should be invoked among the first filters, in between or among the last. + + BeforeFilters should take no arguments and return false + if controller method should not be invoked. + + + + + Filters position in before filter queue + + + + + Determins when a before filter is executed. + + + + + + Filter will be invoked first (unless another filter is added after this one with the First position) + + + + + Invoke after all first filters, and before the last filters. + + + + + Filter will be invoked last (unless another filter is added after this one with the Last position) + + + + + The "basic" authentication scheme is based on the model that the + client must authenticate itself with a user-ID and a password for + each realm. The realm value should be considered an opaque string + which can only be compared for equality with other realms on that + server. The server will service the request only if it can validate + the user-ID and password for the protection space of the Request-URI. + There are no optional authentication parameters. + + + + + Authentication modules are used to implement different + kind of http authentication. + + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + Delegate used to determine if authentication is required (may be null). + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + + + + Create a response that can be sent in the WWW-Authenticate header. + + Realm that the user should authenticate in + Array with optional options. + A correct auth request. + If realm is empty or null. + + + + An authentication response have been received from the web browser. + Check if it's correct + + Contents from the Authorization header + Realm that should be authenticated + GET/POST/PUT/DELETE etc. + options to specific implementations + Authentication object that is stored for the request. A user class or something like that. + if authenticationHeader is invalid + If any of the paramters is empty or null. + + + + Used to invoke the auth delegate that is used to lookup the username/realm. + + Realm (domain) that user want to authenticate in + Username + Password used for validation. Some implementations got password in clear text, they are then sent to client. + object that will be stored in the request to help you identify the user if authentication was successful. + true if authentication was successful + + + + Determines if authentication is required. + + Http request from browser + true if user should be authenticated. + throw ForbiddenException from your delegate if no more attempts are allowed. + If no more attempts are allowed + + + + name used in http request. + + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + Delegate used to determine if authentication is required (may be null). + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + + + + Create a response that can be sent in the WWW-Authenticate header. + + Realm that the user should authenticate in + Not used in basic auth + A correct auth request. + + + + An authentication response have been received from the web browser. + Check if it's correct + + Contents from the Authorization header + Realm that should be authenticated + GET/POST/PUT/DELETE etc. + Not used in basic auth + Authentication object that is stored for the request. A user class or something like that. + if authenticationHeader is invalid + If any of the paramters is empty or null. + + + + name used in http request. + + + + + The follow node allows users to display code in a haml document + + + #main Welcome =user.FirstName + + + + + Child nodes may not be the first node on a line + + + + + A node represents a controller code and contents. For example a html tag, an attribute list or something else. + + + + + Add a new node + + parent node. + + + + Modifiers are used to modify the first node on the line. + Typical modifiers are attribute lists, class names and IDs. + + Modifier node + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + First node on line, used since some nodes cannot exist on their own on a line. + + + + Generate HTML code (with ASP tags) + + + + + + Converts the node to c# code + + true if we are inside the internal stringbuilder + c# code + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + c# code + + + + Generate C# code of the node + + true if we are inside the internal stringbuilder + code is small enough to fit on one row. + smallEnough is a default value, recalc it + c# code + + + + Get intendation level for this node. + + + + + + Returns true if the node is applicable after another node as text instead of being applied as a modifier + + + + + Count our children and our childrens children and so on... + + + + + All child nodes for this node. + + + + + Should only be set for each parent. + + + + + Modifiers are used to modify the first node on the line. + Typical modifiers are attribute lists, class names and IDs. + + + + + Last modifier for this node + + + + + + Number of modifiers for this line. + + + + + Parent node. + + + + + Child nodes may not be the first node on a line + + parent node + + + + Creates a DIV node and add's the specified node to it. + + Contains all prototypes for each control char. used to instanciate new nodes. + parent node + current line information + node to add to the DIV node + current node + + + + Get endposition for this modifier. + + where to start searching + contents of the current line + char that tells us that this is the end position + index on the current line + + + + Get endposition for this modifier. + + where to start searching + contents of the current line + index on the current line + + + + This is a plain text node + + + + + Contains C# code that will be rendered into the view. + + Parent node + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line + + + + Generate HTML for this node (with asp tags for code) + + + + + + = is placed at the end of a tag definition, after class, id, and attribute declarations. + It’s just a shortcut for inserting Ruby code into an element. It works the same as = without a tag: + it inserts the result of the Ruby code into the template. + However, if the result is short enough, it is displayed entirely on one line. + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + Determines if this is a textnode (containg plain text) + + + + + Contains HTML attributes. + + + + + Create a new node + + parent node + collection of attributes + + + + create an attribute node + + parent node + + + + Get an attribute + + name of the attribute (case sensitive) + attribute if found; otherwise null. + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + html attributes + + + + + A attribute + + + + + value is a simple word or quoted text + + + + + Name of the attribute + + + + + Value, can be a statement, variable or quoted text. + + + + + Arguments being used in a template. + + + + + + + Holds the arguments connected to their names for quick access. + (since the ArgumentContainer also holds the name for the argument the mapping with strings is somewhat redundant + but since the data do 'belong' to the ArgumentContainer this solution was chosen to speed up access) + + + + + Initializes the class without any set arguments. + + + + + Initializes the class with all the arguments of the parameter class. + + Cannot be null + If arguments is null + + + + Initializes the class with the objects in the parameterlist. + Note that each object that is null must be followed by a type. + + Should contain ordered pairs/truples of string, object and type where type is optional if the object isn´t null + new TemplateArguments("Dir", "\", "Users", null, typeof(User)); + If optional type differs from type of object (if object != null) or argument name is duplicate + If the order of objects is incorrect + If any argument name or type is null + + + + A function that merges two argument holders updating and adding values + + + If arguments is null + + + + Clears added arguments + + + + + Adds an argument. + (Will throw ArgumentException on duplicates since adding an argument twice points to incorrect code, for ways around + this + + Cannot be null + Cannot be null + If argumentName or argumentObject is null + If an argument named argumentName already exists + + + + Adds an argument. Allows for argumentObject to be null + (Will throw ArgumentException + + Cannot be null + + Cannot be null + If argumentName or argumentType is null + If an argument named argumentName already exists or argumentObject != null and typeof(argumentObject) differs from argumentType + + + + Updates an already added argument + + Cannot be null + Cannot be null + If no argument named argumentName exists + If argumentName or argumentObject is null + + + + Updates an already added argument, allows for argumentObject to be null + + Cannot be null + + Cannot be null + If argumentName or argumentType is null + If an argument named argumentName doesn´t exists or argumentObject != null and typeof(argumentObject) differs from argumentType + + + + Clears all added arguments + + + + + Retrieves the arguments + (Does so now by copying the values to a new array, could be optimized?) + + An array containing arguments with name, object and type + + + + Returns a individual hashcode built upon the specified types the class is holding + + The hashcode is made by joining the typenames of all held arguments and making a string hashcode from them + + + + + Retrieves a concated typename ie DictinaryInt32String + + The type to retrieve the name for + + + + Checks whether a specific argument is specified or not. + + Argument name + true if argument is specified; otherwise false. + + + + Function to make it possible to index out known arguments + + The name of an added argument + Null if no ArgumentContainer by name was found + + + + A container class grouping mapping name, argument type and the argument object + + + + + Contains the name mapped to the argument + + + + + Contains the type of the argument, this must be valid if _argumentObject is null + + + + + Holds the actual object + + + + + Constructor to initiate an ArgumentContainer, will set the ArgumentType to the value of the argumentObject's type + + Cannot be null + Cannot be null + If argumentName or argumentObject is null + + + + Alternative constructor allowing argumentObject parameter to be null + + Cannot be null + + Cannot be null + If argumentName or argumentType is null + If argumentObject != null and argumentType != typeof(argumentObject) + + + + Sets the object and type of the argument, equal to ArgumentContainer.Object = ... + + Cannot be null + If argumentObject is null + + + + Sets the argument object and type. Type of the object and argumentType must correspond. + + + Cannot be null + If argumentType is null + If typeof(argumentObject) differs from argumentType and object != null + + + + Attribute for retrieving the name. The name cannot be set however because an argument is defined by its name + changing the name would be changing the arguments meaning, thus an argument needing a name change should rather + be recreated + + + + + Returns the type of the argument object. The property cannot be set since the type depends on and must correspond to + the type of the object + + + + + Returns or changes the argument object. If the object is to be changed to null the type must be passed aswell, + in that case + + If set value is null + + + + A partial is a HAML template that is inserted into other HAML templates. + + + + + Contains the page/controller target for the partial. + The PartialNode should be written as follows: + ex. + + _"requestedpage"{parametername="parametervalue",parametername2=parameter2,parametername3=parameter3:typeof(parameter3type)} + + + + + create a new partial node. + + parent node + + + + Determines if this node can handle the line (by checking the first word); + + Controller char (word) + True if text belongs to this node type + First node on line. + + + + Parse node contents add return a fresh node. + + Node that this is a subnode to. Can be null + A list with node types + Line to parse + Where to start the parsing. Will be set to where the next node should start parsing + A node corresponding to the bla bla; null if parsing failed. + + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + Helper function to retrieve the code for the partial request + + A string representing the code for invocating a render of the partial + + + + Throw an exception with predefined information + + why the exception was thrown + + + + This is a plain text node + + + + + Returns the page/controller target for the node + + + + + Loads templates from embedded resources. + + + + + Loads templates from a namespace in the given assembly to an uri + + The uri to map the resources to + The assembly in which the resources reside + The namespace from which to load the resources + + resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); + + will make ie the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ + + + + + Load a template into a and return it. + + Relative path (and filename) to template. + + a if file was found; otherwise null. + + + + + Fetch all files from the resource that matches the specified arguments. + + Where the file should reside. + Files to check + + a list of files if found; or an empty array if no files are found. + + + + + Always returns true since a resource won't be updated during execution + + + + + + + Returns whether or not the loader has an instance of the file requested + + The name of the template/file + True if the loader can provide the file + + + + Priority for log entries + + + + + + Very detailed logs to be able to follow the flow of the program. + + + + + Logs to help debug errors in the application + + + + + Information to be able to keep track of state changes etc. + + + + + Something did not go as we expected, but it's no problem. + + + + + Something that should not fail failed, but we can still keep + on going. + + + + + Something failed, and we cannot handle it properly. + + + + + Interface used to write to log files. + + + + + Write an entry to the log file. + + object that is writing to the log + importance of the log message + the message + + + + This class writes to the console. It colors the output depending on the logprio and includes a 3-level stacktrace (in debug mode) + + + + + + The actual instance of this class. + + + + + Logwriters the specified source. + + object that wrote the logentry. + Importance of the log message + The message. + + + + Get color for the specified logprio + + prio for the log entry + A for the prio + + + + Default log writer, writes everything to null (nowhere). + + + + + + The logging instance. + + + + + Writes everything to null + + object that wrote the logentry. + Importance of the log message + The message. + + + + Contains some kind of input from the browser/client. + can be QueryString, form data or any other request body content. + + + + + Base class for request data containers + + + + + Adds a parameter mapped to the presented name + + The name to map the parameter to + The parameter value + + + + Returns true if the container contains the requested parameter + + Parameter id + True if parameter exists + + + + Returns a request parameter + + The name associated with the parameter + + + + Representation of a non-initialized class instance + + + Variable telling the class that it is non-initialized + + + + Initializes a new instance of the class. + + form name. + + + + Initializes a new instance of the class. + + form name. + if set to true all changes will be ignored. + this constructor should only be used by Empty + + + Creates a deep copy of the HttpInput class + The object to copy + The function makes a deep copy of quite a lot which can be slow + + + + Add a new element. Form array elements are parsed + and added in a correct hierachy. + + Name is converted to lower case. + + + + + Returns true if the class contains a HttpInput value with the corresponding name + + The field/querystring name + True if the value exists + + + + Parses an item and returns it. + This function is primarly used to parse array items as in user[name]. + + + + + + + Outputs the instance representing all its values joined together + + + + Returns all items as an unescaped query string. + + + + + Extracts one parameter from an array + + Containing the string array + All but the first value + + string test1 = ExtractOne("system[user][extension][id]"); + string test2 = ExtractOne(test1); + string test3 = ExtractOne(test2); + // test1 = user[extension][id] + // test2 = extension[id] + // test3 = id + + + + Resets all data contained by class + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Returns an enumerator that iterates through a collection. + + + + An object that can be used to iterate through the collection. + + 2 + + + + Form name as lower case + + + + + Get a form item. + + + Returns HttpInputItem.Empty if item was not found. + + + + Returns item either from a form or a query string (checks them in that order) + + + + Representation of a non-initialized HttpParam + + + Initialises the class to hold a value either from a post request or a querystring request + + + + The add method is not availible for HttpParam + since HttpParam checks both Request.Form and Request.QueryString + + name identifying the value + value to add + + + + + Checks whether the form or querystring has the specified value + + Name, case sensitive + true if found; otherwise false. + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Returns an enumerator that iterates through a collection. + + + + An object that can be used to iterate through the collection. + + 2 + + + + Fetch an item from the form or querystring (in that order). + + + Item if found; otherwise HttpInputItem.EmptyLanguageNode + + + + Container class for posted files + + + + + Creates a container for a posted file + + The identifier of the post field + The file path + The content type of the file + The name of the file uploaded + If any parameter is null or empty + + + + Creates a container for a posted file + + If any parameter is null or empty + + + Destructor disposing the file + + + + Deletes the temporary file + + True if manual dispose + + + + Disposing interface, cleans up managed resources (the temporary file) and suppresses finalization + + + + + The name/id of the file + + + + + The full file path + + + + + The name of the uploaded file + + + + + The type of file + + + + + The object form class takes an object and creates form items for it. + + + + + Initializes a new instance of the class. + + + form name *and* id. + action to do when form is posted. + + + + + Initializes a new instance of the class. + + form name *and* id. + action to do when form is posted. + object to get values from + + + + Initializes a new instance of the class. + + form action. + object to get values from. + + + + write out the FORM-tag. + + generated html code + + + + Writeout the form tag + + form should be posted through ajax. + generated html code + + + + Generates a text box. + + + + generated html code + + + + password box + + + + generated html code + + + + Hiddens the specified property name. + + Name of the property. + The options. + generated html code + + + + Labels the specified property name. + + property in object. + caption + generated html code + + + + Generate a checkbox + + property in object + checkbox value + additional html attributes. + generated html code + + + + Write a html select tag + + object property. + id column + The title column. + The options. + + + + + Selects the specified property name. + + Name of the property. + The items. + The id column. + The title column. + The options. + + + + + Write a submit tag. + + button caption + html submit tag + + + + html end form tag + + html + + + + This provider is used to let us implement any type of form decoding we want without + having to rewrite anything else in the server. + + + + + + + Should contain boundary and type, as in: multipart/form-data; boundary=---------------------------230051238959 + Stream containg form data. + Encoding used when decoding the stream + HttpInput.EmptyLanguageNode if no parser was found. Must always return something (HttpInput.Empty instead of null) + If stream is null or not readable. + If stream contents cannot be decoded properly. + + + + Add a decoder. + + + + + + + Number of added decoders. + + + + + Use with care. + + + + + Decoder used for unknown content types. + + + + + Contains an (html) attribute list. + + + + + Rules are used during preparse + + + + + Determines if this node spans over multiple lines. + + contains line information (and text) + true if rule have previously inited a multiline. + true if this line continues onto the next./// + + + + Determines if this node spans over multiple lines. + + contains line information (and text) + true if the previous line was continued. + true if this line continues onto the next. + + + + A text only node. + + + + + + + parent node + plain text + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + true if this is the first node on the line. + + + + Generate HTML for this node. + + + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + todo: add description + c# code + + + + The text. + + + + + Is this a text node (containing plain text)? + + + + + Serves files that are stored in embedded resources. + + + + + Initializes a new instance of the class. + Runs to make sure the basic mime types are available, they can be cleared later + through the use of if desired. + + + + + Mimtypes that this class can handle per default + + + + + Loads resources from a namespace in the given assembly to an uri + + The uri to map the resources to + The assembly in which the resources reside + The namespace from which to load the resources + + resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); + + will make ie the resource MyLib.Models.User.Views.stylesheet.css accessible via /user/stylesheet.css + + + + + Returns true if the module can handle the request + + + + + Method that process the url + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + true if this module handled the request. + + + + List with all mime-type that are allowed. + + All other mime types will result in a Forbidden http status code. + + + + This decoder converts XML documents to form items. + Each element becomes a subitem in the form, and each attribute becomes an item. + + + // xml: somethingdata + // result: + // form["hello"].Value = "something" + // form["hello"]["id"].Value = 1 + // form["hello"]["world]["id"].Value = 1 + // form["hello"]["world"].Value = "data" + + + The original xml document is stored in form["__xml__"].Value. + + + + + Interface for form content decoders. + + + + + + + Stream containing the content + Content type (with any additional info like boundry). Content type is always supplied in lower case + Stream enconding + A http form, or null if content could not be parsed. + If contents in the stream is not valid input data. + + + + Checks if the decoder can handle the mime type + + Content type (with any additional info like boundry). Content type is always supplied in lower case. + True if the decoder can parse the specified content type + + + + + + Stream containing the content + Content type (with any additional info like boundry). Content type is always supplied in lower case + Stream encoding + Note: contentType and encoding are not used? + A http form, or null if content could not be parsed. + + + + + Recursive function that will go through an xml element and store it's content + to the form item. + + (parent) Item in form that content should be added to. + Node that should be parsed. + + + + Checks if the decoder can handle the mime type + + Content type (with any additional info like boundry). Content type is always supplied in lower case. + True if the decoder can parse the specified content type + + + + This attribute can be used to map a controller to a specific url without using + the class name. + + + + + Maps a controller to a url without using the controller name. + + + Per default the class name is used to determine which url to handle. + For instance, "class UserController" or "class User" tells the framework that + the urls that starts with "/user" should be handled by that controller. + This attribute can be used to circumvent that. + + The name. + + + + The name that the controller should use + + + + + A session store is used to store and load sessions on a media. + The default implementation () saves/retrieves sessions from memory. + + + + + Creates a new http session with a generated id. + + A object + + + + Creates a new http session with a specific id + + Id used to identify the new cookie.. + A object. + + Id should be generated by the store implementation if it's null or . + + + + + Load an existing session. + + Session id (usually retrieved from a client side cookie). + A session if found; otherwise null. + + + + Save an updated session to the store. + + Session id (usually retrieved from a client side cookie). + If Id property have not been specified. + + + + We use the flyweight pattern which reuses small objects + instead of creating new each time. + + Unused session that should be reused next time Create is called. + + + + Remove expired sessions + + + + + Remove a session + + id of the session. + + + + Load a session from the store + + + null if session is not found. + + + + Number of minutes before a session expires. + + Default time is 20 minutes. + + + + HTTP Listener waits for HTTP connections and provide us with s using the + delegate. + + + + + Listen for regular HTTP connections + + IP Address to accept connections on + TCP Port to listen on, default HTTP port is 80. + + + + Launch HttpListener in SSL mode + + IP Address to accept connections on + TCP Port to listen on, default HTTPS port is 443 + Certificate to use + + + + Launch HttpListener in SSL mode + + IP Address to accept connections on + TCP Port to listen on, default HTTPS port is 443 + Certificate to use + which HTTPS protocol to use, default is TLS. + + + + Start listen for new connections + + Number of connections that can stand in a queue to be accepted. + + + + Stop the listener + + + + + + A client have been accepted, but not handled, by the listener. + + + + + Invoked when a client disconnects + + + + + Gives you a change to receive log entries for all internals of the HTTP library. + + + You may not switch log writer after starting the listener. + + + + + This handler will be invoked each time a new connection is accepted. + + + + + True if we should turn on trace logs. + + + + + Let's to receive unhandled exceptions from the threads. + + + Exceptions will be thrown during debug mode if this event is not used, + exceptions will be printed to console and suppressed during release mode. + + + + + PrototypeJS implementation of the javascript functions. + + + + + Requests a url through ajax + + url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. + optional options in format "key, value, key, value", used in JS request object. All keys should end with colon. + a link tag + onclick attribute is used by this method. + + + // plain text + JSHelper.AjaxRequest("'/user/show/1'"); + + // ajax request using this.href + string link = "<a href=\"/user/call/1\" onclick=\"" + JSHelper.AjaxRequest("this.href") + "/<call user</a>"; + + + + + + Determins if a list of strings contains a specific value + + options to check in + value to find + true if value was found + case insensitive + + + + Ajax requests that updates an element with + the fetched content + + url to fetch. Url is NOT enclosed in quotes by the implementation. You need to do that yourself. + element to update + options in format "key, value, key, value". All keys should end with colon. + A link tag. + + + JSHelper.AjaxUpdater("'/user/show/1'", "user", "onsuccess:", "alert('hello');", "asynchronous:", "true"); + + + + + + A link that pop ups a Dialog (overlay div) + + url to contents of dialog + link title + name, value, name, value + + A "a"-tag that popups a dialog when clicked + + Requires Control.Modal found here: http://livepipe.net/projects/control_modal/ + And the following javascript (load it in application.js): + + Event.observe(window, 'load', + function() { + document.getElementsByClassName('modal').each(function(link){ new Control.Modal(link); }); + } + ); + + + + WebHelper.DialogLink("/user/show/1", "show user", "onmouseover", "alert('booh!');"); + + + + + create a modal dialog (usually using DIVs) + + url to fetch + dialog title + javascript/html attributes. javascript options ends with colon ':'. + + + + + Close a javascript dialog window/div. + + javascript for closing a dialog. + + + + + javascript action that should be added to the "onsubmit" event in the form tag. + + remember to encapsulate strings in '' + + All javascript option names should end with colon. + + + JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); + + + + + + The requested resource was not found in the web server. + + + + + All HTTP based exceptions will derive this class. + + + + + Create a new HttpException + + http status code (sent in the response) + error description + + + + Create a new HttpException + + http status code (sent in the response) + error description + inner exception + + + + status code to use in the response. + + + + + Create a new exception + + message describing the error + inner exception + + + + Create a new exception + + message describing the error + + + + A controller in the Model-View-Controller pattern. + Derive this class and add method with one of the following signatures: + "public string MethodName()" or "public void MyMethod()". + + The first should return a string with the response, the latter + should use SendHeader and SendBody methods to handle the response. + + + Last segment of the path is always broken into the properties Id and RequestedType + Alhtough note that the RequestedType can also be empty if no file extension have + been specified. A typical use of file extensions in controllers is to specify which type of + format to return. + + + public class MyController : RequestController + { + public string Hello() + { + if (RequestedType == "xml") + return "<hello>World<hello>"; + else + return "Hello " + Request.QueryString["user"].Value + ", welcome to my world"; + } + + public void File() + { + Response.Headers.ContentType = "text/xml"; + Response.SendHeader(); + } + } + + + + + + + + create a new request controller + + prototype to copy information from + + + + create a new controller + + + + + Method that determines if an url should be handled or not by the module + + Url requested by the client. + true if module should handle the url. + + + + Determines which method to use. + + Requested resource + + + + Call all before filters + + true if a before filter wants to abort the processing. + + + + Override this method to be able to process result + returned by controller method. + + + + + Override this method if you want to be able to + handle unhanded exceptions + + thrown exception + Don't "eat" exceptions derived from HttpException since + they are handled by the framework,unless your are sure of what you are + doing.. + + + + This method goes through all methods in the controller and + add's them to a dictionary. They are later used to invoke + the correct method depending on the url + + + + + Method that process the url + + Uses Uri and QueryString to determine method. + Relays response object to invoked method. + Relays session object to invoked method. + + + + Will assign all variables that are unique for each session + + + + + + + + Make a clone of this controller + + a new controller with the same base information as this one. + + + + object that was attached during http authentication process. + + + You can also assign this tag yourself if you are using regular + http page login. + + + + + + Name of this controller (class name without the "Controller" part) + + + + + Specifies the method to use if no action have been specified. + + If specified method do not exist. + + + + Id is the third part of the uri path. + + + Is extracted as in: /controllername/methodname/id/ + + string.Empty if not specified. + + + + + + Method currently being invoked. + Always in lower case. + + + + + Request information (like Url, form, querystring etc) + + + + + Extension if a filename was specified. + + + + + Response information (that is going to be sent back to the browser/client) + + + + + Session information, is stored between requests as long as the session cookie is valid. + + + + + Marks methods to let framework know that the method is protected + + + + + + + Initializes a new instance of the class. + + + + + + + + Level is a value defined by you. It should be used to determine the users + that can access the method tagged with the AuthRequired attribute. + + + = level; + } + } + ]]> + + + + + Level is a value defined by you. It should be used to determine the users + that can access the method tagged with the AuthRequired attribute. + + + + + A session stored in memory. + + + + + Interface for sessions + + + + + Remove everything from the session + + + + + Remove everything from the session + + True if the session is cleared due to expiration + + + + Session id + + + + + Should + + Name of the session variable + null if it's not set + If the object cant be serialized. + + + + When the session was last accessed. + This property is touched by the http server each time the + session is requested. + + + + + Number of session variables. + + + + + Event triggered upon clearing the session + + + + + + + A unique id used by the sessions store to identify the session + + + + Id + + + + + + Remove everything from the session + + + + + Clears the specified expire. + + True if the session is cleared due to expiration + + + + Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + + 2 + + + + Session id + + + + + Should + + Name of the session variable + null if it's not set + + + + when the session was last accessed. + + + Used to determine when the session should be removed. + + + + + Number of values in the session + + + + + Flag to indicate that the session have been changed + and should be saved into the session store. + + + + + Event triggered upon clearing the session + + + + + IRule that says that something :) + + + + + Determines if this node spans over multiple lines. + + contains line information (and text) + true if the previous line was continued. + true if this line continues onto the next. + + + + Represents a HTML tag. + + + + + Create a new HTML tag node. + + parent node + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line. + + + + Parse node contents add return a fresh node. + + Node that this is a subnode to. Can be null + A list with node types + Line to parse + Where to start the parsing. Will be set to where the next node should start parsing + A node corresponding to the bla bla; null if parsing failed. + + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + This is a plain text node + + + + + tag name + + + + + Thrown when a template cannot be compiled. + + + + + Initializes a new instance of the class. + + Template that failed compilation. + Exception thrown by the compiler. + + + + Creates and returns a string representation of the current exception. + + + A string representation of the current exception. + + + + + + + + Gets a message that describes the current exception. + + + + The error message that explains the reason for the exception, or an empty string(""). + + + + + Contains all HTTP Methods (according to the HTTP 1.1 specification) + + See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + + + + + + The DELETE method requests that the origin server delete the resource identified by the Request-URI. + + + + This method MAY be overridden by human intervention (or other means) on the origin server. + The client cannot be guaranteed that the operation has been carried out, even if the status code + returned from the origin server indicates that the action has been completed successfully. + + + However, the server SHOULD NOT indicate success unless, at the time the response is given, + it intends to delete the resource or move it to an inaccessible location. + + + A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, + 202 (Accepted) if the action has not yet been enacted, + or 204 (No Content) if the action has been enacted but the response does not include an entity. + + + If the request passes through a cache and the Request-URI identifies one or more currently cached entities, + those entries SHOULD be treated as stale. Responses to this method are not cacheable. + + + + + + The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. + + + + If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the + entity in the response and not the source text of the process, unless that text happens to be the output of the process. + + + The semantics of the GET method change to a "conditional GET" if the request message includes an + If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. + A conditional GET method requests that the entity be transferred only under the circumstances described + by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network + usage by allowing cached entities to be refreshed without requiring multiple requests or transferring + data already held by the client. + + + + + + The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. + + + The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the + information sent in response to a GET request. This method can be used for obtaining metainformation about + the entity implied by the request without transferring the entity-body itself. + + This method is often used for testing hypertext links for validity, accessibility, and recent modification. + + + + + The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. + + + This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. + + + + + The POST method is used to request that the origin server accept the entity enclosed + in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. + + + POST is designed to allow a uniform method to cover the following functions: + + + Annotation of existing resources; + + Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; + + Providing a block of data, such as the result of submitting a form, to a data-handling process; + + Extending a database through an append operation. + + + + If a resource has been created on the origin server, the response SHOULD be 201 (Created) and + contain an entity which describes the status of the request and refers to the new resource, and a + Location header (see section 14.30). + + + The action performed by the POST method might not result in a resource that can be identified by a URI. + In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on + whether or not the response includes an entity that describes the result. + + Responses to this method are not cacheable, unless the response includes appropriate Cache-Control + or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent + to retrieve a cacheable resource. + + + + + + The PUT method requests that the enclosed entity be stored under the supplied Request-URI. + + + + + If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a + modified version of the one residing on the origin server. + + If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new + resource by the requesting user agent, the origin server can create the resource with that URI. + + If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. + + If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to + indicate successful completion of the request. + + If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be + given that reflects the nature of the problem. + + + + The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not + understand or implement and MUST return a 501 (Not Implemented) response in such cases. + + + + + + The TRACE method is used to invoke a remote, application-layer loop- back of the request message. + + + + + Contains all HTTP Methods (according to the HTTP 1.1 specification) + + See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + + + + + + The DELETE method requests that the origin server delete the resource identified by the Request-URI. + + + + This method MAY be overridden by human intervention (or other means) on the origin server. + The client cannot be guaranteed that the operation has been carried out, even if the status code + returned from the origin server indicates that the action has been completed successfully. + + + However, the server SHOULD NOT indicate success unless, at the time the response is given, + it intends to delete the resource or move it to an inaccessible location. + + + A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, + 202 (Accepted) if the action has not yet been enacted, + or 204 (No Content) if the action has been enacted but the response does not include an entity. + + + If the request passes through a cache and the Request-URI identifies one or more currently cached entities, + those entries SHOULD be treated as stale. Responses to this method are not cacheable. + + + + + + The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. + + + + If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the + entity in the response and not the source text of the process, unless that text happens to be the output of the process. + + + The semantics of the GET method change to a "conditional GET" if the request message includes an + If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. + A conditional GET method requests that the entity be transferred only under the circumstances described + by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network + usage by allowing cached entities to be refreshed without requiring multiple requests or transferring + data already held by the client. + + + + + + The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. + + + The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the + information sent in response to a GET request. This method can be used for obtaining metainformation about + the entity implied by the request without transferring the entity-body itself. + + This method is often used for testing hypertext links for validity, accessibility, and recent modification. + + + + + The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. + + + This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. + + + + + The POST method is used to request that the origin server accept the entity enclosed + in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. + + + POST is designed to allow a uniform method to cover the following functions: + + + Annotation of existing resources; + + Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; + + Providing a block of data, such as the result of submitting a form, to a data-handling process; + + Extending a database through an append operation. + + + + If a resource has been created on the origin server, the response SHOULD be 201 (Created) and + contain an entity which describes the status of the request and refers to the new resource, and a + Location header (see section 14.30). + + + The action performed by the POST method might not result in a resource that can be identified by a URI. + In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on + whether or not the response includes an entity that describes the result. + + Responses to this method are not cacheable, unless the response includes appropriate Cache-Control + or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent + to retrieve a cacheable resource. + + + + + + The PUT method requests that the enclosed entity be stored under the supplied Request-URI. + + + + + If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a + modified version of the one residing on the origin server. + + If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new + resource by the requesting user agent, the origin server can create the resource with that URI. + + If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. + + If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to + indicate successful completion of the request. + + If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be + given that reflects the nature of the problem. + + + + The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not + understand or implement and MUST return a 501 (Not Implemented) response in such cases. + + + + + + The TRACE method is used to invoke a remote, application-layer loop- back of the request message. + + + + + Contains serverside http request information. + + + + + Decode body into a form. + + A list with form decoders. + If body contents is not valid for the chosen decoder. + If body is still being transferred. + + + + Sets the cookies. + + The cookies. + + + + Called during parsing of a IHttpRequest. + + Name of the header, should not be url encoded + Value of the header, should not be url encoded + If a header is incorrect. + + + + Add bytes to the body + + buffer to read bytes from + where to start read + number of bytes to read + Number of bytes actually read (same as length unless we got all body bytes). + + If body is not writable + + + + Clear everything in the request + + + + + Have all body content bytes been received? + + + + + Kind of types accepted by the client. + + + + + Submitted body contents + + + + + Kind of connection used for the session. + + + + + Number of bytes in the body + + + + + Headers sent by the client. All names are in lower case. + + + + + Version of http. + Probably HttpHelper.HTTP10 or HttpHelper.HTTP11 + + + + + + Requested method, always upper case. + + + + + + Variables sent in the query string + + + + + Requested URI (url) + + + + + Uri absolute path splitted into parts. + + + // uri is: http://gauffin.com/code/tiny/ + Console.WriteLine(request.UriParts[0]); // result: code + Console.WriteLine(request.UriParts[1]); // result: tiny + + + If you're using controllers than the first part is controller name, + the second part is method name and the third part is Id property. + + + + + + Check's both QueryString and Form after the parameter. + + + + + Form parameters. + + + + Returns true if the request was made by Ajax (Asyncronous Javascript) + + + Returns set cookies for the request + + + + Parses a HTTP request directly from a stream + + + + + Create a new request parser + + delegate called when a complete request have been generated + delegate receiving log entries. + + + + Add a number of bytes to the body + + + + + + + + + Remove all state information for the request. + + + + + Parse request line + + + If line is incorrect + Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF" + + + + We've parsed a new header. + + Name in lower case + Value, unmodified. + If content length cannot be parsed. + + + + Parse a message + + + where in buffer that parsing should start + number of bytes to parse + Unparsed bytes left in buffer. + + + + Current state in parser. + + + + + Invoked when a request have been completed. + + + + + + Current state in the parsing. + + + + + Should parse the request line + + + + + Searching for a complete header name + + + + + Searching for colon after header name (ignoring white spaces) + + + + + Searching for start of header value (ignoring white spaces) + + + + + Searching for a complete header value (can span over multiple lines, as long as they are prefixed with one/more whitespaces) + + + + + Adding bytes to body + + + + + Contains serverside http request information. + + + + + Chars used to split an url path into multiple parts. + + + + + Assign a form. + + + + + + Creates a new object that is a copy of the current instance. + + + + A new object that is a copy of this instance. + + 2 + + + + Decode body into a form. + + A list with form decoders. + If body contents is not valid for the chosen decoder. + If body is still being transferred. + + + + Cookies + + the cookies + + + + Called during parsing of a IHttpRequest. + + Name of the header, should not be url encoded + Value of the header, should not be url encoded + If a header is incorrect. + + + + Add bytes to the body + + buffer to read bytes from + where to start read + number of bytes to read + Number of bytes actually read (same as length unless we got all body bytes). + + If body is not writable + + + + Clear everything in the request + + + + + Have all body content bytes been received? + + + + + Kind of types accepted by the client. + + + + + Submitted body contents + + + + + Kind of connection used for the session. + + + + + Number of bytes in the body + + + + + Headers sent by the client. All names are in lower case. + + + + + Version of http. + Probably HttpHelper.HTTP10 or HttpHelper.HTTP11 + + + + + + Requested method, always upper case. + + + + + + Variables sent in the query string + + + + + Requested URI (url) + + + + + + Uri absolute path splitted into parts. + + + // uri is: http://gauffin.com/code/tiny/ + Console.WriteLine(request.UriParts[0]); // result: code + Console.WriteLine(request.UriParts[1]); // result: tiny + + + If you're using controllers than the first part is controller name, + the second part is method name and the third part is Id property. + + + + + + Path and query (will be merged with the host header) and put in Uri + + + + + + Check's both QueryString and Form after the parameter. + + + + + Form parameters. + + + + Returns true if the request was made by Ajax (Asyncronous Javascript) + + + Returns set cookies for the request + + + + Current request is sent over secure protocol + + + + + The website module let's you handle multiple websites in the same server. + It uses the "Host" header to check which site you want. + + It's recommended that you do not + add any other modules to HttpServer if you are using the website module. Instead, + add all wanted modules to each website. + + + + + + domain name that should be handled. + + + + + Method that process the url + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + + + + Name of site. + + + + + Helpers making it easier to work with forms. + + + + + + Used to let the website use different javascript libraries. + Default is + + + + + Create a <form> tag. + + name of form + action to invoke on submit + form should be posted as ajax + html code + + + // without options + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); + + // with options + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax, "style", "display:inline", "class", "greenForm"); + + + html attributes or javscript options. + Method will ALWAYS be POST. + + + + Creates a select list with the values in a collection. + + Name of the SELECT-tag + collection used to generate options. + delegate used to return id and title from objects. + value that should be marked as selected. + First row should contain an empty value. + string containtain a SELECT-tag. + + + + + Creates a select list with the values in a collection. + + Name of the SELECT-tag + Id of the SELECT-tag + collection used to generate options. + delegate used to return id and title from objects. + value that should be marked as selected. + First row should contain an empty value. + string containtain a SELECT-tag. + + + + // Class that is going to be used in a SELECT-tag. + public class User + { + private readonly string _realName; + private readonly int _id; + public User(int id, string realName) + { + _id = id; + _realName = realName; + } + public string RealName + { + get { return _realName; } + } + + public int Id + { + get { return _id; } + } + } + + // Using an inline delegate to generate the select list + public void UserInlineDelegate() + { + List<User> items = new List<User>(); + items.Add(new User(1, "adam")); + items.Add(new User(2, "bertial")); + items.Add(new User(3, "david")); + string htmlSelect = Select("users", "users", items, delegate(object o, out object id, out object value) + { + User user = (User)o; + id = user.Id; + value = user.RealName; + }, 2, true); + } + + // Using an method as delegate to generate the select list. + public void UseExternalDelegate() + { + List<User> items = new List<User>(); + items.Add(new User(1, "adam")); + items.Add(new User(2, "bertial")); + items.Add(new User(3, "david")); + string htmlSelect = Select("users", "users", items, UserOptions, 1, true); + } + + // delegate returning id and title + public static void UserOptions(object o, out object id, out object title) + { + User user = (User)o; + id = user.Id; + value = user.RealName; + } + + + + + + Creates a select list with the values in a collection. + + Name of the SELECT-tag + Id of the SELECT-tag + collection used to generate options. + delegate used to return id and title from objects. + value that should be marked as selected. + First row should contain an empty value. + name, value collection of extra html attributes. + string containtain a SELECT-tag. + + + + + Generate a list of HTML options + + collection used to generate options. + delegate used to return id and title from objects. + value that should be marked as selected. + First row should contain an empty value. + + + + + Creates a checkbox. + + element name + element value + determines if the check box is selected or not. This is done diffrently depending on the + type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if + the box is checked or not. + a list with additional attributes (name, value, name, value). + a generated radio button + + + + Creates a checkbox. + + element name + element id + element value + determines if the check box is selected or not. This is done diffrently depending on the + type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if + the box is checked or not. + a list with additional attributes (name, value, name, value). + a generated radio button + + value in your business object. (check box will be selected if it matches the element value) + + + + + Creates a checkbox. + + element name + element id + determines if the check box is selected or not. This is done diffrently depending on the + type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if + the box is checked or not. + a list with additional attributes (name, value, name, value). + a generated radio button + will set value to "1". + + + + Creates a RadioButton. + + element name + element value + determines if the radio button is selected or not. This is done diffrently depending on the + type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if + the box is checked or not. + a list with additional attributes (name, value, name, value). + a generated radio button + + + + Creates a RadioButton. + + element name + element id + element value + determines if the radio button is selected or not. This is done diffrently depending on the + type of variable. A bool simply trigges checked or not, all other types are compared with "value" to determine if + the box is checked or not. + a list with additional attributes (name, value, name, value). + a generated radio button + + + + form close tag + + + + + + The request could not be understood by the server due to malformed syntax. + The client SHOULD NOT repeat the request without modifications. + + Text taken from: http://www.submissionchamber.com/help-guides/error-codes.php + + + + + Create a new bad request exception. + + reason to why the request was bad. + + + + Create a new bad request exception. + + reason to why the request was bad. + inner exception + + + + Implements HTTP Digest authentication. It's more secure than Basic auth since password is + encrypted with a "key" from the server. + + + Keep in mind that the password is encrypted with MD5. Use a combination of SSL and digest auth to be secure. + + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + Delegate used to determine if authentication is required (may be null). + + + + Initializes a new instance of the class. + + Delegate used to provide information used during authentication. + + + + Used by test classes to be able to use hardcoded values + + + + + An authentication response have been received from the web browser. + Check if it's correct + + Contents from the Authorization header + Realm that should be authenticated + GET/POST/PUT/DELETE etc. + First option: true if username/password is correct but not cnonce + + Authentication object that is stored for the request. A user class or something like that. + + if authenticationHeader is invalid + If any of the paramters is empty or null. + + + + Encrypts parameters into a Digest string + + Realm that the user want's to log into. + User logging in + Users password. + HTTP metod. + Uri/domain that generated the login prompt. + The qop. + The nonce. + The nc. + The cnonce. + Digest enrypted string + + + + Create a response that can be sent in the WWW-Authenticate header. + + Realm that the user should authenticate in + First options specifies if true if username/password is correct but not cnonce. + A correct auth request. + If realm is empty or null. + + + + Decodes authorization header value + + header value + Encoding that the buffer is in + All headers and their values if successful; otherwise null + + NameValueCollection header = DigestAuthentication.Decode("response=\"6629fae49393a05397450978507c4ef1\",\r\nc=00001", Encoding.ASCII); + + Can handle lots of whitespaces and new lines without failing. + + + + Gets the current nonce. + + + + + + Gets the Md5 hash bin hex2. + + To be hashed. + + + + + determines if the nonce is valid or has expired. + + nonce value (check wikipedia for info) + true if the nonce has not expired. + + + + name used in http request. + + + + + Session store using memory for each session. + + + + + Initializes the class setting the expirationtimer to clean the session every minute + + + + + Delegate for the cleanup timer + + + + + Creates a new http session + + + + + + Creates a new http session with a specific id + + Id used to identify the new cookie.. + A object. + + Id should be generated by the store implementation if it's null or . + + + + + Load an existing session. + + + + + + + Save an updated session to the store. + + + + + + We use the flyweight pattern which reuses small objects + instead of creating new each time. + + EmptyLanguageNode (unused) session that should be reused next time Create is called. + + + + Remove expired sessions + + + + + Remove a session + + id of the session. + + + + Load a session from the store + + + null if session is not found. + + + + Number of minutes before a session expires. + Default is 20 minutes. + + + + + Keeps information about templates, so we know when to regenerate it. + + + + + When the template was compiled. + + Use this date to determine if the template is old and needs to be recompiled. + + + + Template file name. + + + + + The actual template. + + + + + Validator is used to validate all input items in a form. + + + + + Initializes a new instance of the class. + + collection to be filled with errors + + + + Initializes a new instance of the class. + + collection to be filled with errors + Translation used to translate the "name" parameters in all validation methods. + + + + Initializes a new instance of the class. + + Translation used to translate the "name" parameters in all validation methods. + + + + + + form that validation should be made on. + + + + + + collection that all validation errors are added to. + form that validation should be made on. + + + + + + collection that all validation errors are added to. + form that validation should be made on. + Language category used to translate field names. + + + + Switch to a new http input. + + form to use validation for now + + + + Switch to a new http input. + + form to use validation for now + language for the validation + + + + Check if a value is digits only + + Field name. + true if field is required (may not be empty) + string if validated, otherwise string.Empty + + + + Check if a value is digits only + + Field name. + extra characters that is allowed. + true if field is required (may not be empty) + string if validated, otherwise string.Empty + + + + Check whether the specified form item is an integer. + + Form parameter to validate + value if parameter is an int; 0 if not. + + + + Check whether the specified form item is an integer. + + Form parameter to validate + Paramater is required (adds an error if it's not specified) + value if parameter is an int; 0 if not. + + + + Check whether the specified value is a double. + + Name of the parameter + Paramater is required (adds an error if it's not specified) + value if parameter is a double; 0 if not. + + + + Check whether the specified value is a currency amount. + + Name of the parameter + Paramater is required (adds an error if it's not specified) + value if parameter is a currency amount; 0 if not. + + + + Validates a string to hex + + The name of the field to validate + If the field must be set + The value if validated otherwise string.Empty + + + + Validate that a string only contains letters or digits. + + Name of form parameter to validate. + Value is required. + value if valid; otherwise string.EmptyLanguageNode. + + + + Validate that a string only contains letters or digits. + + Form parameter name. + vaue if found; otherwise string.Empty + + + + Validate that a string only contains letters, digits or the specified characters + + Form parameter name. + may not be null or empty if true. + any other allowed characters. + value if valid; otherwise string.Empty + + + + Validate that a string consists of only letters (including special letters) + + + If a value must be passed + + + + + Validate that a string consists of only letters (a-z and A-Z) + + + If a value must be passed + A string of extra character to test against, dont forget language specific characters and spaces if wished for + + + + + Check whether the specified value is an integer. + + Name of the parameter + value if parameter contains valid characters; string.Empty if not. + + + + Check whether the specified value is an integer. + + Name of the parameter + Paramater is required (adds an error if it's not specified) + value if parameter contains valid characters; string.Empty if not. + + + + Validate that a string only contains letters or digits or any of the . + + Name of form parameter to validate. + Value is required. + value if valid; otherwise string.Empty. + + + + Validate that a string only contains letters or digits or any of the . + + Form parameter name. + vaue if found; otherwise string.Empty + + + + Check's weather a parameter is null or not. + + Parameter in form + true if value is not null; otherwise false. + + + + Validate a string value + + Name of form parameter to validate. + Value is required. + value if valid; otherwise string.Empty. + + + + Validate a string parameter in the form + + Form parameter name. + vaue if found; otherwise string.Empty + + + + validates email address using a regexp. + + field name + field is required (may not be null or empty). + value if validation is ok; otherwise string.Empty. + + + + Check whether the specified value is an character. + + Name of the parameter + Paramater is required (adds an error if it's not specified) + value if parameter is an int; char.MinValue if not. + + + + Check whether the specified value is an character. + + Name of the parameter + value if parameter is an int; char.MinValue if not. + + + + Checks whether a field is true (can also be in native language). + + field name + field is required (may not be null or empty). + true if value is true; false if value is false or if validation failed. + Check validation errors to see if error ocurred. + + + + Checks whether a field is true (can also be in native language). + + field name + true if value is true; false if value is false or if validation failed. + Check validation errors to see if error ocurred. + + + + Class to handle loading of resource files + + + + + ]]> + + + + Parses a filename and sets it to the extensionless name in lowercase. The extension is cut out without the dot. + + + + + string ext; + string filename = "/uSeR/teSt.haMl"; + ParseName(ref filename, out ext); + Console.WriteLine("File: " + filename); + Console.WriteLine("Ext: " + ext); + -> user/test + -> haml + + + + + Add a resource to a specified uri without extension, ie user/test + + The uri to add the resource to + The instance describing the resource + + + + Loads resources from a namespace in the given assembly to an uri + + The uri to map the resources to + The assembly in which the resources reside + The namespace from which to load the resources + + resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); + + will make ie the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ + + + + + Retrieves a stream for the specified resource path if loaded otherwise null + + Path to the resource to retrieve a stream for + A stream or null if the resource couldn't be found + + + + Fetch all files from the resource that matches the specified arguments. + + The path to the resource to extract + + a list of files if found; or an empty array if no files are found. + + + + + Fetch all files from the resource that matches the specified arguments. + + Where the file should reside. + Files to check + + a list of files if found; or an empty array if no files are found. + + + + + Returns whether or not the loader has an instance of the file requested + + The name of the template/file + True if the loader can provide the file + + + + We dont want to let the server to die due to exceptions thrown in worker threads. + therefore we use this delegate to give you a change to handle uncaught exceptions. + + Class that the exception was thrown in. + Exception + + Server will throw a InternalServerException in release version if you dont + handle this delegate. + + + + + Method marked with this attribute determines if authentication is required. + + + + + + + The method should take one parameter (int level), return a bool and be protected/private. + You should throw UnauthorizedException if you are using HTTP authentication. + + + = level; + } + } + ]]> + + + + + This class is created as a wrapper, since there are two different cookie types in .Net (Cookie and HttpCookie). + The framework might switch class in the future and we dont want to have to replace all instances + + + + + Let's copy all the cookies. + + value from cookie header. + + + + Adds a cookie in the collection. + + cookie to add + cookie is null + + + + Gets a collection enumerator on the cookie list. + + collection enumerator + + + + Remove all cookies. + + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Gets the count of cookies in the collection. + + + + + Gets the cookie of a given identifier (null if not existing). + + + + + Delegate used to find a realm/domain. + + + + + Realms are used during HTTP Authentication + + + + + + + A complete HTTP server, you need to add a module to it to be able to handle incoming requests. + + + + // this small example will add two web site modules, thus handling + // two different sites. In reality you should add Controller modules or something + // two the website modules to be able to handle different requests. + HttpServer server = new HttpServer(); + server.Add(new WebSiteModule("www.gauffin.com", "Gauffin Telecom AB")); + server.Add(new WebSiteModule("www.vapadi.se", "Remote PBX")); + + // start regular http + server.Start(IPAddress.Any, 80); + + // start https + server.Start(IPAddress.Any, 443, myCertificate); + + + + + + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + Form decoders are used to convert different types of posted data to the object types. + + + + + + Initializes a new instance of the class. + + A session store is used to save and retrieve sessions + + + + + Initializes a new instance of the class. + + The log writer. + + + + + Initializes a new instance of the class. + + Form decoders are used to convert different types of posted data to the object types. + The log writer. + + + + + + + Initializes a new instance of the class. + + Form decoders are used to convert different types of posted data to the object types. + A session store is used to save and retrieve sessions + The log writer. + + + + + + + + Adds the specified rule. + + The rule. + + + + Add a to the server. + + mode to add + + + + Decodes the request body. + + The request. + + + + Generate a HTTP error page (that will be added to the response body). + response status code is also set. + + Response that the page will be generated in. + . + response body contents. + + + + Generate a HTTP error page (that will be added to the response body). + response status code is also set. + + Response that the page will be generated in. + exception. + + + + Realms are used by the s. + + HTTP request + domain/realm. + + + + Process an incoming request. + + connection to client + request information + response that should be filled + session information + + + + Can be overloaded to implement stuff when a client have been connected. + + + Default implementation does nothing. + + client that disconnected + disconnect reason + + + + Handle authentication + + + + + true if request can be handled; false if not. + + + + Will request authentication. + + + Sends respond to client, nothing else can be done with the response after this. + + + + + + + + Start the web server using regular HTTP. + + IP Address to listen on, use IpAddress.Any to accept connections on all ip addresses/network cards. + Port to listen on. 80 can be a good idea =) + + + + Accept secure connections. + + IP Address to listen on, use IpAddress.Any to accept connections on all ipaddresses/network cards. + Port to listen on. 80 can be a good idea =) + Certificate to use + + + + shut down the server and listeners + + + + + write an entry to the log file + + importance of the message + log message + + + + write an entry to the log file + + object that wrote the message + importance of the message + log message + + + + Modules used for authentication. The module that is is added first is used as + the default authentication module. + + Use the corresponding property + in the WebSiteModule if you are using multiple websites. + + + + Form decoder providers are used to decode request body (which normally contains form data). + + + + + Server name sent in HTTP responses. + + + Do NOT include version in name, since it makes it + easier for hackers. + + + + + Name of cookie where session id is stored. + + + + + Specified where logging should go. + + + + + + + + Number of connections that can wait to be accepted by the server. + + Default is 10. + + + + Realms are used during HTTP authentication. + Default realm is same as server name. + + + + + Let's to receive unhandled exceptions from the threads. + + + Exceptions will be thrown during debug mode if this event is not used, + exceptions will be printed to console and suppressed during release mode. + + + + + The request requires user authentication. The response MUST include a + WWW-Authenticate header field (section 14.47) containing a challenge + applicable to the requested resource. + + The client MAY repeat the request with a suitable Authorization header + field (section 14.8). If the request already included Authorization + credentials, then the 401 response indicates that authorization has been + refused for those credentials. If the 401 response contains the same challenge + as the prior response, and the user agent has already attempted authentication + at least once, then the user SHOULD be presented the entity that was given in the response, + since that entity might include relevant diagnostic information. + + HTTP access authentication is explained in rfc2617: + http://www.ietf.org/rfc/rfc2617.txt + + (description is taken from + http://www.submissionchamber.com/help-guides/error-codes.php#sec10.4.2) + + + + + Create a new unauhtorized exception. + + + + + + Create a new unauhtorized exception. + + reason to why the request was unauthorized. + inner exception + + + + Create a new unauhtorized exception. + + reason to why the request was unauthorized. + + + + Generates C# rendering object using ASP similiar tags in the HTML code. + + + + + Generate C# code from the template. + + A textwriter that the generated code will be written to. + If the template have not been parsed first. + If template is incorrect + + + + Parse a file and convert into to our own template object code. + + Path and filename to a template + If something is incorrect in the template. + + + + + + + + + Parse a file and convert into to our own template object code. + + A textreader containing our template + If something is incorrect in the template. + + + + Purpose if this class is to take template objects and keep them in + memory. It will also take a filename and the code generator to use + if when the template have been changed on disk. + + + + + Initializes a new instance of the class. + + + Template loaders used to load templates from any source. + The loaders will be invoked in the order they are given, that is the first loader will always be asked to give a template + first. + + + + + Initializes a new instance of the class. + + Uses the file template loader. + + + + Add a template generator + + File extension without the dot. + Generator to handle the extension + If the generator already exists. + If file extension is incorrect + If generator is not specified. + + + cache.Add("haml", new HamlGenerator()); + + + + + + This type should be included, so it may be called from the scripts (name space and assembly). + + + + + + Checks the template. + + Template information, filename must be set. + true if template exists and have been compiled. + + + + Compiles the specified code. + + Name of template. + c# code generated from a template. + Arguments as in name, value, name, value, name, value + + An id to specify the exact instance of a template. Made from joining the 'TemplateClass' with the hashcode of the filename + and the hashcode of the supplied arguments + + Template + If compilation fails + + + + Will generate code from the template. + Next step is to compile the code. + + Path and filename to template. + + If no template generator exists for the specified extension. + If parsing/compiling fails + + + + + Find a template using wildcards in filename. + + Full path (including wildcards in filename) to where we should find a template. + First found generator if an extension was matched; otherwise null. + method is not thread safe + + + + Render a partial + + Path and filename + Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents. + Arguments passed from parent template + + + + + + + + Generate HTML from a template. + + Path and filename + Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents. + + + + + + string html = cache.Generate("views\\users\\view.haml", new TemplateArguments("user", dbUser, "isAdmin", dbUser.IsAdmin), null); + + + + + + Keeps information about templates, so we know when to regenerate it. + + + + + Container to bind resource names to assemblies + + + + + Instantiates an instance of + + The full name/path of the resource + The assembly the resource exists in + + + + Retrieves a stream to the resouce + + Null if the resource couldn't be located somehow + + + + Retrieves the assembly the resource resides in + + + + + Retrieves the full name/path of the assembly + + + + + Retrieves the extension of the resource + + + + + This template loader loads all templates from a folder on the hard drive. + + + + + Initializes a new instance of the class. + + A prefix that is prepended to all requested files. + + + + + Initializes a new instance of the class. + + + + + Load a template into a and return it. + + Relative path (and filename) to template. + + a if file was found; otherwise null. + + + + + Fetch all files from the resource that matches the specified arguments. + + Where the file should reside. + Files to check + + a list of files if found; or an empty array if no files are found. + + + + + Returns whether or not the loader has an instance of the file requested + + The name of the template/file + True if the loader can provide the file + + + + Check's whether a template should be reloaded or not. + + template information + + true if template is OK; false if it do not exist or are old. + + + + + A prefix that is prepended to all requested files. + + + + \\templateName.*" + mgr.PathPrefix = "views\\"; + ]]> + + + PathPrefix may not be null, only string.Empty + + + + + Helpers to make XML handling easier + + + + + Serializes object to XML. + + object to serialize. + xml + + Removes namespaces and adds intendation + + + + + Response that is sent back to the web browser / client. + + A response can be sent if different ways. The easiest one is + to just fill the Body stream with content, everything else + will then be taken care of by the framework. The default content-type + is text/html, you should change it if you send anything else. + + The second and slighty more complex way is to send the response + as parts. Start with sending the header using the SendHeaders method and + then you can send the body using SendBody method, but do not forget + to set ContentType and ContentLength before doing so. + + + public void MyHandler(IHttpRequest request, IHttpResponse response) + { + + } + + + + + Add another header to the document. + + Name of the header, case sensitive, use lower cases. + Header values can span over multiple lines as long as each line starts with a white space. New line chars should be \r\n + If headers already been sent. + If value conditions have not been met. + Adding any header will override the default ones and those specified by properties. + + + + Send headers and body to the browser. + + If content have already been sent. + + + + Make sure that you have specified ContentLength and sent the headers first. + + + If headers have not been sent. + + offest of first byte to send + number of bytes to send. + + + This method can be used if you want to send body contents without caching them first. This + is recommended for larger files to keep the memory usage low. + + + + Make sure that you have specified ContentLength and sent the headers first. + + + If headers have not been sent. + + + + This method can be used if you want to send body contents without caching them first. This + is recommended for larger files to keep the memory usage low. + + + + Send headers to the client. + + If headers already been sent. + + + + + + + Redirect client to somewhere else using the 302 status code. + + Destination of the redirect + If headers already been sent. + You can not do anything more with the request when a redirect have been done. This should be your last + action. + + + + redirect to somewhere + + where the redirect should go + + No body are allowed when doing redirects. + + + + + The body stream is used to cache the body contents + before sending everything to the client. It's the simplest + way to serve documents. + + + + + The chunked encoding modifies the body of a message in order to + transfer it as a series of chunks, each with its own size indicator, + followed by an OPTIONAL trailer containing entity-header fields. This + allows dynamically produced content to be transferred along with the + information necessary for the recipient to verify that it has + received the full message. + + + + + Kind of connection + + + + + Encoding to use when sending stuff to the client. + + Default is UTF8 + + + + Number of seconds to keep connection alive + + Only used if Connection property is set to ConnectionType.KeepAlive + + + + Status code that is sent to the client. + + Default is HttpStatusCode.Ok + + + + Information about why a specific status code was used. + + + + + Size of the body. MUST be specified before sending the header, + unless property Chunked is set to true. + + + + + Kind of content in the body + + Default is text/html + + + + Headers have been sent to the client- + + You can not send any additional headers if they have already been sent. + + + + The whole response have been sent. + + + + + Cookies that should be created/changed. + + + + + Type of HTTP connection + + + + + Connection is closed after each request-response + + + + + Connection is kept alive for X seconds (unless another request have been made) + + + + + represents a http input item. Each item can have multiple sub items, a sub item + is made in a html form by using square brackets + + + // becomes: + Console.WriteLine("Value: {0}", form["user"]["FirstName"].Value); + + + All names in a form SHOULD be in lowercase. + + + + Representation of a non-initialized HttpInputItem + + + + Initializes an input item setting its name/identifier and value + + Parameter name/id + Parameter value + + + Creates a deep copy of the item specified + The item to copy + The function makes a deep copy of quite a lot which can be slow + + + + Add another value to this item + + + + + + checks if a subitem exists (and has a value). + + name in lower case + true if the subitem exists and has a value; otherwise false. + + + Returns a formatted representation of the instance with the values of all contained parameters + + + + Outputs the string in a formatted manner + + A prefix to append, used internally + produce a query string + + + + Add a sub item + + Can contain array formatting, the item is then parsed and added in multiple levels + + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Returns an enumerator that iterates through a collection. + + + + An object that can be used to iterate through the collection. + + 2 + + + + Outputs the string in a formatted manner + + A prefix to append, used internally + + + + + Number of values + + + + + Get a sub item + + name in lower case. + HttpInputItem.Empty if no item was found. + + + + Name of item (in lower case). + + + + + Returns the first value, or null if no value exist. + + + + + Returns the last value, or null if no value exist. + + + + + Returns the list with values. + todo: Return a readonly collection + + + + + + + name in lower case + + + + + Can handle application/x-www-form-urlencoded + + + + + + Stream containing the content + Content type (with any additional info like boundry). Content type is always supplied in lower case + Stream enconding + + A http form, or null if content could not be parsed. + + If contents in the stream is not valid input data. + + + + Checks if the decoder can handle the mime type + + Content type (with any additional info like boundry). Content type is always supplied in lower case. + True if the decoder can parse the specified content type + + + + Used to simply testing of controls. + + + + + Fake host name, default is "http://localhost" + + + + + Session used if null have been specified as argument to one of the class methods. + + + + + Send a GET request to a controller. + + Controller receiving the post request. + Uri visited. + Response from the controller. + Session used during the test. null = is used. + body posted by the response object + + + void MyTest() + { + ControllerTester tester = new ControllerTester(); + + MyController controller = new MyController(); + IHttpResponse response; + string text = Get(controller, "/my/hello/1?hello=world", out response, null); + Assert.Equal("world|1", text); + } + + + + + + Send a POST request to a controller. + + Controller receiving the post request. + Uri visited. + Form being processed by controller. + Response from the controller. + Session used during the test. null = is used. + body posted by the response object + + + void MyTest() + { + // Create a controller. + MyController controller = new MyController(); + + // build up a form that is used by the controller. + HttpForm form = new HttpForm(); + form.Add("user[firstName]", "Jonas"); + + // Invoke the request + ControllerTester tester = new ControllerTester(); + IHttpResponse response; + string text = tester.Get(controller, "/user/create/", form, out response, null); + + // validate response back from controller. + Assert.Equal("User 'Jonas' has been created.", text); + } + + + + + + Invoked when a client have been accepted by the + + + Can be used to revoke incoming connections + + + + + Initializes a new instance of the class. + + The socket. + + + + Client may not be handled. + + + + + Accepted socket. + + + + + Client should be revoked. + + + + + cookie being sent back to the browser. + + + + + + cookie sent by the client/browser + + + + + + Constructor. + + cookie identifier + cookie content + id or content is null + id is empty + + + + Gets the cookie HTML representation. + + cookie string + + + + Gets the cookie identifier. + + + + + Cookie value. Set to null to remove cookie. + + + + + Constructor. + + cookie identifier + cookie content + cookie expiration date. Use DateTime.MinValue for session cookie. + id or content is null + id is empty + + + + Create a new cookie + + name identifying the cookie + cookie value + when the cookie expires. Setting DateTime.MinValue will delete the cookie when the session is closed. + Path to where the cookie is valid + Domain that the cookie is valid for. + + + + Create a new cookie + + Name and value will be used + when the cookie expires. + + + + Gets the cookie HTML representation. + + cookie string + + + + When the cookie expires. + DateTime.MinValue means that the cookie expires when the session do so. + + + + + Cookie is only valid under this path. + + + + + Interface for dynamically generated templates. + + + + + + Run the template to generate HTML code. + + arguments passed to the template + template manager (a manager is used to generate templates) + HTML code. + + + + Contains information on where in the template the error occurred, and what the error was. + + + + + Initializes a new instance of the class. + + Line that the error appeared on. + error description. + + + + Initializes a new instance of the class. + + Line that the error appeared on. + error description. + line contents. + + + + Returns the actual line where the error originated + + + + + Line number in template + + + + + The ’-’ character makes the text following it into “silent” code: C# code that is evaluated, but not output. + It is not recommended that you use this widely; almost all processing code and logic should be restricted to the Controller, Helpers, or partials. + + For example + + - string foo = "hello" + - foo += " there" + - foo += " you!" + %p= foo + + + Is compiled to + +

+ hello there you! +

+
+
+
+ + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + The compiler is responsible of creating a render object which can be + cached and used over and over again. + + + + + + + Base c# code for a template object. + + + + + Create a new template compiler + + + + + Adds the specified type. + + The type. + + + + Compiles the specified args. + + Arguments, should contain "name, value, name, value" etc. + c# code that will be included in the generated template class + Id of the template class + Tiny template if successful; otherwise null. + If compilation fails + If args are incorrect + + + + Response that is sent back to the web browser / client. + + A response can be sent if different ways. The easiest one is + to just fill the Body stream with content, everything else + will then be taken care of by the framework. The default content-type + is text/html, you should change it if you send anything else. + + The second and slighty more complex way is to send the response + as parts. Start with sending the header using the SendHeaders method and + then you can send the body using SendBody method, but do not forget + to set ContentType and ContentLength before doing so. + + + public void MyHandler(IHttpRequest request, IHttpResponse response) + { + + } + + todo: add two examples, using SendHeaders/SendBody and just the Body stream. + + + + Initializes a new instance of the class. + + The context. + The request. + + + + Add another header to the document. + + Name of the header, case sensitive, use lower cases. + Header values can span over multiple lines as long as each line starts with a white space. New line chars should be \r\n + If headers already been sent. + If value conditions have not been met. + Adding any header will override the default ones and those specified by properties. + + + + Send headers and body to the browser. + + If content have already been sent. + + + + Make sure that you have specified ContentLength and sent the headers first. + + + If headers have not been sent. + + offest of first byte to send + number of bytes to send. + + + This method can be used if you want to send body contents without caching them first. This + is recommended for larger files to keep the memory usage low. + + + + Make sure that you have specified ContentLength and sent the headers first. + + + If headers have not been sent. + + + + This method can be used if you want to send body contents without caching them first. This + is recommended for larger files to keep the memory usage low. + + + + Send headers to the client. + + If headers already been sent. + + + + + + + Redirect client to somewhere else using the 302 status code. + + Destination of the redirect + If headers already been sent. + You can not do anything more with the request when a redirect have been done. This should be your last + action. + + + + redirect to somewhere + + where the redirect should go + + No body are allowed when doing redirects. + + + + + The body stream is used to cache the body contents + before sending everything to the client. It's the simplest + way to serve documents. + + + + + The chunked encoding modifies the body of a message in order to + transfer it as a series of chunks, each with its own size indicator, + followed by an OPTIONAL trailer containing entity-header fields. This + allows dynamically produced content to be transferred along with the + information necessary for the recipient to verify that it has + received the full message. + + + + + Kind of connection + + + + + Encoding to use when sending stuff to the client. + + Default is UTF8 + + + + Number of seconds to keep connection alive + + Only used if Connection property is set to ConnectionType.KeepAlive + + + + Status code that is sent to the client. + + Default is HttpStatusCode.Ok + + + + Information about why a specific status code was used. + + + + + Size of the body. MUST be specified before sending the header, + unless property Chunked is set to true. + + + + + Kind of content in the body + + Default is text/html + + + + Headers have been sent to the client- + + You can not send any additional headers if they have already been sent. + + + + The whole response have been sent. + + + + + Cookies that should be created/changed. + + + + + A reverse proxy are used to act as a bridge between local (protected/hidden) websites + and public clients. + + A typical usage is to allow web servers on non standard ports to still be available + to the public clients, or allow web servers on private ips to be available. + + + + + + + Base url requested from browser + Base url on private web server + + // this will return contents from http://192.168.1.128/view/jonas when client requests http://www.gauffin.com/user/view/jonas + _server.Add(new ReverseProxyModule("http://www.gauffin.com/user/", "http://192.168.1.128/"); + + + + + Method that determines if an url should be handled or not by the module + + Url requested by the client. + true if module should handle the url. + + + + Method that process the url + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + + + Container for posted form data + + + Instance to help mark a non-initialized form + + + Initializes a form container with the specified name + + + + Makes a deep copy of the input + + The input to copy + + + + Adds a file to the collection of posted files + + The file to add + If the file is already added + If file is null + If the instance is HttpForm.EmptyForm which cannot be modified + + + + Checks if the form contains a specified file + + Field name of the file parameter + True if the file exists + If the instance is HttpForm.EmptyForm which cannot be modified + + + + Retrieves a file held by by the form + + The identifier of the file + The requested file or null if the file was not found + If name is null or empty + If the instance is HttpForm.EmptyForm which cannot be modified + + + Disposes all held HttpFile's and resets values + + + + The server encountered an unexpected condition which prevented it from fulfilling the request. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + error message. + + + + Initializes a new instance of the class. + + error message. + inner exception. + + + + This attribute tells the controller that the method + uses SendHeader and/or SendBody to handle the request. + + + + + Contains line text and state information about a line in a HAML template. + + + + + Initializes a new instance of the class. + + The line number. + The unparsed data (line contents). + + + + Will check that all rule conditions have been met. + Will also remove the rules if they are done. + + + + + + + Append another line + + + + + + Parsed line contents (without whitespaces in the beginning) + + text contents + + + + Set intendation info to previously added line text. + + + + + + + Assign line text + + + + + + + + + + + If extra lines have been added. + + + + If the next line should be appended to us (multi line) + + + + + Do NOT add yourself using the Add methods of the linkedList. + Parent property will add node. + + + + + Untouched line text + + + + + Has one or more children (intented more that this one) + + + + + Number of intends (two spaces = 1, one tab = 1) + + + + + Line number + + + + + Parent node (one level up in intendation) + + + + + All line data generated on one line + + + + + IRule have not got all needed information yet, + keep appending lines to this LineInfo until rule says that it's done. + + + + + Number of whitespaces before actual entry beings. + + + + + True if node is selfclosed (i.e. <br />) + + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + First node on line, used since some nodes cannot exist on their own on a line. + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + Text nodes should be added as child. + + + + + Used to inform http server that + + + + + Eventarguments used when an exception is thrown by a module + + the exception + + + + Exception thrown in a module + + + + + View controllers integrates the templates, by adding + Render methods. + + + + + Create a new . + + + + + Create a new . + + prototype to copy information from. + + + + Render template for the currently invoked method. + + arguments/parameters used in template + template generated content + calls RenderActionWithErrors + + + + Render contents into a template. + + method/template to generate + arguments/parameters used in template + template generated content + calls RenderActionWithErrors. + + + + Merge arguments array and Arguments property. + + Arguments array to merge + arguments/parameters that can be used in the template. + Will add Request/Response/Session arguments + + + + Renders errors from the property into the + current method template, or as a JavaScript alert if the request is Ajax. + + name of the currently invoked method. + arguments used in the method template. + generated string + Creates a JavaScript Alert box if request is Ajax. + + + + Renders errors from the property into the + current method template, or as a JavaScript alert if the request is Ajax. + + A collection of errors. + name of the currently invoked method. + arguments used in the method template. + generated string + Creates a JavaScript Alert box if request is Ajax. + + + + Switches content-type to "text/JavaScript" and returns content. + + JavaScript to send to the client. + JavaScript + + + + Creates a JavaScript "alert" filled with all errors. + + + a + + + + renders one of the layouts + + layout to render (should be found in the "views\\layouts" folder). + contents will be put in the template variable called "text". + generated text/HTML. + + + + Render a template. + + Merges the Arguments property with the args parameter and pass those to the template. + controller name are used as a folder name when looking for the template. + method are used as filename when looking for the template. + arguments that should be passed to the template. + + + + + Invoked each time a new request is about to be invoked. + + Can be used to clear old data. + + + + + + + Arguments that are being used in the templates. + + + + + A set of errors that occurred during request processing. + Key should be argument name (if argument error, otherwise ), value should be + the error message. + + Errors can be rendered into templates using the method. + + + + + True if we always should render contents inside page layouts when request is Ajax. + + default is false. + + + + Which page layout to use (without file extension) + + + + Page layouts should be places in the Views\Layouts folder. + + + default is "Application" + + + + + + Page title (are added as a parameter to the layout template, use it in <title> HTML tag. + + + + + Arguments sent when a is cleared + + + + + Instantiates the arguments for the event + + True if the session is cleared due to expiration + + + + Returns true if the session is cleared due to expiration + + + + + Delegate for when a IHttpSession is cleared + + this is being cleared. + Arguments for the clearing + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + A list of prototype nodes. + + + + + Creates the node. + + node identifier. + parent node. + created node if identifier was found; otherwise null. + + + + + + + first node on line + + + + + Add a prototype + + prototype node + + + + The purpose of this module is to serve files. + + + + + Initializes a new instance of the class. + + Uri to serve, for instance "/files/" + Path on hard drive where we should start looking for files + If true a Last-Modifed header will be sent upon requests urging webbrowser to cache files + + + + Initializes a new instance of the class. + + Uri to serve, for instance "/files/" + Path on hard drive where we should start looking for files + + + + Mimtypes that this class can handle per default + + + + + Determines if the request should be handled by this module. + Invoked by the HttpServer + + + true if this module should handle it. + + + + check if source contains any of the chars. + + + + + + + + Method that process the url + + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to + + + + return a file extension from an absolute uri path (or plain filename) + + + + + + + List with all mime-type that are allowed. + + All other mime types will result in a Forbidden http status code. + + + + characters that may not exist in a path. + + + fileMod.ForbiddenChars = new string[]{ "\\", "..", ":" }; + + + + + Generic helper functions for Http + + + + + Version string for HTTP v1.0 + + + + + Version string for HTTP v1.1 + + + + + An empty url + + + + + Parses a querystring. + + Querystring (url decoded) + A HttpInput object if successful; otherwise HttpInput.Empty + + + + The server understood the request, but is refusing to fulfill it. + Authorization will not help and the request SHOULD NOT be repeated. + If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, + it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information + available to the client, the status code 404 (Not Found) can be used instead. + + Text taken from: http://www.submissionchamber.com/help-guides/error-codes.php + + + + + Initializes a new instance of the class. + + error message + + + + Delegate used to let authentication modules authenticate the username and password. + + Realm that the user want to authenticate in + Username specified by client + Password supplied by the delagete + object that will be stored in a session variable called if authentication was successful. + throw forbidden exception if too many attempts have been made. + + + + Let's you decide on a system level if authentication is requried. + You can also decide if authentication is required in each HttpModule. + + Http request from client + true if user should be authenticated. + throw ForbiddenException if no more attempts are allowed. + If no more attempts are allowed + + + + Represents a html class node. + + + + + Parse node contents add return a fresh node. + + List containing all node types + Node that this is a subnode to. Can be null + Line to parse + Where to start the parsing. Should be set to where the next node should start parsing. + A node corresponding to the bla bla; null if parsing failed. + + + + + determines if this node can handle the line (by checking the first word); + + Controller char (word) + true if text belongs to this node type + first node on line + + + + Convert node to HTML (with ASP-tags) + + HTML string + + + + Convert the node to c# code + + True if we are inside the internal stringbuilder + true if all subnodes fit on one line + smallEnough is a default value, recalc it + c# code + + + + + + + http://www.faqs.org/rfcs/rfc1867.html + + + + + multipart/form-data + + + + + form-data + + + + + + + Stream containing the content + Content type (with any additional info like boundry). Content type is always supplied in lower case + Stream enconding + A http form, or null if content could not be parsed. + If contents in the stream is not valid input data. + If any parameter is null + + + + Checks if the decoder can handle the mime type + + Content type (with any additional info like boundry). Content type is always supplied in lower case. + True if the decoder can parse the specified content type + + + + + + + + + + + Represents a field in a multipart form + + + + Lists content type mime types. + + + + + text/plain + + + + + text/haml + + + + + content type for javascript documents = application/javascript + + + + RFC 4329 states that text/javascript have been superseeded by + application/javascript. You might still want to check browser versions + since older ones do not support application/javascript. + + Browser support: http://krijnhoetmer.nl/stuff/javascript/mime-types/ + + + + + text/xml + + + + + A list of content types + + + + + + + Semicolon separated content types. + + + + Returns an enumerator that iterates through a collection. + + + An object that can be used to iterate through the collection. + + + + + Searches for the specified type + + Can also be a part of a type (searching for "xml" would return true for "application/xml"). + true if type was found. + + + + Get this first content type. + + + + + Fetch a content type + + Part of type ("xml" would return "application/xml") + + All content types are in lower case. + +
+
diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 47a3d3e..9937cb9 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -198,7 +198,7 @@ ;WorldMapModule = "WorldMap" ;MapImageModule = "MapImageModule" - + ; ## ; ## Customized Cache Implementation ; ## @@ -231,8 +231,8 @@ [Communications] -;InterregionComms = "LocalComms" -InterregionComms = "RESTComms" + ;InterregionComms = "LocalComms" + InterregionComms = "RESTComms" [StandAlone] accounts_authenticate = true @@ -579,16 +579,16 @@ InterregionComms = "RESTComms" [RestHandler] - ; Change this to true to enable the REST Asset and Inventory Plugin - enabled = false - authenticate=true - secured=true - extended-escape=true - realm=OpenSim REST - dump-asset=false - path-fill=true - dump-line-size=32 - flush-on-error=true + ; Change this to true to enable the REST Asset and Inventory Plugin + enabled = false + authenticate = true + secured = true + extended-escape = true + realm = OpenSim REST + dump-asset = false + path-fill = true + dump-line-size = 32 + flush-on-error = true ; Uncomment the following for IRC bridge @@ -1122,16 +1122,16 @@ InterregionComms = "RESTComms" ; default is false enabled = false - ; Channel on which to signal region readiness through a message - ; formatted as follows: "{server_startup|oar_file_load},{0|1},n,[oar error]" - ; - the first field indicating whether this is an initial server startup - ; - the second field is a number indicating whether the OAR file loaded ok (1 == ok, 0 == error) - ; - the third field is a number indicating how many scripts failed to compile - ; - "oar error" if supplied, provides the error message from the OAR load + ; Channel on which to signal region readiness through a message + ; formatted as follows: "{server_startup|oar_file_load},{0|1},n,[oar error]" + ; - the first field indicating whether this is an initial server startup + ; - the second field is a number indicating whether the OAR file loaded ok (1 == ok, 0 == error) + ; - the third field is a number indicating how many scripts failed to compile + ; - "oar error" if supplied, provides the error message from the OAR load channel_notify = -800 [MRM] ; Enables the Mini Region Modules Script Engine. WARNING: SECURITY RISK. ; default is false - Enabled = false + Enabled = false -- cgit v1.1