telnet_loop.c 16.8 KB
Newer Older
W
wenjun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
/*
 * Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "telnet_loop.h"
#ifdef LOSCFG_NET_TELNET
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "pthread.h"
#include "netinet/tcp.h"
#include "sys/select.h"
#include "sys/types.h"
#include "sys/prctl.h"

#include "los_task.h"
#include "linux/atomic.h"
#include "lwip/sockets.h"
#include "lwip/inet.h"
#include "lwip/netif.h"
#include "console.h"
#ifdef LOSCFG_SHELL
#include "shell.h"
#include "shcmd.h"
#endif
#include "telnet_pri.h"
#include "telnet_dev.h"

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */

/* TELNET commands in RFC854 */
#define TELNET_SB   250 /* Indicates that what follows is subnegotiation of the indicated option */
#define TELNET_WILL 251 /* Indicates the desire to perform the indicated option */
#define TELNET_DO   253 /* Indicates the request for the other party to perform the indicated option */
#define TELNET_IAC  255 /* Interpret as Command */

/* telnet options in IANA */
#define TELNET_ECHO 1    /* Echo */
#define TELNET_SGA  3    /* Suppress Go Ahead */
#define TELNET_NAWS 31   /* Negotiate About Window Size */
#define TELNET_NOP  0xf1 /* Unassigned in IANA, putty use this to keepalive */

#define LEN_IAC_CMD      2 /* Only 2 char: |IAC|cmd| */
#define LEN_IAC_CMD_OPT  3 /* Only 3 char: |IAC|cmd|option| */
#define LEN_IAC_CMD_NAWS 9 /* NAWS: |IAC|SB|NAWS|x1|x2|x3|x4|IAC|SE| */

/* server/client settings */
#define TELNET_TASK_STACK_SIZE  0x2000
#define TELNET_TASK_PRIORITY    9

/* server settings */
#define TELNET_LISTEN_BACKLOG   128
#define TELNET_ACCEPT_INTERVAL  200

/* client settings */
#define TELNET_CLIENT_POLL_TIMEOUT  2000
#define TELNET_CLIENT_READ_BUF_SIZE 256
#define TELNET_CLIENT_READ_FILTER_BUF_SIZE (8 * 1024)

/* limitation: only support 1 telnet client connection */
STATIC volatile INT32 g_telnetClientFd = -1;  /* client fd */

/* limitation: only support 1 telnet server */
STATIC volatile INT32 g_telnetListenFd = -1;  /* listen fd of telnetd */

/* each bit for a client connection, although only support 1 connection for now */
STATIC volatile UINT32 g_telnetMask = 0;
/* taskID of telnetd */
STATIC atomic_t g_telnetTaskId = 0;
/* protect listenFd, clientFd etc. */
pthread_mutex_t g_telnetMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;

VOID TelnetLock(VOID)
{
    (VOID)pthread_mutex_lock(&g_telnetMutex);
}

VOID TelnetUnlock(VOID)
{
    (VOID)pthread_mutex_unlock(&g_telnetMutex);
}

/* filter out iacs from client stream */
STATIC UINT8 *ReadFilter(const UINT8 *src, UINT32 srcLen, UINT32 *dstLen)
{
    STATIC UINT8 buf[TELNET_CLIENT_READ_FILTER_BUF_SIZE];
    UINT8 *dst = buf;
    UINT32 left = srcLen;

    while (left > 0) {
        if (*src != TELNET_IAC) {
            *dst = *src;
            dst++;
            src++;
            left--;
            continue;
        }

        /*
         * if starting with IAC, filter out IAC as following
         * |IAC|          --> skip
         * |IAC|NOP|...   --> ... : skip for putty keepalive etc.
         * |IAC|x|        --> skip
         * |IAC|IAC|x|... --> |IAC|... : skip for literal cmds
         * |IAC|SB|NAWS|x1|x2|x3|x4|IAC|SE|... --> ... : skip NAWS(unsupported)
         * |IAC|x|x|...   --> ... : skip unsupported IAC
         */
        if (left == 1) {
            break;
        }
        /* left no less than 2 */
        if (*(src + 1) == TELNET_NOP) {
            src += LEN_IAC_CMD;
            left -= LEN_IAC_CMD;
            continue;
        }
        if (left == LEN_IAC_CMD) {
            break;
        }
        /* left no less than 3 */
        if (*(src + 1) == TELNET_IAC) {
            *dst = TELNET_IAC;
            dst++;
            src += LEN_IAC_CMD;
            left -= LEN_IAC_CMD;
            continue;
        }
        if ((*(src + 1) == TELNET_SB) && (*(src + LEN_IAC_CMD) == TELNET_NAWS)) {
            if (left > LEN_IAC_CMD_NAWS) {
                src += LEN_IAC_CMD_NAWS;
                left -= LEN_IAC_CMD_NAWS;
                continue;
            }
            break;
        }
        src += LEN_IAC_CMD_OPT;
        left -= LEN_IAC_CMD_OPT;
    }

    if (dstLen != NULL) {
        *dstLen = dst - buf;
    }
    return buf;
}

