2

Can we bind a Unix domain socket to any random existing file ? If no, how do you recognize a file that is used by a socket ?

1 Answers1

3

Can we bind a Unix domain socket to any random existing file

No. The file should not exist, or bind(2) will fail with EADDRINUSE. bind(2) will create a new file with the path given in .sun_path.

If no, how do you recognize a file that is used by a socket?

lsof may help. Up to a point.

Or ss:

$ nc -Ul foo &
[3] 9268
$ ls -i ./foo
1179674 ./foo
$ ss -elx | grep -w 1179674
u_str LISTEN  0  5 foo 618789 * 0 <-> ino:1179674 dev:0/2072 peers:

(the ss output above was manually trimmed of white spaces)

The -l option will direct ss to select only listening sockets, the -x option only Unix sockets, and the -e option to print extended info, as the inode number I've used to match the file.

Both ss and lsof will only see the sockets from the current network namespace; but two unix sockets from different network namespaces cannot be bound to the same file.

You may want to check if the device numbers match too; but you should proceed carefully, because the sock_diag(7) (as used by ss) will return it in the format used internally by the kernel (MMMm mmmm), but the buggy ss will treat as if it were in the mmmM MMmm userland format; the device number in the example above is not 0/2072, but 8/24 (/dev/sdb8) ;-)

  • I thought pathname UNIX domain sockets doesn't belongs to any network space, they can be seen as long as you can access that bound address from your mount namespace. By the way, haven't such an obvious bug of ss been fixed yet? – 炸鱼薯条德里克 Dec 15 '19 at 05:01
  • @炸鱼薯条德里克 1. just try it. run unshare -Un nc -Ul /tmp/sock in a terminal, and ss -xl | grep /tmp/sock or lsof /tmp/sock in another. Of course, you can connect to a unix socket from another namespace, if you can access the file it's bound to. 2. fixing it now will break all the scripts which use workarounds for it. –  Dec 15 '19 at 05:20
  • ls -l file tells you whether the file is a Unix socket. The very first character will be an s in that case. Very simple. – Alexis Wilke Jul 20 '21 at 17:23
  • @Alex ls -l file does NOT tell you if a socket file is actually in use -- ie if any process is actually listening on, bound to or connected to it. Reliably determining that is not simple at all, for all the reasons already mentioned in this and the linked answer. –  Jul 22 '21 at 04:51