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