CommandListener.cpp 38.7 KB
Newer Older
San Mehat's avatar
San Mehat committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18
// #define LOG_NDEBUG 0

San Mehat's avatar
San Mehat committed
19 20 21 22 23 24 25
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
26
#include <string.h>
27
#include <fcntl.h>
28 29
#include <linux/if.h>

San Mehat's avatar
San Mehat committed
30 31
#define LOG_TAG "CommandListener"

32 33
#include <cutils/log.h>
#include <netutils/ifc.h>
San Mehat's avatar
San Mehat committed
34 35 36 37
#include <sysutils/SocketClient.h>

#include "CommandListener.h"
#include "ResponseCode.h"
San Mehat's avatar
San Mehat committed
38
#include "ThrottleController.h"
39
#include "BandwidthController.h"
San Mehat's avatar
San Mehat committed
40

San Mehat's avatar
San Mehat committed
41

42

43
TetherController *CommandListener::sTetherCtrl = NULL;
San Mehat's avatar
San Mehat committed
44
NatController *CommandListener::sNatCtrl = NULL;
45
PppController *CommandListener::sPppCtrl = NULL;
46
PanController *CommandListener::sPanCtrl = NULL;
47
SoftapController *CommandListener::sSoftapCtrl = NULL;
48
BandwidthController * CommandListener::sBandwidthCtrl = NULL;
Mattias Falk's avatar
Mattias Falk committed
49
ResolverController *CommandListener::sResolverCtrl = NULL;
50

San Mehat's avatar
San Mehat committed
51 52
CommandListener::CommandListener() :
                 FrameworkListener("netd") {
53
    registerCmd(new InterfaceCmd());
San Mehat's avatar
San Mehat committed
54 55 56
    registerCmd(new IpFwdCmd());
    registerCmd(new TetherCmd());
    registerCmd(new NatCmd());
57 58
    registerCmd(new ListTtysCmd());
    registerCmd(new PppdCmd());
59
    registerCmd(new PanCmd());
60
    registerCmd(new SoftapCmd());
61
    registerCmd(new BandwidthControlCmd());
Mattias Falk's avatar
Mattias Falk committed
62
    registerCmd(new ResolverCmd());
63 64 65

    if (!sTetherCtrl)
        sTetherCtrl = new TetherController();
San Mehat's avatar
San Mehat committed
66 67
    if (!sNatCtrl)
        sNatCtrl = new NatController();
68 69
    if (!sPppCtrl)
        sPppCtrl = new PppController();
70 71
    if (!sPanCtrl)
        sPanCtrl = new PanController();
72 73
    if (!sSoftapCtrl)
        sSoftapCtrl = new SoftapController();
74 75
    if (!sBandwidthCtrl)
        sBandwidthCtrl = new BandwidthController();
Mattias Falk's avatar
Mattias Falk committed
76 77
    if (!sResolverCtrl)
        sResolverCtrl = new ResolverController();
San Mehat's avatar
San Mehat committed
78 79
}

80 81
CommandListener::InterfaceCmd::InterfaceCmd() :
                 NetdCommand("interface") {
San Mehat's avatar
San Mehat committed
82 83
}

