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