void host_object::test<10>()
	{
		std::string hostStr = "64.233.167.99";		
		LLHost host;
		host.setHostByName(hostStr);	
		ensure("SetHostByName for dotted IP Address failed", host.getAddress() == ip_string_to_u32(hostStr.c_str()));
	}
// static
bool LLFloaterMessageLog::onConfirmCloseCircuit(const LLSD& notification, const LLSD& response )
{
	S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
	LLCircuitData* cdp = gMessageSystem->mCircuitInfo.findCircuit(LLHost(notification["payload"]["circuittoclose"].asString()));
	if(!cdp) return false;
	LLViewerRegion* regionp = LLWorld::getInstance()->getRegion(cdp->getHost());
	switch(option)
	{
	case 0: // yes
		gMessageSystem->newMessageFast(_PREHASH_CloseCircuit);
		gMessageSystem->sendReliable(cdp->getHost());
		break;
	case 2: // cancel
		return false;
		break;
	case 1: // no
	default:
		break;
	}
	if(gMessageSystem->findCircuitCode(cdp->getHost()))
		gMessageSystem->disableCircuit(cdp->getHost());
	else
		gMessageSystem->mCircuitInfo.removeCircuitData(cdp->getHost());
	if(regionp)
	{
		LLHost myhost = regionp->getHost();
		LLSD args;
		args["MESSAGE"] = "That host had a region associated with it.\nDo you want to clean that up?";
		LLSD payload;
		payload["regionhost"] = myhost.getString();
		LLNotificationsUtil::add("GenericAlertYesCancel", args, payload, onConfirmRemoveRegion);
	}
	return false;
}
bool LLViewerParcelMedia::allowedMedia(std::string media_url)
{
	LLStringUtil::trim(media_url);
	std::string domain = extractDomain(media_url);
	LLHost host;
	host.setHostByName(domain);
	std::string ip = host.getIPString();
	if (sAllowedMedia.count(domain) || sAllowedMedia.count(ip))
	{
		return true;
	}
	std::string server;
	for (S32 i = 0; i < (S32)sMediaFilterList.size(); i++)
	{
		server = sMediaFilterList[i]["domain"].asString();
		if (server == domain || server == ip)
		{
			if (sMediaFilterList[i]["action"].asString() == "allow")
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	return false;
}
Example #4
0
BOOL LLPacketRing::sendPacketImpl(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
{
	
	if (!LLProxy::isSOCKSProxyEnabled())
	{
		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort());
	}

	char headered_send_buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE];

	proxywrap_t *socks_header = static_cast<proxywrap_t*>(static_cast<void*>(&headered_send_buffer));
	socks_header->rsv   = 0;
	socks_header->addr  = host.getAddress();
	socks_header->port  = htons(host.getPort());
	socks_header->atype = ADDRESS_IPV4;
	socks_header->frag  = 0;

	memcpy(headered_send_buffer + SOCKS_HEADER_SIZE, send_buffer, buf_size);

	return send_packet(	h_socket,
						headered_send_buffer,
						buf_size + SOCKS_HEADER_SIZE,
						LLProxy::getInstance()->getUDPProxy().getAddress(),
						LLProxy::getInstance()->getUDPProxy().getPort());
}
	void host_object::test<6>()
	{
		U32 ip = 0xc098017d, port = 8080;
		LLHost host;
		host.set(ip,port);
		ensure("IP address is invalid", (ip == host.getAddress()));
		ensure("Port Number is invalid", (port == host.getPort()));
	}
Example #6
0
S32 tcp_open_channel(LLHost host)
{
    // Open a TCP channel
    // Jump through some hoops to ensure that if the request hosts is down
    // or not reachable connect() does not block

    S32 handle;
    handle = socket(AF_INET, SOCK_STREAM, 0);
    if (!handle)
    {
        llwarns << "Error opening TCP control socket, socket() returned " << handle << llendl;
        return -1;
    }

    struct sockaddr_in address;
    address.sin_port        = htons(host.getPort());
    address.sin_family      = AF_INET;
    address.sin_addr.s_addr = host.getAddress();

    // Non blocking
    WSAEVENT hEvent=WSACreateEvent();
    WSAEventSelect(handle, hEvent, FD_CONNECT) ;
    connect(handle, (struct sockaddr*)&address, sizeof(address)) ;
    // Wait fot 5 seconds, if we can't get a TCP channel open in this
    // time frame then there is something badly wrong.
    WaitForSingleObject(hEvent, 1000*5); // 5 seconds time out

    WSANETWORKEVENTS netevents;
    WSAEnumNetworkEvents(handle,hEvent,&netevents);

    // Check the async event status to see if we connected
    if ((netevents.lNetworkEvents & FD_CONNECT) == FD_CONNECT)
    {
        if (netevents.iErrorCode[FD_CONNECT_BIT] != 0)
        {
            llwarns << "Unable to open TCP channel, WSA returned an error code of " << netevents.iErrorCode[FD_CONNECT_BIT] << llendl;
            WSACloseEvent(hEvent);
            return -1;
        }

        // Now we are connected disable non blocking
        // we don't need support an async interface as
        // currently our only consumer (socks5) will make one round
        // of packets then just hold the connection open
        WSAEventSelect(handle, hEvent, NULL) ;
        unsigned long NonBlock = 0;
        ioctlsocket(handle, FIONBIO, &NonBlock);

        return handle;
    }

    llwarns << "Unable to open TCP channel, Timeout is the host up?" << netevents.iErrorCode[FD_CONNECT_BIT] << llendl;
    return -1;
}
Example #7
0
void host_object::test<9>()
{
    std::string hostStr = "google.com";
    LLHost host;
    host.setHostByName(hostStr);

    // reverse DNS will likely result in appending of some
    // sub-domain to the main hostname. so look for
    // the main domain name and not do the exact compare

    std::string hostname = host.getHostName();
    ensure("getHostName failed", hostname.find(hostStr) != std::string::npos);
}
	void host_object::test<8>()
	{
		const std::string str("192.168.1.1");
		U32 port = 8080;
		LLHost host;
		host.set(str,port);

		std::string ip_string = host.getIPString();
		ensure("Function Failed", (ip_string == str));

		std::string ip_string_port = host.getIPandPort();
		ensure("Function Failed", (ip_string_port == "192.168.1.1:8080"));
	}
// static
BOOL LLFloaterMessageLog::onClickCloseCircuit(void* user_data)
{
	LLNetListItem* itemp = (LLNetListItem*)user_data;
	LLCircuitData* cdp = (LLCircuitData*)itemp->mCircuitData;
	if(!cdp) return FALSE;
	LLHost myhost = cdp->getHost();
	LLSD args;
	args["MESSAGE"] = "This will delete local circuit data.\nDo you want to tell the remote host to close the circuit too?";
	LLSD payload;
	payload["circuittoclose"] = myhost.getString(); 
	LLNotificationsUtil::add("GenericAlertYesCancel", args, payload, onConfirmCloseCircuit);
	return TRUE;
}
void SLFloaterMediaFilter::onBlacklistRemove()
{	
	LLScrollListItem* selected = mBlacklistSLC->getFirstSelected();

	if (selected)
	{
		std::string domain = mBlacklistSLC->getSelectedItemLabel();
		size_t pos = domain.find(' ');
		if (pos != std::string::npos)
		{
			domain = domain.substr(0, pos);
		}

		LLViewerParcelMedia::sDeniedMedia.erase(domain);

		for (S32 i = 0; i < (S32)LLViewerParcelMedia::sMediaFilterList.size(); i++)
		{
			if (LLViewerParcelMedia::sMediaFilterList[i]["domain"].asString() == domain)
			{
				LLViewerParcelMedia::sMediaFilterList.erase(i);
				break;
			}
		}

		if (childGetValue("match_ip") && domain.find('/') == std::string::npos)
		{
			LLHost host;
			host.setHostByName(domain);
			std::string ip = host.getIPString();

			if (ip != domain)
			{
				LLViewerParcelMedia::sDeniedMedia.erase(ip);

				for (S32 i = 0; i < (S32)LLViewerParcelMedia::sMediaFilterList.size(); i++)
				{
					if (LLViewerParcelMedia::sMediaFilterList[i]["domain"].asString() == ip)
					{
						LLViewerParcelMedia::sMediaFilterList.erase(i);
						break;
					}
				}
			}
		}

		LLViewerParcelMedia::saveDomainFilterList();
		setDirty();
	}
}	
Example #11
0
/**
 * @brief Initiates a SOCKS 5 proxy session.
 *
 * Performs basic checks on host to verify that it is a valid address. Opens the control channel
 * and then negotiates the proxy connection with the server. Closes any existing SOCKS
 * connection before proceeding. Also disables an HTTP proxy if it is using SOCKS as the proxy.
 *
 *
 * @param host Socks server to connect to.
 * @return SOCKS_OK if successful, otherwise a SOCKS error code defined in llproxy.h.
 */
S32 LLProxy::startSOCKSProxy(LLHost host)
{
	if (host.isOk())
	{
		mTCPProxy = host;
	}
	else
	{
		return SOCKS_INVALID_HOST;
	}

	// Close any running SOCKS connection.
	stopSOCKSProxy();

	mProxyControlChannel = tcp_open_channel(mTCPProxy);
	if (!mProxyControlChannel)
	{
		return SOCKS_HOST_CONNECT_FAILED;
	}

	S32 status = proxyHandshake(mTCPProxy);

	if (status != SOCKS_OK)
	{
		// Shut down the proxy if any of the above steps failed.
		stopSOCKSProxy();
	}
	else
	{
		// Connection was successful.
		sUDPProxyEnabled = true;
	}

	return status;
}
Example #12
0
S32 tcp_open_channel(LLHost host)
{
    S32 handle;
    handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (!handle)
    {
        llwarns << "Error opening TCP control socket, socket() returned " << handle << llendl;
        return -1;
    }

    struct sockaddr_in address;
    address.sin_port        = htons(host.getPort());
    address.sin_family      = AF_INET;
    address.sin_addr.s_addr = host.getAddress();

    // Set the socket to non blocking for the connect()
    int flags = fcntl(handle, F_GETFL, 0);
    fcntl(handle, F_SETFL, flags | O_NONBLOCK);

    S32 error = connect(handle, (sockaddr*)&address, sizeof(address));
    if (error && (errno != EINPROGRESS))
    {
        llwarns << "Unable to open TCP channel, error code: " << errno << llendl;
        return -1;
    }

    struct timeval timeout;
    timeout.tv_sec  = 5; // Maximum time to wait for the connect() to complete
    timeout.tv_usec = 0;
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(handle, &fds);

    // See if we have connectde or time out after 5 seconds
    U32 rc = select(sizeof(fds)*8, NULL, &fds, NULL, &timeout);

    if (rc != 1) // we require exactly one descriptor to be set
    {
        llwarns << "Unable to open TCP channel" << llendl;
        return -1;
    }

    // Return the socket to blocking operations
    fcntl(handle, F_SETFL, flags);

    return handle;
}
Example #13
0
BOOL LLPacketRing::doSendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
{
	
	if (!LLSocks::isEnabled())
	{
		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort());
	}

	proxywrap_t *socks_header = (proxywrap_t *)&mProxyWrappedSendBuffer;
	socks_header->rsv   = 0;
	socks_header->addr  = host.getAddress();
	socks_header->port  = htons(host.getPort());
	socks_header->atype = ADDRESS_IPV4;
	socks_header->frag  = 0;

	memcpy(mProxyWrappedSendBuffer+10, send_buffer, buf_size);

	return send_packet(h_socket,(const char*) mProxyWrappedSendBuffer, buf_size+10, LLSocks::getInstance()->getUDPPproxy().getAddress(), LLSocks::getInstance()->getUDPPproxy().getPort());
}
Example #14
0
	void host_object::test<9>()
	{
		skip("this test is irreparably flaky");
//		skip("setHostByName(\"google.com\"); getHostName() -> (e.g.) \"yx-in-f100.1e100.net\"");
		// nat: is it reasonable to expect LLHost::getHostName() to echo
		// back something resembling the string passed to setHostByName()?
		//
		// If that's not even reasonable, would a round trip in the /other/
		// direction make more sense? (Call getHostName() for something with
		// known IP address; call setHostByName(); verify IP address)
		//
		// Failing that... is there a plausible way to test getHostName() and
		// setHostByName()? Hopefully without putting up a dummy local DNS
		// server?

		// monty: If you don't control the DNS server or the DNS configuration
		// for the test point then, no, none of these will necessarily be
		// reliable and may start to fail at any time. Forward translation
		// is subject to CNAME records and round-robin address assignment.
		// Reverse lookup is 1-to-many and is more and more likely to have
		// nothing to do with the forward translation.
		// 
		// So the test is increasingly meaningless on a real network.

		std::string hostStr = "lindenlab.com";
		LLHost host;
		host.setHostByName(hostStr);

		// reverse DNS will likely result in appending of some
		// sub-domain to the main hostname. so look for
		// the main domain name and not do the exact compare
		
		std::string hostname = host.getHostName();
		try
		{
			ensure("getHostName failed", hostname.find(hostStr) != std::string::npos);
		}
		catch (const std::exception&)
		{
			std::cerr << "set '" << hostStr << "'; reported '" << hostname << "'" << std::endl;
			throw;
		}
	}