repo sync's avatar
repo sync committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
int CommandListener::writeFile(const char *path, const char *value, int size) {
    int fd = open(path, O_WRONLY);
    if (fd < 0) {
        LOGE("Failed to open %s: %s", path, strerror(errno));
        return -1;
    }

    if (write(fd, value, size) != size) {
        LOGE("Failed to write %s: %s", path, strerror(errno));
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}

100
int CommandListener::InterfaceCmd::runCommand(SocketClient *cli,
San Mehat's avatar
San Mehat committed
101
                                                      int argc, char **argv) {
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

    if (!strcmp(argv[1], "list")) {
        DIR *d;
        struct dirent *de;

        if (!(d = opendir("/sys/class/net"))) {
            cli->sendMsg(ResponseCode::OperationFailed, "Failed to open sysfs dir", true);
            return 0;
        }

        while((de = readdir(d))) {
            if (de->d_name[0] == '.')
                continue;
            cli->sendMsg(ResponseCode::InterfaceListResult, de->d_name, false);
        }
        closedir(d);
        cli->sendMsg(ResponseCode::CommandOkay, "Interface list completed", false);
        return 0;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    } else if (!strcmp(argv[1], "readrxcounter")) {
        if (argc != 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Usage: interface readrxcounter <interface>", false);
            return 0;
        }
        unsigned long rx = 0, tx = 0;
        if (readInterfaceCounters(argv[2], &rx, &tx)) {
            cli->sendMsg(ResponseCode::OperationFailed, "Failed to read counters", true);
            return 0;
        }

        char *msg;
        asprintf(&msg, "%lu", rx);
        cli->sendMsg(ResponseCode::InterfaceRxCounterResult, msg, false);
        free(msg);

        return 0;
    } else if (!strcmp(argv[1], "readtxcounter")) {
        if (argc != 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Usage: interface readtxcounter <interface>", false);
            return 0;
        }
        unsigned long rx = 0, tx = 0;
        if (readInterfaceCounters(argv[2], &rx, &tx)) {
            cli->sendMsg(ResponseCode::OperationFailed, "Failed to read counters", true);
            return 0;
        }

        char *msg = NULL;
        asprintf(&msg, "%lu", tx);
        cli->sendMsg(ResponseCode::InterfaceTxCounterResult, msg, false);
        free(msg);
        return 0;
    } else if (!strcmp(argv[1], "getthrottle")) {
San Mehat's avatar
San Mehat committed
160
        if (argc != 4 || (argc == 4 && (strcmp(argv[3], "rx") && (strcmp(argv[3], "tx"))))) {
161 162 163 164
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Usage: interface getthrottle <interface> <rx|tx>", false);
            return 0;
        }
San Mehat's avatar
San Mehat committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        int val = 0;
        int rc = 0;
        int voldRc = ResponseCode::InterfaceRxThrottleResult;

        if (!strcmp(argv[3], "rx")) {
            rc = ThrottleController::getInterfaceRxThrottle(argv[2], &val);
        } else {
            rc = ThrottleController::getInterfaceTxThrottle(argv[2], &val);
            voldRc = ResponseCode::InterfaceTxThrottleResult;
        }
        if (rc) {
            cli->sendMsg(ResponseCode::OperationFailed, "Failed to get throttle", true);
        } else {
            char *msg = NULL;
            asprintf(&msg, "%u", val);
            cli->sendMsg(voldRc, msg, false);
            free(msg);
            return 0;
        }
184 185 186 187
        return 0;
    } else if (!strcmp(argv[1], "setthrottle")) {
        if (argc != 5) {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
San Mehat's avatar
San Mehat committed
188
                    "Usage: interface setthrottle <interface> <rx_kbps> <tx_kbps>", false);
189 190
            return 0;
        }
San Mehat's avatar
San Mehat committed
191 192 193 194 195
        if (ThrottleController::setInterfaceThrottle(argv[2], atoi(argv[3]), atoi(argv[4]))) {
            cli->sendMsg(ResponseCode::OperationFailed, "Failed to set throttle", true);
        } else {
            cli->sendMsg(ResponseCode::CommandOkay, "Interface throttling set", false);
        }
196
        return 0;
197 198 199 200 201 202 203 204
    } else {
        /*
         * These commands take a minimum of 3 arguments
         */
        if (argc < 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
            return 0;
        }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

        if (!strcmp(argv[1], "route")) {
            int prefix_length = 0;
            if (argc < 7) {
                cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
                return 0;
            }
            if (sscanf(argv[5], "%d", &prefix_length) != 1) {
                cli->sendMsg(ResponseCode::CommandParameterError, "Invalid route prefix", false);
                return 0;
            }
            if (!strcmp(argv[2], "add")) {
                if (ifc_add_route(argv[3], argv[4], prefix_length, argv[6])) {
                    cli->sendMsg(ResponseCode::OperationFailed, "Failed to add route", true);
                } else {
                    cli->sendMsg(ResponseCode::CommandOkay, "Route added", false);
                }
            } else if (!strcmp(argv[2], "remove")) {
                if (ifc_remove_route(argv[3], argv[4], prefix_length, argv[6])) {
                    cli->sendMsg(ResponseCode::OperationFailed, "Failed to remove route", true);
                } else {
                    cli->sendMsg(ResponseCode::CommandOkay, "Route removed", false);
                }
            } else {
                cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown interface cmd", false);
            }
            return 0;
        }

234
        if (!strcmp(argv[1], "getcfg")) {
235 236
            struct in_addr addr;
            int prefixLength;
237 238 239 240 241 242
            unsigned char hwaddr[6];
            unsigned flags = 0;

            ifc_init();
            memset(hwaddr, 0, sizeof(hwaddr));

243
            if (ifc_get_info(argv[2], &addr.s_addr, &prefixLength, &flags)) {
244
                cli->sendMsg(ResponseCode::OperationFailed, "Interface not found", true);
245
                ifc_close();
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                return 0;
            }

            if (ifc_get_hwaddr(argv[2], (void *) hwaddr)) {
                LOGW("Failed to retrieve HW addr for %s (%s)", argv[2], strerror(errno));
            }

            char *addr_s = strdup(inet_ntoa(addr));
            const char *updown, *brdcst, *loopbk, *ppp, *running, *multi;

            updown =  (flags & IFF_UP)           ? "up" : "down";
            brdcst =  (flags & IFF_BROADCAST)    ? " broadcast" : "";
            loopbk =  (flags & IFF_LOOPBACK)     ? " loopback" : "";
            ppp =     (flags & IFF_POINTOPOINT)  ? " point-to-point" : "";
            running = (flags & IFF_RUNNING)      ? " running" : "";
            multi =   (flags & IFF_MULTICAST)    ? " multicast" : "";

            char *flag_s;

265
            asprintf(&flag_s, "[%s%s%s%s%s%s]", updown, brdcst, loopbk, ppp, running, multi);
266 267

            char *msg = NULL;
268
            asprintf(&msg, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x %s %d %s",
269
                     hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5],
270
                     addr_s, prefixLength, flag_s);
271

272
            cli->sendMsg(ResponseCode::InterfaceGetCfgResult, msg, false);
273 274 275 276

            free(addr_s);
            free(flag_s);
            free(msg);
277 278

            ifc_close();
279 280
            return 0;
        } else if (!strcmp(argv[1], "setcfg")) {
281
            // arglist: iface addr prefixLength [flags]
282 283 284 285
            if (argc < 5) {
                cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
                return 0;
            }
286
            LOGD("Setting iface cfg");
287

288
            struct in_addr addr;
289 290 291 292 293 294 295 296 297 298
            unsigned flags = 0;

            if (!inet_aton(argv[3], &addr)) {
                cli->sendMsg(ResponseCode::CommandParameterError, "Invalid address", false);
                return 0;
            }

            ifc_init();
            if (ifc_set_addr(argv[2], addr.s_addr)) {
                cli->sendMsg(ResponseCode::OperationFailed, "Failed to set address", true);
299
                ifc_close();
300 301 302
                return 0;
            }

303 304
            //Set prefix length on a non zero address
            if (addr.s_addr != 0 && ifc_set_prefixLength(argv[2], atoi(argv[4]))) {
305
                cli->sendMsg(ResponseCode::OperationFailed, "Failed to set prefixLength", true);
306
                ifc_close();
307 308 309 310
                return 0;
            }

            /* Process flags */
311 312
            /* read from "[XX" arg to "YY]" arg */
            bool bStarted = false;
313
            for (int i = 5; i < argc; i++) {
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
                char *flag = argv[i];
                if (!bStarted) {
                    if (*flag == '[') {
                        flag++;
                        bStarted = true;
                    } else {
                        continue;
                    }
                }
                int len = strlen(flag);
                if (flag[len-1] == ']') {
                    i = argc;  // stop after this loop
                    flag[len-1] = 0;
                }
                if (!strcmp(flag, "up")) {
                    LOGD("Trying to bring up %s", argv[2]);
330 331 332
                    if (ifc_up(argv[2])) {
                        LOGE("Error upping interface");
                        cli->sendMsg(ResponseCode::OperationFailed, "Failed to up interface", true);
333
                        ifc_close();
334 335
                        return 0;
                    }
336 337
                } else if (!strcmp(flag, "down")) {
                    LOGD("Trying to bring down %s", argv[2]);
338 339 340
                    if (ifc_down(argv[2])) {
                        LOGE("Error downing interface");
                        cli->sendMsg(ResponseCode::OperationFailed, "Failed to down interface", true);
341
                        ifc_close();
342 343
                        return 0;
                    }
344 345 346 347
                } else if (!strcmp(flag, "broadcast")) {
                    LOGD("broadcast flag ignored");
                } else if (!strcmp(flag, "multicast")) {
                    LOGD("multicast flag ignored");
348 349
                } else {
                    cli->sendMsg(ResponseCode::CommandParameterError, "Flag unsupported", false);
350
                    ifc_close();
351 352 353
                    return 0;
                }
            }
354

355
            cli->sendMsg(ResponseCode::CommandOkay, "Interface configuration set", false);
356 357 358 359 360 361
            ifc_close();
            return 0;
        } else if (!strcmp(argv[1], "clearaddrs")) {
            // arglist: iface
            LOGD("Clearing all IP addresses on %s", argv[2]);

362 363
            ifc_clear_addresses(argv[2]);

364
            cli->sendMsg(ResponseCode::CommandOkay, "Interface IP addresses cleared", false);
365
            return 0;
366 367 368 369 370 371 372 373
        } else if (!strcmp(argv[1], "ipv6privacyextensions")) {
            if (argc != 4) {
                cli->sendMsg(ResponseCode::CommandSyntaxError,
                        "Usage: interface ipv6privacyextensions <interface> <enable|disable>",
                        false);
                return 0;
            }

repo sync's avatar
repo sync committed
374
            char *tmp;
375
            asprintf(&tmp, "/proc/sys/net/ipv6/conf/%s/use_tempaddr", argv[2]);
repo sync's avatar
repo sync committed
376 377

            if (writeFile(tmp, !strncmp(argv[3], "enable", 7) ? "2" : "0", 1) < 0) {
378 379 380 381 382 383
                free(tmp);
                cli->sendMsg(ResponseCode::OperationFailed,
                        "Failed to set ipv6 privacy extensions", true);
                return 0;
            }

repo sync's avatar
repo sync committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
            free(tmp);
            cli->sendMsg(ResponseCode::CommandOkay, "IPv6 privacy extensions changed", false);
            return 0;
        } else if (!strcmp(argv[1], "ipv6")) {
            if (argc != 4) {
                cli->sendMsg(ResponseCode::CommandSyntaxError,
                        "Usage: interface ipv6 <interface> <enable|disable>",
                        false);
                return 0;
            }

            char *tmp;
            asprintf(&tmp, "/proc/sys/net/ipv6/conf/%s/disable_ipv6", argv[2]);

            if (writeFile(tmp, !strncmp(argv[3], "enable", 7) ? "0" : "1", 1) < 0) {
399 400
                free(tmp);
                cli->sendMsg(ResponseCode::OperationFailed,
repo sync's avatar
repo sync committed
401
                        "Failed to change IPv6 state", true);
402 403
                return 0;
            }
repo sync's avatar
repo sync committed
404

405
            free(tmp);
repo sync's avatar
repo sync committed
406
            cli->sendMsg(ResponseCode::CommandOkay, "IPv6 state changed", false);
407
            return 0;
408 409 410 411 412
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown interface cmd", false);
            return 0;
        }
    }
