Error fixing up map structure, incompatible struct bpf_elf_map used? - ebpf

I am trying to learn ebpf map. Compiling the code with libbpf but getting the error like "Error fixing up map structure, incompatible struct bpf_elf_map used?". Here is my ebpf code:
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <stdint.h>
#include <iproute2/bpf_elf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#ifndef __section
# define __section(NAME) \
__attribute__((section(NAME), used))
#endif
#ifndef __inline
# define __inline \
inline __attribute__((always_inline))
#endif
struct bpf_map_def SEC("maps") port_h = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(int),
.value_size = sizeof(int),
.max_entries = 1,
};
static __always_inline int do_inline_hash_lookup(void *inner_map, int port)
{
int *result;
if (inner_map != &port_h)
return 99;
result = bpf_map_lookup_elem(&port_h, &port);
return result ? *result : 99;
}
__section("ingress")
int tc_ingress(struct __sk_buff *skb)
{
void *outer_map, *inner_map;
do_inline_hash_lookup(inner_map, 100);
return TC_ACT_OK;
}
__section("egress")
int tc_egress(struct __sk_buff *skb)
{
return TC_ACT_OK;
}
char LICENSE[] SEC("license") = "GPL";
Here is how I am loading the code into kernel:
tc filter del dev lo ingress
tc filter del dev lo egress
tc filter show dev lo ingress
# use right device like eth0 or lo
# Add qdisc to a particular interface like eth0 or lo
tc qdisc add dev lo clsact
# Load the object file into kernel
tc filter add dev lo ingress bpf da obj ./.output/map.bpf.o sec ingress
tc filter add dev lo egress bpf da obj ./.output/map.bpf.o sec egress
Any idea, what I am doing wrong? It will be a great help.

I think you need to declare your map according to the libbpf style:
#define __uint(name, val) int(*(name))[val]
#define __type(name, val) typeof(val) *(name)
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__type(key, int);
__type(value, int);
__uint(max_entries, 1);
} port_h __section(".maps");

Related

Why this program which use BPF and RAW SOCKET just hangs?

