From 27a0b3ecbdcf248b331742c7b2771d2a87dc8c3a Mon Sep 17 00:00:00 2001 From: teravus Date: Sun, 3 Feb 2013 06:49:17 -0500 Subject: Commit 1 in of this branch feature. This is one of many... --- .../TCPJSONStream/ClientAcceptedEventArgs.cs | 50 +++++++ .../TCPJSONStream/ClientNetworkContext.cs | 143 ++++++++++++++++++ .../TCPJSONStream/DisconnectedEventArgs.cs | 17 +++ .../TCPJSONStream/OpenSimWebSocketBase.cs | 73 +++++++++ .../TCPJSONStream/TCPJsonWebSocketServer.cs | 163 +++++++++++++++++++++ prebuild.xml | 45 ++++++ 6 files changed, 491 insertions(+) create mode 100644 OpenSim/Region/ClientStack/TCPJSONStream/ClientAcceptedEventArgs.cs create mode 100644 OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs create mode 100644 OpenSim/Region/ClientStack/TCPJSONStream/DisconnectedEventArgs.cs create mode 100644 OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs create mode 100644 OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/ClientAcceptedEventArgs.cs b/OpenSim/Region/ClientStack/TCPJSONStream/ClientAcceptedEventArgs.cs new file mode 100644 index 0000000..a58eab1 --- /dev/null +++ b/OpenSim/Region/ClientStack/TCPJSONStream/ClientAcceptedEventArgs.cs @@ -0,0 +1,50 @@ +using System; +using System.Net.Sockets; + +namespace OpenSim.Region.ClientStack.TCPJSONStream +{ + /// + /// Invoked when a client have been accepted by the + /// + /// + /// Can be used to revoke incoming connections + /// + public class ClientAcceptedEventArgs : EventArgs + { + private readonly Socket _socket; + private bool _revoke; + + /// + /// Initializes a new instance of the class. + /// + /// The socket. + public ClientAcceptedEventArgs(Socket socket) + { + _socket = socket; + } + + /// + /// Accepted socket. + /// + public Socket Socket + { + get { return _socket; } + } + + /// + /// Client should be revoked. + /// + public bool Revoked + { + get { return _revoke; } + } + + /// + /// Client may not be handled. + /// + public void Revoke() + { + _revoke = true; + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs b/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs new file mode 100644 index 0000000..591f817 --- /dev/null +++ b/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace OpenSim.Region.ClientStack.TCPJSONStream +{ + public class ClientNetworkContext + { + private Socket _socket; + private string _remoteAddress; + private string _remotePort; + private WebSocketConnectionStage _wsConnectionStatus = WebSocketConnectionStage.Accept; + private int _bytesLeft; + private NetworkStream _stream; + private byte[] _buffer; + public event EventHandler Disconnected = delegate { }; + + public ClientNetworkContext(IPEndPoint endPoint, int port, Stream stream, int buffersize, Socket sock) + { + _socket = sock; + _remoteAddress = endPoint.Address.ToString(); + _remotePort = port.ToString(); + _stream = stream as NetworkStream; + _buffer = new byte[buffersize]; + + + } + + public void BeginRead() + { + _wsConnectionStatus = WebSocketConnectionStage.Http; + try + { + _stream.BeginRead(_buffer, 0, _buffer.Length, OnReceive, _wsConnectionStatus); + } + catch (IOException err) + { + //m_log.Debug(err.ToString()); + } + } + + private void OnReceive(IAsyncResult ar) + { + try + { + int bytesRead = _stream.EndRead(ar); + if (bytesRead == 0) + { + + Disconnected(this, new DisconnectedEventArgs(SocketError.ConnectionReset)); + return; + } + + } + } + /// + /// send a whole buffer + /// + /// buffer to send + /// + public void Send(byte[] buffer) + { + if (buffer == null) + throw new ArgumentNullException("buffer"); + Send(buffer, 0, buffer.Length); + } + + /// + /// Send data using the stream + /// + /// Contains data to send + /// Start position in buffer + /// number of bytes to send + /// + /// + public void Send(byte[] buffer, int offset, int size) + { + + if (offset + size > buffer.Length) + throw new ArgumentOutOfRangeException("offset", offset, "offset + size is beyond end of buffer."); + + if (_stream != null && _stream.CanWrite) + { + try + { + _stream.Write(buffer, offset, size); + } + catch (IOException) + { + + } + } + + } + private void Reset() + { + if (_stream == null) + return; + _stream.Dispose(); + _stream = null; + if (_socket == null) + return; + if (_socket.Connected) + _socket.Disconnect(true); + _socket = null; + } + } + + public enum WebSocketConnectionStage + { + Reuse, + Accept, + Http, + WebSocket, + Closed + } + + public enum FrameOpCodesRFC6455 + { + Continue = 0x0, + Text = 0x1, + Binary = 0x2, + Close = 0x8, + Ping = 0x9, + Pong = 0xA + } + + public enum DataState + { + Empty = 0, + Waiting = 1, + Receiving = 2, + Complete = 3, + Closed = 4, + Ping = 5, + Pong = 6 + } + + +} diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/DisconnectedEventArgs.cs b/OpenSim/Region/ClientStack/TCPJSONStream/DisconnectedEventArgs.cs new file mode 100644 index 0000000..32880cc --- /dev/null +++ b/OpenSim/Region/ClientStack/TCPJSONStream/DisconnectedEventArgs.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Text; + +namespace OpenSim.Region.ClientStack.TCPJSONStream +{ + public class DisconnectedEventArgs:EventArgs + { + public SocketError Error { get; private set; } + public DisconnectedEventArgs(SocketError err) + { + Error = err; + } + } +} diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs b/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs new file mode 100644 index 0000000..379438d --- /dev/null +++ b/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs @@ -0,0 +1,73 @@ +/* + * 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.Net; +using Nini.Config; +using OpenSim.Framework; + +namespace OpenSim.Region.ClientStack.TCPJSONStream +{ + public sealed class TCPJsonWebSocketBase : IClientNetworkServer + { + private TCPJsonWebSocketServer m_tcpServer; + + public TCPJsonWebSocketBase() + { + } + + public void Initialise(IPAddress _listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager authenticateClass) + { + m_tcpServer = new TCPJsonWebSocketServer(_listenIP,ref port, proxyPortOffsetParm, allow_alternate_port,configSource,authenticateClass); + } + + public void NetworkStop() + { + m_tcpServer.Stop(); + } + + public bool HandlesRegion(Location x) + { + return m_tcpServer.HandlesRegion(x); + } + + public void AddScene(IScene x) + { + m_tcpServer.AddScene(x); + } + + public void Start() + { + m_tcpServer.Start(); + } + + public void Stop() + { + m_tcpServer.Stop(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs b/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs new file mode 100644 index 0000000..0713bf4 --- /dev/null +++ b/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Text; +using System.Threading; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Region.Framework.Scenes; +using log4net; + +namespace OpenSim.Region.ClientStack.TCPJSONStream +{ + public delegate void ExceptionHandler(object source, Exception exception); + + public class TCPJsonWebSocketServer + { + private readonly IPAddress _address; + private readonly int _port; + private readonly ManualResetEvent _shutdownEvent = new ManualResetEvent(false); + private TcpListener _listener; + private int _pendingAccepts; + private bool _shutdown; + private int _backlogAcceptQueueLength = 5; + private Scene m_scene; + private Location m_location; + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public event EventHandler Accepted = delegate { }; + + + public TCPJsonWebSocketServer(IPAddress _listenIP, ref uint port, int proxyPortOffsetParm, + bool allow_alternate_port, IConfigSource configSource, + AgentCircuitManager authenticateClass) + { + _address = _listenIP; + _port = (int)port; //Why is a uint passed in? + } + public void Stop() + { + _shutdown = true; + _listener.Stop(); + if (!_shutdownEvent.WaitOne()) + m_log.Error("[WEBSOCKETSERVER]: Failed to shutdown listener properly."); + _listener = null; + } + + public bool HandlesRegion(Location x) + { + return x == m_location; + } + + public void AddScene(IScene scene) + { + if (m_scene != null) + { + m_log.Debug("[WEBSOCKETSERVER]: AddScene() called but I already have a scene."); + return; + } + if (!(scene is Scene)) + { + m_log.Error("[WEBSOCKETSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType()); + return; + } + + m_scene = (Scene)scene; + m_location = new Location(m_scene.RegionInfo.RegionHandle); + } + + public void Start() + { + _listener = new TcpListener(_address, _port); + _listener.Start(_backlogAcceptQueueLength); + Interlocked.Increment(ref _pendingAccepts); + _listener.BeginAcceptSocket(OnAccept, null); + } + + private void OnAccept(IAsyncResult ar) + { + bool beginAcceptCalled = false; + try + { + int count = Interlocked.Decrement(ref _pendingAccepts); + if (_shutdown) + { + if (count == 0) + _shutdownEvent.Set(); + return; + } + Interlocked.Increment(ref _pendingAccepts); + _listener.BeginAcceptSocket(OnAccept, null); + beginAcceptCalled = true; + Socket socket = _listener.EndAcceptSocket(ar); + if (!OnAcceptingSocket(socket)) + { + socket.Disconnect(true); + return; + } + ClientNetworkContext context = new ClientNetworkContext((IPEndPoint) socket.RemoteEndPoint, _port, + new NetworkStream(socket), 16384, socket); + HttpRequestParser parser; + context.BeginRead(); + + } + catch (Exception err) + { + if (ExceptionThrown == null) +#if DEBUG + throw; +#else + _logWriter.Write(this, LogPrio.Fatal, err.Message); + // we can't really do anything but close the connection +#endif + if (ExceptionThrown != null) + ExceptionThrown(this, err); + + if (!beginAcceptCalled) + RetryBeginAccept(); + + } + } + + private void RetryBeginAccept() + { + try + { + + _listener.BeginAcceptSocket(OnAccept, null); + } + catch (Exception err) + { + + if (ExceptionThrown == null) +#if DEBUG + throw; +#else + // we can't really do anything but close the connection +#endif + if (ExceptionThrown != null) + ExceptionThrown(this, err); + } + } + + private bool OnAcceptingSocket(Socket sock) + { + ClientAcceptedEventArgs args = new ClientAcceptedEventArgs(sock); + Accepted(this, args); + return !args.Revoked; + } + /// + /// Catch exceptions not handled by the listener. + /// + /// + /// Exceptions will be thrown during debug mode if this event is not used, + /// exceptions will be printed to console and suppressed during release mode. + /// + public event ExceptionHandler ExceptionThrown = delegate { }; + + + + } +} diff --git a/prebuild.xml b/prebuild.xml index 329ff73..d8b4145 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -1466,6 +1466,8 @@ + + @@ -1508,6 +1510,49 @@ + + + + ../../../../bin/ + + + + + ../../../../bin/ + + + + ../../../../bin/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.1 From d18fbb98b7f51d46eb3e716c59a8e76bc772bad1 Mon Sep 17 00:00:00 2001 From: teravus Date: Sun, 3 Feb 2013 07:44:45 -0500 Subject: Adds the ability to load more then one IClientNetworkServer thereby allowing additional client stacks. Use comma separated values in clientstack_plugin in your config. --- OpenSim/Region/Application/OpenSimBase.cs | 37 ++++++---- OpenSim/Region/ClientStack/ClientStackManager.cs | 83 +++++++++++++--------- .../TCPJSONStream/ClientNetworkContext.cs | 3 + .../TCPJSONStream/TCPJsonWebSocketServer.cs | 2 +- bin/OpenSimDefaults.ini | 2 +- 5 files changed, 78 insertions(+), 49 deletions(-) diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs index c3c87e7..f5c06df 100644 --- a/OpenSim/Region/Application/OpenSimBase.cs +++ b/OpenSim/Region/Application/OpenSimBase.cs @@ -316,7 +316,7 @@ namespace OpenSim /// /// /// - public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene) + public List CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene) { return CreateRegion(regionInfo, portadd_flag, false, out scene); } @@ -326,7 +326,7 @@ namespace OpenSim /// /// /// - public IClientNetworkServer CreateRegion(RegionInfo regionInfo, out IScene scene) + public List CreateRegion(RegionInfo regionInfo, out IScene scene) { return CreateRegion(regionInfo, false, true, out scene); } @@ -338,7 +338,7 @@ namespace OpenSim /// /// /// - public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene) + public List CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene) { int port = regionInfo.InternalEndPoint.Port; @@ -363,8 +363,8 @@ namespace OpenSim Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName); } - IClientNetworkServer clientServer; - Scene scene = SetupScene(regionInfo, proxyOffset, Config, out clientServer); + List clientServers; + Scene scene = SetupScene(regionInfo, proxyOffset, Config, out clientServers); m_log.Info("[MODULES]: Loading Region's modules (old style)"); @@ -414,8 +414,11 @@ namespace OpenSim if (m_autoCreateClientStack) { - m_clientServers.Add(clientServer); - clientServer.Start(); + foreach (IClientNetworkServer clientserver in clientServers) + { + m_clientServers.Add(clientserver); + clientserver.Start(); + } } scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); }; @@ -425,7 +428,7 @@ namespace OpenSim scene.Start(); scene.StartScripts(); - return clientServer; + return clientServers; } /// @@ -641,7 +644,7 @@ namespace OpenSim /// /// /// - protected Scene SetupScene(RegionInfo regionInfo, out IClientNetworkServer clientServer) + protected Scene SetupScene(RegionInfo regionInfo, out List clientServer) { return SetupScene(regionInfo, 0, null, out clientServer); } @@ -655,19 +658,20 @@ namespace OpenSim /// /// protected Scene SetupScene( - RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out IClientNetworkServer clientServer) + RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out List clientServer) { + List clientNetworkServers = null; + AgentCircuitManager circuitManager = new AgentCircuitManager(); IPAddress listenIP = regionInfo.InternalEndPoint.Address; //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP)) // listenIP = IPAddress.Parse("0.0.0.0"); uint port = (uint) regionInfo.InternalEndPoint.Port; - + IClientNetworkServer clientNetworkServer; if (m_autoCreateClientStack) { - clientServer - = m_clientStackManager.CreateServer( + clientNetworkServers = m_clientStackManager.CreateServers( listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource, circuitManager); } @@ -682,9 +686,12 @@ namespace OpenSim if (m_autoCreateClientStack) { - clientServer.AddScene(scene); + foreach (IClientNetworkServer clientnetserver in clientNetworkServers) + { + clientnetserver.AddScene(scene); + } } - + clientServer = clientNetworkServers; scene.LoadWorldMap(); scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName); diff --git a/OpenSim/Region/ClientStack/ClientStackManager.cs b/OpenSim/Region/ClientStack/ClientStackManager.cs index 84ea0b3..299aabd 100644 --- a/OpenSim/Region/ClientStack/ClientStackManager.cs +++ b/OpenSim/Region/ClientStack/ClientStackManager.cs @@ -26,6 +26,7 @@ */ using System; +using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; @@ -38,39 +39,53 @@ namespace OpenSim.Region.ClientStack { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Type plugin; - private Assembly pluginAssembly; + private List plugin = new List(); + private List pluginAssembly = new List(); - public ClientStackManager(string dllName) + public ClientStackManager(string pDllName) { - m_log.Info("[CLIENTSTACK]: Attempting to load " + dllName); - - try + List clientstacks = new List(); + if (pDllName.Contains(",")) + { + clientstacks = new List(pDllName.Split(',')); + } + else { - plugin = null; - pluginAssembly = Assembly.LoadFrom(dllName); + clientstacks.Add(pDllName); + } + foreach (string dllName in clientstacks) + { + m_log.Info("[CLIENTSTACK]: Attempting to load " + dllName); - foreach (Type pluginType in pluginAssembly.GetTypes()) + try { - if (pluginType.IsPublic) - { - Type typeInterface = pluginType.GetInterface("IClientNetworkServer", true); + //plugin = null; + Assembly itemAssembly = Assembly.LoadFrom(dllName); + pluginAssembly.Add(itemAssembly); - if (typeInterface != null) + foreach (Type pluginType in itemAssembly.GetTypes()) + { + if (pluginType.IsPublic) { - m_log.Info("[CLIENTSTACK]: Added IClientNetworkServer Interface"); - plugin = pluginType; - return; + Type typeInterface = pluginType.GetInterface("IClientNetworkServer", true); + + if (typeInterface != null) + { + m_log.Info("[CLIENTSTACK]: Added IClientNetworkServer Interface"); + plugin.Add(pluginType); + break; + } } } } - } catch (ReflectionTypeLoadException e) - { - foreach (Exception e2 in e.LoaderExceptions) + catch (ReflectionTypeLoadException e) { - m_log.Error(e2.ToString()); + foreach (Exception e2 in e.LoaderExceptions) + { + m_log.Error(e2.ToString()); + } + throw e; } - throw e; } } @@ -84,11 +99,11 @@ namespace OpenSim.Region.ClientStack /// /// /// - public IClientNetworkServer CreateServer( + public List CreateServers( IPAddress _listenIP, ref uint port, int proxyPortOffset, bool allow_alternate_port, AgentCircuitManager authenticateClass) { - return CreateServer( + return CreateServers( _listenIP, ref port, proxyPortOffset, allow_alternate_port, null, authenticateClass); } @@ -105,20 +120,24 @@ namespace OpenSim.Region.ClientStack /// /// /// - public IClientNetworkServer CreateServer( + public List CreateServers( IPAddress _listenIP, ref uint port, int proxyPortOffset, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager authenticateClass) { + List servers = new List(); if (plugin != null) { - IClientNetworkServer server = - (IClientNetworkServer)Activator.CreateInstance(pluginAssembly.GetType(plugin.ToString())); - - server.Initialise( - _listenIP, ref port, proxyPortOffset, allow_alternate_port, - configSource, authenticateClass); - - return server; + for (int i = 0; i < plugin.Count; i++) + { + IClientNetworkServer server = + (IClientNetworkServer) Activator.CreateInstance(pluginAssembly[i].GetType(plugin[i].ToString())); + + server.Initialise( + _listenIP, ref port, proxyPortOffset, allow_alternate_port, + configSource, authenticateClass); + servers.Add(server); + } + return servers; } m_log.Error("[CLIENTSTACK]: Couldn't initialize a new server"); diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs b/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs index 591f817..b077b6a 100644 --- a/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs +++ b/OpenSim/Region/ClientStack/TCPJSONStream/ClientNetworkContext.cs @@ -55,6 +55,9 @@ namespace OpenSim.Region.ClientStack.TCPJSONStream } } + catch (Exception) + { + } } /// /// send a whole buffer diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs b/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs index 0713bf4..c0f6792 100644 --- a/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs +++ b/OpenSim/Region/ClientStack/TCPJSONStream/TCPJsonWebSocketServer.cs @@ -99,7 +99,7 @@ namespace OpenSim.Region.ClientStack.TCPJSONStream } ClientNetworkContext context = new ClientNetworkContext((IPEndPoint) socket.RemoteEndPoint, _port, new NetworkStream(socket), 16384, socket); - HttpRequestParser parser; + //HttpRequestParser parser; context.BeginRead(); } diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index c60579b..cc08094 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -58,7 +58,7 @@ ; ## ; Set this to the DLL containing the client stack to use. - clientstack_plugin="OpenSim.Region.ClientStack.LindenUDP.dll" + clientstack_plugin="OpenSim.Region.ClientStack.LindenUDP.dll,OpenSim.Region.ClientStack.TCPJSONStream.dll" ; ## ; ## REGIONS -- cgit v1.1 From 29d521e2733bf8dc11cfdbdad104f9f141f7c895 Mon Sep 17 00:00:00 2001 From: teravus Date: Sun, 3 Feb 2013 07:56:31 -0500 Subject: Changing OpenSimDefaults back to default --- bin/OpenSimDefaults.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index cc08094..c60579b 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -58,7 +58,7 @@ ; ## ; Set this to the DLL containing the client stack to use. - clientstack_plugin="OpenSim.Region.ClientStack.LindenUDP.dll,OpenSim.Region.ClientStack.TCPJSONStream.dll" + clientstack_plugin="OpenSim.Region.ClientStack.LindenUDP.dll" ; ## ; ## REGIONS -- cgit v1.1 From 1dc09d8e8f4a6caa321d0227722af97ee4aeed6a Mon Sep 17 00:00:00 2001 From: teravus Date: Tue, 5 Feb 2013 18:02:25 -0500 Subject: We're not really done here.. but we're getting there. Socket Read is working.. Still have to do Header.ToBytes and compose a websocket frame with a payload. --- .../Framework/Servers/HttpServer/BaseHttpServer.cs | 38 +- OpenSim/Framework/Servers/Tests/OSHttpTests.cs | 5 + .../TCPJSONStream/OpenSimWebSocketBase.cs | 6 +- bin/HttpServer_OpenSim.dll | Bin 115712 -> 116224 bytes bin/HttpServer_OpenSim.pdb | Bin 413184 -> 302592 bytes bin/HttpServer_OpenSim.xml | 6398 ++++++++++---------- 6 files changed, 3244 insertions(+), 3203 deletions(-) diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs index b24336d..dcfe99a 100644 --- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs +++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs @@ -54,6 +54,8 @@ namespace OpenSim.Framework.Servers.HttpServer private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HttpServerLogWriter httpserverlog = new HttpServerLogWriter(); + public delegate void WebSocketRequestDelegate(string servicepath, WebSocketHTTPServerHandler handler); + /// /// Gets or sets the debug level. /// @@ -87,6 +89,9 @@ namespace OpenSim.Framework.Servers.HttpServer protected Dictionary m_pollHandlers = new Dictionary(); + protected Dictionary m_WebSocketHandlers = + new Dictionary(); + protected uint m_port; protected uint m_sslport; protected bool m_ssl; @@ -170,6 +175,22 @@ namespace OpenSim.Framework.Servers.HttpServer } } + public void AddWebSocketHandler(string servicepath, WebSocketRequestDelegate handler) + { + lock (m_WebSocketHandlers) + { + if (!m_WebSocketHandlers.ContainsKey(servicepath)) + m_WebSocketHandlers.Add(servicepath, handler); + } + } + + public void RemoveWebSocketHandler(string servicepath) + { + lock (m_WebSocketHandlers) + if (m_WebSocketHandlers.ContainsKey(servicepath)) + m_WebSocketHandlers.Remove(servicepath); + } + public List GetStreamHandlerKeys() { lock (m_streamHandlers) @@ -409,9 +430,24 @@ namespace OpenSim.Framework.Servers.HttpServer public void OnHandleRequestIOThread(IHttpClientContext context, IHttpRequest request) { + OSHttpRequest req = new OSHttpRequest(context, request); + WebSocketRequestDelegate dWebSocketRequestDelegate = null; + lock (m_WebSocketHandlers) + { + if (m_WebSocketHandlers.ContainsKey(req.RawUrl)) + dWebSocketRequestDelegate = m_WebSocketHandlers[req.RawUrl]; + } + if (dWebSocketRequestDelegate != null) + { + dWebSocketRequestDelegate(req.Url.AbsolutePath, new WebSocketHTTPServerHandler(req, context, 16384)); + return; + } + OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context); + HandleRequest(req, resp); + // !!!HACK ALERT!!! // There seems to be a bug in the underlying http code that makes subsequent requests @@ -500,7 +536,7 @@ namespace OpenSim.Framework.Servers.HttpServer LogIncomingToStreamHandler(request, requestHandler); response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type. - + if (requestHandler is IStreamedRequestHandler) { IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler; diff --git a/OpenSim/Framework/Servers/Tests/OSHttpTests.cs b/OpenSim/Framework/Servers/Tests/OSHttpTests.cs index 3412e0f..5b912b4 100644 --- a/OpenSim/Framework/Servers/Tests/OSHttpTests.cs +++ b/OpenSim/Framework/Servers/Tests/OSHttpTests.cs @@ -70,6 +70,11 @@ namespace OpenSim.Framework.Servers.Tests public void Close() { } public bool EndWhenDone { get { return false;} set { return;}} + public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing() + { + return new HTTPNetworkContext(); + } + public event EventHandler Disconnected = delegate { }; /// /// A request have been received in the context. diff --git a/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs b/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs index 379438d..6d02543 100644 --- a/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs +++ b/OpenSim/Region/ClientStack/TCPJSONStream/OpenSimWebSocketBase.cs @@ -47,7 +47,7 @@ namespace OpenSim.Region.ClientStack.TCPJSONStream public void NetworkStop() { - m_tcpServer.Stop(); + // m_tcpServer.Stop(); } public bool HandlesRegion(Location x) @@ -62,12 +62,12 @@ namespace OpenSim.Region.ClientStack.TCPJSONStream public void Start() { - m_tcpServer.Start(); + //m_tcpServer.Start(); } public void Stop() { - m_tcpServer.Stop(); + // m_tcpServer.Stop(); } } } \ No newline at end of file diff --git a/bin/HttpServer_OpenSim.dll b/bin/HttpServer_OpenSim.dll index d910bb9..9cd1e08 100755 Binary files a/bin/HttpServer_OpenSim.dll and b/bin/HttpServer_OpenSim.dll differ diff --git a/bin/HttpServer_OpenSim.pdb b/bin/HttpServer_OpenSim.pdb index b9161e1..d20a0c5 100644 Binary files a/bin/HttpServer_OpenSim.pdb and b/bin/HttpServer_OpenSim.pdb differ diff --git a/bin/HttpServer_OpenSim.xml b/bin/HttpServer_OpenSim.xml index d31bcca..fa88fc7 100644 --- a/bin/HttpServer_OpenSim.xml +++ b/bin/HttpServer_OpenSim.xml @@ -4,547 +4,659 @@ HttpServer_OpenSim - - - 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. + Delegate used to find a realm/domain. - A object + + + + Realms are used during HTTP Authentication + + + - + - Creates a new http session with a specific id + A complete HTTP server, you need to add a module to it to be able to handle incoming requests. - Id used to identify the new cookie.. - A object. - - Id should be generated by the store implementation if it's null or . - + + + // 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); + + + + + - + - Load an existing session. + Initializes a new instance of the class. - Session id (usually retrieved from a client side cookie). - A session if found; otherwise null. + Used to get all components used in the server.. - + - Save an updated session to the store. + Initializes a new instance of the class. - 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. + Initializes a new instance of the class. - Unused session that should be reused next time Create is called. + Form decoders are used to convert different types of posted data to the object types. + + - + - Remove expired sessions + Initializes a new instance of the class. + A session store is used to save and retrieve sessions + - + - Remove a session + Initializes a new instance of the class. - id of the session. + The log writer. + - + - Load a session from the store + Initializes a new instance of the class. - - null if session is not found. + Form decoders are used to convert different types of posted data to the object types. + The log writer. + + + - + - Number of minutes before a session expires. + Initializes a new instance of the class. - Default time is 20 minutes. + 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. + + + + - + - Contains server side HTTP request information. + Adds the specified rule. + The rule. - + - Called during parsing of a . + Add a to the server. - Name of the header, should not be URL encoded - Value of the header, should not be URL encoded - If a header is incorrect. + mode to add - + - Add bytes to the body + Decodes the request 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 - bytes is null. - offset is out of range. + The request. + Failed to decode form data. - + - Clear everything in 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. - + - Decode body into a form. + Generate a HTTP error page (that will be added to the response body). + response status code is also set. - A list with form decoders. - If body contents is not valid for the chosen decoder. - If body is still being transferred. + Response that the page will be generated in. + exception. - + - Sets the cookies. + Realms are used by the s. - The cookies. + HTTP request + domain/realm. - + - Create a response object. + Process an incoming request. - Context for the connected client. - A new . + connection to client + request information + response that should be filled + session information - + - Gets kind of types accepted by the client. + Can be overloaded to implement stuff when a client have been connected. + + Default implementation does nothing. + + client that disconnected + disconnect reason - + - Gets or sets body stream. + Handle authentication + + + + true if request can be handled; false if not. + Invalid authorization header - + - Gets whether the body is complete. + Will request authentication. + + Sends respond to client, nothing else can be done with the response after this. + + + + - + - Gets or sets kind of connection used for the session. + Received from a when a request have been parsed successfully. + that received the request. + The request. - + - Gets or sets number of bytes in the body. + To be able to track request count. + + - + - Gets cookies that was sent with the request. + 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 =) + address is null. + Port must be a positive number. - + - Gets form parameters. + Accept secure connections. + IP Address to listen on, use to accept connections on all IP Addresses / network cards. + Port to listen on. 80 can be a good idea =) + Certificate to use + address is null. + Port must be a positive number. - + - Gets headers sent by the client. + shut down the server and listeners - + - Gets or sets version of HTTP protocol that's used. + write an entry to the log file - - Probably or . - - + importance of the message + log message - + - Gets whether the request was made by Ajax (Asynchronous JavaScript) + write an entry to the log file + object that wrote the message + importance of the message + log message - + - Gets or sets requested method. + Server that is handling the current request. - Will always be in upper case. + Will be set as soon as a request arrives to the object. - - + - Gets parameter from or . - - - - - Gets variables sent in the query string + Modules used for authentication. The module that is is added first is used as + the default authentication module. + Use the corresponding property + in the if you are using multiple websites. - + - Gets or sets requested URI. + Form decoder providers are used to decode request body (which normally contains form data). - + - Gets URI absolute path divided into parts. + Server name sent in HTTP responses. - - // 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. + Do NOT include version in name, since it makes it + easier for hackers. - - + - Gets or sets path and query. + Name of cookie where session id is stored. - - - Are only used during request parsing. Cannot be set after "Host" header have been - added. - - + - Class that receives Requests from a . + Specified where logging should go. + + + - + - Client have been disconnected. + Number of connections that can wait to be accepted by the server. - Client that was disconnected. - Reason - + Default is 10. - + - Invoked when a client context have received a new HTTP request + Gets or sets maximum number of allowed simultaneous requests. - Client that received the request. - Request that was received. - + + + This property is useful in busy systems. The HTTP server + will start queuing new requests if this limit is hit, instead + of trying to process all incoming requests directly. + + + The default number if allowed simultaneous requests are 10. + + - + - Delegate used by to populate select options. + Gets or sets maximum number of requests queuing to be handled. - 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; - } /// + + + The WebServer will start turning requests away if response code + to indicate that the server + is too busy to be able to handle the request. + + - + - 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 + Realms are used during HTTP authentication. + Default realm is same as server name. - + - All HTTP based exceptions will derive this class. + 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. + - + - Create a new HttpException + Serves files that are stored in embedded resources. - http status code (sent in the response) - error description - + - Create a new HttpException + A HttpModule can be used to serve Uri's. The module itself + decides if it should serve a Uri or not. In this way, you can + get a very flexible http application since you can let multiple modules + serve almost similar urls. - http status code (sent in the response) - error description - inner exception + + Throw if you are using a and want to prompt for user name/password. + - + - status code to use in the response. + 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. - + - Initializes a new instance of the class. + Set the log writer to use. - error message + logwriter to use. - + - A session stored in memory. + Log something. + importance of log message + message - + - Interface for sessions + 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. - + - Remove everything from the session + 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. - + - Remove everything from the session + 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. - True if the session is cleared due to expiration + The log writer to use when logging events - + - Session id + Mimtypes that this class can handle per default - + - Should + Loads resources from a namespace in the given assembly to an uri - Name of the session variable - null if it's not set - If the object cant be serialized. + 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 + + The amount of loaded files, giving you the possibility of making sure the resources needed gets loaded - + - When the session was last accessed. - This property is touched by the http server each time the - session is requested. + Returns true if the module can handle the request - + - Number of session variables. + 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. - + - Event triggered upon clearing the session + List with all mime-type that are allowed. + All other mime types will result in a Forbidden http status code. - + - + Contains some kind of input from the browser/client. + can be QueryString, form data or any other request body content. - A unique id used by the sessions store to identify the session - + - Id + Base class for request data containers - - + - Remove everything from the session + Adds a parameter mapped to the presented name + The name to map the parameter to + The parameter value - + - Clears the specified expire. + Returns true if the container contains the requested parameter - True if the session is cleared due to expiration + Parameter id + True if parameter exists - + - Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + Returns a request parameter - 2 + The name associated with the parameter + - + + Representation of a non-initialized class instance + + + Variable telling the class that it is non-initialized + + - Session id + Initializes a new instance of the class. + form name. - + - Should + Initializes a new instance of the class. - Name of the session variable - null if it's not set + 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 + + - when the session was last accessed. + Add a new element. Form array elements are parsed + and added in a correct hierarchy. - - Used to determine when the session should be removed. - + Name is converted to lower case. + + name is null. + Cannot add stuff to . - + - Number of values in the session + Returns true if the class contains a with the corresponding name. + The field/query string name + True if the value exists - + - Flag to indicate that the session have been changed - and should be saved into the session store. + Parses an item and returns it. + This function is primarily 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. + + + - Event triggered upon clearing the session + 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 + + - cookie being sent back to the browser. + Returns an enumerator that iterates through the collection. - + + + A that can be used to iterate through the collection. + + 1 - + - cookie sent by the client/browser + Returns an enumerator that iterates through a collection. - + + + An object that can be used to iterate through the collection. + + 2 - + - Constructor. + Form name as lower case - cookie identifier - cookie content - id or content is null - id is empty - + - Gets the cookie HTML representation. + Get a form item. - cookie string + + Returns if item was not found. - + - Gets the cookie identifier. + 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 - + - Cookie value. Set to null to remove cookie. + All HTTP based exceptions will derive this class. - + - Constructor. + Create a new HttpException - cookie identifier - cookie content - cookie expiration date. Use DateTime.MinValue for session cookie. - id or content is null - id is empty + http status code (sent in the response) + error description - + - Create a new cookie + Create a new HttpException - 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. + http status code (sent in the response) + error description + inner exception - + - Create a new cookie + status code to use in the response. - Name and value will be used - when the cookie expires. - + - Gets the cookie HTML representation. + Initializes a new instance of the class. - cookie string + error message - + - When the cookie expires. - DateTime.MinValue means that the cookie expires when the session do so. + 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 - + - Cookie is only valid under this path. + 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 + + + + Remove a cookie from the collection. + + Name of cookie. + + + + Gets the count of cookies in the collection. + + + + + Gets the cookie of a given identifier (null if not existing). @@ -660,102 +772,130 @@ Gets received request. - + - Contains a listener that doesn't do anything with the connections. + 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 + + - Listen for regular HTTP connections + The add method is not availible for HttpParam + since HttpParam checks both Request.Form and Request.QueryString - IP Address to accept connections on - TCP Port to listen on, default HTTP port is 80. - Factory used to create es. - address is null. - Port must be a positive number. + name identifying the value + value to add + - + - Initializes a new instance of the class. + Checks whether the form or querystring has the specified value - IP Address to accept connections on - TCP Port to listen on, default HTTPS port is 443 - Factory used to create es. - Certificate to use + Name, case sensitive + true if found; otherwise false. - + - Initializes a new instance of the class. + Returns an enumerator that iterates through the collection. - IP Address to accept connections on - TCP Port to listen on, default HTTPS port is 443 - Factory used to create es. - Certificate to use - which HTTPS protocol to use, default is TLS. + + + A that can be used to iterate through the collection. + + 1 - - Exception. + + + Returns an enumerator that iterates through a collection. + + + + An object that can be used to iterate through the collection. + + 2 - + - Will try to accept connections one more time. + Fetch an item from the form or querystring (in that order). - If any exceptions is thrown. + + Item if found; otherwise HttpInputItem.EmptyLanguageNode - + - Can be used to create filtering of new connections. + Container class for posted files - Accepted socket - true if connection can be accepted; otherwise false. - + - Start listen for new connections + Creates a container for a posted file - Number of connections that can stand in a queue to be accepted. - Listener have already been started. + 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 - + - Stop the listener + Creates a container for a posted file - + If any parameter is null or empty - + + Destructor disposing the file + + - Gives you a change to receive log entries for all internals of the HTTP library. + Deletes the temporary file - - You may not switch log writer after starting the listener. - + True if manual dispose - + - True if we should turn on trace logs. + Disposing interface, cleans up managed resources (the temporary file) and suppresses finalization - + - Catch exceptions not handled by the listener. + The name/id of the file - - Exceptions will be thrown during debug mode if this event is not used, - exceptions will be printed to console and suppressed during release mode. - - + - A request have been received from a . + The full file path - + - + The name of the uploaded file + + + + + The type of file + + + + + 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" + - http://www.faqs.org/rfcs/rfc1867.html + The original xml document is stored in form["__xml__"].Value. @@ -780,257 +920,237 @@ 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 - - - 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 + Stream encoding + Note: contentType and encoding are not used? 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 + - + + + 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 - + - The requested resource was not found in the web server. + The object form class takes an object and creates form items for it. - + - Create a new exception + Initializes a new instance of the class. - message describing the error - inner exception + + form name *and* id. + action to do when form is posted. + - + - Create a new exception + Initializes a new instance of the class. - message describing the error + form name *and* id. + action to do when form is posted. + object to get values from - + - Delegate used to let authentication modules authenticate the user name and password. + Initializes a new instance of the class. - Realm that the user want to authenticate in - User name specified by client - Can either be user password or implementation specific token. - object that will be stored in a session variable called if authentication was successful. - throw forbidden exception if too many attempts have been made. - - - Use to specify that the token is a HA1 token. (MD5 generated - string from realm, user name and password); Md5String(userName + ":" + realm + ":" + password); - - + form action. + object to get values from. - + - Let's you decide on a system level if authentication is required. + write out the FORM-tag. - HTTP request from client - true if user should be authenticated. - throw if no more attempts are allowed. - If no more attempts are allowed + generated html code - + - Authentication modules are used to implement different - kind of HTTP authentication. + Writeout the form tag + form should be posted through ajax. + generated html code - + - Tag used for authentication. + Generates a text box. + + + generated html code - + - Initializes a new instance of the class. + password box - Delegate used to provide information used during authentication. - Delegate used to determine if authentication is required (may be null). + + + generated html code - + - Initializes a new instance of the class. + Hiddens the specified property name. - Delegate used to provide information used during authentication. + Name of the property. + The options. + generated html code - + - Create a response that can be sent in the WWW-Authenticate header. + Labels the specified property name. - Realm that the user should authenticate in - Array with optional options. - A correct authentication request. - If realm is empty or null. + property in object. + caption + generated html code - + - An authentication response have been received from the web browser. - Check if it's correct + Generate a checkbox - 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 is invalid - If any of the parameters is empty or null. - - + property in object + checkbox value + additional html attributes. + generated html code + + - Used to invoke the authentication delegate that is used to lookup the user name/realm. + Write a html select tag - Realm (domain) that user want to authenticate in - User name - 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 + object property. + id column + The title column. + The options. + - + - Determines if authentication is required. + Selects the specified property name. - HTTP request from browser - true if user should be authenticated. - throw from your delegate if no more attempts are allowed. - If no more attempts are allowed + Name of the property. + The items. + The id column. + The title column. + The options. + - + - name used in HTTP request. + Write a submit tag. + button caption + html submit tag - + - Contains some kind of input from the browser/client. - can be QueryString, form data or any other request body content. + html end form tag + html - + - Base class for request data containers + + + http://www.faqs.org/rfcs/rfc1867.html + - + - Adds a parameter mapped to the presented name + multipart/form-data - The name to map the parameter to - The parameter value - + - Returns true if the container contains the requested parameter + form-data - 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 + 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 - + - Initializes a new instance of the class. + Checks if the decoder can handle the mime type - form name. + 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 - + - Initializes a new instance of the class. + 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 - 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 hierarchy. + Create a new bad request exception. - Name is converted to lower case. - - name is null. - Cannot add stuff to . + reason to why the request was bad. - + - Returns true if the class contains a with the corresponding name. + Create a new bad request exception. - The field/query string name - True if the value exists + reason to why the request was bad. + inner exception - + - Parses an item and returns it. - This function is primarily used to parse array items as in user[name]. + Cookies that should be set. - - - - - Outputs the instance representing all its values joined together - + + + Adds a cookie in the collection. + + cookie to add + cookie is null - - Returns all items as an unescaped query string. - + + + Copy a request cookie + + + When the cookie should expire - + - Extracts one parameter from an array + Gets a collection enumerator on the cookie list. - 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 - + collection enumerator - - Resets all data contained by class + + + Remove all cookies + - + Returns an enumerator that iterates through the collection. @@ -1040,2593 +1160,2516 @@ 1 - + - Returns an enumerator that iterates through a collection. + Gets the count of cookies in the collection. - - - An object that can be used to iterate through the collection. - - 2 - + - Form name as lower case + Gets the cookie of a given identifier (null if not existing). - + - Get a form item. + cookie being sent back to the browser. - - Returns if item was not found. + - + - Small design by contract implementation. + cookie sent by the client/browser + - + - Check whether a parameter is empty. + Constructor. - Parameter value - Parameter name, or error description. - value is empty. + cookie identifier + cookie content + id or content is null + id is empty - + - Checks whether a parameter is null. + Gets the cookie HTML representation. - Parameter value - Parameter name, or error description. - value is null. + cookie string - + - Checks whether a parameter is null. + Gets the cookie identifier. - - Parameter value - Parameter name, or error description. - value is null. - + - Contains all HTTP Methods (according to the HTTP 1.1 specification) - - See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - + Cookie value. Set to null to remove cookie. - + - The DELETE method requests that the origin server delete the resource identified by the Request-URI. + Constructor. - - - 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 meta information 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 meta information 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. - - + cookie identifier + cookie content + cookie expiration date. Use DateTime.MinValue for session cookie. + id or content is null + id is empty - + - The TRACE method is used to invoke a remote, application-layer loop- back of the request message. + 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. - + - Contains all HTTP Methods (according to the HTTP 1.1 specification) - - See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - + Create a new cookie + Name and value will be used + when the cookie expires. - + - The DELETE method requests that the origin server delete the resource identified by the Request-URI. + Gets the cookie HTML representation. - - - 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. - - + cookie string - + - The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. + When the cookie expires. + DateTime.MinValue means that the cookie expires when the session do so. - - - 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. + Cookie is only valid under this path. - - The meta information 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 meta information 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. + Inversion of control interface. - - 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. + Add a component instance - - 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. - - + Interface type + Instance to add - + - The PUT method requests that the enclosed entity be stored under the supplied Request-URI. + Get a component. + Interface type + Component if registered, otherwise null. - - - 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. - + Component will get created if needed. - - - The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - - - - - 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. + Checks if the specified component interface have been added. + + true if found; otherwise false. - + - Something did not go as we expected, but it's no problem. + Add a component. + Type being requested. + Type being created. - + - Something that should not fail failed, but we can still keep - on going. + Contains a listener that doesn't do anything with the connections. - + - Something failed, and we cannot handle it properly. + Listen for regular HTTP connections + IP Address to accept connections on + TCP Port to listen on, default HTTP port is 80. + Factory used to create es. + address is null. + Port must be a positive number. - + - Interface used to write to log files. + Initializes a new instance of the class. + IP Address to accept connections on + TCP Port to listen on, default HTTPS port is 443 + Factory used to create es. + Certificate to use - + - Write an entry to the log file. + Initializes a new instance of the class. - object that is writing to the log - importance of the log message - the message + IP Address to accept connections on + TCP Port to listen on, default HTTPS port is 443 + Factory used to create es. + Certificate to use + which HTTPS protocol to use, default is TLS. - - - This class writes to the console. It colors the output depending on the logprio and includes a 3-level stacktrace (in debug mode) - - + + Exception. - + - The actual instance of this class. + Will try to accept connections one more time. + If any exceptions is thrown. - + - Logwriters the specified source. + Can be used to create filtering of new connections. - object that wrote the logentry. - Importance of the log message - The message. + Accepted socket + true if connection can be accepted; otherwise false. - + - Get color for the specified logprio + Start listen for new connections - prio for the log entry - A for the prio + Number of connections that can stand in a queue to be accepted. + Listener have already been started. - + - Default log writer, writes everything to null (nowhere). + Stop the listener - + - + - The logging instance. + 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. + - + - Writes everything to null + True if we should turn on trace logs. - object that wrote the log entry. - Importance of the log message - The message. - + - Inversion of control interface. + Catch exceptions not handled by the listener. + + Exceptions will be thrown during debug mode if this event is not used, + exceptions will be printed to console and suppressed during release mode. + - + - Add a component instance + A request have been received from a . - Interface type - Instance to add - + - Get a component. + New implementation of the HTTP listener. - Interface type - Component if registered, otherwise null. - Component will get created if needed. + Use the Create methods to create a default listener. - + - Checks if the specified component interface have been added. + Initializes a new instance of the class. - - true if found; otherwise false. + IP Address to accept connections on + TCP Port to listen on, default HTTP port is 80. + Factory used to create es. + address is null. + Port must be a positive number. - + - Add a component. + Initializes a new instance of the class. - Type being requested. - Type being created. + The address. + The port. + The factory. + The certificate. - + - Returns item either from a form or a query string (checks them in that order) + Initializes a new instance of the class. + The address. + The port. + The factory. + The certificate. + The protocol. - - 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 + Creates a new instance with default factories. - name identifying the value - value to add - + Address that the listener should accept connections on. + Port that listener should accept connections on. + Created HTTP listener. - + - Checks whether the form or querystring has the specified value + Creates a new instance with default factories. - Name, case sensitive - true if found; otherwise false. + Address that the listener should accept connections on. + Port that listener should accept connections on. + Certificate to use + Created HTTP listener. - + - Returns an enumerator that iterates through the collection. + Creates a new instance with default factories. - - - A that can be used to iterate through the collection. - - 1 + Address that the listener should accept connections on. + Port that listener should accept connections on. + Certificate to use + which HTTPS protocol to use, default is TLS. + Created HTTP listener. - + - Returns an enumerator that iterates through a collection. + Can be used to create filtering of new connections. - + Accepted socket - An object that can be used to iterate through the collection. + true if connection can be accepted; otherwise false. - 2 - + - Fetch an item from the form or querystring (in that order). + A client have been accepted, but not handled, by the listener. - - Item if found; otherwise HttpInputItem.EmptyLanguageNode - - - 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 + redirects from one URL to another. - The input to copy - + - Adds a file to the collection of posted files + Rules are used to perform operations before a request is being handled. + Rules can be used to create routing etc. - 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 + Process the incoming request. - Field name of the file parameter - True if the file exists - If the instance is HttpForm.EmptyForm which cannot be modified + 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. - + - Retrieves a file held by by the form + Initializes a new instance of the class. - 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 + Absolute path (no server name) + Absolute path (no server name) + + server.Add(new RedirectRule("/", "/user/index")); + - + - Retrieves the number of files added to the + Initializes a new instance of the class. - 0 if no files are added + Absolute path (no server name) + Absolute path (no server name) + true if request should be redirected, false if the request URI should be replaced. + + server.Add(new RedirectRule("/", "/user/index")); + - + - The object form class takes an object and creates form items for it. + 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. + - + - Initializes a new instance of the class. + Gets string to match request URI with. - - form name *and* id. - action to do when form is posted. - + Is compared to request.Uri.AbsolutePath - + - Initializes a new instance of the class. + Gets where to redirect. - form name *and* id. - action to do when form is posted. - object to get values from - + - Initializes a new instance of the class. + Gets whether server should redirect client. - form action. - object to get values from. + + false means that the rule will replace + the current request URI with the new one from this class. + true means that a redirect response is sent to the client. + - + - write out the FORM-tag. + Parses a HTTP request directly from a stream - generated html code - + - Writeout the form tag + Event driven parser used to parse incoming HTTP requests. - form should be posted through ajax. - generated html code + + The parser supports partial messages and keeps the states between + each parsed buffer. It's therefore important that the parser gets + ed if a client disconnects. + - + - Generates a text box. + Parse partial or complete message. - - - generated html code + buffer containing incoming bytes + where in buffer that parsing should start + number of bytes to parse + Unparsed bytes left in buffer. + BadRequestException. - + - password box + Clear parser state. - - - generated html code - + - Hiddens the specified property name. + Current state in parser. - Name of the property. - The options. - generated html code - + - Labels the specified property name. + A request have been successfully parsed. - property in object. - caption - generated html code - + - Generate a checkbox + More body bytes have been received. - property in object - checkbox value - additional html attributes. - generated html code - + - Write a html select tag + Request line have been received. - object property. - id column - The title column. - The options. - - + - Selects the specified property name. + A header have been received. - Name of the property. - The items. - The id column. - The title column. - The options. - - + - Write a submit tag. + Gets or sets the log writer. - button caption - html submit tag - + - html end form tag + Create a new request parser - html + delegate receiving log entries. - + - This provider is used to let us implement any type of form decoding we want without - having to rewrite anything else in the server. + Add a number of bytes to the body + buffer containing more body bytes. + starting offset in buffer + number of bytes, from offset, to read. + offset to continue from. - + - + Remove all state information for the request. - Should contain boundary and type, as in: multipart/form-data; boundary=---------------------------230051238959 - Stream containing form data. - Encoding used when decoding the stream - if no parser was found. - If stream is null or not readable. - If stream contents cannot be decoded properly. - + - Add a decoder. + Parse request line - - + + If line is incorrect + Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF" - + - Number of added decoders. + We've parsed a new header. + Name in lower case + Value, unmodified. + If content length cannot be parsed. - + - Use with care. + Parse a message + bytes to parse. + where in buffer that parsing should start + number of bytes to parse, starting on . + offset (where to start parsing next). + BadRequestException. - + - Decoder used for unknown content types. + Gets or sets the log writer. - + - 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. + Current state in parser. - Class that the exception was thrown in. - Exception - - Server will throw a InternalServerException in release version if you dont - handle this delegate. - - + - Contains a connection to a browser/client. + A request have been successfully parsed. - - Remember to after you have hooked the event. - - TODO: Maybe this class should be broken up into HttpClientChannel and HttpClientContext? - + - Initializes a new instance of the class. + More body bytes have been received. - true if the connection is secured (SSL/TLS) - client that connected. - Stream used for communication - Used to create a . - Size of buffer to use when reading data. Must be at least 4096 bytes. - If fails - Stream must be writable and readable. - + - Process incoming body bytes. + Request line have been received. - - Bytes - + - + A header have been received. - - - + - Start reading content. + Contains server side HTTP request information. - - Make sure to call base.Start() if you override this method. - - + - Clean up context. - - - Make sure to call base.Cleanup() if you override the method. - + Called during parsing of a . + + Name of the header, should not be URL encoded + Value of the header, should not be URL encoded + If a header is incorrect. - + - Disconnect from client + Add bytes to the body - error to report in the event. + 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 + bytes is null. + offset is out of range. - + - Send a response. + Clear everything in the request - Either or - HTTP status code - reason for the status code. - HTML body contents, can be null or empty. - A content type to return the body as, i.e. 'text/html' or 'text/plain', defaults to 'text/html' if null or empty - If is invalid. - + - Send a response. + Decode body into a form. - Either or - HTTP status code - reason for the status code. + A list with form decoders. + If body contents is not valid for the chosen decoder. + If body is still being transferred. - + - Send a response. + Sets the cookies. - + The cookies. - + - send a whole buffer + Create a response object. - buffer to send - + Context for the connected client. + A new . - + - Send data using the stream + Gets kind of types accepted by the client. - Contains data to send - Start position in buffer - number of bytes to send - - - + - This context have been cleaned, which means that it can be reused. + Gets or sets body stream. - + - Context have been started (a new client have connected) + Gets whether the body is complete. - + - Overload to specify own type. + Gets or sets kind of connection used for the session. - - Must be specified before the context is being used. - - + - Using SSL or other encryption method. + Gets or sets number of bytes in the body. - + - Using SSL or other encryption method. + Gets cookies that was sent with the request. - + - Specify which logger to use. + Gets form parameters. - + - Gets or sets the network stream. + Gets headers sent by the client. - + - Gets or sets IP address that the client connected from. + Gets or sets version of HTTP protocol that's used. + + Probably or . + + - + - Gets or sets port that the client connected from. + Gets whether the request was made by Ajax (Asynchronous JavaScript) - + - The context have been disconnected. + Gets or sets requested method. - Event can be used to clean up a context, or to reuse it. + Will always be in upper case. + - + - A request have been received in the context. + Gets parameter from or . - + - Helpers to make XML handling easier + Gets variables sent in the query string - + - Serializes object to XML. + Gets or sets requested URI. - object to serialize. - XML + + + + Gets URI absolute path divided into parts. + + + // URI is: http://gauffin.com/code/tiny/ + Console.WriteLine(request.UriParts[0]); // result: code + Console.WriteLine(request.UriParts[1]); // result: tiny + - Removes name spaces and adds indentation + 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. + - + - Create an object from a XML string + Gets or sets path and query. - Type of object - XML string - object + + + Are only used during request parsing. Cannot be set after "Host" header have been + added. + - + - Can handle application/x-www-form-urlencoded + PrototypeJS implementation of the javascript functions. - + + Purpose of this class is to create a javascript toolkit independent javascript helper. - Stream containing the content - Content type (with any additional info like boundry). Content type is always supplied in lower case - Stream encoding - - 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 + Generates a list with JS options. - 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 + 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. - + - Invoked when a client have been accepted by the + Removes any javascript parameters from an array of parameters - - Can be used to revoke incoming connections - + The array of parameters to remove javascript params from + An array of html parameters - + - Initializes a new instance of the class. + javascript action that should be added to the "onsubmit" event in the form tag. - The socket. + + All javascript option names should end with colon. + + + JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); + + - + - Client may not be handled. + 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);"); + + - + - Accepted socket. + 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!');"); + + - + - Client should be revoked. + 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!');"); + - + - Arguments sent when a is cleared + Close a javascript dialog window/div. + javascript for closing a dialog. + - + - Instantiates the arguments for the event + Creates a new modal dialog window - True if the session is cleared due to expiration + url to open in window. + window title (may not be supported by all js implementations) + + - + - Returns true if the session is cleared due to expiration + 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>"; + + - + - Delegate for when a IHttpSession is cleared + Determins if a list of strings contains a specific value - this is being cleared. - Arguments for the clearing + options to check in + value to find + true if value was found + case insensitive - + - Event arguments used when a new header have been parsed. + 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"); + + - + - Initializes a new instance of the class. + A link that pop ups a Dialog (overlay div) - Name of header. - Header value. + 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!');"); + - + - Initializes a new instance of the class. + create a modal dialog (usually using DIVs) + url to fetch + dialog title + javascript/html attributes. javascript options ends with colon ':'. + - + - Gets or sets header name. + Close a javascript dialog window/div. + javascript for closing a dialog. + - + - Gets or sets header value. + 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);"); + + - - Class to handle loading of resource files - - + - Initializes a new instance of the class. + Helpers making it easier to work with forms. + - + - Initializes a new instance of the class. + Used to let the website use different JavaScript libraries. + Default is - logger. - + - Loads resources from a namespace in the given assembly to an URI + Create a <form> tag. - The URI to map the resources to - The assembly in which the resources reside - The namespace from which to load the resources - + name of form + action to invoke on submit + form should be posted as Ajax + HTML code + - resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views"); + // without options + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); + + // with options + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax, "style", "display:inline", "class", "greenForm"); - Will make the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ - - The amount of loaded files, giving you the possibility of making sure the resources needed gets loaded - If a resource has already been mapped to an uri + + HTML attributes or JavaScript options. + Method will ALWAYS be POST. + options must consist of name, value, name, value - + - Retrieves a stream for the specified resource path if loaded otherwise null + Creates a select list with the values in a collection. - Path to the resource to retrieve a stream for - A stream or null if the resource couldn't be found + 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 containing a SELECT-tag. + - + - Fetch all files from the resource that matches the specified arguments. + Creates a select list with the values in a collection. - The path to the resource to extract - - a list of files if found; or an empty array if no files are found. - - Search path must end with an asterisk for finding arbitrary files + 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 containing 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; + } + + + name, id, collection or getIdTitle is null. - + - Fetch all files from the resource that matches the specified arguments. + Creates a select list with the values in a collection. - Where the file should reside. - Files to check - - a list of files if found; or an empty array if no files are found. - + 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 containing a SELECT-tag. + + name, id, collection or getIdTitle is null. + Invalid HTML attribute list. - + - Returns whether or not the loader has an instance of the file requested + Generate a list of HTML options - The name of the template/file - True if the loader can provide the file + 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. + + collection or getIdTitle is null. - - - redirects from one URL to another. - + + sb is null. - + - Rules are used to perform operations before a request is being handled. - Rules can be used to create routing etc. + Creates a check box. + element name + element value + determines if the check box is selected or not. This is done differently depending on the + type of variable. A boolean simply triggers 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 - + - Process the incoming request. + Creates a check box. - incoming HTTP request - outgoing HTTP response - true if response should be sent to the browser directly (no other rules or modules will be processed). + element name + element id + element value + determines if the check box is selected or not. This is done differently depending on the + type of variable. A boolean simply triggers 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 - returning true means that no modules will get the request. Returning true is typically being done - for redirects. + value in your business object. (check box will be selected if it matches the element value) - If request or response is null. - - - - Initializes a new instance of the class. - - Absolute path (no server name) - Absolute path (no server name) - - server.Add(new RedirectRule("/", "/user/index")); - - + - Initializes a new instance of the class. + Creates a check box. - Absolute path (no server name) - Absolute path (no server name) - true if request should be redirected, false if the request URI should be replaced. - - server.Add(new RedirectRule("/", "/user/index")); - + element name + element id + determines if the check box is selected or not. This is done differently depending on the + type of variable. A boolean simply triggers 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". - + - Process the incoming request. + Creates a RadioButton. - 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. - + element name + element value + determines if the radio button is selected or not. This is done differently depending on the + type of variable. A boolean simply triggers 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 - + - Gets string to match request URI with. + Creates a RadioButton. - Is compared to request.Uri.AbsolutePath + element name + element id + element value + determines if the radio button is selected or not. This is done differently depending on the + type of variable. A boolean simply triggers 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 - + - Gets where to redirect. + form close tag + - + - Gets whether server should redirect client. + 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 - false means that the rule will replace - the current request URI with the new one from this class. - true means that a redirect response is sent to the client. + Server will throw a InternalServerException in release version if you dont + handle this delegate. - + - Used to queue incoming requests. + 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. + Authentication modules are used to implement different + kind of HTTP authentication. - Called when a request should be processed. - + - Used to process queued requests. + Tag used for authentication. - + - Gets or sets maximum number of allowed simultaneous requests. + 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). - + - Gets or sets maximum number of requests queuing to be handled. + Initializes a new instance of the class. + Delegate used to provide information used during authentication. - + - Specifies how many requests the HTTP server is currently processing. + 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 authentication request. + If realm is empty or null. - + - Used two queue incoming requests to avoid - thread starvation. + 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 is invalid + If any of the parameters is empty or null. - + - Method used to process a queued request + Used to invoke the authentication delegate that is used to lookup the user name/realm. - Context that the request was received from. - Request to process. + Realm (domain) that user want to authenticate in + User name + 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 - + - Parses a HTTP request directly from a stream + Determines if authentication is required. + HTTP request from browser + true if user should be authenticated. + throw from your delegate if no more attempts are allowed. + If no more attempts are allowed - + - Event driven parser used to parse incoming HTTP requests. + name used in HTTP request. - - The parser supports partial messages and keeps the states between - each parsed buffer. It's therefore important that the parser gets - ed if a client disconnects. - - + - Parse partial or complete message. + Initializes a new instance of the class. - buffer containing incoming bytes - where in buffer that parsing should start - number of bytes to parse - Unparsed bytes left in buffer. - BadRequestException. + Delegate used to provide information used during authentication. + Delegate used to determine if authentication is required (may be null). - + - Clear parser state. + Initializes a new instance of the class. + Delegate used to provide information used during authentication. - + - Current state in parser. + Used by test classes to be able to use hardcoded values - + - A request have been successfully parsed. + 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. - + - More body bytes have been received. + Encrypts parameters into a Digest string + Realm that the user want to log into. + User logging in + Users password. + HTTP method. + Uri/domain that generated the login prompt. + Quality of Protection. + "Number used ONCE" + Hexadecimal request counter. + "Client Number used ONCE" + Digest encrypted string - + - Request line have been received. + + Md5 hex encoded "userName:realm:password", without the quotes. + Md5 hex encoded "method:uri", without the quotes + Quality of Protection + "Number used ONCE" + Hexadecimal request counter. + Client number used once + - + - A header have been received. + 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. - + - Gets or sets the log writer. + 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. - + - Create a new request parser + Gets the current nonce. - delegate receiving log entries. + - + - Add a number of bytes to the body + Gets the Md5 hash bin hex2. - buffer containing more body bytes. - starting offset in buffer - number of bytes, from offset, to read. - offset to continue from. + To be hashed. + - + - Remove all state information for the request. + determines if the nonce is valid or has expired. + nonce value (check wikipedia for info) + true if the nonce has not expired. - + - Parse request line + name used in http request. - - If line is incorrect - Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF" - + - We've parsed a new header. + Gets or sets whether the token supplied in is a + HA1 generated string. - Name in lower case - Value, unmodified. - If content length cannot be parsed. - + - Parse a message + Generic helper functions for HTTP - bytes to parse. - where in buffer that parsing should start - number of bytes to parse, starting on . - offset (where to start parsing next). - BadRequestException. - + - Gets or sets the log writer. + Version string for HTTP v1.0 - + - Current state in parser. + Version string for HTTP v1.1 - + - A request have been successfully parsed. + An empty URI - + - More body bytes have been received. + Parses a query string. + Query string (URI encoded) + A object if successful; otherwise + queryString is null. + If string cannot be parsed. - + - Request line have been received. + Delegate used to let authentication modules authenticate the user name and password. + Realm that the user want to authenticate in + User name specified by client + Can either be user password or implementation specific token. + object that will be stored in a session variable called if authentication was successful. + throw forbidden exception if too many attempts have been made. + + + Use to specify that the token is a HA1 token. (MD5 generated + string from realm, user name and password); Md5String(userName + ":" + realm + ":" + password); + + - + - A header have been received. + Let's you decide on a system level if authentication is required. + HTTP request from client + true if user should be authenticated. + throw if no more attempts are allowed. + If no more attempts are allowed - + - 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. + Arguments used when more body bytes have come. - - public void MyHandler(IHttpRequest request, IHttpResponse response) - { - - } - - + - Add another header to the document. + Initializes a new instance of the class. - 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. + buffer that contains the received bytes. + offset in buffer where to start processing. + number of bytes from that should be parsed. - + - Send headers and body to the browser. + Initializes a new instance of the class. - If content have already been sent. - + - Make sure that you have specified ContentLength and sent the headers first. + Gets or sets buffer that contains the received bytes. - - 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. + Gets or sets number of bytes from that should be parsed. - - 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. + Gets or sets offset in buffer where to start processing. - If headers already been sent. - - - - + - Redirect client to somewhere else using the 302 status code. + Contains all HTTP Methods (according to the HTTP 1.1 specification) + + See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + - 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 + The DELETE method requests that the origin server delete the resource identified by the Request-URI. - where the redirect should go - No body are allowed when doing redirects. + + 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 body stream is used to cache the body contents - before sending everything to the client. It's the simplest - way to serve documents. + 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. + + - + - Defines the version of the HTTP Response for applications where it's required - for this to be forced. + The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. + + The meta information 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 meta information 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 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. + 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. + - + - Kind of connection + 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. + + - + - Encoding to use when sending stuff to the client. + The PUT method requests that the enclosed entity be stored under the supplied Request-URI. - Default is UTF8 + + + + 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. + + - + - Number of seconds to keep connection alive + The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - Only used if Connection property is set to ConnectionType.KeepAlive - + - Status code that is sent to the client. + Contains all HTTP Methods (according to the HTTP 1.1 specification) + + See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + - Default is HttpStatusCode.Ok - + - Information about why a specific status code was used. + 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. + + - + - Size of the body. MUST be specified before sending the header, - unless property Chunked is set to true. + 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. + + - + - Kind of content in the body + The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. - Default is text/html + + The meta information 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 meta information 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. + - + - Headers have been sent to the client- + The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. - You can not send any additional headers if they have already been sent. + + 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 whole response have been sent. + 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. + + - + - Cookies that should be created/changed. + 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. + + - + - Type of HTTP connection + The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - + - Connection is closed after each request-response + Used to create and reuse contexts. - + - Connection is kept alive for X seconds (unless another request have been made) + Used to create es. - + - Response that is sent back to the web browser / client. + Creates a that handles a connected 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 slightly 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 and before doing so. - - - - - // Example using response body. - class MyModule : HttpModule - { - public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session) - { - StreamWriter writer = new StreamWriter(response.Body); - writer.WriteLine("Hello dear World!"); - writer.Flush(); - - // return true to tell webserver that we've handled the url - return true; - } - } - - - todo: add two examples, using SendHeaders/SendBody and just the Body stream. + Client socket (accepted by the ). + A creates . - + - Initializes a new instance of the class. + Create a secure . - Client that send the . - Contains information of what the client want to receive. - cannot be empty. + Client socket (accepted by the ). + HTTPS certificate to use. + Kind of HTTPS protocol. Usually TLS or SSL. + A created . - + - Initializes a new instance of the class. + A request have been received from one of the contexts. - Client that send the . - Version of HTTP protocol that the client uses. - Type of HTTP connection used. - + - Add another header to the document. + Initializes a new instance of the class. - 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. + The writer. + Amount of bytes to read from the incoming socket stream. + Used to create a request parser. - + - Send headers and body to the browser. + Create a new context. - If content have already been sent. + true if socket is running HTTPS. + Client that connected + Network/SSL stream. + A context. - + - Make sure that you have specified and sent the headers first. + Create a new context. - - If headers have not been sent. - - offset 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. + true if HTTPS is used. + Remote client + Network stream, uses . + A new context (always). - + - Make sure that you have specified and sent the headers first. + Create a secure . - - 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. + Client socket (accepted by the ). + HTTPS certificate to use. + Kind of HTTPS protocol. Usually TLS or SSL. + + A created . + - + - Send headers to the client. + Creates a that handles a connected client. - If headers already been sent. - - - + Client socket (accepted by the ). + + A creates . + - + - Redirect client to somewhere else using the 302 status code. + True if detailed trace logs should be written. - 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 + A request have been received from one of the contexts. - 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. + Custom network stream to mark sockets as reusable when disposing the stream. - + - 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. + Creates a new instance of the class for the specified . + + The that the will use to send and receive data. + + + The parameter is null. + + + The parameter is not connected. + -or- + The property of the parameter is not . + -or- + The parameter is in a nonblocking state. + - + - Defines the version of the HTTP Response for applications where it's required - for this to be forced. + Initializes a new instance of the class for the specified with the specified ownership. + + The that the will use to send and receive data. + + + Set to true to indicate that the will take ownership of the ; otherwise, false. + + + The parameter is null. + + + The parameter is not connected. + -or- + the value of the property of the parameter is not . + -or- + the parameter is in a nonblocking state. + - + - Kind of connection + Creates a new instance of the class for the specified with the specified access rights. + + The that the will use to send and receive data. + + + A bitwise combination of the values that specify the type of access given to the over the provided . + + + The parameter is null. + + + The parameter is not connected. + -or- + the property of the parameter is not . + -or- + the parameter is in a nonblocking state. + - + - Encoding to use when sending stuff to the client. + Creates a new instance of the class for the specified with the specified access rights and the specified ownership. - Default is UTF8 + + The that the will use to send and receive data. + + + A bitwise combination of the values that specifies the type of access given to the over the provided . + + + Set to true to indicate that the will take ownership of the ; otherwise, false. + + + The parameter is null. + + + The parameter is not connected. + -or- + The property of the parameter is not . + -or- + The parameter is in a nonblocking state. + - + - Number of seconds to keep connection alive + Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. - Only used if Connection property is set to . - + - Status code that is sent to the client. + Releases the unmanaged resources used by the and optionally releases the managed resources. - Default is + true to release both managed and unmanaged resources; false to release only unmanaged resources. - + - Information about why a specific status code was used. + Invoked when a client have been accepted by the + + Can be used to revoke incoming connections + - + - Size of the body. MUST be specified before sending the header, - unless property Chunked is set to true. + Initializes a new instance of the class. + The socket. - + - Kind of content in the body + Client may not be handled. - Default type is "text/html" - + - Headers have been sent to the client- + Accepted socket. - You can not send any additional headers if they have already been sent. - + - The whole response have been sent. + Client should be revoked. - + - Cookies that should be created/changed. + A session stored in memory. - + - 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 + Interface for sessions - - // becomes: - Console.WriteLine("Value: {0}", form["user"]["FirstName"].Value); - - - All names in a form SHOULD be in lowercase. - - - Representation of a non-initialized . - - + - Initializes an input item setting its name/identifier and value + Remove everything from the session - 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 + Remove everything from the session - Value to add. - Cannot add stuff to . + True if the session is cleared due to expiration - + - checks if a sub-item exists (and has a value). + Session id - name in lower case - true if the sub-item exists and has a value; otherwise false. - - Returns a formatted representation of the instance with the values of all contained parameters + + + Should + + Name of the session variable + null if it's not set + If the object cant be serialized. - + - Outputs the string in a formatted manner + When the session was last accessed. + This property is touched by the http server each time the + session is requested. - A prefix to append, used internally - produce a query string - + - Add a sub item. + Number of session variables. - Can contain array formatting, the item is then parsed and added in multiple levels - Value to add. - Argument is null. - Cannot add stuff to . - + - Returns an enumerator that iterates through the collection. + Event triggered upon clearing the session + + + - - A that can be used to iterate through the collection. - - 1 + + A unique id used by the sessions store to identify the session - + - Returns an enumerator that iterates through a collection. + Id - - - An object that can be used to iterate through the collection. - - 2 + - + - Outputs the string in a formatted manner + Remove everything from the session - A prefix to append, used internally - - + - Number of values + Clears the specified expire. + True if the session is cleared due to expiration - + - Get a sub item + Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - name in lower case. - if no item was found. + 2 - + - Name of item (in lower case). + Session id - + - Returns the first value, or null if no value exist. + Should + Name of the session variable + null if it's not set - + - Returns the last value, or null if no value exist. + when the session was last accessed. + + Used to determine when the session should be removed. + - + - Returns the list with values. + Number of values in the session - + - + Flag to indicate that the session have been changed + and should be saved into the session store. - name in lower case - - + - Helpers making it easier to work with forms. + Event triggered upon clearing the session - - + - Used to let the website use different JavaScript libraries. - Default is + 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. - + - Create a <form> tag. + - name of form - action to invoke on submit - form should be posted as Ajax - HTML code + Base url requested from browser + Base url on private web server - - // without options - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); - - // with options - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax, "style", "display:inline", "class", "greenForm"); - + // 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/"); - HTML attributes or JavaScript options. - Method will ALWAYS be POST. - options must consist of name, value, name, value - + - Creates a select list with the values in a collection. + Method that determines if an url should be handled or not by the module - 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 containing a SELECT-tag. - + Url requested by the client. + true if module should handle the url. - + - Creates a select list with the values in a collection. + Method that process the url - 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 containing 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; - } - - - name, id, collection or getIdTitle is null. + Information sent by the browser about the request + Information that is being sent back to the client. + Session used to - + - Creates a select list with the values in a collection. + Can handle application/x-www-form-urlencoded - 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 containing a SELECT-tag. - - name, id, collection or getIdTitle is null. - Invalid HTML attribute list. - + - 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. - - collection or getIdTitle is null. - - - sb is null. + Stream containing the content + Content type (with any additional info like boundry). Content type is always supplied in lower case + Stream encoding + + A HTTP form, or null if content could not be parsed. + + If contents in the stream is not valid input data. - + - Creates a check box. + Checks if the decoder can handle the mime type - element name - element value - determines if the check box is selected or not. This is done differently depending on the - type of variable. A boolean simply triggers 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 + 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 - + - Creates a check box. + This provider is used to let us implement any type of form decoding we want without + having to rewrite anything else in the server. - element name - element id - element value - determines if the check box is selected or not. This is done differently depending on the - type of variable. A boolean simply triggers 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 check box. + - element name - element id - determines if the check box is selected or not. This is done differently depending on the - type of variable. A boolean simply triggers 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". + Should contain boundary and type, as in: multipart/form-data; boundary=---------------------------230051238959 + Stream containing form data. + Encoding used when decoding the stream + if no parser was found. + If stream is null or not readable. + If stream contents cannot be decoded properly. - + - Creates a RadioButton. + Add a decoder. - element name - element value - determines if the radio button is selected or not. This is done differently depending on the - type of variable. A boolean simply triggers 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. + Number of added decoders. - element name - element id - element value - determines if the radio button is selected or not. This is done differently depending on the - type of variable. A boolean simply triggers 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 + Use with care. - - + - Add a component instance + Decoder used for unknown content types. - Interface type - Instance to add - + - Get a component. + The server encountered an unexpected condition which prevented it from fulfilling the request. - Interface type - Component if registered, otherwise null. - - Component will get created if needed. - - - - If instance cannot be created. - + - Checks if the specified component interface have been added. + Initializes a new instance of the class. - - true if found; otherwise false. - + - Add a component. + Initializes a new instance of the class. - Type being requested. - Type being created. - Type have already been mapped. + error message. - + - Arguments used when more body bytes have come. + Initializes a new instance of the class. + error message. + inner exception. - + - Initializes a new instance of the class. + 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. - buffer that contains the received bytes. - offset in buffer where to start processing. - number of bytes from that should be parsed. + + public void MyHandler(IHttpRequest request, IHttpResponse response) + { + + } + - + - Initializes a new instance of the class. + 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. - + - Gets or sets buffer that contains the received bytes. + Send headers and body to the browser. + If content have already been sent. - + - Gets or sets number of bytes from that should be parsed. + 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. - + - Gets or sets offset in buffer where to start processing. + 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. - + - Used to create and reuse contexts. + Send headers to the client. + If headers already been sent. + + + - + - Used to create es. + 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. - + - Creates a that handles a connected client. + redirect to somewhere - Client socket (accepted by the ). - A creates . + where the redirect should go + + No body are allowed when doing redirects. + - + - Create a secure . + The body stream is used to cache the body contents + before sending everything to the client. It's the simplest + way to serve documents. - Client socket (accepted by the ). - HTTPS certificate to use. - Kind of HTTPS protocol. Usually TLS or SSL. - A created . - + - A request have been received from one of the contexts. + Defines the version of the HTTP Response for applications where it's required + for this to be forced. - + - Initializes a new instance of the class. + 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. - The writer. - Amount of bytes to read from the incoming socket stream. - Used to create a request parser. - + - Create a new context. + Kind of connection - true if socket is running HTTPS. - Client that connected - Network/SSL stream. - A context. - + - Create a new context. + Encoding to use when sending stuff to the client. - true if HTTPS is used. - Remote client - Network stream, uses . - A new context (always). + Default is UTF8 - + - Create a secure . + Number of seconds to keep connection alive - Client socket (accepted by the ). - HTTPS certificate to use. - Kind of HTTPS protocol. Usually TLS or SSL. - - A created . - + Only used if Connection property is set to ConnectionType.KeepAlive - + - Creates a that handles a connected client. + Status code that is sent to the client. - Client socket (accepted by the ). - - A creates . - + Default is HttpStatusCode.Ok - + - True if detailed trace logs should be written. + Information about why a specific status code was used. - + - A request have been received from one of the contexts. + Size of the body. MUST be specified before sending the header, + unless property Chunked is set to true. - + - Custom network stream to mark sockets as reusable when disposing the stream. + Kind of content in the body + Default is text/html - + - Creates a new instance of the class for the specified . + Headers have been sent to the client- - - The that the will use to send and receive data. - - - The parameter is null. - - - The parameter is not connected. - -or- - The property of the parameter is not . - -or- - The parameter is in a nonblocking state. - + You can not send any additional headers if they have already been sent. - + - Initializes a new instance of the class for the specified with the specified ownership. + The whole response have been sent. - - The that the will use to send and receive data. - - - Set to true to indicate that the will take ownership of the ; otherwise, false. - - - The parameter is null. - - - The parameter is not connected. - -or- - the value of the property of the parameter is not . - -or- - the parameter is in a nonblocking state. - - + - Creates a new instance of the class for the specified with the specified access rights. + Cookies that should be created/changed. - - The that the will use to send and receive data. - - - A bitwise combination of the values that specify the type of access given to the over the provided . - - - The parameter is null. - - - The parameter is not connected. - -or- - the property of the parameter is not . - -or- - the parameter is in a nonblocking state. - - + - Creates a new instance of the class for the specified with the specified access rights and the specified ownership. + Type of HTTP connection - - The that the will use to send and receive data. - - - A bitwise combination of the values that specifies the type of access given to the over the provided . - - - Set to true to indicate that the will take ownership of the ; otherwise, false. - - - The parameter is null. - - - The parameter is not connected. - -or- - The property of the parameter is not . - -or- - The parameter is in a nonblocking state. - - + - Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. + Connection is closed after each request-response - + - Releases the unmanaged resources used by the and optionally releases the managed resources. + Connection is kept alive for X seconds (unless another request have been made) - true to release both managed and unmanaged resources; false to release only unmanaged resources. - + - Serves files that are stored in embedded resources. + 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. - + - A HttpModule can be used to serve Uri's. The module itself - decides if it should serve a Uri or not. In this way, you can - get a very flexible http application since you can let multiple modules - serve almost similar urls. + - - Throw if you are using a and want to prompt for user name/password. - + 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 - true if this module handled the request. - + - Set the log writer to use. + Name of site. - logwriter to use. - + - Log something. + Used to inform http server that - 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. + Eventarguments used when an exception is thrown by a module + the exception - + - 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. + Exception thrown in a module - + - 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. + 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 - The log writer to use when logging events + + // becomes: + Console.WriteLine("Value: {0}", form["user"]["FirstName"].Value); + + + All names in a form SHOULD be in lowercase. + - - - Mimtypes that this class can handle per default - + + Representation of a non-initialized . - + - Loads resources from a namespace in the given assembly to an uri + Initializes an input item setting its name/identifier and value - 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 - - The amount of loaded files, giving you the possibility of making sure the resources needed gets loaded + Parameter name/id + Parameter value - - - Returns true if the module can handle the request - + + 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 - + - Method that process the url + Add another value to this item - 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. + Value to add. + Cannot add stuff to . - + - List with all mime-type that are allowed. + checks if a sub-item exists (and has a value). - All other mime types will result in a Forbidden http status code. + name in lower case + true if the sub-item exists and has a value; otherwise false. - + + Returns a formatted representation of the instance with the values of all contained parameters + + - The purpose of this module is to serve files. + Outputs the string in a formatted manner + A prefix to append, used internally + produce a query string - + - Initializes a new instance of the class. + Add a sub item. - 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 web browser to cache files + Can contain array formatting, the item is then parsed and added in multiple levels + Value to add. + Argument is null. + Cannot add stuff to . - + - Initializes a new instance of the class. + Returns an enumerator that iterates through the collection. - Uri to serve, for instance "/files/" - Path on hard drive where we should start looking for files + + + A that can be used to iterate through the collection. + + 1 - + - Mimtypes that this class can handle per default + Returns an enumerator that iterates through a collection. + + + An object that can be used to iterate through the collection. + + 2 - + - Determines if the request should be handled by this module. - Invoked by the + Outputs the string in a formatted manner - - true if this module should handle it. - - - Illegal path + A prefix to append, used internally + - + - check if source contains any of the chars. + Number of values - - - - + - Method that process the Uri. + Get a sub item - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to - Failed to find file extension - File type is forbidden. + name in lower case. + if no item was found. - + - return a file extension from an absolute Uri path (or plain filename) + Name of item (in lower case). - - - + - List with all mime-type that are allowed. + Returns the first value, or null if no value exist. - All other mime types will result in a Forbidden http status code. - + - characters that may not exist in a path. + Returns the last value, or null if no value exist. - - fileMod.ForbiddenChars = new string[]{ "\\", "..", ":" }; - - + - The server encountered an unexpected condition which prevented it from fulfilling the request. + Returns the list with values. - + - Initializes a new instance of the class. + + name in lower case + - + + Class to handle loading of resource files + + - Initializes a new instance of the class. + Initializes a new instance of the class. - error message. - + - Initializes a new instance of the class. + Initializes a new instance of the class. - error message. - inner exception. + logger. - + - 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 their targets. + Loads resources from a namespace in the given assembly to an URI - - [a-z0-9]+)", "/users/${target}?find=true", RegexOptions.IgnoreCase) - ]]> - + 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 the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/ + + The amount of loaded files, giving you the possibility of making sure the resources needed gets loaded + If a resource has already been mapped to an uri - + - Initializes a new instance of the class. + Retrieves a stream for the specified resource path if loaded otherwise null - Expression to match URL - Expression to generate URL - - [a-zA-Z0-9]+)", "/user/${first}")); - Result of ie. /employee1 will then be /user/employee1 - ]]> - + Path to the resource to retrieve a stream for + A stream or null if the resource couldn't be found - + - Initializes a new instance of the class. + Fetch all files from the resource that matches the specified arguments. - 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 - ]]> - + The path to the resource to extract + + a list of files if found; or an empty array if no files are found. + + Search path must end with an asterisk for finding arbitrary files - + - Initializes a new instance of the class. + Fetch all files from the resource that matches the specified arguments. - 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 - ]]> - - Argument is null. - + Where the file should reside. + Files to check + + a list of files if found; or an empty array if no files are found. + - + - Process the incoming request. + Returns whether or not the loader has an instance of the file requested - 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 + The name of the template/file + True if the loader can provide the file @@ -3664,908 +3707,849 @@ Gets or sets requested URI path. - + + + Class that receives Requests from a . + + + + + 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. + + + + 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 + + + + Retrieves the number of files added to the + + 0 if no files are added + + + + Contains a connection to a browser/client. + + + Remember to after you have hooked the event. + + TODO: Maybe this class should be broken up into HttpClientChannel and HttpClientContext? + + + + Initializes a new instance of the class. + + true if the connection is secured (SSL/TLS) + client that connected. + Stream used for communication + Used to create a . + Size of buffer to use when reading data. Must be at least 4096 bytes. + If fails + Stream must be writable and readable. + + + + Process incoming body bytes. + + + Bytes + + + + + + + + + - Delegate used to find a realm/domain. + Start reading content. - - - Realms are used during HTTP Authentication + Make sure to call base.Start() if you override this method. - - - - - - 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. + Clean up context. - Used to get all components used in the server.. + + Make sure to call base.Cleanup() if you override the method. + - + - Initializes a new instance of the class. + Disconnect from client + error to report in the event. - + - Initializes a new instance of the class. + Send a response. - Form decoders are used to convert different types of posted data to the object types. - - + Either or + HTTP status code + reason for the status code. + HTML body contents, can be null or empty. + A content type to return the body as, i.e. 'text/html' or 'text/plain', defaults to 'text/html' if null or empty + If is invalid. - + - Initializes a new instance of the class. + Send a response. - A session store is used to save and retrieve sessions - + Either or + HTTP status code + reason for the status code. - + - Initializes a new instance of the class. + Send a response. - The log writer. - + - + - Initializes a new instance of the class. + send a whole buffer - Form decoders are used to convert different types of posted data to the object types. - The log writer. - - - + buffer to send + - + - Initializes a new instance of the class. + Send data using the stream - 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. - - - - + Contains data to send + Start position in buffer + number of bytes to send + + - + - Adds the specified rule. + This context have been cleaned, which means that it can be reused. - The rule. - + - Add a to the server. + Context have been started (a new client have connected) - mode to add - + - Decodes the request body. + Overload to specify own type. - The request. - Failed to decode form data. + + Must be specified before the context is being used. + - + - Generate a HTTP error page (that will be added to the response body). - response status code is also set. + Using SSL or other encryption method. - 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. + Using SSL or other encryption method. - Response that the page will be generated in. - exception. - + - Realms are used by the s. + Specify which logger to use. - HTTP request - domain/realm. - + - Process an incoming request. + Gets or sets the network stream. - connection to client - request information - response that should be filled - session information - + - Can be overloaded to implement stuff when a client have been connected. + Gets or sets IP address that the client connected from. - - Default implementation does nothing. - - client that disconnected - disconnect reason - + - Handle authentication + Gets or sets port that the client connected from. - - - - true if request can be handled; false if not. - Invalid authorization header - + - Will request authentication. + The context have been disconnected. - Sends respond to client, nothing else can be done with the response after this. + Event can be used to clean up a context, or to reuse it. - - - - + - Received from a when a request have been parsed successfully. + A request have been received in the context. - that received the request. - The request. - + - To be able to track request count. + Helpers to make XML handling easier - - - + - Start the web server using regular HTTP. + Serializes object to XML. - 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 =) - address is null. - Port must be a positive number. + object to serialize. + XML + + Removes name spaces and adds indentation + - + - Accept secure connections. + Create an object from a XML string - IP Address to listen on, use to accept connections on all IP Addresses / network cards. - Port to listen on. 80 can be a good idea =) - Certificate to use - address is null. - Port must be a positive number. + Type of object + XML string + object - + - shut down the server and listeners + + + + - + + Represents a field in a multipart form + + - write an entry to the log file + Small design by contract implementation. - importance of the message - log message - + - write an entry to the log file + Check whether a parameter is empty. - object that wrote the message - importance of the message - log message + Parameter value + Parameter name, or error description. + value is empty. - + - Server that is handling the current request. + Checks whether a parameter is null. - - Will be set as soon as a request arrives to the object. - + Parameter value + Parameter name, or error description. + value is null. - + - Modules used for authentication. The module that is is added first is used as - the default authentication module. + Checks whether a parameter is null. - Use the corresponding property - in the if you are using multiple websites. + + Parameter value + Parameter name, or error description. + value is null. - + - Form decoder providers are used to decode request body (which normally contains form data). + Priority for log entries + - + - Server name sent in HTTP responses. + Very detailed logs to be able to follow the flow of the program. - - Do NOT include version in name, since it makes it - easier for hackers. - - + - Name of cookie where session id is stored. + Logs to help debug errors in the application - + - Specified where logging should go. + Information to be able to keep track of state changes etc. - - - - + - Number of connections that can wait to be accepted by the server. + Something did not go as we expected, but it's no problem. - Default is 10. - + - Gets or sets maximum number of allowed simultaneous requests. + Something that should not fail failed, but we can still keep + on going. - - - This property is useful in busy systems. The HTTP server - will start queuing new requests if this limit is hit, instead - of trying to process all incoming requests directly. - - - The default number if allowed simultaneous requests are 10. - - - + - Gets or sets maximum number of requests queuing to be handled. + Something failed, and we cannot handle it properly. - - - The WebServer will start turning requests away if response code - to indicate that the server - is too busy to be able to handle the request. - - - + - Realms are used during HTTP authentication. - Default realm is same as server name. + Interface used to write to log files. - + - Let's to receive unhandled exceptions from the threads. + Write an entry to the log file. - - Exceptions will be thrown during debug mode if this event is not used, - exceptions will be printed to console and suppressed during release mode. - + object that is writing to the log + importance of the log message + the message - + - 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) + This class writes to the console. It colors the output depending on the logprio and includes a 3-level stacktrace (in debug mode) + - + - Create a new unauhtorized exception. + The actual instance of this class. - - + - Create a new unauhtorized exception. + Logwriters the specified source. - reason to why the request was unauthorized. - inner exception + object that wrote the logentry. + Importance of the log message + The message. - + - Create a new unauhtorized exception. + Get color for the specified logprio - reason to why the request was unauthorized. + prio for the log entry + A for the prio - + - Lists content type mime types. + Default log writer, writes everything to null (nowhere). + - + - text/plain + The logging instance. - + - text/haml + Writes everything to null + object that wrote the log entry. + Importance of the log message + The message. - + - content type for javascript documents = application/javascript + Response that is sent back to the web browser / client. - 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. + 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 slightly 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 and before doing so. - Browser support: http://krijnhoetmer.nl/stuff/javascript/mime-types/ - - - - text/xml - - - - - A list of content types - - - - + + + // Example using response body. + class MyModule : HttpModule + { + public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session) + { + StreamWriter writer = new StreamWriter(response.Body); + writer.WriteLine("Hello dear World!"); + writer.Flush(); - - Semicolon separated content types. + // return true to tell webserver that we've handled the url + return true; + } + } + + + todo: add two examples, using SendHeaders/SendBody and just the Body stream. - + - Returns an enumerator that iterates through a collection. + Initializes a new instance of the class. - - An object that can be used to iterate through the collection. - + Client that send the . + Contains information of what the client want to receive. + cannot be empty. - + - Searches for the specified type + Initializes a new instance of the class. - Can also be a part of a type (searching for "xml" would return true for "application/xml"). - true if type was found. + Client that send the . + Version of HTTP protocol that the client uses. + Type of HTTP connection used. - + - Get this first content type. + 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. - + - Fetch a content type + Send headers and body to the browser. - Part of type ("xml" would return "application/xml") - - All content types are in lower case. + If content have already been sent. - + - Session store using memory for each session. + Make sure that you have specified and sent the headers first. + + If headers have not been sent. + + offset 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. - + - Initializes the class setting the expirationtimer to clean the session every minute + Make sure that you have specified 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. - + - Delegate for the cleanup timer + Send headers to the client. + If headers already been sent. + + + - + - Creates a new http session + 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. - + - Creates a new http session with a specific id + redirect to somewhere - Id used to identify the new cookie.. - A object. + where the redirect should go - Id should be generated by the store implementation if it's null or . + No body are allowed when doing redirects. - + - Load an existing session. + The body stream is used to cache the body contents + before sending everything to the client. It's the simplest + way to serve documents. - - - + - Save an updated session to the store. + 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. - - + - We use the flyweight pattern which reuses small objects - instead of creating new each time. + Defines the version of the HTTP Response for applications where it's required + for this to be forced. - EmptyLanguageNode (unused) session that should be reused next time Create is called. - + - Remove expired sessions + Kind of connection - + - Remove a session + Encoding to use when sending stuff to the client. - id of the session. + Default is UTF8 - + - Load a session from the store + Number of seconds to keep connection alive - - null if session is not found. + Only used if Connection property is set to . - + - Number of minutes before a session expires. - Default is 20 minutes. + Status code that is sent to the client. + Default is - + - Webhelper provides helpers for common tasks in HTML. + Information about why a specific status code was used. - + - Used to let the website use different javascript libraries. - Default is + Size of the body. MUST be specified before sending the header, + unless property Chunked is set to true. - + - Creates a link that invokes through ajax. + Kind of content in the body - 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');"); - + Default type is "text/html" - + - Builds a link that updates an element with the fetched ajax content. + Headers have been sent to the client- - 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. + You can not send any additional headers if they have already been sent. - + - A link that pop ups a Dialog (overlay div) + The whole response have been sent. - 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 + Cookies that should be created/changed. - - - - - + - Close a javascript dialog window/div. + The requested resource was not found in the web server. - javascript for closing a dialog. - - + - Create a <form> tag. + Create a new exception - name of form - action to invoke on submit - form should be posted as ajax - html code - - WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); - + message describing the error + inner exception - + - Create a link tag. + Create a new exception - 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?');"); - + message describing the error - + - Build a link + Session store using memory for each session. - url to go to. - title of link (displayed text) - extra html attributes. - a complete link - + - Build a link + A session store is used to store and load sessions on a media. + The default implementation () saves/retrieves sessions from memory. - url to go to. - title of link (displayed text) - extra html attributes. - a complete link - more options - + - Obsolete + Creates a new http session with a generated id. - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete + A object - + - Obsolete + Creates a new http session with a specific id - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete - Obsolete + Id used to identify the new cookie.. + A object. + + Id should be generated by the store implementation if it's null or . + - + - Render errors into a UL with class "errors" + Load an existing session. - class used by UL-tag. - items to list - an unordered html list. + Session id (usually retrieved from a client side cookie). + A session if found; otherwise null. - + - Render errors into a UL with class "errors" + Save an updated session to the store. - class used by UL-tag. - items to list - an unordered html list. + Session id (usually retrieved from a client side cookie). + If Id property have not been specified. - + - Render errors into a UL with class "errors" + 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. - + - Generates a list with html attributes. + Remove expired sessions - 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. + Remove a session - StringBuilder that the options should be added to. - + id of the session. - + - Purpose of this class is to create a javascript toolkit independent javascript helper. + Load a session from the store + + null if session is not found. - + - Generates a list with JS options. + Number of minutes before a session expires. - 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. + Default time is 20 minutes. - + - Removes any javascript parameters from an array of parameters + Initializes the class setting the expirationtimer to clean the session every minute + + + + + Delegate for the cleanup timer - 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. + Creates a new http session - All javascript option names should end with colon. - - - JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); - - - + - Requests a url through ajax + Creates a new http session with a specific id - 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);"); - - + Id used to identify the new cookie.. + A object. + + Id should be generated by the store implementation if it's null or . + - + - Ajax requests that updates an element with - the fetched content + Load an existing session. - 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) + Save an updated session to the store. - 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. + We use the flyweight pattern which reuses small objects + instead of creating new each time. - javascript for closing a dialog. - + EmptyLanguageNode (unused) session that should be reused next time Create is called. - + - Creates a new modal dialog window + Remove expired sessions - url to open in window. - window title (may not be supported by all js implementations) - - - + - + Remove a session - - - + id of the session. - - Represents a field in a multipart form + + + Load a session from the store + + + null if session is not found. - + - 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 + Number of minutes before a session expires. + Default is 20 minutes. - + - Create a new bad request exception. + Arguments sent when a is cleared - reason to why the request was bad. - + - Create a new bad request exception. + Instantiates the arguments for the event - reason to why the request was bad. - inner exception + True if the session is cleared due to expiration - + - Container class for posted files + Returns true if the session is cleared due to expiration - + - Creates a container for a posted file + Delegate for when a IHttpSession is cleared - 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 + this is being cleared. + Arguments for the clearing - + - Creates a container for a posted file + Used to queue incoming requests. - If any parameter is null or empty - - Destructor disposing the file + + + Initializes a new instance of the class. + + Called when a request should be processed. - + - Deletes the temporary file + Used to process queued requests. - True if manual dispose - + - Disposing interface, cleans up managed resources (the temporary file) and suppresses finalization + Gets or sets maximum number of allowed simultaneous requests. - + - The name/id of the file + Gets or sets maximum number of requests queuing to be handled. - + - The full file path + Specifies how many requests the HTTP server is currently processing. - + - The name of the uploaded file + Used two queue incoming requests to avoid + thread starvation. - + - The type of file + Method used to process a queued request + Context that the request was received from. + Request to process. - + - Will contain helper functions for javascript. + Event arguments used when a new header have been parsed. - + - Requests a url through ajax + Initializes a new instance of the class. - 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>"; - - + Name of header. + Header value. - + - Ajax requests that updates an element with - the fetched content + Initializes a new instance of the class. - 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. + Gets or sets header name. - url to contents of dialog - link title - name, value, name, value, all parameter names should end with colon. - + - Close a javascript dialog window/div. + Gets or sets header value. - javascript for closing a dialog. - @@ -4738,39 +4722,113 @@ Gets whether the request was made by Ajax (Asynchronous JavaScript) - + + + Gets cookies that was sent with the request. + + + + + Add a component instance + + Interface type + Instance to add + + + + Get a component. + + Interface type + Component if registered, otherwise null. + + Component will get created if needed. + + + + If instance cannot be created. + + + + Checks if the specified component interface have been added. + + + true if found; otherwise false. + + + + Add a component. + + Type being requested. + Type being created. + Type have already been mapped. + + - Gets cookies that was sent with the request. + 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 their targets. + + [a-z0-9]+)", "/users/${target}?find=true", RegexOptions.IgnoreCase) + ]]> + - + - The website module let's you handle multiple websites in the same server. - It uses the "Host" header to check which site you want. + Initializes a new instance of the class. - 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. + 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. - domain name that should be handled. - + 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 + ]]> + - + - Method that process the url + Initializes a new instance of the class. - Information sent by the browser about the request - Information that is being sent back to the client. - Session used to + 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 + ]]> + + Argument is null. + - + - Name of site. + 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 @@ -4812,30 +4870,6 @@ Retrieves the full path name to the resource file - - - Creates request parsers when needed. - - - - - Creates request parsers when needed. - - - - - Create a new request parser. - - Used when logging should be enabled. - A new request parser. - - - - Create a new request parser. - - Used when logging should be enabled. - A new request parser. - The "basic" authentication scheme is based on the model that the @@ -4921,533 +4955,499 @@ Adding bytes to body - - - 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. - - - - - - - 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 - - - - 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 + Will contain helper functions for javascript. - + - Returns an enumerator that iterates through the collection. + 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'"); - - A that can be used to iterate through the collection. - - 1 + // ajax request using this.href + string link = "<a href=\"/user/call/1\" onclick=\"" + JSHelper.AjaxRequest("this.href") + "/<call user</a>"; + + - + - Gets the count of cookies in the collection. + 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"); + + - + - Gets the cookie of a given identifier (null if not existing). + Opens contents in a dialog window. + url to contents of dialog + link title + name, value, name, value, all parameter names should end with colon. - + - 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 + Close a javascript dialog window/div. + javascript for closing a dialog. + - + - Let's copy all the cookies. + Lists content type mime types. - value from cookie header. - + - Adds a cookie in the collection. + text/plain - cookie to add - cookie is null - + - Gets a collection enumerator on the cookie list. + text/haml - collection enumerator - + - Remove all cookies. + 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/ + - + - Returns an enumerator that iterates through the collection. + text/xml - - - A that can be used to iterate through the collection. - - 1 - + - Remove a cookie from the collection. + A list of content types - Name of cookie. - + - Gets the count of cookies in the collection. + + Semicolon separated content types. - + - Gets the cookie of a given identifier (null if not existing). + Returns an enumerator that iterates through a collection. + + An object that can be used to iterate through the collection. + - + - New implementation of the HTTP listener. + Searches for the specified type - - Use the Create methods to create a default listener. - + Can also be a part of a type (searching for "xml" would return true for "application/xml"). + true if type was found. - + - Initializes a new instance of the class. + Get this first content type. - IP Address to accept connections on - TCP Port to listen on, default HTTP port is 80. - Factory used to create es. - address is null. - Port must be a positive number. - + - Initializes a new instance of the class. + Fetch a content type - The address. - The port. - The factory. - The certificate. + Part of type ("xml" would return "application/xml") + + All content types are in lower case. - + - Initializes a new instance of the class. + Creates request parsers when needed. - The address. - The port. - The factory. - The certificate. - The protocol. - + - Creates a new instance with default factories. + Creates request parsers when needed. - Address that the listener should accept connections on. - Port that listener should accept connections on. - Created HTTP listener. - + - Creates a new instance with default factories. + Create a new request parser. - Address that the listener should accept connections on. - Port that listener should accept connections on. - Certificate to use - Created HTTP listener. + Used when logging should be enabled. + A new request parser. - + - Creates a new instance with default factories. + Create a new request parser. - Address that the listener should accept connections on. - Port that listener should accept connections on. - Certificate to use - which HTTPS protocol to use, default is TLS. - Created HTTP listener. + Used when logging should be enabled. + A new request parser. - + - Can be used to create filtering of new connections. + 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) - Accepted socket - - true if connection can be accepted; otherwise false. - - + - A client have been accepted, but not handled, by the listener. + Create a new unauhtorized exception. + - + - Generic helper functions for HTTP + Create a new unauhtorized exception. + reason to why the request was unauthorized. + inner exception - + - Version string for HTTP v1.0 + Create a new unauhtorized exception. + reason to why the request was unauthorized. - + - Version string for HTTP v1.1 + The purpose of this module is to serve files. - + - An empty URI + 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 web browser to cache files - + - Parses a query string. + Initializes a new instance of the class. - Query string (URI encoded) - A object if successful; otherwise - queryString is null. - If string cannot be parsed. + Uri to serve, for instance "/files/" + Path on hard drive where we should start looking for files - + - 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. + Mimtypes that this class can handle per default - + - + Determines if the request should be handled by this module. + Invoked by the - 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/"); - + + true if this module should handle it. - + + Illegal path + + - Method that determines if an url should be handled or not by the module + check if source contains any of the chars. - Url requested by the client. - true if module should handle the url. + + + - + - Method that process the url + Method that process the Uri. Information sent by the browser about the request Information that is being sent back to the client. Session used to + Failed to find file extension + File type is forbidden. - + - Used to inform http server that + return a file extension from an absolute Uri path (or plain filename) + + - + - Eventarguments used when an exception is thrown by a module + List with all mime-type that are allowed. - the exception + All other mime types will result in a Forbidden http status code. - + - Exception thrown in a module + characters that may not exist in a path. + + fileMod.ForbiddenChars = new string[]{ "\\", "..", ":" }; + - + - PrototypeJS implementation of the javascript functions. + Webhelper provides helpers for common tasks in HTML. - + - Requests a url through ajax + Used to let the website use different javascript libraries. + Default is - 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 + Creates a link that invokes through ajax. - options to check in - value to find - true if value was found - case insensitive + 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');"); + - + - Ajax requests that updates an element with - the fetched content + Builds a link that updates an element with the fetched ajax 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. + 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. - - - 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 + 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); }); - } - ); - - + 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 a modal dialog (usually using DIVs) + Create/Open a dialog box using ajax - 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. + Create a <form> tag. - remember to encapsulate strings in '' - - All javascript option names should end with colon. + name of form + action to invoke on submit + form should be posted as ajax + html code - - JSHelper.AjaxRequest("/user/show/1", "onsuccess:", "$('userInfo').update(result);"); - + WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax); - - - 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 + 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?');"); + - + - An authentication response have been received from the web browser. - Check if it's correct + Build a link - 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. + url to go to. + title of link (displayed text) + extra html attributes. + a complete link - + - Encrypts parameters into a Digest string + Build a link - Realm that the user want to log into. - User logging in - Users password. - HTTP method. - Uri/domain that generated the login prompt. - Quality of Protection. - "Number used ONCE" - Hexadecimal request counter. - "Client Number used ONCE" - Digest encrypted string + url to go to. + title of link (displayed text) + extra html attributes. + a complete link + more options - + - + Obsolete - Md5 hex encoded "userName:realm:password", without the quotes. - Md5 hex encoded "method:uri", without the quotes - Quality of Protection - "Number used ONCE" - Hexadecimal request counter. - Client number used once - + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete - + - Create a response that can be sent in the WWW-Authenticate header. + Obsolete - 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. + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete + Obsolete - + - Decodes authorization header value + Render errors into a UL with class "errors" - 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. + class used by UL-tag. + items to list + an unordered html list. - + - Gets the current nonce. + Render errors into a UL with class "errors" - + class used by UL-tag. + items to list + an unordered html list. - + - Gets the Md5 hash bin hex2. + Render errors into a UL with class "errors" - To be hashed. + - + - determines if the nonce is valid or has expired. + Generates a list with html attributes. - nonce value (check wikipedia for info) - true if the nonce has not expired. + StringBuilder that the options should be added to. + attributes set by user. + attributes set by any of the helper classes. - + - name used in http request. + Generates a list with html attributes. + StringBuilder that the options should be added to. + - + - Gets or sets whether the token supplied in is a - HA1 generated string. + 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; + } /// -- cgit v1.1 From 0baa2590bef8ad4e0a78a7c88d55acd0848e0068 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 6 Feb 2013 15:52:28 -0800 Subject: BulletSim: check for completely degenerate meshes (ones with all triangles having zero width) and output an error rather than throwing and exception. --- .../Physics/BulletSPlugin/BSShapeCollection.cs | 28 +++++++++++++++------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index fe0f984..15747c9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -608,7 +608,7 @@ public sealed class BSShapeCollection : IDisposable // Since we're recreating new, get rid of the reference to the previous shape DereferenceShape(prim.PhysShape, shapeCallback); - newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, prim.BaseShape, prim.Size, lod); + newShape = CreatePhysicalMesh(prim, newMeshKey, prim.BaseShape, prim.Size, lod); // Take evasive action if the mesh was not constructed. newShape = VerifyMeshCreated(newShape, prim); @@ -619,7 +619,7 @@ public sealed class BSShapeCollection : IDisposable return true; // 'true' means a new shape has been added to this prim } - private BulletShape CreatePhysicalMesh(string objName, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + private BulletShape CreatePhysicalMesh(BSPhysObject prim, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); @@ -631,7 +631,7 @@ public sealed class BSShapeCollection : IDisposable } else { - IMesh meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, + IMesh meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, false, // say it is not physical so a bounding box is not built false // do not cache the mesh and do not use previously built versions ); @@ -651,18 +651,20 @@ public sealed class BSShapeCollection : IDisposable realIndicesIndex = 0; for (int tri = 0; tri < indices.Length; tri += 3) { + // Compute displacements into vertex array for each vertex of the triangle int v1 = indices[tri + 0] * 3; int v2 = indices[tri + 1] * 3; int v3 = indices[tri + 2] * 3; - if (!((verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0] + // Check to see if any two of the vertices are the same + if (!( ( verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0] && verticesAsFloats[v1 + 1] == verticesAsFloats[v2 + 1] && verticesAsFloats[v1 + 2] == verticesAsFloats[v2 + 2]) - || (verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0] + || ( verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0] && verticesAsFloats[v2 + 1] == verticesAsFloats[v3 + 1] && verticesAsFloats[v2 + 2] == verticesAsFloats[v3 + 2]) - || (verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0] + || ( verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0] && verticesAsFloats[v1 + 1] == verticesAsFloats[v3 + 1] - && verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2])) + && verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2]) ) ) { // None of the vertices of the triangles are the same. This is a good triangle; @@ -676,8 +678,16 @@ public sealed class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.CreatePhysicalMesh,origTri={1},realTri={2},numVerts={3}", BSScene.DetailLogZero, indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3); - newShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, - realIndicesIndex, indices, verticesAsFloats.Length/3, verticesAsFloats); + if (realIndicesIndex != 0) + { + newShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, + realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats); + } + else + { + PhysicsScene.Logger.ErrorFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", + LogHeader, prim.PhysObjectName, prim.RawPosition, PhysicsScene.Name); + } } } newShape.shapeKey = newMeshKey; -- cgit v1.1 From d2ece00e68c070bf9ffbda3f76e4eccf3c33545f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 6 Feb 2013 15:59:59 -0800 Subject: BulletSim: set removing zero width triangles in meshes to be enabled by default. This should fix the invisible barrier in sculptie doorways bug. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 306928a..965c382 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -220,7 +220,7 @@ public static class BSParam (s) => { return BSParam.NumericBool(ShouldUseHullsForPhysicalObjects); }, (s,p,l,v) => { ShouldUseHullsForPhysicalObjects = BSParam.BoolNumeric(v); } ), new ParameterDefn("ShouldRemoveZeroWidthTriangles", "If true, remove degenerate triangles from meshes", - ConfigurationParameters.numericFalse, + ConfigurationParameters.numericTrue, (s,cf,p,v) => { ShouldRemoveZeroWidthTriangles = cf.GetBoolean(p, BSParam.BoolNumeric(v)); }, (s) => { return BSParam.NumericBool(ShouldRemoveZeroWidthTriangles); }, (s,p,l,v) => { ShouldRemoveZeroWidthTriangles = BSParam.BoolNumeric(v); } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 823402b..ec25aa9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -75,6 +75,7 @@ public abstract class BSPhysObject : PhysicsActor PhysicsScene = parentScene; LocalID = localID; PhysObjectName = name; + Name = name; // PhysicsActor also has the name of the object. Someday consolidate. TypeName = typeName; // We don't have any physical representation yet. -- cgit v1.1 From e2c1e37b077bad2d1b6d0ac5277c3f9001d819dd Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Thu, 7 Feb 2013 00:15:50 +0000 Subject: Add key length validation to DAMap.Add(KeyValuePair kvp) to match Add(string key, OSDMap store) --- OpenSim/Framework/DAMap.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/OpenSim/Framework/DAMap.cs b/OpenSim/Framework/DAMap.cs index 291c8b8..dd9c61b 100644 --- a/OpenSim/Framework/DAMap.cs +++ b/OpenSim/Framework/DAMap.cs @@ -188,7 +188,8 @@ namespace OpenSim.Framework } public void Add(KeyValuePair kvp) - { + { + ValidateKey(kvp.Key); lock (this) m_map.Add(kvp.Key, kvp.Value); } -- cgit v1.1 From c8c5d74c22056deb0b079d0651c005d610626f66 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Thu, 7 Feb 2013 00:22:39 +0000 Subject: minor: add method doc to DAMap.ValidateKey() --- OpenSim/Framework/DAMap.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/OpenSim/Framework/DAMap.cs b/OpenSim/Framework/DAMap.cs index dd9c61b..24e0895 100644 --- a/OpenSim/Framework/DAMap.cs +++ b/OpenSim/Framework/DAMap.cs @@ -168,6 +168,10 @@ namespace OpenSim.Framework } } + /// + /// Validate the key used for storing separate data stores. + /// + /// private static void ValidateKey(string key) { if (key.Length < MIN_STORE_NAME_LENGTH) -- cgit v1.1 From df37738ce7702774c4d3ff1f3835bfe87e0f1a5e Mon Sep 17 00:00:00 2001 From: Dan Lake Date: Wed, 6 Feb 2013 16:42:55 -0800 Subject: WebStats will now use actual logfile as specified in OpenSim.exe.config rather than hardcoded ./OpenSim.log. This allows for rotating logs and other file appender types --- OpenSim/Framework/Util.cs | 16 +++++++++++++++- OpenSim/Region/UserStatistics/WebStatsModule.cs | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs index 9b1e97d..d9148fb 100644 --- a/OpenSim/Framework/Util.cs +++ b/OpenSim/Framework/Util.cs @@ -45,6 +45,7 @@ using System.Text.RegularExpressions; using System.Xml; using System.Threading; using log4net; +using log4net.Appender; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; @@ -816,9 +817,22 @@ namespace OpenSim.Framework return "."; } + public static string logFile() + { + foreach (IAppender appender in LogManager.GetRepository().GetAppenders()) + { + if (appender is FileAppender) + { + return ((FileAppender)appender).File; + } + } + + return "./OpenSim.log"; + } + public static string logDir() { - return "."; + return Path.GetDirectoryName(logFile()); } // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html diff --git a/OpenSim/Region/UserStatistics/WebStatsModule.cs b/OpenSim/Region/UserStatistics/WebStatsModule.cs index 438ef48..b98b762 100644 --- a/OpenSim/Region/UserStatistics/WebStatsModule.cs +++ b/OpenSim/Region/UserStatistics/WebStatsModule.cs @@ -420,7 +420,7 @@ namespace OpenSim.Region.UserStatistics Encoding encoding = Encoding.ASCII; int sizeOfChar = encoding.GetByteCount("\n"); byte[] buffer = encoding.GetBytes("\n"); - string logfile = Util.logDir() + "/" + "OpenSim.log"; + string logfile = Util.logFile(); FileStream fs = new FileStream(logfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Int64 tokenCount = 0; Int64 endPosition = fs.Length / sizeOfChar; -- cgit v1.1 From 4d1758985f64fbdbfd142684c1a4ac82c9a4b97a Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Thu, 7 Feb 2013 00:54:09 +0000 Subject: Make json store tests operate on a single thread to ensure we don't run into any race related test failures in the future. --- .../JsonStore/Tests/JsonStoreScriptModuleTests.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs index 8042a93..34422b4 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs @@ -54,6 +54,22 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests private MockScriptEngine m_engine; private ScriptModuleCommsModule m_smcm; + [TestFixtureSetUp] + public void FixtureInit() + { + // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. + Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; + } + + [TestFixtureTearDown] + public void TearDown() + { + // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple + // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression + // tests really shouldn't). + Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; + } + [SetUp] public override void SetUp() { -- cgit v1.1 From 3657a08844731e5a24eeda3195c23f417b4570a5 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Thu, 7 Feb 2013 02:19:26 +0000 Subject: Add TestJsonWriteReadNotecard() regression test --- .../JsonStore/Tests/JsonStoreScriptModuleTests.cs | 45 +++++++++++++++++++++- OpenSim/Tests/Common/Mock/MockScriptEngine.cs | 2 +- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs index 34422b4..98b5624 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs @@ -101,7 +101,12 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests private object InvokeOp(string name, params object[] args) { - return m_smcm.InvokeOperation(UUID.Zero, UUID.Zero, name, args); + return InvokeOpOnHost(name, UUID.Zero, args); + } + + private object InvokeOpOnHost(string name, UUID hostId, params object[] args) + { + return m_smcm.InvokeOperation(hostId, UUID.Zero, name, args); } [Test] @@ -209,6 +214,44 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests Assert.That(value, Is.EqualTo("World")); } + /// + /// Test for reading and writing json to a notecard + /// + /// + /// TODO: Really needs to test correct receipt of the link_message event. Could do this by directly fetching + /// it via the MockScriptEngine or perhaps by a dummy script instance. + /// + [Test] + public void TestJsonWriteReadNotecard() + { + TestHelpers.InMethod(); + TestHelpers.EnableLogging(); + + string notecardName = "nc1"; + + SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1)); + m_scene.AddSceneObject(so); + + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); + + // Write notecard + UUID writeNotecardRequestId = (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, storeId, "/", notecardName); + Assert.That(writeNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); + + TaskInventoryItem nc1Item = so.RootPart.Inventory.GetInventoryItem(notecardName); + Assert.That(nc1Item, Is.Not.Null); + + // TODO: Should probably independently check the contents. + + // Read notecard + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); + UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "/", notecardName); + Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); + + string value = (string)InvokeOp("JsonGetValue", storeId, "Hello"); + Assert.That(value, Is.EqualTo("World")); + } + public object DummyTestMethod(object o1, object o2, object o3, object o4, object o5) { return null; } } } \ No newline at end of file diff --git a/OpenSim/Tests/Common/Mock/MockScriptEngine.cs b/OpenSim/Tests/Common/Mock/MockScriptEngine.cs index 51f2712..78bab5b 100644 --- a/OpenSim/Tests/Common/Mock/MockScriptEngine.cs +++ b/OpenSim/Tests/Common/Mock/MockScriptEngine.cs @@ -85,7 +85,7 @@ namespace OpenSim.Tests.Common public bool PostScriptEvent(UUID itemID, string name, object[] args) { - throw new System.NotImplementedException (); + return false; } public bool PostObjectEvent(UUID itemID, string name, object[] args) -- cgit v1.1 From 6504e3d4cee1573115e8a83c06227a297a32f093 Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 7 Feb 2013 03:30:02 +0000 Subject: Rename "Bounciness" to "Restitution" --- OpenSim/Data/MySQL/MySQLSimulationData.cs | 4 ++-- OpenSim/Region/Framework/Scenes/SceneObjectPart.cs | 6 +++--- .../Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs | 6 +++--- OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OpenSim/Data/MySQL/MySQLSimulationData.cs b/OpenSim/Data/MySQL/MySQLSimulationData.cs index 41174f4..1b02b4f 100644 --- a/OpenSim/Data/MySQL/MySQLSimulationData.cs +++ b/OpenSim/Data/MySQL/MySQLSimulationData.cs @@ -1311,7 +1311,7 @@ namespace OpenSim.Data.MySQL prim.Density = (float)(double)row["Density"]; prim.GravityModifier = (float)(double)row["GravityModifier"]; prim.Friction = (float)(double)row["Friction"]; - prim.Bounciness = (float)(double)row["Restitution"]; + prim.Restitution = (float)(double)row["Restitution"]; return prim; } @@ -1663,7 +1663,7 @@ namespace OpenSim.Data.MySQL cmd.Parameters.AddWithValue("Density", (double)prim.Density); cmd.Parameters.AddWithValue("GravityModifier", (double)prim.GravityModifier); cmd.Parameters.AddWithValue("Friction", (double)prim.Friction); - cmd.Parameters.AddWithValue("Restitution", (double)prim.Bounciness); + cmd.Parameters.AddWithValue("Restitution", (double)prim.Restitution); if (prim.DynAttrs.Count > 0) cmd.Parameters.AddWithValue("DynAttrs", prim.DynAttrs.ToXml()); diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index 55b5462..b00f388 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -1390,7 +1390,7 @@ namespace OpenSim.Region.Framework.Scenes public float Density { get; set; } public float GravityModifier { get; set; } public float Friction { get; set; } - public float Bounciness { get; set; } + public float Restitution { get; set; } #endregion Public Properties with only Get @@ -3964,8 +3964,8 @@ namespace OpenSim.Region.Framework.Scenes GravityModifier = physdata.GravitationModifier; if(Friction != physdata.Friction) Friction = physdata.Friction; - if(Bounciness != physdata.Bounce) - Bounciness = physdata.Bounce; + if(Restitution != physdata.Bounce) + Restitution = physdata.Bounce; } /// /// Update the flags on this prim. This covers properties such as phantom, physics and temporary. diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs index 78229fe..39420a6 100644 --- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs +++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs @@ -618,7 +618,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization private static void ProcessBounce(SceneObjectPart obj, XmlTextReader reader) { - obj.Bounciness = reader.ReadElementContentAsFloat("Bounce", String.Empty); + obj.Restitution = reader.ReadElementContentAsFloat("Bounce", String.Empty); } private static void ProcessGravityModifier(SceneObjectPart obj, XmlTextReader reader) @@ -1295,8 +1295,8 @@ namespace OpenSim.Region.Framework.Scenes.Serialization writer.WriteElementString("Density", sop.Density.ToString().ToLower()); if (sop.Friction != 0.6f) writer.WriteElementString("Friction", sop.Friction.ToString().ToLower()); - if (sop.Bounciness != 0.5f) - writer.WriteElementString("Bounce", sop.Bounciness.ToString().ToLower()); + if (sop.Restitution != 0.5f) + writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower()); if (sop.GravityModifier != 1.0f) writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower()); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 64052ae..be6ac0a 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -7602,7 +7602,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api ExtraPhysicsData physdata = new ExtraPhysicsData(); physdata.Density = part.Density; - physdata.Bounce = part.Bounciness; + physdata.Bounce = part.Restitution; physdata.GravitationModifier = part.GravityModifier; physdata.PhysShapeType = (PhysShapeType)shape_type; -- cgit v1.1 From 4867a7cbbf7302845fff031db5eae6fbf93bf26b Mon Sep 17 00:00:00 2001 From: teravus Date: Thu, 7 Feb 2013 10:26:48 -0500 Subject: This is the final commit that enables the Websocket handler --- .../Framework/Servers/HttpServer/BaseHttpServer.cs | 12 +- .../Servers/HttpServer/WebsocketServerHandler.cs | 1085 ++++++++++++++++++++ bin/HttpServer_OpenSim.dll | Bin 116224 -> 116224 bytes bin/HttpServer_OpenSim.pdb | Bin 302592 -> 343552 bytes 4 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 OpenSim/Framework/Servers/HttpServer/WebsocketServerHandler.cs diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs index dcfe99a..70c531c 100644 --- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs +++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs @@ -54,7 +54,15 @@ namespace OpenSim.Framework.Servers.HttpServer private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HttpServerLogWriter httpserverlog = new HttpServerLogWriter(); - public delegate void WebSocketRequestDelegate(string servicepath, WebSocketHTTPServerHandler handler); + + /// + /// This is a pending websocket request before it got an sucessful upgrade response. + /// The consumer must call handler.HandshakeAndUpgrade() to signal to the handler to + /// start the connection and optionally provide an origin authentication method. + /// + /// + /// + public delegate void WebSocketRequestDelegate(string servicepath, WebSocketHttpServerHandler handler); /// /// Gets or sets the debug level. @@ -440,7 +448,7 @@ namespace OpenSim.Framework.Servers.HttpServer } if (dWebSocketRequestDelegate != null) { - dWebSocketRequestDelegate(req.Url.AbsolutePath, new WebSocketHTTPServerHandler(req, context, 16384)); + dWebSocketRequestDelegate(req.Url.AbsolutePath, new WebSocketHttpServerHandler(req, context, 8192)); return; } diff --git a/OpenSim/Framework/Servers/HttpServer/WebsocketServerHandler.cs b/OpenSim/Framework/Servers/HttpServer/WebsocketServerHandler.cs new file mode 100644 index 0000000..cfb1605 --- /dev/null +++ b/OpenSim/Framework/Servers/HttpServer/WebsocketServerHandler.cs @@ -0,0 +1,1085 @@ +/* + * 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.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using HttpServer; + +namespace OpenSim.Framework.Servers.HttpServer +{ + // Sealed class. If you're going to unseal it, implement IDisposable. + /// + /// This class implements websockets. It grabs the network context from C#Webserver and utilizes it directly as a tcp streaming service + /// + public sealed class WebSocketHttpServerHandler : BaseRequestHandler + { + + private class WebSocketState + { + public List ReceivedBytes; + public int ExpectedBytes; + public WebsocketFrameHeader Header; + public bool FrameComplete; + public WebSocketFrame ContinuationFrame; + } + + /// + /// Binary Data will trigger this event + /// + public event DataDelegate OnData; + + /// + /// Textual Data will trigger this event + /// + public event TextDelegate OnText; + + /// + /// A ping request form the other side will trigger this event. + /// This class responds to the ping automatically. You shouldn't send a pong. + /// it's informational. + /// + public event PingDelegate OnPing; + + /// + /// This is a response to a ping you sent. + /// + public event PongDelegate OnPong; + + /// + /// This is a regular HTTP Request... This may be removed in the future. + /// + public event RegularHttpRequestDelegate OnRegularHttpRequest; + + /// + /// When the upgrade from a HTTP request to a Websocket is completed, this will be fired + /// + public event UpgradeCompletedDelegate OnUpgradeCompleted; + + /// + /// If the upgrade failed, this will be fired + /// + public event UpgradeFailedDelegate OnUpgradeFailed; + + /// + /// When the websocket is closed, this will be fired. + /// + public event CloseDelegate OnClose; + + /// + /// Set this delegate to allow your module to validate the origin of the + /// Websocket request. Primary line of defense against cross site scripting + /// + public ValidateHandshake HandshakeValidateMethodOverride = null; + + private OSHttpRequest _request; + private HTTPNetworkContext _networkContext; + private IHttpClientContext _clientContext; + + private int _pingtime = 0; + private byte[] _buffer; + private int _bufferPosition; + private int _bufferLength; + private bool _closing; + private bool _upgraded; + + private const string HandshakeAcceptText = + "HTTP/1.1 101 Switching Protocols\r\n" + + "upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "sec-websocket-accept: {0}\r\n\r\n";// + + //"{1}"; + + private const string HandshakeDeclineText = + "HTTP/1.1 {0} {1}\r\n" + + "Connection: close\r\n\r\n"; + + /// + /// Mysterious constant defined in RFC6455 to append to the client provided security key + /// + private const string WebsocketHandshakeAcceptHashConstant = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + + public WebSocketHttpServerHandler(OSHttpRequest preq, IHttpClientContext pContext, int bufferlen) + : base(preq.HttpMethod, preq.Url.OriginalString) + { + _request = preq; + _networkContext = pContext.GiveMeTheNetworkStreamIKnowWhatImDoing(); + _clientContext = pContext; + _bufferLength = bufferlen; + _buffer = new byte[_bufferLength]; + } + + // Sealed class implments destructor and an internal dispose method. complies with C# unmanaged resource best practices. + ~WebSocketHttpServerHandler() + { + Dispose(); + + } + + /// + /// Sets the length of the stream buffer + /// + /// Byte length. + public void SetChunksize(int pChunk) + { + if (!_upgraded) + { + _buffer = new byte[pChunk]; + } + else + { + throw new InvalidOperationException("You must set the chunksize before the connection is upgraded"); + } + } + + /// + /// This is the famous nagle. + /// + public bool NoDelay_TCP_Nagle + { + get + { + if (_networkContext != null && _networkContext.Socket != null) + { + return _networkContext.Socket.NoDelay; + } + else + { + throw new InvalidOperationException("The socket has been shutdown"); + } + } + set + { + if (_networkContext != null && _networkContext.Socket != null) + _networkContext.Socket.NoDelay = value; + else + { + throw new InvalidOperationException("The socket has been shutdown"); + } + } + } + + /// + /// This triggers the websocket to start the upgrade process... + /// This is a Generalized Networking 'common sense' helper method. Some people expect to call Start() instead + /// of the more context appropriate HandshakeAndUpgrade() + /// + public void Start() + { + HandshakeAndUpgrade(); + } + + /// + /// This triggers the websocket start the upgrade process + /// + public void HandshakeAndUpgrade() + { + string webOrigin = string.Empty; + string websocketKey = string.Empty; + string acceptKey = string.Empty; + string accepthost = string.Empty; + if (!string.IsNullOrEmpty(_request.Headers["origin"])) + webOrigin = _request.Headers["origin"]; + + if (!string.IsNullOrEmpty(_request.Headers["sec-websocket-key"])) + websocketKey = _request.Headers["sec-websocket-key"]; + + if (!string.IsNullOrEmpty(_request.Headers["host"])) + accepthost = _request.Headers["host"]; + + if (string.IsNullOrEmpty(_request.Headers["upgrade"])) + { + FailUpgrade(OSHttpStatusCode.ClientErrorBadRequest, "no upgrade request submitted"); + } + + string connectionheader = _request.Headers["upgrade"]; + if (connectionheader.ToLower() != "websocket") + { + FailUpgrade(OSHttpStatusCode.ClientErrorBadRequest, "no connection upgrade request submitted"); + } + + // If the object consumer provided a method to validate the origin, we should call it and give the client a success or fail. + // If not.. we should accept any. The assumption here is that there would be no Websocket handlers registered in baseHTTPServer unless + // Something asked for it... + if (HandshakeValidateMethodOverride != null) + { + if (HandshakeValidateMethodOverride(webOrigin, websocketKey, accepthost)) + { + acceptKey = GenerateAcceptKey(websocketKey); + string rawaccept = string.Format(HandshakeAcceptText, acceptKey); + SendUpgradeSuccess(rawaccept); + + } + else + { + FailUpgrade(OSHttpStatusCode.ClientErrorForbidden, "Origin Validation Failed"); + } + } + else + { + acceptKey = GenerateAcceptKey(websocketKey); + string rawaccept = string.Format(HandshakeAcceptText, acceptKey); + SendUpgradeSuccess(rawaccept); + } + } + + /// + /// Generates a handshake response key string based on the client's + /// provided key to prove to the client that we're allowing the Websocket + /// upgrade of our own free will and we were not coerced into doing it. + /// + /// Client provided security key + /// + private static string GenerateAcceptKey(string key) + { + if (string.IsNullOrEmpty(key)) + return string.Empty; + + string acceptkey = key + WebsocketHandshakeAcceptHashConstant; + + SHA1 hashobj = SHA1.Create(); + string ret = Convert.ToBase64String(hashobj.ComputeHash(Encoding.UTF8.GetBytes(acceptkey))); + hashobj.Clear(); + + return ret; + } + + /// + /// Informs the otherside that we accepted their upgrade request + /// + /// The HTTP 1.1 101 response that says Yay \o/ + private void SendUpgradeSuccess(string pHandshakeResponse) + { + // Create a new websocket state so we can keep track of data in between network reads. + WebSocketState socketState = new WebSocketState() { ReceivedBytes = new List(), Header = WebsocketFrameHeader.HeaderDefault(), FrameComplete = true}; + + byte[] bhandshakeResponse = Encoding.UTF8.GetBytes(pHandshakeResponse); + try + { + + // Begin reading the TCP stream before writing the Upgrade success message to the other side of the stream. + _networkContext.Stream.BeginRead(_buffer, 0, _bufferLength, OnReceive, socketState); + + // Write the upgrade handshake success message + _networkContext.Stream.Write(bhandshakeResponse, 0, bhandshakeResponse.Length); + _networkContext.Stream.Flush(); + _upgraded = true; + UpgradeCompletedDelegate d = OnUpgradeCompleted; + if (d != null) + d(this, new UpgradeCompletedEventArgs()); + } + catch (IOException fail) + { + Close(string.Empty); + } + catch (ObjectDisposedException fail) + { + Close(string.Empty); + } + + } + + /// + /// The server has decided not to allow the upgrade to a websocket for some reason. The Http 1.1 response that says Nay >:( + /// + /// HTTP Status reflecting the reason why + /// Textual reason for the upgrade fail + private void FailUpgrade(OSHttpStatusCode pCode, string pMessage ) + { + string handshakeResponse = string.Format(HandshakeDeclineText, (int)pCode, pMessage.Replace("\n", string.Empty).Replace("\r", string.Empty)); + byte[] bhandshakeResponse = Encoding.UTF8.GetBytes(handshakeResponse); + _networkContext.Stream.Write(bhandshakeResponse, 0, bhandshakeResponse.Length); + _networkContext.Stream.Flush(); + _networkContext.Stream.Dispose(); + + UpgradeFailedDelegate d = OnUpgradeFailed; + if (d != null) + d(this,new UpgradeFailedEventArgs()); + } + + + /// + /// This is our ugly Async OnReceive event handler. + /// This chunks the input stream based on the length of the provided buffer and processes out + /// as many frames as it can. It then moves the unprocessed data to the beginning of the buffer. + /// + /// Our Async State from beginread + private void OnReceive(IAsyncResult ar) + { + WebSocketState _socketState = ar.AsyncState as WebSocketState; + try + { + int bytesRead = _networkContext.Stream.EndRead(ar); + if (bytesRead == 0) + { + // Do Disconnect + _networkContext.Stream.Dispose(); + _networkContext = null; + return; + } + _bufferPosition += bytesRead; + + if (_bufferPosition > _bufferLength) + { + // Message too big for chunksize.. not sure how this happened... + //Close(string.Empty); + } + + int offset = 0; + bool headerread = true; + int headerforwardposition = 0; + while (headerread && offset < bytesRead) + { + if (_socketState.FrameComplete) + { + WebsocketFrameHeader pheader = WebsocketFrameHeader.ZeroHeader; + + headerread = WebSocketReader.TryReadHeader(_buffer, offset, _bufferPosition - offset, out pheader, + out headerforwardposition); + offset += headerforwardposition; + + if (headerread) + { + _socketState.FrameComplete = false; + + if (pheader.PayloadLen > 0) + { + if ((int) pheader.PayloadLen > _bufferPosition - offset) + { + byte[] writebytes = new byte[_bufferPosition - offset]; + + Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition - offset); + _socketState.ExpectedBytes = (int) pheader.PayloadLen; + _socketState.ReceivedBytes.AddRange(writebytes); + _socketState.Header = pheader; // We need to add the header so that we can unmask it + offset += (int) _bufferPosition - offset; + } + else + { + byte[] writebytes = new byte[pheader.PayloadLen]; + Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) pheader.PayloadLen); + WebSocketReader.Mask(pheader.Mask, writebytes); + pheader.IsMasked = false; + _socketState.FrameComplete = true; + _socketState.ReceivedBytes.AddRange(writebytes); + _socketState.Header = pheader; + offset += (int) pheader.PayloadLen; + } + } + else + { + pheader.Mask = 0; + _socketState.FrameComplete = true; + _socketState.Header = pheader; + } + + + + if (_socketState.FrameComplete) + { + ProcessFrame(_socketState); + _socketState.Header.SetDefault(); + _socketState.ReceivedBytes.Clear(); + _socketState.ExpectedBytes = 0; + + } + + } + } + else + { + WebsocketFrameHeader frameHeader = _socketState.Header; + int bytesleft = _socketState.ExpectedBytes - _socketState.ReceivedBytes.Count; + + if (bytesleft > _bufferPosition) + { + byte[] writebytes = new byte[_bufferPosition]; + + Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition); + _socketState.ReceivedBytes.AddRange(writebytes); + _socketState.Header = frameHeader; // We need to add the header so that we can unmask it + offset += (int) _bufferPosition; + } + else + { + byte[] writebytes = new byte[_bufferPosition]; + Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition); + _socketState.FrameComplete = true; + _socketState.ReceivedBytes.AddRange(writebytes); + _socketState.Header = frameHeader; + offset += (int) _bufferPosition; + } + if (_socketState.FrameComplete) + { + ProcessFrame(_socketState); + _socketState.Header.SetDefault(); + _socketState.ReceivedBytes.Clear(); + _socketState.ExpectedBytes = 0; + // do some processing + } + + } + } + if (offset > 0) + { + // If the buffer is maxed out.. we can just move the cursor. Nothing to move to the beginning. + if (offset <_buffer.Length) + Buffer.BlockCopy(_buffer, offset, _buffer, 0, _bufferPosition - offset); + _bufferPosition -= offset; + } + if (_networkContext.Stream != null && _networkContext.Stream.CanRead && !_closing) + { + _networkContext.Stream.BeginRead(_buffer, _bufferPosition, _bufferLength - _bufferPosition, OnReceive, + _socketState); + } + else + { + // We can't read the stream anymore... + } + + } + catch (IOException fail) + { + Close(string.Empty); + } + catch (ObjectDisposedException fail) + { + Close(string.Empty); + } + } + + /// + /// Sends a string to the other side + /// + /// the string message that is to be sent + public void SendMessage(string message) + { + byte[] messagedata = Encoding.UTF8.GetBytes(message); + WebSocketFrame textMessageFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = messagedata }; + textMessageFrame.Header.Opcode = WebSocketReader.OpCode.Text; + textMessageFrame.Header.IsEnd = true; + SendSocket(textMessageFrame.ToBytes()); + + } + + public void SendData(byte[] data) + { + WebSocketFrame dataMessageFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = data}; + dataMessageFrame.Header.IsEnd = true; + dataMessageFrame.Header.Opcode = WebSocketReader.OpCode.Binary; + SendSocket(dataMessageFrame.ToBytes()); + + } + + /// + /// Writes raw bytes to the websocket. Unframed data will cause disconnection + /// + /// + private void SendSocket(byte[] data) + { + if (!_closing) + { + try + { + + _networkContext.Stream.Write(data, 0, data.Length); + } + catch (IOException) + { + + } + } + } + + /// + /// Sends a Ping check to the other side. The other side SHOULD respond as soon as possible with a pong frame. This interleaves with incoming fragmented frames. + /// + public void SendPingCheck() + { + WebSocketFrame pingFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = new byte[0] }; + pingFrame.Header.Opcode = WebSocketReader.OpCode.Ping; + pingFrame.Header.IsEnd = true; + _pingtime = Util.EnvironmentTickCount(); + SendSocket(pingFrame.ToBytes()); + } + + /// + /// Closes the websocket connection. Sends a close message to the other side if it hasn't already done so. + /// + /// + public void Close(string message) + { + if (_networkContext.Stream != null) + { + if (_networkContext.Stream.CanWrite) + { + byte[] messagedata = Encoding.UTF8.GetBytes(message); + WebSocketFrame closeResponseFrame = new WebSocketFrame() + { + Header = WebsocketFrameHeader.HeaderDefault(), + WebSocketPayload = messagedata + }; + closeResponseFrame.Header.Opcode = WebSocketReader.OpCode.Close; + closeResponseFrame.Header.PayloadLen = (ulong) messagedata.Length; + closeResponseFrame.Header.IsEnd = true; + SendSocket(closeResponseFrame.ToBytes()); + } + } + CloseDelegate closeD = OnClose; + if (closeD != null) + { + closeD(this, new CloseEventArgs()); + } + + _closing = true; + } + + /// + /// Processes a websocket frame and triggers consumer events + /// + /// We need to modify the websocket state here depending on the frame + private void ProcessFrame(WebSocketState psocketState) + { + if (psocketState.Header.IsMasked) + { + byte[] unmask = psocketState.ReceivedBytes.ToArray(); + WebSocketReader.Mask(psocketState.Header.Mask, unmask); + psocketState.ReceivedBytes = new List(unmask); + } + + switch (psocketState.Header.Opcode) + { + case WebSocketReader.OpCode.Ping: + PingDelegate pingD = OnPing; + if (pingD != null) + { + pingD(this, new PingEventArgs()); + } + + WebSocketFrame pongFrame = new WebSocketFrame(){Header = WebsocketFrameHeader.HeaderDefault(),WebSocketPayload = new byte[0]}; + pongFrame.Header.Opcode = WebSocketReader.OpCode.Pong; + pongFrame.Header.IsEnd = true; + SendSocket(pongFrame.ToBytes()); + break; + case WebSocketReader.OpCode.Pong: + + PongDelegate pongD = OnPong; + if (pongD != null) + { + pongD(this, new PongEventArgs(){PingResponseMS = Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(),_pingtime)}); + } + break; + case WebSocketReader.OpCode.Binary: + if (!psocketState.Header.IsEnd) // Not done, so we need to store this and wait for the end frame. + { + psocketState.ContinuationFrame = new WebSocketFrame + { + Header = psocketState.Header, + WebSocketPayload = + psocketState.ReceivedBytes.ToArray() + }; + } + else + { + // Send Done Event! + DataDelegate dataD = OnData; + if (dataD != null) + { + dataD(this,new WebsocketDataEventArgs(){Data = psocketState.ReceivedBytes.ToArray()}); + } + } + break; + case WebSocketReader.OpCode.Text: + if (!psocketState.Header.IsEnd) // Not done, so we need to store this and wait for the end frame. + { + psocketState.ContinuationFrame = new WebSocketFrame + { + Header = psocketState.Header, + WebSocketPayload = + psocketState.ReceivedBytes.ToArray() + }; + } + else + { + TextDelegate textD = OnText; + if (textD != null) + { + textD(this, new WebsocketTextEventArgs() { Data = Encoding.UTF8.GetString(psocketState.ReceivedBytes.ToArray()) }); + } + + // Send Done Event! + } + break; + case WebSocketReader.OpCode.Continue: // Continuation. Multiple frames worth of data for one message. Only valid when not using Control Opcodes + //Console.WriteLine("currhead " + psocketState.Header.IsEnd); + //Console.WriteLine("Continuation! " + psocketState.ContinuationFrame.Header.IsEnd); + byte[] combineddata = new byte[psocketState.ReceivedBytes.Count+psocketState.ContinuationFrame.WebSocketPayload.Length]; + byte[] newdata = psocketState.ReceivedBytes.ToArray(); + Buffer.BlockCopy(psocketState.ContinuationFrame.WebSocketPayload, 0, combineddata, 0, psocketState.ContinuationFrame.WebSocketPayload.Length); + Buffer.BlockCopy(newdata, 0, combineddata, + psocketState.ContinuationFrame.WebSocketPayload.Length, newdata.Length); + psocketState.ContinuationFrame.WebSocketPayload = combineddata; + psocketState.Header.PayloadLen = (ulong)combineddata.Length; + if (psocketState.Header.IsEnd) + { + if (psocketState.ContinuationFrame.Header.Opcode == WebSocketReader.OpCode.Text) + { + // Send Done event + TextDelegate textD = OnText; + if (textD != null) + { + textD(this, new WebsocketTextEventArgs() { Data = Encoding.UTF8.GetString(combineddata) }); + } + } + else if (psocketState.ContinuationFrame.Header.Opcode == WebSocketReader.OpCode.Binary) + { + // Send Done event + DataDelegate dataD = OnData; + if (dataD != null) + { + dataD(this, new WebsocketDataEventArgs() { Data = combineddata }); + } + } + else + { + // protocol violation + } + psocketState.ContinuationFrame = null; + } + break; + case WebSocketReader.OpCode.Close: + Close(string.Empty); + + break; + + } + psocketState.Header.SetDefault(); + psocketState.ReceivedBytes.Clear(); + psocketState.ExpectedBytes = 0; + } + public void Dispose() + { + if (_networkContext != null && _networkContext.Stream != null) + { + if (_networkContext.Stream.CanWrite) + _networkContext.Stream.Flush(); + _networkContext.Stream.Close(); + _networkContext.Stream.Dispose(); + _networkContext.Stream = null; + } + + if (_request != null && _request.InputStream != null) + { + _request.InputStream.Close(); + _request.InputStream.Dispose(); + _request = null; + } + + if (_clientContext != null) + { + _clientContext.Close(); + _clientContext = null; + } + } + } + + /// + /// Reads a byte stream and returns Websocket frames. + /// + public class WebSocketReader + { + /// + /// Bit to determine if the frame read on the stream is the last frame in a sequence of fragmented frames + /// + private const byte EndBit = 0x80; + + /// + /// These are the Frame Opcodes + /// + public enum OpCode + { + // Data Opcodes + Continue = 0x0, + Text = 0x1, + Binary = 0x2, + + // Control flow Opcodes + Close = 0x8, + Ping = 0x9, + Pong = 0xA + } + + /// + /// Masks and Unmasks data using the frame mask. Mask is applied per octal + /// Note: Frames from clients MUST be masked + /// Note: Frames from servers MUST NOT be masked + /// + /// Int representing 32 bytes of mask data. Mask is applied per octal + /// + public static void Mask(int pMask, byte[] pBuffer) + { + byte[] maskKey = BitConverter.GetBytes(pMask); + int currentMaskIndex = 0; + for (int i = 0; i < pBuffer.Length; i++) + { + pBuffer[i] = (byte)(pBuffer[i] ^ maskKey[currentMaskIndex]); + if (currentMaskIndex == 3) + { + currentMaskIndex = 0; + } + else + { + currentMaskIndex++; + + } + + } + } + + /// + /// Attempts to read a header off the provided buffer. Returns true, exports a WebSocketFrameheader, + /// and an int to move the buffer forward when it reads a header. False when it can't read a header + /// + /// Bytes read from the stream + /// Starting place in the stream to begin trying to read from + /// Lenth in the stream to try and read from. Provided for cases where the + /// buffer's length is larger then the data in it + /// Outputs the read WebSocket frame header + /// Informs the calling stream to move the buffer forward + /// True if it got a header, False if it didn't get a header + public static bool TryReadHeader(byte[] pBuffer, int pOffset, int length, out WebsocketFrameHeader oHeader, + out int moveBuffer) + { + oHeader = WebsocketFrameHeader.ZeroHeader; + int minumheadersize = 2; + if (length > pBuffer.Length - pOffset) + throw new ArgumentOutOfRangeException("The Length specified was larger the byte array supplied"); + if (length < minumheadersize) + { + moveBuffer = 0; + return false; + } + + byte nibble1 = (byte)(pBuffer[pOffset] & 0xF0); //FIN/RSV1/RSV2/RSV3 + byte nibble2 = (byte)(pBuffer[pOffset] & 0x0F); // Opcode block + + oHeader = new WebsocketFrameHeader(); + oHeader.SetDefault(); + + if ((nibble1 & WebSocketReader.EndBit) == WebSocketReader.EndBit) + { + oHeader.IsEnd = true; + } + else + { + oHeader.IsEnd = false; + } + //Opcode + oHeader.Opcode = (WebSocketReader.OpCode)nibble2; + //Mask + oHeader.IsMasked = Convert.ToBoolean((pBuffer[pOffset + 1] & 0x80) >> 7); + + // Payload length + oHeader.PayloadLen = (byte)(pBuffer[pOffset + 1] & 0x7F); + + int index = 2; // LargerPayload length starts at byte 3 + + switch (oHeader.PayloadLen) + { + case 126: + minumheadersize += 2; + if (length < minumheadersize) + { + moveBuffer = 0; + return false; + } + Array.Reverse(pBuffer, pOffset + index, 2); // two bytes + oHeader.PayloadLen = BitConverter.ToUInt16(pBuffer, pOffset + index); + index += 2; + break; + case 127: // we got more this is a bigger frame + // 8 bytes - uint64 - most significant bit 0 network byte order + minumheadersize += 8; + if (length < minumheadersize) + { + moveBuffer = 0; + return false; + } + Array.Reverse(pBuffer, pOffset + index, 8); + oHeader.PayloadLen = BitConverter.ToUInt64(pBuffer, pOffset + index); + index += 8; + break; + + } + //oHeader.PayloadLeft = oHeader.PayloadLen; // Start the count in case it's chunked over the network. This is different then frame fragmentation + if (oHeader.IsMasked) + { + minumheadersize += 4; + if (length < minumheadersize) + { + moveBuffer = 0; + return false; + } + oHeader.Mask = BitConverter.ToInt32(pBuffer, pOffset + index); + index += 4; + } + moveBuffer = index; + return true; + + } + } + + /// + /// RFC6455 Websocket Frame + /// + public class WebSocketFrame + { + /* + * RFC6455 +nib 0 1 2 3 4 5 6 7 +byt 0 1 2 3 +dec 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) + + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | + + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ + + * When reading these, the frames are possibly fragmented and interleaved with control frames + * the fragmented frames are not interleaved with data frames. Just control frames + */ + public static readonly WebSocketFrame DefaultFrame = new WebSocketFrame(){Header = new WebsocketFrameHeader(),WebSocketPayload = new byte[0]}; + public WebsocketFrameHeader Header; + public byte[] WebSocketPayload; + + public byte[] ToBytes() + { + Header.PayloadLen = (ulong)WebSocketPayload.Length; + return Header.ToBytes(WebSocketPayload); + } + + } + + public struct WebsocketFrameHeader + { + //public byte CurrentMaskIndex; + /// + /// The last frame in a sequence of fragmented frames or the one and only frame for this message. + /// + public bool IsEnd; + + /// + /// Returns whether the payload data is masked or not. Data from Clients MUST be masked, Data from Servers MUST NOT be masked + /// + public bool IsMasked; + + /// + /// A set of cryptologically sound random bytes XoR-ed against the payload octally. Looped + /// + public int Mask; + /* +byt 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +---------------+---------------+---------------+---------------+ + | Octal 1 | Octal 2 | Octal 3 | Octal 4 | + +---------------+---------------+---------------+---------------+ +*/ + + + public WebSocketReader.OpCode Opcode; + + public UInt64 PayloadLen; + //public UInt64 PayloadLeft; + // Payload is X + Y + //public UInt64 ExtensionDataLength; + //public UInt64 ApplicationDataLength; + public static readonly WebsocketFrameHeader ZeroHeader = WebsocketFrameHeader.HeaderDefault(); + + public void SetDefault() + { + + //CurrentMaskIndex = 0; + IsEnd = true; + IsMasked = true; + Mask = 0; + Opcode = WebSocketReader.OpCode.Close; + // PayloadLeft = 0; + PayloadLen = 0; + // ExtensionDataLength = 0; + // ApplicationDataLength = 0; + + } + + /// + /// Returns a byte array representing the Frame header + /// + /// This is the frame data payload. The header describes the size of the payload. + /// If payload is null, a Zero sized payload is assumed + /// Returns a byte array representing the frame header + public byte[] ToBytes(byte[] payload) + { + List result = new List(); + + // Squeeze in our opcode and our ending bit. + result.Add((byte)((byte)Opcode | (IsEnd?0x80:0x00) )); + + // Again with the three different byte interpretations of size.. + + //bytesize + if (PayloadLen <= 125) + { + result.Add((byte) PayloadLen); + } //Uint16 + else if (PayloadLen <= ushort.MaxValue) + { + result.Add(126); + byte[] payloadLengthByte = BitConverter.GetBytes(Convert.ToUInt16(PayloadLen)); + Array.Reverse(payloadLengthByte); + result.AddRange(payloadLengthByte); + } //UInt64 + else + { + result.Add(127); + byte[] payloadLengthByte = BitConverter.GetBytes(PayloadLen); + Array.Reverse(payloadLengthByte); + result.AddRange(payloadLengthByte); + } + + // Only add a payload if it's not null + if (payload != null) + { + result.AddRange(payload); + } + return result.ToArray(); + } + + /// + /// A Helper method to define the defaults + /// + /// + + public static WebsocketFrameHeader HeaderDefault() + { + return new WebsocketFrameHeader + { + //CurrentMaskIndex = 0, + IsEnd = false, + IsMasked = true, + Mask = 0, + Opcode = WebSocketReader.OpCode.Close, + //PayloadLeft = 0, + PayloadLen = 0, + // ExtensionDataLength = 0, + // ApplicationDataLength = 0 + }; + } + } + + public delegate void DataDelegate(object sender, WebsocketDataEventArgs data); + + public delegate void TextDelegate(object sender, WebsocketTextEventArgs text); + + public delegate void PingDelegate(object sender, PingEventArgs pingdata); + + public delegate void PongDelegate(object sender, PongEventArgs pongdata); + + public delegate void RegularHttpRequestDelegate(object sender, RegularHttpRequestEvnetArgs request); + + public delegate void UpgradeCompletedDelegate(object sender, UpgradeCompletedEventArgs completeddata); + + public delegate void UpgradeFailedDelegate(object sender, UpgradeFailedEventArgs faileddata); + + public delegate void CloseDelegate(object sender, CloseEventArgs closedata); + + public delegate bool ValidateHandshake(string pWebOrigin, string pWebSocketKey, string pHost); + + + public class WebsocketDataEventArgs : EventArgs + { + public byte[] Data; + } + + public class WebsocketTextEventArgs : EventArgs + { + public string Data; + } + + public class PingEventArgs : EventArgs + { + /// + /// The ping event can arbitrarily contain data + /// + public byte[] Data; + } + + public class PongEventArgs : EventArgs + { + /// + /// The pong event can arbitrarily contain data + /// + public byte[] Data; + + public int PingResponseMS; + + } + + public class RegularHttpRequestEvnetArgs : EventArgs + { + + } + + public class UpgradeCompletedEventArgs : EventArgs + { + + } + + public class UpgradeFailedEventArgs : EventArgs + { + + } + + public class CloseEventArgs : EventArgs + { + + } + + +} diff --git a/bin/HttpServer_OpenSim.dll b/bin/HttpServer_OpenSim.dll index 9cd1e08..fd7ad74 100755 Binary files a/bin/HttpServer_OpenSim.dll and b/bin/HttpServer_OpenSim.dll differ diff --git a/bin/HttpServer_OpenSim.pdb b/bin/HttpServer_OpenSim.pdb index d20a0c5..f56e891 100644 Binary files a/bin/HttpServer_OpenSim.pdb and b/bin/HttpServer_OpenSim.pdb differ -- cgit v1.1 From 4bd1794b5a05147788950208f9644c2b9d731859 Mon Sep 17 00:00:00 2001 From: teravus Date: Thu, 7 Feb 2013 12:19:54 -0500 Subject: * missing example module.. Oops. --- .../WebSocketEchoTest/WebSocketEchoModule.cs | 174 +++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs diff --git a/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs new file mode 100644 index 0000000..34e20b7 --- /dev/null +++ b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs @@ -0,0 +1,174 @@ +/* + * 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.Generic; +using System.Reflection; +using OpenSim.Framework.Servers; +using Mono.Addins; +using log4net; +using Nini.Config; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +using OpenSim.Framework.Servers.HttpServer; + + +namespace OpenSim.Region.OptionalModules.WebSocketEchoModule +{ + + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebSocketEchoModule")] + public class WebSocketEchoModule : ISharedRegionModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private bool enabled; + public string Name { get { return "WebSocketEchoModule"; } } + + public Type ReplaceableInterface { get { return null; } } + + + private HashSet _activeHandlers = new HashSet(); + + public void Initialise(IConfigSource pConfig) + { + enabled = true;// (pConfig.Configs["WebSocketEcho"] != null); + if (enabled) + m_log.DebugFormat("[WebSocketEchoModule]: INITIALIZED MODULE"); + } + + /// + /// This method sets up the callback to WebSocketHandlerCallback below when a HTTPRequest comes in for /echo + /// + public void PostInitialise() + { + if (enabled) + MainServer.Instance.AddWebSocketHandler("/echo", WebSocketHandlerCallback); + } + + // This gets called by BaseHttpServer and gives us an opportunity to set things on the WebSocket handler before we turn it on + public void WebSocketHandlerCallback(string path, WebSocketHttpServerHandler handler) + { + SubscribeToEvents(handler); + handler.SetChunksize(8192); + handler.NoDelay_TCP_Nagle = true; + handler.HandshakeAndUpgrade(); + } + + //These are our normal events + public void SubscribeToEvents(WebSocketHttpServerHandler handler) + { + handler.OnClose += HandlerOnOnClose; + handler.OnText += HandlerOnOnText; + handler.OnUpgradeCompleted += HandlerOnOnUpgradeCompleted; + handler.OnData += HandlerOnOnData; + handler.OnPong += HandlerOnOnPong; + } + + public void UnSubscribeToEvents(WebSocketHttpServerHandler handler) + { + handler.OnClose -= HandlerOnOnClose; + handler.OnText -= HandlerOnOnText; + handler.OnUpgradeCompleted -= HandlerOnOnUpgradeCompleted; + handler.OnData -= HandlerOnOnData; + handler.OnPong -= HandlerOnOnPong; + } + + private void HandlerOnOnPong(object sender, PongEventArgs pongdata) + { + m_log.Info("[WebSocketEchoModule]: Got a pong.. ping time: " + pongdata.PingResponseMS); + } + + private void HandlerOnOnData(object sender, WebsocketDataEventArgs data) + { + WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler; + obj.SendData(data.Data); + m_log.Info("[WebSocketEchoModule]: We received a bunch of ugly non-printable bytes"); + obj.SendPingCheck(); + } + + + private void HandlerOnOnUpgradeCompleted(object sender, UpgradeCompletedEventArgs completeddata) + { + WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler; + _activeHandlers.Add(obj); + } + + private void HandlerOnOnText(object sender, WebsocketTextEventArgs text) + { + WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler; + obj.SendMessage(text.Data); + m_log.Info("[WebSocketEchoModule]: We received this: " + text.Data); + } + + // Remove the references to our handler + private void HandlerOnOnClose(object sender, CloseEventArgs closedata) + { + WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler; + UnSubscribeToEvents(obj); + + lock (_activeHandlers) + _activeHandlers.Remove(obj); + obj.Dispose(); + } + + // Shutting down.. so shut down all sockets. + // Note.. this should be done outside of an ienumerable if you're also hook to the close event. + public void Close() + { + if (!enabled) + return; + + // We convert this to a for loop so we're not in in an IEnumerable when the close + //call triggers an event which then removes item from _activeHandlers that we're enumerating + WebSocketHttpServerHandler[] items = new WebSocketHttpServerHandler[_activeHandlers.Count]; + _activeHandlers.CopyTo(items); + + for (int i = 0; i < items.Length; i++) + { + items[i].Close(string.Empty); + items[i].Dispose(); + } + _activeHandlers.Clear(); + MainServer.Instance.RemoveWebSocketHandler("/echo"); + } + + public void AddRegion(Scene scene) + { + m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} ADDED", scene.RegionInfo.RegionName); + } + + public void RemoveRegion(Scene scene) + { + m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} REMOVED", scene.RegionInfo.RegionName); + } + + public void RegionLoaded(Scene scene) + { + m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} LOADED", scene.RegionInfo.RegionName); + } + } +} \ No newline at end of file -- cgit v1.1 From a5c83f7505bf897c2d445391802f1ac7a2143d3d Mon Sep 17 00:00:00 2001 From: teravus Date: Thu, 7 Feb 2013 12:22:03 -0500 Subject: Websocket Echo module should not be on by default. --- .../OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs index 34e20b7..112ba4e 100644 --- a/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs +++ b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs @@ -55,7 +55,7 @@ namespace OpenSim.Region.OptionalModules.WebSocketEchoModule public void Initialise(IConfigSource pConfig) { - enabled = true;// (pConfig.Configs["WebSocketEcho"] != null); + enabled =(pConfig.Configs["WebSocketEcho"] != null); if (enabled) m_log.DebugFormat("[WebSocketEchoModule]: INITIALIZED MODULE"); } -- cgit v1.1 From af73ea909cad78eee78bd4e9d9e3a42cf8856263 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 6 Feb 2013 22:34:03 -0800 Subject: Change passed PhysicsParameter value from float to the more general string value --- .../PhysicsParameters/PhysicsParameters.cs | 19 +++------- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 34 +++++++++--------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 41 +++++++++++++++++----- .../Region/Physics/Manager/IPhysicsParameters.cs | 6 ++-- 4 files changed, 57 insertions(+), 43 deletions(-) diff --git a/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs b/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs index 40f7fbc..3083a33 100755 --- a/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs +++ b/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs @@ -146,7 +146,7 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters { foreach (PhysParameterEntry ppe in physScene.GetParameterList()) { - float val = 0.0f; + string val = string.Empty; if (physScene.GetPhysicsParameter(ppe.name, out val)) { WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, ppe.name, val); @@ -159,7 +159,7 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters } else { - float val = 0.0f; + string val = string.Empty; if (physScene.GetPhysicsParameter(parm, out val)) { WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, parm, val); @@ -185,21 +185,12 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters return; } string parm = "xxx"; - float val = 0f; + string valparm = String.Empty; uint localID = (uint)PhysParameterEntry.APPLY_TO_NONE; // set default value try { parm = cmdparms[2]; - string valparm = cmdparms[3].ToLower(); - if (valparm == "true") - val = PhysParameterEntry.NUMERIC_TRUE; - else - { - if (valparm == "false") - val = PhysParameterEntry.NUMERIC_FALSE; - else - val = float.Parse(valparm, Culture.NumberFormatInfo); - } + valparm = cmdparms[3].ToLower(); if (cmdparms.Length > 4) { if (cmdparms[4].ToLower() == "all") @@ -224,7 +215,7 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters; if (physScene != null) { - if (!physScene.SetPhysicsParameter(parm, val, localID)) + if (!physScene.SetPhysicsParameter(parm, valparm, localID)) { WriteError("Failed set of parameter '{0}' for region '{1}'", parm, scene.RegionInfo.RegionName); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 965c382..601c78c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -641,24 +641,6 @@ public static class BSParam return (b == ConfigurationParameters.numericTrue ? true : false); } - private static void ResetBroadphasePoolTainted(BSScene pPhysScene, float v) - { - BSScene physScene = pPhysScene; - physScene.TaintedObject("BSParam.ResetBroadphasePoolTainted", delegate() - { - physScene.PE.ResetBroadphasePool(physScene.World); - }); - } - - private static void ResetConstraintSolverTainted(BSScene pPhysScene, float v) - { - BSScene physScene = pPhysScene; - physScene.TaintedObject("BSParam.ResetConstraintSolver", delegate() - { - physScene.PE.ResetConstraintSolver(physScene.World); - }); - } - // Search through the parameter definitions and return the matching // ParameterDefn structure. // Case does not matter as names are compared after converting to lower case. @@ -722,6 +704,22 @@ public static class BSParam } } + private static void ResetBroadphasePoolTainted(BSScene pPhysScene, float v) + { + BSScene physScene = pPhysScene; + physScene.TaintedObject("BSParam.ResetBroadphasePoolTainted", delegate() + { + physScene.PE.ResetBroadphasePool(physScene.World); + }); + } + private static void ResetConstraintSolverTainted(BSScene pPhysScene, float v) + { + BSScene physScene = pPhysScene; + physScene.TaintedObject("BSParam.ResetConstraintSolver", delegate() + { + physScene.PE.ResetConstraintSolver(physScene.World); + }); + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 6cd72f2..f8a0c1e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -876,14 +876,39 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // will use the next time since it's pinned and shared memory. // Some of the values require calling into the physics engine to get the new // value activated ('terrainFriction' for instance). - public bool SetPhysicsParameter(string parm, float val, uint localID) + public bool SetPhysicsParameter(string parm, string val, uint localID) { bool ret = false; + + float valf = 0f; + if (val.ToLower() == "true") + { + valf = PhysParameterEntry.NUMERIC_TRUE; + } + else + { + if (val.ToLower() == "false") + { + valf = PhysParameterEntry.NUMERIC_FALSE; + } + else + { + try + { + valf = float.Parse(val); + } + catch + { + valf = 0f; + } + } + } + BSParam.ParameterDefn theParam; if (BSParam.TryGetParameter(parm, out theParam)) { // Set the value in the C# code - theParam.setter(this, parm, localID, val); + theParam.setter(this, parm, localID, valf); // Optionally set the parameter in the unmanaged code if (theParam.onObject != null) @@ -898,16 +923,16 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters case PhysParameterEntry.APPLY_TO_NONE: // This will cause a call into the physical world if some operation is specified (SetOnObject). objectIDs.Add(TERRAIN_ID); - TaintedUpdateParameter(parm, objectIDs, val); + TaintedUpdateParameter(parm, objectIDs, valf); break; case PhysParameterEntry.APPLY_TO_ALL: lock (PhysObjects) objectIDs = new List(PhysObjects.Keys); - TaintedUpdateParameter(parm, objectIDs, val); + TaintedUpdateParameter(parm, objectIDs, valf); break; default: // setting only one localID objectIDs.Add(localID); - TaintedUpdateParameter(parm, objectIDs, val); + TaintedUpdateParameter(parm, objectIDs, valf); break; } } @@ -942,14 +967,14 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Get parameter. // Return 'false' if not able to get the parameter. - public bool GetPhysicsParameter(string parm, out float value) + public bool GetPhysicsParameter(string parm, out string value) { - float val = 0f; + string val = String.Empty; bool ret = false; BSParam.ParameterDefn theParam; if (BSParam.TryGetParameter(parm, out theParam)) { - val = theParam.getter(this); + val = theParam.getter(this).ToString(); ret = true; } value = val; diff --git a/OpenSim/Region/Physics/Manager/IPhysicsParameters.cs b/OpenSim/Region/Physics/Manager/IPhysicsParameters.cs index b8676ba..31a397c 100755 --- a/OpenSim/Region/Physics/Manager/IPhysicsParameters.cs +++ b/OpenSim/Region/Physics/Manager/IPhysicsParameters.cs @@ -60,14 +60,14 @@ namespace OpenSim.Region.Physics.Manager // Set parameter on a specific or all instances. // Return 'false' if not able to set the parameter. - bool SetPhysicsParameter(string parm, float value, uint localID); + bool SetPhysicsParameter(string parm, string value, uint localID); // Get parameter. // Return 'false' if not able to get the parameter. - bool GetPhysicsParameter(string parm, out float value); + bool GetPhysicsParameter(string parm, out string value); // Get parameter from a particular object // TODO: - // bool GetPhysicsParameter(string parm, out float value, uint localID); + // bool GetPhysicsParameter(string parm, out string value, uint localID); } } -- cgit v1.1 From c658fa1c0dd83f23c66ccfedb12e8ab02ff01d0a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 7 Feb 2013 11:05:21 -0800 Subject: Add plumbing for physics properties to get to the physics engine. Addition of entries to PhysicsActor and setting code in SceneObjectPart. --- OpenSim/Region/Framework/Scenes/SceneObjectPart.cs | 56 +++++++++++++++++++--- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 5 ++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index b00f388..a3c7ed3 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -1387,10 +1387,46 @@ namespace OpenSim.Region.Framework.Scenes } } - public float Density { get; set; } - public float GravityModifier { get; set; } - public float Friction { get; set; } - public float Restitution { get; set; } + private float m_density = 10f; + public float Density { + get { return m_density; } + set + { + m_density = value; + if (PhysActor != null) + PhysActor.Density = m_density; + } + } + private float m_gravityModifier = 1f; + public float GravityModifier { + get { return m_gravityModifier; } + set + { + m_gravityModifier = value; + if (PhysActor != null) + PhysActor.GravityModifier = m_gravityModifier; + } + } + private float m_friction = 0.5f; + public float Friction { + get { return m_friction; } + set + { + m_friction = value; + if (PhysActor != null) + PhysActor.Friction = m_friction; + } + } + private float m_restitution = 0f; + public float Restitution { + get { return m_restitution; } + set + { + m_restitution = value; + if (PhysActor != null) + PhysActor.Restitution = m_restitution; + } + } #endregion Public Properties with only Get @@ -1896,8 +1932,18 @@ namespace OpenSim.Region.Framework.Scenes { ParentGroup.Scene.AddPhysicalPrim(1); + // Update initial values for various physical properties + pa.SetMaterial(Material); + pa.Density = Density; + pa.Friction = Friction; + pa.Restitution = Restitution; + pa.GravityModifier = GravityModifier; + + // Link up callbacks for property updates from the physics engine pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; pa.OnOutOfBounds += PhysicsOutOfBounds; + + // If this is a child prim, tell the physics engine about the parent if (ParentID != 0 && ParentID != LocalId) { PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; @@ -4062,7 +4108,6 @@ namespace OpenSim.Region.Framework.Scenes if (pa != null) { - pa.SetMaterial(Material); DoPhysicsPropertyUpdate(UsePhysics, true); if ( @@ -4175,7 +4220,6 @@ namespace OpenSim.Region.Framework.Scenes if (pa != null) { pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info - pa.SetMaterial(Material); DoPhysicsPropertyUpdate(rigidBody, true); } diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index d119791..4820ca4 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -235,6 +235,11 @@ namespace OpenSim.Region.Physics.Manager public abstract float Mass { get; } public abstract Vector3 Force { get; set; } + public virtual float Density { get; set; } + public virtual float Friction { get; set; } + public virtual float Restitution { get; set; } + public virtual float GravityModifier { get; set; } + public abstract int VehicleType { get; set; } public abstract void VehicleFloatParam(int param, float value); public abstract void VehicleVectorParam(int param, Vector3 value); -- cgit v1.1 From 9089757ea2cabe49f40de64b7e6befa13a4553c1 Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 7 Feb 2013 21:05:58 +0000 Subject: Revert "Add plumbing for physics properties to get to the physics engine." This reverts commit c658fa1c0dd83f23c66ccfedb12e8ab02ff01d0a. --- OpenSim/Region/Framework/Scenes/SceneObjectPart.cs | 56 +++------------------- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 5 -- 2 files changed, 6 insertions(+), 55 deletions(-) diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index a3c7ed3..b00f388 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -1387,46 +1387,10 @@ namespace OpenSim.Region.Framework.Scenes } } - private float m_density = 10f; - public float Density { - get { return m_density; } - set - { - m_density = value; - if (PhysActor != null) - PhysActor.Density = m_density; - } - } - private float m_gravityModifier = 1f; - public float GravityModifier { - get { return m_gravityModifier; } - set - { - m_gravityModifier = value; - if (PhysActor != null) - PhysActor.GravityModifier = m_gravityModifier; - } - } - private float m_friction = 0.5f; - public float Friction { - get { return m_friction; } - set - { - m_friction = value; - if (PhysActor != null) - PhysActor.Friction = m_friction; - } - } - private float m_restitution = 0f; - public float Restitution { - get { return m_restitution; } - set - { - m_restitution = value; - if (PhysActor != null) - PhysActor.Restitution = m_restitution; - } - } + public float Density { get; set; } + public float GravityModifier { get; set; } + public float Friction { get; set; } + public float Restitution { get; set; } #endregion Public Properties with only Get @@ -1932,18 +1896,8 @@ namespace OpenSim.Region.Framework.Scenes { ParentGroup.Scene.AddPhysicalPrim(1); - // Update initial values for various physical properties - pa.SetMaterial(Material); - pa.Density = Density; - pa.Friction = Friction; - pa.Restitution = Restitution; - pa.GravityModifier = GravityModifier; - - // Link up callbacks for property updates from the physics engine pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; pa.OnOutOfBounds += PhysicsOutOfBounds; - - // If this is a child prim, tell the physics engine about the parent if (ParentID != 0 && ParentID != LocalId) { PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; @@ -4108,6 +4062,7 @@ namespace OpenSim.Region.Framework.Scenes if (pa != null) { + pa.SetMaterial(Material); DoPhysicsPropertyUpdate(UsePhysics, true); if ( @@ -4220,6 +4175,7 @@ namespace OpenSim.Region.Framework.Scenes if (pa != null) { pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info + pa.SetMaterial(Material); DoPhysicsPropertyUpdate(rigidBody, true); } diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index 4820ca4..d119791 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -235,11 +235,6 @@ namespace OpenSim.Region.Physics.Manager public abstract float Mass { get; } public abstract Vector3 Force { get; set; } - public virtual float Density { get; set; } - public virtual float Friction { get; set; } - public virtual float Restitution { get; set; } - public virtual float GravityModifier { get; set; } - public abstract int VehicleType { get; set; } public abstract void VehicleFloatParam(int param, float value); public abstract void VehicleVectorParam(int param, Vector3 value); -- cgit v1.1 From 338b02a8bc51d1dc5c1161a2a5a10b85521d1f8e Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 7 Feb 2013 21:23:35 +0000 Subject: Send the new physics params to the viewer build dialog --- .../Linden/Caps/BunchOfCaps/BunchOfCaps.cs | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs index 568e216..1af61db 100644 --- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs +++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs @@ -96,6 +96,8 @@ namespace OpenSim.Region.ClientStack.Linden // private static readonly string m_fetchInventoryPath = "0006/"; private static readonly string m_copyFromNotecardPath = "0007/"; // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule. + private static readonly string m_getObjectPhysicsDataPath = "0101/"; + /* 0102 - 0103 RESERVED */ private static readonly string m_UpdateAgentInformationPath = "0500/"; // These are callbacks which will be setup by the scene so that we can update scene data when we @@ -204,6 +206,8 @@ namespace OpenSim.Region.ClientStack.Linden m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req); m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req); m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req); + IRequestHandler getObjectPhysicsDataHandler = new RestStreamHandler("POST", capsBase + m_getObjectPhysicsDataPath, GetObjectPhysicsData); + m_HostCapsObj.RegisterHandler("GetObjectPhysicsData", getObjectPhysicsDataHandler); IRequestHandler UpdateAgentInformationHandler = new RestStreamHandler("POST", capsBase + m_UpdateAgentInformationPath, UpdateAgentInformation); m_HostCapsObj.RegisterHandler("UpdateAgentInformation", UpdateAgentInformationHandler); @@ -873,6 +877,37 @@ namespace OpenSim.Region.ClientStack.Linden return LLSDHelpers.SerialiseLLSDReply(response); } + public string GetObjectPhysicsData(string request, string path, + string param, IOSHttpRequest httpRequest, + IOSHttpResponse httpResponse) + { + OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); + OSDMap resp = new OSDMap(); + OSDArray object_ids = (OSDArray)req["object_ids"]; + + for (int i = 0 ; i < object_ids.Count ; i++) + { + UUID uuid = object_ids[i].AsUUID(); + + SceneObjectPart obj = m_Scene.GetSceneObjectPart(uuid); + if (obj != null) + { + OSDMap object_data = new OSDMap(); + + object_data["PhysicsShapeType"] = obj.PhysicsShapeType; + object_data["Density"] = obj.Density; + object_data["Friction"] = obj.Friction; + object_data["Restitution"] = obj.Restitution; + object_data["GravityMultiplier"] = obj.GravityModifier; + + resp[uuid.ToString()] = object_data; + } + } + + string response = OSDParser.SerializeLLSDXmlString(resp); + return response; + } + public string UpdateAgentInformation(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) -- cgit v1.1 From 7bf33d333af6e7393a05940d1ab436f5dce73814 Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 7 Feb 2013 22:25:28 +0000 Subject: Plumb the path from the client to the extra physics params and back --- OpenSim/Framework/IClientAPI.cs | 4 +- .../Linden/Caps/EventQueue/EventQueueGetModule.cs | 8 +++ .../Linden/Caps/EventQueue/EventQueueHelper.cs | 20 ++++++++ .../Region/ClientStack/Linden/UDP/LLClientView.cs | 59 ++++++++++++++++++++-- OpenSim/Region/Framework/Interfaces/IEventQueue.cs | 2 + OpenSim/Region/Framework/Scenes/SceneGraph.cs | 25 ++++++++- OpenSim/Region/Framework/Scenes/SceneObjectPart.cs | 1 + .../Server/IRCClientView.cs | 5 ++ .../Region/OptionalModules/World/NPC/NPCAvatar.cs | 5 ++ OpenSim/Tests/Common/Mock/TestClient.cs | 5 ++ 10 files changed, 127 insertions(+), 7 deletions(-) diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs index 87433cc..f6b7689 100644 --- a/OpenSim/Framework/IClientAPI.cs +++ b/OpenSim/Framework/IClientAPI.cs @@ -124,7 +124,7 @@ namespace OpenSim.Framework public delegate void ObjectDrop(uint localID, IClientAPI remoteClient); public delegate void UpdatePrimFlags( - uint localID, bool UsePhysics, bool IsTemporary, bool IsPhantom, IClientAPI remoteClient); + uint localID, bool UsePhysics, bool IsTemporary, bool IsPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient); public delegate void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient); @@ -1356,6 +1356,8 @@ namespace OpenSim.Framework void SendObjectPropertiesReply(ISceneEntity Entity); + void SendPartPhysicsProprieties(ISceneEntity Entity); + void SendAgentOffline(UUID[] agentIDs); void SendAgentOnline(UUID[] agentIDs); diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs index 4d2c0f2..3cc3950 100644 --- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs +++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs @@ -807,5 +807,13 @@ namespace OpenSim.Region.ClientStack.Linden { return EventQueueHelper.BuildEvent(eventName, eventBody); } + + public void partPhysicsProperties(uint localID, byte physhapetype, + float density, float friction, float bounce, float gravmod,UUID avatarID) + { + OSD item = EventQueueHelper.partPhysicsProperties(localID, physhapetype, + density, friction, bounce, gravmod); + Enqueue(item, avatarID); + } } } diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs index 3f49aba..dab727f 100644 --- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs +++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs @@ -395,5 +395,25 @@ namespace OpenSim.Region.ClientStack.Linden return message; } + public static OSD partPhysicsProperties(uint localID, byte physhapetype, + float density, float friction, float bounce, float gravmod) + { + + OSDMap physinfo = new OSDMap(6); + physinfo["LocalID"] = localID; + physinfo["Density"] = density; + physinfo["Friction"] = friction; + physinfo["GravityMultiplier"] = gravmod; + physinfo["Restitution"] = bounce; + physinfo["PhysicsShapeType"] = (int)physhapetype; + + OSDArray array = new OSDArray(1); + array.Add(physinfo); + + OSDMap llsdBody = new OSDMap(1); + llsdBody.Add("ObjectData", array); + + return BuildEvent("ObjectPhysicsProperties", llsdBody); + } } } diff --git a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs index 88b64f5..bd4a2d1 100644 --- a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs @@ -2627,6 +2627,34 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } + public void SendPartPhysicsProprieties(ISceneEntity entity) + { + SceneObjectPart part = (SceneObjectPart)entity; + if (part != null && AgentId != UUID.Zero) + { + try + { + IEventQueue eq = Scene.RequestModuleInterface(); + if (eq != null) + { + uint localid = part.LocalId; + byte physshapetype = part.PhysicsShapeType; + float density = part.Density; + float friction = part.Friction; + float bounce = part.Restitution; + float gravmod = part.GravityModifier; + eq.partPhysicsProperties(localid, physshapetype, density, friction, bounce, gravmod,AgentId); + } + } + catch (Exception ex) + { + m_log.Error("Unable to send part Physics Proprieties - exception: " + ex.ToString()); + } + part.UpdatePhysRequired = false; + } + } + + public void SendGroupNameReply(UUID groupLLUID, string GroupName) { @@ -7035,10 +7063,33 @@ namespace OpenSim.Region.ClientStack.LindenUDP // 46,47,48 are special positions within the packet // This may change so perhaps we need a better way // of storing this (OMV.FlagUpdatePacket.UsePhysics,etc?) - bool UsePhysics = (data[46] != 0) ? true : false; - bool IsTemporary = (data[47] != 0) ? true : false; - bool IsPhantom = (data[48] != 0) ? true : false; - handlerUpdatePrimFlags(flags.AgentData.ObjectLocalID, UsePhysics, IsTemporary, IsPhantom, this); + /* + bool UsePhysics = (data[46] != 0) ? true : false; + bool IsTemporary = (data[47] != 0) ? true : false; + bool IsPhantom = (data[48] != 0) ? true : false; + handlerUpdatePrimFlags(flags.AgentData.ObjectLocalID, UsePhysics, IsTemporary, IsPhantom, this); + */ + bool UsePhysics = flags.AgentData.UsePhysics; + bool IsPhantom = flags.AgentData.IsPhantom; + bool IsTemporary = flags.AgentData.IsTemporary; + ObjectFlagUpdatePacket.ExtraPhysicsBlock[] blocks = flags.ExtraPhysics; + ExtraPhysicsData physdata = new ExtraPhysicsData(); + + if (blocks == null || blocks.Length == 0) + { + physdata.PhysShapeType = PhysShapeType.invalid; + } + else + { + ObjectFlagUpdatePacket.ExtraPhysicsBlock phsblock = blocks[0]; + physdata.PhysShapeType = (PhysShapeType)phsblock.PhysicsShapeType; + physdata.Bounce = phsblock.Restitution; + physdata.Density = phsblock.Density; + physdata.Friction = phsblock.Friction; + physdata.GravitationModifier = phsblock.GravityMultiplier; + } + + handlerUpdatePrimFlags(flags.AgentData.ObjectLocalID, UsePhysics, IsTemporary, IsPhantom, physdata, this); } return true; } diff --git a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs index bfa5d17..5512642 100644 --- a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs +++ b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs @@ -59,5 +59,7 @@ namespace OpenSim.Region.Framework.Interfaces void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID); OSD ScriptRunningEvent(UUID objectID, UUID itemID, bool running, bool mono); OSD BuildEvent(string eventName, OSD eventBody); + void partPhysicsProperties(uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod, UUID avatarID); + } } diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs index a4383fd..a84f6d3 100644 --- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs +++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs @@ -1408,7 +1408,7 @@ namespace OpenSim.Region.Framework.Scenes /// /// protected internal void UpdatePrimFlags( - uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, IClientAPI remoteClient) + uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) @@ -1416,7 +1416,28 @@ namespace OpenSim.Region.Framework.Scenes if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) { // VolumeDetect can't be set via UI and will always be off when a change is made there - group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, false); + // now only change volume dtc if phantom off + + if (PhysData.PhysShapeType == PhysShapeType.invalid) // check for extraPhysics data + { + bool vdtc; + if (SetPhantom) // if phantom keep volumedtc + vdtc = group.RootPart.VolumeDetectActive; + else // else turn it off + vdtc = false; + + group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc); + } + else + { + SceneObjectPart part = GetSceneObjectPart(localID); + if (part != null) + { + part.UpdateExtraPhysics(PhysData); + if (part.UpdatePhysRequired) + remoteClient.SendPartPhysicsProprieties(part); + } + } } } } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index b00f388..cd40b29 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -1042,6 +1042,7 @@ namespace OpenSim.Region.Framework.Scenes } public UpdateRequired UpdateFlag { get; set; } + public bool UpdatePhysRequired { get; set; } /// /// Used for media on a prim. diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs index 781539a..0ac56fa 100644 --- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs +++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs @@ -1678,5 +1678,10 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } + + public void SendPartPhysicsProprieties(ISceneEntity entity) + { + } + } } diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs index 5ea2bcd..6bd27f0 100644 --- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs +++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs @@ -1234,5 +1234,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } + + public void SendPartPhysicsProprieties(ISceneEntity entity) + { + } + } } diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs index dde37ab..182f4d9 100644 --- a/OpenSim/Tests/Common/Mock/TestClient.cs +++ b/OpenSim/Tests/Common/Mock/TestClient.cs @@ -1276,5 +1276,10 @@ namespace OpenSim.Tests.Common.Mock public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } + + public void SendPartPhysicsProprieties(ISceneEntity entity) + { + } + } } -- cgit v1.1