sockets.c 55.9 KB
Newer Older
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
/**
 * @file
 * Sockets BSD-Like API module
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * 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. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 * Improved by Marc Boucher <marc@mbsi.ca> and David Haas <dhaas@alum.rpi.edu>
 *
 */

#include "lwip/opt.h"

#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */

#include "lwip/sockets.h"
#include "lwip/api.h"
#include "lwip/sys.h"
#include "lwip/igmp.h"
#include "lwip/inet.h"
#include "lwip/tcp.h"
#include "lwip/raw.h"
#include "lwip/udp.h"
#include "lwip/tcpip.h"

#include <string.h>

#define NUM_SOCKETS MEMP_NUM_NETCONN

/** Contains all internal pointers and states used for a socket */
struct lwip_socket {
  /** sockets currently are built on netconns, each socket has one netconn */
  struct netconn *conn;
  /** data that was left from the previous read */
  struct netbuf *lastdata;
  /** offset in the data that was left from the previous read */
  u16_t lastoffset;
  /** number of times data was received, set by event_callback(),
      tested by the receive and select functions */
B
bernard.xiong 已提交
69
  s16_t rcvevent;
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
  /** number of times data was received, set by event_callback(),
      tested by select */
  u16_t sendevent;
  /** socket flags (currently, only used for O_NONBLOCK) */
  u16_t flags;
  /** last error that occurred on this socket */
  int err;
};

/** Description for a task waiting in select */
struct lwip_select_cb {
  /** Pointer to the next waiting task */
  struct lwip_select_cb *next;
  /** readset passed to select */
  fd_set *readset;
  /** writeset passed to select */
  fd_set *writeset;
  /** unimplemented: exceptset passed to select */
  fd_set *exceptset;
  /** don't signal the same semaphore twice: set to 1 when signalled */
  int sem_signalled;
  /** semaphore to wake up a task waiting for select */
  sys_sem_t sem;
};

/** This struct is used to pass data to the set/getsockopt_internal
 * functions running in tcpip_thread context (only a void* is allowed) */
struct lwip_setgetsockopt_data {
  /** socket struct for which to change options */
  struct lwip_socket *sock;
  /** socket index for which to change options */
  int s;
  /** level of the option to process */
  int level;
  /** name of the option to process */
  int optname;
  /** set: value to set the option to
    * get: value of the option is stored here */
  void *optval;
  /** size of *optval */
  socklen_t *optlen;
  /** if an error occures, it is temporarily stored here */
  err_t err;
};

/** The global array of available sockets */
static struct lwip_socket sockets[NUM_SOCKETS];
/** The global list of tasks waiting for select */
static struct lwip_select_cb *select_cb_list;

/** Semaphore protecting the sockets array */
static sys_sem_t socksem;
/** Semaphore protecting select_cb_list */
static sys_sem_t selectsem;

/** Table to quickly map an lwIP error (err_t) to a socket error
  * by using -err as an index */
static const int err_to_errno_table[] = {
  0,             /* ERR_OK          0      No error, everything OK. */
  ENOMEM,        /* ERR_MEM        -1      Out of memory error.     */
  ENOBUFS,       /* ERR_BUF        -2      Buffer error.            */
B
bernard.xiong 已提交
131 132 133 134 135 136 137 138 139 140 141
  ETIMEDOUT,     /* ERR_TIMEOUT    -3      Timeout                  */
  EHOSTUNREACH,  /* ERR_RTE        -4      Routing problem.         */
  ECONNABORTED,  /* ERR_ABRT       -5      Connection aborted.      */
  ECONNRESET,    /* ERR_RST        -6      Connection reset.        */
  ESHUTDOWN,     /* ERR_CLSD       -7      Connection closed.       */
  ENOTCONN,      /* ERR_CONN       -8      Not connected.           */
  EINVAL,        /* ERR_VAL        -9      Illegal value.           */
  EIO,           /* ERR_ARG        -10     Illegal argument.        */
  EADDRINUSE,    /* ERR_USE        -11     Address in use.          */
  -1,            /* ERR_IF         -12     Low-level netif error    */
  -1,            /* ERR_ISCONN     -13     Already connected.       */
142 143 144 145 146 147 148 149 150 151 152
  EINPROGRESS    /* ERR_INPROGRESS -14     Operation in progress    */
};

#define ERR_TO_ERRNO_TABLE_SIZE \
  (sizeof(err_to_errno_table)/sizeof(err_to_errno_table[0]))

#define err_to_errno(err) \
  ((unsigned)(-(err)) < ERR_TO_ERRNO_TABLE_SIZE ? \
    err_to_errno_table[-(err)] : EIO)

#ifdef ERRNO
B
bernard.xiong 已提交
153
#ifndef set_errno
154
#define set_errno(err) errno = (err)
B
bernard.xiong 已提交
155
#endif
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
#else
#define set_errno(err)
#endif

#define sock_set_errno(sk, e) do { \
  sk->err = (e); \
  set_errno(sk->err); \
} while (0)

/* Forward delcaration of some functions */
static void event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len);
static void lwip_getsockopt_internal(void *arg);
static void lwip_setsockopt_internal(void *arg);

/**
 * Initialize this module. This function has to be called before any other
 * functions in this module!
 */
void
lwip_socket_init(void)
{
  socksem   = sys_sem_new(1);
  selectsem = sys_sem_new(1);
}

/**
 * Map a externally used socket index to the internal socket representation.
 *
 * @param s externally used socket index
 * @return struct lwip_socket for the socket or NULL if not found
 */
static struct lwip_socket *
get_socket(int s)
{
  struct lwip_socket *sock;

  if ((s < 0) || (s >= NUM_SOCKETS)) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): invalid\n", s));
    set_errno(EBADF);
    return NULL;
  }

  sock = &sockets[s];

  if (!sock->conn) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): not active\n", s));
    set_errno(EBADF);
    return NULL;
  }

  return sock;
}

/**
 * Allocate a new socket for a given netconn.
 *
 * @param newconn the netconn for which to allocate a socket
 * @return the index of the new socket; -1 on error
 */
static int
alloc_socket(struct netconn *newconn)
{
  int i;

  /* Protect socket array */
  sys_sem_wait(socksem);

  /* allocate a new socket identifier */
  for (i = 0; i < NUM_SOCKETS; ++i) {
    if (!sockets[i].conn) {
      sockets[i].conn       = newconn;
      sockets[i].lastdata   = NULL;
      sockets[i].lastoffset = 0;
      sockets[i].rcvevent   = 0;
      sockets[i].sendevent  = 1; /* TCP send buf is empty */
      sockets[i].flags      = 0;
      sockets[i].err        = 0;
      sys_sem_signal(socksem);
      return i;
    }
  }
  sys_sem_signal(socksem);
  return -1;
}

/* Below this, the well-known socket functions are implemented.
 * Use google.com or opengroup.org to get a good description :-)
 *
 * Exceptions are documented!
 */

int
lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
  struct lwip_socket *sock, *nsock;
  struct netconn *newconn;
  struct ip_addr naddr;
  u16_t port;
  int newsock;
  struct sockaddr_in sin;
  err_t err;

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d)...\n", s));
  sock = get_socket(s);
  if (!sock)
    return -1;

B
bernard.xiong 已提交
263 264 265 266 267 268
  if ((sock->flags & O_NONBLOCK) && (sock->rcvevent <= 0)) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): returning EWOULDBLOCK\n", s));
    sock_set_errno(sock, EWOULDBLOCK);
    return -1;
  }

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  newconn = netconn_accept(sock->conn);
  if (!newconn) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) failed, err=%d\n", s, sock->conn->err));
    sock_set_errno(sock, err_to_errno(sock->conn->err));
    return -1;
  }

  /* get the IP address and port of the remote host */
  err = netconn_peer(newconn, &naddr, &port);
  if (err != ERR_OK) {
    netconn_delete(newconn);
    sock_set_errno(sock, err_to_errno(err));
    return -1;
  }