San Mehat's avatar
San Mehat committed
413 414 415
    return 0;
}

416

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
CommandListener::ListTtysCmd::ListTtysCmd() :
                 NetdCommand("list_ttys") {
}

int CommandListener::ListTtysCmd::runCommand(SocketClient *cli,
                                             int argc, char **argv) {
    TtyCollection *tlist = sPppCtrl->getTtyList();
    TtyCollection::iterator it;

    for (it = tlist->begin(); it != tlist->end(); ++it) {
        cli->sendMsg(ResponseCode::TtyListResult, *it, false);
    }

    cli->sendMsg(ResponseCode::CommandOkay, "Ttys listed.", false);
    return 0;
}

San Mehat's avatar
San Mehat committed
434 435 436 437 438 439
CommandListener::IpFwdCmd::IpFwdCmd() :
                 NetdCommand("ipfwd") {
}

int CommandListener::IpFwdCmd::runCommand(SocketClient *cli,
                                                      int argc, char **argv) {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    int rc = 0;

    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

    if (!strcmp(argv[1], "status")) {
        char *tmp = NULL;

        asprintf(&tmp, "Forwarding %s", (sTetherCtrl->getIpFwdEnabled() ? "enabled" : "disabled"));
        cli->sendMsg(ResponseCode::IpFwdStatusResult, tmp, false);
        free(tmp);
        return 0;
    } else if (!strcmp(argv[1], "enable")) {
        rc = sTetherCtrl->setIpFwdEnabled(true);
    } else if (!strcmp(argv[1], "disable")) {
        rc = sTetherCtrl->setIpFwdEnabled(false);
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown ipfwd cmd", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "ipfwd operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "ipfwd operation failed", true);
    }
