summaryrefslogtreecommitdiffstats
path: root/ffvisd/ffvisd.c
blob: 851ab3c0c87930240a3d3f9fb91f81f1abc537c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
  Copyright (c) 2012, Matthias Schiffer <mschiffer@universe-factory.net>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    2. 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.

  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.
*/


#define _GNU_SOURCE

#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <arpa/inet.h>

#include <linux/rtnetlink.h>

#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>

#include <netinet/in.h>

#include <sys/types.h>
#include <sys/stat.h>


#define ANNOUNCE_INTERVAL 10000
#define ANNOUNCE_TIMEOUT 30000

#define SYSFS_PATH_MAX 256
#define SYSFS_CLASS_NET "/sys/class/net"

#define FFD_MAGIC 0xffd
#define FFVISD_VERSION 0

#define FFD_PORT 0xffd


static const struct in6_addr ffd_addr = { .s6_addr = {0xff, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xfd} };


typedef struct __attribute__((__packed__)) _ffvisd_eth_address_t {
	uint8_t address[ETH_ALEN];
} ffvisd_eth_address_t;

typedef struct __attribute__((__packed__)) _ffvisd_ipv6_host_address_t {
	uint8_t address[8];
} ffvisd_ipv6_host_address_t;

typedef struct __attribute__((__packed__)) _ffvisd_packet_server_announce_t {
	uint32_t seqno;
	ffvisd_eth_address_t eth_address;
	ffvisd_ipv6_host_address_t address;
} ffvisd_packet_server_announce_t;

typedef struct __attribute__((__packed__)) _ffvisd_packet_announce_t {
	uint16_t magic;
	uint16_t version;
	uint32_t n_servers;
	ffvisd_packet_server_announce_t servers[];
} ffvisd_packet_announce_t;

typedef enum _ffvisd_iftype_t {
	IF_UNKNOWN = 0,
	IF_WIRED,
	IF_WIRELESS,
	IF_VIRTUAL,
	IF_BRIDGE,
	IF_MESH,
	IF_MAX
} ffvisd_iftype_t;

typedef struct _ffvisd_iface_t {
	unsigned ifindex;
	ffvisd_iftype_t iftype;
	char *ifname;
	char *bridge_iface;
	char *mesh_iface;
} ffvisd_iface_t;

typedef struct _ffvisd_orig_t {
	struct _ffvisd_orig_t *next;

	ffvisd_eth_address_t eth_address;
} ffvisd_orig_t;

typedef struct _ffvisd_announce_t {
	struct _ffvisd_announce_t *next;

	struct timeval received;
	ffvisd_packet_server_announce_t announce;
} ffvisd_announce_t;

static const char *ffvisd_iftype_names[IF_MAX] = {
	[IF_UNKNOWN] = "unknown",
	[IF_WIRED] = "wired",
	[IF_WIRELESS] = "wireless",
	[IF_VIRTUAL] = "virtual",
	[IF_BRIDGE] = "bridge",
	[IF_MESH] = "mesh",
};


typedef void (*iface_cb)(const ffvisd_iface_t *iface, void *arg);


static int sockfd;
static char *mesh = "bat0";


ffvisd_announce_t *announcements = NULL;


static void ffvisd_iface_free(ffvisd_iface_t *iface);



/* returns (tp1 - tp2) in milliseconds  */
static inline int timespec_diff(const struct timespec *tp1, const struct timespec *tp2) {
	return ((tp1->tv_sec - tp2->tv_sec))*1000 + (tp1->tv_nsec - tp2->tv_nsec)/1e6;
}


static bool file_readv(const char *file, const char *format, va_list ap) {
	FILE *f = fopen(file, "r");
	if (!f)
		return false;

	int ret = vfscanf(f, format, ap);

	fclose(f);

	return (ret > 0);
}

static bool iface_file_read(const char *ifname, const char *file, const char *format, ...) {
	char filename[SYSFS_PATH_MAX];

	snprintf(filename, SYSFS_PATH_MAX, SYSFS_CLASS_NET"/%s/%s", ifname, file);

	va_list ap;
	va_start(ap, format);
	bool ret = file_readv(filename, format, ap);
	va_end(ap);

	return ret;
}

