예제 #1
0
static char *
pseudo_serialno_from_addr(char *name)
{
	int sd, rc, errnum;
	char buf[128];
	struct hostent *hp;
	struct xarpreq ar;

	if (name == NULL)
		return (NULL);

	memset(&ar, 0, sizeof (ar));

	hp = getipnodebyname(name, AF_INET6, AI_ADDRCONFIG, &errnum);
	if (hp != NULL) {
		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ar.xarp_pa;

		sin6->sin6_family = AF_INET6;
		(void) memcpy(&sin6->sin6_addr, hp->h_addr_list[0],
				hp->h_length);
	} else {
		struct sockaddr_in *sin = (struct sockaddr_in *)&ar.xarp_pa;

		sin->sin_family = AF_INET;
		sin->sin_addr.s_addr = inet_addr(name);
	}

	sd = socket(AF_INET, SOCK_DGRAM, 0);

	ar.xarp_ha.sdl_family = AF_LINK;
	rc = ioctl(sd, SIOCGXARP, (caddr_t)&ar);

	close(sd);

	if (ar.xarp_flags & ATF_COM) {  /* use the MAC address */
		uchar_t *ea = (uchar_t *)LLADDR(&ar.xarp_ha);

		addr_to_string("LLADDR-", ea, ar.xarp_ha.sdl_alen,
					buf, sizeof (buf));

	} else if (hp != NULL) {	  /* use the IPv6 address */
		addr_to_string("IPV6ADDR-", (uchar_t *)&hp->h_addr_list[0],
					hp->h_length, buf, sizeof (buf));
	} else {			  /* use the IPv4 address */
		struct sockaddr_in *sin = (struct sockaddr_in *)&ar.xarp_pa;

		addr_to_string("IPV4ADDR-", (uchar_t *)&sin->sin_addr.s_addr, 4,
					buf, sizeof (buf));
	}

	return (strdup(buf));
}
void _hna_global_del_orig(struct hna_global_entry *hna_global_entry,
			  char *message)
{
	char hna_str[ETH_STR_LEN], orig_str[ETH_STR_LEN];

	addr_to_string(orig_str, hna_global_entry->orig_node->orig);
	addr_to_string(hna_str, hna_global_entry->addr);

	debug_log(LOG_TYPE_ROUTES, "Deleting global hna entry %s (via %s): %s \n", hna_str, orig_str, message);

	hash_remove(hna_global_hash, hna_global_entry->addr);
	kfree(hna_global_entry);
}
예제 #3
0
파일: stunclient.cpp 프로젝트: kitech/toxsh
QString StunClient::getStunAddress(QByteArray resp, uint16_t attr_type)
{
    stun_buffer buf;
    u08bits addr_buff[STUN_BUFFER_SIZE] = {0};

    buf.len = resp.length();
    memcpy(buf.buf, resp.data(), resp.length());

    uint16_t t_attr_type;
    const u08bits *attr_value;
    int attr_len;
    ioa_addr stun_addr;
    stun_attr_ref raw_attr = stun_attr_get_first_str(buf.buf, buf.len);
    for ( ; raw_attr ; raw_attr = stun_attr_get_next_str(buf.buf, buf.len, raw_attr)) {
        t_attr_type = stun_attr_get_type(raw_attr);
        attr_value = stun_attr_get_value(raw_attr);
        attr_len = stun_attr_get_len(raw_attr);

        if (t_attr_type == attr_type) {
            stun_attr_get_addr_str(buf.buf, buf.len, raw_attr, &stun_addr, NULL);
            addr_to_string(&stun_addr, (u08bits*)addr_buff);
            break;
        }
    }

    return QString((char*)addr_buff);
}
예제 #4
0
static int create_server_listener(tls_listener_relay_server_type* server) {

  FUNCSTART;

  if(!server) return -1;

  evutil_socket_t tls_listen_fd = -1;

  tls_listen_fd = socket(server->addr.ss.ss_family, SOCK_STREAM, 0);
  if (tls_listen_fd < 0) {
      perror("socket");
      return -1;
  }

  if(sock_bind_to_device(tls_listen_fd, (unsigned char*)server->ifname)<0) {
    TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind listener socket to device %s\n",server->ifname);
  }

  if(addr_bind(tls_listen_fd,&server->addr)<0) {
  	  perror("Cannot bind local socket to addr");
  	  char saddr[129];
  	  addr_to_string(&server->addr,(u08bits*)saddr);
  	  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind TCP/TLS listener socket to addr %s\n",saddr);
  	  socket_closesocket(tls_listen_fd);
  	  return -1;
  }

  socket_tcp_set_keepalive(tls_listen_fd);

  socket_set_nonblocking(tls_listen_fd);

  server->l = evconnlistener_new(server->e->event_base,
		  server_input_handler, server,
		  LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
		  1024, tls_listen_fd);

  if(!(server->l)) {
	  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot create TLS listener\n");
	  socket_closesocket(tls_listen_fd);
	  return -1;
  }

  if(addr_get_from_sock(tls_listen_fd, &(server->addr))) {
    perror("Cannot get local socket addr");
    socket_closesocket(tls_listen_fd);
    return -1;
  }

  if(!no_tcp && !no_tls)
	  addr_debug_print(server->verbose, &server->addr,"TCP/TLS listener opened on ");
  else if(!no_tls)
	  addr_debug_print(server->verbose, &server->addr,"TLS listener opened on ");
  else if(!no_tcp)
	  addr_debug_print(server->verbose, &server->addr,"TCP listener opened on ");

  FUNCEND;
  
  return 0;
}
예제 #5
0
/*
 * Send the gossip to connected peers. 
 */
void send_gossip()
{
	int size = 256;
	char *payload = (char *) malloc(size);
	char *g;
	int index = 0;
	struct file_info *fi;

	for(fi=file_info;fi!=NULL;fi=fi->next)
	{
	  char *addr = addr_to_string(fi->addr);
		printf("Checking %s type = %d outgoing status = %d\n", addr, fi->type,fi->u.fi_outgoing.status);
		if(fi->type == FI_INCOMING || (fi->type == FI_OUTGOING && fi->status == FI_KNOWN && fi->u.fi_outgoing.status == FI_CONNECTED))
		{
		  printf("Address extracted - %s\n", addr);
			if(strlen(addr) + index > size)
			{
				size *= 2;
				payload = realloc(payload, size);
			}
			if (index == 0) {
				strcpy(payload, ";");
				sprintf(payload, "%s%s", payload, addr);		
			}
			else {
				sprintf(payload, "%s;%s", payload, addr);
			}
			printf("Gossip Payload = %s\n", payload);
			index += strlen(addr) + 1;
		}
		free(addr);
	}
	
	payload[index++] = '\n';
	payload[index++] = '\0';
	char *my_addr_str = (char *) addr_to_string(my_addr);
	gossip_gen++;
	g = (char *) malloc(sizeof(char)*(strlen(payload) + strlen(my_addr_str) + 4 + 4));
	printf ("payload length = %d, my_addr length = %d\n", strlen(payload), strlen(my_addr_str));
	memset(g, 0, strlen(payload) + strlen(my_addr_str) + 8);
	sprintf(g, "G%s/%d/%s", my_addr_str, gossip_gen, payload);
	printf("Gossip created - %s\n", g);
	printf("DONE\n");
	file_broadcast(g, strlen(g), NULL);
	free(my_addr_str);
}
예제 #6
0
static int create_server_socket(dtls_listener_relay_server_type* server) {

  FUNCSTART;

  if(!server) return -1;

  clean_server(server);

  ioa_socket_raw udp_listen_fd = -1;

  udp_listen_fd = socket(server->addr.ss.ss_family, SOCK_DGRAM, 0);
  if (udp_listen_fd < 0) {
    perror("socket");
    return -1;
  }

  server->udp_listen_s = create_ioa_socket_from_fd(server->e, udp_listen_fd, NULL, UDP_SOCKET, LISTENER_SOCKET, NULL, &(server->addr));

  server->udp_listen_s->listener_server = server;

  set_sock_buf_size(udp_listen_fd,UR_SERVER_SOCK_BUF_SIZE);

  if(sock_bind_to_device(udp_listen_fd, (unsigned char*)server->ifname)<0) {
    TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind listener socket to device %s\n",server->ifname);
  }

  if(addr_bind(udp_listen_fd,&server->addr)<0) {
	  perror("Cannot bind local socket to addr");
	  char saddr[129];
	  addr_to_string(&server->addr,(u08bits*)saddr);
	  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind UDP/DTLS listener socket to addr %s\n",saddr);
	  return -1;
  }

  server->udp_listen_ev = event_new(server->e->event_base,udp_listen_fd,
				    EV_READ|EV_PERSIST,udp_server_input_handler,server);

  event_add(server->udp_listen_ev,NULL);

  if(addr_get_from_sock(udp_listen_fd, &(server->addr))) {
    perror("Cannot get local socket addr");
    return -1;
  }

  if(!no_udp && !no_dtls)
	  addr_debug_print(server->verbose, &server->addr,"UDP/DTLS listener opened on ");
  else if(!no_dtls)
	  addr_debug_print(server->verbose, &server->addr,"DTLS listener opened on ");
  else if(!no_udp)
	  addr_debug_print(server->verbose, &server->addr,"UDP listener opened on ");

  FUNCEND;
  
  return 0;
}
예제 #7
0
int tcpopen(_addr *addr) {
    int sockid;
    if ((sockid = socket(struct_pf(addr), SOCK_STREAM, IPPROTO_TCP)) < 0)
	throw PException("Could not create TCP socket");
    if (connect(sockid, (sockaddr *)addr, struct_len(addr)) < 0) { 
	closesocket(sockid);
        std::string txt = addr_to_string(addr, false);
	throw PException(true, "Could not connect TCP socket to dst addr=%s", txt.c_str());
    }
    return sockid;
}
예제 #8
0
static void print_pcap_addrs(pcap_addr_t *addr) {
    char addrbuf[1024];

    for(; addr; addr = addr->next) {
        if(addr->netmask)
            printf("     %s/%d ",
                   addr_to_string(addr->addr, addrbuf, sizeof addrbuf),
                   netmask_to_string(addr->netmask));
        else
            printf("     %s ",
                   addr_to_string(addr->addr, addrbuf, sizeof addrbuf));
        if(addr->broadaddr)
            printf("brd %s",
                   addr_to_string(addr->broadaddr, addrbuf, sizeof addrbuf));
        if(addr->dstaddr)
            printf("dst %s",
                   addr_to_string(addr->dstaddr, addrbuf, sizeof addrbuf));
        puts("");
    }
}
static void hna_local_del(struct hna_local_entry *hna_local_entry,
			  char *message)
{
	char hna_str[ETH_STR_LEN];

	addr_to_string(hna_str, hna_local_entry->addr);
	debug_log(LOG_TYPE_ROUTES, "Deleting local hna entry (%s): %s \n",
		  hna_str, message);

	hash_remove(hna_local_hash, hna_local_entry->addr);
	_hna_local_del(hna_local_entry);
}
예제 #10
0
			int get_name_from_addr (struct qsockaddr *addr, char *name)
			{
				struct hostent *hostentry;

				hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, sizeof(struct in_addr), AF_INET);
				if (hostentry)
				{
					Q_strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1);
					return 0;
				}

				Q_strcpy (name, addr_to_string (addr));
				return 0;
			}