San Mehat's avatar
San Mehat committed
468 469 470 471 472 473 474 475 476 477

    return 0;
}

CommandListener::TetherCmd::TetherCmd() :
                 NetdCommand("tether") {
}

int CommandListener::TetherCmd::runCommand(SocketClient *cli,
                                                      int argc, char **argv) {
478 479
    int rc = 0;

San Mehat's avatar
San Mehat committed
480 481 482 483 484
    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

485 486
    if (!strcmp(argv[1], "stop")) {
        rc = sTetherCtrl->stopTethering();
San Mehat's avatar
San Mehat committed
487
    } else if (!strcmp(argv[1], "status")) {
488 489 490 491 492 493
        char *tmp = NULL;

        asprintf(&tmp, "Tethering services %s",
                 (sTetherCtrl->isTetheringStarted() ? "started" : "stopped"));
        cli->sendMsg(ResponseCode::TetherStatusResult, tmp, false);
        free(tmp);
San Mehat's avatar
San Mehat committed
494
        return 0;
495 496 497 498 499 500 501 502 503 504
    } else {
        /*
         * These commands take a minimum of 4 arguments
         */
        if (argc < 4) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
            return 0;
        }

        if (!strcmp(argv[1], "start")) {
505 506
            if (argc % 2 == 1) {
                cli->sendMsg(ResponseCode::CommandSyntaxError, "Bad number of arguments", false);
507 508
                return 0;
            }
509 510 511 512 513 514 515 516 517 518 519

            int num_addrs = argc - 2;
            int arg_index = 2;
            int array_index = 0;
            in_addr *addrs = (in_addr *)malloc(sizeof(in_addr) * num_addrs);
            while (array_index < num_addrs) {
                if (!inet_aton(argv[arg_index++], &(addrs[array_index++]))) {
                    cli->sendMsg(ResponseCode::CommandParameterError, "Invalid address", false);
                    free(addrs);
                    return 0;
                }
520
            }
521 522
            rc = sTetherCtrl->startTethering(num_addrs, addrs);
            free(addrs);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        } else if (!strcmp(argv[1], "interface")) {
            if (!strcmp(argv[2], "add")) {
                rc = sTetherCtrl->tetherInterface(argv[3]);
            } else if (!strcmp(argv[2], "remove")) {
                rc = sTetherCtrl->untetherInterface(argv[3]);
            } else if (!strcmp(argv[2], "list")) {
                InterfaceCollection *ilist = sTetherCtrl->getTetheredInterfaceList();
                InterfaceCollection::iterator it;

                for (it = ilist->begin(); it != ilist->end(); ++it) {
                    cli->sendMsg(ResponseCode::TetherInterfaceListResult, *it, false);
                }
            } else {
                cli->sendMsg(ResponseCode::CommandParameterError,
                             "Unknown tether interface operation", false);
                return 0;
            }
        } else if (!strcmp(argv[1], "dns")) {
            if (!strcmp(argv[2], "set")) {
                rc = sTetherCtrl->setDnsForwarders(&argv[3], argc - 3);
            } else if (!strcmp(argv[2], "list")) {
                NetAddressCollection *dlist = sTetherCtrl->getDnsForwarders();
                NetAddressCollection::iterator it;

                for (it = dlist->begin(); it != dlist->end(); ++it) {
                    cli->sendMsg(ResponseCode::TetherDnsFwdTgtListResult, inet_ntoa(*it), false);
                }
            } else {
                cli->sendMsg(ResponseCode::CommandParameterError,
                             "Unknown tether interface operation", false);
                return 0;
            }
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown tether cmd", false);
            return 0;
        }
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Tether operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Tether operation failed", true);
San Mehat's avatar
San Mehat committed
565 566 567 568 569 570 571 572 573 574 575
    }

    return 0;
}

CommandListener::NatCmd::NatCmd() :
                 NetdCommand("nat") {
}

