boost asio bind: bad file descriptor - c++

I'm creating multithreading application, that will work as "router" but on application layer.
The software will run on multiple hosts with multiple network interfaces.
In my application in one thread runs server, that accepts every connection on every interface and pass it to another worker-thread, which decide if the message will be forwarded and which interface schould be used.
I decided to use boost-asio.
So summarizing: incoming messages only in server (only here the read function), outgoing depending on typ through different gateway (only send function). The gateway should always connect to one interface, therefore I try to use the bind method.
But I get an exception: "bind: Bad file descriptor"
Here is the code snippet:
try
{
MY_LOG(trace) << "Connecting on IFace" << routingConf->connections[interface].ipSource;
boost::asio::io_service *svc = new boost::asio::io_service();
this->socket = new boost::asio::ip::tcp::socket(*svc);
boost::asio::ip::tcp::endpoint localEndpoint =
ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 0);
boost::asio::ip::tcp::endpoint remoteEndpoint = ip::tcp::endpoint(
boost::asio::ip::address::from_string("127.0.0.1"), port);
this->socket->bind(localEndpoint);
MY_LOG(trace) << "socket success";
this->socket->connect(remoteEndpoint);
} catch (std::exception &e)
{
MY_LOG(fatal) << e.what();
}
I tried different settings for local and remote endpoint. The server is already running in another thread, and if I not perform the binding operation, it is getting the sent message from send function (not included here).

socket::bind throws bad file descrption when socket was created but it is not open. You used constructor
basic_stream_socket(
boost::asio::io_service & io_service);
which constructs socket without opening it.
You should call open method before calling bind or use one of overloaded version of socket constructor which creates and also opens socket.

Related

Reconnect ZMQ_ROUTER socket with custom identity

I'm writing a code which uses routers' identities to dynamically manage the peers.
To do that, I build the messages with target identity in the first frame, and then I send them trough a router socket to the appropriate peer. If a peer with that identity doesn't exist, I'll create a new one.
In code is something like that:
Main.cpp
zmq::socket_t sendSocket(*_pZmqContext.get(), ZMQ_ROUTER);
// It forces to throw an exception when peer doesn't exists, so I can create a new one.
sendSocket.setsockopt(ZMQ_ROUTER_MANDATORY, 1);
sendSocket.bind("inproc://processors");
...
try
{
...
isSuccess = message2send.send(sendSocket);
...
}
catch (zmq::error_t& ex)
{
if (ex.num() == EHOSTUNREACH)
{
// new peer is created (see OtherRouter.cpp)
...
}
}
...
OtherRouter.cpp
// This is how reader sockets are created...
zmq::socket_t reader(*_pZmqContext, ZMQ_ROUTER);
reader.setsockopt(ZMQ_ROUTING_ID,(std::byte *)&newIdentityValueForSocket[0],sizeof(newIdentityValueForSocket)); ;
reader.connect("inproc://processors");
assert(reader.connected());
...
This works fine, but I need some extra.
Some peers might be destroyed due to inactivity, and being recreated later, when activity is back.
When this happen, code is not working as expected. Even the peer is created successfully, I'm getting EHOSTUNREACH exception. It's like sockets can't communicate again..
So, It seems the sender socket knows that the older peer has been disconnected, but It can't connect to new one.
Any suggestion about how to solve it ?
Thanks!

Segmentation fault in handlers with shared_ptr's

