ip-conflict: Don't remove already removed timer
[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[18];                         /* pad for min. Ethernet payload (60 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 = true;
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         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
140         return G_SOURCE_REMOVE;
141 }
142
143 static gboolean __netconfig_check_arp_receive(GIOChannel *source,
144                                                   GIOCondition condition, gpointer data)
145 {
146         struct sock_data *sd = data;
147         gchar buffer[ARP_PACKET_SIZE] = {0, };
148         gsize bytes_read = 0;
149         struct arp_message arp_recv;
150         char sbuf[WLAN_MAC_ADDR_MAX];
151         char tbuf[WLAN_MAC_ADDR_MAX];
152         const char *default_ip = NULL;
153
154         if (g_io_channel_read_chars(source, buffer, ARP_PACKET_SIZE,
155                                 &bytes_read, NULL) == G_IO_STATUS_NORMAL) {
156                 unsigned int target_ip = 0;
157
158                 memset(&arp_recv, 0, sizeof(arp_recv));
159                 memcpy(&arp_recv, buffer, sizeof(buffer));
160
161                 default_ip = netconfig_get_default_ipaddress();
162                 if (default_ip == NULL) {
163                         INFO("ip address is not set yet");
164                         goto out;
165                 }
166                 target_ip = inet_addr(default_ip);
167
168
169                 /* Only handle ARP replies */
170                 if (arp_recv.operation != htons(ARPOP_REPLY))
171                         goto out;
172
173                 UCHAR_TO_ADDRESS(arp_recv.t_hwaddr, tbuf);
174                 UCHAR_TO_ADDRESS(arp_recv.s_hwaddr, sbuf);
175
176                 int zero_mac = strcmp(tbuf , GRATUITOUS_ARP_MAC_ADDR);
177                 if (zero_mac == 0) {
178                         DBG("Broadcast packet.\n");
179                         goto skip;
180                 }
181                 DBG("our mac= %s source mac= %s target mac= %s", netconfig_get_default_mac_address(), sbuf, tbuf);
182                 int mac_cmp = strcmp(tbuf , netconfig_get_default_mac_address());
183                 if (mac_cmp != 0) {
184                         INFO("Packet not intended to us.\n");
185                         goto out;
186                 }
187 skip:
188                 mac_cmp = strcmp(sbuf, netconfig_get_default_mac_address());
189                 DBG("target ip = %d source ip = %d", target_ip, __convert_uchar_to_uint(arp_recv.s_IPaddr));
190                 if ((mac_cmp != 0) && (__convert_uchar_to_uint(arp_recv.s_IPaddr) == target_ip)) {
191                         sd->iteration = 0;
192                         if (conflict_state != NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED) {
193                                 INFO("ip conflict is detected !\n");
194                                 conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED;
195                                 __netconfig_wifi_notify_ip_conflict("conflict", sbuf);
196                                 sd->timeout = BURST_ARP_SEND_TIME;
197                         }
198
199                         if (sd->arp_reply_timer != -1) {
200                                 g_source_remove(sd->arp_reply_timer);
201                                 sd->arp_reply_timer = -1;
202                         }
203
204                         if (sd->timer_id)
205                                 g_source_remove(sd->timer_id);
206                         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
207
208                 }
209         }
210
211 out:
212         return TRUE;
213 }
214
215 static gboolean send_arp(gpointer data)
216 {
217         struct sock_data *sd = data;
218         struct ether_addr *source_mac = NULL;
219         struct arp_message arp;
220         char error_buf[MAX_SIZE_ERROR_BUFFER] = {0, };
221         unsigned int source_ip = 0;
222         unsigned int target_ip = 0;
223         const unsigned char broadcast_addr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
224         struct sockaddr_ll addr = {0};
225         struct ifreq net_ifr;
226         int ifindex = 0;
227         errno = 0;
228         const char *default_ip = NULL;
229         static int initial_send_arp_count = 0;
230
231         if (initial_bursts && initial_send_arp_count >= INITIAL_BURST_ARP_COUNT) {
232                 initial_bursts = false;
233                 initial_send_arp_count = 0;
234         }
235
236         if (initial_bursts)
237                 initial_send_arp_count++;
238
239         const char *mac = netconfig_get_default_mac_address();
240         if (mac == NULL)
241                 goto err;
242         source_mac = ether_aton(mac);
243         if (source_mac == NULL) {
244                 INFO("Mac address is NULL");
245                 goto err;
246         }
247
248         memset(&arp, 0, sizeof(arp));
249
250         unsigned char  broadcast_mac_addr[MAC_ADDRESS_LENGTH];
251         memset(broadcast_mac_addr, 0xff, sizeof(broadcast_mac_addr));
252         memcpy(arp.h_dest, broadcast_mac_addr, MAC_ADDRESS_LENGTH);             /* MAC dest */
253         memcpy(arp.h_source, source_mac, MAC_ADDRESS_LENGTH);                   /* MAC source */
254
255         arp.h_proto = htons(ETH_P_ARP);                                         /* protocol type (Ethernet) */
256         arp.hw_type = htons(ARPHRD_ETHER);                                      /* hardware type */
257         arp.p_type = htons(ETH_P_IP);                                           /* protocol type (ARP message) */
258         arp.hw_len = MAC_ADDRESS_LENGTH;                                        /* hardware address length */
259         arp.p_len = IP_ADDRESS_LENGTH;                                          /* protocol address length */
260         arp.operation = htons(ARPOP_REQUEST);                                   /* ARP op code */
261         default_ip = netconfig_get_default_ipaddress();
262         if (default_ip == NULL) {
263                 INFO("ip address is not set yet");
264                 goto err;
265         }
266
267         source_ip = inet_addr(ARP_SOURCE_IP);
268         target_ip = inet_addr(default_ip);
269         memcpy(arp.s_IPaddr, &source_ip, IP_ADDRESS_LENGTH);                    /* source IP address */
270         memcpy(arp.s_hwaddr, source_mac, MAC_ADDRESS_LENGTH);                   /* source hardware address */
271         memcpy(arp.t_IPaddr, &target_ip, IP_ADDRESS_LENGTH);                    /* target IP addressshek" */
272
273         memset(&net_ifr, 0, sizeof(net_ifr));
274         /* ifreq structure creation */
275         size_t if_name_len = strlen(netconfig_get_default_ifname());
276         if (if_name_len < sizeof(net_ifr.ifr_name)) {
277                 memcpy(net_ifr.ifr_name, netconfig_get_default_ifname(), if_name_len);
278                 net_ifr.ifr_name[if_name_len] = 0;
279         } else {
280                 INFO("Error : Interface name is too long");
281                 goto err;
282         }
283
284         if (ioctl(sd->chk_conflict_sd, SIOCGIFINDEX, &net_ifr) == -1) {
285                 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER);
286                 INFO("ioctl Failed. Error..... = %s\n", error_buf);
287                 goto err;
288         }
289
290         ifindex = net_ifr.ifr_ifindex;
291         /* Construct the destination address */
292         addr.sll_family = AF_PACKET;
293         addr.sll_ifindex = ifindex;
294         addr.sll_halen = ETHER_ADDR_LEN;
295         addr.sll_protocol = htons(ETH_P_ARP);
296         memcpy(addr.sll_addr, broadcast_addr, ETHER_ADDR_LEN);
297
298         if (sendto(sd->chk_conflict_sd, &arp, sizeof(arp), 0, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
299                 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER);
300                 INFO("Sending ARP Packet Failed. Error. = %s\n", error_buf);
301                 /* close socket */
302                 if (-1 < sd->chk_conflict_sd) {
303                         close(sd->chk_conflict_sd);
304                         sd->chk_conflict_sd = -1;
305                 }
306
307                 /* reopen socket */
308                 if ((sd->chk_conflict_sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) == -1) {
309                         INFO("socket %d", sd->chk_conflict_sd);
310                         strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER);
311                         INFO("socket Failed. Error = %s\n", error_buf);
312                 }
313                 goto err;
314         } else {
315                 DBG("Sent ARP Packet \n");
316         }
317
318         g_source_remove(sd->timer_id);
319
320         if (conflict_state == NETCONFIG_IP_CONFLICT_STATE_CONFLICT_DETECTED || initial_bursts)
321                 sd->timeout = BURST_ARP_SEND_TIME;
322         else
323                 sd->timeout = td.initial_time;
324
325         /* Adding timeout callback for arp request */
326         sd->arp_reply_timer = g_timeout_add(1000, __arp_reply_timeout_cb,
327                                         (gpointer) &sd->arp_reply_timer);
328         return FALSE;
329 err:
330         if (sd->timer_id)
331                 g_source_remove(sd->timer_id);
332         sd->timer_id = g_timeout_add(sd->timeout, send_arp, sd);
333         return FALSE;
334 }
335
336 struct sock_data * start_ip_conflict_mon(void)
337 {
338         if (is_ip_conflict_detect_enabled == false) {
339                 INFO("detection mode is set to false");
340                 return NULL;
341         }
342
343         char error_buf[MAX_SIZE_ERROR_BUFFER] = {0, };
344         initial_bursts = true;
345
346         sd = g_try_malloc0(sizeof(struct sock_data));
347         if (sd == NULL) {
348                 INFO("Failed to malloc sock_data");
349                 return NULL;
350         }
351         sd->chk_conflict_data_id = -1;
352         sd->chk_conflict_sd = -1;
353         sd->timer_id = 0;
354         sd->iteration = 0;
355
356         if ((sd->chk_conflict_sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) == -1) {
357                 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER);
358                 INFO("socket Failed. Error = %s\n", error_buf);
359                 g_free(sd);
360                 return NULL;
361         } else {
362                 sd->chk_conflict_sock_io = g_io_channel_unix_new(sd->chk_conflict_sd);
363                 if (sd->chk_conflict_sock_io == NULL) {
364                         INFO("Failed to create channel");
365                         INFO("Exit");
366                         g_free(sd);
367                         return NULL;
368                 }
369
370                 g_io_channel_set_close_on_unref(sd->chk_conflict_sock_io, TRUE);
371
372                 if (G_IO_STATUS_NORMAL != g_io_channel_set_encoding(sd->chk_conflict_sock_io,
373                                                                    NULL, NULL))
374                         INFO("Failed to set encoding NULL on io channel");
375                 if (G_IO_STATUS_NORMAL != g_io_channel_set_flags(sd->chk_conflict_sock_io,
376                                                                 G_IO_FLAG_NONBLOCK, NULL))
377                         INFO("Failed to set flags on io channel");
378                 sd->chk_conflict_data_id = g_io_add_watch(sd->chk_conflict_sock_io, G_IO_IN,
379                                                           __netconfig_check_arp_receive, sd);
380                 DBG("socket %d", sd->chk_conflict_sd);
381
382                 sd->timeout = td.initial_time;
383                 send_arp(sd);
384                 return sd;
385         }
386 }
387
388 void stop_ip_conflict_mon()
389 {
390         INFO("+");
391         GError* error = NULL;
392         if (sd == NULL) {
393                 INFO("sd is NULL");
394                 return;
395         }
396         if (-1 < sd->chk_conflict_sd) {
397                 if (G_IO_STATUS_NORMAL !=
398                     g_io_channel_shutdown(sd->chk_conflict_sock_io, FALSE,
399                                           &error)) {
400                         INFO("Failure received while shutdown io channel[%d]:[%s]", error->code, error->message);
401                         g_error_free(error);
402                 }
403                 g_io_channel_unref(sd->chk_conflict_sock_io);
404                 g_source_remove(sd->chk_conflict_data_id);
405                 sd->chk_conflict_data_id = -1;
406                 close(sd->chk_conflict_sd);
407                 sd->chk_conflict_sd = -1;
408         }
409         if (sd->timer_id > 0) {
410                 g_source_remove(sd->timer_id);
411                 sd->timer_id = 0;
412         }
413         g_free(sd);
414         sd = NULL;
415         INFO("Monitoring stopped");
416 }
417
418 static void __netconfig_wifi_notify_ip_conflict(char *state, char *mac)
419 {
420         GVariantBuilder *builder = NULL;
421
422         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
423         g_variant_builder_add(builder, "{sv}", "state", g_variant_new_string(state));
424         g_variant_builder_add(builder, "{sv}", "mac", g_variant_new_string(mac));
425
426         wifi_emit_ip_conflict_event((Wifi *)get_wifi_object(), g_variant_builder_end(builder));
427         g_variant_builder_unref(builder);
428
429         /* send notification using net-popup */
430         if (!strcmp(state, "conflict"))
431                 netconfig_send_notification_to_net_popup(NETCONFIG_ADD_IP_CONFLICT_NOTI, mac);
432         else
433                 netconfig_send_notification_to_net_popup(NETCONFIG_DEL_IP_CONFLICT_NOTI, mac);
434
435         return;
436 }
437
438 gboolean handle_ip_conflict_set_enable(Wifi *wifi, GDBusMethodInvocation *context,
439                                        bool detect)
440 {
441         g_return_val_if_fail(wifi != NULL, TRUE);
442
443
444         if (detect == false) {
445                 is_ip_conflict_detect_enabled = false;
446                 conflict_state = NETCONFIG_IP_CONFLICT_STATE_UNKNOWN;
447                 if (sd != NULL)
448                         stop_ip_conflict_mon();
449                 else {
450                         netconfig_error_dbus_method_return(context, NETCONFIG_ERROR_INTERNAL, "AlreadyExists");
451                         wifi_complete_ip_conflict_set_enable(wifi, context);
452                         return TRUE;
453                 }
454         } else {
455                 is_ip_conflict_detect_enabled = true;
456                 conflict_state = NETCONFIG_IP_CONFLICT_STATE_CONFLICT_NOT_DETECTED;
457                 if (sd == NULL) {
458                         if (start_ip_conflict_mon() == NULL) {
459                                 INFO("Failed to start IP conflict monitoring");
460                                 netconfig_error_dbus_method_return(context,
461                                                 NETCONFIG_ERROR_INTERNAL, "Failed");
462                                 wifi_complete_ip_conflict_set_enable(wifi, context);
463                                 return TRUE;
464                         }
465                 } else {
466                         netconfig_error_dbus_method_return(context, NETCONFIG_ERROR_INTERNAL, "AlreadyExists");
467                         wifi_complete_ip_conflict_set_enable(wifi, context);
468                         return TRUE;
469                 }
470         }
471
472         wifi_complete_ip_conflict_set_enable(wifi, context);
473         return TRUE;
474 }
475
476 gboolean handle_is_ip_conflict_detect_enabled(Wifi *wifi, GDBusMethodInvocation *context)
477 {
478         g_return_val_if_fail(wifi != NULL, TRUE);
479         GVariant *param = NULL;
480         param = g_variant_new("(b)", is_ip_conflict_detect_enabled);
481         g_dbus_method_invocation_return_value(context, param);
482         return TRUE;
483 }
484
485 gboolean handle_set_ip_conflict_period(Wifi *wifi, GDBusMethodInvocation *context, guint initial_time)
486 {
487         g_return_val_if_fail(wifi != NULL, TRUE);
488         if (initial_time < MAX_ARP_SEND_TIME && initial_time > MIN_ARP_SEND_TIME) {
489                 netconfig_error_dbus_method_return(context,
490                                                 NETCONFIG_ERROR_INTERNAL, "Failed");
491                 return TRUE;
492         }
493
494         td.initial_time = 1000 * initial_time;
495         // remove timer
496         stop_ip_conflict_mon();
497         start_ip_conflict_mon();
498         wifi_complete_set_ip_conflict_period(wifi, context);
499         return TRUE;
500 }
501
502 gboolean handle_get_ip_conflict_state(Wifi *wifi, GDBusMethodInvocation *context)
503 {
504         g_return_val_if_fail(wifi != NULL, TRUE);
505         GVariant *param = NULL;
506         param = g_variant_new("(u)", conflict_state);
507         g_dbus_method_invocation_return_value(context, param);
508         return TRUE;
509 }
510
511 gboolean handle_get_ip_conflict_period(Wifi *wifi, GDBusMethodInvocation *context)
512 {
513         g_return_val_if_fail(wifi != NULL, TRUE);
514         GVariant *param = NULL;
515         param = g_variant_new("(u)", td.initial_time/1000);
516         g_dbus_method_invocation_return_value(context, param);
517         return TRUE;
518 }