Share socket (listen) between unrelated processes - c++

Running in Linux 3.9 kernel and later, I have an application X, which listens on a particular socket for connections. I want to write an unrelated application, Y, which tracks the number of attempts to connect to this socket, the source IP, etc.
Is it possible in c++ (ideally through Qt library) to share / monitor a socket already in use by an unrelated process? I found several StackOverflow questions which suggest forking to share the socket, but that's not possible in this case.

It is possible to transfer a file descriptor to another process, which behaves like a cross process dup(2). See Can I open a socket and pass it to another process in Linux for details. But this needs to be explicitly done, i.e. one process sends the file descriptor and another receives it. Thus the "unrelated" process must cooperate.
But a listen socket cannot be used for monitoring. The socket can only accept a connection but it is not possible to see if another process accepted a connection on the same socket, no matter if the sockets are shared with fork,threading or by file descriptor passing.
Given the right permissions and OS you can monitor the behavior of an application at the syscall level using the ptrace(2) or similar interface. There you could see if the application uses accept and what it returns. Or like suggested in a comment you can use packet capturing (tcpdump, raw sockets) to simply watch the traffic and deduct from a successful TCP handshake that some (unknown) process must have accepted the connection.

Related

multi way inter process communication

There are 10 processes in my machine and each should have the capability to communicate with each other.
Now the scenario is all the 10 processes should be in the listening state so that any process can communicate with it at any time. Again when required it should be able to pass a message to any of the processes.
I am trying to code it with C++ and unix tcp/udp sockets. However I don't understand how to structure it. Shall I use UDP or TCP, which would be better? How can a process listen and send data simultaneously.
I need help.
The decision of UDP vs TCP depends on your messages, whether or not they need to be reliably delivered, etc.
For pure TCP, each peer would have a TCP socket on which each process accepts connections from other peers (and each accept would result in a new socket). This new socket is bi directional and can be used for sending / recieving from one peer to another. With this solution, you would need some sort of discovery mechanism.
For UDP, it's much the same except you don't need the accept socket. You still need some form of discovery mechanism.
The discovery mechanism could either be another peer with a well known (via configuration, etc) address, or possibly you could use UDP broadcast for the discovery mechanism.
In terms of zeroMQ, which is a slightly higher level than raw sockets, you would have a single ROUTER socket on which you're listening and recieving data, and one DEALER socket per peer on which you're sending data.
No matter the solution, you would likely need a thread for handling the network connections using poll() or something like that, and as messages are received you need another thread (or thread pool) for handling the messages.
you can run each process as severer & span 9 more thread to connect other processes as client.
This question applies to any language, so the answer is not C++ related.
When given a choice, look for a library to have an easier communication (e.g. apache-thrift).
About TCP/UDP: TCP is typically slower but more reliable, so by default, go for TCP, but there might be reasons for choosing UDP, like streaming, multicast/broadcast,... Reliability might not be an issue when all processes are on the same board, but you might want to communicate with external processes later on.
A threaded process can use the same socket for sending and receiving without locks.
Also, you need some kind of scheme to find out to what port to send to reach a process and with TCP, you need to decide whether to use static connections or connect every time you want to send.
what you want to do seems to be message passing.
before trying to build it yourself, take a look at boost mpi

Multiple connections on the same port socket C++