I am trying to make a proxy that works properly only for the first session in one execution of app. It catches SIGSEGV trying to handle the second one.
It works next way:
client connects
proxy connects to end server (unique connection for each session)
proxy sends data to server, gets handled data from server and sends handled data to client
proxy breaks connection with server and client
The problem is when we start the app and the first client tries to use proxy, it works fine (let it be clients connect to proxy consistently e.g. first one got its data, disconnection occured and only then the second one connects). But when the second one tries to connect after this, execution can not even reach the handleAccept and catches SIGSEGV in __atomic_add function in atomicity.h (I am working in Linux).
I can not understand either I make handlers incorrectly, use shared_ptr's incorrectly, or both.
run is called once after creating Proxy object to make it accept and handle client connections:
void Proxy::run() // create the very first session and keep waiting for other connections
{
auto newSession = std::make_shared<Session>(ioService_);
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error) // handler is made according to boost documentation
{
handleAccept(newSession, error);
}
);
ioService_.run();
}
handleAccept does almost the same thing but also makes session start transferring data between client and end server:
void Proxy::handleAccept(std::shared_ptr<Session> session, const boost::system::error_code &error) // handle the new connection and keep waiting other ones
{
if (!error)
{
session->connectToServer(serverEndpoint_);
session->run(); // two more shared_ptr's to session are appeared here and we just let it go (details are further)
}
auto newSession = std::make_shared<Session>(ioService_);
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
}
Session contains two Socket objects (server and client) each of which has shared_ptr to it. When each of them will have done all actions or some error will have occured, they reset their shared_ptr's to session so it is deallocated.
Why you use/catch local variable by reference in handleAccept(...) ?:
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
Would you like to use:
acceptor_.async_accept(
newSession->getClientSocket(),
[this, newSession](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
The lambda will be run after function will be completed, and local variable newSession will be destroied before that.

"Already Open" error on new connection in Asio

I'm using the non-Boost version of Asio and have made a TCP server based on the code at http://think-async.com/Asio/asio-1.11.0/doc/asio/tutorial/tutdaytime3.html
I can establish a connection to the server just fine, but only the first time. If I disconnect my client and then attempt to connect again, Asio passes an "Already Open" error to my accept handler. As you can see from the code, before a connection is accepted, a new instance of the tcp_connection class is created. I'm not sure why I'm getting this error, even though it's a completely separate instance whose socket shouldn't already be open. Any help would be greatly appreciated.
Thanks in advance.
EDIT:
Here's the server class:
http://pastebin.com/yvZmFQvA
And the client class (equivalent to the tcp_connection class in the example):
http://pastebin.com/LDhr2nZz
This might be because you are not correctly closing the socket upon disconnection. As a disconnection might happen due to an exception that can't be handled (such as signal 9), you need a solution to work even if the process didn't die gracefully...
I bealive this can solve it:
Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?
You have:
void server::do_accept() {
//client::pointer con = client::create(acceptor_.get_executor().context());
client::pointer con = client::create(acceptor_.get_io_service());
acceptor_.async_accept(con->socket(),
std::bind(&server::on_accepted, this, con,
std::placeholders::_1));
}
Client classes don't belong in the server. This doesn't make sense.
Your source material has:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_executor().context());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
asio::placeholders::error));
}

boost asio for sync server keeping TCP session open (with google proto buffers)

