Date: Thu, 24 Sep 2020 12:46:13 +0200 From: Vasil Dimov vd@freebsd.org
Which creates a hidden service addrwhatever.onion. Later somebody connects to addrwhatever.onion:8333 and the tor daemon opens a TCP connection like 127.0.0.1:46153 -> 127.0.0.1:8333. Next, some other application (not the tor daemon) connects directly to 127.0.0.1:8333 and that is 127.0.0.1:52490 -> 127.0.0.1:8333.
What if the application running at 127.0.0.1:8333 wants to distinguish incoming tor connections from the rest? From its point of view the connections from the example above are just TCP connections coming from 127.0.0.1:46153 and 127.0.0.1:52490.
Can you just use two different sockets, one for connections via Tor and one for non-Tor connections? Then you won't have to go to the trouble of communicating with the tor daemon, worrying about race conditions, &c.
You can use local sockets instead of IP sockets too -- just do:
ADD_ONION <secretkey> Port:8333,unix:/var/service/torsocket
to make the tor daemon connect to /var/service/torsocket instead of 127:0.0.1:8333. Then you can use ordinary file system permissions to control access to it so nobody other than the tor daemon can connect to that socket.
This is the mechanism that my ucspi-onion tool uses: