Ejemplo n.º 1
0
void cTCPLinkImpl::UpdateAddress(const sockaddr * a_Address, socklen_t a_AddrLen, AString & a_IP, UInt16 & a_Port)
{
	// Based on the family specified in the address, use the correct datastructure to convert to IP string:
	char IP[128];
	switch (a_Address->sa_family)
	{
		case AF_INET:  // IPv4:
		{
			const sockaddr_in * sin = reinterpret_cast<const sockaddr_in *>(a_Address);
			evutil_inet_ntop(AF_INET, &(sin->sin_addr), IP, sizeof(IP));
			a_Port = ntohs(sin->sin_port);
			break;
		}
		case AF_INET6:  // IPv6
		{
			const sockaddr_in6 * sin = reinterpret_cast<const sockaddr_in6 *>(a_Address);
			evutil_inet_ntop(AF_INET6, &(sin->sin6_addr), IP, sizeof(IP));
			a_Port = ntohs(sin->sin6_port);
			break;
		}

		default:
		{
			LOGWARNING("%s: Unknown socket address family: %d", __FUNCTION__, a_Address->sa_family);
			ASSERT(!"Unknown socket address family");
			break;
		}
	}
	a_IP.assign(IP);
}
Ejemplo n.º 2
0
char const *
endpoint_presentation(struct endpoint const *e)
{
    static char name[INET6_ADDRSTRLEN];

    switch (e->addr.ss_family)
    {
        case AF_INET:
            {
                struct sockaddr_in *sin = (struct sockaddr_in *)&e->addr;
                char tmp[INET_ADDRSTRLEN];

                evutil_inet_ntop(AF_INET, &sin->sin_addr, tmp, sizeof tmp);
                evutil_snprintf(name, INET6_ADDRSTRLEN, "%s:%d", tmp, ntohs(sin->sin_port));
                break;
            }
        case AF_INET6:
            {
                struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&e->addr;
                char tmp[INET6_ADDRSTRLEN];

                evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, tmp, sizeof tmp);
                evutil_snprintf(name, INET6_ADDRSTRLEN, "%s:%d", tmp, ntohs(sin6->sin6_port));
                break;
            }
        default:
            {
                log_warnx("[ENDPOINT] presentation doesn't handle protocol", e->addr.ss_family);
            }
    }
    return name;
}
Ejemplo n.º 3
0
/** Converts the SOCKET_ADDRESS structure received from the OS into an IP address string. */
static AString PrintAddress(SOCKET_ADDRESS & a_Addr)
{
	char IP[128];
	switch (a_Addr.lpSockaddr->sa_family)
	{
		case AF_INET:
		{
			auto sin = reinterpret_cast<const sockaddr_in *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin_addr), IP, sizeof(IP));
			break;
		}
		case AF_INET6:
		{
			auto sin = reinterpret_cast<const sockaddr_in6 *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin6_addr), IP, sizeof(IP));
			break;
		}
		default:
		{
			IP[0] = 0;
			break;
		}
	}
	return IP;
}
Ejemplo n.º 4
0
const char *
tr_address_to_string_with_buf (const tr_address * addr, char * buf, size_t buflen)
{
    assert (tr_address_is_valid (addr));

    if (addr->type == TR_AF_INET)
        return evutil_inet_ntop (AF_INET, &addr->addr, buf, buflen);
    else
        return evutil_inet_ntop (AF_INET6, &addr->addr, buf, buflen);
}
Ejemplo n.º 5
0
static void dns_cb(int errcode, struct evutil_addrinfo *addr, void *ptr)
{
	struct evutil_addrinfo *ai;
	struct timeval tv;
	const char *host = ptr;

	if (errcode) {
		tmate_status_message("%s lookup failure. Retrying in %d seconds (%s)",
				     host, TMATE_DNS_RETRY_TIMEOUT,
				     evutil_gai_strerror(errcode));

		tv.tv_sec = TMATE_DNS_RETRY_TIMEOUT;
		tv.tv_usec = 0;

		evtimer_assign(&tmate_session.ev_dns_retry, tmate_session.ev_base,
			       on_dns_retry, NULL);
		evtimer_add(&tmate_session.ev_dns_retry, &tv);

		return;
	}

	tmate_status_message("Connecting to %s...", host);

	for (ai = addr; ai; ai = ai->ai_next) {
		char buf[128];
		const char *ip = NULL;
		if (ai->ai_family == AF_INET) {
			struct sockaddr_in *sin = (struct sockaddr_in *)ai->ai_addr;
			ip = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, 128);
		} else if (ai->ai_family == AF_INET6) {
			struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ai->ai_addr;
			ip = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, 128);
		}

		tmate_debug("Trying server %s", ip);

		/*
		 * Note: We don't deal with the client list. Clients manage it
		 * and free client structs when necessary.
		 */
		(void)tmate_ssh_client_alloc(&tmate_session, ip);
	}

	evutil_freeaddrinfo(addr);

	/*
	 * XXX For some reason, freeing the DNS resolver makes MacOSX flip out...
	 * not sure what's going on...
	 * evdns_base_free(tmate_session.ev_dnsbase, 0);
	 * tmate_session.ev_dnsbase = NULL;
	 */
}
Ejemplo n.º 6
0
char const* tr_address_to_string_with_buf(tr_address const* addr, char* buf, size_t buflen)
{
    TR_ASSERT(tr_address_is_valid(addr));

    if (addr->type == TR_AF_INET)
    {
        return evutil_inet_ntop(AF_INET, &addr->addr, buf, buflen);
    }
    else
    {
        return evutil_inet_ntop(AF_INET6, &addr->addr, buf, buflen);
    }
}
Ejemplo n.º 7
0
int Socks5Req::parse(evbuffer *input) {
  auto len = evbuffer_get_length(input);
  if (len <= 6) return 1;
  uint8_t buffer[512];
  evbuffer_copyout(input, buffer, 6);
  if (buffer[0] != 0x5) return -1;

  switch (buffer[1]) {
    case 0x1:
      this->cmd = CONNECT;
      break;
    case 0x02:
      this->cmd = BIND;
      break;
    case 0x03:
      this->cmd = UDP;
      break;
  }
  size_t addrlen = 0;

  switch (buffer[3]) {
    case 0x01: {
      this->addressType = IPV4;
      addrlen = 4;
      if (len < 6 + addrlen) return 1;
      evbuffer_remove(input, buffer, sizeof(buffer));
      this->port = ntohs(*(uint16_t *)(buffer + 4 + addrlen));
      evutil_inet_ntop(AF_INET, buffer + 4, this->addr, sizeof(this->addr));
    } break;
    case 0x03:
      this->addressType = DOMAINNAME;
      addrlen = buffer[4];
      if (len < 6 + addrlen + 1) return 1;
      evbuffer_remove(input, buffer, sizeof(buffer));
      this->port = ntohs(*(uint16_t *)(buffer + 5 + addrlen));
      memcpy(this->addr, buffer + 5, addrlen);
      this->addr[addrlen] = '\0';
      break;
    case 0x04: {
      this->addressType = IPV6;
      addrlen = 16;
      if (len < 6 + addrlen) return 1;
      evbuffer_remove(input, buffer, sizeof(buffer));
      this->port = ntohs(*(uint16_t *)(buffer + 4 + addrlen));
      evutil_inet_ntop(AF_INET6, buffer + 4, this->addr, sizeof(this->addr));
    } break;
  }
  return 0;
}
Ejemplo n.º 8
0
void cServerHandleImpl::Callback(evconnlistener * a_Listener, evutil_socket_t a_Socket, sockaddr * a_Addr, int a_Len, void * a_Self)
{
	// Cast to true self:
	cServerHandleImpl * Self = reinterpret_cast<cServerHandleImpl *>(a_Self);
	ASSERT(Self != nullptr);
	ASSERT(Self->m_SelfPtr != nullptr);

	// Get the textual IP address and port number out of a_Addr:
	char IPAddress[128];
	UInt16 Port = 0;
	switch (a_Addr->sa_family)
	{
		case AF_INET:
		{
			sockaddr_in * sin = reinterpret_cast<sockaddr_in *>(a_Addr);
			evutil_inet_ntop(AF_INET, &(sin->sin_addr), IPAddress, ARRAYCOUNT(IPAddress));
			Port = ntohs(sin->sin_port);
			break;
		}
		case AF_INET6:
		{
			sockaddr_in6 * sin6 = reinterpret_cast<sockaddr_in6 *>(a_Addr);
			evutil_inet_ntop(AF_INET6, &(sin6->sin6_addr), IPAddress, ARRAYCOUNT(IPAddress));
			Port = ntohs(sin6->sin6_port);
			break;
		}
	}

	// Call the OnIncomingConnection callback to get the link callbacks to use:
	cTCPLink::cCallbacksPtr LinkCallbacks = Self->m_ListenCallbacks->OnIncomingConnection(IPAddress, Port);
	if (LinkCallbacks == nullptr)
	{
		// Drop the connection:
		evutil_closesocket(a_Socket);
		return;
	}

	// Create a new cTCPLink for the incoming connection:
	cTCPLinkImplPtr Link = std::make_shared<cTCPLinkImpl>(a_Socket, LinkCallbacks, Self->m_SelfPtr, a_Addr, static_cast<socklen_t>(a_Len));
	{
		cCSLock Lock(Self->m_CS);
		Self->m_Connections.push_back(Link);
	}  // Lock(m_CS)
	LinkCallbacks->OnLinkCreated(Link);
	Link->Enable(Link);

	// Call the OnAccepted callback:
	Self->m_ListenCallbacks->OnAccepted(*Link);
}
Ejemplo n.º 9
0
    static bool HHVM_STATIC_METHOD(EventUtil, getSocketName, const Resource &socket, VRefParam address, VRefParam port){
        evutil_socket_t fd = resource_to_fd(socket);
        struct sockaddr sa;
        socklen_t sa_len = sizeof(struct sockaddr);
        long l_port = 0;

        if (getsockname(fd, &sa, &sa_len)) {
            raise_warning("Unable to retreive socket name.");
            return false;
        }

        switch (sa.sa_family) {
            case AF_INET:
            {
                struct sockaddr_in *sa_in = (struct sockaddr_in *) &sa;
                char c_addr[INET_ADDRSTRLEN + 1];
                if (evutil_inet_ntop(sa.sa_family, &sa_in->sin_addr, c_addr, sizeof(c_addr))) {
                    address = StringData::Make(c_addr, CopyString);
                    l_port = ntohs(sa_in->sin_port);
                }
            }
            break;
#ifdef AF_INET6
            case AF_INET6: {
                struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *) &sa;
                char c_addr6[INET6_ADDRSTRLEN + 1];
                if (evutil_inet_ntop(sa.sa_family, &sa_in6->sin6_addr, c_addr6, sizeof(c_addr6))) {
                    address = StringData::Make(c_addr6, CopyString);
                    l_port = ntohs(sa_in6->sin6_port);
                }
                break;
            }
#endif
#ifdef HAVE_SYS_UN_H
            case AF_UNIX: {
                struct sockaddr_un *ua = (struct sockaddr_un *) &sa;
                address = StringData::Make(ua->sun_path, CopyString);
                break;
            }
#endif
            default:
                raise_warning("Unsupported address family.");
                return false;
        }
        if(port.isReferenced()){
            port = l_port;
        }
        return true;
    }