int CommandListener::NatCmd::runCommand(SocketClient *cli,
                                                      int argc, char **argv) {
576 577 578 579 580 581 582
    int rc = 0;

    if (argc < 3) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

San Mehat's avatar
San Mehat committed
583 584
    if (!strcmp(argv[1], "enable")) {
        rc = sNatCtrl->enableNat(argv[2], argv[3]);
585 586 587 588
        if(!rc) {
            /* Ignore ifaces for now. */
            rc = sBandwidthCtrl->setGlobalAlertInForwardChain();
        }
San Mehat's avatar
San Mehat committed
589 590
    } else if (!strcmp(argv[1], "disable")) {
        rc = sNatCtrl->disableNat(argv[2], argv[3]);
591 592
        /* Ignore ifaces for now. */
        rc |= sBandwidthCtrl->removeGlobalAlertInForwardChain();
593 594 595 596 597 598 599 600 601 602
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown nat cmd", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Nat operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Nat operation failed", true);
    }
San Mehat's avatar
San Mehat committed
603 604 605 606

    return 0;
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620
CommandListener::PppdCmd::PppdCmd() :
                 NetdCommand("pppd") {
}

int CommandListener::PppdCmd::runCommand(SocketClient *cli,
                                                      int argc, char **argv) {
    int rc = 0;

    if (argc < 3) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

    if (!strcmp(argv[1], "attach")) {
621 622 623 624
        struct in_addr l, r, dns1, dns2;

        memset(&dns1, sizeof(struct in_addr), 0);
        memset(&dns2, sizeof(struct in_addr), 0);
625 626 627 628 629 630 631 632 633

        if (!inet_aton(argv[3], &l)) {
            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid local address", false);
            return 0;
        }
        if (!inet_aton(argv[4], &r)) {
            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid remote address", false);
            return 0;
        }
634 635 636 637 638 639 640 641 642
        if ((argc > 3) && (!inet_aton(argv[5], &dns1))) {
            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid dns1 address", false);
            return 0;
        }
        if ((argc > 4) && (!inet_aton(argv[6], &dns2))) {
            cli->sendMsg(ResponseCode::CommandParameterError, "Invalid dns2 address", false);
            return 0;
        }
        rc = sPppCtrl->attachPppd(argv[2], l, r, dns1, dns2);
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    } else if (!strcmp(argv[1], "detach")) {
        rc = sPppCtrl->detachPppd(argv[2]);
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown pppd cmd", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Pppd operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Pppd operation failed", true);
    }

    return 0;
}
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696

CommandListener::PanCmd::PanCmd() :
                 NetdCommand("pan") {
}

int CommandListener::PanCmd::runCommand(SocketClient *cli,
                                        int argc, char **argv) {
    int rc = 0;

    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
        return 0;
    }

    if (!strcmp(argv[1], "start")) {
        rc = sPanCtrl->startPan();
    } else if (!strcmp(argv[1], "stop")) {
        rc = sPanCtrl->stopPan();
    } else if (!strcmp(argv[1], "status")) {
        char *tmp = NULL;

        asprintf(&tmp, "Pan services %s",
                 (sPanCtrl->isPanStarted() ? "started" : "stopped"));
        cli->sendMsg(ResponseCode::PanStatusResult, tmp, false);
        free(tmp);
        return 0;
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown pan cmd", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Pan operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Pan operation failed", true);
    }

    return 0;
}
697 698 699 700 701 702 703

CommandListener::SoftapCmd::SoftapCmd() :
                 NetdCommand("softap") {
}

int CommandListener::SoftapCmd::runCommand(SocketClient *cli,
                                        int argc, char **argv) {
704
    int rc = 0, flag = 0;
Dmitry Shmidt's avatar
Dmitry Shmidt committed
705
    char *retbuf = NULL;
706 707 708 709 710 711 712

    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Softap Missing argument", false);
        return 0;
    }

    if (!strcmp(argv[1], "start")) {
713
        rc = sSoftapCtrl->startDriver(argv[2]);
714
    } else if (!strcmp(argv[1], "stop")) {
715 716 717 718
        rc = sSoftapCtrl->stopDriver(argv[2]);
    } else if (!strcmp(argv[1], "startap")) {
        rc = sSoftapCtrl->startSoftap();
    } else if (!strcmp(argv[1], "stopap")) {
719
        rc = sSoftapCtrl->stopSoftap();
720 721
    } else if (!strcmp(argv[1], "fwreload")) {
        rc = sSoftapCtrl->fwReloadSoftap(argc, argv);
Dmitry Shmidt's avatar
Dmitry Shmidt committed
722 723 724 725 726 727 728
    } else if (!strcmp(argv[1], "clients")) {
        rc = sSoftapCtrl->clientsSoftap(&retbuf);
        if (!rc) {
            cli->sendMsg(ResponseCode::CommandOkay, retbuf, false);
            free(retbuf);
            return 0;
        }
729
    } else if (!strcmp(argv[1], "status")) {
Dmitry Shmidt's avatar
Dmitry Shmidt committed
730
        asprintf(&retbuf, "Softap service %s",
731
                 (sSoftapCtrl->isSoftapStarted() ? "started" : "stopped"));
Dmitry Shmidt's avatar
Dmitry Shmidt committed
732 733
        cli->sendMsg(ResponseCode::SoftapStatusResult, retbuf, false);
        free(retbuf);
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        return 0;
    } else if (!strcmp(argv[1], "set")) {
        rc = sSoftapCtrl->setSoftap(argc, argv);
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Softap Unknown cmd", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Softap operation succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Softap operation failed", true);
    }

    return 0;
}
750