예제 #11
0
/* Broadcast to all connections except fi.
 */
void file_broadcast(char *buf, int size, struct file_info *fi){
	printf("In send broadcast\n");
	struct file_info *fi2;
	for (fi2 = file_info; fi2 != 0; fi2 = fi2->next) {
	  char * fi2_addr = addr_to_string(fi2->addr);
		//printf("Checking %s type = %d outgoing status = %d\n", fi2_addr, fi2->type, fi2->u.fi_outgoing.status);
		if (fi2->type == FI_FREE || fi2 == fi) {
			//printf("C1\n");
			continue;
		}
		if (fi2->type == FI_OUTGOING && fi2->u.fi_outgoing.status == FI_CONNECTING) {
			//printf("C2\n");
			continue;
		}
		if (fi2->type == FI_OUTGOING || fi2->type == FI_INCOMING) {
			//printf("Sending broadcast\n");
			file_info_send(fi2, buf, size);
		}
	}
	//printf("C3\n");
}
예제 #12
0
int datagram_recv(struct datagram *d, char *data, int length, char *addr, int *port, int timeout)
{
	int result;
	struct sockaddr_in iaddr;
	SOCKLEN_T iaddr_length;
	fd_set fds;
	struct timeval tm;

	while(1) {

		tm.tv_sec = timeout / 1000000;
		tm.tv_usec = timeout % 1000000;

		FD_ZERO(&fds);
		FD_SET(d->fd, &fds);

		result = select(d->fd + 1, &fds, 0, 0, &tm);
		if(result > 0) {
			if(FD_ISSET(d->fd, &fds))
				break;
		} else if(result < 0 && errno_is_temporary(errno)) {
			continue;
		} else {
			return -1;
		}
	}

	iaddr_length = sizeof(iaddr);

	result = recvfrom(d->fd, data, length, 0, (struct sockaddr *) &iaddr, &iaddr_length);
	if(result < 0)
		return result;

	addr_to_string(&iaddr.sin_addr, addr);
	*port = ntohs(iaddr.sin_port);

	return result;
}
예제 #13
0
/*
 * evaluate the RAF frame
 */