Ejemplo n.º 10
0
static void
ipv6_query_cb(int result, char type, int count, int ttl,
              void * const ips_, void * const app_context_)
{
    char             ip_s_buf[INET6_ADDRSTRLEN + 1U];
    AppContext      *app_context = app_context_;
    struct in6_addr *ips = ips_;
    const char      *ip_s;
    int              i = 0;

    (void) ttl;
    if (result != DNS_ERR_NONE) {
        query_cb_err_print(result);
    }
    assert(type == DNS_IPv6_AAAA);
    assert(count >= 0);
    while (i < count) {
        ip_s = evutil_inet_ntop(AF_INET6, &ips[i], ip_s_buf, sizeof ip_s_buf);
        if (ip_s != NULL) {
            puts(ip_s);
        }
        i++;
    }
    event_base_loopexit(app_context->event_loop, NULL);
}
Ejemplo n.º 11
0
void diplay_socket_information(struct evhttp_bound_socket *handle) {
	struct sockaddr_storage ss;
	evutil_socket_t fd;
	ev_socklen_t socklen = sizeof(ss);
	char addrbuf[128];
	void *inaddr;
	const char *addr;
	int got_port = -1;

	fd = evhttp_bound_socket_get_fd(handle);
	memset(&ss, 0, sizeof(ss));
	if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
		perror("getsockname() failed");
		exit(1);
	}
	if (ss.ss_family == AF_INET) {
		got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
		inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
	} else {
		fprintf(stderr, "Weird address family %d\n", ss.ss_family);
		exit(1);
	}
	addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf, sizeof(addrbuf));
	if (addr) {
		printf("Listening on %s:%d\n", addr, got_port);
		evutil_snprintf(uri_root, sizeof(uri_root),
			"http://%s:%d",addr,got_port);
	} else {
		fprintf(stderr, "evutil_inet_ntop failed\n");
		exit(1);
	}
}
Ejemplo n.º 12
0
static void
socks_accept_cb(struct evconnlistener *lis, evutil_socket_t fd,
	struct sockaddr *addr, int len, void *ptr)
{
	obfsproxyssh_client_t *client = ptr;
	obfsproxyssh_t *state = client->state;
	obfsproxyssh_client_session_t *session;
	struct sockaddr_in *sa;
	char addr_buf[INET_ADDRSTRLEN];
	uint32_t tmp;