bool LLSocket::blockingConnect(const LLHost& host)
{
	if(!mSocket) return false;
	apr_sockaddr_t* sa = NULL;
	std::string ip_address;
	ip_address = host.getIPString();
	if(ll_apr_warn_status(apr_sockaddr_info_get(
		&sa,
		ip_address.c_str(),
		APR_UNSPEC,
		host.getPort(),
		0,
		mPool())))
	{
		return false;
	}
	setBlocking(1000);
	ll_debug_socket("Blocking connect", mSocket);
	if(ll_apr_warn_status(apr_socket_connect(mSocket, sa))) return false;
	setNonBlocking();
	return true;
}
	void host_object::test<9>()
	{
//		skip("setHostByName(\"google.com\"); getHostName() -> (e.g.) \"yx-in-f100.1e100.net\"");
		std::string hostStr = "linux.org";		
		LLHost host;
		host.setHostByName(hostStr);	

		// reverse DNS will likely result in appending of some
		// sub-domain to the main hostname. so look for
		// the main domain name and not do the exact compare
		
		std::string hostname = host.getHostName();
		try
		{
			ensure("getHostName failed", hostname.find(hostStr) != std::string::npos);
		}
		catch (const std::exception&)
		{
			std::cerr << "set '" << hostStr << "'; reported '" << hostname << "'" << std::endl;
			throw;
		}
	}