B
bernard.xiong 已提交
284 285 286 287 288 289 290 291 292 293
  /* Note that POSIX only requires us to check addr is non-NULL. addrlen must
   * not be NULL if addr is valid.
   */
  if (NULL != addr) {
    LWIP_ASSERT("addr valid but addrlen NULL", addrlen != NULL);
    memset(&sin, 0, sizeof(sin));
    sin.sin_len = sizeof(sin);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = naddr.addr;
294

B
bernard.xiong 已提交
295 296
    if (*addrlen > sizeof(sin))
      *addrlen = sizeof(sin);
297

B
bernard.xiong 已提交
298 299
    MEMCPY(addr, &sin, *addrlen);
  }
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

  newsock = alloc_socket(newconn);
  if (newsock == -1) {
    netconn_delete(newconn);
    sock_set_errno(sock, ENFILE);
    return -1;
  }
  LWIP_ASSERT("invalid socket index", (newsock >= 0) && (newsock < NUM_SOCKETS));
  newconn->callback = event_callback;
  nsock = &sockets[newsock];
  LWIP_ASSERT("invalid socket pointer", nsock != NULL);

  sys_sem_wait(socksem);
  /* See event_callback: If data comes in right away after an accept, even
   * though the server task might not have created a new socket yet.
   * In that case, newconn->socket is counted down (newconn->socket--),
   * so nsock->rcvevent is >= 1 here!
   */
  nsock->rcvevent += -1 - newconn->socket;
  newconn->socket = newsock;
  sys_sem_signal(socksem);

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d addr=", s, newsock));
  ip_addr_debug_print(SOCKETS_DEBUG, &naddr);
B
bernard.xiong 已提交
324
  LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", port));
325 326 327 328 329 330

  sock_set_errno(sock, 0);
  return newsock;
}

int
B
bernard.xiong 已提交
331
lwip_bind(int s, const struct sockaddr *name, socklen_t namelen)
332 333 334 335 336 337 338 339 340 341 342
{
  struct lwip_socket *sock;
  struct ip_addr local_addr;
  u16_t local_port;
  err_t err;

  sock = get_socket(s);
  if (!sock)
    return -1;

  LWIP_ERROR("lwip_bind: invalid address", ((namelen == sizeof(struct sockaddr_in)) &&
B
bernard.xiong 已提交
343
             ((((const struct sockaddr_in *)name)->sin_family) == AF_INET)),
344 345
             sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;);

B
bernard.xiong 已提交
346 347
  local_addr.addr = ((const struct sockaddr_in *)name)->sin_addr.s_addr;
  local_port = ((const struct sockaddr_in *)name)->sin_port;
348 349 350

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d, addr=", s));
  ip_addr_debug_print(SOCKETS_DEBUG, &local_addr);
B
bernard.xiong 已提交
351
  LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", ntohs(local_port)));
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

  err = netconn_bind(sock->conn, &local_addr, ntohs(local_port));

  if (err != ERR_OK) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) failed, err=%d\n", s, err));
    sock_set_errno(sock, err_to_errno(err));
    return -1;
  }

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) succeeded\n", s));
  sock_set_errno(sock, 0);
  return 0;
}

int
lwip_close(int s)
{
  struct lwip_socket *sock;

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_close(%d)\n", s));

  sock = get_socket(s);
  if (!sock) {
    return -1;
  }

  netconn_delete(sock->conn);

  sys_sem_wait(socksem);
  if (sock->lastdata) {
    netbuf_delete(sock->lastdata);
  }
  sock->lastdata   = NULL;
  sock->lastoffset = 0;
  sock->conn       = NULL;
  sock_set_errno(sock, 0);
  sys_sem_signal(socksem);
  return 0;
}

int
lwip_connect(int s, const struct sockaddr *name, socklen_t namelen)
{
  struct lwip_socket *sock;
  err_t err;

  sock = get_socket(s);
  if (!sock)
    return -1;

  LWIP_ERROR("lwip_connect: invalid address", ((namelen == sizeof(struct sockaddr_in)) &&
B
bernard.xiong 已提交
403
             ((((const struct sockaddr_in *)name)->sin_family) == AF_INET)),
404 405
             sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;);

B
bernard.xiong 已提交
406
  if (((const struct sockaddr_in *)name)->sin_family == AF_UNSPEC) {
407 408 409 410 411 412
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, AF_UNSPEC)\n", s));
    err = netconn_disconnect(sock->conn);
  } else {
    struct ip_addr remote_addr;
    u16_t remote_port;

B
bernard.xiong 已提交
413 414
    remote_addr.addr = ((const struct sockaddr_in *)name)->sin_addr.s_addr;
    remote_port = ((const struct sockaddr_in *)name)->sin_port;
415 416 417

    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, addr=", s));
    ip_addr_debug_print(SOCKETS_DEBUG, &remote_addr);
B
bernard.xiong 已提交
418
    LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", ntohs(remote_port)));
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

    err = netconn_connect(sock->conn, &remote_addr, ntohs(remote_port));
  }

  if (err != ERR_OK) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) failed, err=%d\n", s, err));
    sock_set_errno(sock, err_to_errno(err));
    return -1;
  }

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) succeeded\n", s));
  sock_set_errno(sock, 0);
  return 0;
}

/**
 * Set a socket into listen mode.
 * The socket may not have been used for another connection previously.
 *
 * @param s the socket to set to listening mode
 * @param backlog (ATTENTION: need TCP_LISTEN_BACKLOG=1)
 * @return 0 on success, non-zero on failure
 */
int
lwip_listen(int s, int backlog)
{
  struct lwip_socket *sock;
  err_t err;

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d, backlog=%d)\n", s, backlog));

  sock = get_socket(s);
  if (!sock)
    return -1;

  /* limit the "backlog" parameter to fit in an u8_t */
  if (backlog < 0) {
    backlog = 0;
  }
  if (backlog > 0xff) {
    backlog = 0xff;
  }

  err = netconn_listen_with_backlog(sock->conn, backlog);

  if (err != ERR_OK) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d) failed, err=%d\n", s, err));
    sock_set_errno(sock, err_to_errno(err));
    return -1;
  }

  sock_set_errno(sock, 0);
  return 0;
}

int
B
bernard.xiong 已提交
475
lwip_recvfrom(int s, void *mem, size_t len, int flags,
476 477 478 479 480 481 482 483 484
        struct sockaddr *from, socklen_t *fromlen)
{
  struct lwip_socket *sock;
  struct netbuf      *buf;
  u16_t               buflen, copylen, off = 0;
  struct ip_addr     *addr;
  u16_t               port;
  u8_t                done = 0;

B
bernard.xiong 已提交
485
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d, %p, %"SZT_F", 0x%x, ..)\n", s, mem, len, flags));
486 487 488 489 490 491 492 493 494 495 496
  sock = get_socket(s);
  if (!sock)
    return -1;

  do {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: top while sock->lastdata=%p\n", (void*)sock->lastdata));
    /* Check if there is data left from the last recv operation. */
    if (sock->lastdata) {
      buf = sock->lastdata;
    } else {
      /* If this is non-blocking call, then check first */
B
bernard.xiong 已提交
497
      if (((flags & MSG_DONTWAIT) || (sock->flags & O_NONBLOCK)) && 
B
bernard.xiong 已提交
498 499 500 501 502 503
          (sock->rcvevent <= 0)) {
        if (off > 0) {
          /* already received data, return that */
          sock_set_errno(sock, 0);
          return off;
        }
504 505 506 507 508 509 510 511 512 513 514
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s));
        sock_set_errno(sock, EWOULDBLOCK);
        return -1;
      }

      /* No data was left from the previous operation, so we try to get
      some from the network. */
      sock->lastdata = buf = netconn_recv(sock->conn);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: netconn_recv netbuf=%p\n", (void*)buf));

      if (!buf) {
B
bernard.xiong 已提交
515 516 517 518 519
        if (off > 0) {
          /* already received data, return that */
          sock_set_errno(sock, 0);
          return off;
        }
520 521
        /* We should really do some error checking here. */
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): buf == NULL!\n", s));
B
bernard.xiong 已提交
522 523
        sock_set_errno(sock, (((sock->conn->pcb.ip != NULL) && (sock->conn->err == ERR_OK))
          ? ETIMEDOUT : err_to_errno(sock->conn->err)));