	assert(lis == client->listener);

	/*
	 * It is possible to defer allocating the session object till after the
	 * SOCKS protocol handling is done, but there isn't much point in doing
	 * so.
	 */

	session = calloc(1, sizeof(obfsproxyssh_client_session_t));
	if (NULL == session) {
		log_f(state, "SOCKS: Error: Failed to allocate session");
		goto out_close;
	}

	session->socks_ev = bufferevent_socket_new(state->base, fd,
					BEV_OPT_CLOSE_ON_FREE);
	if (NULL == session->socks_ev) {
		log_f(state, "SOCKS: Error: Failed to allocate bev");
		free(session);
		goto out_close;
	}
	bufferevent_setcb(session->socks_ev, socks_read_cb, NULL,
			socks_event_cb, session);
	bufferevent_enable(session->socks_ev, EV_READ | EV_WRITE);

	sa = (struct sockaddr_in *) addr;
	if (0 == state->unsafe_logging) {
		tmp = ntohl(sa->sin_addr.s_addr);
		tmp &= 0x000000ff;
		session->socks_addr = bformat("xxx.xxx.xxx.%d:%d", tmp,
			ntohs(sa->sin_port));
	} else {
		evutil_inet_ntop(AF_INET, &sa->sin_addr, addr_buf,
				INET_ADDRSTRLEN);
		session->socks_addr = bformat("%s:%d", addr_buf,
				ntohs(sa->sin_port));
	}
	/* TODO: Set the timeout */

	LIST_INSERT_HEAD(&client->sessions, session, entries);
	session->client = client;

	log_f(state, "SOCKS: %s Connect", bdata(session->socks_addr));

	return;

out_close:
	evutil_closesocket(fd);
}
Ejemplo n.º 13
0
void CDNSManager::LookupDNSCallback(int _errcode, struct evutil_addrinfo *_addr, void* _context)
{
    DNS_RECORD_t* record = (DNS_RECORD_t*)_context;
 
    if (_errcode)
    {
        LOG_ERROR_STREAM << "Fail to parse " << record->name << ": " << evutil_gai_strerror(_errcode);
    }
    else
    {
        record->address.clear();
        record->visitTime = time(NULL);
        record->status = MAIN_TABLE_RECORD_t::STATUS_e::STATUS_READY;
        if (_addr->ai_canonname)    record->cname = _addr->ai_canonname;

        //
        // get ip addresses
        //
        struct evutil_addrinfo  *ai;
        for (ai = _addr; ai; ai = ai->ai_next) 
        {
            char buf[128] = { 0 };
            const char* ipAddr = NULL;
            if (ai->ai_family == AF_INET) 
            {
                struct sockaddr_in* sin = (struct sockaddr_in *)ai->ai_addr;
                ipAddr = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
            }
            else if (ai->ai_family == AF_INET6) 
            {
                struct sockaddr_in6* sin6 = (struct sockaddr_in6 *)ai->ai_addr;
                ipAddr = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
            }

            if (ipAddr)
            {
                record->address += ipAddr;
                record->address += ", ";
            }
        }

        evutil_freeaddrinfo(_addr);
    }

    if (--s_pendingLookupCount == 0)
        event_base_loopexit(CDNSManager::GetInstance()->m_evbase, NULL);        
}
Ejemplo n.º 14
0
char *
sock_ntop(const struct sockaddr *sa, socklen_t salen)
{
    static char str[128];       /* Unix domain is largest */

    switch (sa->sa_family) {
    case AF_INET: {
        struct sockaddr_in  *sin = (struct sockaddr_in *) sa;

        if (evutil_inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL)
            return(NULL);
        return(str);
    }

#ifdef  IPv6
    case AF_INET6: {
        struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;

        if (evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, str, sizeof(str) - 1) == NULL)
            return(NULL);
        return (str);
    }
#endif

#ifndef WIN32
#ifdef  AF_UNIX 
    case AF_UNIX: {
        struct sockaddr_un  *unp = (struct sockaddr_un *) sa;

            /* OK to have no pathname bound to the socket: happens on
               every connect() unless client calls bind() first. */
        if (unp->sun_path[0] == 0)
            strcpy(str, "(no pathname bound)");
        else
            snprintf(str, sizeof(str), "%s", unp->sun_path);
        return(str);
    }
#endif
#endif

    default:
        snprintf(str, sizeof(str), "sock_ntop: unknown AF_xxx: %d, len %d",
                 sa->sa_family, salen);
        return(str);
    }
    return (NULL);
}
Ejemplo n.º 15
0
	static void
accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
		struct sockaddr *a, int slen, void *p)
{
	/* Extract and display the address we're connect. */
	struct sockaddr_storage ss;
	ev_socklen_t socklen = sizeof(ss);
	char addrbuf[128];
	void *inaddr;
	const char *addr;
	int got_port = -1;
	memset(&ss, 0, sizeof(ss));
	if (getpeername(fd, (struct sockaddr *)&ss, &socklen)) {
		perror("getpeerkname() failed");
		return ;
	}
	if (ss.ss_family == AF_INET) {
		got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
		inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
	} else if (ss.ss_family == AF_INET6) {
		got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
		inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
	} else {
		fprintf(stderr, "Weird address family %d\n",
				ss.ss_family);
		return;
	}
	addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf, sizeof(addrbuf));
	if (addr) {
		printf("connection from address %s:%d\n", addr, got_port);
	} else {
		fprintf(stderr, "evutil_inet_ntop failed\n");
		return ;
	}
	struct bufferevent *b_out, *b_in;
	/* Create two linked bufferevent objects: one to connect, one for the
	 * new connection */
	b_in = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);

	b_out = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);


	assert(b_in && b_out);

	if (bufferevent_socket_connect(b_out, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) 
	{
		perror("bufferevent_socket_connect");
		bufferevent_free(b_out);
		bufferevent_free(b_in);
		return;
	}

	bufferevent_setcb(b_in, readcbin, NULL, eventcbin, b_out);
	bufferevent_setcb(b_out, readcbout, NULL, eventcbout, b_in);

	bufferevent_enable(b_in, EV_READ|EV_WRITE);
	bufferevent_enable(b_out, EV_READ|EV_WRITE);
}
Ejemplo n.º 16
0
Archivo: dns.c Proyecto: ens-ds23/fuse8
static char * addrinfo_to_string(struct evutil_addrinfo *ai) {
  char *buf,*out;
  const char *s=0;
  struct sockaddr_in *sin;
  struct sockaddr_in6 *sin6;

  buf = safe_malloc(ADDRMAX);
  if(ai->ai_family == AF_INET) {
    sin = (struct sockaddr_in *)ai->ai_addr;
    s = evutil_inet_ntop(AF_INET,&sin->sin_addr,buf,ADDRMAX);
  } else if (ai->ai_family == AF_INET6) {
    sin6 = (struct sockaddr_in6 *)ai->ai_addr;
    s = evutil_inet_ntop(AF_INET6,&sin6->sin6_addr,buf,ADDRMAX);
  }
  out = strdup(s);
  free(buf);
  return out;
}
Ejemplo n.º 17
0
static void
regress_ipv6_parse(void *ptr)
{
#ifdef AF_INET6
	int i, j;

	for (i = 0; ipv6_entries[i].addr; ++i) {
		char written[128];
		struct ipv6_entry *ent = &ipv6_entries[i];
		struct in6_addr in6;
		int r;
		r = evutil_inet_pton(AF_INET6, ent->addr, &in6);
		if (r == 0) {
			if (ent->status != BAD)
				TT_FAIL(("%s did not parse, but it's a good address!",
					ent->addr));
			continue;
		}
		if (ent->status == BAD) {
			TT_FAIL(("%s parsed, but we expected an error", ent->addr));
			continue;
		}
		for (j = 0; j < 4; ++j) {
			/* Can't use s6_addr32 here; some don't have it. */
			ev_uint32_t u =
			    ((ev_uint32_t)in6.s6_addr[j*4  ] << 24) |
			    ((ev_uint32_t)in6.s6_addr[j*4+1] << 16) |
			    ((ev_uint32_t)in6.s6_addr[j*4+2] << 8) |
			    ((ev_uint32_t)in6.s6_addr[j*4+3]);
			if (u != ent->res[j]) {
				TT_FAIL(("%s did not parse as expected.", ent->addr));
				continue;
			}
		}
		if (ent->status == CANONICAL) {
			const char *w = evutil_inet_ntop(AF_INET6, &in6, written,
											 sizeof(written));
			if (!w) {
				TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
				continue;
			}
			if (strcmp(written, ent->addr)) {
				TT_FAIL(("Tried to write out %s; got %s", ent->addr, written));
				continue;
			}
		}

	}
#else
	TT_BLATHER(("Skipping IPv6 address parsing."));
#endif
}
Ejemplo n.º 18
0
void Spider_Url_Rinse::dns_callback(int errcode, struct evutil_addrinfo *addr, void *ptr)
{
	dns_cb_arg *arg = (dns_cb_arg *)ptr;
	UrlPtr myurl = arg->url_ptr;

	if (errcode)
	{
		LLOG(L_ERROR,"DNS parse error:%s -> %s\n", myurl->domain, evutil_gai_strerror(errcode));
	}
	else
	{
		struct evutil_addrinfo *ai=addr;
		char buf[128];
		const char *s = NULL;
		if (addr->ai_family == AF_INET)
		{
			struct sockaddr_in *sin =(struct sockaddr_in *)ai->ai_addr;
			s = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, 128);	/*从套接口内部数据类型转换为点分十进制 */
		}
		else if (addr->ai_family == AF_INET6)
		{
			struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ai->ai_addr;
			s = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,128);
		}
		if (s)
		{
			myurl->ip=strdup(s);
			arg->pthis->put_url_to_executor(myurl);
			arg->pthis->m_dns_database[std::string(myurl->domain)] = std::string(myurl->ip);
			arg->pthis->record_domain(myurl->domain);
		}
		evutil_freeaddrinfo(addr);
	}

	if (--g_pending_requests == 0)
	{
		event_base_loopexit(arg->pthis->m_evbase, NULL);
	}
}
Ejemplo n.º 19
0
static void showConn(struct IpTunnel_Connection* conn, String* txid, struct Admin* admin)
{
    struct Allocator* alloc;
    BufferAllocator_STACK(alloc, 1024);
    Dict* d = Dict_new(alloc);

    char ip6[40];
    if (!Bits_isZero(conn->connectionIp6, 16)) {
        Assert_always(evutil_inet_ntop(AF_INET6, conn->connectionIp6, ip6, 40));
        Dict_putString(d, String_CONST("ip6Address"), String_CONST(ip6), alloc);
    }

    char ip4[16];
    if (!Bits_isZero(conn->connectionIp4, 4)) {
        Assert_always(evutil_inet_ntop(AF_INET, conn->connectionIp4, ip4, 16));
        Dict_putString(d, String_CONST("ip4Address"), String_CONST(ip4), alloc);
    }

    Dict_putString(d, String_CONST("key"), Key_stringify(conn->header.nodeKey, alloc), alloc);
    Dict_putInt(d, String_CONST("outgoing"), conn->isOutgoing, alloc);

    Admin_sendMessage(d, txid, admin);
}
Ejemplo n.º 20
0
Archivo: util.c Proyecto: Phoul/shim
const char *
format_addr(const struct sockaddr *addr)
{
	const char *r = NULL;
	static char buf[256];
	char tmp[256];

	if (addr->sa_family == AF_INET) {	
		struct sockaddr_in *sin = (struct sockaddr_in *)addr;
		r = evutil_inet_ntop(AF_INET, &sin->sin_addr, tmp,
		            	     sizeof(tmp));
		if (r) {
			if (sin->sin_port)
				evutil_snprintf(buf, sizeof(buf), "%s:%hu",
						tmp, ntohs(sin->sin_port));
			else
				strcpy(buf, tmp);
		}
	} else if (addr->sa_family == AF_INET6) {
		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
		r = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, tmp,
				     sizeof(tmp));
		if (r) {
			if (sin6->sin6_port)
				evutil_snprintf(buf, sizeof(buf), "[%s]:%hu",
						tmp, ntohs(sin6->sin6_port));
			else
				strcpy(buf, tmp);
		}
	}

	if (!r)
		strcpy(buf, "???"); // XXX: Is this really a reasonable thing to return?
	
	return buf;
}
Ejemplo n.º 21
0
static int http_get_address(struct evhttp_bound_socket *handle, char *buffer, int buflen)
{
    /* Extract and display the address we're listening on. */
    struct sockaddr_storage ss;
    evutil_socket_t fd;
    ev_socklen_t socklen = sizeof(ss);
    char addrbuf[128];
    void *inaddr;
    const char *addr;
    int got_port = -1;

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

    fd = evhttp_bound_socket_get_fd(handle);
    if (getsockname(fd, (struct sockaddr *)&ss, &socklen))
    {
        return ERROR_FAIL;
    }

    if (ss.ss_family == AF_INET)
    {
        got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
        inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
    }
    else if (ss.ss_family == AF_INET6)
    {
        got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
        inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
    }
    else
    {
        fprintf(stderr, "Unexpected address family %d\n", ss.ss_family);
        return ERROR_FAIL;
    }

    addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf, sizeof(addrbuf));
    if (addr)
    {
        evutil_snprintf(buffer, buflen, "http://%s:%d", addr,got_port);
    }
    else
    {
        fprintf(stderr, "evutil_inet_ntop failed\n");
        return ERROR_FAIL;
    }

    return S_OK;
}
Ejemplo n.º 22
0
	void Conn::OnConnListenerCb(struct evconnlistener *evListener, evutil_socket_t evSocket, struct sockaddr *pAddrIn, int socklen, void *arg)
	{
		LOG_DEBUG("New connecter !");

		char addr[64];
		memset(addr, 0, socklen);
		struct sockaddr_in* sIn = (struct sockaddr_in*)pAddrIn;
		evutil_inet_ntop(AF_INET, (void*)&sIn->sin_addr, addr, socklen);

		LOG_DEBUG("Peer IP is " << addr);

		Conn *cn = (Conn*)arg;
		cn->connAddr.assign(addr, strlen(addr));
		struct bufferevent* pEvBuf = bufferevent_socket_new(cn->pEvbase, evSocket, BEV_OPT_CLOSE_ON_FREE);
		bufferevent_setcb(pEvBuf, cn->OnReadCbAddr, NULL, cn->OnConnEventCb, (void*)cn);
		bufferevent_enable(pEvBuf, EV_READ);
	}
