Merge "Added logic to monitor and restrict data usage per interface" into tizen
[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 (system->contr_sock != -1) {
551                 close(system->contr_sock);
552                 system->contr_sock = -1;
553         }
554
555         if (system->contr_gsource_id != 0) {
556                 g_source_remove(system->contr_gsource_id);
557                 system->contr_gsource_id = 0;
558         }
559
560         return STC_ERROR_NONE;
561 }
562
563 static gboolean __process_contr_reply(GIOChannel *source,
564                                       GIOCondition condition,
565                                       gpointer user_data);
566
567 static stc_error_e __close_and_reopen_contr_sock(stc_system_s *system)
568 {
569         GIOChannel *gio = NULL;
570         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
571
572         /* close netlink socket for updating kernel counters */
573         if (system->contr_sock != -1) {
574                 close(system->contr_sock);
575                 system->contr_sock = -1;
576         }
577
578         if (system->contr_gsource_id != 0) {
579                 g_source_remove(system->contr_gsource_id);
580                 system->contr_gsource_id = 0;
581         }
582
583         /* create netlink socket for updating kernel counters */
584         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
585         if (!(system->contr_sock)) {
586                 STC_LOGE("failed to open socket");
587                 FREE(system);
588                 return STC_ERROR_FAIL;
589         }
590
591         gio = g_io_channel_unix_new(system->contr_sock);
592         system->contr_gsource_id =
593                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
594                                (GIOFunc) __process_contr_reply,
595                                NULL);
596         g_io_channel_unref(gio);
597
598         return STC_ERROR_NONE;
599 }
600
601 static gboolean __rstn_counter_update(stc_rstn_key_s *rstn_key,
602                                                       stc_rstn_value_s *rstn_value,
603                                                       classid_bytes_context_s *context)
604 {
605         switch (context->counter->iotype) {
606         case NFACCT_COUNTER_IN:
607         case NFACCT_COUNTER_OUT:
608                 rstn_value->data_counter += context->bytes;
609
610                 if (rstn_value->data_counter >= rstn_value->data_warn_limit &&
611                     rstn_value->warn_limit_crossed_notified == FALSE) {
612
613                         gboolean rv = FALSE;
614                         char iftype[MAX_INT_LENGTH];
615                         char byte[MAX_INT_LENGTH];
616                         stc_s *stc = (stc_s *)stc_get_manager();
617                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
618
619                         /* emit signal */
620                         rv = stc_manager_dbus_emit_signal(stc->connection,
621                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
622                                                           STC_DBUS_INTERFACE_RESTRICTION,
623                                                           "WarnThresholdCrossed",
624                                                           g_variant_new("(si)", rstn_key->app_id, rstn_key->iftype));
625                         if (rv == TRUE)
626                                 rstn_value->warn_limit_crossed_notified = TRUE;
627
628                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
629                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_warn_limit);
630                         stc_send_warn_message_to_net_popup("warn threshold crossed",
631                                                            "warning_noti",
632                                                            rstn_key->app_id,
633                                                            iftype, byte);
634                 }
635
636                 if (rstn_value->data_counter >= rstn_value->data_limit &&
637                     rstn_value->rstn_limit_crossed_notified == FALSE) {
638
639                         gboolean rv = FALSE;
640                         char iftype[MAX_INT_LENGTH];
641                         char byte[MAX_INT_LENGTH];
642                         stc_s *stc = (stc_s *)stc_get_manager();
643                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
644
645                         /* block immediately */
646                         context->counter->intend = NFACCT_BLOCK;
647                         __del_iptables_in(context->counter);
648                         __del_iptables_out(context->counter);
649                         __add_iptables_in(context->counter);
650                         __add_iptables_out(context->counter);
651                         context->counter->intend = NFACCT_COUNTER;
652
653                         rstn_value->data_limit_reached = TRUE;
654
655                         /* emit signal */
656                         rv = stc_manager_dbus_emit_signal(stc->connection,
657                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
658                                                           STC_DBUS_INTERFACE_RESTRICTION,
659                                                           "RestrictionThresholdCrossed",
660                                                           g_variant_new("(si)", rstn_key->app_id, rstn_key->iftype));
661                         if (rv == TRUE)
662                                 rstn_value->rstn_limit_crossed_notified = TRUE;
663
664                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
665                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_limit);
666                         stc_send_restriction_message_to_net_popup("restriction threshold crossed",
667                                                                   "restriction_noti", rstn_key->app_id,
668                                                                   iftype, byte);
669                 }
670
671                 g_system->rstns_tree_updated = TRUE;
672                 __print_rstn(rstn_key, rstn_value);
673                 break;
674         default:
675                 STC_LOGE("unknown iotype");
676         }
677
678         return FALSE;
679 }
680
681 static gboolean __interface_rstn_counter_update(stc_rstn_key_s *rstn_key,
682                                                       stc_rstn_value_s *rstn_value,
683                                                       classid_bytes_context_s *context)
684 {
685         if ((rstn_value->classid == STC_TOTAL_DATACALL_CLASSID &&
686                 context->counter->iftype == STC_IFACE_DATACALL) ||
687                 (rstn_value->classid == STC_TOTAL_WIFI_CLASSID &&
688                 context->counter->iftype == STC_IFACE_WIFI) ||
689                 (rstn_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
690                 context->counter->iftype == STC_IFACE_BLUETOOTH)) {
691                 context->counter->classid = rstn_value->classid;
692                 return __rstn_counter_update(rstn_key, rstn_value, context);
693         }
694
695         return FALSE;
696 }
697
698 static gboolean __rstn_counter_update_foreach_classid(gpointer key,
699                                                       gpointer value,
700                                                       gpointer data)
701 {
702         gboolean rv = FALSE;
703         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
704         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
705         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
706         uint32_t classid;
707
708         if (context->counter->intend != NFACCT_COUNTER)
709                 goto try_next_callback;
710
711         if (rstn_value->data_limit_reached == TRUE) {
712                 context->data_limit_reached = TRUE;
713                 goto try_next_callback;
714         }
715
716         classid = context->counter->classid;
717         rv = __interface_rstn_counter_update(rstn_key, rstn_value, context);
718
719         context->counter->classid = classid;
720         if (rstn_value->classid != context->counter->classid)
721                 goto try_next_callback;
722
723         rv = __rstn_counter_update(rstn_key, rstn_value, context);
724
725 try_next_callback:
726         return rv;
727 }
728
729 static gboolean __update_app_statistics(gpointer key, gpointer value,
730                                         gpointer data)
731 {
732         stc_app_key_s *app_key = (stc_app_key_s *)key;
733         stc_app_value_s *app_value = (stc_app_value_s *)value;
734         time_t *touch_time = (time_t *)data;
735         stc_db_classid_iftype_key stat_key;
736         stc_db_app_stats stat;
737         char *default_ifname = stc_default_connection_get_ifname();
738
739         memset(&stat_key, 0, sizeof(stc_db_classid_iftype_key));
740         memset(&stat, 0 , sizeof(stc_db_app_stats));
741
742         stat_key.classid = app_value->classid;
743         stat_key.iftype = stc_default_connection_get_type();
744         if (STC_IFACE_DATACALL == stat_key.iftype)
745                 stat_key.imsi = g_strdup("unknown");
746         else
747                 stat_key.imsi = g_strdup("noneimsi");
748         g_strlcpy(stat_key.ifname, default_ifname, MAX_IFACE_LENGTH);
749
750         stat.app_id = g_strdup(app_key->app_id);
751         stat.snd_count = app_value->counter.out_bytes;
752         stat.rcv_count = app_value->counter.in_bytes;
753         stat.is_roaming = stc_default_connection_get_roaming();
754         stat.ground = STC_APP_STATE_UNKNOWN;
755
756         table_statistics_insert(&stat_key, &stat, *touch_time);
757
758         app_value->counter.out_bytes = 0;
759         app_value->counter.in_bytes = 0;
760
761         FREE(stat.app_id);
762         FREE(stat_key.imsi);
763         FREE(default_ifname);
764
765         return FALSE;
766 }
767
768 static gboolean __flush_apps_stats_to_database(gpointer user_data)
769 {
770         time_t current_time = time(0);
771
772         if (g_system->apps_tree_updated == FALSE)
773                 return G_SOURCE_REMOVE;
774
775         g_system->apps_tree_updated = FALSE;
776
777         if (g_system->apps)
778                 g_tree_foreach(g_system->apps,
779                                __update_app_statistics,
780                                &current_time);
781
782         STC_LOGI("Flushed app stats to database");
783         return G_SOURCE_REMOVE;
784 }
785
786 static gboolean __update_counter_statistics(gpointer key, gpointer value,
787                                             gpointer data)
788 {
789         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
790         table_counters_info info = {
791                 .restriction_id = rstn_value->restriction_id,
792                 .data_counter = rstn_value->data_counter
793         };
794
795         table_counters_update_counters(&info);
796
797         return FALSE;
798 }
799
800 static gboolean __flush_rstns_counter_to_database(gpointer user_data)
801 {
802         time_t current_time = time(0);
803
804         if (g_system->rstns_tree_updated == FALSE)
805                 return G_SOURCE_REMOVE;
806
807         g_system->rstns_tree_updated = FALSE;
808
809         if (g_system->rstns)
810                 g_tree_foreach(g_system->rstns,
811                                __update_counter_statistics,
812                                &current_time);
813
814         STC_LOGI("Flushed rstns counters to database");
815         return G_SOURCE_REMOVE;
816 }
817
818 static void __app_counter_update(stc_app_key_s *app_key,
819                                                         stc_app_value_s *app_value,
820                                                         classid_bytes_context_s *context)
821 {
822         switch (context->counter->iotype) {
823         case NFACCT_COUNTER_IN:
824                 app_value->data_usage.in_bytes += context->bytes;
825                 app_value->counter.in_bytes = context->bytes;
826                 g_system->apps_tree_updated = TRUE;
827
828                 __apps_tree_foreach_print(app_key, app_value, NULL);
829                 break;
830         case NFACCT_COUNTER_OUT:
831                 app_value->data_usage.out_bytes += context->bytes;
832                 app_value->counter.out_bytes = context->bytes;
833                 g_system->apps_tree_updated = TRUE;
834
835                 __apps_tree_foreach_print(app_key, app_value, NULL);
836                 break;
837         default:
838                 STC_LOGE("unknown iotype");
839         }
840 }
841
842 static void __interface_counter_update(stc_app_key_s *app_key,
843                                                         stc_app_value_s *app_value,
844                                                         classid_bytes_context_s *context)
845 {
846         if ((app_value->classid == STC_TOTAL_DATACALL_CLASSID &&
847                 context->counter->iftype == STC_IFACE_DATACALL) ||
848                 (app_value->classid == STC_TOTAL_WIFI_CLASSID &&
849                 context->counter->iftype == STC_IFACE_WIFI) ||
850                 (app_value->classid == STC_TOTAL_BLUETOOTH_CLASSID &&
851                 context->counter->iftype == STC_IFACE_BLUETOOTH))
852                 __app_counter_update(app_key, app_value, context);
853 }
854
855 static gboolean __apps_counter_update_foreach_classid(gpointer key,
856                                                       gpointer value,
857                                                       gpointer data)
858 {
859         stc_app_key_s *app_key = (stc_app_key_s *)key;
860         stc_app_value_s *app_value = (stc_app_value_s *)value;
861         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
862
863         if (context->counter->intend != NFACCT_COUNTER)
864                 goto try_next_callback;
865
866         __interface_counter_update(app_key, app_value, context);
867
868         if (app_value->classid != context->counter->classid)
869                 goto try_next_callback;
870
871         __app_counter_update(app_key, app_value, context);
872
873 try_next_callback:
874         return FALSE;
875 }
876
877 static void __fill_nfacct_result(char *cnt_name, int64_t bytes,
878                                  struct counter_arg *carg)
879 {
880         struct nfacct_rule counter = {
881                 .carg = carg,
882                 .name = {0},
883                 .ifname = {0},
884                 0
885         };
886
887         classid_bytes_context_s context = {
888                 .counter = &counter,
889                 .bytes = bytes,
890                 .data_limit_reached = FALSE,
891         };
892
893         STC_LOGD("cnt_name %s", cnt_name);
894
895         if (!recreate_counter_by_name(cnt_name, &counter)) {
896                 STC_LOGE("Can't parse counter name %s", cnt_name);
897                 return;
898         }
899
900         STC_LOGI("classid %lu, iftype %u, iotype %d, intend %d, ifname %s, bytes %lld",
901                  context.counter->classid, context.counter->iftype,
902                  context.counter->iotype, context.counter->intend,
903                  context.counter->ifname, context.bytes);
904
905         if (g_system->rstns)
906                 g_tree_foreach(g_system->rstns,
907                                __rstn_counter_update_foreach_classid,
908                                &context);
909
910         if (g_system->apps)
911                 g_tree_foreach(g_system->apps,
912                                __apps_counter_update_foreach_classid,
913                                &context);
914 }
915
916 static int __fill_counters(struct rtattr *attr_list[__NFACCT_MAX],
917                            void *user_data)
918 {
919         struct counter_arg *carg = user_data;
920         char *cnt_name = (char *)RTA_DATA(attr_list[NFACCT_NAME]);
921         if (carg->initiate) {
922                 /**
923                  * TODO: this will be used when daemon starts to update existing
924                  * counter data if present.
925                  *
926                  populate_counters(cnt_name, carg);
927                  */
928         } else {
929                 int64_t *bytes_p =
930                         (int64_t *)RTA_DATA(attr_list[NFACCT_BYTES]);
931                 int bytes = be64toh(*bytes_p);
932                 if (bytes) {
933                         ++carg->serialized_counters;
934                         __fill_nfacct_result(cnt_name, bytes, carg);
935                 }
936         }
937
938         return 0;
939 }
940
941 static int __post_fill_counters(void *user_data)
942 {
943         struct counter_arg *carg = user_data;
944
945         if (carg->initiate)
946                 carg->initiate = 0;
947
948         return 0;
949 }
950
951 static void __process_network_counter(struct genl *ans,
952                                       struct counter_arg *carg)
953 {
954         struct netlink_serialization_params ser_params = {
955                 .carg = carg,
956                 .ans = ans,
957                 .eval_attr = __fill_counters,
958                 .post_eval_attr = __post_fill_counters,
959         };
960
961         netlink_serialization_command *netlink =
962                 netlink_create_command(&ser_params);
963         if (!netlink) {
964                 STC_LOGE("Can not create command");
965                 return;
966         }
967
968         netlink->deserialize_answer(&(netlink->params));
969 }
970
971 static gboolean __process_contr_reply(GIOChannel *source,
972                                       GIOCondition condition,
973                                       gpointer user_data)
974 {
975         int sock = g_io_channel_unix_get_fd(source);
976         struct genl ans;
977         int ret;
978         stc_s *stc = stc_get_manager();
979
980         if ((condition & G_IO_ERR) ||
981             (condition & G_IO_HUP) ||
982             (condition & G_IO_NVAL)) {
983                 /* G_IO_ERR/G_IO_HUP/G_IO_NVAL received */
984
985                 STC_LOGE("Counter socket received G_IO event, closing socket."
986                          "G_IO_ERR [%d], G_IO_HUP [%d], G_IO_NVAL [%s]",
987                          (condition & G_IO_ERR), (condition & G_IO_HUP),
988                          (condition & G_IO_NVAL));
989                 __close_and_reopen_contr_sock(g_system);
990                 return FALSE;
991         }
992
993         if (stc == NULL) {
994                 STC_LOGE("Can't get stc data");
995                 goto out;
996         }
997
998         ret = read_netlink(sock,
999                            &ans, sizeof(struct genl));
1000         /* STC_LOGD("Counter data received ret [%d]", ret); */
1001         if (ret == 0)
1002                 goto out;
1003
1004         stc->carg->ans_len = ret;
1005         __process_network_counter(&ans, stc->carg);
1006
1007         g_idle_add(__flush_apps_stats_to_database, NULL);
1008         g_idle_add(__flush_rstns_counter_to_database, NULL);
1009 out:
1010         return TRUE;
1011 }
1012
1013 static gboolean __update_contr_cb(void *user_data)
1014 {
1015         /* Here we just sent command, answer we receive in another callback */
1016         stc_s *stc = stc_get_manager();
1017         ret_value_msg_if(stc == NULL, STC_ERROR_FAIL, "Can't get stc data");
1018         if (!stc->carg) {
1019                 stc->carg = MALLOC0(counter_arg_s, 1);
1020                 stc->carg->sock = stc_monitor_get_counter_socket();
1021         }
1022
1023         /* STC_LOGD("Get all counters"); */
1024         nfacct_send_get_all(stc->carg);
1025
1026         /* we need to continue the timer */
1027         return TRUE;
1028 }
1029 #if 0
1030 static gboolean __rstn_tree_foreach_print(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         __print_rstn(rstn_key, rstn_value);
1037         return FALSE;
1038 }
1039
1040 static void __rstn_tree_printall(void)
1041 {
1042         g_tree_foreach(g_system->rstns, __rstn_tree_foreach_print, NULL);
1043 }
1044 #endif
1045 static stc_rstn_value_s * __rstn_lookup(GTree *rstns_tree,
1046                                         const stc_rstn_key_s *key)
1047 {
1048         stc_rstn_value_s *lookup;
1049
1050         ret_value_msg_if(rstns_tree == NULL, NULL, "rstns_tree is null!");
1051
1052         lookup = g_tree_lookup(rstns_tree, key);
1053
1054         return lookup;
1055 }
1056
1057 static gboolean __remove_restriction(gpointer key, gpointer value,
1058                                      gpointer data)
1059 {
1060         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1061         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1062
1063         /* rstn rule is already removed */
1064         if (rstn_value->rst_state == STC_RESTRICTION_REMOVED)
1065                 return FALSE;
1066
1067         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
1068         __print_rstn(rstn_key, rstn_value);
1069         return FALSE;
1070 }
1071
1072 static gboolean __add_restriction_debug(gpointer key, gpointer value,
1073                                         gpointer data)
1074 {
1075         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1076         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1077
1078         /* rstn rule is activated */
1079         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1080                 return FALSE;
1081
1082         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1083                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1084         else
1085                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1086
1087         __print_rstn(rstn_key, rstn_value);
1088
1089         return FALSE;
1090 }
1091
1092 static gboolean __add_restriction(gpointer key, gpointer value, gpointer data)
1093 {
1094         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1095         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1096
1097         /* rstn rule is activated */
1098         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1099                 return FALSE;
1100
1101         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1102                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1103         else
1104                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1105
1106         return FALSE;
1107 }
1108
1109 static stc_error_e __rstn_tree_remove(stc_rstn_key_s *key)
1110 {
1111         stc_rstn_value_s *lookup_value;
1112
1113         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1114
1115         lookup_value = __rstn_lookup(g_system->rstns, key);
1116         if (!lookup_value) {
1117                 STC_LOGE("key not found");
1118                 return STC_ERROR_NO_DATA;
1119         }
1120
1121         __remove_restriction(key, lookup_value, NULL);
1122
1123         /* remove counter also */
1124         table_counters_delete(lookup_value->restriction_id);
1125
1126         if (!g_tree_remove(g_system->rstns, key)) {
1127                 STC_LOGD("key not found");
1128                 return STC_ERROR_NO_DATA;
1129         }
1130
1131         return STC_ERROR_NONE;
1132 }
1133
1134 static stc_error_e __rstn_tree_add(stc_rstn_key_s *key,
1135                                    stc_rstn_value_s *value, gboolean debug)
1136 {
1137         stc_rstn_value_s *rstn_value;
1138
1139         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1140
1141         rstn_value = __rstn_lookup(g_system->rstns, key);
1142         if (!rstn_value) {
1143                 stc_rstn_key_s *rstn_key = MALLOC0(stc_rstn_key_s, 1);
1144                 if (!rstn_key) {
1145                         STC_LOGE("rstn_key allocation failed");
1146                         return STC_ERROR_OUT_OF_MEMORY;
1147                 }
1148
1149                 rstn_value = MALLOC0(stc_rstn_value_s, 1);
1150                 if (!rstn_value) {
1151                         STC_LOGE("rstn_value allocation failed");
1152                         FREE(rstn_key);
1153                         return STC_ERROR_OUT_OF_MEMORY;
1154                 }
1155
1156                 rstn_key->app_id = g_strdup(key->app_id);
1157                 rstn_key->ifname = g_strdup(key->ifname);
1158                 rstn_key->imsi = g_strdup(key->imsi);
1159                 rstn_key->iftype = key->iftype;
1160                 rstn_key->roaming = key->roaming;
1161
1162                 g_tree_insert(g_system->rstns, rstn_key, rstn_value);
1163         }
1164
1165         rstn_value->restriction_id = value->restriction_id;
1166         rstn_value->rst_state = value->rst_state;
1167         rstn_value->classid = value->classid;
1168         rstn_value->data_limit = value->data_limit;
1169         rstn_value->data_warn_limit = value->data_warn_limit;
1170         rstn_value->data_counter = 0;
1171         rstn_value->warn_limit_crossed_notified = FALSE;
1172         rstn_value->rstn_limit_crossed_notified = FALSE;
1173
1174         if (debug == TRUE)
1175                 __add_restriction_debug(key, rstn_value, NULL);
1176         else
1177                 __add_restriction(key, rstn_value, NULL);
1178
1179         return STC_ERROR_NONE;
1180 }
1181
1182 static stc_cb_ret_e __insert_restriction_cb(const table_restrictions_info *info,
1183                                             void *user_data)
1184 {
1185         stc_cb_ret_e ret = STC_CONTINUE;
1186
1187         stc_rstn_key_s key;
1188         stc_rstn_value_s value;
1189
1190         memset(&key, 0, sizeof(stc_rstn_key_s));
1191         memset(&value, 0, sizeof(stc_rstn_value_s));
1192
1193         key.app_id = g_strdup(info->app_id);
1194         key.ifname = g_strdup(info->ifname);
1195         key.imsi = g_strdup(info->imsi);
1196         key.iftype = info->iftype;
1197         key.roaming = info->roaming;
1198
1199         value.rst_state = info->rst_state;
1200         value.restriction_id = info->restriction_id;
1201
1202         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1203                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1204         else
1205                 value.classid = STC_UNKNOWN_CLASSID;
1206
1207         value.data_limit = info->data_limit;
1208         value.data_warn_limit = info->data_warn_limit;
1209
1210         if (__rstn_tree_add(&key, &value, FALSE) != STC_ERROR_NONE)
1211                 ret = STC_CANCEL;
1212
1213         FREE(key.app_id);
1214         FREE(key.ifname);
1215         FREE(key.imsi);
1216         return ret;
1217 }
1218
1219 static void __fill_restritions_list(void)
1220 {
1221         table_restrictions_foreach(__insert_restriction_cb, NULL);
1222         //__rstn_tree_printall();
1223 }
1224
1225 static gboolean __add_rstn_foreach_application(gpointer key,
1226                                                gpointer value,
1227                                                gpointer data)
1228 {
1229         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1230         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1231         gchar *app_id = (gchar *)data;
1232
1233         /* rstn rule is not for applications */
1234         if (rstn_key->app_id == NULL)
1235                 goto out;
1236
1237         /* rstn rule is not for this application */
1238         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
1239                 goto out;
1240
1241         /* rstn rule is already applied */
1242         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1243                 goto out;
1244
1245         /* add restriction to system */
1246         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1247                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1248         else
1249                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1250
1251         __print_rstn(rstn_key, rstn_value);
1252 out:
1253         return FALSE;
1254 }
1255
1256 static void __add_rstns_for_application(gchar *app_id)
1257 {
1258         g_tree_foreach(g_system->rstns, __add_rstn_foreach_application,
1259                        app_id);
1260 }
1261
1262 static void __stc_monitor_add_application_by_interface(const char *app_id)
1263 {
1264         stc_app_key_s app_key;
1265         stc_app_value_s app_value;
1266
1267         if (app_id == NULL)
1268                 return;
1269
1270         memset(&app_key, 0, sizeof(stc_app_key_s));
1271         memset(&app_value, 0, sizeof(stc_app_value_s));
1272
1273         app_key.pkg_id = g_strdup(app_id);
1274         app_key.app_id = g_strdup(app_id);
1275
1276         app_value.type = STC_APP_TYPE_NONE;
1277         app_value.processes = NULL;
1278         app_value.counter.in_bytes = 0;
1279         app_value.counter.out_bytes = 0;
1280
1281         stc_monitor_application_add(app_key, app_value);
1282
1283         FREE(app_key.pkg_id);
1284         FREE(app_key.app_id);
1285 }
1286
1287 stc_error_e stc_monitor_init(void)
1288 {
1289         stc_system_s *system = MALLOC0(stc_system_s, 1);
1290         GIOChannel *gio = NULL;
1291
1292         ret_value_msg_if(system == NULL, STC_ERROR_OUT_OF_MEMORY, "stc_system_s malloc fail!");
1293
1294         /* initializing cgroups */
1295         cgroup_init();
1296
1297         /* creating monitored application tree */
1298         system->apps = g_tree_new_full(__apps_tree_key_compare, NULL,
1299                                        __apps_tree_key_free,
1300                                        __apps_tree_value_free);
1301
1302         system->rstns = g_tree_new_full(__rstns_tree_key_compare, NULL,
1303                                         __rstns_tree_key_free,
1304                                         __rstns_tree_value_free);
1305
1306         /* create netlink socket for updating kernel counters */
1307         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
1308         if (!(system->contr_sock)) {
1309                 STC_LOGE("failed to open socket");
1310                 FREE(system);
1311                 return STC_ERROR_FAIL;
1312         }
1313
1314         gio = g_io_channel_unix_new(system->contr_sock);
1315         system->contr_gsource_id =
1316                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
1317                                (GIOFunc) __process_contr_reply,
1318                                NULL);
1319         g_io_channel_unref(gio);
1320
1321         g_system = system;
1322
1323         __stc_monitor_add_application_by_interface(STC_TOTAL_DATACALL);
1324         __stc_monitor_add_application_by_interface(STC_TOTAL_WIFI);
1325         __stc_monitor_add_application_by_interface(STC_TOTAL_BLUETOOTH);
1326
1327         /* creating restriction rules tree */
1328         __update_contr_cb(NULL);
1329
1330         /* registering periodic kernel counters update callback */
1331         g_system->contr_timer_id = g_timeout_add_seconds(CONTR_TIMER_INTERVAL,
1332                                                          __update_contr_cb,
1333                                                          NULL);
1334         if (g_system->contr_timer_id == 0) {
1335                 STC_LOGE("Failed to register kernel counters update timer");
1336                 __close_contr_sock(g_system);
1337                 return STC_ERROR_FAIL;
1338         }
1339
1340         __fill_restritions_list();
1341
1342         return STC_ERROR_NONE;
1343 }
1344
1345 stc_error_e stc_monitor_deinit(void)
1346 {
1347         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1348
1349         /* close netlink socket for updating kernel counters */
1350         __close_contr_sock(g_system);
1351
1352         /* remove kernel counters update timer */
1353         if (g_system->contr_timer_id > 0) {
1354                 g_source_remove(g_system->contr_timer_id);
1355                 g_system->contr_timer_id = 0;
1356         }
1357
1358         /* destroy monitored application tree */
1359         g_tree_destroy(g_system->apps);
1360         g_system->apps = NULL;
1361
1362         /* destroy restriction rules tree */
1363         g_tree_destroy(g_system->rstns);
1364         g_system->rstns = NULL;
1365
1366         FREE(g_system);
1367
1368         return STC_ERROR_NONE;
1369 }
1370
1371 stc_error_e stc_monitor_application_add(const stc_app_key_s app_key,
1372                                         const stc_app_value_s app_value)
1373 {
1374         stc_error_e ret = STC_ERROR_NONE;
1375         stc_app_key_s *key;
1376         stc_app_value_s *value;
1377         stc_app_value_s *lookup;
1378
1379         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1380
1381         lookup = __application_lookup(g_system->apps, &app_key);
1382         if (lookup) {
1383                 STC_LOGD("app_key already present");
1384                 return STC_ERROR_NONE;
1385         }
1386
1387         key = MALLOC0(stc_app_key_s, 1);
1388         if (!key) {
1389                 STC_LOGE("key allocation failed");
1390                 return STC_ERROR_OUT_OF_MEMORY;
1391         }
1392
1393         value = MALLOC0(stc_app_value_s, 1);
1394         if (!value) {
1395                 STC_LOGE("value allocation failed");
1396                 FREE(key);
1397                 return STC_ERROR_OUT_OF_MEMORY;
1398         }
1399
1400         key->app_id = g_strdup(app_key.app_id);
1401         key->pkg_id = g_strdup(app_key.pkg_id);
1402
1403         value->type = app_value.type;
1404         value->data_usage.in_bytes = app_value.data_usage.in_bytes;
1405         value->data_usage.out_bytes = app_value.data_usage.out_bytes;
1406
1407         value->processes = g_tree_new_full(__processes_tree_key_compare, NULL,
1408                                            __processes_tree_key_free,
1409                                            __processes_tree_value_free);
1410
1411         /* create cgroup and update classid */
1412         value->classid = get_classid_by_app_id(app_key.app_id, TRUE);
1413
1414         g_tree_insert(g_system->apps, key, value);
1415
1416         /* add nfacct rule for this classid */
1417         __add_application_monitor(key, value, stc_get_default_connection());
1418         __add_rstns_for_application(app_key.app_id);
1419
1420         return ret;
1421 }
1422
1423 stc_error_e stc_monitor_process_add(const stc_app_key_s app_key,
1424                                     const stc_process_key_s proc_key,
1425                                     const stc_process_value_s proc_value)
1426 {
1427         stc_error_e ret = STC_ERROR_NONE;
1428         stc_app_value_s *app_lookup;
1429         stc_process_key_s *key;
1430         stc_process_value_s *value;
1431         stc_process_value_s *proc_lookup;
1432
1433         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1434
1435         app_lookup = __application_lookup(g_system->apps, &app_key);
1436         if (!app_lookup) {
1437                 STC_LOGD("app_key not found");
1438                 return STC_ERROR_FAIL;
1439         }
1440
1441         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1442         if (proc_lookup) {
1443                 STC_LOGD("proc_key already present");
1444                 return STC_ERROR_NONE;
1445         }
1446
1447         key = MALLOC0(stc_process_key_s, 1);
1448         if (!key) {
1449                 STC_LOGE("key allocation failed");
1450                 return STC_ERROR_OUT_OF_MEMORY;
1451         }
1452
1453         value = MALLOC0(stc_process_value_s, 1);
1454         if (!value) {
1455                 STC_LOGE("value allocation failed");
1456                 FREE(key);
1457                 return STC_ERROR_OUT_OF_MEMORY;
1458         }
1459
1460         key->pid = proc_key.pid;
1461
1462         value->ground = proc_value.ground;
1463
1464         g_tree_insert(app_lookup->processes, key, value);
1465
1466         /* add pid to application cgroup */
1467         place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1468
1469         return ret;
1470 }
1471
1472 stc_error_e stc_monitor_process_remove(pid_t pid)
1473 {
1474         stc_error_e ret = STC_ERROR_NONE;
1475         stc_process_key_s proc_key = {
1476                 .pid = pid
1477         };
1478
1479         remove_pid_context_s context = {
1480                 .app_key = NULL,
1481                 .proc_key = &proc_key,
1482                 .entry_removed = FALSE,
1483         };
1484
1485         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1486
1487         g_tree_foreach(g_system->apps, __apps_tree_foreach_remove_pid,
1488                        &context);
1489
1490         if (context.entry_removed)
1491                 __application_remove_if_empty(context.app_key);
1492
1493         return ret;
1494 }
1495
1496 stc_error_e stc_monitor_process_update_ground(const stc_app_key_s app_key,
1497                                               const stc_process_key_s proc_key,
1498                                               stc_app_state_e ground)
1499 {
1500         stc_error_e ret = STC_ERROR_NONE;
1501         stc_app_value_s *app_lookup;
1502         stc_process_value_s *proc_lookup;
1503
1504         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1505
1506         app_lookup = __application_lookup(g_system->apps, &app_key);
1507         if (!app_lookup) {
1508                 STC_LOGD("app_key not found");
1509                 return STC_ERROR_FAIL;
1510         }
1511
1512         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1513         if (!proc_lookup) {
1514                 STC_LOGD("proc_key not found");
1515                 return STC_ERROR_FAIL;
1516         }
1517
1518         if (proc_lookup->ground != ground)
1519                 proc_lookup->ground = ground;
1520
1521         if (ground == STC_APP_STATE_BACKGROUND) {
1522                 char *background_app_id = g_strconcat(app_key.app_id,
1523                                                      STC_BACKGROUND_APP_SUFFIX,
1524                                                      NULL);
1525                 place_pids_to_net_cgroup(proc_key.pid, background_app_id);
1526                 g_free(background_app_id);
1527         } else {
1528                 place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1529         }
1530
1531         return ret;
1532 }
1533
1534 void stc_monitor_update_rstn_by_default_connection(void *data)
1535 {
1536         static default_connection_s old_connection;
1537         default_connection_s *new_connection = (default_connection_s *)data;
1538
1539         if (old_connection.path != NULL) {
1540                 if (g_system->apps)
1541                         g_tree_foreach(g_system->apps,
1542                                        __remove_application_monitor,
1543                                        (gpointer)&old_connection);
1544
1545                 if (g_system->rstns)
1546                         g_tree_foreach(g_system->rstns,
1547                                        __remove_restriction,
1548                                        (gpointer)&old_connection);
1549         }
1550
1551         FREE(old_connection.path);
1552         FREE(old_connection.ifname);
1553         old_connection.type = 0;
1554         old_connection.roaming = 0;
1555
1556         if (new_connection != NULL && new_connection->path != NULL) {
1557                 if (g_system->apps)
1558                         g_tree_foreach(g_system->apps,
1559                                        __add_application_monitor,
1560                                        (gpointer)new_connection);
1561
1562                 if (g_system->rstns)
1563                         g_tree_foreach(g_system->rstns, __add_restriction,
1564                                        NULL);
1565
1566                 old_connection.path = g_strdup(new_connection->path);
1567                 old_connection.ifname = g_strdup(new_connection->ifname);
1568                 old_connection.type = new_connection->type;
1569                 old_connection.roaming = new_connection->roaming;
1570         }
1571 }
1572
1573 stc_error_e stc_monitor_rstns_tree_add(const table_restrictions_info *info)
1574 {
1575         stc_error_e ret;
1576
1577         stc_rstn_key_s key;
1578         stc_rstn_value_s value;
1579
1580         memset(&key, 0, sizeof(stc_rstn_key_s));
1581         memset(&value, 0, sizeof(stc_rstn_value_s));
1582
1583         key.app_id = g_strdup(info->app_id);
1584         key.ifname = g_strdup(info->ifname);
1585         key.imsi = g_strdup(info->imsi);
1586         key.iftype = info->iftype;
1587         key.roaming = info->roaming;
1588
1589         value.rst_state = info->rst_state;
1590         value.restriction_id = info->restriction_id;
1591
1592         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1593                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1594         else
1595                 value.classid = STC_UNKNOWN_CLASSID;
1596
1597         value.data_limit = info->data_limit;
1598         value.data_warn_limit = info->data_warn_limit;
1599
1600         ret = __rstn_tree_add(&key, &value, TRUE);
1601
1602         FREE(key.app_id);
1603         FREE(key.ifname);
1604         FREE(key.imsi);
1605         return ret;
1606 }
1607
1608 stc_error_e stc_monitor_rstns_tree_remove(const table_restrictions_info *info)
1609 {
1610         stc_error_e ret;
1611
1612         stc_rstn_key_s key = {
1613                 .app_id = g_strdup(info->app_id),
1614                 .ifname = g_strdup(info->ifname),
1615                 .imsi = g_strdup(info->imsi),
1616                 .iftype = info->iftype,
1617                 .roaming = info->roaming,
1618         };
1619
1620         ret = __rstn_tree_remove(&key);
1621
1622         FREE(key.app_id);
1623         FREE(key.ifname);
1624         FREE(key.imsi);
1625         return ret;
1626 }
1627
1628 int stc_monitor_get_counter_socket(void)
1629 {
1630         return g_system->contr_sock;
1631 }