524 525 526 527 528
        return 0;
      }
    }

    buflen = netbuf_len(buf);
B
bernard.xiong 已提交
529 530
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: buflen=%"U16_F" len=%"SZT_F" off=%"U16_F" sock->lastoffset=%"U16_F"\n",
      buflen, len, off, sock->lastoffset));
531 532 533 534 535 536

    buflen -= sock->lastoffset;

    if (len > buflen) {
      copylen = buflen;
    } else {
B
bernard.xiong 已提交
537
      copylen = (u16_t)len;
538 539 540 541 542 543 544 545 546
    }

    /* copy the contents of the received buffer into
    the supplied memory pointer mem */
    netbuf_copy_partial(buf, (u8_t*)mem + off, copylen, sock->lastoffset);

    off += copylen;

    if (netconn_type(sock->conn) == NETCONN_TCP) {
B
bernard.xiong 已提交
547
      LWIP_ASSERT("invalid copylen, len would underflow", len >= copylen);
548
      len -= copylen;
B
bernard.xiong 已提交
549 550 551
      if ( (len <= 0) || 
           (buf->p->flags & PBUF_FLAG_PUSH) || 
           (sock->rcvevent <= 0) || 
B
bernard.xiong 已提交
552
           ((flags & MSG_PEEK)!=0)) {
553 554 555 556 557 558
        done = 1;
      }
    } else {
      done = 1;
    }

B
bernard.xiong 已提交
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 595 596 597 598 599 600 601 602 603 604 605
    /* Check to see from where the data was.*/
    if (done) {
      if (from && fromlen) {
        struct sockaddr_in sin;

        if (netconn_type(sock->conn) == NETCONN_TCP) {
          addr = (struct ip_addr*)&(sin.sin_addr.s_addr);
          netconn_getaddr(sock->conn, addr, &port, 0);
        } else {
          addr = netbuf_fromaddr(buf);
          port = netbuf_fromport(buf);
        }

        memset(&sin, 0, sizeof(sin));
        sin.sin_len = sizeof(sin);
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
        sin.sin_addr.s_addr = addr->addr;

        if (*fromlen > sizeof(sin)) {
          *fromlen = sizeof(sin);
        }

        MEMCPY(from, &sin, *fromlen);

        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
        ip_addr_debug_print(SOCKETS_DEBUG, addr);
        LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%"U16_F"\n", port, off));
      } else {
  #if SOCKETS_DEBUG
        struct sockaddr_in sin;

        if (netconn_type(sock->conn) == NETCONN_TCP) {
          addr = (struct ip_addr*)&(sin.sin_addr.s_addr);
          netconn_getaddr(sock->conn, addr, &port, 0);
        } else {
          addr = netbuf_fromaddr(buf);
          port = netbuf_fromport(buf);
        }

        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
        ip_addr_debug_print(SOCKETS_DEBUG, addr);
        LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%"U16_F"\n", port, off));
  #endif /*  SOCKETS_DEBUG */
      }
    }

606 607 608 609 610
    /* If we don't peek the incoming message... */
    if ((flags & MSG_PEEK)==0) {
      /* If this is a TCP socket, check if there is data left in the
         buffer. If so, it should be saved in the sock structure for next
         time around. */
B
bernard.xiong 已提交
611
      if ((netconn_type(sock->conn) == NETCONN_TCP) && (buflen - copylen > 0)) {
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        sock->lastdata = buf;
        sock->lastoffset += copylen;
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: lastdata now netbuf=%p\n", (void*)buf));
      } else {
        sock->lastdata = NULL;
        sock->lastoffset = 0;
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: deleting netbuf=%p\n", (void*)buf));
        netbuf_delete(buf);
      }
    }
  } while (!done);

  sock_set_errno(sock, 0);
  return off;
}

int
B
bernard.xiong 已提交
629
lwip_read(int s, void *mem, size_t len)
630 631 632 633 634
{
  return lwip_recvfrom(s, mem, len, 0, NULL, NULL);
}

int
B
bernard.xiong 已提交
635
lwip_recv(int s, void *mem, size_t len, int flags)
636 637 638 639 640
{
  return lwip_recvfrom(s, mem, len, flags, NULL, NULL);
}

int
B
bernard.xiong 已提交
641
lwip_send(int s, const void *data, size_t size, int flags)
642 643 644 645
{
  struct lwip_socket *sock;
  err_t err;

B
bernard.xiong 已提交
646
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%"SZT_F", flags=0x%x)\n",
647 648 649 650 651 652
                              s, data, size, flags));

  sock = get_socket(s);
  if (!sock)
    return -1;

B
bernard.xiong 已提交
653
  if (sock->conn->type != NETCONN_TCP) {
654 655 656 657 658 659 660 661 662 663
#if (LWIP_UDP || LWIP_RAW)
    return lwip_sendto(s, data, size, flags, NULL, 0);
#else
    sock_set_errno(sock, err_to_errno(ERR_ARG));
    return -1;
#endif /* (LWIP_UDP || LWIP_RAW) */
  }

  err = netconn_write(sock->conn, data, size, NETCONN_COPY | ((flags & MSG_MORE)?NETCONN_MORE:0));

B
bernard.xiong 已提交
664
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d size=%"SZT_F"\n", s, err, size));
665
  sock_set_errno(sock, err_to_errno(err));
B
bernard.xiong 已提交
666
  return (err == ERR_OK ? (int)size : -1);
667 668 669
}

int
B
bernard.xiong 已提交
670 671
lwip_sendto(int s, const void *data, size_t size, int flags,
       const struct sockaddr *to, socklen_t tolen)
672 673 674
{
  struct lwip_socket *sock;
  struct ip_addr remote_addr;
B
bernard.xiong 已提交
675 676
  err_t err;
  u16_t short_size;
677 678 679 680 681 682 683 684 685
#if !LWIP_TCPIP_CORE_LOCKING
  struct netbuf buf;
  u16_t remote_port;
#endif

  sock = get_socket(s);
  if (!sock)
    return -1;

B
bernard.xiong 已提交
686
  if (sock->conn->type == NETCONN_TCP) {
687 688 689 690 691 692 693 694
#if LWIP_TCP
    return lwip_send(s, data, size, flags);
#else
    sock_set_errno(sock, err_to_errno(ERR_ARG));
    return -1;
#endif /* LWIP_TCP */
  }

B
bernard.xiong 已提交
695 696
  LWIP_ASSERT("lwip_sendto: size must fit in u16_t", size <= 0xffff);
  short_size = (u16_t)size;
697 698
  LWIP_ERROR("lwip_sendto: invalid address", (((to == NULL) && (tolen == 0)) ||
             ((tolen == sizeof(struct sockaddr_in)) &&
B
bernard.xiong 已提交
699
             ((((const struct sockaddr_in *)to)->sin_family) == AF_INET))),
700 701 702 703 704
             sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;);

#if LWIP_TCPIP_CORE_LOCKING
  /* Should only be consider like a sample or a simple way to experiment this option (no check of "to" field...) */
  { struct pbuf* p;
B
bernard.xiong 已提交
705
  
706 707 708 709 710
    p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
    if (p == NULL) {
      err = ERR_MEM;
    } else {
      p->payload = (void*)data;
B
bernard.xiong 已提交
711
      p->len = p->tot_len = short_size;
B
bernard.xiong 已提交
712
      
B
bernard.xiong 已提交
713
      remote_addr.addr = ((const struct sockaddr_in *)to)->sin_addr.s_addr;
B
bernard.xiong 已提交
714
      
715 716 717 718
      LOCK_TCPIP_CORE();
      if (sock->conn->type==NETCONN_RAW) {
        err = sock->conn->err = raw_sendto(sock->conn->pcb.raw, p, &remote_addr);
      } else {
B
bernard.xiong 已提交
719
        err = sock->conn->err = udp_sendto(sock->conn->pcb.udp, p, &remote_addr, ntohs(((const struct sockaddr_in *)to)->sin_port));
720 721
      }
      UNLOCK_TCPIP_CORE();
B
bernard.xiong 已提交
722
      
723 724 725 726 727 728 729
      pbuf_free(p);
    }
  }
#else
  /* initialize a buffer */
  buf.p = buf.ptr = NULL;
  if (to) {
B
bernard.xiong 已提交
730 731
    remote_addr.addr = ((const struct sockaddr_in *)to)->sin_addr.s_addr;
    remote_port      = ntohs(((const struct sockaddr_in *)to)->sin_port);
732 733 734 735 736 737 738 739 740
    buf.addr         = &remote_addr;
    buf.port         = remote_port;
  } else {
    remote_addr.addr = 0;
    remote_port      = 0;
    buf.addr         = NULL;
    buf.port         = 0;
  }

B
bernard.xiong 已提交
741 742
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_sendto(%d, data=%p, short_size=%d"U16_F", flags=0x%x to=",
              s, data, short_size, flags));