Ejemplo n.º 23
0
	void Conn::init(const unsigned int conn_type, const char* ip, const unsigned int port)
	{
		this->conn_type = conn_type;

		bzero(&sAddrIn, sizeof(sAddrIn));
		sAddrIn.sin_family = AF_INET;

		if(ip != NULL)
		{
			inet_pton(AF_INET, ip, &sAddrIn.sin_addr);
		}

		sAddrIn.sin_port = htons(port);

		int outlen = sizeof(this->addr);
		memset(this->addr, 0, outlen);
		evutil_inet_ntop(AF_INET, (void*)&sAddrIn.sin_addr, this->addr, outlen);
	}
Ejemplo n.º 24
0
static void
regress_ipv4_parse(void *ptr)
{
	int i;
	for (i = 0; ipv4_entries[i].addr; ++i) {
		char written[128];
		struct ipv4_entry *ent = &ipv4_entries[i];
		struct in_addr in;
		int r;
		r = evutil_inet_pton(AF_INET, ent->addr, &in);
		if (r == 0) {
			if (ent->status != BAD) {
				TT_FAIL(("%s did not parse, but it's a good address!",
					ent->addr));
			}
			continue;
		}
		if (ent->status == BAD) {
			TT_FAIL(("%s parsed, but we expected an error", ent->addr));
			continue;
		}
		if (ntohl(in.s_addr) != ent->res) {
			TT_FAIL(("%s parsed to %lx, but we expected %lx", ent->addr,
				(unsigned long)ntohl(in.s_addr),
				(unsigned long)ent->res));
			continue;
		}
		if (ent->status == CANONICAL) {
			const char *w = evutil_inet_ntop(AF_INET, &in, written,
											 sizeof(written));
			if (!w) {
				TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
				continue;
			}
			if (strcmp(written, ent->addr)) {
				TT_FAIL(("Tried to write out %s; got %s",
					ent->addr, written));
				continue;
			}
		}

	}

}
Ejemplo n.º 25
0
static char*
announce_url_new (const tr_session * session, const tr_announce_request * req)
{
    const char * str;
    const unsigned char * ipv6;
    struct evbuffer * buf = evbuffer_new ();
    char escaped_info_hash[SHA_DIGEST_LENGTH*3 + 1];

    tr_http_escape_sha1 (escaped_info_hash, req->info_hash);

    evbuffer_expand (buf, 1024);

    evbuffer_add_printf (buf, "%s"
                              "%c"
                              "info_hash=%s"
                              "&peer_id=%*.*s"
                              "&port=%d"
                              "&uploaded=%" PRIu64
                              "&downloaded=%" PRIu64
                              "&left=%" PRIu64
                              "&numwant=%d"
                              "&key=%x"
                              "&compact=1"
                              "&supportcrypto=1",
                              req->url,
                              strchr (req->url, '?') ? '&' : '?',
                              escaped_info_hash,
                              PEER_ID_LEN, PEER_ID_LEN, req->peer_id,
                              req->port,
                              req->up,
                              req->down,
                              req->leftUntilComplete,
                              req->numwant,
                              req->key);

    if (session->encryptionMode == TR_ENCRYPTION_REQUIRED)
        evbuffer_add_printf (buf, "&requirecrypto=1");

    if (req->corrupt)
        evbuffer_add_printf (buf, "&corrupt=%" PRIu64, req->corrupt);

    str = get_event_string (req);
    if (str && *str)
        evbuffer_add_printf (buf, "&event=%s", str);

    str = req->tracker_id_str;
    if (str && *str)
        evbuffer_add_printf (buf, "&trackerid=%s", str);

    /* There are two incompatible techniques for announcing an IPv6 address.
       BEP-7 suggests adding an "ipv6=" parameter to the announce URL,
       while OpenTracker requires that peers announce twice, once over IPv4
       and once over IPv6.

       To be safe, we should do both: add the "ipv6=" parameter and
       announce twice. At any rate, we're already computing our IPv6
       address (for the LTEP handshake), so this comes for free. */

    ipv6 = tr_globalIPv6 ();
    if (ipv6) {
        char ipv6_readable[INET6_ADDRSTRLEN];
        evutil_inet_ntop (AF_INET6, ipv6, ipv6_readable, INET6_ADDRSTRLEN);
        evbuffer_add_printf (buf, "&ipv6=");
        tr_http_escape (buf, ipv6_readable, -1, true);
    }

    return evbuffer_free_to_str (buf);
}
Ejemplo n.º 26
0
int
main(int argc, char **argv)
{
	struct event_base *base;
	struct evhttp *http;
	struct evhttp_bound_socket *handle;

	unsigned short port = atoi(argv[1]);
#ifdef WIN32
	WSADATA WSAData;
	WSAStartup(0x101, &WSAData);
#else
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return (1);
#endif
	base = event_base_new();
	if (!base) {
		fprintf(stderr, "Couldn't create an event_base: exiting\n");
		return 1;
	}

	/* Create a new evhttp object to handle requests. */
	http = evhttp_new(base);
	if (!http) {
		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
		return 1;
	}

	evhttp_set_cb(http, "/s2cover", s2cover_request_cb, NULL);
	evhttp_set_cb(http, "/s2info", s2info_request_cb, NULL);
	evhttp_set_cb(http, "/fetch", fetch_request_cb, NULL);

	/* Now we tell the evhttp what port to listen on */
	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
	if (!handle) {
		fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
		    (int)port);
		return 1;
	}

	{
		/* Extract and display the address we're listening on. */
		struct sockaddr_storage ss;
		evutil_socket_t fd;
		ev_socklen_t socklen = sizeof(ss);
		char addrbuf[128];
		void *inaddr;
		const char *addr;
		int got_port = -1;
		fd = evhttp_bound_socket_get_fd(handle);
		memset(&ss, 0, sizeof(ss));
		if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
			perror("getsockname() failed");
			return 1;
		}
		if (ss.ss_family == AF_INET) {
			got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
			inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
		} else if (ss.ss_family == AF_INET6) {
			got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
			inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
		} else {
			fprintf(stderr, "Weird address family %d\n",
			    ss.ss_family);
			return 1;
		}
		addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
		    sizeof(addrbuf));
		if (addr) {
			printf("HI Listening on %s:%d\n", addr, got_port);
			evutil_snprintf(uri_root, sizeof(uri_root),
			    "http://%s:%d",addr,got_port);
		} else {
			fprintf(stderr, "evutil_inet_ntop failed\n");
			return 1;
		}
	}

	event_base_dispatch(base);

	return 0;
}
Ejemplo n.º 27
0
static int
ssh_new_connection(obfsproxyssh_client_session_t *session,
	struct sockaddr_in *addr, const char *args)
{
	obfsproxyssh_t *state = session->client->state;
	char addr_buf[INET_ADDRSTRLEN];
	char *cached_arg;
	uint32_t tmp;
	bstring tmp_addr;
	int rval;