int ess_raf_received_pack(struct s_smc *smc, SMbuf *mb, struct smt_header *sm,
			  int fs)
{
	void			*p ;		/* universal pointer */
	struct smt_p_0016	*cmd ;		/* para: command for the ESS */
	SMbuf			*db ;
	u_long			msg_res_type ;	/* recource type */
	u_long			payload, overhead ;
	int			local ;
	int			i ;

	/*
	 * Message Processing Code
	 */
	 local = ((fs & L_INDICATOR) != 0) ;

	/*
	 * get the resource type
	 */
	if (!(p = (void *) sm_to_para(smc,sm,SMT_P0015))) {
		DB_ESS("ESS: RAF frame error, parameter type not found\n",0,0) ;
		return fs;
	}
	msg_res_type = ((struct smt_p_0015 *)p)->res_type ;

	/*
	 * get the pointer to the ESS command
	 */
	if (!(cmd = (struct smt_p_0016 *) sm_to_para(smc,sm,SMT_P0016))) {
		/*
		 * error in frame: para ESS command was not found
		 */
		 DB_ESS("ESS: RAF frame error, parameter command not found\n",0,0);
		 return fs;
	}

	DB_ESSN(2,"fc %x	ft %x\n",sm->smt_class,sm->smt_type) ;
	DB_ESSN(2,"ver %x	tran %lx\n",sm->smt_version,sm->smt_tid) ;
	DB_ESSN(2,"stn_id %s\n",addr_to_string(&sm->smt_source),0) ;

	DB_ESSN(2,"infolen %x	res %x\n",sm->smt_len, msg_res_type) ;
	DB_ESSN(2,"sbacmd %x\n",cmd->sba_cmd,0) ;

	/*
	 * evaluate the ESS command
	 */
	switch (cmd->sba_cmd) {

	/*
	 * Process an ESS Allocation Request
	 */
	case REQUEST_ALLOCATION :
		/*
		 * check for an RAF Request (Allocation Request)
		 */
		if (sm->smt_type == SMT_REQUEST) {
			/*
			 * process the Allocation request only if the frame is
			 * local and no static allocation is used
			 */
			if (!local || smc->mib.fddiESSPayload)
				return fs;

			p = (void *) sm_to_para(smc,sm,SMT_P0019)  ;
			for (i = 0; i < 5; i++) {
				if (((struct smt_p_0019 *)p)->alloc_addr.a[i]) {
					return fs;
				}
			}

			/*
			 * Note: The Application should send a LAN_LOC_FRAME.
			 *	 The ESS do not send the Frame to the network!
			 */
			smc->ess.alloc_trans_id = sm->smt_tid ;
			DB_ESS("ESS: save Alloc Req Trans ID %lx\n",sm->smt_tid,0);
			p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
			((struct smt_p_320f *)p)->mib_payload =
				smc->mib.a[PATH0].fddiPATHSbaPayload ;
			p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
			((struct smt_p_3210 *)p)->mib_overhead =
				smc->mib.a[PATH0].fddiPATHSbaOverhead ;
			sm->smt_dest = smt_sba_da ;

			if (smc->ess.local_sba_active)
				return fs | I_INDICATOR;

			if (!(db = smt_get_mbuf(smc)))
				return fs;

			db->sm_len = mb->sm_len ;
			db->sm_off = mb->sm_off ;
			memcpy(((char *)(db->sm_data+db->sm_off)),(char *)sm,
				(int)db->sm_len) ;
			dump_smt(smc,
				(struct smt_header *)(db->sm_data+db->sm_off),
				"RAF") ;
			smt_send_frame(smc,db,FC_SMT_INFO,0) ;
			return fs;
		}

		/*
		 * The RAF frame is an Allocation Response !
		 * check the parameters
		 */
		if (smt_check_para(smc,sm,plist_raf_alc_res)) {
			DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
			return fs;
		}

		/*
		 * VERIFY THE FRAME IS WELL BUILT:
		 *
		 *	1. path index = primary ring only
		 *	2. resource type = sync bw only
		 *	3. trans action id = alloc_trans_id
		 *	4. reason code = success
		 *
		 * If any are violated, discard the RAF frame
		 */
		if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
			!= PRIMARY_RING) ||
			(msg_res_type != SYNC_BW) ||
		(((struct smt_p_reason *)sm_to_para(smc,sm,SMT_P0012))->rdf_reason
			!= SMT_RDF_SUCCESS) ||
			(sm->smt_tid != smc->ess.alloc_trans_id)) {

			DB_ESS("ESS: Allocation Response not accepted\n",0,0) ;
			return fs;
		}

		/*
		 * Extract message parameters
		 */
		p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
                if (!p) {
                        printk(KERN_ERR "ESS: sm_to_para failed");
                        return fs;
                }
		payload = ((struct smt_p_320f *)p)->mib_payload ;
		p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
                if (!p) {
                        printk(KERN_ERR "ESS: sm_to_para failed");
                        return fs;
                }
		overhead = ((struct smt_p_3210 *)p)->mib_overhead ;

		DB_ESSN(2,"payload= %lx	overhead= %lx\n",payload,overhead) ;

		/*
		 * process the bandwidth allocation
		 */
		(void)process_bw_alloc(smc,(long)payload,(long)overhead) ;

		return fs;
		/* end of Process Allocation Request */

	/*
	 * Process an ESS Change Request
	 */
	case CHANGE_ALLOCATION :
		/*
		 * except only replies
		 */
		if (sm->smt_type != SMT_REQUEST) {
			DB_ESS("ESS: Do not process Change Responses\n",0,0) ;
			return fs;
		}

		/*
		 * check the para for the Change Request
		 */
		if (smt_check_para(smc,sm,plist_raf_chg_req)) {
			DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
			return fs;
		}

		/*
		 * Verify the path index and resource
		 * type are correct. If any of
		 * these are false, don't process this
		 * change request frame.
		 */
		if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
			!= PRIMARY_RING) || (msg_res_type != SYNC_BW)) {
			DB_ESS("ESS: RAF frame with para problem, ignoring\n",0,0) ;
			return fs;
		}

		/*
		 * Extract message queue parameters
		 */
		p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
		payload = ((struct smt_p_320f *)p)->mib_payload ;
		p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
		overhead = ((struct smt_p_3210 *)p)->mib_overhead ;

		DB_ESSN(2,"ESS: Change Request from %s\n",
			addr_to_string(&sm->smt_source),0) ;
		DB_ESSN(2,"payload= %lx	overhead= %lx\n",payload,overhead) ;

		/*
		 * process the bandwidth allocation
		 */
		if(!process_bw_alloc(smc,(long)payload,(long)overhead))
			return fs;

		/*
		 * send an RAF Change Reply
		 */
		ess_send_response(smc,sm,CHANGE_ALLOCATION) ;

		return fs;
		/* end of Process Change Request */

	/*
	 * Process Report Response
	 */
	case REPORT_ALLOCATION :
		/*
		 * except only requests
		 */
		if (sm->smt_type != SMT_REQUEST) {
			DB_ESS("ESS: Do not process a Report Reply\n",0,0) ;
			return fs;
		}

		DB_ESSN(2,"ESS: Report Request from %s\n",
			addr_to_string(&(sm->smt_source)),0) ;

		/*
		 * verify that the resource type is sync bw only
		 */
		if (msg_res_type != SYNC_BW) {
			DB_ESS("ESS: ignoring RAF with para problem\n",0,0) ;
			return fs;
		}

		/*
		 * send an RAF Change Reply
		 */
		ess_send_response(smc,sm,REPORT_ALLOCATION) ;

		return fs;
		/* end of Process Report Request */

	default:
		/*
		 * error in frame
		 */
		DB_ESS("ESS: ignoring RAF with bad sba_cmd\n",0,0) ;
		break ;
	}

	return fs;
}
예제 #14
0
void updateGraph()
{
  if(dist) {
    free(dist);
    dist = NULL;
  }
  if(prev) {
    free(prev);
    prev = NULL;
  }
  if(graph) {
    free(graph);
    graph = NULL;
  }
int r= 0, s=0;
  dist = (int *) malloc(nl_nsites(nl) * sizeof(int));
  prev = (int *) malloc(nl_nsites(nl) * sizeof(int));
  graph = (int *) malloc(sizeof(int) * (nl_nsites(nl)) * (nl_nsites(nl)));
	for(r=0;r<nl_nsites(nl);r++)
    	{
    		dist[r] = INFINITY;
    		prev[r] = UNDEFINED;
    	for(s=0;s<nl_nsites(nl);s++)
    	{
    		graph[INDEX(r, s, nl_nsites(nl))] = 0;
    	}
    }


	struct gossip *g = gossip;

	while(g != NULL)
	{
		int len = strlen(gossip_latest(g));
		char *lat = (char *) malloc(sizeof(char) * (len+1));
		strcpy(lat, gossip_latest(g));

		char *addr = lat;

		char *ctr = index(addr, '/');		
		*ctr++ = 0;

		char *payload = index(ctr, '/');		
		*payload++ = 0;

		char *token = strtok(payload, ";");	

		while (token) 
		{	
			//printf("Address = %s\n", addr);
			//printf("Token = %s\n", token);	
			set_dist(nl, graph, nl_nsites(nl), addr, token, 1);
			token = strtok(NULL, ";");
		}
		g = gossip_next(g);
		free(lat);
	}
	char *my_addr_str = addr_to_string(my_addr);
	int my_index = nl_index(nl, my_addr_str);
	// update connections of immediate neighbours
	struct file_info *f = file_info;
	while (f) {
		char *addr = addr_to_string(f->addr);

		if(strcmp(addr,my_addr_str ) != 0 && (f->type == FI_INCOMING || (f->type == FI_OUTGOING && f->status == FI_KNOWN && f->u.fi_outgoing.status == FI_CONNECTED)))
		{
			set_dist(nl, graph, nl_nsites(nl), addr, my_addr_str, 1);
		}

		f = f->next;
		free(addr);
	}
	free(my_addr_str);
	// call graph on updated graph
	dijkstra(graph, nl_nsites(nl), my_index, dist, prev);
	
	printf("PRINTING GRAPH\n");
    for(r=0;r<nl_nsites(nl);r++)
    {
    	for(s=0;s<nl_nsites(nl);s++)
    	{
    		printf("%d ", graph[INDEX(r, s, nl_nsites(nl))]);
    	}

    	printf("\n");
    }

	printf("\nPRINTING DISTANCE\n");
	for(r=0;r<nl_nsites(nl);r++)
	{
	  printf("Distance to Site [%d] %s = %d\n", r, nl_name(nl,r), dist[r]);
	}

	printf("\nPRINTING PREV\n");
	for(r=0;r<nl_nsites(nl);r++)
	{
	  printf("Previous to Site [%d] %s = %d\n", r, nl_name(nl,r), prev[r]);
	}
}
void hna_local_add(uint8_t *addr)
{
	struct hna_local_entry *hna_local_entry;
	struct hna_global_entry *hna_global_entry;
	struct hashtable_t *swaphash;
	char hna_str[ETH_STR_LEN];
	unsigned long flags;

	spin_lock_irqsave(&hna_local_hash_lock, flags);
	hna_local_entry =
		((struct hna_local_entry *)hash_find(hna_local_hash, addr));
	spin_unlock_irqrestore(&hna_local_hash_lock, flags);

	if (hna_local_entry != NULL) {
		hna_local_entry->last_seen = jiffies;
		return;
	}

	addr_to_string(hna_str, addr);

	/* only announce as many hosts as possible in the batman-packet and
	   space in batman_packet->num_hna That also should give a limit to
	   MAC-flooding. */
	if ((num_hna + 1 > (ETH_DATA_LEN - BAT_PACKET_LEN) / ETH_ALEN) ||
	    (num_hna + 1 > 255)) {
		debug_log(LOG_TYPE_ROUTES, "Can't add new local hna entry (%s): number of local hna entries exceeds packet size \n", hna_str);
		return;
	}

	debug_log(LOG_TYPE_ROUTES, "Creating new local hna entry: %s \n",
		  hna_str);

	hna_local_entry = kmalloc(sizeof(struct hna_local_entry), GFP_ATOMIC);
	if (!hna_local_entry)
		return;

	memcpy(hna_local_entry->addr, addr, ETH_ALEN);
	hna_local_entry->last_seen = jiffies;

	/* the batman interface mac address should never be purged */
	if (compare_orig(addr, soft_device->dev_addr))
		hna_local_entry->never_purge = 1;
	else
		hna_local_entry->never_purge = 0;

	spin_lock_irqsave(&hna_local_hash_lock, flags);

	hash_add(hna_local_hash, hna_local_entry);
	num_hna++;
	atomic_set(&hna_local_changed, 1);

	if (hna_local_hash->elements * 4 > hna_local_hash->size) {
		swaphash = hash_resize(hna_local_hash,
				       hna_local_hash->size * 2);

		if (swaphash == NULL)
			debug_log(LOG_TYPE_CRIT, "Couldn't resize local hna hash table \n");
		else
			hna_local_hash = swaphash;
	}

	spin_unlock_irqrestore(&hna_local_hash_lock, flags);

	/* remove address from global hash if present */
	spin_lock_irqsave(&hna_global_hash_lock, flags);

	hna_global_entry =
		((struct hna_global_entry *)hash_find(hna_global_hash, addr));

	if (hna_global_entry != NULL)
		_hna_global_del_orig(hna_global_entry, "local hna received");

	spin_unlock_irqrestore(&hna_global_hash_lock, flags);
}
예제 #16
0
파일: stunclient.cpp 프로젝트: kitech/toxsh
void StunClient::processResponse(QByteArray resp, QString peer_addr)
{
    u08bits rbuf[STUN_BUFFER_SIZE];
    size_t rlen = 0;
    stun_buffer buf;
    QString mapped_addr;
    u08bits addr_buff[STUN_BUFFER_SIZE] = {0};

    rlen = resp.length();
    memcpy(rbuf, resp.data(), resp.length());

    buf.len = resp.length();
    memcpy(buf.buf, resp.data(), resp.length());

    if (!stun_is_command_message(&buf)) {
        qDebug()<<resp.length()<<("The response is not a STUN message")<<peer_addr;
        // should be a relayed raw UDP packet to peerA
        emit packetReceived(resp, peer_addr);
        return;
    }

    u16bits stun_method;
    u16bits stun_msg_type;
    stun_method = stun_get_method_str(buf.buf, buf.len);
    stun_msg_type = stun_get_msg_type_str(buf.buf, buf.len);
    qDebug()<<"method:"<<stun_method<<getMethodName(stun_method)<<",msg type:"<<stun_msg_type;

    if (stun_method == STUN_METHOD_BINDING) {
    } else {
        this->debugStunResponse(resp);
    }

    // channel data
    if (stun_is_indication(&buf)) {
        u16bits chan_no;
        size_t blen = 0;

        qDebug()<<"indication data:"<<buf.len;

        stun_attr_ref t_attr = stun_attr_get_first_by_type(&buf, STUN_ATTRIBUTE_DATA);
        const u08bits *t_value = stun_attr_get_value(t_attr);
        blen = stun_attr_get_len(t_attr);
        QString xor_peer_addr = getStunAddress(resp, STUN_ATTRIBUTE_XOR_PEER_ADDRESS);

        qDebug()<<"is chan msg:"<<stun_is_channel_message_str(t_value, &blen, &chan_no, 0);
        qDebug()<<"chan no:"<<chan_no<<blen<<xor_peer_addr;

        emit this->packetReceived(QByteArray((char*)t_value + 4, blen - 4), xor_peer_addr);

        return;
    }

    if (!stun_is_response(&buf)) {
        qDebug()<<resp.length()<<("The response is not a reponse message\n");
        return;
    }

    if (!stun_is_success_response(&buf)) {
        int err_code = 0;
        u08bits err_msg[1025] = "\0";
        size_t err_msg_size = sizeof(err_msg);
        if (stun_is_error_response(&buf, &err_code, err_msg, err_msg_size)) {
            printf("The response is an error %d (%s)\n", err_code, (char*) err_msg);
        } else {
            printf("The response is an unrecognized error\n");
        }

        
        // test unauth
        u08bits realm[128] = {0};
        u08bits nonce[256] = {0};
        
        if (stun_is_challenge_response_str(buf.buf, buf.len, &err_code, err_msg, err_msg_size, realm, nonce)) {
            qDebug()<<err_code;
            qDebug()<<err_code<<(char*)err_msg<<(char*)realm<<(char*)nonce;

            m_realm = QByteArray((char*)realm);
            m_nonce = QByteArray((char*)nonce);

            if (stun_method == STUN_METHOD_ALLOCATE) {
                this->allocate((char*)realm, (char*)nonce);
            }
            if (stun_method == STUN_METHOD_CHANNEL_BIND) {
                QThread::msleep(100);
                this->channelBind(m_peer_addr);
            }
        }

        if (err_code == 437) {
            assert(err_code != 437); // allocate mismatch
        }

        if (err_code == 438) {
            assert(err_code != 438); // stale nonce
        }

        if (err_code == 486) {
            assert(err_code != 486); // allocate quota reached
        }

        return;
    }


    if (stun_is_binding_response(&buf)) {
        ioa_addr reflexive_addr;
        addr_set_any(&reflexive_addr);
        if (stun_attr_get_first_addr(&buf, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, &reflexive_addr, NULL) >= 0) {
            stun_attr_ref sar = stun_attr_get_first_by_type_str(buf.buf, buf.len, STUN_ATTRIBUTE_OTHER_ADDRESS);
            if (sar) {
                // *rfc5780 = 1;
                printf("\n========================================\n");
                // printf("RFC 5780 response %d\n",++counter);
                ioa_addr other_addr;
                stun_attr_get_addr_str((u08bits *) buf.buf, (size_t) buf.len, sar, &other_addr, NULL);
                sar = stun_attr_get_first_by_type_str(buf.buf, buf.len, STUN_ATTRIBUTE_RESPONSE_ORIGIN);
                if (sar) {
                    ioa_addr response_origin;
                    stun_attr_get_addr_str((u08bits *) buf.buf, (size_t) buf.len, sar, &response_origin, NULL);
                    addr_debug_print(1, &response_origin, "Response origin: ");
                }
                addr_debug_print(1, &other_addr, "Other addr: ");
            }
            addr_debug_print(1, &reflexive_addr, "UDP reflexive addr");
            addr_to_string(&reflexive_addr, addr_buff);
        } else {
            printf("Cannot read the response\n");
        }

        // emit got addr
        if (strlen((char*)addr_buff) > 0) {
            mapped_addr = QString((char*)addr_buff);
            emit this->mappedAddressRecieved(mapped_addr);
        }
        return;
    } // end bind resp


    if (stun_method == STUN_METHOD_ALLOCATE) {
        m_relayed_addr = this->getStunAddress(resp, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS);
        this->saveAllocatePuples(m_realm, m_nonce);
        emit this->allocateDone(m_relayed_addr);

        if (!m_channel_refresh_timer) {
            m_channel_refresh_timer = new QTimer();
            QObject::connect(m_channel_refresh_timer, &QTimer::timeout, this, &StunClient::onRefreshTimeout);
        }
        if (!m_channel_refresh_timer->isActive()) {
            m_channel_refresh_timer->start(m_channel_refresh_timeout);
        }
    }

    if (stun_method == STUN_METHOD_CREATE_PERMISSION) {
        if (!m_permission_keepalive_timer) {
            emit this->createPermissionDone();
        }

        if (!m_permission_keepalive_timer) {
            m_permission_keepalive_timer = new QTimer();
            QObject::connect(m_permission_keepalive_timer, &QTimer::timeout, this, &StunClient::onPermKATimeout);
        }
        if (!m_permission_keepalive_timer->isActive()) {
            m_permission_keepalive_timer->start(m_permission_keepalive_timeout);
        }
    }

    if (stun_method == STUN_METHOD_CHANNEL_BIND) {
        emit this->channelBindDone(m_relayed_addr);
    }

    if (stun_method == STUN_METHOD_REFRESH) {
        qDebug()<<"refresh responsed.";
    }
}
void hna_global_add_orig(struct orig_node *orig_node,
			 unsigned char *hna_buff, int hna_buff_len)
{
	struct hna_global_entry *hna_global_entry;
	struct hna_local_entry *hna_local_entry;
	struct hashtable_t *swaphash;
	char hna_str[ETH_STR_LEN], orig_str[ETH_STR_LEN];
	int hna_buff_count = 0;
	unsigned long flags;
	unsigned char *hna_ptr;

	addr_to_string(orig_str, orig_node->orig);

	while ((hna_buff_count + 1) * ETH_ALEN <= hna_buff_len) {
		spin_lock_irqsave(&hna_global_hash_lock, flags);

		hna_ptr = hna_buff + (hna_buff_count * ETH_ALEN);
		hna_global_entry = (struct hna_global_entry *)
			hash_find(hna_global_hash, hna_ptr);

		if (hna_global_entry == NULL) {
			spin_unlock_irqrestore(&hna_global_hash_lock, flags);

			hna_global_entry =
				kmalloc(sizeof(struct hna_global_entry),
					GFP_ATOMIC);

			if (!hna_global_entry)
				break;

			memcpy(hna_global_entry->addr, hna_ptr, ETH_ALEN);

			addr_to_string(hna_str, hna_global_entry->addr);
			debug_log(LOG_TYPE_ROUTES, "Creating new global hna entry: %s (via %s)\n", hna_str, orig_str);

			spin_lock_irqsave(&hna_global_hash_lock, flags);
			hash_add(hna_global_hash, hna_global_entry);

		}

		hna_global_entry->orig_node = orig_node;
		spin_unlock_irqrestore(&hna_global_hash_lock, flags);

		/* remove address from local hash if present */
		spin_lock_irqsave(&hna_local_hash_lock, flags);

		hna_ptr = hna_buff + (hna_buff_count * ETH_ALEN);
		hna_local_entry = (struct hna_local_entry *)
			hash_find(hna_local_hash, hna_ptr);

		if (hna_local_entry != NULL)
			hna_local_del(hna_local_entry, "global hna received");

		spin_unlock_irqrestore(&hna_local_hash_lock, flags);

		hna_buff_count++;
	}

	orig_node->hna_buff_len = hna_buff_len;

	if (orig_node->hna_buff_len > 0) {
		orig_node->hna_buff = kmalloc(orig_node->hna_buff_len,
					      GFP_ATOMIC);
		memcpy(orig_node->hna_buff, hna_buff, orig_node->hna_buff_len);
	} else {
		orig_node->hna_buff = NULL;
	}

	spin_lock_irqsave(&hna_global_hash_lock, flags);

	if (hna_global_hash->elements * 4 > hna_global_hash->size) {
		swaphash = hash_resize(hna_global_hash,
				       hna_global_hash->size * 2);

		if (swaphash == NULL)
			debug_log(LOG_TYPE_CRIT, "Couldn't resize global hna hash table \n");
		else
			hna_global_hash = swaphash;
	}

	spin_unlock_irqrestore(&hna_global_hash_lock, flags);
}
예제 #18
0
파일: stunclient.cpp 프로젝트: kitech/toxsh
void StunClient::debugStunResponse(QByteArray resp)
{
    u08bits rbuf[STUN_BUFFER_SIZE];
    size_t rlen = 0;
    stun_buffer buf;
    u08bits addr_buff[STUN_BUFFER_SIZE] = {0};

    rlen = resp.length();
    memcpy(rbuf, resp.data(), resp.length());

    buf.len = resp.length();
    memcpy(buf.buf, resp.data(), resp.length());

    if (!stun_is_command_message(&buf)) {
        qDebug()<<resp.length()<<("The response is not a STUN message\n");
        return;
    }

    if (!stun_is_response(&buf)) {
        qDebug()<<resp.length()<<("The response is not a reponse message\n");
        // return;
    }

    u16bits stun_method;
    u16bits stun_msg_type;
    stun_method = stun_get_method_str(buf.buf, buf.len);
    stun_msg_type = stun_get_msg_type_str(buf.buf, buf.len);
    qDebug()<<"method:"<<stun_method<<getMethodName(stun_method)<<",msg type:"<<stun_msg_type;

    int attr_type;
    const u08bits *attr_value;
    int attr_len;
    char relayed_addr_str[32] = {0};
    char mapped_addr_str[32] = {0};
    char addr_str[32] = {0};
    ioa_addr relayed_addr;
    ioa_addr mapped_addr;
    ioa_addr stun_addr;
    uint32_t lifetime = 0;
    uint32_t bandwidth = 0;
    stun_attr_ref raw_attr = stun_attr_get_first_str(buf.buf, buf.len);
    for ( ; raw_attr ; raw_attr = stun_attr_get_next_str(buf.buf, buf.len, raw_attr)) {
        attr_type = stun_attr_get_type(raw_attr);
        attr_value = stun_attr_get_value(raw_attr);
        attr_len = stun_attr_get_len(raw_attr);

        switch (attr_type) {
        case STUN_ATTRIBUTE_SOFTWARE:
            qDebug()<<"attr software:"<<QByteArray((char*)attr_value, attr_len);
            break;
        case STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS:
            stun_attr_get_addr_str(buf.buf, buf.len, raw_attr, &mapped_addr, NULL);
            addr_to_string(&mapped_addr, (u08bits*)mapped_addr_str);
            qDebug()<<"mapped addr:"<<mapped_addr_str;
            break;
        case STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS:
            stun_attr_get_addr_str(buf.buf, buf.len, raw_attr, &relayed_addr, NULL);
            addr_to_string(&relayed_addr, (u08bits*)relayed_addr_str);
            qDebug()<<"relayed addr:"<<relayed_addr_str;
            break;
        case STUN_ATTRIBUTE_MESSAGE_INTEGRITY:
            qDebug()<<"message integrity:"<<attr_len<<QByteArray((char*)attr_value, attr_len).toHex();
            break;
        case STUN_ATTRIBUTE_LIFETIME:
            memcpy(&lifetime, attr_value, attr_len);
            lifetime = nswap32(lifetime);
            qDebug()<<"lifetime:"<<lifetime;
            break;
        case STUN_ATTRIBUTE_BANDWIDTH:
            memcpy(&bandwidth, attr_value, attr_len);
            bandwidth = nswap32(bandwidth);
            qDebug()<<"bandwidth:"<<bandwidth;
            break;
        case STUN_ATTRIBUTE_XOR_PEER_ADDRESS:
            stun_attr_get_addr_str(buf.buf, buf.len, raw_attr, &stun_addr, NULL);
            addr_to_string(&stun_addr, (u08bits*)addr_str);
            qDebug()<<"xor peer addr:"<<addr_str;
            break;
        case STUN_ATTRIBUTE_DATA:
            
            qDebug()<<"attr data len:"<<attr_len<<QString(QByteArray((char*)attr_value + 4, attr_len - 4)).left(50)<<"...";
            break;
        default:
            qDebug()<<"unkown attr:"<<attr_type<<attr_len;
            break;
        }
    }
}
예제 #19
0
static int turn_create_permission(int verbose, app_ur_conn_info *clnet_info,
		ioa_addr *peer_addr, int addrnum)
{

	if(no_permissions || (addrnum<1))
		return 0;

	char saddr[129]="\0";
	if (verbose) {
		addr_to_string(peer_addr,(u08bits*)saddr);
	}

	stun_buffer request_message, response_message;

	beg_cp:

	{
		int cp_sent = 0;

		stun_init_request(STUN_METHOD_CREATE_PERMISSION, &request_message);
		{
			int addrindex;
			for(addrindex=0;addrindex<addrnum;++addrindex) {
				stun_attr_add_addr(&request_message, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr+addrindex);
			}
		}

		add_origin(&request_message);

		if(add_integrity(clnet_info, &request_message)<0) return -1;

		stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

		while (!cp_sent) {

			int len = send_buffer(clnet_info, &request_message, 0,0);

			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "create perm sent: %s\n",saddr);
				}
				cp_sent = 1;
			} else {
				perror("send");
				exit(1);
			}
		}
	}

	////////////<<==create permission send

	if(not_rare_event()) return 0;

	////////create permission response==>>

	{
		int cp_received = 0;
		while (!cp_received) {

			int len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);
			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
							"cp response received: \n");
				}
				int err_code = 0;
				u08bits err_msg[129];
				if (stun_is_success_response(&response_message)) {

					cp_received = 1;

					if(clnet_info->nonce[0]) {
						if(check_integrity(clnet_info, &response_message)<0)
							return -1;
					}

					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
					}
				} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
									&err_code,err_msg,sizeof(err_msg),
									clnet_info->realm,clnet_info->nonce,
									clnet_info->server_name, &(clnet_info->oauth))) {
					goto beg_cp;
				} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {
					cp_received = 1;
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "create permission error %d (%s)\n",
							      err_code,(char*)err_msg);
					return -1;
				} else {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "unknown create permission response\n");
					/* Try again ? */
				}
			} else {
				perror("recv");
				exit(-1);
			}
		}
	}

	return 0;
}
예제 #20
0
int ess_raf_received_pack(struct s_smc *smc, SMbuf *mb, struct smt_header *sm,
			  int fs)
{
	void			*p ;		
	struct smt_p_0016	*cmd ;		
	SMbuf			*db ;
	u_long			msg_res_type ;	
	u_long			payload, overhead ;
	int			local ;
	int			i ;

	 local = ((fs & L_INDICATOR) != 0) ;

	if (!(p = (void *) sm_to_para(smc,sm,SMT_P0015))) {
		DB_ESS("ESS: RAF frame error, parameter type not found\n",0,0) ;
		return fs;
	}
	msg_res_type = ((struct smt_p_0015 *)p)->res_type ;

	if (!(cmd = (struct smt_p_0016 *) sm_to_para(smc,sm,SMT_P0016))) {
		 DB_ESS("ESS: RAF frame error, parameter command not found\n",0,0);
		 return fs;
	}

	DB_ESSN(2,"fc %x	ft %x\n",sm->smt_class,sm->smt_type) ;
	DB_ESSN(2,"ver %x	tran %lx\n",sm->smt_version,sm->smt_tid) ;
	DB_ESSN(2,"stn_id %s\n",addr_to_string(&sm->smt_source),0) ;

	DB_ESSN(2,"infolen %x	res %x\n",sm->smt_len, msg_res_type) ;
	DB_ESSN(2,"sbacmd %x\n",cmd->sba_cmd,0) ;

	switch (cmd->sba_cmd) {

	case REQUEST_ALLOCATION :
		if (sm->smt_type == SMT_REQUEST) {
			if (!local || smc->mib.fddiESSPayload)
				return fs;
			
			p = (void *) sm_to_para(smc,sm,SMT_P0019)  ;
			for (i = 0; i < 5; i++) {
				if (((struct smt_p_0019 *)p)->alloc_addr.a[i]) {
					return fs;
				}
			}

			smc->ess.alloc_trans_id = sm->smt_tid ;
			DB_ESS("ESS: save Alloc Req Trans ID %lx\n",sm->smt_tid,0);
			p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
			((struct smt_p_320f *)p)->mib_payload =
				smc->mib.a[PATH0].fddiPATHSbaPayload ;
			p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
			((struct smt_p_3210 *)p)->mib_overhead =
				smc->mib.a[PATH0].fddiPATHSbaOverhead ;
			sm->smt_dest = smt_sba_da ;

			if (smc->ess.local_sba_active)
				return fs | I_INDICATOR;

			if (!(db = smt_get_mbuf(smc)))
				return fs;

			db->sm_len = mb->sm_len ;
			db->sm_off = mb->sm_off ;
			memcpy(((char *)(db->sm_data+db->sm_off)),(char *)sm,
				(int)db->sm_len) ;
			dump_smt(smc,
				(struct smt_header *)(db->sm_data+db->sm_off),
				"RAF") ;
			smt_send_frame(smc,db,FC_SMT_INFO,0) ;
			return fs;
		}

		if (smt_check_para(smc,sm,plist_raf_alc_res)) {
			DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
			return fs;
		}

		if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
			!= PRIMARY_RING) ||
			(msg_res_type != SYNC_BW) ||
		(((struct smt_p_reason *)sm_to_para(smc,sm,SMT_P0012))->rdf_reason
			!= SMT_RDF_SUCCESS) ||
			(sm->smt_tid != smc->ess.alloc_trans_id)) {

			DB_ESS("ESS: Allocation Response not accepted\n",0,0) ;
			return fs;
		}

		p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
                if (!p) {
                        printk(KERN_ERR "ESS: sm_to_para failed");
                        return fs;
                }       
		payload = ((struct smt_p_320f *)p)->mib_payload ;
		p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
                if (!p) {
                        printk(KERN_ERR "ESS: sm_to_para failed");
                        return fs;
                }       
		overhead = ((struct smt_p_3210 *)p)->mib_overhead ;

		DB_ESSN(2,"payload= %lx	overhead= %lx\n",payload,overhead) ;

		(void)process_bw_alloc(smc,(long)payload,(long)overhead) ;

		return fs;
		

	case CHANGE_ALLOCATION :
		if (sm->smt_type != SMT_REQUEST) {
			DB_ESS("ESS: Do not process Change Responses\n",0,0) ;
			return fs;
		}

		if (smt_check_para(smc,sm,plist_raf_chg_req)) {
			DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
			return fs;
		}

		if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
			!= PRIMARY_RING) || (msg_res_type != SYNC_BW)) {
			DB_ESS("ESS: RAF frame with para problem, ignoring\n",0,0) ;
			return fs;
		}

		p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
		payload = ((struct smt_p_320f *)p)->mib_payload ;
		p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
		overhead = ((struct smt_p_3210 *)p)->mib_overhead ;

		DB_ESSN(2,"ESS: Change Request from %s\n",
			addr_to_string(&sm->smt_source),0) ;
		DB_ESSN(2,"payload= %lx	overhead= %lx\n",payload,overhead) ;

		if(!process_bw_alloc(smc,(long)payload,(long)overhead))
			return fs;

		ess_send_response(smc,sm,CHANGE_ALLOCATION) ;

		return fs;
		

	case REPORT_ALLOCATION :
		if (sm->smt_type != SMT_REQUEST) {
			DB_ESS("ESS: Do not process a Report Reply\n",0,0) ;
			return fs;
		}

		DB_ESSN(2,"ESS: Report Request from %s\n",
			addr_to_string(&(sm->smt_source)),0) ;

		if (msg_res_type != SYNC_BW) {
			DB_ESS("ESS: ignoring RAF with para problem\n",0,0) ;
			return fs;
		}

		ess_send_response(smc,sm,REPORT_ALLOCATION) ;

		return fs;
		

	default:
		DB_ESS("ESS: ignoring RAF with bad sba_cmd\n",0,0) ;
		break ;
	}

	return fs;
}
예제 #21
0
glibtop_open_files_entry *
glibtop_get_proc_open_files_s (glibtop *server, glibtop_proc_open_files *buf,	pid_t pid)
{
#if __FreeBSD_version > 800018 || (__FreeBSD_version < 800000 && __FreeBSD_version >= 700104)
	struct kinfo_file *freep, *kif;
#ifndef HAVE_KINFO_GETFILE
	int name[4];
	size_t len;
#else
	int cnt;
#endif
	ssize_t i;
#else
	char *output;
#endif
	GArray *entries;

	memset(buf, 0, sizeof (glibtop_proc_open_files));

#if __FreeBSD_version > 800018 || (__FreeBSD_version < 800000 && __FreeBSD_version >= 700104)
#ifndef HAVE_KINFO_GETFILE
	name[0] = CTL_KERN;
	name[1] = KERN_PROC;
	name[2] = KERN_PROC_FILEDESC;
	name[3] = pid;

	if (sysctl(name, 4, NULL, &len, NULL, 0) < 0)
		return NULL;

	freep = kif = g_malloc(len);
	if (sysctl(name, 4, kif, &len, NULL, 0) < 0) {
		g_free(freep);
		return NULL;
	}
#else
	freep = kinfo_getfile(pid, &cnt);
#endif

	entries = g_array_new(FALSE, FALSE, sizeof(glibtop_open_files_entry));

#ifndef HAVE_KINFO_GETFILE
	for (i = 0; i < len / sizeof(*kif); i++, kif++) {
		glibtop_open_files_entry entry = {0};

		if (kif->kf_structsize != sizeof(*kif))
			continue;
#else
	for (i = 0; i < cnt; i++) {
		glibtop_open_files_entry entry = {0};

		kif = &freep[i];
#endif

		if (kif->kf_fd < 0)
			continue;

		if (kif->kf_type == KF_TYPE_SOCKET) {
			if (kif->kf_sock_domain == AF_LOCAL) {
				struct sockaddr_un *sun;

				entry.type = GLIBTOP_FILE_TYPE_LOCALSOCKET;
				sun = (struct sockaddr_un *)&kif->kf_sa_local;

				if (sun->sun_path[0]) {
					char *addrstr;

					addrstr = addr_to_string(&kif->kf_sa_local);
					g_strlcpy(entry.info.localsock.name,
						  addrstr,
						  sizeof(entry.info.localsock.name));
					g_free(addrstr);
				} else {
					char *addrstr;

					addrstr = addr_to_string(&kif->kf_sa_peer);
					g_strlcpy(entry.info.localsock.name,
						  addrstr,
						  sizeof(entry.info.localsock.name));
					g_free(addrstr);
				}
			} else if (kif->kf_sock_domain == AF_INET ||
				   kif->kf_sock_domain == AF_INET6) {
				char *addrstr;

				if (kif->kf_sock_domain == AF_INET)
					entry.type = GLIBTOP_FILE_TYPE_INETSOCKET;
				else
					entry.type = GLIBTOP_FILE_TYPE_INET6SOCKET;
				addrstr = addr_to_string(&kif->kf_sa_peer);
				g_strlcpy(entry.info.sock.dest_host,
					  addrstr,
					  sizeof(entry.info.sock.dest_host));
				g_free(addrstr);
				entry.info.sock.dest_port = addr_to_port(&kif->kf_sa_peer);
			}
		} else if (kif->kf_type == KF_TYPE_PIPE) {
			entry.type = GLIBTOP_FILE_TYPE_PIPE;
		} else if (kif->kf_type == KF_TYPE_VNODE) {
			entry.type = GLIBTOP_FILE_TYPE_FILE;
			g_strlcpy(entry.info.file.name, kif->kf_path,
				  sizeof(entry.info.file.name));
		} else
			continue;

		entry.fd = kif->kf_fd;

		g_array_append_val(entries, entry);
	}
	g_free(freep);
#else

	output = execute_lsof(pid);
	if (output == NULL) return NULL;

	entries = parse_output(output);

	g_free(output);
#endif

	buf->flags = _glibtop_sysdeps_proc_open_files;
	buf->number = entries->len;
	buf->size = sizeof(glibtop_open_files_entry);
	buf->total = buf->number * buf->size;

	return (glibtop_open_files_entry*)g_array_free(entries, FALSE);
}
예제 #22
0
static int create_server_socket(dtls_listener_relay_server_type* server, int report_creation) {

  FUNCSTART;

  if(!server) return -1;

  clean_server(server);

  {
	  ioa_socket_raw udp_listen_fd = -1;

	  udp_listen_fd = socket(server->addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
	  if (udp_listen_fd < 0) {
		  perror("socket");
		  return -1;
	  }

	  server->udp_listen_s = create_ioa_socket_from_fd(server->e, udp_listen_fd, NULL, UDP_SOCKET, LISTENER_SOCKET, NULL, &(server->addr));

	  set_sock_buf_size(udp_listen_fd,UR_SERVER_SOCK_BUF_SIZE);

	  if(sock_bind_to_device(udp_listen_fd, (unsigned char*)server->ifname)<0) {
		  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind listener socket to device %s\n",server->ifname);
	  }

	  set_raw_socket_ttl_options(udp_listen_fd, server->addr.ss.sa_family);
	  set_raw_socket_tos_options(udp_listen_fd, server->addr.ss.sa_family);

	  {
		  const int max_binding_time = 60;
		  int addr_bind_cycle = 0;
		  retry_addr_bind:

		  if(addr_bind(udp_listen_fd,&server->addr,1,1,UDP_SOCKET)<0) {
			  perror("Cannot bind local socket to addr");
			  char saddr[129];
			  addr_to_string(&server->addr,(u08bits*)saddr);
			  TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING,"Cannot bind DTLS/UDP listener socket to addr %s\n",saddr);
			  if(addr_bind_cycle++<max_binding_time) {
				  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Trying to bind DTLS/UDP listener socket to addr %s, again...\n",saddr);
				  sleep(1);
				  goto retry_addr_bind;
			  }
			  TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Fatal final failure: cannot bind DTLS/UDP listener socket to addr %s\n",saddr);
			  exit(-1);
		  }
	  }

	  server->udp_listen_ev = event_new(server->e->event_base,udp_listen_fd,
				    EV_READ|EV_PERSIST,udp_server_input_handler,
				    server);

	  event_add(server->udp_listen_ev,NULL);
  }

  if(report_creation) {
	  if(!turn_params.no_udp && !turn_params.no_dtls)
		  addr_debug_print(server->verbose, &server->addr,"DTLS/UDP listener opened on");
	  else if(!turn_params.no_dtls)
		  addr_debug_print(server->verbose, &server->addr,"DTLS listener opened on");
	  else if(!turn_params.no_udp)
		  addr_debug_print(server->verbose, &server->addr,"UDP listener opened on");
  }

  FUNCEND;
  
  return 0;
}
예제 #23
0
static int create_new_connected_udp_socket(
		dtls_listener_relay_server_type* server, ioa_socket_handle s)
{

	evutil_socket_t udp_fd = socket(s->local_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
	if (udp_fd < 0) {
		perror("socket");
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Cannot allocate new socket\n",
				__FUNCTION__);
		return -1;
	}

	if (sock_bind_to_device(udp_fd, (unsigned char*) (s->e->relay_ifname))
			< 0) {
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
				"Cannot bind udp server socket to device %s\n",
				(char*) (s->e->relay_ifname));
	}

	ioa_socket_handle ret = (ioa_socket*) turn_malloc(sizeof(ioa_socket));
	if (!ret) {
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
				"%s: Cannot allocate new socket structure\n", __FUNCTION__);
		close(udp_fd);
		return -1;
	}

	ns_bzero(ret, sizeof(ioa_socket));

	ret->magic = SOCKET_MAGIC;

	ret->fd = udp_fd;

	ret->family = s->family;
	ret->st = s->st;
	ret->sat = CLIENT_SOCKET;
	ret->local_addr_known = 1;
	addr_cpy(&(ret->local_addr), &(s->local_addr));

	if (addr_bind(udp_fd,&(s->local_addr),1,1,UDP_SOCKET) < 0) {
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
				"Cannot bind new detached udp server socket to local addr\n");
		IOA_CLOSE_SOCKET(ret);
		return -1;
	}
	ret->bound = 1;

	{
		int connect_err = 0;
		if (addr_connect(udp_fd, &(server->sm.m.sm.nd.src_addr), &connect_err) < 0) {
			char sl[129];
			char sr[129];
			addr_to_string(&(ret->local_addr),(u08bits*)sl);
			addr_to_string(&(server->sm.m.sm.nd.src_addr),(u08bits*)sr);
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
					"Cannot connect new detached udp client socket from local addr %s to remote addr %s\n",sl,sr);
			IOA_CLOSE_SOCKET(ret);
			return -1;
		}
	}
	ret->connected = 1;
	addr_cpy(&(ret->remote_addr), &(server->sm.m.sm.nd.src_addr));

	set_socket_options(ret);

	ret->current_ttl = s->current_ttl;
	ret->default_ttl = s->default_ttl;

	ret->current_tos = s->current_tos;
	ret->default_tos = s->default_tos;

