Is it recommended to use build.rs to set capabilities?

I am writing a ping program in Rust - which means I have to be able to set ICMP packets, which requires me, on Linux, to use raw sockets. For that, the final executable needs to have the CAP_RAW_NET capability, which by default only programs run as super-user have. So, in order to not have to use sudo every time I run the binary, I would like to set the capability once (using sudo) and then run it normally.
I want to be able to do this using Cargo itself. So, a build script, using build.rs seemed to be ideal - except that I need to run a sudo command from within it. So is this recommended? Or should I simply make a Makfile, put sudo setcap ... and be done with it?

Build scripts can't see the final executable. They run before compiling the crate they are associated with. You can use for example makefiles, just or the GitHub - matklad/cargo-xtask pattern instead.

2 Likes