reSIProcate
SIP stack, Dialog Usage Manager and related libraries
Loading...
Searching...
No Matches
TlsConnection.cxx
Go to the documentation of this file.
1#if defined(HAVE_CONFIG_H)
2#include "config.h"
3#endif
4
5#ifdef USE_SSL
6
7#ifdef WIN32
8#pragma warning(disable : 4267)
9#endif
10
11#include "TlsConnection.hxx"
12#include <vector>
13#include "ConnectionManager.hxx"
14#include "RequestHandler.hxx"
15#include <rutil/Logger.hxx>
16#include "ReTurnSubsystem.hxx"
17
18#define RESIPROCATE_SUBSYSTEM ReTurnSubsystem::RETURN
19
20using namespace std;
21using namespace resip;
22
23namespace reTurn {
24
25TlsConnection::TlsConnection(asio::io_context& ioService,
26 ConnectionManager& manager,
27 RequestHandler& handler,
28 asio::ssl::context& context)
29 : AsyncTlsSocketBase(ioService, context, false /* not needed in server */),
30 mConnectionManager(manager),
31 mRequestHandler(handler)
32{
33}
34
36{
37 DebugLog(<< "TlsConnection destroyed.");
38}
39
40ssl_socket::lowest_layer_type&
42{
43 return mSocket.lowest_layer();
44}
45
46void
48{
49 DebugLog(<< "TlsConnection started.");
50
52}
53
54void
56{
58 asio::error_code ec;
59 //mSocket.shutdown(ec); // !slg! note: this fn gives a stack overflow since ASIO 1.0.0 for some reason
60 mSocket.lowest_layer().close(ec);
61 if(ec)
62 {
63 WarningLog(<< "TlsConnection shutdown, error=" << ec.value() << "-" << ec.message());
64 }
65}
66
67void
69{
70 mConnectionManager.stop(shared_from_this());
71}
72
73void
75{
76 DebugLog(<< "TlsConnection handshake completed.");
77 asio::error_code ec;
78 mLocalAddress = mSocket.lowest_layer().local_endpoint().address();
79 mLocalPort = mSocket.lowest_layer().local_endpoint().port();
80 // Closed if it goes TcpConnectionIdleTimeout without receiving anything while it carries no
81 // allocation
82 startIdleTimer(mRequestHandler.getConfig().mTcpConnectionIdleTimeout, [this]() { return !mTurnAllocationManager.empty(); });
84}
85
86void
88{
89 WarningLog(<< "TlsConnection handshake failure, error=" << e.value() << "-" << e.message());
90 close();
91}
92
93void
94TlsConnection::onReceiveSuccess(const asio::ip::address& address, unsigned short port, const std::shared_ptr<DataBuffer>& data)
95{
97 if (data->size() > 4)
98 {
99 /*
100 std::cout << "Read " << bytesTransferred << " bytes from tls socket (" << address.to_string() << ":" << port << "): " << std::endl;
101 cout << std::hex;
102 for(int i = 0; i < data->size(); i++)
103 {
104 std::cout << (char)(*data)[i] << "(" << int((*data)[i]) << ") ";
105 }
106 std::cout << std::dec << std::endl;
107 */
108
109 if(((*data)[0] & 0xC0) == 0) // Stun/Turn Messages always have bits 0 and 1 as 00 - otherwise ChannelData message
110 {
111 // Try to parse stun message
113 StunTuple(StunTuple::TLS, address, port),
114 (char*)&(*data)[0], data->size());
115 if(request.isValid())
116 {
117 StunMessage response;
119
120 switch(result)
121 {
123 // No response to send - just receive next message
125 return;
129 // These only happen for UDP server for RFC3489 backwards compatibility
130 resip_assert(false);
131 break;
133 default:
134 break;
135 }
136 constexpr size_t RESPONSE_BUFFER_SIZE = 1024;
137 const auto buffer = allocateBuffer(RESPONSE_BUFFER_SIZE);
138 unsigned int responseSize;
139 responseSize = response.stunEncodeMessage((char*)buffer->data(), RESPONSE_BUFFER_SIZE);
140 buffer->truncate(responseSize); // set size to real size
141
142 doSend(response.mRemoteTuple, buffer);
143 }
144 else
145 {
146 WarningLog(<< "Received invalid StunMessage. Dropping.");
147 }
148 }
149 else // ChannelData message
150 {
151 unsigned short channelNumber;
152 memcpy(&channelNumber, &(*data)[0], 2);
153 channelNumber = ntohs(channelNumber);
154
156 channelNumber,
158 StunTuple(StunTuple::TLS, address, port),
159 data);
160 }
161 }
162 else
163 {
164 WarningLog(<< "Not enough data for stun message or framed message. Closing connection.");
165 close();
166 return;
167 }
168
170}
171
172void
173TlsConnection::onReceiveFailure(const asio::error_code& e)
174{
175 if(e != asio::error::operation_aborted)
176 {
177 InfoLog(<< "TlsConnection::onReceiveFailure: " << e.value() << "-" << e.message());
178
179 close();
180 }
181}
182
183void
187
188void
189TlsConnection::onSendFailure(const asio::error_code& error)
190{
191 if(error != asio::error::operation_aborted)
192 {
193 InfoLog(<< "TlsConnection::onSendFailure: " << error.value() << "-" << error.message());
194 close();
195 }
196}
197
198}
199
200#endif
201
202/* ====================================================================
203
204 Copyright (c) 2008-2026 SIP Spectrum, Inc. https://www.sipspectrum.com
205 Copyright (c) 2007-2008, Plantronics, Inc.
206 All rights reserved.
207
208 Redistribution and use in source and binary forms, with or without
209 modification, are permitted provided that the following conditions are
210 met:
211
212 1. Redistributions of source code must retain the above copyright
213 notice, this list of conditions and the following disclaimer.
214
215 2. Redistributions in binary form must reproduce the above copyright
216 notice, this list of conditions and the following disclaimer in the
217 documentation and/or other materials provided with the distribution.
218
219 3. Neither the name of Plantronics nor the names of its contributors
220 may be used to endorse or promote products derived from this
221 software without specific prior written permission.
222
223 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
224 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
225 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
226 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
227 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
228 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
229 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
230 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
231 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
232 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
233 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
234
235 ==================================================================== */
#define DebugLog(args_)
Definition Logger.hxx:128
#define InfoLog(args_)
Definition Logger.hxx:131
#define WarningLog(args_)
Definition Logger.hxx:134
#define resip_assert(x)
This file needs to work for both C and C++ code.
static std::shared_ptr< DataBuffer > allocateBuffer(size_t size)
Utility API.
virtual void doSend(const StunTuple &destination, unsigned short channel, const std::shared_ptr< DataBuffer > &data, const std::size_t bufferStartPos=0)
Use these if you already operating within the ioService thread.
void startIdleTimer(unsigned int timeoutSeconds, std::function< bool()> inUse)
For server connections (TcpConnectionIdleTimeout): the connection is closed, with close(),...
asio::ssl::stream< asio::ip::tcp::socket > mSocket
void doHandshake(unsigned int timeoutSeconds=0)
Starts the server side handshake.
Manages open connections so that they may be cleanly stopped when the server needs to shut down,...
void stop(ConnectionPtr c)
Stop the specified connection.
unsigned long mTlsHandshakeTimeout
unsigned long mTcpConnectionIdleTimeout
The common handler for all incoming requests.
void processTurnData(TurnAllocationManager &turnAllocationManager, unsigned short channelNumber, const StunTuple &localTuple, const StunTuple &remoteTuple, const std::shared_ptr< DataBuffer > &data)
const ReTurnConfig & getConfig()
ProcessResult processStunMessage(AsyncSocketBase *turnSocket, TurnAllocationManager &turnAllocationManager, StunMessage &request, StunMessage &response, bool isRFC3489BackwardsCompatServer=false)
Process a received StunMessage, and produce a reply Returns true if the response message is to be sen...
unsigned int stunEncodeMessage(char *buf, unsigned int bufLen)
virtual void onServerHandshakeFailure(const asio::error_code &e)
ssl_socket::lowest_layer_type & socket()
Get the socket associated with the connection.
virtual void onSendSuccess()
Handle completion of a send operation.
virtual void stop()
Stop all asynchronous operations associated with the connection.
virtual void onServerHandshakeSuccess()
Handle completion of a handshake operation.
unsigned short mLocalPort
virtual void onReceiveFailure(const asio::error_code &e)
TurnAllocationManager mTurnAllocationManager
Manages turn allocations.
RequestHandler & mRequestHandler
The handler used to process the incoming request.
virtual void onReceiveSuccess(const asio::ip::address &address, unsigned short port, const std::shared_ptr< DataBuffer > &data)
Handle completion of a receive operation.
asio::ip::address mLocalAddress
virtual void close()
Override close fn in AsyncTcpSocketBase so that we can remove ourselves from connection manager.
ConnectionManager & mConnectionManager
The manager for this connection.
virtual void start()
Start the first asynchronous operation for the connection.
virtual void onSendFailure(const asio::error_code &e)
dcm! – add UnusedChecking(_enum) below;