/*
 * Description : Write data to fd.
 * Input       : fd     --- the fd to write.
 *             : src    --- data pointer.
 *             : srcLen --- data length.
 * Return      : length of written data.
 */
STATIC ssize_t WriteToFd(INT32 fd, const CHAR *src, size_t srcLen)
{
    size_t sizeLeft;
    ssize_t sizeWritten;

    sizeLeft = srcLen;
    while (sizeLeft > 0) {
        sizeWritten = write(fd, src, sizeLeft);
        if (sizeWritten < 0) {
            /* last write failed */
            if (sizeLeft == srcLen) {
                /* nothing was written in any loop */
                return -1;
            } else {
                /* something was written in previous loop */
                break;
            }
        } else if (sizeWritten == 0) {
            break;
        }
        sizeLeft -= (size_t)sizeWritten;
        src += sizeWritten;
    }

    return (ssize_t)(srcLen - sizeLeft);
}

/* Try to remove the client device if there is any client connection */
STATIC VOID TelnetClientClose(VOID)
{
    /* check if there is any client connection */
    if (g_telnetMask == 0) {
        return;
    }
    (VOID)TelnetDevDeinit();
    g_telnetMask = 0;
    printf("telnet client disconnected.\n");
}

/* Release the client and server fd */
STATIC VOID TelnetRelease(VOID)
{
    if (g_telnetClientFd >= 0) {
        (VOID)close(g_telnetClientFd);
        g_telnetClientFd = -1;
    }

    if (g_telnetListenFd >= 0) {
        (VOID)close(g_telnetListenFd);
        g_telnetListenFd = -1;
    }
}

/* Stop telnet server */
STATIC VOID TelnetdDeinit(VOID)
{
    if (atomic_read(&g_telnetTaskId) == 0) {
        PRINTK("telnet server is not running!\n");
        return;
    }

    TelnetRelease();
    (VOID)TelnetedUnregister();
    atomic_set(&g_telnetTaskId, 0);
    PRINTK("telnet server closed.\n");
}

/*
 * Description : Setup the listen fd for telnetd with specific port.
 * Input       : port --- the port at which telnet server listens.
 * Return      : -1           --- on error
 *             : non-negative --- listen fd if OK
 */
STATIC INT32 TelnetdInit(UINT16 port)
{
    INT32 listenFd;
    INT32 reuseAddr = 1;
    struct sockaddr_in inTelnetAddr;

    listenFd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenFd == -1) {
        PRINT_ERR("TelnetdInit : socket error.\n");
        goto ERR_OUT;
    }

    /* reuse listen port */
    if (setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0) {
        PRINT_ERR("TelnetdInit : setsockopt REUSEADDR error.\n");
        goto ERR_CLOSE_FD;
    }

    (VOID)memset_s(&inTelnetAddr, sizeof(struct sockaddr_in), 0, sizeof(struct sockaddr_in));
    inTelnetAddr.sin_family = AF_INET;
    inTelnetAddr.sin_addr.s_addr = INADDR_ANY;
    inTelnetAddr.sin_port = htons(port);

    if (bind(listenFd, (const struct sockaddr *)&inTelnetAddr, sizeof(struct sockaddr_in)) == -1) {
        PRINT_ERR("TelnetdInit : bind error.\n");
        goto ERR_CLOSE_FD;
    }

    if (listen(listenFd, TELNET_LISTEN_BACKLOG) == -1) {
        PRINT_ERR("TelnetdInit : listen error.\n");
        goto ERR_CLOSE_FD;
    }

    return listenFd;

ERR_CLOSE_FD:
    (VOID)close(listenFd);
ERR_OUT:
    return -1;
}