743
  ip_addr_debug_print(SOCKETS_DEBUG, &remote_addr);
B
bernard.xiong 已提交
744 745
  LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", remote_port));

746
  /* make the buffer point to the data that should be sent */
B
bernard.xiong 已提交
747 748 749 750 751 752 753 754 755 756 757
#if LWIP_NETIF_TX_SINGLE_PBUF
  /* Allocate a new netbuf and copy the data into it. */
  if (netbuf_alloc(&buf, short_size) == NULL) {
    err = ERR_MEM;
  } else {
    err = netbuf_take(&buf, data, short_size);
  }
#else /* LWIP_NETIF_TX_SINGLE_PBUF */
  err = netbuf_ref(&buf, data, short_size);
#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
  if (err == ERR_OK) {
758 759 760 761 762
    /* send the data */
    err = netconn_send(sock->conn, &buf);
  }

  /* deallocated the buffer */
B
bernard.xiong 已提交
763
  netbuf_free(&buf);
764 765
#endif /* LWIP_TCPIP_CORE_LOCKING */
  sock_set_errno(sock, err_to_errno(err));
B
bernard.xiong 已提交
766
  return (err == ERR_OK ? short_size : -1);
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 820 821
}

int
lwip_socket(int domain, int type, int protocol)
{
  struct netconn *conn;
  int i;

  LWIP_UNUSED_ARG(domain);

  /* create a netconn */
  switch (type) {
  case SOCK_RAW:
    conn = netconn_new_with_proto_and_callback(NETCONN_RAW, (u8_t)protocol, event_callback);
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_RAW, %d) = ",
                                 domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
    break;
  case SOCK_DGRAM:
    conn = netconn_new_with_callback( (protocol == IPPROTO_UDPLITE) ?
                 NETCONN_UDPLITE : NETCONN_UDP, event_callback);
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_DGRAM, %d) = ",
                                 domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
    break;
  case SOCK_STREAM:
    conn = netconn_new_with_callback(NETCONN_TCP, event_callback);
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_STREAM, %d) = ",
                                 domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
    break;
  default:
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%d, %d/UNKNOWN, %d) = -1\n",
                                 domain, type, protocol));
    set_errno(EINVAL);
    return -1;
  }

  if (!conn) {
    LWIP_DEBUGF(SOCKETS_DEBUG, ("-1 / ENOBUFS (could not create netconn)\n"));
    set_errno(ENOBUFS);
    return -1;
  }

  i = alloc_socket(conn);

  if (i == -1) {
    netconn_delete(conn);
    set_errno(ENFILE);
    return -1;
  }
  conn->socket = i;
  LWIP_DEBUGF(SOCKETS_DEBUG, ("%d\n", i));
  set_errno(0);
  return i;
}

int
B
bernard.xiong 已提交
822
lwip_write(int s, const void *data, size_t size)
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
{
  return lwip_send(s, data, size, 0);
}

/**
 * Go through the readset and writeset lists and see which socket of the sockets
 * set in the sets has events. On return, readset, writeset and exceptset have
 * the sockets enabled that had events.
 *
 * exceptset is not used for now!!!
 *
 * @param maxfdp1 the highest socket index in the sets
 * @param readset in: set of sockets to check for read events;
 *                out: set of sockets that had read events
 * @param writeset in: set of sockets to check for write events;
 *                 out: set of sockets that had write events
 * @param exceptset not yet implemented
 * @return number of sockets that had events (read+write)
 */
static int
lwip_selscan(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset)
{
  int i, nready = 0;
  fd_set lreadset, lwriteset, lexceptset;
  struct lwip_socket *p_sock;
B
bernard.xiong 已提交
848
  
849 850 851
  FD_ZERO(&lreadset);
  FD_ZERO(&lwriteset);
  FD_ZERO(&lexceptset);
B
bernard.xiong 已提交
852
  
853 854 855 856 857 858
  /* Go through each socket in each list to count number of sockets which
  currently match */
  for(i = 0; i < maxfdp1; i++) {
    if (FD_ISSET(i, readset)) {
      /* See if netconn of this socket is ready for read */
      p_sock = get_socket(i);
B
bernard.xiong 已提交
859
      if (p_sock && (p_sock->lastdata || (p_sock->rcvevent > 0))) {
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
        FD_SET(i, &lreadset);
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for reading\n", i));
        nready++;
      }
    }
    if (FD_ISSET(i, writeset)) {
      /* See if netconn of this socket is ready for write */
      p_sock = get_socket(i);
      if (p_sock && p_sock->sendevent) {
        FD_SET(i, &lwriteset);
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for writing\n", i));
        nready++;
      }
    }
  }
  *readset = lreadset;
  *writeset = lwriteset;
  FD_ZERO(exceptset);
B
bernard.xiong 已提交
878
  
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
  return nready;
}


/**
 * Processing exceptset is not yet implemented.
 */
