Reopening socket if G_IO error is received and updated debug logs.
[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 (stc && connection && connection->ifname) {
280                 struct nfacct_rule counter;
281
282                 if (!stc->carg) {
283                         stc->carg = MALLOC0(counter_arg_s, 1);
284                         stc->carg->sock = stc_monitor_get_counter_socket();
285                 }
286
287                 memset(&counter, 0, sizeof(struct nfacct_rule));
288
289                 counter.carg = stc->carg;
290                 counter.classid = app_value->classid;
291                 counter.intend = NFACCT_COUNTER;
292                 g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
293
294                 __add_iptables_in(&counter);
295                 __add_iptables_out(&counter);
296         }
297
298         return FALSE;
299 }
300
301 static gboolean __remove_application_monitor(gpointer key, gpointer value,
302                                              gpointer data)
303 {
304         stc_app_value_s *app_value = (stc_app_value_s *)value;
305         default_connection_s *connection = (default_connection_s *)data;
306         stc_s *stc = stc_get_manager();
307
308         if (stc && connection && connection->ifname) {
309                 struct nfacct_rule counter;
310
311                 if (!stc->carg) {
312                         stc->carg = MALLOC0(counter_arg_s, 1);
313                         stc->carg->sock = stc_monitor_get_counter_socket();
314                 }
315
316                 memset(&counter, 0, sizeof(struct nfacct_rule));
317
318                 counter.carg = stc->carg;
319                 counter.classid = app_value->classid;
320                 counter.intend = NFACCT_COUNTER;
321                 g_strlcpy(counter.ifname, connection->ifname, MAX_IFACE_LENGTH);
322
323                 __del_iptables_in(&counter);
324                 __del_iptables_out(&counter);
325         }
326
327         return FALSE;
328 }
329
330 static void __print_rstn(stc_rstn_key_s *rstn_key, stc_rstn_value_s *rstn_value)
331 {
332         STC_LOGI("rstn info => rstn_id [%llu], "
333                  "app_id [%s], classid [%lu], ifname [%s], "
334                  "iftype [%d], rst_state [%d], "
335                  "limit [ (%lld) bytes], "
336                  "warn_limit [ (%lld) bytes], "
337                  "counter [ (%lld) bytes], "
338                  "roaming [%d], imsi [%s]",
339                  rstn_value->restriction_id,
340                  rstn_key->app_id, rstn_value->classid , rstn_key->ifname,
341                  rstn_key->iftype, rstn_value->rst_state,
342                  rstn_value->data_limit,
343                  rstn_value->data_warn_limit,
344                  rstn_value->data_counter,
345                  rstn_key->roaming, rstn_key->imsi);
346 }
347
348 static void __process_restriction(enum traffic_restriction_type rst_type,
349                                   stc_rstn_key_s *rstn_key,
350                                   stc_rstn_value_s *rstn_value, void *data)
351 {
352         int64_t effective_data_limit, effective_data_warn_limit;
353         default_connection_s *old_connection = (default_connection_s *)data;
354         default_connection_s *connection = NULL;
355
356         if (old_connection != NULL)
357                 connection = old_connection;
358         else
359                 connection = stc_get_default_connection();
360
361         /* no default ifname */
362         if (connection->ifname == NULL)
363                 return;
364
365         /* rstn not applicable for this interface */
366         if (rstn_key->ifname != NULL && g_strcmp0("", rstn_key->ifname) != 0 &&
367             g_strcmp0(connection->ifname, rstn_key->ifname) != 0)
368                 return;
369
370         /* classid is invalid */
371         if (rstn_value->classid == STC_UNKNOWN_CLASSID)
372                 return;
373
374         effective_data_limit = rstn_value->data_limit;
375         effective_data_warn_limit = rstn_value->data_warn_limit;
376
377         if (rst_type == RST_SET) {
378                 /* TODO: Change this to runtime memory */
379                 table_counters_info info;
380
381                 memset(&info, 0, sizeof(table_counters_info));
382                 table_counters_get(rstn_value->restriction_id, &info);
383
384                 effective_data_limit -= info.data_counter;
385                 effective_data_warn_limit -= info.data_counter;
386
387                 if (effective_data_limit < 0) {
388                         effective_data_limit = 0;
389                         rstn_value->data_limit_reached = TRUE;
390                 }
391
392                 if (effective_data_warn_limit < 0)
393                         effective_data_warn_limit = 0;
394
395                 STC_LOGD("datausage [%lld] bytes", info.data_counter);
396         }
397
398         STC_LOGD("rstn_id [%llu], effective_data_limit [%lld] bytes, "
399                  "effective_data_warn_limit [%lld] bytes",
400                  rstn_value->restriction_id, effective_data_limit,
401                  effective_data_warn_limit);
402
403         switch (rst_type) {
404         case RST_SET:
405                 if (effective_data_limit <= 0) {
406                         char *default_ifname = stc_default_connection_get_ifname();
407                         struct nfacct_rule counter;
408                         stc_s *stc = stc_get_manager();
409
410                         if (!stc->carg) {
411                                 stc->carg = MALLOC0(counter_arg_s, 1);
412                                 stc->carg->sock =
413                                         stc_monitor_get_counter_socket();
414                         }
415
416                         counter.carg = stc->carg;
417                         counter.classid = rstn_value->classid;
418                         counter.intend = NFACCT_BLOCK;
419                         counter.iftype = STC_IFACE_UNKNOWN;
420                         g_strlcpy(counter.ifname, default_ifname,
421                                   MAX_IFACE_LENGTH);
422
423                         generate_counter_name(&counter);
424                         g_free(default_ifname);
425
426                         /* iptables rule */
427                         __add_iptables_in(&counter);
428                         __add_iptables_out(&counter);
429                 }
430
431                 rstn_value->rst_state = STC_RESTRICTION_ACTIVATED;
432                 rstn_value->data_limit_reached = FALSE;
433                 break;
434         case RST_EXCLUDE:
435                 ;//Do Nothing
436                 break;
437         case RST_UNSET:
438                 {
439                         char *default_ifname = stc_default_connection_get_ifname();
440                         struct nfacct_rule counter;
441                         stc_s *stc = stc_get_manager();
442
443                         if (!stc->carg) {
444                                 stc->carg = MALLOC0(counter_arg_s, 1);
445                                 stc->carg->sock =
446                                         stc_monitor_get_counter_socket();
447                         }
448
449                         counter.carg = stc->carg;
450                         counter.classid = rstn_value->classid;
451                         counter.intend = NFACCT_BLOCK;
452                         counter.iftype = STC_IFACE_UNKNOWN;
453                         g_strlcpy(counter.ifname, default_ifname,
454                                   MAX_IFACE_LENGTH);
455
456                         generate_counter_name(&counter);
457                         g_free(default_ifname);
458
459                         /* iptables rule */
460                         __del_iptables_in(&counter);
461                         __del_iptables_out(&counter);
462
463                         rstn_value->rst_state = STC_RESTRICTION_REMOVED;
464                         rstn_value->data_limit_reached = FALSE;
465                 }
466                 break;
467         default:
468                 ;//Do Nothing
469         }
470 }
471
472 static gboolean __remove_rstns_foreach_application(gpointer key,
473                                                    gpointer value,
474                                                    gpointer data)
475 {
476         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
477         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
478         gchar *app_id = (gchar *)data;
479
480         /* rstn rule is not for applications */
481         if (rstn_key->app_id == NULL)
482                 goto out;
483
484         /* rstn rule is not for this application */
485         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
486                 goto out;
487
488         /* rstn rule is already removed */
489         if (rstn_value->rst_state == STC_RESTRICTION_REMOVED)
490                 goto out;
491
492         /* remove restriction from system */
493         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
494
495         __print_rstn(rstn_key, rstn_value);
496 out:
497         return FALSE;
498 }
499
500 static void __remove_rstns_for_application(gchar *app_id)
501 {
502         g_tree_foreach(g_system->rstns, __remove_rstns_foreach_application,
503                        app_id);
504 }
505
506 static stc_error_e __application_remove_if_empty(const stc_app_key_s *app_key)
507 {
508         stc_error_e ret = STC_ERROR_NONE;
509         guint pid_count = 0;
510         stc_app_value_s *lookup;
511
512         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
513
514         lookup = __application_lookup(g_system->apps, app_key);
515         if (!lookup) {
516                 STC_LOGE("app_key not found");
517                 return STC_ERROR_NO_DATA;
518         }
519
520         g_tree_foreach(lookup->processes, __processes_tree_check_empty,
521                        &pid_count);
522
523         if (!pid_count) {
524                 /* remove nfacct rule for this classid */
525                 __remove_application_monitor((gpointer) app_key, lookup,
526                                              stc_get_default_connection());
527                 __remove_rstns_for_application(app_key->app_id);
528         }
529
530         if (!g_tree_remove(g_system->apps, app_key)) {
531                 ret = STC_ERROR_NO_DATA;
532                 STC_LOGE("key not found");
533         }
534
535         return ret;
536 }
537
538 static stc_error_e __close_contr_sock(stc_system_s *system)
539 {
540         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
541
542         /* close netlink socket for updating kernel counters */
543         if (system->contr_sock != -1) {
544                 close(system->contr_sock);
545                 system->contr_sock = -1;
546         }
547
548         if (system->contr_gsource_id != 0) {
549                 g_source_remove(system->contr_gsource_id);
550                 system->contr_gsource_id = 0;
551         }
552
553         return STC_ERROR_NONE;
554 }
555
556 static gboolean __process_contr_reply(GIOChannel *source,
557                                       GIOCondition condition,
558                                       gpointer user_data);
559
560 static stc_error_e __close_and_reopen_contr_sock(stc_system_s *system)
561 {
562         GIOChannel *gio = NULL;
563         ret_value_msg_if(system == NULL, STC_ERROR_INVALID_PARAMETER, "invalid parameter");
564
565         /* close netlink socket for updating kernel counters */
566         if (system->contr_sock != -1) {
567                 close(system->contr_sock);
568                 system->contr_sock = -1;
569         }
570
571         if (system->contr_gsource_id != 0) {
572                 g_source_remove(system->contr_gsource_id);
573                 system->contr_gsource_id = 0;
574         }
575
576         /* create netlink socket for updating kernel counters */
577         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
578         if (!(system->contr_sock)) {
579                 STC_LOGE("failed to open socket");
580                 FREE(system);
581                 return STC_ERROR_FAIL;
582         }
583
584         gio = g_io_channel_unix_new(system->contr_sock);
585         system->contr_gsource_id =
586                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
587                                (GIOFunc) __process_contr_reply,
588                                NULL);
589         g_io_channel_unref(gio);
590
591         return STC_ERROR_NONE;
592 }
593
594 static gboolean __rstn_counter_update_foreach_classid(gpointer key,
595                                                       gpointer value,
596                                                       gpointer data)
597 {
598         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
599         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
600         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
601
602         if (context->counter->intend != NFACCT_COUNTER)
603                 goto try_next_callback;
604
605         if (rstn_value->classid != context->counter->classid)
606                 goto try_next_callback;
607
608         if (rstn_value->data_limit_reached == TRUE) {
609                 context->data_limit_reached = TRUE;
610                 goto try_next_callback;
611         }
612
613         switch (context->counter->iotype) {
614         case NFACCT_COUNTER_IN:
615         case NFACCT_COUNTER_OUT:
616                 rstn_value->data_counter += context->bytes;
617
618                 if (rstn_value->data_counter >= rstn_value->data_warn_limit &&
619                     rstn_value->warn_limit_crossed_notified == FALSE) {
620
621                         gboolean rv = FALSE;
622                         char iftype[MAX_INT_LENGTH];
623                         char byte[MAX_INT_LENGTH];
624                         stc_s *stc = (stc_s *)stc_get_manager();
625                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
626
627                         /* emit signal */
628                         rv = stc_manager_dbus_emit_signal(stc->connection,
629                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
630                                                           STC_DBUS_INTERFACE_RESTRICTION,
631                                                           "WarnThresholdCrossed",
632                                                           g_variant_new("(s)", rstn_key->app_id));
633                         if (rv == TRUE)
634                                 rstn_value->warn_limit_crossed_notified = TRUE;
635
636                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
637                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_warn_limit);
638                         stc_send_warn_message_to_net_popup("warn threshold crossed",
639                                                            "warning_noti",
640                                                            rstn_key->app_id,
641                                                            iftype, byte);
642                 }
643
644                 if (rstn_value->data_counter >= rstn_value->data_limit &&
645                     rstn_value->rstn_limit_crossed_notified == FALSE) {
646
647                         gboolean rv = FALSE;
648                         char iftype[MAX_INT_LENGTH];
649                         char byte[MAX_INT_LENGTH];
650                         stc_s *stc = (stc_s *)stc_get_manager();
651                         ret_value_msg_if(stc == NULL, FALSE, "failed to get stc data");
652
653                         /* block immediately */
654                         context->counter->intend = NFACCT_BLOCK;
655                         __del_iptables_in(context->counter);
656                         __del_iptables_out(context->counter);
657                         __add_iptables_in(context->counter);
658                         __add_iptables_out(context->counter);
659                         context->counter->intend = NFACCT_COUNTER;
660
661                         rstn_value->data_limit_reached = TRUE;
662
663                         /* emit signal */
664                         rv = stc_manager_dbus_emit_signal(stc->connection,
665                                                           STC_DBUS_SERVICE_RESTRICTION_PATH,
666                                                           STC_DBUS_INTERFACE_RESTRICTION,
667                                                           "RestrictionThresholdCrossed",
668                                                           g_variant_new("(s)", rstn_key->app_id));
669                         if (rv == TRUE)
670                                 rstn_value->rstn_limit_crossed_notified = TRUE;
671
672                         snprintf(iftype, MAX_INT_LENGTH, "%d", rstn_key->iftype);
673                         snprintf(byte, MAX_INT_LENGTH, "%lld", rstn_value->data_limit);
674                         stc_send_restriction_message_to_net_popup("restriction threshold crossed",
675                                                                   "restriction_noti", rstn_key->app_id,
676                                                                   iftype, byte);
677                 }
678
679                 g_system->rstns_tree_updated = TRUE;
680                 __print_rstn(rstn_key, rstn_value);
681                 break;
682         default:
683                 STC_LOGE("unknown iotype");
684         }
685
686
687 try_next_callback:
688         return FALSE;
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 gboolean __apps_counter_update_foreach_classid(gpointer key,
781                                                       gpointer value,
782                                                       gpointer data)
783 {
784         stc_app_key_s *app_key = (stc_app_key_s *)key;
785         stc_app_value_s *app_value = (stc_app_value_s *)value;
786         classid_bytes_context_s *context = (classid_bytes_context_s *)data;
787
788         if (context->counter->intend != NFACCT_COUNTER)
789                 goto try_next_callback;
790
791         if (app_value->classid != context->counter->classid)
792                 goto try_next_callback;
793
794         switch (context->counter->iotype) {
795         case NFACCT_COUNTER_IN:
796                 app_value->data_usage.in_bytes += context->bytes;
797                 app_value->counter.in_bytes = context->bytes;
798                 g_system->apps_tree_updated = TRUE;
799
800                 __apps_tree_foreach_print(app_key, app_value, NULL);
801                 break;
802         case NFACCT_COUNTER_OUT:
803                 app_value->data_usage.out_bytes += context->bytes;
804                 app_value->counter.out_bytes = context->bytes;
805                 g_system->apps_tree_updated = TRUE;
806
807                 __apps_tree_foreach_print(app_key, app_value, NULL);
808                 break;
809         default:
810                 STC_LOGE("unknown iotype");
811         }
812
813 try_next_callback:
814         return FALSE;
815 }
816
817 static void __fill_nfacct_result(char *cnt_name, int64_t bytes,
818                                  struct counter_arg *carg)
819 {
820         struct nfacct_rule counter = {
821                 .carg = carg,
822                 .name = {0},
823                 .ifname = {0},
824                 0
825         };
826
827         classid_bytes_context_s context = {
828                 .counter = &counter,
829                 .bytes = bytes,
830                 .data_limit_reached = FALSE,
831         };
832
833         STC_LOGD("cnt_name %s", cnt_name);
834
835         if (!recreate_counter_by_name(cnt_name, &counter)) {
836                 STC_LOGE("Can't parse counter name %s", cnt_name);
837                 return;
838         }
839
840         STC_LOGI("classid %lu, iftype %u, iotype %d, intend %d, ifname %s, bytes %lld",
841                  context.counter->classid, context.counter->iftype,
842                  context.counter->iotype, context.counter->intend,
843                  context.counter->ifname, context.bytes);
844
845         if (g_system->rstns)
846                 g_tree_foreach(g_system->rstns,
847                                __rstn_counter_update_foreach_classid,
848                                &context);
849
850         if (g_system->apps)
851                 g_tree_foreach(g_system->apps,
852                                __apps_counter_update_foreach_classid,
853                                &context);
854 }
855
856 static int __fill_counters(struct rtattr *attr_list[__NFACCT_MAX],
857                            void *user_data)
858 {
859         struct counter_arg *carg = user_data;
860         char *cnt_name = (char *)RTA_DATA(attr_list[NFACCT_NAME]);
861         if (carg->initiate) {
862                 /**
863                  * TODO: this will be used when daemon starts to update existing
864                  * counter data if present.
865                  *
866                  populate_counters(cnt_name, carg);
867                  */
868         } else {
869                 int64_t *bytes_p =
870                         (int64_t *)RTA_DATA(attr_list[NFACCT_BYTES]);
871                 int bytes = be64toh(*bytes_p);
872                 if (bytes) {
873                         ++carg->serialized_counters;
874                         __fill_nfacct_result(cnt_name, bytes, carg);
875                 }
876         }
877
878         return 0;
879 }
880
881 static int __post_fill_counters(void *user_data)
882 {
883         struct counter_arg *carg = user_data;
884
885         if (carg->initiate)
886                 carg->initiate = 0;
887
888         return 0;
889 }
890
891 static void __process_network_counter(struct genl *ans,
892                                       struct counter_arg *carg)
893 {
894         struct netlink_serialization_params ser_params = {
895                 .carg = carg,
896                 .ans = ans,
897                 .eval_attr = __fill_counters,
898                 .post_eval_attr = __post_fill_counters,
899         };
900
901         netlink_serialization_command *netlink =
902                 netlink_create_command(&ser_params);
903         if (!netlink) {
904                 STC_LOGE("Can not create command");
905                 return;
906         }
907
908         netlink->deserialize_answer(&(netlink->params));
909 }
910
911 static gboolean __process_contr_reply(GIOChannel *source,
912                                       GIOCondition condition,
913                                       gpointer user_data)
914 {
915         int sock = g_io_channel_unix_get_fd(source);
916         struct genl ans;
917         int ret;
918         stc_s *stc = stc_get_manager();
919
920         if ((condition & G_IO_ERR) ||
921             (condition & G_IO_HUP) ||
922             (condition & G_IO_NVAL)) {
923                 /* G_IO_ERR/G_IO_HUP/G_IO_NVAL received */
924
925                 STC_LOGE("Counter socket received G_IO event, closing socket."
926                          "G_IO_ERR [%d], G_IO_HUP [%d], G_IO_NVAL [%s]",
927                          (condition & G_IO_ERR), (condition & G_IO_HUP),
928                          (condition & G_IO_NVAL));
929                 __close_and_reopen_contr_sock(g_system);
930                 return FALSE;
931         }
932
933         if (stc == NULL) {
934                 STC_LOGE("Can't get stc data");
935                 goto out;
936         }
937
938         ret = read_netlink(sock,
939                            &ans, sizeof(struct genl));
940         /* STC_LOGD("Counter data received ret [%d]", ret); */
941         if (ret == 0)
942                 goto out;
943
944         stc->carg->ans_len = ret;
945         __process_network_counter(&ans, stc->carg);
946
947         g_idle_add(__flush_apps_stats_to_database, NULL);
948         g_idle_add(__flush_rstns_counter_to_database, NULL);
949 out:
950         return TRUE;
951 }
952
953 static gboolean __update_contr_cb(void *user_data)
954 {
955         /* Here we just sent command, answer we receive in another callback */
956         stc_s *stc = stc_get_manager();
957         ret_value_msg_if(stc == NULL, STC_ERROR_FAIL, "Can't get stc data");
958         if (!stc->carg) {
959                 stc->carg = MALLOC0(counter_arg_s, 1);
960                 stc->carg->sock = stc_monitor_get_counter_socket();
961         }
962
963         /* STC_LOGD("Get all counters"); */
964         nfacct_send_get_all(stc->carg);
965
966         /* we need to continue the timer */
967         return TRUE;
968 }
969 #if 0
970 static gboolean __rstn_tree_foreach_print(gpointer key, gpointer value,
971                                           gpointer data)
972 {
973         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
974         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
975
976         __print_rstn(rstn_key, rstn_value);
977         return FALSE;
978 }
979
980 static void __rstn_tree_printall(void)
981 {
982         g_tree_foreach(g_system->rstns, __rstn_tree_foreach_print, NULL);
983 }
984 #endif
985 static stc_rstn_value_s * __rstn_lookup(GTree *rstns_tree,
986                                         const stc_rstn_key_s *key)
987 {
988         stc_rstn_value_s *lookup;
989
990         ret_value_msg_if(rstns_tree == NULL, NULL, "rstns_tree is null!");
991
992         lookup = g_tree_lookup(rstns_tree, key);
993
994         return lookup;
995 }
996
997 static gboolean __remove_restriction(gpointer key, gpointer value,
998                                      gpointer data)
999 {
1000         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1001         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1002
1003         /* rstn rule is already removed */
1004         if (rstn_value->rst_state == STC_RESTRICTION_REMOVED)
1005                 return FALSE;
1006
1007         __process_restriction(RST_UNSET, rstn_key, rstn_value, data);
1008         __print_rstn(rstn_key, rstn_value);
1009         return FALSE;
1010 }
1011
1012 static gboolean __add_restriction_debug(gpointer key, gpointer value,
1013                                         gpointer data)
1014 {
1015         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1016         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1017
1018         /* rstn rule is activated */
1019         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1020                 return FALSE;
1021
1022         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1023                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1024         else
1025                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1026
1027         __print_rstn(rstn_key, rstn_value);
1028
1029         return FALSE;
1030 }
1031
1032 static gboolean __add_restriction(gpointer key, gpointer value, gpointer data)
1033 {
1034         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1035         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1036
1037         /* rstn rule is activated */
1038         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1039                 return FALSE;
1040
1041         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1042                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1043         else
1044                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1045
1046         return FALSE;
1047 }
1048
1049 static stc_error_e __rstn_tree_remove(stc_rstn_key_s *key)
1050 {
1051         stc_rstn_value_s *lookup_value;
1052
1053         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1054
1055         lookup_value = __rstn_lookup(g_system->rstns, key);
1056         if (!lookup_value) {
1057                 STC_LOGE("key not found");
1058                 return STC_ERROR_NO_DATA;
1059         }
1060
1061         __remove_restriction(key, lookup_value, NULL);
1062
1063         /* remove counter also */
1064         table_counters_delete(lookup_value->restriction_id);
1065
1066         if (!g_tree_remove(g_system->rstns, key)) {
1067                 STC_LOGD("key not found");
1068                 return STC_ERROR_NO_DATA;
1069         }
1070
1071         return STC_ERROR_NONE;
1072 }
1073
1074 static stc_error_e __rstn_tree_add(stc_rstn_key_s *key,
1075                                    stc_rstn_value_s *value, gboolean debug)
1076 {
1077         stc_rstn_value_s *rstn_value;
1078
1079         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1080
1081         rstn_value = __rstn_lookup(g_system->rstns, key);
1082         if (!rstn_value) {
1083                 stc_rstn_key_s *rstn_key = MALLOC0(stc_rstn_key_s, 1);
1084                 if (!rstn_key) {
1085                         STC_LOGE("rstn_key allocation failed");
1086                         return STC_ERROR_OUT_OF_MEMORY;
1087                 }
1088
1089                 rstn_value = MALLOC0(stc_rstn_value_s, 1);
1090                 if (!rstn_value) {
1091                         STC_LOGE("rstn_value allocation failed");
1092                         FREE(rstn_key);
1093                         return STC_ERROR_OUT_OF_MEMORY;
1094                 }
1095
1096                 rstn_key->app_id = g_strdup(key->app_id);
1097                 rstn_key->ifname = g_strdup(key->ifname);
1098                 rstn_key->imsi = g_strdup(key->imsi);
1099                 rstn_key->iftype = key->iftype;
1100                 rstn_key->roaming = key->roaming;
1101
1102                 g_tree_insert(g_system->rstns, rstn_key, rstn_value);
1103         }
1104
1105         rstn_value->restriction_id = value->restriction_id;
1106         rstn_value->rst_state = value->rst_state;
1107         rstn_value->classid = value->classid;
1108         rstn_value->data_limit = value->data_limit;
1109         rstn_value->data_warn_limit = value->data_warn_limit;
1110         rstn_value->data_counter = 0;
1111         rstn_value->warn_limit_crossed_notified = FALSE;
1112         rstn_value->rstn_limit_crossed_notified = FALSE;
1113
1114         if (debug == TRUE)
1115                 __add_restriction_debug(key, rstn_value, NULL);
1116         else
1117                 __add_restriction(key, rstn_value, NULL);
1118
1119         return STC_ERROR_NONE;
1120 }
1121
1122 static stc_cb_ret_e __insert_restriction_cb(const table_restrictions_info *info,
1123                                             void *user_data)
1124 {
1125         stc_cb_ret_e ret = STC_CONTINUE;
1126
1127         stc_rstn_key_s key;
1128         stc_rstn_value_s value;
1129
1130         memset(&key, 0, sizeof(stc_rstn_key_s));
1131         memset(&value, 0, sizeof(stc_rstn_value_s));
1132
1133         key.app_id = g_strdup(info->app_id);
1134         key.ifname = g_strdup(info->ifname);
1135         key.imsi = g_strdup(info->imsi);
1136         key.iftype = info->iftype;
1137         key.roaming = info->roaming;
1138
1139         value.rst_state = info->rst_state;
1140         value.restriction_id = info->restriction_id;
1141
1142         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1143                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1144         else
1145                 value.classid = STC_UNKNOWN_CLASSID;
1146
1147         value.data_limit = info->data_limit;
1148         value.data_warn_limit = info->data_warn_limit;
1149
1150         if (__rstn_tree_add(&key, &value, FALSE) != STC_ERROR_NONE)
1151                 ret = STC_CANCEL;
1152
1153         FREE(key.app_id);
1154         FREE(key.ifname);
1155         FREE(key.imsi);
1156         return ret;
1157 }
1158
1159 static void __fill_restritions_list(void)
1160 {
1161         table_restrictions_foreach(__insert_restriction_cb, NULL);
1162         //__rstn_tree_printall();
1163 }
1164
1165 static gboolean __add_rstn_foreach_application(gpointer key,
1166                                                gpointer value,
1167                                                gpointer data)
1168 {
1169         stc_rstn_key_s *rstn_key = (stc_rstn_key_s *)key;
1170         stc_rstn_value_s *rstn_value = (stc_rstn_value_s *)value;
1171         gchar *app_id = (gchar *)data;
1172
1173         /* rstn rule is not for applications */
1174         if (rstn_key->app_id == NULL)
1175                 goto out;
1176
1177         /* rstn rule is not for this application */
1178         if (g_strcmp0(rstn_key->app_id, app_id) != 0)
1179                 goto out;
1180
1181         /* rstn rule is already applied */
1182         if (rstn_value->rst_state == STC_RESTRICTION_ACTIVATED)
1183                 goto out;
1184
1185         /* add restriction to system */
1186         if (rstn_value->rst_state == STC_RESTRICTION_EXCLUDED)
1187                 __process_restriction(RST_EXCLUDE, rstn_key, rstn_value, data);
1188         else
1189                 __process_restriction(RST_SET, rstn_key, rstn_value, data);
1190
1191         __print_rstn(rstn_key, rstn_value);
1192 out:
1193         return FALSE;
1194 }
1195
1196 static void __add_rstns_for_application(gchar *app_id)
1197 {
1198         g_tree_foreach(g_system->rstns, __add_rstn_foreach_application,
1199                        app_id);
1200 }
1201
1202 stc_error_e stc_monitor_init(void)
1203 {
1204         stc_system_s *system = MALLOC0(stc_system_s, 1);
1205         GIOChannel *gio = NULL;
1206
1207         ret_value_msg_if(system == NULL, STC_ERROR_OUT_OF_MEMORY, "stc_system_s malloc fail!");
1208
1209         /* initializing cgroups */
1210         cgroup_init();
1211
1212         /* creating monitored application tree */
1213         system->apps = g_tree_new_full(__apps_tree_key_compare, NULL,
1214                                        __apps_tree_key_free,
1215                                        __apps_tree_value_free);
1216
1217         system->rstns = g_tree_new_full(__rstns_tree_key_compare, NULL,
1218                                         __rstns_tree_key_free,
1219                                         __rstns_tree_value_free);
1220
1221         /* create netlink socket for updating kernel counters */
1222         system->contr_sock = create_netlink(NETLINK_NETFILTER, 0);
1223         if (!(system->contr_sock)) {
1224                 STC_LOGE("failed to open socket");
1225                 FREE(system);
1226                 return STC_ERROR_FAIL;
1227         }
1228
1229         gio = g_io_channel_unix_new(system->contr_sock);
1230         system->contr_gsource_id =
1231                 g_io_add_watch(gio, G_IO_IN | G_IO_ERR | G_IO_HUP,
1232                                (GIOFunc) __process_contr_reply,
1233                                NULL);
1234         g_io_channel_unref(gio);
1235
1236         g_system = system;
1237
1238         /* creating restriction rules tree */
1239         __update_contr_cb(NULL);
1240
1241         /* registering periodic kernel counters update callback */
1242         g_system->contr_timer_id = g_timeout_add_seconds(CONTR_TIMER_INTERVAL,
1243                                                          __update_contr_cb,
1244                                                          NULL);
1245         if (g_system->contr_timer_id == 0) {
1246                 STC_LOGE("Failed to register kernel counters update timer");
1247                 __close_contr_sock(g_system);
1248                 return STC_ERROR_FAIL;
1249         }
1250
1251         __fill_restritions_list();
1252
1253         return STC_ERROR_NONE;
1254 }
1255
1256 stc_error_e stc_monitor_deinit(void)
1257 {
1258         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1259
1260         /* close netlink socket for updating kernel counters */
1261         __close_contr_sock(g_system);
1262
1263         /* remove kernel counters update timer */
1264         if (g_system->contr_timer_id > 0) {
1265                 g_source_remove(g_system->contr_timer_id);
1266                 g_system->contr_timer_id = 0;
1267         }
1268
1269         /* destroy monitored application tree */
1270         g_tree_destroy(g_system->apps);
1271         g_system->apps = NULL;
1272
1273         /* destroy restriction rules tree */
1274         g_tree_destroy(g_system->rstns);
1275         g_system->rstns = NULL;
1276
1277         FREE(g_system);
1278
1279         return STC_ERROR_NONE;
1280 }
1281
1282 stc_error_e stc_monitor_application_add(const stc_app_key_s app_key,
1283                                         const stc_app_value_s app_value)
1284 {
1285         stc_error_e ret = STC_ERROR_NONE;
1286         stc_app_key_s *key;
1287         stc_app_value_s *value;
1288         stc_app_value_s *lookup;
1289
1290         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1291
1292         lookup = __application_lookup(g_system->apps, &app_key);
1293         if (lookup) {
1294                 STC_LOGD("app_key already present");
1295                 return STC_ERROR_NONE;
1296         }
1297
1298         key = MALLOC0(stc_app_key_s, 1);
1299         if (!key) {
1300                 STC_LOGE("key allocation failed");
1301                 return STC_ERROR_OUT_OF_MEMORY;
1302         }
1303
1304         value = MALLOC0(stc_app_value_s, 1);
1305         if (!value) {
1306                 STC_LOGE("value allocation failed");
1307                 FREE(key);
1308                 return STC_ERROR_OUT_OF_MEMORY;
1309         }
1310
1311         key->app_id = g_strdup(app_key.app_id);
1312         key->pkg_id = g_strdup(app_key.pkg_id);
1313
1314         value->type = app_value.type;
1315         value->data_usage.in_bytes = app_value.data_usage.in_bytes;
1316         value->data_usage.out_bytes = app_value.data_usage.out_bytes;
1317
1318         value->processes = g_tree_new_full(__processes_tree_key_compare, NULL,
1319                                            __processes_tree_key_free,
1320                                            __processes_tree_value_free);
1321
1322         /* create cgroup and update classid */
1323         value->classid = get_classid_by_app_id(app_key.app_id, TRUE);
1324
1325         g_tree_insert(g_system->apps, key, value);
1326
1327         /* add nfacct rule for this classid */
1328         __add_application_monitor(key, value, stc_get_default_connection());
1329         __add_rstns_for_application(app_key.app_id);
1330
1331         return ret;
1332 }
1333
1334 stc_error_e stc_monitor_process_add(const stc_app_key_s app_key,
1335                                     const stc_process_key_s proc_key,
1336                                     const stc_process_value_s proc_value)
1337 {
1338         stc_error_e ret = STC_ERROR_NONE;
1339         stc_app_value_s *app_lookup;
1340         stc_process_key_s *key;
1341         stc_process_value_s *value;
1342         stc_process_value_s *proc_lookup;
1343
1344         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1345
1346         app_lookup = __application_lookup(g_system->apps, &app_key);
1347         if (!app_lookup) {
1348                 STC_LOGD("app_key not found");
1349                 return STC_ERROR_FAIL;
1350         }
1351
1352         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1353         if (proc_lookup) {
1354                 STC_LOGD("proc_key already present");
1355                 return STC_ERROR_NONE;
1356         }
1357
1358         key = MALLOC0(stc_process_key_s, 1);
1359         if (!key) {
1360                 STC_LOGE("key allocation failed");
1361                 return STC_ERROR_OUT_OF_MEMORY;
1362         }
1363
1364         value = MALLOC0(stc_process_value_s, 1);
1365         if (!value) {
1366                 STC_LOGE("value allocation failed");
1367                 FREE(key);
1368                 return STC_ERROR_OUT_OF_MEMORY;
1369         }
1370
1371         key->pid = proc_key.pid;
1372
1373         value->ground = proc_value.ground;
1374
1375         g_tree_insert(app_lookup->processes, key, value);
1376
1377         /* add pid to application cgroup */
1378         place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1379
1380         return ret;
1381 }
1382
1383 stc_error_e stc_monitor_process_remove(pid_t pid)
1384 {
1385         stc_error_e ret = STC_ERROR_NONE;
1386         stc_process_key_s proc_key = {
1387                 .pid = pid
1388         };
1389
1390         remove_pid_context_s context = {
1391                 .app_key = NULL,
1392                 .proc_key = &proc_key,
1393                 .entry_removed = FALSE,
1394         };
1395
1396         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1397
1398         g_tree_foreach(g_system->apps, __apps_tree_foreach_remove_pid,
1399                        &context);
1400
1401         if (context.entry_removed)
1402                 __application_remove_if_empty(context.app_key);
1403
1404         return ret;
1405 }
1406
1407 stc_error_e stc_monitor_process_update_ground(const stc_app_key_s app_key,
1408                                               const stc_process_key_s proc_key,
1409                                               stc_app_state_e ground)
1410 {
1411         stc_error_e ret = STC_ERROR_NONE;
1412         stc_app_value_s *app_lookup;
1413         stc_process_value_s *proc_lookup;
1414
1415         ret_value_msg_if(g_system == NULL, STC_ERROR_FAIL, "stc monitor not initialized!");
1416
1417         app_lookup = __application_lookup(g_system->apps, &app_key);
1418         if (!app_lookup) {
1419                 STC_LOGD("app_key not found");
1420                 return STC_ERROR_FAIL;
1421         }
1422
1423         proc_lookup = __process_lookup(app_lookup->processes, &proc_key);
1424         if (!proc_lookup) {
1425                 STC_LOGD("proc_key not found");
1426                 return STC_ERROR_FAIL;
1427         }
1428
1429         if (proc_lookup->ground != ground)
1430                 proc_lookup->ground = ground;
1431
1432         if (ground == STC_APP_STATE_BACKGROUND) {
1433                 char *background_app_id = g_strconcat(app_key.app_id,
1434                                                      STC_BACKGROUND_APP_SUFFIX,
1435                                                      NULL);
1436                 place_pids_to_net_cgroup(proc_key.pid, background_app_id);
1437                 g_free(background_app_id);
1438         } else {
1439                 place_pids_to_net_cgroup(proc_key.pid, app_key.app_id);
1440         }
1441
1442         return ret;
1443 }
1444
1445 void stc_monitor_update_rstn_by_default_connection(void *data)
1446 {
1447         static default_connection_s old_connection;
1448         default_connection_s *new_connection = (default_connection_s *)data;
1449
1450         if (old_connection.path != NULL) {
1451                 if (g_system->apps)
1452                         g_tree_foreach(g_system->apps,
1453                                        __remove_application_monitor,
1454                                        (gpointer)&old_connection);
1455
1456                 if (g_system->rstns)
1457                         g_tree_foreach(g_system->rstns,
1458                                        __remove_restriction,
1459                                        (gpointer)&old_connection);
1460         }
1461
1462         FREE(old_connection.path);
1463         FREE(old_connection.ifname);
1464         old_connection.type = 0;
1465         old_connection.roaming = 0;
1466
1467         if (new_connection != NULL && new_connection->path != NULL) {
1468                 if (g_system->apps)
1469                         g_tree_foreach(g_system->apps,
1470                                        __add_application_monitor,
1471                                        (gpointer)new_connection);
1472
1473                 if (g_system->rstns)
1474                         g_tree_foreach(g_system->rstns, __add_restriction,
1475                                        NULL);
1476
1477                 old_connection.path = g_strdup(new_connection->path);
1478                 old_connection.ifname = g_strdup(new_connection->ifname);
1479                 old_connection.type = new_connection->type;
1480                 old_connection.roaming = new_connection->roaming;
1481         }
1482 }
1483
1484 stc_error_e stc_monitor_rstns_tree_add(const table_restrictions_info *info)
1485 {
1486         stc_error_e ret;
1487
1488         stc_rstn_key_s key;
1489         stc_rstn_value_s value;
1490
1491         memset(&key, 0, sizeof(stc_rstn_key_s));
1492         memset(&value, 0, sizeof(stc_rstn_value_s));
1493
1494         key.app_id = g_strdup(info->app_id);
1495         key.ifname = g_strdup(info->ifname);
1496         key.imsi = g_strdup(info->imsi);
1497         key.iftype = info->iftype;
1498         key.roaming = info->roaming;
1499
1500         value.rst_state = info->rst_state;
1501         value.restriction_id = info->restriction_id;
1502
1503         if (value.rst_state != STC_RESTRICTION_EXCLUDED && info->app_id)
1504                 value.classid = get_classid_by_app_id(info->app_id, TRUE);
1505         else
1506                 value.classid = STC_UNKNOWN_CLASSID;
1507
1508         value.data_limit = info->data_limit;
1509         value.data_warn_limit = info->data_warn_limit;
1510
1511         ret = __rstn_tree_add(&key, &value, TRUE);
1512
1513         FREE(key.app_id);
1514         FREE(key.ifname);
1515         FREE(key.imsi);
1516         return ret;
1517 }
1518
1519 stc_error_e stc_monitor_rstns_tree_remove(const table_restrictions_info *info)
1520 {
1521         stc_error_e ret;
1522
1523         stc_rstn_key_s key = {
1524                 .app_id = g_strdup(info->app_id),
1525                 .ifname = g_strdup(info->ifname),
1526                 .imsi = g_strdup(info->imsi),
1527                 .iftype = info->iftype,
1528                 .roaming = info->roaming,
1529         };
1530
1531         ret = __rstn_tree_remove(&key);
1532
1533         FREE(key.app_id);
1534         FREE(key.ifname);
1535         FREE(key.imsi);
1536         return ret;
1537 }
1538
1539 int stc_monitor_get_counter_socket(void)
1540 {
1541         return g_system->contr_sock;
1542 }