#if DTLS_SUPPORTED
	if (!turn_params.no_dtls
			&& is_dtls_handshake_message(
					ioa_network_buffer_data(server->sm.m.sm.nd.nbh),
					(int) ioa_network_buffer_get_size(
							server->sm.m.sm.nd.nbh))) {

		SSL* connecting_ssl = NULL;

		BIO *wbio = NULL;
		struct timeval timeout;

		/* Create BIO */
		wbio = BIO_new_dgram(ret->fd, BIO_NOCLOSE);
		(void) BIO_dgram_set_peer(wbio, (struct sockaddr*) &(server->sm.m.sm.nd.src_addr));

		BIO_ctrl(wbio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &(server->sm.m.sm.nd.src_addr));

		/* Set and activate timeouts */
		timeout.tv_sec = DTLS_MAX_RECV_TIMEOUT;
		timeout.tv_usec = 0;
		BIO_ctrl(wbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);

#if DTLSv1_2_SUPPORTED
		if(get_dtls_version(ioa_network_buffer_data(server->sm.m.sm.nd.nbh),
							(int)ioa_network_buffer_get_size(server->sm.m.sm.nd.nbh)) == 1) {
			connecting_ssl = SSL_NEW(server->dtls_ctx_v1_2);
		} else {
			connecting_ssl = SSL_NEW(server->dtls_ctx);
		}
#else
		{
			connecting_ssl = SSL_NEW(server->dtls_ctx);
		}
#endif

		SSL_set_accept_state(connecting_ssl);

		SSL_set_bio(connecting_ssl, NULL, wbio);

		SSL_set_options(connecting_ssl, SSL_OP_COOKIE_EXCHANGE);
		SSL_set_max_cert_list(connecting_ssl, 655350);
		int rc = ssl_read(ret->fd, connecting_ssl, server->sm.m.sm.nd.nbh,
				server->verbose);

		if (rc < 0) {
			if (!(SSL_get_shutdown(connecting_ssl) & SSL_SENT_SHUTDOWN)) {
				SSL_set_shutdown(connecting_ssl, SSL_RECEIVED_SHUTDOWN);
				SSL_shutdown(connecting_ssl);
			}
			SSL_FREE(connecting_ssl);
			IOA_CLOSE_SOCKET(ret);
			return -1;
		}

		addr_debug_print(server->verbose, &(server->sm.m.sm.nd.src_addr),
				"Accepted DTLS connection from");

		ret->ssl = connecting_ssl;

		ioa_network_buffer_delete(server->e, server->sm.m.sm.nd.nbh);
		server->sm.m.sm.nd.nbh = NULL;

		ret->st = DTLS_SOCKET;
	}