int
lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
               struct timeval *timeout)
{
  int i;
  int nready;
  fd_set lreadset, lwriteset, lexceptset;
  u32_t msectimeout;
  struct lwip_select_cb select_cb;
  struct lwip_select_cb *p_selcb;

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select(%d, %p, %p, %p, tvsec=%ld tvusec=%ld)\n",
                  maxfdp1, (void *)readset, (void *) writeset, (void *) exceptset,
B
bernard.xiong 已提交
899 900
                  timeout ? (long)timeout->tv_sec : (long)-1,
                  timeout ? (long)timeout->tv_usec : (long)-1));
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

  select_cb.next = 0;
  select_cb.readset = readset;
  select_cb.writeset = writeset;
  select_cb.exceptset = exceptset;
  select_cb.sem_signalled = 0;

  /* Protect ourselves searching through the list */
  sys_sem_wait(selectsem);

  if (readset)
    lreadset = *readset;
  else
    FD_ZERO(&lreadset);
  if (writeset)
    lwriteset = *writeset;
  else
    FD_ZERO(&lwriteset);
  if (exceptset)
    lexceptset = *exceptset;
  else
    FD_ZERO(&lexceptset);

  /* Go through each socket in each list to count number of sockets which
     currently match */
  nready = lwip_selscan(maxfdp1, &lreadset, &lwriteset, &lexceptset);

  /* If we don't have any current events, then suspend if we are supposed to */
  if (!nready) {
    if (timeout && timeout->tv_sec == 0 && timeout->tv_usec == 0) {
      sys_sem_signal(selectsem);
      if (readset)
        FD_ZERO(readset);
      if (writeset)
        FD_ZERO(writeset);
      if (exceptset)
        FD_ZERO(exceptset);
B
bernard.xiong 已提交
938
  
939 940
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: no timeout, returning 0\n"));
      set_errno(0);
B
bernard.xiong 已提交
941
  
942 943
      return 0;
    }
B
bernard.xiong 已提交
944
    
945 946 947 948
    /* add our semaphore to list */
    /* We don't actually need any dynamic memory. Our entry on the
     * list is only valid while we are in this function, so it's ok
     * to use local variables */
B
bernard.xiong 已提交
949
    
950 951 952 953 954
    select_cb.sem = sys_sem_new(0);
    /* Note that we are still protected */
    /* Put this select_cb on top of list */
    select_cb.next = select_cb_list;
    select_cb_list = &select_cb;
B
bernard.xiong 已提交
955
    
956 957
    /* Now we can safely unprotect */
    sys_sem_signal(selectsem);
B
bernard.xiong 已提交
958
    
959 960 961 962 963 964 965 966 967
    /* Now just wait to be woken */
    if (timeout == 0)
      /* Wait forever */
      msectimeout = 0;
    else {
      msectimeout =  ((timeout->tv_sec * 1000) + ((timeout->tv_usec + 500)/1000));
      if(msectimeout == 0)
        msectimeout = 1;
    }
B
bernard.xiong 已提交
968
    
969
	if (sys_arch_timeouts() == NULL){
970 971 972 973 974 975 976 977 978
	  /* it's not a lwip thread, use os semaphore with timeout to handle it */
	  i = sys_arch_sem_wait(select_cb.sem, msectimeout);
	  if (i == SYS_ARCH_TIMEOUT) i = 0;
	  else i = 1;
	}
    else {
	  /* it's a lwip thread, use os semaphore with timeout to handle it */
      i = sys_sem_wait_timeout(select_cb.sem, msectimeout);
    }
B
bernard.xiong 已提交
979
    
980 981 982 983 984 985 986 987 988 989 990
    /* Take us off the list */
    sys_sem_wait(selectsem);
    if (select_cb_list == &select_cb)
      select_cb_list = select_cb.next;
    else
      for (p_selcb = select_cb_list; p_selcb; p_selcb = p_selcb->next) {
        if (p_selcb->next == &select_cb) {
          p_selcb->next = select_cb.next;
          break;
        }
      }
B
bernard.xiong 已提交
991
    
992
    sys_sem_signal(selectsem);
B
bernard.xiong 已提交
993
    
994 995 996 997 998 999 1000 1001 1002
    sys_sem_free(select_cb.sem);
    if (i == 0)  {
      /* Timeout */
      if (readset)
        FD_ZERO(readset);
      if (writeset)
        FD_ZERO(writeset);
      if (exceptset)
        FD_ZERO(exceptset);
B
bernard.xiong 已提交
1003
  
1004 1005
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: timeout expired\n"));
      set_errno(0);
B
bernard.xiong 已提交
1006
  
1007 1008
      return 0;
    }
B
bernard.xiong 已提交
1009
    
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    if (readset)
      lreadset = *readset;
    else
      FD_ZERO(&lreadset);
    if (writeset)
      lwriteset = *writeset;
    else
      FD_ZERO(&lwriteset);
    if (exceptset)
      lexceptset = *exceptset;
    else
      FD_ZERO(&lexceptset);
B
bernard.xiong 已提交
1022
    
1023 1024 1025 1026
    /* See what's set */
    nready = lwip_selscan(maxfdp1, &lreadset, &lwriteset, &lexceptset);
  } else
    sys_sem_signal(selectsem);
B
bernard.xiong 已提交
1027
  
1028 1029 1030 1031 1032 1033
  if (readset)
    *readset = lreadset;
  if (writeset)
    *writeset = lwriteset;
  if (exceptset)
    *exceptset = lexceptset;
B
bernard.xiong 已提交
1034
  
1035 1036
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: nready=%d\n", nready));
  set_errno(0);
B
bernard.xiong 已提交
1037
  
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
  return nready;
}

/**
 * Callback registered in the netconn layer for each socket-netconn.
 * Processes recvevent (data available) and wakes up tasks waiting for select.
 */
static void
event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len)
{
  int s;
  struct lwip_socket *sock;
  struct lwip_select_cb *scb;

  LWIP_UNUSED_ARG(len);

  /* Get socket */
  if (conn) {
    s = conn->socket;
    if (s < 0) {
      /* Data comes in right away after an accept, even though
       * the server task might not have created a new socket yet.
       * Just count down (or up) if that's the case and we
       * will use the data later. Note that only receive events
       * can happen before the new socket is set up. */
      sys_sem_wait(socksem);
      if (conn->socket < 0) {
        if (evt == NETCONN_EVT_RCVPLUS) {
          conn->socket--;
        }
        sys_sem_signal(socksem);
        return;
      }
B
bernard.xiong 已提交
1071
      s = conn->socket;
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      sys_sem_signal(socksem);
    }

    sock = get_socket(s);
    if (!sock) {
      return;
    }
  } else {
    return;
  }

  sys_sem_wait(selectsem);
  /* Set event as required */
  switch (evt) {
    case NETCONN_EVT_RCVPLUS:
      sock->rcvevent++;
      break;
    case NETCONN_EVT_RCVMINUS:
      sock->rcvevent--;
      break;
    case NETCONN_EVT_SENDPLUS:
      sock->sendevent = 1;
      break;
    case NETCONN_EVT_SENDMINUS:
      sock->sendevent = 0;
      break;
    default:
      LWIP_ASSERT("unknown event", 0);
      break;
  }
  sys_sem_signal(selectsem);

  /* Now decide if anyone is waiting for this socket */
  /* NOTE: This code is written this way to protect the select link list
     but to avoid a deadlock situation by releasing socksem before
     signalling for the select. This means we need to go through the list
     multiple times ONLY IF a select was actually waiting. We go through
     the list the number of waiting select calls + 1. This list is
     expected to be small. */
  while (1) {
    sys_sem_wait(selectsem);
    for (scb = select_cb_list; scb; scb = scb->next) {
      if (scb->sem_signalled == 0) {
        /* Test this select call for our socket */
        if (scb->readset && FD_ISSET(s, scb->readset))
B
bernard.xiong 已提交
1117
          if (sock->rcvevent > 0)
1118 1119 1120 1121 1122 1123 1124 1125 1126
            break;
        if (scb->writeset && FD_ISSET(s, scb->writeset))
          if (sock->sendevent)
            break;
      }
    }
    if (scb) {
      scb->sem_signalled = 1;
      sys_sem_signal(scb->sem);
B
bernard.xiong 已提交
1127
      sys_sem_signal(selectsem);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    } else {
      sys_sem_signal(selectsem);
      break;
    }
  }
}

/**
 * Unimplemented: Close one end of a full-duplex connection.
 * Currently, the full connection is closed.
 */
int
lwip_shutdown(int s, int how)
{
  LWIP_UNUSED_ARG(how);
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_shutdown(%d, how=%d)\n", s, how));
  return lwip_close(s); /* XXX temporary hack until proper implementation */
}

static int
lwip_getaddrname(int s, struct sockaddr *name, socklen_t *namelen, u8_t local)
{
  struct lwip_socket *sock;
  struct sockaddr_in sin;
  struct ip_addr naddr;

  sock = get_socket(s);
  if (!sock)
    return -1;

  memset(&sin, 0, sizeof(sin));
  sin.sin_len = sizeof(sin);
  sin.sin_family = AF_INET;

  /* get the IP address and port */
  netconn_getaddr(sock->conn, &naddr, &sin.sin_port, local);

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getaddrname(%d, addr=", s));
  ip_addr_debug_print(SOCKETS_DEBUG, &naddr);
B
bernard.xiong 已提交
1167
  LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", sin.sin_port));
1168 1169 1170 1171 1172 1173 1174

  sin.sin_port = htons(sin.sin_port);
  sin.sin_addr.s_addr = naddr.addr;

  if (*namelen > sizeof(sin))
    *namelen = sizeof(sin);

B
bernard.xiong 已提交
1175
  MEMCPY(name, &sin, *namelen);
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
  sock_set_errno(sock, 0);
  return 0;
}

int
lwip_getpeername(int s, struct sockaddr *name, socklen_t *namelen)
{
  return lwip_getaddrname(s, name, namelen, 0);
}

int
lwip_getsockname(int s, struct sockaddr *name, socklen_t *namelen)
{
  return lwip_getaddrname(s, name, namelen, 1);
}

int
lwip_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
{
  err_t err = ERR_OK;
  struct lwip_socket *sock = get_socket(s);
  struct lwip_setgetsockopt_data data;

  if (!sock)
    return -1;

  if ((NULL == optval) || (NULL == optlen)) {
    sock_set_errno(sock, EFAULT);
    return -1;
  }

  /* Do length and type checks for the various options first, to keep it readable. */
  switch (level) {
B
bernard.xiong 已提交
1209
   
1210 1211 1212
/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch (optname) {
B
bernard.xiong 已提交
1213
       
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    case SO_ACCEPTCONN:
    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_ERROR:
    case SO_KEEPALIVE:
    /* UNIMPL case SO_CONTIMEO: */
    /* UNIMPL case SO_SNDTIMEO: */
#if LWIP_SO_RCVTIMEO
    case SO_RCVTIMEO:
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
    case SO_RCVBUF:
#endif /* LWIP_SO_RCVBUF */
    /* UNIMPL case SO_OOBINLINE: */
    /* UNIMPL case SO_SNDBUF: */
    /* UNIMPL case SO_RCVLOWAT: */
    /* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    case SO_TYPE:
    /* UNIMPL case SO_USELOOPBACK: */
      if (*optlen < sizeof(int)) {
        err = EINVAL;
      }
      break;

    case SO_NO_CHECK:
      if (*optlen < sizeof(int)) {
        err = EINVAL;
      }
#if LWIP_UDP
      if ((sock->conn->type != NETCONN_UDP) ||
          ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0)) {
        /* this flag is only available for UDP, not for UDP lite */
        err = EAFNOSUPPORT;
      }
#endif /* LWIP_UDP */
      break;

    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n",
                                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
B
bernard.xiong 已提交
1262
                     
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch (optname) {
    /* UNIMPL case IP_HDRINCL: */
    /* UNIMPL case IP_RCVDSTADDR: */
    /* UNIMPL case IP_RCVIF: */
    case IP_TTL:
    case IP_TOS:
      if (*optlen < sizeof(int)) {
        err = EINVAL;
      }
      break;
#if LWIP_IGMP
    case IP_MULTICAST_TTL:
      if (*optlen < sizeof(u8_t)) {
        err = EINVAL;
      }
      break;
    case IP_MULTICAST_IF:
      if (*optlen < sizeof(struct in_addr)) {
        err = EINVAL;
      }
      break;
#endif /* LWIP_IGMP */

    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n",
                                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
B
bernard.xiong 已提交
1294
         
1295 1296 1297 1298 1299 1300 1301
#if LWIP_TCP
/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    if (*optlen < sizeof(int)) {
      err = EINVAL;
      break;
    }
B
bernard.xiong 已提交
1302
    
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    /* If this is no TCP socket, ignore any options. */
    if (sock->conn->type != NETCONN_TCP)
      return 0;

    switch (optname) {
    case TCP_NODELAY:
    case TCP_KEEPALIVE:
#if LWIP_TCP_KEEPALIVE
    case TCP_KEEPIDLE:
    case TCP_KEEPINTVL:
    case TCP_KEEPCNT:
#endif /* LWIP_TCP_KEEPALIVE */
      break;
B
bernard.xiong 已提交
1316
       
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n",
                                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
#endif /* LWIP_TCP */
#if LWIP_UDP && LWIP_UDPLITE
/* Level: IPPROTO_UDPLITE */
  case IPPROTO_UDPLITE:
    if (*optlen < sizeof(int)) {
      err = EINVAL;
      break;
    }
B
bernard.xiong 已提交
1331
    
1332 1333 1334 1335 1336 1337 1338 1339
    /* If this is no UDP lite socket, ignore any options. */
    if (sock->conn->type != NETCONN_UDPLITE)
      return 0;

    switch (optname) {
    case UDPLITE_SEND_CSCOV:
    case UDPLITE_RECV_CSCOV:
      break;
B
bernard.xiong 已提交
1340
       
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n",
                                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
#endif /* LWIP_UDP && LWIP_UDPLITE*/
/* UNDEFINED LEVEL */
  default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n",
                                  s, level, optname));
      err = ENOPROTOOPT;
  }  /* switch */

B
bernard.xiong 已提交
1355
   
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  if (err != ERR_OK) {
    sock_set_errno(sock, err);
    return -1;
  }

  /* Now do the actual option processing */
  data.sock = sock;
  data.level = level;
  data.optname = optname;
  data.optval = optval;
  data.optlen = optlen;
  data.err = err;
  tcpip_callback(lwip_getsockopt_internal, &data);
  sys_arch_sem_wait(sock->conn->op_completed, 0);
  /* maybe lwip_getsockopt_internal has changed err */
  err = data.err;

  sock_set_errno(sock, err);
  return err ? -1 : 0;
}

static void
lwip_getsockopt_internal(void *arg)
{
  struct lwip_socket *sock;
#ifdef LWIP_DEBUG
  int s;
#endif /* LWIP_DEBUG */
  int level, optname;
  void *optval;
  struct lwip_setgetsockopt_data *data;

  LWIP_ASSERT("arg != NULL", arg != NULL);

  data = (struct lwip_setgetsockopt_data*)arg;
  sock = data->sock;
#ifdef LWIP_DEBUG
  s = data->s;
#endif /* LWIP_DEBUG */
  level = data->level;
  optname = data->optname;
  optval = data->optval;

  switch (level) {
B
bernard.xiong 已提交
1400
   
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch (optname) {

    /* The option flags */
    case SO_ACCEPTCONN:
    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /*case SO_USELOOPBACK: UNIMPL */
      *(int*)optval = sock->conn->pcb.ip->so_options & optname;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, optname=0x%x, ..) = %s\n",
                                  s, optname, (*(int*)optval?"on":"off")));
      break;

    case SO_TYPE:
      switch (NETCONNTYPE_GROUP(sock->conn->type)) {
      case NETCONN_RAW:
        *(int*)optval = SOCK_RAW;
        break;
      case NETCONN_TCP:
        *(int*)optval = SOCK_STREAM;
        break;
      case NETCONN_UDP:
        *(int*)optval = SOCK_DGRAM;
        break;
      default: /* unrecognized socket type */
        *(int*)optval = sock->conn->type;
        LWIP_DEBUGF(SOCKETS_DEBUG,
                    ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE): unrecognized socket type %d\n",
                    s, *(int *)optval));
      }  /* switch (sock->conn->type) */
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE) = %d\n",
                  s, *(int *)optval));
      break;

    case SO_ERROR:
      if (sock->err == 0) {
        sock_set_errno(sock, err_to_errno(sock->conn->err));
B
bernard.xiong 已提交
1446
      } 
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
      *(int *)optval = sock->err;
      sock->err = 0;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_ERROR) = %d\n",
                  s, *(int *)optval));
      break;

#if LWIP_SO_RCVTIMEO
    case SO_RCVTIMEO:
      *(int *)optval = sock->conn->recv_timeout;
      break;
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
    case SO_RCVBUF:
      *(int *)optval = sock->conn->recv_bufsize;
      break;
#endif /* LWIP_SO_RCVBUF */
#if LWIP_UDP
    case SO_NO_CHECK:
      *(int*)optval = (udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_NOCHKSUM) ? 1 : 0;
      break;
