Remove incorrect code
[platform/core/connectivity/net-config.git] / src / ip-conflict-detect.c
1 /*
2  * Network Configuration Module
3  *
4  * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #include <stdio.h>
21 #include <net/if.h>
22 #include <linux/if_packet.h>
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <arpa/inet.h>
26 #include <netinet/ether.h>
27 #include <net/ethernet.h>
28 #include <netinet/in.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <errno.h>
32 #include <glib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <stdbool.h>
36
37 #include "ip-conflict-detect.h"
38 #include "network-state.h"
39 #include "log.h"
40 #include "neterror.h"
41 #include "util.h"
42
43 #define ARP_PACKET_SIZE 60
44 #define MAX_SIZE_ERROR_BUFFER 256
45 #define IP_ADDRESS_LENGTH 4
46 #define MAC_ADDRESS_LENGTH 6
47 #define WLAN_MAC_ADDR_MAX 20
48 #define ARP_SOURCE_IP "0.0.0.0"
49 #define INITIAL_BURST_ARP_COUNT 5
50
51 #define CONFLICT_REMOVE_ITERATION_LIMIT 4
52 #define MIN_ARP_SEND_TIME 20000
53 #define BURST_ARP_SEND_TIME 3000
54 #define MAX_ARP_SEND_TIME 32000
55 #define GRATUITOUS_ARP_MAC_ADDR "00:00:00:00:00:00"
56 #define UCHAR_TO_ADDRESS(hwaddr, buf) do {\
57                 snprintf(buf, WLAN_MAC_ADDR_MAX,\
58                 "%02X:%02X:%02X:%02X:%02X:%02X", hwaddr[0], hwaddr[1],\
59                 hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);\
60                 } while (0)
61
62 struct arp_message {
63         /* Ethernet header */
64         unsigned char   h_dest[MAC_ADDRESS_LENGTH];     /* destination ether addr */
65         unsigned char   h_source[MAC_ADDRESS_LENGTH];   /* source ether addr */
66         unsigned short  h_proto;                                /* packet type ID field */
67
68         /* ARP packet */
69         unsigned short hw_type;                         /* hardware type(ARPHRD_ETHER) */
70         unsigned short p_type;                          /* protocol type(ETH_P_IP) */
71         unsigned char  hw_len;                          /* hardware address length */
72         unsigned char  p_len;                                   /* protocol address length */
73         unsigned short operation;                               /* ARP opcode */
74         unsigned char  s_hwaddr[MAC_ADDRESS_LENGTH];            /* sender hardware address */
75         unsigned char  s_IPaddr[IP_ADDRESS_LENGTH];             /* sender IP address */
76         unsigned char  t_hwaddr[MAC_ADDRESS_LENGTH];            /* target hardware address */
77         unsigned char  t_IPaddr[IP_ADDRESS_LENGTH];             /* target IP address */
78         unsigned char  pad[22];                         /* pad for min. Ethernet payload (64 bytes) */
79 };
80
81 typedef enum {
82         NETCONFIG_IP_CONFLICT_STATE_UNKNOWN,
83         NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED,
84         NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED
85 } ip_conflict_state_e;
86
87 struct timer_data {
88         guint initial_time;
89         guint timeout;
90 };
91 static struct timer_data td = {
92         MIN_ARP_SEND_TIME, MIN_ARP_SEND_TIME
93 };
94
95 int ioctl_sock;
96 static bool initial_bursts = true;
97 bool is_ip_conflict_detect_enabled = false;
98 static gboolean send_arp(gpointer data);
99 static void __netconfig_wifi_notify_ip_conflict(char *state, char *mac);
100 ip_conflict_state_e conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED;
101
102 struct sock_data *sd;
103
104 typedef unsigned int in_addr_t;
105
106 union uchar_to_uint {
107         unsigned int uint;
108         unsigned char uchar[IP_ADDRESS_LENGTH];
109 };
110
111 static unsigned int __convert_uchar_to_uint(unsigned char b[IP_ADDRESS_LENGTH])
112 {
113         int idx = 0;
114         union uchar_to_uint u;
115         for (; idx < IP_ADDRESS_LENGTH; ++idx)
116                 u.uchar[idx] = b[idx];
117
118         return u.uint;
119 }
120
121 static gboolean __arp_reply_timeout_cb(gpointer data)
122 {
123         if (sd == NULL) {
124                 INFO("Ignore timeout cb");
125                 return G_SOURCE_REMOVE;
126         }
127
128         sd->iteration++;
129         sd->arp_reply_timer = -1;
130
131         if (conflict_state != NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED &&
132                         sd->iteration == CONFLICT_REMOVE_ITERATION_LIMIT) {
133                 sd->iteration = 0;
134                 conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED;
135                 __netconfig_wifi_notify_ip_conflict("resolved", GRATUITOUS_ARP_MAC_ADDR);
136                 initial_bursts = true;
137         }
138
139         if (sd->timer_id)
140                 g_source_remove(sd->timer_id);
141         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
142         return G_SOURCE_REMOVE;
143 }
144
145 static gboolean __netconfig_check_arp_receive(GIOChannel *source,
146                                                   GIOCondition condition, gpointer data)
147 {
148         struct sock_data *sd = data;
149         gchar buffer[ARP_PACKET_SIZE] = {0, };
150         gsize bytes_read = 0;
151         struct arp_message arp_recv;
152         char sbuf[WLAN_MAC_ADDR_MAX];
153         char tbuf[WLAN_MAC_ADDR_MAX];
154         const char *default_ip = NULL;
155         int mac_cmp = 0;
156
157         if (g_io_channel_read_chars(source, buffer, ARP_PACKET_SIZE,
158                                 &bytes_read, NULL) == G_IO_STATUS_NORMAL) {
159                 unsigned int target_ip = 0;
160
161                 memset(&arp_recv, 0, sizeof(arp_recv));
162                 memcpy(&arp_recv, buffer, sizeof(buffer));
163
164                 default_ip = netconfig_get_default_ipaddress();
165                 if (default_ip == NULL) {
166                         INFO("ip address is not set yet");
167                         goto out;
168                 }
169                 target_ip = inet_addr(default_ip);
170
171
172                 /* Only handle ARP replies */
173                 if (arp_recv.operation != htons(ARPOP_REPLY))
174                         goto out;
175
176                 UCHAR_TO_ADDRESS(arp_recv.t_hwaddr, tbuf);
177                 UCHAR_TO_ADDRESS(arp_recv.s_hwaddr, sbuf);
178
179                 int zero_mac = strcmp(tbuf , GRATUITOUS_ARP_MAC_ADDR);
180                 if (zero_mac == 0) {
181                         DBG("Broadcast packet.\n");
182                         goto skip;
183                 }
184                 DBG("our mac= %s source mac= %s target mac= %s", netconfig_get_default_mac_address(), sbuf, tbuf);
185                 mac_cmp = strcmp(tbuf , netconfig_get_default_mac_address());
186                 if (mac_cmp != 0) {
187                         INFO("Packet not intended to us.\n");
188                         goto out;
189                 }
190 skip:
191                 mac_cmp = strcmp(sbuf, netconfig_get_default_mac_address());
192                 DBG("target ip = %d source ip = %d", target_ip, __convert_uchar_to_uint(arp_recv.s_IPaddr));
193                 if ((mac_cmp != 0) && (__convert_uchar_to_uint(arp_recv.s_IPaddr) == target_ip)) {
194                         sd->iteration = 0;
195                         if (conflict_state != NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED) {
196                                 INFO("ip conflict is detected !\n");
197                                 conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED;
198                                 __netconfig_wifi_notify_ip_conflict("conflict", sbuf);
199                                 sd->timeout = BURST_ARP_SEND_TIME;
200                         }
201
202                         if (sd->arp_reply_timer != -1) {
203                                 g_source_remove(sd->arp_reply_timer);
204                                 sd->arp_reply_timer = -1;
205                         }
206
207                         if (sd->timer_id)
208                                 g_source_remove(sd->timer_id);
209                         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
210                 }
211         }
212
213 out:
214         return TRUE;
215 }
216
217 static void __close_channel_and_sock(struct sock_data *sd)
218 {
219         if (sd == NULL)
220                 return;
221
222         g_io_channel_unref(sd->chk_conflict_sock_io);
223         g_source_remove(sd->chk_conflict_data_id);
224         sd->chk_conflict_data_id = -1;
225
226         close(sd->chk_conflict_sd);
227         sd->chk_conflict_sd = -1;
228 }
229
230 static int __open_channel_and_sock(struct sock_data *sd)
231 {
232         if (sd == NULL)
233                 return -1;
234
235         if ((sd->chk_conflict_sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) == -1) {
236                 INFO("socket Failed.\n");
237                 return -1;
238         }
239
240         sd->chk_conflict_sock_io = g_io_channel_unix_new(sd->chk_conflict_sd);
241         if (sd->chk_conflict_sock_io == NULL) {
242                 INFO("Failed to create channel");
243                 close(sd->chk_conflict_sd);
244                 sd->chk_conflict_sd = -1;
245                 return -1;
246         }
247
248         if (G_IO_STATUS_NORMAL != g_io_channel_set_encoding(sd->chk_conflict_sock_io, NULL, NULL))
249                 INFO("Failed to set encoding NULL on io channel");
250
251         if (G_IO_STATUS_NORMAL != g_io_channel_set_flags(sd->chk_conflict_sock_io,
252                                 G_IO_FLAG_NONBLOCK, NULL))
253                 INFO("Failed to set flags on io channel");
254
255         sd->chk_conflict_data_id = g_io_add_watch(sd->chk_conflict_sock_io, G_IO_IN,
256                         __netconfig_check_arp_receive, sd);
257         DBG("socket %d", sd->chk_conflict_sd);
258         return 0;
259 }
260
261 static gboolean send_arp(gpointer data)
262 {
263         struct sock_data *sd = data;
264         struct ether_addr *source_mac = NULL;
265         struct arp_message arp;
266         char error_buf[MAX_SIZE_ERROR_BUFFER] = {0, };
267         unsigned int source_ip = 0;
268         unsigned int target_ip = 0;
269         const unsigned char broadcast_addr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
270         struct sockaddr_ll addr = {0};
271         struct ifreq net_ifr;
272         int ifindex = 0;
273         errno = 0;
274         const char *default_ip = NULL;
275         const char *if_name = NULL;
276         static int initial_send_arp_count = 0;
277
278         if (initial_bursts && initial_send_arp_count >= INITIAL_BURST_ARP_COUNT) {
279                 initial_bursts = false;
280                 initial_send_arp_count = 0;
281         }
282
283         if (initial_bursts)
284                 initial_send_arp_count++;
285
286         const char *mac = netconfig_get_default_mac_address();
287         if (mac == NULL)
288                 goto err;
289         source_mac = ether_aton(mac);
290         if (source_mac == NULL) {
291                 INFO("Mac address is NULL");
292                 goto err;
293         }
294
295         memset(&arp, 0, sizeof(arp));
296
297         unsigned char  broadcast_mac_addr[MAC_ADDRESS_LENGTH];
298         memset(broadcast_mac_addr, 0xff, sizeof(broadcast_mac_addr));
299         memcpy(arp.h_dest, broadcast_mac_addr, MAC_ADDRESS_LENGTH);             /* MAC dest */
300         memcpy(arp.h_source, source_mac, MAC_ADDRESS_LENGTH);                   /* MAC source */
301
302         arp.h_proto = htons(ETH_P_ARP);                                         /* protocol type (Ethernet) */
303         arp.hw_type = htons(ARPHRD_ETHER);                                      /* hardware type */
304         arp.p_type = htons(ETH_P_IP);                                           /* protocol type (ARP message) */
305         arp.hw_len = MAC_ADDRESS_LENGTH;                                        /* hardware address length */
306         arp.p_len = IP_ADDRESS_LENGTH;                                          /* protocol address length */
307         arp.operation = htons(ARPOP_REQUEST);                                   /* ARP op code */
308         default_ip = netconfig_get_default_ipaddress();
309         if (default_ip == NULL) {
310                 INFO("ip address is not set yet");
311                 goto err;
312         }
313
314         source_ip = inet_addr(ARP_SOURCE_IP);
315         target_ip = inet_addr(default_ip);
316         memcpy(arp.s_IPaddr, &source_ip, IP_ADDRESS_LENGTH);                    /* source IP address */
317         memcpy(arp.s_hwaddr, source_mac, MAC_ADDRESS_LENGTH);                   /* source hardware address */
318         memcpy(arp.t_IPaddr, &target_ip, IP_ADDRESS_LENGTH);                    /* target IP addressshek" */
319
320         memset(&net_ifr, 0, sizeof(net_ifr));
321         /* ifreq structure creation */
322         if_name = netconfig_get_default_ifname();
323         size_t if_name_len = strlen(if_name);
324
325         if (if_name_len == 0) {
326                 INFO("Error : Unable to get interface name ");
327                 goto err;
328         }
329
330         if (if_name_len < sizeof(net_ifr.ifr_name)) {
331                 memcpy(net_ifr.ifr_name, netconfig_get_default_ifname(), if_name_len);
332                 net_ifr.ifr_name[if_name_len] = 0;
333         } else {
334                 INFO("Error : Interface name is too long");
335                 goto err;
336         }
337
338         if (ioctl(sd->chk_conflict_sd, SIOCGIFINDEX, &net_ifr) == -1) {
339                 INFO("ioctl Failed. Error..... = %s\n",
340                                 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
341                 goto err;
342         }
343
344         ifindex = net_ifr.ifr_ifindex;
345         /* Construct the destination address */
346         addr.sll_family = AF_PACKET;
347         addr.sll_ifindex = ifindex;
348         addr.sll_halen = ETHER_ADDR_LEN;
349         addr.sll_protocol = htons(ETH_P_ARP);
350         memcpy(addr.sll_addr, broadcast_addr, ETHER_ADDR_LEN);
351
352         if (sendto(sd->chk_conflict_sd, &arp, sizeof(arp), 0,
353                                 (struct sockaddr*)&addr, sizeof(addr)) < 0) {
354                 INFO("Sending ARP Packet Failed. Error. = %s\n",
355                                 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
356                 __close_channel_and_sock(sd);
357                 if (__open_channel_and_sock(sd) == -1)
358                         INFO("__open_channel_and_sock failed");
359                 goto err;
360         } else {
361                 DBG("Sent ARP Packet \n");
362         }
363
364         if (sd->timer_id) {
365                 g_source_remove(sd->timer_id);
366                 sd->timer_id = 0;
367         }
368
369         if (conflict_state == NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED || initial_bursts)
370                 sd->timeout = BURST_ARP_SEND_TIME;
371         else
372                 sd->timeout = td.initial_time;
373
374         /* Adding timeout callback for arp request */
375         sd->arp_reply_timer = g_timeout_add(1000, __arp_reply_timeout_cb,
376                                         (gpointer) &sd->arp_reply_timer);
377         return FALSE;
378 err:
379         if (sd->timer_id)
380                 g_source_remove(sd->timer_id);
381         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
382         return FALSE;
383 }
384
385 struct sock_data * start_ip_conflict_mon(void)
386 {
387         if (is_ip_conflict_detect_enabled == true) {
388                 INFO("detection mode is set to true");
389                 return NULL;
390         }
391
392         initial_bursts = true;
393
394         sd = g_try_malloc0(sizeof(struct sock_data));
395         if (sd == NULL) {
396                 INFO("Failed to malloc sock_data");
397                 return NULL;
398         }
399         sd->chk_conflict_data_id = -1;
400         sd->chk_conflict_sd = -1;
401
402         if (__open_channel_and_sock(sd) == -1) {
403                 INFO("__open_channel_and_sock failed");
404                 g_free(sd);
405                 return NULL;
406         }
407
408         sd->timeout = td.initial_time;
409         send_arp(sd);
410         is_ip_conflict_detect_enabled = true;
411         conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED;
412
413         return sd;
414 }
415
416 void stop_ip_conflict_mon()
417 {
418         INFO("+");
419         if (sd == NULL) {
420                 INFO("sd is NULL");
421                 return;
422         }
423
424         if (-1 < sd->chk_conflict_sd)
425                 __close_channel_and_sock(sd);
426
427         if (sd->timer_id) {
428                 g_source_remove(sd->timer_id);
429         }
430         g_free(sd);
431         sd = NULL;
432         is_ip_conflict_detect_enabled = false;
433         conflict_state = NETCONFIG_IP_CONFLICT_STATE_UNKNOWN;
434         INFO("Monitoring stopped");
435 }
436
437 static void __netconfig_wifi_notify_ip_conflict(char *state, char *mac)
438 {
439         GVariantBuilder *builder = NULL;
440
441         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
442         g_variant_builder_add(builder, "{sv}", "state", g_variant_new_string(state));
443         g_variant_builder_add(builder, "{sv}", "mac", g_variant_new_string(mac));
444
445         wifi_emit_ip_conflict_event((Wifi *)get_wifi_object(), g_variant_builder_end(builder));
446         g_variant_builder_unref(builder);
447
448         /* send notification using net-popup */
449         if (!strcmp(state, "conflict"))
450                 netconfig_send_notification_to_net_popup(NETCONFIG_ADD_IP_CONFLICT_NOTI, mac);
451         else
452                 netconfig_send_notification_to_net_popup(NETCONFIG_DEL_IP_CONFLICT_NOTI, mac);
453
454         return;
455 }
456
457 gboolean handle_ip_conflict_set_enable(Wifi *wifi, GDBusMethodInvocation *context,
458                                        bool detect)
459 {
460         g_return_val_if_fail(wifi != NULL, TRUE);
461
462         if (detect == false) {
463                 if (sd != NULL)
464                         stop_ip_conflict_mon();
465                 else {
466                         netconfig_error_dbus_method_return(context, NETCONFIG_ERROR_INTERNAL, "AlreadyExists");
467                         return TRUE;
468                 }
469         } else {
470                 if (sd == NULL) {
471                         if (start_ip_conflict_mon() == NULL) {
472                                 INFO("Failed to start IP conflict monitoring");
473                                 netconfig_error_dbus_method_return(context,
474                                                 NETCONFIG_ERROR_INTERNAL, "Failed");
475                                 return TRUE;
476                         }
477                 } else {
478                         netconfig_error_dbus_method_return(context, NETCONFIG_ERROR_INTERNAL, "AlreadyExists");
479                         return TRUE;
480                 }
481         }
482
483         wifi_complete_ip_conflict_set_enable(wifi, context);
484         return TRUE;
485 }
486
487 gboolean handle_is_ip_conflict_detect_enabled(Wifi *wifi, GDBusMethodInvocation *context)
488 {
489         g_return_val_if_fail(wifi != NULL, TRUE);
490         GVariant *param = NULL;
491         param = g_variant_new("(b)", is_ip_conflict_detect_enabled);
492         g_dbus_method_invocation_return_value(context, param);
493         return TRUE;
494 }
495
496 gboolean handle_set_ip_conflict_period(Wifi *wifi, GDBusMethodInvocation *context, guint initial_time)
497 {
498         g_return_val_if_fail(wifi != NULL, TRUE);
499         INFO("%d", initial_time);
500         if (initial_time > MAX_ARP_SEND_TIME || initial_time < MIN_ARP_SEND_TIME) {
501                 netconfig_error_dbus_method_return(context,
502                                                 NETCONFIG_ERROR_INTERNAL, "Failed");
503                 return TRUE;
504         }
505
506         td.initial_time = 1000 * initial_time;
507         // remove timer
508         stop_ip_conflict_mon();
509         start_ip_conflict_mon();
510         wifi_complete_set_ip_conflict_period(wifi, context);
511         return TRUE;
512 }
513
514 gboolean handle_get_ip_conflict_state(Wifi *wifi, GDBusMethodInvocation *context)
515 {
516         g_return_val_if_fail(wifi != NULL, TRUE);
517         GVariant *param = NULL;
518         param = g_variant_new("(u)", conflict_state);
519         g_dbus_method_invocation_return_value(context, param);
520         return TRUE;
521 }
522
523 gboolean handle_get_ip_conflict_period(Wifi *wifi, GDBusMethodInvocation *context)
524 {
525         g_return_val_if_fail(wifi != NULL, TRUE);
526         GVariant *param = NULL;
527         param = g_variant_new("(u)", td.initial_time/1000);
528         g_dbus_method_invocation_return_value(context, param);
529         return TRUE;
530 }