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