Exemple #1
0
/*
 * Setup RTSP(S) connection
 */
static int
iptv_rtsp_start
  ( iptv_mux_t *im, const char *raw, const url_t *u )
{
  rtsp_priv_t *rp;
  http_client_t *hc;
  udp_connection_t *rtp, *rtcp;
  int r;

  if (!(hc = http_client_connect(im, RTSP_VERSION_1_0, u->scheme,
                                 u->host, u->port, NULL)))
    return SM_CODE_TUNING_FAILED;

  if (u->user)
    hc->hc_rtsp_user = strdup(u->user);
  if (u->pass)
    hc->hc_rtsp_pass = strdup(u->pass);

  if (udp_bind_double(&rtp, &rtcp,
                      "IPTV", "rtp", "rtcp",
                      NULL, 0, NULL,
                      128*1024, 16384, 4*1024, 4*1024) < 0) {
    http_client_close(hc);
    return SM_CODE_TUNING_FAILED;
  }

  hc->hc_hdr_received        = iptv_rtsp_header;
  hc->hc_data_received       = iptv_rtsp_data;
  hc->hc_handle_location     = 1;                      /* allow redirects */
  hc->hc_rtsp_keep_alive_cmd = RTSP_CMD_GET_PARAMETER; /* start keep alive loop with GET_PARAMETER */
  http_client_register(hc);                            /* register to the HTTP thread */
  r = rtsp_setup(hc, u->path, u->query, NULL,
                 ntohs(IP_PORT(rtp->ip)),
                 ntohs(IP_PORT(rtcp->ip)));
  if (r < 0) {
    udp_close(rtcp);
    udp_close(rtp);
    http_client_close(hc);
    return SM_CODE_TUNING_FAILED;
  }

  rp = calloc(1, sizeof(*rp));
  rp->rtcp_info = calloc(1, sizeof(iptv_rtcp_info_t));
  rtcp_init(rp->rtcp_info);
  rp->rtcp_info->connection = rtcp;
  rp->hc = hc;
  udp_multirecv_init(&rp->um, IPTV_PKTS, IPTV_PKT_PAYLOAD);
  rp->path = strdup(u->path ?: "");
  rp->query = strdup(u->query ?: "");

  im->im_data = rp;
  im->mm_iptv_fd = rtp->fd;
  im->mm_iptv_connection = rtp;
  im->mm_iptv_fd2 = rtcp->fd;
  im->mm_iptv_connection2 = rtcp;

  return 0;
}
/* start a new listen server to get the list */
int ogc_init (char *localport, char *server, char *port, char *game, int ai_family) {
	int i;
	
	ogc_sock = -1;

	ogc_sock = udp_server (localport, ai_family);
	d_printf ("ogc_init (Localport: %s, Server %s:%s Game %s socket=%d)\n", localport, server, port, game, ogc_sock);
	if (ogc_sock <= 0)
		return 0;

	strncpy (ogc_host, server, LEN_OGCHOST);
	strncpy (ogc_port, port, LEN_OGCPORT);
	strncpy (ogc_game, game, LEN_GAME);
	ogc_ai_family = ai_family;
	
	d_printf ("ogc_host:%s ogc_port:%s ogc_game:%s ogc_ai_family:%d\n", ogc_host, ogc_port, ogc_game, ogc_ai_family);
	if (dns_filladdr (ogc_host, LEN_OGCHOST, ogc_port, LEN_OGCPORT, ogc_ai_family, &ogc_addr) < 0) {
		udp_close (ogc_sock);
		ogc_sock = -1;
		return 0;
	}
	
	for (i = 0; i < MAX_OGC_ENTRYS; i++)
		ogc_array[i].serial = -1;
	
	return 1;
};
Exemple #3
0
/* FUNCTION: dhcpc_close()
 *
 * Cleanup various data structures associated with the DHCP client module.
 *
 * PARAM1: unsigned int       close flags
 *
 * RETURNS: int               0 if OK, else error code
 */