I need to accept multiple connections to the same port.
I'm using socket in C++, i want to do something like the SSH do.
I can do an ssh user#machine "ls -lathrR /" and run another command to the same machine, even if the first one still running.
How can i do that?
Thanks.
What you want is a multithreaded socket server.
For this, you need a main thread that opens up a socket to listen to (and waits for incoming client connections). This has to go into a while loop of some sort.
Then, when a client connects to it, the accept() function will unblock and at that point you need to serve the client request by passing on the request to a thread that will deal with it.
The server side will loop back and wait for another connection whilst the previous thread carries on its task.
You can either create threads as you need, or use a thread pool which might be more efficient (saving on time initialising new threads).
Have a look here for some more details.
Look for multithreaded server socket on the web, specifically bind(), listen() and accept() from the server side.
You need to read up on ::listen() and ::accept().
The former will set up your socket for listening. You then need a loop (probably in its own thread) which uses ::accept() which will return each time a new connection arrives.
That loop should then spawn a new thread to which you should pass the file descriptor received from ::accept() and then handles all I/O on that socket from thereon.
Old question is old, but I feel no one who answered understood the OP's question.
You're misunderstanding how ssh works. When you send multiple commands/multiple connections to a server over ssh, there is actually only ONE program on the server you're connecting to that is receiving all those commands.
Sshd (the ssh daemon) runs on the server, and is a multithreaded socket server (see fduff's answer). This is the only program that listens on port 22, and handles all incoming ssh connections by itself.

How to pass OpenSSL socket to another process

I want to pass the SSL socket(along with its SSL session) to another process. Is this possible ?
In the non-SSL socket implementation, I use WSADuplicateSocket(Windows API) to get socket info and then send it to another process to create a duplicated socket.
How can I do this on SSL socket? Which information I has to pass to the second process to let them create the duplicated socket and continue the SSL session from the first process? Once the socket is passed to the second process, the first process will close its socket handle.
No, it is not possible. A socket is an OS object, which is why you can duplicate the socket handle in another process. OpenSSL, on the other hand, is an application-level library that just sits on top on whatever connection framework you decide to use for the physical communication. So you cannot duplicate the SSL structures and state machine that are attached to the original socket, as it cannot be shared across process boundaries.

Multithreaded Server Issue

I am writing a server in linux that is supposed to serve an API.
Initially, I wanted to make it Multi-threaded on a single port, meaning that I'd have multiple threads working on various request received on a single port.
One of my friends told me that it not the way it is supposed to work. He told me that when a request is received, I first have to follow a Handshake procedure, create a thread that is listening to some other port dedicated to the request and then redirect the requested client to the new port.
Theoretically, it's very interesting but I could not find any information on how to implement the handshake and do the redirection. Can someone help?
If I'm not wrong in interpreting your responses, once I create a multithreaded server with a main thread listening to a port, and creates a new thread to handle requests, I'm essentially making it multithreaded on a single port?
Consider the scenario where I get a large number of requests every second. Isn't it true that every request on the port should now wait for the "current" request to complete? If not, how would the communication still be done: Say a browser sends a request, so the thread handling this has to first listen to the port, block it, process it, respond and then unblock it.
By this, eventhough I'm having "multithreads" , all I'm using is one single thread at a time apart from the main thread because the port is being blocked.
What your friend told you is similar to passive FTP - a client tells the server that it needs a connection, the server sends back the port number and the client creates a data connection to that port.
But all you wanted to do is a multithreaded server. All you need is one server socket listening and accepting connections on a given port. As soon as the automatic TCP handshake is finished, you'll get a new socket from the accept function - that socket will be used for communication with the client that has just connected. So now you only have to create a new thread, passing that client socket to the thread function. In your server thread, you will then call accept again in order to accept another connection.
TCP/IP does the handshake, if you can't think of any reason to do a handshake than your application does not demand it.
An example of an application specific handshake could be for user authentication.
What your colleague is suggesting sounds like the way FTP works. This is not a good thing to do -- the internet these days is more or less used for protocols which use a single port, and having a command port is bad. One of the reasons is because statefull firewalls aren't designed for multi-port applications; they have to be extended for each individual application that does things this way.
Look at ASIO's tutorial on async TCP. There one part accept connections on TCP and spawns handlers that each communicate with a single client. That's how TCP-servers usually work (including HTTP/web, the most common tcp protocol.)
You may disregard the asynchronous stuff of ASIO if you're set on creating a thread per connection. It doesn't apply to your question. (Going fully async and have one worker-thread per core is nice, but it might not integrate well with the rest of your environment.)

Determine if device is connected/disconnected to RS232 port without opening the port

I"m working on a C++ Win32 application for which I'm trying to essentially "auto detect" if a device has been plugged into one of the RS232 ports and then if it has been disconnected.
The checking for a connected device is easy enough because my use case allows me to assume that this particular thread will be the first to try to initiate communication with the port. I'm able to scan the available ports every minute or so and once I've found a port with the device on it I flag that port has having a device, close the port, then set an event so that the process that actually will use the device knows it can now connect on that port.
The disconnect detect is where I run into trouble. When I'm scanning for connected devices I can actually send data to the port to be sure that, if there is a device, it's the specific device I'm looking for. But once it's connected, that port will already be open by the other process and I can no longer open that port from the detect thread. So I am looking for a way to either open the port in a "listen mode" or something like that so I can just see if the device is still there.
I briefly came across something about watching the DSR or DTR line or something...but couldn't find any more or how to actually do it.
Any suggestions?
Edit: Looks like I need to clarify a little more... For detecting the disconnect, I cannot send data to the RS232 port in any way. Also, I cannot assume that another application actually has the port open. The device may be physically connected, but without and open connection...but I still can't risk sending data to it. I was hoping there was a way to just check that there was still power on that port or something like that.
It depends on the connected hardware whether there will be a change in the modem state registers when you disconnect the hardware, but if there is then you could check the state of for example the CTS or DSR line using the GetCommModemStatus() function.
There is however the problem that you need a file handle to the COM port to call any API function, and this is exclusive as the documentation of CreateFile() states:
The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be zero (exclusive access)
So you can not open the COM port to watch the line state while another process has the port opened for communication.
There are ways to do this, but they involve a driver. SysInternals has the Portmon tool, and a Google search will turn up some companies selling software for sharing COM port access between applications, but AFAIK simultaneous access is impossible using the standard API.
Sounds like it might be a good idea to have that process that will give notification of connected and disconnected events also relay the data to the other process. Have your app work in layers such that there is a process that takes control of the RS232 connection and sends your upper layer app events: connected, disconnected, data available, etc.
I have done applications like this and its not really a language specific problem (unless you have no serial port access in your language).
My preferred solution has always been to have one thread per port, according to your configuration and the thread maintains a state which is accessible from some sort of controller.
The default condition is that the thread polls the port every few seconds and while there is no answer assume there is no device connected. Once a device seems to respond, change the state to indicate this is so.
I designed an application that had a number of queues: One with disconnected threads, one with connected, but idle threads and another with connected and busy threads. The controller moved threads between queues as they changed state.