Example #17
0
/**
 * @brief Enable the HTTP proxy for either SOCKS or HTTP.
 *
 * Check the supplied host to see if it is a valid IP and port.
 *
 * @param httpHost Proxy server to connect to.
 * @param type Is the host a SOCKS or HTTP proxy.
 * @return Return true if applying the setting was successful. No changes are made if false.
 */
bool LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
{
	if (!httpHost.isOk())
	{
		LL_WARNS("Proxy") << "Invalid SOCKS 5 Server" << LL_ENDL;
		return false;
	}

	LLMutexLock lock(&mProxyMutex);

	mHTTPProxy        = httpHost;
	mProxyType        = type;

	mHTTPProxyEnabled = true;

	return true;
}
Example #18
0
	LLViewerRegionImpl(LLViewerRegion * region, LLHost const & host)
		:	mHost(host),
			mCompositionp(NULL),
			mEventPoll(NULL),
		    // I'd prefer to set the LLCapabilityListener name to match the region
		    // name -- it's disappointing that's not available at construction time.
		    // We could instead store an LLCapabilityListener*, making
		    // setRegionNameAndZone() replace the instance. Would that pose
		    // consistency problems? Can we even request a capability before calling
		    // setRegionNameAndZone()?
		    // For testability -- the new Michael Feathers paradigm --
		    // LLCapabilityListener binds all the globals it expects to need at
		    // construction time.
		    mCapabilityListener(host.getString(), gMessageSystem, *region,
		                        gAgent.getID(), gAgent.getSessionID())
	{
	}
