View Source procket (procket v0.9.10)
procket is an Erlang library for socket creation and manipulation.
procket can use a setuid helper so actions like binding low ports and requesting some sockets types can be done while Erlang is running as an unprivileged user.
## FEATURES
Other features include:
* low level socket manipulation using socket/3, ioctl/3, setsockopt/4, ...
* support any protocols supported by the socket interface: ICMP, Unix sockets, ...
* support for the BSD raw socket interface
* generate and snoop packets using PF_PACKET sockets on Linux
* generate and snoop packets using the BPF interface on BSDs like Mac OS X
* support for creating and reading/writing from character devices like TUN/TAP interfaces
## SETUID vs SUDO vs Capabilities
The procket helper executable needs root privileges. Either allow your user to run procket using sudo or copy procket to somewhere owned by root and make it setuid.
* for sudo
sudo visudo
youruser ALL=NOPASSWD: /path/to/procket/priv/procket
# if sudoers has enabled "Default requiretty", you will need to set
# one of these options too:
Defaults!/path/to/procket/priv/procket !requiretty
Defaults:youruser !requiretty* to make it setuid
# Default location
sudo chown root priv/procket
sudo chmod 4750 priv/procketThe procket setuid helper can also be placed in a system directory:
# System directory
sudo cp priv/procket /usr/local/bin
sudo chown root:yourgroup /usr/local/bin/procket
sudo chmod 4750 /usr/local/bin/procketThen pass the progname argument to open/2:
{ok, FD} = procket:open(53, [{progname, "/usr/local/bin/procket"},
{protocol, udp},{type, dgram},{family, inet}]).* use Linux capabilities: beam or the user running beam can be given whatever socket privileges are needed. For example, using file capabilities:
setcap cap_net_raw=ep /usr/local/lib/erlang/erts-5.8.3/bin/beam.smpTo see the capabilities:
getcap /usr/local/lib/erlang/erts-5.8.3/bin/beam.smpTo remove the capabilities:
setcap -r /usr/local/lib/erlang/erts-5.8.3/bin/beam.smp
Summary
Functions
accept(2): accept a connection on a socket
accept(2): accept a connection on a socket
Allocate structure for ioctl/3.
bind(2): bind a name to a socket
Return the contents of memory allocated using alloc/1.
close(2): close a file descriptor
connect(2): initiate a connection on a socket
Open a character device such as bpf, tun or tap devices.
Open a character device such as bpf, tun or tap devices with options.
Return atom describing error number.
Convert protocol family (aka domain) to OS defined constant.
getsockname(2): get socket name
getsockopt(2): get options on sockets
ioctl(2): control device
listen(2): listen for connections on a socket
listen(2): listen for connections on a socket
Write data to memory allocated using alloc/1.
Convert a long unsigned integer from network byte order to host byte order.
Convert a short unsigned integer from network byte order to host byte order.
Open a socket or device using the procket setuid helper.
Open a socket or device using the procket setuid helper.
read(2): read bytes from a file descriptor
recv(2): receive a message from a socket
recvfrom(2): receive a message from a socket
recvfrom(2): receive a message from a socket
recvmsg(2): receive a message from a socket
recvmsg(2): receive a message from a socket
sendmsg(2): send a message on a socket
sendmsg(2): send a message on a socket
sendto(2): send a message on a socket
sendto(2): send a message on a socket
sendto(2): send a message on a socket
Set O_NONBLOCK status flag on socket.
setns(2): reassociate thread with a namespace, joining any namespace type.
setns(2): reassociate thread with a namespace, joining the specified namespace type.
setsockopt(2): set options on sockets
Return the family field of a struct sockaddr for BSD and Linux.
socket(2): returns a file descriptor for a communication endpoint
Types
-type family() :: unspec | inet | inet6 | netlink | packet | local | unix | file.
-type fd() :: int32_t().
-type int32_t() :: -2147483647..2147483647.
-type posix() ::
e2big | eacces | eaddrinuse | eaddrnotavail | eadv | eafnosupport | eagain | ealign |
ealready | ebade | ebadf | ebadfd | ebadmsg | ebadr | ebadrpc | ebadrqc | ebadslt | ebfont |
ebusy | ecapmode | echild | echrng | ecomm | econnaborted | econnrefused | econnreset |
edeadlk | edeadlock | edestaddrreq | edirty | edom | edotdot | edquot | eduppkg | eexist |
efault | efbig | ehostdown | ehostunreach | eidrm | einit | einprogress | eintr | einval |
eio | eisconn | eisdir | eisnam | el2hlt | el2nsync | el3hlt | el3rst | elbin | elibacc |
elibbad | elibexec | elibmax | elibscn | elnrng | eloop | emfile | emlink | emsgsize |
emultihop | enametoolong | enavail | enet | enetdown | enetreset | enetunreach | enfile |
enoano | enobufs | enocsi | enodata | enodev | enoent | enoexec | enolck | enolink | enomem |
enomsg | enonet | enopkg | enoprotoopt | enospc | enosr | enostr | enosym | enosys | enotblk |
enotcapable | enotconn | enotdir | enotempty | enotnam | enotrecoverable | enotsock |
enotsup | enotty | enotuniq | enxio | eopnotsupp | eoverflow | eownerdead | eperm |
epfnosupport | epipe | eproclim | eprocunavail | eprogmismatch | eprogunavail | eproto |
eprotonosupport | eprototype | erange | erefused | eremchg | eremdev | eremote | eremoteio |
eremoterelease | erofs | erpcmismatch | erremote | eshutdown | esocktnosupport | espipe |
esrch | esrmnt | estale | esuccess | etime | etimedout | etoomanyrefs | etxtbsy | euclean |
eunatch | eusers | eversion | ewouldblock | exdev | exfull.
-type protocol() :: ip | icmp | tcp | udp | 'ipv6-icmp' | raw.
-type size_t() :: uint64_t().
-type type() :: stream | dgram | raw | seqpacket.
-type uint8_t() :: 0..255.
-type uint16_t() :: 0..65535.
-type uint32_t() :: 0..4294967295.
-type uint64_t() :: 0..18446744073709551615.
Functions
accept(2): accept a connection on a socket
accept/1 returns the file descriptor associated with the new connection.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
4> procket:listen(S).
ok
5> procket:accept(S).
{error,eagain}
% Connect: nc localhost 10022
6> procket:accept(S).
{ok,21}
accept(2): accept a connection on a socket
accept/2 will allocate a struct sockaddr of size Salen bytes that will hold the peer address. If the size is too small, the returned binary will be zero padded to indicate the size required.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
4> procket:listen(S).
ok
5> procket:accept(S, 16).
{error,eagain}
% Connect: nc localhost 10022
6> procket:accept(S, 16).
{ok,22,<<2,0,207,110,127,0,0,1,0,0,0,0,0,0,0,0>>}
-spec alloc([binary() | {ptr, size_t()} | {ptr, binary()}]) -> {ok, binary(), [reference()]} | {error, posix()}.
Allocate structure for ioctl/3.
Create a structure containing pointers to memory that can be passed as the third argument to ioctl/3.
The size of the allocated memory can be indicated by either using an integer or passing in a binary of the appropriate size. If an integer is used, the contents are zero'ed. If a binary is used, the memory is initialized to the contents of the binary.
Resource is a list of NIF resources (one for each piece of allocated memory) requested in the struct. The memory will automatically be freed by the resource.
It is up to the caller to ensure the structure has the proper endianness and alignment for the platform.
Examples
For example, a struct bpf_program is used to set a filter on a bpf character device:
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;
};
struct bpf_insn {
u_short code;
u_char jt;
u_char jf;
bpf_u_int32 k;
};To allocate a binary in Erlang:
Insn = [
?BPF_STMT(?BPF_LD+?BPF_H+?BPF_ABS, 12), % offset = Ethernet Type
?BPF_JUMP(?BPF_JMP+?BPF_JEQ+?BPF_K, ?ETHERTYPE_IP, 0, 1), % type = IP
?BPF_STMT(?BPF_RET+?BPF_K, 16#FFFFFFFF), % return: entire packet
?BPF_STMT(?BPF_RET+?BPF_K, 0) % return: drop packet
],
{ok, Code, [Res]} = procket:alloc([
<<(length(Insn)):4/native-unsigned-integer-unit:8>>,
{ptr, list_to_binary(Insn)}
]).To use the ioctl and return the contents of the memory:
case procket:ioctl(Socket, ?BIOCSETF, Code) of
{ok, _} ->
procket:buf(Res);
Error ->
Error
end.See also: ioctl/3.
bind(2): bind a name to a socket
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
Return the contents of memory allocated using alloc/1.
See also: alloc/1.
close(2): close a file descriptor
Examples
1> procket:open(8080).
{ok,22}
2> procket:close(22)
ok
connect(2): initiate a connection on a socket
Sockaddr is a struct sockaddr whose layout is dependent on platform. If Sockaddr is an empty binary, connect(2) will be called with NULL as the second option.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
22:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,0,22,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:connect(S, Sockaddr).
{error,einprogress}
4> procket:connect(S, Sockaddr).
{error,econnrefused}
Open a character device such as bpf, tun or tap devices.
Wrapper around open/2.
Examples
1> procket:dev("net/tun").
{ok,22}See also: open/2.
Open a character device such as bpf, tun or tap devices with options.
Examples
# ip netns add foo 1> procket:dev("net/tun", [{namespace, "/var/run/netns/foo"}]).
{ok,22}
Return atom describing error number.
Examples
1> procket:errno_id(1).
eperm
-spec family(Protocol :: family()) -> 0 | 1 | 2 | 10 | 16 | 17 | 24 | 26 | 28 | 30 | 38.
Convert protocol family (aka domain) to OS defined constant.
getsockname(2): get socket name
If the input binary is too small to hold the socket address structure, the returned binary is zero padded to indicate the size required.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
4> procket:getsockname(S, <<0:(byte_size(Sockaddr)*8)>>).
{ok,<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>}
-spec getsockopt(Socket :: integer(), Level :: integer() | atom(), Optname :: integer() | atom(), Optval :: binary()) -> {ok, binary()} | {error, posix() | unsupported}.
getsockopt(2): get options on sockets
Similar to inet:getopts/2 but can be used with file descriptors.
Retrieve a socket option for a file descriptor. Use an empty binary to indicate no option value is supplied or will be returned.
Examples
1> {ok, FD} = procket:open(0, [{protocol, 'ipv6-icmp'}, {type, raw}, {family, inet6}]).
{ok,28}
% IPPROTO_V6 = 41, Linux: IPV6_UNICAST_HOPS = 16 set to 255
2> procket:setsockopt(FD, 41, 16, <<255:4/native-unsigned-integer-unit:8>>).
ok
3> procket:getsockopt(FD, 41, 16, <<0:32>>).
{ok,<<255,0,0,0>>}See also: setsockopt/4.
-spec ioctl(FD :: integer(), Request :: uint64_t(), Arg :: binary() | integer()) -> {ok, binary()} | {error, posix()}.
ioctl(2): control device
Be careful with this function.
Request is an integer with the direction of the request encoded into it (IN, OUT, IN/OUT). Result is a binary holding the result. If the ioctl is IN only, the Result will be the same as Arg.
Arg is a structure dependent on the request.
See procket_ioctl.erl for some helper functions for dealing with ioctl.
Caveats:
* Request is an integer on Linux and an unsigned long on OS X
* some ioctl requests require a structure with a pointer to memory. Use alloc/1 to create these structures and buf/1 to retrieve the data from them.
* some ioctl requests use an integer instead of a pointer to a structure. This means that it's possible to pass in an arbitrary pointer (an integer) as an argument to an ioctl expecting a structure. Don't do this.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
% SIOCGIFINDEX = 16#8933
2> {ok, <<Ifname:16/bytes, Ifr:32/native, _/binary>>} = procket:ioctl(S, 16#8933, <<"eth0", 0:224>>).
{ok,<<101,116,104,48,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,
0,0,0,0,0,...>>}
4> Ifname.
<<101,116,104,48,0,0,0,0,0,0,0,0,0,0,0,0>>
5> Ifr.
7
listen(2): listen for connections on a socket
listen/1 sets the backlog to 50.
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> procket:listen(S).
ok
listen(2): listen for connections on a socket
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> procket:listen(S, 16#ffff).
ok
Write data to memory allocated using alloc/1.
Examples
1> {ok, Buf, [Ref]} = procket:alloc([{ptr, 1024}]).
{ok,<<112,125,4,72,127,0,0,0>>,
[#Ref<0.4091636758.1194983426.105614>]}
2> procket:memcpy(Ref, <<1,2,3,4,5,6,7,8,9>>).
ok
3> procket:buf(Ref).
{ok,<<1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,...>>}See also: alloc/1.
Convert a long unsigned integer from network byte order to host byte order.
Examples
1> procket:ntohl(<<1:32>>).
16777216
Convert a short unsigned integer from network byte order to host byte order.
Examples
1> procket:ntohs(<<1:32>>).
256
Open a socket or device using the procket setuid helper.
Examples
1> procket:open(8080).
{ok,22}
Open a socket or device using the procket setuid helper.
The file descriptor is passed back over a Unix socket.
The default behaviour of open/1,2 is to attempt to open the socket twice: first by running the procket setuid helper and, if this fails because the process does not have the appropriate permissions, running the setuid helper again using "sudo". The default behaviour can be changed by using the 'exec' option:
procket:open(Port, [{exec, ["", "sudo"]}]).Linux only: the {namespace, string()} option causes the procket setuid helper to open the socket in a pre-configured namespace. By default, all namespaces are joined by the helper.
Examples
1> procket:open(9019, [{exec, [""]}]).
{ok,24}
read(2): read bytes from a file descriptor
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
4> procket:listen(S).
ok
% echo "test test 123" | nc localhost 10022
5> {ok, FD, _} = procket:accept(S, 16).
{ok,21,<<2,0,207,110,127,0,0,1,0,0,0,0,0,0,0,0>>}
6> procket:read(FD, 1024).
{ok,<<"test test 123\n">>}
recv(2): receive a message from a socket
recvfrom(2): receive a message from a socket
Examples
1> {ok, S} = procket:socket(inet, stream, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
4> procket:listen(S).
ok
% echo "test test 123" | nc localhost 10022
5> {ok, FD, _} = procket:accept(S, 16).
{ok,21,<<2,0,207,110,127,0,0,1,0,0,0,0,0,0,0,0>>}
6> procket:recvfrom(FD, 1024).
{ok,<<"test test 123\n">>}
-spec recvfrom(Socket :: integer(), Size :: size_t(), Flags :: integer(), Salen :: size_t()) -> {ok, binary(), binary()} | {error, posix()}.
recvfrom(2): receive a message from a socket
Examples
1> {ok, S} = procket:socket(inet, dgram, 0).
{ok,20}
2> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
3> procket:bind(S, Sockaddr).
ok
% echo "test test 123" | nc -u localhost 10022
4> procket:recvfrom(S, 1024, 0, byte_size(Sockaddr)).
{ok,<<"test test 123\n">>,
<<2,0,173,123,127,0,0,1,0,0,0,0,0,0,0,0>>}
-spec recvmsg(Socket :: integer(), Size :: size_t(), Flags :: integer(), CtrlDataSize :: size_t()) -> {ok, binary(), integer(), [{integer(), integer(), binary()}]} | {error, posix()}.
recvmsg(2): receive a message from a socket
-spec recvmsg(Socket :: integer(), Size :: size_t(), Flags :: integer(), CtrlDataSize :: size_t(), SockaddrSize :: size_t()) -> {ok, binary(), integer(), [{integer(), integer(), binary()}], binary()} | {error, posix()}.
recvmsg(2): receive a message from a socket
-spec sendmsg(Socket :: integer(), Buf :: binary(), Flags :: integer(), CtrlData :: [{integer(), integer(), binary()}]) -> ok | {error, posix()}.
sendmsg(2): send a message on a socket
-spec sendmsg(Socket :: integer(), Buf :: binary(), Flags :: integer(), CtrlData :: [{integer(), integer(), binary()}], Sockaddr :: binary()) -> ok | {ok, size_t()} | {error, posix()}.
sendmsg(2): send a message on a socket
sendto(2): send a message on a socket
sendto(2): send a message on a socket
-spec sendto(Socket :: integer(), Buf :: binary(), Flags :: integer(), Sockaddr :: binary()) -> ok | {ok, size_t()} | {error, posix()}.
sendto(2): send a message on a socket
Set O_NONBLOCK status flag on socket.
Note: file descriptors opened by procket are opened in non-blocking mode.
setns(2): reassociate thread with a namespace, joining any namespace type.
Note: the beam process must have root privileges to call this function.
Examples
1> procket:setns("/proc/self/ns/net").
ok
setns(2): reassociate thread with a namespace, joining the specified namespace type.
Note: the beam process must have root privileges to call this function.
The constants are defined in linux/sched.h:
0 Allow any type of namespace to be joined.
CLONE_NEWCGROUP (since Linux 4.6)
fd must refer to a cgroup namespace.
CLONE_NEWIPC (since Linux 3.0)
fd must refer to an IPC namespace.
CLONE_NEWNET (since Linux 3.0)
fd must refer to a network namespace.
CLONE_NEWNS (since Linux 3.8)
fd must refer to a mount namespace.
CLONE_NEWPID (since Linux 3.8)
fd must refer to a descendant PID namespace.
CLONE_NEWUSER (since Linux 3.8)
fd must refer to a user namespace.
CLONE_NEWUTS (since Linux 3.0)
fd must refer to a UTS namespace.Examples
1> procket:setns("/proc/self/ns/net", 16#40000000).
ok
-spec setsockopt(Socket :: integer(), Level :: integer() | atom(), Optname :: integer() | atom(), Optval :: binary()) -> ok | {error, posix() | unsupported}.
setsockopt(2): set options on sockets
Level and Optname can either be an integer or an atom with the same name as the definitions in the system header files, e.g., 'IPPROTO_IPIP', 'SO_REUSEPORT'. Note these are uppercase atoms and so must be quoted.
If an atom is used as an argument and is not supported by the OS, setsockopt/4 will return {error,unsupported}.
Examples
1> {ok, FD} = procket:open(0, [{protocol, 'ipv6-icmp'}, {type, raw}, {family, inet6}]).
{ok,28}
% IPPROTO_V6 = 41, Linux: IPV6_UNICAST_HOPS = 16 set to 255
2> procket:setsockopt(FD, 41, 16, <<255:4/native-unsigned-integer-unit:8>>).
ok
% : IPPROTO_V6 = 41, Linux: IPV6_MULTICAST_HOPS = 16 set to 255
3> procket:setsockopt(FD, 41, 18, <<255:4/native-unsigned-integer-unit:8>>).
ok
Return the family field of a struct sockaddr for BSD and Linux.
Examples
1> Sockaddr = <<(procket:sockaddr_common(inet, 16))/binary,
10022:16, % Port
127,0,0,1, % IPv4 loopback
0:64
>>.
<<2,0,39,38,127,0,0,1,0,0,0,0,0,0,0,0>>
-spec socket(Family :: family() | integer(), Type :: type() | integer(), Protocol :: protocol() | integer()) -> {ok, fd()} | {error, posix()}.
socket(2): returns a file descriptor for a communication endpoint
Examples
1> procket:socket(inet, stream, 0).
{ok,20}