#endif /* LWIP_UDP*/
    }  /* switch (optname) */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch (optname) {
    case IP_TTL:
      *(int*)optval = sock->conn->pcb.ip->ttl;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TTL) = %d\n",
                  s, *(int *)optval));
      break;
    case IP_TOS:
      *(int*)optval = sock->conn->pcb.ip->tos;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TOS) = %d\n",
                  s, *(int *)optval));
      break;
#if LWIP_IGMP
    case IP_MULTICAST_TTL:
      *(u8_t*)optval = sock->conn->pcb.ip->ttl;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_TTL) = %d\n",
                  s, *(int *)optval));
      break;
    case IP_MULTICAST_IF:
      ((struct in_addr*) optval)->s_addr = sock->conn->pcb.udp->multicast_ip.addr;
B
bernard.xiong 已提交
1492
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_IF) = 0x%"X32_F"\n",
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
                  s, *(u32_t *)optval));
      break;
#endif /* LWIP_IGMP */
    }  /* switch (optname) */
    break;

#if LWIP_TCP
/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    switch (optname) {
    case TCP_NODELAY:
B
bernard.xiong 已提交
1504
      *(int*)optval = tcp_nagle_disabled(sock->conn->pcb.tcp);
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_NODELAY) = %s\n",
                  s, (*(int*)optval)?"on":"off") );
      break;
    case TCP_KEEPALIVE:
      *(int*)optval = (int)sock->conn->pcb.tcp->keep_idle;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPALIVE) = %d\n",
                  s, *(int *)optval));
      break;

#if LWIP_TCP_KEEPALIVE
    case TCP_KEEPIDLE:
      *(int*)optval = (int)(sock->conn->pcb.tcp->keep_idle/1000);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPIDLE) = %d\n",
                  s, *(int *)optval));
      break;
    case TCP_KEEPINTVL:
      *(int*)optval = (int)(sock->conn->pcb.tcp->keep_intvl/1000);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPINTVL) = %d\n",
                  s, *(int *)optval));
      break;
    case TCP_KEEPCNT:
      *(int*)optval = (int)sock->conn->pcb.tcp->keep_cnt;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPCNT) = %d\n",
                  s, *(int *)optval));
      break;
#endif /* LWIP_TCP_KEEPALIVE */

    }  /* switch (optname) */
    break;
#endif /* LWIP_TCP */
#if LWIP_UDP && LWIP_UDPLITE
  /* Level: IPPROTO_UDPLITE */
  case IPPROTO_UDPLITE:
    switch (optname) {
    case UDPLITE_SEND_CSCOV:
      *(int*)optval = sock->conn->pcb.udp->chksum_len_tx;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) = %d\n",
                  s, (*(int*)optval)) );
      break;
    case UDPLITE_RECV_CSCOV:
      *(int*)optval = sock->conn->pcb.udp->chksum_len_rx;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) = %d\n",
                  s, (*(int*)optval)) );
      break;
    }  /* switch (optname) */
    break;
#endif /* LWIP_UDP */
  } /* switch (level) */
  sys_sem_signal(sock->conn->op_completed);
}

int
lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen)
{
  struct lwip_socket *sock = get_socket(s);
  int err = ERR_OK;
  struct lwip_setgetsockopt_data data;

  if (!sock)
    return -1;

  if (NULL == optval) {
    sock_set_errno(sock, EFAULT);
    return -1;
  }

  /* Do length and type checks for the various options first, to keep it readable. */
  switch (level) {

/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch (optname) {

    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case case SO_CONTIMEO: */
    /* UNIMPL case case SO_SNDTIMEO: */
#if LWIP_SO_RCVTIMEO
    case SO_RCVTIMEO:
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
    case SO_RCVBUF:
#endif /* LWIP_SO_RCVBUF */
    /* UNIMPL case SO_OOBINLINE: */
    /* UNIMPL case SO_SNDBUF: */
    /* UNIMPL case SO_RCVLOWAT: */
    /* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /* UNIMPL case SO_USELOOPBACK: */
      if (optlen < sizeof(int)) {
        err = EINVAL;
      }
      break;
    case SO_NO_CHECK:
      if (optlen < sizeof(int)) {
        err = EINVAL;
      }
#if LWIP_UDP
      if ((sock->conn->type != NETCONN_UDP) ||
          ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0)) {
        /* this flag is only available for UDP, not for UDP lite */
        err = EAFNOSUPPORT;
      }
#endif /* LWIP_UDP */
      break;
    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n",
                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch (optname) {
    /* UNIMPL case IP_HDRINCL: */
    /* UNIMPL case IP_RCVDSTADDR: */
    /* UNIMPL case IP_RCVIF: */
    case IP_TTL:
    case IP_TOS:
      if (optlen < sizeof(int)) {
        err = EINVAL;
      }
      break;
#if LWIP_IGMP
    case IP_MULTICAST_TTL:
      if (optlen < sizeof(u8_t)) {
        err = EINVAL;
      }
      if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) {
        err = EAFNOSUPPORT;
      }
      break;
    case IP_MULTICAST_IF:
      if (optlen < sizeof(struct in_addr)) {
        err = EINVAL;
      }
      if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) {
        err = EAFNOSUPPORT;
      }
      break;
    case IP_ADD_MEMBERSHIP:
    case IP_DROP_MEMBERSHIP:
      if (optlen < sizeof(struct ip_mreq)) {
        err = EINVAL;
      }
      if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) {
        err = EAFNOSUPPORT;
      }
      break;
#endif /* LWIP_IGMP */
      default:
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n",
                    s, optname));
        err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;

#if LWIP_TCP
/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    if (optlen < sizeof(int)) {
      err = EINVAL;
      break;
    }

    /* If this is no TCP socket, ignore any options. */
    if (sock->conn->type != NETCONN_TCP)
      return 0;

    switch (optname) {
    case TCP_NODELAY:
    case TCP_KEEPALIVE:
#if LWIP_TCP_KEEPALIVE
    case TCP_KEEPIDLE:
    case TCP_KEEPINTVL:
    case TCP_KEEPCNT:
#endif /* LWIP_TCP_KEEPALIVE */
      break;

    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n",
                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
#endif /* LWIP_TCP */
#if LWIP_UDP && LWIP_UDPLITE
/* Level: IPPROTO_UDPLITE */
  case IPPROTO_UDPLITE:
    if (optlen < sizeof(int)) {
      err = EINVAL;
      break;
    }

    /* If this is no UDP lite socket, ignore any options. */
    if (sock->conn->type != NETCONN_UDPLITE)
      return 0;

    switch (optname) {
    case UDPLITE_SEND_CSCOV:
    case UDPLITE_RECV_CSCOV:
      break;

    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n",
                  s, optname));
      err = ENOPROTOOPT;
    }  /* switch (optname) */
    break;
#endif /* LWIP_UDP && LWIP_UDPLITE */
/* UNDEFINED LEVEL */
  default:
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n",
                s, level, optname));
    err = ENOPROTOOPT;
  }  /* switch (level) */


  if (err != ERR_OK) {
    sock_set_errno(sock, err);
    return -1;
  }


  /* Now do the actual option processing */
  data.sock = sock;
  data.level = level;
  data.optname = optname;
  data.optval = (void*)optval;
  data.optlen = &optlen;
  data.err = err;
  tcpip_callback(lwip_setsockopt_internal, &data);
  sys_arch_sem_wait(sock->conn->op_completed, 0);
  /* maybe lwip_setsockopt_internal has changed err */
  err = data.err;

  sock_set_errno(sock, err);
  return err ? -1 : 0;
}

