Permalink
Browse files

Initial support for BPF on BSDs

Add support for sending and receiving raw frames on BSD systems.
Only tested on Mac OS X. The bpf module calls the C interface with
the appropriate parameters.
  • Loading branch information...
msantos committed Apr 17, 2011
1 parent 94fead2 commit dd34004894d603517a09987a75f9e254ed03671b
Showing with 270 additions and 16 deletions.
  1. +2 −3 README
  2. +63 −4 c_src/procket.c
  3. +2 −0 c_src/procket.h
  4. +41 −4 c_src/procket_cmd.c
  5. +1 −0 ebin/procket.app
  6. +127 −0 src/bpf.erl
  7. +7 −4 src/packet.erl
  8. +27 −1 src/procket.erl
View
5 README
@@ -127,10 +127,9 @@ procket uses libancillary for passing file descriptors between processes:
TODO
-* Support BPF on BSD for sending/receiving packets
+* add support for BPF filter rules
-* Examples/changes to support sending TCP/UDP packets using the raw
- socket interface, using epcap to receive packets
+* interface for opening any character device
* Docs and type specs
View
@@ -289,6 +289,64 @@ nif_sendto(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
}
+/* 0: socket, 1: length */
+ static ERL_NIF_TERM
+nif_read(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
+{
+ int fd = -1;
+ unsigned long len = 0;
+
+ ErlNifBinary buf;
+ ssize_t bufsz = 0;
+
+
+ if (!enif_get_int(env, argv[0], &fd))
+ return enif_make_badarg(env);
+ if (!enif_get_ulong(env, argv[1], &len))
+ return enif_make_badarg(env);
+
+ if (!enif_alloc_binary(len, &buf))
+ return error_tuple(env, ENOMEM);
+
+ if ( (bufsz = read(fd, buf.data, buf.size)) == -1) {
+ enif_release_binary(&buf);
+ switch (errno) {
+ case EAGAIN:
+ case EINTR:
+ return enif_make_tuple2(env, atom_error, atom_eagain);
+ default:
+ return error_tuple(env, errno);
+ }
+ }
+
+ if (bufsz != buf.size)
+ enif_realloc_binary(&buf, bufsz);
+
+ return enif_make_tuple2(env, atom_ok, enif_make_binary(env, &buf));
+}
+
+
+/* 0: fd, 1: buffer */
+ static ERL_NIF_TERM
+nif_write(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
+{
+ int fd = -1;
+
+ ErlNifBinary buf;
+
+ if (!enif_get_int(env, argv[0], &fd))
+ return enif_make_badarg(env);
+
+ if (!enif_inspect_binary(env, argv[1], &buf))
+ return enif_make_badarg(env);
+
+ if (write(fd, buf.data, buf.size) == -1)
+ return error_tuple(env, errno);
+
+ return atom_ok;
+}
+
+
/* 0: socket descriptor, 1: struct sockaddr */
static ERL_NIF_TERM
nif_bind(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
@@ -338,14 +396,14 @@ nif_connect(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
nif_ioctl(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
int s = -1;
- int req = 0;
+ unsigned long req = 0;
ErlNifBinary arg;
if (!enif_get_int(env, argv[0], &s))
return enif_make_badarg(env);
- if (!enif_get_int(env, argv[1], &req))
+ if (!enif_get_ulong(env, argv[1], &req))
return enif_make_badarg(env);
if (!enif_inspect_binary(env, argv[2], &arg))
@@ -560,11 +618,12 @@ static ErlNifFunc nif_funcs[] = {
{"sendto", 4, nif_sendto},
{"setsockopt", 4, nif_setsockopt},
+ {"read", 2, nif_read},
+ {"write", 2, nif_write},
+
{"alloc", 1, nif_alloc},
{"memcpy", 2, nif_memcpy},
{"buf", 1, nif_buf}
};
ERL_NIF_INIT(procket, nif_funcs, load, NULL, NULL, NULL)
-
-
View
@@ -36,6 +36,7 @@
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
+#include <sys/param.h>
#include <unistd.h>
#include <sys/types.h>
@@ -101,6 +102,7 @@ typedef struct {
int type; /* socket type: SOCK_STREAM */
int protocol; /* socket protocol: IPPROTO_TCP */
int backlog; /* Listen backlog */
+ int bpf; /* Open a bpf device */
} PROCKET_STATE;
View
@@ -1,4 +1,4 @@
-/* Copyright (c) 2010, Michael Santos <michael.santos@gmail.com>
+/* Copyright (c) 2010-2011, Michael Santos <michael.santos@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -38,6 +38,7 @@
void procket_parse_address(PROCKET_STATE *ps);
int procket_pipe(PROCKET_STATE *ps);
int procket_open_socket(PROCKET_STATE *ps);
+int procket_open_bpf(PROCKET_STATE *ps);
void usage(PROCKET_STATE *ep);
@@ -57,7 +58,7 @@ main(int argc, char *argv[])
ps->type = SOCK_STREAM;
ps->protocol = IPPROTO_TCP;
- while ( (ch = getopt(argc, argv, "b:F:hp:P:T:v:I:")) != -1) {
+ while ( (ch = getopt(argc, argv, "b:BF:hp:P:T:v:I:")) != -1) {
switch (ch) {
case 'b': /* listen backlog */
ps->backlog = atoi(optarg);
@@ -79,6 +80,9 @@ main(int argc, char *argv[])
case 'I': /* Interface name */
IS_NULL(ps->ifname = strdup(optarg));
break;
+ case 'B': /* Open a BPF device */
+ ps->bpf = 1;
+ break;
case 'v':
ps->verbose++;
break;
@@ -91,6 +95,7 @@ main(int argc, char *argv[])
argc -= optind;
argv += optind;
+ if (ps->bpf == 0) {
if (ps->path == NULL)
usage(ps);
@@ -105,6 +110,13 @@ main(int argc, char *argv[])
(void)fprintf(stderr, "%s", strerror(errno));
exit (-errno);
}
+ }
+ else {
+ if (procket_open_bpf(ps) < 0) {
+ (void)fprintf(stderr, "%s", strerror(errno));
+ exit (-errno);
+ }
+ }
if (setgid(getgid()) == -1)
err(EXIT_FAILURE, "setgid");
@@ -196,6 +208,32 @@ procket_pipe(PROCKET_STATE *ps)
return (0);
}
+/* BPF support */
+ int
+procket_open_bpf(PROCKET_STATE *ps)
+{
+ char dev[MAXPATHLEN];
+ int i = 0;
+
+ for (i = 0; i < 255; i++) {
+ (void)snprintf(dev, sizeof(dev), "/dev/bpf%d", i);
+
+ ps->s = open(dev, O_RDWR);
+
+ if (ps->s > -1)
+ return 0;
+
+ switch (errno) {
+ case EBUSY:
+ break;
+ default:
+ return -1;
+ }
+ }
+
+ return -1;
+}
+
void
usage(PROCKET_STATE *ps)
@@ -210,11 +248,10 @@ usage(PROCKET_STATE *ps)
#ifdef SO_BINDTODEVICE
" -I <name> interface [default: ANY]\n"
#endif
+ " -B enable BPF support\n"
" -v verbose mode\n",
__progname
);
exit (EXIT_FAILURE);
}
-
-
View
@@ -5,6 +5,7 @@
{modules, [
procket,
packet,
+ bpf,
mktmp,
icmp,
echo
View
@@ -0,0 +1,127 @@
+%% Copyright (c) 2011, Michael Santos <michael.santos@gmail.com>
+%% All rights reserved.
+%%
+%% Redistribution and use in source and binary forms, with or without
+%% modification, are permitted provided that the following conditions
+%% are met:
+%%
+%% Redistributions of source code must retain the above copyright
+%% notice, this list of conditions and the following disclaimer.
+%%
+%% Redistributions in binary form must reproduce the above copyright
+%% notice, this list of conditions and the following disclaimer in the
+%% documentation and/or other materials provided with the distribution.
+%%
+%% Neither the name of the author nor the names of its contributors
+%% may be used to endorse or promote products derived from this software
+%% without specific prior written permission.
+%%
+%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+%% COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+%% POSSIBILITY OF SUCH DAMAGE.
+-module(bpf).
+
+-export([open/1, data/1]).
+-export([pad/1, align/1]).
+
+-define(SIZEOF_STRUCT_IFREQ, 32).
+-define(SIZEOF_INT32_T, 4).
+-define(SIZEOF_U_INT, ?SIZEOF_INT32_T).
+
+-define(BPF_ALIGNMENT, ?SIZEOF_INT32_T).
+
+-define(IOC_IN, 16#80000000).
+-define(IOC_OUT, 16#40000000).
+-define(IOCPARM_MASK, 16#1fff).
+
+-define(BIOCSETIF, iow($B, 108, ?SIZEOF_STRUCT_IFREQ)).
+-define(BIOCIMMEDIATE, iow($B, 112, ?SIZEOF_U_INT)).
+-define(BIOCGBLEN, ior($B,102, ?SIZEOF_U_INT)).
+
+
+open(Dev) ->
+ {ok, Socket} = procket:open(0, [{bpf, true}]),
+
+ % struct ifreq
+ Ifreq = list_to_binary([
+ Dev, <<0:((15*8) - (length(Dev)*8)), 0:8>>,
+ <<0:(16*8)>>
+ ]),
+
+ % Set the interface for the bpf
+ {ok, _} = procket:ioctl(Socket, ?BIOCSETIF, Ifreq),
+
+ % Set immediate mode (reads/writes return immediately)
+ {ok, _} = procket:ioctl(Socket, ?BIOCIMMEDIATE, <<1:32/native>>),
+
+ % Get bpf buf len
+ {ok, Len} = procket:ioctl(Socket, ?BIOCGBLEN, <<1:32/native>>),
+
+ {ok, Socket, procket:ntohl(Len)}.
+
+
+%% struct bpf_hdr {
+%% struct BPF_TIMEVAL bh_tstamp; /* time stamp */
+%% bpf_u_int32 bh_caplen; /* length of captured portion */
+%% bpf_u_int32 bh_datalen; /* original length of packet */
+%% u_short bh_hdrlen; /* length of bpf header (this struct
+%% plus alignment padding) */
+%% };
+
+%% struct BPF_TIMEVAL bh_tstamp;
+%%
+%% On 32-bit, struct timeval32: 4 bytes tv_sec, 4 bytes tv_usec
+%% On 64-bit, struct timeval: 8 bytes tv_sec, 4 bytes tv_usec
+
+%% #define BPF_ALIGNMENT sizeof(int32_t)
+%% #define BPF_WORDALIGN(x) (((x)+(BPF_ALIGNMENT-1))&~(BPF_ALIGNMENT-1))
+pad(Len) ->
+ align(Len) - Len.
+
+align(N) ->
+ (N + (?BPF_ALIGNMENT-1)) band bnot (?BPF_ALIGNMENT-1).
+
+data(Data) when is_binary(Data) ->
+ Size = erlang:system_info({wordsize, external}),
+
+ <<Sec:Size/native-unsigned-integer-unit:8,
+ Usec:4/native-unsigned-integer-unit:8,
+ Caplen:4/native-unsigned-integer-unit:8,
+ Datalen:4/native-unsigned-integer-unit:8,
+ Hdrlen:2/native-unsigned-integer-unit:8,
+ _/binary>> = Data,
+
+ Time = {Sec div 1000000, Sec rem 1000000, Usec},
+
+ Pad = pad(Caplen),
+
+ % Include the padding
+ <<_Hdr:Hdrlen/bytes,
+ Packet:Caplen/bytes,
+ _Pad:Pad/bytes,
+ Rest/binary>> = Data,
+
+ {Time, Datalen, Packet, Rest}.
+
+
+%%-------------------------------------------------------------------------
+%%% Internal functions
+%%-------------------------------------------------------------------------
+%% BSD ioctl request calculation (taken from ioccom.h)
+ioc(Inout, Group, Num, Len) ->
+ Inout bor ((Len band ?IOCPARM_MASK) bsl 16) bor (Group bsl 8) bor Num.
+
+iow(G,N,T) ->
+ ioc(?IOC_IN, G, N, T).
+
+ior(G,N,T) ->
+ ioc(?IOC_OUT, G, N, T).
View
@@ -1,4 +1,4 @@
-%% Copyright (c) 2010, Michael Santos <michael.santos@gmail.com>
+%% Copyright (c) 2010-2011, Michael Santos <michael.santos@gmail.com>
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
@@ -73,9 +73,12 @@
%%-------------------------------------------------------------------------
socket() ->
socket(?ETH_P_IP).
-socket(EthType) when is_integer(EthType) ->
- <<Protocol:16>> = <<EthType:16/native>>,
- procket:open(0, [{protocol, Protocol}, {type, raw}, {family, packet}]).
+socket(Protocol) when is_integer(Protocol) ->
+ procket:open(0, [
+ {protocol, procket:ntohl(Protocol)},
+ {type, raw},
+ {family, packet}
+ ]).
%%-------------------------------------------------------------------------
Oops, something went wrong.

0 comments on commit dd34004

Please sign in to comment.