Issue 1492240: Socket-object convenience function: getpeercred(). (original) (raw)

The attached patch implements a convenience function called getpeercred() which internally calls getsockopt(SO_PEERCRED) to retrieve the credentials (pid, uid and gid) of the remote process a socket is attached to, in case the remote end is local.

This currently (AFAIK) only works (properly) on Linux 2.4+, but might work on BSD-style systems too.

The returned data is wrapped in a new ucred type, which is subclassable to implement additional convenience functions in Lib/socket.py.

The patch updates the socket module, the test suite, the documentation (including whatsnew), and adds a configure check for the definition of struct ucred in sys/socket.h, which is the default place for struct ucred if it is available.

If struct ucred is not available on the current system, getpeercred() is made a dummy method, which returns a python-defined ucred type which contains pid=0, uid=gid=-1, which are the default values returned under Linux when the call fails because there is no credentials data associated with the socket.

The decision to move the data to a separate type was made with respect to the ability to use struct ucred under other systems in a SCM_CREDENTIALS sendmsg() call. I'll post the implementation of sendmsg() and recvmsg() as a separate tracker item, but the latter patch will rely on the inclusion of this patch.

I'm uncomfortable with including something that only works on certain versions of a single platform. Are there any other functions or methods (not modules) that are only available for Linux? I can think of a number of places flagged as "Availability: Unix", but if getpeercred() doesn't work on the BSDs, it doesn't even meet that standard.

If a decision is made to include this, and if it only works on Linux 2.4+, I'd rather see it not available at all on other platforms (rather than returning dummy values).