Use heap instead of stack, to aviod large stack usage issue in __process_contr_reply()
[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 "counter.h"
27 #include "table-statistics.h"
28 #include "table-counters.h"
29 #include "stc-exception.h"
30 #include "stc-monitor.h"
31 #include "stc-manager-plugin.h"
32
33 #define MAX_INT_LENGTH 128
34 #define VCONFKEY_STC_BACKGROUND_STATE "db/stc/background_state"
35
36 typedef struct {
37         stc_app_key_s *app_key;
38         stc_process_key_s *proc_key;
39         gboolean entry_removed;
40 } remove_pid_context_s;
41
42 typedef struct {
43         struct nfacct_rule *counter;
44         int64_t bytes;
45         gboolean data_limit_reached;
46 } classid_bytes_context_s;
47
48 static stc_system_s *g_system = NULL;
49
50 static nfacct_rule_jump __get_jump_by_intend(struct nfacct_rule *counter)
51 {
52         if (counter->intend == NFACCT_WARN)
53                 return NFACCT_JUMP_ACCEPT;
54         else if (counter->intend == NFACCT_BLOCK)
55                 return NFACCT_JUMP_REJECT;
56
57         return NFACCT_JUMP_UNKNOWN;
58 }
59
60 static stc_error_e __add_iptables_in(struct nfacct_rule *counter)
61 {
62         if (counter == NULL)
63                 return STC_ERROR_INVALID_PARAMETER;
64
65         counter->action = NFACCT_ACTION_INSERT;
66         counter->iotype = NFACCT_COUNTER_IN;
67         counter->jump = __get_jump_by_intend(counter);
68         counter->iptype = NFACCT_TYPE_IPV4;
69         counter->send_limit = 0;
70         counter->rcv_limit = 0;
71
72         return produce_net_rule(counter);
73 }
74
75 static stc_error_e __add_iptables_out(struct nfacct_rule *counter)
76 {
77         if (counter == NULL)
78                 return STC_ERROR_INVALID_PARAMETER;
79
80         counter->action = NFACCT_ACTION_INSERT;
81         counter->iotype = NFACCT_COUNTER_OUT;
82         counter->jump = __get_jump_by_intend(counter);
83         counter->iptype = NFACCT_TYPE_IPV4;
84         counter->send_limit = 0;
85         counter->rcv_limit = 0;
86
87         return produce_net_rule(counter);
88 }
89
90 static stc_error_e __del_iptables_in(struct nfacct_rule *counter)
91 {
92         if (counter == NULL)
93                 return STC_ERROR_INVALID_PARAMETER;
94
95         counter->action = NFACCT_ACTION_DELETE;
96         counter->iotype = NFACCT_COUNTER_IN;
97         counter->jump = __get_jump_by_intend(counter);
98         counter->iptype = NFACCT_TYPE_IPV4;
99         counter->send_limit = 0;
100         counter->rcv_limit = 0;
101
102         return produce_net_rule(counter);
103 }
104
105 static stc_error_e __del_iptables_out(struct nfacct_rule *counter)
106 {
107         if (counter == NULL)
108                 return STC_ERROR_INVALID_PARAMETER;
109
110         counter->action = NFACCT_ACTION_DELETE;
111         counter->iotype = NFACCT_COUNTER_OUT;
112         counter->jump = __get_jump_by_intend(counter);
113         counter->iptype = NFACCT_TYPE_IPV4;
114         counter->send_limit = 0;
115         counter->rcv_limit = 0;
116
117         return produce_net_rule(counter);
118 }
119
120 static stc_error_e __add_ip6tables_in(struct nfacct_rule *counter)
121 {
122         if (counter == NULL)
123                 return STC_ERROR_INVALID_PARAMETER;
124
125         counter->action = NFACCT_ACTION_INSERT;
126         counter->iotype = NFACCT_COUNTER_IN;
127         counter->jump = __get_jump_by_intend(counter);
128         counter->iptype = NFACCT_TYPE_IPV6;
129         counter->send_limit = 0;
130         counter->rcv_limit = 0;
131
132         return produce_net_rule(counter);
133 }
134
135 static stc_error_e __add_ip6tables_out(struct nfacct_rule *counter)
136 {
137         if (counter == NULL)
138                 return STC_ERROR_INVALID_PARAMETER;
139
140         counter->action = NFACCT_ACTION_INSERT;
141         counter->iotype = NFACCT_COUNTER_OUT;
142         counter->jump = __get_jump_by_intend(counter);
143         counter->iptype = NFACCT_TYPE_IPV6;
144         counter->send_limit = 0;
145         counter->rcv_limit = 0;
146
147         return produce_net_rule(counter);
148 }
149
150 static stc_error_e __del_ip6tables_in(struct nfacct_rule *counter)
151 {
152         if (counter == NULL)
153                 return STC_ERROR_INVALID_PARAMETER;
154
155         counter->action = NFACCT_ACTION_DELETE;
156         counter->iotype = NFACCT_COUNTER_IN;
157         counter->jump = __get_jump_by_intend(counter);
158         counter->iptype = NFACCT_TYPE_IPV6;
159         counter->send_limit = 0;
160         counter->rcv_limit = 0;
161
162         return produce_net_rule(counter);
163 }
164
165 static stc_error_e __del_ip6tables_out(struct nfacct_rule *counter)
166 {
167         if (counter == NULL)
168                 return STC_ERROR_INVALID_PARAMETER;
169
170         counter->action = NFACCT_ACTION_DELETE;
171         counter->iotype = NFACCT_COUNTER_OUT;
172         counter->jump = __get_jump_by_intend(counter);
173         counter->iptype = NFACCT_TYPE_IPV6;
174         counter->send_limit = 0;
175         counter->rcv_limit = 0;
176
177         return produce_net_rule(counter);
178 }
179
180 static int __processes_tree_key_compare(gconstpointer a, gconstpointer b,
181                                         gpointer UNUSED user_data)
182 {
183         stc_process_key_s *key_a = (stc_process_key_s *)a;
184         stc_process_key_s *key_b = (stc_process_key_s *)b;
185
186         return key_a->pid - key_b->pid;
187 }
188
189 static void __processes_tree_value_free(gpointer data)
190 {
191         stc_process_value_s *value = (stc_process_value_s *)data;
192
193         FREE(value);
194 }
195
196 static void __processes_tree_key_free(gpointer data)
197 {
198         stc_process_key_s *key = (stc_process_key_s *)data;
199
200         FREE(key);
201 }
202
203 static int __apps_tree_key_compare(gconstpointer a, gconstpointer b,
204                                    gpointer UNUSED user_data)
205 {
206         stc_app_key_s *key_a = (stc_app_key_s *)a;
207         stc_app_key_s *key_b = (stc_app_key_s *)b;
208         gint ret;
209
210         ret = g_strcmp0(key_a->pkg_id, key_b->pkg_id);
211         if (ret)
212                 return ret;
213
214         return g_strcmp0(key_a->app_id, key_b->app_id);
215 }
216
217 static void __apps_tree_value_free(gpointer data)
218 {
219         stc_app_value_s *value = (stc_app_value_s *)data;
220
221         g_tree_destroy(value->processes);
222         value->processes = NULL;
223
224         FREE(value);
225 }
226
227 static void __apps_tree_key_free(gpointer data)
228 {
229         stc_app_key_s *key = (stc_app_key_s *)data;
230
231         g_free(key->pkg_id);
232         g_free(key->app_id);
233         FREE(key);
234 }
235
236 static int __rstns_tree_key_compare(gconstpointer a, gconstpointer b,
237                                     gpointer UNUSED user_data)
238 {
239         stc_rstn_key_s *key_a = (stc_rstn_key_s *)a;
240         stc_rstn_key_s *key_b = (stc_rstn_key_s *)b;
241         int ret;
242
243         ret = g_strcmp0(key_a->app_id, key_b->app_id);
244         if (ret != 0)
245                 return ret;
246
247         ret = g_strcmp0(key_a->ifname, key_b->ifname);
248         if (ret != 0)
249                 return ret;
250
251         ret = g_strcmp0(key_a->subscriber_id, key_b->subscriber_id);
252         if (ret != 0)
253                 return ret;
254
255         ret = key_a->iftype - key_b->iftype;
256         if (ret != 0)
257                 return ret;
258
259         return 0;
260 }
261
262 static void __rstns_tree_value_free(gpointer data)
263 {
264         stc_rstn_value_s *value = (stc_rstn_value_s *)data;
265
266         FREE(value);
267 }
268
269 static void __rstns_tree_key_free(gpointer data)
270 {
271         stc_rstn_key_s *key = (stc_rstn_key_s *)data;
272
273         FREE(key->app_id);
274         FREE(key->ifname);
275         FREE(key->subscriber_id);
276         FREE(key);
277 }
278
279 static gboolean __processes_tree_foreach_print(gpointer key, gpointer value,
280                                                gpointer data)
281 {
282         stc_process_key_s *proc_key = (stc_process_key_s *)key;
283         stc_process_value_s *proc_value = (stc_process_value_s *)value;
284
285         STC_LOGD("Process entry => PID [\033[1;33m%d\033[0;m], Ground state [%d]",
286                  proc_key->pid, proc_value->ground);
287         return FALSE;
288 }
289
290 static void __processes_tree_printall(GTree *processes)
291 {
292         g_tree_foreach(processes, __processes_tree_foreach_print, NULL);
293 }
294
295 static gboolean __apps_tree_foreach_print(gpointer key, gpointer value,
296                                           gpointer data)
297 {
298         stc_app_key_s *app_key = (stc_app_key_s *)key;
299         stc_app_value_s *app_value = (stc_app_value_s *)value;
300
301         STC_LOGD("Application info => Pkg ID [\033[0;34m%s\033[0;m], "
302                  "App ID [\033[0;32m%s\033[0;m], Type [%d], classid [%d],"
303                  " counter [ in (%lld), out (%lld)]",
304                  app_key->pkg_id, app_key->app_id,
305                  app_value->type, app_value->classid,
306                  app_value->data_usage.in_bytes, app_value->data_usage.out_bytes);
307
308         __processes_tree_printall(app_value->processes);
309         return FALSE;
310 }
311
312 static void __apps_tree_printall(void)
313 {
314         g_tree_foreach(g_system->apps, __apps_tree_foreach_print, NULL);
315 }
316
317 static gboolean __apps_tree_foreach_remove_pid(gpointer key, gpointer value,
318                                                gpointer data)
319 {
320         remove_pid_context_s *context = (remove_pid_context_s *)data;
321         stc_app_value_s *app_value = (stc_app_value_s *)value;
322
323         if (!g_tree_remove(app_value->processes, context->proc_key)) {
324                 if (STC_DEBUG_LOG)
325                         STC_LOGD("key not found");
326                 return FALSE;
327         }
328
329         context->entry_removed = TRUE;
330         context->app_key = (stc_app_key_s *)key;
331
332         return TRUE;
333 }
334
335 static stc_app_value_s * __application_lookup(GTree *apps,
336                                               const stc_app_key_s *key)
337 {
338         stc_app_value_s *lookup;
339
340         ret_value_msg_if(apps == NULL, NULL, "apps is null!");
341
342         lookup = g_tree_lookup(apps, key);
343
344         return lookup;
345 }
346
347 static stc_process_value_s * __process_lookup(GTree *processes,
348                                               const stc_process_key_s *key)
349 {
350         stc_process_value_s *lookup;
351
352         ret_value_msg_if(processes == NULL, NULL, "processes is null!");
353
354         lookup = g_tree_lookup(processes, key);
355
356         return lookup;
357 }
358
359 static gboolean __processes_tree_check_empty(gpointer key, gpointer value,
360                                              gpointer data)
361 {
362         guint *pid_count = (guint *)data;
363         (*pid_count)++;
364         return TRUE;
365 }
366
367 static gboolean __add_application_monitor(gpointer key, gpointer value,
368                                           gpointer data)
369 {
370         stc_app_value_s *app_value = (stc_app_value_s *)value;
371         default_connection_s *connection = (default_connection_s *)data;
372         stc_s *stc = stc_get_manager();
373
374         if (app_value->classid == STC_TOTAL_DATACALL_CLASSID ||
375             app_value->classid == STC_TOTAL_WIFI_CLASSID ||
376             app_value->classid == STC_TOTAL_BLUETOOTH_CLASSID)
377                 return FALSE;
378
379         if (stc && connection && connection->ifname) {
380                 struct nfacct_rule counter;
381
382                 if (!stc->carg) {
383                         stc->carg = MALLOC0(counter_arg_s, 1);
384                         if (stc->carg == NULL)
385                                 return FALSE;
386
387                         stc->carg->sock = stc_monitor_get_counter_socket();
388                 }
389
390                 memset(&counter, 0, sizeof(struct nfacct_rule));
391
392                 counter.carg = stc->carg;
393                 counter.classid = app_value->classid;
394                 counter.intend = NFACCT_COUNTER;
395                 counter.iftype = connection->type;
396                 g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
397
398                 if (app_value->classid == STC_TOTAL_IPV4_CLASSID) {
399                         __add_iptables_in(&counter);
400                         __add_iptables_out(&counter);
401                 } else if (app_value->classid == STC_TOTAL_IPV6_CLASSID) {
402                         __add_ip6tables_in(&counter);
403                         __add_ip6tables_out(&counter);
404                 } else {
405                         __add_iptables_in(&counter);
406                         __add_iptables_out(&counter);
407                         __add_ip6tables_in(&counter);
408                         __add_ip6tables_out(&counter);
409                 }
410         }
411
412         return FALSE;
413 }
414
415 static gboolean __remove_application_monitor(gpointer key, gpointer value,
416                                              gpointer data)
417 {
418         stc_app_value_s *app_value = (stc_app_value_s *)value;
419         default_connection_s *connection = (default_connection_s *)data;
420         stc_s *stc = stc_get_manager();
421
422         if (stc && connection && connection->ifname) {
423                 struct nfacct_rule counter;
424
425                 if (!stc->carg) {
426                         stc->carg = MALLOC0(counter_arg_s, 1);
427                         if (stc->carg == NULL)
428                                 return FALSE;
429
430                         stc->carg->sock = stc_monitor_get_counter_socket();
431                 }
432
433                 memset(&counter, 0, sizeof(struct nfacct_rule));
434
435                 counter.carg = stc->carg;
436                 counter.classid = app_value->classid;
437                 counter.intend = NFACCT_COUNTER;
438                 counter.iftype = connection->type;
439                 g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
440
441                 __del_iptables_in(&counter);
442                 __del_iptables_out(&counter);
443                 __del_ip6tables_in(&counter);
444                 __del_ip6tables_out(&counter);
445         }
446
447         return FALSE;
448 }
449
450 static void __print_rstn(stc_rstn_key_s *rstn_key, stc_rstn_value_s *rstn_value)
451 {
452         STC_LOGI("rstn info => rstn_id [%llu], "
453                  "app_id [%s], classid [%lu], ifname [%s], "
454                  "iftype [%d], rst_state [%d], "
455                  "limit [ (%lld) bytes], "
456                  "warn_limit [ (%lld) bytes], "
457                  "counter [ (%lld) bytes], "
458                  "roaming [%d], subscriber_id [%s]",
459                  rstn_value->restriction_id,
460                  rstn_key->app_id, rstn_value->classid , rstn_key->ifname,
461                  rstn_key->iftype, rstn_value->rst_state,
462                  rstn_value->data_limit,
463                  rstn_value->data_warn_limit,
464                  rstn_value->data_counter,
465                  rstn_key->roaming, rstn_key->subscriber_id);
466 }
467
468 static void __process_restriction(enum traffic_restriction_type rst_type,
469                                   stc_rstn_key_s *rstn_key,
470                                   stc_rstn_value_s *rstn_value, void *data)
471 {
472         int64_t effective_data_limit, effective_data_warn_limit;
473         default_connection_s *old_connection = (default_connection_s *)data;
474         default_connection_s *connection = NULL;
475
476         if (old_connection != NULL)
477                 connection = old_connection;
478         else
479                 connection = stc_get_default_connection();
480
481         /* no default ifname */
482         if (connection->ifname == NULL)
483                 return;
484
485         /* rstn not applicable for this interface */
486         if (rstn_key->ifname != NULL && g_strcmp0("", rstn_key->ifname) != 0 &&
487             g_strcmp0(connection->ifname, rstn_key->ifname) != 0)
488                 return;
489
490         /* classid is invalid */
491         if (rstn_value->classid == STC_UNKNOWN_CLASSID)
492                 return;
493
494         effective_data_limit = rstn_value->data_limit;
495         effective_data_warn_limit = rstn_value->data_warn_limit;
496
497         if (rst_type == RST_SET) {
498                 /* TODO: Change this to runtime memory */
499                 table_counters_info info;
500
501                 memset(&info, 0, sizeof(table_counters_info));
502                 table_counters_get(rstn_value->restriction_id, &info);
503
504                 effective_data_limit -= info.data_counter;
505                 effective_data_warn_limit -= info.data_counter;
506
507                 if (effective_data_limit < 0) {
508                         effective_data_limit = 0;
509                         rstn_value->data_limit_reached = TRUE;
510                 }
511
512                 if (effective_data_warn_limit < 0)
513                         effective_data_warn_limit = 0;
514
515                 STC_LOGD("datausage [%lld] bytes", info.data_counter);
516         }
517
518         STC_LOGD("rstn_id [%llu], effective_data_limit [%lld] bytes, "
519                  "effective_data_warn_limit [%lld] bytes",
520                  rstn_value->restriction_id, effective_data_limit,
521                  effective_data_warn_limit);
522
523         switch (rst_type) {
524         case RST_SET:
525                 if (effective_data_limit <= 0) {
526                         char *default_ifname = stc_default_connection_get_ifname();
527                         struct nfacct_rule counter;
528                         stc_s *stc = stc_get_manager();
529
530                         if (!stc->carg) {
531                                 stc->carg = MALLOC0(counter_arg_s, 1);
532                                 if (stc->carg == NULL) {
533                                         g_free(default_ifname);
534                                         return;
535                                 }
536
537                                 stc->carg->sock =
538                                         stc_monitor_get_counter_socket();
539                         }
540
541                         counter.carg = stc->carg;
542                         counter.classid = rstn_value->classid;
543                         counter.intend = NFACCT_BLOCK;
544                         counter.iftype = rstn_key->iftype;
545                         g_strlcpy(counter.ifname, default_ifname,
546                                   MAX_IFACE_LENGTH);
547
548                         generate_counter_name(&counter);
549                         g_free(default_ifname);
550
551                         /* iptables rule */
552                         __add_iptables_in(&counter);
553                         __add_iptables_out(&counter);
554
555                         /* ip6tables rule */
556                         __add_ip6tables_in(&counter);
557                         __add_ip6tables_out(&counter);
558                 }
559
560                 rstn_value->rst_state = STC_RESTRICTION_ACTIVATED;
561                 rstn_value->data_limit_reached = FALSE;
562                 break;
563         case RST_EXCLUDE:
564                 ;//Do Nothing
565                 break;
566         case RST_UNSET:
567                 {
568                         char *default_ifname = stc_default_connection_get_ifname();
569                         struct nfacct_rule counter;
570                         stc_s *stc = stc_get_manager();
571
572                         if (!stc->carg) {
573                                 stc->carg = MALLOC0(counter_arg_s, 1);
574                                 if (stc->carg == NULL) {
575                                         g_free(default_ifname);
576                                         return;
577                                 }
578
579                                 stc->carg->sock =
580                                         stc_monitor_get_counter_socket();
581                         }
582
583                         counter.carg = stc->carg;
584                         counter.classid = rstn_value->classid;
585                         counter.intend = NFACCT_BLOCK;
586                         counter.iftype = rstn_key->iftype;
587                         g_strlcpy(counter.ifname, default_ifname,
588                                   MAX_IFACE_LENGTH);
589
590                         generate_counter_name(&counter);
591                         g_free(default_ifname);
592
593                         /* iptables rule */
594                         __del_iptables_in(&counter);
595                         __del_iptables_out(&counter);
596
597                         /* ip6tables rule */
598                         __del_ip6tables_in(&counter);
599                         __del_ip6tables_out(&counter);
600
601                         rstn_value->rst_state = STC_RESTRICTION_REMOVED;
602                         rstn_value->data_limit_reached = FALSE;
603                 }
604                 break;
605         default:
606                 ;//Do Nothing
607         }
608 }
609
610 static gboolean __remove_rstns_foreach_application(gpointer key,
611                                                    gpointer value,
612                                                    gpointer data)
613 {
614         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
615         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
616         gchar *app_id = (gchar *)data;
617
618         /* rstn rule is not for applications */
619         if (rstn_key->app_id == NULL)
620                 goto out;
621
622         /* rstn rule is not for this application */
623         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
624                 goto out;
625
626         /* rstn rule is already removed */
627         if (rstn_value->rst_state == STC_RESTRICTION_REMOVED)
628                 goto out;
629
630         /* remove restriction from system */
631         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
632
633         __print_rstn(rstn_key, rstn_value);
634 out:
635         return FALSE;
636 }
637
638 static void __remove_rstns_for_application(gchar *app_id)
639 {
640         g_tree_foreach(g_system->rstns, __remove_rstns_foreach_application,
641                        app_id);
642 }
643
644 static stc_error_e __application_remove_if_empty(const stc_app_key_s *app_key)
645 {
646         stc_error_e ret = STC_ERROR_NONE;
647         guint pid_count = 0;
648         stc_app_value_s *lookup;
649
650         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
651
652         lookup = __application_lookup(g_system->apps, app_key);
653         if (!lookup) {
654                 STC_LOGE("app_key not found");
655                 return STC_ERROR_NO_DATA;
656         }
657
658         g_tree_foreach(lookup->processes, __processes_tree_check_empty,
659                        &pid_count);
660
661         if (!pid_count) {
662                 /* remove nfacct rule for this classid */
663                 __remove_application_monitor((gpointer) app_key, lookup,
664                                              stc_get_default_connection());
665                 __remove_rstns_for_application(app_key->app_id);
666         }
667
668         if (!g_tree_remove(g_system->apps, app_key)) {
669                 ret = STC_ERROR_NO_DATA;
670                 STC_LOGE("key not found");
671         }
672
673         return ret;
674 }
675
676 static stc_error_e __close_contr_sock(stc_system_s *system)
677 {
678         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
679
680         /* close netlink socket for updating kernel counters */
681         if (system->contr_sock != -1) {
682                 close(system->contr_sock);
683                 system->contr_sock = -1;
684         }
685
686         if (system->contr_gsource_id != 0) {
687                 g_source_remove(system->contr_gsource_id);
688                 system->contr_gsource_id = 0;
689         }
690
691         return STC_ERROR_NONE;
692 }
693
694 static gboolean __process_contr_reply(GIOChannel *source,
695                                       GIOCondition condition,
696                                       gpointer user_data);
697
698 static stc_error_e __close_and_reopen_contr_sock(stc_system_s *system)
699 {
700         GIOChannel *gio = NULL;
701         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
702
703         /* close netlink socket for updating kernel counters */
704         if (system->contr_sock != -1) {
705                 close(system->contr_sock);
706                 system->contr_sock = -1;
707         }
708
709         if (system->contr_gsource_id != 0) {
710                 g_source_remove(system->contr_gsource_id);
711                 system->contr_gsource_id = 0;
712         }
713
714         /* create netlink socket for updating kernel counters */
715         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
716         if (system->contr_sock < 0) {
717                 STC_LOGE("failed to open socket");
718                 FREE(system);
719                 return STC_ERROR_FAIL;
720         }
721
722         gio = g_io_channel_unix_new(system->contr_sock);
723         system->contr_gsource_id =
724                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
725                                (GIOFunc) __process_contr_reply,
726                                NULL);
727         g_io_channel_unref(gio);
728
729         return STC_ERROR_NONE;
730 }
731
732 static gboolean __rstn_counter_update(stc_rstn_key_s *rstn_key,
733                                       stc_rstn_value_s *rstn_value,
734                                       classid_bytes_context_s *context)
735 {
736         switch (context->counter->iotype) {
737         case NFACCT_COUNTER_IN:
738         case NFACCT_COUNTER_OUT:
739                 rstn_value->data_counter += context->bytes;
740
741                 if (rstn_value->data_counter >= rstn_value->data_warn_limit &&
742                     rstn_value->warn_limit_crossed_notified == FALSE) {
743
744                         gboolean rv;
745                         char iftype[MAX_INT_LENGTH];
746                         char byte[MAX_INT_LENGTH];
747                         stc_s *stc = (stc_s *)stc_get_manager();
748                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
749
750                         /* emit signal */
751                         rv = stc_manager_dbus_emit_signal(stc->connection,
752                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
753                                                           STC_DBUS_INTERFACE_RESTRICTION,
754                                                           "WarnThresholdCrossed",
755                                                           g_variant_new("(si)", rstn_key->app_id, rstn_key->iftype));
756                         if (rv == TRUE)
757                                 rstn_value->warn_limit_crossed_notified = TRUE;
758
759                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
760                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_warn_limit);
761                         stc_send_warn_message_to_net_popup("warn threshold crossed",
762                                                            "warning_noti",
763                                                            rstn_key->app_id,
764                                                            iftype, byte);
765                 }
766
767                 if (rstn_value->data_counter >= rstn_value->data_limit &&
768                     rstn_value->rstn_limit_crossed_notified == FALSE) {
769
770                         gboolean rv;
771                         char iftype[MAX_INT_LENGTH];
772                         char byte[MAX_INT_LENGTH];
773                         stc_s *stc = (stc_s *)stc_get_manager();
774                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
775
776                         /* block immediately */
777                         context->counter->intend = NFACCT_BLOCK;
778                         __del_iptables_in(context->counter);
779                         __del_iptables_out(context->counter);
780                         __add_iptables_in(context->counter);
781                         __add_iptables_out(context->counter);
782
783                         __del_ip6tables_in(context->counter);
784                         __del_ip6tables_out(context->counter);
785                         __add_ip6tables_in(context->counter);
786                         __add_ip6tables_out(context->counter);
787                         context->counter->intend = NFACCT_COUNTER;
788
789                         rstn_value->data_limit_reached = TRUE;
790
791                         /* emit signal */
792                         rv = stc_manager_dbus_emit_signal(stc->connection,
793                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
794                                                           STC_DBUS_INTERFACE_RESTRICTION,
795                                                           "RestrictionThresholdCrossed",
796                                                           g_variant_new("(si)", rstn_key->app_id, rstn_key->iftype));
797                         if (rv == TRUE)
798                                 rstn_value->rstn_limit_crossed_notified = TRUE;
799
800                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
801                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_limit);
802                         stc_send_restriction_message_to_net_popup("restriction threshold crossed",
803                                                                   "restriction_noti", rstn_key->app_id,
804                                                                   iftype, byte);
805                 }
806
807                 g_system->rstns_tree_updated = TRUE;
808                 __print_rstn(rstn_key, rstn_value);
809                 break;
810         default:
811                 STC_LOGE("unknown iotype");
812         }
813
814         return FALSE;
815 }
816
817 static gboolean __interface_rstn_counter_update(stc_rstn_key_s *rstn_key,
818                                                 stc_rstn_value_s *rstn_value,
819                                                 classid_bytes_context_s *context)
820 {
821         if ((rstn_value->classid == STC_TOTAL_DATACALL_CLASSID &&
822              context->counter->iftype == STC_IFACE_DATACALL) ||
823             (rstn_value->classid == STC_TOTAL_WIFI_CLASSID &&
824              context->counter->iftype == STC_IFACE_WIFI) ||
825             (rstn_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
826              context->counter->iftype == STC_IFACE_BLUETOOTH)) {
827                 context->counter->classid = rstn_value->classid;
828                 return __rstn_counter_update(rstn_key, rstn_value, context);
829         }
830
831         return FALSE;
832 }
833
834 static gboolean __rstn_counter_update_foreach_classid(gpointer key,
835                                                       gpointer value,
836                                                       gpointer data)
837 {
838         gboolean rv = FALSE;
839         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
840         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
841         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
842         uint32_t classid;
843
844         if (context->counter->intend != NFACCT_COUNTER)
845                 goto try_next_callback;
846
847         if (rstn_value->data_limit_reached == TRUE) {
848                 context->data_limit_reached = TRUE;
849                 goto try_next_callback;
850         }
851
852         classid = context->counter->classid;
853         rv = __interface_rstn_counter_update(rstn_key, rstn_value, context);
854
855         context->counter->classid = classid;
856         if (rstn_value->classid != context->counter->classid)
857                 goto try_next_callback;
858
859         rv = __rstn_counter_update(rstn_key, rstn_value, context);
860
861 try_next_callback:
862         return rv;
863 }
864
865 static gboolean __update_app_statistics(gpointer key, gpointer value,
866                                         gpointer data)
867 {
868         stc_app_key_s *app_key = (stc_app_key_s *)key;
869         stc_app_value_s *app_value = (stc_app_value_s *)value;
870         time_t *touch_time = (time_t *)data;
871         stc_db_classid_iftype_key stat_key;
872         stc_db_app_stats stat;
873         default_connection_s *default_connection = stc_get_default_connection();
874
875         memset(&stat_key, 0, sizeof(stc_db_classid_iftype_key));
876         memset(&stat, 0 , sizeof(stc_db_app_stats));
877
878         stat_key.classid = app_value->classid;
879         stat_key.iftype = default_connection->type;
880
881         if (STC_IFACE_DATACALL == stat_key.iftype)
882                 stat_key.subscriber_id = g_strdup(default_connection->subscriber_id);
883         else
884                 stat_key.subscriber_id = g_strdup("none_subid");
885
886         g_strlcpy(stat_key.ifname, default_connection->ifname,
887                   MAX_IFACE_LENGTH);
888
889         stat.app_id = g_strdup(app_key->app_id);
890         stat.snd_count = app_value->counter.out_bytes;
891         stat.rcv_count = app_value->counter.in_bytes;
892         stat.is_roaming = default_connection->roaming;
893
894         if (strstr(stat.app_id, "_BACKGROUND")) {
895                 stat.ground = STC_APP_STATE_BACKGROUND;
896         } else {
897                 if (strstr(stat.app_id, "TOTAL_"))
898                         stat.ground = STC_APP_STATE_UNKNOWN;
899                 else
900                         stat.ground = STC_APP_STATE_FOREGROUND;
901         }
902
903         table_statistics_insert(&stat_key, &stat, *touch_time);
904
905         app_value->counter.out_bytes = 0;
906         app_value->counter.in_bytes = 0;
907
908         FREE(stat.app_id);
909         FREE(stat_key.subscriber_id);
910
911         return FALSE;
912 }
913
914 static gboolean __flush_apps_stats_to_database(gpointer user_data)
915 {
916         time_t current_time = time(0);
917
918         if (g_system->apps_tree_updated == FALSE)
919                 return G_SOURCE_REMOVE;
920
921         g_system->apps_tree_updated = FALSE;
922
923         if (g_system->apps)
924                 g_tree_foreach(g_system->apps,
925                                __update_app_statistics,
926                                &current_time);
927
928         STC_LOGI("Flushed app stats to database");
929         return G_SOURCE_REMOVE;
930 }
931
932 static gboolean __update_counter_statistics(gpointer key, gpointer value,
933                                             gpointer data)
934 {
935         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
936         table_counters_info info = {
937                 .restriction_id = rstn_value->restriction_id,
938                 .data_counter = rstn_value->data_counter
939         };
940
941         table_counters_update_counters(&info);
942
943         return FALSE;
944 }
945
946 static gboolean __flush_rstns_counter_to_database(gpointer user_data)
947 {
948         time_t current_time = time(0);
949
950         if (g_system->rstns_tree_updated == FALSE)
951                 return G_SOURCE_REMOVE;
952
953         g_system->rstns_tree_updated = FALSE;
954
955         if (g_system->rstns)
956                 g_tree_foreach(g_system->rstns,
957                                __update_counter_statistics,
958                                &current_time);
959
960         STC_LOGI("Flushed rstns counters to database");
961         return G_SOURCE_REMOVE;
962 }
963
964 static void __app_counter_update(stc_app_key_s *app_key,
965                                  stc_app_value_s *app_value,
966                                  classid_bytes_context_s *context)
967 {
968         switch (context->counter->iotype) {
969         case NFACCT_COUNTER_IN:
970                 app_value->data_usage.in_bytes += context->bytes;
971                 app_value->counter.in_bytes = context->bytes;
972                 g_system->apps_tree_updated = TRUE;
973
974                 if (STC_DEBUG_LOG)
975                         __apps_tree_foreach_print(app_key, app_value, NULL);
976                 break;
977         case NFACCT_COUNTER_OUT:
978                 app_value->data_usage.out_bytes += context->bytes;
979                 app_value->counter.out_bytes = context->bytes;
980                 g_system->apps_tree_updated = TRUE;
981
982                 if (STC_DEBUG_LOG)
983                         __apps_tree_foreach_print(app_key, app_value, NULL);
984                 break;
985         default:
986                 STC_LOGE("unknown iotype");
987         }
988 }
989
990 static void __interface_counter_update(stc_app_key_s *app_key,
991                                        stc_app_value_s *app_value,
992                                        classid_bytes_context_s *context)
993 {
994         if ((app_value->classid == STC_TOTAL_DATACALL_CLASSID &&
995              context->counter->iftype == STC_IFACE_DATACALL) ||
996             (app_value->classid == STC_TOTAL_WIFI_CLASSID &&
997              context->counter->iftype == STC_IFACE_WIFI) ||
998             (app_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
999              context->counter->iftype == STC_IFACE_BLUETOOTH))
1000                 __app_counter_update(app_key, app_value, context);
1001 }
1002
1003
1004 static gboolean __apps_counter_update_foreach_classid(gpointer key,
1005                                                       gpointer value,
1006                                                       gpointer data)
1007 {
1008         stc_app_key_s *app_key = (stc_app_key_s *)key;
1009         stc_app_value_s *app_value = (stc_app_value_s *)value;
1010         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
1011
1012         if (context->counter->intend != NFACCT_COUNTER)
1013                 goto try_next_callback;
1014
1015         __interface_counter_update(app_key, app_value, context);
1016
1017         if (app_value->classid != context->counter->classid)
1018                 goto try_next_callback;
1019
1020         __app_counter_update(app_key, app_value, context);
1021
1022 try_next_callback:
1023         return FALSE;
1024 }
1025
1026 static void __fill_nfacct_result(char *cnt_name, int64_t bytes,
1027                                  struct counter_arg *carg)
1028 {
1029         struct nfacct_rule counter = {
1030                 .carg = carg,
1031                 .name = {0},
1032                 .ifname = {0},
1033                 0
1034         };
1035
1036         classid_bytes_context_s context = {
1037                 .counter = &counter,
1038                 .bytes = bytes,
1039                 .data_limit_reached = FALSE,
1040         };
1041
1042         if (STC_DEBUG_LOG)
1043                 STC_LOGD("cnt_name %s", cnt_name);
1044
1045         if (!recreate_counter_by_name(cnt_name, &counter)) {
1046                 STC_LOGE("Can't parse counter name %s", cnt_name);
1047                 return;
1048         }
1049
1050         STC_LOGI("classid %lu, iftype %u, iotype %d, intend %d, ifname %s, bytes %lld",
1051                  context.counter->classid, context.counter->iftype,
1052                  context.counter->iotype, context.counter->intend,
1053                  context.counter->ifname, context.bytes);
1054
1055         if (g_system->rstns)
1056                 g_tree_foreach(g_system->rstns,
1057                                __rstn_counter_update_foreach_classid,
1058                                &context);
1059
1060         if (g_system->apps)
1061                 g_tree_foreach(g_system->apps,
1062                                __apps_counter_update_foreach_classid,
1063                                &context);
1064 }
1065
1066 static int __fill_counters(struct rtattr *attr_list[__NFACCT_MAX],
1067                            void *user_data)
1068 {
1069         struct counter_arg *carg = user_data;
1070         char *cnt_name = (char *)RTA_DATA(attr_list[NFACCT_NAME]);
1071         if (carg->initiate) {
1072                 /**
1073                  * TODO: this will be used when daemon starts to update existing
1074                  * counter data if present.
1075                  *
1076                  populate_counters(cnt_name, carg);
1077                  */
1078         } else {
1079                 int64_t *bytes_p =
1080                         (int64_t *)RTA_DATA(attr_list[NFACCT_BYTES]);
1081                 int bytes = be64toh(*bytes_p);
1082                 if (bytes) {
1083                         ++carg->serialized_counters;
1084                         __fill_nfacct_result(cnt_name, bytes, carg);
1085                 }
1086         }
1087
1088         return 0;
1089 }
1090
1091 static int __post_fill_counters(void *user_data)
1092 {
1093         struct counter_arg *carg = user_data;
1094
1095         if (carg->initiate)
1096                 carg->initiate = 0;
1097
1098         return 0;
1099 }
1100
1101 static void __process_network_counter(struct genl *ans,
1102                                       struct counter_arg *carg)
1103 {
1104         struct netlink_serialization_params ser_params = {
1105                 .carg = carg,
1106                 .ans = ans,
1107                 .eval_attr = __fill_counters,
1108                 .post_eval_attr = __post_fill_counters,
1109         };
1110
1111         netlink_serialization_command *netlink =
1112                 netlink_create_command(&ser_params);
1113         if (!netlink) {
1114                 STC_LOGE("Can not create command");
1115                 return;
1116         }
1117
1118         netlink->deserialize_answer(&(netlink->params));
1119 }
1120
1121 static gboolean __process_contr_reply(GIOChannel *source,
1122                                       GIOCondition condition,
1123                                       gpointer user_data)
1124 {
1125         int sock = g_io_channel_unix_get_fd(source);
1126         struct genl *ans;
1127         int ret;
1128         stc_s *stc = stc_get_manager();
1129
1130         if ((condition & G_IO_ERR) || (condition & G_IO_HUP) ||
1131             (condition & G_IO_NVAL)) {
1132                 /* G_IO_ERR/G_IO_HUP/G_IO_NVAL received */
1133
1134                 STC_LOGE("Counter socket received G_IO event, closing socket."
1135                          "G_IO_ERR [%d], G_IO_HUP [%d], G_IO_NVAL [%s]",
1136                          (condition & G_IO_ERR), (condition & G_IO_HUP),
1137                          (condition & G_IO_NVAL));
1138                 __close_and_reopen_contr_sock(g_system);
1139                 return FALSE;
1140         }
1141
1142         ans = MALLOC0(struct genl, 1);
1143         if (ans == NULL) {
1144                 STC_LOGE("Failed allocate memory to genl reply message");
1145                 return TRUE;
1146         }
1147
1148         if (stc == NULL) {
1149                 STC_LOGE("Can't get stc data");
1150                 goto out;
1151         }
1152
1153         ret = read_netlink(sock, ans, sizeof(struct genl));
1154         /* STC_LOGD("Counter data received ret [%d]", ret); */
1155         if (ret == 0)
1156                 goto out;
1157
1158         stc->carg->ans_len = ret;
1159         __process_network_counter(ans, stc->carg);
1160
1161         g_idle_add(__flush_apps_stats_to_database, NULL);
1162         g_idle_add(__flush_rstns_counter_to_database, NULL);
1163 out:
1164         FREE(ans);
1165         return TRUE;
1166 }
1167
1168 static gboolean __update_contr_cb(void *user_data)
1169 {
1170         /* Here we just sent command, answer we receive in another callback */
1171         stc_s *stc = stc_get_manager();
1172         ret_value_msg_if(stc == NULL, STC_ERROR_FAIL, "Can't get stc data");
1173         if (!stc->carg) {
1174                 stc->carg = MALLOC0(counter_arg_s, 1);
1175                 if (stc->carg == NULL)
1176                         return TRUE;  /* we need to continue the timer */
1177
1178                 stc->carg->sock = stc_monitor_get_counter_socket();
1179         }
1180
1181         /* STC_LOGD("Get all counters"); */
1182         nfacct_send_get_all(stc->carg);
1183
1184         /* we need to continue the timer */
1185         return TRUE;
1186 }
1187 #if 0
1188 static gboolean __rstn_tree_foreach_print(gpointer key, gpointer value,
1189                                           gpointer data)
1190 {
1191         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1192         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1193
1194         __print_rstn(rstn_key, rstn_value);
1195         return FALSE;
1196 }
1197
1198 static void __rstn_tree_printall(void)
1199 {
1200         g_tree_foreach(g_system->rstns, __rstn_tree_foreach_print, NULL);
1201 }
1202 #endif
1203 static stc_rstn_value_s * __rstn_lookup(GTree *rstns_tree,
1204                                         const stc_rstn_key_s *key)
1205 {
1206         stc_rstn_value_s *lookup;
1207
1208         ret_value_msg_if(rstns_tree == NULL, NULL, "rstns_tree is null!");
1209
1210         lookup = g_tree_lookup(rstns_tree, key);
1211
1212         return lookup;
1213 }
1214
1215 static gboolean __remove_restriction(gpointer key, gpointer value,
1216                                      gpointer data)
1217 {
1218         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1219         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1220
1221         /* rstn rule is already removed */
1222         if (rstn_value->rst_state == STC_RESTRICTION_REMOVED)
1223                 return FALSE;
1224
1225         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
1226         __print_rstn(rstn_key, rstn_value);
1227         return FALSE;
1228 }
1229
1230 static gboolean __add_restriction_debug(gpointer key, gpointer value,
1231                                         gpointer data)
1232 {
1233         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1234         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1235
1236         /* rstn rule is activated */
1237         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1238                 return FALSE;
1239
1240         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1241                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1242         else
1243                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1244
1245         __print_rstn(rstn_key, rstn_value);
1246
1247         return FALSE;
1248 }
1249
1250 static gboolean __add_restriction(gpointer key, gpointer value, gpointer data)
1251 {
1252         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1253         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1254
1255         /* rstn rule is activated */
1256         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1257                 return FALSE;
1258
1259         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1260                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1261         else
1262                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1263
1264         return FALSE;
1265 }
1266
1267 static stc_error_e __rstn_tree_remove(stc_rstn_key_s *key)
1268 {
1269         stc_rstn_value_s *lookup_value;
1270
1271         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1272
1273         lookup_value = __rstn_lookup(g_system->rstns, key);
1274         if (!lookup_value) {
1275                 STC_LOGE("key not found");
1276                 return STC_ERROR_NO_DATA;
1277         }
1278
1279         __remove_restriction(key, lookup_value, NULL);
1280
1281         /* remove counter also */
1282         table_counters_delete(lookup_value->restriction_id);
1283
1284         if (!g_tree_remove(g_system->rstns, key)) {
1285                 STC_LOGD("key not found");
1286                 return STC_ERROR_NO_DATA;
1287         }
1288
1289         return STC_ERROR_NONE;
1290 }
1291
1292 static stc_error_e __rstn_tree_add(stc_rstn_key_s *key,
1293                                    stc_rstn_value_s *value, gboolean debug)
1294 {
1295         stc_rstn_value_s *rstn_value;
1296
1297         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1298
1299         rstn_value = __rstn_lookup(g_system->rstns, key);
1300         if (!rstn_value) {
1301                 stc_rstn_key_s *rstn_key = MALLOC0(stc_rstn_key_s, 1);
1302                 if (!rstn_key) {
1303                         STC_LOGE("rstn_key allocation failed");
1304                         return STC_ERROR_OUT_OF_MEMORY;
1305                 }
1306
1307                 rstn_value = MALLOC0(stc_rstn_value_s, 1);
1308                 if (!rstn_value) {
1309                         STC_LOGE("rstn_value allocation failed");
1310                         FREE(rstn_key);
1311                         return STC_ERROR_OUT_OF_MEMORY;
1312                 }
1313
1314                 rstn_key->app_id = g_strdup(key->app_id);
1315                 rstn_key->ifname = g_strdup(key->ifname);
1316                 rstn_key->subscriber_id = g_strdup(key->subscriber_id);
1317                 rstn_key->iftype = key->iftype;
1318                 rstn_key->roaming = key->roaming;
1319
1320                 g_tree_insert(g_system->rstns, rstn_key, rstn_value);
1321         }
1322
1323         rstn_value->restriction_id = value->restriction_id;
1324         rstn_value->rst_state = value->rst_state;
1325         rstn_value->classid = value->classid;
1326         rstn_value->data_limit = value->data_limit;
1327         rstn_value->data_warn_limit = value->data_warn_limit;
1328         rstn_value->data_counter = 0;
1329         rstn_value->warn_limit_crossed_notified = FALSE;
1330         rstn_value->rstn_limit_crossed_notified = FALSE;
1331
1332         if (debug == TRUE)
1333                 __add_restriction_debug(key, rstn_value, NULL);
1334         else
1335                 __add_restriction(key, rstn_value, NULL);
1336
1337         return STC_ERROR_NONE;
1338 }
1339
1340 static stc_cb_ret_e __insert_restriction_cb(const table_restrictions_info *info,
1341                                             void *user_data)
1342 {
1343         stc_cb_ret_e ret = STC_CONTINUE;
1344
1345         stc_rstn_key_s key;
1346         stc_rstn_value_s value;
1347
1348         memset(&key, 0, sizeof(stc_rstn_key_s));
1349         memset(&value, 0, sizeof(stc_rstn_value_s));
1350
1351         key.app_id = g_strdup(info->app_id);
1352         key.ifname = g_strdup(info->ifname);
1353         key.subscriber_id = g_strdup(info->subscriber_id);
1354         key.iftype = info->iftype;
1355         key.roaming = info->roaming;
1356
1357         value.rst_state = info->rst_state;
1358         value.restriction_id = info->restriction_id;
1359
1360         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1361                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1362         else
1363                 value.classid = STC_UNKNOWN_CLASSID;
1364
1365         value.data_limit = info->data_limit;
1366         value.data_warn_limit = info->data_warn_limit;
1367
1368         if (__rstn_tree_add(&key, &value, FALSE) != STC_ERROR_NONE)
1369                 ret = STC_CANCEL;
1370
1371         FREE(key.app_id);
1372         FREE(key.ifname);
1373         FREE(key.subscriber_id);
1374         return ret;
1375 }
1376
1377 static void __fill_restritions_list(void)
1378 {
1379         table_restrictions_foreach(__insert_restriction_cb, NULL);
1380         //__rstn_tree_printall();
1381 }
1382
1383 static gboolean __add_rstn_foreach_application(gpointer key,
1384                                                gpointer value,
1385                                                gpointer data)
1386 {
1387         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1388         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1389         gchar *app_id = (gchar *)data;
1390
1391         /* rstn rule is not for applications */
1392         if (rstn_key->app_id == NULL)
1393                 goto out;
1394
1395         /* rstn rule is not for this application */
1396         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
1397                 goto out;
1398
1399         /* rstn rule is already applied */
1400         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1401                 goto out;
1402
1403         /* add restriction to system */
1404         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1405                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1406         else
1407                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1408
1409         __print_rstn(rstn_key, rstn_value);
1410 out:
1411         return FALSE;
1412 }
1413
1414 static void __add_rstns_for_application(gchar *app_id)
1415 {
1416         g_tree_foreach(g_system->rstns, __add_rstn_foreach_application,
1417                        app_id);
1418 }
1419
1420 static void __add_application_by_interface(const char *app_id)
1421 {
1422         stc_app_key_s app_key;
1423         stc_app_value_s app_value;
1424
1425         if (app_id == NULL)
1426                 return;
1427
1428         memset(&app_key, 0, sizeof(stc_app_key_s));
1429         memset(&app_value, 0, sizeof(stc_app_value_s));
1430
1431         app_key.pkg_id = g_strdup(app_id);
1432         app_key.app_id = g_strdup(app_id);
1433
1434         app_value.type = STC_APP_TYPE_NONE;
1435         app_value.processes = NULL;
1436         app_value.counter.in_bytes = 0;
1437         app_value.counter.out_bytes = 0;
1438
1439         stc_monitor_application_add(app_key, app_value);
1440
1441         FREE(app_key.pkg_id);
1442         FREE(app_key.app_id);
1443 }
1444
1445 static int __vconf_get_int(const char *key, int *value)
1446 {
1447         int ret = 0;
1448
1449         ret = vconf_get_int(key, value);
1450         if (ret != VCONF_OK) {
1451                 STC_LOGE("Failed to get vconfkey [%s] value", key);
1452                 return -1;
1453         }
1454
1455         return 0;
1456 }
1457
1458 static int __vconf_set_int(const char *key, int value)
1459 {
1460         int ret = 0;
1461
1462         ret = vconf_set_int(key, value);
1463         if (ret != VCONF_OK) {
1464                 STC_LOGE("Failed to set vconfkey [%s] value", key);
1465                 return -1;
1466         }
1467
1468         return 0;
1469 }
1470
1471 static guint __get_background_state(void)
1472 {
1473         return g_system->background_state;;
1474 }
1475
1476 static void __set_background_state(guint state)
1477 {
1478         g_system->background_state = state;
1479 }
1480
1481 static gboolean __processes_tree_foreach_background(gpointer key,
1482                                                     gpointer value,
1483                                                     gpointer data)
1484 {
1485         stc_process_key_s *proc_key = (stc_process_key_s *)key;
1486         stc_app_key_s *app_key = (stc_app_key_s *)data;
1487
1488         if (g_system->background_state)
1489                 place_pids_to_net_cgroup(proc_key->pid, STC_BACKGROUND_APP_ID);
1490         else
1491                 place_pids_to_net_cgroup(proc_key->pid, app_key->app_id);
1492
1493         return FALSE;
1494 }
1495
1496 static gboolean __apps_tree_foreach_background(gpointer key, gpointer value,
1497                                         gpointer data)
1498 {
1499         stc_app_key_s *app_key = (stc_app_key_s *)key;
1500         stc_app_value_s *app_value = (stc_app_value_s *)value;
1501
1502         if (strstr(app_key->app_id, STC_BACKGROUND_APP_SUFFIX))
1503                 g_tree_foreach(app_value->processes,
1504                                __processes_tree_foreach_background, app_key);
1505
1506         return FALSE;
1507 }
1508
1509 static stc_error_e __process_update_background(void)
1510 {
1511         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1512
1513         g_tree_foreach(g_system->apps, __apps_tree_foreach_background, NULL);
1514
1515         return STC_ERROR_NONE;
1516 }
1517
1518 #if 0
1519 static void __excn_hash_foreach_print(gpointer key, gpointer value,
1520                                           gpointer data)
1521 {
1522         const char *process_name = key;
1523         const char *exe_type = value;
1524
1525         STC_LOGI("excn info => process_name [%s] exe_type [%s]",
1526                 process_name, exe_type);
1527 }
1528
1529 static void __excn_hash_printall(void)
1530 {
1531         g_hash_table_foreach(g_system->excns_hash,
1532                 __excn_hash_foreach_print, NULL);
1533 }
1534 #endif
1535
1536 static gboolean __remove_exception_app(gpointer key, gpointer value,
1537                                         gpointer data)
1538 {
1539         const char *exe_type = value;
1540
1541         if (g_strcmp0(exe_type, EXE_TYPE_APPLICATION) == 0)
1542                 return TRUE;
1543
1544         return FALSE;
1545 }
1546
1547 static void __remove_exception_appall(void)
1548 {
1549         g_hash_table_foreach_remove(g_system->excns_hash,
1550                 __remove_exception_app, NULL);
1551 }
1552
1553 static stc_cb_ret_e __insert_exception_cb(const stc_exceptions_info *info,
1554                                             void *user_data)
1555 {
1556         stc_cb_ret_e ret = STC_CONTINUE;
1557
1558         if (g_hash_table_insert(g_system->excns_hash,
1559                         g_strdup(info->process_name),
1560                         g_strdup(info->exe_type)) != TRUE)
1561                 ret = STC_CANCEL;
1562
1563         return ret;
1564 }
1565
1566 static void __fill_exceptions_list(void)
1567 {
1568         table_exceptions_foreach(__insert_exception_cb, NULL);
1569         pkginfo_exceptions_foreach(__insert_exception_cb, NULL);
1570
1571         /* __excn_hash_printall(); */
1572 }
1573
1574 static gboolean __update_exceptions_app_list(void *user_data)
1575 {
1576         __remove_exception_appall();
1577         pkginfo_exceptions_foreach(__insert_exception_cb, NULL);
1578
1579         /* __excn_hash_printall(); */
1580
1581         return TRUE;
1582 }
1583
1584 stc_error_e stc_monitor_init(void)
1585 {
1586         stc_system_s *system = MALLOC0(stc_system_s, 1);
1587         GIOChannel *gio = NULL;
1588
1589         ret_value_msg_if(system == NULL, STC_ERROR_OUT_OF_MEMORY, "stc_system_s malloc fail!");
1590
1591         /* initializing current classid */
1592         init_current_classid();
1593
1594         /* initializing cgroups */
1595         cgroup_init();
1596
1597         /* creating monitored application tree */
1598         system->apps = g_tree_new_full(__apps_tree_key_compare, NULL,
1599                                        __apps_tree_key_free,
1600                                        __apps_tree_value_free);
1601
1602         system->rstns = g_tree_new_full(__rstns_tree_key_compare, NULL,
1603                                         __rstns_tree_key_free,
1604                                         __rstns_tree_value_free);
1605
1606         system->excns_hash = g_hash_table_new_full(g_str_hash,
1607                                         g_str_equal, g_free, g_free);
1608
1609         /* create netlink socket for updating kernel counters */
1610         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
1611         if (system->contr_sock < 0) {
1612                 STC_LOGE("failed to open socket");
1613                 FREE(system);
1614                 return STC_ERROR_FAIL;
1615         }
1616
1617         gio = g_io_channel_unix_new(system->contr_sock);
1618         system->contr_gsource_id =
1619                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
1620                                (GIOFunc) __process_contr_reply,
1621                                NULL);
1622         g_io_channel_unref(gio);
1623
1624         g_system = system;
1625
1626         __add_application_by_interface(STC_TOTAL_DATACALL);
1627         __add_application_by_interface(STC_TOTAL_WIFI);
1628         __add_application_by_interface(STC_TOTAL_BLUETOOTH);
1629         __add_application_by_interface(STC_TOTAL_IPV4);
1630         __add_application_by_interface(STC_TOTAL_IPV6);
1631
1632         /* creating restriction rules tree */
1633         __update_contr_cb(NULL);
1634
1635         /* registering periodic kernel counters update callback */
1636         g_system->contr_timer_id = g_timeout_add_seconds(CONTR_TIMER_INTERVAL,
1637                                                          __update_contr_cb,
1638                                                          NULL);
1639         if (g_system->contr_timer_id == 0) {
1640                 STC_LOGE("Failed to register kernel counters update timer");
1641                 __close_contr_sock(g_system);
1642                 return STC_ERROR_FAIL;
1643         }
1644
1645         __vconf_get_int(VCONFKEY_STC_BACKGROUND_STATE,
1646                         (int *)&g_system->background_state);
1647
1648         __fill_exceptions_list();
1649         __fill_restritions_list();
1650
1651         g_system->excns_timer_id = g_timeout_add_seconds(EXCNS_TIMER_INTERVAL,
1652                                                          __update_exceptions_app_list,
1653                                                          NULL);
1654
1655         return STC_ERROR_NONE;
1656 }
1657
1658 stc_error_e stc_monitor_deinit(void)
1659 {
1660         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1661
1662         /* close netlink socket for updating kernel counters */
1663         __close_contr_sock(g_system);
1664
1665         /* remove kernel counters update timer */
1666         if (g_system->contr_timer_id > 0) {
1667                 g_source_remove(g_system->contr_timer_id);
1668                 g_system->contr_timer_id = 0;
1669         }
1670
1671         /* remove exceptions app list update timer */
1672         if (g_system->excns_timer_id > 0) {
1673                 g_source_remove(g_system->excns_timer_id);
1674                 g_system->excns_timer_id = 0;
1675         }
1676
1677         /* destroy monitored application tree */
1678         g_tree_destroy(g_system->apps);
1679         g_system->apps = NULL;
1680
1681         /* destroy restriction rules tree */
1682         g_tree_destroy(g_system->rstns);
1683         g_system->rstns = NULL;
1684
1685         /* destroy exception hash table */
1686         g_hash_table_destroy(g_system->excns_hash);
1687         g_system->excns_hash = NULL;
1688
1689         FREE(g_system);
1690
1691         return STC_ERROR_NONE;
1692 }
1693
1694 stc_error_e stc_monitor_application_add(const stc_app_key_s app_key,
1695                                         const stc_app_value_s app_value)
1696 {
1697         stc_error_e ret = STC_ERROR_NONE;
1698         stc_app_key_s *key;
1699         stc_app_value_s *value;
1700         stc_app_value_s *lookup;
1701
1702         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1703
1704         lookup = __application_lookup(g_system->apps, &app_key);
1705         if (lookup) {
1706                 STC_LOGD("app_key already present");
1707                 return STC_ERROR_NONE;
1708         }
1709
1710         key = MALLOC0(stc_app_key_s, 1);
1711         if (!key) {
1712                 STC_LOGE("key allocation failed");
1713                 return STC_ERROR_OUT_OF_MEMORY;
1714         }
1715
1716         value = MALLOC0(stc_app_value_s, 1);
1717         if (!value) {
1718                 STC_LOGE("value allocation failed");
1719                 FREE(key);
1720                 return STC_ERROR_OUT_OF_MEMORY;
1721         }
1722
1723         key->app_id = g_strdup(app_key.app_id);
1724         key->pkg_id = g_strdup(app_key.pkg_id);
1725
1726         value->type = app_value.type;
1727         value->data_usage.in_bytes = app_value.data_usage.in_bytes;
1728         value->data_usage.out_bytes = app_value.data_usage.out_bytes;
1729
1730         value->processes = g_tree_new_full(__processes_tree_key_compare, NULL,
1731                                            __processes_tree_key_free,
1732                                            __processes_tree_value_free);
1733
1734         /* create cgroup and update classid */
1735         value->classid = get_classid_by_app_id(app_key.app_id, TRUE);
1736
1737         g_tree_insert(g_system->apps, key, value);
1738
1739         /* add nfacct rule for this classid */
1740         __add_application_monitor(key, value, stc_get_default_connection());
1741         __add_rstns_for_application(app_key.app_id);
1742
1743         return ret;
1744 }
1745
1746 stc_error_e stc_monitor_process_add(const stc_app_key_s app_key,
1747                                     const stc_process_key_s proc_key,
1748                                     const stc_process_value_s proc_value)
1749 {
1750         stc_error_e ret = STC_ERROR_NONE;
1751         stc_app_value_s *app_lookup;
1752         stc_process_key_s *key;
1753         stc_process_value_s *value;
1754         stc_process_value_s *proc_lookup;
1755
1756         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1757
1758         app_lookup = __application_lookup(g_system->apps, &app_key);
1759         if (!app_lookup) {
1760                 STC_LOGD("app_key not found");
1761                 return STC_ERROR_FAIL;
1762         }
1763
1764         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1765         if (proc_lookup) {
1766                 STC_LOGD("proc_key already present");
1767                 return STC_ERROR_NONE;
1768         }
1769
1770         key = MALLOC0(stc_process_key_s, 1);
1771         if (!key) {
1772                 STC_LOGE("key allocation failed");
1773                 return STC_ERROR_OUT_OF_MEMORY;
1774         }
1775
1776         value = MALLOC0(stc_process_value_s, 1);
1777         if (!value) {
1778                 STC_LOGE("value allocation failed");
1779                 FREE(key);
1780                 return STC_ERROR_OUT_OF_MEMORY;
1781         }
1782
1783         key->pid = proc_key.pid;
1784
1785         value->ground = proc_value.ground;
1786
1787         g_tree_insert(app_lookup->processes, key, value);
1788
1789         /* add pid to application cgroup */
1790         place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1791
1792         if (STC_DEBUG_LOG)
1793                 __apps_tree_printall();
1794
1795         return ret;
1796 }
1797
1798 stc_error_e stc_monitor_process_remove(pid_t pid)
1799 {
1800         stc_error_e ret = STC_ERROR_NONE;
1801         stc_process_key_s proc_key = {
1802                 .pid = pid
1803         };
1804
1805         remove_pid_context_s context = {
1806                 .app_key = NULL,
1807                 .proc_key = &proc_key,
1808                 .entry_removed = FALSE,
1809         };
1810
1811         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1812
1813         g_tree_foreach(g_system->apps, __apps_tree_foreach_remove_pid,
1814                        &context);
1815
1816         if (context.entry_removed)
1817                 __application_remove_if_empty(context.app_key);
1818
1819         if (STC_DEBUG_LOG)
1820                 __apps_tree_printall();
1821
1822         return ret;
1823 }
1824
1825 stc_error_e stc_monitor_process_update_ground(const stc_app_key_s app_key,
1826                                               const stc_process_key_s proc_key,
1827                                               stc_app_state_e ground)
1828 {
1829         stc_error_e ret = STC_ERROR_NONE;
1830         stc_app_value_s *app_lookup;
1831         stc_process_value_s *proc_lookup;
1832
1833         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1834
1835         app_lookup = __application_lookup(g_system->apps, &app_key);
1836         if (!app_lookup) {
1837                 STC_LOGD("app_key not found");
1838                 return STC_ERROR_FAIL;
1839         }
1840
1841         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1842         if (!proc_lookup) {
1843                 STC_LOGD("proc_key not found");
1844                 return STC_ERROR_FAIL;
1845         }
1846
1847         if (proc_lookup->ground != ground)
1848                 proc_lookup->ground = ground;
1849
1850         if (ground == STC_APP_STATE_BACKGROUND && __get_background_state())
1851                 place_pids_to_net_cgroup(proc_key.pid, STC_BACKGROUND_APP_ID);
1852         else
1853                 place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1854
1855         return ret;
1856 }
1857
1858 void stc_monitor_update_rstn_by_default_connection(void *data)
1859 {
1860         static default_connection_s old_connection;
1861         default_connection_s *new_connection = (default_connection_s *)data;
1862
1863         if (old_connection.path != NULL) {
1864                 if (g_system->apps)
1865                         g_tree_foreach(g_system->apps,
1866                                        __remove_application_monitor,
1867                                        (gpointer)&old_connection);
1868
1869                 if (g_system->rstns)
1870                         g_tree_foreach(g_system->rstns,
1871                                        __remove_restriction,
1872                                        (gpointer)&old_connection);
1873         }
1874
1875         FREE(old_connection.path);
1876         FREE(old_connection.ifname);
1877         old_connection.type = 0;
1878         old_connection.roaming = 0;
1879
1880         if (new_connection != NULL && new_connection->path != NULL) {
1881                 if (g_system->apps)
1882                         g_tree_foreach(g_system->apps,
1883                                        __add_application_monitor,
1884                                        (gpointer)new_connection);
1885
1886                 if (g_system->rstns)
1887                         g_tree_foreach(g_system->rstns, __add_restriction,
1888                                        NULL);
1889
1890                 old_connection.path = g_strdup(new_connection->path);
1891                 old_connection.ifname = g_strdup(new_connection->ifname);
1892                 old_connection.type = new_connection->type;
1893                 old_connection.roaming = new_connection->roaming;
1894         }
1895 }
1896
1897 stc_error_e stc_monitor_rstns_tree_add(const table_restrictions_info *info)
1898 {
1899         stc_error_e ret;
1900
1901         stc_rstn_key_s key;
1902         stc_rstn_value_s value;
1903
1904         memset(&key, 0, sizeof(stc_rstn_key_s));
1905         memset(&value, 0, sizeof(stc_rstn_value_s));
1906
1907         key.app_id = g_strdup(info->app_id);
1908         key.ifname = g_strdup(info->ifname);
1909         key.subscriber_id = g_strdup(info->subscriber_id);
1910         key.iftype = info->iftype;
1911         key.roaming = info->roaming;
1912
1913         value.rst_state = info->rst_state;
1914         value.restriction_id = info->restriction_id;
1915
1916         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1917                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1918         else
1919                 value.classid = STC_UNKNOWN_CLASSID;
1920
1921         if (value.classid == STC_BACKGROUND_APP_CLASSID) {
1922                 __set_background_state(TRUE);
1923                 __vconf_set_int(VCONFKEY_STC_BACKGROUND_STATE, g_system->background_state);
1924                 __process_update_background();
1925         }
1926
1927         value.data_limit = info->data_limit;
1928         value.data_warn_limit = info->data_warn_limit;
1929
1930         ret = __rstn_tree_add(&key, &value, TRUE);
1931
1932         FREE(key.app_id);
1933         FREE(key.ifname);
1934         FREE(key.subscriber_id);
1935         return ret;
1936 }
1937
1938 stc_error_e stc_monitor_rstns_tree_remove(const table_restrictions_info *info)
1939 {
1940         stc_error_e ret;
1941
1942         stc_rstn_key_s key = {
1943                 .app_id = g_strdup(info->app_id),
1944                 .ifname = g_strdup(info->ifname),
1945                 .subscriber_id = g_strdup(info->subscriber_id),
1946                 .iftype = info->iftype,
1947                 .roaming = info->roaming,
1948         };
1949
1950         if (!strcmp(key.app_id, STC_BACKGROUND_APP_ID)) {
1951                 __set_background_state(FALSE);
1952                 __vconf_set_int(VCONFKEY_STC_BACKGROUND_STATE, g_system->background_state);
1953                 __process_update_background();
1954         }
1955
1956         ret = __rstn_tree_remove(&key);
1957
1958         FREE(key.app_id);
1959         FREE(key.ifname);
1960         FREE(key.subscriber_id);
1961         return ret;
1962 }
1963
1964 stc_error_e stc_monitor_check_excn_by_cmdline(char *cmdline)
1965 {
1966         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1967
1968         char *exe_type = NULL;
1969
1970         exe_type = g_hash_table_lookup(g_system->excns_hash, cmdline);
1971         if (!exe_type)
1972                 return STC_ERROR_NO_DATA;
1973
1974         return STC_ERROR_NONE;
1975 }
1976
1977 int stc_monitor_get_counter_socket(void)
1978 {
1979         return g_system->contr_sock;
1980 }