> you can chdir to the directory before bind/connect
Since working directory is per-process not per-thread, this seems a great way to introduce race condition bugs. It also basically rules it out for anything meant to be used as a library or framework.
Working directory can be changed on a per-thread basis on Mac with pthread_chdir_np, and on Linux you can create a thread with the clone syscall and without the CLONE_FS flag to avoid sharing working directory with the rest of the process. I don't know about Windows.
One could fork a subprocess, chdir()+socket() there, then pass the socket back to parent over another socket (opened maybe with socketpair().) Should work on any Unix-like which supports SCM_RIGHTS (which is almost everybody, apparently even obscure platforms like AIX, IBM i, z/OS). But not Windows, which doesn't (at least not yet, they may add it at some point.)
Makes one really wish there was a bindat() call:
int bindat(int sockfd, const struct sockaddr *addr, socklen_t addrlen, int dirfd);
or maybe funixsockat:
int funixsockat(int type, int dirfd, const char * name);
which would combine socket() and bind() in a single call
In Windows we actually have a way to set the parent directory for a UDS bind or connect, via a socket ioctl. It’s not documented yet, but it’s in the header.
Cool, did not know that. Indeed I see this in shared/afunix.h:
#define SIO_AF_UNIX_GETPEERPID _WSAIOR(IOC_VENDOR, 256) // Returns ULONG PID of the connected peer process
#define SIO_AF_UNIX_SETBINDPARENTPATH _WSAIOW(IOC_VENDOR, 257) // Set the parent path for bind calls
#define SIO_AF_UNIX_SETCONNPARENTPATH _WSAIOW(IOC_VENDOR, 258) // Set the parent path for connect calls
// NOTE: setting the parent path is not thread safe.
What does the "NOTE: setting the parent path is not thread safe" comment mean? Not thread safe if multiple threads are sharing the same socket? (Which seems like an acceptable limitation.) Or something worse than that?
Since working directory is per-process not per-thread, this seems a great way to introduce race condition bugs. It also basically rules it out for anything meant to be used as a library or framework.