I currently have a very simple boost::asio server that sends a status update upon connecting (using google proto buffers):
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service,tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
...
std::stringstream message;
protoMsg.SerializeToOstream(&message);
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message.str()), ignored_error);
}
}
catch (std::exception& e) { }
I would like to extend it to first read after accepting a new connection, check what request was received, and send different messages back depending on this message. I'd also like to keep the TCP connection open so the client doesn't have to re-connect, and would like to handle multiple clients (not many, maybe 2 or 3).
I had a look at a few examples on boost asio, namely the async time tcp server and the chat server, but both are a bit over my head tbh. I don't even understand whether I need an async server. I guess I could just do a read after acceptor.accept(socket), but I guess then I wouldn't keep on listening for further requests. And if I go into a loop I guess that would mean I could only handle one client. So I guess that means I have to go async? Is there a simpler example maybe that isn't 250 lines of code? Or do I just have to bite my way through those examples? Thanks
The examples you mention from the Boost.Asio documentation are actually pretty good to see how things work. You're right that at first it might look a bit difficult to understand, especially if you're new to these concepts. However, I would recommend that you start with the chat server example and get that built on your machine. This will allow you to closer look into things and start changing things in order to learn how it works. Let me guide you through a few things I find important to get started.
From your description what you want to do, it seems that the chat server gives you a good starting point as it already has similar pieces you need. Having the server asynchronous is what you want as you then quite easily can handle multiple clients with a single thread. Nothing too complicated from the start.
Simplified, asynchronous in this case means that your server works off a queue, taking a handler (task) and executes it. If there is nothing on the queue, it just waits for something to be put on the queue. In your case that means it could be a connect from a client, a new read of a message from a client or something like this. In order for this to work, each handler (the function handling the reaction to a particular event) needs to be set up.
Let me explain a bit using code from the chat server example.
In the server source file, you see the chat_server class which calls start_accept in the constructor. Here the accept handler gets set up.
void start_accept()
{
chat_session_ptr new_session(new chat_session(io_service_, room_)); // 1
acceptor_.async_accept(new_session->socket(), // 2
boost::bind(&chat_server::handle_accept, this, new_session, // 3
boost::asio::placeholders::error)); // 4
}
Line 1: A chat_session object is created which represents a session between one client and the server. A session is created for the accept (no client has connected yet).
Line 2: An asynchronous accept for the socket...
Line 3: ...bound to call chat_server::handle_accept when it happens. The session is passed along to be used by the first client which connects.
Now, if we look at the handle_accept we see that upon client connect, start is called for the session (this just starts stuff between the server and this client). Lastly a new accept is put outstanding in case other clients want to connect as well.
void handle_accept(chat_session_ptr session,
const boost::system::error_code& error)
{
if (!error)
{
session->start();
}
start_accept();
}
This is what you want to have as well. An outstanding accept for incoming connections. And if multiple clients can connect, there should always be one of these outstanding so the server can handle the accept.
How the server and the client(s) interact is all in the session and you could follow the same design and modify this to do what you want. You mention that the server needs to look at what is sent and do different things. Take a look at chat_session and the start function which was called by the server in handle_accept.
void start()
{
room_.join(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(
&chat_session::handle_read_header, shared_from_this(),
boost::asio::placeholders::error));
}
What is important here is the call to boost::asio::async_read. This is what you want too. This puts an outstanding read on the socket, so the server can read what the client sends. There is a handler (function) which is bound to this event chat_session::handle_read_header. This will be called whenever the server reads something on the socket. In this handler function you could start putting your specific code to determine what to do if a specific message is sent and so on.
What is important to know is that whenever calling these asynchronous boost::asio functions things will not happen within that call (i.e. the socket is not read if you call the function read). This is the asynchronous aspect. You just kind of register a handler for something and your code is called back when this happens. Hence, when this read is called it will immediately return and you're back in the handle_accept for the server (if you follow how things get called). And if you remember there we also call start_accept to set up another asynchronous accept. At this point you have two outstanding handlers waiting for either another client to connect or the first client to send something. Depending on what happens first, that specific handler will be called.
Also what is important to understand is that whenever something is run, it will run uninterrupted until everything it needs to do has been done. Other handlers have to wait even if there is are outstanding events which trigger them.
Finally, in order to run the server you'll need the io_service which is a central concept in Asio.
io_service.run();
This is one line you see in the main function. This just says that the thread (only one in the example) should run the io_service, which is the queue where handlers get enqueued when there is work to be done. When nothing, the io_service just waits (blocking the main thread there of course).
I hope this helps you get started with what you want to do. There is a lot of stuff you can do and things to learn. I find it a great piece of software! Good luck!
In case anyone else wants to do this, here is the minimum to get above going: (similar to the tutorials, but a bit shorter and a bit different)
class Session : public boost::enable_shared_from_this<Session>
{
tcp::socket socket;
char buf[1000];
public:
Session(boost::asio::io_service& io_service)
: socket(io_service) { }
tcp::socket& SocketRef() { return socket; }
void Read() {
boost::asio::async_read( socket,boost::asio::buffer(buf),boost::asio::transfer_at_least(1),boost::bind(&Session::Handle_Read,shared_from_this(),boost::asio::placeholders::error));
}
void Handle_Read(const boost::system::error_code& error) {
if (!error)
{
//read from buffer and handle requests
//if you want to write sth, you can do it sync. here: e.g. boost::asio::write(socket, ..., ignored_error);
Read();
}
}
};
typedef boost::shared_ptr<Session> SessionPtr;
class Server
{
boost::asio::io_service io_service;
tcp::acceptor acceptor;
public:
Server() : acceptor(io_service,tcp::endpoint(tcp::v4(), 13)) { }
~Server() { }
void operator()() { StartAccept(); io_service.run(); }
void StartAccept() {
SessionPtr session_ptr(new Session(io_service));
acceptor.async_accept(session_ptr->SocketRef(),boost::bind(&Server::HandleAccept,this,session_ptr,boost::asio::placeholders::error));
}
void HandleAccept(SessionPtr session,const boost::system::error_code& error) {
if (!error)
session->Read();
StartAccept();
}
};
From what I gathered through trial and error and reading: I kick it off in the operator()() so you can have it run in the background in an additional thread. You run one Server instance. To handle multiple clients, you need an extra class, I called this a session class. For asio to clean up dead sessions, you need a shared pointer as pointed out above. Otherwise the code should get you started.

How to connect/disconnect from a server?

I am using the latest version of boost and boost.asio.
I have this class:
enum IPVersion
{
IPv4,
IPv6
};
template <IPVersion version = IPv4>
class Connection
{
private:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver;
boost::asio::ip::tcp::resolver::query query;
boost::asio::ip::tcp::resolver::iterator iterator;
public:
Connection(std::string host, std::string port);
virtual void connect() { iterator = resolver.resolve(query); } // Is this the moment where the client actually connects?
virtual void disconnect() { /* what goes in here? */ }
};
Should I call io_service::stop() and then on my Connection::connect() call io_service::reset() first before I resolve the query?
Generally, once you've made a call to io_service::run, there's often few reasons to call io_service::stop or io_service::reset.
In your code above, the connect method is not going to actively establish a connection - tcp::resolver::resolve merely turns a query (such as a hostname, or an IP address, etc.) into a TCP endpoint which can be used to connect a socket. You typically need to dereference an iterator returned by resolver::resolve and pass it to a boost::asio::ip::tcp::socket object's connect method (or one of the asynchronous varieties) to connect an endpoint.
The Asio tutorials have a good example of this. See the first synchronous TCP daytime server example here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime1.html. Note that the code first runs:
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
to turn a query object into a TCP endpoint, and then:
socket.connect(*endpoint_iterator++, error);
to connect a socket object on that endpoint.
As for what should go in your disconnect method, that's entirely dependent on the application. But usually you'll need to keep track of an active connection by encapsulating a socket object, which you can close as necessary when you call disconnect. For an example of this, have a look at the tutorial titled "Daytime 3 - An Asynchronous TCP daytime server" here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime3.html