void SLFloaterMediaFilter::draw()
{
	if (mIsDirty && mWhitelistSLC && mBlacklistSLC)
	{
		S32 whitescrollpos = mWhitelistSLC->getScrollPos();
		S32 blackscrollpos = mBlacklistSLC->getScrollPos();
		mWhitelistSLC->deleteAllItems();
		mBlacklistSLC->deleteAllItems();
		std::set<std::string> listed;
		LLHost host;
		std::string ip;
		std::string domain;
		std::string action;
		LLSD element;
		element["columns"][0]["font"] = "SANSSERIF";
		element["columns"][0]["font-style"] = "BOLD";
		for (S32 i = 0; i < (S32)LLViewerParcelMedia::sMediaFilterList.size(); i++)
		{
			domain = LLViewerParcelMedia::sMediaFilterList[i]["domain"].asString();
			if (mShowIPs)
			{
				host.setHostByName(domain);
				ip = host.getIPString();
				if (ip != domain && domain.find('/') == std::string::npos)
				{
					domain += " (" + ip + ")";
				}
			}

			action = LLViewerParcelMedia::sMediaFilterList[i]["action"].asString();
			if (!domain.empty() && action == "allow")
			{	
				element["columns"][0]["column"] = "whitelist_col";
				element["columns"][0]["value"] = domain;
				//element["columns"][0]["color"] = LLColor4::green3.getValue();
				mWhitelistSLC->addElement(element, ADD_BOTTOM);
				listed.insert(domain);
			}
			else if (!domain.empty() && action == "deny")
			{
				element["columns"][0]["column"] = "blacklist_col";
				element["columns"][0]["value"] = domain;
				//element["columns"][0]["color"] = LLColor4::red2.getValue();
				mBlacklistSLC->addElement(element, ADD_BOTTOM);
				listed.insert(domain);
			}
			else
			{
				LL_WARNS("MediaFilter") << "Bad media filter list: removing corrupted entry for \"" << domain << "\"" << LL_ENDL;
				LLViewerParcelMedia::sMediaFilterList.erase(i--);
			}
		}
		std::set<std::string>::iterator it;
		element["columns"][0]["font"] = "SANSSERIF";
		element["columns"][0]["font-style"] = "ITALIC";
		//element["columns"][0]["color"] = LLColor4::green3.getValue();
		element["columns"][0]["column"] = "whitelist_col";
		for (it = LLViewerParcelMedia::sAllowedMedia.begin(); it != LLViewerParcelMedia::sAllowedMedia.end(); it++)
		{
			domain = *it;
			if (mShowIPs)
			{
				host.setHostByName(domain);
				ip = host.getIPString();
				if (ip != domain && domain.find('/') == std::string::npos)
				{
					domain += " (" + ip + ")";
				}
			}
			if (listed.count(domain) == 0)
			{
				element["columns"][0]["value"] = domain;
				mWhitelistSLC->addElement(element, ADD_BOTTOM);
			}
		}
		element["columns"][0]["column"] = "blacklist_col";
		for (it = LLViewerParcelMedia::sDeniedMedia.begin(); it != LLViewerParcelMedia::sDeniedMedia.end(); it++)
		{
			domain = *it;
			if (mShowIPs)
			{
				host.setHostByName(domain);
				ip = host.getIPString();
				if (ip != domain && domain.find('/') == std::string::npos)
				{
					domain += " (" + ip + ")";
				}
			}
			if (listed.count(domain) == 0)
			{
				element["columns"][0]["value"] = domain;
				mBlacklistSLC->addElement(element, ADD_BOTTOM);
			}
		}
		mWhitelistSLC->setScrollPos(whitescrollpos);
		mBlacklistSLC->setScrollPos(blackscrollpos);

		if (!gSavedSettings.getBOOL("MediaEnableFilter"))
		{
			childDisable("clear_lists");
			childDisable("show_ips");
			childDisable("blacklist_list");
			childDisable("whitelist_list");
			childDisable("remove_whitelist");
			childDisable("add_whitelist");
			childDisable("remove_blacklist");
			childDisable("add_blacklist");
			childDisable("match_ip");
			childDisable("input_domain");
			childDisable("commit_domain");
			childSetText("add_text", std::string("****** WARNING: media filtering is currently DISABLED ******"));
		}

		mIsDirty = false;
		mShowIPs = false;
	}

	LLFloater::draw();
}
void LLViewerParcelMedia::filterMedia(LLParcel* parcel, U32 type)
{
	std::string media_action;
	std::string media_url;
	std::string domain;
	std::string ip;

	if (parcel != LLViewerParcelMgr::getInstance()->getAgentParcel())
	{
		// The parcel just changed (may occur right out after a TP)
		sIsUserAction = false;
		return;
	}		

	if (type == 0)
	{
		media_url = parcel->getMediaURL();
	}
	else
	{
		media_url = parcel->getMusicURL();
	}
	LLStringUtil::trim(media_url);

	domain = extractDomain(media_url);

	if (sMediaQueries.count(domain) > 0)
	{
		sIsUserAction = false;
		return;
	}

	LLHost host;
	host.setHostByName(domain);
	ip = host.getIPString();

	if (sIsUserAction)
	{
		// This was a user manual request to play this media, so give
		// it another chance...
		sIsUserAction = false;
		bool dirty = false;
		if (sDeniedMedia.count(domain))
		{
			sDeniedMedia.erase(domain);
			dirty = true;
		}
		if (sDeniedMedia.count(ip))
		{
			sDeniedMedia.erase(ip);
			dirty = true;
		}
		if (dirty)
		{
			SLFloaterMediaFilter::setDirty();
		}
	}

	if (media_url.empty())
	{
		media_action = "allow";
	}
	else if (!sMediaFilterListLoaded || sDeniedMedia.count(domain) || sDeniedMedia.count(ip))
	{
		media_action = "ignore";
	}
	else if (sAllowedMedia.count(domain) || sAllowedMedia.count(ip))
	{
		media_action = "allow";
	}
	else
	{
		std::string server;
		for (S32 i = 0; i < (S32)sMediaFilterList.size(); i++)
		{
			server = sMediaFilterList[i]["domain"].asString();
			if (server == domain || server == ip)
			{
				media_action = sMediaFilterList[i]["action"].asString();
				break;
			}
		}
	}

	if (media_action == "allow")
	{
		if (type == 0)
		{
			play(parcel, false);
		}
		else
		{
			playStreamingMusic(parcel, false);
		}
		return;
	}
	if (media_action == "ignore")
	{
		if (type == 1)
		{
			LLViewerParcelMedia::stopStreamingMusic();
		}
		return;
	}

	LLSD args;
	if (ip != domain && domain.find('/') == std::string::npos)
	{
		args["DOMAIN"] = domain + " (" + ip + ")";
	}
	else
	{
		args["DOMAIN"] = domain;
	}

	if (media_action == "deny")
	{
		LLNotificationsUtil::add("MediaBlocked", args);
		if (type == 1)
		{
			LLViewerParcelMedia::stopStreamingMusic();
		}
		// So to avoid other "blocked" messages later in the session
		// for this url should it be requested again by a script.
		// We don't add the IP, on purpose (want to show different
		// blocks for different domains pointing to the same IP).
		sDeniedMedia.insert(domain);
	}
	else
	{
		sMediaQueries.insert(domain);
		args["URL"] = media_url;
		if (type == 0)
		{
			args["TYPE"] = "media";
		}
		else
		{
			args["TYPE"] = "audio";
		}
		LLNotificationsUtil::add("MediaAlert", args, LLSD(), boost::bind(callback_media_alert, _1, _2, parcel, type, domain));
	}
}
	void host_object::test<1>()
	{
		LLHost host;
		ensure("IP address is not NULL", (0 == host.getAddress()) && (0 == host.getPort()) && !host.isOk());
	}
