Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix TCPSocket constructor exception safety #112

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/sockets/TCPSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,29 @@ namespace eipScanner {
}
#endif

//once _sockedFd turns out to be a value not less than zero then
//we have to free it via a shutdown/close pair. Normally the destructor
//for the TCPSocket object would do that; however if a throw happens in this
//constructor then the destructor isn't called. Therefore we need to cause
//cleanup to happen ourselves in that case.
class socket_scope_cleanup {
private:
bool should_cleanup = true;
TCPSocket* socket_;
public:
socket_scope_cleanup(TCPSocket* socket):socket_(socket){}
~socket_scope_cleanup() {
if(should_cleanup) {
Logger(LogLevel::DEBUG) << "Close TCP socket fd=" << _sockedFd;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Logger(LogLevel::DEBUG) << "Close TCP socket fd=" << _sockedFd;
Logger(LogLevel::DEBUG) << "Close TCP socket fd=" << socket_->_sockedFd;

socket_->Shutdown();
socket_->Close();
}
}
void do_not_cleanup() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not called anywhere, which means the file descriptor is always cleaned up after the constructor is finished

should_cleanup = false;
}
} socket_scope_cleanup_instance{this};

// Set non-blocking
#if defined(__unix__) || defined(__APPLE__)
auto arg = fcntl(_sockedFd, F_GETFL, NULL);
Expand Down