#endif

	server->sm.m.sm.s = ret;
	return server->connect_cb(server->e, &(server->sm));
}
예제 #24
0
/* Received a H(ello) message of the form H<addr>:<port>.  This is the first message
 * that's sent over a TCP connection (in both directions) so the peers can identify
 * one another.  The port is the server port of the endpoint rather than the
 * connection's port.
 *
 * Sometimes accidentally peers try to connect to one another at the same time.
 * This code kills one of the connections.
 */
void hello_received(struct file_info *fi, char *addr_port){
	char *p = index(addr_port, ':');
	if (p == 0) {
		fprintf(stderr, "do_hello: format is H<addr>:<port>\n");
		return;
	}
	*p++ = 0;

	struct sockaddr_in addr;
	if (addr_get(&addr, addr_port, atoi(p)) < 0) {
		return;
	}
	*--p = ':';

	printf("Got hello from %s:%d on socket %d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), fi->fd);

	/* If a connection breaks and is re-established, a duplicate hello message is likely
	 * to arrive, but we can ignore it as we already know the peer.
	 */
	if (fi->status == FI_KNOWN) {
		fprintf(stderr, "Duplicate hello (ignoring)\n");
		if (addr_cmp(addr, fi->addr) != 0) {
			fprintf(stderr, "do_hello: address has changed???\n");
		}
		return;
	}

	/* It is possible to set up a connection to self.  We deal with it by ignoring the
	 * Hello message but keeping the connection established.
	 */
	if (addr_cmp(addr, my_addr) == 0) {
		fprintf(stderr, "Got hello from self??? (ignoring)\n");
		return;
	}

	/* Search the connections to see if there is already a connection to this peer.
	 */
	struct file_info *fi2;
	for (fi2 = file_info; fi2 != 0; fi2 = fi2->next) {
		if (fi2->type == FI_FREE || fi2->status != FI_KNOWN) {
			continue;
		}
		if (addr_cmp(fi2->addr, addr) != 0) {
			continue;
		}

		/* Found another connection.  We're going to keep just one.  First see if
		 * this is actually an existing connection.  It may have broken.
		 */
		if (fi2->fd == -1) {
			printf("Found a defunct connection---dropping that one\n");
			if (fi2->type == FI_OUTGOING) {
				fi->type = FI_OUTGOING;
				fi->u.fi_outgoing = fi2->u.fi_outgoing;
			}
			fi2->type = FI_FREE;
			return;
		}

		/* Of the two, we keep the "lowest one".  We identify a connection by the lowest
		 * endpoint address.
		 */
		struct sockaddr_in mine, other;
		get_id(fi->fd, &mine);
		get_id(fi2->fd, &other);
		if (addr_cmp(mine, other) < 0) {
			/* We keep mine.
			 */
			printf("duplicate connection -- keep mine\n");
			if (fi2->type == FI_OUTGOING) {
				fi->type = FI_OUTGOING;
				fi->u.fi_outgoing = fi2->u.fi_outgoing;
			}
			close(fi2->fd);
			fi2->type = FI_FREE;
		}
		else {
			printf("duplicate connection -- keep other\n");

			/* The other one wins.
			 */
			if (fi->type == FI_OUTGOING) {
				fi2->type = FI_OUTGOING;
				fi2->u.fi_outgoing = fi->u.fi_outgoing;
			}
			close(fi->fd);
			fi->type = FI_FREE;
			return;
		}
	}

	/* No other connection.  Keep this one.
	 */
	printf("New Connection\n");
	fi->addr = addr;
	fi->status = FI_KNOWN;
	if(!nl)
	{
		nl = (struct node_list *) nl_create();
		char *my_addr_str = addr_to_string(my_addr);
		nl_add(nl, my_addr_str);
		free(my_addr_str);
	}
	char *addr_str = addr_to_string(addr);
	nl_add(nl, addr_str);
        free(addr_str);
	updateGraph();
	send_gossip();
}
예제 #25
0
void send_handler(struct file_info *fi, char *msg)
{
  	printf ("SEND HANDLER CALLED\n");
  	if(isalpha(*msg))
  	{
  		printf("Incorrect send command\n");
  		return;
  	}	

	int len = strlen(msg);
	char *ctr = index(msg, '/');
	*ctr++ = 0;

	char *payload = rindex(ctr, '/');
	*payload++ = 0;
	char *my_addr_str = addr_to_string(my_addr);
	if(strcmp(msg, my_addr_str) == 0)
	{
		printf("%s\n", payload);
		free(my_addr_str);
		return;
	}
	else
	{
		int ttl = atoi(ctr);

		if(ttl == 0)
		{
			//free(msg);
			free(my_addr_str);
			return;
		}
		
		int dest_index = nl_index(nl, msg);
		if (dest_index == -1) {
			//free(msg);
			free(my_addr_str);
			return;
		}
		int my_index =  nl_index(nl, my_addr_str);
		
		while (prev[dest_index] != my_index) {
			dest_index = prev[dest_index];
			//Node disconnected 
			if(dest_index == -1)
			{
				free(my_addr_str);
				return;
			}
		}
		// send to the dest_index
		char *dest_addr = nl_name(nl, dest_index);
		ttl--;
		char *str = (char *) malloc(len);
		sprintf(str, "S%s/%d/%s\n",msg, ttl, payload);
		
		struct file_info *f = file_info;
		
		while(f)
		{
		  char *f_addr_str = addr_to_string(f->addr);
		  if(strcmp(dest_addr, f_addr_str) == 0 &&
		     (f->type == FI_INCOMING || (f->type == FI_OUTGOING && f->status == FI_KNOWN
						 && f->u.fi_outgoing.status == FI_CONNECTED)))
		    break;
		    
		  
		  f = f->next;
		  //free(f_addr_str);
		  //free(myaddr);
		}
		
		if (f) {
		  printf("%s\n", addr_to_string(f->addr));
		  file_info_send(f, str, strlen(str));
		}
		else
		  printf("f not found\n");
	}
	free(my_addr_str);

}
예제 #26
0
static int reopen_server_socket(dtls_listener_relay_server_type* server)
{
	if(!server)
		return 0;

	FUNCSTART;

	EVENT_DEL(server->udp_listen_ev);

	if(server->udp_listen_s->fd>=0) {
		socket_closesocket(server->udp_listen_s->fd);
		server->udp_listen_s->fd = -1;
	}

	if (!(server->udp_listen_s)) {
		return create_server_socket(server);
	}

	ioa_socket_raw udp_listen_fd = socket(server->addr.ss.ss_family, SOCK_DGRAM, 0);
	if (udp_listen_fd < 0) {
		perror("socket");
		FUNCEND;
		return -1;
	}

	server->udp_listen_s->fd = udp_listen_fd;

	/* some UDP sessions may fail due to the race condition here */

	set_socket_options(server->udp_listen_s);

	set_sock_buf_size(udp_listen_fd, UR_SERVER_SOCK_BUF_SIZE);

	if (sock_bind_to_device(udp_listen_fd, (unsigned char*) server->ifname) < 0) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
			"Cannot bind listener socket to device %s\n",
			server->ifname);
	}

	if(addr_bind(udp_listen_fd,&server->addr)<0) {
		  perror("Cannot bind local socket to addr");
		  char saddr[129];
		  addr_to_string(&server->addr,(u08bits*)saddr);
		  TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Cannot bind listener socket to addr %s\n",saddr);
		  return -1;
	}

	server->udp_listen_ev = event_new(server->e->event_base, udp_listen_fd,
				EV_READ | EV_PERSIST, udp_server_input_handler, server);

	event_add(server->udp_listen_ev, NULL );

	if (!no_udp && !no_dtls)
		addr_debug_print(server->verbose, &server->addr,
					"UDP/DTLS listener opened on ");
	else if (!no_dtls)
		addr_debug_print(server->verbose, &server->addr,
					"DTLS listener opened on ");
	else if (!no_udp)
		addr_debug_print(server->verbose, &server->addr,
				"UDP listener opened on ");

	FUNCEND;

	return 0;
}
예제 #27
0
파일: reds-stream.c 프로젝트: fgouget/spice
static char *reds_stream_get_remote_address(RedsStream *stream)
{
    return addr_to_string("%s;%s", &stream->priv->info->paddr_ext,
                          stream->priv->info->plen_ext);
}
예제 #28
0
/* Activity on a socket: input, output, or error...
 */