Example #22
0
/**
 * @brief Open the SOCKS 5 TCP control channel.
 *
 * Perform a SOCKS 5 authentication and UDP association with the proxy server.
 *
 * @param proxy The SOCKS 5 server to connect to.
 * @return SOCKS_OK if successful, otherwise a socks error code from llproxy.h.
 */
S32 LLProxy::proxyHandshake(LLHost proxy)
{
	S32 result;

	/* SOCKS 5 Auth request */
	socks_auth_request_t  socks_auth_request;
	socks_auth_response_t socks_auth_response;

	socks_auth_request.version		= SOCKS_VERSION;				// SOCKS version 5
	socks_auth_request.num_methods	= 1;							// Sending 1 method.
	socks_auth_request.methods		= getSelectedAuthMethod();		// Send only the selected method.

	result = tcp_blocking_handshake(mProxyControlChannel,
									static_cast<char*>(static_cast<void*>(&socks_auth_request)),
									sizeof(socks_auth_request),
									static_cast<char*>(static_cast<void*>(&socks_auth_response)),
									sizeof(socks_auth_response));
	if (result != APR_SUCCESS)
	{
		LL_WARNS("Proxy") << "SOCKS authentication request failed, error on TCP control channel : " << result << LL_ENDL;
		stopSOCKSProxy();
		return SOCKS_CONNECT_ERROR;
	}

	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
	{
		LL_WARNS("Proxy") << "SOCKS 5 server refused all our authentication methods." << LL_ENDL;
		stopSOCKSProxy();
		return SOCKS_NOT_ACCEPTABLE;
	}

	/* SOCKS 5 USERNAME/PASSWORD authentication */
	if (socks_auth_response.method == METHOD_PASSWORD)
	{
		// The server has requested a username/password combination
		std::string socks_username(getSocksUser());
		std::string socks_password(getSocksPwd());
		U32 request_size = socks_username.size() + socks_password.size() + 3;
		char * password_auth = new char[request_size];
		password_auth[0] = 0x01;
		password_auth[1] = (char) socks_username.size();
		memcpy(&password_auth[2], socks_username.c_str(), socks_username.size());
		password_auth[socks_username.size() + 2] = (char) socks_password.size();
		memcpy(&password_auth[socks_username.size() + 3], socks_password.c_str(), socks_password.size());

		authmethod_password_reply_t password_reply;

		result = tcp_blocking_handshake(mProxyControlChannel,
										password_auth,
										request_size,
										static_cast<char*>(static_cast<void*>(&password_reply)),
										sizeof(password_reply));
		delete[] password_auth;

		if (result != APR_SUCCESS)
		{
			LL_WARNS("Proxy") << "SOCKS authentication failed, error on TCP control channel : " << result << LL_ENDL;
			stopSOCKSProxy();
			return SOCKS_CONNECT_ERROR;
		}

		if (password_reply.status != AUTH_SUCCESS)
		{
			LL_WARNS("Proxy") << "SOCKS authentication failed" << LL_ENDL;
			stopSOCKSProxy();
			return SOCKS_AUTH_FAIL;
		}
	}

	/* SOCKS5 connect request */

	socks_command_request_t  connect_request;
	socks_command_response_t connect_reply;

	connect_request.version		= SOCKS_VERSION;         // SOCKS V5
	connect_request.command		= COMMAND_UDP_ASSOCIATE; // Associate UDP
	connect_request.reserved	= FIELD_RESERVED;
	connect_request.atype		= ADDRESS_IPV4;
	connect_request.address		= htonl(0); // 0.0.0.0
	connect_request.port		= htons(0); // 0
	// "If the client is not in possession of the information at the time of the UDP ASSOCIATE,
	//  the client MUST use a port number and address of all zeros. RFC 1928"

	result = tcp_blocking_handshake(mProxyControlChannel,
									static_cast<char*>(static_cast<void*>(&connect_request)),
									sizeof(connect_request),
									static_cast<char*>(static_cast<void*>(&connect_reply)),
									sizeof(connect_reply));
	if (result != APR_SUCCESS)
	{
		LL_WARNS("Proxy") << "SOCKS connect request failed, error on TCP control channel : " << result << LL_ENDL;
		stopSOCKSProxy();
		return SOCKS_CONNECT_ERROR;
	}

	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
	{
		LL_WARNS("Proxy") << "Connection to SOCKS 5 server failed, UDP forward request not granted" << LL_ENDL;
		stopSOCKSProxy();
		return SOCKS_UDP_FWD_NOT_GRANTED;
	}

	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
	mUDPProxy.setAddress(proxy.getAddress());
	// The connection was successful. We now have the UDP port to send requests that need forwarding to.
	LL_INFOS("Proxy") << "SOCKS 5 UDP proxy connected on " << mUDPProxy << LL_ENDL;

	return SOCKS_OK;
}
Example #23
0
void LLAssetStorage::getInvItemAsset(const LLHost &object_sim, const LLUUID &agent_id, const LLUUID &session_id,
									 const LLUUID &owner_id, const LLUUID &task_id, const LLUUID &item_id,
									 const LLUUID &asset_id, LLAssetType::EType atype,
									 LLGetAssetCallback callback, void *user_data, BOOL is_priority)
{
	lldebugs << "LLAssetStorage::getInvItemAsset() - " << asset_id << "," << LLAssetType::lookup(atype) << llendl;

	//
	// Probably will get rid of this early out?
	//
	//if (asset_id.isNull())
	//{
	//	// Special case early out for NULL uuid
	//	if (callback)
	//	{
	//		callback(mVFS, asset_id, atype, user_data, LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE);
	//	}
	//	return;
	//}

	bool exists = false; 
	U32 size = 0;

	if(asset_id.notNull())
	{
		exists = mVFS->getExists(asset_id, atype);
		LLVFile file(mVFS, asset_id, atype);
		size = exists ? file.getSize() : 0;
		if(exists && size < 1)
		{
			llwarns << "Asset vfile " << asset_id << ":" << atype << " found with bad size " << file.getSize() << ", removing" << llendl;
			file.remove();
		}

	}

	if (size < 1)
	{
		// See whether we should talk to the object's originating sim,
		// or the upstream provider.
		LLHost source_host;
		if (object_sim.isOk())
		{
			source_host = object_sim;
		}
		else
		{
			source_host = mUpstreamHost;
		}
		if (source_host.isOk())
		{
			// stash the callback info so we can find it after we get the response message
			LLInvItemRequest *req = new LLInvItemRequest(asset_id, atype);
			req->mDownCallback = callback;
			req->mUserData = user_data;
			req->mIsPriority = is_priority;

			// send request message to our upstream data provider
			// Create a new asset transfer.
			LLTransferSourceParamsInvItem spi;
			spi.setAgentSession(agent_id, session_id);
			spi.setInvItem(owner_id, task_id, item_id);
			spi.setAsset(asset_id, atype);

			// Set our destination file, and the completion callback.
			LLTransferTargetParamsVFile tpvf;
			tpvf.setAsset(asset_id, atype);
			tpvf.setCallback(downloadInvItemCompleteCallback, req);

			llinfos << "Starting transfer for inventory asset "
				<< item_id << " owned by " << owner_id << "," << task_id
				<< llendl;
			LLTransferTargetChannel *ttcp = gTransferManager.getTargetChannel(source_host, LLTCT_ASSET);
			ttcp->requestTransfer(spi, tpvf, 100.f + (is_priority ? 1.f : 0.f));
		}
		else
		{
			// uh-oh, we shouldn't have gotten here
			llwarns << "Attempt to move asset data request upstream w/o valid upstream provider" << llendl;
			if (callback)
			{
				callback(mVFS, asset_id, atype, user_data, LL_ERR_CIRCUIT_GONE, LL_EXSTAT_NO_UPSTREAM);
			}
		}
	}
	else
	{
		// we've already got the file
		// theoretically, partial files w/o a pending request shouldn't happen
		// unless there's a weird error
		if (callback)
		{
			callback(mVFS, asset_id, atype, user_data, LL_ERR_NOERR, LL_EXSTAT_VFS_CACHED);
		}
	}
}
void LLAssetStorage::getEstateAsset(const LLHost &object_sim, const LLUUID &agent_id, const LLUUID &session_id,
									const LLUUID &asset_id, LLAssetType::EType atype, EstateAssetType etype,
									 LLGetAssetCallback callback, void *user_data, BOOL is_priority)
{
	LL_DEBUGS() << "LLAssetStorage::getEstateAsset() - " << asset_id << "," << LLAssetType::lookup(atype) << ", estatetype " << etype << LL_ENDL;

	//
	// Probably will get rid of this early out?
	//
	if (asset_id.isNull())
	{
		// Special case early out for NULL uuid
		if (callback)
		{
			callback(mVFS, asset_id, atype, user_data, LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE, LL_EXSTAT_NULL_UUID);
		}
		return;
	}

	// Try static VFS first.
	if (findInStaticVFSAndInvokeCallback(asset_id,atype,callback,user_data))
	{
		return;
	}
	
	BOOL exists = mVFS->getExists(asset_id, atype);
	LLVFile file(mVFS, asset_id, atype);
	U32 size = exists ? file.getSize() : 0;

	if (size > 0)
	{
		// we've already got the file
		// theoretically, partial files w/o a pending request shouldn't happen
		// unless there's a weird error
		if (callback)
		{
			callback(mVFS, asset_id, atype, user_data, LL_ERR_NOERR, LL_EXSTAT_VFS_CACHED);
		}
	}
	else
	{
		if (exists)
		{
			LL_WARNS() << "Asset vfile " << asset_id << ":" << atype << " found with bad size " << file.getSize() << ", removing" << LL_ENDL;
			file.remove();
		}

		// See whether we should talk to the object's originating sim, or the upstream provider.
		LLHost source_host;
		if (object_sim.isOk())
		{
			source_host = object_sim;
		}
		else
		{
			source_host = mUpstreamHost;
		}
		if (source_host.isOk())
		{
			// stash the callback info so we can find it after we get the response message
			LLEstateAssetRequest *req = new LLEstateAssetRequest(asset_id, atype, etype);
			req->mDownCallback = callback;
			req->mUserData = user_data;
			req->mIsPriority = is_priority;

			// send request message to our upstream data provider
			// Create a new asset transfer.
			LLTransferSourceParamsEstate spe;
			spe.setAgentSession(agent_id, session_id);
			spe.setEstateAssetType(etype);

			// Set our destination file, and the completion callback.
			LLTransferTargetParamsVFile tpvf;
			tpvf.setAsset(asset_id, atype);
			tpvf.setCallback(downloadEstateAssetCompleteCallback, req);

			LL_DEBUGS("AssetStorage") << "Starting transfer for " << asset_id << LL_ENDL;
			LLTransferTargetChannel *ttcp = gTransferManager.getTargetChannel(source_host, LLTCT_ASSET);
			ttcp->requestTransfer(spe, tpvf, 100.f + (is_priority ? 1.f : 0.f));
		}
		else
		{
			// uh-oh, we shouldn't have gotten here
			LL_WARNS() << "Attempt to move asset data request upstream w/o valid upstream provider" << LL_ENDL;
			if (callback)
			{
				callback(mVFS, asset_id, atype, user_data, LL_ERR_CIRCUIT_GONE, LL_EXSTAT_NO_UPSTREAM);
			}
		}
	}
}
Example #25
0
BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LLHost host)
{
	BOOL status = TRUE;
	if (!mUseOutThrottle)
	{
		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort() );
	}
	else
	{
		mActualBitsOut += buf_size * 8;
		LLPacketBuffer *packetp = NULL;
		// See if we've got enough throttle to send a packet.
		while (!mOutThrottle.checkOverflow(0.f))
		{
			// While we have enough bandwidth, send a packet from the queue or the current packet

			S32 packet_size = 0;
			if (!mSendQueue.empty())
			{
				// Send a packet off of the queue
				LLPacketBuffer *packetp = mSendQueue.front();
				mSendQueue.pop();

				mOutBufferLength -= packetp->getSize();
				packet_size = packetp->getSize();

				status = send_packet(h_socket, packetp->getData(), packet_size, packetp->getHost().getAddress(), packetp->getHost().getPort());
				
				delete packetp;
				// Update the throttle
				mOutThrottle.throttleOverflow(packet_size * 8.f);
			}
			else
			{
				// If the queue's empty, we can just send this packet right away.
				status = send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort() );
				packet_size = buf_size;

				// Update the throttle
				mOutThrottle.throttleOverflow(packet_size * 8.f);

				// This was the packet we're sending now, there are no other packets
				// that we need to send
				return status;
			}

		}

		// We haven't sent the incoming packet, add it to the queue
		if (mOutBufferLength + buf_size > mMaxBufferLength)
		{
			// Nuke this packet, we overflowed the buffer.
			// Toss it.
			llwarns << "Throwing away outbound packet, overflowing buffer" << llendl;
		}
		else
		{
			static LLTimer queue_timer;
			if ((mOutBufferLength > 4192) && queue_timer.getElapsedTimeF32() > 1.f)
			{
				// Add it to the queue
				llinfos << "Outbound packet queue " << mOutBufferLength << " bytes" << llendl;
				queue_timer.reset();
			}
			packetp = new LLPacketBuffer(host, send_buffer, buf_size);

			mOutBufferLength += packetp->getSize();
			mSendQueue.push(packetp);
		}
	}

	return status;
}
void SLFloaterMediaFilter::onCommitDomain()
{
	std::string domain = childGetText("input_domain");
	domain = LLViewerParcelMedia::extractDomain(domain);
	LLHost host;
	host.setHostByName(domain);
	std::string ip = host.getIPString();
	bool match_ip = (childGetValue("match_ip") && ip != domain && domain.find('/') == std::string::npos);

	if (!domain.empty())
	{
		LLViewerParcelMedia::sDeniedMedia.erase(domain);
		LLViewerParcelMedia::sAllowedMedia.erase(domain);
		for (S32 i = 0; i < (S32)LLViewerParcelMedia::sMediaFilterList.size(); i++)
		{
			if (LLViewerParcelMedia::sMediaFilterList[i]["domain"].asString() == domain)
			{
				LLViewerParcelMedia::sMediaFilterList.erase(i);
			}
		}
		if (match_ip)
		{
			LLViewerParcelMedia::sDeniedMedia.erase(ip);
			LLViewerParcelMedia::sAllowedMedia.erase(ip);
			for (S32 i = 0; i < (S32)LLViewerParcelMedia::sMediaFilterList.size(); i++)
			{
				if (LLViewerParcelMedia::sMediaFilterList[i]["domain"].asString() == ip)
				{
					LLViewerParcelMedia::sMediaFilterList.erase(i);
				}
			}
		}
		LLSD newmedia;
		newmedia["domain"] = domain;
		if (mIsWhitelist)
		{
			newmedia["action"] = "allow";
		}
		else
		{
			newmedia["action"] = "deny";
		}
		LLViewerParcelMedia::sMediaFilterList.append(newmedia);
		if (match_ip)
		{
			newmedia["domain"] = ip;
			LLViewerParcelMedia::sMediaFilterList.append(newmedia);
		}
		LLViewerParcelMedia::saveDomainFilterList();
	}

	childEnable("clear_lists");
	childEnable("show_ips");
	childEnable("blacklist_list");
	childEnable("whitelist_list");
	childEnable("remove_whitelist");
	childEnable("add_whitelist");
	childEnable("remove_blacklist");
	childEnable("add_blacklist");
	childDisable("input_domain");
	childDisable("commit_domain");
	childSetText("add_text", std::string("New domain:"));
	childSetText("input_domain", std::string(""));
	setDirty();
}
void callback_media_alert(const LLSD &notification, const LLSD &response, LLParcel* parcel, U32 type, std::string domain)
{
	S32 option = LLNotification::getSelectedOption(notification, response);

	LLHost host;
	host.setHostByName(domain);
	std::string ip = host.getIPString();

	LLSD args;
	if (ip != domain && domain.find('/') == std::string::npos)
	{
		args["DOMAIN"] = domain + " (" + ip + ")";
	}
	else
	{
		args["DOMAIN"] = domain;
	}

	if (option == 0 || option == 3) // Allow or Whitelist
	{
		LLViewerParcelMedia::sAllowedMedia.insert(domain);
		if (option == 3) // Whitelist
		{
			LLSD newmedia;
			newmedia["domain"] = domain;
			newmedia["action"] = "allow";
			LLViewerParcelMedia::sMediaFilterList.append(newmedia);
			if (ip != domain && domain.find('/') == std::string::npos)
			{
				newmedia["domain"] = ip;
				LLViewerParcelMedia::sMediaFilterList.append(newmedia);
			}
			LLViewerParcelMedia::saveDomainFilterList();
			args["LISTED"] = "whitelisted";
			LLNotificationsUtil::add("MediaListed", args);
		}
		if (type == 0)
		{
			LLViewerParcelMedia::play(parcel, false);
		}
		else
		{
			LLViewerParcelMedia::playStreamingMusic(parcel, false);
		}
	}
	else if (option == 1 || option == 2) // Deny or Blacklist
	{
		LLViewerParcelMedia::sDeniedMedia.insert(domain);
		if (ip != domain && domain.find('/') == std::string::npos)
		{
			LLViewerParcelMedia::sDeniedMedia.insert(ip);
		}
		if (type == 1)
		{
			LLViewerParcelMedia::stopStreamingMusic();
		}
		if (option == 1) // Deny
		{
			LLNotificationsUtil::add("MediaBlocked", args);
		}
		else // Blacklist
		{
			LLSD newmedia;
			newmedia["domain"] = domain;
			newmedia["action"] = "deny";
			LLViewerParcelMedia::sMediaFilterList.append(newmedia);
			if (ip != domain && domain.find('/') == std::string::npos)
			{
				newmedia["domain"] = ip;
				LLViewerParcelMedia::sMediaFilterList.append(newmedia);
			}
			LLViewerParcelMedia::saveDomainFilterList();
			args["LISTED"] = "blacklisted";
			LLNotificationsUtil::add("MediaListed", args);
		}
	}

	LLViewerParcelMedia::sMediaQueries.erase(domain);
	SLFloaterMediaFilter::setDirty();
}
	void host_object::test<7>()
	{
		const char* str = "192.168.1.1";
		U32 port = 8080, ip;
		LLHost host;
		host.set(str,port);
		ip = ip_string_to_u32(str);
		ensure("IP address is invalid", (ip == host.getAddress()));
		ensure("Port Number is invalid", (port == host.getPort()));
		
		str = "64.233.187.99";
		ip = ip_string_to_u32(str);
		host.setAddress(str);
		ensure("IP address is invalid", (ip == host.getAddress()));

		ip = 0xc098017b;
		host.setAddress(ip);
		ensure("IP address is invalid", (ip == host.getAddress()));
		// should still use the old port
		ensure("Port Number is invalid", (port == host.getPort()));

		port = 8084;
		host.setPort(port);
		ensure("Port Number is invalid", (port == host.getPort()));
		// should still use the old address
		ensure("IP address is invalid", (ip == host.getAddress()));
	}