static void
lwip_setsockopt_internal(void *arg)
{
  struct lwip_socket *sock;
#ifdef LWIP_DEBUG
  int s;
#endif /* LWIP_DEBUG */
  int level, optname;
  const void *optval;
  struct lwip_setgetsockopt_data *data;

  LWIP_ASSERT("arg != NULL", arg != NULL);

  data = (struct lwip_setgetsockopt_data*)arg;
  sock = data->sock;
#ifdef LWIP_DEBUG
  s = data->s;
#endif /* LWIP_DEBUG */
  level = data->level;
  optname = data->optname;
  optval = data->optval;

  switch (level) {

/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch (optname) {

    /* The option flags */
    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /* UNIMPL case SO_USELOOPBACK: */
      if (*(int*)optval) {
        sock->conn->pcb.ip->so_options |= optname;
      } else {
        sock->conn->pcb.ip->so_options &= ~optname;
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, optname=0x%x, ..) -> %s\n",
                  s, optname, (*(int*)optval?"on":"off")));
      break;
#if LWIP_SO_RCVTIMEO
    case SO_RCVTIMEO:
      sock->conn->recv_timeout = ( *(int*)optval );
      break;
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
    case SO_RCVBUF:
      sock->conn->recv_bufsize = ( *(int*)optval );
      break;
#endif /* LWIP_SO_RCVBUF */
#if LWIP_UDP
    case SO_NO_CHECK:
      if (*(int*)optval) {
        udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) | UDP_FLAGS_NOCHKSUM);
      } else {
        udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) & ~UDP_FLAGS_NOCHKSUM);
      }
      break;
#endif /* LWIP_UDP */
    }  /* switch (optname) */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch (optname) {
    case IP_TTL:
      sock->conn->pcb.ip->ttl = (u8_t)(*(int*)optval);
B
bernard.xiong 已提交
1825
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TTL, ..) -> %d\n",
1826 1827 1828 1829
                  s, sock->conn->pcb.ip->ttl));
      break;
    case IP_TOS:
      sock->conn->pcb.ip->tos = (u8_t)(*(int*)optval);
B
bernard.xiong 已提交
1830
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TOS, ..)-> %d\n",
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
                  s, sock->conn->pcb.ip->tos));
      break;
#if LWIP_IGMP
    case IP_MULTICAST_TTL:
      sock->conn->pcb.udp->ttl = (u8_t)(*(u8_t*)optval);
      break;
    case IP_MULTICAST_IF:
      sock->conn->pcb.udp->multicast_ip.addr = ((struct in_addr*) optval)->s_addr;
      break;
    case IP_ADD_MEMBERSHIP:
    case IP_DROP_MEMBERSHIP:
      {
        /* If this is a TCP or a RAW socket, ignore these options. */
        struct ip_mreq *imr = (struct ip_mreq *)optval;
        if(optname == IP_ADD_MEMBERSHIP){
          data->err = igmp_joingroup((struct ip_addr*)&(imr->imr_interface.s_addr), (struct ip_addr*)&(imr->imr_multiaddr.s_addr));
        } else {
          data->err = igmp_leavegroup((struct ip_addr*)&(imr->imr_interface.s_addr), (struct ip_addr*)&(imr->imr_multiaddr.s_addr));
        }
        if(data->err != ERR_OK) {
          data->err = EADDRNOTAVAIL;
        }
      }
      break;
#endif /* LWIP_IGMP */
    }  /* switch (optname) */
    break;

#if LWIP_TCP
/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    switch (optname) {
    case TCP_NODELAY:
      if (*(int*)optval) {
B
bernard.xiong 已提交
1865
        tcp_nagle_disable(sock->conn->pcb.tcp);
1866
      } else {
B
bernard.xiong 已提交
1867
        tcp_nagle_enable(sock->conn->pcb.tcp);
1868 1869 1870 1871 1872 1873
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) -> %s\n",
                  s, (*(int *)optval)?"on":"off") );
      break;
    case TCP_KEEPALIVE:
      sock->conn->pcb.tcp->keep_idle = (u32_t)(*(int*)optval);
B
bernard.xiong 已提交
1874
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) -> %"U32_F"\n",
1875 1876 1877 1878 1879 1880
                  s, sock->conn->pcb.tcp->keep_idle));
      break;

#if LWIP_TCP_KEEPALIVE
    case TCP_KEEPIDLE:
      sock->conn->pcb.tcp->keep_idle = 1000*(u32_t)(*(int*)optval);
B
bernard.xiong 已提交
1881
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPIDLE) -> %"U32_F"\n",
1882 1883 1884 1885
                  s, sock->conn->pcb.tcp->keep_idle));
      break;
    case TCP_KEEPINTVL:
      sock->conn->pcb.tcp->keep_intvl = 1000*(u32_t)(*(int*)optval);
B
bernard.xiong 已提交
1886
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPINTVL) -> %"U32_F"\n",
1887 1888 1889 1890
                  s, sock->conn->pcb.tcp->keep_intvl));
      break;
    case TCP_KEEPCNT:
      sock->conn->pcb.tcp->keep_cnt = (u32_t)(*(int*)optval);
B
bernard.xiong 已提交
1891
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPCNT) -> %"U32_F"\n",
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
                  s, sock->conn->pcb.tcp->keep_cnt));
      break;
#endif /* LWIP_TCP_KEEPALIVE */

    }  /* switch (optname) */
    break;
#endif /* LWIP_TCP*/
#if LWIP_UDP && LWIP_UDPLITE
  /* Level: IPPROTO_UDPLITE */
  case IPPROTO_UDPLITE:
    switch (optname) {
    case UDPLITE_SEND_CSCOV:
      if ((*(int*)optval != 0) && (*(int*)optval < 8)) {
        /* don't allow illegal values! */
        sock->conn->pcb.udp->chksum_len_tx = 8;
      } else {
        sock->conn->pcb.udp->chksum_len_tx = *(int*)optval;
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) -> %d\n",
                  s, (*(int*)optval)) );
      break;
    case UDPLITE_RECV_CSCOV:
      if ((*(int*)optval != 0) && (*(int*)optval < 8)) {
        /* don't allow illegal values! */
        sock->conn->pcb.udp->chksum_len_rx = 8;
      } else {
        sock->conn->pcb.udp->chksum_len_rx = *(int*)optval;
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) -> %d\n",
                  s, (*(int*)optval)) );
      break;
    }  /* switch (optname) */
    break;
#endif /* LWIP_UDP */
  }  /* switch (level) */
  sys_sem_signal(sock->conn->op_completed);
}

int
lwip_ioctl(int s, long cmd, void *argp)
{
  struct lwip_socket *sock = get_socket(s);
  u16_t buflen = 0;
B
bernard.xiong 已提交
1935
  s16_t recv_avail;
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

  if (!sock)
    return -1;

  switch (cmd) {
  case FIONREAD:
    if (!argp) {
      sock_set_errno(sock, EINVAL);
      return -1;
    }

B
bernard.xiong 已提交
1947 1948 1949 1950
    SYS_ARCH_GET(sock->conn->recv_avail, recv_avail);
    if (recv_avail < 0)
      recv_avail = 0;
    *((u16_t*)argp) = (u16_t)recv_avail;
1951 1952 1953 1954 1955 1956 1957 1958 1959

    /* Check if there is data left from the last recv operation. /maq 041215 */
    if (sock->lastdata) {
      buflen = netbuf_len(sock->lastdata);
      buflen -= sock->lastoffset;

      *((u16_t*)argp) += buflen;
    }

B
bernard.xiong 已提交
1960
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONREAD, %p) = %"U16_F"\n", s, argp, *((u16_t*)argp)));
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    sock_set_errno(sock, 0);
    return 0;

  case FIONBIO:
    if (argp && *(u32_t*)argp)
      sock->flags |= O_NONBLOCK;
    else
      sock->flags &= ~O_NONBLOCK;
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONBIO, %d)\n", s, !!(sock->flags & O_NONBLOCK)));
    sock_set_errno(sock, 0);
    return 0;

  default:
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, UNIMPL: 0x%lx, %p)\n", s, cmd, argp));
    sock_set_errno(sock, ENOSYS); /* not yet implemented */
    return -1;
  } /* switch (cmd) */
}

#endif /* LWIP_SOCKET */