blob: 3ffb5a1026b61e6d0d4f6df222d9b4db5a932b58 [file] [log] [blame]
Austin Schuh9d823002019-04-14 12:53:17 -07001// Copyright (c) 2013-2017, Matt Godbolt
Austin Schuh24adb6b2015-09-06 17:37:40 -07002// All rights reserved.
Austin Schuh9d823002019-04-14 12:53:17 -07003//
4// Redistribution and use in source and binary forms, with or without
Austin Schuh24adb6b2015-09-06 17:37:40 -07005// modification, are permitted provided that the following conditions are met:
Austin Schuh9d823002019-04-14 12:53:17 -07006//
7// Redistributions of source code must retain the above copyright notice, this
Austin Schuh24adb6b2015-09-06 17:37:40 -07008// list of conditions and the following disclaimer.
Austin Schuh9d823002019-04-14 12:53:17 -07009//
10// Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
Austin Schuh24adb6b2015-09-06 17:37:40 -070012// and/or other materials provided with the distribution.
Austin Schuh9d823002019-04-14 12:53:17 -070013//
14// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
18// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Austin Schuh24adb6b2015-09-06 17:37:40 -070024// POSSIBILITY OF SUCH DAMAGE.
25
26#pragma once
27
28#include "seasocks/ResponseCode.h"
29#include "seasocks/WebSocket.h"
Austin Schuh9d823002019-04-14 12:53:17 -070030#include "seasocks/ResponseWriter.h"
31#include "seasocks/TransferEncoding.h"
32#include "seasocks/ZlibContext.h"
Austin Schuh24adb6b2015-09-06 17:37:40 -070033
34#include <netinet/in.h>
35
36#include <sys/socket.h>
37
Austin Schuh9d823002019-04-14 12:53:17 -070038#include <cinttypes>
Austin Schuh24adb6b2015-09-06 17:37:40 -070039#include <list>
40#include <memory>
41#include <string>
42#include <vector>
43
Austin Schuh9d823002019-04-14 12:53:17 -070044
Austin Schuh24adb6b2015-09-06 17:37:40 -070045namespace seasocks {
46
47class Logger;
48class ServerImpl;
49class PageRequest;
50class Response;
51
52class Connection : public WebSocket {
53public:
54 Connection(
Austin Schuh9d823002019-04-14 12:53:17 -070055 std::shared_ptr<Logger> logger,
56 ServerImpl& server,
57 int fd,
58 const sockaddr_in& address);
Austin Schuh24adb6b2015-09-06 17:37:40 -070059 virtual ~Connection();
60
61 bool write(const void* data, size_t size, bool flush);
62 void handleDataReadyForRead();
63 void handleDataReadyForWrite();
64
Austin Schuh9d823002019-04-14 12:53:17 -070065 int getFd() const {
66 return _fd;
67 }
Austin Schuh24adb6b2015-09-06 17:37:40 -070068
69 // From WebSocket.
70 virtual void send(const char* webSocketResponse) override;
71 virtual void send(const uint8_t* webSocketResponse, size_t length) override;
72 virtual void close() override;
73
74 // From Request.
75 virtual std::shared_ptr<Credentials> credentials() const override;
Austin Schuh9d823002019-04-14 12:53:17 -070076 virtual const sockaddr_in& getRemoteAddress() const override {
77 return _address;
78 }
Austin Schuh24adb6b2015-09-06 17:37:40 -070079 virtual const std::string& getRequestUri() const override;
Austin Schuh9d823002019-04-14 12:53:17 -070080 virtual Request::Verb verb() const override {
81 return Request::Verb::WebSocket;
82 }
83 virtual size_t contentLength() const override {
84 return 0;
85 }
86 virtual const uint8_t* content() const override {
87 return nullptr;
88 }
Austin Schuh24adb6b2015-09-06 17:37:40 -070089 virtual bool hasHeader(const std::string&) const override;
90 virtual std::string getHeader(const std::string&) const override;
Austin Schuh9d823002019-04-14 12:53:17 -070091 virtual Server& server() const override;
Austin Schuh24adb6b2015-09-06 17:37:40 -070092
93 void setLinger();
94
Austin Schuh9d823002019-04-14 12:53:17 -070095 size_t inputBufferSize() const {
96 return _inBuf.size();
97 }
98 size_t outputBufferSize() const {
99 return _outBuf.size();
100 }
Austin Schuh24adb6b2015-09-06 17:37:40 -0700101
Austin Schuh9d823002019-04-14 12:53:17 -0700102 size_t bytesReceived() const {
103 return _bytesReceived;
104 }
105 size_t bytesSent() const {
106 return _bytesSent;
107 }
Austin Schuh24adb6b2015-09-06 17:37:40 -0700108
109 // For testing:
Austin Schuh9d823002019-04-14 12:53:17 -0700110 std::vector<uint8_t>& getInputBuffer() {
111 return _inBuf;
112 }
Austin Schuh24adb6b2015-09-06 17:37:40 -0700113 void handleHixieWebSocket();
114 void handleHybiWebSocket();
115 void setHandler(std::shared_ptr<WebSocket::Handler> handler) {
116 _webSocketHandler = handler;
117 }
118 void handleNewData();
119
Austin Schuh9d823002019-04-14 12:53:17 -0700120
121 Connection(Connection& other) = delete;
122 Connection& operator=(Connection& other) = delete;
123
124
Austin Schuh24adb6b2015-09-06 17:37:40 -0700125private:
126 void finalise();
127 bool closed() const;
128
129 void closeWhenEmpty();
130 void closeInternal();
131
132 void handleHeaders();
133 void handleWebSocketKey3();
134 void handleWebSocketTextMessage(const char* message);
135 void handleWebSocketBinaryMessage(const std::vector<uint8_t>& message);
136 void handleBufferingPostData();
137 bool handlePageRequest();
138
139 bool bufferLine(const char* line);
140 bool bufferLine(const std::string& line);
141 bool flush();
142
143 bool handleHybiHandshake(int webSocketVersion, const std::string& webSocketKey);
144
145 // Send an error document. Returns 'true' for convenience in handle*() routines.
146 bool sendError(ResponseCode errorCode, const std::string& document);
147
148 // Send individual errors. Again all return true for convenience.
149 bool sendUnsupportedError(const std::string& reason);
150 bool send404();
151 bool sendBadRequest(const std::string& reason);
152 bool sendISE(const std::string& error);
153
Austin Schuh9d823002019-04-14 12:53:17 -0700154 void sendHybi(uint8_t opcode, const uint8_t* webSocketResponse,
155 size_t messageLength);
156 void sendHybiData(const uint8_t* webSocketResponse, size_t messageLength);
157
Austin Schuh24adb6b2015-09-06 17:37:40 -0700158
159 bool sendResponse(std::shared_ptr<Response> response);
160
161 bool processHeaders(uint8_t* first, uint8_t* last);
162 bool sendData(const std::string& type, const char* start, size_t size);
Austin Schuh9d823002019-04-14 12:53:17 -0700163 bool sendHeader(const std::string& type, size_t size);
164
165 // Delegated from ResponseWriter.
166 struct Writer;
167 void begin(ResponseCode responseCode, TransferEncoding encoding);
168 void header(const std::string& header, const std::string& value);
169 void payload(const void* data, size_t size, bool flush);
170 void finish(bool keepConnectionOpen);
171 void error(ResponseCode responseCode, const std::string& payload);
Austin Schuh24adb6b2015-09-06 17:37:40 -0700172
173 struct Range {
174 long start;
175 long end;
Austin Schuh9d823002019-04-14 12:53:17 -0700176 size_t length() const {
177 return end - start + 1;
178 }
Austin Schuh24adb6b2015-09-06 17:37:40 -0700179 };
180
181 bool parseRange(const std::string& rangeStr, Range& range) const;
182 bool parseRanges(const std::string& range, std::list<Range>& ranges) const;
183 bool sendStaticData();
184
Austin Schuh9d823002019-04-14 12:53:17 -0700185 ssize_t safeSend(const void* data, size_t size);
Austin Schuh24adb6b2015-09-06 17:37:40 -0700186
187 void bufferResponseAndCommonHeaders(ResponseCode code);
188
189 std::list<Range> processRangesForStaticData(const std::list<Range>& ranges, long fileSize);
190
191 std::shared_ptr<Logger> _logger;
Austin Schuh9d823002019-04-14 12:53:17 -0700192 ServerImpl& _server;
Austin Schuh24adb6b2015-09-06 17:37:40 -0700193 int _fd;
194 bool _shutdown;
195 bool _hadSendError;
196 bool _closeOnEmpty;
197 bool _registeredForWriteEvents;
198 sockaddr_in _address;
199 size_t _bytesSent;
200 size_t _bytesReceived;
201 std::vector<uint8_t> _inBuf;
202 std::vector<uint8_t> _outBuf;
203 std::shared_ptr<WebSocket::Handler> _webSocketHandler;
204 bool _shutdownByUser;
205 std::unique_ptr<PageRequest> _request;
Austin Schuh9d823002019-04-14 12:53:17 -0700206 std::shared_ptr<Response> _response;
207 TransferEncoding _transferEncoding;
208 unsigned _chunk;
209 std::shared_ptr<Writer> _writer;
Austin Schuh24adb6b2015-09-06 17:37:40 -0700210
Austin Schuh9d823002019-04-14 12:53:17 -0700211 void parsePerMessageDeflateHeader(const std::string& header);
212 bool _perMessageDeflate = false;
213 ZlibContext zlibContext;
214
215 void pickProtocol();
216
217 enum class State {
Austin Schuh24adb6b2015-09-06 17:37:40 -0700218 INVALID,
219 READING_HEADERS,
220 READING_WEBSOCKET_KEY3,
221 HANDLING_HIXIE_WEBSOCKET,
222 HANDLING_HYBI_WEBSOCKET,
223 BUFFERING_POST_DATA,
Austin Schuh9d823002019-04-14 12:53:17 -0700224 AWAITING_RESPONSE_BEGIN,
225 SENDING_RESPONSE_HEADERS,
226 SENDING_RESPONSE_BODY
Austin Schuh24adb6b2015-09-06 17:37:40 -0700227 };
228 State _state;
229
Austin Schuh9d823002019-04-14 12:53:17 -0700230 void writeChunkHeader(size_t size);
Austin Schuh24adb6b2015-09-06 17:37:40 -0700231};
232
Austin Schuh9d823002019-04-14 12:53:17 -0700233} // namespace seasocks