int
dhcpc_close(uint32_t flags)
{
   int err = 0;

   /* terminate the UDP lightweight API registration */
   if (dhc_conn)
   {
      udp_close(dhc_conn);
      dhc_conn = NULL;
   }
   /* zero out the DHCP client state structures */
   MEMSET(&dhc_states[0], 0, sizeof(dhc_states));
   xids = DC_INITIAL_XID;
   /* zero out DHCP client statistics */
   MEMSET(&dhc_stats, 0, sizeof(dhc_stats));

#ifdef USE_UPNP
   /* cleanup data structures */
#ifdef USE_AUTOIP
   MEMSET(autoIPs, 0, sizeof (autoIPs));
   dBASE_AUTO_IP_ADDRESS = AUTOIP_BASE_ADDR;
   dMAX_AUTO_IP_ADDRESS  = AUTOIP_MAX_ADDR;
   rand_seed = 0;
#endif
   MEMSET(upnp, 0, sizeof (upnp));
#ifndef USER_DS_SUPPORT
   MEMSET(ds_structs, 0, sizeof (ds_structs));
#endif

   upnp_started = 0;
#endif

   return (err);
}
Exemple #4
0
static void eap_wps_deinit(struct eap_sm *sm, void *priv)
{
	wpa_printf(MSG_DEBUG,"@#*@#*@#*EAP-WPS: Entered eap_wps_reset *#@*#@*#@");

	struct eap_wps_data *data = (struct eap_wps_data *)priv;
	if (data == NULL)
		return;

	if (data->udpFdEap != -1)
	{
		udp_close(data->udpFdEap);
		data->udpFdEap = -1;
	}

	/*
	if (data->udpFdCom != -1)
	{
		eloop_unregister_read_sock(data->udpFdCom);
		udp_close(data->udpFdCom);
		data->udpFdCom = -1;
	}
	*/

	os_free(data);
}
static int _tftp_close(tftp_info_t *info)
{
    ebuf_t *buf;
    const char *emsg = "transfer cancelled";	/* some error message */

    if (info->tftp_socket == -1) return 0;

    if (info->tftp_filemode == FILE_MODE_READ) {
	buf = udp_alloc();
	if (buf) {
	    /* If we're on the EOF packet, just send an ack */
	    if (info->tftp_lastblock) {
		ebuf_append_u16_be(buf,TFTP_OP_ACK);
		ebuf_append_u16_be(buf,info->tftp_blknum);
		}
	    else {
		ebuf_append_u16_be(buf,TFTP_OP_ERROR);
		ebuf_append_u16_be(buf,TFTP_ERR_DISKFULL);
		ebuf_append_bytes(buf,emsg,strlen(emsg)+1);
		}
	    udp_send(info->tftp_socket,buf,info->tftp_ipaddr);
	    }
	}
    else {
	/* Just flush out the remaining write data, if any */
	_tftp_writemore(info);
	}

    udp_close(info->tftp_socket);
    info->tftp_socket = -1;
    return 0;
}
Exemple #6
0
void TrapList::deInitial(void) {
    if( inited ) {
        os_tsk_delete(tsk_send_trap);
        udp_close(soc_massage);
        udp_release_socket(soc_massage);
    }
}
Exemple #7
0
extern int send_rescueack(unsigned short no, unsigned short lo)
{
	ebuf_t *buf = NULL;
	int acksocket;
	char tftpnull;
	int res, i;

	/*
	 * Open a UDP socket to the TFTP server
	 */
	acksocket = udp_socket(UDP_PROTO_TFTP);
	res = udp_bind(acksocket, 69);
	if (res < 0) {
		return res;
	}
	udp_connect(acksocket, ackport);
	for (i = 0; i < 1; i++) {
		buf = udp_alloc();
		if (!buf)
			return -1;
		/*
		 * Send the data
		 */
		ebuf_append_u16_be(buf, no);
		ebuf_append_u16_be(buf, lo);
		ebuf_append_bytes(buf,&tftpnull, 0);
		udp_send(acksocket ,buf, tftpipto);
	}
	if (buf)
		udp_free(buf);
	udp_close(acksocket);
	return 0;
}
Exemple #8
0
static void rtp_close( hnd_t handle )
{
    obe_rtp_ctx *p_rtp = handle;

    udp_close( p_rtp->udp_handle );
    free( p_rtp );
}
Exemple #9
0
int syscall_handler(int num, struct syscall_arguments *args)
{
    interrupt_unmask();
    
    switch (num)
    {
        case ADDPROCESS:
            interrupt_mask();
                process_add((void (*)())args->arg1);
            interrupt_unmask();
        break;
        case YIELD:
            interrupt_sleepinsyscall();
        break;
        
        case UDPSEND:
            return udp_output(args->arg1, (struct sockaddr*)args->arg2, 
                (char *)args->arg3, args->arg4);
        break;
        case UDPRECV:
            return udp_recvfrom(args->arg1, (struct sockaddr*)args->arg2, 
                (char *)args->arg3, args->arg4);
        break;
        case UDPSOCKET: 
            return udp_socket();
        break;
        case UDPBIND:
            return udp_bind(args->arg1, (struct sockaddr*)args->arg2);
        break;
        case UDPCLOSE:
            return udp_close(args->arg1);
        break;
        
        case TCPCONNECT:
            return tcp_connect(args->arg1, (struct sockaddr*)args->arg2);
        break;
        
        case TCPSEND:
            return tcp_send(args->arg1, (char *)args->arg2, args->arg3);
        break;
        case TCPRECV:
            return tcp_recv(args->arg1, (char *)args->arg2, args->arg3);
        break;
        case TCPSOCKET: 
            return tcp_socket();
        break;
        case TCPBIND:
            return tcp_bind(args->arg1, (struct sockaddr*)args->arg2);
        break;
        case TCPCLOSE:
            return tcp_close(args->arg1);
        break;
        case TCPLISTEN:
            return tcp_listen(args->arg1);
        break;
    }
    
    return 0;
}
Exemple #10
0
int
tftp_udpclose(void * conn)
{
   UDPCONN cn = (UDPCONN)conn;

   udp_close(cn);
   return 0;   /* no ability to detect error on this API */
}
Exemple #11
0
int main() {
    int fd = udp_init_broadcast(8887);
    char *sendtext = "UDP Test\n";
    printf("Sending text:\n%s\n", sendtext);
    udp_send(fd, sendtext, strlen(sendtext));
    udp_close(fd);
    return 0;
}
Exemple #12
0
int
udp_bind_double ( udp_connection_t **_u1, udp_connection_t **_u2,
                  int subsystem, const char *name1,
                  const char *name2, const char *host, int port,
                  const char *ifname, int rxsize1, int rxsize2,
                  int txsize1, int txsize2 )
{
  udp_connection_t *u1 = NULL, *u2 = NULL;
  udp_connection_t *ucs[10];
  int tst = 40, pos = 0, i, port2;

  memset(&ucs, 0, sizeof(ucs));
  while (1) {
    u1 = udp_bind(subsystem, name1, host, port, NULL, ifname, rxsize1, txsize1);
    if (u1 == NULL || u1 == UDP_FATAL_ERROR)
      goto fail;
    port2 = ntohs(IP_PORT(u1->ip));
    /* RTP port should be even, RTCP port should be odd */
    if ((port2 % 2) == 0) {
      u2 = udp_bind(subsystem, name2, host, port2 + 1, NULL, ifname, rxsize2, txsize2);
      if (u2 != NULL && u2 != UDP_FATAL_ERROR)
        break;
    }
    if (tst) {
      udp_close(u1);
      tst--;
      continue;
    }
    ucs[pos++] = u1;
    if (port || pos >= ARRAY_SIZE(ucs))
      goto fail;
  }
  for (i = 0; i < pos; i++)
    udp_close(ucs[i]);
  *_u1 = u1;
  *_u2 = u2;
  return 0;
fail:
  for (i = 0; i < pos; i++)
    udp_close(ucs[i]);
  return -1;
}
/* send to the gamecache that this browser does not anymore exist */
void ogc_shutdown () {
	if (ogc_sock <= 0)
		return;
	
	d_printf ("ogc_shutdown\n");
	if (ogc_browsing)
		ogc_browsestop ();
	udp_close (ogc_sock);
	
	ogc_sock = -1;
};
Exemple #14
0
int main(void)
{
    int server_fd;
    char buf[128];
    struct sockaddr client;
    socklen_t client_len = sizeof(struct sockaddr);

    server_fd = udp_server("127.0.0.1", "21114");
    udp_recvfrom(server_fd, buf, sizeof(buf), &client, &client_len);
    strcat(buf, " from server");
    udp_sendto(server_fd, buf, sizeof(buf), &client, client_len);
    udp_close(server_fd);
}
Exemple #15
0
// ------------------------------------------------
// Function:        dhcp_release_ip()
// ------------------------------------------------
// Input:           -
// Output:          TRUE if succesful
// ------------------------------------------------
// Description:     Release current dinamic IP
//                  address
// ------------------------------------------------
BOOL dhcp_release_ip(void)
{
    BYTE i;

    if(ip_local[INTERFACE_ETH].d == 0) return TRUE;             // no IP for releasing

    udp_close(SOCKET_DHCP);
    if(!udp_open(SOCKET_DHCP, UDP_DHCP_CLI, ip_dhcp, UDP_DHCP_SERV, INTERFACE_ETH))
        return FALSE;

    for(i=0; i<3; i++) {
        if(!dhcp_envia(DHCPRELEASE, TRUE)) break;
        os_sleep(100);
    }

    udp_close(SOCKET_DHCP);
    ip_local[INTERFACE_ETH].d = 0;
    ip_gateway[INTERFACE_ETH].d = 0;
    ip_mask[INTERFACE_ETH].d = 0;
    ip_dhcp.d = 0xffffffff;
    return TRUE;
}	
Exemple #16
0
// ------------------------------------------------
// Function:        dhcp_get_ip()
// ------------------------------------------------
// Input:           -
// Output:          TRUE if succesful
// ------------------------------------------------
// Description:     Obtain a local IP address
//                  using the DHCP protocol
// ------------------------------------------------
BOOL dhcp_get_ip(void)
{
    IPV4 ip;

    if(ip_local[INTERFACE_ETH].d) return TRUE;                  // already has an IP

    ip.d = 0xffffffff;

    udp_close(SOCKET_DHCP);
    if(!udp_open(SOCKET_DHCP, UDP_DHCP_CLI, ip, UDP_DHCP_SERV, INTERFACE_ETH))
        return FALSE;

    ip_local[INTERFACE_ETH].d = 0;
    ip_tmp.d = 0;
    ip_dhcp.d = 0xffffffff;
    xid.b[0] = random();
    xid.b[1] = random();
    xid.b[2] = random();
    xid.b[3] = random();

    if(!dhcp_discover()) goto fail;                             // find a DHCP server

    udp_close(SOCKET_DHCP);
    if(!udp_open(SOCKET_DHCP, UDP_DHCP_CLI, ip, UDP_DHCP_SERV, INTERFACE_ETH))
        return FALSE;

    if(!dhcp_req()) goto fail;                                  // request an IP address

    ip_local[INTERFACE_ETH].d = ip_tmp.d;
    udp_close(SOCKET_DHCP);
    return TRUE;

fail:
    ip_local[INTERFACE_ETH].d = 0;
    udp_close(SOCKET_DHCP);
    return FALSE;
}	
static void eap_wsc_reset(struct eap_sm *sm, void *priv)
{
    wpa_printf(MSG_DEBUG, "EAP-WSC: Entered eap_wsc_reset");

    struct eap_wsc_data *data = (struct eap_wsc_data *)priv;
    if (data == NULL)
        return;

    if (data->udpFdEap != -1)
    {
        udp_close(data->udpFdEap);
        data->udpFdEap = -1;
    }

    free(data);
}
Exemple #18
0
void send_test(void)
{
	u32 ip = ((u32)192 << 24) | ((u32)168 << 16) | ((u32)1 << 8) | 20;
	u16 src_port;
	u16 port = 8888;
	char data[] = "hello world!";
	u16 len;

	udp_close(0);
	
	if (udp_setup(ip, port, port) < 0)
		err_log("udp_setup");
	
	send_data(ip, port, port, data, strlen(data));
	
	recv_data(&ip, &src_port, data_i, &len);
}
Exemple #19
0
static void close_output( void *handle )
{
    struct ip_status *status = handle;

    if( status->output_params->output_opts.output == OUTPUT_RTP )
    {
        if( *status->ip_handle )
            rtp_close( *status->ip_handle );
    }
    else
    {
        if( *status->ip_handle )
            udp_close( *status->ip_handle );
    }
    if( status->output_params->output_opts.target  )
        free( status->output_params->output_opts.target );
    free( status->output_params );
}
Exemple #20
0
/*
	shutdown the network part
*/
void
network_shutdown ()
{
    int i;
    int new_server = bman.p_servnr;
    d_printf ("network_shutdown\n");

    if (GT_MP_PTPM) {
        d_printf ("Server Quit Send information\n");

        /* find new server */
        for (i = 0; i < MAX_PLAYERS; i++) {
            if (PS_IS_used (players[i].state) && PS_IS_netplayer (players[i].state)
                && i != bman.p_servnr && players[i].net.flags == 0)
                new_server = i;
        }

        d_printf ("netword_shutdown: new server set to: %d\n", new_server);

        for (i = 0; i < MAX_PLAYERS; i++)
            if (i != bman.p_servnr && PS_IS_netplayer (players[i].state)
                && !PS_IS_aiplayer (players[i].state))
                send_quit (&players[i].net.addr, bman.p_servnr, new_server);
    }
    else if (players[bman.p_servnr].net.addr.host[0] != 0) {
        send_quit (&players[bman.p_servnr].net.addr, bman.p_nr, bman.p_servnr);
        if (IS_LPLAYER2)
            send_quit (&players[bman.p_servnr].net.addr, bman.p2_nr, bman.p_servnr);
    }

    if (bman.notifygamemaster) {
        ogc_sendgamequit (bman.sock);
        ogc_shutdown ();
    }

    udp_close (bman.sock);

    bman.p_nr = -1;
    bman.sock = -1;
#ifdef _WIN32
    WSACleanup ();
#endif
};
// TODO make sure it is called on object destruction
// Finish connection
errno_t cn_udp_disconnect( struct data_area_4_connection *c )
{
    (void) c;

    SHOW_FLOW0( 1, "disconnect" );

    struct cn_udp_volatile *vp = c->v_kernel_state;

    if( !(vp->udp_endpoint) )
        return 0;

#if HAVE_NET
    int rc = udp_close( vp->udp_endpoint );
    if( rc )
#endif // HAVE_NET
        return EINVAL;

    return 0;
}
int wsc_ie_deinit(struct hostapd_data *hapd)
{
#ifdef ACTION_TEC
	if (g_wsc_ie_data == NULL)
		return 0;
#endif
	if (g_wsc_ie_data->udpFdCom != -1) {
		eloop_unregister_read_sock(g_wsc_ie_data->udpFdCom);
		udp_close(g_wsc_ie_data->udpFdCom);
		g_wsc_ie_data->udpFdCom = -1;
	}

	g_wsc_ie_data->hapd = NULL;

	free(g_wsc_ie_data);
	g_wsc_ie_data = NULL;

	return 0;
}
Exemple #23
0
uint8_t dhcp_get_ip()
{

    uint8_t sockid = SOCKET_INVALID;

    // First get a socket
    sockid = udp_open(DHCP_CLIENT_PORT);
    if (sockid == SOCKET_INVALID)
        return 1;
    dhcp_send_packet(sockid, DHCP_DISCOVER);
    if (dhcp_read_packet(sockid) != DHCP_OFFER)
        return 2;
    dhcp_send_packet(sockid, DHCP_REQUEST);
    if (dhcp_read_packet(sockid) != DHCP_ACK)
        return 3;
    
    // Finally close the socket
    udp_close(sockid);
    return 0;
}
Exemple #24
0
int url_close(URL *url)
{
        if(NULL == url)
        {
                printf("Bad parameter!\n");
                return -1;
        }

        switch(url->protocol)
        {
                case PRTCL_UDP:
                        udp_close(url->udp, url->ip);
                        break;
                default: // PRTCL_FILE
                        fclose(url->fd);
                        break;
        }

        free(url);
        return 0;
}
Exemple #25
0
int net_Close(TNetWork *_ptNetWork)
{
	TNetWorkMsg *ptNetWorkMsg = (TNetWorkMsg *)_ptNetWork;

	if(NULL == ptNetWorkMsg)
	{
		dbg();
		return ERR;
	}
	LockMx(ptNetWorkMsg->m_SendMux);
	if(NET_TYPE_TCP == ptNetWorkMsg->m_iType)
	{
		tcp_close(ptNetWorkMsg->m_iSocket);
	}
	else
	{
		udp_close(ptNetWorkMsg->m_iSocket);
	}
	UnLockMx(ptNetWorkMsg->m_SendMux);
	
	ptNetWorkMsg->m_iSocket = INVALID_SOCKET;

	return OK;
}
Exemple #26
0
udp_connection_t *
udp_sendinit ( int subsystem, const char *name,
               const char *ifname, int txsize )
{
  int fd, ifindex;
  udp_connection_t *uc;

  uc = calloc(1, sizeof(udp_connection_t));
  uc->fd                   = -1;
  uc->ifname               = ifname ? strdup(ifname) : NULL;
  uc->subsystem            = subsystem;
  uc->name                 = name ? strdup(name) : NULL;
  uc->rxtxsize             = txsize;

  /* Open socket */
  if ((fd = tvh_socket(uc->ip.ss_family, SOCK_DGRAM, 0)) == -1) {
    tvherror(subsystem, "%s - failed to create socket [%s]",
             name, strerror(errno));
    udp_close(uc);
    return UDP_FATAL_ERROR;
  }

  uc->fd = fd;

  /* Bind to interface */
  ifindex = udp_ifindex_required(uc) ? udp_get_ifindex(ifname) : 0;
  if (ifindex < 0) {
    tvherror(subsystem, "%s - could not find interface %s",
             name, ifname);
    goto error;
  }

  if (uc->multicast) {
    if (uc->ip.ss_family == AF_INET) {
#if !defined(PLATFORM_DARWIN)
      struct ip_mreqn m;
      memset(&m, 0, sizeof(m));
      m.imr_ifindex = ifindex;
#else
      struct in_addr m;
      if (udp_get_ifaddr(fd, ifname, &m) == -1) {
        tvherror(subsystem, "%s - cannot find ip address for interface %s [e=%s]",
                 name, ifname,  strerror(errno));
        goto error;
      }
#endif
      if (setsockopt(fd, udp_get_solip(), IP_MULTICAST_IF, &m, sizeof(m)))
        tvhwarn(subsystem, "%s - cannot set source interface %s [%s]",
                name, ifname, strerror(errno));
    } else {
      struct ipv6_mreq m;
      memset(&m,   0, sizeof(m));
      m.ipv6mr_interface = ifindex;
#ifdef SOL_IPV6
      if (setsockopt(fd, SOL_IPV6, IPV6_MULTICAST_IF, &m, sizeof(m))) {
        tvhwarn(subsystem, "%s - cannot set source interface %s [%s]",
                name, ifname, strerror(errno));
      }
#else
      tvherror(subsystem, "IPv6 multicast not supported");
      goto error;
#endif
    }
  }

  /* Increase TX buffer size */
  if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &txsize, sizeof(txsize)) == -1)
    tvhwarn(subsystem, "%s - cannot increase UDP tx buffer size [%s]",
            name, strerror(errno));

  return uc;

