wlantest: Add preliminary version of IEEE 802.11 protocol testing tool
[mech_eap.git] / wlantest / monitor.c
1 /*
2  * Linux packet socket monitor
3  * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "utils/includes.h"
16 #include <net/if.h>
17 #include <netpacket/packet.h>
18
19 #include "utils/common.h"
20 #include "utils/eloop.h"
21 #include "wlantest.h"
22
23
24 static void monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
25 {
26         struct wlantest *wt = eloop_ctx;
27         u8 buf[3000];
28         int len;
29
30         len = recv(sock, buf, sizeof(buf), 0);
31         if (len < 0) {
32                 wpa_printf(MSG_INFO, "recv(PACKET): %s", strerror(errno));
33                 return;
34         }
35
36         wlantest_process(wt, buf, len);
37 }
38
39
40 int monitor_init(struct wlantest *wt, const char *ifname)
41 {
42         struct sockaddr_ll ll;
43
44         os_memset(&ll, 0, sizeof(ll));
45         ll.sll_family = AF_PACKET;
46         ll.sll_ifindex = if_nametoindex(ifname);
47         if (ll.sll_ifindex == 0) {
48                 wpa_printf(MSG_ERROR, "Monitor interface '%s' does not exist",
49                            ifname);
50                 return -1;
51         }
52
53         wt->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
54         if (wt->monitor_sock < 0) {
55                 wpa_printf(MSG_ERROR, "socket(PF_PACKET,SOCK_RAW): %s",
56                            strerror(errno));
57                 return -1;
58         }
59
60         if (bind(wt->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
61                 wpa_printf(MSG_ERROR, "bind(PACKET): %s", strerror(errno));
62                 close(wt->monitor_sock);
63                 wt->monitor_sock = -1;
64                 return -1;
65         }
66
67         if (eloop_register_read_sock(wt->monitor_sock, monitor_read, wt, NULL))
68         {
69                 wpa_printf(MSG_ERROR, "Could not register monitor read "
70                            "socket");
71                 close(wt->monitor_sock);
72                 wt->monitor_sock = -1;
73                 return -1;
74         }
75
76         return 0;
77 }
78
79
80 void monitor_deinit(struct wlantest *wt)
81 {
82         if (wt->monitor_sock >= 0) {
83                 eloop_unregister_read_sock(wt->monitor_sock);
84                 close(wt->monitor_sock);
85                 wt->monitor_sock = -1;
86         }
87 }