I am facing issue with c++ service which uses port 30015.It runs fine,but sometime it fails to start as the port 30015 is occupied and bind fails with error WSAEADDRINUSE.
I ran netstat command to know the port status
netstat -aon | findstr 30015
Output:
TCP 0.0.0.0:30015 0.0.0.0 LISTENING 6740
I checked the PID 6740 in task manager,this PID is not be taken by an process.
After searching in the net, I used TCPVIEW to see the status of the port. TCPView is showing port in listening mode and process name is "non-existance".
Application basically compress,decompress the file using 7za. Application listen on 30015 port for request and than create a child process and pass the commandline to run 7za command to compress and decompress file.
Here child process doesn't uses socket. Server runs on the main thread and listen on port 30015. This problem comes after restart of the server.
Here child process does not use socket as such. Do I need to make bInheritHandle = FALSE ?
Are you sure? This all sounds very confused. It's not possible for netstat to show a socket in the LISTEN state but for there to be no process -- especially if it shows the pid! You're confused because the process simply exited by the time you looked in Task Manager. All TCP connections in netstat are associated with a running process (except for unusual cases like TIME-WAIT sockets). So, find out which process has the socket open.
Secondly, I think you're trying to say that using bInheritHandles=TRUE as an argument to CreateProcess can lead to handle leaks. Only you have your code -- why not just look at the handles in your child and see if you do have a leak? It is only possible to use bInheritHandles=TRUE with great discipline, in the hands of novice programmers it will only lead to bugs. Create a named pipe with a suitable security descriptor, pass the name on the commandline to the child, and connect back, rather than using handle inheritance which is much too coarse-grained.
Finally, just to make sure, you do know to bind listening sockets with SO_REUSEADDR to prevent conflicting with active sockets using the same port? (SO_REUSEADDR still won't let two passive sockets be created on the same address/port combination, although it is a bit broken on Windows.)
Yes this can happen on Windows. If you've created a child process that inherits handles from the parent process then that includes TCP server sockets in the LISTEN state that will always be listed as owned by the parent PID even after that PID has died.
These sockets will disappear when all child processes that you spawned have exited, causing the reference count on their handles to reach zero.
From a security standpoint you should not use inter-process handle-inheritance, particularly when launching a 3rd part application, unless you have a good reason to need the feature.
Related
How do I close tcp v4 and tcp v6 connections on Windows? I don't want to kill the entire process that has the open connection as this obviously will kick everyone else off that process. I need to do this from a separate process, and so will not have access to socket handles, etc. I am using Windows API to get tcp table, etc. so I know which connections are active.
One way might be to enumerate all open handles on the system, or at least the open handles of a given target process, until you find the SOCKET handle you are interested in (see HOWTO: Enumerate handles, Socket Handles, and C++ Get Handle of Open Sockets of a Program - though I'm not sure how you would be able to retrieve the IP/Port pairs of a SOCKET to compare to the active connection you are interested in, without injecting remote getsockname()/getpeername() calls into the owning process of the SOCKET).
Once you have found the SOCKET handle you want, you can then close it by using DuplicateHandle() with the DUPLICATE_CLOSE_SOURCE flag 1.
1: This is how the "Close Handle" feature in Process Explorer works.
Since I'm using C#, I cannot PInvoke SetTcpEntry, even as administrator with an app.manifest file, it always sends a 317 error. So I created a C++ .exe to close a comma separated list of ipv4 addresses on the command line using SetTcpEntry, works fine even without an app.manifest file. That solves kicking ipv4 connections.
I tried using the get handles approach with NtQuerySystemInformation but never could get it working quite right, and it is a private mostly undocumented API and seems unsafe to use.
So, for ipv6, I am using windivert and injecting RST flag to ipv6 packets with certain ip addresses. It is as simple as setting the RST flag of an incoming packet before sending it on through with windivert. The downside is, if the client never sends another packet, the ipv6 socket still stays open indefinitely.
Perhaps someday Microsoft will add a SetTcpEntry6 function, but until then this appears to be the only realistic way.
UPDATE 2022-05-01, found this gem at https://www.x86matthew.com/view_post?id=settcpentry6
I made a UDP server class and my program creates a process (running in the background). It is a command line utility, and so running 'udpserver.exe start' would bind the socket and begin a blocking recvfrom() call inside a for(;;) loop.
What is the best way to safely and 'gracefully' stop the server?
I was thinking about 'udpserver.exe stop' would send a udp msg such as 'stop' and the ongoing process from 'udpserver.exe start' would recognize this msg, break from the loop, and clean up (closesocket/wsacleanup).
Also, is just killing the process not a good idea?
Why are you running the UDP server as an external process instead of as a worker thread inside of your main program? That would make it a lot easier to manage the server. Simple close the socket, which will abort a blocked recvfrom(), thus allowing the thread to terminate itself.
But if you must run the UDP server in an external process, personally I would just kill that process, quick and simple. But if you really want to be graceful about it, you could make the server program handle CTRL-BREAK via SetConsoleCtrlHandler() so it knows when it needs to close its socket, stopping recvfrom(). Then you can have the main program spawn the server program via CreateProcess() with the CREATE_NEW_PROCESS_GROUP flag to get a group ID that can then be used to send CTRL-BREAK to the server process via GenerateConsoleCtrlEvent() when needed.
I have processes that after started, bind to an address and port. These processes are run in screen using exec so that the screen closes when the child process closes.
When killing the process, I use kill -9 PID, but sometimes the screen ends, yet when I restart the process, the old process is still using the port, and I have to terminate the process again.
I've also read that SIGKILL leaves sockets open, stale memory, random resources in use, so I turned to just plain kill PID, which is a SIGTERM.
Is a SIGTERM guaranteed to allow the process to unbind from the address and port, or is there a better alternative?
If you SIGKILL all the processes that keep a listening port open, it is guaranteed to close.
However, it might not close for a few minutes, while it's in the TIME_WAIT state, as required by the TCP specification (to let listening clients know the port is closed in case they miss the original closing packet).
Well behaved servers will open the socket with the option SO_REUSEADDR, allowing it to reclaim the same port on restart immediately, but this is application specific. Without it, the port will appear to be in use for a few minutes.
I want a method of finding out what process opened what port without the aid of an external application. I.e. no netstat or other tools like it.
You need to use the IP helper functions. More specifically GetExtendedTcpTable and GetExtendedUdpTable.
For example, for GetExtendedUdpTable, you can pass in MIB_UDPTABLE_OWNER_PID as the TableClass and you will be able to receive the PID of the process that issued the call to bind for the UDP endpoint.
I am trying to reverse engineer a third-party TCP client / server Windows XP, SP 3 app for which I have no source available. My main line of attack is to use WireShark to capture TCP traffic.
When I issue a certain GUI command on the client side, the client creates a TCP connection to the server, sends some data, and tears down the connection. The server port is 1234, and the client port is assigned by the OS and therefore varies.
WireShark is showing that the message corresponding to the GUI command I issued gets sent twice. The two messages bear a different source port, but they have the same destination port (1234, as mentioned previosuly).
The client side actually consists of several processes, and I would like to determine which processes are sending these messages. These processes are long-lived, so their PIDs are stable and known. However, the TCP connections involved are transient, lasting only a few milliseconds or so. Though I've captured the client-side port numbers in WireShark and though I know all of the PIDs involved, the fact the connections are transient makes it difficult to determine which PID opened the port. (If the connections were long-lived, I could use netstat to map port numbers to PIDs.) Does anybody have any suggestions on how I can determine which processes are creating these transient connections?
I can think of two things:
Try sysinternals' tcpview program. It gives a detailed listing of all tcp connections opened by all the processes in the system. If a process creates connections, you will be able to see them flash (both connect and disconnect are flashed) in tcpview and you will know which processes to start looking into.
Try running the binary under a debugger. Windbg supports multi-process debugging (so does visual studio I think). You may have only export symbols to work with but that should still work for calls made to system dlls. Try breaking on any suspected windows APIs you know will be called by the process to create the connections. MSDN should have the relevant dlls for most system APIs documented.
Start here... post a follow-up if you get stuck again.
I ended up creating a batch file that runs netstat in a tight loop and appends its output to a text file. I ran this batch file while running the system, and by combing through all of the netstat dumps, I was able to find a dump that contained the PIDs associated with the ports.