error:
  udp_close(uc);
  return NULL;
}
Exemple #27
0
/*
 *  Discovery thread
 */
static void *
upnp_thread( void *aux )
{
  char *bindaddr = aux;
  tvhpoll_t *poll = tvhpoll_create(2);
  tvhpoll_event_t ev[2];
  upnp_data_t *data;
  udp_connection_t *multicast = NULL, *unicast = NULL;
  udp_connection_t *conn;
  unsigned char buf[16384];
  upnp_service_t *us;
  struct sockaddr_storage ip;
  socklen_t iplen;
  size_t size;
  int r, delay_ms;

  multicast = udp_bind(LS_UPNP, "upnp_thread_multicast",
                       "239.255.255.250", 1900, NULL,
                       NULL, 32*1024, 32*1024);
  if (multicast == NULL || multicast == UDP_FATAL_ERROR)
    goto error;
  unicast = udp_bind(LS_UPNP, "upnp_thread_unicast", bindaddr, 0, NULL,
                     NULL, 32*1024, 32*1024);
  if (unicast == NULL || unicast == UDP_FATAL_ERROR)
    goto error;

  memset(&ev, 0, sizeof(ev));
  ev[0].fd     = multicast->fd;
  ev[0].events = TVHPOLL_IN;
  ev[0].ptr    = multicast;
  ev[1].fd     = unicast->fd;
  ev[1].events = TVHPOLL_IN;
  ev[1].ptr    = unicast;
  tvhpoll_add(poll, ev, 2);

  delay_ms = 0;

  while (atomic_get(&upnp_running) && multicast->fd >= 0) {
    r = tvhpoll_wait(poll, ev, 2, delay_ms ?: 1000);
    if (r == 0) /* timeout */
      delay_ms = 0;

    while (r-- > 0) {
      if ((ev[r].events & TVHPOLL_IN) != 0) {
        conn = ev[r].ptr;
        iplen = sizeof(ip);
        size = recvfrom(conn->fd, buf, sizeof(buf), 0,
                                           (struct sockaddr *)&ip, &iplen);
        if (size > 0 && tvhtrace_enabled()) {
          char tbuf[256];
          inet_ntop(ip.ss_family, IP_IN_ADDR(ip), tbuf, sizeof(tbuf));
          tvhtrace(LS_UPNP, "%s - received data from %s:%hu [size=%zi]",
                   conn == multicast ? "multicast" : "unicast",
                   tbuf, (unsigned short) ntohs(IP_PORT(ip)), size);
          tvhlog_hexdump(LS_UPNP, buf, size);
        }
        /* TODO: a filter */
        TAILQ_FOREACH(us, &upnp_services, us_link)
          us->us_received(buf, size, conn, &ip);
      }
    }

    while (delay_ms == 0) {
      tvh_mutex_lock(&upnp_lock);
      data = TAILQ_FIRST(&upnp_data_write);
      if (data) {
        delay_ms = data->delay_ms;
        data->delay_ms = 0;
        if (!delay_ms) {
          TAILQ_REMOVE(&upnp_data_write, data, data_link);
        } else {
          data = NULL;
        }
      }
      tvh_mutex_unlock(&upnp_lock);
      if (data == NULL)
        break;
      upnp_dump_data(data);
      udp_write_queue(data->from_multicast ? multicast : unicast,
                      &data->queue, &data->storage);
      htsbuf_queue_flush(&data->queue);
      free(data);
      delay_ms = 0;
    }
  }

  /* flush the write queue (byebye messages) */
  while (1) {
    tvh_mutex_lock(&upnp_lock);
    data = TAILQ_FIRST(&upnp_data_write);
    if (data)
      TAILQ_REMOVE(&upnp_data_write, data, data_link);
    tvh_mutex_unlock(&upnp_lock);
    if (data == NULL)
      break;
    tvh_safe_usleep((long)data->delay_ms * 1000);
    upnp_dump_data(data);
    udp_write_queue(unicast, &data->queue, &data->storage);
    htsbuf_queue_flush(&data->queue);
    free(data);
  }

error:
  atomic_set(&upnp_running, 0);
  tvhpoll_destroy(poll);
  udp_close(unicast);
  udp_close(multicast);
  return NULL;
}
Exemple #28
0
udp_connection_t *
udp_bind ( int subsystem, const char *name,
           const char *bindaddr, int port, const char *multicast_src,
           const char *ifname, int rxsize, int txsize )
{
  int fd, ifindex, reuse = 1;
  udp_connection_t *uc;
  char buf[256];
  socklen_t addrlen;

  uc = calloc(1, sizeof(udp_connection_t));
  uc->fd                   = -1;
  uc->host                 = bindaddr ? strdup(bindaddr) : NULL;
  uc->port                 = port;
  uc->ifname               = ifname ? strdup(ifname) : NULL;
  uc->subsystem            = subsystem;
  uc->name                 = name ? strdup(name) : NULL;
  uc->rxtxsize             = rxsize;

  if (udp_resolve(uc, &uc->ip, uc->host, port, &uc->multicast, 1)) {
    udp_close(uc);
    return UDP_FATAL_ERROR;
  }

  /* Open socket */
  if ((fd = tvh_socket(uc->ip.ss_family, SOCK_DGRAM, 0)) == -1) {
    tvherror(subsystem, "%s - failed to create socket [%s]",
             name, strerror(errno));
    udp_close(uc);
    return UDP_FATAL_ERROR;
  }

  uc->fd = fd;

  /* Mark reuse address */
  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) {
    tvherror(subsystem, "%s - failed to reuse address for socket [%s]",
             name, strerror(errno));
    udp_close(uc);
    return UDP_FATAL_ERROR;
  }

  /* Bind to interface */
  ifindex = udp_ifindex_required(uc) ? udp_get_ifindex(ifname) : 0;
  if (ifindex < 0) {
    tvherror(subsystem, "%s - could not find interface %s",
             name, ifname);
    goto error;
  }

  /* IPv4 */
  if (uc->ip.ss_family == AF_INET) {
    /* Bind */
    if (bind(fd, (struct sockaddr *)&uc->ip, sizeof(struct sockaddr_in))) {
      inet_ntop(AF_INET, &IP_AS_V4(uc->ip, addr), buf, sizeof(buf));
      tvherror(subsystem, "%s - cannot bind %s:%hu [e=%s]",
               name, buf, ntohs(IP_AS_V4(uc->ip, port)), strerror(errno));
      goto error;
    }

    if (uc->multicast) {
      /* Join multicast group */
      if (multicast_src && *multicast_src) {
        /* Join with specific source address (SSM) */
        struct ip_mreq_source ms;
        memset(&ms, 0, sizeof(ms));

        ms.imr_multiaddr = IP_AS_V4(uc->ip, addr);

        /* Note, ip_mreq_source does not support the ifindex parameter,
           so we have to resolve to the ip of the interface on all platforms. */
        if (udp_get_ifaddr(fd, ifname, &ms.imr_interface) == -1) {
          tvherror(subsystem, "%s - cannot find ip address for interface %s [e=%s]",
                   name, ifname, strerror(errno));
          goto error;
        }

        if (inet_pton(AF_INET, multicast_src, &ms.imr_sourceaddr) < 1) {
          tvherror(subsystem, "%s - invalid ipv4 address '%s' specified as multicast source [e=%s]",
                   name, multicast_src, strerror(errno));
          goto error;
        }

        if (setsockopt(fd, udp_get_solip(), IP_ADD_SOURCE_MEMBERSHIP,
                       &ms, sizeof(ms)) < 0) {
          tvherror(subsystem, "%s - setsockopt IP_ADD_SOURCE_MEMBERSHIP failed [e=%s]",
                   name,  strerror(errno));
          goto error;
        }
      }
      else {
        /* Standard multicast join (non-SSM) */
#if defined(PLATFORM_DARWIN)
        struct ip_mreq       m;
#else
        struct ip_mreqn      m;
#endif
        memset(&m,   0, sizeof(m));

        m.imr_multiaddr      = IP_AS_V4(uc->ip, addr);
#if !defined(PLATFORM_DARWIN)
        m.imr_address.s_addr = 0;
        m.imr_ifindex        = ifindex;
#else
        if (udp_get_ifaddr(fd, ifname, &m.imr_interface) == -1) {
          tvherror(subsystem, "%s - cannot find ip address for interface %s [e=%s]",
                   name, ifname,  strerror(errno));
          goto error;
        }
#endif

        if (setsockopt(fd, udp_get_solip(), IP_ADD_MEMBERSHIP, &m, sizeof(m))) {
          inet_ntop(AF_INET, &m.imr_multiaddr, buf, sizeof(buf));
          tvhwarn(subsystem, "%s - cannot join %s [%s]",
                  name, buf, strerror(errno));
        }
      }
   }

  /* Bind to IPv6 group */
  } else {
    struct ipv6_mreq m;
    memset(&m,   0, sizeof(m));

    /* Bind */
    if (bind(fd, (struct sockaddr *)&uc->ip, sizeof(struct sockaddr_in6))) {
      inet_ntop(AF_INET6, &IP_AS_V6(uc->ip, addr), buf, sizeof(buf));
      tvherror(subsystem, "%s - cannot bind %s:%hu [e=%s]",
               name, buf, ntohs(IP_AS_V6(uc->ip, port)), strerror(errno));
      goto error;
    }

    if (uc->multicast) {
      /* Join group */
      m.ipv6mr_multiaddr = IP_AS_V6(uc->ip, addr);
      m.ipv6mr_interface = ifindex;
#ifdef SOL_IPV6
      if (setsockopt(fd, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &m, sizeof(m))) {
        inet_ntop(AF_INET, &m.ipv6mr_multiaddr, buf, sizeof(buf));
        tvhwarn(subsystem, "%s - cannot join %s [%s]",
                name, buf, strerror(errno));
      }
#else
      tvherror(subsystem, "IPv6 multicast not supported");
      goto error;
#endif
    }
  }

  addrlen = sizeof(uc->ip);
  if (getsockname(fd, (struct sockaddr *)&uc->ip, &addrlen)) {
    tvherror(subsystem, "%s - cannot obtain socket name [%s]",
             name, strerror(errno));
    goto error;
  }
    
  /* Increase/Decrease RX buffer size */
  if (rxsize > 0 &&
      setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rxsize, sizeof(rxsize)) == -1)
    tvhwarn(subsystem, "%s - cannot change UDP rx buffer size [%s]",
            name, strerror(errno));

  /* Increase/Decrease TX buffer size */
  if (txsize > 0 &&
      setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &txsize, sizeof(txsize)) == -1)
    tvhwarn(subsystem, "%s - cannot change UDP tx buffer size [%s]",
            name, strerror(errno));

  return uc;

error:
  udp_close(uc);
  return NULL;
}
Exemple #29
0
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;
}
Exemple #30
0
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;
}