Mattias Falk's avatar
Mattias Falk committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
CommandListener::ResolverCmd::ResolverCmd() :
        NetdCommand("resolver") {
}

int CommandListener::ResolverCmd::runCommand(SocketClient *cli, int argc, char **argv) {
    int rc = 0;
    struct in_addr addr;

    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Resolver missing arguments", false);
        return 0;
    }

    if (!strcmp(argv[1], "setdefaultif")) { // "resolver setdefaultif <iface>"
        if (argc == 3) {
            rc = sResolverCtrl->setDefaultInterface(argv[2]);
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Wrong number of arguments to resolver setdefaultif", false);
            return 0;
        }
    } else if (!strcmp(argv[1], "setifdns")) { // "resolver setifdns <iface> <dns1> <dns2> ..."
        if (argc >= 4) {
            rc = sResolverCtrl->setInterfaceDnsServers(argv[2], &argv[3], argc - 3);
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Wrong number of arguments to resolver setifdns", false);
            return 0;
        }

        // set the address of the interface to which the name servers
        // are bound. Required in order to bind to right interface when
        // doing the dns query.
        if (!rc) {
            ifc_init();
            ifc_get_info(argv[2], &addr.s_addr, NULL, 0);

            rc = sResolverCtrl->setInterfaceAddress(argv[2], &addr);
        }
    } else if (!strcmp(argv[1], "flushdefaultif")) { // "resolver flushdefaultif"
        if (argc == 2) {
            rc = sResolverCtrl->flushDefaultDnsCache();
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Wrong number of arguments to resolver flushdefaultif", false);
            return 0;
        }
    } else if (!strcmp(argv[1], "flushif")) { // "resolver flushif <iface>"
        if (argc == 3) {
            rc = sResolverCtrl->flushInterfaceDnsCache(argv[2]);
        } else {
            cli->sendMsg(ResponseCode::CommandSyntaxError,
                    "Wrong number of arguments to resolver setdefaultif", false);
            return 0;
        }
    } else {
        cli->sendMsg(ResponseCode::CommandSyntaxError,"Resolver unknown command", false);
        return 0;
    }

    if (!rc) {
        cli->sendMsg(ResponseCode::CommandOkay, "Resolver command succeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Resolver command failed", true);
    }

    return 0;
}

820 821 822 823 824 825 826 827 828 829 830 831 832 833
int CommandListener::readInterfaceCounters(const char *iface, unsigned long *rx, unsigned long *tx) {
    FILE *fp = fopen("/proc/net/dev", "r");
    if (!fp) {
        LOGE("Failed to open /proc/net/dev (%s)", strerror(errno));
        return -1;
    }

    char buffer[512];

    fgets(buffer, sizeof(buffer), fp); // Header 1
    fgets(buffer, sizeof(buffer), fp); // Header 2
    while(fgets(buffer, sizeof(buffer), fp)) {
        buffer[strlen(buffer)-1] = '\0';

834
        char name[31];
835
        unsigned long d;
836
        sscanf(buffer, "%30s %lu %lu %lu %lu %lu %lu %lu %lu %lu",
837
                name, rx, &d, &d, &d, &d, &d, &d, &d, tx);
838 839 840 841 842 843 844 845 846 847
        char *rxString = strchr(name, ':');
        *rxString = '\0';
        rxString++;
        // when the rx count gets too big it changes from "name: 999" to "name:1000"
        // and the sscanf munge the two together.  Detect that and fix
        // note that all the %lu will be off by one and the real tx value will be in d
        if (*rxString != '\0') {
            *tx = d;
            sscanf(rxString, "%20lu", rx);
        }
848 849 850 851 852 853 854 855
        if (strcmp(name, iface)) {
            continue;
        }
        fclose(fp);
        return 0;
    }

    fclose(fp);
856 857 858
    *rx = 0;
    *tx = 0;
    return 0;
859
}
860 861