STATIC INT32 TelnetClientPrepare(INT32 clientFd)
{
    INT32 keepAlive = TELNET_KEEPALIVE;
    INT32 keepIdle = TELNET_KEEPIDLE;
    INT32 keepInterval = TELNET_KEEPINTV;
    INT32 keepCnt = TELNET_KEEPCNT;
    const UINT8 doEcho[] = { TELNET_IAC, TELNET_DO, TELNET_ECHO };
    const UINT8 doNaws[] = { TELNET_IAC, TELNET_DO, TELNET_NAWS };
    const UINT8 willEcho[] = { TELNET_IAC, TELNET_WILL, TELNET_ECHO };
    const UINT8 willSga[] = { TELNET_IAC, TELNET_WILL, TELNET_SGA };

    if (g_telnetListenFd == -1) {
        return -1;
    }
    g_telnetClientFd = clientFd;
    if (TelnetDevInit(clientFd) != 0) {
        g_telnetClientFd = -1;
        return -1;
    }
    g_telnetMask = 1;

    /* negotiate with client */
    (VOID)WriteToFd(clientFd, (CHAR *)doEcho, sizeof(doEcho));
    (VOID)WriteToFd(clientFd, (CHAR *)doNaws, sizeof(doNaws));
    (VOID)WriteToFd(clientFd, (CHAR *)willEcho, sizeof(willEcho));
    (VOID)WriteToFd(clientFd, (CHAR *)willSga, sizeof(willSga));

    /* enable TCP keepalive to check whether telnet link is alive */
    if (setsockopt(clientFd, SOL_SOCKET, SO_KEEPALIVE, (VOID *)&keepAlive, sizeof(keepAlive)) < 0) {
        PRINT_ERR("telnet setsockopt SO_KEEPALIVE error.\n");
    }
    if (setsockopt(clientFd, IPPROTO_TCP, TCP_KEEPIDLE, (VOID *)&keepIdle, sizeof(keepIdle)) < 0) {
        PRINT_ERR("telnet setsockopt TCP_KEEPIDLE error.\n");
    }
    if (setsockopt(clientFd, IPPROTO_TCP, TCP_KEEPINTVL, (VOID *)&keepInterval, sizeof(keepInterval)) < 0) {
        PRINT_ERR("telnet setsockopt TCP_KEEPINTVL error.\n");
    }
    if (setsockopt(clientFd, IPPROTO_TCP, TCP_KEEPCNT, (VOID *)&keepCnt, sizeof(keepCnt)) < 0) {
        PRINT_ERR("telnet setsockopt TCP_KEEPCNT error.\n");
    }
    return 0;
}

STATIC VOID *TelnetClientLoop(VOID *arg)
{
    struct pollfd pollFd;
    INT32 ret;
    INT32 nRead;
    UINT32 len;
    UINT8 buf[TELNET_CLIENT_READ_BUF_SIZE];
    UINT8 *cmdBuf = NULL;
    INT32 clientFd = (INT32)(UINTPTR)arg;

    (VOID)prctl(PR_SET_NAME, "TelnetClientLoop", 0, 0, 0);
    TelnetLock();
    if (TelnetClientPrepare(clientFd) != 0) {
        TelnetUnlock();
        (VOID)close(clientFd);
        return NULL;
    }
    TelnetUnlock();

    while (1) {
        pollFd.fd = clientFd;
        pollFd.events = POLLIN | POLLRDHUP;
        pollFd.revents = 0;

        ret = poll(&pollFd, 1, TELNET_CLIENT_POLL_TIMEOUT);
        if (ret < 0) {
            break;
        }
        if (ret == 0) {
            continue;
        }
        /* connection reset, maybe keepalive failed or reset by peer */
        if ((UINT16)pollFd.revents & (POLLERR | POLLHUP | POLLRDHUP)) {
            break;
        }

        if ((UINT16)pollFd.revents & POLLIN) {
            nRead = read(clientFd, buf, sizeof(buf));
            if (nRead <= 0) {
                /* telnet client shutdown */
                break;
            }
            cmdBuf = ReadFilter(buf, (UINT32)nRead, &len);
            if (len > 0) {
                (VOID)TelnetTx((CHAR *)cmdBuf, len);
            }
        }
    }
    TelnetLock();
    TelnetClientClose();
    (VOID)close(clientFd);
    clientFd = -1;
    g_telnetClientFd = -1;
    TelnetUnlock();
    return NULL;
}

STATIC VOID TelnetClientTaskAttr(pthread_attr_t *threadAttr)
{
    (VOID)pthread_attr_init(threadAttr);
    threadAttr->inheritsched = PTHREAD_EXPLICIT_SCHED;
    threadAttr->schedparam.sched_priority = TELNET_TASK_PRIORITY;
    threadAttr->detachstate = PTHREAD_CREATE_DETACHED;
    (VOID)pthread_attr_setstacksize(threadAttr, TELNET_TASK_STACK_SIZE);
}

/*
 * Description : Handle the client connection request.
 *               Create a client connection if permitted.
 * Return      : 0  --- please continue the server accept loop
 *             : -1 --- please stop the server accept loop.
 */