GOAL: write a simple packet filter using BPF. The packet filter should allow you to choose the interface.
PROBLEM: if I uncomment the third to last instruction in the code (where there is a call to recvfrom, the execution just hangs and I can't see no output (neither "buffer zeroed" which I should be able to see in the stdout).
QUESTIONS: 1) how can I fix it? 2) why the programs hangs during the execution and doesn't show the first printf output? 3) how can I receive from ANY interface?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <linux/filter.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <net/if.h>
#define DEFAULT_IF "wlan0"
/* definisco programma bpf */
/* tcpdump -i lo icmp -dd */
struct sock_filter bpfcode[] = {
{ 0x28, 0, 0, 0x0000000c }, /* (000) ldh [12] */
{ 0x15, 0, 3, 0x00000800 }, /* (001) jeq #0x800 jt 2 jf 5 */
{ 0x30, 0, 0, 0x00000017 }, /* (002) ldb [23] */
{ 0x15, 0, 1, 0x00000001 }, /* (003) jeq #0x1 jt 4 jf 5 */
{ 0x6, 0, 0, 0x00040000 }, /* (004) ret #262144 */
{ 0x6, 0, 0, 0x00000000 }, /* (005) ret #0 */
};
int main(int argc, char *argv[])
{
struct sock_fprog bpf = {
sizeof(bpfcode) / sizeof(struct sock_filter),
bpfcode
};
socklen_t saddr_len = sizeof(struct sockaddr_ll);
struct sockaddr_ll addr;
unsigned char *buffer;
char ifname[IFNAMSIZ];
int ret, sfd, rval;
buffer = calloc(1, 65536);
if (!buffer) {
perror("calloc");
return -1;
}
// prendi nome interfaccia
if (argc > 1)
strcpy(ifname, argv[1]);
else
strcpy(ifname, DEFAULT_IF);
// creazione raw socket
sfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sfd < 0) {
perror("socket");
return -1;
}
// attacco filtro alla socket
ret = setsockopt(sfd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
if (ret < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// quando si usa packet socket bisogna settare sll_protocol e
// sll_ifindex se si vuol fare il bind ad una specifica interfaccia
memset(&addr, 0, sizeof(addr));
addr.sll_family = AF_PACKET;
addr.sll_protocol = htons(ETH_P_ALL);
addr.sll_ifindex = if_nametoindex(ifname);
printf("index %d", addr.sll_ifindex);
// viene assegnato un indirizzo al socket
if (bind(sfd, (struct sockaddr *) &addr,
sizeof(struct sockaddr_ll)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// ricevo traffico
if (!buffer[0])
printf("buffer zeroed");
// rval = recvfrom(sfd, buffer, 65536, 0, (struct sockaddr *)&addr,
// &saddr_len);
if (buffer[0])
printf("something was written in the buffer");
return 0;
}
How do I fix it?
What do you want to fix exactly? See below.
Why the programs hangs during the execution and doesn't show the first printf output?
Both printf() do work, except you're not printing any line breaks ('\n') at the end of your messages, so the system does not flush your message to the console. Just end your messages with line breaks and you will see your messages as expected.
As for the hang, this is simply because recvfrom() waits until a packet arrives. Well, not just any packet in your case, since you are filtering on ICMP. Ping your interface from the outside, and the program should resume. Alternatively, for debugging your C program, just keep { 0x6, 0, 0, 0x00040000 } (return non-zero) in your BPF program, and any received packet should do.
How can I receive from ANY interface?
How to bind a socket to multiple interfaces

Cannot do network programming in XCode anymore

Until recently, the following code worked perfectly in my project. But since a few days ago, it no longer works. I can replace the NSLog statements with printf statements, replace the other Obj-C style statements and compile with g++ in terminal it works just fine.
It should just connect to a very primitive server on a Raspberry Pi, send a single character 'R', and read back a 2-Byte integer. When I compiled or ran it in XCode months ago it worked. When I compile now in terminal with g++ it works. When I run in XCode now, though, it fails to open the socket and reports setDAC: connection failed.
I fear I may be going insane. Did Apple hide some new setting I need to turn on network access in XCode 9.4.1? Any advice?
Previously functional code in XCode:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include "stdio.h"
.
.
.
float readDAC(uint8_t ch){
if(!isConnected){
const char *servIP = [[txtIPAddress stringValue] UTF8String];
in_port_t servPort = 5001;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock < 0){
NSLog(#"setDAC: Socket creation failed\n");
ok = false;
}
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if(ok){
if(rtnVal == 0){
NSLog(#"setDAC: inet_pton() failed: invalid address string\n");
ok = false;
}
else if (rtnVal < 0){
NSLog(#"setDAC: inet_pton() failed\n");
ok = false;
}
servAddr.sin_port = htons(servPort);
}
if(ok) if(connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0){
NSLog(#"setDAC: connection failed\n");
ok = false;
}
datastream = fdopen(sock, "r+");
isConnected = true;
}
//send 'R' to read
//send 'W' to write
char writeChar = 'R';
if([AD5754 intValue]==1){
uint8_t writeChannel;
int16_t setVal;
float theVal;
uint8_t nDAC = 0;
if(ch>3) nDAC = 1;
ch = ch%4;
ch = 16*nDAC+ch;
writeChannel = ch;
fwrite(&writeChar, sizeof(writeChar), 1, datastream);
fwrite(&writeChannel, sizeof(writeChannel), 1, datastream);
fread(&setVal, sizeof(setVal), 1, datastream);
int16_t theSetVal;
theSetVal = ntohs(setVal);
theVal = (float)theSetVal/100;
NSLog(#"Read channel %i: %0.2f", ch, theVal);
fflush(datastream);
fclose(datastream);
return theVal;
}
I paid Apple the $99 annual fee to join the developer program and now the network coding works again. Not impressed with Apple, but ok.
I wouldn't mind paying to recover the functionality if it was documented or some notice was given. But I struggled for a few days before getting desperate enough to try throwing money at the problem, randomly.

systemd-activate socket activation for UDP daemons

I like using systemd-activate(8) for testing socket-activated daemons during development,
however, it seems it only listens for TCP connections:
% /usr/lib/systemd/systemd-activate -l 5700 ./prog
Listening on [::]:5700 as 3.
% netstat -nl |grep 5700
tcp6 0 0 :::5700 :::* LISTEN
I am using a program that handles datagrams (UDP). How can I make systemd-activate listen on a UDP port? Or is there a
simple way to do this using other tools, without going to the trouble of crafting and installing a systemd unit file?
This was recently added to systemd-activate: https://github.com/systemd/systemd/pull/2411, and will be part of systemd-229 when it is released.
I'm not sure that there is a way to do it with systemd-activate.
You may want to employ some .service unit file and a .socket unit file with dependencies. In a .socket unit you will describe ListenDatagram= option. See here for more details.
I ended up writing a simple C program to do this; code below (public domain).
The usage is:
./a.out <port-number> <prog> [<arg1> ...]
The program opens a UDP socket on <port-number>, sets the environment variables that systemd socket-activated daemons expect, then executes <prog> with whatever arguments follow.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char **argv) {
if (argc < 2) {
printf("no port specified\n");
return -1;
}
if (argc < 3) {
printf("no program specified\n");
return -1;
}
uint16_t port = htons((uint16_t) strtoul(argv[1], NULL, 10));
if (port == 0 || errno) {
printf("failed to parse port: %s\n", argv[1]);
return -1;
}
/* create datagram socket */
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
printf("failed to open socket; errno: %d\n", errno);
return -1;
}
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = port;
sa.sin_addr.s_addr = INADDR_ANY;
/* bind socket to port */
int r = bind(fd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in));
if (r < 0) {
printf("bind failed; errno: %d\n", errno);
return -1;
}
/* execute subprocess */
setenv("LISTEN_FDS", "1", 0);
execvp(argv[2], argv + 2);
}

Calling setsockopt many times

I have application which uses sockets to transfer data between two clients. It uses a single socket to communicate control and data traffic (over UDP).
Qos and tos fields of IP header can be changed using
setsockopt(sockfd, IPPROTO_IP, IP_TOS, &tos, toslen);
setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &cos, coslen);
But how many calls to setsockopt (to the same socket) is too many?
For example, lets assume it will be called every 1ms.
To narrow question scope, I am asking about modern linux system (generic explanation is more than welcomed).
Here is an example to demonstrate it (this is the sending-only part of the application):
#include <stdlib.h>
#include <memory.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define NPACK 10000
#define PORT 44444
#define BUFLEN 128
void diep(char *s) {
perror(s);
exit(1);
}
#define SRV_IP "12.34.56.78"
int main(void) {
struct sockaddr_in si_other, si_me;
int s, i, slen = sizeof(si_other);
int toss[2] = { 56, 160 }, coss[] = { 1, 3 };
char buf[BUFLEN];
//Create UDP socket
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
diep("socket");
//Create remote socket
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SRV_IP, &si_other.sin_addr) == 0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
//Create local socket and bind to it.
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, &si_me, sizeof(si_me)) == -1)
diep("bind");
//Loop on number of packets
for (i = 0; i < NPACK; i++) {
sprintf(buf, "This is packet %d, %d\n", i, toss[i % 2]);
printf("Sending packet %d. %s", i, buf);
//Change tos and cos. odd packets high priority , even packets low priority.
setsockopt(s, IPPROTO_IP, IP_TOS, &toss[i % 2], sizeof(int));
setsockopt(s, SOL_SOCKET, SO_PRIORITY, &coss[i % 2], sizeof(int));
//Send!
if (sendto(s, buf, strlen(buf), 0, &si_other, slen) == -1)
diep("sendto()");
}
close(s);
return 0;
}
NOTES:
Both control and data should share the same socket (same UDP source port).
Multiple threads will use the same socket (so some locking mechanism needed between setsockopt and sendto; but this is outside the scope of the question).
SO_PRIORITY is linux only.

How to find Address already in use?

This is my code which can run CentOS and Windows just fixing some headers.
#define _WIN32_WINNT 0x0501
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
/*
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
*/
int main()
{
int sock;
int ret = 0;
int port= 12345;
struct sockaddr_in addr;
char buf[1024];
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
printf("socket() ret = %d : %s\n",ret,strerror(errno));
return ret;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
if(ret<0){
printf("bind() ret = %d errno =%d : %s\n",ret,errno,strerror(errno));
return ret;
}
printf("############# Binding port %d type Enter to stop \t",port);
fgets(buf,sizeof(buf),stdin);
return 0;
}
When I tried to bind same port by this program with runing tow process, there must be the messages that Address already in use like below.
[The first proc#centOS ]
$ ./udp
############# Binding port 12345 type Enter to stop
[The second proc#centOS]
$ ./udp
bind() ret = -1 errno =98 : Address already in use
$
However when I do same thing with same code on windows, message is different.
[The first proc#windows]
C:\ >udp
############# Binding port 12345 type Enter to stop
[The second proc#windows]
C:\ >udp
bind() ret = -1 errno =34 : Result too large
C:\ >
How can I get Address already in use on Windows?
I don't think you should use errno on windows for sockets code. You could try to use WSAGetLastError which returns WSAEADDRINUSE.
The MSDN page for errno suggests EADDRINUSE is not supported for errno.
I think you should devise a scheme where you have a my_errno function that depending on the platform uses errno or WSAGetLastError.
printf("socket() ret = %d : %s\n",ret,strerror(errno));
There may be a subtle issue with this call. The order of argument evaluation is unspecified and strerror itself can change errno, which means it has side-effects. You should print errno separately, before doing anything else.
Like cnicular said, you have to use WSAGetLastError() on Windows, not errno. To get a text message for a socket error code, you can use FormatMessage().
To answer your question, if you want to find out who is using the port, you can use the command-line netstat tool, or programmably using GetTcpTable2().