CommandListener::BandwidthControlCmd::BandwidthControlCmd() :
862
    NetdCommand("bandwidth") {
863 864
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
void CommandListener::BandwidthControlCmd::sendGenericSyntaxError(SocketClient *cli, const char *usageMsg) {
    char *msg;
    asprintf(&msg, "Usage: bandwidth %s", usageMsg);
    cli->sendMsg(ResponseCode::CommandSyntaxError, msg, false);
    free(msg);
}

void CommandListener::BandwidthControlCmd::sendGenericOkFail(SocketClient *cli, int cond) {
    if (!cond) {
        cli->sendMsg(ResponseCode::CommandOkay, "Bandwidth command succeeeded", false);
    } else {
        cli->sendMsg(ResponseCode::OperationFailed, "Bandwidth command failed", false);
    }
}

void CommandListener::BandwidthControlCmd::sendGenericOpFailed(SocketClient *cli, const char *errMsg) {
    cli->sendMsg(ResponseCode::OperationFailed, errMsg, false);
}

884
int CommandListener::BandwidthControlCmd::runCommand(SocketClient *cli, int argc, char **argv) {
885
    if (argc < 2) {
886
        sendGenericSyntaxError(cli, "<cmds> <args...>");
887 888 889
        return 0;
    }

890 891
    LOGV("bwctrlcmd: argc=%d %s %s ...", argc, argv[0], argv[1]);

892
    if (!strcmp(argv[1], "enable")) {
893 894 895 896 897 898 899 900 901
        int rc = sBandwidthCtrl->enableBandwidthControl();
        sendGenericOkFail(cli, rc);
        return 0;

    }
    if (!strcmp(argv[1], "disable")) {
        int rc = sBandwidthCtrl->disableBandwidthControl();
        sendGenericOkFail(cli, rc);
        return 0;
902

903 904
    }
    if (!strcmp(argv[1], "removequota") || !strcmp(argv[1], "rq")) {
905
        if (argc != 3) {
906
            sendGenericSyntaxError(cli, "removequota <interface>");
907 908
            return 0;
        }
909 910 911
        int rc = sBandwidthCtrl->removeInterfaceSharedQuota(argv[2]);
        sendGenericOkFail(cli, rc);
        return 0;
912

913 914
    }
    if (!strcmp(argv[1], "getquota") || !strcmp(argv[1], "gq")) {
915 916
        int64_t bytes;
        if (argc != 2) {
917
            sendGenericSyntaxError(cli, "getquota");
918 919
            return 0;
        }
920
        int rc = sBandwidthCtrl->getInterfaceSharedQuota(&bytes);
921
        if (rc) {
922
            sendGenericOpFailed(cli, "Failed to get quota");
923 924
            return 0;
        }
925

926 927 928 929
        char *msg;
        asprintf(&msg, "%lld", bytes);
        cli->sendMsg(ResponseCode::QuotaCounterResult, msg, false);
        free(msg);
930
        return 0;
931

932 933
    }
    if (!strcmp(argv[1], "getiquota") || !strcmp(argv[1], "giq")) {
934 935
        int64_t bytes;
        if (argc != 3) {
936
            sendGenericSyntaxError(cli, "getiquota <iface>");
937 938
            return 0;
        }
939 940

        int rc = sBandwidthCtrl->getInterfaceQuota(argv[2], &bytes);
941
        if (rc) {
942
            sendGenericOpFailed(cli, "Failed to get quota");
943 944 945 946 947 948
            return 0;
        }
        char *msg;
        asprintf(&msg, "%lld", bytes);
        cli->sendMsg(ResponseCode::QuotaCounterResult, msg, false);
        free(msg);
949
        return 0;
950

951 952
    }
    if (!strcmp(argv[1], "setquota") || !strcmp(argv[1], "sq")) {
953
        if (argc != 4) {
954
            sendGenericSyntaxError(cli, "setquota <interface> <bytes>");
955 956
            return 0;
        }
957 958 959 960 961 962
        int rc = sBandwidthCtrl->setInterfaceSharedQuota(argv[2], atoll(argv[3]));
        sendGenericOkFail(cli, rc);
        return 0;
    }
    if (!strcmp(argv[1], "setquotas") || !strcmp(argv[1], "sqs")) {
        int rc;
963
        if (argc < 4) {
964
            sendGenericSyntaxError(cli, "setquotas <bytes> <interface> ...");
965 966
            return 0;
        }
967

968
        for (int q = 3; argc >= 4; q++, argc--) {
969 970 971 972 973 974 975
            rc = sBandwidthCtrl->setInterfaceSharedQuota(argv[q], atoll(argv[2]));
            if (rc) {
                char *msg;
                asprintf(&msg, "bandwidth setquotas %s %s failed", argv[2], argv[q]);
                cli->sendMsg(ResponseCode::OperationFailed,
                             msg, false);
                free(msg);
976
                return 0;
977 978
            }
        }
979 980
        sendGenericOkFail(cli, rc);
        return 0;
981

982 983 984
    }
    if (!strcmp(argv[1], "removequotas") || !strcmp(argv[1], "rqs")) {
        int rc;
985
        if (argc < 3) {
986
            sendGenericSyntaxError(cli, "removequotas <interface> ...");
987 988
            return 0;
        }
989

990
        for (int q = 2; argc >= 3; q++, argc--) {
991 992 993 994 995 996 997
            rc = sBandwidthCtrl->removeInterfaceSharedQuota(argv[q]);
            if (rc) {
                char *msg;
                asprintf(&msg, "bandwidth removequotas %s failed", argv[q]);
                cli->sendMsg(ResponseCode::OperationFailed,
                             msg, false);
                free(msg);
998
                return 0;
999 1000
            }
        }
1001 1002
        sendGenericOkFail(cli, rc);
        return 0;
1003

1004 1005
    }
    if (!strcmp(argv[1], "removeiquota") || !strcmp(argv[1], "riq")) {
1006
        if (argc != 3) {
1007
            sendGenericSyntaxError(cli, "removeiquota <interface>");
1008 1009
            return 0;
        }
1010 1011 1012
        int rc = sBandwidthCtrl->removeInterfaceQuota(argv[2]);
        sendGenericOkFail(cli, rc);
        return 0;
1013

1014 1015
    }
    if (!strcmp(argv[1], "setiquota") || !strcmp(argv[1], "siq")) {
1016
        if (argc != 4) {
1017
            sendGenericSyntaxError(cli, "setiquota <interface> <bytes>");
1018 1019
            return 0;
        }
1020 1021 1022
        int rc = sBandwidthCtrl->setInterfaceQuota(argv[2], atoll(argv[3]));
        sendGenericOkFail(cli, rc);
        return 0;
1023

1024 1025
    }
    if (!strcmp(argv[1], "addnaughtyapps") || !strcmp(argv[1], "ana")) {
1026
        if (argc < 3) {
1027
            sendGenericSyntaxError(cli, "addnaughtyapps <appUid> ...");
1028
            return 0;
1029
        }
1030 1031 1032 1033
        int rc = sBandwidthCtrl->addNaughtyApps(argc - 2, argv + 2);
        sendGenericOkFail(cli, rc);
        return 0;

1034

1035 1036
    }
    if (!strcmp(argv[1], "removenaughtyapps") || !strcmp(argv[1], "rna")) {
1037
        if (argc < 3) {
1038
            sendGenericSyntaxError(cli, "removenaughtyapps <appUid> ...");
1039 1040
            return 0;
        }
1041 1042 1043
        int rc = sBandwidthCtrl->removeNaughtyApps(argc - 2, argv + 2);
        sendGenericOkFail(cli, rc);
        return 0;
1044

1045 1046
    }
    if (!strcmp(argv[1], "setglobalalert") || !strcmp(argv[1], "sga")) {
1047
        if (argc != 3) {
1048
            sendGenericSyntaxError(cli, "setglobalalert <bytes>");
1049 1050
            return 0;
        }
1051 1052 1053
        int rc = sBandwidthCtrl->setGlobalAlert(atoll(argv[2]));
        sendGenericOkFail(cli, rc);
        return 0;
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    }
    if (!strcmp(argv[1], "debugsettetherglobalalert") || !strcmp(argv[1], "dstga")) {
        if (argc != 4) {
            sendGenericSyntaxError(cli, "debugsettetherglobalalert <interface0> <interface1>");
            return 0;
        }
        /* We ignore the interfaces for now. */
        int rc = sBandwidthCtrl->setGlobalAlertInForwardChain();
        sendGenericOkFail(cli, rc);
        return 0;

1066 1067
    }
    if (!strcmp(argv[1], "removeglobalalert") || !strcmp(argv[1], "rga")) {
1068
        if (argc != 2) {
1069
            sendGenericSyntaxError(cli, "removeglobalalert");
1070 1071
            return 0;
        }
1072 1073 1074
        int rc = sBandwidthCtrl->removeGlobalAlert();
        sendGenericOkFail(cli, rc);
        return 0;
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    }
    if (!strcmp(argv[1], "debugremovetetherglobalalert") || !strcmp(argv[1], "drtga")) {
        if (argc != 4) {
            sendGenericSyntaxError(cli, "debugremovetetherglobalalert <interface0> <interface1>");
            return 0;
        }
        /* We ignore the interfaces for now. */
        int rc = sBandwidthCtrl->removeGlobalAlertInForwardChain();
        sendGenericOkFail(cli, rc);
        return 0;

1087 1088
    }
    if (!strcmp(argv[1], "setsharedalert") || !strcmp(argv[1], "ssa")) {
1089
        if (argc != 3) {
1090
            sendGenericSyntaxError(cli, "setsharedalert <bytes>");
1091 1092
            return 0;
        }
1093 1094 1095
        int rc = sBandwidthCtrl->setSharedAlert(atoll(argv[2]));
        sendGenericOkFail(cli, rc);
        return 0;
1096

1097 1098
    }
    if (!strcmp(argv[1], "removesharedalert") || !strcmp(argv[1], "rsa")) {
1099
        if (argc != 2) {
1100
            sendGenericSyntaxError(cli, "removesharedalert");
1101 1102
            return 0;
        }
1103 1104 1105
        int rc = sBandwidthCtrl->removeSharedAlert();
        sendGenericOkFail(cli, rc);
        return 0;
1106

1107 1108
    }
    if (!strcmp(argv[1], "setinterfacealert") || !strcmp(argv[1], "sia")) {
1109
        if (argc != 4) {
1110
            sendGenericSyntaxError(cli, "setinterfacealert <interface> <bytes>");
1111 1112
            return 0;
        }
1113 1114 1115
        int rc = sBandwidthCtrl->setInterfaceAlert(argv[2], atoll(argv[3]));
        sendGenericOkFail(cli, rc);
        return 0;
1116

1117 1118
    }
    if (!strcmp(argv[1], "removeinterfacealert") || !strcmp(argv[1], "ria")) {
1119
        if (argc != 3) {
1120
            sendGenericSyntaxError(cli, "removeinterfacealert <interface>");
1121 1122
            return 0;
        }
1123 1124
        int rc = sBandwidthCtrl->removeInterfaceAlert(argv[2]);
        sendGenericOkFail(cli, rc);
1125
        return 0;
1126

1127
    }
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    if (!strcmp(argv[1], "gettetherstats") || !strcmp(argv[1], "gts")) {
        BandwidthController::TetherStats tetherStats;
        if (argc != 4) {
            sendGenericSyntaxError(cli, "gettetherstats <interface0> <interface1>");
            return 0;
        }

        tetherStats.ifaceIn = argv[2];
        tetherStats.ifaceOut = argv[3];
        int rc = sBandwidthCtrl->getTetherStats(tetherStats);
        if (rc) {
            sendGenericOpFailed(cli, "Failed to get tethering stats");
            return 0;
        }

        char *msg = tetherStats.getStatsLine();
        cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
        free(msg);
        return 0;
1147 1148

    }
1149 1150

    cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown bandwidth cmd", false);
1151 1152
    return 0;
}