STATIC INT32 TelnetdAcceptClient(INT32 clientFd, const struct sockaddr_in *inTelnetAddr)
{
    INT32 ret = 0;
    pthread_t tmp;
    pthread_attr_t useAttr;

    TelnetClientTaskAttr(&useAttr);

    if (clientFd < 0) {
        ret = -1;
        goto ERROUT;
    }

    TelnetLock();

    if (g_telnetListenFd == -1) {
        /* server already has been closed, so quit this task now */
        ret = -1;
        goto ERROUT_UNLOCK;
    }

    if (g_telnetClientFd >= 0) {
        /* alreay connected and support only one */
        goto ERROUT_UNLOCK;
    }

    g_telnetClientFd = clientFd;

    if (pthread_create(&tmp, &useAttr, TelnetClientLoop, (VOID *)(UINTPTR)clientFd) != 0) {
        PRINT_ERR("Failed to create client handle task\n");
        g_telnetClientFd = -1;
        goto ERROUT_UNLOCK;
    }
    TelnetUnlock();
    return ret;

ERROUT_UNLOCK:
    (VOID)close(clientFd);
    clientFd = -1;
    TelnetUnlock();
ERROUT:
    return ret;
}

/*
 * Waiting for client's connection. Only allow 1 connection, and others will be discarded.
 */
STATIC VOID TelnetdAcceptLoop(INT32 listenFd)
{
    INT32 clientFd = -1;
    struct sockaddr_in inTelnetAddr;
    INT32 len = sizeof(inTelnetAddr);

    TelnetLock();
    g_telnetListenFd = listenFd;

    while (g_telnetListenFd >= 0) {
        TelnetUnlock();

        (VOID)memset_s(&inTelnetAddr, sizeof(inTelnetAddr), 0, sizeof(inTelnetAddr));
        clientFd = accept(listenFd, (struct sockaddr *)&inTelnetAddr, (socklen_t *)&len);
        if (TelnetdAcceptClient(clientFd, &inTelnetAddr) == 0) {
            /*
             * Sleep sometime before next loop: mostly we already have one connection here,
             * and the next connection will be declined. So don't waste our cpu.
             */
            LOS_Msleep(TELNET_ACCEPT_INTERVAL);
        } else {
            return;
        }
        TelnetLock();
    }
    TelnetUnlock();
}

STATIC INT32 TelnetdMain(VOID)
{
    INT32 sock;
    INT32 ret;

    sock = TelnetdInit(TELNETD_PORT);
    if (sock == -1) {
        PRINT_ERR("telnet init error.\n");
        return -1;
    }

    TelnetLock();
    ret = TelnetedRegister();
    TelnetUnlock();

    if (ret != 0) {
        PRINT_ERR("telnet register error.\n");
        (VOID)close(sock);
        return -1;
    }

    PRINTK("start telnet server successfully, waiting for connection.\n");
    TelnetdAcceptLoop(sock);
    return 0;
}

/*
 * Try to create telnetd task.
 */
STATIC VOID TelnetdTaskInit(VOID)
{
    UINT32 ret;
    TSK_INIT_PARAM_S initParam = {0};

    initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)TelnetdMain;
    initParam.uwStackSize = TELNET_TASK_STACK_SIZE;
    initParam.pcName = "TelnetServer";
    initParam.usTaskPrio = TELNET_TASK_PRIORITY;
    initParam.uwResved = LOS_TASK_STATUS_DETACHED;

    if (atomic_read(&g_telnetTaskId) != 0) {
        PRINT_ERR("telnet server is already running!\n");
        return;
    }

    ret = LOS_TaskCreate((UINT32 *)&g_telnetTaskId, &initParam);
    if (ret != LOS_OK) {
        PRINT_ERR("failed to create telnet server task!\n");
    }
}

/*
 * Try to destroy telnetd task.
 */
STATIC VOID TelnetdTaskDeinit(VOID)
{
    if (atomic_read(&g_telnetTaskId) == 0) {
        PRINTK("telnet server is not running, please start up telnet server first.\n");
        return;
    }

    TelnetLock();
    TelnetClientClose();
    TelnetdDeinit();
    TelnetUnlock();
}

STATIC VOID TelnetUsage(VOID)
{
    PRINTK("Usage: telnet [OPTION]...\n");
    PRINTK("Start or close telnet server.\n\n");
    PRINTK("  on       Init the telnet server\n");
    PRINTK("  off      Deinit the telnet server\n");
}

INT32 TelnetCmd(UINT32 argc, const CHAR **argv)
{
    if (argc != 1) {
        TelnetUsage();
        return 0;
    }

    if (strcmp(argv[0], "on") == 0) {
        /* telnet on: try to start telnet server task */
        TelnetdTaskInit();
        return 0;
    }
    if (strcmp(argv[0], "off") == 0) {
        /* telnet off: try to stop clients, then stop server task */
        TelnetdTaskDeinit();
        return 0;
    }

    TelnetUsage();
    return 0;
}

#ifdef LOSCFG_SHELL_CMD_DEBUG
SHELLCMD_ENTRY(telnet_shellcmd, CMD_TYPE_EX, "telnet", 1, (CmdCallBackFunc)TelnetCmd);
#endif /* LOSCFG_SHELL_CMD_DEBUG */
#endif

#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */