Skip to content

Commit d066518

Browse files
author
Marian Krivos
committed
trunk: add websocket class
1 parent 7d7c02c commit d066518

4 files changed

Lines changed: 914 additions & 0 deletions

File tree

‎Net/include/Poco/Net/WebSocket.h‎

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
//
2+
// WebSocket.h
3+
//
4+
// $Id: //poco/1.4/Net/include/Poco/Net/WebSocket.h#1 $
5+
//
6+
// Library: Net
7+
// Package: WebSocket
8+
// Module: WebSocket
9+
//
10+
// Definition of the WebSocket class.
11+
//
12+
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
13+
// and Contributors.
14+
//
15+
// Permission is hereby granted, free of charge, to any person or organization
16+
// obtaining a copy of the software and accompanying documentation covered by
17+
// this license (the "Software") to use, reproduce, display, distribute,
18+
// execute, and transmit the Software, and to prepare derivative works of the
19+
// Software, and to permit third-parties to whom the Software is furnished to
20+
// do so, all subject to the following:
21+
//
22+
// The copyright notices in the Software and this entire statement, including
23+
// the above license grant, this restriction and the following disclaimer,
24+
// must be included in all copies of the Software, in whole or in part, and
25+
// all derivative works of the Software, unless such copies or derivative
26+
// works are solely in the form of machine-executable object code generated by
27+
// a source language processor.
28+
//
29+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31+
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
32+
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
33+
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
34+
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
35+
// DEALINGS IN THE SOFTWARE.
36+
//
37+
38+
39+
#ifndef Net_WebSocket_INCLUDED
40+
#define Net_WebSocket_INCLUDED
41+
42+
43+
#include "Poco/Net/Net.h"
44+
#include "Poco/Net/StreamSocket.h"
45+
#include "Poco/Net/HTTPCredentials.h"
46+
47+
48+
namespace Poco {
49+
namespace Net {
50+
51+
52+
class WebSocketImpl;
53+
class HTTPServerRequest;
54+
class HTTPServerResponse;
55+
class HTTPClientSession;
56+
57+
58+
class Net_API WebSocket: public StreamSocket
59+
/// This class implements a WebSocket according
60+
/// to the WebSocket protocol specification in RFC 6455.
61+
///
62+
/// Both client-side and server-side WebSockets
63+
/// are supported.
64+
///
65+
/// Server-side WebSockets are usually created from within
66+
/// a HTTPRequestHandler.
67+
///
68+
/// Client-side WebSockets are created using a HTTPClientSession.
69+
///
70+
/// Note that special frames like PING must be handled at
71+
/// application level. In the case of a PING, a PONG message
72+
/// must be returned.
73+
{
74+
public:
75+
enum Mode
76+
{
77+
WS_SERVER, /// Server-side WebSocket.
78+
WS_CLIENT /// Client-side WebSocket.
79+
};
80+
81+
enum FrameFlags
82+
/// Frame header flags.
83+
{
84+
FRAME_FLAG_FIN = 0x80, /// FIN bit: final fragment of a multi-fragment message.
85+
FRAME_FLAG_RSV1 = 0x40, /// Reserved for future use. Must be zero.
86+
FRAME_FLAG_RSV2 = 0x20, /// Reserved for future use. Must be zero.
87+
FRAME_FLAG_RSV3 = 0x10, /// Reserved for future use. Must be zero.
88+
};
89+
90+
enum FrameOpcodes
91+
/// Frame header opcodes.
92+
{
93+
FRAME_OP_CONT = 0x00, /// Continuation frame.
94+
FRAME_OP_TEXT = 0x01, /// Text frame.
95+
FRAME_OP_BINARY = 0x02, /// Binary frame.
96+
FRAME_OP_CLOSE = 0x08, /// Close connection.
97+
FRAME_OP_PING = 0x09, /// Ping frame.
98+
FRAME_OP_PONG = 0x0a, /// Pong frame.
99+
FRAME_OP_BITMASK = 0x0f /// Bit mask for opcodes.
100+
};
101+
102+
enum SendFlags
103+
/// Combined header flags and opcodes for use with sendFrame().
104+
{
105+
FRAME_TEXT = FRAME_FLAG_FIN | FRAME_OP_TEXT,
106+
/// Use this for sending a single text (UTF-8) payload frame.
107+
FRAME_BINARY = FRAME_FLAG_FIN | FRAME_OP_BINARY
108+
/// Use this for sending a single binary payload frame.
109+
};
110+
111+
enum StatusCodes
112+
/// StatusCodes for CLOSE frames sent with shutdown().
113+
{
114+
WS_NORMAL_CLOSE = 1000,
115+
WS_ENDPOINT_GOING_AWAY = 1001,
116+
WS_PROTOCOL_ERROR = 1002,
117+
WS_PAYLOAD_NOT_ACCEPTABLE = 1003,
118+
WS_RESERVED = 1004,
119+
WS_RESERVED_NO_STATUS_CODE = 1005,
120+
WS_RESERVED_ABNORMAL_CLOSE = 1006,
121+
WS_MALFORMED_PAYLOAD = 1007,
122+
WS_POLICY_VIOLATION = 1008,
123+
WS_PAYLOAD_TOO_BIG = 1009,
124+
WS_EXTENSION_REQUIRED = 1010,
125+
WS_UNEXPECTED_CONDITION = 1011,
126+
WS_RESERVED_TLS_FAILURE = 1015
127+
};
128+
129+
enum ErrorCodes
130+
/// These error codes can be obtained from a WebSocketException
131+
/// to determine the exact cause of the error.
132+
{
133+
WS_ERR_NO_HANDSHAKE = 1,
134+
/// No Connection: Upgrade or Upgrade: websocket header in handshake request.
135+
WS_ERR_HANDSHAKE_NO_VERSION = 2,
136+
/// No Sec-WebSocket-Version header in handshake request.
137+
WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION = 3,
138+
/// Unsupported WebSocket version requested by client.
139+
WS_ERR_HANDSHAKE_NO_KEY = 4,
140+
/// No Sec-WebSocket-Key header in handshake request.
141+
WS_ERR_HANDSHAKE_ACCEPT = 5,
142+
/// No Sec-WebSocket-Accept header or wrong value.
143+
WS_ERR_UNAUTHORIZED = 6,
144+
/// The server rejected the username or password for authentication.
145+
WS_ERR_PAYLOAD_TOO_BIG = 10,
146+
/// Payload too big for supplied buffer.
147+
WS_ERR_INCOMPLETE_FRAME = 11
148+
/// Incomplete frame received.
149+
};
150+
151+
WebSocket(HTTPServerRequest& request, HTTPServerResponse& response);
152+
/// Creates a server-side WebSocket from within a
153+
/// HTTPRequestHandler.
154+
///
155+
/// First verifies that the request is a valid WebSocket upgrade
156+
/// request. If so, completes the handshake by sending
157+
/// a proper 101 response.
158+
///
159+
/// Throws an exception if the request is not a proper WebSocket
160+
/// upgrade request.
161+
162+
WebSocket(HTTPClientSession& cs, HTTPRequest& request, HTTPResponse& response);
163+
/// Creates a client-side WebSocket, using the given
164+
/// HTTPClientSession and HTTPRequest for the initial handshake
165+
/// (HTTP Upgrade request).
166+
///
167+
/// Additional HTTP headers for the initial handshake request
168+
/// (such as Origin or Sec-WebSocket-Protocol) can be given
169+
/// in the request object.
170+
///
171+
/// The result of the handshake can be obtained from the response
172+
/// object.
173+
174+
WebSocket(HTTPClientSession& cs, HTTPRequest& request, HTTPResponse& response, HTTPCredentials& credentials);
175+
/// Creates a client-side WebSocket, using the given
176+
/// HTTPClientSession and HTTPRequest for the initial handshake
177+
/// (HTTP Upgrade request).
178+
///
179+
/// The given credentials are used for authentication
180+
/// if requested by the server.
181+
///
182+
/// Additional HTTP headers for the initial handshake request
183+
/// (such as Origin or Sec-WebSocket-Protocol) can be given
184+
/// in the request object.
185+
///
186+
/// The result of the handshake can be obtained from the response
187+
/// object.
188+
189+
virtual ~WebSocket();
190+
/// Destroys the StreamSocket.
191+
192+
WebSocket& operator = (const Socket& socket);
193+
/// Assignment operator.
194+
///
195+
/// Releases the socket's SocketImpl and
196+
/// attaches the SocketImpl from the other socket and
197+
/// increments the reference count of the SocketImpl.
198+
199+
void shutdown();
200+
/// Sends a Close control frame to the server end of
201+
/// the connection to initiate an orderly shutdown
202+
/// of the connection.
203+
204+
void shutdown(Poco::UInt16 statusCode, const std::string& statusMessage = "");
205+
/// Sends a Close control frame to the server end of
206+
/// the connection to initiate an orderly shutdown
207+
/// of the connection.
208+
209+
int sendFrame(const void* buffer, int length, int flags = FRAME_TEXT);
210+
/// Sends the contents of the given buffer through
211+
/// the socket as a single frame.
212+
///
213+
/// Values from the FrameFlags, FrameOpcodes and SendFlags enumerations
214+
/// can be specified in flags.
215+
///
216+
/// Returns the number of bytes sent, which may be
217+
/// less than the number of bytes specified.
218+
///
219+
/// Certain socket implementations may also return a negative
220+
/// value denoting a certain condition.
221+
222+
int receiveFrame(void* buffer, int length, int& flags);
223+
/// Receives a frame from the socket and stores it
224+
/// in buffer. Up to length bytes are received. If
225+
/// the frame's payload is larger, a WebSocketException
226+
/// is thrown and the WebSocket connection must be
227+
/// terminated.
228+
///
229+
/// Returns the number of bytes received.
230+
/// A return value of 0 means a graceful shutdown
231+
/// of the connection from the peer.
232+
///
233+
/// Throws a TimeoutException if a receive timeout has
234+
/// been set and nothing is received within that interval.
235+
/// Throws a NetException (or a subclass) in case of other errors.
236+
///
237+
/// The frame flags and opcode (FrameFlags and FrameOpcodes)
238+
/// is stored in flags.
239+
240+
Mode mode() const;
241+
/// Returns WS_SERVER if the WebSocket is a server-side
242+
/// WebSocket, or WS_CLIENT otherwise.
243+
244+
static const std::string WEBSOCKET_VERSION;
245+
/// The WebSocket protocol version supported (13).
246+
247+
protected:
248+
static WebSocketImpl* accept(HTTPServerRequest& request, HTTPServerResponse& response);
249+
static WebSocketImpl* connect(HTTPClientSession& cs, HTTPRequest& request, HTTPResponse& response, HTTPCredentials& credentials);
250+
static WebSocketImpl* completeHandshake(HTTPClientSession& cs, HTTPResponse& response, const std::string& key);
251+
static std::string computeAccept(const std::string& key);
252+
static std::string createKey();
253+
254+
private:
255+
WebSocket();
256+
257+
static const std::string WEBSOCKET_GUID;
258+
static HTTPCredentials _defaultCreds;
259+
};
260+
261+
262+
} } // namespace Poco::Net
263+
264+
265+
#endif // Net_WebSocket_INCLUDED
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
//
2+
// WebSocketImpl.h
3+
//
4+
// $Id: //poco/1.4/Net/include/Poco/Net/WebSocketImpl.h#1 $
5+
//
6+
// Library: Net
7+
// Package: WebSocket
8+
// Module: WebSocketImpl
9+
//
10+
// Definition of the StreamSocketImpl class.
11+
//
12+
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
13+
// and Contributors.
14+
//
15+
// Permission is hereby granted, free of charge, to any person or organization
16+
// obtaining a copy of the software and accompanying documentation covered by
17+
// this license (the "Software") to use, reproduce, display, distribute,
18+
// execute, and transmit the Software, and to prepare derivative works of the
19+
// Software, and to permit third-parties to whom the Software is furnished to
20+
// do so, all subject to the following:
21+
//
22+
// The copyright notices in the Software and this entire statement, including
23+
// the above license grant, this restriction and the following disclaimer,
24+
// must be included in all copies of the Software, in whole or in part, and
25+
// all derivative works of the Software, unless such copies or derivative
26+
// works are solely in the form of machine-executable object code generated by
27+
// a source language processor.
28+
//
29+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31+
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
32+
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
33+
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
34+
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
35+
// DEALINGS IN THE SOFTWARE.
36+
//
37+
38+
39+
#ifndef Net_WebSocketImpl_INCLUDED
40+
#define Net_WebSocketImpl_INCLUDED
41+
42+
43+
#include "Poco/Net/StreamSocketImpl.h"
44+
#include "Poco/Random.h"
45+
46+
47+
namespace Poco {
48+
namespace Net {
49+
50+
51+
class Net_API WebSocketImpl: public StreamSocketImpl
52+
/// This class implements a WebSocket, according
53+
/// to the WebSocket protocol described in RFC 6455.
54+
{
55+
public:
56+
WebSocketImpl(StreamSocketImpl* pStreamSocketImpl, bool mustMaskPayload);
57+
/// Creates a StreamSocketImpl using the given native socket.
58+
59+
// StreamSocketImpl
60+
virtual int sendBytes(const void* buffer, int length, int flags);
61+
/// Sends a WebSocket protocol frame.
62+
63+
virtual int receiveBytes(void* buffer, int length, int flags);
64+
/// Receives a WebSocket protocol frame.
65+
66+
virtual SocketImpl* acceptConnection(SocketAddress& clientAddr);
67+
virtual void connect(const SocketAddress& address);
68+
virtual void connect(const SocketAddress& address, const Poco::Timespan& timeout);
69+
virtual void connectNB(const SocketAddress& address, const Poco::Timespan& timeout);
70+
virtual void bind(const SocketAddress& address, bool reuseAddress = false);
71+
virtual void bind6(const SocketAddress& address, bool reuseAddress = false, bool ipV6Only = false);
72+
virtual void listen(int backlog = 64);
73+
virtual void close();
74+
virtual void shutdownReceive();
75+
virtual void shutdownSend();
76+
virtual void shutdown();
77+
virtual int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0);
78+
virtual int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0);
79+
virtual void sendUrgent(unsigned char data);
80+
virtual bool secure() const;
81+
82+
// Internal
83+
int frameFlags() const;
84+
/// Returns the frame flags of the most recently received frame.
85+
86+
bool mustMaskPayload() const;
87+
/// Returns true if the payload must be masked.
88+
89+
protected:
90+
enum
91+
{
92+
FRAME_FLAG_MASK = 0x80,
93+
MAX_HEADER_LENGTH = 14
94+
};
95+
96+
virtual ~WebSocketImpl();
97+
98+
private:
99+
WebSocketImpl();
100+
101+
StreamSocketImpl* _pStreamSocketImpl;
102+
int _frameFlags;
103+
bool _mustMaskPayload;
104+
Poco::Random _rnd;
105+
};
106+
107+
108+
//
109+
// inlines
110+
//
111+
inline int WebSocketImpl::frameFlags() const
112+
{
113+
return _frameFlags;
114+
}
115+
116+
117+
inline bool WebSocketImpl::mustMaskPayload() const
118+
{
119+
return _mustMaskPayload;
120+
}
121+
122+
123+
} } // namespace Poco::Net
124+
125+
126+
#endif // Net_WebSocketImpl_INCLUDED

0 commit comments

Comments
 (0)