CommandListener.cpp revision 2eab1f762badb7ba46b95716e62ea4548a979903
1/*
2 * Copyright (C) 2008 The Android Open Source Project
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// #define LOG_NDEBUG 0
18
19#include <stdlib.h>
20#include <sys/socket.h>
21#include <sys/types.h>
22#include <netinet/in.h>
23#include <arpa/inet.h>
24#include <dirent.h>
25#include <errno.h>
26#include <string.h>
27#include <fcntl.h>
28#include <linux/if.h>
29
30#define LOG_TAG "CommandListener"
31
32#include <cutils/log.h>
33#include <netutils/ifc.h>
34#include <sysutils/SocketClient.h>
35
36#include "CommandListener.h"
37#include "ResponseCode.h"
38#include "ThrottleController.h"
39#include "BandwidthController.h"
40#include "IdletimerController.h"
41#include "SecondaryTableController.h"
42#include "oem_iptables_hook.h"
43#include "NetdConstants.h"
44#include "FirewallController.h"
45
46TetherController *CommandListener::sTetherCtrl = NULL;
47NatController *CommandListener::sNatCtrl = NULL;
48PppController *CommandListener::sPppCtrl = NULL;
49PanController *CommandListener::sPanCtrl = NULL;
50SoftapController *CommandListener::sSoftapCtrl = NULL;
51BandwidthController * CommandListener::sBandwidthCtrl = NULL;
52IdletimerController * CommandListener::sIdletimerCtrl = NULL;
53InterfaceController *CommandListener::sInterfaceCtrl = NULL;
54ResolverController *CommandListener::sResolverCtrl = NULL;
55SecondaryTableController *CommandListener::sSecondaryTableCtrl = NULL;
56FirewallController *CommandListener::sFirewallCtrl = NULL;
57
58/**
59 * List of module chains to be created, along with explicit ordering. ORDERING
60 * IS CRITICAL, AND SHOULD BE TRIPLE-CHECKED WITH EACH CHANGE.
61 */
62static const char* FILTER_INPUT[] = {
63        // Bandwidth should always be early in input chain, to make sure we
64        // correctly count incoming traffic against data plan.
65        BandwidthController::LOCAL_INPUT,
66        FirewallController::LOCAL_INPUT,
67        NULL,
68};
69
70static const char* FILTER_FORWARD[] = {
71        OEM_IPTABLES_FILTER_FORWARD,
72        FirewallController::LOCAL_FORWARD,
73        BandwidthController::LOCAL_FORWARD,
74        NatController::LOCAL_FORWARD,
75        NULL,
76};
77
78static const char* FILTER_OUTPUT[] = {
79        OEM_IPTABLES_FILTER_OUTPUT,
80        FirewallController::LOCAL_OUTPUT,
81        BandwidthController::LOCAL_OUTPUT,
82        NULL,
83};
84
85static const char* RAW_PREROUTING[] = {
86        BandwidthController::LOCAL_RAW_PREROUTING,
87        NULL,
88};
89
90static const char* MANGLE_POSTROUTING[] = {
91        BandwidthController::LOCAL_MANGLE_POSTROUTING,
92        NULL,
93};
94
95static const char* NAT_PREROUTING[] = {
96        OEM_IPTABLES_NAT_PREROUTING,
97        IdletimerController::LOCAL_NAT_PREROUTING,
98        NULL,
99};
100
101static const char* NAT_POSTROUTING[] = {
102        IdletimerController::LOCAL_NAT_POSTROUTING,
103        NatController::LOCAL_NAT_POSTROUTING,
104        NULL,
105};
106
107static void createChildChains(IptablesTarget target, const char* table, const char* parentChain,
108        const char** childChains) {
109    const char** childChain = childChains;
110    do {
111        // Order is important:
112        // -D to delete any pre-existing jump rule (removes references
113        //    that would prevent -X from working)
114        // -F to flush any existing chain
115        // -X to delete any existing chain
116        // -N to create the chain
117        // -A to append the chain to parent
118
119        execIptablesSilently(target, "-t", table, "-D", parentChain, "-j", *childChain, NULL);
120        execIptablesSilently(target, "-t", table, "-F", *childChain, NULL);
121        execIptablesSilently(target, "-t", table, "-X", *childChain, NULL);
122        execIptables(target, "-t", table, "-N", *childChain, NULL);
123        execIptables(target, "-t", table, "-A", parentChain, "-j", *childChain, NULL);
124    } while (*(++childChain) != NULL);
125}
126
127CommandListener::CommandListener() :
128                 FrameworkListener("netd", true) {
129    registerCmd(new InterfaceCmd());
130    registerCmd(new IpFwdCmd());
131    registerCmd(new TetherCmd());
132    registerCmd(new NatCmd());
133    registerCmd(new ListTtysCmd());
134    registerCmd(new PppdCmd());
135    registerCmd(new PanCmd());
136    registerCmd(new SoftapCmd());
137    registerCmd(new BandwidthControlCmd());
138    registerCmd(new IdletimerControlCmd());
139    registerCmd(new ResolverCmd());
140    registerCmd(new FirewallCmd());
141
142    if (!sSecondaryTableCtrl)
143        sSecondaryTableCtrl = new SecondaryTableController();
144    if (!sTetherCtrl)
145        sTetherCtrl = new TetherController();
146    if (!sNatCtrl)
147        sNatCtrl = new NatController(sSecondaryTableCtrl);
148    if (!sPppCtrl)
149        sPppCtrl = new PppController();
150    if (!sPanCtrl)
151        sPanCtrl = new PanController();
152    if (!sSoftapCtrl)
153        sSoftapCtrl = new SoftapController();
154    if (!sBandwidthCtrl)
155        sBandwidthCtrl = new BandwidthController();
156    if (!sIdletimerCtrl)
157        sIdletimerCtrl = new IdletimerController();
158    if (!sResolverCtrl)
159        sResolverCtrl = new ResolverController();
160    if (!sFirewallCtrl)
161        sFirewallCtrl = new FirewallController();
162    if (!sInterfaceCtrl)
163        sInterfaceCtrl = new InterfaceController();
164
165    /*
166     * This is the only time we touch top-level chains in iptables; controllers
167     * should only mutate rules inside of their children chains, as created by
168     * the constants above.
169     *
170     * Modules should never ACCEPT packets (except in well-justified cases);
171     * they should instead defer to any remaining modules using RETURN, or
172     * otherwise DROP/REJECT.
173     */
174
175    // Create chains for children modules
176    createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT);
177    createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD);
178    createChildChains(V4V6, "filter", "OUTPUT", FILTER_OUTPUT);
179    createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING);
180    createChildChains(V4V6, "mangle", "POSTROUTING", MANGLE_POSTROUTING);
181    createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING);
182    createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING);
183
184    // Let each module setup their child chains
185    setupOemIptablesHook();
186
187    /* When enabled, DROPs all packets except those matching rules. */
188    sFirewallCtrl->setupIptablesHooks();
189
190    /* Does DROPs in FORWARD by default */
191    sNatCtrl->setupIptablesHooks();
192    /*
193     * Does REJECT in INPUT, OUTPUT. Does counting also.
194     * No DROP/REJECT allowed later in netfilter-flow hook order.
195     */
196    sBandwidthCtrl->setupIptablesHooks();
197    /*
198     * Counts in nat: PREROUTING, POSTROUTING.
199     * No DROP/REJECT allowed later in netfilter-flow hook order.
200     */
201    sIdletimerCtrl->setupIptablesHooks();
202
203    sBandwidthCtrl->enableBandwidthControl(false);
204}
205
206CommandListener::InterfaceCmd::InterfaceCmd() :
207                 NetdCommand("interface") {
208}
209
210int CommandListener::writeFile(const char *path, const char *value, int size) {
211    int fd = open(path, O_WRONLY);
212    if (fd < 0) {
213        ALOGE("Failed to open %s: %s", path, strerror(errno));
214        return -1;
215    }
216
217    if (write(fd, value, size) != size) {
218        ALOGE("Failed to write %s: %s", path, strerror(errno));
219        close(fd);
220        return -1;
221    }
222    close(fd);
223    return 0;
224}
225
226int CommandListener::InterfaceCmd::runCommand(SocketClient *cli,
227                                                      int argc, char **argv) {
228    if (argc < 2) {
229        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
230        return 0;
231    }
232
233    if (!strcmp(argv[1], "list")) {
234        DIR *d;
235        struct dirent *de;
236
237        if (!(d = opendir("/sys/class/net"))) {
238            cli->sendMsg(ResponseCode::OperationFailed, "Failed to open sysfs dir", true);
239            return 0;
240        }
241
242        while((de = readdir(d))) {
243            if (de->d_name[0] == '.')
244                continue;
245            cli->sendMsg(ResponseCode::InterfaceListResult, de->d_name, false);
246        }
247        closedir(d);
248        cli->sendMsg(ResponseCode::CommandOkay, "Interface list completed", false);
249        return 0;
250    } else if (!strcmp(argv[1], "readrxcounter")) {
251        if (argc != 3) {
252            cli->sendMsg(ResponseCode::CommandSyntaxError,
253                    "Usage: interface readrxcounter <interface>", false);
254            return 0;
255        }
256        unsigned long rx = 0, tx = 0;
257        if (readInterfaceCounters(argv[2], &rx, &tx)) {
258            cli->sendMsg(ResponseCode::OperationFailed, "Failed to read counters", true);
259            return 0;
260        }
261
262        char *msg;
263        asprintf(&msg, "%lu", rx);
264        cli->sendMsg(ResponseCode::InterfaceRxCounterResult, msg, false);
265        free(msg);
266
267        return 0;
268    } else if (!strcmp(argv[1], "readtxcounter")) {
269        if (argc != 3) {
270            cli->sendMsg(ResponseCode::CommandSyntaxError,
271                    "Usage: interface readtxcounter <interface>", false);
272            return 0;
273        }
274        unsigned long rx = 0, tx = 0;
275        if (readInterfaceCounters(argv[2], &rx, &tx)) {
276            cli->sendMsg(ResponseCode::OperationFailed, "Failed to read counters", true);
277            return 0;
278        }
279
280        char *msg = NULL;
281        asprintf(&msg, "%lu", tx);
282        cli->sendMsg(ResponseCode::InterfaceTxCounterResult, msg, false);
283        free(msg);
284        return 0;
285    } else if (!strcmp(argv[1], "getthrottle")) {
286        if (argc != 4 || (argc == 4 && (strcmp(argv[3], "rx") && (strcmp(argv[3], "tx"))))) {
287            cli->sendMsg(ResponseCode::CommandSyntaxError,
288                    "Usage: interface getthrottle <interface> <rx|tx>", false);
289            return 0;
290        }
291        int val = 0;
292        int rc = 0;
293        int voldRc = ResponseCode::InterfaceRxThrottleResult;
294
295        if (!strcmp(argv[3], "rx")) {
296            rc = ThrottleController::getInterfaceRxThrottle(argv[2], &val);
297        } else {
298            rc = ThrottleController::getInterfaceTxThrottle(argv[2], &val);
299            voldRc = ResponseCode::InterfaceTxThrottleResult;
300        }
301        if (rc) {
302            cli->sendMsg(ResponseCode::OperationFailed, "Failed to get throttle", true);
303        } else {
304            char *msg = NULL;
305            asprintf(&msg, "%u", val);
306            cli->sendMsg(voldRc, msg, false);
307            free(msg);
308            return 0;
309        }
310        return 0;
311    } else if (!strcmp(argv[1], "setthrottle")) {
312        if (argc != 5) {
313            cli->sendMsg(ResponseCode::CommandSyntaxError,
314                    "Usage: interface setthrottle <interface> <rx_kbps> <tx_kbps>", false);
315            return 0;
316        }
317        if (ThrottleController::setInterfaceThrottle(argv[2], atoi(argv[3]), atoi(argv[4]))) {
318            cli->sendMsg(ResponseCode::OperationFailed, "Failed to set throttle", true);
319        } else {
320            cli->sendMsg(ResponseCode::CommandOkay, "Interface throttling set", false);
321        }
322        return 0;
323    } else if (!strcmp(argv[1], "driver")) {
324        int rc;
325        char *rbuf;
326
327        if (argc < 4) {
328            cli->sendMsg(ResponseCode::CommandSyntaxError,
329                    "Usage: interface driver <interface> <cmd> <args>", false);
330            return 0;
331        }
332        rc = sInterfaceCtrl->interfaceCommand(argc, argv, &rbuf);
333        if (rc) {
334            cli->sendMsg(ResponseCode::OperationFailed, "Failed to execute command", true);
335        } else {
336            cli->sendMsg(ResponseCode::CommandOkay, rbuf, false);
337        }
338        return 0;
339    } else {
340        /*
341         * These commands take a minimum of 3 arguments
342         */
343        if (argc < 3) {
344            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
345            return 0;
346        }
347
348        //     0       1       2        3          4           5     6      7
349        // interface route add/remove iface default/secondary dest prefix gateway
350        if (!strcmp(argv[1], "route")) {
351            int prefix_length = 0;
352            if (argc < 8) {
353                cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
354                return 0;
355            }
356            if (sscanf(argv[6], "%d", &prefix_length) != 1) {
357                cli->sendMsg(ResponseCode::CommandParameterError, "Invalid route prefix", false);
358                return 0;
359            }
360            if (!strcmp(argv[2], "add")) {
361                if (!strcmp(argv[4], "default")) {
362                    if (ifc_add_route(argv[3], argv[5], prefix_length, argv[7])) {
363                        cli->sendMsg(ResponseCode::OperationFailed,
364                                "Failed to add route to default table", true);
365                    } else {
366                        cli->sendMsg(ResponseCode::CommandOkay,
367                                "Route added to default table", false);
368                    }
369                } else if (!strcmp(argv[4], "secondary")) {
370                    return sSecondaryTableCtrl->addRoute(cli, argv[3], argv[5],
371                            prefix_length, argv[7]);
372                } else {
373                    cli->sendMsg(ResponseCode::CommandParameterError,
374                            "Invalid route type, expecting 'default' or 'secondary'", false);
375                    return 0;
376                }
377            } else if (!strcmp(argv[2], "remove")) {
378                if (!strcmp(argv[4], "default")) {
379                    if (ifc_remove_route(argv[3], argv[5], prefix_length, argv[7])) {
380                        cli->sendMsg(ResponseCode::OperationFailed,
381                                "Failed to remove route from default table", true);
382                    } else {
383                        cli->sendMsg(ResponseCode::CommandOkay,
384                                "Route removed from default table", false);
385                    }
386                } else if (!strcmp(argv[4], "secondary")) {
387                    return sSecondaryTableCtrl->removeRoute(cli, argv[3], argv[5],
388                            prefix_length, argv[7]);
389                } else {
390                    cli->sendMsg(ResponseCode::CommandParameterError,
391                            "Invalid route type, expecting 'default' or 'secondary'", false);
392                    return 0;
393                }
394            } else {
395                cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown interface cmd", false);
396            }
397            return 0;
398        }
399
400        if (!strcmp(argv[1], "getcfg")) {
401            struct in_addr addr;
402            int prefixLength;
403            unsigned char hwaddr[6];
404            unsigned flags = 0;
405
406            ifc_init();
407            memset(hwaddr, 0, sizeof(hwaddr));
408
409            if (ifc_get_info(argv[2], &addr.s_addr, &prefixLength, &flags)) {
410                cli->sendMsg(ResponseCode::OperationFailed, "Interface not found", true);
411                ifc_close();
412                return 0;
413            }
414
415            if (ifc_get_hwaddr(argv[2], (void *) hwaddr)) {
416                ALOGW("Failed to retrieve HW addr for %s (%s)", argv[2], strerror(errno));
417            }
418
419            char *addr_s = strdup(inet_ntoa(addr));
420            const char *updown, *brdcst, *loopbk, *ppp, *running, *multi;
421
422            updown =  (flags & IFF_UP)           ? "up" : "down";
423            brdcst =  (flags & IFF_BROADCAST)    ? " broadcast" : "";
424            loopbk =  (flags & IFF_LOOPBACK)     ? " loopback" : "";
425            ppp =     (flags & IFF_POINTOPOINT)  ? " point-to-point" : "";
426            running = (flags & IFF_RUNNING)      ? " running" : "";
427            multi =   (flags & IFF_MULTICAST)    ? " multicast" : "";
428
429            char *flag_s;
430
431            asprintf(&flag_s, "%s%s%s%s%s%s", updown, brdcst, loopbk, ppp, running, multi);
432
433            char *msg = NULL;
434            asprintf(&msg, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x %s %d %s",
435                     hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5],
436                     addr_s, prefixLength, flag_s);
437
438            cli->sendMsg(ResponseCode::InterfaceGetCfgResult, msg, false);
439
440            free(addr_s);
441            free(flag_s);
442            free(msg);
443
444            ifc_close();
445            return 0;
446        } else if (!strcmp(argv[1], "setcfg")) {
447            // arglist: iface [addr prefixLength] flags
448            if (argc < 4) {
449                cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
450                return 0;
451            }
452            ALOGD("Setting iface cfg");
453
454            struct in_addr addr;
455            unsigned flags = 0;
456            int index = 5;
457
458            ifc_init();
459
460            if (!inet_aton(argv[3], &addr)) {
461                // Handle flags only case
462                index = 3;
463            } else {
464                if (ifc_set_addr(argv[2], addr.s_addr)) {
465                    cli->sendMsg(ResponseCode::OperationFailed, "Failed to set address", true);
466                    ifc_close();
467                    return 0;
468                }
469
470                // Set prefix length on a non zero address
471                if (addr.s_addr != 0 && ifc_set_prefixLength(argv[2], atoi(argv[4]))) {
472                   cli->sendMsg(ResponseCode::OperationFailed, "Failed to set prefixLength", true);
473                   ifc_close();
474                   return 0;
475               }
476            }
477
478            /* Process flags */
479            for (int i = index; i < argc; i++) {
480                char *flag = argv[i];
481                if (!strcmp(flag, "up")) {
482                    ALOGD("Trying to bring up %s", argv[2]);
483                    if (ifc_up(argv[2])) {
484                        ALOGE("Error upping interface");
485                        cli->sendMsg(ResponseCode::OperationFailed, "Failed to up interface", true);
486                        ifc_close();
487                        return 0;
488                    }
489                } else if (!strcmp(flag, "down")) {
490                    ALOGD("Trying to bring down %s", argv[2]);
491                    if (ifc_down(argv[2])) {
492                        ALOGE("Error downing interface");
493                        cli->sendMsg(ResponseCode::OperationFailed, "Failed to down interface", true);
494                        ifc_close();
495                        return 0;
496                    }
497                } else if (!strcmp(flag, "broadcast")) {
498                    // currently ignored
499                } else if (!strcmp(flag, "multicast")) {
500                    // currently ignored
501                } else if (!strcmp(flag, "running")) {
502                    // currently ignored
503                } else if (!strcmp(flag, "loopback")) {
504                    // currently ignored
505                } else if (!strcmp(flag, "point-to-point")) {
506                    // currently ignored
507                } else {
508                    cli->sendMsg(ResponseCode::CommandParameterError, "Flag unsupported", false);
509                    ifc_close();
510                    return 0;
511                }
512            }
513
514            cli->sendMsg(ResponseCode::CommandOkay, "Interface configuration set", false);
515            ifc_close();
516            return 0;
517        } else if (!strcmp(argv[1], "clearaddrs")) {
518            // arglist: iface
519            ALOGD("Clearing all IP addresses on %s", argv[2]);
520
521            ifc_clear_addresses(argv[2]);
522
523            cli->sendMsg(ResponseCode::CommandOkay, "Interface IP addresses cleared", false);
524            return 0;
525        } else if (!strcmp(argv[1], "ipv6privacyextensions")) {
526            if (argc != 4) {
527                cli->sendMsg(ResponseCode::CommandSyntaxError,
528                        "Usage: interface ipv6privacyextensions <interface> <enable|disable>",
529                        false);
530                return 0;
531            }
532
533            char *tmp;
534            asprintf(&tmp, "/proc/sys/net/ipv6/conf/%s/use_tempaddr", argv[2]);
535
536            if (writeFile(tmp, !strncmp(argv[3], "enable", 7) ? "2" : "0", 1) < 0) {
537                free(tmp);
538                cli->sendMsg(ResponseCode::OperationFailed,
539                        "Failed to set ipv6 privacy extensions", true);
540                return 0;
541            }
542
543            free(tmp);
544            cli->sendMsg(ResponseCode::CommandOkay, "IPv6 privacy extensions changed", false);
545            return 0;
546        } else if (!strcmp(argv[1], "ipv6")) {
547            if (argc != 4) {
548                cli->sendMsg(ResponseCode::CommandSyntaxError,
549                        "Usage: interface ipv6 <interface> <enable|disable>",
550                        false);
551                return 0;
552            }
553
554            char *tmp;
555            asprintf(&tmp, "/proc/sys/net/ipv6/conf/%s/disable_ipv6", argv[2]);
556
557            if (writeFile(tmp, !strncmp(argv[3], "enable", 7) ? "0" : "1", 1) < 0) {
558                free(tmp);
559                cli->sendMsg(ResponseCode::OperationFailed,
560                        "Failed to change IPv6 state", true);
561                return 0;
562            }
563
564            free(tmp);
565            cli->sendMsg(ResponseCode::CommandOkay, "IPv6 state changed", false);
566            return 0;
567        } else {
568            cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown interface cmd", false);
569            return 0;
570        }
571    }
572    return 0;
573}
574
575
576CommandListener::ListTtysCmd::ListTtysCmd() :
577                 NetdCommand("list_ttys") {
578}
579
580int CommandListener::ListTtysCmd::runCommand(SocketClient *cli,
581                                             int argc, char **argv) {
582    TtyCollection *tlist = sPppCtrl->getTtyList();
583    TtyCollection::iterator it;
584
585    for (it = tlist->begin(); it != tlist->end(); ++it) {
586        cli->sendMsg(ResponseCode::TtyListResult, *it, false);
587    }
588
589    cli->sendMsg(ResponseCode::CommandOkay, "Ttys listed.", false);
590    return 0;
591}
592
593CommandListener::IpFwdCmd::IpFwdCmd() :
594                 NetdCommand("ipfwd") {
595}
596
597int CommandListener::IpFwdCmd::runCommand(SocketClient *cli,
598                                                      int argc, char **argv) {
599    int rc = 0;
600
601    if (argc < 2) {
602        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
603        return 0;
604    }
605
606    if (!strcmp(argv[1], "status")) {
607        char *tmp = NULL;
608
609        asprintf(&tmp, "Forwarding %s", (sTetherCtrl->getIpFwdEnabled() ? "enabled" : "disabled"));
610        cli->sendMsg(ResponseCode::IpFwdStatusResult, tmp, false);
611        free(tmp);
612        return 0;
613    } else if (!strcmp(argv[1], "enable")) {
614        rc = sTetherCtrl->setIpFwdEnabled(true);
615    } else if (!strcmp(argv[1], "disable")) {
616        rc = sTetherCtrl->setIpFwdEnabled(false);
617    } else {
618        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown ipfwd cmd", false);
619        return 0;
620    }
621
622    if (!rc) {
623        cli->sendMsg(ResponseCode::CommandOkay, "ipfwd operation succeeded", false);
624    } else {
625        cli->sendMsg(ResponseCode::OperationFailed, "ipfwd operation failed", true);
626    }
627
628    return 0;
629}
630
631CommandListener::TetherCmd::TetherCmd() :
632                 NetdCommand("tether") {
633}
634
635int CommandListener::TetherCmd::runCommand(SocketClient *cli,
636                                                      int argc, char **argv) {
637    int rc = 0;
638
639    if (argc < 2) {
640        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
641        return 0;
642    }
643
644    if (!strcmp(argv[1], "stop")) {
645        rc = sTetherCtrl->stopTethering();
646    } else if(!strcmp(argv[1], "start-reverse")) {
647        ALOGD("CommandListener::TetherCmd::run, call startReverseTethering, iface:%s", argv[2]);
648        sTetherCtrl->startReverseTethering(argv[2]);
649    } else if (!strcmp(argv[1], "stop-reverse")) {
650        ALOGD("CommandListener::TetherCmd::run, call stopReverseTethering");
651        rc = sTetherCtrl->stopReverseTethering();
652    } else if (!strcmp(argv[1], "status")) {
653        char *tmp = NULL;
654
655        asprintf(&tmp, "Tethering services %s",
656                 (sTetherCtrl->isTetheringStarted() ? "started" : "stopped"));
657        cli->sendMsg(ResponseCode::TetherStatusResult, tmp, false);
658        free(tmp);
659        return 0;
660    } else {
661        /*
662         * These commands take a minimum of 4 arguments
663         */
664        if (argc < 4) {
665            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
666            return 0;
667        }
668
669        if (!strcmp(argv[1], "start")) {
670            if (argc % 2 == 1) {
671                cli->sendMsg(ResponseCode::CommandSyntaxError, "Bad number of arguments", false);
672                return 0;
673            }
674
675            int num_addrs = argc - 2;
676            int arg_index = 2;
677            int array_index = 0;
678            in_addr *addrs = (in_addr *)malloc(sizeof(in_addr) * num_addrs);
679            while (array_index < num_addrs) {
680                if (!inet_aton(argv[arg_index++], &(addrs[array_index++]))) {
681                    cli->sendMsg(ResponseCode::CommandParameterError, "Invalid address", false);
682                    free(addrs);
683                    return 0;
684                }
685            }
686            rc = sTetherCtrl->startTethering(num_addrs, addrs);
687            free(addrs);
688        } else if (!strcmp(argv[1], "interface")) {
689            if (!strcmp(argv[2], "add")) {
690                rc = sTetherCtrl->tetherInterface(argv[3]);
691            } else if (!strcmp(argv[2], "remove")) {
692                rc = sTetherCtrl->untetherInterface(argv[3]);
693            } else if (!strcmp(argv[2], "list")) {
694                InterfaceCollection *ilist = sTetherCtrl->getTetheredInterfaceList();
695                InterfaceCollection::iterator it;
696
697                for (it = ilist->begin(); it != ilist->end(); ++it) {
698                    cli->sendMsg(ResponseCode::TetherInterfaceListResult, *it, false);
699                }
700            } else {
701                cli->sendMsg(ResponseCode::CommandParameterError,
702                             "Unknown tether interface operation", false);
703                return 0;
704            }
705        } else if (!strcmp(argv[1], "dns")) {
706            if (!strcmp(argv[2], "set")) {
707                rc = sTetherCtrl->setDnsForwarders(&argv[3], argc - 3);
708            } else if (!strcmp(argv[2], "list")) {
709                NetAddressCollection *dlist = sTetherCtrl->getDnsForwarders();
710                NetAddressCollection::iterator it;
711
712                for (it = dlist->begin(); it != dlist->end(); ++it) {
713                    cli->sendMsg(ResponseCode::TetherDnsFwdTgtListResult, inet_ntoa(*it), false);
714                }
715            } else {
716                cli->sendMsg(ResponseCode::CommandParameterError,
717                             "Unknown tether interface operation", false);
718                return 0;
719            }
720        } else {
721            cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown tether cmd", false);
722            return 0;
723        }
724    }
725
726    if (!rc) {
727        cli->sendMsg(ResponseCode::CommandOkay, "Tether operation succeeded", false);
728    } else {
729        cli->sendMsg(ResponseCode::OperationFailed, "Tether operation failed", true);
730    }
731
732    return 0;
733}
734
735CommandListener::NatCmd::NatCmd() :
736                 NetdCommand("nat") {
737}
738
739int CommandListener::NatCmd::runCommand(SocketClient *cli,
740                                                      int argc, char **argv) {
741    int rc = 0;
742
743    if (argc < 5) {
744        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
745        return 0;
746    }
747
748    if (!strcmp(argv[1], "enable")) {
749        rc = sNatCtrl->enableNat(argc, argv);
750        if(!rc) {
751            /* Ignore ifaces for now. */
752            rc = sBandwidthCtrl->setGlobalAlertInForwardChain();
753        }
754    } else if (!strcmp(argv[1], "disable")) {
755        /* Ignore ifaces for now. */
756        rc = sBandwidthCtrl->removeGlobalAlertInForwardChain();
757        rc |= sNatCtrl->disableNat(argc, argv);
758    } else {
759        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown nat cmd", false);
760        return 0;
761    }
762
763    if (!rc) {
764        cli->sendMsg(ResponseCode::CommandOkay, "Nat operation succeeded", false);
765    } else {
766        cli->sendMsg(ResponseCode::OperationFailed, "Nat operation failed", true);
767    }
768
769    return 0;
770}
771
772CommandListener::PppdCmd::PppdCmd() :
773                 NetdCommand("pppd") {
774}
775
776int CommandListener::PppdCmd::runCommand(SocketClient *cli,
777                                                      int argc, char **argv) {
778    int rc = 0;
779
780    if (argc < 3) {
781        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
782        return 0;
783    }
784
785    if (!strcmp(argv[1], "attach")) {
786        struct in_addr l, r, dns1, dns2;
787
788        memset(&dns1, sizeof(struct in_addr), 0);
789        memset(&dns2, sizeof(struct in_addr), 0);
790
791        if (!inet_aton(argv[3], &l)) {
792            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid local address", false);
793            return 0;
794        }
795        if (!inet_aton(argv[4], &r)) {
796            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid remote address", false);
797            return 0;
798        }
799        if ((argc > 3) && (!inet_aton(argv[5], &dns1))) {
800            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid dns1 address", false);
801            return 0;
802        }
803        if ((argc > 4) && (!inet_aton(argv[6], &dns2))) {
804            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid dns2 address", false);
805            return 0;
806        }
807        rc = sPppCtrl->attachPppd(argv[2], l, r, dns1, dns2);
808    } else if (!strcmp(argv[1], "detach")) {
809        rc = sPppCtrl->detachPppd(argv[2]);
810    } else {
811        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown pppd cmd", false);
812        return 0;
813    }
814
815    if (!rc) {
816        cli->sendMsg(ResponseCode::CommandOkay, "Pppd operation succeeded", false);
817    } else {
818        cli->sendMsg(ResponseCode::OperationFailed, "Pppd operation failed", true);
819    }
820
821    return 0;
822}
823
824CommandListener::PanCmd::PanCmd() :
825                 NetdCommand("pan") {
826}
827
828int CommandListener::PanCmd::runCommand(SocketClient *cli,
829                                        int argc, char **argv) {
830    int rc = 0;
831
832    if (argc < 2) {
833        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
834        return 0;
835    }
836
837    if (!strcmp(argv[1], "start")) {
838        rc = sPanCtrl->startPan();
839    } else if (!strcmp(argv[1], "stop")) {
840        rc = sPanCtrl->stopPan();
841    } else if (!strcmp(argv[1], "status")) {
842        char *tmp = NULL;
843
844        asprintf(&tmp, "Pan services %s",
845                 (sPanCtrl->isPanStarted() ? "started" : "stopped"));
846        cli->sendMsg(ResponseCode::PanStatusResult, tmp, false);
847        free(tmp);
848        return 0;
849    } else {
850        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown pan cmd", false);
851        return 0;
852    }
853
854    if (!rc) {
855        cli->sendMsg(ResponseCode::CommandOkay, "Pan operation succeeded", false);
856    } else {
857        cli->sendMsg(ResponseCode::OperationFailed, "Pan operation failed", true);
858    }
859
860    return 0;
861}
862
863CommandListener::SoftapCmd::SoftapCmd() :
864                 NetdCommand("softap") {
865}
866
867int CommandListener::SoftapCmd::runCommand(SocketClient *cli,
868                                        int argc, char **argv) {
869    int rc = 0, flag = 0;
870    char *retbuf = NULL;
871
872    if (argc < 2) {
873        cli->sendMsg(ResponseCode::CommandSyntaxError, "Softap Missing argument", false);
874        return 0;
875    }
876
877    if (!strcmp(argv[1], "startap")) {
878        rc = sSoftapCtrl->startSoftap();
879    } else if (!strcmp(argv[1], "stopap")) {
880        rc = sSoftapCtrl->stopSoftap();
881    } else if (!strcmp(argv[1], "fwreload")) {
882        rc = sSoftapCtrl->fwReloadSoftap(argc, argv);
883    } else if (!strcmp(argv[1], "clients")) {
884        rc = sSoftapCtrl->clientsSoftap(&retbuf);
885        if (!rc) {
886            cli->sendMsg(ResponseCode::CommandOkay, retbuf, false);
887            free(retbuf);
888            return 0;
889        }
890    } else if (!strcmp(argv[1], "status")) {
891        asprintf(&retbuf, "Softap service %s",
892                 (sSoftapCtrl->isSoftapStarted() ? "started" : "stopped"));
893        cli->sendMsg(ResponseCode::SoftapStatusResult, retbuf, false);
894        free(retbuf);
895        return 0;
896    } else if (!strcmp(argv[1], "set")) {
897        rc = sSoftapCtrl->setSoftap(argc, argv);
898    } else {
899        cli->sendMsg(ResponseCode::CommandSyntaxError, "Softap Unknown cmd", false);
900        return 0;
901    }
902
903    if (!rc) {
904        cli->sendMsg(ResponseCode::CommandOkay, "Softap operation succeeded", false);
905    } else {
906        cli->sendMsg(ResponseCode::OperationFailed, "Softap operation failed", true);
907    }
908
909    return 0;
910}
911
912CommandListener::ResolverCmd::ResolverCmd() :
913        NetdCommand("resolver") {
914}
915
916int CommandListener::ResolverCmd::runCommand(SocketClient *cli, int argc, char **argv) {
917    int rc = 0;
918    struct in_addr addr;
919
920    if (argc < 2) {
921        cli->sendMsg(ResponseCode::CommandSyntaxError, "Resolver missing arguments", false);
922        return 0;
923    }
924
925    if (!strcmp(argv[1], "setdefaultif")) { // "resolver setdefaultif <iface>"
926        if (argc == 3) {
927            rc = sResolverCtrl->setDefaultInterface(argv[2]);
928        } else {
929            cli->sendMsg(ResponseCode::CommandSyntaxError,
930                    "Wrong number of arguments to resolver setdefaultif", false);
931            return 0;
932        }
933    } else if (!strcmp(argv[1], "setifdns")) { // "resolver setifdns <iface> <dns1> <dns2> ..."
934        if (argc >= 4) {
935            rc = sResolverCtrl->setInterfaceDnsServers(argv[2], &argv[3], argc - 3);
936        } else {
937            cli->sendMsg(ResponseCode::CommandSyntaxError,
938                    "Wrong number of arguments to resolver setifdns", false);
939            return 0;
940        }
941
942        // set the address of the interface to which the name servers
943        // are bound. Required in order to bind to right interface when
944        // doing the dns query.
945        if (!rc) {
946            ifc_init();
947            ifc_get_info(argv[2], &addr.s_addr, NULL, 0);
948
949            rc = sResolverCtrl->setInterfaceAddress(argv[2], &addr);
950        }
951    } else if (!strcmp(argv[1], "flushdefaultif")) { // "resolver flushdefaultif"
952        if (argc == 2) {
953            rc = sResolverCtrl->flushDefaultDnsCache();
954        } else {
955            cli->sendMsg(ResponseCode::CommandSyntaxError,
956                    "Wrong number of arguments to resolver flushdefaultif", false);
957            return 0;
958        }
959    } else if (!strcmp(argv[1], "flushif")) { // "resolver flushif <iface>"
960        if (argc == 3) {
961            rc = sResolverCtrl->flushInterfaceDnsCache(argv[2]);
962        } else {
963            cli->sendMsg(ResponseCode::CommandSyntaxError,
964                    "Wrong number of arguments to resolver setdefaultif", false);
965            return 0;
966        }
967    } else {
968        cli->sendMsg(ResponseCode::CommandSyntaxError,"Resolver unknown command", false);
969        return 0;
970    }
971
972    if (!rc) {
973        cli->sendMsg(ResponseCode::CommandOkay, "Resolver command succeeded", false);
974    } else {
975        cli->sendMsg(ResponseCode::OperationFailed, "Resolver command failed", true);
976    }
977
978    return 0;
979}
980
981int CommandListener::readInterfaceCounters(const char *iface, unsigned long *rx, unsigned long *tx) {
982    FILE *fp = fopen("/proc/net/dev", "r");
983    if (!fp) {
984        ALOGE("Failed to open /proc/net/dev (%s)", strerror(errno));
985        return -1;
986    }
987
988    char buffer[512];
989
990    fgets(buffer, sizeof(buffer), fp); // Header 1
991    fgets(buffer, sizeof(buffer), fp); // Header 2
992    while(fgets(buffer, sizeof(buffer), fp)) {
993        buffer[strlen(buffer)-1] = '\0';
994
995        char name[31];
996        unsigned long d;
997        sscanf(buffer, "%30s %lu %lu %lu %lu %lu %lu %lu %lu %lu",
998                name, rx, &d, &d, &d, &d, &d, &d, &d, tx);
999        char *rxString = strchr(name, ':');
1000        *rxString = '\0';
1001        rxString++;
1002        // when the rx count gets too big it changes from "name: 999" to "name:1000"
1003        // and the sscanf munge the two together.  Detect that and fix
1004        // note that all the %lu will be off by one and the real tx value will be in d
1005        if (*rxString != '\0') {
1006            *tx = d;
1007            sscanf(rxString, "%20lu", rx);
1008        }
1009        if (strcmp(name, iface)) {
1010            continue;
1011        }
1012        fclose(fp);
1013        return 0;
1014    }
1015
1016    fclose(fp);
1017    *rx = 0;
1018    *tx = 0;
1019    return 0;
1020}
1021
1022CommandListener::BandwidthControlCmd::BandwidthControlCmd() :
1023    NetdCommand("bandwidth") {
1024}
1025
1026void CommandListener::BandwidthControlCmd::sendGenericSyntaxError(SocketClient *cli, const char *usageMsg) {
1027    char *msg;
1028    asprintf(&msg, "Usage: bandwidth %s", usageMsg);
1029    cli->sendMsg(ResponseCode::CommandSyntaxError, msg, false);
1030    free(msg);
1031}
1032
1033void CommandListener::BandwidthControlCmd::sendGenericOkFail(SocketClient *cli, int cond) {
1034    if (!cond) {
1035        cli->sendMsg(ResponseCode::CommandOkay, "Bandwidth command succeeeded", false);
1036    } else {
1037        cli->sendMsg(ResponseCode::OperationFailed, "Bandwidth command failed", false);
1038    }
1039}
1040
1041void CommandListener::BandwidthControlCmd::sendGenericOpFailed(SocketClient *cli, const char *errMsg) {
1042    cli->sendMsg(ResponseCode::OperationFailed, errMsg, false);
1043}
1044
1045int CommandListener::BandwidthControlCmd::runCommand(SocketClient *cli, int argc, char **argv) {
1046    if (argc < 2) {
1047        sendGenericSyntaxError(cli, "<cmds> <args...>");
1048        return 0;
1049    }
1050
1051    ALOGV("bwctrlcmd: argc=%d %s %s ...", argc, argv[0], argv[1]);
1052
1053    if (!strcmp(argv[1], "enable")) {
1054        int rc = sBandwidthCtrl->enableBandwidthControl(true);
1055        sendGenericOkFail(cli, rc);
1056        return 0;
1057
1058    }
1059    if (!strcmp(argv[1], "disable")) {
1060        int rc = sBandwidthCtrl->disableBandwidthControl();
1061        sendGenericOkFail(cli, rc);
1062        return 0;
1063
1064    }
1065    if (!strcmp(argv[1], "removequota") || !strcmp(argv[1], "rq")) {
1066        if (argc != 3) {
1067            sendGenericSyntaxError(cli, "removequota <interface>");
1068            return 0;
1069        }
1070        int rc = sBandwidthCtrl->removeInterfaceSharedQuota(argv[2]);
1071        sendGenericOkFail(cli, rc);
1072        return 0;
1073
1074    }
1075    if (!strcmp(argv[1], "getquota") || !strcmp(argv[1], "gq")) {
1076        int64_t bytes;
1077        if (argc != 2) {
1078            sendGenericSyntaxError(cli, "getquota");
1079            return 0;
1080        }
1081        int rc = sBandwidthCtrl->getInterfaceSharedQuota(&bytes);
1082        if (rc) {
1083            sendGenericOpFailed(cli, "Failed to get quota");
1084            return 0;
1085        }
1086
1087        char *msg;
1088        asprintf(&msg, "%lld", bytes);
1089        cli->sendMsg(ResponseCode::QuotaCounterResult, msg, false);
1090        free(msg);
1091        return 0;
1092
1093    }
1094    if (!strcmp(argv[1], "getiquota") || !strcmp(argv[1], "giq")) {
1095        int64_t bytes;
1096        if (argc != 3) {
1097            sendGenericSyntaxError(cli, "getiquota <iface>");
1098            return 0;
1099        }
1100
1101        int rc = sBandwidthCtrl->getInterfaceQuota(argv[2], &bytes);
1102        if (rc) {
1103            sendGenericOpFailed(cli, "Failed to get quota");
1104            return 0;
1105        }
1106        char *msg;
1107        asprintf(&msg, "%lld", bytes);
1108        cli->sendMsg(ResponseCode::QuotaCounterResult, msg, false);
1109        free(msg);
1110        return 0;
1111
1112    }
1113    if (!strcmp(argv[1], "setquota") || !strcmp(argv[1], "sq")) {
1114        if (argc != 4) {
1115            sendGenericSyntaxError(cli, "setquota <interface> <bytes>");
1116            return 0;
1117        }
1118        int rc = sBandwidthCtrl->setInterfaceSharedQuota(argv[2], atoll(argv[3]));
1119        sendGenericOkFail(cli, rc);
1120        return 0;
1121    }
1122    if (!strcmp(argv[1], "setquotas") || !strcmp(argv[1], "sqs")) {
1123        int rc;
1124        if (argc < 4) {
1125            sendGenericSyntaxError(cli, "setquotas <bytes> <interface> ...");
1126            return 0;
1127        }
1128
1129        for (int q = 3; argc >= 4; q++, argc--) {
1130            rc = sBandwidthCtrl->setInterfaceSharedQuota(argv[q], atoll(argv[2]));
1131            if (rc) {
1132                char *msg;
1133                asprintf(&msg, "bandwidth setquotas %s %s failed", argv[2], argv[q]);
1134                cli->sendMsg(ResponseCode::OperationFailed,
1135                             msg, false);
1136                free(msg);
1137                return 0;
1138            }
1139        }
1140        sendGenericOkFail(cli, rc);
1141        return 0;
1142
1143    }
1144    if (!strcmp(argv[1], "removequotas") || !strcmp(argv[1], "rqs")) {
1145        int rc;
1146        if (argc < 3) {
1147            sendGenericSyntaxError(cli, "removequotas <interface> ...");
1148            return 0;
1149        }
1150
1151        for (int q = 2; argc >= 3; q++, argc--) {
1152            rc = sBandwidthCtrl->removeInterfaceSharedQuota(argv[q]);
1153            if (rc) {
1154                char *msg;
1155                asprintf(&msg, "bandwidth removequotas %s failed", argv[q]);
1156                cli->sendMsg(ResponseCode::OperationFailed,
1157                             msg, false);
1158                free(msg);
1159                return 0;
1160            }
1161        }
1162        sendGenericOkFail(cli, rc);
1163        return 0;
1164
1165    }
1166    if (!strcmp(argv[1], "removeiquota") || !strcmp(argv[1], "riq")) {
1167        if (argc != 3) {
1168            sendGenericSyntaxError(cli, "removeiquota <interface>");
1169            return 0;
1170        }
1171        int rc = sBandwidthCtrl->removeInterfaceQuota(argv[2]);
1172        sendGenericOkFail(cli, rc);
1173        return 0;
1174
1175    }
1176    if (!strcmp(argv[1], "setiquota") || !strcmp(argv[1], "siq")) {
1177        if (argc != 4) {
1178            sendGenericSyntaxError(cli, "setiquota <interface> <bytes>");
1179            return 0;
1180        }
1181        int rc = sBandwidthCtrl->setInterfaceQuota(argv[2], atoll(argv[3]));
1182        sendGenericOkFail(cli, rc);
1183        return 0;
1184
1185    }
1186    if (!strcmp(argv[1], "addnaughtyapps") || !strcmp(argv[1], "ana")) {
1187        if (argc < 3) {
1188            sendGenericSyntaxError(cli, "addnaughtyapps <appUid> ...");
1189            return 0;
1190        }
1191        int rc = sBandwidthCtrl->addNaughtyApps(argc - 2, argv + 2);
1192        sendGenericOkFail(cli, rc);
1193        return 0;
1194
1195
1196    }
1197    if (!strcmp(argv[1], "removenaughtyapps") || !strcmp(argv[1], "rna")) {
1198        if (argc < 3) {
1199            sendGenericSyntaxError(cli, "removenaughtyapps <appUid> ...");
1200            return 0;
1201        }
1202        int rc = sBandwidthCtrl->removeNaughtyApps(argc - 2, argv + 2);
1203        sendGenericOkFail(cli, rc);
1204        return 0;
1205
1206    }
1207    if (!strcmp(argv[1], "setglobalalert") || !strcmp(argv[1], "sga")) {
1208        if (argc != 3) {
1209            sendGenericSyntaxError(cli, "setglobalalert <bytes>");
1210            return 0;
1211        }
1212        int rc = sBandwidthCtrl->setGlobalAlert(atoll(argv[2]));
1213        sendGenericOkFail(cli, rc);
1214        return 0;
1215
1216    }
1217    if (!strcmp(argv[1], "debugsettetherglobalalert") || !strcmp(argv[1], "dstga")) {
1218        if (argc != 4) {
1219            sendGenericSyntaxError(cli, "debugsettetherglobalalert <interface0> <interface1>");
1220            return 0;
1221        }
1222        /* We ignore the interfaces for now. */
1223        int rc = sBandwidthCtrl->setGlobalAlertInForwardChain();
1224        sendGenericOkFail(cli, rc);
1225        return 0;
1226
1227    }
1228    if (!strcmp(argv[1], "removeglobalalert") || !strcmp(argv[1], "rga")) {
1229        if (argc != 2) {
1230            sendGenericSyntaxError(cli, "removeglobalalert");
1231            return 0;
1232        }
1233        int rc = sBandwidthCtrl->removeGlobalAlert();
1234        sendGenericOkFail(cli, rc);
1235        return 0;
1236
1237    }
1238    if (!strcmp(argv[1], "debugremovetetherglobalalert") || !strcmp(argv[1], "drtga")) {
1239        if (argc != 4) {
1240            sendGenericSyntaxError(cli, "debugremovetetherglobalalert <interface0> <interface1>");
1241            return 0;
1242        }
1243        /* We ignore the interfaces for now. */
1244        int rc = sBandwidthCtrl->removeGlobalAlertInForwardChain();
1245        sendGenericOkFail(cli, rc);
1246        return 0;
1247
1248    }
1249    if (!strcmp(argv[1], "setsharedalert") || !strcmp(argv[1], "ssa")) {
1250        if (argc != 3) {
1251            sendGenericSyntaxError(cli, "setsharedalert <bytes>");
1252            return 0;
1253        }
1254        int rc = sBandwidthCtrl->setSharedAlert(atoll(argv[2]));
1255        sendGenericOkFail(cli, rc);
1256        return 0;
1257
1258    }
1259    if (!strcmp(argv[1], "removesharedalert") || !strcmp(argv[1], "rsa")) {
1260        if (argc != 2) {
1261            sendGenericSyntaxError(cli, "removesharedalert");
1262            return 0;
1263        }
1264        int rc = sBandwidthCtrl->removeSharedAlert();
1265        sendGenericOkFail(cli, rc);
1266        return 0;
1267
1268    }
1269    if (!strcmp(argv[1], "setinterfacealert") || !strcmp(argv[1], "sia")) {
1270        if (argc != 4) {
1271            sendGenericSyntaxError(cli, "setinterfacealert <interface> <bytes>");
1272            return 0;
1273        }
1274        int rc = sBandwidthCtrl->setInterfaceAlert(argv[2], atoll(argv[3]));
1275        sendGenericOkFail(cli, rc);
1276        return 0;
1277
1278    }
1279    if (!strcmp(argv[1], "removeinterfacealert") || !strcmp(argv[1], "ria")) {
1280        if (argc != 3) {
1281            sendGenericSyntaxError(cli, "removeinterfacealert <interface>");
1282            return 0;
1283        }
1284        int rc = sBandwidthCtrl->removeInterfaceAlert(argv[2]);
1285        sendGenericOkFail(cli, rc);
1286        return 0;
1287
1288    }
1289    if (!strcmp(argv[1], "gettetherstats") || !strcmp(argv[1], "gts")) {
1290        BandwidthController::TetherStats tetherStats;
1291        std::string extraProcessingInfo = "";
1292        if (argc != 4) {
1293            sendGenericSyntaxError(cli, "gettetherstats <interface0> <interface1>");
1294            return 0;
1295        }
1296
1297        tetherStats.ifaceIn = argv[2];
1298        tetherStats.ifaceOut = argv[3];
1299        int rc = sBandwidthCtrl->getTetherStats(tetherStats, extraProcessingInfo);
1300        if (rc) {
1301                extraProcessingInfo.insert(0, "Failed to get tethering stats.\n");
1302                sendGenericOpFailed(cli, extraProcessingInfo.c_str());
1303            return 0;
1304        }
1305
1306        char *msg = tetherStats.getStatsLine();
1307        cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
1308        free(msg);
1309        return 0;
1310
1311    }
1312
1313    cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown bandwidth cmd", false);
1314    return 0;
1315}
1316
1317CommandListener::IdletimerControlCmd::IdletimerControlCmd() :
1318    NetdCommand("idletimer") {
1319}
1320
1321int CommandListener::IdletimerControlCmd::runCommand(SocketClient *cli, int argc, char **argv) {
1322  // TODO(ashish): Change the error statements
1323    if (argc < 2) {
1324        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
1325        return 0;
1326    }
1327
1328    ALOGV("idletimerctrlcmd: argc=%d %s %s ...", argc, argv[0], argv[1]);
1329
1330    if (!strcmp(argv[1], "enable")) {
1331      if (0 != sIdletimerCtrl->enableIdletimerControl()) {
1332        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
1333      } else {
1334        cli->sendMsg(ResponseCode::CommandOkay, "Enable success", false);
1335      }
1336      return 0;
1337
1338    }
1339    if (!strcmp(argv[1], "disable")) {
1340      if (0 != sIdletimerCtrl->disableIdletimerControl()) {
1341        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
1342      } else {
1343        cli->sendMsg(ResponseCode::CommandOkay, "Disable success", false);
1344      }
1345      return 0;
1346    }
1347    if (!strcmp(argv[1], "add")) {
1348        if (argc != 5) {
1349            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
1350            return 0;
1351        }
1352        if(0 != sIdletimerCtrl->addInterfaceIdletimer(
1353                                        argv[2], atoi(argv[3]), argv[4])) {
1354          cli->sendMsg(ResponseCode::OperationFailed, "Failed to add interface", false);
1355        } else {
1356          cli->sendMsg(ResponseCode::CommandOkay,  "Add success", false);
1357        }
1358        return 0;
1359    }
1360    if (!strcmp(argv[1], "remove")) {
1361        if (argc != 5) {
1362            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
1363            return 0;
1364        }
1365        // ashish: fixme timeout
1366        if (0 != sIdletimerCtrl->removeInterfaceIdletimer(
1367                                        argv[2], atoi(argv[3]), argv[4])) {
1368          cli->sendMsg(ResponseCode::OperationFailed, "Failed to remove interface", false);
1369        } else {
1370          cli->sendMsg(ResponseCode::CommandOkay, "Remove success", false);
1371        }
1372        return 0;
1373    }
1374
1375    cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown idletimer cmd", false);
1376    return 0;
1377}
1378
1379CommandListener::FirewallCmd::FirewallCmd() :
1380    NetdCommand("firewall") {
1381}
1382
1383int CommandListener::FirewallCmd::sendGenericOkFail(SocketClient *cli, int cond) {
1384    if (!cond) {
1385        cli->sendMsg(ResponseCode::CommandOkay, "Firewall command succeeded", false);
1386    } else {
1387        cli->sendMsg(ResponseCode::OperationFailed, "Firewall command failed", false);
1388    }
1389    return 0;
1390}
1391
1392FirewallRule CommandListener::FirewallCmd::parseRule(const char* arg) {
1393    if (!strcmp(arg, "allow")) {
1394        return ALLOW;
1395    } else {
1396        return DENY;
1397    }
1398}
1399
1400int CommandListener::FirewallCmd::runCommand(SocketClient *cli, int argc,
1401        char **argv) {
1402    if (argc < 2) {
1403        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing command", false);
1404        return 0;
1405    }
1406
1407    if (!strcmp(argv[1], "enable")) {
1408        int res = sFirewallCtrl->enableFirewall();
1409        return sendGenericOkFail(cli, res);
1410    }
1411    if (!strcmp(argv[1], "disable")) {
1412        int res = sFirewallCtrl->disableFirewall();
1413        return sendGenericOkFail(cli, res);
1414    }
1415    if (!strcmp(argv[1], "is_enabled")) {
1416        int res = sFirewallCtrl->isFirewallEnabled();
1417        return sendGenericOkFail(cli, res);
1418    }
1419
1420    if (!strcmp(argv[1], "set_interface_rule")) {
1421        if (argc != 4) {
1422            cli->sendMsg(ResponseCode::CommandSyntaxError,
1423                         "Usage: firewall set_interface_rule <rmnet0> <allow|deny>", false);
1424            return 0;
1425        }
1426
1427        const char* iface = argv[2];
1428        FirewallRule rule = parseRule(argv[3]);
1429
1430        int res = sFirewallCtrl->setInterfaceRule(iface, rule);
1431        return sendGenericOkFail(cli, res);
1432    }
1433
1434    if (!strcmp(argv[1], "set_egress_source_rule")) {
1435        if (argc != 4) {
1436            cli->sendMsg(ResponseCode::CommandSyntaxError,
1437                         "Usage: firewall set_egress_source_rule <192.168.0.1> <allow|deny>",
1438                         false);
1439            return 0;
1440        }
1441
1442        const char* addr = argv[2];
1443        FirewallRule rule = parseRule(argv[3]);
1444
1445        int res = sFirewallCtrl->setEgressSourceRule(addr, rule);
1446        return sendGenericOkFail(cli, res);
1447    }
1448
1449    if (!strcmp(argv[1], "set_egress_dest_rule")) {
1450        if (argc != 5) {
1451            cli->sendMsg(ResponseCode::CommandSyntaxError,
1452                         "Usage: firewall set_egress_dest_rule <192.168.0.1> <80> <allow|deny>",
1453                         false);
1454            return 0;
1455        }
1456
1457        const char* addr = argv[2];
1458        int port = atoi(argv[3]);
1459        FirewallRule rule = parseRule(argv[4]);
1460
1461        int res = 0;
1462        res |= sFirewallCtrl->setEgressDestRule(addr, PROTOCOL_TCP, port, rule);
1463        res |= sFirewallCtrl->setEgressDestRule(addr, PROTOCOL_UDP, port, rule);
1464        return sendGenericOkFail(cli, res);
1465    }
1466
1467    if (!strcmp(argv[1], "set_uid_rule")) {
1468        if (argc != 4) {
1469            cli->sendMsg(ResponseCode::CommandSyntaxError,
1470                         "Usage: firewall set_uid_rule <1000> <allow|deny>",
1471                         false);
1472            return 0;
1473        }
1474
1475        int uid = atoi(argv[2]);
1476        FirewallRule rule = parseRule(argv[3]);
1477
1478        int res = sFirewallCtrl->setUidRule(uid, rule);
1479        return sendGenericOkFail(cli, res);
1480    }
1481
1482    cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown command", false);
1483    return 0;
1484}
1485