Example #29
0
LLViewerRegion::LLViewerRegion(const U64 &handle,
							   const LLHost &host,
							   const U32 grids_per_region_edge, 
							   const U32 grids_per_patch_edge, 
							   const F32 region_width_meters)
:	mCenterGlobal(),
	mHandle(handle),
	mHost( host ),
	mTimeDilation(1.0f),
	mName(""),
	mZoning(""),
	mOwnerID(),
	mIsEstateManager(FALSE),
	mCompositionp(NULL),
	mRegionFlags( REGION_FLAGS_DEFAULT ),
	mSimAccess( SIM_ACCESS_MIN ),
	mBillableFactor(1.0),
	mMaxTasks(DEFAULT_MAX_REGION_WIDE_PRIM_COUNT),
	mClassID(0),
	mCPURatio(0),
	mColoName("unknown"),
	mProductSKU("unknown"),
	mProductName("unknown"),
	mHttpUrl(""),
	mCacheLoaded(FALSE),
	mCacheDirty(FALSE),
	mCacheID(),
	mEventPoll(NULL),
	mReleaseNotesRequested(FALSE),
    // I'd prefer to set the LLCapabilityListener name to match the region
    // name -- it's disappointing that's not available at construction time.
    // We could instead store an LLCapabilityListener*, making
    // setRegionNameAndZone() replace the instance. Would that pose
    // consistency problems? Can we even request a capability before calling
    // setRegionNameAndZone()?
    // For testability -- the new Michael Feathers paradigm --
    // LLCapabilityListener binds all the globals it expects to need at
    // construction time.
    mCapabilityListener(host.getString(), gMessageSystem, *this,
                        gAgent.getID(), gAgent.getSessionID())
{
	mWidth = region_width_meters;
	mOriginGlobal = from_region_handle(handle); 
	updateRenderMatrix();

	mLandp = new LLSurface('l', NULL);
	if (!gNoRender)
	{
		// Create the composition layer for the surface
		mCompositionp = new LLVLComposition(mLandp, grids_per_region_edge, region_width_meters/grids_per_region_edge);
		mCompositionp->setSurface(mLandp);

		// Create the surfaces
		mLandp->setRegion(this);
		mLandp->create(grids_per_region_edge,
						grids_per_patch_edge,
						mOriginGlobal,
						mWidth);
	}

	if (!gNoRender)
	{
		mParcelOverlay = new LLViewerParcelOverlay(this, region_width_meters);
	}
	else
	{
		mParcelOverlay = NULL;
	}

	setOriginGlobal(from_region_handle(handle));
	calculateCenterGlobal();

	// Create the object lists
	initStats();

	//create object partitions
	//MUST MATCH declaration of eObjectPartitions
	mObjectPartition.push_back(new LLHUDPartition());		//PARTITION_HUD
	mObjectPartition.push_back(new LLTerrainPartition());	//PARTITION_TERRAIN
	mObjectPartition.push_back(new LLWaterPartition());		//PARTITION_WATER
	mObjectPartition.push_back(new LLTreePartition());		//PARTITION_TREE
	mObjectPartition.push_back(new LLParticlePartition());	//PARTITION_PARTICLE
	mObjectPartition.push_back(new LLCloudPartition());		//PARTITION_CLOUD
	mObjectPartition.push_back(new LLGrassPartition());		//PARTITION_GRASS
	mObjectPartition.push_back(new LLVolumePartition());	//PARTITION_VOLUME
	mObjectPartition.push_back(new LLBridgePartition());	//PARTITION_BRIDGE
	mObjectPartition.push_back(new LLHUDParticlePartition());//PARTITION_HUD_PARTICLE
	mObjectPartition.push_back(NULL);						//PARTITION_NONE
}