	evutil_inet_ntop(AF_INET, &addr->sin_addr, addr_buf, INET_ADDRSTRLEN);
	tmp_addr = bformat("%s:%d", addr_buf, ntohs(addr->sin_port));

	if (0 == state->unsafe_logging) {
		tmp = ntohl(addr->sin_addr.s_addr);
		tmp &= 0x000000ff;
		session->ssh_addr = bformat("xxx.xxx.xxx.%d:%d", tmp,
			ntohs(addr->sin_port));
	} else {
		session->ssh_addr = bstrcpy(tmp_addr);
	}

	log_f(state, "SOCKS: %s SOCKS 4 CONNECT -> %s",
			bdata(session->socks_addr), bdata(session->ssh_addr));

	cached_arg = client_arg_cache(session->client, tmp_addr, args);
	bdestroy(tmp_addr);

	rval = ssh_parse_args(session, cached_arg);
	if (rval) {
		log_f(state, "SOCKS: Error: %s Invalid arguments in CONNECT",
				bdata(session->socks_addr));
		return -1;
	}

	/* Note: Yes, this needs defered callbacks */
	session->ssh_ev = bufferevent_socket_new(state->base, -1,
			BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
	if (NULL == session->ssh_ev) {
		log_f(state, "SOCKS: Error: %s Failed to allocate ssh event",
				bdata(session->socks_addr));
		return -1;
	}

	bufferevent_setcb(session->ssh_ev, NULL, NULL, ssh_event_cb, session);

	rval = bufferevent_socket_connect(session->ssh_ev,
			(struct sockaddr *) addr, sizeof (struct sockaddr_in));
	if (rval < 0) {
		log_f(state, "SOCKS: Error: %s Failed to connect ssh socket",
				bdata(session->socks_addr));
		return -1;
	}

	session->ssh_session = libssh2_session_init_ex(NULL, NULL, NULL, session);
	if (NULL == session->ssh_session) {
		log_f(state, "SOCKS: Error: %s Failed to initialize libssh2 session",
				bdata(session->socks_addr));
		return -1;
	}

	libssh2_session_callback_set(session->ssh_session,
				LIBSSH2_CALLBACK_RECV, libssh2_recv_cb);
	libssh2_session_callback_set(session->ssh_session,
				LIBSSH2_CALLBACK_SEND, libssh2_send_cb);
	libssh2_session_set_blocking(session->ssh_session, 0);
	rval = ssh_client_profile_set(session);
	if (rval < 0) {
		log_f(state, "SOCKS: Error: Failed to enable fingerprint resistance",
				bdata(session->socks_addr));
		return -1;
	}

	/*
	 * This only works with debug builds of libssh2 and creates an
	 * astronomical amount of log spam.
	 */
#ifdef TRACE_LIBSSH2
	if (1 == state->unsafe_logging) {
		libssh2_trace(session->ssh_session, LIBSSH2_TRACE_SOCKET |
				LIBSSH2_TRACE_TRANS | LIBSSH2_TRACE_KEX |
				LIBSSH2_TRACE_AUTH | LIBSSH2_TRACE_CONN |
				LIBSSH2_TRACE_ERROR);
		libssh2_trace_sethandler(session->ssh_session, state,
				libssh2_trace_cb);
	}
#endif

	return 0;
}
struct request_mngr_s *
create_request_mngr_from_evhtp_request_with_arg(evhtp_request_t *req,
                                                void            *arg,
                                                const char      *context) {
    struct request_mngr_s      *request_mngr;

    if (!req)
        return NULL;

    /* Request administration object */
    request_mngr = calloc(sizeof(struct request_mngr_s), 1);
    if (request_mngr == NULL) {
        syslog(LOG_ERR, "[%s][pid:%lu][threadid:%lu]"
                        "[msg=Error: out of memory]",
                         context,
                         (uint64_t)getpid(),
                         pthread_self()
                        );
        return NULL;
    }
    request_mngr->mf_sock = malloc(sizeof(mf_sock_address_t));
    if (request_mngr->mf_sock == NULL) {
        syslog(LOG_ERR, "[%s][pid:%lu][threadid:%lu]"
                        "[msg=Error: out of memory]",
                         context,
                         (uint64_t)getpid(),
                         pthread_self()
                        );
        return NULL;
    }

    /* Request administration */
    request_mngr->paused             = NO;
    request_mngr->evhtp_req          = req;
    request_mngr->conn               = req ? evhtp_request_get_connection(req) : NULL;
    request_mngr->evhtp_thr          = request_mngr->evhtp_req ?
                                        get_request_thr(request_mngr->evhtp_req) : NULL;
    request_mngr->service            = arg ? (struct tq_service_s *)arg : NULL;
    request_mngr->listener           = request_mngr->service ?
                                        request_mngr->service->parent_listener : NULL;
    request_mngr->app                = request_mngr->listener ? request_mngr->listener->app_thr : NULL;
    request_mngr->pthr               = pthread_self();
    request_mngr->pid                = (uint64_t)getpid();
    request_mngr->accept_type        = mimetype_normalizer_int(request_mngr->evhtp_req, "Accept");
    request_mngr->accept_header      = mimetype_normalizer_str(request_mngr->accept_type);
    request_mngr->content_type       = mimetype_normalizer_int(request_mngr->evhtp_req, "Content-Type");
    request_mngr->contenttype_header = mimetype_normalizer_str(request_mngr->content_type);
    request_mngr->xacml_req          = NULL;
    request_mngr->xacml_res          = NULL;
    request_mngr->mf_sock->sa        = request_mngr->conn->saddr;
    if (request_mngr->mf_sock->sa_stor->ss_family == AF_INET6) {
        request_mngr->sin_port       = request_mngr->mf_sock ?
                                            ntohs(request_mngr->mf_sock->sa_in6->sin6_port) : 0;
    } else {
        request_mngr->sin_port       = request_mngr->mf_sock ?
                                            ntohs(request_mngr->mf_sock->sa_in->sin_port) : 0;
    }

    /* Normalizing flawed input for human readable strings */
    if (request_mngr->accept_header == NULL)      request_mngr->accept_header = "<empty Accept>";
    if (request_mngr->contenttype_header == NULL) request_mngr->contenttype_header = "<empty Content-Type>";

    /* Copy the IP address */
    request_mngr->sin_ip_addr = calloc(GA_HTTP_IP_ADDRESS_LEN, 1);
    if (request_mngr->sin_ip_addr == NULL) {
        syslog(LOG_ERR, "[%s][pid:%lu][threadid:%lu]"
                        "[error=out of memory]",
                         context,
                         request_mngr->pid, request_mngr->pthr);
        goto cleanup;
    }

    /* Extract the source IP */
    if (request_mngr->mf_sock->sa_stor->ss_family == AF_INET6) {
        evutil_inet_ntop(request_mngr->mf_sock->sa_stor->ss_family,
                         &(request_mngr->mf_sock->sa_in6->sin6_addr),
                         request_mngr->sin_ip_addr,
                         GA_HTTP_IP_ADDRESS_LEN);
    } else {
        evutil_inet_ntop(request_mngr->mf_sock->sa_stor->ss_family,
                         &(request_mngr->mf_sock->sa_in->sin_addr),
                         request_mngr->sin_ip_addr,
                         GA_HTTP_IP_ADDRESS_LEN);
    }

    return request_mngr;
cleanup:
    delete_request_mngr(request_mngr);
    return NULL;
}
int
tr_natpmpPulse( struct tr_natpmp * nat, tr_port private_port, bool is_enabled, tr_port * public_port )
{
    int ret;

    if( is_enabled && ( nat->state == TR_NATPMP_DISCOVER ) )
    {
        int val = initnatpmp( &nat->natpmp );
        logVal( "initnatpmp", val );
        val = sendpublicaddressrequest( &nat->natpmp );
        logVal( "sendpublicaddressrequest", val );
        nat->state = val < 0 ? TR_NATPMP_ERR : TR_NATPMP_RECV_PUB;
        nat->has_discovered = true;
        setCommandTime( nat );
    }

    if( ( nat->state == TR_NATPMP_RECV_PUB ) && canSendCommand( nat ) )
    {
        natpmpresp_t response;
        const int val = readnatpmpresponseorretry( &nat->natpmp, &response );
        logVal( "readnatpmpresponseorretry", val );
        if( val >= 0 )
        {
            char str[128];
            evutil_inet_ntop( AF_INET, &response.pnu.publicaddress.addr, str, sizeof( str ) );
            tr_ninf( getKey( ), _( "Found public address \"%s\"" ), str );
            nat->state = TR_NATPMP_IDLE;
        }
        else if( val != NATPMP_TRYAGAIN )
        {
            nat->state = TR_NATPMP_ERR;
        }
    }

    if( ( nat->state == TR_NATPMP_IDLE ) || ( nat->state == TR_NATPMP_ERR ) )
    {
        if( nat->is_mapped && ( !is_enabled || ( nat->private_port != private_port ) ) )
            nat->state = TR_NATPMP_SEND_UNMAP;
    }

    if( ( nat->state == TR_NATPMP_SEND_UNMAP ) && canSendCommand( nat ) )
    {
        const int val = sendnewportmappingrequest( &nat->natpmp, NATPMP_PROTOCOL_TCP,
                                                   nat->private_port,
                                                   nat->public_port,
                                                   0 );
        logVal( "sendnewportmappingrequest", val );
        nat->state = val < 0 ? TR_NATPMP_ERR : TR_NATPMP_RECV_UNMAP;
        setCommandTime( nat );
    }

    if( nat->state == TR_NATPMP_RECV_UNMAP )
    {
        natpmpresp_t resp;
        const int val = readnatpmpresponseorretry( &nat->natpmp, &resp );
        logVal( "readnatpmpresponseorretry", val );
        if( val >= 0 )
        {
            const int private_port = resp.pnu.newportmapping.privateport;

            tr_ninf( getKey( ), _( "no longer forwarding port %d" ), private_port );

            if( nat->private_port == private_port )
            {
                nat->private_port = 0;
                nat->public_port = 0;
                nat->state = TR_NATPMP_IDLE;
                nat->is_mapped = false;
            }
        }
        else if( val != NATPMP_TRYAGAIN )
        {
            nat->state = TR_NATPMP_ERR;
        }
    }

    if( nat->state == TR_NATPMP_IDLE )
    {
        if( is_enabled && !nat->is_mapped && nat->has_discovered )
            nat->state = TR_NATPMP_SEND_MAP;

        else if( nat->is_mapped && tr_time( ) >= nat->renew_time )
            nat->state = TR_NATPMP_SEND_MAP;
    }

    if( ( nat->state == TR_NATPMP_SEND_MAP ) && canSendCommand( nat ) )
    {
        const int val = sendnewportmappingrequest( &nat->natpmp, NATPMP_PROTOCOL_TCP, private_port, private_port, LIFETIME_SECS );
        logVal( "sendnewportmappingrequest", val );
        nat->state = val < 0 ? TR_NATPMP_ERR : TR_NATPMP_RECV_MAP;
        setCommandTime( nat );
    }

    if( nat->state == TR_NATPMP_RECV_MAP )
    {
        natpmpresp_t resp;
        const int    val = readnatpmpresponseorretry( &nat->natpmp, &resp );
        logVal( "readnatpmpresponseorretry", val );
        if( val >= 0 )
        {
            nat->state = TR_NATPMP_IDLE;
            nat->is_mapped = true;
            nat->renew_time = tr_time( ) + ( resp.pnu.newportmapping.lifetime / 2 );
            nat->private_port = resp.pnu.newportmapping.privateport;
            nat->public_port = resp.pnu.newportmapping.mappedpublicport;
            tr_ninf( getKey( ), _( "Port %d forwarded successfully" ), nat->private_port );
        }
        else if( val != NATPMP_TRYAGAIN )
        {
            nat->state = TR_NATPMP_ERR;
        }
    }

    switch( nat->state )
    {
        case TR_NATPMP_IDLE:
            *public_port = nat->public_port;
            return nat->is_mapped ? TR_PORT_MAPPED : TR_PORT_UNMAPPED;
            break;

        case TR_NATPMP_DISCOVER:
            ret = TR_PORT_UNMAPPED; break;

        case TR_NATPMP_RECV_PUB:
        case TR_NATPMP_SEND_MAP:
        case TR_NATPMP_RECV_MAP:
            ret = TR_PORT_MAPPING; break;

        case TR_NATPMP_SEND_UNMAP:
        case TR_NATPMP_RECV_UNMAP:
            ret = TR_PORT_UNMAPPING; break;

        default:
            ret = TR_PORT_ERROR; break;
    }
    return ret;
}
Ejemplo n.º 30
0
void test_protocol()
{
    /* get new string buffer */
    cstring *version_msg_cstr = cstr_new_sz(256);
    cstring *inv_msg_cstr = cstr_new_sz(256);

    struct sockaddr_in test_sa, test_sa_check;
    memset(&test_sa, 0, sizeof(test_sa));
    memset(&test_sa_check, 0, sizeof(test_sa_check));
    test_sa.sin_family = AF_INET;
    struct sockaddr_in6 test_sa6, test_sa6_check;
    test_sa6.sin6_family = AF_INET6;
    test_sa6.sin6_port = htons(1024);
    evutil_inet_pton(AF_INET, "10.0.0.1", &test_sa.sin_addr); // store IP in antelope

    char i6buf[1024];
    memset(&i6buf, 0, 1024);

    evutil_inet_pton(AF_INET6, "::1", &test_sa6.sin6_addr);
    btc_p2p_address ipv6Test;
    btc_p2p_address_init(&ipv6Test);
    btc_addr_to_p2paddr((struct sockaddr *)&test_sa6, &ipv6Test);
    btc_p2paddr_to_addr(&ipv6Test, (struct sockaddr *)&test_sa6_check);
    memset(&i6buf, 0, 1024);
    u_assert_int_eq(test_sa6.sin6_port, test_sa6_check.sin6_port);

    /* copy socket_addr to p2p addr */
    btc_p2p_address fromAddr;
    btc_p2p_address_init(&fromAddr);
    btc_p2p_address toAddr;
    btc_p2p_address_init(&toAddr);
    btc_addr_to_p2paddr((struct sockaddr *)&test_sa, &toAddr);
    btc_p2paddr_to_addr(&toAddr, (struct sockaddr *)&test_sa_check);
    u_assert_int_eq(test_sa.sin_port, test_sa_check.sin_port);
    evutil_inet_ntop(AF_INET, &test_sa_check.sin_addr, i6buf, 1024);
    u_assert_str_eq(i6buf, "10.0.0.1");

    /* create a inv message struct */
    btc_p2p_inv_msg inv_msg, inv_msg_check;
    memset(&inv_msg, 0, sizeof(inv_msg));

    uint256 hash = {0};

    btc_p2p_msg_inv_init(&inv_msg, 1, hash);
    btc_p2p_msg_inv_ser(&inv_msg, inv_msg_cstr);

    struct const_buffer buf_inv = {inv_msg_cstr->str, inv_msg_cstr->len};
    u_assert_int_eq(btc_p2p_msg_inv_deser(&inv_msg_check, &buf_inv), true);
    u_assert_int_eq(inv_msg_check.type, 1);
    u_assert_mem_eq(inv_msg_check.hash, inv_msg.hash, sizeof(inv_msg.hash));
    cstr_free(inv_msg_cstr, true);

    /* create a version message struct */
    btc_p2p_version_msg version_msg;
    memset(&version_msg, 0, sizeof(version_msg));

    /* create a serialized version message */
    btc_p2p_msg_version_init(&version_msg, &fromAddr, &toAddr, "client", false);
    btc_p2p_msg_version_ser(&version_msg, version_msg_cstr);

    /* create p2p message */
    cstring *p2p_msg = btc_p2p_message_new((unsigned const char *)&btc_chainparams_main.netmagic, BTC_MSG_VERSION, version_msg_cstr->str, version_msg_cstr->len);

    struct const_buffer buf = {p2p_msg->str, p2p_msg->len};
    btc_p2p_msg_hdr hdr;
    btc_p2p_deser_msghdr(&hdr, &buf);

    u_assert_mem_eq(hdr.netmagic, &btc_chainparams_main.netmagic, 4);
    u_assert_str_eq(hdr.command, BTC_MSG_VERSION);
    u_assert_int_eq(hdr.data_len, version_msg_cstr->len);
    u_assert_int_eq(buf.len, hdr.data_len);
    u_assert_int_eq(buf.len, hdr.data_len);
    u_assert_mem_eq(buf.p, version_msg_cstr->str, hdr.data_len);

    btc_p2p_version_msg v_msg_check;
    u_assert_int_eq(btc_p2p_msg_version_deser(&v_msg_check, &buf), true);

    u_assert_int_eq(v_msg_check.version, BTC_PROTOCOL_VERSION);
    u_assert_str_eq(v_msg_check.useragent, "client");
    u_assert_int_eq(v_msg_check.start_height, 0);

    cstr_free(p2p_msg, true);
    cstr_free(version_msg_cstr, true);

    /* getheaders */
    uint256 genesis_hash = {0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68, 0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93, 0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1, 0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f};
    vector *blocklocators = vector_new(1, NULL);
    vector_add(blocklocators, genesis_hash);
    cstring *getheader_msg = cstr_new_sz(256);
    btc_p2p_msg_getheaders(blocklocators, NULL, getheader_msg);
    p2p_msg = btc_p2p_message_new((unsigned const char *)&btc_chainparams_main.netmagic, BTC_MSG_GETHEADERS, getheader_msg->str, getheader_msg->len);


    buf.p = p2p_msg->str;
    buf.len = p2p_msg->len;
    btc_p2p_deser_msghdr(&hdr, &buf);
    u_assert_str_eq(hdr.command, BTC_MSG_GETHEADERS);
    u_assert_int_eq(hdr.data_len, getheader_msg->len);


    uint256 hashstop_check;
    vector *blocklocators_check = vector_new(1, free);
    btc_p2p_deser_msg_getheaders(blocklocators_check, hashstop_check, &buf);
    u_assert_mem_eq(NULLHASH, hashstop_check, sizeof(hashstop_check));
    uint8_t *hash_loc_0 = vector_idx(blocklocators_check, 0);
    u_assert_mem_eq(genesis_hash, hash_loc_0, sizeof(genesis_hash));


    /* cleanup */
    cstr_free(getheader_msg, true);
    vector_free(blocklocators, true);
    vector_free(blocklocators_check, true);
    cstr_free(p2p_msg, true);
}