static bool iface_file_exists(const char *ifname, const char *file) {
	char filename[SYSFS_PATH_MAX];

	snprintf(filename, SYSFS_PATH_MAX, SYSFS_CLASS_NET"/%s/%s", ifname, file);

	struct stat st;
	return (stat(filename, &st) == 0);
}

static bool iface_is_mesh(const char *ifname) {
	return iface_file_exists(ifname, "mesh");
}

static char* iface_get_bridge(const char *ifname) {
	char filename[SYSFS_PATH_MAX], filename2[SYSFS_PATH_MAX] = {0};

	snprintf(filename, SYSFS_PATH_MAX, SYSFS_CLASS_NET"/%s/brport/bridge", ifname);
	if (readlink(filename, filename2, sizeof(filename2)) < 0)
		return NULL;

	return strdup(basename(filename2));
}

static struct in6_addr* iface_get_address(ffvisd_iface_t *iface, int scope) {
	struct msg {
		struct nlmsghdr nh;
		struct ifaddrmsg addr;
		uint8_t attrbuf[16384];
	} msg;

	memset(&msg, 0, sizeof(msg));

	int rtnetlink_sk = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);

	msg.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
	msg.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT;
	msg.nh.nlmsg_type = RTM_GETADDR;

	msg.addr.ifa_family = AF_INET6;

	if(write(rtnetlink_sk, &msg, msg.nh.nlmsg_len) <= 0) {
		fprintf(stderr, "error: write: %m\n");
		close(rtnetlink_sk);
		return NULL;
	}

	int readlen = read(rtnetlink_sk, &msg, sizeof(msg));

	if (readlen <= 0) {
		fprintf(stderr, "error: read: %m\n");
		close(rtnetlink_sk);
		return NULL;
	}

	close(rtnetlink_sk);

	struct msg *chunk;

	for (chunk = &msg; readlen > sizeof(sizeof(struct nlmsghdr));) {
		int len = chunk->nh.nlmsg_len - sizeof(struct nlmsghdr);

		if (len < sizeof(struct ifaddrmsg) || readlen < len)
			return NULL;

		if (!NLMSG_OK(&chunk->nh, readlen))
			return NULL;

		if (chunk->nh.nlmsg_type == RTM_NEWADDR && chunk->addr.ifa_scope == scope && chunk->addr.ifa_index == iface->ifindex) {
			struct rtattr *rta = (struct rtattr *)IFA_RTA(&chunk->addr);
			int rtattrlen = IFA_PAYLOAD(&chunk->nh);

			for (; RTA_OK(rta, rtattrlen); rta = RTA_NEXT(rta, rtattrlen)) {
				if(rta->rta_type == IFA_ADDRESS && rta->rta_len == RTA_LENGTH(16)) {
					struct in6_addr *ret = malloc(sizeof(struct in6_addr));
					memcpy(ret->s6_addr, RTA_DATA(rta), 16);
					return ret;
				}
			}
		}

		readlen -= NLMSG_ALIGN(chunk->nh.nlmsg_len);
		chunk = (struct msg*)((uint8_t*)chunk + NLMSG_ALIGN(chunk->nh.nlmsg_len));
	}

	return NULL;
}

static ffvisd_iface_t* ffvisd_iface_new(const char *ifname, unsigned ifindex) {
	if (!ifname || !ifindex)
		return false;

	ffvisd_iface_t *iface = calloc(1, sizeof(ffvisd_iface_t));

	iface->ifname = strdup(ifname);
	iface->ifindex = ifindex;

	if (!iface_file_read(ifname, "batman_adv/mesh_iface", "%as", &iface->mesh_iface) || !strcmp(iface->mesh_iface, "none")) {
		free(iface->mesh_iface);
		iface->mesh_iface = NULL;
	}

	iface->bridge_iface = iface_get_bridge(ifname);

	int type;
	if (iface_file_read(ifname, "type", "%i", &type) && type == ARPHRD_ETHER) {
		if(iface_file_exists(ifname, "mesh"))
			iface->iftype = IF_MESH;
		else if(iface_file_exists(ifname, "bridge"))
			iface->iftype = IF_BRIDGE;
		else if(iface_file_exists(ifname, "tun_flags"))
			iface->iftype = IF_VIRTUAL;
		else if(iface_file_exists(ifname, "wireless"))
			iface->iftype = IF_WIRELESS;
		else
			iface->iftype = IF_WIRED;
	}

	return iface;
}

