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