static void message_handler(struct file_info *fi, int events){
  	printf("Message handler called\n");
	char buf[512];

	if (events & (POLLERR | POLLHUP)) {
		double time;
		int error;
		socklen_t len = sizeof(error);
		if (getsockopt(fi->fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
			perror("getsockopt");
		}
		switch (error) {
		case 0:
			printf("Lost connection on socket %d\n", fi->fd);
			time = timer_now() + 1;
			break;
		default:
			printf("Error '%s' on socket %d\n", strerror(error), fi->fd);
			time = timer_now() + 5;
		}

		close(fi->fd);

		/* Start a timer to reconnect.
		 */
		if (fi->type == FI_OUTGOING) {
			timer_start(time, timer_reconnect, fi->uid);
			fi->fd = -1;
			fi->u.fi_outgoing.status = FI_CONNECTING;
		}
		else {
			fi->type = FI_FREE;
		}
		char *my_addr_str = addr_to_string(my_addr);
		char *fi_addr_str = addr_to_string(fi->addr);
		  
		set_dist(nl, graph, nl_nsites(nl), fi_addr_str, my_addr_str, 0);
		updateGraph();
		send_gossip();
		free (my_addr_str);
		free (fi_addr_str);

		return;
	}
	if (events & POLLOUT) {
		int n = send(fi->fd, fi->output_buffer, fi->amount_to_send, 0);
		if (n < 0) {
			perror("send");
		}
		if (n > 0) {
			if (n == fi->amount_to_send) {
				fi->amount_to_send = 0;
			}
			else {
				memmove(&fi->output_buffer[n], fi->output_buffer, fi->amount_to_send - n);
				fi->amount_to_send -= n;
			}
		}
	}
	if (events & POLLIN) {
		add_input(fi);
	}
	if (events & ~(POLLIN|POLLOUT|POLLERR|POLLHUP)) {
		printf("message_handler: unknown events\n");
		fi->events = 0;
	}
}
예제 #29
0
static RList *r_debug_desc_native_list (int pid) {
// TODO: windows
#if __APPLE__
	return xnu_desc_list (pid);
#elif __WINDOWS__
	return win_desc_list(pid);
#elif __KFBSD__
	RList *ret = NULL;
	int perm, type, mib[4];
	size_t len;
	char *buf, *bp, *eb, *str, path[1024];
	RDebugDesc *desc;
	struct kinfo_file *kve;

	len = 0;
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_FILEDESC;
	mib[3] = pid;

	if (sysctl (mib, 4, NULL, &len, NULL, 0) != 0) return NULL;
	len = len * 4 / 3;
	buf = malloc(len);
	if (buf == NULL) return (NULL);
	if (sysctl (mib, 4, buf, &len, NULL, 0) != 0) {
		free (buf);
		return NULL;
	}
	bp = buf;
	eb = buf + len;
	ret = r_list_new ();
	if (!ret) {
		free (buf);
		return NULL;
	}
	ret->free = (RListFree) r_debug_desc_free;
	while (bp < eb) {
		kve = (struct kinfo_file *)(uintptr_t)bp;
		bp += kve->kf_structsize;
		if (kve->kf_fd < 0) continue; // Skip root and cwd. We need it ??
		str = kve->kf_path;
		switch (kve->kf_type) {
		case KF_TYPE_VNODE: type = 'v'; break;
		case KF_TYPE_SOCKET:
			type = 's';
			if (kve->kf_sock_domain == AF_LOCAL) {
				struct sockaddr_un *sun =
					(struct sockaddr_un *)&kve->kf_sa_local;
				if (sun->sun_path[0] != 0)
					addr_to_string (&kve->kf_sa_local, path, sizeof(path));
				else
					addr_to_string (&kve->kf_sa_peer, path, sizeof(path));
			} else {
				addr_to_string (&kve->kf_sa_local, path, sizeof(path));
				strcat (path, " ");
				addr_to_string (&kve->kf_sa_peer, path + strlen (path),
						sizeof (path));
			}
			str = path;
			break;
		case KF_TYPE_PIPE: type = 'p'; break;
		case KF_TYPE_FIFO: type = 'f'; break;
		case KF_TYPE_KQUEUE: type = 'k'; break;
		case KF_TYPE_CRYPTO: type = 'c'; break;
		case KF_TYPE_MQUEUE: type = 'm'; break;
		case KF_TYPE_SHM: type = 'h'; break;
		case KF_TYPE_PTS: type = 't'; break;
		case KF_TYPE_SEM: type = 'e'; break;
		case KF_TYPE_NONE:
		case KF_TYPE_UNKNOWN:
		default: type = '-'; break;
		}
		perm = (kve->kf_flags & KF_FLAG_READ)?R_IO_READ:0;
		perm |= (kve->kf_flags & KF_FLAG_WRITE)?R_IO_WRITE:0;
		desc = r_debug_desc_new (kve->kf_fd, str, perm, type,
					kve->kf_offset);
		if (desc == NULL) break;
		r_list_append (ret, desc);
	}

	free (buf);
	return ret;
#elif __linux__
	return linux_desc_list (pid);
#else
#warning list filedescriptors not supported for this platform
	return NULL;
#endif
}
예제 #30
0
static int handle_udp_packet(dtls_listener_relay_server_type *server,
				struct message_to_relay *sm,
				ioa_engine_handle ioa_eng, turn_turnserver *ts)
{
	int verbose = ioa_eng->verbose;
	ioa_socket_handle s = sm->m.sm.s;

	ur_addr_map_value_type mvt = 0;
	ur_addr_map *amap = server->children_ss;

	ioa_socket_handle chs = NULL;
	if ((ur_addr_map_get(amap, &(sm->m.sm.nd.src_addr), &mvt) > 0) && mvt) {
		chs = (ioa_socket_handle) mvt;
	}

	if (chs && !ioa_socket_tobeclosed(chs)
			&& (chs->sockets_container == amap)
			&& (chs->magic == SOCKET_MAGIC)) {
		s = chs;
		sm->m.sm.s = s;
		if(s->ssl) {
			int read_len = (int)ioa_network_buffer_get_size(sm->m.sm.nd.nbh);
			int sslret = ssl_read(s->fd, s->ssl, (s08bits*)ioa_network_buffer_data(sm->m.sm.nd.nbh),
				(int)ioa_network_buffer_get_capacity(),
				verbose, &read_len);
			if(sslret < 0) {
				ioa_network_buffer_delete(ioa_eng, sm->m.sm.nd.nbh);
				sm->m.sm.nd.nbh = NULL;
				ts_ur_super_session *ss = (ts_ur_super_session *) s->session;
				if (ss) {
					turn_turnserver *server = (turn_turnserver *) ss->server;
					if (server) {
						shutdown_client_connection(server, ss);
					}
				} else {
					close_ioa_socket(s);
				}
				ur_addr_map_del(amap, &(sm->m.sm.nd.src_addr), NULL);
				sm->m.sm.s = NULL;
				s = NULL;
				chs = NULL;
			} else if(read_len>0) {
				ioa_network_buffer_set_size(sm->m.sm.nd.nbh,(size_t)read_len);
			} else {
				ioa_network_buffer_delete(ioa_eng, sm->m.sm.nd.nbh);
				sm->m.sm.nd.nbh = NULL;
			}
		}

		if (s && s->read_cb && sm->m.sm.nd.nbh) {
			s->e = ioa_eng;
			s->read_cb(s, IOA_EV_READ, &(sm->m.sm.nd), s->read_ctx);
			ioa_network_buffer_delete(ioa_eng, sm->m.sm.nd.nbh);
			sm->m.sm.nd.nbh = NULL;

			if (ioa_socket_tobeclosed(s)) {
				ts_ur_super_session *ss = (ts_ur_super_session *) s->session;
				if (ss) {
					turn_turnserver *server = (turn_turnserver *) ss->server;
					if (server) {
						shutdown_client_connection(server, ss);
					}
				}
			}
		}
	} else {
		if (chs && ioa_socket_tobeclosed(chs)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
					"%s: socket to be closed\n", __FUNCTION__);
			{
				u08bits saddr[129];
				u08bits rsaddr[129];
				long thrid = 0;
#if !defined(TURN_NO_THREADS)
				thrid = (long) pthread_self();
#endif
				addr_to_string(get_local_addr_from_ioa_socket(chs),saddr);
				addr_to_string(get_remote_addr_from_ioa_socket(chs),rsaddr);
				TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
					"%s: thrid=0x%lx: Amap = 0x%lx, socket container=0x%lx, local addr %s, remote addr %s, s=0x%lx, done=%d, tbc=%d\n",
					__FUNCTION__, thrid, (long) amap,
					(long) (chs->sockets_container), (char*) saddr,
					(char*) rsaddr, (long) s, (int) (chs->done),
					(int) (chs->tobeclosed));
			}
		}

		if (chs && (chs->magic != SOCKET_MAGIC)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
					"%s: wrong socket magic\n", __FUNCTION__);
		}

		if (chs && (chs->sockets_container != amap)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
					"%s: wrong socket container\n", __FUNCTION__);
			{
				u08bits saddr[129];
				u08bits rsaddr[129];
				long thrid = 0;
#if !defined(TURN_NO_THREADS)
				thrid = (long) pthread_self();
#endif
				addr_to_string(get_local_addr_from_ioa_socket(chs),saddr);
				addr_to_string(get_remote_addr_from_ioa_socket(chs),rsaddr);
				TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
					"%s: thrid=0x%lx: Amap = 0x%lx, socket container=0x%lx, local addr %s, remote addr %s, s=0x%lx, done=%d, tbc=%d, st=%d, sat=%d\n",
					__FUNCTION__, thrid, (long) amap,
					(long) (chs->sockets_container), (char*) saddr,
					(char*) rsaddr, (long) chs, (int) (chs->done),
					(int) (chs->tobeclosed), (int) (chs->st),
					(int) (chs->sat));
			}
		}

		chs = NULL;

