b46b3a41022cbedccc6ba1aa98e6f9b346ebdfbd
[platform/core/connectivity/stc-manager.git] / src / helper / helper-nfacct-rule.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 <errno.h>
18 #include <inttypes.h>
19 #include <stdbool.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 #include <arpa/inet.h>
26
27 #include "counter.h"
28 #include "helper-nfacct-rule.h"
29
30 #include "configure_stub.h"
31
32 #define IPTABLES "/usr/sbin/iptables"
33 #define IP6TABLES "/usr/sbin/ip6tables"
34 #define IPTABLES_CHECK "-C"
35 #define APPEND "-A"
36 #define DELETE "-D"
37 #define INSERT "-I"
38
39 #define NFACCT_NAME_MOD " -m nfacct --nfacct-name %s"
40 #define REJECT_RULE " -j REJECT"
41 #define ACCEPT_RULE " -j ACCEPT"
42 #define OUT_RULE "OUTPUT"
43 #define IN_RULE "INPUT"
44 #define FORWARD_RULE "FORWARD"
45
46 /* TODO idea to use the same rule both for BLOCK (REJECT) and WARNING (ACCEPT) */
47 #define RULE_APP_OUT "%s -w %s OUTPUT -o %s -m cgroup --cgroup %u %s %s"
48 #define RULE_APP_IN "%s -w %s INPUT -i %s -m cgroup --cgroup %u %s %s"
49
50
51 /* iptables -w [I/A/D] [OUTPUT/FORWARD/INPUT] -o/-i iface -m nfacct --nfacct-name name -j ACCEPT/REJECT */
52
53 #define RULE_IFACE_OUT "%s -w %s %s -o %s %s %s"
54 #define RULE_IFACE_IN "%s -w %s %s -i %s %s  %s"
55
56
57 #define NFNL_SUBSYS_ACCT                7
58 #define BUF_SIZE_FOR_ERR 100
59
60 static void prepare_netlink_msg(struct genl *req, int type, int flag)
61 {
62         int seq = time(NULL);
63         memset(req, 0, sizeof(struct genl));
64         req->n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);
65         req->n.nlmsg_type = (NFNL_SUBSYS_ACCT << 8) | type;
66         req->n.nlmsg_flags = NLM_F_REQUEST | flag;
67         req->n.nlmsg_seq = seq;
68 }
69
70 static void add_value_attr(struct genl *req, const void *data, int len,
71                            int type)
72 {
73         int payload;
74         /* get tail */
75         struct nlattr *na = (struct nlattr *)((char *)req +
76                                               NLMSG_ALIGN(req->n.nlmsg_len));
77
78         na->nla_type = type;
79         payload = len + NLA_HDRLEN;
80         na->nla_len = payload;
81         memcpy(NLA_DATA(na), data, len);
82         req->n.nlmsg_len += NLMSG_ALIGN(payload);
83 }
84
85 /*
86  * following 2 function should be used in combination.
87  * start_nest_attr returns nlattr structure, which should be completed by
88  * end_nest_attr,
89  * before these invocations any number of netlink arguments could be inserted
90  * */
91 static struct nlattr *start_nest_attr(struct genl *req, uint16_t type)
92 {
93         struct nlattr *start = (struct nlattr *)((char *)req +
94                                                  NLMSG_ALIGN(req->n.nlmsg_len));
95
96         start->nla_type = NLA_F_NESTED | type;
97         req->n.nlmsg_len += NLMSG_ALIGN(sizeof(struct nlattr));
98         return start;
99 }
100
101 static void end_nest_attr(struct genl *req, struct nlattr *start)
102 {
103         start->nla_len = (__u16)((char *)req +
104                                  NLMSG_ALIGN(req->n.nlmsg_len) - (char *)start);
105 }
106
107 static void add_string_attr(struct genl *req, const char *str, int type)
108 {
109         add_value_attr(req, str, strlen(str) + 1, type);
110 }
111
112 static void add_uint64_attr(struct genl *req, const uint64_t v, int type)
113 {
114         add_value_attr(req, &v, sizeof(v), type);
115 }
116
117 /* macros or templare, due uint64 and uint32 is the same functions */
118 static void add_uint32_attr(struct genl *req, const uint32_t v, int type)
119 {
120         add_value_attr(req, &v, sizeof(v), type);
121 }
122
123 static stc_error_e send_nfacct_request(int sock, struct genl *req)
124 {
125         struct sockaddr_nl nladdr = {.nl_family = AF_NETLINK};
126         int ret = sendto(sock, (char *)(&req->n), req->n.nlmsg_len, 0,
127                          (struct sockaddr *)&nladdr, sizeof(nladdr));
128         ret_value_msg_if(ret < 0, STC_ERROR_FAIL,
129                          "Failed to send nfacct request, error [%d]", ret);
130
131         return STC_ERROR_NONE;
132 }
133
134 static stc_error_e nfacct_send_new(nfacct_rule_s *counter)
135 {
136         struct genl req;
137
138         prepare_netlink_msg(&req, NFNL_MSG_ACCT_NEW, NLM_F_CREATE | NLM_F_ACK);
139         add_string_attr(&req, counter->name, NFACCT_NAME);
140
141         STC_LOGD("counter name %s", counter->name);
142
143         /* padding */
144         add_uint64_attr(&req, 0, NFACCT_PKTS);
145         add_uint64_attr(&req, 0, NFACCT_BYTES);
146         if (counter->quota) {
147                 STC_LOGD("quota bytes %"PRId64, counter->quota);
148
149                 add_uint32_attr(&req, htobe32(NFACCT_F_QUOTA_BYTES),
150                                 NFACCT_FLAGS);
151                 add_uint64_attr(&req, htobe64(counter->quota), NFACCT_QUOTA);
152         }
153
154         return send_nfacct_request(counter->carg->sock, &req);
155 }
156
157 stc_error_e nfacct_send_del(nfacct_rule_s *counter)
158 {
159         struct genl req;
160
161         STC_LOGD("send remove request for %s", counter->name);
162
163         prepare_netlink_msg(&req, NFNL_MSG_ACCT_DEL, NLM_F_ACK);
164         add_string_attr(&req, counter->name, NFACCT_NAME);
165         return send_nfacct_request(counter->carg->sock, &req);
166 }
167 #define NFACCT_F_QUOTAS (NFACCT_F_QUOTA_BYTES | NFACCT_F_QUOTA_PKTS)
168
169 static stc_error_e internal_nfacct_send_get(struct counter_arg *carg,
170                                             enum nfnl_acct_msg_types get_type,
171                                             const char *name,
172                                             int mask, int filter)
173 {
174         struct genl req;
175         struct nlattr *na;
176         int flag = !name ? NLM_F_DUMP : 0;
177         prepare_netlink_msg(&req, get_type,
178                             flag);
179         /* due we don't get counter with quota any where else,
180          * here we will request just counters by default */
181         if (name)
182                 add_string_attr(&req, name, NFACCT_NAME);
183
184         na = start_nest_attr(&req, NFACCT_FILTER);
185         add_uint32_attr(&req, htonl(mask),
186                         NFACCT_FILTER_ATTR_MASK);
187         add_uint32_attr(&req, htonl(filter), NFACCT_FILTER_ATTR_VALUE);
188         end_nest_attr(&req, na);
189         return send_nfacct_request(carg->sock, &req);
190 }
191
192 stc_error_e nfacct_send_get_counters(struct counter_arg *carg, const char *name)
193 {
194         /* get and reset countes value */
195         return internal_nfacct_send_get(carg, NFNL_MSG_ACCT_GET_CTRZERO, name,
196                                         NFACCT_F_QUOTAS, 0);
197 }
198
199 stc_error_e nfacct_send_get_quotas(struct counter_arg *carg, const char *name)
200 {
201         /* just get counters */
202         return internal_nfacct_send_get(carg, NFNL_MSG_ACCT_GET, name,
203                                         NFACCT_F_QUOTA_BYTES,
204                                         NFACCT_F_QUOTA_BYTES);
205 }
206
207 stc_error_e nfacct_send_get_all(struct counter_arg *carg)
208 {
209         /* get and reset everything, used when quiting */
210         return internal_nfacct_send_get(carg, NFNL_MSG_ACCT_GET_CTRZERO, NULL,
211                                         0, 0);
212 }
213
214 stc_error_e nfacct_send_get(nfacct_rule_s *rule)
215 {
216         if (rule->intend == NFACCT_BLOCK || rule->intend == NFACCT_WARN)
217                 return nfacct_send_get_quotas(rule->carg, rule->name);
218         else if (rule->intend == NFACCT_COUNTER)
219                 return nfacct_send_get_counters(rule->carg, rule->name);
220
221         return STC_ERROR_INVALID_PARAMETER;
222 }
223
224 static nfacct_rule_direction convert_to_iotype(int type)
225 {
226         return (type < NFACCT_COUNTER_LAST_ELEM &&
227                 type > NFACCT_COUNTER_UNKNOWN) ? type : NFACCT_COUNTER_UNKNOWN;
228 }
229
230 static stc_iface_type_e convert_to_iftype(int type)
231 {
232         return (type < STC_IFACE_LAST_ELEM &&
233                 type > STC_IFACE_UNKNOWN) ? type : STC_IFACE_UNKNOWN;
234 }
235
236 bool recreate_counter_by_name(char *cnt_name, nfacct_rule_s *cnt)
237 {
238         char *iftype_part;
239         char *classid_part;
240         char *io_part;
241         char *ifname_part;
242         char *save_ptr = NULL;
243         char name[NFACCT_NAME_MAX] = {0}; /* parse buffer to avoid cnt_name modification */
244
245         strncpy(name, cnt_name, sizeof(name) - 1);
246
247         switch (name[0]) {
248         case 'c':
249                 cnt->intend  = NFACCT_COUNTER;
250                 break;
251         case 'w':
252                 cnt->intend  = NFACCT_WARN;
253                 break;
254         case 'r':
255                 cnt->intend  = NFACCT_BLOCK;
256                 break;
257         case 't':
258                 cnt->intend  = NFACCT_TETH_COUNTER;
259                 break;
260         default:
261                 return false;
262         }
263
264         STRING_SAVE_COPY(cnt->name, cnt_name);
265
266         if (cnt->intend == NFACCT_TETH_COUNTER) {
267                 char ifname_buf[MAX_IFACE_LENGTH];
268                 int ifname_len;
269                 stc_iface_type_e iface;
270                 /* tbnep+:seth_w0; means comes by bt go away by mobile interface,
271                  * it's outgoing traffic, due all tethering is mobile databased */
272                 iftype_part = strchr(name, ':');
273                 ret_value_msg_if(iftype_part == NULL,
274                                  false, "Invalid format of the tethering counter %s", name);
275                 ifname_len = iftype_part - name - 1;
276                 strncpy(ifname_buf, name + 1, ifname_len); /* skip first t */
277                 ifname_buf[ifname_len] = '\0';
278                 iface = get_iftype_by_name(ifname_buf);
279                 /* check first part is it datacall */
280                 if (iface == STC_IFACE_DATACALL) {
281                         strncpy(cnt->ifname, ifname_buf, MAX_IFACE_LENGTH);
282                         cnt->iotype = NFACCT_COUNTER_IN;
283                 } else {
284                         /* +1, due : symbol and till the end of cnt_name */
285                         strncpy(ifname_buf, iftype_part + 1, MAX_IFACE_LENGTH);
286                         iface = get_iftype_by_name(ifname_buf);
287                         if (iface == STC_IFACE_DATACALL) {
288                                 cnt->iotype = NFACCT_COUNTER_OUT;
289                                 strncpy(cnt->ifname, ifname_buf, MAX_IFACE_LENGTH);
290                         }
291                 }
292
293                 if (cnt->iotype == NFACCT_COUNTER_UNKNOWN) {
294                         STC_LOGE("can't determine tethering direction %s", name);
295                         return false;
296                 }
297                 cnt->iftype = STC_IFACE_DATACALL;
298                 cnt->classid = STC_TETHERING_APP_CLASSID;
299                 return true;
300         }
301
302         io_part = strtok_r(name, "_", &save_ptr);
303         if (io_part != NULL)
304                 cnt->iotype = convert_to_iotype(atoi(io_part + 1));
305         else
306                 return false;
307
308         iftype_part = strtok_r(NULL, "_", &save_ptr);
309         if (iftype_part != NULL)
310                 cnt->iftype = convert_to_iftype(atoi(iftype_part));
311         else
312                 return false;
313
314         classid_part = strtok_r(NULL, "_", &save_ptr);
315         if (classid_part != NULL)
316                 cnt->classid = atoi(classid_part);
317         else {
318                 cnt->classid = STC_ALL_APP_CLASSID;
319                 return cnt->intend == NFACCT_BLOCK ? true : false;
320         }
321
322         ifname_part = strtok_r(NULL, "\0", &save_ptr);
323         if (ifname_part != NULL)
324                 STRING_SAVE_COPY(cnt->ifname, ifname_part);
325         else
326                 return false;
327
328         return true;
329 }
330
331 static void _process_answer(struct netlink_serialization_params *params)
332 {
333         struct rtattr *na;
334         struct rtattr *attr_list[__NFACCT_MAX] = {0};
335         struct counter_arg *carg = params->carg;
336         struct genl *ans = params->ans;;
337         struct nlmsghdr *nlhdr = &ans->n;
338         int len = GENLMSG_PAYLOAD(nlhdr);
339         int ans_len = carg->ans_len;
340
341         if (len == 0)
342                 return;
343
344         /* parse reply message */
345         na = (struct rtattr *)GENLMSG_DATA(ans);
346
347         while (NLMSG_OK(nlhdr, ans_len)) {
348                 fill_attribute_list(attr_list, NFACCT_MAX,
349                                     na, len);
350                 if (!attr_list[NFACCT_NAME] ||
351                     !attr_list[NFACCT_BYTES])
352                         goto next;
353                 params->eval_attr(attr_list, carg);
354
355 next:
356                 nlhdr = NLMSG_NEXT(nlhdr, ans_len);
357                 if (ans_len < 0)
358                         break;
359                 na = (struct rtattr *)GENLMSG_DATA(nlhdr);
360         }
361
362         if (params->post_eval_attr)
363                 params->post_eval_attr(carg);
364 }
365
366 netlink_serialization_command *
367 netlink_create_command(struct netlink_serialization_params *params)
368 {
369         static netlink_serialization_command command = {0,};
370         command.deserialize_answer = _process_answer;
371         command.params = *params;
372         return &command;
373 }
374
375 static unsigned int get_args_number(const char *cmd_buf)
376 {
377         char *str;
378         unsigned int count = 0;
379
380         for (str = (char *)cmd_buf; *str != '\0'; ++str) {
381                 if (*str == ' ')
382                         ++count;
383         }
384         return count;
385 }
386
387 static void wait_for_rule_cmd(pid_t pid)
388 {
389         int status;
390         pid_t ret_pid;
391         char buf[BUF_SIZE_FOR_ERR] = { 0 };
392
393         if (!pid || pid == -1) {
394                 STC_LOGD("no need to wait");
395                 return;
396         }
397
398         ret_pid = waitpid(pid, &status, 0);
399         if (ret_pid < 0)
400                 STC_LOGD("can't wait for a pid %d %d %s", pid, status,
401                          strerror_r(errno, buf, BUF_SIZE_FOR_ERR));
402 }
403
404 static char* get_cmd_pos(const char *cmd_buf)
405 {
406         char *cmd_pos = strstr(cmd_buf, APPEND);
407         if (!cmd_pos)
408                 cmd_pos = strstr(cmd_buf, INSERT);
409
410         return cmd_pos;
411 }
412
413 static bool is_rule_present(const char *cmd_buf)
414 {
415         size_t buf_len;
416         char *exec_buf;
417         char *cmd_pos = get_cmd_pos(cmd_buf);
418         bool ret = false;
419         if (!cmd_pos)
420                 return false;
421
422         buf_len = strlen(cmd_buf) + 1;
423         exec_buf = (char *)malloc(buf_len);
424         if (!exec_buf)
425                 return false;
426
427         strncpy(exec_buf, cmd_buf, buf_len);
428         strncpy(exec_buf + (cmd_pos - cmd_buf), IPTABLES_CHECK,
429                 sizeof(IPTABLES_CHECK) - 1);
430
431         STC_LOGD("check rule %s", exec_buf);
432
433         ret = system(exec_buf) == 0;
434         free(exec_buf);
435         return ret;
436 }
437
438 stc_error_e exec_iptables_cmd(const char *cmd_buf, pid_t *cmd_pid)
439 {
440         const size_t args_number = get_args_number(cmd_buf);
441         *cmd_pid = 0;
442
443         ret_value_msg_if(args_number == 0, STC_ERROR_FAIL, "no arguments");
444
445         pid_t pid = fork();
446
447         if (pid == 0) {
448                 char *cmd;
449                 unsigned int i;
450                 char *args[args_number + 2];
451                 int ret;
452                 char *save_ptr = NULL;
453                 char buf[BUF_SIZE_FOR_ERR] = { 0 };
454
455                 STC_LOGD("executing iptables cmd %s in forked process",
456                          cmd_buf);
457
458                 if (is_rule_present(cmd_buf)) {
459                         STC_LOGD("Rule %s already present", cmd_buf);
460                         exit(0);
461                 }
462
463                 args[0] = "iptables";
464                 cmd = strtok_r((char *)cmd_buf, " ", &save_ptr);
465                 if (cmd == NULL) {
466                         STC_LOGE("no arguments");
467                         exit(-EINVAL);
468                 }
469
470                 for (i = 1; i <= args_number; ++i)
471                         args[i] = strtok_r(NULL, " ", &save_ptr);
472
473                 args[i] = NULL;
474
475                 ret = execv(cmd, args);
476                 if (ret)
477                         STC_LOGE("Can't execute %s: %s",
478                                  cmd_buf, strerror_r(errno, buf,
479                                                      BUF_SIZE_FOR_ERR));
480                 exit(ret);
481         }
482
483         *cmd_pid = pid;
484         return STC_ERROR_NONE;
485 }
486
487 stc_error_e exec_ip6tables_cmd(const char *cmd_buf, pid_t *cmd_pid)
488 {
489         const size_t args_number = get_args_number(cmd_buf);
490         *cmd_pid = 0;
491
492         ret_value_msg_if(args_number == 0, STC_ERROR_FAIL, "no arguments");
493
494         pid_t pid = fork();
495
496         if (pid == 0) {
497                 char *cmd;
498                 unsigned int i;
499                 char *args[args_number + 2];
500                 int ret;
501                 char *save_ptr = NULL;
502                 char buf[BUF_SIZE_FOR_ERR] = { 0 };
503
504                 STC_LOGD("executing ip6tables cmd %s in forked process",
505                          cmd_buf);
506
507                 if (is_rule_present(cmd_buf)) {
508                         STC_LOGD("Rule %s already present", cmd_buf);
509                         exit(0);
510                 }
511
512                 args[0] = "ip6tables";
513                 cmd = strtok_r((char *)cmd_buf, " ", &save_ptr);
514                 if (cmd == NULL) {
515                         STC_LOGE("no arguments");
516                         exit(-EINVAL);
517                 }
518
519                 for (i = 1; i <= args_number; ++i)
520                         args[i] = strtok_r(NULL, " ", &save_ptr);
521
522                 args[i] = NULL;
523
524                 ret = execv(cmd, args);
525                 if (ret)
526                         STC_LOGE("Can't execute %s: %s",
527                                  cmd_buf, strerror_r(errno, buf, BUF_SIZE_FOR_ERR));
528                 exit(ret);
529         }
530
531         *cmd_pid = pid;
532         return STC_ERROR_NONE;
533 }
534
535 static char *choose_iftype_name(nfacct_rule_s *rule)
536 {
537         return strlen(rule->ifname) != 0 ? rule->ifname :
538                 get_iftype_name(rule->iftype);
539 }
540
541 static stc_error_e exec_iface_cmd(const char *pattern, const char *cmd,
542                                   const char *chain, const char *nfacct,
543                                   const char *jump, char *iftype_name,
544                                   pid_t *pid)
545 {
546         char block_buf[MAX_PATH_LENGTH];
547         int ret;
548
549         ret_value_msg_if(iftype_name == NULL, STC_ERROR_FAIL,
550                          "Invalid network interface name argument");
551
552         /* iptables rule */
553         ret = snprintf(block_buf, sizeof(block_buf), pattern, IPTABLES, cmd, chain,
554                       iftype_name, nfacct, jump);
555         ret_value_msg_if(ret > sizeof(block_buf), STC_ERROR_FAIL,
556                          "Not enough buffer");
557         exec_iptables_cmd(block_buf, pid);
558         wait_for_rule_cmd(*pid);
559
560         /* ip6tables rule */
561         ret = snprintf(block_buf, sizeof(block_buf), pattern, IP6TABLES, cmd, chain,
562                       iftype_name, nfacct, jump);
563         ret_value_msg_if(ret > sizeof(block_buf), STC_ERROR_FAIL,
564                          "Not enough buffer");
565         ret = exec_ip6tables_cmd(block_buf, pid);
566         wait_for_rule_cmd(*pid);
567
568         return ret;
569 }
570
571 static stc_error_e exec_app_cmd(const char *pattern, const char *cmd,
572                                 const char *nfacct, const char *jump,
573                                 const uint32_t classid, char *iftype_name,
574                                 pid_t *pid)
575 {
576         char block_buf[MAX_PATH_LENGTH];
577         int ret;
578         ret_value_msg_if(iftype_name == NULL, STC_ERROR_FAIL,
579                          "Invalid network interface name argument");
580
581         /* iptables rules */
582         ret = snprintf(block_buf, sizeof(block_buf), pattern, IPTABLES, cmd,
583                       iftype_name, classid, nfacct, jump);
584         ret_value_msg_if(ret > sizeof(block_buf), STC_ERROR_FAIL,
585                          "Not enough buffer");
586         exec_iptables_cmd(block_buf, pid);
587         wait_for_rule_cmd(*pid);
588
589         /* ip6tables rules */
590         ret = snprintf(block_buf, sizeof(block_buf), pattern, IP6TABLES, cmd,
591                       iftype_name, classid, nfacct, jump);
592         ret_value_msg_if(ret > sizeof(block_buf), STC_ERROR_FAIL,
593                          "Not enough buffer");
594         ret = exec_ip6tables_cmd(block_buf, pid);
595         wait_for_rule_cmd(*pid);
596
597         return ret;
598 }
599
600 static char *get_iptables_cmd(const nfacct_rule_action action)
601 {
602         if (action == NFACCT_ACTION_APPEND)
603                 return APPEND;
604         else if (action == NFACCT_ACTION_DELETE)
605                 return DELETE;
606         else if (action == NFACCT_ACTION_INSERT)
607                 return INSERT;
608
609         return "";
610 }
611
612 static char *get_iptables_chain(const nfacct_rule_direction iotype)
613 {
614         if (iotype == NFACCT_COUNTER_IN)
615                 return IN_RULE;
616         else if (iotype == NFACCT_COUNTER_OUT)
617                 return OUT_RULE;
618
619         return "";
620 }
621
622 static char *get_iptables_jump(const nfacct_rule_jump jump)
623 {
624         if (jump == NFACCT_JUMP_ACCEPT)
625                 return ACCEPT_RULE;
626         else if (jump == NFACCT_JUMP_REJECT)
627                 return REJECT_RULE;
628
629         return "";
630 }
631
632 static stc_error_e produce_app_rule(nfacct_rule_s *rule,
633                                     const int64_t send_limit,
634                                     const int64_t rcv_limit,
635                                     const nfacct_rule_action action,
636                                     const nfacct_rule_jump jump,
637                                     const nfacct_rule_direction iotype)
638 {
639         char *set_cmd = get_iptables_cmd(action);
640         char *jump_cmd = get_iptables_jump(jump);
641         char nfacct_buf[sizeof(NFACCT_NAME_MOD) +
642                 3*MAX_DEC_SIZE(int) + 4];
643         stc_error_e ret = STC_ERROR_NONE;
644         pid_t pid = 0;
645
646         /* income part */
647         if (iotype & NFACCT_COUNTER_IN) {
648                 rule->quota = rcv_limit;
649                 rule->iotype = NFACCT_COUNTER_IN;
650                 generate_counter_name(rule);
651
652                 /* to support quated counter we need nfacct,
653                  *      don't use it in case of just block without a limit
654                  *      iow, send_limit = 0 and rcv_limit 0 */
655                 if (action != NFACCT_ACTION_DELETE) {
656                         ret = nfacct_send_del(rule);
657                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
658                                          "can't del quota counter");
659
660                         ret = nfacct_send_new(rule);
661                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
662                                          "can't set nfacct counter");
663                         keep_counter(rule);
664                 }
665
666                 /* we have a counter, let's key in a rule, drop in case of
667                  *  send_limit/rcv_limit */
668                 ret = snprintf(nfacct_buf, sizeof(nfacct_buf), NFACCT_NAME_MOD,
669                                rule->name);
670                 ret_value_msg_if(ret > sizeof(nfacct_buf) || ret < 0,
671                                  STC_ERROR_FAIL, "Not enought buffer");
672
673                 ret = exec_app_cmd(RULE_APP_IN, set_cmd, nfacct_buf, jump_cmd,
674                                    rule->classid, choose_iftype_name(rule),
675                                    &pid);
676                 ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
677                                  "Can't set conditional block for ingress"
678                                  " traffic, for classid %u, cmd %s, j %s",
679                                  rule->classid, set_cmd, jump_cmd);
680
681                 /* remove in any case */
682                 if (action == NFACCT_ACTION_DELETE) {
683                         /* TODO here and everywhere should be not just a del,
684                          *      here should be get counted value and than
685                          *      set new counter with that value, but it's minor issue,
686                          *      due it's not clear when actual counters was stored,
687                          *      and based on which value settings made such decition */
688                         rule->iptables_rule = nfacct_send_del;
689                         set_finalize_flag(rule);
690                         nfacct_send_get(rule);
691                         ret = nfacct_send_del(rule);
692                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
693                                          "can't del quota counter");
694                 }
695         }
696
697         if (iotype & NFACCT_COUNTER_OUT) {
698                 /* outcome part */
699                 rule->iotype = NFACCT_COUNTER_OUT;
700                 rule->quota = send_limit;
701                 generate_counter_name(rule);
702                 if (action != NFACCT_ACTION_DELETE) {
703                         ret = nfacct_send_del(rule);
704                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
705                                          "can't del quota counter");
706
707                         ret = nfacct_send_new(rule);
708                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
709                                          "can't set quota counter");
710                         keep_counter(rule);
711                 }
712
713                 ret = snprintf(nfacct_buf, sizeof(nfacct_buf), NFACCT_NAME_MOD,
714                                rule->name);
715                 ret_value_msg_if(ret > sizeof(nfacct_buf) || ret < 0,
716                                  STC_ERROR_FAIL, "Not enought buffer");
717
718                 ret = exec_app_cmd(RULE_APP_OUT, set_cmd, nfacct_buf, jump_cmd,
719                                    rule->classid, choose_iftype_name(rule),
720                                    &pid);
721                 ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
722                                  "Can't set conditional block for engress"
723                                  " traffic, for classid %u, cmd %s, j %s",
724                                  rule->classid, set_cmd, jump_cmd);
725                 if (action == NFACCT_ACTION_DELETE) {
726                         rule->iptables_rule = nfacct_send_del;
727                         /* not effective, it's better to replace
728                          * set_finalize_flag by set_property,
729                          * due keep_counter it necessary only for
730                          * setting iptables_rule */
731                         set_finalize_flag(rule);
732                         nfacct_send_get(rule);
733                         ret = nfacct_send_del(rule);
734                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
735                                          "can't del quota counter");
736                 }
737         }
738         return STC_ERROR_NONE;
739 }
740
741 static stc_error_e produce_iface_rule(nfacct_rule_s *rule,
742                                       const int64_t send_limit,
743                                       const int64_t rcv_limit,
744                                       const nfacct_rule_action action,
745                                       const nfacct_rule_jump jump,
746                                       const nfacct_rule_direction iotype)
747 {
748         char *set_cmd = get_iptables_cmd(action);
749         char *jump_cmd = get_iptables_jump(jump);
750         char nfacct_buf[sizeof(NFACCT_NAME_MOD) +
751                 3*MAX_DEC_SIZE(int) + 4];
752         stc_error_e ret;
753         pid_t pid = 0;
754
755         if (iotype & NFACCT_COUNTER_IN) {
756                 /* income part */
757                 rule->iotype = NFACCT_COUNTER_IN;
758                 rule->quota = rcv_limit;
759                 generate_counter_name(rule);
760
761                 if (action != NFACCT_ACTION_DELETE) {
762                         /* send delete comman in case of creation,
763                          * because nfacct doesn't reset value for nfacct quota
764                          * in case of quota existing */
765                         ret = nfacct_send_del(rule);
766                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
767                                          "can't del quota counter");
768
769                         ret = nfacct_send_new(rule);
770                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
771                                          "can't set quota counter");
772                         keep_counter(rule);
773                 }
774
775                 ret = snprintf(nfacct_buf, sizeof(nfacct_buf),
776                                NFACCT_NAME_MOD, rule->name);
777                 ret_value_msg_if(ret > sizeof(nfacct_buf) || ret < 0,
778                                  STC_ERROR_FAIL, "Not enought buffer");
779
780                 ret = exec_iface_cmd(RULE_IFACE_IN, set_cmd,
781                                      get_iptables_chain(rule->iotype),
782                                      nfacct_buf, jump_cmd,
783                                      choose_iftype_name(rule), &pid);
784                 ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
785                                  "Can't set conditional block for ingress"
786                                  " traffic, for iftype %d, cmd %s, j %s",
787                                  rule->iftype, set_cmd, jump_cmd);
788
789                 /* for tethering */
790                 if (rule->intend == NFACCT_WARN ||
791                     rule->intend == NFACCT_BLOCK) {
792                         /* RULE_IFACE_OUT is not a misprint here */
793                         ret = exec_iface_cmd(RULE_IFACE_IN, set_cmd,
794                                              FORWARD_RULE, nfacct_buf, jump_cmd,
795                                              choose_iftype_name(rule), &pid);
796                         ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
797                                          "Can't set forward rule for ingress "
798                                          "traffic, for iftype %d, cmd %s, j %s",
799                                          rule->iftype, set_cmd, jump_cmd);
800                 }
801                 /* tethering */
802
803                 if (action == NFACCT_ACTION_DELETE) {
804                         rule->iptables_rule = nfacct_send_del;
805                         set_finalize_flag(rule);
806                         nfacct_send_get(rule);
807                         ret = nfacct_send_del(rule);
808                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
809                                          "can't del quota counter");
810                 }
811         }
812
813         if (iotype & NFACCT_COUNTER_OUT) {
814                 /* outcome part */
815                 rule->iotype = NFACCT_COUNTER_OUT;
816                 rule->quota = send_limit;
817                 generate_counter_name(rule);
818
819                 if (action != NFACCT_ACTION_DELETE) {
820                         /* send delete comman in case of creation,
821                          * because nfacct doesn't reset value for nfacct quota
822                          * in case of quota existing */
823                         ret = nfacct_send_del(rule);
824                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
825                                          "can't del quota counter");
826
827                         ret = nfacct_send_new(rule);
828                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
829                                          "can't set quota counter");
830                         keep_counter(rule);
831                 }
832
833                 ret = snprintf(nfacct_buf, sizeof(nfacct_buf),
834                                NFACCT_NAME_MOD, rule->name);
835                 ret_value_msg_if(ret > sizeof(nfacct_buf) || ret < 0,
836                                  STC_ERROR_FAIL, "Not enough buffer");
837
838                 ret = exec_iface_cmd(RULE_IFACE_OUT, set_cmd, OUT_RULE,
839                                      nfacct_buf, jump_cmd,
840                                      choose_iftype_name(rule), &pid);
841                 ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
842                                  "Can't set conditional block for "
843                                  "engress traffic, for iftype %d, cmd %s, j %s",
844                                  rule->iftype, set_cmd, jump_cmd);
845                 /* for tethering  */
846                 if (rule->intend == NFACCT_WARN ||
847                     rule->intend == NFACCT_BLOCK) {
848                         ret = exec_iface_cmd(RULE_IFACE_OUT, set_cmd,
849                                              FORWARD_RULE, nfacct_buf, jump_cmd,
850                                              choose_iftype_name(rule), &pid);
851                         ret_value_msg_if(ret != STC_ERROR_NONE, STC_ERROR_FAIL,
852                                          "Can't set forward rule for engress "
853                                          "traffic, for iftype %d, cmd %s, j %s",
854                                          rule->iftype, set_cmd, jump_cmd);
855                 }
856                 /* tethering  */
857
858                 if (action == NFACCT_ACTION_DELETE) {
859                         rule->iptables_rule = nfacct_send_del;
860                         set_finalize_flag(rule);
861                         nfacct_send_get(rule);
862                         ret = nfacct_send_del(rule);
863                         ret_value_msg_if(ret != STC_ERROR_NONE, ret,
864                                          "can't del quota counter");
865                 }
866         }
867         return STC_ERROR_NONE;
868 }
869
870 stc_error_e produce_net_rule(nfacct_rule_s *rule,
871                              const int64_t send_limit,
872                              const int64_t rcv_limit,
873                              const nfacct_rule_action action,
874                              const nfacct_rule_jump jump,
875                              const nfacct_rule_direction iotype)
876 {
877         stc_error_e ret = STC_ERROR_NONE;
878
879         if (action == NFACCT_ACTION_APPEND && rule->intend == NFACCT_WARN
880             && !send_limit && !rcv_limit)
881                 return STC_ERROR_NONE;
882
883         if (rule->classid != STC_ALL_APP_CLASSID &&
884             rule->classid != STC_TETHERING_APP_CLASSID &&
885             rule->classid != STC_TOTAL_DATACALL_CLASSID &&
886             rule->classid != STC_TOTAL_WIFI_CLASSID &&
887             rule->classid != STC_TOTAL_BLUETOOTH_CLASSID)
888                 ret = produce_app_rule(rule, send_limit,
889                                        rcv_limit, action, jump, iotype);
890         else
891                 ret = produce_iface_rule(rule, send_limit, rcv_limit,
892                                          action, jump, iotype);
893
894         return ret;
895 }
896
897 void generate_counter_name(nfacct_rule_s *counter)
898 {
899         char warn_symbol = 'c';
900         if (!strlen(counter->ifname)) {
901                 char *iftype_name = get_iftype_name(counter->iftype);
902                 /* trace counter name, maybe name was already generated */
903                 ret_msg_if(iftype_name == NULL,
904                            "Can't get interface name for counter %s, iftype %d)!",
905                            counter->name, counter->iftype);
906                 STRING_SAVE_COPY(counter->ifname, iftype_name);
907         }
908
909         if (counter->intend  == NFACCT_WARN)
910                 warn_symbol = 'w';
911         else if (counter->intend  == NFACCT_BLOCK)
912                 warn_symbol = 'r';
913         snprintf(counter->name, NFACCT_NAME_MAX, "%c%d_%d_%d_%s",
914                  warn_symbol, counter->iotype, counter->iftype,
915                  counter->classid, counter->ifname);
916 }
917