Added new vconf key for VCONFKEY_SETAPPL_DATA_RESTRICTION_INT
[platform/core/connectivity/stc-manager.git] / src / monitor / stc-monitor.c
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <linux/netlink.h>
18 #include <vconf.h>
19 #include <vconf-keys.h>
20
21 #include "stc-default-connection.h"
22 #include "helper-nl.h"
23 #include "helper-nfacct-rule.h"
24 #include "helper-net-cls.h"
25 #include "helper-cgroup.h"
26 #include "helper-iptables.h"
27 #include "counter.h"
28 #include "table-statistics.h"
29 #include "table-counters.h"
30 #include "stc-monitor.h"
31 #include "stc-time.h"
32 #include "stc-manager-plugin-appstatus.h"
33 #include "stc-manager-plugin-exception.h"
34
35 #define GRANULARITY 10
36 #define MAX_INT_LENGTH 128
37
38 #ifndef VCONFKEY_STC_BACKGROUND_STATE
39 #define VCONFKEY_STC_BACKGROUND_STATE "db/stc/background_state"
40 #endif
41
42 #ifndef VCONFKEY_SETAPPL_DATA_RESTRICTION_INT
43 #define VCONFKEY_SETAPPL_DATA_RESTRICTION_INT "db/setting/data_restriction"
44 #endif
45
46 typedef struct {
47         time_t now;
48         time_t month_start_ts;
49         time_t week_start_ts;
50         time_t day_start_ts;
51         int is_updated;
52 } reset_time_limits_context_s;
53
54 typedef struct {
55         stc_app_key_s *app_key;
56         stc_process_key_s *proc_key;
57         gboolean entry_removed;
58 } remove_pid_context_s;
59
60 typedef struct {
61         struct nfacct_rule *counter;
62         int64_t bytes;
63         gboolean data_limit_exceeded;
64 } classid_bytes_context_s;
65
66 static stc_system_s *g_system = NULL;
67
68 //LCOV_EXCL_START
69 static int __vconf_get_int(const char *key, int *value)
70 {
71         int ret = 0;
72
73         ret = vconf_get_int(key, value);
74         if (ret != VCONF_OK) {
75                 STC_LOGE("Failed to get vconfkey [%s] value", key); //LCOV_EXCL_LINE
76                 return -1; //LCOV_EXCL_LINE
77         }
78
79         return 0;
80 }
81
82 static int __vconf_set_int(const char *key, int value)
83 {
84         int ret = 0;
85
86         ret = vconf_set_int(key, value);
87         if (ret != VCONF_OK) {
88                 STC_LOGE("Failed to set vconfkey [%s] value", key); //LCOV_EXCL_LINE
89                 return -1; //LCOV_EXCL_LINE
90         }
91
92         return 0;
93 }
94 //LCOV_EXCL_STOP
95
96 static nfacct_rule_jump __get_jump_by_intend(struct nfacct_rule *counter)
97 {
98         if (counter->intend == NFACCT_WARN)
99                 return NFACCT_JUMP_ACCEPT;
100         else if (counter->intend == NFACCT_BLOCK)
101                 return NFACCT_JUMP_REJECT;
102         else if (counter->intend == NFACCT_ALLOW)
103                 return NFACCT_JUMP_ACCEPT;
104
105         return NFACCT_JUMP_UNKNOWN;
106 }
107
108 static stc_error_e __add_iptables_in(struct nfacct_rule *counter)
109 {
110         if (counter == NULL)
111                 return STC_ERROR_INVALID_PARAMETER;
112
113         counter->action = NFACCT_ACTION_INSERT;
114         counter->iotype = NFACCT_COUNTER_IN;
115         counter->jump = __get_jump_by_intend(counter);
116         counter->iptype = NFACCT_TYPE_IPV4;
117         counter->send_limit = 0;
118         counter->rcv_limit = 0;
119
120         return produce_net_rule(counter);
121 }
122
123 static stc_error_e __add_iptables_out(struct nfacct_rule *counter)
124 {
125         if (counter == NULL)
126                 return STC_ERROR_INVALID_PARAMETER;
127
128         counter->action = NFACCT_ACTION_INSERT;
129         counter->iotype = NFACCT_COUNTER_OUT;
130         counter->jump = __get_jump_by_intend(counter);
131         counter->iptype = NFACCT_TYPE_IPV4;
132         counter->send_limit = 0;
133         counter->rcv_limit = 0;
134
135         return produce_net_rule(counter);
136 }
137
138 static stc_error_e __del_iptables_in(struct nfacct_rule *counter)
139 {
140         if (counter == NULL)
141                 return STC_ERROR_INVALID_PARAMETER;
142
143         counter->action = NFACCT_ACTION_DELETE;
144         counter->iotype = NFACCT_COUNTER_IN;
145         counter->jump = __get_jump_by_intend(counter);
146         counter->iptype = NFACCT_TYPE_IPV4;
147         counter->send_limit = 0;
148         counter->rcv_limit = 0;
149
150         return produce_net_rule(counter);
151 }
152
153 static stc_error_e __del_iptables_out(struct nfacct_rule *counter)
154 {
155         if (counter == NULL)
156                 return STC_ERROR_INVALID_PARAMETER;
157
158         counter->action = NFACCT_ACTION_DELETE;
159         counter->iotype = NFACCT_COUNTER_OUT;
160         counter->jump = __get_jump_by_intend(counter);
161         counter->iptype = NFACCT_TYPE_IPV4;
162         counter->send_limit = 0;
163         counter->rcv_limit = 0;
164
165         return produce_net_rule(counter);
166 }
167
168 static stc_error_e __add_ip6tables_in(struct nfacct_rule *counter)
169 {
170         if (counter == NULL)
171                 return STC_ERROR_INVALID_PARAMETER;
172
173         counter->action = NFACCT_ACTION_INSERT;
174         counter->iotype = NFACCT_COUNTER_IN;
175         counter->jump = __get_jump_by_intend(counter);
176         counter->iptype = NFACCT_TYPE_IPV6;
177         counter->send_limit = 0;
178         counter->rcv_limit = 0;
179
180         return produce_net_rule(counter);
181 }
182
183 static stc_error_e __add_ip6tables_out(struct nfacct_rule *counter)
184 {
185         if (counter == NULL)
186                 return STC_ERROR_INVALID_PARAMETER;
187
188         counter->action = NFACCT_ACTION_INSERT;
189         counter->iotype = NFACCT_COUNTER_OUT;
190         counter->jump = __get_jump_by_intend(counter);
191         counter->iptype = NFACCT_TYPE_IPV6;
192         counter->send_limit = 0;
193         counter->rcv_limit = 0;
194
195         return produce_net_rule(counter);
196 }
197
198 static stc_error_e __del_ip6tables_in(struct nfacct_rule *counter)
199 {
200         if (counter == NULL)
201                 return STC_ERROR_INVALID_PARAMETER;
202
203         counter->action = NFACCT_ACTION_DELETE;
204         counter->iotype = NFACCT_COUNTER_IN;
205         counter->jump = __get_jump_by_intend(counter);
206         counter->iptype = NFACCT_TYPE_IPV6;
207         counter->send_limit = 0;
208         counter->rcv_limit = 0;
209
210         return produce_net_rule(counter);
211 }
212
213 static stc_error_e __del_ip6tables_out(struct nfacct_rule *counter)
214 {
215         if (counter == NULL)
216                 return STC_ERROR_INVALID_PARAMETER;
217
218         counter->action = NFACCT_ACTION_DELETE;
219         counter->iotype = NFACCT_COUNTER_OUT;
220         counter->jump = __get_jump_by_intend(counter);
221         counter->iptype = NFACCT_TYPE_IPV6;
222         counter->send_limit = 0;
223         counter->rcv_limit = 0;
224
225         return produce_net_rule(counter);
226 }
227
228 static int __processes_tree_key_compare(gconstpointer a, gconstpointer b,
229                                         gpointer UNUSED user_data)
230 {
231         stc_process_key_s *key_a = (stc_process_key_s *)a;
232         stc_process_key_s *key_b = (stc_process_key_s *)b;
233
234         return key_a->pid - key_b->pid;
235 }
236
237 static void __processes_tree_value_free(gpointer data)
238 {
239         stc_process_value_s *value = (stc_process_value_s *)data;
240
241         FREE(value);
242 }
243
244 static void __processes_tree_key_free(gpointer data)
245 {
246         stc_process_key_s *key = (stc_process_key_s *)data;
247
248         FREE(key);
249 }
250
251 static int __apps_tree_key_compare(gconstpointer a, gconstpointer b,
252                                    gpointer UNUSED user_data)
253 {
254         stc_app_key_s *key_a = (stc_app_key_s *)a;
255         stc_app_key_s *key_b = (stc_app_key_s *)b;
256         gint ret;
257
258         ret = g_strcmp0(key_a->pkg_id, key_b->pkg_id);
259         if (ret)
260                 return ret;
261
262         return g_strcmp0(key_a->app_id, key_b->app_id);
263 }
264
265 static void __apps_tree_value_free(gpointer data)
266 {
267         stc_app_value_s *value = (stc_app_value_s *)data;
268
269         g_tree_destroy(value->processes);
270         value->processes = NULL;
271
272         FREE(value);
273 }
274
275 static void __apps_tree_key_free(gpointer data)
276 {
277         stc_app_key_s *key = (stc_app_key_s *)data;
278
279         g_free(key->pkg_id);
280         g_free(key->app_id);
281         FREE(key);
282 }
283
284 static int __rstns_tree_key_compare(gconstpointer a, gconstpointer b,
285                                     gpointer UNUSED user_data)
286 {
287         stc_rstn_key_s *key_a = (stc_rstn_key_s *)a;
288         stc_rstn_key_s *key_b = (stc_rstn_key_s *)b;
289         int ret;
290
291         ret = g_strcmp0(key_a->app_id, key_b->app_id);
292         if (ret != 0)
293                 return ret;
294
295         ret = g_strcmp0(key_a->ifname, key_b->ifname);
296         if (ret != 0)
297                 return ret;
298
299         ret = g_strcmp0(key_a->subscriber_id, key_b->subscriber_id);
300         if (ret != 0)
301                 return ret;
302
303         ret = key_a->iftype - key_b->iftype;
304         if (ret != 0)
305                 return ret;
306
307         ret = key_a->roaming - key_b->roaming;
308         if (ret != 0)
309                 return ret;
310
311         return 0;
312 }
313
314 static void __rstns_tree_value_free(gpointer data)
315 {
316         stc_rstn_value_s *value = (stc_rstn_value_s *)data;
317
318         FREE(value);
319 }
320
321 static void __rstns_tree_key_free(gpointer data)
322 {
323         stc_rstn_key_s *key = (stc_rstn_key_s *)data;
324
325         FREE(key->app_id);
326         FREE(key->ifname);
327         FREE(key->subscriber_id);
328         FREE(key);
329 }
330
331 /*
332 //LCOV_EXCL_START
333 static gboolean __processes_tree_foreach_print(gpointer key, gpointer value,
334                                                gpointer data)
335 {
336         stc_process_key_s *proc_key = (stc_process_key_s *)key;
337         stc_process_value_s *proc_value = (stc_process_value_s *)value;
338
339         STC_LOGD("Process entry => PID [\033[1;33m%d\033[0;m], Ground state [%d]",
340                  proc_key->pid, proc_value->ground);
341         return FALSE;
342 }
343
344 static void __processes_tree_printall(GTree *processes)
345 {
346         g_tree_foreach(processes, __processes_tree_foreach_print, NULL);
347 }
348
349 static gboolean __apps_tree_foreach_print(gpointer key, gpointer value,
350                                           gpointer data)
351 {
352         stc_app_key_s *app_key = (stc_app_key_s *)key;
353         stc_app_value_s *app_value = (stc_app_value_s *)value;
354
355         STC_LOGD("Application info => Pkg ID [\033[0;34m%s\033[0;m], "
356                  "App ID [\033[0;32m%s\033[0;m], Type [%d], classid [%d],"
357                  " counter [ in (%lld), out (%lld)]",
358                  app_key->pkg_id, app_key->app_id,
359                  app_value->type, app_value->classid,
360                  app_value->data_usage.in_bytes, app_value->data_usage.out_bytes);
361
362         __processes_tree_printall(app_value->processes);
363         return FALSE;
364 }
365
366 static void __apps_tree_printall(void)
367 {
368         g_tree_foreach(g_system->apps, __apps_tree_foreach_print, NULL);
369 }
370 //LCOV_EXCL_STOP
371 */
372
373 static gboolean __apps_tree_foreach_remove_pid(gpointer key, gpointer value,
374                                                gpointer data)
375 {
376         remove_pid_context_s *context = (remove_pid_context_s *)data;
377         stc_app_value_s *app_value = (stc_app_value_s *)value;
378
379         if (!g_tree_remove(app_value->processes, context->proc_key))
380                 return FALSE;
381
382         context->entry_removed = TRUE;
383         context->app_key = (stc_app_key_s *)key;
384
385         return TRUE;
386 }
387
388 static stc_app_value_s * __application_lookup(GTree *apps,
389                                               const stc_app_key_s *key)
390 {
391         stc_app_value_s *lookup;
392
393         ret_value_msg_if(apps == NULL, NULL, "apps is null!");
394
395         lookup = g_tree_lookup(apps, key);
396
397         return lookup;
398 }
399
400 static stc_process_value_s * __process_lookup(GTree *processes,
401                                               const stc_process_key_s *key)
402 {
403         stc_process_value_s *lookup;
404
405         ret_value_msg_if(processes == NULL, NULL, "processes is null!");
406
407         lookup = g_tree_lookup(processes, key);
408
409         return lookup;
410 }
411
412 //LCOV_EXCL_START
413 static gboolean __processes_tree_check_empty(gpointer key, gpointer value,
414                                              gpointer data)
415 {
416         guint *pid_count = (guint *)data;
417         (*pid_count)++;
418         return TRUE;
419 }
420 //LCOV_EXCL_STOP
421
422 static gboolean __add_application_monitor(gpointer key, gpointer value,
423                                           gpointer data)
424 {
425         stc_app_value_s *app_value = (stc_app_value_s *)value;
426         default_connection_s *connection = (default_connection_s *)data;
427         stc_s *stc = stc_get_manager();
428
429         if (app_value->classid == STC_TOTAL_DATACALL_CLASSID ||
430             app_value->classid == STC_TOTAL_WIFI_CLASSID ||
431             app_value->classid == STC_TOTAL_BLUETOOTH_CLASSID)
432                 return FALSE;
433
434         if (stc && connection && connection->ifname) {
435                 struct nfacct_rule counter;
436
437                 if (!stc->carg) {
438                         stc->carg = MALLOC0(counter_arg_s, 1); //LCOV_EXCL_LINE
439                         if (stc->carg == NULL) //LCOV_EXCL_LINE
440                                 return FALSE; //LCOV_EXCL_LINE
441
442                         stc->carg->sock = stc_monitor_get_counter_socket(); //LCOV_EXCL_LINE
443                 }
444
445                 memset(&counter, 0, sizeof(struct nfacct_rule));
446
447                 counter.carg = stc->carg;
448                 counter.classid = app_value->classid;
449                 counter.intend = NFACCT_COUNTER;
450
451                 if (connection->tether_state == TRUE &&
452                         connection->tether_iface.ifname != NULL &&
453                         app_value->classid == STC_TETHERING_APP_CLASSID) {
454                         counter.iftype = connection->tether_iface.type;
455                         g_strlcpy(counter.ifname, connection->tether_iface.ifname, MAX_IFACE_LENGTH);
456                 } else {
457                         counter.iftype = connection->type;
458                         g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
459                 }
460
461                 if (app_value->classid == STC_TOTAL_IPV4_CLASSID) {
462                         __add_iptables_in(&counter);
463                         __add_iptables_out(&counter);
464                 } else if (app_value->classid == STC_TOTAL_IPV6_CLASSID) {
465                         __add_ip6tables_in(&counter);
466                         __add_ip6tables_out(&counter);
467                 } else {
468                         __add_iptables_in(&counter);
469                         __add_iptables_out(&counter);
470                         __add_ip6tables_in(&counter);
471                         __add_ip6tables_out(&counter);
472                 }
473         }
474
475         return FALSE;
476 }
477
478 static gboolean __remove_application_monitor(gpointer key, gpointer value,
479                                              gpointer data)
480 {
481         stc_app_value_s *app_value = (stc_app_value_s *)value;
482         default_connection_s *connection = (default_connection_s *)data;
483         stc_s *stc = stc_get_manager();
484
485         if (stc && connection && connection->ifname) {
486                 struct nfacct_rule counter;
487
488                 if (!stc->carg) {
489                         stc->carg = MALLOC0(counter_arg_s, 1); //LCOV_EXCL_LINE
490                         if (stc->carg == NULL) //LCOV_EXCL_LINE
491                                 return FALSE; //LCOV_EXCL_LINE
492
493                         stc->carg->sock = stc_monitor_get_counter_socket(); //LCOV_EXCL_LINE
494                 }
495
496                 memset(&counter, 0, sizeof(struct nfacct_rule));
497
498                 counter.carg = stc->carg;
499                 counter.classid = app_value->classid;
500                 counter.intend = NFACCT_COUNTER;
501
502                 if (connection->tether_state == FALSE &&
503                         connection->tether_iface.ifname != NULL &&
504                         app_value->classid == STC_TETHERING_APP_CLASSID) {
505                         counter.iftype = connection->tether_iface.type;
506                         g_strlcpy(counter.ifname, connection->tether_iface.ifname, MAX_IFACE_LENGTH);
507                 } else {
508                         counter.iftype = connection->type;
509                         g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
510                 }
511
512                 __del_iptables_in(&counter);
513                 __del_iptables_out(&counter);
514                 __del_ip6tables_in(&counter);
515                 __del_ip6tables_out(&counter);
516         }
517
518         return FALSE;
519 }
520
521 static void __print_rstn(stc_rstn_key_s *rstn_key, stc_rstn_value_s *rstn_value)
522 {
523         STC_LOGI("rstn info => rstn_id [%llu], "
524                  "app_id [%s], classid [%u], ifname [%s], "
525                  "iftype [%d], rstn_state [%d], rstn_type [%d], "
526                  "month_start_date [%d], limit [ (%lld) bytes], "
527                  "warn_limit [ (%lld) bytes], "
528                  "monthly_limit [ (%lld) bytes], "
529                  "weekly_limit [ (%lld) bytes], "
530                  "daily_limit [ (%lld) bytes], "
531                  "data_counter [ (%lld) bytes], "
532                  "warn_counter [ (%lld) bytes], "
533                  "monthly_counter [ (%lld) bytes], "
534                  "weekly_counter [ (%lld) bytes], "
535                  "daily_counter [ (%lld) bytes], "
536                  "roaming [%d], subscriber_id [%s]",
537                  rstn_value->restriction_id,
538                  rstn_key->app_id, rstn_value->classid , rstn_key->ifname,
539                  rstn_key->iftype, rstn_value->rstn_state, rstn_value->rstn_type,
540                  rstn_value->month_start_date,
541                  rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA],
542                  rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA_WARN],
543                  rstn_value->limit[STC_RSTN_LIMIT_TYPE_MONTHLY],
544                  rstn_value->limit[STC_RSTN_LIMIT_TYPE_WEEKLY],
545                  rstn_value->limit[STC_RSTN_LIMIT_TYPE_DAILY],
546                  rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA],
547                  rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN],
548                  rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY],
549                  rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY],
550                  rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY],
551                  rstn_key->roaming, rstn_key->subscriber_id);
552 }
553
554 static void __add_iptables_rule(int64_t classid, nfacct_rule_intend intend,
555                                 stc_iface_type_e iftype)
556 {
557         char *default_ifname = stc_default_connection_get_ifname();
558         default_connection_s *connection = stc_get_default_connection();
559         struct nfacct_rule counter;
560         stc_s *stc = stc_get_manager();
561         if (!stc) {
562                 g_free(default_ifname); //LCOV_EXCL_LINE
563                 return; //LCOV_EXCL_LINE
564         }
565
566         if (!stc->carg) {
567                 stc->carg = MALLOC0(counter_arg_s, 1); //LCOV_EXCL_LINE
568                 if (stc->carg == NULL) { //LCOV_EXCL_LINE
569                         g_free(default_ifname); //LCOV_EXCL_LINE
570                         return; //LCOV_EXCL_LINE
571                 }
572
573                 stc->carg->sock = stc_monitor_get_counter_socket(); //LCOV_EXCL_LINE
574         }
575
576         counter.carg = stc->carg;
577         counter.classid = classid;
578         counter.intend = intend;
579
580         if (connection && connection->tether_iface.ifname != NULL &&
581                 classid == STC_TETHERING_APP_CLASSID) {
582                 counter.iftype = connection->tether_iface.type;
583                 g_strlcpy(counter.ifname, connection->tether_iface.ifname, MAX_IFACE_LENGTH);
584         } else {
585                 counter.iftype = iftype;
586                 g_strlcpy(counter.ifname, default_ifname, MAX_IFACE_LENGTH);
587         }
588
589         g_free(default_ifname);
590
591         /* iptables rule */
592         __add_iptables_in(&counter);
593         __add_iptables_out(&counter);
594
595         /* ip6tables rule */
596         __add_ip6tables_in(&counter);
597         __add_ip6tables_out(&counter);
598 }
599
600 static void __del_iptables_rule(int64_t classid, nfacct_rule_intend intend,
601                                 stc_iface_type_e iftype)
602 {
603         char *default_ifname = stc_default_connection_get_ifname();
604         default_connection_s *connection = stc_get_default_connection();
605         struct nfacct_rule counter;
606         stc_s *stc = stc_get_manager();
607         if (!stc) {
608                 g_free(default_ifname); //LCOV_EXCL_LINE
609                 return; //LCOV_EXCL_LINE
610         }
611
612         if (!stc->carg) {
613                 stc->carg = MALLOC0(counter_arg_s, 1); //LCOV_EXCL_LINE
614                 if (stc->carg == NULL) { //LCOV_EXCL_LINE
615                         g_free(default_ifname); //LCOV_EXCL_LINE
616                         return; //LCOV_EXCL_LINE
617                 }
618
619                 stc->carg->sock = stc_monitor_get_counter_socket(); //LCOV_EXCL_LINE
620         }
621
622         counter.carg = stc->carg;
623         counter.classid = classid;
624         counter.intend = intend;
625
626         if (connection && connection->tether_iface.ifname != NULL &&
627                 classid == STC_TETHERING_APP_CLASSID) {
628                 counter.iftype = connection->tether_iface.type;
629                 g_strlcpy(counter.ifname, connection->tether_iface.ifname, MAX_IFACE_LENGTH);
630         } else {
631                 counter.iftype = iftype;
632                 g_strlcpy(counter.ifname, default_ifname, MAX_IFACE_LENGTH);
633         }
634
635         g_free(default_ifname);
636
637         /* iptables rule */
638         __del_iptables_in(&counter);
639         __del_iptables_out(&counter);
640
641         /* ip6tables rule */
642         __del_ip6tables_in(&counter);
643         __del_ip6tables_out(&counter);
644 }
645
646 static void __set_rstn_noti_state(int value)
647 {
648         int state = STC_RSTN_STATE_INIT;
649
650         if (__vconf_get_int(VCONFKEY_SETAPPL_DATA_RESTRICTION_INT, &state))
651                 return;
652
653         if (state == value) {
654                 STC_LOGI("No need to change a restriction status: %d", state);
655                 return;
656         }
657
658         vconf_set_int(VCONFKEY_SETAPPL_DATA_RESTRICTION_INT, value);
659         return;
660 }
661
662 typedef struct {
663         time_t month_start_ts;
664         time_t week_start_ts;
665         time_t day_start_ts;
666         int64_t monthly_stat;
667         int64_t weekly_stat;
668         int64_t daily_stat;
669 } cumulative_data_s;
670
671 static stc_cb_ret_e __statistics_info_cb(const table_statistics_info *info,
672                                         void *user_data)
673 {
674         cumulative_data_s *stat = (cumulative_data_s *)user_data;
675         int64_t counters = 0;
676
677         counters = info->cnt.in_bytes + info->cnt.out_bytes;
678
679         stat->monthly_stat += counters;
680         if (stat->week_start_ts <= info->interval->from)
681                 stat->weekly_stat += counters;
682         if (stat->day_start_ts <= info->interval->from)
683                 stat->daily_stat += counters;
684
685         return STC_CONTINUE;
686 }
687
688 static void __process_restriction(enum traffic_restriction_type rstn_type,
689                                   stc_rstn_key_s *rstn_key,
690                                   stc_rstn_value_s *rstn_value, void *data)
691 {
692         default_connection_s *old_connection = (default_connection_s *)data;
693         default_connection_s *connection = NULL;
694
695         if (old_connection != NULL)
696                 connection = old_connection;
697         else
698                 connection = stc_get_default_connection();
699
700         /* no default ifname */
701         if (connection->ifname == NULL)
702                 return;
703
704         /* rstn not applicable for this interface */
705         if (rstn_key->ifname != NULL && g_strcmp0("", rstn_key->ifname) != 0 &&
706             (g_strcmp0(connection->ifname, rstn_key->ifname) != 0) &&
707                 (g_strcmp0(connection->tether_iface.ifname, rstn_key->ifname) != 0))
708                 return;
709
710         /* classid is invalid */
711         if (rstn_value->classid <= STC_UNKNOWN_CLASSID)
712                 return;
713
714         switch (rstn_type) {
715         case RST_SET:
716         {
717                 int i;
718                 table_counters_info info;
719                 int64_t effective_limit[STC_RSTN_LIMIT_TYPE_MAX] = { 0, };
720
721                 memset(&info, 0, sizeof(table_counters_info));
722                 rstn_value->limit_exceeded = 0;
723
724                 if ((rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA] == 0 &&
725                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA] >= 0) ||
726                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN] == 0 &&
727                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA_WARN] >= 0) ||
728                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY] == 0 &&
729                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_MONTHLY] >= 0) ||
730                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY] == 0 &&
731                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_WEEKLY] >= 0) ||
732                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY] == 0 &&
733                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DAILY] >= 0)) {
734                         table_counters_get(rstn_value->restriction_id, &info);
735
736                         time_t current_time = 0;
737                         cumulative_data_s stat;
738                         table_statistics_select_rule rule;
739
740                         memset(&stat, 0, sizeof(cumulative_data_s));
741                         stat.month_start_ts = rstn_value->month_start_ts;
742                         stat.week_start_ts = g_system->last_week_ts;
743                         stat.day_start_ts = g_system->last_day_ts;
744
745                         memset(&rule, 0, sizeof(table_statistics_select_rule));
746                         rule.from = rstn_value->month_start_ts;
747                         time(&current_time);
748                         rule.to = current_time;
749                         rule.iftype = rstn_key->iftype;
750                         rule.granularity = GRANULARITY;
751
752                         table_statistics_per_app(rstn_key->app_id, &rule, __statistics_info_cb, &stat);
753
754                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA] = info.data_counter;
755                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN] = info.warn_counter;
756                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY] = info.monthly_counter + stat.monthly_stat;
757                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY] = info.weekly_counter + stat.weekly_stat;
758                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY] = info.daily_counter + stat.daily_stat;
759                 }
760
761                 for (i = 0; i < STC_RSTN_LIMIT_TYPE_MAX; i++) {
762                         if (rstn_value->limit[i] >= 0) {
763                                 effective_limit[i] = rstn_value->limit[i] - rstn_value->counter[i];
764
765                                 if (effective_limit[i] < 0)
766                                         rstn_value->limit_exceeded |= (1 << i);
767                         }
768                 }
769
770                 STC_LOGD("rstn_id [%llu], datausage [%llu] bytes",
771                         rstn_value->restriction_id, info.data_counter);
772
773                 if (rstn_value->limit_exceeded != 0 &&
774                         rstn_value->limit_exceeded != (1 << STC_RSTN_LIMIT_TYPE_DATA_WARN)) {
775                         __add_iptables_rule(rstn_value->classid, NFACCT_BLOCK, rstn_key->iftype);
776                 }
777
778                 rstn_value->rstn_state = STC_RSTN_STATE_ACTIVATED;
779         }
780         break;
781         case RST_EXCLUDE:
782                 __add_iptables_rule(rstn_value->classid, NFACCT_ALLOW,
783                                     rstn_key->iftype);
784
785                 rstn_value->rstn_state = STC_RSTN_STATE_ACTIVATED;
786                 rstn_value->limit_exceeded = 0;
787                 rstn_value->limit_notified = 0;
788                 break;
789         case RST_UNSET:
790         {
791                 int i;
792
793                 if (rstn_value->classid == STC_TETHERING_APP_CLASSID)
794                         __del_iptables_rule(rstn_value->classid, NFACCT_BLOCK,
795                                             rstn_key->iftype);
796                 else
797                         __del_iptables_rule(rstn_value->classid, rstn_value->rstn_type,
798                                             rstn_key->iftype);
799
800                 rstn_value->rstn_state = STC_RSTN_STATE_DEACTIVATED;
801                 rstn_value->limit_exceeded = 0;
802                 rstn_value->limit_notified = 0;
803
804                 for (i = 0; i < STC_RSTN_LIMIT_TYPE_MAX; i++)
805                         if (rstn_value->limit[i] >= 0)
806                                 rstn_value->counter[i] = 0;
807
808                 __set_rstn_noti_state(STC_RSTN_STATE_UNSET);
809         }
810         break;
811         default:
812                 ;//Do Nothing
813         }
814 }
815
816 //LCOV_EXCL_START
817 static gboolean __remove_rstns_foreach_application(gpointer key,
818                                                    gpointer value,
819                                                    gpointer data)
820 {
821         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
822         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
823         gchar *app_id = (gchar *)data;
824
825         /* rstn rule is not for applications */
826         if (rstn_key->app_id == NULL)
827                 goto out;
828
829         /* rstn rule is not for this application */
830         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
831                 goto out;
832
833         /* rstn rule is already removed */
834         if (rstn_value->rstn_state == STC_RSTN_STATE_DEACTIVATED)
835                 goto out;
836
837         /* remove restriction from system */
838         __process_restriction(RST_UNSET, rstn_key, rstn_value, NULL);
839
840         __print_rstn(rstn_key, rstn_value);
841 out:
842         return FALSE;
843 }
844 //LCOV_EXCL_STOP
845
846 static void __remove_rstns_for_application(gchar *app_id)
847 {
848         g_tree_foreach(g_system->rstns, __remove_rstns_foreach_application,
849                        app_id);
850 }
851
852 static stc_error_e __application_remove_if_empty(const stc_app_key_s *app_key)
853 {
854         stc_error_e ret = STC_ERROR_NONE;
855         guint pid_count = 0;
856         stc_app_value_s *lookup;
857
858         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
859
860         lookup = __application_lookup(g_system->apps, app_key);
861         if (!lookup) {
862                 STC_LOGE("app_key not found"); //LCOV_EXCL_LINE
863                 return STC_ERROR_NO_DATA; //LCOV_EXCL_LINE
864         }
865
866         g_tree_foreach(lookup->processes, __processes_tree_check_empty,
867                        &pid_count);
868
869         if (!pid_count) {
870                 /* remove nfacct rule for this classid */
871                 __remove_application_monitor((gpointer) app_key, lookup,
872                                              stc_get_default_connection());
873                 __remove_rstns_for_application(app_key->app_id);
874         }
875
876         if (!g_tree_remove(g_system->apps, app_key)) {
877                 ret = STC_ERROR_NO_DATA; //LCOV_EXCL_LINE
878                 STC_LOGE("key not found"); //LCOV_EXCL_LINE
879         }
880
881         return ret;
882 }
883
884 static stc_error_e __close_contr_sock(stc_system_s *system)
885 {
886         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
887
888         /* close netlink socket for updating kernel counters */
889         if (system->contr_sock != -1) {
890                 close(system->contr_sock);
891                 system->contr_sock = -1;
892         }
893
894         if (system->contr_gsource_id != 0) {
895                 g_source_remove(system->contr_gsource_id);
896                 system->contr_gsource_id = 0;
897         }
898
899         return STC_ERROR_NONE;
900 }
901
902 static gboolean __process_contr_reply(GIOChannel *source,
903                                       GIOCondition condition,
904                                       gpointer user_data);
905
906 //LCOV_EXCL_START
907 static stc_error_e __close_and_reopen_contr_sock(stc_system_s *system)
908 {
909         GIOChannel *gio = NULL;
910         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
911
912         /* close netlink socket for updating kernel counters */
913         if (system->contr_sock != -1) {
914                 close(system->contr_sock);
915                 system->contr_sock = -1;
916         }
917
918         if (system->contr_gsource_id != 0) {
919                 g_source_remove(system->contr_gsource_id);
920                 system->contr_gsource_id = 0;
921         }
922
923         /* create netlink socket for updating kernel counters */
924         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
925         if (system->contr_sock < 0) {
926                 STC_LOGE("failed to open socket");
927                 FREE(system);
928                 return STC_ERROR_FAIL;
929         }
930
931         gio = g_io_channel_unix_new(system->contr_sock);
932         system->contr_gsource_id =
933                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
934                                (GIOFunc) __process_contr_reply,
935                                NULL);
936         g_io_channel_unref(gio);
937
938         return STC_ERROR_NONE;
939 }
940
941 static void __action_when_rstn_limit_exceeded(stc_rstn_limit_type_e limit_type,
942                                                 stc_rstn_key_s *rstn_key,
943                                                 stc_rstn_value_s *rstn_value,
944                                                 classid_bytes_context_s *context)
945 {
946         gboolean rv;
947         char iftype[MAX_INT_LENGTH] = { 0, };
948         char byte[MAX_INT_LENGTH] = { 0, };
949         const char *signal_name = NULL;
950         const char *net_popup_content = NULL;
951         const char *net_popup_type = NULL;
952         stc_s *stc = (stc_s *)stc_get_manager();
953
954         if (stc == NULL) {
955                 STC_LOGE("Failed to get stc data");
956                 return;
957         }
958
959         switch (limit_type) {
960         case STC_RSTN_LIMIT_TYPE_DATA_WARN:
961         {
962                 signal_name = "WarnThresholdCrossed";
963                 net_popup_content = "warn threshold crossed";
964                 net_popup_type = "warning_noti";
965         }
966         break;
967         case STC_RSTN_LIMIT_TYPE_DATA:
968         case STC_RSTN_LIMIT_TYPE_MONTHLY:
969         case STC_RSTN_LIMIT_TYPE_WEEKLY:
970         case STC_RSTN_LIMIT_TYPE_DAILY:
971         {
972                 signal_name = "RestrictionThresholdCrossed";
973                 net_popup_content = "restriction threshold crossed";
974                 net_popup_type = "restriction_noti";
975
976                 /* block immediately */
977                 context->counter->intend = NFACCT_BLOCK;
978                 __del_iptables_in(context->counter);
979                 __del_iptables_out(context->counter);
980                 __add_iptables_in(context->counter);
981                 __add_iptables_out(context->counter);
982
983                 __del_ip6tables_in(context->counter);
984                 __del_ip6tables_out(context->counter);
985                 __add_ip6tables_in(context->counter);
986                 __add_ip6tables_out(context->counter);
987                 context->counter->intend = NFACCT_COUNTER;
988
989                 rstn_value->limit_exceeded |= (1 << limit_type);
990
991                 __set_rstn_noti_state(STC_RSTN_STATE_SET);
992         }
993         break;
994         default:
995                 break;
996         }
997
998         if (signal_name == NULL) {
999                 STC_LOGE("Invalid parameter: limit_type");
1000                 return;
1001         }
1002
1003         /* emit signal */
1004         rv = stc_manager_dbus_emit_signal(stc->connection,
1005                                                   STC_DBUS_SERVICE_RESTRICTION_PATH,
1006                                                   STC_DBUS_INTERFACE_RESTRICTION,
1007                                                   signal_name,
1008                                                   g_variant_new("(si)",
1009                                                   rstn_key->app_id,
1010                                                   rstn_key->iftype));
1011
1012         if (rv == TRUE)
1013                 rstn_value->limit_notified |= (1 << limit_type);
1014
1015         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
1016         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->limit[limit_type]);
1017         stc_plugin_appstatus_send_message(net_popup_content,
1018                         net_popup_type, rstn_key->app_id, iftype, byte);
1019 }
1020
1021 static gboolean __rstn_counter_update(stc_rstn_key_s *rstn_key,
1022                                       stc_rstn_value_s *rstn_value,
1023                                       classid_bytes_context_s *context)
1024 {
1025         int i;
1026         switch (context->counter->iotype) {
1027         case NFACCT_COUNTER_IN:
1028         case NFACCT_COUNTER_OUT:
1029                 if ((rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA] == 0 &&
1030                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA] >= 0) ||
1031                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN] == 0 &&
1032                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DATA_WARN] >= 0) ||
1033                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY] == 0 &&
1034                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_MONTHLY] >= 0) ||
1035                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY] == 0 &&
1036                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_WEEKLY] >= 0) ||
1037                         (rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY] == 0 &&
1038                         rstn_value->limit[STC_RSTN_LIMIT_TYPE_DAILY] >= 0)) {
1039                         table_counters_info info;
1040                         memset(&info, 0, sizeof(table_counters_info));
1041                         table_counters_get(rstn_value->restriction_id, &info);
1042
1043                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA] = info.data_counter;
1044                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN] = info.warn_counter;
1045                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY] = info.monthly_counter;
1046                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY] = info.weekly_counter;
1047                         rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY] = info.daily_counter;
1048                 }
1049
1050                 for (i = 0; i < STC_RSTN_LIMIT_TYPE_MAX; i++) {
1051                         if (rstn_value->limit[i] >= 0 &&
1052                                 !(rstn_value->limit_notified & (1 << i))) {
1053                                 rstn_value->counter[i] += context->bytes;
1054                                 if (rstn_value->limit[i] <= rstn_value->counter[i])
1055                                         __action_when_rstn_limit_exceeded(i,
1056                                                                                 rstn_key,
1057                                                                                 rstn_value,
1058                                                                                 context);
1059                         }
1060                 }
1061
1062                 g_system->rstns_tree_updated = TRUE;
1063                 __print_rstn(rstn_key, rstn_value);
1064                 break;
1065         default:
1066                 STC_LOGE("unknown iotype");
1067         }
1068
1069         return FALSE;
1070 }
1071
1072 static gboolean __interface_rstn_counter_update(stc_rstn_key_s *rstn_key,
1073                                                 stc_rstn_value_s *rstn_value,
1074                                                 classid_bytes_context_s *context)
1075 {
1076         if ((rstn_value->classid == STC_TOTAL_DATACALL_CLASSID &&
1077                 context->counter->iftype == STC_IFACE_DATACALL) ||
1078                 (rstn_value->classid == STC_TOTAL_WIFI_CLASSID &&
1079                 context->counter->iftype == STC_IFACE_WIFI) ||
1080                 (rstn_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
1081                 context->counter->iftype == STC_IFACE_BLUETOOTH) ||
1082                 (rstn_value->classid == STC_TETHERING_APP_CLASSID &&
1083                  context->counter->iftype == STC_IFACE_WIFI) ||
1084                 (rstn_value->classid == STC_TETHERING_APP_CLASSID &&
1085                  context->counter->iftype == STC_IFACE_BLUETOOTH) ||
1086                 (rstn_value->classid == STC_TETHERING_APP_CLASSID &&
1087                  context->counter->iftype == STC_IFACE_USB) ||
1088                 (rstn_value->classid == STC_TETHERING_APP_CLASSID &&
1089                  context->counter->iftype == STC_IFACE_P2P)) {
1090                 context->counter->classid = rstn_value->classid;
1091                 return __rstn_counter_update(rstn_key, rstn_value, context);
1092         }
1093
1094         return FALSE;
1095 }
1096
1097 static gboolean __rstn_counter_update_foreach_classid(gpointer key,
1098                                                       gpointer value,
1099                                                       gpointer data)
1100 {
1101         gboolean rv = FALSE;
1102         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1103         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1104         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
1105         uint32_t classid;
1106
1107         if (context->counter->intend != NFACCT_COUNTER)
1108                 goto try_next_callback;
1109
1110         if (rstn_value->limit_exceeded == TRUE) {
1111                 context->data_limit_exceeded = TRUE; //LCOV_EXCL_LINE
1112                 goto try_next_callback; //LCOV_EXCL_LINE
1113         }
1114
1115         classid = context->counter->classid;
1116         rv = __interface_rstn_counter_update(rstn_key, rstn_value, context);
1117
1118         context->counter->classid = classid;
1119         if (rstn_value->classid != context->counter->classid)
1120                 goto try_next_callback;
1121
1122         rv = __rstn_counter_update(rstn_key, rstn_value, context);
1123
1124 try_next_callback:
1125         return rv;
1126 }
1127 //LCOV_EXCL_STOP
1128
1129 static gboolean __update_app_statistics(gpointer key, gpointer value,
1130                                         gpointer data)
1131 {
1132         stc_app_key_s *app_key = (stc_app_key_s *)key;
1133         stc_app_value_s *app_value = (stc_app_value_s *)value;
1134         time_t *touch_time = (time_t *)data;
1135         stc_db_classid_iftype_key stat_key;
1136         stc_db_app_stats stat;
1137         default_connection_s *default_connection = stc_get_default_connection();
1138
1139         memset(&stat_key, 0, sizeof(stc_db_classid_iftype_key));
1140         memset(&stat, 0 , sizeof(stc_db_app_stats));
1141
1142         /* Do not update statistics for Tethering
1143          * if tethering is in-active found */
1144         if (default_connection &&
1145                 default_connection->tether_state == FALSE &&
1146                 !strcmp(app_key->app_id, STC_TOTAL_TETHERING))
1147                 return FALSE;
1148
1149         /* Do not update statistics for Wi-Fi
1150          * if tethering is active on wlan0 iface */
1151         if (default_connection && default_connection->tether_state &&
1152                 default_connection->tether_iface.type == STC_IFACE_WIFI &&
1153                 !strcmp(app_key->app_id, STC_TOTAL_WIFI))
1154                 return FALSE;
1155
1156         stat_key.classid = app_value->classid;
1157
1158         if (app_value->classid == STC_TETHERING_APP_CLASSID &&
1159                 default_connection->tether_state == TRUE)
1160                 stat_key.iftype = default_connection->tether_iface.type;
1161         else
1162                 stat_key.iftype = default_connection->type;
1163
1164         if (STC_IFACE_DATACALL == stat_key.iftype)
1165                 stat_key.subscriber_id = g_strdup(default_connection->subscriber_id);
1166         else
1167                 stat_key.subscriber_id = g_strdup("none_subid"); //LCOV_EXCL_LINE
1168
1169         if (app_value->classid == STC_TETHERING_APP_CLASSID &&
1170                 default_connection->tether_state == TRUE)
1171                 g_strlcpy(stat_key.ifname, default_connection->tether_iface.ifname,
1172                           MAX_IFACE_LENGTH);
1173         else
1174                 g_strlcpy(stat_key.ifname, default_connection->ifname,
1175                           MAX_IFACE_LENGTH);
1176
1177         stat.app_id = g_strdup(app_key->app_id);
1178         stat.snd_count = app_value->counter.out_bytes;
1179         stat.rcv_count = app_value->counter.in_bytes;
1180         stat.is_roaming = default_connection->roaming;
1181
1182         if (strstr(stat.app_id, "_BACKGROUND")) {
1183                 stat.ground = STC_APP_STATE_BACKGROUND;
1184         } else {
1185                 if (strstr(stat.app_id, "TOTAL_"))
1186                         stat.ground = STC_APP_STATE_UNKNOWN;
1187                 else
1188                         stat.ground = STC_APP_STATE_FOREGROUND;
1189         }
1190
1191         table_statistics_insert(&stat_key, &stat, *touch_time);
1192
1193         app_value->counter.out_bytes = 0;
1194         app_value->counter.in_bytes = 0;
1195
1196         FREE(stat.app_id);
1197         FREE(stat_key.subscriber_id);
1198
1199         return FALSE;
1200 }
1201
1202 static gboolean __flush_apps_stats_to_database(gpointer user_data)
1203 {
1204         time_t current_time = 0;
1205         stc_s *stc = stc_get_manager();
1206
1207         if (stc && stc->carg)
1208                 current_time = stc->carg->last_run_time;
1209
1210         if (g_system->apps_tree_updated == FALSE)
1211                 return G_SOURCE_REMOVE;
1212
1213         g_system->apps_tree_updated = FALSE;
1214
1215         if (g_system->apps)
1216                 g_tree_foreach(g_system->apps,
1217                                __update_app_statistics,
1218                                &current_time);
1219
1220         STC_LOGI("Flushed app stats to database");
1221         return G_SOURCE_REMOVE;
1222 }
1223
1224 //LCOV_EXCL_START
1225 static gboolean __update_counter_statistics(gpointer key, gpointer value,
1226                                             gpointer data)
1227 {
1228         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1229         table_counters_info info = {
1230                 .restriction_id = rstn_value->restriction_id,
1231                 .data_counter = rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA],
1232                 .warn_counter = rstn_value->counter[STC_RSTN_LIMIT_TYPE_DATA_WARN],
1233                 .monthly_counter = rstn_value->counter[STC_RSTN_LIMIT_TYPE_MONTHLY],
1234                 .weekly_counter = rstn_value->counter[STC_RSTN_LIMIT_TYPE_WEEKLY],
1235                 .daily_counter = rstn_value->counter[STC_RSTN_LIMIT_TYPE_DAILY]
1236         };
1237
1238         table_counters_update_counters(&info);
1239
1240         return FALSE;
1241 }
1242
1243 static gboolean __flush_rstns_counter_to_database(gpointer user_data)
1244 {
1245         time_t current_time = 0;
1246         stc_s *stc = stc_get_manager();
1247
1248         if (stc && stc->carg)
1249                 current_time = stc->carg->last_run_time;
1250
1251         if (g_system->rstns_tree_updated == FALSE)
1252                 return G_SOURCE_REMOVE;
1253
1254         g_system->rstns_tree_updated = FALSE;
1255
1256         if (g_system->rstns)
1257                 g_tree_foreach(g_system->rstns,
1258                                __update_counter_statistics,
1259                                &current_time);
1260
1261         STC_LOGI("Flushed rstns counters to database");
1262         return G_SOURCE_REMOVE;
1263 }
1264 //LCOV_EXCL_STOP
1265
1266 static void __app_counter_update(stc_app_key_s *app_key,
1267                                  stc_app_value_s *app_value,
1268                                  classid_bytes_context_s *context)
1269 {
1270         switch (context->counter->iotype) {
1271         case NFACCT_COUNTER_IN:
1272                 app_value->data_usage.in_bytes += context->bytes;
1273                 app_value->counter.in_bytes = context->bytes;
1274                 g_system->apps_tree_updated = TRUE;
1275
1276                 /*
1277                 __apps_tree_foreach_print(app_key, app_value, NULL); //LCOV_EXCL_LINE
1278                 */
1279                 break;
1280         case NFACCT_COUNTER_OUT:
1281                 app_value->data_usage.out_bytes += context->bytes;
1282                 app_value->counter.out_bytes = context->bytes;
1283                 g_system->apps_tree_updated = TRUE;
1284
1285                 /*
1286                 __apps_tree_foreach_print(app_key, app_value, NULL); //LCOV_EXCL_LINE
1287                 */
1288                 break;
1289         default:
1290                 STC_LOGE("unknown iotype"); //LCOV_EXCL_LINE
1291         }
1292 }
1293
1294 static void __interface_counter_update(stc_app_key_s *app_key,
1295                                        stc_app_value_s *app_value,
1296                                        classid_bytes_context_s *context)
1297 {
1298         if ((app_value->classid == STC_TOTAL_DATACALL_CLASSID &&
1299              context->counter->iftype == STC_IFACE_DATACALL) ||
1300             (app_value->classid == STC_TOTAL_WIFI_CLASSID &&
1301              context->counter->iftype == STC_IFACE_WIFI) ||
1302             (app_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
1303              context->counter->iftype == STC_IFACE_BLUETOOTH) ||
1304                 (app_value->classid == STC_TETHERING_APP_CLASSID &&
1305                  context->counter->iftype == STC_IFACE_WIFI) ||
1306                 (app_value->classid == STC_TETHERING_APP_CLASSID &&
1307                  context->counter->iftype == STC_IFACE_BLUETOOTH) ||
1308                 (app_value->classid == STC_TETHERING_APP_CLASSID &&
1309                  context->counter->iftype == STC_IFACE_USB) ||
1310                 (app_value->classid == STC_TETHERING_APP_CLASSID &&
1311                  context->counter->iftype == STC_IFACE_P2P))
1312                  __app_counter_update(app_key, app_value, context);
1313 }
1314
1315
1316 static gboolean __apps_counter_update_foreach_classid(gpointer key,
1317                                                       gpointer value,
1318                                                       gpointer data)
1319 {
1320         stc_app_key_s *app_key = (stc_app_key_s *)key;
1321         stc_app_value_s *app_value = (stc_app_value_s *)value;
1322         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
1323
1324         if (context->counter->intend != NFACCT_COUNTER)
1325                 goto try_next_callback;
1326
1327         __interface_counter_update(app_key, app_value, context);
1328
1329         if (app_value->classid != context->counter->classid)
1330                 goto try_next_callback;
1331
1332         __app_counter_update(app_key, app_value, context);
1333
1334 try_next_callback:
1335         return FALSE;
1336 }
1337
1338 static gboolean __reset_time_counter_foreach_rstn(gpointer key,
1339                                                   gpointer value,
1340                                                   gpointer data)
1341 {
1342         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1343         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1344         reset_time_limits_context_s *context = (reset_time_limits_context_s *)data;
1345         int i;
1346         time_t now_month_start_ts;
1347
1348         if (rstn_value->month_start_date == 0) {
1349                 table_counters_info info;
1350                 memset(&info, 0, sizeof(table_counters_info));
1351                 table_counters_get_timestamps(rstn_value->restriction_id, &info);
1352
1353                 if (info.month_start_date == 0)
1354                         rstn_value->month_start_date = 1;
1355                 else
1356                         rstn_value->month_start_date = info.month_start_date;
1357                 rstn_value->month_start_ts = info.month_start_ts;
1358         }
1359
1360         now_month_start_ts =
1361                 stc_time_get_month_start(context->now,
1362                                          rstn_value->month_start_date);
1363
1364         if (rstn_value->month_start_ts != now_month_start_ts) {
1365                 rstn_value->month_start_ts = now_month_start_ts;
1366                 context->month_start_ts = now_month_start_ts;
1367                 context->is_updated |= (1 << STC_RSTN_LIMIT_TYPE_MONTHLY);
1368         }
1369
1370         if (context->is_updated) {
1371                 table_counters_info info;
1372                 memset(&info, 0, sizeof(table_counters_info));
1373
1374                 info.restriction_id = rstn_value->restriction_id;
1375                 info.month_start_date = rstn_value->month_start_date;
1376                 info.month_start_ts = rstn_value->month_start_ts;
1377                 info.week_start_ts = context->week_start_ts;
1378                 info.day_start_ts = context->day_start_ts;
1379
1380                 table_counters_update_timestamps(&info);
1381         }
1382
1383         for (i = STC_RSTN_LIMIT_TYPE_MONTHLY; i < STC_RSTN_LIMIT_TYPE_MAX; i++) {
1384
1385                 if ((context->is_updated) & (1 << i)) {
1386                         /* reset limit */
1387                         rstn_value->counter[i] = 0;
1388
1389                         if (rstn_value->limit_exceeded & (1 << i)) {
1390                                 /* remove iptables rule */
1391                                 char *default_ifname = stc_default_connection_get_ifname();
1392                                 struct nfacct_rule counter;
1393                                 stc_s *stc = stc_get_manager();
1394                                 if (stc == NULL) {
1395                                         STC_LOGE("Can't get stc data");
1396                                         g_free(default_ifname);
1397                                         goto try_next_callback;
1398                                 }
1399
1400                                 if (!stc->carg) {
1401                                         stc->carg = MALLOC0(counter_arg_s, 1);
1402                                         if (stc->carg == NULL) {
1403                                                 g_free(default_ifname);
1404                                                 goto try_next_callback;
1405                                         }
1406
1407                                         stc->carg->sock =
1408                                                 stc_monitor_get_counter_socket();
1409                                 }
1410
1411                                 counter.carg = stc->carg;
1412                                 counter.classid = rstn_value->classid;
1413                                 counter.intend = NFACCT_BLOCK;
1414                                 counter.iftype = rstn_key->iftype;
1415                                 g_strlcpy(counter.ifname, default_ifname,
1416                                           MAX_IFACE_LENGTH);
1417
1418                                 g_free(default_ifname);
1419
1420                                 /* iptables rule */
1421                                 __del_iptables_in(&counter);
1422                                 __del_iptables_out(&counter);
1423
1424                                 /* ip6tables rule */
1425                                 __del_ip6tables_in(&counter);
1426                                 __del_ip6tables_out(&counter);
1427
1428                                 rstn_value->rstn_state = STC_RSTN_STATE_DEACTIVATED;
1429                                 rstn_value->limit_exceeded &= ~(1 << i);
1430                                 rstn_value->limit_notified &= ~(1 << i);
1431                         }
1432                 }
1433         }
1434
1435 try_next_callback:
1436         return FALSE;
1437 }
1438
1439 static void __reset_time_counters_if_required(void)
1440 {
1441         reset_time_limits_context_s context;
1442
1443         if (g_system == NULL) {
1444                 STC_LOGE("stc monitor not initialized!");
1445                 return;
1446         }
1447
1448         context.now = time(NULL);
1449         context.week_start_ts = stc_time_get_week_start(context.now);
1450         context.day_start_ts = stc_time_get_day_start(context.now);
1451         context.is_updated = 0;
1452
1453         if (g_system->last_week_ts != context.week_start_ts) {
1454                 g_system->last_week_ts = context.week_start_ts;
1455                 context.is_updated |= (1 << STC_RSTN_LIMIT_TYPE_WEEKLY);
1456         }
1457
1458         if (g_system->last_day_ts != context.day_start_ts) {
1459                 g_system->last_day_ts = context.day_start_ts;
1460                 context.is_updated |= (1 << STC_RSTN_LIMIT_TYPE_DAILY);
1461         }
1462
1463         if (g_system->rstns) {
1464                 g_tree_foreach(g_system->rstns,
1465                                __reset_time_counter_foreach_rstn,
1466                                &context);
1467                 if (context.is_updated)
1468                         STC_LOGD("Counter reset completed month_start [%ld], week_start [%ld], day_start [%ld]",
1469                                  context.month_start_ts, g_system->last_week_ts, g_system->last_day_ts);
1470         }
1471 }
1472
1473 static void __fill_nfacct_result(char *cnt_name, int64_t bytes,
1474                                  struct counter_arg *carg)
1475 {
1476         __reset_time_counters_if_required();
1477
1478         struct nfacct_rule counter = {
1479                 .carg = carg,
1480                 .name = {0},
1481                 .ifname = {0},
1482                 0
1483         };
1484
1485         classid_bytes_context_s context = {
1486                 .counter = &counter,
1487                 .bytes = bytes,
1488                 .data_limit_exceeded = FALSE,
1489         };
1490
1491         if (!recreate_counter_by_name(cnt_name, &counter)) {
1492                 STC_LOGE("Can't parse counter name %s", cnt_name); //LCOV_EXCL_LINE
1493                 return; //LCOV_EXCL_LINE
1494         }
1495
1496         if (STC_DEBUG_LOG)
1497                 STC_LOGI("classid %u, iftype %u, iotype %d, intend %d, ifname %s, bytes %lld",
1498                         context.counter->classid, context.counter->iftype,
1499                         context.counter->iotype, context.counter->intend,
1500                         context.counter->ifname, context.bytes);
1501
1502         if (g_system->rstns)
1503                 g_tree_foreach(g_system->rstns,
1504                                __rstn_counter_update_foreach_classid,
1505                                &context);
1506
1507         if (g_system->apps)
1508                 g_tree_foreach(g_system->apps,
1509                                __apps_counter_update_foreach_classid,
1510                                &context);
1511 }
1512
1513 static int __fill_counters(struct rtattr *attr_list[__NFACCT_MAX],
1514                            void *user_data)
1515 {
1516         struct counter_arg *carg = user_data;
1517         char *cnt_name = (char *)RTA_DATA(attr_list[NFACCT_NAME]);
1518         if (carg->initiate) {
1519                 /**
1520                  * TODO: this will be used when daemon starts to update existing
1521                  * counter data if present.
1522                  *
1523                  populate_counters(cnt_name, carg);
1524                  */
1525         } else {
1526                 int64_t *bytes_p =
1527                         (int64_t *)RTA_DATA(attr_list[NFACCT_BYTES]);
1528                 int bytes = be64toh(*bytes_p);
1529                 if (bytes) {
1530                         ++carg->serialized_counters;
1531                         __fill_nfacct_result(cnt_name, bytes, carg);
1532                 }
1533         }
1534
1535         return 0;
1536 }
1537
1538 static int __post_fill_counters(void *user_data)
1539 {
1540         struct counter_arg *carg = user_data;
1541
1542         if (carg->initiate)
1543                 carg->initiate = 0;
1544
1545         return 0;
1546 }
1547
1548 static void __process_network_counter(struct genl *ans,
1549                                       struct counter_arg *carg)
1550 {
1551         struct netlink_serialization_params ser_params = {
1552                 .carg = carg,
1553                 .ans = ans,
1554                 .eval_attr = __fill_counters,
1555                 .post_eval_attr = __post_fill_counters,
1556         };
1557
1558         netlink_serialization_command *netlink =
1559                 netlink_create_command(&ser_params);
1560         if (!netlink) {
1561                 STC_LOGE("Can not create command"); //LCOV_EXCL_LINE
1562                 return; //LCOV_EXCL_LINE
1563         }
1564
1565         netlink->deserialize_answer(&(netlink->params));
1566 }
1567
1568 static gboolean __process_contr_reply(GIOChannel *source,
1569                                       GIOCondition condition,
1570                                       gpointer user_data)
1571 {
1572         int sock = g_io_channel_unix_get_fd(source);
1573         struct genl *ans;
1574         int ret;
1575         stc_s *stc = stc_get_manager();
1576
1577 #ifdef TIZEN_GTESTS
1578         void __gcov_flush(void);
1579         __gcov_flush();
1580 #endif
1581
1582         if ((condition & G_IO_ERR) || (condition & G_IO_HUP) ||
1583             (condition & G_IO_NVAL)) {
1584                 /* G_IO_ERR/G_IO_HUP/G_IO_NVAL received */
1585
1586                 STC_LOGE("Counter socket received G_IO event, closing socket." //LCOV_EXCL_LINE
1587                          "G_IO_ERR [%u], G_IO_HUP [%u], G_IO_NVAL [%u]",
1588                          (condition & G_IO_ERR), (condition & G_IO_HUP),
1589                          (condition & G_IO_NVAL));
1590                 __close_and_reopen_contr_sock(g_system); //LCOV_EXCL_LINE
1591                 return FALSE; //LCOV_EXCL_LINE
1592         }
1593
1594         ans = MALLOC0(struct genl, 1);
1595         if (ans == NULL) {
1596                 STC_LOGE("Failed allocate memory to genl reply message"); //LCOV_EXCL_LINE
1597                 return TRUE; //LCOV_EXCL_LINE
1598         }
1599
1600         if (stc == NULL) {
1601                 STC_LOGE("Can't get stc data"); //LCOV_EXCL_LINE
1602                 goto out; //LCOV_EXCL_LINE
1603         }
1604
1605         ret = read_netlink(sock, ans, sizeof(struct genl));
1606         /* STC_LOGD("Counter data received ret [%d]", ret); */
1607         if (ret == 0)
1608                 goto out;
1609
1610         stc->carg->ans_len = ret;
1611         stc->carg->last_run_time = time(NULL);
1612
1613         __process_network_counter(ans, stc->carg);
1614
1615         g_idle_add(__flush_apps_stats_to_database, NULL);
1616         g_idle_add(__flush_rstns_counter_to_database, NULL);
1617 out:
1618
1619         FREE(ans);
1620         return TRUE;
1621 }
1622
1623 static gboolean __update_contr_cb(void *user_data)
1624 {
1625         /* Here we just sent command, answer we receive in another callback */
1626         stc_s *stc = stc_get_manager();
1627         ret_value_msg_if(stc == NULL, STC_ERROR_FAIL, "Can't get stc data");
1628         if (!stc->carg) {
1629                 stc->carg = MALLOC0(counter_arg_s, 1);
1630                 if (stc->carg == NULL)
1631                         return TRUE;  /* we need to continue the timer */
1632
1633                 stc->carg->sock = stc_monitor_get_counter_socket();
1634         }
1635
1636 #ifdef TIZEN_GTESTS
1637         void __gcov_flush(void);
1638         __gcov_flush();
1639 #endif
1640
1641         /* STC_LOGD("Get all counters"); */
1642         nfacct_send_get_all(stc->carg);
1643
1644         /* we need to continue the timer */
1645         return TRUE;
1646 }
1647
1648 /*
1649 //LCOV_EXCL_START
1650 static gboolean __rstn_tree_foreach_print(gpointer key, gpointer value,
1651                                           gpointer data)
1652 {
1653         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1654         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1655
1656         __print_rstn(rstn_key, rstn_value);
1657         return FALSE;
1658 }
1659
1660 static void __rstn_tree_printall(void)
1661 {
1662         g_tree_foreach(g_system->rstns, __rstn_tree_foreach_print, NULL);
1663 }
1664 //LCOV_EXCL_STOP
1665 */
1666
1667 static stc_rstn_value_s * __rstn_lookup(GTree *rstns_tree,
1668                                         const stc_rstn_key_s *key)
1669 {
1670         stc_rstn_value_s *lookup;
1671
1672         ret_value_msg_if(rstns_tree == NULL, NULL, "rstns_tree is null!");
1673
1674         lookup = g_tree_lookup(rstns_tree, key);
1675
1676         return lookup;
1677 }
1678
1679 static gboolean __remove_restriction(gpointer key, gpointer value,
1680                                      gpointer data)
1681 {
1682         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1683         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1684
1685         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
1686         __print_rstn(rstn_key, rstn_value);
1687         return FALSE;
1688 }
1689
1690 static gboolean __add_restriction_debug(gpointer key, gpointer value,
1691                                         gpointer data)
1692 {
1693         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1694         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1695
1696         /* rstn rule is activated */
1697         if (rstn_value->rstn_state == STC_RSTN_STATE_ACTIVATED)
1698                 return FALSE;
1699
1700         if (rstn_value->rstn_type == STC_RSTN_TYPE_ACCEPT)
1701                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1702         else
1703                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1704
1705         __print_rstn(rstn_key, rstn_value);
1706
1707         return FALSE;
1708 }
1709
1710 //LCOV_EXCL_START
1711 static gboolean __add_restriction(gpointer key, gpointer value, gpointer data)
1712 {
1713         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1714         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1715
1716         /* rstn rule is activated */
1717         if (rstn_value->rstn_state == STC_RSTN_STATE_ACTIVATED)
1718                 return FALSE;
1719
1720         if (rstn_value->rstn_type == STC_RSTN_TYPE_ACCEPT)
1721                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1722         else
1723                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1724
1725         return FALSE;
1726 }
1727 //LCOV_EXCL_STOP
1728
1729 static stc_error_e __rstn_tree_remove(stc_rstn_key_s *key)
1730 {
1731         stc_rstn_value_s *lookup_value;
1732
1733         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1734
1735         lookup_value = __rstn_lookup(g_system->rstns, key);
1736         if (!lookup_value) {
1737                 STC_LOGE("key not found"); //LCOV_EXCL_LINE
1738                 return STC_ERROR_NO_DATA; //LCOV_EXCL_LINE
1739         }
1740
1741         /* remove counter also */
1742         table_counters_delete(lookup_value->restriction_id);
1743         __remove_restriction(key, lookup_value, NULL);
1744
1745         if (!g_tree_remove(g_system->rstns, key)) {
1746                 STC_LOGD("key not found"); //LCOV_EXCL_LINE
1747                 return STC_ERROR_NO_DATA; //LCOV_EXCL_LINE
1748         }
1749
1750         return STC_ERROR_NONE;
1751 }
1752
1753 static stc_error_e __rstn_tree_add(stc_rstn_key_s *key,
1754                                    stc_rstn_value_s *value, gboolean debug)
1755 {
1756         stc_rstn_key_s *rstn_key;
1757         stc_rstn_value_s *rstn_value;
1758
1759         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1760
1761         rstn_value = __rstn_lookup(g_system->rstns, key);
1762         if (rstn_value)
1763                 __rstn_tree_remove(key);
1764
1765         rstn_key = MALLOC0(stc_rstn_key_s, 1);
1766         if (!rstn_key) {
1767                 STC_LOGE("rstn_key allocation failed"); //LCOV_EXCL_LINE
1768                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
1769         }
1770
1771         rstn_value = MALLOC0(stc_rstn_value_s, 1);
1772         if (!rstn_value) {
1773                 STC_LOGE("rstn_value allocation failed"); //LCOV_EXCL_LINE
1774                 FREE(rstn_key); //LCOV_EXCL_LINE
1775                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
1776         }
1777
1778         rstn_key->app_id = g_strdup(key->app_id);
1779         rstn_key->ifname = g_strdup(key->ifname);
1780         rstn_key->subscriber_id = g_strdup(key->subscriber_id);
1781         rstn_key->iftype = key->iftype;
1782         rstn_key->roaming = key->roaming;
1783
1784         g_tree_insert(g_system->rstns, rstn_key, rstn_value);
1785
1786         rstn_value->restriction_id = value->restriction_id;
1787         rstn_value->rstn_state = value->rstn_state;
1788         rstn_value->rstn_type = value->rstn_type;
1789         rstn_value->classid = value->classid;
1790
1791         int i;
1792         for (i = 0; i < STC_RSTN_LIMIT_TYPE_MAX; i++) {
1793                 rstn_value->limit[i] = value->limit[i];
1794                 rstn_value->counter[i] = 0;
1795         }
1796
1797         rstn_value->limit_exceeded = 0;
1798         rstn_value->limit_notified = 0;
1799         rstn_value->month_start_date = value->month_start_date;
1800         rstn_value->month_start_ts = value->month_start_ts;
1801
1802         if (debug == TRUE)
1803                 __add_restriction_debug(key, rstn_value, NULL);
1804         else
1805                 __add_restriction(key, rstn_value, NULL);
1806
1807         return STC_ERROR_NONE;
1808 }
1809
1810 //LCOV_EXCL_START
1811 static stc_cb_ret_e __insert_restriction_cb(const table_restrictions_info *info,
1812                                             void *user_data)
1813 {
1814         stc_cb_ret_e ret = STC_CONTINUE;
1815
1816         stc_rstn_key_s key;
1817         stc_rstn_value_s value;
1818
1819         memset(&key, 0, sizeof(stc_rstn_key_s));
1820         memset(&value, 0, sizeof(stc_rstn_value_s));
1821
1822         key.app_id = g_strdup(info->app_id);
1823         key.ifname = g_strdup(info->ifname);
1824         key.subscriber_id = g_strdup(info->subscriber_id);
1825         key.iftype = info->iftype;
1826         key.roaming = info->roaming;
1827
1828         value.rstn_type = info->rstn_type;
1829         value.rstn_state = STC_RSTN_STATE_UNKNOWN;
1830         value.restriction_id = info->restriction_id;
1831
1832         if (info->app_id)
1833                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1834         else
1835                 value.classid = STC_UNKNOWN_CLASSID;
1836
1837         value.limit[STC_RSTN_LIMIT_TYPE_DATA] = info->data_limit;
1838         value.limit[STC_RSTN_LIMIT_TYPE_DATA_WARN] = info->data_warn_limit;
1839         value.limit[STC_RSTN_LIMIT_TYPE_MONTHLY] = info->monthly_limit;
1840         value.limit[STC_RSTN_LIMIT_TYPE_WEEKLY] = info->weekly_limit;
1841         value.limit[STC_RSTN_LIMIT_TYPE_DAILY] = info->daily_limit;
1842
1843         if (__rstn_tree_add(&key, &value, FALSE) != STC_ERROR_NONE)
1844                 ret = STC_CANCEL;
1845
1846         FREE(key.app_id);
1847         FREE(key.ifname);
1848         FREE(key.subscriber_id);
1849         return ret;
1850 }
1851
1852 static void __fill_restritions_list(void)
1853 {
1854         table_restrictions_foreach(__insert_restriction_cb, NULL);
1855
1856         /* __rstn_tree_printall(); */
1857 }
1858
1859 static gboolean __add_rstn_foreach_application(gpointer key,
1860                                                gpointer value,
1861                                                gpointer data)
1862 {
1863         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1864         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1865         gchar *app_id = (gchar *)data;
1866
1867         /* rstn rule is not for applications */
1868         if (rstn_key->app_id == NULL)
1869                 goto out;
1870
1871         /* rstn rule is not for this application */
1872         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
1873                 goto out;
1874
1875         /* rstn rule is already applied */
1876         if (rstn_value->rstn_state == STC_RSTN_STATE_ACTIVATED)
1877                 goto out;
1878
1879         /* add restriction to system */
1880         if (rstn_value->rstn_type == STC_RSTN_TYPE_ACCEPT)
1881                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, NULL);
1882         else
1883                 __process_restriction(RST_SET, rstn_key, rstn_value, NULL);
1884
1885         __print_rstn(rstn_key, rstn_value);
1886 out:
1887         return FALSE;
1888 }
1889 //LCOV_EXCL_STOP
1890
1891 static void __add_rstns_for_application(gchar *app_id)
1892 {
1893         g_tree_foreach(g_system->rstns, __add_rstn_foreach_application,
1894                        app_id);
1895 }
1896
1897 static void __add_application_by_interface(const char *app_id)
1898 {
1899         stc_app_key_s app_key;
1900         stc_app_value_s app_value;
1901
1902         if (app_id == NULL)
1903                 return; //LCOV_EXCL_LINE
1904
1905         memset(&app_key, 0, sizeof(stc_app_key_s));
1906         memset(&app_value, 0, sizeof(stc_app_value_s));
1907
1908         app_key.pkg_id = g_strdup(app_id);
1909         app_key.app_id = g_strdup(app_id);
1910
1911         app_value.type = STC_APP_TYPE_NONE;
1912         app_value.processes = NULL;
1913         app_value.counter.in_bytes = 0;
1914         app_value.counter.out_bytes = 0;
1915
1916         stc_monitor_application_add(app_key, app_value);
1917
1918         FREE(app_key.pkg_id);
1919         FREE(app_key.app_id);
1920 }
1921
1922 static guint __get_background_state(void)
1923 {
1924         return g_system->background_state;;
1925 }
1926
1927 static void __set_background_state(guint state)
1928 {
1929         g_system->background_state = state;
1930 }
1931
1932 static gboolean __processes_tree_foreach_background(gpointer key,
1933                                                     gpointer value,
1934                                                     gpointer data)
1935 {
1936         stc_process_key_s *proc_key = (stc_process_key_s *)key;
1937         stc_app_key_s *app_key = (stc_app_key_s *)data;
1938
1939         if (g_system->background_state)
1940                 place_pids_to_net_cgroup(proc_key->pid, STC_BACKGROUND_APP_ID);
1941         else
1942                 place_pids_to_net_cgroup(proc_key->pid, app_key->app_id);
1943
1944         return FALSE;
1945 }
1946
1947 static gboolean __apps_tree_foreach_background(gpointer key, gpointer value,
1948                                         gpointer data)
1949 {
1950         stc_app_key_s *app_key = (stc_app_key_s *)key;
1951         stc_app_value_s *app_value = (stc_app_value_s *)value;
1952
1953         if (strstr(app_key->app_id, STC_BACKGROUND_APP_SUFFIX))
1954                 g_tree_foreach(app_value->processes,
1955                                __processes_tree_foreach_background, app_key);
1956
1957         return FALSE;
1958 }
1959
1960 static stc_error_e __process_update_background(void)
1961 {
1962         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1963
1964         g_tree_foreach(g_system->apps, __apps_tree_foreach_background, NULL);
1965
1966         return STC_ERROR_NONE;
1967 }
1968 //LCOV_EXCL_STOP
1969
1970 static void __fill_exceptions_list(void)
1971 {
1972         stc_plugin_fill_exception_list();
1973 }
1974
1975 stc_error_e stc_monitor_init(void)
1976 {
1977         stc_system_s *system = MALLOC0(stc_system_s, 1);
1978         GIOChannel *gio = NULL;
1979
1980         ret_value_msg_if(system == NULL, STC_ERROR_OUT_OF_MEMORY, "stc_system_s malloc fail!");
1981
1982         /* initializing current classid */
1983         init_current_classid();
1984
1985         /* initializing cgroups */
1986         cgroup_init();
1987
1988         /* creating monitored application tree */
1989         system->apps = g_tree_new_full(__apps_tree_key_compare, NULL,
1990                                        __apps_tree_key_free,
1991                                        __apps_tree_value_free);
1992
1993         system->rstns = g_tree_new_full(__rstns_tree_key_compare, NULL,
1994                                         __rstns_tree_key_free,
1995                                         __rstns_tree_value_free);
1996
1997         /* create netlink socket for updating kernel counters */
1998         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
1999         if (system->contr_sock < 0) {
2000                 STC_LOGE("failed to open socket"); //LCOV_EXCL_LINE
2001                 FREE(system); //LCOV_EXCL_LINE
2002                 return STC_ERROR_FAIL; //LCOV_EXCL_LINE
2003         }
2004
2005         gio = g_io_channel_unix_new(system->contr_sock);
2006         system->contr_gsource_id =
2007                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
2008                                (GIOFunc) __process_contr_reply,
2009                                NULL);
2010         g_io_channel_unref(gio);
2011
2012         g_system = system;
2013
2014         __add_application_by_interface(STC_TOTAL_DATACALL);
2015         __add_application_by_interface(STC_TOTAL_WIFI);
2016         __add_application_by_interface(STC_TOTAL_BLUETOOTH);
2017         __add_application_by_interface(STC_TOTAL_IPV4);
2018         __add_application_by_interface(STC_TOTAL_IPV6);
2019         __add_application_by_interface(STC_TOTAL_TETHERING);
2020
2021         /* creating restriction rules tree */
2022         __update_contr_cb(NULL);
2023
2024         /* registering periodic kernel counters update callback */
2025         g_system->contr_timer_id = g_timeout_add_seconds(CONTR_TIMER_INTERVAL,
2026                                                          __update_contr_cb,
2027                                                          NULL);
2028         if (g_system->contr_timer_id == 0) {
2029                 STC_LOGE("Failed to register kernel counters update timer"); //LCOV_EXCL_LINE
2030                 __close_contr_sock(g_system); //LCOV_EXCL_LINE
2031                 return STC_ERROR_FAIL; //LCOV_EXCL_LINE
2032         }
2033
2034         __vconf_get_int(VCONFKEY_STC_BACKGROUND_STATE,
2035                         (int *)&g_system->background_state);
2036
2037         __fill_exceptions_list();
2038         __fill_restritions_list();
2039
2040         return STC_ERROR_NONE;
2041 }
2042
2043 stc_error_e stc_monitor_deinit(void)
2044 {
2045         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
2046
2047         /* close netlink socket for updating kernel counters */
2048         __close_contr_sock(g_system);
2049
2050         /* remove kernel counters update timer */
2051         if (g_system->contr_timer_id > 0) {
2052                 g_source_remove(g_system->contr_timer_id);
2053                 g_system->contr_timer_id = 0;
2054         }
2055
2056         /* destroy monitored application tree */
2057         g_tree_destroy(g_system->apps);
2058         g_system->apps = NULL;
2059
2060         /* destroy restriction rules tree */
2061         g_tree_destroy(g_system->rstns);
2062         g_system->rstns = NULL;
2063
2064         FREE(g_system);
2065
2066         return STC_ERROR_NONE;
2067 }
2068
2069 API stc_error_e stc_monitor_application_add(const stc_app_key_s app_key,
2070                                         const stc_app_value_s app_value)
2071 {
2072         stc_error_e ret = STC_ERROR_NONE;
2073         stc_app_key_s *key;
2074         stc_app_value_s *value;
2075         stc_app_value_s *lookup;
2076
2077         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
2078
2079         lookup = __application_lookup(g_system->apps, &app_key);
2080         if (lookup)
2081                 return STC_ERROR_NONE; //LCOV_EXCL_LINE
2082
2083         key = MALLOC0(stc_app_key_s, 1);
2084         if (!key) {
2085                 STC_LOGE("key allocation failed"); //LCOV_EXCL_LINE
2086                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
2087         }
2088
2089         value = MALLOC0(stc_app_value_s, 1);
2090         if (!value) {
2091                 STC_LOGE("value allocation failed"); //LCOV_EXCL_LINE
2092                 FREE(key); //LCOV_EXCL_LINE
2093                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
2094         }
2095
2096         key->app_id = g_strdup(app_key.app_id);
2097         key->pkg_id = g_strdup(app_key.pkg_id);
2098
2099         value->type = app_value.type;
2100         value->data_usage.in_bytes = app_value.data_usage.in_bytes;
2101         value->data_usage.out_bytes = app_value.data_usage.out_bytes;
2102
2103         value->processes = g_tree_new_full(__processes_tree_key_compare, NULL,
2104                                            __processes_tree_key_free,
2105                                            __processes_tree_value_free);
2106
2107         /* create cgroup and update classid */
2108         value->classid = get_classid_by_app_id(app_key.app_id, TRUE);
2109
2110         g_tree_insert(g_system->apps, key, value);
2111
2112         /* add nfacct rule for this classid */
2113         __add_application_monitor(key, value, stc_get_default_connection());
2114         __add_rstns_for_application(app_key.app_id);
2115
2116         return ret;
2117 }
2118
2119 API stc_error_e stc_monitor_process_add(const stc_app_key_s app_key,
2120                                     const stc_process_key_s proc_key,
2121                                     const stc_process_value_s proc_value)
2122 {
2123         stc_error_e ret = STC_ERROR_NONE;
2124         stc_app_value_s *app_lookup;
2125         stc_process_key_s *key;
2126         stc_process_value_s *value;
2127         stc_process_value_s *proc_lookup;
2128
2129         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
2130
2131         app_lookup = __application_lookup(g_system->apps, &app_key);
2132         if (!app_lookup) {
2133                 if (STC_DEBUG_LOG)
2134                         STC_LOGD("app_key not found"); //LCOV_EXCL_LINE
2135                 return STC_ERROR_FAIL; //LCOV_EXCL_LINE
2136         }
2137
2138         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
2139         if (proc_lookup)
2140                 return STC_ERROR_NONE; //LCOV_EXCL_LINE
2141
2142         key = MALLOC0(stc_process_key_s, 1);
2143         if (!key) {
2144                 STC_LOGE("key allocation failed"); //LCOV_EXCL_LINE
2145                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
2146         }
2147
2148         value = MALLOC0(stc_process_value_s, 1);
2149         if (!value) {
2150                 STC_LOGE("value allocation failed"); //LCOV_EXCL_LINE
2151                 FREE(key); //LCOV_EXCL_LINE
2152                 return STC_ERROR_OUT_OF_MEMORY; //LCOV_EXCL_LINE
2153         }
2154
2155         key->pid = proc_key.pid;
2156
2157         value->ground = proc_value.ground;
2158
2159         g_tree_insert(app_lookup->processes, key, value);
2160
2161         /* add pid to application cgroup */
2162         place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
2163
2164         /*
2165         __apps_tree_printall(); //LCOV_EXCL_LINE
2166         */
2167
2168         return ret;
2169 }
2170
2171 API stc_error_e stc_monitor_process_remove(pid_t pid)
2172 {
2173         stc_error_e ret = STC_ERROR_NONE;
2174         stc_process_key_s proc_key = {
2175                 .pid = pid
2176         };
2177
2178         remove_pid_context_s context = {
2179                 .app_key = NULL,
2180                 .proc_key = &proc_key,
2181                 .entry_removed = FALSE,
2182         };
2183
2184         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
2185
2186         g_tree_foreach(g_system->apps, __apps_tree_foreach_remove_pid,
2187                        &context);
2188
2189         if (context.entry_removed)
2190                 __application_remove_if_empty(context.app_key);
2191
2192         /*
2193         __apps_tree_printall(); //LCOV_EXCL_LINE
2194         */
2195
2196         return ret;
2197 }
2198
2199 //LCOV_EXCL_START
2200 API stc_error_e stc_monitor_process_update_ground(const stc_app_key_s app_key,
2201                                               const stc_process_key_s proc_key,
2202                                               stc_app_state_e ground)
2203 {
2204         stc_error_e ret = STC_ERROR_NONE;
2205         stc_app_value_s *app_lookup;
2206         stc_process_value_s *proc_lookup;
2207
2208         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
2209
2210         app_lookup = __application_lookup(g_system->apps, &app_key);
2211         if (!app_lookup) {
2212                 STC_LOGD("app_key not found");
2213                 return STC_ERROR_FAIL;
2214         }
2215
2216         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
2217         if (!proc_lookup) {
2218                 STC_LOGD("proc_key not found");
2219                 return STC_ERROR_FAIL;
2220         }
2221
2222         if (proc_lookup->ground != ground)
2223                 proc_lookup->ground = ground;
2224
2225         if (ground == STC_APP_STATE_BACKGROUND && __get_background_state())
2226                 place_pids_to_net_cgroup(proc_key.pid, STC_BACKGROUND_APP_ID);
2227         else
2228                 place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
2229
2230         return ret;
2231 }
2232 //LCOV_EXCL_STOP
2233
2234 void stc_monitor_update_rstn_by_default_connection(void *data)
2235 {
2236         static default_connection_s old_connection;
2237         default_connection_s *new_connection = (default_connection_s *)data;
2238
2239         if (old_connection.path != NULL) {
2240                 //LCOV_EXCL_START
2241                 if (g_system->apps)
2242                         g_tree_foreach(g_system->apps,
2243                                        __remove_application_monitor,
2244                                        (gpointer)&old_connection);
2245
2246                 if (g_system->rstns)
2247                         g_tree_foreach(g_system->rstns,
2248                                        __remove_restriction,
2249                                        (gpointer)&old_connection);
2250
2251                 iptables_flush_chains();
2252                 //LCOV_EXCL_STOP
2253         }
2254
2255         FREE(old_connection.path);
2256         FREE(old_connection.ifname);
2257         FREE(old_connection.tether_iface.ifname);
2258         old_connection.type = 0;
2259         old_connection.roaming = 0;
2260         old_connection.tether_state = FALSE;
2261         old_connection.tether_iface.type = 0;
2262
2263         if (new_connection != NULL && new_connection->path != NULL) {
2264                 if (g_system->apps)
2265                         g_tree_foreach(g_system->apps,
2266                                        __add_application_monitor,
2267                                        (gpointer)new_connection);
2268
2269                 if (g_system->rstns)
2270                         g_tree_foreach(g_system->rstns, __add_restriction,
2271                                        NULL);
2272
2273                 old_connection.path = g_strdup(new_connection->path);
2274                 old_connection.ifname = g_strdup(new_connection->ifname);
2275                 old_connection.tether_iface.ifname = g_strdup(new_connection->tether_iface.ifname);
2276                 old_connection.type = new_connection->type;
2277                 old_connection.roaming = new_connection->roaming;
2278                 old_connection.tether_state = new_connection->tether_state;
2279                 old_connection.tether_iface.type = new_connection->tether_iface.type;
2280         }
2281 }
2282
2283 stc_error_e stc_monitor_rstns_tree_add(const table_restrictions_info *info)
2284 {
2285         stc_error_e ret;
2286
2287         stc_rstn_key_s key;
2288         stc_rstn_value_s value;
2289
2290         memset(&key, 0, sizeof(stc_rstn_key_s));
2291         memset(&value, 0, sizeof(stc_rstn_value_s));
2292
2293         key.app_id = g_strdup(info->app_id);
2294         key.ifname = g_strdup(info->ifname);
2295         key.subscriber_id = g_strdup(info->subscriber_id);
2296         key.iftype = info->iftype;
2297         key.roaming = info->roaming;
2298
2299         value.rstn_type = info->rstn_type;
2300         value.rstn_state = STC_RSTN_STATE_UNKNOWN;
2301         value.restriction_id = info->restriction_id;
2302
2303         if (info->app_id)
2304                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
2305         else
2306                 value.classid = STC_UNKNOWN_CLASSID;
2307
2308         if (value.classid == STC_BACKGROUND_APP_CLASSID) {
2309                 __set_background_state(TRUE); //LCOV_EXCL_LINE
2310                 __vconf_set_int(VCONFKEY_STC_BACKGROUND_STATE, g_system->background_state); //LCOV_EXCL_LINE
2311                 __process_update_background(); //LCOV_EXCL_LINE
2312         }
2313
2314         value.limit[STC_RSTN_LIMIT_TYPE_DATA] = info->data_limit;
2315         value.limit[STC_RSTN_LIMIT_TYPE_DATA_WARN] = info->data_warn_limit;
2316         value.limit[STC_RSTN_LIMIT_TYPE_MONTHLY] = info->monthly_limit;
2317         value.limit[STC_RSTN_LIMIT_TYPE_WEEKLY] = info->weekly_limit;
2318         value.limit[STC_RSTN_LIMIT_TYPE_DAILY] = info->daily_limit;
2319         value.month_start_date = info->month_start_date;
2320         value.month_start_ts = stc_time_get_month_start(time(NULL),
2321                                                                                 info->month_start_date);
2322
2323         ret = __rstn_tree_add(&key, &value, TRUE);
2324
2325         FREE(key.app_id);
2326         FREE(key.ifname);
2327         FREE(key.subscriber_id);
2328         return ret;
2329 }
2330
2331 stc_error_e stc_monitor_rstns_tree_remove(const table_restrictions_info *info)
2332 {
2333         stc_error_e ret;
2334
2335         stc_rstn_key_s key = {
2336                 .app_id = g_strdup(info->app_id),
2337                 .ifname = g_strdup(info->ifname),
2338                 .subscriber_id = g_strdup(info->subscriber_id),
2339                 .iftype = info->iftype,
2340                 .roaming = info->roaming,
2341         };
2342
2343         if (!strcmp(key.app_id, STC_BACKGROUND_APP_ID)) {
2344                 __set_background_state(FALSE); //LCOV_EXCL_LINE
2345                 __vconf_set_int(VCONFKEY_STC_BACKGROUND_STATE, g_system->background_state); //LCOV_EXCL_LINE
2346                 __process_update_background(); //LCOV_EXCL_LINE
2347         }
2348
2349         ret = __rstn_tree_remove(&key);
2350
2351         FREE(key.app_id);
2352         FREE(key.ifname);
2353         FREE(key.subscriber_id);
2354         return ret;
2355 }
2356
2357 API stc_error_e stc_monitor_check_excn_by_cmdline(char *cmdline)
2358 {
2359         return stc_plugin_check_exception_by_cmdline(cmdline);
2360 }
2361
2362 int stc_monitor_get_counter_socket(void)
2363 {
2364         return g_system->contr_sock;
2365 }