#if !defined(TURN_NO_DTLS)
		if (!no_dtls &&
			is_dtls_handshake_message(ioa_network_buffer_data(sm->m.sm.nd.nbh),
			(int)ioa_network_buffer_get_size(sm->m.sm.nd.nbh))) {
			chs = dtls_server_input_handler(server,
				ioa_network_buffer_data(sm->m.sm.nd.nbh),
				(int)ioa_network_buffer_get_size(sm->m.sm.nd.nbh));
			ioa_network_buffer_delete(server->e, sm->m.sm.nd.nbh);
			sm->m.sm.nd.nbh = NULL;
		}
#endif

		if(!chs) {
			chs = create_ioa_socket_from_fd(ioa_eng, s->fd, s,
				UDP_SOCKET, CLIENT_SOCKET, &(sm->m.sm.nd.src_addr),
				get_local_addr_from_ioa_socket(s));
		}

		s = chs;
		sm->m.sm.s = s;

		if (s) {
			if(verbose) {
				u08bits saddr[129];
				u08bits rsaddr[129];
				addr_to_string(get_local_addr_from_ioa_socket(s),saddr);
				addr_to_string(get_remote_addr_from_ioa_socket(s),rsaddr);
				TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
					"%s: New UDP endpoint: local addr %s, remote addr %s\n",
					__FUNCTION__, (char*) saddr,(char*) rsaddr);
			}
			s->e = ioa_eng;
			add_socket_to_map(s, amap);
			open_client_connection_session(ts, &(sm->m.sm));
		}
	}

	return 0;
}