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