static void ffvisd_iface_free(ffvisd_iface_t *iface) {
	if (iface) {
		free(iface->ifname);
		free(iface->bridge_iface);
		free(iface->mesh_iface);
		free(iface);
	}
}

static void ffvisd_iface_foreach(iface_cb cb, void *arg) {
	struct if_nameindex *ifaces = if_nameindex();

	if (!ifaces) {
		fprintf(stderr, "error: if_nameindex: %m\n");
		return;
	}

	int i;
	for (i = 0; ifaces[i].if_name; i++) {
		ffvisd_iface_t *iface = ffvisd_iface_new(ifaces[i].if_name, ifaces[i].if_index);

		if (iface)
			cb(iface, arg);

		ffvisd_iface_free(iface);
	}

	if_freenameindex(ifaces);
}


static void pr_iface_info(const ffvisd_iface_t *iface, void *arg) {
	printf("Interface %s: ifindex=%i bridge_iface=%s mesh_iface=%s iftype=%s\n", iface->ifname, iface->ifindex, iface->bridge_iface, iface->mesh_iface, ffvisd_iftype_names[iface->iftype]);
}


static void join_mcast(const ffvisd_iface_t *iface, void *arg) {
	if (!iface->mesh_iface || strcmp(iface->mesh_iface, mesh))
		return;

	struct ipv6_mreq imr;
	imr.ipv6mr_multiaddr = ffd_addr;
	imr.ipv6mr_interface = iface->ifindex;
	if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &imr, sizeof(struct ipv6_mreq)) && errno != EADDRINUSE)
		fprintf(stderr, "warning: setsockopt: %m\n");
}

static bool check_config() {
	if (!iface_is_mesh(mesh)) {
		fprintf(stderr, "error: configured interface is no mesh\n");
		return false;
	}

	return true;
}

static bool init_socket() {
	sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
	if (sockfd < 0) {
		fprintf(stderr, "error: socket: %m\n");
		return false;
	}

	int val = 1;
	if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val))) {
		fprintf(stderr, "error: setsockopt: %m\n");
		return false;
	}

	val = 0;
	if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val))) {
		fprintf(stderr, "error: setsockopt: %m\n");
		return false;
	}

	struct sockaddr_in6 sa6;
	memset(&sa6, 0, sizeof(sa6));
	sa6.sin6_family = AF_INET6;
	sa6.sin6_port = htons(FFD_PORT);

	if (bind(sockfd, (struct sockaddr*)&sa6, sizeof(struct sockaddr_in6))) {
		fprintf(stderr, "error: bind: %m\n");
		return false;
	}

	return true;
}

static bool init_announcements() {
	ffvisd_iface_t *iface;

	char *ifname = iface_get_bridge(mesh);

	if (ifname) {
		iface = ffvisd_iface_new(ifname, if_nametoindex(ifname));
		free(ifname);
	}
	else {
		iface = ffvisd_iface_new(mesh, if_nametoindex(mesh));
	}

	if (!iface)
		return false;

	ffvisd_announce_t *announce = announcements = calloc(1, sizeof(ffvisd_announce_t));

	uint8_t *a = announce->announce.eth_address.address;
	if (!iface_file_read(iface->ifname, "address", "%x:%x:%x:%x:%x:%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]))
		return false;

	struct in6_addr *addr = iface_get_address(iface, RT_SCOPE_LINK);
	if (!addr) {
		ffvisd_iface_free(iface);
		return false;
	}

	char buf[INET6_ADDRSTRLEN];
	inet_ntop(AF_INET6, addr, buf, sizeof(buf));
	puts(buf);

	memcpy(announce->announce.address.address, addr->s6_addr+8, 8);
	free(addr);

	ffvisd_iface_free(iface);

	return true;
}

static void maintenance() {
	ffvisd_announce_t **announce;

	for(announce = &announcements; *announce; announce = &(*announce)->next) {
		if (!(*announce)->received.tv_sec) /* announcement is local */
			(*announce)->announce.seqno++;
	}
}

int main() {
	if (!check_config())
		return 1;

	ffvisd_iface_foreach(pr_iface_info, NULL);

	if (!init_socket())
		return 1;

	if (!init_announcements())
		return 1;

	while (true) {
		ffvisd_iface_foreach(join_mcast, NULL);

		maintenance();

		usleep(ANNOUNCE_INTERVAL*1000);
	}

	return 0;
}