Convert all networking/* applets to "new style" applet definitions
[oweals/busybox.git] / networking / tc.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4  *
5  * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
6  *
7  * Bernhard Reutner-Fischer adjusted for busybox
8  */
9 //kbuild:lib-$(CONFIG_TC) += tc.o
10
11 //usage:#define tc_trivial_usage
12 /* //usage: "[OPTIONS] OBJECT CMD [dev STRING]" */
13 //usage:        "OBJECT CMD [dev STRING]"
14 //usage:#define tc_full_usage "\n\n"
15 //usage:        "OBJECT: {qdisc|class|filter}\n"
16 //usage:        "CMD: {add|del|change|replace|show}\n"
17 //usage:        "\n"
18 //usage:        "qdisc [ handle QHANDLE ] [ root |"IF_FEATURE_TC_INGRESS(" ingress |")" parent CLASSID ]\n"
19 /* //usage: "[ estimator INTERVAL TIME_CONSTANT ]\n" */
20 //usage:        "       [ [ QDISC_KIND ] [ help | OPTIONS ] ]\n"
21 //usage:        "       QDISC_KIND := { [p|b]fifo | tbf | prio | cbq | red | etc. }\n"
22 //usage:        "qdisc show [ dev STRING ]"IF_FEATURE_TC_INGRESS(" [ingress]")"\n"
23 //usage:        "class [ classid CLASSID ] [ root | parent CLASSID ]\n"
24 //usage:        "       [ [ QDISC_KIND ] [ help | OPTIONS ] ]\n"
25 //usage:        "class show [ dev STRING ] [ root | parent CLASSID ]\n"
26 //usage:        "filter [ pref PRIO ] [ protocol PROTO ]\n"
27 /* //usage: "\t[ estimator INTERVAL TIME_CONSTANT ]\n" */
28 //usage:        "       [ root | classid CLASSID ] [ handle FILTERID ]\n"
29 //usage:        "       [ [ FILTER_TYPE ] [ help | OPTIONS ] ]\n"
30 //usage:        "filter show [ dev STRING ] [ root | parent CLASSID ]"
31
32 #include "libbb.h"
33 #include "common_bufsiz.h"
34
35 #include "libiproute/utils.h"
36 #include "libiproute/ip_common.h"
37 #include "libiproute/rt_names.h"
38 #include <linux/pkt_sched.h> /* for the TC_H_* macros */
39
40 #define parse_rtattr_nested(tb, max, rta) \
41         (parse_rtattr((tb), (max), RTA_DATA(rta), RTA_PAYLOAD(rta)))
42
43 /* nullifies tb on error */
44 #define __parse_rtattr_nested_compat(tb, max, rta, len) \
45         ({if ((RTA_PAYLOAD(rta) >= len) && \
46                  (RTA_PAYLOAD(rta) >= RTA_ALIGN(len) + sizeof(struct rtattr))) { \
47                         rta = RTA_DATA(rta) + RTA_ALIGN(len); \
48                         parse_rtattr_nested(tb, max, rta); \
49           } else \
50                         memset(tb, 0, sizeof(struct rtattr *) * (max + 1)); \
51         })
52
53 #define parse_rtattr_nested_compat(tb, max, rta, data, len) \
54         ({data = RTA_PAYLOAD(rta) >= len ? RTA_DATA(rta) : NULL; \
55         __parse_rtattr_nested_compat(tb, max, rta, len); })
56
57 #define show_details (0) /* not implemented. Does anyone need it? */
58 #define use_iec (0) /* not currently documented in the upstream manpage */
59
60
61 struct globals {
62         int filter_ifindex;
63         uint32_t filter_qdisc;
64         uint32_t filter_parent;
65         uint32_t filter_prio;
66         uint32_t filter_proto;
67 } FIX_ALIASING;
68 #define G (*(struct globals*)bb_common_bufsiz1)
69 #define filter_ifindex (G.filter_ifindex)
70 #define filter_qdisc (G.filter_qdisc)
71 #define filter_parent (G.filter_parent)
72 #define filter_prio (G.filter_prio)
73 #define filter_proto (G.filter_proto)
74 #define INIT_G() do { \
75         setup_common_bufsiz(); \
76         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
77 } while (0)
78
79 /* Allocates a buffer containing the name of a class id.
80  * The caller must free the returned memory.  */
81 static char* print_tc_classid(uint32_t cid)
82 {
83 #if 0 /* IMPOSSIBLE */
84         if (cid == TC_H_ROOT)
85                 return xasprintf("root");
86         else
87 #endif
88         if (cid == TC_H_UNSPEC)
89                 return xasprintf("none");
90         else if (TC_H_MAJ(cid) == 0)
91                 return xasprintf(":%x", TC_H_MIN(cid));
92         else if (TC_H_MIN(cid) == 0)
93                 return xasprintf("%x:", TC_H_MAJ(cid)>>16);
94         else
95                 return xasprintf("%x:%x", TC_H_MAJ(cid)>>16, TC_H_MIN(cid));
96 }
97
98 /* Get a qdisc handle.  Return 0 on success, !0 otherwise.  */
99 static int get_qdisc_handle(uint32_t *h, const char *str) {
100         uint32_t maj;
101         char *p;
102
103         maj = TC_H_UNSPEC;
104         if (!strcmp(str, "none"))
105                 goto ok;
106         maj = strtoul(str, &p, 16);
107         if (p == str)
108                 return 1;
109         maj <<= 16;
110         if (*p != ':' && *p != '\0')
111                 return 1;
112  ok:
113         *h = maj;
114         return 0;
115 }
116
117 /* Get class ID.  Return 0 on success, !0 otherwise.  */
118 static int get_tc_classid(uint32_t *h, const char *str) {
119         uint32_t maj, min;
120         char *p;
121
122         maj = TC_H_ROOT;
123         if (!strcmp(str, "root"))
124                 goto ok;
125         maj = TC_H_UNSPEC;
126         if (!strcmp(str, "none"))
127                 goto ok;
128         maj = strtoul(str, &p, 16);
129         if (p == str) {
130                 if (*p != ':')
131                         return 1;
132                 maj = 0;
133         }
134         if (*p == ':') {
135                 if (maj >= (1<<16))
136                         return 1;
137                 maj <<= 16;
138                 str = p + 1;
139                 min = strtoul(str, &p, 16);
140 //FIXME: check for "" too?
141                 if (*p != '\0' || min >= (1<<16))
142                         return 1;
143                 maj |= min;
144         } else if (*p != 0)
145                 return 1;
146  ok:
147         *h = maj;
148         return 0;
149 }
150
151 static void print_rate(char *buf, int len, uint32_t rate)
152 {
153         double tmp = (double)rate*8;
154
155         if (use_iec) {
156                 if (tmp >= 1000*1024*1024)
157                         snprintf(buf, len, "%.0fMibit", tmp/(1024*1024));
158                 else if (tmp >= 1000*1024)
159                         snprintf(buf, len, "%.0fKibit", tmp/1024);
160                 else
161                         snprintf(buf, len, "%.0fbit", tmp);
162         } else {
163                 if (tmp >= 1000*1000000)
164                         snprintf(buf, len, "%.0fMbit", tmp/1000000);
165                 else if (tmp >= 1000*1000)
166                         snprintf(buf, len, "%.0fKbit", tmp/1000);
167                 else
168                         snprintf(buf, len, "%.0fbit",  tmp);
169         }
170 }
171
172 /* This is "pfifo_fast".  */
173 static int prio_parse_opt(int argc, char **argv, struct nlmsghdr *n)
174 {
175         return 0;
176 }
177 static int prio_print_opt(struct rtattr *opt)
178 {
179         int i;
180         struct tc_prio_qopt *qopt;
181         struct rtattr *tb[TCA_PRIO_MAX+1];
182
183         if (opt == NULL)
184                 return 0;
185         parse_rtattr_nested_compat(tb, TCA_PRIO_MAX, opt, qopt, sizeof(*qopt));
186         if (tb == NULL)
187                 return 0;
188         printf("bands %u priomap ", qopt->bands);
189         for (i=0; i<=TC_PRIO_MAX; i++)
190                 printf(" %d", qopt->priomap[i]);
191
192         if (tb[TCA_PRIO_MQ])
193                 printf(" multiqueue: o%s ",
194                     *(unsigned char *)RTA_DATA(tb[TCA_PRIO_MQ]) ? "n" : "ff");
195
196         return 0;
197 }
198
199 /* Class Based Queue */
200 static int cbq_parse_opt(int argc, char **argv, struct nlmsghdr *n)
201 {
202         return 0;
203 }
204 static int cbq_print_opt(struct rtattr *opt)
205 {
206         struct rtattr *tb[TCA_CBQ_MAX+1];
207         struct tc_ratespec *r = NULL;
208         struct tc_cbq_lssopt *lss = NULL;
209         struct tc_cbq_wrropt *wrr = NULL;
210         struct tc_cbq_fopt *fopt = NULL;
211         struct tc_cbq_ovl *ovl = NULL;
212         const char *const error = "CBQ: too short %s opt";
213         char buf[64];
214
215         if (opt == NULL)
216                 goto done;
217         parse_rtattr_nested(tb, TCA_CBQ_MAX, opt);
218
219         if (tb[TCA_CBQ_RATE]) {
220                 if (RTA_PAYLOAD(tb[TCA_CBQ_RATE]) < sizeof(*r))
221                         bb_error_msg(error, "rate");
222                 else
223                         r = RTA_DATA(tb[TCA_CBQ_RATE]);
224         }
225         if (tb[TCA_CBQ_LSSOPT]) {
226                 if (RTA_PAYLOAD(tb[TCA_CBQ_LSSOPT]) < sizeof(*lss))
227                         bb_error_msg(error, "lss");
228                 else
229                         lss = RTA_DATA(tb[TCA_CBQ_LSSOPT]);
230         }
231         if (tb[TCA_CBQ_WRROPT]) {
232                 if (RTA_PAYLOAD(tb[TCA_CBQ_WRROPT]) < sizeof(*wrr))
233                         bb_error_msg(error, "wrr");
234                 else
235                         wrr = RTA_DATA(tb[TCA_CBQ_WRROPT]);
236         }
237         if (tb[TCA_CBQ_FOPT]) {
238                 if (RTA_PAYLOAD(tb[TCA_CBQ_FOPT]) < sizeof(*fopt))
239                         bb_error_msg(error, "fopt");
240                 else
241                         fopt = RTA_DATA(tb[TCA_CBQ_FOPT]);
242         }
243         if (tb[TCA_CBQ_OVL_STRATEGY]) {
244                 if (RTA_PAYLOAD(tb[TCA_CBQ_OVL_STRATEGY]) < sizeof(*ovl))
245                         bb_error_msg("CBQ: too short overlimit strategy %u/%u",
246                                 (unsigned) RTA_PAYLOAD(tb[TCA_CBQ_OVL_STRATEGY]),
247                                 (unsigned) sizeof(*ovl));
248                 else
249                         ovl = RTA_DATA(tb[TCA_CBQ_OVL_STRATEGY]);
250         }
251
252         if (r) {
253                 print_rate(buf, sizeof(buf), r->rate);
254                 printf("rate %s ", buf);
255                 if (show_details) {
256                         printf("cell %ub ", 1<<r->cell_log);
257                         if (r->mpu)
258                                 printf("mpu %ub ", r->mpu);
259                         if (r->overhead)
260                                 printf("overhead %ub ", r->overhead);
261                 }
262         }
263         if (lss && lss->flags) {
264                 bool comma = false;
265                 bb_putchar('(');
266                 if (lss->flags&TCF_CBQ_LSS_BOUNDED) {
267                         printf("bounded");
268                         comma = true;
269                 }
270                 if (lss->flags&TCF_CBQ_LSS_ISOLATED) {
271                         if (comma)
272                                 bb_putchar(',');
273                         printf("isolated");
274                 }
275                 printf(") ");
276         }
277         if (wrr) {
278                 if (wrr->priority != TC_CBQ_MAXPRIO)
279                         printf("prio %u", wrr->priority);
280                 else
281                         printf("prio no-transmit");
282                 if (show_details) {
283                         printf("/%u ", wrr->cpriority);
284                         if (wrr->weight != 1) {
285                                 print_rate(buf, sizeof(buf), wrr->weight);
286                                 printf("weight %s ", buf);
287                         }
288                         if (wrr->allot)
289                                 printf("allot %ub ", wrr->allot);
290                 }
291         }
292  done:
293         return 0;
294 }
295
296 static int print_qdisc(const struct sockaddr_nl *who UNUSED_PARAM,
297                                                 struct nlmsghdr *hdr, void *arg UNUSED_PARAM)
298 {
299         struct tcmsg *msg = NLMSG_DATA(hdr);
300         int len = hdr->nlmsg_len;
301         struct rtattr * tb[TCA_MAX+1];
302         char *name;
303
304         if (hdr->nlmsg_type != RTM_NEWQDISC && hdr->nlmsg_type != RTM_DELQDISC) {
305                 /* bb_error_msg("not a qdisc"); */
306                 return 0; /* ??? mimic upstream; should perhaps return -1 */
307         }
308         len -= NLMSG_LENGTH(sizeof(*msg));
309         if (len < 0) {
310                 /* bb_error_msg("wrong len %d", len); */
311                 return -1;
312         }
313         /* not the desired interface? */
314         if (filter_ifindex && filter_ifindex != msg->tcm_ifindex)
315                 return 0;
316         memset (tb, 0, sizeof(tb));
317         parse_rtattr(tb, TCA_MAX, TCA_RTA(msg), len);
318         if (tb[TCA_KIND] == NULL) {
319                 /* bb_error_msg("%s: NULL kind", "qdisc"); */
320                 return -1;
321         }
322         if (hdr->nlmsg_type == RTM_DELQDISC)
323                 printf("deleted ");
324         name = (char*)RTA_DATA(tb[TCA_KIND]);
325         printf("qdisc %s %x: ", name, msg->tcm_handle>>16);
326         if (filter_ifindex == 0)
327                 printf("dev %s ", ll_index_to_name(msg->tcm_ifindex));
328         if (msg->tcm_parent == TC_H_ROOT)
329                 printf("root ");
330         else if (msg->tcm_parent) {
331                 char *classid = print_tc_classid(msg->tcm_parent);
332                 printf("parent %s ", classid);
333                 if (ENABLE_FEATURE_CLEAN_UP)
334                         free(classid);
335         }
336         if (msg->tcm_info != 1)
337                 printf("refcnt %d ", msg->tcm_info);
338         if (tb[TCA_OPTIONS]) {
339                 static const char _q_[] ALIGN1 = "pfifo_fast\0""cbq\0";
340                 int qqq = index_in_strings(_q_, name);
341                 if (qqq == 0) { /* pfifo_fast aka prio */
342                         prio_print_opt(tb[TCA_OPTIONS]);
343                 } else if (qqq == 1) { /* class based queuing */
344                         cbq_print_opt(tb[TCA_OPTIONS]);
345                 } else
346                         bb_error_msg("unknown %s", name);
347         }
348         bb_putchar('\n');
349         return 0;
350 }
351
352 static int print_class(const struct sockaddr_nl *who UNUSED_PARAM,
353                                                 struct nlmsghdr *hdr, void *arg UNUSED_PARAM)
354 {
355         struct tcmsg *msg = NLMSG_DATA(hdr);
356         int len = hdr->nlmsg_len;
357         struct rtattr * tb[TCA_MAX+1];
358         char *name, *classid;
359
360         /*XXX Eventually factor out common code */
361
362         if (hdr->nlmsg_type != RTM_NEWTCLASS && hdr->nlmsg_type != RTM_DELTCLASS) {
363                 /* bb_error_msg("not a class"); */
364                 return 0; /* ??? mimic upstream; should perhaps return -1 */
365         }
366         len -= NLMSG_LENGTH(sizeof(*msg));
367         if (len < 0) {
368                 /* bb_error_msg("wrong len %d", len); */
369                 return -1;
370         }
371         /* not the desired interface? */
372         if (filter_qdisc && TC_H_MAJ(msg->tcm_handle^filter_qdisc))
373                 return 0;
374         memset (tb, 0, sizeof(tb));
375         parse_rtattr(tb, TCA_MAX, TCA_RTA(msg), len);
376         if (tb[TCA_KIND] == NULL) {
377                 /* bb_error_msg("%s: NULL kind", "class"); */
378                 return -1;
379         }
380         if (hdr->nlmsg_type == RTM_DELTCLASS)
381                 printf("deleted ");
382
383         name = (char*)RTA_DATA(tb[TCA_KIND]);
384         classid = !msg->tcm_handle ? NULL : print_tc_classid(
385                                 filter_qdisc ? TC_H_MIN(msg->tcm_parent) : msg->tcm_parent);
386         printf ("class %s %s", name, classid);
387         if (ENABLE_FEATURE_CLEAN_UP)
388                 free(classid);
389
390         if (filter_ifindex == 0)
391                 printf("dev %s ", ll_index_to_name(msg->tcm_ifindex));
392         if (msg->tcm_parent == TC_H_ROOT)
393                 printf("root ");
394         else if (msg->tcm_parent) {
395                 classid = print_tc_classid(filter_qdisc ?
396                                 TC_H_MIN(msg->tcm_parent) : msg->tcm_parent);
397                 printf("parent %s ", classid);
398                 if (ENABLE_FEATURE_CLEAN_UP)
399                         free(classid);
400         }
401         if (msg->tcm_info)
402                 printf("leaf %x ", msg->tcm_info >> 16);
403         /* Do that get_qdisc_kind(RTA_DATA(tb[TCA_KIND])).  */
404         if (tb[TCA_OPTIONS]) {
405                 static const char _q_[] ALIGN1 = "pfifo_fast\0""cbq\0";
406                 int qqq = index_in_strings(_q_, name);
407                 if (qqq == 0) { /* pfifo_fast aka prio */
408                         /* nothing. */ /*prio_print_opt(tb[TCA_OPTIONS]);*/
409                 } else if (qqq == 1) { /* class based queuing */
410                         /* cbq_print_copt() is identical to cbq_print_opt(). */
411                         cbq_print_opt(tb[TCA_OPTIONS]);
412                 } else
413                         bb_error_msg("unknown %s", name);
414         }
415         bb_putchar('\n');
416
417         return 0;
418 }
419
420 static int print_filter(const struct sockaddr_nl *who UNUSED_PARAM,
421                                                 struct nlmsghdr *hdr, void *arg UNUSED_PARAM)
422 {
423         return 0;
424 }
425
426 int tc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
427 int tc_main(int argc UNUSED_PARAM, char **argv)
428 {
429         static const char objects[] ALIGN1 =
430                 "qdisc\0""class\0""filter\0"
431                 ;
432         enum { OBJ_qdisc = 0, OBJ_class, OBJ_filter };
433         static const char commands[] ALIGN1 =
434                 "add\0""delete\0""change\0"
435                 "link\0" /* only qdisc */
436                 "replace\0"
437                 "show\0""list\0"
438                 ;
439         static const char args[] ALIGN1 =
440                 "dev\0" /* qdisc, class, filter */
441                 "root\0" /* class, filter */
442                 "parent\0" /* class, filter */
443                 "qdisc\0" /* class */
444                 "handle\0" /* change: qdisc, class(classid) list: filter */
445                 "classid\0" /* change: for class use "handle" */
446                 "preference\0""priority\0""protocol\0" /* filter */
447                 ;
448         enum { CMD_add = 0, CMD_del, CMD_change, CMD_link, CMD_replace, CMD_show };
449         enum { ARG_dev = 0, ARG_root, ARG_parent, ARG_qdisc,
450                         ARG_handle, ARG_classid, ARG_pref, ARG_prio, ARG_proto};
451         struct rtnl_handle rth;
452         struct tcmsg msg;
453         int ret, obj, cmd, arg;
454         char *dev = NULL;
455
456         INIT_G();
457
458         if (!*++argv)
459                 bb_show_usage();
460         xrtnl_open(&rth);
461         ret = EXIT_SUCCESS;
462
463         obj = index_in_substrings(objects, *argv++);
464
465         if (obj < 0)
466                 bb_show_usage();
467         if (!*argv)
468                 cmd = CMD_show; /* list is the default */
469         else {
470                 cmd = index_in_substrings(commands, *argv);
471                 if (cmd < 0)
472                         invarg_1_to_2(*argv, argv[-1]);
473                 argv++;
474         }
475         memset(&msg, 0, sizeof(msg));
476         msg.tcm_family = AF_UNSPEC;
477         ll_init_map(&rth);
478         while (*argv) {
479                 arg = index_in_substrings(args, *argv);
480                 if (arg == ARG_dev) {
481                         NEXT_ARG();
482                         if (dev)
483                                 duparg2("dev", *argv);
484                         dev = *argv++;
485                         msg.tcm_ifindex = xll_name_to_index(dev);
486                         if (cmd >= CMD_show)
487                                 filter_ifindex = msg.tcm_ifindex;
488                 } else
489                 if ((arg == ARG_qdisc && obj == OBJ_class && cmd >= CMD_show)
490                  || (arg == ARG_handle && obj == OBJ_qdisc && cmd == CMD_change)
491                 ) {
492                         NEXT_ARG();
493                         /* We don't care about duparg2("qdisc handle",*argv) for now */
494                         if (get_qdisc_handle(&filter_qdisc, *argv))
495                                 invarg_1_to_2(*argv, "qdisc");
496                 } else
497                 if (obj != OBJ_qdisc
498                  && (arg == ARG_root
499                     || arg == ARG_parent
500                     || (obj == OBJ_filter && arg >= ARG_pref)
501                     )
502                 ) {
503                         /* nothing */
504                 } else {
505                         invarg_1_to_2(*argv, "command");
506                 }
507                 NEXT_ARG();
508                 if (arg == ARG_root) {
509                         if (msg.tcm_parent)
510                                 duparg("parent", *argv);
511                         msg.tcm_parent = TC_H_ROOT;
512                         if (obj == OBJ_filter)
513                                 filter_parent = TC_H_ROOT;
514                 } else if (arg == ARG_parent) {
515                         uint32_t handle;
516                         if (msg.tcm_parent)
517                                 duparg(*argv, "parent");
518                         if (get_tc_classid(&handle, *argv))
519                                 invarg_1_to_2(*argv, "parent");
520                         msg.tcm_parent = handle;
521                         if (obj == OBJ_filter)
522                                 filter_parent = handle;
523                 } else if (arg == ARG_handle) { /* filter::list */
524                         if (msg.tcm_handle)
525                                 duparg(*argv, "handle");
526                         /* reject LONG_MIN || LONG_MAX */
527                         /* TODO: for fw
528                         slash = strchr(handle, '/');
529                         if (slash != NULL)
530                                    *slash = '\0';
531                          */
532                         msg.tcm_handle = get_u32(*argv, "handle");
533                         /* if (slash) {if (get_u32(uint32_t &mask, slash+1, NULL)) inv mask; addattr32(n, MAX_MSG, TCA_FW_MASK, mask); */
534                 } else if (arg == ARG_classid && obj == OBJ_class && cmd == CMD_change){
535                 } else if (arg == ARG_pref || arg == ARG_prio) { /* filter::list */
536                         if (filter_prio)
537                                 duparg(*argv, "priority");
538                         filter_prio = get_u32(*argv, "priority");
539                 } else if (arg == ARG_proto) { /* filter::list */
540                         uint16_t tmp;
541                         if (filter_proto)
542                                 duparg(*argv, "protocol");
543                         if (ll_proto_a2n(&tmp, *argv))
544                                 invarg_1_to_2(*argv, "protocol");
545                         filter_proto = tmp;
546                 }
547         }
548         if (cmd >= CMD_show) { /* show or list */
549                 if (obj == OBJ_filter)
550                         msg.tcm_info = TC_H_MAKE(filter_prio<<16, filter_proto);
551                 if (rtnl_dump_request(&rth, obj == OBJ_qdisc ? RTM_GETQDISC :
552                                                 obj == OBJ_class ? RTM_GETTCLASS : RTM_GETTFILTER,
553                                                 &msg, sizeof(msg)) < 0)
554                         bb_simple_perror_msg_and_die("can't send dump request");
555
556                 xrtnl_dump_filter(&rth, obj == OBJ_qdisc ? print_qdisc :
557                                                 obj == OBJ_class ? print_class : print_filter,
558                                                 NULL);
559         }
560         if (ENABLE_FEATURE_CLEAN_UP) {
561                 rtnl_close(&rth);
562         }
563         return ret;
564 }