From 74d9bf0d5525426feae4ea21e2a81034ddcf4d7f Mon Sep 17 00:00:00 2001
From: Robin Cornelius <robin.cornelius@gmail.com>
Date: Mon, 28 Mar 2011 11:20:06 +0100
Subject: VWR-20801 Implement SOCKS 5 Proxy for the viewer

---
 indra/llmessage/CMakeLists.txt                     |   2 +
 indra/llmessage/llcurl.cpp                         |  44 ++++
 indra/llmessage/llpacketring.cpp                   |  60 ++++-
 indra/llmessage/llpacketring.h                     |   3 +
 indra/llmessage/llsocks5.cpp                       | 224 +++++++++++++++++
 indra/llmessage/llsocks5.h                         | 243 ++++++++++++++++++
 indra/llmessage/net.cpp                            | 156 ++++++++++++
 indra/llmessage/net.h                              |   5 +
 indra/newview/app_settings/settings.xml            |  77 ++++++
 indra/newview/llfloaterpreference.cpp              | 171 +++++++++++++
 indra/newview/llfloaterpreference.h                |  30 +++
 indra/newview/llstartup.cpp                        | 123 ++++++++-
 indra/newview/llstartup.h                          |   2 +
 indra/newview/llviewerfloaterreg.cpp               |   1 +
 indra/newview/llxmlrpctransaction.cpp              |  21 +-
 .../default/xui/en/floater_preferences_proxy.xml   | 274 +++++++++++++++++++++
 .../newview/skins/default/xui/en/notifications.xml |  70 ++++++
 .../default/xui/en/panel_preferences_setup.xml     |  85 +++----
 18 files changed, 1525 insertions(+), 66 deletions(-)
 create mode 100644 indra/llmessage/llsocks5.cpp
 create mode 100644 indra/llmessage/llsocks5.h
 create mode 100644 indra/newview/skins/default/xui/en/floater_preferences_proxy.xml

diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt
index 1cad0f6d22..8c68d38926 100644
--- a/indra/llmessage/CMakeLists.txt
+++ b/indra/llmessage/CMakeLists.txt
@@ -74,6 +74,7 @@ set(llmessage_SOURCE_FILES
     llsdrpcserver.cpp
     llservicebuilder.cpp
     llservice.cpp
+    llsocks5.cpp
     llstoredmessage.cpp
     lltemplatemessagebuilder.cpp
     lltemplatemessagedispatcher.cpp
@@ -172,6 +173,7 @@ set(llmessage_HEADER_FILES
     llsdrpcserver.h
     llservice.h
     llservicebuilder.h
+    llsocks5.h
     llstoredmessage.h
     lltaskname.h
     llteleportflags.h
diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index a485fa0160..020c0d6a4a 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -50,6 +50,8 @@
 #include "llsdserialize.h"
 #include "llthread.h"
 
+#include "llsocks5.h"
+
 //////////////////////////////////////////////////////////////////////////////
 /*
 	The trick to getting curl to do keep-alives is to reuse the
@@ -273,6 +275,28 @@ LLCurl::Easy* LLCurl::Easy::getEasy()
 	// set no DMS caching as default for all easy handles. This prevents them adopting a
 	// multi handles cache if they are added to one.
 	curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
+
+	//Set the CURL options for either Socks or HTTP proxy
+	if (LLSocks::getInstance()->isHttpProxyEnabled())
+	{
+		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
+		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXY,address.c_str());
+		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYPORT,port);
+		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		{
+			curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
+			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			{
+				curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd().c_str());
+			}
+		}
+		else
+		{
+			curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+		}
+	}
+
 	++gCurlEasyCount;
 	return easy;
 }
@@ -446,6 +470,26 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 //	setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
+	if (LLSocks::getInstance()->isHttpProxyEnabled())
+	{
+		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
+		setoptString(CURLOPT_PROXY, address.c_str());
+		setopt(CURLOPT_PROXYPORT, port);
+		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		{
+			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
+			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			{
+				setoptString(CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd());
+			}
+		}
+		else
+		{
+			setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+		}
+	}
+
 	mOutput.reset(new LLBufferArray);
 	setopt(CURLOPT_WRITEFUNCTION, (void*)&curlWriteCallback);
 	setopt(CURLOPT_WRITEDATA, (void*)this);
diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index 8999dec64a..0c8c5f763c 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -35,6 +35,17 @@
 #include "llrand.h"
 #include "u64.h"
 
+#include "llsocks5.h"
+#include "message.h"
+
+#if LL_WINDOWS
+	#include <winsock2.h>
+#else
+	#include <sys/socket.h>
+	#include <netinet/in.h>
+#endif
+
+
 ///////////////////////////////////////////////////////////
 LLPacketRing::LLPacketRing () :
 	mUseInThrottle(FALSE),
@@ -216,8 +227,31 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 	else
 	{
 		// no delay, pull straight from net
+		if (LLSocks::isEnabled())
+		{
+			U8 buffer[MAX_BUFFER_SIZE];
+			packet_size = receive_packet(socket, (char*)buffer);
+			
+			if (packet_size > 10)
+			{
+				memcpy(datap,buffer+10,packet_size-10);
+			}
+			else
+			{
+				packet_size=0;
+			}
+
+			proxywrap_t * header;
+			header = (proxywrap_t *)buffer;
+			mLastSender.setAddress(header->addr);
+			mLastSender.setPort(ntohs(header->port));
+		}
+		else
+		{
 		packet_size = receive_packet(socket, datap);		
 		mLastSender = ::get_sender();
+		}
+
 		mLastReceivingIF = ::get_receiving_interface();
 
 		if (packet_size)  // did we actually get a packet?
@@ -243,7 +277,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 	BOOL status = TRUE;
 	if (!mUseOutThrottle)
 	{
-		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort() );
+		return doSendPacket(h_socket, send_buffer, buf_size, host );
 	}
 	else
 	{
@@ -264,7 +298,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 				mOutBufferLength -= packetp->getSize();
 				packet_size = packetp->getSize();
 
-				status = send_packet(h_socket, packetp->getData(), packet_size, packetp->getHost().getAddress(), packetp->getHost().getPort());
+				status = doSendPacket(h_socket, packetp->getData(), packet_size, packetp->getHost());
 				
 				delete packetp;
 				// Update the throttle
@@ -273,7 +307,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 			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() );
+				status =  doSendPacket(h_socket, send_buffer, buf_size, host );
 				packet_size = buf_size;
 
 				// Update the throttle
@@ -311,3 +345,23 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 
 	return status;
 }
+
+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()->getUDPProxy().getAddress(), LLSocks::getInstance()->getUDPProxy().getPort());
+}
diff --git a/indra/llmessage/llpacketring.h b/indra/llmessage/llpacketring.h
index e6409d2048..2fe2f8e1e9 100644
--- a/indra/llmessage/llpacketring.h
+++ b/indra/llmessage/llpacketring.h
@@ -82,6 +82,9 @@ protected:
 
 	LLHost mLastSender;
 	LLHost mLastReceivingIF;
+
+	BOOL doSendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host);
+	U8 mProxyWrappedSendBuffer[NET_BUFFER_SIZE];
 };
 
 
diff --git a/indra/llmessage/llsocks5.cpp b/indra/llmessage/llsocks5.cpp
new file mode 100644
index 0000000000..1f458a007c
--- /dev/null
+++ b/indra/llmessage/llsocks5.cpp
@@ -0,0 +1,224 @@
+/** 
+ * @file llsocks5.cpp
+ * @brief Socks 5 implementation
+ *
+ * $LicenseInfo:firstyear=2000&license=viewergpl$
+ * 
+ * Copyright (c) 2000-2009, Linden Research, Inc.
+ * 
+ * Second Life Viewer Source Code
+ * The source code in this file ("Source Code") is provided by Linden Lab
+ * to you under the terms of the GNU General Public License, version 2.0
+ * ("GPL"), unless you have obtained a separate licensing agreement
+ * ("Other License"), formally executed by you and Linden Lab.  Terms of
+ * the GPL can be found in doc/GPL-license.txt in this distribution, or
+ * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
+ * 
+ * There are special exceptions to the terms and conditions of the GPL as
+ * it is applied to this Source Code. View the full text of the exception
+ * in the file doc/FLOSS-exception.txt in this software distribution, or
+ * online at
+ * http://secondlifegrid.net/programs/open_source/licensing/flossexception
+ * 
+ * By copying, modifying or distributing this software, you acknowledge
+ * that you have read and understood your obligations described above,
+ * and agree to abide by those obligations.
+ * 
+ * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
+ * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
+ * COMPLETENESS OR PERFORMANCE.
+ * $/LicenseInfo$
+ */
+
+#include <string>
+
+#include "linden_common.h"
+#include "net.h"
+#include "llhost.h"
+#include "message.h"
+#include "llsocks5.h"
+
+// Static class variable instances
+
+// We want this to be static to avoid excessive indirection on every
+// incomming packet just to do a simple bool test. The getter for this
+// member is also static
+bool LLSocks::sUdpProxyEnabled;
+bool LLSocks::sHttpProxyEnabled;
+
+LLSocks::LLSocks()
+{
+    sUdpProxyEnabled  = false;
+    sHttpProxyEnabled = false;
+    hProxyControlChannel = 0;
+    mProxyType = LLPROXY_SOCKS;
+}
+
+// Perform a Socks5 authentication and UDP assioacation to the proxy
+// specified by proxy, and assiocate UDP port message_port
+int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
+{
+    int 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     = mAuthMethodSelected; // send only the selected metho
+
+    result = tcp_handshake(hProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request_t), (char*)&socks_auth_response, sizeof(socks_auth_response_t));
+    if (result != 0)
+    {
+        llwarns << "Socks authentication request failed, error on TCP control channel : " << result << llendl;
+        stopProxy();
+        return SOCKS_CONNECT_ERROR;
+    }
+    
+    if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
+    {
+        llwarns << "Socks5 server refused all our authentication methods" << llendl;
+        stopProxy();
+        return SOCKS_NOT_ACCEPTABLE;
+    }
+
+    // SOCKS5 USERNAME/PASSWORD authentication
+    if (socks_auth_response.method == METHOD_PASSWORD)
+    {
+        // The server has requested a username/password combination
+        U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
+        char * password_auth = (char *)malloc(request_size);
+        password_auth[0] = 0x01;
+        password_auth[1] = mSocksUsername.size();
+        memcpy(&password_auth[2],mSocksUsername.c_str(), mSocksUsername.size());
+        password_auth[mSocksUsername.size()+2] = mSocksPassword.size();
+        memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
+
+        authmethod_password_reply_t password_reply;
+
+        result = tcp_handshake(hProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
+        free (password_auth);
+
+        if (result != 0)
+        {
+        llwarns << "Socks authentication failed, error on TCP control channel : " << result << llendl;
+            stopProxy();
+            return SOCKS_CONNECT_ERROR;
+        }
+
+        if (password_reply.status != AUTH_SUCCESS)
+        {
+            llwarns << "Socks authentication failed" << llendl;
+            stopProxy();
+            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.flag    = FIELD_RESERVED;
+    connect_request.atype   = ADDRESS_IPV4;
+    connect_request.address = 0; // 0.0.0.0 We are not fussy about address
+                                 // UDP is promiscious receive for our protocol
+    connect_request.port    = 0; // Port must be 0 if you ever want to connect via NAT and your router does port rewrite for you
+
+    result = tcp_handshake(hProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
+    if (result != 0)
+    {
+        llwarns << "Socks connect request failed, error on TCP control channel : " << result << llendl;
+        stopProxy();
+        return SOCKS_CONNECT_ERROR;
+    }
+
+    if (connect_reply.reply != REPLY_REQUEST_GRANTED)
+    {
+        //Something went wrong
+        llwarns << "Connection to SOCKS5 server failed, UDP forward request not granted" << llendl;
+        stopProxy();
+        return SOCKS_UDP_FWD_NOT_GRANTED;
+    }
+
+    mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
+    mUDPProxy.setAddress(proxy.getAddress());
+    // All good now we have been given the UDP port to send requests that need forwarding.
+    llinfos << "Socks 5 UDP proxy connected on " << mUDPProxy << llendl;
+    return SOCKS_OK;
+}
+
+int LLSocks::startProxy(LLHost proxy, U32 message_port)
+{
+    int status;
+
+    mTCPProxy   = proxy;
+
+    if (hProxyControlChannel)
+    {
+        tcp_close_channel(hProxyControlChannel);
+        hProxyControlChannel=0;
+    }
+
+    hProxyControlChannel = tcp_open_channel(proxy);	
+    if (hProxyControlChannel == -1)
+    {
+        return SOCKS_HOST_CONNECT_FAILED;
+    }
+
+    status = proxyHandshake(proxy, message_port);	
+    if (status == SOCKS_OK)
+    {
+        sUdpProxyEnabled=true;
+    }
+    return status;
+}
+
+int LLSocks::startProxy(std::string host, U32 port)
+{
+        mTCPProxy.setHostByName(host);
+        mTCPProxy.setPort(port);
+        return startProxy(mTCPProxy, (U32)gMessageSystem->mPort);
+}
+
+void LLSocks::stopProxy()
+{
+    sUdpProxyEnabled = false;
+
+    // If the Socks proxy is requested to stop and we are using that for http as well
+    // then we must shut down any http proxy operations. But it is allowable if web 
+    // proxy is being used to continue proxying http.
+
+    if(LLPROXY_SOCKS == mProxyType)
+    {
+        sHttpProxyEnabled = false;
+    }
+
+    if (hProxyControlChannel)
+    {
+        tcp_close_channel(hProxyControlChannel);
+        hProxyControlChannel=0;
+    }
+}
+
+void LLSocks::setAuthNone()
+{
+    mAuthMethodSelected = METHOD_NOAUTH;
+}
+
+void LLSocks::setAuthPassword(std::string username, std::string password)
+{
+    mAuthMethodSelected = METHOD_PASSWORD;
+    mSocksUsername      = username;
+    mSocksPassword      = password;
+}
+
+void LLSocks::EnableHttpProxy(LLHost httpHost, LLHttpProxyType type)
+{ 
+    sHttpProxyEnabled = true; 
+    mHTTPProxy        = httpHost; 
+    mProxyType        = type;
+}
diff --git a/indra/llmessage/llsocks5.h b/indra/llmessage/llsocks5.h
new file mode 100644
index 0000000000..83e311a962
--- /dev/null
+++ b/indra/llmessage/llsocks5.h
@@ -0,0 +1,243 @@
+/** 
+ * @file llsocks5.h
+ * @brief Socks 5 implementation
+ *
+ * $LicenseInfo:firstyear=2001&license=viewergpl$
+ * 
+ * Copyright (c) 2001-2009, Linden Research, Inc.
+ * 
+ * Second Life Viewer Source Code
+ * The source code in this file ("Source Code") is provided by Linden Lab
+ * to you under the terms of the GNU General Public License, version 2.0
+ * ("GPL"), unless you have obtained a separate licensing agreement
+ * ("Other License"), formally executed by you and Linden Lab.  Terms of
+ * the GPL can be found in doc/GPL-license.txt in this distribution, or
+ * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
+ * 
+ * There are special exceptions to the terms and conditions of the GPL as
+ * it is applied to this Source Code. View the full text of the exception
+ * in the file doc/FLOSS-exception.txt in this software distribution, or
+ * online at
+ * http://secondlifegrid.net/programs/open_source/licensing/flossexception
+ * 
+ * By copying, modifying or distributing this software, you acknowledge
+ * that you have read and understood your obligations described above,
+ * and agree to abide by those obligations.
+ * 
+ * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
+ * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
+ * COMPLETENESS OR PERFORMANCE.
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_SOCKS5_H
+#define LL_SOCKS5_H
+
+#include "llhost.h"
+#include "llmemory.h"
+#include "llsingleton.h"
+#include <string>
+
+// Error codes returned from the StartProxy method
+
+#define SOCKS_OK 0
+#define SOCKS_CONNECT_ERROR -1
+#define SOCKS_NOT_PERMITTED -2
+#define SOCKS_NOT_ACCEPTABLE -3
+#define SOCKS_AUTH_FAIL -4
+#define SOCKS_UDP_FWD_NOT_GRANTED -5
+#define SOCKS_HOST_CONNECT_FAILED -6
+
+#ifndef MAXHOSTNAMELEN
+#define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
+#endif
+
+#define SOCKS_VERSION 0x05 // we are using socks 5
+
+// socks 5 address/hostname types
+#define ADDRESS_IPV4     0x01
+#define ADDRESS_HOSTNAME 0x03
+#define ADDRESS_IPV6     0x04
+
+// Lets just use our own ipv4 struct rather than dragging in system
+// specific headers
+union ipv4_address_t {
+    unsigned char octects[4];
+    U32 addr32;
+};
+
+// Socks 5 control channel commands
+#define COMMAND_TCP_STREAM    0x01
+#define COMMAND_TCP_BIND      0x02
+#define COMMAND_UDP_ASSOCIATE 0x03
+
+// Socks 5 command replys
+#define REPLY_REQUEST_GRANTED     0x00
+#define REPLY_GENERAL_FAIL        0x01
+#define REPLY_RULESET_FAIL        0x02
+#define REPLY_NETWORK_UNREACHABLE 0x03
+#define REPLY_HOST_UNREACHABLE    0x04
+#define REPLY_CONNECTION_REFUSED  0x05
+#define REPLY_TTL_EXPIRED         0x06
+#define REPLY_PROTOCOL_ERROR      0x07
+#define REPLY_TYPE_NOT_SUPPORTED  0x08
+
+#define FIELD_RESERVED 0x00
+
+// The standard socks5 request packet
+// Push current alignment to stack and set alignment to 1 byte boundary
+// This enabled us to use structs directly to set up and receive network packets
+// into the correct fields, without fear of boundary alignment causing issues
+#pragma pack(push,1)
+
+// Socks5 command packet
+struct socks_command_request_t {
+    unsigned char version;
+    unsigned char command;
+    unsigned char flag;
+    unsigned char atype;
+    U32           address;
+    U16           port;
+};
+
+// Standard socks5 reply packet
+struct socks_command_response_t {
+    unsigned char version;
+    unsigned char reply;
+    unsigned char flag;
+    unsigned char atype;
+    unsigned char add_bytes[4];
+    U16           port;
+};
+
+#define AUTH_NOT_ACCEPTABLE 0xFF // reply if prefered methods are not avaiable
+#define AUTH_SUCCESS        0x00 // reply if authentication successfull
+
+// socks 5 authentication request, stating which methods the client supports
+struct socks_auth_request_t {
+    unsigned char version;
+    unsigned char num_methods;
+    unsigned char methods; // We are only using a single method currently
+};
+
+// socks 5 authentication response packet, stating server prefered method
+struct socks_auth_response_t {
+    unsigned char version;
+    unsigned char method;
+};
+
+// socks 5 password reply packet
+struct authmethod_password_reply_t {
+    unsigned char version;
+    unsigned char status;
+};
+
+// socks 5 UDP packet header
+struct proxywrap_t {
+    U16 rsv;
+    U8  frag;
+    U8  atype;
+    U32 addr;
+    U16 port;
+};
+
+#pragma pack(pop) /* restore original alignment from stack */
+
+
+// Currently selected http proxy type
+enum LLHttpProxyType
+{
+    LLPROXY_SOCKS = 0,
+    LLPROXY_HTTP  = 1
+};
+
+// Auth types
+enum LLSocks5AuthType
+{
+    METHOD_NOAUTH   = 0x00,	// Client supports no auth
+    METHOD_GSSAPI   = 0x01,	// Client supports GSSAPI (Not currently supported)
+    METHOD_PASSWORD = 0x02 	// Client supports username/password
+};
+
+class LLSocks: public LLSingleton<LLSocks>
+{
+public:
+    LLSocks();
+
+    // Start a connection to the socks 5 proxy
+    int startProxy(std::string host,U32 port);
+    int startProxy(LLHost proxy,U32 messagePort);
+
+    // Disconnect and clean up any connection to the socks 5 proxy
+    void stopProxy();
+
+    // Set up to use Password auth when connecting to the socks proxy
+    void setAuthPassword(std::string username,std::string password);
+
+    // Set up to use No Auth when connecting to the socks proxy;
+    void setAuthNone();
+
+    // get the currently selected auth method
+    LLSocks5AuthType getSelectedAuthMethod() { return mAuthMethodSelected; };
+
+    // static check for enabled status for UDP packets
+    static bool isEnabled(){return sUdpProxyEnabled;};
+
+    // static check for enabled status for http packets
+    static bool isHttpProxyEnabled(){return sHttpProxyEnabled;};
+
+    // Proxy http packets via httpHost, which can be a Socks5 or a http proxy
+    // as specified in type
+    void EnableHttpProxy(LLHost httpHost,LLHttpProxyType type);
+
+    // Stop proxying http packets
+    void DisableHttpProxy() {sHttpProxyEnabled = false;};
+
+    // get the UDP proxy address and port
+    LLHost getUDPProxy(){return mUDPProxy;};
+
+    // get the socks 5 TCP control channel address and port
+    LLHost getTCPProxy(){return mTCPProxy;};
+
+    //get the http proxy address and port
+    LLHost getHTTPProxy(){return mHTTPProxy;};
+
+    // get the currently selected http proxy type
+    LLHttpProxyType getHttpProxyType(){return mProxyType;};
+
+    //Get the username password in a curl compatible format
+    std::string getProxyUserPwd(){ return (mSocksUsername + ":" + mSocksPassword);};
+
+private:
+
+    // Open a communication channel to the socks5 proxy proxy, at port messagePort
+    int proxyHandshake(LLHost proxy,U32 messagePort);
+
+    // socket handle to proxy tcp control channel
+    S32 hProxyControlChannel;
+
+    // is the UDP proxy enabled
+    static bool sUdpProxyEnabled;
+    // is the http proxy enabled
+    static bool sHttpProxyEnabled;
+
+    // currently selected http proxy type
+    LLHttpProxyType mProxyType;
+
+    // UDP proxy address and port
+    LLHost mUDPProxy;
+    // TCP Proxy control channel address and port
+    LLHost mTCPProxy;
+    // HTTP proxy address and port
+    LLHost mHTTPProxy;
+
+    // socks 5 auth method selected
+    LLSocks5AuthType mAuthMethodSelected;
+
+    // socks 5 username
+    std::string mSocksUsername;
+    // socks 5 password
+    std::string mSocksPassword;
+};
+
+#endif
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index 97611c3b51..ab5c1950c6 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -50,6 +50,7 @@
 #include "lltimer.h"
 #include "indra_constants.h"
 
+#include "llsocks5.h"
 
 // Globals
 #if LL_WINDOWS
@@ -189,6 +190,90 @@ U32 ip_string_to_u32(const char* ip_string)
 
 #if LL_WINDOWS
  
+int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen)
+{
+	int result;
+	result = send(handle, dataout, outlen, 0);
+	if (result != outlen)
+	{
+		S32 err = WSAGetLastError();
+		llwarns << "Error sending data to proxy control channel, number of bytes sent were " << result << " error code was " << err << llendl;
+		return -1;
+	}
+
+	result = recv(handle, datain, maxinlen, 0);
+	if (result != maxinlen)
+	{
+		S32 err = WSAGetLastError();
+		llwarns << "Error receiving data from proxy control channel, number of bytes received were " << result << " error code was " << err << llendl;
+		return -1;
+	}
+
+	return 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;
+}
+
+void tcp_close_channel(S32 handle)
+{
+	llinfos << "Closing TCP channel" << llendl;
+	shutdown(handle, SD_BOTH);
+	closesocket(handle);
+}
+
 S32 start_net(S32& socket_out, int& nPort) 
 {			
 	// Create socket, make non-blocking
@@ -385,6 +470,77 @@ BOOL send_packet(int hSocket, const char *sendBuffer, int size, U32 recipient, i
 
 #else
 
+
+int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen)
+{
+	if (send(handle, dataout, outlen, 0) != outlen)
+	{
+		llwarns << "Error sending data to proxy control channel" << llendl;
+		return -1;
+	}
+
+	if (recv(handle, datain, maxinlen, 0) != maxinlen)
+	{
+		llwarns << "Error receiving data to proxy control channel" << llendl;		
+		return -1;
+	}
+
+	return 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;
+}
+
+void tcp_close_channel(S32 handle)
+{
+	close(handle);
+}
+
 //  Create socket, make non-blocking
 S32 start_net(S32& socket_out, int& nPort)
 {
diff --git a/indra/llmessage/net.h b/indra/llmessage/net.h
index 9f4f5c5821..d93ed20c98 100644
--- a/indra/llmessage/net.h
+++ b/indra/llmessage/net.h
@@ -52,6 +52,11 @@ U32		get_sender_ip(void);
 LLHost  get_receiving_interface();
 U32		get_receiving_interface_ip(void);
 
+// Some helpful tcp functions added for the socks 5 proxy support
+S32 tcp_open_channel(LLHost host); // Open a tcp channel to a given host
+void tcp_close_channel(S32 handle); // Close an open tcp channel
+int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen); // Do a TCP data handshake
+
 const char*	u32_to_ip_string(U32 ip);					// Returns pointer to internal string buffer, "(bad IP addr)" on failure, cannot nest calls 
 char*		u32_to_ip_string(U32 ip, char *ip_string);	// NULL on failure, ip_string on success, you must allocate at least MAXADDRSTR chars
 U32			ip_string_to_u32(const char* ip_string);	// Wrapper for inet_addr()
diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index f0e28d4ae3..2b7b7b8484 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -774,6 +774,83 @@
       <key>Value</key>
       <integer>5</integer>
     </map>
+    <key>Socks5ProxyEnabled</key>
+    <map>
+      <key>Comment</key>
+      <string>Use Socks5 Proxy</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>Boolean</string>
+      <key>Value</key>
+      <integer>1</integer>
+    </map>
+    <key>Socks5HttpProxyType</key>
+    <map>
+      <key>Comment</key>
+      <string>Proxy type to use for HTTP operations</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>String</string>
+      <key>Value</key>
+      <string>Socks</string>
+    </map>
+    <key>Socks5ProxyHost</key>
+    <map>
+      <key>Comment</key>
+      <string>Socks 5 Proxy Host</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>String</string>
+      <key>Value</key>
+      <string>64.79.219.97</string>
+    </map>
+    <key>Socks5ProxyPort</key>
+    <map>
+      <key>Comment</key>
+      <string>Socks 5 Proxy Port</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>U32</string>
+      <key>Value</key>
+      <integer>1080</integer>
+    </map>
+     <key>Socks5Username</key>
+    <map>
+      <key>Comment</key>
+      <string>Socks 5 Username</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>String</string>
+      <key>Value</key>
+      <string></string>
+    </map>
+    <key>Socks5Password</key>
+    <map>
+      <key>Comment</key>
+      <string>Socks 5 Password</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>String</string>
+      <key>Value</key>
+      <string></string>
+    </map>
+    <key>Socks5AuthType</key>
+    <map>
+      <key>Comment</key>
+      <string>Selected Auth mechanism for Socks5</string>
+      <key>Persist</key>
+      <integer>1</integer>
+      <key>Type</key>
+      <string>String</string>
+      <key>Value</key>
+      <string>None</string>
+    </map>
     <key>BuildAxisDeadZone0</key>
     <map>
       <key>Comment</key>
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index 724096b443..a0d3852d30 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -103,6 +103,7 @@
 #include "llviewermedia.h"
 #include "llpluginclassmedia.h"
 #include "llteleporthistorystorage.h"
+#include "llsocks5.h"
 
 #include "lllogininstance.h"        // to check if logged in yet
 #include "llsdserialize.h"
@@ -325,6 +326,7 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key)
 	mCommitCallbackRegistrar.add("Pref.getUIColor",				boost::bind(&LLFloaterPreference::getUIColor, this ,_1, _2));
 	mCommitCallbackRegistrar.add("Pref.MaturitySettings",		boost::bind(&LLFloaterPreference::onChangeMaturity, this));
 	mCommitCallbackRegistrar.add("Pref.BlockList",				boost::bind(&LLFloaterPreference::onClickBlockList, this));
+    mCommitCallbackRegistrar.add("Pref.Proxy",                    boost::bind(&LLFloaterPreference::onClickProxySettings, this));
 	
 	sSkin = gSavedSettings.getString("SkinCurrent");
 
@@ -603,6 +605,12 @@ void LLFloaterPreference::cancel()
 		updateDoubleClickControls();
 		mDoubleClickActionDirty = false;
 	}
+    LLFloaterPreferenceProxy * advanced_socks_settings = LLFloaterReg::findTypedInstance<LLFloaterPreferenceProxy>("prefs_socks5_advanced");
+    if(advanced_socks_settings)
+    {
+        advanced_socks_settings->cancel();
+    }
+    
 }
 
 void LLFloaterPreference::onOpen(const LLSD& key)
@@ -1497,6 +1505,11 @@ void LLFloaterPreference::updateDoubleClickSettings()
 	}
 }
 
+void LLFloaterPreference::onClickProxySettings()
+{
+    LLFloaterReg::showInstance("prefs_proxy");
+}
+
 void LLFloaterPreference::updateDoubleClickControls()
 {
 	// check is one of double-click actions settings enabled
@@ -1805,3 +1818,161 @@ void LLPanelPreferenceGraphics::setHardwareDefaults()
 	resetDirtyChilds();
 	LLPanelPreference::setHardwareDefaults();
 }
+
+
+/* ------------------------------------------------------------ */
+
+LLFloaterPreferenceProxy::LLFloaterPreferenceProxy(const LLSD& key)
+    : LLFloater(key),
+    mSocksSettingsDirty(false)
+{
+    mCommitCallbackRegistrar.add("Proxy.OK",                boost::bind(&LLFloaterPreferenceProxy::onBtnOk, this));
+    mCommitCallbackRegistrar.add("Proxy.Cancel",            boost::bind(&LLFloaterPreferenceProxy::onBtnCancel, this));
+    mCommitCallbackRegistrar.add("Proxy.Change",            boost::bind(&LLFloaterPreferenceProxy::onChangeSocksSettings, this));
+}
+
+LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
+{
+}
+
+BOOL LLFloaterPreferenceProxy::postBuild()
+{
+    LLLineEditor* edit = getChild<LLLineEditor>("socks_password_editor");
+    if (edit) edit->setDrawAsterixes(TRUE);
+
+    LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+    if(socksAuth->getSelectedValue().asString() == "None")
+    {
+        getChild<LLLineEditor>("socks5_username")->setEnabled(false);
+        getChild<LLLineEditor>("socks5_password")->setEnabled(false);
+    }
+
+    center();
+    return TRUE;
+}
+
+void LLFloaterPreferenceProxy::onOpen(const LLSD& key)
+{
+    saveSettings();
+}
+
+void LLFloaterPreferenceProxy::onClose(bool app_quitting)
+{
+    if(mSocksSettingsDirty)
+    {
+
+        // If the user plays with the Socks proxy settings after login, its only fair we let them know
+        // it will not be updated untill next restart.
+        if(LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
+        {        
+            if(this->mSocksSettingsDirty == true )
+            {
+                LLNotifications::instance().add("ChangeSocks5Settings",LLSD(),LLSD());
+                mSocksSettingsDirty = false; // we have notified the user now be quiet again
+            }
+        }
+    }
+}
+
+void LLFloaterPreferenceProxy::saveSettings()
+{
+    // Save the value of all controls in the hierarchy
+    mSavedValues.clear();
+    std::list<LLView*> view_stack;
+    view_stack.push_back(this);
+    while(!view_stack.empty())
+    {
+        // Process view on top of the stack
+        LLView* curview = view_stack.front();
+        view_stack.pop_front();
+
+        LLUICtrl* ctrl = dynamic_cast<LLUICtrl*>(curview);
+        if (ctrl)
+        {
+            LLControlVariable* control = ctrl->getControlVariable();
+            if (control)
+            {
+                mSavedValues[control] = control->getValue();
+            }
+        }
+                    
+        // Push children onto the end of the work stack
+        for (child_list_t::const_iterator iter = curview->getChildList()->begin();
+             iter != curview->getChildList()->end(); ++iter)
+        {
+            view_stack.push_back(*iter);
+        }
+    }    
+
+}
+
+void LLFloaterPreferenceProxy::onBtnOk()
+{
+    // commit any outstanding text entry
+    if (hasFocus())
+    {
+        LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+        if (cur_focus && cur_focus->acceptsTextInput())
+        {
+            cur_focus->onCommit();
+        }
+    }
+    closeFloater(false);
+}
+
+void LLFloaterPreferenceProxy::onBtnCancel()
+{
+    if (hasFocus())
+    {
+        LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+        if (cur_focus && cur_focus->acceptsTextInput())
+        {
+            cur_focus->onCommit();
+        }
+        refresh();
+    }
+    
+    cancel();
+    
+}
+void LLFloaterPreferenceProxy::cancel()
+{
+
+    for (control_values_map_t::iterator iter =  mSavedValues.begin();
+         iter !=  mSavedValues.end(); ++iter)
+    {
+        LLControlVariable* control = iter->first;
+        LLSD ctrl_value = iter->second;
+        control->set(ctrl_value);
+    }
+    
+    closeFloater();
+}
+
+void LLFloaterPreferenceProxy::onChangeSocksSettings() 
+{
+    mSocksSettingsDirty = true; 
+
+    LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+    if(socksAuth->getSelectedValue().asString() == "None")
+    {
+        getChild<LLLineEditor>("socks5_username")->setEnabled(false);
+        getChild<LLLineEditor>("socks5_password")->setEnabled(false);
+    }
+    else
+    {
+        getChild<LLLineEditor>("socks5_username")->setEnabled(true);
+        getChild<LLLineEditor>("socks5_password")->setEnabled(true);
+    }
+
+    //Check for invalid states for the other http proxy radio
+    LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
+    if( (otherHttpProxy->getSelectedValue().asString() == "Socks" && 
+        getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
+        otherHttpProxy->getSelectedValue().asString() == "Web" && 
+        getChild<LLCheckBoxCtrl>("web_proxy_enabled")->get() == FALSE ) )
+    {    
+        otherHttpProxy->selectFirstItem();
+    }
+
+};
\ No newline at end of file
diff --git a/indra/newview/llfloaterpreference.h b/indra/newview/llfloaterpreference.h
index 46014804ec..fd5454ebcf 100644
--- a/indra/newview/llfloaterpreference.h
+++ b/indra/newview/llfloaterpreference.h
@@ -154,6 +154,7 @@ public:
 	void applyResolution();
 	void onChangeMaturity();
 	void onClickBlockList();
+	void onClickProxySettings();
 	void applyUIColor(LLUICtrl* ctrl, const LLSD& param);
 	void getUIColor(LLUICtrl* ctrl, const LLSD& param);
 	
@@ -225,4 +226,33 @@ protected:
 	
 };
 
+class LLFloaterPreferenceProxy : public LLFloater
+{
+public: 
+	LLFloaterPreferenceProxy(const LLSD& key);
+	~LLFloaterPreferenceProxy();
+
+	/// show off our menu
+	static void show();
+	void cancel();
+	
+protected:
+	BOOL postBuild();
+	void onOpen(const LLSD& key);
+	void onClose(bool app_quitting);
+	void saveSettings();
+	void onBtnOk();
+	void onBtnCancel();
+
+	void onChangeSocksSettings();
+
+private:
+	
+	bool mSocksSettingsDirty;
+	typedef std::map<LLControlVariable*, LLSD> control_values_map_t;
+	control_values_map_t mSavedValues;
+
+};
+
+
 #endif  // LL_LLPREFERENCEFLOATER_H
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 8fccb35886..f054bd11b8 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -191,6 +191,8 @@
 #include "llevents.h"
 #include "llstartuplistener.h"
 
+#include "llsocks5.h"
+
 #if LL_WINDOWS
 #include "lldxhardware.h"
 #endif
@@ -393,7 +395,7 @@ bool idle_startup()
 		gSavedSettings.setS32("LastGPUClass", LLFeatureManager::getInstance()->getGPUClass());
 
 		// load dynamic GPU/feature tables from website (S3)
-		LLFeatureManager::getInstance()->fetchHTTPTables();
+		//LLFeatureManager::getInstance()->fetchHTTPTables();
 		
 		std::string xml_file = LLUI::locateSkin("xui_version.xml");
 		LLXMLNodePtr root;
@@ -595,6 +597,15 @@ bool idle_startup()
 
 		LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
 		
+		//-------------------------------------------------
+		// Init the socks 5 proxy and open the control TCP 
+		// connection if the user is using SOCKS5
+		// We need to do this early incase the user is using
+		// socks for http so we get the login screen via socks
+		//-------------------------------------------------
+
+		LLStartUp::handleSocksProxy(false);
+
 		//-------------------------------------------------
 		// Init audio, which may be needed for prefs dialog
 		// or audio cues in connection UI.
@@ -809,6 +820,27 @@ bool idle_startup()
 
 	if (STATE_LOGIN_CLEANUP == LLStartUp::getStartupState())
 	{
+		// Post login screen, we should see if any settings have changed that may
+		// require us to either start/stop or change the socks proxy. As various communications
+		// past this point may require the proxy to be up.
+		if ( gSavedSettings.getBOOL("Socks5ProxyEnabled") )
+		{
+			if (!LLStartUp::handleSocksProxy(true))
+			{
+				// Proxy start up failed, we should now bail the state machine
+				// HandleSocksProxy() will have reported an error to the user 
+				// already, so we just go back to the login screen. The user
+				// could then change the preferences to fix the issue. 
+				LLStartUp::setStartupState(STATE_LOGIN_SHOW);
+				return FALSE;
+			}
+		}
+		else
+		{
+			LLSocks::getInstance()->stopProxy();
+		}
+		
+
 		//reset the values that could have come in from a slurl
 		// DEV-42215: Make sure they're not empty -- gUserCredential
 		// might already have been set from gSavedSettings, and it's too bad
@@ -2746,6 +2778,95 @@ void LLStartUp::setStartSLURL(const LLSLURL& slurl)
     }
 }
 
+bool LLStartUp::handleSocksProxy(bool reportOK)
+{
+	std::string httpProxyType = gSavedSettings.getString("Socks5HttpProxyType");
+
+	// Determine the http proxy type (if any)
+	if ((httpProxyType.compare("Web") == 0) && gSavedSettings.getBOOL("BrowserProxyEnabled"))
+	{
+		LLHost httpHost;
+		httpHost.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
+		httpHost.setPort(gSavedSettings.getS32("BrowserProxyPort"));
+		LLSocks::getInstance()->EnableHttpProxy(httpHost,LLPROXY_HTTP);
+	}
+	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
+	{
+		LLHost httpHost;
+		httpHost.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
+		httpHost.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
+		LLSocks::getInstance()->EnableHttpProxy(httpHost,LLPROXY_SOCKS);
+	}
+	else
+	{
+		LLSocks::getInstance()->DisableHttpProxy();
+	}
+	
+	bool use_socks_proxy = gSavedSettings.getBOOL("Socks5ProxyEnabled");
+	if (use_socks_proxy)
+	{	
+
+		// Determine and update LLSocks with the saved authentication system
+		std::string auth_type = gSavedSettings.getString("Socks5AuthType");
+			
+		if (auth_type.compare("None") == 0)
+		{
+			LLSocks::getInstance()->setAuthNone();
+		}
+
+		if (auth_type.compare("UserPass") == 0)
+		{
+			LLSocks::getInstance()->setAuthPassword(gSavedSettings.getString("Socks5Username"),gSavedSettings.getString("Socks5Password"));
+		}
+
+		// Start the proxy and check for errors
+		int status = LLSocks::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
+		LLSD subs;
+		LLSD payload;
+		subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
+		subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
+
+		switch(status)
+		{
+			case SOCKS_OK:
+				return true;
+				break;
+
+			case SOCKS_CONNECT_ERROR: // TCP Fail
+				LLNotifications::instance().add("SOCKS_CONNECT_ERROR", subs,payload);
+				break;
+
+			case SOCKS_NOT_PERMITTED: // Socks5 server rule set refused connection
+				LLNotifications::instance().add("SOCKS_NOT_PERMITTED", subs,payload);
+				break;
+					
+			case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
+				LLNotifications::instance().add("SOCKS_NOT_ACCEPTABLE", subs,payload);
+				break;
+
+			case SOCKS_AUTH_FAIL: // Authentication failed
+				LLNotifications::instance().add("SOCKS_AUTH_FAIL", subs,payload);
+				break;
+
+			case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
+				LLNotifications::instance().add("SOCKS_UDP_FWD_NOT_GRANTED", subs,payload);
+				break;
+
+			case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
+				LLNotifications::instance().add("SOCKS_HOST_CONNECT_FAILED", subs,payload);
+				break;		
+		}
+
+		return false;
+	}
+	else
+	{
+		LLSocks::getInstance()->stopProxy(); //ensure no UDP proxy is running and its all cleaned up
+	}
+
+	return true;
+}
+
 bool login_alert_done(const LLSD& notification, const LLSD& response)
 {
 	LLPanelLogin::giveFocus();
diff --git a/indra/newview/llstartup.h b/indra/newview/llstartup.h
index b3d9ef1dcc..a512ec7bff 100644
--- a/indra/newview/llstartup.h
+++ b/indra/newview/llstartup.h
@@ -113,6 +113,8 @@ public:
 	static void setStartSLURL(const LLSLURL& slurl); 
 	static LLSLURL& getStartSLURL() { return sStartSLURL; } 
 
+	static bool handleSocksProxy(bool reportOK); //handle kicking the socks 5 proxy code at startup time
+
 private:
 	static LLSLURL sStartSLURL;
 
diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp
index dca1e33e60..976dc76b50 100644
--- a/indra/newview/llviewerfloaterreg.cpp
+++ b/indra/newview/llviewerfloaterreg.cpp
@@ -202,6 +202,7 @@ void LLViewerFloaterReg::registerFloaters()
 
 	LLFloaterReg::add("postcard", "floater_postcard.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterPostcard>);
 	LLFloaterReg::add("preferences", "floater_preferences.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterPreference>);
+	LLFloaterReg::add("prefs_proxy", "floater_preferences_proxy.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterPreferenceProxy>);
 	LLFloaterReg::add("prefs_hardware_settings", "floater_hardware_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterHardwareSettings>);
 	LLFloaterReg::add("perm_prefs", "floater_perm_prefs.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterPerms>);
 	LLFloaterReg::add("pref_joystick", "floater_joystick.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterJoystick>);
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index 257884d921..b3d899c61a 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -41,6 +41,8 @@
 #include "llappviewer.h"
 #include "lltrans.h"
 
+#include "llsocks5.h"
+
 // Static instance of LLXMLRPCListener declared here so that every time we
 // bring in this code, we instantiate a listener. If we put the static
 // instance of LLXMLRPCListener into llxmlrpclistener.cpp, the linker would
@@ -307,16 +309,23 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 	}
 	mErrorCert = NULL;
 	
-	if (gSavedSettings.getBOOL("BrowserProxyEnabled"))
+	if (LLSocks::getInstance()->isHttpProxyEnabled())
 	{
-		mProxyAddress = gSavedSettings.getString("BrowserProxyAddress");
-		S32 port = gSavedSettings.getS32 ( "BrowserProxyPort" );
-
-		// tell curl about the settings
-		mCurlRequest->setoptString(CURLOPT_PROXY, mProxyAddress);
+		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
+		mCurlRequest->setoptString(CURLOPT_PROXY, address.c_str());
 		mCurlRequest->setopt(CURLOPT_PROXYPORT, port);
+		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		{
+			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
+			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd());
+		}
+		else
+		{
 		mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
 	}
+	}
 
 //	mCurlRequest->setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
 	mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
new file mode 100644
index 0000000000..bb9ade067b
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -0,0 +1,274 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<floater
+ legacy_header_height="18"
+ height="490"
+ layout="topleft"
+ name="Socks5 Advanced Settings Floater"
+ help_topic="hardware_settings_floater"
+ title="Socks5 proxy advanced settings"
+ width="385">
+    <check_box
+     control_name="BrowserProxyEnabled"
+     top="30"
+     enabled="true"
+     follows="left|top"
+     height="14"
+     initial_value="false"
+     commit_callback.function="Proxy.Change"
+     label="Use HTTP Proxy for Web pages"
+     left_delta="10"
+     mouse_opaque="true"
+     name="web_proxy_enabled"
+     radio_style="false"
+     width="400"
+     top_pad="5" />
+    <check_box
+     control_name="Socks5ProxyEnabled"
+     height="16"
+     label="Use Socks 5 Proxy for UDP traffic"
+     layout="topleft"
+     left_delta="0"
+     name="socks_proxy_enabled"
+     top_pad="5"
+     width="256"
+     commit_callback.function="Proxy.Change" />
+    <text
+     type="string"
+     length="1"
+     follows="left|top"
+     height="10"
+     layout="topleft"
+     left="10"
+     name="Proxy location"
+     top_delta="30"
+     width="300">
+        Other Http traffic proxy:
+     </text>
+     <radio_group
+      control_name="Socks5HttpProxyType"
+      height="60"
+      layout="topleft"
+      name="other_http_proxy_selection"
+      top_pad="10"
+      width="120"
+      border="1"
+      left_delta="10" 
+      commit_callback.function="Proxy.Change" >
+          <radio_item
+           height="16"
+           label="Do not proxy"
+           layout="topleft"
+           value="None"
+           width="120"
+           tool_tip="Non web Http trafic should NOT be sent to any proxy."/>
+          <radio_item
+           height="16"
+           label="Use Socks 5 Proxy"
+           layout="topleft"
+           value="Socks"
+           width="120"
+           enabled_control="Socks5ProxyEnabled"
+           tool_tip="Non-web Http will be sent to the configured Socks 5 proxy."/>
+          <radio_item
+           height="16"
+           label="Use Http Proxy"
+           layout="topleft"
+           value="Web"
+           width="120"
+           enabled_control="BrowserProxyEnabled"
+           tool_tip="Non-web Http will be sent to the configured Web proxy." />
+    </radio_group>
+    <text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 left="15"
+	 layout="topleft"
+	 name="Proxy location"
+	 top_delta="82"
+	 width="300">
+	    HTTP Proxy:
+	</text>
+	<line_editor
+	 control_name="BrowserProxyAddress"
+	 enabled_control="BrowserProxyEnabled"
+     follows="left|top"
+	 font="SansSerif"
+	 height="23"
+	 layout="topleft"
+	 left_delta="0"
+	 name="web_proxy_editor"
+	 tool_tip="The DNS name or IP address of the HTTP proxy you would like to use."
+	 top_pad="4"
+	 width="200" />
+	<spinner
+	 control_name="BrowserProxyPort"
+	 enabled_control="BrowserProxyEnabled"
+     decimal_digits="0"
+	 follows="left|top"
+	 height="23"
+	 increment="1"
+	 initial_value="80"
+	 label="Port number:"
+	 label_width="95"
+	 layout="topleft"
+	 left_delta="210"
+	 max_val="12000"
+	 min_val="10"
+	 name="web_proxy_port"
+	 top_delta="0"
+      tool_tip="The port of the HTTP proxy you would like to use."
+	 width="145" />
+	<text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 layout="topleft"
+	 left="15"
+	 name="Proxy location"
+	 top_delta="32"
+	 width="300">
+	    SOCKS 5 Proxy:
+	</text>
+	<line_editor
+	 control_name="Socks5ProxyHost"
+	 enabled_control="Socks5ProxyEnabled"
+	 follows="left|top"
+	 font="SansSerif"
+	 height="23"
+	 layout="topleft"
+	 left_delta="0"
+	 name="socks_proxy_editor"
+	 tool_tip="The DNS name or IP address of the SOCKS 5 proxy you would like to use."
+	 top_pad="4"
+	 width="200"
+	 commit_callback.function="Proxy.Change" />
+	<spinner
+	 control_name="Socks5ProxyPort"
+	 enabled_control="Socks5ProxyEnabled"
+	 decimal_digits="0"
+	 follows="left|top"
+	 height="23"
+	 increment="1"
+	 initial_value="80"
+	 label="Port number:"
+	 label_width="95"
+	 layout="topleft"
+	 left_delta="210"
+	 max_val="12000"
+	 min_val="10"
+	 name="socks_proxy_port"
+	 top_delta="0"
+	 width="145"
+     tool_tip="The port of the SOCKS 5 proxy you would like to use."
+	 commit_callback.function="Pref.SocksProxy" />
+	<text
+     type="string"
+     length="1"
+     follows="left|top"
+     height="10"
+     layout="topleft"
+     left="16"
+     name="Proxy location"
+     top_delta="35"
+     width="300">
+	    Authentication:
+	</text>
+	<radio_group
+	 control_name="Socks5AuthType"
+	 enabled_control="Socks5ProxyEnabled"
+	 height="50"
+	 layout="topleft"
+	 name="socks5_auth_type"
+	 top_pad="10"
+	 width="120"
+	 border="1"
+	 commit_callback.function="Proxy.Change" >
+	    <radio_item
+		 height="16"
+		 label="No Authentication"
+		 layout="topleft"
+		 name="Socks5NoAuth"
+		 value="None"
+		 tool_tip="Socks5 proxy requires no authentication."/>
+		 width="120" />
+		<radio_item
+		 height="16"
+		 label="Username/Password"
+		 layout="topleft"
+		 name="Socks5UserPass"
+		 value="UserPass"
+		 tool_tip="Socks5 proxy requires username/password authentication."/>
+		 width="120" />
+	</radio_group>
+	<text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 layout="topleft"
+	 left_delta="20"
+	 top_delta="50"
+	 width="300">
+	    Username:
+	</text>
+	<line_editor
+	 control_name="Socks5Username"
+	 follows="left|top"
+	 font="SansSerif"
+	 height="23"
+	 layout="topleft"
+	 left_delta="0"
+	 name="socks5_username"
+	 tool_tip="The username used to authenticate with your SOCKS 5 server"
+	 top_pad="4"
+	 width="200"
+	 commit_callback.function="Proxy.Change" />
+	<text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 layout="topleft"
+	 left_delta="0"
+	 top_delta="30"
+	 width="300">
+	    Password:
+	</text>
+	<line_editor
+	 control_name="Socks5Password"
+	 follows="left|top"
+	 font="SansSerif"
+	 height="23"
+	 layout="topleft"
+	 left_delta="0"
+	 name="socks5_password"
+	 tool_tip="The password used to authenticate with your SOCKS 5 server"
+	 top_pad="4"
+	 width="200"
+	 commit_callback.function="Proxy.Change" />
+	<button
+	 follows="left|top"
+	 height="22"
+	 label="OK"
+	 label_selected="OK"
+	 layout="topleft"
+	 right="275"
+	 name="OK"
+	 top_delta="53"
+	 width="90"
+	 commit_callback.function="Proxy.OK" />
+	<button
+	 follows="left|top"
+	 height="22"
+	 label="Cancel"
+	 label_selected="Cancel"
+	 layout="topleft"
+	 right="375"
+	 name="Cancel"
+	 top_delta="0"
+	 width="90"
+	 commit_callback.function="Proxy.Cancel" />
+</floater>
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index ba13479860..751b038252 100644
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -7069,6 +7069,76 @@ Mute everyone?
     </form>
   </notification>
 
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_NOT_PERMITTED"
+   type="alertmodal">
+	The Socks5 proxy "[HOST]:[PORT]" refused the connection, not allowed by rule set
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_CONNECT_ERROR"
+   type="alertmodal">
+	The Socks5 proxy "[HOST]:[PORT]" refused the connection, could not open TCP channel
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>	 
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_NOT_ACCEPTABLE"
+   type="alertmodal">
+	The Socks5 proxy "[HOST]:[PORT]" refused the selected authentication system
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_AUTH_FAIL"
+   type="alertmodal">
+	The Socks5 proxy "[HOST]:[PORT]" reported your credentials are invalid
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_UDP_FWD_NOT_GRANTED"
+   type="alertmodal">
+	The Socks5 proxy "[HOST]:[PORT]" refused the UDP associate request
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_HOST_CONNECT_FAILED"
+   type="alertmodal">
+	Could not connect to Socks5 proxy server "[HOST]:[PORT]"
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="ChangeSocks5Settings"
+   type="alert">
+	Socks 5 proxy settings take effect after you restart [APP_NAME].
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
   <notification
   name="AuthRequest"
   type="browser">
diff --git a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
index 901a1257e0..1a631293e7 100644
--- a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
+++ b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
@@ -70,7 +70,7 @@
    layout="topleft"
    left="77"
    name="connection_port_enabled"
-   top_pad="20"
+   top_pad="10"
    width="256">
     <check_box.commit_callback
      function="Notification.Show"
@@ -102,7 +102,7 @@
    left="80"
    mouse_opaque="false"
    name="cache_size_label_l"
-   top_pad="20"
+   top_pad="10"
    width="200">
     Cache size
   </text>
@@ -287,60 +287,6 @@
     name="media_popup_enabled"
     width="400"           
     top_pad="5"/>
-  <check_box
-    top_delta="4"
-    enabled="true"
-    follows="left|top"
-    height="14"
-    initial_value="false"
-    control_name="BrowserProxyEnabled"
-    label="Enable Web Proxy"
-    left_delta="0"
-    mouse_opaque="true"
-    name="web_proxy_enabled"
-    radio_style="false"
-    width="400"           top_pad="5"/>
-  <text
-   type="string"
-   length="1"
-   follows="left|top"
-   height="10"
-   layout="topleft"
-   left_delta="20"
-   name="Proxy location"
-   top_delta="16"
-   width="300">
-    Proxy location:
-  </text>
-  <line_editor
-   control_name="BrowserProxyAddress"
-   enabled_control="BrowserProxyEnabled"
- follows="left|top"
-   font="SansSerif"
-   height="23"
-   layout="topleft"
-   left_delta="0"
-   name="web_proxy_editor"
-   tool_tip="The name or IP address of the proxy you would like to use"
-   top_pad="4"
-   width="200" />
-  <spinner
-   control_name="BrowserProxyPort"
-   enabled_control="BrowserProxyEnabled"
- decimal_digits="0"
-   follows="left|top"
-   height="23"
-   increment="1"
-   initial_value="80"
-   label="Port number:"
-   label_width="95"
-   layout="topleft"
-   left_delta="210"
-   max_val="12000"
-   min_val="10"
-   name="web_proxy_port"
-   top_delta="0"
-   width="145" />
   <text
      type="string"
      length="1"
@@ -378,4 +324,31 @@
          name="Install_manual"
          value="0" />
   </combo_box>
+  <text
+     type="string"
+     length="1"
+     follows="left|top"
+     height="10"
+     layout="topleft"
+     left="30"
+     name="Software updates:"
+     mouse_opaque="false"
+     top_pad="5"
+     width="300">
+		Proxy Settings:
+  </text>
+  <button
+	label="Adjust proxy settings"
+    follows="left|top"
+    height="23"
+	width="140" 
+    label_selected="Browse"
+    layout="topleft"
+    left_delta="50"
+    name="set_proxy"
+    top_pad="5"
+    >
+		<button.commit_callback
+		  function="Pref.Proxy" />
+  </button>
 </panel>
-- 
cgit v1.2.3


From 6ce2c20a06e32825f4e4260575059a9867510ecd Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Fri, 10 Jun 2011 17:34:00 -0400
Subject: STORM-1112 First pass at cleanup of SOCKS 5 proxy code based on
 Linden Coding Standard and comments in the code review.

---
 indra/llmessage/llpacketring.cpp                   |  23 +-
 indra/llmessage/llsocks5.cpp                       | 295 +++++++++++----------
 indra/llmessage/llsocks5.h                         | 184 ++++++-------
 indra/llmessage/net.cpp                            |  61 +++--
 indra/llmessage/net.h                              |   4 +-
 indra/newview/llfloaterpreference.cpp              | 225 ++++++++--------
 indra/newview/llstartup.cpp                        |   8 +-
 indra/newview/llxmlrpctransaction.cpp              |   8 +-
 .../default/xui/en/floater_preferences_proxy.xml   |   2 +-
 9 files changed, 409 insertions(+), 401 deletions(-)

diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index 0c8c5f763c..62aaca0672 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -28,22 +28,26 @@
 
 #include "llpacketring.h"
 
+#if LL_WINDOWS
+	#include <winsock2.h>
+#else
+	#include <sys/socket.h>
+	#include <netinet/in.h>
+#endif
+
 // linden library includes
 #include "llerror.h"
+#include "message.h"
+#include "llsocks5.h"
 #include "lltimer.h"
 #include "timing.h"
 #include "llrand.h"
 #include "u64.h"
 
-#include "llsocks5.h"
-#include "message.h"
 
-#if LL_WINDOWS
-	#include <winsock2.h>
-#else
-	#include <sys/socket.h>
-	#include <netinet/in.h>
-#endif
+
+
+
 
 
 ///////////////////////////////////////////////////////////
@@ -241,8 +245,7 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 				packet_size=0;
 			}
 
-			proxywrap_t * header;
-			header = (proxywrap_t *)buffer;
+			proxywrap_t * header = (proxywrap_t *)buffer;
 			mLastSender.setAddress(header->addr);
 			mLastSender.setPort(ntohs(header->port));
 		}
diff --git a/indra/llmessage/llsocks5.cpp b/indra/llmessage/llsocks5.cpp
index 8a63287f22..7eac27d4bb 100644
--- a/indra/llmessage/llsocks5.cpp
+++ b/indra/llmessage/llsocks5.cpp
@@ -35,184 +35,185 @@
 // Static class variable instances
 
 // We want this to be static to avoid excessive indirection on every
-// incomming packet just to do a simple bool test. The getter for this
+// incoming packet just to do a simple bool test. The getter for this
 // member is also static
 bool LLSocks::sUdpProxyEnabled;
 bool LLSocks::sHttpProxyEnabled;
 
 LLSocks::LLSocks()
 {
-    sUdpProxyEnabled  = false;
-    sHttpProxyEnabled = false;
-    hProxyControlChannel = 0;
-    mProxyType = LLPROXY_SOCKS;
+	sUdpProxyEnabled  = false;
+	sHttpProxyEnabled = false;
+	mProxyControlChannel = 0;
+	mProxyType = LLPROXY_SOCKS;
 }
 
-// Perform a Socks5 authentication and UDP assioacation to the proxy
-// specified by proxy, and assiocate UDP port message_port
+// Perform a Socks5 authentication and UDP association to the proxy
+// specified by proxy, and associate UDP port message_port
 int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 {
-    int 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     = mAuthMethodSelected; // send only the selected metho
-
-    result = tcp_handshake(hProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request_t), (char*)&socks_auth_response, sizeof(socks_auth_response_t));
-    if (result != 0)
-    {
-        llwarns << "Socks authentication request failed, error on TCP control channel : " << result << llendl;
-        stopProxy();
-        return SOCKS_CONNECT_ERROR;
-    }
-    
-    if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
-    {
-        llwarns << "Socks5 server refused all our authentication methods" << llendl;
-        stopProxy();
-        return SOCKS_NOT_ACCEPTABLE;
-    }
-
-    // SOCKS5 USERNAME/PASSWORD authentication
-    if (socks_auth_response.method == METHOD_PASSWORD)
-    {
-        // The server has requested a username/password combination
-        U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
-        char * password_auth = (char *)malloc(request_size);
-        password_auth[0] = 0x01;
-        password_auth[1] = mSocksUsername.size();
-        memcpy(&password_auth[2],mSocksUsername.c_str(), mSocksUsername.size());
-        password_auth[mSocksUsername.size()+2] = mSocksPassword.size();
-        memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
-
-        authmethod_password_reply_t password_reply;
-
-        result = tcp_handshake(hProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
-        free (password_auth);
-
-        if (result != 0)
-        {
-        llwarns << "Socks authentication failed, error on TCP control channel : " << result << llendl;
-            stopProxy();
-            return SOCKS_CONNECT_ERROR;
-        }
-
-        if (password_reply.status != AUTH_SUCCESS)
-        {
-            llwarns << "Socks authentication failed" << llendl;
-            stopProxy();
-            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.flag    = FIELD_RESERVED;
-    connect_request.atype   = ADDRESS_IPV4;
-    connect_request.address = 0; // 0.0.0.0 We are not fussy about address
-                                 // UDP is promiscious receive for our protocol
-    connect_request.port    = 0; // Port must be 0 if you ever want to connect via NAT and your router does port rewrite for you
-
-    result = tcp_handshake(hProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
-    if (result != 0)
-    {
-        llwarns << "Socks connect request failed, error on TCP control channel : " << result << llendl;
-        stopProxy();
-        return SOCKS_CONNECT_ERROR;
-    }
-
-    if (connect_reply.reply != REPLY_REQUEST_GRANTED)
-    {
-        //Something went wrong
-        llwarns << "Connection to SOCKS5 server failed, UDP forward request not granted" << llendl;
-        stopProxy();
-        return SOCKS_UDP_FWD_NOT_GRANTED;
-    }
-
-    mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
-    mUDPProxy.setAddress(proxy.getAddress());
-    // All good now we have been given the UDP port to send requests that need forwarding.
-    llinfos << "Socks 5 UDP proxy connected on " << mUDPProxy << llendl;
-    return SOCKS_OK;
+	int 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     = mAuthMethodSelected; // send only the selected method
+
+	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request_t), (char*)&socks_auth_response, sizeof(socks_auth_response_t));
+	if (result != 0)
+	{
+		llwarns << "Socks authentication request failed, error on TCP control channel : " << result << llendl;
+		stopProxy();
+		return SOCKS_CONNECT_ERROR;
+	}
+
+	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
+	{
+		llwarns << "Socks5 server refused all our authentication methods" << llendl;
+		stopProxy();
+		return SOCKS_NOT_ACCEPTABLE;
+	}
+
+	// SOCKS5 USERNAME/PASSWORD authentication
+	if (socks_auth_response.method == METHOD_PASSWORD)
+	{
+		// The server has requested a username/password combination
+		U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
+		// char * password_auth = (char *)malloc(request_size);
+		char * password_auth = new char[request_size];
+		password_auth[0] = 0x01;
+		password_auth[1] = mSocksUsername.size();
+		memcpy(&password_auth[2], mSocksUsername.c_str(), mSocksUsername.size());
+		password_auth[mSocksUsername.size()+2] = mSocksPassword.size();
+		memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
+
+		authmethod_password_reply_t password_reply;
+
+		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
+		delete[] password_auth;
+
+		if (result != 0)
+		{
+			llwarns << "Socks authentication failed, error on TCP control channel : " << result << llendl;
+			stopProxy();
+			return SOCKS_CONNECT_ERROR;
+		}
+
+		if (password_reply.status != AUTH_SUCCESS)
+		{
+			llwarns << "Socks authentication failed" << llendl;
+			stopProxy();
+			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.flag    = FIELD_RESERVED;
+	connect_request.atype   = ADDRESS_IPV4;
+	connect_request.address = 0; // 0.0.0.0 We are not fussy about address
+	// UDP is promiscuous receive for our protocol
+	connect_request.port    = 0; // Port must be 0 if you ever want to connect via NAT and your router does port rewrite for you
+
+	result = tcp_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
+	if (result != 0)
+	{
+		llwarns << "Socks connect request failed, error on TCP control channel : " << result << llendl;
+		stopProxy();
+		return SOCKS_CONNECT_ERROR;
+	}
+
+	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
+	{
+		//Something went wrong
+		llwarns << "Connection to SOCKS5 server failed, UDP forward request not granted" << llendl;
+		stopProxy();
+		return SOCKS_UDP_FWD_NOT_GRANTED;
+	}
+
+	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
+	mUDPProxy.setAddress(proxy.getAddress());
+	// All good now we have been given the UDP port to send requests that need forwarding.
+	llinfos << "Socks 5 UDP proxy connected on " << mUDPProxy << llendl;
+	return SOCKS_OK;
 }
 
 int LLSocks::startProxy(LLHost proxy, U32 message_port)
 {
-    int status;
-
-    mTCPProxy   = proxy;
-
-    if (hProxyControlChannel)
-    {
-        tcp_close_channel(hProxyControlChannel);
-        hProxyControlChannel=0;
-    }
-
-    hProxyControlChannel = tcp_open_channel(proxy);	
-    if (hProxyControlChannel == -1)
-    {
-        return SOCKS_HOST_CONNECT_FAILED;
-    }
-
-    status = proxyHandshake(proxy, message_port);	
-    if (status == SOCKS_OK)
-    {
-        sUdpProxyEnabled=true;
-    }
-    return status;
+	int status;
+
+	mTCPProxy = proxy;
+
+	if (mProxyControlChannel)
+	{
+		tcp_close_channel(mProxyControlChannel);
+		mProxyControlChannel = 0;
+	}
+
+	mProxyControlChannel = tcp_open_channel(proxy);
+	if (mProxyControlChannel == -1)
+	{
+		return SOCKS_HOST_CONNECT_FAILED;
+	}
+
+	status = proxyHandshake(proxy, message_port);
+	if (status == SOCKS_OK)
+	{
+		sUdpProxyEnabled = true;
+	}
+	return status;
 }
 
 int LLSocks::startProxy(std::string host, U32 port)
 {
-        mTCPProxy.setHostByName(host);
-        mTCPProxy.setPort(port);
-        return startProxy(mTCPProxy, (U32)gMessageSystem->mPort);
+	mTCPProxy.setHostByName(host);
+	mTCPProxy.setPort(port);
+	return startProxy(mTCPProxy, (U32)gMessageSystem->mPort);
 }
 
 void LLSocks::stopProxy()
 {
-    sUdpProxyEnabled = false;
-
-    // If the Socks proxy is requested to stop and we are using that for http as well
-    // then we must shut down any http proxy operations. But it is allowable if web 
-    // proxy is being used to continue proxying http.
-
-    if(LLPROXY_SOCKS == mProxyType)
-    {
-        sHttpProxyEnabled = false;
-    }
-
-    if (hProxyControlChannel)
-    {
-        tcp_close_channel(hProxyControlChannel);
-        hProxyControlChannel=0;
-    }
+	sUdpProxyEnabled = false;
+
+	// If the Socks proxy is requested to stop and we are using that for http as well
+	// then we must shut down any http proxy operations. But it is allowable if web
+	// proxy is being used to continue proxying http.
+
+	if(LLPROXY_SOCKS == mProxyType)
+	{
+		sHttpProxyEnabled = false;
+	}
+
+	if (mProxyControlChannel)
+	{
+		tcp_close_channel(mProxyControlChannel);
+		mProxyControlChannel = 0;
+	}
 }
 
 void LLSocks::setAuthNone()
 {
-    mAuthMethodSelected = METHOD_NOAUTH;
+	mAuthMethodSelected = METHOD_NOAUTH;
 }
 
 void LLSocks::setAuthPassword(std::string username, std::string password)
 {
-    mAuthMethodSelected = METHOD_PASSWORD;
-    mSocksUsername      = username;
-    mSocksPassword      = password;
+	mAuthMethodSelected = METHOD_PASSWORD;
+	mSocksUsername      = username;
+	mSocksPassword      = password;
 }
 
-void LLSocks::EnableHttpProxy(LLHost httpHost, LLHttpProxyType type)
+void LLSocks::enableHttpProxy(LLHost httpHost, LLHttpProxyType type)
 { 
-    sHttpProxyEnabled = true; 
-    mHTTPProxy        = httpHost; 
-    mProxyType        = type;
+	sHttpProxyEnabled = true;
+	mHTTPProxy        = httpHost;
+	mProxyType        = type;
 }
diff --git a/indra/llmessage/llsocks5.h b/indra/llmessage/llsocks5.h
index a78acb8b23..171a933d32 100644
--- a/indra/llmessage/llsocks5.h
+++ b/indra/llmessage/llsocks5.h
@@ -35,12 +35,12 @@
 // Error codes returned from the StartProxy method
 
 #define SOCKS_OK 0
-#define SOCKS_CONNECT_ERROR -1
-#define SOCKS_NOT_PERMITTED -2
-#define SOCKS_NOT_ACCEPTABLE -3
-#define SOCKS_AUTH_FAIL -4
-#define SOCKS_UDP_FWD_NOT_GRANTED -5
-#define SOCKS_HOST_CONNECT_FAILED -6
+#define SOCKS_CONNECT_ERROR (-1)
+#define SOCKS_NOT_PERMITTED (-2)
+#define SOCKS_NOT_ACCEPTABLE (-3)
+#define SOCKS_AUTH_FAIL (-4)
+#define SOCKS_UDP_FWD_NOT_GRANTED (-5)
+#define SOCKS_HOST_CONNECT_FAILED (-6)
 
 #ifndef MAXHOSTNAMELEN
 #define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
@@ -56,8 +56,8 @@
 // Lets just use our own ipv4 struct rather than dragging in system
 // specific headers
 union ipv4_address_t {
-    unsigned char octects[4];
-    U32 addr32;
+	unsigned char octets[4];
+	U32 addr32;
 };
 
 // Socks 5 control channel commands
@@ -86,53 +86,53 @@ union ipv4_address_t {
 
 // Socks5 command packet
 struct socks_command_request_t {
-    unsigned char version;
-    unsigned char command;
-    unsigned char flag;
-    unsigned char atype;
-    U32           address;
-    U16           port;
+	unsigned char version;
+	unsigned char command;
+	unsigned char flag;
+	unsigned char atype;
+	U32           address;
+	U16           port;
 };
 
 // Standard socks5 reply packet
 struct socks_command_response_t {
-    unsigned char version;
-    unsigned char reply;
-    unsigned char flag;
-    unsigned char atype;
-    unsigned char add_bytes[4];
-    U16           port;
+	unsigned char version;
+	unsigned char reply;
+	unsigned char flag;
+	unsigned char atype;
+	unsigned char add_bytes[4];
+	U16           port;
 };
 
-#define AUTH_NOT_ACCEPTABLE 0xFF // reply if prefered methods are not avaiable
-#define AUTH_SUCCESS        0x00 // reply if authentication successfull
+#define AUTH_NOT_ACCEPTABLE 0xFF // reply if preferred methods are not available
+#define AUTH_SUCCESS        0x00 // reply if authentication successful
 
 // socks 5 authentication request, stating which methods the client supports
 struct socks_auth_request_t {
-    unsigned char version;
-    unsigned char num_methods;
-    unsigned char methods; // We are only using a single method currently
+	unsigned char version;
+	unsigned char num_methods;
+	unsigned char methods; // We are only using a single method currently
 };
 
 // socks 5 authentication response packet, stating server prefered method
 struct socks_auth_response_t {
-    unsigned char version;
-    unsigned char method;
+	unsigned char version;
+	unsigned char method;
 };
 
 // socks 5 password reply packet
 struct authmethod_password_reply_t {
-    unsigned char version;
-    unsigned char status;
+	unsigned char version;
+	unsigned char status;
 };
 
 // socks 5 UDP packet header
 struct proxywrap_t {
-    U16 rsv;
-    U8  frag;
-    U8  atype;
-    U32 addr;
-    U16 port;
+	U16 rsv;
+	U8  frag;
+	U8  atype;
+	U32 addr;
+	U16 port;
 };
 
 #pragma pack(pop) /* restore original alignment from stack */
@@ -141,97 +141,97 @@ struct proxywrap_t {
 // Currently selected http proxy type
 enum LLHttpProxyType
 {
-    LLPROXY_SOCKS = 0,
-    LLPROXY_HTTP  = 1
+	LLPROXY_SOCKS = 0,
+	LLPROXY_HTTP  = 1
 };
 
 // Auth types
 enum LLSocks5AuthType
 {
-    METHOD_NOAUTH   = 0x00,	// Client supports no auth
-    METHOD_GSSAPI   = 0x01,	// Client supports GSSAPI (Not currently supported)
-    METHOD_PASSWORD = 0x02 	// Client supports username/password
+	METHOD_NOAUTH   = 0x00,	// Client supports no auth
+	METHOD_GSSAPI   = 0x01,	// Client supports GSSAPI (Not currently supported)
+	METHOD_PASSWORD = 0x02 	// Client supports username/password
 };
 
 class LLSocks: public LLSingleton<LLSocks>
 {
 public:
-    LLSocks();
+	LLSocks();
 
-    // Start a connection to the socks 5 proxy
-    int startProxy(std::string host,U32 port);
-    int startProxy(LLHost proxy,U32 messagePort);
+	// Start a connection to the socks 5 proxy
+	int startProxy(std::string host,U32 port);
+	int startProxy(LLHost proxy,U32 messagePort);
 
-    // Disconnect and clean up any connection to the socks 5 proxy
-    void stopProxy();
+	// Disconnect and clean up any connection to the socks 5 proxy
+	void stopProxy();
 
-    // Set up to use Password auth when connecting to the socks proxy
-    void setAuthPassword(std::string username,std::string password);
+	// Set up to use Password auth when connecting to the socks proxy
+	void setAuthPassword(std::string username,std::string password);
 
-    // Set up to use No Auth when connecting to the socks proxy;
-    void setAuthNone();
+	// Set up to use No Auth when connecting to the socks proxy
+	void setAuthNone();
 
-    // get the currently selected auth method
-    LLSocks5AuthType getSelectedAuthMethod() { return mAuthMethodSelected; };
+	// get the currently selected auth method
+	LLSocks5AuthType getSelectedAuthMethod() const { return mAuthMethodSelected; }
 
-    // static check for enabled status for UDP packets
-    static bool isEnabled(){return sUdpProxyEnabled;};
+	// static check for enabled status for UDP packets
+	static bool isEnabled() { return sUdpProxyEnabled; }
 
-    // static check for enabled status for http packets
-    static bool isHttpProxyEnabled(){return sHttpProxyEnabled;};
+	// static check for enabled status for http packets
+	static bool isHttpProxyEnabled() { return sHttpProxyEnabled; }
 
-    // Proxy http packets via httpHost, which can be a Socks5 or a http proxy
-    // as specified in type
-    void EnableHttpProxy(LLHost httpHost,LLHttpProxyType type);
+	// Proxy http packets via httpHost, which can be a Socks5 or a http proxy
+	// as specified in type
+	void enableHttpProxy(LLHost httpHost, LLHttpProxyType type);
 
-    // Stop proxying http packets
-    void DisableHttpProxy() {sHttpProxyEnabled = false;};
+	// Stop proxying http packets
+	void disableHttpProxy() { sHttpProxyEnabled = false; };
 
-    // get the UDP proxy address and port
-    LLHost getUDPProxy(){return mUDPProxy;};
+	// Get the UDP proxy address and port
+	LLHost getUDPProxy() const { return mUDPProxy; }
 
-    // get the socks 5 TCP control channel address and port
-    LLHost getTCPProxy(){return mTCPProxy;};
+	// Get the socks 5 TCP control channel address and port
+	LLHost getTCPProxy() const { return mTCPProxy; }
 
-    //get the http proxy address and port
-    LLHost getHTTPProxy(){return mHTTPProxy;};
+	// Get the http proxy address and port
+	LLHost getHTTPProxy() const { return mHTTPProxy; }
 
-    // get the currently selected http proxy type
-    LLHttpProxyType getHttpProxyType(){return mProxyType;};
+	// Get the currently selected http proxy type
+	LLHttpProxyType getHttpProxyType() const { return mProxyType; }
 
-    //Get the username password in a curl compatible format
-    std::string getProxyUserPwd(){ return (mSocksUsername + ":" + mSocksPassword);};
+	// Get the username password in a curl compatible format
+	std::string getProxyUserPwd() const { return (mSocksUsername + ":" + mSocksPassword); }
 
 private:
 
-    // Open a communication channel to the socks5 proxy proxy, at port messagePort
-    int proxyHandshake(LLHost proxy,U32 messagePort);
+	// Open a communication channel to the socks5 proxy proxy, at port messagePort
+	int proxyHandshake(LLHost proxy,U32 messagePort);
 
-    // socket handle to proxy tcp control channel
-    S32 hProxyControlChannel;
+	// socket handle to proxy tcp control channel
+	S32 mProxyControlChannel;
 
-    // is the UDP proxy enabled
-    static bool sUdpProxyEnabled;
-    // is the http proxy enabled
-    static bool sHttpProxyEnabled;
+	// is the UDP proxy enabled?
+	static bool sUdpProxyEnabled;
+	// is the http proxy enabled?
+	static bool sHttpProxyEnabled;
 
-    // currently selected http proxy type
-    LLHttpProxyType mProxyType;
+	// currently selected http proxy type
+	LLHttpProxyType mProxyType;
 
-    // UDP proxy address and port
-    LLHost mUDPProxy;
-    // TCP Proxy control channel address and port
-    LLHost mTCPProxy;
-    // HTTP proxy address and port
-    LLHost mHTTPProxy;
+	// UDP proxy address and port
+	LLHost mUDPProxy;
+	// TCP Proxy control channel address and port
+	LLHost mTCPProxy;
+	// HTTP proxy address and port
+	LLHost mHTTPProxy;
 
-    // socks 5 auth method selected
-    LLSocks5AuthType mAuthMethodSelected;
+	// socks 5 auth method selected
+	LLSocks5AuthType mAuthMethodSelected;
 
-    // socks 5 username
-    std::string mSocksUsername;
-    // socks 5 password
-    std::string mSocksPassword;
+	// socks 5 username
+	std::string mSocksUsername;
+	// socks 5 password
+	std::string mSocksPassword;
 };
 
 #endif
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index ab5c1950c6..a51d80ff48 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -175,7 +175,7 @@ U32 ip_string_to_u32(const char* ip_string)
 	// use wildcard addresses. -Ambroff
 	U32 ip = inet_addr(ip_string);
 	if (ip == INADDR_NONE 
-	    && strncmp(ip_string, BROADCAST_ADDRESS_STRING, MAXADDRSTR) != 0)
+			&& strncmp(ip_string, BROADCAST_ADDRESS_STRING, MAXADDRSTR) != 0)
 	{
 		llwarns << "ip_string_to_u32() failed, Error: Invalid IP string '" << ip_string << "'" << llendl;
 		return INVALID_HOST_IP_ADDRESS;
@@ -220,9 +220,10 @@ S32 tcp_open_channel(LLHost host)
 
 	S32 handle;
 	handle = socket(AF_INET, SOCK_STREAM, 0);
-	if (!handle)
+	if (INVALID_SOCKET == handle)
 	{
-		llwarns << "Error opening TCP control socket, socket() returned " << handle << llendl;
+		llwarns << "Error opening TCP control socket, socket() returned "
+				<< WSAGetLastError() << ", " << DecodeError(WSAGetLastError()) << llendl;
 		return -1;
 	}
 
@@ -232,15 +233,15 @@ S32 tcp_open_channel(LLHost host)
 	address.sin_addr.s_addr = host.getAddress();
 
 	// Non blocking 
-	WSAEVENT hEvent=WSACreateEvent();
+	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
+	// Wait for 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
+	WaitForSingleObject(hEvent, 1000 * 5); // 5 seconds time out
 
 	WSANETWORKEVENTS netevents;
-	WSAEnumNetworkEvents(handle,hEvent,&netevents);
+	WSAEnumNetworkEvents(handle, hEvent, &netevents);
 
 	// Check the async event status to see if we connected
 	if ((netevents.lNetworkEvents & FD_CONNECT) == FD_CONNECT)
@@ -249,6 +250,7 @@ S32 tcp_open_channel(LLHost host)
 		{
 			llwarns << "Unable to open TCP channel, WSA returned an error code of " << netevents.iErrorCode[FD_CONNECT_BIT] << llendl;
 			WSACloseEvent(hEvent);
+			tcp_close_channel(handle);
 			return -1;
 		}
 
@@ -264,6 +266,7 @@ S32 tcp_open_channel(LLHost host)
 	}
 
 	llwarns << "Unable to open TCP channel, Timeout is the host up?" << netevents.iErrorCode[FD_CONNECT_BIT] << llendl;
+	tcp_close_channel(handle);
 	return -1;
 }
 
@@ -277,7 +280,7 @@ void tcp_close_channel(S32 handle)
 S32 start_net(S32& socket_out, int& nPort) 
 {			
 	// Create socket, make non-blocking
-    // Init WinSock 
+	// Init WinSock
 	int nRet;
 	int hSocket;
 
@@ -286,7 +289,7 @@ S32 start_net(S32& socket_out, int& nPort)
 	int buff_size = 4;
  
 	// Initialize windows specific stuff
-	if(WSAStartup(0x0202, &stWSAData))
+	if (WSAStartup(0x0202, &stWSAData))
 	{
 		S32 err = WSAGetLastError();
 		WSACleanup();
@@ -295,8 +298,8 @@ S32 start_net(S32& socket_out, int& nPort)
 	}
 
 	// Get a datagram socket
-    hSocket = (int)socket(AF_INET, SOCK_DGRAM, 0);
-    if (hSocket == INVALID_SOCKET)
+	hSocket = (int)socket(AF_INET, SOCK_DGRAM, 0);
+	if (hSocket == INVALID_SOCKET)
 	{
 		S32 err = WSAGetLastError();
 		WSACleanup();
@@ -389,7 +392,7 @@ S32 start_net(S32& socket_out, int& nPort)
 	//  Setup a destination address
 	stDstAddr.sin_family =      AF_INET;
 	stDstAddr.sin_addr.s_addr = INVALID_HOST_IP_ADDRESS;
-    stDstAddr.sin_port =        htons(nPort);
+	stDstAddr.sin_port =        htons(nPort);
 
 	socket_out = hSocket;
 	return 0;
@@ -492,9 +495,9 @@ S32 tcp_open_channel(LLHost host)
 {
 	S32 handle;
 	handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-	if (!handle)
+	if (-1 == handle)
 	{
-		llwarns << "Error opening TCP control socket, socket() returned " << handle << llendl;
+		llwarns << "Error opening TCP control socket, socket() returned " << handle << "error code: " << errno << llendl;
 		return -1;
 	}
 
@@ -511,6 +514,7 @@ S32 tcp_open_channel(LLHost host)
 	if (error && (errno != EINPROGRESS))
 	{
 			llwarns << "Unable to open TCP channel, error code: " << errno << llendl;
+			tcp_close_channel(handle);
 			return -1;
 	}
 
@@ -521,12 +525,13 @@ S32 tcp_open_channel(LLHost host)
 	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);	
+	// See if we have connected or time out after 5 seconds
+	S32 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;
+			tcp_close_channel(handle);
 			return -1;
 	}
 
@@ -549,10 +554,10 @@ S32 start_net(S32& socket_out, int& nPort)
 	int rec_size = RECEIVE_BUFFER_SIZE;
 
 	socklen_t buff_size = 4;
-    
+
 	//  Create socket
-    hSocket = socket(AF_INET, SOCK_DGRAM, 0);
-    if (hSocket < 0)
+	hSocket = socket(AF_INET, SOCK_DGRAM, 0);
+	if (hSocket < 0)
 	{
 		llwarns << "socket() failed" << llendl;
 		return 1;
@@ -585,7 +590,7 @@ S32 start_net(S32& socket_out, int& nPort)
 	}
 	else
 	{
-	    // Name the socket (assign the local port number to receive on)
+		// Name the socket (assign the local port number to receive on)
 		stLclAddr.sin_family      = AF_INET;
 		stLclAddr.sin_addr.s_addr = htonl(INADDR_ANY);
 		stLclAddr.sin_port        = htons(nPort);
@@ -630,7 +635,7 @@ S32 start_net(S32& socket_out, int& nPort)
 		nPort = attempt_port;
 	}
 	// Set socket to be non-blocking
- 	fcntl(hSocket, F_SETFL, O_NONBLOCK);
+	fcntl(hSocket, F_SETFL, O_NONBLOCK);
 	// set a large receive buffer
 	nRet = setsockopt(hSocket, SOL_SOCKET, SO_RCVBUF, (char *)&rec_size, buff_size);
 	if (nRet)
@@ -666,8 +671,8 @@ S32 start_net(S32& socket_out, int& nPort)
 	//  Setup a destination address
 	char achMCAddr[MAXADDRSTR] = "127.0.0.1";	/* Flawfinder: ignore */ 
 	stDstAddr.sin_family =      AF_INET;
-        stDstAddr.sin_addr.s_addr = ip_string_to_u32(achMCAddr);
-        stDstAddr.sin_port =        htons(nPort);
+	stDstAddr.sin_addr.s_addr = ip_string_to_u32(achMCAddr);
+	stDstAddr.sin_port =        htons(nPort);
 
 	socket_out = hSocket;
 	return 0;
@@ -693,7 +698,7 @@ static int recvfrom_destip( int socket, void *buf, int len, struct sockaddr *fro
 	iov[0].iov_base = buf;
 	iov[0].iov_len = len;
 
-	memset( &msg, 0, sizeof msg );
+	memset(&msg, 0, sizeof msg);
 	msg.msg_name = from;
 	msg.msg_namelen = *fromlen;
 	msg.msg_iov = iov;
@@ -701,14 +706,14 @@ static int recvfrom_destip( int socket, void *buf, int len, struct sockaddr *fro
 	msg.msg_control = &cmsg;
 	msg.msg_controllen = sizeof(cmsg);
 
-	size = recvmsg( socket, &msg, 0 );
+	size = recvmsg(socket, &msg, 0);
 
-	if( size == -1 )
+	if (size == -1)
 	{
 		return -1;
 	}
 
-	for( cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL; cmsgptr = CMSG_NXTHDR( &msg, cmsgptr ) )
+	for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL; cmsgptr = CMSG_NXTHDR( &msg, cmsgptr))
 	{
 		if( cmsgptr->cmsg_level == SOL_IP && cmsgptr->cmsg_type == IP_PKTINFO )
 		{
@@ -806,7 +811,7 @@ BOOL send_packet(int hSocket, const char * sendBuffer, int size, U32 recipient,
 			}
 		}
 	}
-	while ( resend && send_attempts < 3);
+	while (resend && send_attempts < 3);
 
 	if (send_attempts >= 3)
 	{
diff --git a/indra/llmessage/net.h b/indra/llmessage/net.h
index d93ed20c98..047e8ce646 100644
--- a/indra/llmessage/net.h
+++ b/indra/llmessage/net.h
@@ -46,10 +46,10 @@ S32		receive_packet(int hSocket, char * receiveBuffer);
 BOOL	send_packet(int hSocket, const char *sendBuffer, int size, U32 recipient, int nPort);	// Returns TRUE on success.
 
 //void	get_sender(char * tmp);
-LLHost  get_sender();
+LLHost	get_sender();
 U32		get_sender_port();
 U32		get_sender_ip(void);
-LLHost  get_receiving_interface();
+LLHost	get_receiving_interface();
 U32		get_receiving_interface_ip(void);
 
 // Some helpful tcp functions added for the socks 5 proxy support
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index b49026de38..dfc3fe1fc7 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -343,7 +343,7 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key)
 	mCommitCallbackRegistrar.add("Pref.getUIColor",				boost::bind(&LLFloaterPreference::getUIColor, this ,_1, _2));
 	mCommitCallbackRegistrar.add("Pref.MaturitySettings",		boost::bind(&LLFloaterPreference::onChangeMaturity, this));
 	mCommitCallbackRegistrar.add("Pref.BlockList",				boost::bind(&LLFloaterPreference::onClickBlockList, this));
-    mCommitCallbackRegistrar.add("Pref.Proxy",                    boost::bind(&LLFloaterPreference::onClickProxySettings, this));
+	mCommitCallbackRegistrar.add("Pref.Proxy",                    boost::bind(&LLFloaterPreference::onClickProxySettings, this));
 	
 	sSkin = gSavedSettings.getString("SkinCurrent");
 
@@ -1545,7 +1545,7 @@ void LLFloaterPreference::updateDoubleClickSettings()
 
 void LLFloaterPreference::onClickProxySettings()
 {
-    LLFloaterReg::showInstance("prefs_proxy");
+	LLFloaterReg::showInstance("prefs_proxy");
 }
 
 void LLFloaterPreference::updateDoubleClickControls()
@@ -1916,16 +1916,13 @@ void LLPanelPreferenceGraphics::setHardwareDefaults()
 	LLPanelPreference::setHardwareDefaults();
 }
 
-
-/* ------------------------------------------------------------ */
-
 LLFloaterPreferenceProxy::LLFloaterPreferenceProxy(const LLSD& key)
-    : LLFloater(key),
-    mSocksSettingsDirty(false)
+	: LLFloater(key),
+	  mSocksSettingsDirty(false)
 {
-    mCommitCallbackRegistrar.add("Proxy.OK",                boost::bind(&LLFloaterPreferenceProxy::onBtnOk, this));
-    mCommitCallbackRegistrar.add("Proxy.Cancel",            boost::bind(&LLFloaterPreferenceProxy::onBtnCancel, this));
-    mCommitCallbackRegistrar.add("Proxy.Change",            boost::bind(&LLFloaterPreferenceProxy::onChangeSocksSettings, this));
+	mCommitCallbackRegistrar.add("Proxy.OK",                boost::bind(&LLFloaterPreferenceProxy::onBtnOk, this));
+	mCommitCallbackRegistrar.add("Proxy.Cancel",            boost::bind(&LLFloaterPreferenceProxy::onBtnCancel, this));
+	mCommitCallbackRegistrar.add("Proxy.Change",            boost::bind(&LLFloaterPreferenceProxy::onChangeSocksSettings, this));
 }
 
 LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
@@ -1934,142 +1931,142 @@ LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
 
 BOOL LLFloaterPreferenceProxy::postBuild()
 {
-    LLLineEditor* edit = getChild<LLLineEditor>("socks_password_editor");
-    if (edit) edit->setDrawAsterixes(TRUE);
+	LLLineEditor* edit = getChild<LLLineEditor>("socks_password_editor");
+	if (edit) edit->setDrawAsterixes(TRUE);
 
-    LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
-    if(socksAuth->getSelectedValue().asString() == "None")
-    {
-        getChild<LLLineEditor>("socks5_username")->setEnabled(false);
-        getChild<LLLineEditor>("socks5_password")->setEnabled(false);
-    }
+	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+	if(socksAuth->getSelectedValue().asString() == "None")
+	{
+		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
+		getChild<LLLineEditor>("socks5_password")->setEnabled(false);
+	}
 
-    center();
-    return TRUE;
+	center();
+	return TRUE;
 }
 
 void LLFloaterPreferenceProxy::onOpen(const LLSD& key)
 {
-    saveSettings();
+	saveSettings();
 }
 
 void LLFloaterPreferenceProxy::onClose(bool app_quitting)
 {
-    if(mSocksSettingsDirty)
-    {
+	if(mSocksSettingsDirty)
+	{
 
-        // If the user plays with the Socks proxy settings after login, its only fair we let them know
-        // it will not be updated untill next restart.
-        if(LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
-        {        
-            if(this->mSocksSettingsDirty == true )
-            {
-                LLNotifications::instance().add("ChangeSocks5Settings",LLSD(),LLSD());
-                mSocksSettingsDirty = false; // we have notified the user now be quiet again
-            }
-        }
-    }
+		// If the user plays with the Socks proxy settings after login, it's only fair we let them know
+		// it will not be updated until next restart.
+		if(LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
+		{
+			if(this->mSocksSettingsDirty == true )
+			{
+				LLNotifications::instance().add("ChangeSocks5Settings",LLSD(),LLSD());
+				mSocksSettingsDirty = false; // we have notified the user now be quiet again
+			}
+		}
+	}
 }
 
 void LLFloaterPreferenceProxy::saveSettings()
 {
-    // Save the value of all controls in the hierarchy
-    mSavedValues.clear();
-    std::list<LLView*> view_stack;
-    view_stack.push_back(this);
-    while(!view_stack.empty())
-    {
-        // Process view on top of the stack
-        LLView* curview = view_stack.front();
-        view_stack.pop_front();
-
-        LLUICtrl* ctrl = dynamic_cast<LLUICtrl*>(curview);
-        if (ctrl)
-        {
-            LLControlVariable* control = ctrl->getControlVariable();
-            if (control)
-            {
-                mSavedValues[control] = control->getValue();
-            }
-        }
-                    
-        // Push children onto the end of the work stack
-        for (child_list_t::const_iterator iter = curview->getChildList()->begin();
-             iter != curview->getChildList()->end(); ++iter)
-        {
-            view_stack.push_back(*iter);
-        }
-    }    
+	// Save the value of all controls in the hierarchy
+	mSavedValues.clear();
+	std::list<LLView*> view_stack;
+	view_stack.push_back(this);
+	while(!view_stack.empty())
+	{
+		// Process view on top of the stack
+		LLView* curview = view_stack.front();
+		view_stack.pop_front();
+
+		LLUICtrl* ctrl = dynamic_cast<LLUICtrl*>(curview);
+		if (ctrl)
+		{
+			LLControlVariable* control = ctrl->getControlVariable();
+			if (control)
+			{
+				mSavedValues[control] = control->getValue();
+			}
+		}
+
+		// Push children onto the end of the work stack
+		for (child_list_t::const_iterator iter = curview->getChildList()->begin();
+				iter != curview->getChildList()->end(); ++iter)
+		{
+			view_stack.push_back(*iter);
+		}
+	}
 
 }
 
 void LLFloaterPreferenceProxy::onBtnOk()
 {
-    // commit any outstanding text entry
-    if (hasFocus())
-    {
-        LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
-        if (cur_focus && cur_focus->acceptsTextInput())
-        {
-            cur_focus->onCommit();
-        }
-    }
-    closeFloater(false);
+	// commit any outstanding text entry
+	if (hasFocus())
+	{
+		LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+		if (cur_focus && cur_focus->acceptsTextInput())
+		{
+			cur_focus->onCommit();
+		}
+	}
+	closeFloater(false);
 }
 
 void LLFloaterPreferenceProxy::onBtnCancel()
 {
-    if (hasFocus())
-    {
-        LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
-        if (cur_focus && cur_focus->acceptsTextInput())
-        {
-            cur_focus->onCommit();
-        }
-        refresh();
-    }
-    
-    cancel();
-    
+	if (hasFocus())
+	{
+		LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+		if (cur_focus && cur_focus->acceptsTextInput())
+		{
+			cur_focus->onCommit();
+		}
+		refresh();
+	}
+
+	cancel();
+
 }
 void LLFloaterPreferenceProxy::cancel()
 {
 
-    for (control_values_map_t::iterator iter =  mSavedValues.begin();
-         iter !=  mSavedValues.end(); ++iter)
-    {
-        LLControlVariable* control = iter->first;
-        LLSD ctrl_value = iter->second;
-        control->set(ctrl_value);
-    }
-    
-    closeFloater();
+	for (control_values_map_t::iterator iter =  mSavedValues.begin();
+			iter !=  mSavedValues.end(); ++iter)
+	{
+		LLControlVariable* control = iter->first;
+		LLSD ctrl_value = iter->second;
+		control->set(ctrl_value);
+	}
+
+	closeFloater();
 }
 
 void LLFloaterPreferenceProxy::onChangeSocksSettings() 
 {
-    mSocksSettingsDirty = true; 
+	mSocksSettingsDirty = true;
 
-    LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
-    if(socksAuth->getSelectedValue().asString() == "None")
-    {
-        getChild<LLLineEditor>("socks5_username")->setEnabled(false);
-        getChild<LLLineEditor>("socks5_password")->setEnabled(false);
-    }
-    else
-    {
-        getChild<LLLineEditor>("socks5_username")->setEnabled(true);
-        getChild<LLLineEditor>("socks5_password")->setEnabled(true);
-    }
+	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+	if(socksAuth->getSelectedValue().asString() == "None")
+	{
+		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
+		getChild<LLLineEditor>("socks5_password")->setEnabled(false);
+	}
+	else
+	{
+		getChild<LLLineEditor>("socks5_username")->setEnabled(true);
+		getChild<LLLineEditor>("socks5_password")->setEnabled(true);
+	}
 
-    //Check for invalid states for the other http proxy radio
-    LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
-    if( (otherHttpProxy->getSelectedValue().asString() == "Socks" && 
-        getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
-        otherHttpProxy->getSelectedValue().asString() == "Web" && 
-        getChild<LLCheckBoxCtrl>("web_proxy_enabled")->get() == FALSE ) )
-    {    
-        otherHttpProxy->selectFirstItem();
-    }
+	//Check for invalid states for the other http proxy radio
+	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
+	if( (otherHttpProxy->getSelectedValue().asString() == "Socks" &&
+			getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
+					otherHttpProxy->getSelectedValue().asString() == "Web" &&
+					getChild<LLCheckBoxCtrl>("web_proxy_enabled")->get() == FALSE ) )
+	{
+		otherHttpProxy->selectFirstItem();
+	}
 
-};
\ No newline at end of file
+};
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index d54c5b177a..6d94a5454e 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2770,18 +2770,18 @@ bool LLStartUp::handleSocksProxy(bool reportOK)
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
 		httpHost.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		LLSocks::getInstance()->EnableHttpProxy(httpHost,LLPROXY_HTTP);
+		LLSocks::getInstance()->enableHttpProxy(httpHost,LLPROXY_HTTP);
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
 		httpHost.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		LLSocks::getInstance()->EnableHttpProxy(httpHost,LLPROXY_SOCKS);
+		LLSocks::getInstance()->enableHttpProxy(httpHost,LLPROXY_SOCKS);
 	}
 	else
 	{
-		LLSocks::getInstance()->DisableHttpProxy();
+		LLSocks::getInstance()->disableHttpProxy();
 	}
 	
 	bool use_socks_proxy = gSavedSettings.getBOOL("Socks5ProxyEnabled");
@@ -2843,7 +2843,7 @@ bool LLStartUp::handleSocksProxy(bool reportOK)
 	}
 	else
 	{
-		LLSocks::getInstance()->stopProxy(); //ensure no UDP proxy is running and its all cleaned up
+		LLSocks::getInstance()->stopProxy(); // ensure no UDP proxy is running and it's all cleaned up
 	}
 
 	return true;
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index b3d899c61a..87d2f780be 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -319,15 +319,17 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 		{
 			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			{
 				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd());
+			}
 		}
 		else
 		{
-		mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-	}
+			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+		}
 	}
 
-//	mCurlRequest->setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
+//	mCurlRequest->setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
 	mCurlRequest->setWriteCallback(&curlDownloadCallback, (void*)this);
 	BOOL vefifySSLCert = !gSavedSettings.getBOOL("NoVerifySSLCert");
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index bb9ade067b..9baa9a0e02 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -60,7 +60,7 @@
            layout="topleft"
            value="None"
            width="120"
-           tool_tip="Non web Http trafic should NOT be sent to any proxy."/>
+           tool_tip="Non web Http traffic should NOT be sent to any proxy."/>
           <radio_item
            height="16"
            label="Use Socks 5 Proxy"
-- 
cgit v1.2.3


From 20100ba38c6d3fa16ab11be2ed326ab0964c4c21 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 21 Jun 2011 17:09:12 -0400
Subject: Refactored SOCKS 5 handshake to use existing LLSocket class.

---
 indra/llmessage/llcurl.cpp            |   8 +-
 indra/llmessage/llsocks5.cpp          |  73 ++++++------
 indra/llmessage/llsocks5.h            | 129 ++++++++++----------
 indra/llmessage/net.cpp               | 219 +++++++++-------------------------
 indra/llmessage/net.h                 |  11 +-
 indra/newview/llstartup.cpp           |   6 +-
 indra/newview/llxmlrpctransaction.cpp |   4 +-
 7 files changed, 176 insertions(+), 274 deletions(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index 9c507517c7..32dd438e68 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -359,13 +359,13 @@ LLCurl::Easy* LLCurl::Easy::getEasy()
 	check_curl_code(result);
 
 	//Set the CURL options for either Socks or HTTP proxy
-	if (LLSocks::getInstance()->isHttpProxyEnabled())
+	if (LLSocks::getInstance()->isHTTPProxyEnabled())
 	{
 		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
 		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
 		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXY,address.c_str());
 		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYPORT,port);
-		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
@@ -557,13 +557,13 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	//setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
-	if (LLSocks::getInstance()->isHttpProxyEnabled())
+	if (LLSocks::getInstance()->isHTTPProxyEnabled())
 	{
 		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
 		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
 		setoptString(CURLOPT_PROXY, address.c_str());
 		setopt(CURLOPT_PROXYPORT, port);
-		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
diff --git a/indra/llmessage/llsocks5.cpp b/indra/llmessage/llsocks5.cpp
index 7eac27d4bb..27a31e35b3 100644
--- a/indra/llmessage/llsocks5.cpp
+++ b/indra/llmessage/llsocks5.cpp
@@ -1,6 +1,6 @@
 /**
  * @file llsocks5.cpp
- * @brief Socks 5 implementation
+ * @brief SOCKS 5 implementation
  *
  * $LicenseInfo:firstyear=2011&license=viewerlgpl$
  * Second Life Viewer Source Code
@@ -37,52 +37,51 @@
 // We want this to be static to avoid excessive indirection on every
 // incoming packet just to do a simple bool test. The getter for this
 // member is also static
-bool LLSocks::sUdpProxyEnabled;
-bool LLSocks::sHttpProxyEnabled;
+bool LLSocks::sUDPProxyEnabled;
+bool LLSocks::sHTTPProxyEnabled;
 
 LLSocks::LLSocks()
 {
-	sUdpProxyEnabled  = false;
-	sHttpProxyEnabled = false;
-	mProxyControlChannel = 0;
+	sUDPProxyEnabled  = false;
+	sHTTPProxyEnabled = false;
+	mProxyControlChannel.reset();
 	mProxyType = LLPROXY_SOCKS;
 }
 
-// Perform a Socks5 authentication and UDP association to the proxy
+// Perform a SOCKS 5 authentication and UDP association to the proxy
 // specified by proxy, and associate UDP port message_port
 int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 {
 	int result;
 
-	/* Socks 5 Auth request */
+	/* 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     = mAuthMethodSelected; // send only the selected method
+	socks_auth_request.version     = SOCKS_VERSION;       // SOCKS version 5
+	socks_auth_request.num_methods = 1;                   // Sending 1 method.
+	socks_auth_request.methods     = mAuthMethodSelected; // Send only the selected method.
 
 	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request_t), (char*)&socks_auth_response, sizeof(socks_auth_response_t));
 	if (result != 0)
 	{
-		llwarns << "Socks authentication request failed, error on TCP control channel : " << result << llendl;
+		llwarns << "SOCKS authentication request failed, error on TCP control channel : " << result << llendl;
 		stopProxy();
 		return SOCKS_CONNECT_ERROR;
 	}
 
 	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
 	{
-		llwarns << "Socks5 server refused all our authentication methods" << llendl;
+		llwarns << "SOCKS 5 server refused all our authentication methods" << llendl;
 		stopProxy();
 		return SOCKS_NOT_ACCEPTABLE;
 	}
 
-	// SOCKS5 USERNAME/PASSWORD authentication
+	// SOCKS 5 USERNAME/PASSWORD authentication
 	if (socks_auth_response.method == METHOD_PASSWORD)
 	{
 		// The server has requested a username/password combination
 		U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
-		// char * password_auth = (char *)malloc(request_size);
 		char * password_auth = new char[request_size];
 		password_auth[0] = 0x01;
 		password_auth[1] = mSocksUsername.size();
@@ -97,14 +96,14 @@ int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 
 		if (result != 0)
 		{
-			llwarns << "Socks authentication failed, error on TCP control channel : " << result << llendl;
+			llwarns << "SOCKS authentication failed, error on TCP control channel : " << result << llendl;
 			stopProxy();
 			return SOCKS_CONNECT_ERROR;
 		}
 
 		if (password_reply.status != AUTH_SUCCESS)
 		{
-			llwarns << "Socks authentication failed" << llendl;
+			llwarns << "SOCKS authentication failed" << llendl;
 			stopProxy();
 			return SOCKS_AUTH_FAIL;
 		}
@@ -115,18 +114,19 @@ int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 	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.flag    = FIELD_RESERVED;
-	connect_request.atype   = ADDRESS_IPV4;
-	connect_request.address = 0; // 0.0.0.0 We are not fussy about address
-	// UDP is promiscuous receive for our protocol
-	connect_request.port    = 0; // Port must be 0 if you ever want to connect via NAT and your router does port rewrite for you
+	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 possesion 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_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
 	if (result != 0)
 	{
-		llwarns << "Socks connect request failed, error on TCP control channel : " << result << llendl;
+		llwarns << "SOCKS connect request failed, error on TCP control channel : " << result << llendl;
 		stopProxy();
 		return SOCKS_CONNECT_ERROR;
 	}
@@ -134,7 +134,7 @@ int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
 	{
 		//Something went wrong
-		llwarns << "Connection to SOCKS5 server failed, UDP forward request not granted" << llendl;
+		llwarns << "Connection to SOCKS 5 server failed, UDP forward request not granted" << llendl;
 		stopProxy();
 		return SOCKS_UDP_FWD_NOT_GRANTED;
 	}
@@ -142,7 +142,7 @@ int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
 	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
 	mUDPProxy.setAddress(proxy.getAddress());
 	// All good now we have been given the UDP port to send requests that need forwarding.
-	llinfos << "Socks 5 UDP proxy connected on " << mUDPProxy << llendl;
+	llinfos << "SOCKS 5 UDP proxy connected on " << mUDPProxy << llendl;
 	return SOCKS_OK;
 }
 
@@ -155,19 +155,17 @@ int LLSocks::startProxy(LLHost proxy, U32 message_port)
 	if (mProxyControlChannel)
 	{
 		tcp_close_channel(mProxyControlChannel);
-		mProxyControlChannel = 0;
 	}
 
-	mProxyControlChannel = tcp_open_channel(proxy);
-	if (mProxyControlChannel == -1)
+	mProxyControlChannel = tcp_open_channel(mTCPProxy);
+	if (!mProxyControlChannel)
 	{
 		return SOCKS_HOST_CONNECT_FAILED;
 	}
-
 	status = proxyHandshake(proxy, message_port);
 	if (status == SOCKS_OK)
 	{
-		sUdpProxyEnabled = true;
+		sUDPProxyEnabled = true;
 	}
 	return status;
 }
@@ -181,21 +179,20 @@ int LLSocks::startProxy(std::string host, U32 port)
 
 void LLSocks::stopProxy()
 {
-	sUdpProxyEnabled = false;
+	sUDPProxyEnabled = false;
 
-	// If the Socks proxy is requested to stop and we are using that for http as well
+	// If the SOCKS proxy is requested to stop and we are using that for http as well
 	// then we must shut down any http proxy operations. But it is allowable if web
 	// proxy is being used to continue proxying http.
 
 	if(LLPROXY_SOCKS == mProxyType)
 	{
-		sHttpProxyEnabled = false;
+		sHTTPProxyEnabled = false;
 	}
 
 	if (mProxyControlChannel)
 	{
 		tcp_close_channel(mProxyControlChannel);
-		mProxyControlChannel = 0;
 	}
 }
 
@@ -211,9 +208,9 @@ void LLSocks::setAuthPassword(std::string username, std::string password)
 	mSocksPassword      = password;
 }
 
-void LLSocks::enableHttpProxy(LLHost httpHost, LLHttpProxyType type)
+void LLSocks::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 { 
-	sHttpProxyEnabled = true;
+	sHTTPProxyEnabled = true;
 	mHTTPProxy        = httpHost;
 	mProxyType        = type;
 }
diff --git a/indra/llmessage/llsocks5.h b/indra/llmessage/llsocks5.h
index 171a933d32..43a7c82fea 100644
--- a/indra/llmessage/llsocks5.h
+++ b/indra/llmessage/llsocks5.h
@@ -46,9 +46,9 @@
 #define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
 #endif
 
-#define SOCKS_VERSION 0x05 // we are using socks 5
+#define SOCKS_VERSION 0x05 // we are using SOCKS 5
 
-// socks 5 address/hostname types
+// SOCKS 5 address/hostname types
 #define ADDRESS_IPV4     0x01
 #define ADDRESS_HOSTNAME 0x03
 #define ADDRESS_IPV6     0x04
@@ -56,16 +56,16 @@
 // Lets just use our own ipv4 struct rather than dragging in system
 // specific headers
 union ipv4_address_t {
-	unsigned char octets[4];
-	U32 addr32;
+	U8		octets[4];
+	U32		addr32;
 };
 
-// Socks 5 control channel commands
+// SOCKS 5 control channel commands
 #define COMMAND_TCP_STREAM    0x01
 #define COMMAND_TCP_BIND      0x02
 #define COMMAND_UDP_ASSOCIATE 0x03
 
-// Socks 5 command replys
+// SOCKS 5 command replies
 #define REPLY_REQUEST_GRANTED     0x00
 #define REPLY_GENERAL_FAIL        0x01
 #define REPLY_RULESET_FAIL        0x02
@@ -78,61 +78,61 @@ union ipv4_address_t {
 
 #define FIELD_RESERVED 0x00
 
-// The standard socks5 request packet
+// The standard SOCKS 5 request packet
 // Push current alignment to stack and set alignment to 1 byte boundary
 // This enabled us to use structs directly to set up and receive network packets
 // into the correct fields, without fear of boundary alignment causing issues
 #pragma pack(push,1)
 
-// Socks5 command packet
+// SOCKS 5 command packet
 struct socks_command_request_t {
-	unsigned char version;
-	unsigned char command;
-	unsigned char flag;
-	unsigned char atype;
-	U32           address;
-	U16           port;
+	U8		version;
+	U8		command;
+	U8		reserved;
+	U8		atype;
+	U32		address;
+	U16		port;
 };
 
-// Standard socks5 reply packet
+// Standard SOCKS 5 reply packet
 struct socks_command_response_t {
-	unsigned char version;
-	unsigned char reply;
-	unsigned char flag;
-	unsigned char atype;
-	unsigned char add_bytes[4];
-	U16           port;
+	U8		version;
+	U8		reply;
+	U8		reserved;
+	U8		atype;
+	U8		add_bytes[4];
+	U16		port;
 };
 
 #define AUTH_NOT_ACCEPTABLE 0xFF // reply if preferred methods are not available
 #define AUTH_SUCCESS        0x00 // reply if authentication successful
 
-// socks 5 authentication request, stating which methods the client supports
+// SOCKS 5 authentication request, stating which methods the client supports
 struct socks_auth_request_t {
-	unsigned char version;
-	unsigned char num_methods;
-	unsigned char methods; // We are only using a single method currently
+	U8		version;
+	U8		num_methods;
+	U8		methods; // We are only using a single method currently
 };
 
-// socks 5 authentication response packet, stating server prefered method
+// SOCKS 5 authentication response packet, stating server preferred method
 struct socks_auth_response_t {
-	unsigned char version;
-	unsigned char method;
+	U8		version;
+	U8		method;
 };
 
-// socks 5 password reply packet
+// SOCKS 5 password reply packet
 struct authmethod_password_reply_t {
-	unsigned char version;
-	unsigned char status;
+	U8		version;
+	U8		status;
 };
 
-// socks 5 UDP packet header
+// SOCKS 5 UDP packet header
 struct proxywrap_t {
-	U16 rsv;
-	U8  frag;
-	U8  atype;
-	U32 addr;
-	U16 port;
+	U16		rsv;
+	U8		frag;
+	U8		atype;
+	U32		addr;
+	U16		port;
 };
 
 #pragma pack(pop) /* restore original alignment from stack */
@@ -158,62 +158,62 @@ class LLSocks: public LLSingleton<LLSocks>
 public:
 	LLSocks();
 
-	// Start a connection to the socks 5 proxy
-	int startProxy(std::string host,U32 port);
-	int startProxy(LLHost proxy,U32 messagePort);
+	// Start a connection to the SOCKS 5 proxy
+	int startProxy(std::string host, U32 port);
+	int startProxy(LLHost proxy, U32 messagePort);
 
-	// Disconnect and clean up any connection to the socks 5 proxy
+	// Disconnect and clean up any connection to the SOCKS 5 proxy
 	void stopProxy();
 
-	// Set up to use Password auth when connecting to the socks proxy
-	void setAuthPassword(std::string username,std::string password);
+	// Set up to use Password auth when connecting to the SOCKS proxy
+	void setAuthPassword(std::string username, std::string password);
 
-	// Set up to use No Auth when connecting to the socks proxy
+	// Set up to use No Auth when connecting to the SOCKS proxy
 	void setAuthNone();
 
 	// get the currently selected auth method
 	LLSocks5AuthType getSelectedAuthMethod() const { return mAuthMethodSelected; }
 
 	// static check for enabled status for UDP packets
-	static bool isEnabled() { return sUdpProxyEnabled; }
+	static bool isEnabled() { return sUDPProxyEnabled; }
 
 	// static check for enabled status for http packets
-	static bool isHttpProxyEnabled() { return sHttpProxyEnabled; }
+	static bool isHTTPProxyEnabled() { return sHTTPProxyEnabled; }
 
-	// Proxy http packets via httpHost, which can be a Socks5 or a http proxy
+	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
 	// as specified in type
-	void enableHttpProxy(LLHost httpHost, LLHttpProxyType type);
+	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
 
-	// Stop proxying http packets
-	void disableHttpProxy() { sHttpProxyEnabled = false; };
+	// Stop proxying HTTP packets
+	void disableHTTPProxy() { sHTTPProxyEnabled = false; };
 
 	// Get the UDP proxy address and port
 	LLHost getUDPProxy() const { return mUDPProxy; }
 
-	// Get the socks 5 TCP control channel address and port
+	// Get the SOCKS 5 TCP control channel address and port
 	LLHost getTCPProxy() const { return mTCPProxy; }
 
-	// Get the http proxy address and port
+	// Get the HTTP proxy address and port
 	LLHost getHTTPProxy() const { return mHTTPProxy; }
 
-	// Get the currently selected http proxy type
-	LLHttpProxyType getHttpProxyType() const { return mProxyType; }
+	// Get the currently selected HTTP proxy type
+	LLHttpProxyType getHTTPProxyType() const { return mProxyType; }
 
 	// Get the username password in a curl compatible format
 	std::string getProxyUserPwd() const { return (mSocksUsername + ":" + mSocksPassword); }
 
 private:
 
-	// Open a communication channel to the socks5 proxy proxy, at port messagePort
-	int proxyHandshake(LLHost proxy,U32 messagePort);
+	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
+	int proxyHandshake(LLHost proxy, U32 messagePort);
 
-	// socket handle to proxy tcp control channel
-	S32 mProxyControlChannel;
+	// socket handle to proxy TCP control channel
+	LLSocket::ptr_t mProxyControlChannel;
 
 	// is the UDP proxy enabled?
-	static bool sUdpProxyEnabled;
+	static bool sUDPProxyEnabled;
 	// is the http proxy enabled?
-	static bool sHttpProxyEnabled;
+	static bool sHTTPProxyEnabled;
 
 	// currently selected http proxy type
 	LLHttpProxyType mProxyType;
@@ -225,13 +225,16 @@ private:
 	// HTTP proxy address and port
 	LLHost mHTTPProxy;
 
-	// socks 5 auth method selected
+	// SOCKS 5 auth method selected
 	LLSocks5AuthType mAuthMethodSelected;
 
-	// socks 5 username
+	// SOCKS 5 username
 	std::string mSocksUsername;
-	// socks 5 password
+	// SOCKS 5 password
 	std::string mSocksPassword;
+
+	// APR pool for the socket
+	apr_pool_t* mPool;
 };
 
 #endif
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index a51d80ff48..366a1835ca 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -189,93 +189,6 @@ U32 ip_string_to_u32(const char* ip_string)
 //////////////////////////////////////////////////////////////////////////////////////////
 
 #if LL_WINDOWS
- 
-int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen)
-{
-	int result;
-	result = send(handle, dataout, outlen, 0);
-	if (result != outlen)
-	{
-		S32 err = WSAGetLastError();
-		llwarns << "Error sending data to proxy control channel, number of bytes sent were " << result << " error code was " << err << llendl;
-		return -1;
-	}
-
-	result = recv(handle, datain, maxinlen, 0);
-	if (result != maxinlen)
-	{
-		S32 err = WSAGetLastError();
-		llwarns << "Error receiving data from proxy control channel, number of bytes received were " << result << " error code was " << err << llendl;
-		return -1;
-	}
-
-	return 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 (INVALID_SOCKET == handle)
-	{
-		llwarns << "Error opening TCP control socket, socket() returned "
-				<< WSAGetLastError() << ", " << DecodeError(WSAGetLastError()) << 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 for 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);
-			tcp_close_channel(handle);
-			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;
-	tcp_close_channel(handle);
-	return -1;
-}
-
-void tcp_close_channel(S32 handle)
-{
-	llinfos << "Closing TCP channel" << llendl;
-	shutdown(handle, SD_BOTH);
-	closesocket(handle);
-}
 
 S32 start_net(S32& socket_out, int& nPort) 
 {			
@@ -473,79 +386,6 @@ BOOL send_packet(int hSocket, const char *sendBuffer, int size, U32 recipient, i
 
 #else
 
-
-int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen)
-{
-	if (send(handle, dataout, outlen, 0) != outlen)
-	{
-		llwarns << "Error sending data to proxy control channel" << llendl;
-		return -1;
-	}
-
-	if (recv(handle, datain, maxinlen, 0) != maxinlen)
-	{
-		llwarns << "Error receiving data to proxy control channel" << llendl;		
-		return -1;
-	}
-
-	return 0;
-}
-
-S32 tcp_open_channel(LLHost host)
-{
-	S32 handle;
-	handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-	if (-1 == handle)
-	{
-		llwarns << "Error opening TCP control socket, socket() returned " << handle << "error code: " << errno << 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;
-			tcp_close_channel(handle);
-			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 connected or time out after 5 seconds
-	S32 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;
-			tcp_close_channel(handle);
-			return -1;
-	}
-
-	// Return the socket to blocking operations
-	fcntl(handle, F_SETFL, flags);
-
-	return handle;
-}
-
-void tcp_close_channel(S32 handle)
-{
-	close(handle);
-}
-
 //  Create socket, make non-blocking
 S32 start_net(S32& socket_out, int& nPort)
 {
@@ -824,4 +664,63 @@ BOOL send_packet(int hSocket, const char * sendBuffer, int size, U32 recipient,
 
 #endif
 
+int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
+{
+	apr_socket_t* apr_socket = handle->getSocket();
+	apr_status_t rv;
+
+	apr_size_t expected_len = outlen;
+
+    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
+    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
+
+	rv = apr_socket_send(apr_socket, dataout, &outlen);
+	if (rv != APR_SUCCESS || expected_len != outlen)
+	{
+		llwarns << "Error sending data to proxy control channel" << llendl;
+		ll_apr_warn_status(rv);
+		return -1;
+	}
+
+	expected_len = maxinlen;
+	do
+	{
+		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
+		llinfos << "Receiving packets." << llendl;
+		llwarns << "Proxy control channel status: " << rv << llendl;
+	} while (APR_STATUS_IS_EAGAIN(rv));
+
+	if (rv != APR_SUCCESS)
+	{
+		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
+		llwarns << "Received " << maxinlen << " bytes." << llendl;
+		ll_apr_warn_status(rv);
+		return rv;
+	}
+	else if (expected_len != maxinlen)
+	{
+		llwarns << "Incorrect data received length in proxy control channel" << llendl;
+		return -1;
+	}
+
+	return 0;
+}
+
+LLSocket::ptr_t tcp_open_channel(LLHost host)
+{
+	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
+	bool connected = socket->blockingConnect(host);
+	if (!connected)
+	{
+		tcp_close_channel(socket);
+	}
+
+	return socket;
+}
+
+void tcp_close_channel(LLSocket::ptr_t handle)
+{
+	handle.reset();
+}
+
 //EOF
diff --git a/indra/llmessage/net.h b/indra/llmessage/net.h
index 047e8ce646..0d91cf2a2f 100644
--- a/indra/llmessage/net.h
+++ b/indra/llmessage/net.h
@@ -27,6 +27,9 @@
 #ifndef LL_NET_H					
 #define LL_NET_H
 
+#include "lliosocket.h"
+#include "llapr.h"
+
 class LLTimer;
 class LLHost;
 
@@ -52,10 +55,10 @@ U32		get_sender_ip(void);
 LLHost	get_receiving_interface();
 U32		get_receiving_interface_ip(void);
 
-// Some helpful tcp functions added for the socks 5 proxy support
-S32 tcp_open_channel(LLHost host); // Open a tcp channel to a given host
-void tcp_close_channel(S32 handle); // Close an open tcp channel
-int tcp_handshake(S32 handle, char * dataout, int outlen, char * datain, int maxinlen); // Do a TCP data handshake
+// Some helpful TCP functions
+LLSocket::ptr_t tcp_open_channel(LLHost host); // Open a TCP channel to a given host
+void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
+int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
 
 const char*	u32_to_ip_string(U32 ip);					// Returns pointer to internal string buffer, "(bad IP addr)" on failure, cannot nest calls 
 char*		u32_to_ip_string(U32 ip, char *ip_string);	// NULL on failure, ip_string on success, you must allocate at least MAXADDRSTR chars
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 6d94a5454e..c2f0ca164b 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2770,18 +2770,18 @@ bool LLStartUp::handleSocksProxy(bool reportOK)
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
 		httpHost.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		LLSocks::getInstance()->enableHttpProxy(httpHost,LLPROXY_HTTP);
+		LLSocks::getInstance()->enableHTTPProxy(httpHost,LLPROXY_HTTP);
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
 		httpHost.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		LLSocks::getInstance()->enableHttpProxy(httpHost,LLPROXY_SOCKS);
+		LLSocks::getInstance()->enableHTTPProxy(httpHost,LLPROXY_SOCKS);
 	}
 	else
 	{
-		LLSocks::getInstance()->disableHttpProxy();
+		LLSocks::getInstance()->disableHTTPProxy();
 	}
 	
 	bool use_socks_proxy = gSavedSettings.getBOOL("Socks5ProxyEnabled");
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index 87d2f780be..b9ce7d9fae 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -309,13 +309,13 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 	}
 	mErrorCert = NULL;
 	
-	if (LLSocks::getInstance()->isHttpProxyEnabled())
+	if (LLSocks::getInstance()->isHTTPProxyEnabled())
 	{
 		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
 		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
 		mCurlRequest->setoptString(CURLOPT_PROXY, address.c_str());
 		mCurlRequest->setopt(CURLOPT_PROXYPORT, port);
-		if (LLSocks::getInstance()->getHttpProxyType() == LLPROXY_SOCKS)
+		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
-- 
cgit v1.2.3


From f91d40c25949ee8c5b1d5c1babab62d6dd90d0c8 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Wed, 22 Jun 2011 14:35:31 -0400
Subject: Merge, fixed build issues by refactoring SOCKS 5 code.

---
 indra/llmessage/llsocks5.cpp | 75 ++++++++++++++++++++++++++++++++++++++++++--
 indra/llmessage/llsocks5.h   |  1 +
 indra/llmessage/net.cpp      | 59 ----------------------------------
 indra/llmessage/net.h        |  8 -----
 4 files changed, 73 insertions(+), 70 deletions(-)

diff --git a/indra/llmessage/llsocks5.cpp b/indra/llmessage/llsocks5.cpp
index 27a31e35b3..278350bf25 100644
--- a/indra/llmessage/llsocks5.cpp
+++ b/indra/llmessage/llsocks5.cpp
@@ -24,13 +24,16 @@
  * $/LicenseInfo$
  */
 
+#include "linden_common.h"
+
+#include "llsocks5.h"
+
 #include <string>
 
-#include "linden_common.h"
-#include "net.h"
+#include "llapr.h"
 #include "llhost.h"
 #include "message.h"
-#include "llsocks5.h"
+#include "net.h"
 
 // Static class variable instances
 
@@ -40,6 +43,12 @@
 bool LLSocks::sUDPProxyEnabled;
 bool LLSocks::sHTTPProxyEnabled;
 
+// Some helpful TCP functions
+static LLSocket::ptr_t tcp_open_channel(LLHost host); // Open a TCP channel to a given host
+static void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
+static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
+
+
 LLSocks::LLSocks()
 {
 	sUDPProxyEnabled  = false;
@@ -214,3 +223,63 @@ void LLSocks::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 	mHTTPProxy        = httpHost;
 	mProxyType        = type;
 }
+
+static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
+{
+	apr_socket_t* apr_socket = handle->getSocket();
+	apr_status_t rv;
+
+	apr_size_t expected_len = outlen;
+
+    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
+    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
+
+	rv = apr_socket_send(apr_socket, dataout, &outlen);
+	if (rv != APR_SUCCESS || expected_len != outlen)
+	{
+		llwarns << "Error sending data to proxy control channel" << llendl;
+		ll_apr_warn_status(rv);
+		return -1;
+	}
+
+	expected_len = maxinlen;
+	do
+	{
+		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
+		llinfos << "Receiving packets." << llendl;
+		llwarns << "Proxy control channel status: " << rv << llendl;
+	} while (APR_STATUS_IS_EAGAIN(rv));
+
+	if (rv != APR_SUCCESS)
+	{
+		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
+		llwarns << "Received " << maxinlen << " bytes." << llendl;
+		ll_apr_warn_status(rv);
+		return rv;
+	}
+	else if (expected_len != maxinlen)
+	{
+		llwarns << "Incorrect data received length in proxy control channel" << llendl;
+		return -1;
+	}
+
+	return 0;
+}
+
+static LLSocket::ptr_t tcp_open_channel(LLHost host)
+{
+	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
+	bool connected = socket->blockingConnect(host);
+	if (!connected)
+	{
+		tcp_close_channel(socket);
+	}
+
+	return socket;
+}
+
+static void tcp_close_channel(LLSocket::ptr_t handle)
+{
+	handle.reset();
+}
+
diff --git a/indra/llmessage/llsocks5.h b/indra/llmessage/llsocks5.h
index 43a7c82fea..3c10f661de 100644
--- a/indra/llmessage/llsocks5.h
+++ b/indra/llmessage/llsocks5.h
@@ -28,6 +28,7 @@
 #define LL_SOCKS5_H
 
 #include "llhost.h"
+#include "lliosocket.h"
 #include "llmemory.h"
 #include "llsingleton.h"
 #include <string>
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index 366a1835ca..e2d185b959 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -664,63 +664,4 @@ BOOL send_packet(int hSocket, const char * sendBuffer, int size, U32 recipient,
 
 #endif
 
-int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
-{
-	apr_socket_t* apr_socket = handle->getSocket();
-	apr_status_t rv;
-
-	apr_size_t expected_len = outlen;
-
-    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
-    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
-
-	rv = apr_socket_send(apr_socket, dataout, &outlen);
-	if (rv != APR_SUCCESS || expected_len != outlen)
-	{
-		llwarns << "Error sending data to proxy control channel" << llendl;
-		ll_apr_warn_status(rv);
-		return -1;
-	}
-
-	expected_len = maxinlen;
-	do
-	{
-		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
-		llinfos << "Receiving packets." << llendl;
-		llwarns << "Proxy control channel status: " << rv << llendl;
-	} while (APR_STATUS_IS_EAGAIN(rv));
-
-	if (rv != APR_SUCCESS)
-	{
-		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
-		llwarns << "Received " << maxinlen << " bytes." << llendl;
-		ll_apr_warn_status(rv);
-		return rv;
-	}
-	else if (expected_len != maxinlen)
-	{
-		llwarns << "Incorrect data received length in proxy control channel" << llendl;
-		return -1;
-	}
-
-	return 0;
-}
-
-LLSocket::ptr_t tcp_open_channel(LLHost host)
-{
-	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
-	bool connected = socket->blockingConnect(host);
-	if (!connected)
-	{
-		tcp_close_channel(socket);
-	}
-
-	return socket;
-}
-
-void tcp_close_channel(LLSocket::ptr_t handle)
-{
-	handle.reset();
-}
-
 //EOF
diff --git a/indra/llmessage/net.h b/indra/llmessage/net.h
index 0d91cf2a2f..0f2437479d 100644
--- a/indra/llmessage/net.h
+++ b/indra/llmessage/net.h
@@ -27,9 +27,6 @@
 #ifndef LL_NET_H					
 #define LL_NET_H
 
-#include "lliosocket.h"
-#include "llapr.h"
-
 class LLTimer;
 class LLHost;
 
@@ -55,11 +52,6 @@ U32		get_sender_ip(void);
 LLHost	get_receiving_interface();
 U32		get_receiving_interface_ip(void);
 
-// Some helpful TCP functions
-LLSocket::ptr_t tcp_open_channel(LLHost host); // Open a TCP channel to a given host
-void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
-int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
-
 const char*	u32_to_ip_string(U32 ip);					// Returns pointer to internal string buffer, "(bad IP addr)" on failure, cannot nest calls 
 char*		u32_to_ip_string(U32 ip, char *ip_string);	// NULL on failure, ip_string on success, you must allocate at least MAXADDRSTR chars
 U32			ip_string_to_u32(const char* ip_string);	// Wrapper for inet_addr()
-- 
cgit v1.2.3


From cce5dd64e09eb2f0da039c3e6c4c1ebd7b5aafeb Mon Sep 17 00:00:00 2001
From: Jonathan Yap <none@none>
Date: Sun, 26 Jun 2011 04:59:02 -0400
Subject: STORM-1276 [MULTIPLE LANGS] Text truncation in Email Snapshot floater
 in Spanish localization

---
 doc/contributions.txt                                   |  1 +
 indra/newview/llfloaterpostcard.cpp                     |  4 ++--
 indra/newview/skins/default/xui/en/floater_postcard.xml | 12 ++++++------
 3 files changed, 9 insertions(+), 8 deletions(-)

diff --git a/doc/contributions.txt b/doc/contributions.txt
index b744f4db3e..71c815e00c 100644
--- a/doc/contributions.txt
+++ b/doc/contributions.txt
@@ -446,6 +446,7 @@ Jonathan Yap
 	STORM-1313
 	STORM-899
 	STORM-1273
+	STORM-1276
 Kage Pixel
 	VWR-11
 Ken March
diff --git a/indra/newview/llfloaterpostcard.cpp b/indra/newview/llfloaterpostcard.cpp
index dd0b1d999c..3bcbb987f7 100644
--- a/indra/newview/llfloaterpostcard.cpp
+++ b/indra/newview/llfloaterpostcard.cpp
@@ -137,9 +137,9 @@ void LLFloaterPostcard::draw()
 
 		// first set the max extents of our preview
 		rect.translate(-rect.mLeft, -rect.mBottom);
-		rect.mLeft += 280;
+		rect.mLeft += 320;
 		rect.mRight -= 10;
-		rect.mTop -= 20;
+		rect.mTop -= 27;
 		rect.mBottom = rect.mTop - 130;
 
 		// then fix the aspect ratio
diff --git a/indra/newview/skins/default/xui/en/floater_postcard.xml b/indra/newview/skins/default/xui/en/floater_postcard.xml
index 8da35e9d7f..c756661ffc 100644
--- a/indra/newview/skins/default/xui/en/floater_postcard.xml
+++ b/indra/newview/skins/default/xui/en/floater_postcard.xml
@@ -7,11 +7,11 @@
  height="380"
  layout="topleft"
  min_height="380"
- min_width="450"
+ min_width="490"
  name="Postcard"
  help_topic="postcard"
  title="EMAIL SNAPSHOT"
- width="450">
+ width="490">
     <floater.string
      name="default_subject">
         Postcard from [SECOND_LIFE].
@@ -40,7 +40,7 @@
      follows="left|top"
      height="20"
      layout="topleft"
-     left_delta="108"
+     left_delta="148"
      name="to_form"
      top_delta="-4"
      width="150" />
@@ -59,7 +59,7 @@
      follows="left|top"
      height="20"
      layout="topleft"
-     left_delta="108"
+     left_delta="148"
      name="from_form"
      top_delta="-4"
      width="150" />
@@ -78,7 +78,7 @@
      follows="left|top"
      height="20"
      layout="topleft"
-     left_delta="108"
+     left_delta="148"
      max_length_bytes="100"
      name="name_form"
      top_delta="-4"
@@ -99,7 +99,7 @@
      height="20"
      label="Type your subject here."
      layout="topleft"
-     left_delta="108"
+     left_delta="148"
      max_length_bytes="100"
      name="subject_form"
      top_delta="-4"
-- 
cgit v1.2.3


From 7717b6f647feb250c0b94d038f72a640a7888915 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 28 Jun 2011 19:54:53 -0400
Subject: STORM-1112 More cleanup of SOCKS 5 proxy code.

Renamed llsocks5.cpp to llproxy.cpp.
---
 indra/llmessage/CMakeLists.txt                     |   4 +-
 indra/llmessage/llcurl.cpp                         |  38 +--
 indra/llmessage/lliosocket.h                       |   2 +-
 indra/llmessage/llpacketring.cpp                   |  40 ++-
 indra/llmessage/llproxy.cpp                        | 294 +++++++++++++++++++++
 indra/llmessage/llproxy.h                          | 244 +++++++++++++++++
 indra/llmessage/llsocks5.cpp                       | 285 --------------------
 indra/llmessage/llsocks5.h                         | 241 -----------------
 indra/llmessage/net.cpp                            |   2 +-
 indra/llui/llfunctorregistry.h                     |   4 +-
 indra/newview/llfloaterpreference.cpp              |  47 +++-
 indra/newview/llloginhandler.cpp                   |   6 +-
 indra/newview/llpanellogin.h                       |   3 -
 indra/newview/llsecapi.h                           |   4 +-
 indra/newview/llstartup.cpp                        |  80 +++---
 indra/newview/llstartup.h                          |   2 +-
 indra/newview/llxmlrpctransaction.cpp              |  14 +-
 .../default/xui/en/floater_preferences_proxy.xml   | 181 +++++++------
 .../newview/skins/default/xui/en/notifications.xml |  21 +-
 .../skins/default/xui/en/panel_cof_wearables.xml   |   2 +-
 .../default/xui/en/panel_preferences_privacy.xml   |   2 +-
 .../default/xui/en/panel_preferences_setup.xml     |   2 +-
 22 files changed, 773 insertions(+), 745 deletions(-)
 create mode 100644 indra/llmessage/llproxy.cpp
 create mode 100644 indra/llmessage/llproxy.h
 delete mode 100644 indra/llmessage/llsocks5.cpp
 delete mode 100644 indra/llmessage/llsocks5.h

diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt
index 4b679ef6a5..0f40a670fa 100644
--- a/indra/llmessage/CMakeLists.txt
+++ b/indra/llmessage/CMakeLists.txt
@@ -65,6 +65,7 @@ set(llmessage_SOURCE_FILES
     llpacketbuffer.cpp
     llpacketring.cpp
     llpartdata.cpp
+    llproxy.cpp
     llpumpio.cpp
     llregionpresenceverifier.cpp
     llsdappservices.cpp
@@ -76,7 +77,6 @@ set(llmessage_SOURCE_FILES
     llsdrpcserver.cpp
     llservicebuilder.cpp
     llservice.cpp
-    llsocks5.cpp
     llstoredmessage.cpp
     lltemplatemessagebuilder.cpp
     lltemplatemessagedispatcher.cpp
@@ -162,6 +162,7 @@ set(llmessage_HEADER_FILES
     llpacketring.h
     llpartdata.h
     llpumpio.h
+    llproxy.h
     llqueryflags.h
     llregionflags.h
     llregionhandle.h
@@ -175,7 +176,6 @@ set(llmessage_HEADER_FILES
     llsdrpcserver.h
     llservice.h
     llservicebuilder.h
-    llsocks5.h
     llstoredmessage.h
     lltaskname.h
     llteleportflags.h
diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index 32dd438e68..0b368196d2 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -46,12 +46,12 @@
 #endif
 
 #include "llbufferstream.h"
-#include "llstl.h"
 #include "llsdserialize.h"
+#include "llproxy.h"
+#include "llstl.h"
 #include "llthread.h"
 #include "lltimer.h"
 
-#include "llsocks5.h"
 
 //////////////////////////////////////////////////////////////////////////////
 /*
@@ -357,27 +357,6 @@ LLCurl::Easy* LLCurl::Easy::getEasy()
 	// multi handles cache if they are added to one.
 	CURLcode result = curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
 	check_curl_code(result);
-
-	//Set the CURL options for either Socks or HTTP proxy
-	if (LLSocks::getInstance()->isHTTPProxyEnabled())
-	{
-		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
-		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXY,address.c_str());
-		curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYPORT,port);
-		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
-		{
-			curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
-			{
-				curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd().c_str());
-			}
-		}
-		else
-		{
-			curl_easy_setopt(easy->mCurlEasyHandle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-		}
-	}
 	
 	++gCurlEasyCount;
 	return easy;
@@ -557,18 +536,19 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	//setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
-	if (LLSocks::getInstance()->isHTTPProxyEnabled())
+	// Set the CURL options for either Socks or HTTP proxy
+	if (LLProxy::getInstance()->isHTTPProxyEnabled())
 	{
-		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
+		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
 		setoptString(CURLOPT_PROXY, address.c_str());
 		setopt(CURLOPT_PROXYPORT, port);
-		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			if(LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
 			{
-				setoptString(CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd());
+				setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
 			}
 		}
 		else
diff --git a/indra/llmessage/lliosocket.h b/indra/llmessage/lliosocket.h
index 6806e5084a..ec60470459 100644
--- a/indra/llmessage/lliosocket.h
+++ b/indra/llmessage/lliosocket.h
@@ -159,7 +159,7 @@ protected:
 
 public:
 	/** 
-	 * @brief Do not call this directly.
+	 * @brief Do not call this directly. Use LLSocket::ptr_t.reset() instead.
 	 */
 	~LLSocket();
 
diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index 62aaca0672..91ab1df149 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -37,19 +37,13 @@
 
 // linden library includes
 #include "llerror.h"
-#include "message.h"
-#include "llsocks5.h"
 #include "lltimer.h"
-#include "timing.h"
+#include "llproxy.h"
 #include "llrand.h"
+#include "message.h"
+#include "timing.h"
 #include "u64.h"
 
-
-
-
-
-
-
 ///////////////////////////////////////////////////////////
 LLPacketRing::LLPacketRing () :
 	mUseInThrottle(FALSE),
@@ -231,28 +225,28 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 	else
 	{
 		// no delay, pull straight from net
-		if (LLSocks::isEnabled())
+		if (LLProxy::isEnabled())
 		{
-			U8 buffer[MAX_BUFFER_SIZE];
-			packet_size = receive_packet(socket, (char*)buffer);
+			U8 buffer[NET_BUFFER_SIZE];
+			packet_size = receive_packet(socket, reinterpret_cast<char *>(buffer));
 			
 			if (packet_size > 10)
 			{
-				memcpy(datap,buffer+10,packet_size-10);
+				// *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6)
+				memcpy(datap, buffer + 10, packet_size - 10);
+				proxywrap_t * header = reinterpret_cast<proxywrap_t *>(buffer);
+				mLastSender.setAddress(header->addr);
+				mLastSender.setPort(ntohs(header->port));
 			}
 			else
 			{
-				packet_size=0;
+				packet_size = 0;
 			}
-
-			proxywrap_t * header = (proxywrap_t *)buffer;
-			mLastSender.setAddress(header->addr);
-			mLastSender.setPort(ntohs(header->port));
 		}
 		else
 		{
-		packet_size = receive_packet(socket, datap);		
-		mLastSender = ::get_sender();
+			packet_size = receive_packet(socket, datap);
+			mLastSender = ::get_sender();
 		}
 
 		mLastReceivingIF = ::get_receiving_interface();
@@ -352,7 +346,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 BOOL LLPacketRing::doSendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
 {
 	
-	if (!LLSocks::isEnabled())
+	if (!LLProxy::isEnabled())
 	{
 		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort());
 	}
@@ -364,7 +358,7 @@ BOOL LLPacketRing::doSendPacket(int h_socket, const char * send_buffer, S32 buf_
 	socks_header->atype = ADDRESS_IPV4;
 	socks_header->frag  = 0;
 
-	memcpy(mProxyWrappedSendBuffer+10, send_buffer, buf_size);
+	memcpy(mProxyWrappedSendBuffer + 10, send_buffer, buf_size);
 
-	return send_packet(h_socket,(const char*) mProxyWrappedSendBuffer, buf_size+10, LLSocks::getInstance()->getUDPProxy().getAddress(), LLSocks::getInstance()->getUDPProxy().getPort());
+	return send_packet(h_socket,(const char*) mProxyWrappedSendBuffer, buf_size + 10, LLProxy::getInstance()->getUDPProxy().getAddress(), LLProxy::getInstance()->getUDPProxy().getPort());
 }
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
new file mode 100644
index 0000000000..6bc9e8b62b
--- /dev/null
+++ b/indra/llmessage/llproxy.cpp
@@ -0,0 +1,294 @@
+/**
+ * @file llsocks5.cpp
+ * @brief SOCKS 5 implementation
+ *
+ * $LicenseInfo:firstyear=2011&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2011, Linden Research, Inc.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ * 
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
+ * $/LicenseInfo$
+ */
+
+#include "linden_common.h"
+
+#include "llproxy.h"
+
+#include <string>
+
+#include "llapr.h"
+#include "llhost.h"
+#include "message.h"
+#include "net.h"
+
+// Static class variable instances
+
+// We want this to be static to avoid excessive indirection on every
+// incoming packet just to do a simple bool test. The getter for this
+// member is also static
+bool LLProxy::sUDPProxyEnabled = false;
+bool LLProxy::sHTTPProxyEnabled = false;
+
+// Some helpful TCP functions
+static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host); // Open a TCP channel to a given host
+static void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
+static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
+
+
+LLProxy::LLProxy():
+		mProxyType(LLPROXY_SOCKS),
+		mUDPProxy(),
+		mTCPProxy(),
+		mHTTPProxy(),
+		mAuthMethodSelected(METHOD_NOAUTH),
+		mSocksUsername(),
+		mSocksPassword(),
+		mPool(gAPRPoolp)
+{
+}
+
+LLProxy::~LLProxy()
+{
+	tcp_close_channel(mProxyControlChannel);
+	sUDPProxyEnabled  = false;
+	sHTTPProxyEnabled = false;
+}
+
+// Perform a SOCKS 5 authentication and UDP association to the proxy
+// specified by proxy, and associate UDP port message_port
+int LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
+{
+	int 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     = mAuthMethodSelected; // Send only the selected method.
+
+	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request), (char*)&socks_auth_response, sizeof(socks_auth_response));
+	if (result != 0)
+	{
+		llwarns << "SOCKS authentication request failed, error on TCP control channel : " << result << llendl;
+		stopProxy();
+		return SOCKS_CONNECT_ERROR;
+	}
+
+	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
+	{
+		llwarns << "SOCKS 5 server refused all our authentication methods" << llendl;
+		stopProxy();
+		return SOCKS_NOT_ACCEPTABLE;
+	}
+
+	// SOCKS 5 USERNAME/PASSWORD authentication
+	if (socks_auth_response.method == METHOD_PASSWORD)
+	{
+		// The server has requested a username/password combination
+		U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
+		char * password_auth = new char[request_size];
+		password_auth[0] = 0x01;
+		password_auth[1] = mSocksUsername.size();
+		memcpy(&password_auth[2], mSocksUsername.c_str(), mSocksUsername.size());
+		password_auth[mSocksUsername.size() + 2] = mSocksPassword.size();
+		memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
+
+		authmethod_password_reply_t password_reply;
+
+		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
+		delete[] password_auth;
+
+		if (result != 0)
+		{
+			llwarns << "SOCKS authentication failed, error on TCP control channel : " << result << llendl;
+			stopProxy();
+			return SOCKS_CONNECT_ERROR;
+		}
+
+		if (password_reply.status != AUTH_SUCCESS)
+		{
+			llwarns << "SOCKS authentication failed" << llendl;
+			stopProxy();
+			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_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
+	if (result != 0)
+	{
+		llwarns << "SOCKS connect request failed, error on TCP control channel : " << result << llendl;
+		stopProxy();
+		return SOCKS_CONNECT_ERROR;
+	}
+
+	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
+	{
+		//Something went wrong
+		llwarns << "Connection to SOCKS 5 server failed, UDP forward request not granted" << llendl;
+		stopProxy();
+		return SOCKS_UDP_FWD_NOT_GRANTED;
+	}
+
+	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
+	mUDPProxy.setAddress(proxy.getAddress());
+	// All good now we have been given the UDP port to send requests that need forwarding.
+	llinfos << "SOCKS 5 UDP proxy connected on " << mUDPProxy << llendl;
+	return SOCKS_OK;
+}
+
+int LLProxy::startProxy(std::string host, U32 port)
+{
+	mTCPProxy.setHostByName(host);
+	mTCPProxy.setPort(port);
+
+	int status;
+
+	if (mProxyControlChannel)
+	{
+		tcp_close_channel(mProxyControlChannel);
+	}
+
+	mProxyControlChannel = tcp_open_channel(mPool, mTCPProxy);
+	if (!mProxyControlChannel)
+	{
+		return SOCKS_HOST_CONNECT_FAILED;
+	}
+	status = proxyHandshake(mTCPProxy, (U32)gMessageSystem->mPort);
+	if (status == SOCKS_OK)
+	{
+		sUDPProxyEnabled = true;
+	}
+	else
+	{
+		stopProxy();
+	}
+	return status;
+
+}
+
+void LLProxy::stopProxy()
+{
+	sUDPProxyEnabled = false;
+
+	// If the SOCKS proxy is requested to stop and we are using that for http as well
+	// then we must shut down any http proxy operations. But it is allowable if web
+	// proxy is being used to continue proxying http.
+
+	if(LLPROXY_SOCKS == mProxyType)
+	{
+		sHTTPProxyEnabled = false;
+	}
+
+	if (mProxyControlChannel)
+	{
+		tcp_close_channel(mProxyControlChannel);
+	}
+}
+
+void LLProxy::setAuthNone()
+{
+	mAuthMethodSelected = METHOD_NOAUTH;
+}
+
+void LLProxy::setAuthPassword(const std::string &username, const std::string &password)
+{
+	mAuthMethodSelected = METHOD_PASSWORD;
+	mSocksUsername      = username;
+	mSocksPassword      = password;
+}
+
+void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
+{ 
+	sHTTPProxyEnabled = true;
+	mHTTPProxy        = httpHost;
+	mProxyType        = type;
+}
+
+static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
+{
+	apr_socket_t* apr_socket = handle->getSocket();
+	apr_status_t rv;
+
+	apr_size_t expected_len = outlen;
+
+    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
+    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
+
+	rv = apr_socket_send(apr_socket, dataout, &outlen);
+	if (rv != APR_SUCCESS || expected_len != outlen)
+	{
+		llwarns << "Error sending data to proxy control channel" << llendl;
+		ll_apr_warn_status(rv);
+		return -1;
+	}
+
+	expected_len = maxinlen;
+	do
+	{
+		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
+		llinfos << "Receiving packets." << llendl;
+		llwarns << "Proxy control channel status: " << rv << llendl;
+	} while (APR_STATUS_IS_EAGAIN(rv));
+
+	if (rv != APR_SUCCESS)
+	{
+		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
+		llwarns << "Received " << maxinlen << " bytes." << llendl;
+		ll_apr_warn_status(rv);
+		return rv;
+	}
+	else if (expected_len != maxinlen)
+	{
+		llwarns << "Incorrect data received length in proxy control channel" << llendl;
+		return -1;
+	}
+
+	return 0;
+}
+
+static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
+{
+	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
+	bool connected = socket->blockingConnect(host);
+	if (!connected)
+	{
+		tcp_close_channel(socket);
+	}
+
+	return socket;
+}
+
+static void tcp_close_channel(LLSocket::ptr_t handle)
+{
+	handle.reset();
+}
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
new file mode 100644
index 0000000000..979514a7e0
--- /dev/null
+++ b/indra/llmessage/llproxy.h
@@ -0,0 +1,244 @@
+/**
+ * @file llsocks5.h
+ * @brief Socks 5 implementation
+ *
+ * $LicenseInfo:firstyear=2011&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2011, Linden Research, Inc.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ * 
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_PROXY_H
+#define LL_PROXY_H
+
+#include "llhost.h"
+#include "lliosocket.h"
+#include "llmemory.h"
+#include "llsingleton.h"
+#include <string>
+
+// Error codes returned from the StartProxy method
+
+#define SOCKS_OK 0
+#define SOCKS_CONNECT_ERROR (-1)
+#define SOCKS_NOT_PERMITTED (-2)
+#define SOCKS_NOT_ACCEPTABLE (-3)
+#define SOCKS_AUTH_FAIL (-4)
+#define SOCKS_UDP_FWD_NOT_GRANTED (-5)
+#define SOCKS_HOST_CONNECT_FAILED (-6)
+
+#ifndef MAXHOSTNAMELEN
+#define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
+#endif
+
+#define SOCKS_VERSION 0x05 // we are using SOCKS 5
+
+// SOCKS 5 address/hostname types
+#define ADDRESS_IPV4     0x01
+#define ADDRESS_HOSTNAME 0x03
+#define ADDRESS_IPV6     0x04
+
+// Lets just use our own ipv4 struct rather than dragging in system
+// specific headers
+union ipv4_address_t {
+	U8		octets[4];
+	U32		addr32;
+};
+
+// SOCKS 5 control channel commands
+#define COMMAND_TCP_STREAM    0x01
+#define COMMAND_TCP_BIND      0x02
+#define COMMAND_UDP_ASSOCIATE 0x03
+
+// SOCKS 5 command replies
+#define REPLY_REQUEST_GRANTED     0x00
+#define REPLY_GENERAL_FAIL        0x01
+#define REPLY_RULESET_FAIL        0x02
+#define REPLY_NETWORK_UNREACHABLE 0x03
+#define REPLY_HOST_UNREACHABLE    0x04
+#define REPLY_CONNECTION_REFUSED  0x05
+#define REPLY_TTL_EXPIRED         0x06
+#define REPLY_PROTOCOL_ERROR      0x07
+#define REPLY_TYPE_NOT_SUPPORTED  0x08
+
+#define FIELD_RESERVED 0x00
+
+// The standard SOCKS 5 request packet
+// Push current alignment to stack and set alignment to 1 byte boundary
+// This enabled us to use structs directly to set up and receive network packets
+// into the correct fields, without fear of boundary alignment causing issues
+#pragma pack(push,1)
+
+// SOCKS 5 command packet
+struct socks_command_request_t {
+	U8		version;
+	U8		command;
+	U8		reserved;
+	U8		atype;
+	U32		address;
+	U16		port;
+};
+
+// Standard SOCKS 5 reply packet
+struct socks_command_response_t {
+	U8		version;
+	U8		reply;
+	U8		reserved;
+	U8		atype;
+	U8		add_bytes[4];
+	U16		port;
+};
+
+#define AUTH_NOT_ACCEPTABLE 0xFF // reply if preferred methods are not available
+#define AUTH_SUCCESS        0x00 // reply if authentication successful
+
+// SOCKS 5 authentication request, stating which methods the client supports
+struct socks_auth_request_t {
+	U8		version;
+	U8		num_methods;
+	U8		methods; // We are only using a single method currently
+};
+
+// SOCKS 5 authentication response packet, stating server preferred method
+struct socks_auth_response_t {
+	U8		version;
+	U8		method;
+};
+
+// SOCKS 5 password reply packet
+struct authmethod_password_reply_t {
+	U8		version;
+	U8		status;
+};
+
+// SOCKS 5 UDP packet header
+struct proxywrap_t {
+	U16		rsv;
+	U8		frag;
+	U8		atype;
+	U32		addr;
+	U16		port;
+};
+
+#pragma pack(pop) /* restore original alignment from stack */
+
+
+// Currently selected http proxy type
+enum LLHttpProxyType
+{
+	LLPROXY_SOCKS = 0,
+	LLPROXY_HTTP  = 1
+};
+
+// Auth types
+enum LLSocks5AuthType
+{
+	METHOD_NOAUTH   = 0x00,	// Client supports no auth
+	METHOD_GSSAPI   = 0x01,	// Client supports GSSAPI (Not currently supported)
+	METHOD_PASSWORD = 0x02 	// Client supports username/password
+};
+
+class LLProxy: public LLSingleton<LLProxy>
+{
+public:
+	LLProxy();
+	~LLProxy();
+
+	// Start a connection to the SOCKS 5 proxy
+	int startProxy(std::string host, U32 port);
+
+	// Disconnect and clean up any connection to the SOCKS 5 proxy
+	void stopProxy();
+
+	// Set up to use Password auth when connecting to the SOCKS proxy
+	void setAuthPassword(const std::string &username, const std::string &password);
+
+	// Set up to use No Auth when connecting to the SOCKS proxy
+	void setAuthNone();
+
+	// get the currently selected auth method
+	LLSocks5AuthType getSelectedAuthMethod() const { return mAuthMethodSelected; }
+
+	// static check for enabled status for UDP packets
+	static bool isEnabled() { return sUDPProxyEnabled; }
+
+	// static check for enabled status for http packets
+	static bool isHTTPProxyEnabled() { return sHTTPProxyEnabled; }
+
+	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
+	// as specified in type
+	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
+
+	// Stop proxying HTTP packets
+	void disableHTTPProxy() { sHTTPProxyEnabled = false; };
+
+	// Get the UDP proxy address and port
+	LLHost getUDPProxy() const { return mUDPProxy; }
+
+	// Get the SOCKS 5 TCP control channel address and port
+	LLHost getTCPProxy() const { return mTCPProxy; }
+
+	// Get the HTTP proxy address and port
+	LLHost getHTTPProxy() const { return mHTTPProxy; }
+
+	// Get the currently selected HTTP proxy type
+	LLHttpProxyType getHTTPProxyType() const { return mProxyType; }
+
+	// Get the username password in a curl compatible format
+	std::string getProxyUserPwdCURL() const { return (mSocksUsername + ":" + mSocksPassword); }
+
+	std::string getSocksPwd() const { return mSocksPassword; }
+	std::string getSocksUser() const { return mSocksUsername; }
+
+private:
+
+	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
+	int proxyHandshake(LLHost proxy, U32 messagePort);
+
+	// socket handle to proxy TCP control channel
+	LLSocket::ptr_t mProxyControlChannel;
+
+	// is the UDP proxy enabled?
+	static bool sUDPProxyEnabled;
+	// is the http proxy enabled?
+	static bool sHTTPProxyEnabled;
+
+	// currently selected http proxy type
+	LLHttpProxyType mProxyType;
+
+	// UDP proxy address and port
+	LLHost mUDPProxy;
+	// TCP Proxy control channel address and port
+	LLHost mTCPProxy;
+	// HTTP proxy address and port
+	LLHost mHTTPProxy;
+
+	// SOCKS 5 auth method selected
+	LLSocks5AuthType mAuthMethodSelected;
+
+	// SOCKS 5 username
+	std::string mSocksUsername;
+	// SOCKS 5 password
+	std::string mSocksPassword;
+
+	// APR pool for the socket
+	apr_pool_t* mPool;
+};
+
+#endif
diff --git a/indra/llmessage/llsocks5.cpp b/indra/llmessage/llsocks5.cpp
deleted file mode 100644
index 278350bf25..0000000000
--- a/indra/llmessage/llsocks5.cpp
+++ /dev/null
@@ -1,285 +0,0 @@
-/**
- * @file llsocks5.cpp
- * @brief SOCKS 5 implementation
- *
- * $LicenseInfo:firstyear=2011&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2011, Linden Research, Inc.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- * 
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
- * $/LicenseInfo$
- */
-
-#include "linden_common.h"
-
-#include "llsocks5.h"
-
-#include <string>
-
-#include "llapr.h"
-#include "llhost.h"
-#include "message.h"
-#include "net.h"
-
-// Static class variable instances
-
-// We want this to be static to avoid excessive indirection on every
-// incoming packet just to do a simple bool test. The getter for this
-// member is also static
-bool LLSocks::sUDPProxyEnabled;
-bool LLSocks::sHTTPProxyEnabled;
-
-// Some helpful TCP functions
-static LLSocket::ptr_t tcp_open_channel(LLHost host); // Open a TCP channel to a given host
-static void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
-static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
-
-
-LLSocks::LLSocks()
-{
-	sUDPProxyEnabled  = false;
-	sHTTPProxyEnabled = false;
-	mProxyControlChannel.reset();
-	mProxyType = LLPROXY_SOCKS;
-}
-
-// Perform a SOCKS 5 authentication and UDP association to the proxy
-// specified by proxy, and associate UDP port message_port
-int LLSocks::proxyHandshake(LLHost proxy, U32 message_port)
-{
-	int 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     = mAuthMethodSelected; // Send only the selected method.
-
-	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request_t), (char*)&socks_auth_response, sizeof(socks_auth_response_t));
-	if (result != 0)
-	{
-		llwarns << "SOCKS authentication request failed, error on TCP control channel : " << result << llendl;
-		stopProxy();
-		return SOCKS_CONNECT_ERROR;
-	}
-
-	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
-	{
-		llwarns << "SOCKS 5 server refused all our authentication methods" << llendl;
-		stopProxy();
-		return SOCKS_NOT_ACCEPTABLE;
-	}
-
-	// SOCKS 5 USERNAME/PASSWORD authentication
-	if (socks_auth_response.method == METHOD_PASSWORD)
-	{
-		// The server has requested a username/password combination
-		U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
-		char * password_auth = new char[request_size];
-		password_auth[0] = 0x01;
-		password_auth[1] = mSocksUsername.size();
-		memcpy(&password_auth[2], mSocksUsername.c_str(), mSocksUsername.size());
-		password_auth[mSocksUsername.size()+2] = mSocksPassword.size();
-		memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
-
-		authmethod_password_reply_t password_reply;
-
-		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
-		delete[] password_auth;
-
-		if (result != 0)
-		{
-			llwarns << "SOCKS authentication failed, error on TCP control channel : " << result << llendl;
-			stopProxy();
-			return SOCKS_CONNECT_ERROR;
-		}
-
-		if (password_reply.status != AUTH_SUCCESS)
-		{
-			llwarns << "SOCKS authentication failed" << llendl;
-			stopProxy();
-			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 possesion 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_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
-	if (result != 0)
-	{
-		llwarns << "SOCKS connect request failed, error on TCP control channel : " << result << llendl;
-		stopProxy();
-		return SOCKS_CONNECT_ERROR;
-	}
-
-	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
-	{
-		//Something went wrong
-		llwarns << "Connection to SOCKS 5 server failed, UDP forward request not granted" << llendl;
-		stopProxy();
-		return SOCKS_UDP_FWD_NOT_GRANTED;
-	}
-
-	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
-	mUDPProxy.setAddress(proxy.getAddress());
-	// All good now we have been given the UDP port to send requests that need forwarding.
-	llinfos << "SOCKS 5 UDP proxy connected on " << mUDPProxy << llendl;
-	return SOCKS_OK;
-}
-
-int LLSocks::startProxy(LLHost proxy, U32 message_port)
-{
-	int status;
-
-	mTCPProxy = proxy;
-
-	if (mProxyControlChannel)
-	{
-		tcp_close_channel(mProxyControlChannel);
-	}
-
-	mProxyControlChannel = tcp_open_channel(mTCPProxy);
-	if (!mProxyControlChannel)
-	{
-		return SOCKS_HOST_CONNECT_FAILED;
-	}
-	status = proxyHandshake(proxy, message_port);
-	if (status == SOCKS_OK)
-	{
-		sUDPProxyEnabled = true;
-	}
-	return status;
-}
-
-int LLSocks::startProxy(std::string host, U32 port)
-{
-	mTCPProxy.setHostByName(host);
-	mTCPProxy.setPort(port);
-	return startProxy(mTCPProxy, (U32)gMessageSystem->mPort);
-}
-
-void LLSocks::stopProxy()
-{
-	sUDPProxyEnabled = false;
-
-	// If the SOCKS proxy is requested to stop and we are using that for http as well
-	// then we must shut down any http proxy operations. But it is allowable if web
-	// proxy is being used to continue proxying http.
-
-	if(LLPROXY_SOCKS == mProxyType)
-	{
-		sHTTPProxyEnabled = false;
-	}
-
-	if (mProxyControlChannel)
-	{
-		tcp_close_channel(mProxyControlChannel);
-	}
-}
-
-void LLSocks::setAuthNone()
-{
-	mAuthMethodSelected = METHOD_NOAUTH;
-}
-
-void LLSocks::setAuthPassword(std::string username, std::string password)
-{
-	mAuthMethodSelected = METHOD_PASSWORD;
-	mSocksUsername      = username;
-	mSocksPassword      = password;
-}
-
-void LLSocks::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
-{ 
-	sHTTPProxyEnabled = true;
-	mHTTPProxy        = httpHost;
-	mProxyType        = type;
-}
-
-static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
-{
-	apr_socket_t* apr_socket = handle->getSocket();
-	apr_status_t rv;
-
-	apr_size_t expected_len = outlen;
-
-    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
-    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
-
-	rv = apr_socket_send(apr_socket, dataout, &outlen);
-	if (rv != APR_SUCCESS || expected_len != outlen)
-	{
-		llwarns << "Error sending data to proxy control channel" << llendl;
-		ll_apr_warn_status(rv);
-		return -1;
-	}
-
-	expected_len = maxinlen;
-	do
-	{
-		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
-		llinfos << "Receiving packets." << llendl;
-		llwarns << "Proxy control channel status: " << rv << llendl;
-	} while (APR_STATUS_IS_EAGAIN(rv));
-
-	if (rv != APR_SUCCESS)
-	{
-		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
-		llwarns << "Received " << maxinlen << " bytes." << llendl;
-		ll_apr_warn_status(rv);
-		return rv;
-	}
-	else if (expected_len != maxinlen)
-	{
-		llwarns << "Incorrect data received length in proxy control channel" << llendl;
-		return -1;
-	}
-
-	return 0;
-}
-
-static LLSocket::ptr_t tcp_open_channel(LLHost host)
-{
-	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
-	bool connected = socket->blockingConnect(host);
-	if (!connected)
-	{
-		tcp_close_channel(socket);
-	}
-
-	return socket;
-}
-
-static void tcp_close_channel(LLSocket::ptr_t handle)
-{
-	handle.reset();
-}
-
diff --git a/indra/llmessage/llsocks5.h b/indra/llmessage/llsocks5.h
deleted file mode 100644
index 3c10f661de..0000000000
--- a/indra/llmessage/llsocks5.h
+++ /dev/null
@@ -1,241 +0,0 @@
-/**
- * @file llsocks5.h
- * @brief Socks 5 implementation
- *
- * $LicenseInfo:firstyear=2011&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2011, Linden Research, Inc.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- * 
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
- * $/LicenseInfo$
- */
-
-#ifndef LL_SOCKS5_H
-#define LL_SOCKS5_H
-
-#include "llhost.h"
-#include "lliosocket.h"
-#include "llmemory.h"
-#include "llsingleton.h"
-#include <string>
-
-// Error codes returned from the StartProxy method
-
-#define SOCKS_OK 0
-#define SOCKS_CONNECT_ERROR (-1)
-#define SOCKS_NOT_PERMITTED (-2)
-#define SOCKS_NOT_ACCEPTABLE (-3)
-#define SOCKS_AUTH_FAIL (-4)
-#define SOCKS_UDP_FWD_NOT_GRANTED (-5)
-#define SOCKS_HOST_CONNECT_FAILED (-6)
-
-#ifndef MAXHOSTNAMELEN
-#define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
-#endif
-
-#define SOCKS_VERSION 0x05 // we are using SOCKS 5
-
-// SOCKS 5 address/hostname types
-#define ADDRESS_IPV4     0x01
-#define ADDRESS_HOSTNAME 0x03
-#define ADDRESS_IPV6     0x04
-
-// Lets just use our own ipv4 struct rather than dragging in system
-// specific headers
-union ipv4_address_t {
-	U8		octets[4];
-	U32		addr32;
-};
-
-// SOCKS 5 control channel commands
-#define COMMAND_TCP_STREAM    0x01
-#define COMMAND_TCP_BIND      0x02
-#define COMMAND_UDP_ASSOCIATE 0x03
-
-// SOCKS 5 command replies
-#define REPLY_REQUEST_GRANTED     0x00
-#define REPLY_GENERAL_FAIL        0x01
-#define REPLY_RULESET_FAIL        0x02
-#define REPLY_NETWORK_UNREACHABLE 0x03
-#define REPLY_HOST_UNREACHABLE    0x04
-#define REPLY_CONNECTION_REFUSED  0x05
-#define REPLY_TTL_EXPIRED         0x06
-#define REPLY_PROTOCOL_ERROR      0x07
-#define REPLY_TYPE_NOT_SUPPORTED  0x08
-
-#define FIELD_RESERVED 0x00
-
-// The standard SOCKS 5 request packet
-// Push current alignment to stack and set alignment to 1 byte boundary
-// This enabled us to use structs directly to set up and receive network packets
-// into the correct fields, without fear of boundary alignment causing issues
-#pragma pack(push,1)
-
-// SOCKS 5 command packet
-struct socks_command_request_t {
-	U8		version;
-	U8		command;
-	U8		reserved;
-	U8		atype;
-	U32		address;
-	U16		port;
-};
-
-// Standard SOCKS 5 reply packet
-struct socks_command_response_t {
-	U8		version;
-	U8		reply;
-	U8		reserved;
-	U8		atype;
-	U8		add_bytes[4];
-	U16		port;
-};
-
-#define AUTH_NOT_ACCEPTABLE 0xFF // reply if preferred methods are not available
-#define AUTH_SUCCESS        0x00 // reply if authentication successful
-
-// SOCKS 5 authentication request, stating which methods the client supports
-struct socks_auth_request_t {
-	U8		version;
-	U8		num_methods;
-	U8		methods; // We are only using a single method currently
-};
-
-// SOCKS 5 authentication response packet, stating server preferred method
-struct socks_auth_response_t {
-	U8		version;
-	U8		method;
-};
-
-// SOCKS 5 password reply packet
-struct authmethod_password_reply_t {
-	U8		version;
-	U8		status;
-};
-
-// SOCKS 5 UDP packet header
-struct proxywrap_t {
-	U16		rsv;
-	U8		frag;
-	U8		atype;
-	U32		addr;
-	U16		port;
-};
-
-#pragma pack(pop) /* restore original alignment from stack */
-
-
-// Currently selected http proxy type
-enum LLHttpProxyType
-{
-	LLPROXY_SOCKS = 0,
-	LLPROXY_HTTP  = 1
-};
-
-// Auth types
-enum LLSocks5AuthType
-{
-	METHOD_NOAUTH   = 0x00,	// Client supports no auth
-	METHOD_GSSAPI   = 0x01,	// Client supports GSSAPI (Not currently supported)
-	METHOD_PASSWORD = 0x02 	// Client supports username/password
-};
-
-class LLSocks: public LLSingleton<LLSocks>
-{
-public:
-	LLSocks();
-
-	// Start a connection to the SOCKS 5 proxy
-	int startProxy(std::string host, U32 port);
-	int startProxy(LLHost proxy, U32 messagePort);
-
-	// Disconnect and clean up any connection to the SOCKS 5 proxy
-	void stopProxy();
-
-	// Set up to use Password auth when connecting to the SOCKS proxy
-	void setAuthPassword(std::string username, std::string password);
-
-	// Set up to use No Auth when connecting to the SOCKS proxy
-	void setAuthNone();
-
-	// get the currently selected auth method
-	LLSocks5AuthType getSelectedAuthMethod() const { return mAuthMethodSelected; }
-
-	// static check for enabled status for UDP packets
-	static bool isEnabled() { return sUDPProxyEnabled; }
-
-	// static check for enabled status for http packets
-	static bool isHTTPProxyEnabled() { return sHTTPProxyEnabled; }
-
-	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
-	// as specified in type
-	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
-
-	// Stop proxying HTTP packets
-	void disableHTTPProxy() { sHTTPProxyEnabled = false; };
-
-	// Get the UDP proxy address and port
-	LLHost getUDPProxy() const { return mUDPProxy; }
-
-	// Get the SOCKS 5 TCP control channel address and port
-	LLHost getTCPProxy() const { return mTCPProxy; }
-
-	// Get the HTTP proxy address and port
-	LLHost getHTTPProxy() const { return mHTTPProxy; }
-
-	// Get the currently selected HTTP proxy type
-	LLHttpProxyType getHTTPProxyType() const { return mProxyType; }
-
-	// Get the username password in a curl compatible format
-	std::string getProxyUserPwd() const { return (mSocksUsername + ":" + mSocksPassword); }
-
-private:
-
-	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
-	int proxyHandshake(LLHost proxy, U32 messagePort);
-
-	// socket handle to proxy TCP control channel
-	LLSocket::ptr_t mProxyControlChannel;
-
-	// is the UDP proxy enabled?
-	static bool sUDPProxyEnabled;
-	// is the http proxy enabled?
-	static bool sHTTPProxyEnabled;
-
-	// currently selected http proxy type
-	LLHttpProxyType mProxyType;
-
-	// UDP proxy address and port
-	LLHost mUDPProxy;
-	// TCP Proxy control channel address and port
-	LLHost mTCPProxy;
-	// HTTP proxy address and port
-	LLHost mHTTPProxy;
-
-	// SOCKS 5 auth method selected
-	LLSocks5AuthType mAuthMethodSelected;
-
-	// SOCKS 5 username
-	std::string mSocksUsername;
-	// SOCKS 5 password
-	std::string mSocksPassword;
-
-	// APR pool for the socket
-	apr_pool_t* mPool;
-};
-
-#endif
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index e2d185b959..f8ab55143c 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -50,7 +50,7 @@
 #include "lltimer.h"
 #include "indra_constants.h"
 
-#include "llsocks5.h"
+#include "llproxy.h"
 
 // Globals
 #if LL_WINDOWS
diff --git a/indra/llui/llfunctorregistry.h b/indra/llui/llfunctorregistry.h
index 752c7df7ee..899cc3a326 100644
--- a/indra/llui/llfunctorregistry.h
+++ b/indra/llui/llfunctorregistry.h
@@ -103,7 +103,7 @@ public:
 		}
 		else
 		{
-			llwarns << "tried to find '" << name << "' in LLFunctorRegistry, but it wasn't there." << llendl;
+			lldebugs << "tried to find '" << name << "' in LLFunctorRegistry, but it wasn't there." << llendl;
 			return mMap[LOGFUNCTOR];
 		}
 	}
@@ -115,7 +115,7 @@ private:
 
 	static void log_functor(const LLSD& notification, const LLSD& payload)
 	{
-		llwarns << "log_functor called with payload: " << payload << llendl;
+		lldebugs << "log_functor called with payload: " << payload << llendl;
 	}
 
 	static void do_nothing(const LLSD& notification, const LLSD& payload)
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index c97f0779a1..ebdef8e38f 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -105,7 +105,7 @@
 #include "llviewermedia.h"
 #include "llpluginclassmedia.h"
 #include "llteleporthistorystorage.h"
-#include "llsocks5.h"
+#include "llproxy.h"
 
 #include "lllogininstance.h"        // to check if logged in yet
 #include "llsdserialize.h"
@@ -1940,15 +1940,19 @@ LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
 
 BOOL LLFloaterPreferenceProxy::postBuild()
 {
-	LLLineEditor* edit = getChild<LLLineEditor>("socks_password_editor");
-	if (edit) edit->setDrawAsterixes(TRUE);
-
 	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
 	if(socksAuth->getSelectedValue().asString() == "None")
 	{
 		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
 		getChild<LLLineEditor>("socks5_password")->setEnabled(false);
 	}
+	else
+	{
+		// Populate the SOCKS 5 credential fields with protected values.
+		LLPointer<LLCredential> socks_cred = gSecAPIHandler->loadCredential("SOCKS5");
+		getChild<LLLineEditor>("socks5_username")->setValue(socks_cred->getIdentifier()["username"].asString());
+		getChild<LLLineEditor>("socks5_password")->setValue(socks_cred->getAuthenticator()["creds"].asString());
+	}
 
 	center();
 	return TRUE;
@@ -1968,11 +1972,8 @@ void LLFloaterPreferenceProxy::onClose(bool app_quitting)
 		// it will not be updated until next restart.
 		if(LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
 		{
-			if(this->mSocksSettingsDirty == true )
-			{
-				LLNotifications::instance().add("ChangeSocks5Settings",LLSD(),LLSD());
-				mSocksSettingsDirty = false; // we have notified the user now be quiet again
-			}
+			LLNotifications::instance().add("ChangeSocks5Settings", LLSD(), LLSD());
+			mSocksSettingsDirty = false; // we have notified the user now be quiet again
 		}
 	}
 }
@@ -2006,7 +2007,6 @@ void LLFloaterPreferenceProxy::saveSettings()
 			view_stack.push_back(*iter);
 		}
 	}
-
 }
 
 void LLFloaterPreferenceProxy::onBtnOk()
@@ -2020,6 +2020,29 @@ void LLFloaterPreferenceProxy::onBtnOk()
 			cur_focus->onCommit();
 		}
 	}
+
+	// Save SOCKS proxy credentials securely if password auth is enabled
+	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+	if(socksAuth->getSelectedValue().asString() == "UserPass")
+	{
+		LLSD socks_id = LLSD::emptyMap();
+		socks_id["type"] = "SOCKS5";
+		socks_id["username"] = getChild<LLLineEditor>("socks5_username")->getValue().asString();
+
+		LLSD socks_authenticator = LLSD::emptyMap();
+		socks_authenticator["type"] = "SOCKS5";
+		socks_authenticator["creds"] = getChild<LLLineEditor>("socks5_password")->getValue().asString();
+
+		LLPointer<LLCredential> socks_cred = gSecAPIHandler->createCredential("SOCKS5", socks_id, socks_authenticator);
+		gSecAPIHandler->saveCredential(socks_cred, true);
+	}
+	else
+	{
+		// Clear SOCKS5 credentials since they are no longer needed.
+		LLPointer<LLCredential> socks_cred = new LLCredential("SOCKS5");
+		gSecAPIHandler->deleteCredential(socks_cred);
+	}
+
 	closeFloater(false);
 }
 
@@ -2036,8 +2059,8 @@ void LLFloaterPreferenceProxy::onBtnCancel()
 	}
 
 	cancel();
-
 }
+
 void LLFloaterPreferenceProxy::cancel()
 {
 
@@ -2068,7 +2091,7 @@ void LLFloaterPreferenceProxy::onChangeSocksSettings()
 		getChild<LLLineEditor>("socks5_password")->setEnabled(true);
 	}
 
-	//Check for invalid states for the other http proxy radio
+	// Check for invalid states for the other HTTP proxy radio
 	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
 	if( (otherHttpProxy->getSelectedValue().asString() == "Socks" &&
 			getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
diff --git a/indra/newview/llloginhandler.cpp b/indra/newview/llloginhandler.cpp
index 48be251611..9b4f146332 100644
--- a/indra/newview/llloginhandler.cpp
+++ b/indra/newview/llloginhandler.cpp
@@ -30,13 +30,13 @@
 
 // viewer includes
 #include "llsecapi.h"
-#include "lllogininstance.h"        // to check if logged in yet
-#include "llpanellogin.h"			// save_password_to_disk()
+#include "lllogininstance.h"		// to check if logged in yet
+#include "llpanellogin.h"
 #include "llstartup.h"				// getStartupState()
 #include "llslurl.h"
 #include "llviewercontrol.h"		// gSavedSettings
 #include "llviewernetwork.h"		// EGridInfo
-#include "llviewerwindow.h"                    // getWindow()
+#include "llviewerwindow.h"			// getWindow()
 
 // library includes
 #include "llmd5.h"
diff --git a/indra/newview/llpanellogin.h b/indra/newview/llpanellogin.h
index 11273453ba..b1390a483a 100644
--- a/indra/newview/llpanellogin.h
+++ b/indra/newview/llpanellogin.h
@@ -115,7 +115,4 @@ private:
 	static BOOL		sCapslockDidNotification;
 };
 
-std::string load_password_from_disk(void);
-void save_password_to_disk(const char* hashed_password);
-
 #endif
diff --git a/indra/newview/llsecapi.h b/indra/newview/llsecapi.h
index b65cf37e7f..812a539324 100644
--- a/indra/newview/llsecapi.h
+++ b/indra/newview/llsecapi.h
@@ -286,8 +286,8 @@ bool operator!=(const LLCertificateVector::iterator& _lhs, const LLCertificateVe
 #define CRED_AUTHENTICATOR_TYPE_HASH   "hash"
 //
 // LLCredential - interface for credentials providing the following functionality:
-// * persistance of credential information based on grid (for saving username/password)
-// * serialization to an OGP identifier/authenticator pair
+// * Persistence of credential information based on grid (for saving username/password)
+// * Serialization to an OGP identifier/authenticator pair
 // 
 class LLCredential  : public LLRefCount
 {
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index c2f0ca164b..7f14e403b0 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -125,6 +125,7 @@
 #include "llpanelgroupnotices.h"
 #include "llpreview.h"
 #include "llpreviewscript.h"
+#include "llproxy.h"
 #include "llproductinforequest.h"
 #include "llsecondlifeurls.h"
 #include "llselectmgr.h"
@@ -191,8 +192,6 @@
 #include "llevents.h"
 #include "llstartuplistener.h"
 
-#include "llsocks5.h"
-
 #if LL_WINDOWS
 #include "lldxhardware.h"
 #endif
@@ -392,7 +391,7 @@ bool idle_startup()
 		gSavedSettings.setS32("LastGPUClass", LLFeatureManager::getInstance()->getGPUClass());
 
 		// load dynamic GPU/feature tables from website (S3)
-		//LLFeatureManager::getInstance()->fetchHTTPTables();
+		LLFeatureManager::getInstance()->fetchHTTPTables();
 		
 		std::string xml_file = LLUI::locateSkin("xui_version.xml");
 		LLXMLNodePtr root;
@@ -595,13 +594,13 @@ bool idle_startup()
 		LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
 		
 		//-------------------------------------------------
-		// Init the socks 5 proxy and open the control TCP 
-		// connection if the user is using SOCKS5
-		// We need to do this early incase the user is using
-		// socks for http so we get the login screen via socks
+		// Init the SOCKS 5 proxy and open the control TCP
+		// connection if the user is using SOCKS 5
+		// We need to do this early in case the user is using
+		// socks for HTTP so we get the login screen via SOCKS
 		//-------------------------------------------------
 
-		LLStartUp::handleSocksProxy(false);
+		LLStartUp::handleSocksProxy();
 
 		//-------------------------------------------------
 		// Init audio, which may be needed for prefs dialog
@@ -823,7 +822,7 @@ bool idle_startup()
 		// past this point may require the proxy to be up.
 		if ( gSavedSettings.getBOOL("Socks5ProxyEnabled") )
 		{
-			if (!LLStartUp::handleSocksProxy(true))
+			if (!LLStartUp::handleSocksProxy())
 			{
 				// Proxy start up failed, we should now bail the state machine
 				// HandleSocksProxy() will have reported an error to the user 
@@ -835,7 +834,7 @@ bool idle_startup()
 		}
 		else
 		{
-			LLSocks::getInstance()->stopProxy();
+			LLProxy::getInstance()->stopProxy();
 		}
 		
 
@@ -2760,54 +2759,70 @@ void LLStartUp::setStartSLURL(const LLSLURL& slurl)
     }
 }
 
-bool LLStartUp::handleSocksProxy(bool reportOK)
+bool LLStartUp::handleSocksProxy()
 {
 	std::string httpProxyType = gSavedSettings.getString("Socks5HttpProxyType");
 
-	// Determine the http proxy type (if any)
+	// Determine the HTTP proxy type (if any)
 	if ((httpProxyType.compare("Web") == 0) && gSavedSettings.getBOOL("BrowserProxyEnabled"))
 	{
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
 		httpHost.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		LLSocks::getInstance()->enableHTTPProxy(httpHost,LLPROXY_HTTP);
+		LLProxy::getInstance()->enableHTTPProxy(httpHost, LLPROXY_HTTP);
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{
 		LLHost httpHost;
 		httpHost.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
 		httpHost.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		LLSocks::getInstance()->enableHTTPProxy(httpHost,LLPROXY_SOCKS);
+		LLProxy::getInstance()->enableHTTPProxy(httpHost, LLPROXY_SOCKS);
 	}
 	else
 	{
-		LLSocks::getInstance()->disableHTTPProxy();
+		LLProxy::getInstance()->disableHTTPProxy();
 	}
 	
 	bool use_socks_proxy = gSavedSettings.getBOOL("Socks5ProxyEnabled");
 	if (use_socks_proxy)
 	{	
 
-		// Determine and update LLSocks with the saved authentication system
+		// Determine and update LLProxy with the saved authentication system
 		std::string auth_type = gSavedSettings.getString("Socks5AuthType");
-			
-		if (auth_type.compare("None") == 0)
-		{
-			LLSocks::getInstance()->setAuthNone();
-		}
 
 		if (auth_type.compare("UserPass") == 0)
 		{
-			LLSocks::getInstance()->setAuthPassword(gSavedSettings.getString("Socks5Username"),gSavedSettings.getString("Socks5Password"));
+			LLPointer<LLCredential> socks_cred = gSecAPIHandler->loadCredential("SOCKS5");
+			std::string socks_user = socks_cred->getIdentifier()["username"].asString();
+			std::string socks_password = socks_cred->getAuthenticator()["creds"].asString();
+			LLProxy::getInstance()->setAuthPassword(socks_user, socks_password);
+		}
+		else if (auth_type.compare("None") == 0)
+		{
+			LLProxy::getInstance()->setAuthNone();
+		}
+		else
+		{
+			// Unknown or missing setting.
+			gSavedSettings.setString("Socks5AuthType", "None");
+
+			// Clear the SOCKS credentials.
+			LLPointer<LLCredential> socks_cred = new LLCredential("SOCKS5");
+			gSecAPIHandler->deleteCredential(socks_cred);
+
+			LLProxy::getInstance()->setAuthNone();
 		}
 
 		// Start the proxy and check for errors
-		int status = LLSocks::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
+		// If status != SOCKS_OK, stopProxy() will already have been called when startProxy() returns.
+		int status = LLProxy::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
 		LLSD subs;
 		LLSD payload;
 		subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
 		subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
 
+		std::string error_string;
+
 		switch(status)
 		{
 			case SOCKS_OK:
@@ -2815,35 +2830,36 @@ bool LLStartUp::handleSocksProxy(bool reportOK)
 				break;
 
 			case SOCKS_CONNECT_ERROR: // TCP Fail
-				LLNotifications::instance().add("SOCKS_CONNECT_ERROR", subs,payload);
+				error_string = "SOCKS_CONNECT_ERROR";
 				break;
 
-			case SOCKS_NOT_PERMITTED: // Socks5 server rule set refused connection
-				LLNotifications::instance().add("SOCKS_NOT_PERMITTED", subs,payload);
+			case SOCKS_NOT_PERMITTED: // SOCKS 5 server rule set refused connection
+				error_string = "SOCKS_NOT_PERMITTED";
 				break;
 					
 			case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
-				LLNotifications::instance().add("SOCKS_NOT_ACCEPTABLE", subs,payload);
+				error_string = "SOCKS_NOT_ACCEPTABLE";
 				break;
 
 			case SOCKS_AUTH_FAIL: // Authentication failed
-				LLNotifications::instance().add("SOCKS_AUTH_FAIL", subs,payload);
+				error_string = "SOCKS_AUTH_FAIL";
 				break;
 
 			case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
-				LLNotifications::instance().add("SOCKS_UDP_FWD_NOT_GRANTED", subs,payload);
+				error_string = "SOCKS_UDP_FWD_NOT_GRANTED";
 				break;
 
 			case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
-				LLNotifications::instance().add("SOCKS_HOST_CONNECT_FAILED", subs,payload);
-				break;		
+				error_string = "SOCKS_HOST_CONNECT_FAILED";
+				break;
 		}
 
+		LLNotificationsUtil::add(error_string, subs);
 		return false;
 	}
 	else
 	{
-		LLSocks::getInstance()->stopProxy(); // ensure no UDP proxy is running and it's all cleaned up
+		LLProxy::getInstance()->stopProxy(); // ensure no UDP proxy is running and it's all cleaned up
 	}
 
 	return true;
diff --git a/indra/newview/llstartup.h b/indra/newview/llstartup.h
index a512ec7bff..7292e4d68c 100644
--- a/indra/newview/llstartup.h
+++ b/indra/newview/llstartup.h
@@ -113,7 +113,7 @@ public:
 	static void setStartSLURL(const LLSLURL& slurl); 
 	static LLSLURL& getStartSLURL() { return sStartSLURL; } 
 
-	static bool handleSocksProxy(bool reportOK); //handle kicking the socks 5 proxy code at startup time
+	static bool handleSocksProxy(); // Initialize the SOCKS 5 proxy
 
 private:
 	static LLSLURL sStartSLURL;
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index b9ce7d9fae..ef6763a5d1 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -41,7 +41,7 @@
 #include "llappviewer.h"
 #include "lltrans.h"
 
-#include "llsocks5.h"
+#include "llproxy.h"
 
 // Static instance of LLXMLRPCListener declared here so that every time we
 // bring in this code, we instantiate a listener. If we put the static
@@ -309,18 +309,18 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 	}
 	mErrorCert = NULL;
 	
-	if (LLSocks::getInstance()->isHTTPProxyEnabled())
+	if (LLProxy::getInstance()->isHTTPProxyEnabled())
 	{
-		std::string address = LLSocks::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLSocks::getInstance()->getHTTPProxy().getPort();
+		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
 		mCurlRequest->setoptString(CURLOPT_PROXY, address.c_str());
 		mCurlRequest->setopt(CURLOPT_PROXYPORT, port);
-		if (LLSocks::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLSocks::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			if(LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
 			{
-				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLSocks::getInstance()->getProxyUserPwd());
+				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLProxy::getInstance()->getProxyUserPwdCURL());
 			}
 		}
 		else
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index 9baa9a0e02..53060b0326 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -3,82 +3,82 @@
  legacy_header_height="18"
  height="490"
  layout="topleft"
- name="Socks5 Advanced Settings Floater"
+ name="Proxy Settings Floater"
  help_topic="hardware_settings_floater"
  title="Socks5 proxy advanced settings"
  width="385">
-    <check_box
-     control_name="BrowserProxyEnabled"
-     top="30"
-     enabled="true"
-     follows="left|top"
-     height="14"
-     initial_value="false"
-     commit_callback.function="Proxy.Change"
-     label="Use HTTP Proxy for Web pages"
-     left_delta="10"
-     mouse_opaque="true"
-     name="web_proxy_enabled"
-     radio_style="false"
-     width="400"
-     top_pad="5" />
-    <check_box
-     control_name="Socks5ProxyEnabled"
-     height="16"
-     label="Use Socks 5 Proxy for UDP traffic"
-     layout="topleft"
-     left_delta="0"
-     name="socks_proxy_enabled"
-     top_pad="5"
-     width="256"
-     commit_callback.function="Proxy.Change" />
-    <text
-     type="string"
-     length="1"
-     follows="left|top"
-     height="10"
-     layout="topleft"
-     left="10"
-     name="Proxy location"
-     top_delta="30"
-     width="300">
-        Other Http traffic proxy:
-     </text>
-     <radio_group
-      control_name="Socks5HttpProxyType"
-      height="60"
-      layout="topleft"
-      name="other_http_proxy_selection"
-      top_pad="10"
-      width="120"
-      border="1"
-      left_delta="10" 
-      commit_callback.function="Proxy.Change" >
-          <radio_item
-           height="16"
-           label="Do not proxy"
-           layout="topleft"
-           value="None"
-           width="120"
-           tool_tip="Non web Http traffic should NOT be sent to any proxy."/>
-          <radio_item
-           height="16"
-           label="Use Socks 5 Proxy"
-           layout="topleft"
-           value="Socks"
-           width="120"
-           enabled_control="Socks5ProxyEnabled"
-           tool_tip="Non-web Http will be sent to the configured Socks 5 proxy."/>
-          <radio_item
-           height="16"
-           label="Use Http Proxy"
-           layout="topleft"
-           value="Web"
-           width="120"
-           enabled_control="BrowserProxyEnabled"
-           tool_tip="Non-web Http will be sent to the configured Web proxy." />
-    </radio_group>
-    <text
+	<check_box
+	 control_name="BrowserProxyEnabled"
+	 top="30"
+	 enabled="true"
+	 follows="left|top"
+	 height="14"
+	 initial_value="false"
+	 commit_callback.function="Proxy.Change"
+	 label="Use HTTP Proxy for Web pages"
+	 left_delta="10"
+	 mouse_opaque="true"
+	 name="web_proxy_enabled"
+	 radio_style="false"
+	 width="400"
+	 top_pad="5" />
+	<check_box
+	 control_name="Socks5ProxyEnabled"
+	 height="16"
+	 label="Use Socks 5 Proxy for UDP traffic"
+	 layout="topleft"
+	 left_delta="0"
+	 name="socks_proxy_enabled"
+	 top_pad="5"
+	 width="256"
+	 commit_callback.function="Proxy.Change" />
+	<text
+	type="string"
+	length="1"
+	follows="left|top"
+	height="10"
+	layout="topleft"
+	left="10"
+	name="Proxy location"
+	top_delta="30"
+	width="300">
+	   Other Http traffic proxy:
+	</text>
+	<radio_group
+	 control_name="Socks5HttpProxyType"
+	 height="60"
+	 layout="topleft"
+	 name="other_http_proxy_selection"
+	 top_pad="10"
+	 width="120"
+	 border="1"
+	 left_delta="10" 
+	 commit_callback.function="Proxy.Change" >
+		<radio_item
+		 height="16"
+		 label="Do not proxy"
+		 layout="topleft"
+		 value="None"
+		 width="120"
+		 tool_tip="Non web Http traffic should NOT be sent to any proxy."/>
+		<radio_item
+		 height="16"
+		 label="Use Socks 5 Proxy"
+		 layout="topleft"
+		 value="Socks"
+		 width="120"
+		 enabled_control="Socks5ProxyEnabled"
+		 tool_tip="Non-web Http will be sent to the configured Socks 5 proxy."/>
+		<radio_item
+		 height="16"
+		 label="Use Http Proxy"
+		 layout="topleft"
+		 value="Web"
+		 width="120"
+		 enabled_control="BrowserProxyEnabled"
+		 tool_tip="Non-web Http will be sent to the configured Web proxy." />
+	</radio_group>
+	<text
 	 type="string"
 	 length="1"
 	 follows="left|top"
@@ -93,7 +93,7 @@
 	<line_editor
 	 control_name="BrowserProxyAddress"
 	 enabled_control="BrowserProxyEnabled"
-     follows="left|top"
+	 follows="left|top"
 	 font="SansSerif"
 	 height="23"
 	 layout="topleft"
@@ -118,7 +118,7 @@
 	 min_val="10"
 	 name="web_proxy_port"
 	 top_delta="0"
-      tool_tip="The port of the HTTP proxy you would like to use."
+	 tool_tip="The port of the HTTP proxy you would like to use."
 	 width="145" />
 	<text
 	 type="string"
@@ -162,18 +162,18 @@
 	 name="socks_proxy_port"
 	 top_delta="0"
 	 width="145"
-     tool_tip="The port of the SOCKS 5 proxy you would like to use."
-	 commit_callback.function="Pref.SocksProxy" />
+	 tool_tip="The port of the SOCKS 5 proxy you would like to use."
+	 commit_callback.function="Proxy.Change" />
 	<text
-     type="string"
-     length="1"
-     follows="left|top"
-     height="10"
-     layout="topleft"
-     left="16"
-     name="Proxy location"
-     top_delta="35"
-     width="300">
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 layout="topleft"
+	 left="16"
+	 name="Proxy location"
+	 top_delta="35"
+	 width="300">
 	    Authentication:
 	</text>
 	<radio_group
@@ -186,13 +186,13 @@
 	 width="120"
 	 border="1"
 	 commit_callback.function="Proxy.Change" >
-	    <radio_item
+		<radio_item
 		 height="16"
 		 label="No Authentication"
 		 layout="topleft"
 		 name="Socks5NoAuth"
 		 value="None"
-		 tool_tip="Socks5 proxy requires no authentication."/>
+		 tool_tip="Socks5 proxy requires no authentication."
 		 width="120" />
 		<radio_item
 		 height="16"
@@ -200,7 +200,7 @@
 		 layout="topleft"
 		 name="Socks5UserPass"
 		 value="UserPass"
-		 tool_tip="Socks5 proxy requires username/password authentication."/>
+		 tool_tip="Socks5 proxy requires username/password authentication."
 		 width="120" />
 	</radio_group>
 	<text
@@ -215,7 +215,6 @@
 	    Username:
 	</text>
 	<line_editor
-	 control_name="Socks5Username"
 	 follows="left|top"
 	 font="SansSerif"
 	 height="23"
@@ -238,7 +237,6 @@
 	    Password:
 	</text>
 	<line_editor
-	 control_name="Socks5Password"
 	 follows="left|top"
 	 font="SansSerif"
 	 height="23"
@@ -248,6 +246,7 @@
 	 tool_tip="The password used to authenticate with your SOCKS 5 server"
 	 top_pad="4"
 	 width="200"
+	 is_password="true"
 	 commit_callback.function="Proxy.Change" />
 	<button
 	 follows="left|top"
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index 06a9baf8c8..7bf742d949 100755
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -7164,7 +7164,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_NOT_PERMITTED"
    type="alertmodal">
-	The Socks5 proxy "[HOST]:[PORT]" refused the connection, not allowed by rule set
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, not allowed by rule set
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
@@ -7174,7 +7175,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_CONNECT_ERROR"
    type="alertmodal">
-	The Socks5 proxy "[HOST]:[PORT]" refused the connection, could not open TCP channel
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, could not open TCP channel
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>	 
@@ -7184,7 +7186,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_NOT_ACCEPTABLE"
    type="alertmodal">
-	The Socks5 proxy "[HOST]:[PORT]" refused the selected authentication system
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the selected authentication system
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
@@ -7194,7 +7197,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_AUTH_FAIL"
    type="alertmodal">
-	The Socks5 proxy "[HOST]:[PORT]" reported your credentials are invalid
+	The SOCKS 5 proxy "[HOST]:[PORT]" reported your credentials are invalid
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
@@ -7204,7 +7208,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_UDP_FWD_NOT_GRANTED"
    type="alertmodal">
-	The Socks5 proxy "[HOST]:[PORT]" refused the UDP associate request
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the UDP associate request
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
@@ -7214,7 +7219,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_HOST_CONNECT_FAILED"
    type="alertmodal">
-	Could not connect to Socks5 proxy server "[HOST]:[PORT]"
+	Could not connect to SOCKS 5 proxy server "[HOST]:[PORT]"
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
@@ -7224,7 +7230,8 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="ChangeSocks5Settings"
    type="alert">
-	Socks 5 proxy settings take effect after you restart [APP_NAME].
+	SOCKS 5 proxy settings take effect after you restart [APP_NAME].
+	<tag>fail</tag>
    <usetemplate
      name="okbutton"
      yestext="OK"/>
diff --git a/indra/newview/skins/default/xui/en/panel_cof_wearables.xml b/indra/newview/skins/default/xui/en/panel_cof_wearables.xml
index bbeb592e96..beea53437a 100644
--- a/indra/newview/skins/default/xui/en/panel_cof_wearables.xml
+++ b/indra/newview/skins/default/xui/en/panel_cof_wearables.xml
@@ -52,7 +52,7 @@
              multi_select="true"
              name="list_attachments"
              top="0"
-             width="311">
+			 width="311" />
         </accordion_tab>
         <accordion_tab
          layout="topleft"
diff --git a/indra/newview/skins/default/xui/en/panel_preferences_privacy.xml b/indra/newview/skins/default/xui/en/panel_preferences_privacy.xml
index 30be5bc853..47236c1a48 100644
--- a/indra/newview/skins/default/xui/en/panel_preferences_privacy.xml
+++ b/indra/newview/skins/default/xui/en/panel_preferences_privacy.xml
@@ -139,7 +139,7 @@
      height="16"
      label="Add datestamp to log file name."
      layout="topleft"
-     left_detla="5"
+     left_delta="5"
      name="logfile_name_datestamp"
      top_pad="10"
      width="350"/>
diff --git a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
index d306e46d5e..b0281b11fd 100644
--- a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
+++ b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
@@ -79,7 +79,7 @@
   <spinner
    control_name="ConnectionPort"
    enabled_control="ConnectionPortEnabled"
- decimal_digits="0"
+   decimal_digits="0"
    follows="left|top"
    height="23"
    increment="1"
-- 
cgit v1.2.3


From 73afcff635f3d25432167ca43ab0b82aadd6c687 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 30 Jun 2011 18:31:53 -0400
Subject: STORM-1112 Rearranged proxy preferences panels.

---
 .../default/xui/en/floater_preferences_proxy.xml   | 175 +++++++++++----------
 1 file changed, 88 insertions(+), 87 deletions(-)

diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index 53060b0326..91e85c812c 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -1,92 +1,36 @@
 <?xml version="1.0" encoding="utf-8" standalone="yes" ?>
 <floater
  legacy_header_height="18"
- height="490"
+ height="500"
  layout="topleft"
  name="Proxy Settings Floater"
- help_topic="hardware_settings_floater"
- title="Socks5 proxy advanced settings"
- width="385">
+ help_topic="proxy_settings_floater"
+ title="Proxy Settings"
+ width="500">
 	<check_box
 	 control_name="BrowserProxyEnabled"
-	 top="30"
+	 top="38"
 	 enabled="true"
 	 follows="left|top"
 	 height="14"
 	 initial_value="false"
 	 commit_callback.function="Proxy.Change"
 	 label="Use HTTP Proxy for Web pages"
-	 left_delta="10"
+	 left="22"
 	 mouse_opaque="true"
 	 name="web_proxy_enabled"
 	 radio_style="false"
 	 width="400"
 	 top_pad="5" />
-	<check_box
-	 control_name="Socks5ProxyEnabled"
-	 height="16"
-	 label="Use Socks 5 Proxy for UDP traffic"
-	 layout="topleft"
-	 left_delta="0"
-	 name="socks_proxy_enabled"
-	 top_pad="5"
-	 width="256"
-	 commit_callback.function="Proxy.Change" />
-	<text
-	type="string"
-	length="1"
-	follows="left|top"
-	height="10"
-	layout="topleft"
-	left="10"
-	name="Proxy location"
-	top_delta="30"
-	width="300">
-	   Other Http traffic proxy:
-	</text>
-	<radio_group
-	 control_name="Socks5HttpProxyType"
-	 height="60"
-	 layout="topleft"
-	 name="other_http_proxy_selection"
-	 top_pad="10"
-	 width="120"
-	 border="1"
-	 left_delta="10" 
-	 commit_callback.function="Proxy.Change" >
-		<radio_item
-		 height="16"
-		 label="Do not proxy"
-		 layout="topleft"
-		 value="None"
-		 width="120"
-		 tool_tip="Non web Http traffic should NOT be sent to any proxy."/>
-		<radio_item
-		 height="16"
-		 label="Use Socks 5 Proxy"
-		 layout="topleft"
-		 value="Socks"
-		 width="120"
-		 enabled_control="Socks5ProxyEnabled"
-		 tool_tip="Non-web Http will be sent to the configured Socks 5 proxy."/>
-		<radio_item
-		 height="16"
-		 label="Use Http Proxy"
-		 layout="topleft"
-		 value="Web"
-		 width="120"
-		 enabled_control="BrowserProxyEnabled"
-		 tool_tip="Non-web Http will be sent to the configured Web proxy." />
-	</radio_group>
 	<text
 	 type="string"
 	 length="1"
 	 follows="left|top"
 	 height="10"
-	 left="15"
+	 left_delta="23"
 	 layout="topleft"
 	 name="Proxy location"
-	 top_delta="82"
+	 top_pad="10"
 	 width="300">
 	    HTTP Proxy:
 	</text>
@@ -120,15 +64,25 @@
 	 top_delta="0"
 	 tool_tip="The port of the HTTP proxy you would like to use."
 	 width="145" />
+	<check_box
+	 control_name="Socks5ProxyEnabled"
+	 height="16"
+	 label="Use SOCKS 5 Proxy for UDP traffic"
+	 layout="topleft"
+	 left="22"
+	 name="socks_proxy_enabled"
+	 top_pad="32"
+	 width="256"
+	 commit_callback.function="Proxy.Change" />
 	<text
 	 type="string"
 	 length="1"
 	 follows="left|top"
 	 height="10"
 	 layout="topleft"
-	 left="15"
+	 left_delta="23"
 	 name="Proxy location"
-	 top_delta="32"
+	 top_pad="10"
 	 width="300">
 	    SOCKS 5 Proxy:
 	</text>
@@ -170,11 +124,11 @@
 	 follows="left|top"
 	 height="10"
 	 layout="topleft"
-	 left="16"
+	 left="40"
 	 name="Proxy location"
-	 top_delta="35"
+	 top_pad="15"
 	 width="300">
-	    Authentication:
+	    SOCKS Authentication:
 	</text>
 	<radio_group
 	 control_name="Socks5AuthType"
@@ -211,52 +165,97 @@
 	 layout="topleft"
 	 left_delta="20"
 	 top_delta="50"
-	 width="300">
+	 width="200">
 	    Username:
 	</text>
+	<text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 left_pad="15"
+	 layout="topleft"
+	 width="200">
+	    Password:
+	</text>
 	<line_editor
 	 follows="left|top"
 	 font="SansSerif"
 	 height="23"
 	 layout="topleft"
-	 left_delta="0"
+	 left="60"
 	 name="socks5_username"
 	 tool_tip="The username used to authenticate with your SOCKS 5 server"
 	 top_pad="4"
 	 width="200"
 	 commit_callback.function="Proxy.Change" />
-	<text
-	 type="string"
-	 length="1"
-	 follows="left|top"
-	 height="10"
-	 layout="topleft"
-	 left_delta="0"
-	 top_delta="30"
-	 width="300">
-	    Password:
-	</text>
 	<line_editor
 	 follows="left|top"
 	 font="SansSerif"
 	 height="23"
 	 layout="topleft"
-	 left_delta="0"
+	 left_pad="15"
 	 name="socks5_password"
 	 tool_tip="The password used to authenticate with your SOCKS 5 server"
-	 top_pad="4"
+	 top_delta="0"
 	 width="200"
 	 is_password="true"
 	 commit_callback.function="Proxy.Change" />
+	<text
+	 type="string"
+	 length="1"
+	 follows="left|top"
+	 height="10"
+	 layout="topleft"
+	 left="25"
+	 name="Proxy location"
+	 top_pad="18"
+	 width="300">
+	   Other HTTP traffic proxy:
+	</text>
+	<radio_group
+	 control_name="Socks5HttpProxyType"
+	 height="60"
+	 layout="topleft"
+	 name="other_http_proxy_selection"
+	 top_pad="9"
+	 width="120"
+	 border="1"
+	 left_delta="15" 
+	 commit_callback.function="Proxy.Change" >
+		<radio_item
+		 height="16"
+		 label="Do not proxy"
+		 layout="topleft"
+		 value="None"
+		 width="120"
+		 tool_tip="Non-web HTTP traffic will NOT be sent to any proxy."/>
+		<radio_item
+		 height="16"
+		 label="Use SOCKS 5 Proxy"
+		 layout="topleft"
+		 value="Socks"
+		 width="120"
+		 enabled_control="Socks5ProxyEnabled"
+		 tool_tip="Non-web HTTP traffic will be sent through the configured Socks 5 proxy."/>
+		<radio_item
+		 height="16"
+		 label="Use HTTP Proxy"
+		 layout="topleft"
+		 value="Web"
+		 width="120"
+		 enabled_control="BrowserProxyEnabled"
+		 tool_tip="Non-web HTTP will be sent through the configured Web proxy." />
+	</radio_group>
 	<button
 	 follows="left|top"
 	 height="22"
 	 label="OK"
 	 label_selected="OK"
 	 layout="topleft"
-	 right="275"
+	 left="282"
 	 name="OK"
-	 top_delta="53"
+	 top_pad="36"
 	 width="90"
 	 commit_callback.function="Proxy.OK" />
 	<button
@@ -265,9 +264,11 @@
 	 label="Cancel"
 	 label_selected="Cancel"
 	 layout="topleft"
-	 right="375"
+	 left_pad="10"
 	 name="Cancel"
 	 top_delta="0"
 	 width="90"
 	 commit_callback.function="Proxy.Cancel" />
+	 
+	 
 </floater>
-- 
cgit v1.2.3


From 975975029d7f248cdf917da670ffd6c6b98d40c1 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 5 Jul 2011 16:55:43 -0400
Subject: STORM-1112 Fixed crash on quit. Other minor fixes:

* Reordered HTTP proxy choices in settings dialog
* Now using setBlocking and setNonBlocking LLSocket methods during TCP handshakes.
* Made those LLSocket methods available outside the class.
---
 indra/llmessage/lliosocket.cpp                     |  2 +
 indra/llmessage/lliosocket.h                       | 16 ++--
 indra/llmessage/llproxy.cpp                        | 93 ++++++++++++----------
 indra/llmessage/llproxy.h                          |  7 +-
 indra/newview/llappviewer.cpp                      |  3 +
 indra/newview/llstartup.cpp                        | 16 ++--
 .../default/xui/en/floater_preferences_proxy.xml   | 17 ++--
 7 files changed, 84 insertions(+), 70 deletions(-)

diff --git a/indra/llmessage/lliosocket.cpp b/indra/llmessage/lliosocket.cpp
index 8c752fbe30..a349849c30 100644
--- a/indra/llmessage/lliosocket.cpp
+++ b/indra/llmessage/lliosocket.cpp
@@ -251,10 +251,12 @@ LLSocket::~LLSocket()
 	{
 		ll_debug_socket("Destroying socket", mSocket);
 		apr_socket_close(mSocket);
+		mSocket = NULL;
 	}
 	if(mPool)
 	{
 		apr_pool_destroy(mPool);
+		mPool = NULL;
 	}
 }
 
diff --git a/indra/llmessage/lliosocket.h b/indra/llmessage/lliosocket.h
index 5a2eaf2d44..be0f7dfcc6 100644
--- a/indra/llmessage/lliosocket.h
+++ b/indra/llmessage/lliosocket.h
@@ -145,13 +145,6 @@ public:
 	 */
 	apr_socket_t* getSocket() const { return mSocket; }
 
-protected:
-	/** 
-	 * @brief Protected constructor since should only make sockets
-	 * with one of the two <code>create()</code> calls.
-	 */
-	LLSocket(apr_socket_t* socket, apr_pool_t* pool);
-
 	/** 
 	 * @brief Set default socket options, with SO_NONBLOCK = 0 and a timeout in us.
 	 * @param timeout Number of microseconds to wait on this socket. Any
@@ -164,9 +157,16 @@ protected:
 	 */
 	void setNonBlocking();
 
+protected:
+	/**
+	 * @brief Protected constructor since should only make sockets
+	 * with one of the two <code>create()</code> calls.
+	 */
+	LLSocket(apr_socket_t* socket, apr_pool_t* pool);
+
 public:
 	/** 
-	 * @brief Do not call this directly. Use LLSocket::ptr_t.reset() instead.
+	 * @brief Do not call this directly.
 	 */
 	~LLSocket();
 
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 6bc9e8b62b..6278751c31 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -45,9 +45,8 @@ bool LLProxy::sHTTPProxyEnabled = false;
 
 // Some helpful TCP functions
 static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host); // Open a TCP channel to a given host
-static void tcp_close_channel(LLSocket::ptr_t handle); // Close an open TCP channel
-static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
-
+static void tcp_close_channel(LLSocket::ptr_t* handle_ptr); // Close an open TCP channel
+static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
 
 LLProxy::LLProxy():
 		mProxyType(LLPROXY_SOCKS),
@@ -63,16 +62,16 @@ LLProxy::LLProxy():
 
 LLProxy::~LLProxy()
 {
-	tcp_close_channel(mProxyControlChannel);
+	stopProxy();
 	sUDPProxyEnabled  = false;
 	sHTTPProxyEnabled = false;
 }
 
 // Perform a SOCKS 5 authentication and UDP association to the proxy
 // specified by proxy, and associate UDP port message_port
-int LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
+S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 {
-	int result;
+	S32 result;
 
 	/* SOCKS 5 Auth request */
 	socks_auth_request_t  socks_auth_request;
@@ -153,7 +152,6 @@ int LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 
 	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
 	{
-		//Something went wrong
 		llwarns << "Connection to SOCKS 5 server failed, UDP forward request not granted" << llendl;
 		stopProxy();
 		return SOCKS_UDP_FWD_NOT_GRANTED;
@@ -161,21 +159,21 @@ int LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 
 	mUDPProxy.setPort(ntohs(connect_reply.port)); // reply port is in network byte order
 	mUDPProxy.setAddress(proxy.getAddress());
-	// All good now we have been given the UDP port to send requests that need forwarding.
+	// The connection was successful. We now have the UDP port to send requests that need forwarding to.
 	llinfos << "SOCKS 5 UDP proxy connected on " << mUDPProxy << llendl;
 	return SOCKS_OK;
 }
 
-int LLProxy::startProxy(std::string host, U32 port)
+S32 LLProxy::startProxy(std::string host, U32 port)
 {
 	mTCPProxy.setHostByName(host);
 	mTCPProxy.setPort(port);
 
-	int status;
+	S32 status;
 
 	if (mProxyControlChannel)
 	{
-		tcp_close_channel(mProxyControlChannel);
+		tcp_close_channel(&mProxyControlChannel);
 	}
 
 	mProxyControlChannel = tcp_open_channel(mPool, mTCPProxy);
@@ -200,9 +198,9 @@ void LLProxy::stopProxy()
 {
 	sUDPProxyEnabled = false;
 
-	// If the SOCKS proxy is requested to stop and we are using that for http as well
-	// then we must shut down any http proxy operations. But it is allowable if web
-	// proxy is being used to continue proxying http.
+	// If the SOCKS proxy is requested to stop and we are using that for HTTP as well
+	// then we must shut down any HTTP proxy operations. But it is allowable if web
+	// proxy is being used to continue proxying HTTP.
 
 	if(LLPROXY_SOCKS == mProxyType)
 	{
@@ -211,7 +209,7 @@ void LLProxy::stopProxy()
 
 	if (mProxyControlChannel)
 	{
-		tcp_close_channel(mProxyControlChannel);
+		tcp_close_channel(&mProxyControlChannel);
 	}
 }
 
@@ -234,46 +232,53 @@ void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 	mProxyType        = type;
 }
 
-static int tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
+//static
+void LLProxy::cleanupClass()
 {
+	LLProxy::getInstance()->stopProxy();
+}
+
+static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
+{
+
 	apr_socket_t* apr_socket = handle->getSocket();
-	apr_status_t rv;
+	apr_status_t rv = APR_SUCCESS;
 
 	apr_size_t expected_len = outlen;
 
-    apr_socket_opt_set(apr_socket, APR_SO_NONBLOCK, -5); // Blocking connection, 5 second timeout
-    apr_socket_timeout_set(apr_socket, (APR_USEC_PER_SEC * 5));
+	handle->setBlocking(1000);
 
-	rv = apr_socket_send(apr_socket, dataout, &outlen);
-	if (rv != APR_SUCCESS || expected_len != outlen)
+  	rv = apr_socket_send(apr_socket, dataout, &outlen);
+	if (APR_SUCCESS != rv || expected_len != outlen)
 	{
 		llwarns << "Error sending data to proxy control channel" << llendl;
 		ll_apr_warn_status(rv);
-		return -1;
 	}
-
-	expected_len = maxinlen;
-	do
-	{
-		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
-		llinfos << "Receiving packets." << llendl;
-		llwarns << "Proxy control channel status: " << rv << llendl;
-	} while (APR_STATUS_IS_EAGAIN(rv));
-
-	if (rv != APR_SUCCESS)
+	else if (expected_len != outlen)
 	{
-		llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
-		llwarns << "Received " << maxinlen << " bytes." << llendl;
-		ll_apr_warn_status(rv);
-		return rv;
+		llwarns << "Error sending data to proxy control channel" << llendl;
+		rv = -1;
 	}
-	else if (expected_len != maxinlen)
+
+	if (APR_SUCCESS == rv)
 	{
-		llwarns << "Incorrect data received length in proxy control channel" << llendl;
-		return -1;
+		expected_len = maxinlen;
+		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
+		if (rv != APR_SUCCESS)
+		{
+			llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
+			ll_apr_warn_status(rv);
+		}
+		else if (expected_len != maxinlen)
+		{
+			llwarns << "Received incorrect amount of data in proxy control channel" << llendl;
+			rv = -1;
+		}
 	}
 
-	return 0;
+	handle->setNonBlocking();
+
+	return rv;
 }
 
 static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
@@ -282,13 +287,15 @@ static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
 	bool connected = socket->blockingConnect(host);
 	if (!connected)
 	{
-		tcp_close_channel(socket);
+		tcp_close_channel(&socket);
 	}
 
 	return socket;
 }
 
-static void tcp_close_channel(LLSocket::ptr_t handle)
+// Pass a pointer-to-pointer to avoid changing use_count().
+static void tcp_close_channel(LLSocket::ptr_t* handle_ptr)
 {
-	handle.reset();
+	lldebugs << "Resetting proxy LLSocket handle, use_count == " << handle_ptr->use_count() << llendl;
+	handle_ptr->reset();
 }
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 979514a7e0..498ffce24e 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -161,11 +161,14 @@ public:
 	~LLProxy();
 
 	// Start a connection to the SOCKS 5 proxy
-	int startProxy(std::string host, U32 port);
+	S32 startProxy(std::string host, U32 port);
 
 	// Disconnect and clean up any connection to the SOCKS 5 proxy
 	void stopProxy();
 
+	// Delete LLProxy singleton, destroying the APR pool used by the control channel.
+	static void cleanupClass();
+
 	// Set up to use Password auth when connecting to the SOCKS proxy
 	void setAuthPassword(const std::string &username, const std::string &password);
 
@@ -209,7 +212,7 @@ public:
 private:
 
 	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
-	int proxyHandshake(LLHost proxy, U32 messagePort);
+	S32 proxyHandshake(LLHost proxy, U32 messagePort);
 
 	// socket handle to proxy TCP control channel
 	LLSocket::ptr_t mProxyControlChannel;
diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp
index d2582d524d..57e197a263 100644
--- a/indra/newview/llappviewer.cpp
+++ b/indra/newview/llappviewer.cpp
@@ -136,6 +136,7 @@
 #include "lltoolmgr.h"
 #include "llassetstorage.h"
 #include "llpolymesh.h"
+#include "llproxy.h"
 #include "llaudioengine.h"
 #include "llstreamingaudio.h"
 #include "llviewermenu.h"
@@ -1869,6 +1870,8 @@ bool LLAppViewer::cleanup()
 		LLWeb::loadURLExternal( gLaunchFileOnQuit, false );
 		llinfos << "File launched." << llendflush;
 	}
+	llinfos << "Cleaning up LLProxy." << llendl;
+	LLProxy::cleanupClass();
 
 	LLMainLoopRepeater::instance().stop();
 
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 7f14e403b0..8b333f265c 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2766,17 +2766,17 @@ bool LLStartUp::handleSocksProxy()
 	// Determine the HTTP proxy type (if any)
 	if ((httpProxyType.compare("Web") == 0) && gSavedSettings.getBOOL("BrowserProxyEnabled"))
 	{
-		LLHost httpHost;
-		httpHost.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
-		httpHost.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		LLProxy::getInstance()->enableHTTPProxy(httpHost, LLPROXY_HTTP);
+		LLHost http_host;
+		http_host.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
+		http_host.setPort(gSavedSettings.getS32("BrowserProxyPort"));
+		LLProxy::getInstance()->enableHTTPProxy(http_host, LLPROXY_HTTP);
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{
-		LLHost httpHost;
-		httpHost.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
-		httpHost.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		LLProxy::getInstance()->enableHTTPProxy(httpHost, LLPROXY_SOCKS);
+		LLHost socks_host;
+		socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
+		socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
+		LLProxy::getInstance()->enableHTTPProxy(socks_host, LLPROXY_SOCKS);
 	}
 	else
 	{
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index 91e85c812c..020ee52c18 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -217,7 +217,6 @@
 	 control_name="Socks5HttpProxyType"
 	 height="60"
 	 layout="topleft"
-	 name="other_http_proxy_selection"
 	 top_pad="9"
 	 width="120"
 	 border="1"
@@ -230,14 +229,6 @@
 		 value="None"
 		 width="120"
 		 tool_tip="Non-web HTTP traffic will NOT be sent to any proxy."/>
-		<radio_item
-		 height="16"
-		 label="Use SOCKS 5 Proxy"
-		 layout="topleft"
-		 value="Socks"
-		 width="120"
-		 enabled_control="Socks5ProxyEnabled"
-		 tool_tip="Non-web HTTP traffic will be sent through the configured Socks 5 proxy."/>
 		<radio_item
 		 height="16"
 		 label="Use HTTP Proxy"
@@ -246,6 +237,14 @@
 		 width="120"
 		 enabled_control="BrowserProxyEnabled"
 		 tool_tip="Non-web HTTP will be sent through the configured Web proxy." />
+		<radio_item
+		 height="16"
+		 label="Use SOCKS 5 Proxy"
+		 layout="topleft"
+		 value="Socks"
+		 width="120"
+		 enabled_control="Socks5ProxyEnabled"
+		 tool_tip="Non-web HTTP traffic will be sent through the configured Socks 5 proxy."/>
 	</radio_group>
 	<button
 	 follows="left|top"
-- 
cgit v1.2.3


From f630f997c0d1ceb52872304474160850c0abde72 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Wed, 6 Jul 2011 18:49:22 -0400
Subject: Changed lllog messages in llproxy.cpp to new macros.

---
 indra/llmessage/llproxy.cpp | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 6278751c31..0143803f2b 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -84,14 +84,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request), (char*)&socks_auth_response, sizeof(socks_auth_response));
 	if (result != 0)
 	{
-		llwarns << "SOCKS authentication request failed, error on TCP control channel : " << result << llendl;
+		LL_WARNS("Proxy") << "SOCKS authentication request failed, error on TCP control channel : " << result << LL_ENDL;
 		stopProxy();
 		return SOCKS_CONNECT_ERROR;
 	}
 
 	if (socks_auth_response.method == AUTH_NOT_ACCEPTABLE)
 	{
-		llwarns << "SOCKS 5 server refused all our authentication methods" << llendl;
+		LL_WARNS("Proxy") << "SOCKS 5 server refused all our authentication methods" << LL_ENDL;
 		stopProxy();
 		return SOCKS_NOT_ACCEPTABLE;
 	}
@@ -115,14 +115,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 
 		if (result != 0)
 		{
-			llwarns << "SOCKS authentication failed, error on TCP control channel : " << result << llendl;
+			LL_WARNS("Proxy") << "SOCKS authentication failed, error on TCP control channel : " << result << LL_ENDL;
 			stopProxy();
 			return SOCKS_CONNECT_ERROR;
 		}
 
 		if (password_reply.status != AUTH_SUCCESS)
 		{
-			llwarns << "SOCKS authentication failed" << llendl;
+			LL_WARNS("Proxy") << "SOCKS authentication failed" << LL_ENDL;
 			stopProxy();
 			return SOCKS_AUTH_FAIL;
 		}
@@ -145,14 +145,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	result = tcp_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
 	if (result != 0)
 	{
-		llwarns << "SOCKS connect request failed, error on TCP control channel : " << result << llendl;
+		LL_WARNS("Proxy") << "SOCKS connect request failed, error on TCP control channel : " << result << LL_ENDL;
 		stopProxy();
 		return SOCKS_CONNECT_ERROR;
 	}
 
 	if (connect_reply.reply != REPLY_REQUEST_GRANTED)
 	{
-		llwarns << "Connection to SOCKS 5 server failed, UDP forward request not granted" << llendl;
+		LL_WARNS("Proxy") << "Connection to SOCKS 5 server failed, UDP forward request not granted" << LL_ENDL;
 		stopProxy();
 		return SOCKS_UDP_FWD_NOT_GRANTED;
 	}
@@ -160,7 +160,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	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.
-	llinfos << "SOCKS 5 UDP proxy connected on " << mUDPProxy << llendl;
+	LL_INFOS("Proxy") << "SOCKS 5 UDP proxy connected on " << mUDPProxy << LL_ENDL;
 	return SOCKS_OK;
 }
 
@@ -251,12 +251,12 @@ static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outl
   	rv = apr_socket_send(apr_socket, dataout, &outlen);
 	if (APR_SUCCESS != rv || expected_len != outlen)
 	{
-		llwarns << "Error sending data to proxy control channel" << llendl;
+		LL_WARNS("Proxy") << "Error sending data to proxy control channel" << LL_ENDL;
 		ll_apr_warn_status(rv);
 	}
 	else if (expected_len != outlen)
 	{
-		llwarns << "Error sending data to proxy control channel" << llendl;
+		LL_WARNS("Proxy") << "Error sending data to proxy control channel" << LL_ENDL;
 		rv = -1;
 	}
 
@@ -266,12 +266,12 @@ static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outl
 		rv = apr_socket_recv(apr_socket, datain, &maxinlen);
 		if (rv != APR_SUCCESS)
 		{
-			llwarns << "Error receiving data from proxy control channel, status: " << rv << llendl;
+			LL_WARNS("Proxy") << "Error receiving data from proxy control channel, status: " << rv << LL_ENDL;
 			ll_apr_warn_status(rv);
 		}
 		else if (expected_len != maxinlen)
 		{
-			llwarns << "Received incorrect amount of data in proxy control channel" << llendl;
+			LL_WARNS("Proxy") << "Received incorrect amount of data in proxy control channel" << LL_ENDL;
 			rv = -1;
 		}
 	}
@@ -296,6 +296,6 @@ static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
 // Pass a pointer-to-pointer to avoid changing use_count().
 static void tcp_close_channel(LLSocket::ptr_t* handle_ptr)
 {
-	lldebugs << "Resetting proxy LLSocket handle, use_count == " << handle_ptr->use_count() << llendl;
+	LL_DEBUGS("Proxy") << "Resetting proxy LLSocket handle, use_count == " << handle_ptr->use_count() << LL_ENDL;
 	handle_ptr->reset();
 }
-- 
cgit v1.2.3


From e610304af1032f21ac01a06a5ea37460ca6da42c Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 7 Jul 2011 20:14:19 -0400
Subject: STORM-1112 Disable SOCKS 5 proxy by default.

---
 indra/newview/app_settings/settings.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index befc81f28e..032092fd6c 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -805,7 +805,7 @@
       <key>Type</key>
       <string>Boolean</string>
       <key>Value</key>
-      <integer>1</integer>
+      <integer>0</integer>
     </map>
     <key>Socks5HttpProxyType</key>
     <map>
-- 
cgit v1.2.3


From 9a888818c91e62112bafc5a45eea7f584f06c035 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 11 Jul 2011 11:38:10 -0400
Subject: Renamed proxy settings in xui.

---
 indra/newview/skins/default/xui/en/panel_preferences_setup.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
index b0281b11fd..4a3489f347 100644
--- a/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
+++ b/indra/newview/skins/default/xui/en/panel_preferences_setup.xml
@@ -239,7 +239,7 @@
      height="10"
      layout="topleft"
      left="30"
-     name="Software updates:"
+     name="Proxy Settings:"
      mouse_opaque="false"
      top_pad="5"
      width="300">
-- 
cgit v1.2.3


From 543943279894d76662833c3b4e35efd7d09a91fc Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 12 Jul 2011 13:57:41 -0400
Subject: Removed default proxy server.

---
 indra/newview/app_settings/settings.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index 032092fd6c..85f2215850 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -827,7 +827,7 @@
       <key>Type</key>
       <string>String</string>
       <key>Value</key>
-      <string>64.79.219.97</string>
+      <string></string>
     </map>
     <key>Socks5ProxyPort</key>
     <map>
-- 
cgit v1.2.3


From cfce3686dea74dfa2a6c92dbd1e8e1ae8518f259 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Wed, 13 Jul 2011 11:40:50 -0400
Subject: STORM-1112 Fixed network buffers that need to have space for the
 SOCKS proxy header.

---
 indra/llmessage/llcurl.cpp       |  4 ++--
 indra/llmessage/llpacketring.cpp | 20 ++++++++++----------
 indra/llmessage/llpacketring.h   | 13 ++++++++-----
 indra/llmessage/llproxy.h        |  4 +++-
 4 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index 0b368196d2..25249e9444 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -533,7 +533,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	
 	if (post) setoptString(CURLOPT_ENCODING, "");
 
-	//setopt(CURLOPT_VERBOSE, 1); // usefull for debugging
+	//setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
 	// Set the CURL options for either Socks or HTTP proxy
@@ -546,7 +546,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			if(LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
 			{
 				setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
 			}
diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index 91ab1df149..a86b7b4370 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -227,13 +227,13 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 		// no delay, pull straight from net
 		if (LLProxy::isEnabled())
 		{
-			U8 buffer[NET_BUFFER_SIZE];
+			U8 buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE];
 			packet_size = receive_packet(socket, reinterpret_cast<char *>(buffer));
 			
-			if (packet_size > 10)
+			if (packet_size > SOCKS_HEADER_SIZE)
 			{
 				// *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6)
-				memcpy(datap, buffer + 10, packet_size - 10);
+				memcpy(datap, buffer + SOCKS_HEADER_SIZE, packet_size - SOCKS_HEADER_SIZE);
 				proxywrap_t * header = reinterpret_cast<proxywrap_t *>(buffer);
 				mLastSender.setAddress(header->addr);
 				mLastSender.setPort(ntohs(header->port));
@@ -274,7 +274,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 	BOOL status = TRUE;
 	if (!mUseOutThrottle)
 	{
-		return doSendPacket(h_socket, send_buffer, buf_size, host );
+		return sendPacketImpl(h_socket, send_buffer, buf_size, host );
 	}
 	else
 	{
@@ -295,7 +295,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 				mOutBufferLength -= packetp->getSize();
 				packet_size = packetp->getSize();
 
-				status = doSendPacket(h_socket, packetp->getData(), packet_size, packetp->getHost());
+				status = sendPacketImpl(h_socket, packetp->getData(), packet_size, packetp->getHost());
 				
 				delete packetp;
 				// Update the throttle
@@ -304,7 +304,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 			else
 			{
 				// If the queue's empty, we can just send this packet right away.
-				status =  doSendPacket(h_socket, send_buffer, buf_size, host );
+				status =  sendPacketImpl(h_socket, send_buffer, buf_size, host );
 				packet_size = buf_size;
 
 				// Update the throttle
@@ -343,7 +343,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 	return status;
 }
 
-BOOL LLPacketRing::doSendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
+BOOL LLPacketRing::sendPacketImpl(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
 {
 	
 	if (!LLProxy::isEnabled())
@@ -351,14 +351,14 @@ BOOL LLPacketRing::doSendPacket(int h_socket, const char * send_buffer, S32 buf_
 		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort());
 	}
 
-	proxywrap_t *socks_header = (proxywrap_t *)&mProxyWrappedSendBuffer;
+	proxywrap_t *socks_header = reinterpret_cast<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);
+	memcpy(mProxyWrappedSendBuffer + SOCKS_HEADER_SIZE, send_buffer, buf_size);
 
-	return send_packet(h_socket,(const char*) mProxyWrappedSendBuffer, buf_size + 10, LLProxy::getInstance()->getUDPProxy().getAddress(), LLProxy::getInstance()->getUDPProxy().getPort());
+	return send_packet(h_socket, (const char*) mProxyWrappedSendBuffer, buf_size + 10, LLProxy::getInstance()->getUDPProxy().getAddress(), LLProxy::getInstance()->getUDPProxy().getPort());
 }
diff --git a/indra/llmessage/llpacketring.h b/indra/llmessage/llpacketring.h
index 2fe2f8e1e9..7edcc834db 100644
--- a/indra/llmessage/llpacketring.h
+++ b/indra/llmessage/llpacketring.h
@@ -30,11 +30,11 @@
 
 #include <queue>
 
-#include "llpacketbuffer.h"
 #include "llhost.h"
-#include "net.h"
+#include "llpacketbuffer.h"
+#include "llproxy.h"
 #include "llthrottle.h"
-
+#include "net.h"
 
 class LLPacketRing
 {
@@ -83,8 +83,11 @@ protected:
 	LLHost mLastSender;
 	LLHost mLastReceivingIF;
 
-	BOOL doSendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host);
-	U8 mProxyWrappedSendBuffer[NET_BUFFER_SIZE];
+
+	U8 mProxyWrappedSendBuffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE];
+
+private:
+	BOOL sendPacketImpl(int h_socket, const char * send_buffer, S32 buf_size, LLHost host);
 };
 
 
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 498ffce24e..7893545b9d 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -49,6 +49,8 @@
 
 #define SOCKS_VERSION 0x05 // we are using SOCKS 5
 
+#define SOCKS_HEADER_SIZE 10
+
 // SOCKS 5 address/hostname types
 #define ADDRESS_IPV4     0x01
 #define ADDRESS_HOSTNAME 0x03
@@ -139,7 +141,7 @@ struct proxywrap_t {
 #pragma pack(pop) /* restore original alignment from stack */
 
 
-// Currently selected http proxy type
+// Currently selected HTTP proxy type
 enum LLHttpProxyType
 {
 	LLPROXY_SOCKS = 0,
-- 
cgit v1.2.3


From cb24dff9e36a963af280be1aead9424be8a678b6 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Wed, 13 Jul 2011 16:46:36 -0400
Subject: Code cleanup for the SOCKS 5 proxy viewer.

---
 indra/llmessage/llcurl.cpp              | 10 ++--
 indra/llmessage/llpacketring.cpp        |  2 +
 indra/llmessage/llproxy.cpp             |  6 +--
 indra/llmessage/llproxy.h               |  2 +-
 indra/llmessage/net.cpp                 |  2 -
 indra/newview/app_settings/settings.xml | 22 ---------
 indra/newview/llfloaterpreference.cpp   | 81 ++++++++++++++++-----------------
 indra/newview/llstartup.cpp             |  1 -
 indra/newview/llxmlrpctransaction.cpp   |  2 +-
 9 files changed, 52 insertions(+), 76 deletions(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index 25249e9444..a7ce4310c1 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -206,7 +206,7 @@ namespace boost
 	
 	void intrusive_ptr_release(LLCurl::Responder* p)
 	{
-		if(p && 0 == --p->mReferenceCount)
+		if (p && 0 == --p->mReferenceCount)
 		{
 			delete p;
 		}
@@ -406,11 +406,11 @@ const char* LLCurl::Easy::getErrorBuffer()
 
 void LLCurl::Easy::setCA()
 {
-	if(!sCAPath.empty())
+	if (!sCAPath.empty())
 	{
 		setoptString(CURLOPT_CAPATH, sCAPath);
 	}
-	if(!sCAFile.empty())
+	if (!sCAFile.empty())
 	{
 		setoptString(CURLOPT_CAINFO, sCAFile);
 	}
@@ -546,7 +546,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
 			{
 				setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
 			}
@@ -568,7 +568,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	setopt(CURLOPT_HEADERDATA, (void*)this);
 
 	// Allow up to five redirects
-	if(responder && responder->followRedir())
+	if (responder && responder->followRedir())
 	{
 		setopt(CURLOPT_FOLLOWLOCATION, 1);
 		setopt(CURLOPT_MAXREDIRS, MAX_REDIRECTS);
diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index a86b7b4370..ba82957b47 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -237,6 +237,8 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 				proxywrap_t * header = reinterpret_cast<proxywrap_t *>(buffer);
 				mLastSender.setAddress(header->addr);
 				mLastSender.setPort(ntohs(header->port));
+
+				packet_size -= SOCKS_HEADER_SIZE; // The unwrapped packet size
 			}
 			else
 			{
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 0143803f2b..11a5c480f0 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -110,7 +110,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 
 		authmethod_password_reply_t password_reply;
 
-		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(authmethod_password_reply_t));
+		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(password_reply));
 		delete[] password_auth;
 
 		if (result != 0)
@@ -142,7 +142,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	// "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_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(socks_command_request_t), (char*)&connect_reply, sizeof(socks_command_response_t));
+	result = tcp_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(connect_request), (char*)&connect_reply, sizeof(connect_reply));
 	if (result != 0)
 	{
 		LL_WARNS("Proxy") << "SOCKS connect request failed, error on TCP control channel : " << result << LL_ENDL;
@@ -202,7 +202,7 @@ void LLProxy::stopProxy()
 	// then we must shut down any HTTP proxy operations. But it is allowable if web
 	// proxy is being used to continue proxying HTTP.
 
-	if(LLPROXY_SOCKS == mProxyType)
+	if (LLPROXY_SOCKS == mProxyType)
 	{
 		sHTTPProxyEnabled = false;
 	}
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 7893545b9d..cf2dfdc60e 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -191,7 +191,7 @@ public:
 	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
 
 	// Stop proxying HTTP packets
-	void disableHTTPProxy() { sHTTPProxyEnabled = false; };
+	void disableHTTPProxy() { sHTTPProxyEnabled = false; }
 
 	// Get the UDP proxy address and port
 	LLHost getUDPProxy() const { return mUDPProxy; }
diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp
index f8ab55143c..85aef5da00 100644
--- a/indra/llmessage/net.cpp
+++ b/indra/llmessage/net.cpp
@@ -50,8 +50,6 @@
 #include "lltimer.h"
 #include "indra_constants.h"
 
-#include "llproxy.h"
-
 // Globals
 #if LL_WINDOWS
 
diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index f8b3001aa5..55bab3064f 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -839,28 +839,6 @@
       <string>U32</string>
       <key>Value</key>
       <integer>1080</integer>
-    </map>
-     <key>Socks5Username</key>
-    <map>
-      <key>Comment</key>
-      <string>Socks 5 Username</string>
-      <key>Persist</key>
-      <integer>1</integer>
-      <key>Type</key>
-      <string>String</string>
-      <key>Value</key>
-      <string></string>
-    </map>
-    <key>Socks5Password</key>
-    <map>
-      <key>Comment</key>
-      <string>Socks 5 Password</string>
-      <key>Persist</key>
-      <integer>1</integer>
-      <key>Type</key>
-      <string>String</string>
-      <key>Value</key>
-      <string></string>
     </map>
     <key>Socks5AuthType</key>
     <map>
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index ebdef8e38f..c49191748e 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -159,7 +159,7 @@ BOOL LLVoiceSetKeyDialog::handleKeyHere(KEY key, MASK mask)
 {
 	BOOL result = TRUE;
 	
-	if(key == 'Q' && mask == MASK_CONTROL)
+	if (key == 'Q' && mask == MASK_CONTROL)
 	{
 		result = FALSE;
 	}
@@ -459,7 +459,7 @@ BOOL LLFloaterPreference::postBuild()
 void LLFloaterPreference::onBusyResponseChanged()
 {
 	// set "BusyResponseChanged" TRUE if user edited message differs from default, FALSE otherwise
-	if(LLTrans::getString("BusyModeResponseDefault") != getChild<LLUICtrl>("busy_response")->getValue().asString())
+	if (LLTrans::getString("BusyModeResponseDefault") != getChild<LLUICtrl>("busy_response")->getValue().asString())
 	{
 		gSavedPerAccountSettings.setBOOL("BusyResponseChanged", TRUE );
 	}
@@ -541,7 +541,7 @@ void LLFloaterPreference::apply()
 	
 	LLViewerMedia::setCookiesEnabled(getChild<LLUICtrl>("cookies_enabled")->getValue());
 	
-	if(hasChild("web_proxy_enabled") &&hasChild("web_proxy_editor") && hasChild("web_proxy_port"))
+	if (hasChild("web_proxy_enabled") &&hasChild("web_proxy_editor") && hasChild("web_proxy_port"))
 	{
 		bool proxy_enable = getChild<LLUICtrl>("web_proxy_enabled")->getValue();
 		std::string proxy_address = getChild<LLUICtrl>("web_proxy_editor")->getValue();
@@ -554,13 +554,13 @@ void LLFloaterPreference::apply()
 
 	gSavedSettings.setBOOL("PlainTextChatHistory", getChild<LLUICtrl>("plain_text_chat_history")->getValue().asBoolean());
 	
-	if(mGotPersonalInfo)
+	if (mGotPersonalInfo)
 	{ 
 //		gSavedSettings.setString("BusyModeResponse2", std::string(wstring_to_utf8str(busy_response)));
 		bool new_im_via_email = getChild<LLUICtrl>("send_im_to_email")->getValue().asBoolean();
 		bool new_hide_online = getChild<LLUICtrl>("online_visibility")->getValue().asBoolean();		
 	
-		if((new_im_via_email != mOriginalIMViaEmail)
+		if ((new_im_via_email != mOriginalIMViaEmail)
 			||(new_hide_online != mOriginalHideOnlineStatus))
 		{
 			// This hack is because we are representing several different 	 
@@ -568,13 +568,13 @@ void LLFloaterPreference::apply()
 			// can only select between 2 values, we represent it as a 	 
 			// checkbox. This breaks down a little bit for liaisons, but 	 
 			// works out in the end. 	 
-			if(new_hide_online != mOriginalHideOnlineStatus) 	 
-			{ 	 
-				if(new_hide_online) mDirectoryVisibility = VISIBILITY_HIDDEN;
+			if (new_hide_online != mOriginalHideOnlineStatus)
+			{
+				if (new_hide_online) mDirectoryVisibility = VISIBILITY_HIDDEN;
 				else mDirectoryVisibility = VISIBILITY_DEFAULT;
 			 //Update showonline value, otherwise multiple applys won't work
 				mOriginalHideOnlineStatus = new_hide_online;
-			} 	 
+			}
 			gAgent.sendAgentUpdateUserInfo(new_im_via_email,mDirectoryVisibility);
 		}
 	}
@@ -618,12 +618,11 @@ void LLFloaterPreference::cancel()
 		updateDoubleClickControls();
 		mDoubleClickActionDirty = false;
 	}
-    LLFloaterPreferenceProxy * advanced_socks_settings = LLFloaterReg::findTypedInstance<LLFloaterPreferenceProxy>("prefs_socks5_advanced");
-    if(advanced_socks_settings)
-    {
-        advanced_socks_settings->cancel();
-    }
-    
+	LLFloaterPreferenceProxy * advanced_socks_settings = LLFloaterReg::findTypedInstance<LLFloaterPreferenceProxy>("prefs_socks5_advanced");
+	if (advanced_socks_settings)
+	{
+		advanced_socks_settings->cancel();
+	}
 }
 
 void LLFloaterPreference::onOpen(const LLSD& key)
@@ -810,7 +809,7 @@ void LLFloaterPreference::onBtnCancel()
 void LLFloaterPreference::updateUserInfo(const std::string& visibility, bool im_via_email, const std::string& email)
 {
 	LLFloaterPreference* instance = LLFloaterReg::findTypedInstance<LLFloaterPreference>("preferences");
-	if(instance)
+	if (instance)
 	{
 		instance->setPersonalInfo(visibility, im_via_email, email);	
 	}
@@ -820,7 +819,7 @@ void LLFloaterPreference::updateUserInfo(const std::string& visibility, bool im_
 void LLFloaterPreference::refreshEnabledGraphics()
 {
 	LLFloaterPreference* instance = LLFloaterReg::findTypedInstance<LLFloaterPreference>("preferences");
-	if(instance)
+	if (instance)
 	{
 		instance->refresh();
 		//instance->refreshEnabledState();
@@ -1107,7 +1106,7 @@ void LLFloaterPreference::disableUnavailableSettings()
 	LLCheckBoxCtrl* ctrl_dof = getChild<LLCheckBoxCtrl>("UseDoF");
 
 	// if vertex shaders off, disable all shader related products
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("VertexShaderEnable"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("VertexShaderEnable"))
 	{
 		ctrl_shader_enable->setEnabled(FALSE);
 		ctrl_shader_enable->setValue(FALSE);
@@ -1138,7 +1137,7 @@ void LLFloaterPreference::disableUnavailableSettings()
 	}
 	
 	// disabled windlight
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("WindLightUseAtmosShaders"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("WindLightUseAtmosShaders"))
 	{
 		ctrl_wind_light->setEnabled(FALSE);
 		ctrl_wind_light->setValue(FALSE);
@@ -1175,28 +1174,28 @@ void LLFloaterPreference::disableUnavailableSettings()
 	}
 	
 	// disabled deferred SSAO
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferredSSAO"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferredSSAO"))
 	{
 		ctrl_ssao->setEnabled(FALSE);
 		ctrl_ssao->setValue(FALSE);
 	}
 	
 	// disabled deferred shadows
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderShadowDetail"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderShadowDetail"))
 	{
 		ctrl_shadows->setEnabled(FALSE);
 		ctrl_shadows->setValue(0);
 	}
 
 	// disabled reflections
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderReflectionDetail"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderReflectionDetail"))
 	{
 		ctrl_reflections->setEnabled(FALSE);
 		ctrl_reflections->setValue(FALSE);
 	}
 	
 	// disabled av
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderAvatarVP"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderAvatarVP"))
 	{
 		ctrl_avatar_vp->setEnabled(FALSE);
 		ctrl_avatar_vp->setValue(FALSE);
@@ -1219,14 +1218,14 @@ void LLFloaterPreference::disableUnavailableSettings()
 	}
 
 	// disabled cloth
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderAvatarCloth"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderAvatarCloth"))
 	{
 		ctrl_avatar_cloth->setEnabled(FALSE);
 		ctrl_avatar_cloth->setValue(FALSE);
 	}
 
 	// disabled impostors
-	if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderUseImpostors"))
+	if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderUseImpostors"))
 	{
 		ctrl_avatar_impostors->setEnabled(FALSE);
 		ctrl_avatar_impostors->setValue(FALSE);
@@ -1392,12 +1391,12 @@ void LLFloaterPreference::setPersonalInfo(const std::string& visibility, bool im
 	mOriginalIMViaEmail = im_via_email;
 	mDirectoryVisibility = visibility;
 	
-	if(visibility == VISIBILITY_DEFAULT)
+	if (visibility == VISIBILITY_DEFAULT)
 	{
 		mOriginalHideOnlineStatus = false;
 		getChildView("online_visibility")->setEnabled(TRUE); 	 
 	}
-	else if(visibility == VISIBILITY_HIDDEN)
+	else if (visibility == VISIBILITY_HIDDEN)
 	{
 		mOriginalHideOnlineStatus = true;
 		getChildView("online_visibility")->setEnabled(TRUE); 	 
@@ -1445,7 +1444,7 @@ void LLFloaterPreference::onUpdateSliderText(LLUICtrl* ctrl, const LLSD& name)
 {
 	std::string ctrl_name = name.asString();
 	
-	if((ctrl_name =="" )|| !hasChild(ctrl_name, true))
+	if ((ctrl_name =="" )|| !hasChild(ctrl_name, true))
 		return;
 	
 	LLTextBox* text_box = getChild<LLTextBox>(name.asString());
@@ -1455,7 +1454,7 @@ void LLFloaterPreference::onUpdateSliderText(LLUICtrl* ctrl, const LLSD& name)
 
 void LLFloaterPreference::updateSliderText(LLSliderCtrl* ctrl, LLTextBox* text_box)
 {
-	if(text_box == NULL || ctrl== NULL)
+	if (text_box == NULL || ctrl== NULL)
 		return;
 	
 	// get range and points when text should change
@@ -1468,7 +1467,7 @@ void LLFloaterPreference::updateSliderText(LLSliderCtrl* ctrl, LLTextBox* text_b
 	F32 highPoint = min + (2.0f * range / 3.0f);
 	
 	// choose the right text
-	if(value < midPoint)
+	if (value < midPoint)
 	{
 		text_box->setText(LLTrans::getString("GraphicsQualityLow"));
 	} 
@@ -1653,7 +1652,7 @@ BOOL LLPanelPreference::postBuild()
 {
 
 	////////////////////// PanelVoice ///////////////////
-	if(hasChild("voice_unavailable"))
+	if (hasChild("voice_unavailable"))
 	{
 		BOOL voice_disabled = gSavedSettings.getBOOL("CmdLineDisableVoice");
 		getChildView("voice_unavailable")->setVisible( voice_disabled);
@@ -1675,7 +1674,7 @@ BOOL LLPanelPreference::postBuild()
 
 	}
 
-	if(hasChild("online_visibility") && hasChild("send_im_to_email"))
+	if (hasChild("online_visibility") && hasChild("send_im_to_email"))
 	{
 		getChild<LLUICtrl>("email_address")->setValue(getString("log_in_to_change") );
 //		getChild<LLUICtrl>("busy_response")->setValue(getString("log_in_to_change"));		
@@ -1804,7 +1803,7 @@ void LLPanelPreference::cancel()
 		 iter != mSavedColors.end(); ++iter)
 	{
 		LLColorSwatchCtrl* color_swatch = findChild<LLColorSwatchCtrl>(iter->first);
-		if(color_swatch)
+		if (color_swatch)
 		{
 			color_swatch->set(iter->second);
 			color_swatch->onCommit();
@@ -1848,7 +1847,7 @@ void LLPanelPreferenceGraphics::draw()
 	
 	LLButton* button_apply = findChild<LLButton>("Apply");
 	
-	if(button_apply && button_apply->getVisible())
+	if (button_apply && button_apply->getVisible())
 	{
 		bool enable = hasDirtyChilds();
 
@@ -1868,7 +1867,7 @@ bool LLPanelPreferenceGraphics::hasDirtyChilds()
 		LLUICtrl* ctrl = dynamic_cast<LLUICtrl*>(curview);
 		if (ctrl)
 		{
-			if(ctrl->isDirty())
+			if (ctrl->isDirty())
 				return true;
 		}
 		// Push children onto the end of the work stack
@@ -1941,7 +1940,7 @@ LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
 BOOL LLFloaterPreferenceProxy::postBuild()
 {
 	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
-	if(socksAuth->getSelectedValue().asString() == "None")
+	if (socksAuth->getSelectedValue().asString() == "None")
 	{
 		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
 		getChild<LLLineEditor>("socks5_password")->setEnabled(false);
@@ -1965,12 +1964,12 @@ void LLFloaterPreferenceProxy::onOpen(const LLSD& key)
 
 void LLFloaterPreferenceProxy::onClose(bool app_quitting)
 {
-	if(mSocksSettingsDirty)
+	if (mSocksSettingsDirty)
 	{
 
 		// If the user plays with the Socks proxy settings after login, it's only fair we let them know
 		// it will not be updated until next restart.
-		if(LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
+		if (LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
 		{
 			LLNotifications::instance().add("ChangeSocks5Settings", LLSD(), LLSD());
 			mSocksSettingsDirty = false; // we have notified the user now be quiet again
@@ -2023,7 +2022,7 @@ void LLFloaterPreferenceProxy::onBtnOk()
 
 	// Save SOCKS proxy credentials securely if password auth is enabled
 	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
-	if(socksAuth->getSelectedValue().asString() == "UserPass")
+	if (socksAuth->getSelectedValue().asString() == "UserPass")
 	{
 		LLSD socks_id = LLSD::emptyMap();
 		socks_id["type"] = "SOCKS5";
@@ -2080,7 +2079,7 @@ void LLFloaterPreferenceProxy::onChangeSocksSettings()
 	mSocksSettingsDirty = true;
 
 	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
-	if(socksAuth->getSelectedValue().asString() == "None")
+	if (socksAuth->getSelectedValue().asString() == "None")
 	{
 		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
 		getChild<LLLineEditor>("socks5_password")->setEnabled(false);
@@ -2093,7 +2092,7 @@ void LLFloaterPreferenceProxy::onChangeSocksSettings()
 
 	// Check for invalid states for the other HTTP proxy radio
 	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
-	if( (otherHttpProxy->getSelectedValue().asString() == "Socks" &&
+	if ((otherHttpProxy->getSelectedValue().asString() == "Socks" &&
 			getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
 					otherHttpProxy->getSelectedValue().asString() == "Web" &&
 					getChild<LLCheckBoxCtrl>("web_proxy_enabled")->get() == FALSE ) )
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 3661155e88..1fe241a8ce 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2827,7 +2827,6 @@ bool LLStartUp::handleSocksProxy()
 		// If status != SOCKS_OK, stopProxy() will already have been called when startProxy() returns.
 		int status = LLProxy::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
 		LLSD subs;
-		LLSD payload;
 		subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
 		subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
 
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index ef6763a5d1..c88e829527 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -318,7 +318,7 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
 		{
 			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if(LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
+			if (LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
 			{
 				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLProxy::getInstance()->getProxyUserPwdCURL());
 			}
-- 
cgit v1.2.3


From 792667ff8ef13e16823d96b490ea9a4f498425ea Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 19 Jul 2011 14:20:21 -0400
Subject: STORM-1112 Added LLProxy::applyProxySettings() to apply proxy
 settings to curl handles.

Added call to that function everywhere curl handles are created in the viewer.
---
 indra/llmessage/llcurl.cpp             | 125 ++-------------------------------
 indra/llmessage/llcurl.h               | 103 +++++++++++++++++++++++++++
 indra/llmessage/llhttpassetstorage.cpp |   5 ++
 indra/llmessage/llhttpclient.cpp       |   5 +-
 indra/llmessage/llproxy.cpp            |  88 +++++++++++++++++++++++
 indra/llmessage/llproxy.h              |  10 +++
 indra/llmessage/llurlrequest.cpp       |   2 +
 indra/newview/llxmlrpctransaction.cpp  |  20 +-----
 8 files changed, 217 insertions(+), 141 deletions(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index a7ce4310c1..2b6d3e5dc4 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -46,8 +46,8 @@
 #endif
 
 #include "llbufferstream.h"
-#include "llsdserialize.h"
 #include "llproxy.h"
+#include "llsdserialize.h"
 #include "llstl.h"
 #include "llthread.h"
 #include "lltimer.h"
@@ -216,73 +216,6 @@ namespace boost
 
 //////////////////////////////////////////////////////////////////////////////
 
-
-class LLCurl::Easy
-{
-	LOG_CLASS(Easy);
-
-private:
-	Easy();
-	
-public:
-	static Easy* getEasy();
-	~Easy();
-
-	CURL* getCurlHandle() const { return mCurlEasyHandle; }
-
-	void setErrorBuffer();
-	void setCA();
-	
-	void setopt(CURLoption option, S32 value);
-	// These assume the setter does not free value!
-	void setopt(CURLoption option, void* value);
-	void setopt(CURLoption option, char* value);
-	// Copies the string so that it is gauranteed to stick around
-	void setoptString(CURLoption option, const std::string& value);
-	
-	void slist_append(const char* str);
-	void setHeaders();
-	
-	U32 report(CURLcode);
-	void getTransferInfo(LLCurl::TransferInfo* info);
-
-	void prepRequest(const std::string& url, const std::vector<std::string>& headers, ResponderPtr, bool post = false);
-	
-	const char* getErrorBuffer();
-
-	std::stringstream& getInput() { return mInput; }
-	std::stringstream& getHeaderOutput() { return mHeaderOutput; }
-	LLIOPipe::buffer_ptr_t& getOutput() { return mOutput; }
-	const LLChannelDescriptors& getChannels() { return mChannels; }
-	
-	void resetState();
-
-	static CURL* allocEasyHandle();
-	static void releaseEasyHandle(CURL* handle);
-
-private:	
-	friend class LLCurl;
-
-	CURL*				mCurlEasyHandle;
-	struct curl_slist*	mHeaders;
-	
-	std::stringstream	mRequest;
-	LLChannelDescriptors mChannels;
-	LLIOPipe::buffer_ptr_t mOutput;
-	std::stringstream	mInput;
-	std::stringstream	mHeaderOutput;
-	char				mErrorBuffer[CURL_ERROR_SIZE];
-
-	// Note: char*'s not strings since we pass pointers to curl
-	std::vector<char*>	mStrings;
-	
-	ResponderPtr		mResponder;
-
-	static std::set<CURL*> sFreeHandles;
-	static std::set<CURL*> sActiveHandles;
-	static LLMutex* sHandleMutex;
-};
-
 std::set<CURL*> LLCurl::Easy::sFreeHandles;
 std::set<CURL*> LLCurl::Easy::sActiveHandles;
 LLMutex* LLCurl::Easy::sHandleMutex = NULL;
@@ -537,25 +470,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	setopt(CURLOPT_NOSIGNAL, 1);
 
 	// Set the CURL options for either Socks or HTTP proxy
-	if (LLProxy::getInstance()->isHTTPProxyEnabled())
-	{
-		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
-		setoptString(CURLOPT_PROXY, address.c_str());
-		setopt(CURLOPT_PROXYPORT, port);
-		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
-		{
-			setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
-			{
-				setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
-			}
-		}
-		else
-		{
-			setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-		}
-	}
+	LLProxy::getInstance()->applyProxySettings(this);
 
 	mOutput.reset(new LLBufferArray);
 	setopt(CURLOPT_WRITEFUNCTION, (void*)&curlWriteCallback);
@@ -602,40 +517,6 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 
 ////////////////////////////////////////////////////////////////////////////
 
-class LLCurl::Multi
-{
-	LOG_CLASS(Multi);
-public:
-	
-	Multi();
-	~Multi();
-
-	Easy* allocEasy();
-	bool addEasy(Easy* easy);
-	
-	void removeEasy(Easy* easy);
-
-	S32 process();
-	S32 perform();
-	
-	CURLMsg* info_read(S32* msgs_in_queue);
-
-	S32 mQueued;
-	S32 mErrorCount;
-	
-private:
-	void easyFree(Easy*);
-	
-	CURLM* mCurlMultiHandle;
-
-	typedef std::set<Easy*> easy_active_list_t;
-	easy_active_list_t mEasyActiveList;
-	typedef std::map<CURL*, Easy*> easy_active_map_t;
-	easy_active_map_t mEasyActiveMap;
-	typedef std::set<Easy*> easy_free_list_t;
-	easy_free_list_t mEasyFreeList;
-};
-
 LLCurl::Multi::Multi()
 	: mQueued(0),
 	  mErrorCount(0)
@@ -981,6 +862,8 @@ LLCurlEasyRequest::LLCurlEasyRequest()
 	{
 		mEasy->setErrorBuffer();
 		mEasy->setCA();
+		// Set proxy settings if configured to do so.
+		LLProxy::getInstance()->applyProxySettings(mEasy);
 	}
 }
 
diff --git a/indra/llmessage/llcurl.h b/indra/llmessage/llcurl.h
index 4ce3fa1078..5dd894d9b8 100644
--- a/indra/llmessage/llcurl.h
+++ b/indra/llmessage/llcurl.h
@@ -184,6 +184,106 @@ private:
 	static const unsigned int MAX_REDIRECTS;
 };
 
+class LLCurl::Easy
+{
+	LOG_CLASS(Easy);
+
+private:
+	Easy();
+
+public:
+	static Easy* getEasy();
+	~Easy();
+
+	CURL* getCurlHandle() const { return mCurlEasyHandle; }
+
+	void setErrorBuffer();
+	void setCA();
+
+	void setopt(CURLoption option, S32 value);
+	// These assume the setter does not free value!
+	void setopt(CURLoption option, void* value);
+	void setopt(CURLoption option, char* value);
+	// Copies the string so that it is guaranteed to stick around
+	void setoptString(CURLoption option, const std::string& value);
+
+	void slist_append(const char* str);
+	void setHeaders();
+
+	U32 report(CURLcode);
+	void getTransferInfo(LLCurl::TransferInfo* info);
+
+	void prepRequest(const std::string& url, const std::vector<std::string>& headers, ResponderPtr, bool post = false);
+
+	const char* getErrorBuffer();
+
+	std::stringstream& getInput() { return mInput; }
+	std::stringstream& getHeaderOutput() { return mHeaderOutput; }
+	LLIOPipe::buffer_ptr_t& getOutput() { return mOutput; }
+	const LLChannelDescriptors& getChannels() { return mChannels; }
+
+	void resetState();
+
+	static CURL* allocEasyHandle();
+	static void releaseEasyHandle(CURL* handle);
+
+private:
+	friend class LLCurl;
+
+	CURL*				mCurlEasyHandle;
+	struct curl_slist*	mHeaders;
+
+	std::stringstream	mRequest;
+	LLChannelDescriptors mChannels;
+	LLIOPipe::buffer_ptr_t mOutput;
+	std::stringstream	mInput;
+	std::stringstream	mHeaderOutput;
+	char				mErrorBuffer[CURL_ERROR_SIZE];
+
+	// Note: char*'s not strings since we pass pointers to curl
+	std::vector<char*>	mStrings;
+
+	ResponderPtr		mResponder;
+
+	static std::set<CURL*> sFreeHandles;
+	static std::set<CURL*> sActiveHandles;
+	static LLMutex* sHandleMutex;
+};
+
+class LLCurl::Multi
+{
+	LOG_CLASS(Multi);
+public:
+
+	Multi();
+	~Multi();
+
+	Easy* allocEasy();
+	bool addEasy(Easy* easy);
+
+	void removeEasy(Easy* easy);
+
+	S32 process();
+	S32 perform();
+
+	CURLMsg* info_read(S32* msgs_in_queue);
+
+	S32 mQueued;
+	S32 mErrorCount;
+
+private:
+	void easyFree(Easy*);
+
+	CURLM* mCurlMultiHandle;
+
+	typedef std::set<Easy*> easy_active_list_t;
+	easy_active_list_t mEasyActiveList;
+	typedef std::map<CURL*, Easy*> easy_active_map_t;
+	easy_active_map_t mEasyActiveMap;
+	typedef std::set<Easy*> easy_free_list_t;
+	easy_free_list_t mEasyFreeList;
+};
+
 namespace boost
 {
 	void intrusive_ptr_add_ref(LLCurl::Responder* p);
@@ -250,4 +350,7 @@ private:
 	bool mResultReturned;
 };
 
+void check_curl_code(CURLcode code);
+void check_curl_multi_code(CURLMcode code);
+
 #endif // LL_LLCURL_H
diff --git a/indra/llmessage/llhttpassetstorage.cpp b/indra/llmessage/llhttpassetstorage.cpp
index 5a38b7fd9f..2bca517e97 100644
--- a/indra/llmessage/llhttpassetstorage.cpp
+++ b/indra/llmessage/llhttpassetstorage.cpp
@@ -33,6 +33,7 @@
 
 #include "indra_constants.h"
 #include "message.h"
+#include "llproxy.h"
 #include "llvfile.h"
 #include "llvfs.h"
 
@@ -232,6 +233,10 @@ void LLHTTPAssetRequest::setupCurlHandle()
 {
 	// *NOTE: Similar code exists in mapserver/llcurlutil.cpp  JC
 	mCurlHandle = curl_easy_init();
+
+	// Apply proxy settings if configured to do so
+	LLProxy::getInstance()->applyProxySettings(mCurlHandle);
+
 	curl_easy_setopt(mCurlHandle, CURLOPT_NOSIGNAL, 1);
 	curl_easy_setopt(mCurlHandle, CURLOPT_NOPROGRESS, 1);
 	curl_easy_setopt(mCurlHandle, CURLOPT_URL, mURLBuffer.c_str());
diff --git a/indra/llmessage/llhttpclient.cpp b/indra/llmessage/llhttpclient.cpp
index 0e5206a520..dd4e3a6300 100644
--- a/indra/llmessage/llhttpclient.cpp
+++ b/indra/llmessage/llhttpclient.cpp
@@ -428,6 +428,9 @@ static LLSD blocking_request(
 	std::string body_str;
 	
 	// other request method checks root cert first, we skip?
+
+	// Apply configured proxy settings
+	LLProxy::getInstance()->applyProxySettings(curlp);
 	
 	// * Set curl handle options
 	curl_easy_setopt(curlp, CURLOPT_NOSIGNAL, 1);	// don't use SIGALRM for timeouts
@@ -436,7 +439,7 @@ static LLSD blocking_request(
 	curl_easy_setopt(curlp, CURLOPT_WRITEDATA, &http_buffer);
 	curl_easy_setopt(curlp, CURLOPT_URL, url.c_str());
 	curl_easy_setopt(curlp, CURLOPT_ERRORBUFFER, curl_error_buffer);
-	
+
 	// * Setup headers (don't forget to free them after the call!)
 	curl_slist* headers_list = NULL;
 	if (headers.isMap())
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 11a5c480f0..6040472cba 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -28,9 +28,12 @@
 
 #include "llproxy.h"
 
+#include <algorithm>
 #include <string>
+#include <curl/curl.h>
 
 #include "llapr.h"
+#include "llcurl.h"
 #include "llhost.h"
 #include "message.h"
 #include "net.h"
@@ -65,6 +68,10 @@ LLProxy::~LLProxy()
 	stopProxy();
 	sUDPProxyEnabled  = false;
 	sHTTPProxyEnabled = false;
+
+	// Delete c_str versions of the addresses and credentials.
+	for_each(mSOCKSAuthStrings.begin(), mSOCKSAuthStrings.end(), DeletePointerArray());
+	for_each(mSOCKSAddrStrings.begin(), mSOCKSAddrStrings.end(), DeletePointerArray());
 }
 
 // Perform a SOCKS 5 authentication and UDP association to the proxy
@@ -223,6 +230,11 @@ void LLProxy::setAuthPassword(const std::string &username, const std::string &pa
 	mAuthMethodSelected = METHOD_PASSWORD;
 	mSocksUsername      = username;
 	mSocksPassword      = password;
+
+	U32 size = username.length() + password.length() + 2;
+	char* curl_auth_string  = new char[size];
+	snprintf(curl_auth_string, size, "%s:%s", username.c_str(), password.c_str());
+	mSOCKSAuthStrings.push_back(curl_auth_string);
 }
 
 void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
@@ -230,6 +242,11 @@ void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 	sHTTPProxyEnabled = true;
 	mHTTPProxy        = httpHost;
 	mProxyType        = type;
+
+	U32 size = httpHost.getIPString().length() + 1;
+	char* socks_addr_string = new char[size];
+	strncpy(socks_addr_string, httpHost.getIPString().c_str(), size);
+	mSOCKSAddrStrings.push_back(socks_addr_string);
 }
 
 //static
@@ -238,6 +255,77 @@ void LLProxy::cleanupClass()
 	LLProxy::getInstance()->stopProxy();
 }
 
+// Apply proxy settings to CuRL request if either type of HTTP proxy is enabled.
+void LLProxy::applyProxySettings(LLCurl::Easy* handle)
+{
+	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	{
+		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		handle->setoptString(CURLOPT_PROXY, address.c_str());
+		handle->setopt(CURLOPT_PROXYPORT, port);
+		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		{
+			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
+			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			{
+				handle->setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
+			}
+		}
+		else
+		{
+			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+		}
+	}
+}
+
+void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
+{
+	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	{
+		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
+		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		handle->setoptString(CURLOPT_PROXY, address.c_str());
+		handle->setopt(CURLOPT_PROXYPORT, port);
+		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		{
+			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
+			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			{
+				handle->setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
+			}
+		}
+		else
+		{
+			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+		}
+	}
+}
+
+void LLProxy::applyProxySettings(CURL* handle)
+{
+	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	{
+		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXY, mSOCKSAddrStrings.back()));
+
+		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYPORT, port));
+
+		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		{
+			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5));
+			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			{
+				check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYUSERPWD, mSOCKSAuthStrings.back()));
+			}
+		}
+		else
+		{
+			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP));
+		}
+	}
+}
+
 static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
 {
 
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index cf2dfdc60e..7d1431a4b3 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -27,6 +27,7 @@
 #ifndef LL_PROXY_H
 #define LL_PROXY_H
 
+#include "llcurl.h"
 #include "llhost.h"
 #include "lliosocket.h"
 #include "llmemory.h"
@@ -211,6 +212,11 @@ public:
 	std::string getSocksPwd() const { return mSocksPassword; }
 	std::string getSocksUser() const { return mSocksUsername; }
 
+	// Apply the current proxy settings to a curl request. Doesn't do anything if sHTTPProxyEnabled is false.
+	void applyProxySettings(CURL* handle);
+	void applyProxySettings(LLCurl::Easy* handle);
+	void applyProxySettings(LLCurlEasyRequest* handle);
+
 private:
 
 	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
@@ -242,6 +248,10 @@ private:
 	// SOCKS 5 password
 	std::string mSocksPassword;
 
+	// Vectors to store valid pointers to string options that have been passed to CURL requests.
+	std::vector<char*> mSOCKSAuthStrings;
+	std::vector<char*> mSOCKSAddrStrings;
+
 	// APR pool for the socket
 	apr_pool_t* mPool;
 };
diff --git a/indra/llmessage/llurlrequest.cpp b/indra/llmessage/llurlrequest.cpp
index 28bd09fc4c..6fe9dce7d3 100644
--- a/indra/llmessage/llurlrequest.cpp
+++ b/indra/llmessage/llurlrequest.cpp
@@ -35,6 +35,7 @@
 #include "llcurl.h"
 #include "llioutil.h"
 #include "llmemtype.h"
+#include "llproxy.h"
 #include "llpumpio.h"
 #include "llsd.h"
 #include "llstring.h"
@@ -415,6 +416,7 @@ void LLURLRequest::initialize()
 	LLMemType m1(LLMemType::MTYPE_IO_URL_REQUEST);
 	mState = STATE_INITIALIZED;
 	mDetail = new LLURLRequestDetail;
+	LLProxy::getInstance()->applyProxySettings(mDetail->mCurlRequest);
 	mDetail->mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
 	mDetail->mCurlRequest->setWriteCallback(&downCallback, (void*)this);
 	mDetail->mCurlRequest->setReadCallback(&upCallback, (void*)this);
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index c88e829527..fe5ceea81d 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -309,25 +309,7 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 	}
 	mErrorCert = NULL;
 	
-	if (LLProxy::getInstance()->isHTTPProxyEnabled())
-	{
-		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
-		mCurlRequest->setoptString(CURLOPT_PROXY, address.c_str());
-		mCurlRequest->setopt(CURLOPT_PROXYPORT, port);
-		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
-		{
-			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (LLProxy::getInstance()->getSelectedAuthMethod()==METHOD_PASSWORD)
-			{
-				mCurlRequest->setoptString(CURLOPT_PROXYUSERPWD,LLProxy::getInstance()->getProxyUserPwdCURL());
-			}
-		}
-		else
-		{
-			mCurlRequest->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-		}
-	}
+	LLProxy::getInstance()->applyProxySettings(mCurlRequest);
 
 //	mCurlRequest->setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
-- 
cgit v1.2.3


From 859dc52c30a8c750047323399caa4fec18adfb2d Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 21 Jul 2011 15:16:54 -0400
Subject: STORM-1112 Protected LLProxy members during cross-thread calls to
 LLProxy::applyProxySettings()

---
 indra/llcommon/llsingleton.h     | 20 +++++++----
 indra/llmessage/llproxy.cpp      | 72 ++++++++++++++++++++++++++--------------
 indra/llmessage/llproxy.h        | 21 ++++++++----
 indra/llmessage/llurlrequest.cpp |  3 +-
 4 files changed, 75 insertions(+), 41 deletions(-)

diff --git a/indra/llcommon/llsingleton.h b/indra/llcommon/llsingleton.h
index 7aee1bb85f..00757be277 100644
--- a/indra/llcommon/llsingleton.h
+++ b/indra/llcommon/llsingleton.h
@@ -100,12 +100,6 @@ private:
 		DELETED
 	} EInitState;
 	
-	static void deleteSingleton()
-	{
-		delete getData().mSingletonInstance;
-		getData().mSingletonInstance = NULL;
-	}
-	
 	// stores pointer to singleton instance
 	// and tracks initialization state of singleton
 	struct SingletonInstanceData
@@ -120,7 +114,11 @@ private:
 
 		~SingletonInstanceData()
 		{
-			deleteSingleton();
+			SingletonInstanceData& data = getData();
+			if (data.mInitState != DELETED)
+			{
+				deleteSingleton();
+			}
 		}
 	};
 	
@@ -132,6 +130,14 @@ public:
 		data.mInitState = DELETED;
 	}
 
+	// Can be used to control when the singleton is deleted.  Not normally needed.
+	static void deleteSingleton()
+	{
+		delete getData().mSingletonInstance;
+		getData().mSingletonInstance = NULL;
+		getData().mInitState = DELETED;
+	}
+
 	static SingletonInstanceData& getData()
 	{
 		// this is static to cache the lookup results
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 6040472cba..d34ad1a811 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -59,7 +59,10 @@ LLProxy::LLProxy():
 		mAuthMethodSelected(METHOD_NOAUTH),
 		mSocksUsername(),
 		mSocksPassword(),
-		mPool(gAPRPoolp)
+		mPool(gAPRPoolp),
+		mSOCKSAuthStrings(),
+		mHTTPProxyAddrStrings(),
+		mProxyMutex(0)
 {
 }
 
@@ -71,7 +74,7 @@ LLProxy::~LLProxy()
 
 	// Delete c_str versions of the addresses and credentials.
 	for_each(mSOCKSAuthStrings.begin(), mSOCKSAuthStrings.end(), DeletePointerArray());
-	for_each(mSOCKSAddrStrings.begin(), mSOCKSAddrStrings.end(), DeletePointerArray());
+	for_each(mHTTPProxyAddrStrings.begin(), mHTTPProxyAddrStrings.end(), DeletePointerArray());
 }
 
 // Perform a SOCKS 5 authentication and UDP association to the proxy
@@ -211,7 +214,7 @@ void LLProxy::stopProxy()
 
 	if (LLPROXY_SOCKS == mProxyType)
 	{
-		sHTTPProxyEnabled = false;
+		void disableHTTPProxy();
 	}
 
 	if (mProxyControlChannel)
@@ -234,42 +237,61 @@ void LLProxy::setAuthPassword(const std::string &username, const std::string &pa
 	U32 size = username.length() + password.length() + 2;
 	char* curl_auth_string  = new char[size];
 	snprintf(curl_auth_string, size, "%s:%s", username.c_str(), password.c_str());
+
+	LLMutexLock lock(&mProxyMutex);
 	mSOCKSAuthStrings.push_back(curl_auth_string);
 }
 
 void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 { 
+	LLMutexLock lock(&mProxyMutex);
+
 	sHTTPProxyEnabled = true;
 	mHTTPProxy        = httpHost;
 	mProxyType        = type;
 
 	U32 size = httpHost.getIPString().length() + 1;
-	char* socks_addr_string = new char[size];
-	strncpy(socks_addr_string, httpHost.getIPString().c_str(), size);
-	mSOCKSAddrStrings.push_back(socks_addr_string);
+	char* http_addr_string = new char[size];
+	strncpy(http_addr_string, httpHost.getIPString().c_str(), size);
+	mHTTPProxyAddrStrings.push_back(http_addr_string);
+}
+
+void LLProxy::enableHTTPProxy()
+{
+	LLMutexLock lock(&mProxyMutex);
+
+	sHTTPProxyEnabled = true;
+}
+
+void LLProxy::disableHTTPProxy()
+{
+	LLMutexLock lock(&mProxyMutex);
+
+	sHTTPProxyEnabled = false;
 }
 
 //static
 void LLProxy::cleanupClass()
 {
-	LLProxy::getInstance()->stopProxy();
+	getInstance()->stopProxy();
+	deleteSingleton();
 }
 
 // Apply proxy settings to CuRL request if either type of HTTP proxy is enabled.
 void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 {
-	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	if (sHTTPProxyEnabled)
 	{
-		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		std::string address = mHTTPProxy.getIPString();
+		U16 port = mHTTPProxy.getPort();
 		handle->setoptString(CURLOPT_PROXY, address.c_str());
 		handle->setopt(CURLOPT_PROXYPORT, port);
-		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		if (mProxyType == LLPROXY_SOCKS)
 		{
 			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			if (mAuthMethodSelected == METHOD_PASSWORD)
 			{
-				handle->setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
+				handle->setoptString(CURLOPT_PROXYUSERPWD, getProxyUserPwdCURL());
 			}
 		}
 		else
@@ -281,18 +303,18 @@ void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 
 void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
 {
-	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	if (sHTTPProxyEnabled)
 	{
-		std::string address = LLProxy::getInstance()->getHTTPProxy().getIPString();
-		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		std::string address = mHTTPProxy.getIPString();
+		U16 port = mHTTPProxy.getPort();
 		handle->setoptString(CURLOPT_PROXY, address.c_str());
 		handle->setopt(CURLOPT_PROXYPORT, port);
-		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		if (mProxyType == LLPROXY_SOCKS)
 		{
 			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			if (mAuthMethodSelected == METHOD_PASSWORD)
 			{
-				handle->setoptString(CURLOPT_PROXYUSERPWD, LLProxy::getInstance()->getProxyUserPwdCURL());
+				handle->setoptString(CURLOPT_PROXYUSERPWD, getProxyUserPwdCURL());
 			}
 		}
 		else
@@ -304,17 +326,17 @@ void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
 
 void LLProxy::applyProxySettings(CURL* handle)
 {
-	if (LLProxy::getInstance()->isHTTPProxyEnabled())
+	LLMutexLock lock(&mProxyMutex);
+	if (sHTTPProxyEnabled)
 	{
-		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXY, mSOCKSAddrStrings.back()));
-
-		U16 port = LLProxy::getInstance()->getHTTPProxy().getPort();
+		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXY, mHTTPProxyAddrStrings.back()));
+		U16 port = mHTTPProxy.getPort();
 		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYPORT, port));
 
-		if (LLProxy::getInstance()->getHTTPProxyType() == LLPROXY_SOCKS)
+		if (mProxyType == LLPROXY_SOCKS)
 		{
 			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5));
-			if (LLProxy::getInstance()->getSelectedAuthMethod() == METHOD_PASSWORD)
+			if (mAuthMethodSelected == METHOD_PASSWORD)
 			{
 				check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYUSERPWD, mSOCKSAuthStrings.back()));
 			}
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 7d1431a4b3..df1ec9121e 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -32,6 +32,7 @@
 #include "lliosocket.h"
 #include "llmemory.h"
 #include "llsingleton.h"
+#include "llthread.h"
 #include <string>
 
 // Error codes returned from the StartProxy method
@@ -190,9 +191,10 @@ public:
 	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
 	// as specified in type
 	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
+	void enableHTTPProxy();
 
 	// Stop proxying HTTP packets
-	void disableHTTPProxy() { sHTTPProxyEnabled = false; }
+	void disableHTTPProxy();
 
 	// Get the UDP proxy address and port
 	LLHost getUDPProxy() const { return mUDPProxy; }
@@ -218,16 +220,17 @@ public:
 	void applyProxySettings(LLCurlEasyRequest* handle);
 
 private:
-
 	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
 	S32 proxyHandshake(LLHost proxy, U32 messagePort);
 
+private:
 	// socket handle to proxy TCP control channel
 	LLSocket::ptr_t mProxyControlChannel;
 
-	// is the UDP proxy enabled?
+	// Is the UDP proxy enabled?
 	static bool sUDPProxyEnabled;
-	// is the http proxy enabled?
+	// Is the HTTP proxy enabled? 
+	// Do not toggle directly, use enableHTTPProxy() and disableHTTPProxy()
 	static bool sHTTPProxyEnabled;
 
 	// currently selected http proxy type
@@ -235,7 +238,7 @@ private:
 
 	// UDP proxy address and port
 	LLHost mUDPProxy;
-	// TCP Proxy control channel address and port
+	// TCP proxy control channel address and port
 	LLHost mTCPProxy;
 	// HTTP proxy address and port
 	LLHost mHTTPProxy;
@@ -248,9 +251,13 @@ private:
 	// SOCKS 5 password
 	std::string mSocksPassword;
 
-	// Vectors to store valid pointers to string options that have been passed to CURL requests.
+	// Vectors to store valid pointers to string options that might have been set on CURL requests.
+	// This results in a behavior similar to LLCurl::Easy::setoptstring()
 	std::vector<char*> mSOCKSAuthStrings;
-	std::vector<char*> mSOCKSAddrStrings;
+	std::vector<char*> mHTTPProxyAddrStrings;
+
+	// Mutex to protect members in cross-thread calls to applyProxySettings()
+	LLMutex mProxyMutex;
 
 	// APR pool for the socket
 	apr_pool_t* mPool;
diff --git a/indra/llmessage/llurlrequest.cpp b/indra/llmessage/llurlrequest.cpp
index 6fe9dce7d3..528830dc56 100644
--- a/indra/llmessage/llurlrequest.cpp
+++ b/indra/llmessage/llurlrequest.cpp
@@ -228,8 +228,7 @@ void LLURLRequest::useProxy(bool use_proxy)
         }
     }
 
-
-    lldebugs << "use_proxy = " << (use_proxy?'Y':'N') << ", env_proxy = " << (env_proxy ? env_proxy : "(null)") << llendl;
+    LL_DEBUGS("Proxy") << "use_proxy = " << (use_proxy?'Y':'N') << ", env_proxy = " << (env_proxy ? env_proxy : "(null)") << LL_ENDL;
 
     if (env_proxy && use_proxy)
     {
-- 
cgit v1.2.3


From f15d28a636da7b6d2784d9301e7a030b5bd38a8c Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 28 Jul 2011 13:47:20 -0400
Subject: Proxy cleanup in llstartup.cpp and llproxy.cpp.

---
 indra/llmessage/llcurl.h                           |  2 +
 indra/llmessage/llproxy.cpp                        | 45 ++----------
 indra/newview/llstartup.cpp                        | 79 ++++++++++++----------
 .../newview/skins/default/xui/en/notifications.xml | 11 +++
 4 files changed, 62 insertions(+), 75 deletions(-)

diff --git a/indra/llmessage/llcurl.h b/indra/llmessage/llcurl.h
index 79f5eeb927..d60d3b6f40 100644
--- a/indra/llmessage/llcurl.h
+++ b/indra/llmessage/llcurl.h
@@ -355,6 +355,8 @@ public:
 	bool getResult(CURLcode* result, LLCurl::TransferInfo* info = NULL);
 	std::string getErrorString();
 
+	LLCurl::Easy* getEasy() const { return mEasy; }
+
 private:
 	CURLMsg* info_read(S32* queue, LLCurl::TransferInfo* info);
 	
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index d34ad1a811..e1970f1368 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -278,50 +278,15 @@ void LLProxy::cleanupClass()
 }
 
 // Apply proxy settings to CuRL request if either type of HTTP proxy is enabled.
-void LLProxy::applyProxySettings(LLCurl::Easy* handle)
+void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
 {
-	if (sHTTPProxyEnabled)
-	{
-		std::string address = mHTTPProxy.getIPString();
-		U16 port = mHTTPProxy.getPort();
-		handle->setoptString(CURLOPT_PROXY, address.c_str());
-		handle->setopt(CURLOPT_PROXYPORT, port);
-		if (mProxyType == LLPROXY_SOCKS)
-		{
-			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (mAuthMethodSelected == METHOD_PASSWORD)
-			{
-				handle->setoptString(CURLOPT_PROXYUSERPWD, getProxyUserPwdCURL());
-			}
-		}
-		else
-		{
-			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-		}
-	}
+	applyProxySettings(handle->getEasy());
 }
 
-void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
+
+void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 {
-	if (sHTTPProxyEnabled)
-	{
-		std::string address = mHTTPProxy.getIPString();
-		U16 port = mHTTPProxy.getPort();
-		handle->setoptString(CURLOPT_PROXY, address.c_str());
-		handle->setopt(CURLOPT_PROXYPORT, port);
-		if (mProxyType == LLPROXY_SOCKS)
-		{
-			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
-			if (mAuthMethodSelected == METHOD_PASSWORD)
-			{
-				handle->setoptString(CURLOPT_PROXYUSERPWD, getProxyUserPwdCURL());
-			}
-		}
-		else
-		{
-			handle->setopt(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
-		}
-	}
+	applyProxySettings(handle->getCurlHandle());
 }
 
 void LLProxy::applyProxySettings(CURL* handle)
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 1fe241a8ce..eca3e5439e 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2793,8 +2793,8 @@ bool LLStartUp::handleSocksProxy()
 		LLProxy::getInstance()->disableHTTPProxy();
 	}
 	
-	bool use_socks_proxy = gSavedSettings.getBOOL("Socks5ProxyEnabled");
-	if (use_socks_proxy)
+	// Set up SOCKS proxy (if needed)
+	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{	
 
 		// Determine and update LLProxy with the saved authentication system
@@ -2826,45 +2826,54 @@ bool LLStartUp::handleSocksProxy()
 		// Start the proxy and check for errors
 		// If status != SOCKS_OK, stopProxy() will already have been called when startProxy() returns.
 		int status = LLProxy::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
-		LLSD subs;
-		subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
-		subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
 
-		std::string error_string;
-
-		switch(status)
+		if (status == SOCKS_OK)
 		{
-			case SOCKS_OK:
-				return true;
-				break;
-
-			case SOCKS_CONNECT_ERROR: // TCP Fail
-				error_string = "SOCKS_CONNECT_ERROR";
-				break;
-
-			case SOCKS_NOT_PERMITTED: // SOCKS 5 server rule set refused connection
-				error_string = "SOCKS_NOT_PERMITTED";
-				break;
-					
-			case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
-				error_string = "SOCKS_NOT_ACCEPTABLE";
-				break;
+			return true;
+		}
+		else
+		{
+			LLSD subs;
+			subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
+			subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
 
-			case SOCKS_AUTH_FAIL: // Authentication failed
-				error_string = "SOCKS_AUTH_FAIL";
-				break;
+			std::string error_string;
 
-			case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
-				error_string = "SOCKS_UDP_FWD_NOT_GRANTED";
-				break;
+			switch(status)
+			{
+				case SOCKS_CONNECT_ERROR: // TCP Fail
+					error_string = "SOCKS_CONNECT_ERROR";
+					break;
+
+				case SOCKS_NOT_PERMITTED: // SOCKS 5 server rule set refused connection
+					error_string = "SOCKS_NOT_PERMITTED";
+					break;
+
+				case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
+					error_string = "SOCKS_NOT_ACCEPTABLE";
+					break;
+
+				case SOCKS_AUTH_FAIL: // Authentication failed
+					error_string = "SOCKS_AUTH_FAIL";
+					break;
+
+				case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
+					error_string = "SOCKS_UDP_FWD_NOT_GRANTED";
+					break;
+
+				case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
+					error_string = "SOCKS_HOST_CONNECT_FAILED";
+					break;
+
+				default:
+					error_string = "SOCKS_UNKNOWN_STATUS"; // Something strange happened,
+					LL_WARNS("Proxy") << "Unknown return from LLProxy::startProxy(): " << status << LL_ENDL;
+					break;
+			}
 
-			case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
-				error_string = "SOCKS_HOST_CONNECT_FAILED";
-				break;
+			LLNotificationsUtil::add(error_string, subs);
+			return false;
 		}
-
-		LLNotificationsUtil::add(error_string, subs);
-		return false;
 	}
 	else
 	{
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index 78685dbd79..8b7e6d8c4e 100644
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -7207,6 +7207,17 @@ Click and drag anywhere on the world to rotate your view
      name="okbutton"
      yestext="OK"/>
   </notification>
+  
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_UNKNOWN_STATUS"
+   type="alertmodal">
+	Unknown SOCKS error with server "[HOST]:[PORT]"
+	<tag>fail</tag>
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
 
   <notification
    icon="alertmodal.tga"
-- 
cgit v1.2.3


From d2c72cb7e92896cb414e357ef262d91b0498a6b7 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Fri, 29 Jul 2011 15:38:20 -0400
Subject: STORM-1112 Input sanitization of proxy options.

---
 indra/llmessage/llproxy.cpp                        | 79 +++++++++++++++-------
 indra/llmessage/llproxy.h                          | 18 +++--
 indra/newview/llfloaterpreference.cpp              | 10 ++-
 indra/newview/llstartup.cpp                        | 54 ++++++++++++---
 .../newview/skins/default/xui/en/notifications.xml | 44 ++++++++++++
 5 files changed, 163 insertions(+), 42 deletions(-)

diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index e1970f1368..381308fb2a 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -68,7 +68,7 @@ LLProxy::LLProxy():
 
 LLProxy::~LLProxy()
 {
-	stopProxy();
+	stopSOCKSProxy();
 	sUDPProxyEnabled  = false;
 	sHTTPProxyEnabled = false;
 
@@ -95,14 +95,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	if (result != 0)
 	{
 		LL_WARNS("Proxy") << "SOCKS authentication request failed, error on TCP control channel : " << result << LL_ENDL;
-		stopProxy();
+		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;
-		stopProxy();
+		stopSOCKSProxy();
 		return SOCKS_NOT_ACCEPTABLE;
 	}
 
@@ -126,14 +126,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 		if (result != 0)
 		{
 			LL_WARNS("Proxy") << "SOCKS authentication failed, error on TCP control channel : " << result << LL_ENDL;
-			stopProxy();
+			stopSOCKSProxy();
 			return SOCKS_CONNECT_ERROR;
 		}
 
 		if (password_reply.status != AUTH_SUCCESS)
 		{
 			LL_WARNS("Proxy") << "SOCKS authentication failed" << LL_ENDL;
-			stopProxy();
+			stopSOCKSProxy();
 			return SOCKS_AUTH_FAIL;
 		}
 	}
@@ -156,14 +156,14 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	if (result != 0)
 	{
 		LL_WARNS("Proxy") << "SOCKS connect request failed, error on TCP control channel : " << result << LL_ENDL;
-		stopProxy();
+		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;
-		stopProxy();
+		stopSOCKSProxy();
 		return SOCKS_UDP_FWD_NOT_GRANTED;
 	}
 
@@ -174,37 +174,49 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	return SOCKS_OK;
 }
 
-S32 LLProxy::startProxy(std::string host, U32 port)
+S32 LLProxy::startSOCKSProxy(LLHost host)
 {
-	mTCPProxy.setHostByName(host);
-	mTCPProxy.setPort(port);
+	S32 status = SOCKS_OK;
 
-	S32 status;
+	if (host.isOk())
+	{
+		mTCPProxy = host;
+	}
+	else
+	{
+		status = SOCKS_INVALID_HOST;
+	}
 
-	if (mProxyControlChannel)
+	if (mProxyControlChannel && status == SOCKS_OK)
 	{
 		tcp_close_channel(&mProxyControlChannel);
 	}
 
-	mProxyControlChannel = tcp_open_channel(mPool, mTCPProxy);
-	if (!mProxyControlChannel)
+	if (status == SOCKS_OK)
+	{
+		mProxyControlChannel = tcp_open_channel(mPool, mTCPProxy);
+		if (!mProxyControlChannel)
+		{
+			status = SOCKS_HOST_CONNECT_FAILED;
+		}
+	}
+
+	if (status == SOCKS_OK)
 	{
-		return SOCKS_HOST_CONNECT_FAILED;
+		status = proxyHandshake(mTCPProxy, (U32)gMessageSystem->mPort);
 	}
-	status = proxyHandshake(mTCPProxy, (U32)gMessageSystem->mPort);
 	if (status == SOCKS_OK)
 	{
 		sUDPProxyEnabled = true;
 	}
 	else
 	{
-		stopProxy();
+		stopSOCKSProxy();
 	}
 	return status;
-
 }
 
-void LLProxy::stopProxy()
+void LLProxy::stopSOCKSProxy()
 {
 	sUDPProxyEnabled = false;
 
@@ -228,8 +240,15 @@ void LLProxy::setAuthNone()
 	mAuthMethodSelected = METHOD_NOAUTH;
 }
 
-void LLProxy::setAuthPassword(const std::string &username, const std::string &password)
+bool LLProxy::setAuthPassword(const std::string &username, const std::string &password)
 {
+	if (username.length() > SOCKSMAXUSERNAMELEN || password.length() > SOCKSMAXPASSWORDLEN ||
+			username.length() < SOCKSMINUSERNAMELEN || password.length() < SOCKSMINPASSWORDLEN)
+	{
+		LL_WARNS("Proxy") << "Invalid SOCKS 5 password or username length." << LL_ENDL;
+		return false;
+	}
+
 	mAuthMethodSelected = METHOD_PASSWORD;
 	mSocksUsername      = username;
 	mSocksPassword      = password;
@@ -240,10 +259,18 @@ void LLProxy::setAuthPassword(const std::string &username, const std::string &pa
 
 	LLMutexLock lock(&mProxyMutex);
 	mSOCKSAuthStrings.push_back(curl_auth_string);
+
+	return true;
 }
 
-void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
-{ 
+bool LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
+{
+	if (httpHost.isOk())
+	{
+		LL_WARNS("Proxy") << "Invalid SOCKS 5 Server" << LL_ENDL;
+		return false;
+	}
+
 	LLMutexLock lock(&mProxyMutex);
 
 	sHTTPProxyEnabled = true;
@@ -254,13 +281,17 @@ void LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 	char* http_addr_string = new char[size];
 	strncpy(http_addr_string, httpHost.getIPString().c_str(), size);
 	mHTTPProxyAddrStrings.push_back(http_addr_string);
+
+	return true;
 }
 
-void LLProxy::enableHTTPProxy()
+bool LLProxy::enableHTTPProxy()
 {
 	LLMutexLock lock(&mProxyMutex);
 
 	sHTTPProxyEnabled = true;
+
+	return true;
 }
 
 void LLProxy::disableHTTPProxy()
@@ -273,7 +304,7 @@ void LLProxy::disableHTTPProxy()
 //static
 void LLProxy::cleanupClass()
 {
-	getInstance()->stopProxy();
+	getInstance()->stopSOCKSProxy();
 	deleteSingleton();
 }
 
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index df1ec9121e..ce5bdec5ad 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -44,11 +44,19 @@
 #define SOCKS_AUTH_FAIL (-4)
 #define SOCKS_UDP_FWD_NOT_GRANTED (-5)
 #define SOCKS_HOST_CONNECT_FAILED (-6)
+#define SOCKS_INVALID_HOST (-7)
+
 
 #ifndef MAXHOSTNAMELEN
 #define	MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */
 #endif
 
+#define SOCKSMAXUSERNAMELEN 255
+#define SOCKSMAXPASSWORDLEN 255
+
+#define SOCKSMINUSERNAMELEN 1
+#define SOCKSMINPASSWORDLEN 1
+
 #define SOCKS_VERSION 0x05 // we are using SOCKS 5
 
 #define SOCKS_HEADER_SIZE 10
@@ -165,16 +173,16 @@ public:
 	~LLProxy();
 
 	// Start a connection to the SOCKS 5 proxy
-	S32 startProxy(std::string host, U32 port);
+	S32 startSOCKSProxy(LLHost host);
 
 	// Disconnect and clean up any connection to the SOCKS 5 proxy
-	void stopProxy();
+	void stopSOCKSProxy();
 
 	// Delete LLProxy singleton, destroying the APR pool used by the control channel.
 	static void cleanupClass();
 
 	// Set up to use Password auth when connecting to the SOCKS proxy
-	void setAuthPassword(const std::string &username, const std::string &password);
+	bool setAuthPassword(const std::string &username, const std::string &password);
 
 	// Set up to use No Auth when connecting to the SOCKS proxy
 	void setAuthNone();
@@ -190,8 +198,8 @@ public:
 
 	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
 	// as specified in type
-	void enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
-	void enableHTTPProxy();
+	bool enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
+	bool enableHTTPProxy();
 
 	// Stop proxying HTTP packets
 	void disableHTTPProxy();
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index 84547ec38a..b01dc616a3 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -618,10 +618,10 @@ void LLFloaterPreference::cancel()
 		updateDoubleClickControls();
 		mDoubleClickActionDirty = false;
 	}
-	LLFloaterPreferenceProxy * advanced_socks_settings = LLFloaterReg::findTypedInstance<LLFloaterPreferenceProxy>("prefs_socks5_advanced");
-	if (advanced_socks_settings)
+	LLFloaterPreferenceProxy * advanced_proxy_settings = LLFloaterReg::findTypedInstance<LLFloaterPreferenceProxy>("prefs_proxy");
+	if (advanced_proxy_settings)
 	{
-		advanced_socks_settings->cancel();
+		advanced_proxy_settings->cancel();
 	}
 }
 
@@ -1937,6 +1937,10 @@ LLFloaterPreferenceProxy::~LLFloaterPreferenceProxy()
 BOOL LLFloaterPreferenceProxy::postBuild()
 {
 	LLRadioGroup* socksAuth = getChild<LLRadioGroup>("socks5_auth_type");
+	if (!socksAuth)
+	{
+		return FALSE;
+	}
 	if (socksAuth->getSelectedValue().asString() == "None")
 	{
 		getChild<LLLineEditor>("socks5_username")->setEnabled(false);
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index eca3e5439e..c934ff9f1b 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -825,7 +825,7 @@ bool idle_startup()
 			if (!LLStartUp::handleSocksProxy())
 			{
 				// Proxy start up failed, we should now bail the state machine
-				// HandleSocksProxy() will have reported an error to the user 
+				// handleSocksProxy() will have reported an error to the user
 				// already, so we just go back to the login screen. The user
 				// could then change the preferences to fix the issue. 
 				LLStartUp::setStartupState(STATE_LOGIN_SHOW);
@@ -834,11 +834,11 @@ bool idle_startup()
 		}
 		else
 		{
-			LLProxy::getInstance()->stopProxy();
+			LLProxy::getInstance()->stopSOCKSProxy();
 		}
 		
 
-		//reset the values that could have come in from a slurl
+		// reset the values that could have come in from a slurl
 		// DEV-42215: Make sure they're not empty -- gUserCredential
 		// might already have been set from gSavedSettings, and it's too bad
 		// to overwrite valid values with empty strings.
@@ -2779,20 +2779,40 @@ bool LLStartUp::handleSocksProxy()
 		LLHost http_host;
 		http_host.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
 		http_host.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		LLProxy::getInstance()->enableHTTPProxy(http_host, LLPROXY_HTTP);
+		if (!LLProxy::getInstance()->enableHTTPProxy(http_host, LLPROXY_HTTP))
+		{
+			LLSD subs;
+			subs["HOST"] = http_host.getIPString();
+			subs["PORT"] = (S32)http_host.getPort();
+			LLNotificationsUtil::add("PROXY_INVALID_HTTP_HOST", subs);
+		}
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{
 		LLHost socks_host;
 		socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
 		socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		LLProxy::getInstance()->enableHTTPProxy(socks_host, LLPROXY_SOCKS);
+		if (!LLProxy::getInstance()->enableHTTPProxy(socks_host, LLPROXY_SOCKS))
+		{
+			LLSD subs;
+			subs["HOST"] = socks_host.getIPString();
+			subs["PORT"] = (S32)socks_host.getPort();
+			LLNotificationsUtil::add("PROXY_INVALID_SOCKS_HOST", subs);
+		}
+
+
+	}
+	else if (httpProxyType.compare("None") == 0)
+	{
+		LLProxy::getInstance()->disableHTTPProxy();
 	}
 	else
 	{
+		LL_WARNS("Proxy") << "Invalid HTTP proxy configuration."<< LL_ENDL;
+		gSavedSettings.setString("Socks5HttpProxyType", "None");
 		LLProxy::getInstance()->disableHTTPProxy();
 	}
-	
+
 	// Set up SOCKS proxy (if needed)
 	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{	
@@ -2805,7 +2825,14 @@ bool LLStartUp::handleSocksProxy()
 			LLPointer<LLCredential> socks_cred = gSecAPIHandler->loadCredential("SOCKS5");
 			std::string socks_user = socks_cred->getIdentifier()["username"].asString();
 			std::string socks_password = socks_cred->getAuthenticator()["creds"].asString();
-			LLProxy::getInstance()->setAuthPassword(socks_user, socks_password);
+
+			bool ok;
+			ok = LLProxy::getInstance()->setAuthPassword(socks_user, socks_password);
+			if (!ok)
+			{
+				LLNotificationsUtil::add("SOCKS_BAD_CREDS");
+			}
+
 		}
 		else if (auth_type.compare("None") == 0)
 		{
@@ -2824,8 +2851,11 @@ bool LLStartUp::handleSocksProxy()
 		}
 
 		// Start the proxy and check for errors
-		// If status != SOCKS_OK, stopProxy() will already have been called when startProxy() returns.
-		int status = LLProxy::getInstance()->startProxy(gSavedSettings.getString("Socks5ProxyHost"), gSavedSettings.getU32("Socks5ProxyPort"));
+		// If status != SOCKS_OK, stopSOCKSProxy() will already have been called when startSOCKSProxy() returns.
+		LLHost socks_host;
+		socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
+		socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
+		int status = LLProxy::getInstance()->startSOCKSProxy(socks_host);
 
 		if (status == SOCKS_OK)
 		{
@@ -2865,6 +2895,10 @@ bool LLStartUp::handleSocksProxy()
 					error_string = "SOCKS_HOST_CONNECT_FAILED";
 					break;
 
+				case SOCKS_INVALID_HOST: // Improperly formatted host address or port.
+					error_string = "SOCKS_INVALID_HOST";
+					break;
+
 				default:
 					error_string = "SOCKS_UNKNOWN_STATUS"; // Something strange happened,
 					LL_WARNS("Proxy") << "Unknown return from LLProxy::startProxy(): " << status << LL_ENDL;
@@ -2877,7 +2911,7 @@ bool LLStartUp::handleSocksProxy()
 	}
 	else
 	{
-		LLProxy::getInstance()->stopProxy(); // ensure no UDP proxy is running and it's all cleaned up
+		LLProxy::getInstance()->stopSOCKSProxy(); // ensure no UDP proxy is running and it's all cleaned up
 	}
 
 	return true;
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index 8b7e6d8c4e..ccc678d942 100644
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -7218,6 +7218,50 @@ Click and drag anywhere on the world to rotate your view
      name="okbutton"
      yestext="OK"/>
   </notification>
+  
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_INVALID_HOST"
+   type="alertmodal">
+	Invalid SOCKS proxy address or port "[HOST]:[PORT]".
+	<tag>fail</tag>
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+  
+  <notification
+   icon="alertmodal.tga"
+   name="SOCKS_BAD_CREDS"
+   type="alertmodal">
+	Invalid SOCKS 5 username or password.
+	<tag>fail</tag>
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+  
+  <notification
+   icon="alertmodal.tga"
+   name="PROXY_INVALID_HTTP_HOST"
+   type="alertmodal">
+    Invalid HTTP proxy address or port "[HOST]:[PORT]".
+	<tag>fail</tag>
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
+
+  <notification
+   icon="alertmodal.tga"
+   name="PROXY_INVALID_SOCKS_HOST"
+   type="alertmodal">
+	Invalid SOCKS proxy address or port "[HOST]:[PORT]".
+	<tag>fail</tag>
+   <usetemplate
+     name="okbutton"
+     yestext="OK"/>
+  </notification>
 
   <notification
    icon="alertmodal.tga"
-- 
cgit v1.2.3


From 97bedac2a1274f26a6a346afccea7596f1d13923 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 2 Aug 2011 11:08:07 -0400
Subject: Proxy: Improved mutex usage in LLProxy. Introduced an LLAtomic member
 to track the status of the http proxy that can be checked without locking a
 mutex.

---
 indra/llmessage/llproxy.cpp | 129 ++++++++++++++++++++++++++------------------
 indra/llmessage/llproxy.h   |  72 ++++++++++++-------------
 indra/newview/llstartup.cpp |  11 ++--
 3 files changed, 119 insertions(+), 93 deletions(-)

diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index 381308fb2a..b224757673 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -1,6 +1,6 @@
 /**
- * @file llsocks5.cpp
- * @brief SOCKS 5 implementation
+ * @file llproxy.cpp
+ * @brief UDP and HTTP proxy communications
  *
  * $LicenseInfo:firstyear=2011&license=viewerlgpl$
  * Second Life Viewer Source Code
@@ -28,7 +28,6 @@
 
 #include "llproxy.h"
 
-#include <algorithm>
 #include <string>
 #include <curl/curl.h>
 
@@ -44,7 +43,6 @@
 // incoming packet just to do a simple bool test. The getter for this
 // member is also static
 bool LLProxy::sUDPProxyEnabled = false;
-bool LLProxy::sHTTPProxyEnabled = false;
 
 // Some helpful TCP functions
 static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host); // Open a TCP channel to a given host
@@ -52,17 +50,16 @@ static void tcp_close_channel(LLSocket::ptr_t* handle_ptr); // Close an open TCP
 static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
 
 LLProxy::LLProxy():
-		mProxyType(LLPROXY_SOCKS),
+		mHTTPProxyEnabled(false),
+		mProxyMutex(0),
 		mUDPProxy(),
 		mTCPProxy(),
+		mPool(gAPRPoolp),
 		mHTTPProxy(),
+		mProxyType(LLPROXY_SOCKS),
 		mAuthMethodSelected(METHOD_NOAUTH),
 		mSocksUsername(),
-		mSocksPassword(),
-		mPool(gAPRPoolp),
-		mSOCKSAuthStrings(),
-		mHTTPProxyAddrStrings(),
-		mProxyMutex(0)
+		mSocksPassword()
 {
 }
 
@@ -70,11 +67,7 @@ LLProxy::~LLProxy()
 {
 	stopSOCKSProxy();
 	sUDPProxyEnabled  = false;
-	sHTTPProxyEnabled = false;
-
-	// Delete c_str versions of the addresses and credentials.
-	for_each(mSOCKSAuthStrings.begin(), mSOCKSAuthStrings.end(), DeletePointerArray());
-	for_each(mHTTPProxyAddrStrings.begin(), mHTTPProxyAddrStrings.end(), DeletePointerArray());
+	mHTTPProxyEnabled = false;
 }
 
 // Perform a SOCKS 5 authentication and UDP association to the proxy
@@ -89,7 +82,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 
 	socks_auth_request.version     = SOCKS_VERSION;       // SOCKS version 5
 	socks_auth_request.num_methods = 1;                   // Sending 1 method.
-	socks_auth_request.methods     = mAuthMethodSelected; // Send only the selected method.
+	socks_auth_request.methods     = getSelectedAuthMethod(); // Send only the selected method.
 
 	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request), (char*)&socks_auth_response, sizeof(socks_auth_response));
 	if (result != 0)
@@ -110,13 +103,15 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	if (socks_auth_response.method == METHOD_PASSWORD)
 	{
 		// The server has requested a username/password combination
-		U32 request_size = mSocksUsername.size() + mSocksPassword.size() + 3;
+		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] = mSocksUsername.size();
-		memcpy(&password_auth[2], mSocksUsername.c_str(), mSocksUsername.size());
-		password_auth[mSocksUsername.size() + 2] = mSocksPassword.size();
-		memcpy(&password_auth[mSocksUsername.size()+3], mSocksPassword.c_str(), mSocksPassword.size());
+		password_auth[1] = socks_username.size();
+		memcpy(&password_auth[2], socks_username.c_str(), socks_username.size());
+		password_auth[socks_username.size() + 2] = socks_password.size();
+		memcpy(&password_auth[socks_username.size()+3], socks_password.c_str(), socks_password.size());
 
 		authmethod_password_reply_t password_reply;
 
@@ -224,7 +219,7 @@ void LLProxy::stopSOCKSProxy()
 	// then we must shut down any HTTP proxy operations. But it is allowable if web
 	// proxy is being used to continue proxying HTTP.
 
-	if (LLPROXY_SOCKS == mProxyType)
+	if (LLPROXY_SOCKS == getHTTPProxyType())
 	{
 		void disableHTTPProxy();
 	}
@@ -237,6 +232,8 @@ void LLProxy::stopSOCKSProxy()
 
 void LLProxy::setAuthNone()
 {
+	LLMutexLock lock(&mProxyMutex);
+
 	mAuthMethodSelected = METHOD_NOAUTH;
 }
 
@@ -249,23 +246,18 @@ bool LLProxy::setAuthPassword(const std::string &username, const std::string &pa
 		return false;
 	}
 
+	LLMutexLock lock(&mProxyMutex);
+
 	mAuthMethodSelected = METHOD_PASSWORD;
 	mSocksUsername      = username;
 	mSocksPassword      = password;
 
-	U32 size = username.length() + password.length() + 2;
-	char* curl_auth_string  = new char[size];
-	snprintf(curl_auth_string, size, "%s:%s", username.c_str(), password.c_str());
-
-	LLMutexLock lock(&mProxyMutex);
-	mSOCKSAuthStrings.push_back(curl_auth_string);
-
 	return true;
 }
 
 bool LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 {
-	if (httpHost.isOk())
+	if (!httpHost.isOk())
 	{
 		LL_WARNS("Proxy") << "Invalid SOCKS 5 Server" << LL_ENDL;
 		return false;
@@ -273,14 +265,10 @@ bool LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 
 	LLMutexLock lock(&mProxyMutex);
 
-	sHTTPProxyEnabled = true;
 	mHTTPProxy        = httpHost;
 	mProxyType        = type;
 
-	U32 size = httpHost.getIPString().length() + 1;
-	char* http_addr_string = new char[size];
-	strncpy(http_addr_string, httpHost.getIPString().c_str(), size);
-	mHTTPProxyAddrStrings.push_back(http_addr_string);
+	mHTTPProxyEnabled = true;
 
 	return true;
 }
@@ -289,7 +277,7 @@ bool LLProxy::enableHTTPProxy()
 {
 	LLMutexLock lock(&mProxyMutex);
 
-	sHTTPProxyEnabled = true;
+	mHTTPProxyEnabled = true;
 
 	return true;
 }
@@ -298,7 +286,40 @@ void LLProxy::disableHTTPProxy()
 {
 	LLMutexLock lock(&mProxyMutex);
 
-	sHTTPProxyEnabled = false;
+	mHTTPProxyEnabled = false;
+}
+
+// Get the HTTP proxy address and port
+LLHost LLProxy::getHTTPProxy() const
+{
+	LLMutexLock lock(&mProxyMutex);
+	return mHTTPProxy;
+}
+
+// Get the currently selected HTTP proxy type
+LLHttpProxyType LLProxy::getHTTPProxyType() const
+{
+	LLMutexLock lock(&mProxyMutex);
+	return mProxyType;
+}
+
+std::string LLProxy::getSocksPwd() const
+{
+	LLMutexLock lock(&mProxyMutex);
+	return mSocksPassword;
+}
+
+std::string LLProxy::getSocksUser() const
+{
+	LLMutexLock lock(&mProxyMutex);
+	return mSocksUsername;
+}
+
+// get the currently selected auth method
+LLSocks5AuthType LLProxy::getSelectedAuthMethod() const
+{
+	LLMutexLock lock(&mProxyMutex);
+	return mAuthMethodSelected;
 }
 
 //static
@@ -322,24 +343,30 @@ void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 
 void LLProxy::applyProxySettings(CURL* handle)
 {
-	LLMutexLock lock(&mProxyMutex);
-	if (sHTTPProxyEnabled)
+	// Do a faster unlocked check to see if we are supposed to proxy.
+	if (mHTTPProxyEnabled)
 	{
-		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXY, mHTTPProxyAddrStrings.back()));
-		U16 port = mHTTPProxy.getPort();
-		check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYPORT, port));
-
-		if (mProxyType == LLPROXY_SOCKS)
+		// We think we should proxy, lock the proxy mutex.
+		LLMutexLock lock(&mProxyMutex);
+		// Now test again to verify that the proxy wasn't disabled between the first check and the lock.
+		if (mHTTPProxyEnabled)
 		{
-			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5));
-			if (mAuthMethodSelected == METHOD_PASSWORD)
+			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXY, mHTTPProxy.getIPString().c_str()));
+			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYPORT, mHTTPProxy.getPort()));
+
+			if (mProxyType == LLPROXY_SOCKS)
 			{
-				check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYUSERPWD, mSOCKSAuthStrings.back()));
+				check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5));
+				if (mAuthMethodSelected == METHOD_PASSWORD)
+				{
+					std::string auth_string = mSocksUsername + ":" + mSocksPassword;
+					check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYUSERPWD, auth_string.c_str()));
+				}
+			}
+			else
+			{
+				check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP));
 			}
-		}
-		else
-		{
-			check_curl_code(curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP));
 		}
 	}
 }
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index ce5bdec5ad..22954f2733 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -1,6 +1,6 @@
 /**
- * @file llsocks5.h
- * @brief Socks 5 implementation
+ * @file llproxy.h
+ * @brief UDP and HTTP proxy communications
  *
  * $LicenseInfo:firstyear=2011&license=viewerlgpl$
  * Second Life Viewer Source Code
@@ -188,13 +188,14 @@ public:
 	void setAuthNone();
 
 	// get the currently selected auth method
-	LLSocks5AuthType getSelectedAuthMethod() const { return mAuthMethodSelected; }
+	LLSocks5AuthType getSelectedAuthMethod() const;
 
 	// static check for enabled status for UDP packets
 	static bool isEnabled() { return sUDPProxyEnabled; }
 
-	// static check for enabled status for http packets
-	static bool isHTTPProxyEnabled() { return sHTTPProxyEnabled; }
+	// check for enabled status for HTTP packets
+	// mHTTPProxyEnabled is atomic, so no locking is required for thread safety.
+	bool isHTTPProxyEnabled() const { return mHTTPProxyEnabled; }
 
 	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
 	// as specified in type
@@ -204,6 +205,11 @@ public:
 	// Stop proxying HTTP packets
 	void disableHTTPProxy();
 
+	// Apply the current proxy settings to a curl request. Doesn't do anything if mHTTPProxyEnabled is false.
+	void applyProxySettings(CURL* handle);
+	void applyProxySettings(LLCurl::Easy* handle);
+	void applyProxySettings(LLCurlEasyRequest* handle);
+
 	// Get the UDP proxy address and port
 	LLHost getUDPProxy() const { return mUDPProxy; }
 
@@ -211,46 +217,51 @@ public:
 	LLHost getTCPProxy() const { return mTCPProxy; }
 
 	// Get the HTTP proxy address and port
-	LLHost getHTTPProxy() const { return mHTTPProxy; }
+	LLHost getHTTPProxy() const;
 
 	// Get the currently selected HTTP proxy type
-	LLHttpProxyType getHTTPProxyType() const { return mProxyType; }
+	LLHttpProxyType getHTTPProxyType() const;
 
-	// Get the username password in a curl compatible format
-	std::string getProxyUserPwdCURL() const { return (mSocksUsername + ":" + mSocksPassword); }
-
-	std::string getSocksPwd() const { return mSocksPassword; }
-	std::string getSocksUser() const { return mSocksUsername; }
-
-	// Apply the current proxy settings to a curl request. Doesn't do anything if sHTTPProxyEnabled is false.
-	void applyProxySettings(CURL* handle);
-	void applyProxySettings(LLCurl::Easy* handle);
-	void applyProxySettings(LLCurlEasyRequest* handle);
+	std::string getSocksPwd() const;
+	std::string getSocksUser() const;
 
 private:
 	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
 	S32 proxyHandshake(LLHost proxy, U32 messagePort);
 
 private:
-	// socket handle to proxy TCP control channel
-	LLSocket::ptr_t mProxyControlChannel;
+	// Is the HTTP proxy enabled?
+	// Safe to read in any thread, do not write directly,
+	// use enableHTTPProxy() and disableHTTPProxy() instead.
+	mutable LLAtomic32<bool> mHTTPProxyEnabled;
+
+	// Mutex to protect shared members in non-main thread calls to applyProxySettings()
+	mutable LLMutex mProxyMutex;
+
+	// MEMBERS READ AND WRITTEN ONLY IN THE MAIN THREAD. DO NOT SHARE!
 
 	// Is the UDP proxy enabled?
 	static bool sUDPProxyEnabled;
-	// Is the HTTP proxy enabled? 
-	// Do not toggle directly, use enableHTTPProxy() and disableHTTPProxy()
-	static bool sHTTPProxyEnabled;
-
-	// currently selected http proxy type
-	LLHttpProxyType mProxyType;
 
 	// UDP proxy address and port
 	LLHost mUDPProxy;
 	// TCP proxy control channel address and port
 	LLHost mTCPProxy;
+
+	// socket handle to proxy TCP control channel
+	LLSocket::ptr_t mProxyControlChannel;
+
+	// APR pool for the socket
+	apr_pool_t* mPool;
+
+	// MEMBERS WRITTEN IN MAIN THREAD AND READ IN ANY THREAD. ONLY READ OR WRITE AFTER LOCKING mProxyMutex!
+
 	// HTTP proxy address and port
 	LLHost mHTTPProxy;
 
+	// Currently selected HTTP proxy type. Can be web or socks.
+	LLHttpProxyType mProxyType;
+
 	// SOCKS 5 auth method selected
 	LLSocks5AuthType mAuthMethodSelected;
 
@@ -258,17 +269,6 @@ private:
 	std::string mSocksUsername;
 	// SOCKS 5 password
 	std::string mSocksPassword;
-
-	// Vectors to store valid pointers to string options that might have been set on CURL requests.
-	// This results in a behavior similar to LLCurl::Easy::setoptstring()
-	std::vector<char*> mSOCKSAuthStrings;
-	std::vector<char*> mHTTPProxyAddrStrings;
-
-	// Mutex to protect members in cross-thread calls to applyProxySettings()
-	LLMutex mProxyMutex;
-
-	// APR pool for the socket
-	apr_pool_t* mPool;
 };
 
 #endif
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index c934ff9f1b..3ec5842e3c 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2785,6 +2785,7 @@ bool LLStartUp::handleSocksProxy()
 			subs["HOST"] = http_host.getIPString();
 			subs["PORT"] = (S32)http_host.getPort();
 			LLNotificationsUtil::add("PROXY_INVALID_HTTP_HOST", subs);
+			return false;
 		}
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
@@ -2798,9 +2799,8 @@ bool LLStartUp::handleSocksProxy()
 			subs["HOST"] = socks_host.getIPString();
 			subs["PORT"] = (S32)socks_host.getPort();
 			LLNotificationsUtil::add("PROXY_INVALID_SOCKS_HOST", subs);
+			return false;
 		}
-
-
 	}
 	else if (httpProxyType.compare("None") == 0)
 	{
@@ -2816,7 +2816,6 @@ bool LLStartUp::handleSocksProxy()
 	// Set up SOCKS proxy (if needed)
 	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{	
-
 		// Determine and update LLProxy with the saved authentication system
 		std::string auth_type = gSavedSettings.getString("Socks5AuthType");
 
@@ -2826,13 +2825,13 @@ bool LLStartUp::handleSocksProxy()
 			std::string socks_user = socks_cred->getIdentifier()["username"].asString();
 			std::string socks_password = socks_cred->getAuthenticator()["creds"].asString();
 
-			bool ok;
-			ok = LLProxy::getInstance()->setAuthPassword(socks_user, socks_password);
+			bool ok = LLProxy::getInstance()->setAuthPassword(socks_user, socks_password);
+
 			if (!ok)
 			{
 				LLNotificationsUtil::add("SOCKS_BAD_CREDS");
+				return false;
 			}
-
 		}
 		else if (auth_type.compare("None") == 0)
 		{
-- 
cgit v1.2.3


From d3b4cc34a8d388ab66ef2ca717ee0d814d87ff3d Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 2 Aug 2011 17:18:54 -0400
Subject: LLProxy cleanup.

* Removed early returns in LLStartup::handleSocksProxy
* Corrected some cases that would result in handleSocksProxy not being called again during login if settings changed
* Allowed for short replies in tcp_handshake in LLProxy.cpp
* Renamed LLProxy::isEnabled() to LLProxy::isSocksProxyEnabled() to clarify its use.
---
 indra/llmessage/llpacketring.cpp |   4 +-
 indra/llmessage/llproxy.cpp      |  12 ++--
 indra/llmessage/llproxy.h        |   2 +-
 indra/newview/llstartup.cpp      | 141 +++++++++++++++++++--------------------
 4 files changed, 79 insertions(+), 80 deletions(-)

diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp
index ba82957b47..7628984de4 100644
--- a/indra/llmessage/llpacketring.cpp
+++ b/indra/llmessage/llpacketring.cpp
@@ -225,7 +225,7 @@ S32 LLPacketRing::receivePacket (S32 socket, char *datap)
 	else
 	{
 		// no delay, pull straight from net
-		if (LLProxy::isEnabled())
+		if (LLProxy::isSOCKSProxyEnabled())
 		{
 			U8 buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE];
 			packet_size = receive_packet(socket, reinterpret_cast<char *>(buffer));
@@ -348,7 +348,7 @@ BOOL LLPacketRing::sendPacket(int h_socket, char * send_buffer, S32 buf_size, LL
 BOOL LLPacketRing::sendPacketImpl(int h_socket, const char * send_buffer, S32 buf_size, LLHost host)
 {
 	
-	if (!LLProxy::isEnabled())
+	if (!LLProxy::isSOCKSProxyEnabled())
 	{
 		return send_packet(h_socket, send_buffer, buf_size, host.getAddress(), host.getPort());
 	}
diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index b224757673..d2e64e60ac 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -382,14 +382,15 @@ static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outl
 	handle->setBlocking(1000);
 
   	rv = apr_socket_send(apr_socket, dataout, &outlen);
-	if (APR_SUCCESS != rv || expected_len != outlen)
+	if (APR_SUCCESS != rv)
 	{
-		LL_WARNS("Proxy") << "Error sending data to proxy control channel" << LL_ENDL;
+		LL_WARNS("Proxy") << "Error sending data to proxy control channel, status: " << rv << LL_ENDL;
 		ll_apr_warn_status(rv);
 	}
 	else if (expected_len != outlen)
 	{
-		LL_WARNS("Proxy") << "Error sending data to proxy control channel" << LL_ENDL;
+		LL_WARNS("Proxy") << "Incorrect data length sent. Expected: " << expected_len <<
+				" Sent: " << outlen << LL_ENDL;
 		rv = -1;
 	}
 
@@ -402,9 +403,10 @@ static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outl
 			LL_WARNS("Proxy") << "Error receiving data from proxy control channel, status: " << rv << LL_ENDL;
 			ll_apr_warn_status(rv);
 		}
-		else if (expected_len != maxinlen)
+		else if (expected_len < maxinlen)
 		{
-			LL_WARNS("Proxy") << "Received incorrect amount of data in proxy control channel" << LL_ENDL;
+			LL_WARNS("Proxy") << "Incorrect data length received. Expected: " << expected_len <<
+					" Received: " << maxinlen << LL_ENDL;
 			rv = -1;
 		}
 	}
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 22954f2733..68c40561c8 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -191,7 +191,7 @@ public:
 	LLSocks5AuthType getSelectedAuthMethod() const;
 
 	// static check for enabled status for UDP packets
-	static bool isEnabled() { return sUDPProxyEnabled; }
+	static bool isSOCKSProxyEnabled() { return sUDPProxyEnabled; }
 
 	// check for enabled status for HTTP packets
 	// mHTTPProxyEnabled is atomic, so no locking is required for thread safety.
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 3ec5842e3c..25af63c0d3 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -598,6 +598,9 @@ bool idle_startup()
 		// connection if the user is using SOCKS 5
 		// We need to do this early in case the user is using
 		// socks for HTTP so we get the login screen via SOCKS
+		// We don't do anything if proxy setup was
+		// unsuccessful, since the user can configure their
+		// proxy settings before starting to log in.
 		//-------------------------------------------------
 
 		LLStartUp::handleSocksProxy();
@@ -820,23 +823,16 @@ bool idle_startup()
 		// Post login screen, we should see if any settings have changed that may
 		// require us to either start/stop or change the socks proxy. As various communications
 		// past this point may require the proxy to be up.
-		if ( gSavedSettings.getBOOL("Socks5ProxyEnabled") )
+		if (!LLStartUp::handleSocksProxy())
 		{
-			if (!LLStartUp::handleSocksProxy())
-			{
-				// Proxy start up failed, we should now bail the state machine
-				// handleSocksProxy() will have reported an error to the user
-				// already, so we just go back to the login screen. The user
-				// could then change the preferences to fix the issue. 
-				LLStartUp::setStartupState(STATE_LOGIN_SHOW);
-				return FALSE;
-			}
-		}
-		else
-		{
-			LLProxy::getInstance()->stopSOCKSProxy();
+			// Proxy start up failed, we should now bail the state machine
+			// handleSocksProxy() will have reported an error to the user
+			// already, so we just go back to the login screen. The user
+			// could then change the preferences to fix the issue.
+
+			LLStartUp::setStartupState(STATE_LOGIN_SHOW);
+			return FALSE;
 		}
-		
 
 		// reset the values that could have come in from a slurl
 		// DEV-42215: Make sure they're not empty -- gUserCredential
@@ -2771,6 +2767,7 @@ void LLStartUp::setStartSLURL(const LLSLURL& slurl)
 
 bool LLStartUp::handleSocksProxy()
 {
+	bool proxy_ok = true;
 	std::string httpProxyType = gSavedSettings.getString("Socks5HttpProxyType");
 
 	// Determine the HTTP proxy type (if any)
@@ -2785,7 +2782,7 @@ bool LLStartUp::handleSocksProxy()
 			subs["HOST"] = http_host.getIPString();
 			subs["PORT"] = (S32)http_host.getPort();
 			LLNotificationsUtil::add("PROXY_INVALID_HTTP_HOST", subs);
-			return false;
+			proxy_ok = false;
 		}
 	}
 	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
@@ -2799,7 +2796,7 @@ bool LLStartUp::handleSocksProxy()
 			subs["HOST"] = socks_host.getIPString();
 			subs["PORT"] = (S32)socks_host.getPort();
 			LLNotificationsUtil::add("PROXY_INVALID_SOCKS_HOST", subs);
-			return false;
+			proxy_ok = false;
 		}
 	}
 	else if (httpProxyType.compare("None") == 0)
@@ -2814,7 +2811,7 @@ bool LLStartUp::handleSocksProxy()
 	}
 
 	// Set up SOCKS proxy (if needed)
-	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
+	if (gSavedSettings.getBOOL("Socks5ProxyEnabled") && proxy_ok)
 	{	
 		// Determine and update LLProxy with the saved authentication system
 		std::string auth_type = gSavedSettings.getString("Socks5AuthType");
@@ -2830,7 +2827,7 @@ bool LLStartUp::handleSocksProxy()
 			if (!ok)
 			{
 				LLNotificationsUtil::add("SOCKS_BAD_CREDS");
-				return false;
+				proxy_ok = false;
 			}
 		}
 		else if (auth_type.compare("None") == 0)
@@ -2849,63 +2846,63 @@ bool LLStartUp::handleSocksProxy()
 			LLProxy::getInstance()->setAuthNone();
 		}
 
-		// Start the proxy and check for errors
-		// If status != SOCKS_OK, stopSOCKSProxy() will already have been called when startSOCKSProxy() returns.
-		LLHost socks_host;
-		socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
-		socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		int status = LLProxy::getInstance()->startSOCKSProxy(socks_host);
-
-		if (status == SOCKS_OK)
-		{
-			return true;
-		}
-		else
+		if (proxy_ok)
 		{
-			LLSD subs;
-			subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
-			subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
 
-			std::string error_string;
+			// Start the proxy and check for errors
+			// If status != SOCKS_OK, stopSOCKSProxy() will already have been called when startSOCKSProxy() returns.
+			LLHost socks_host;
+			socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
+			socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
+			int status = LLProxy::getInstance()->startSOCKSProxy(socks_host);
 
-			switch(status)
+			if (status != SOCKS_OK)
 			{
-				case SOCKS_CONNECT_ERROR: // TCP Fail
-					error_string = "SOCKS_CONNECT_ERROR";
-					break;
-
-				case SOCKS_NOT_PERMITTED: // SOCKS 5 server rule set refused connection
-					error_string = "SOCKS_NOT_PERMITTED";
-					break;
-
-				case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
-					error_string = "SOCKS_NOT_ACCEPTABLE";
-					break;
-
-				case SOCKS_AUTH_FAIL: // Authentication failed
-					error_string = "SOCKS_AUTH_FAIL";
-					break;
-
-				case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
-					error_string = "SOCKS_UDP_FWD_NOT_GRANTED";
-					break;
-
-				case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
-					error_string = "SOCKS_HOST_CONNECT_FAILED";
-					break;
-
-				case SOCKS_INVALID_HOST: // Improperly formatted host address or port.
-					error_string = "SOCKS_INVALID_HOST";
-					break;
-
-				default:
-					error_string = "SOCKS_UNKNOWN_STATUS"; // Something strange happened,
-					LL_WARNS("Proxy") << "Unknown return from LLProxy::startProxy(): " << status << LL_ENDL;
-					break;
-			}
+				LLSD subs;
+				subs["HOST"] = gSavedSettings.getString("Socks5ProxyHost");
+				subs["PORT"] = (S32)gSavedSettings.getU32("Socks5ProxyPort");
+
+				std::string error_string;
+
+				switch(status)
+				{
+					case SOCKS_CONNECT_ERROR: // TCP Fail
+						error_string = "SOCKS_CONNECT_ERROR";
+						break;
+
+					case SOCKS_NOT_PERMITTED: // SOCKS 5 server rule set refused connection
+						error_string = "SOCKS_NOT_PERMITTED";
+						break;
+
+					case SOCKS_NOT_ACCEPTABLE: // Selected authentication is not acceptable to server
+						error_string = "SOCKS_NOT_ACCEPTABLE";
+						break;
+
+					case SOCKS_AUTH_FAIL: // Authentication failed
+						error_string = "SOCKS_AUTH_FAIL";
+						break;
+
+					case SOCKS_UDP_FWD_NOT_GRANTED: // UDP forward request failed
+						error_string = "SOCKS_UDP_FWD_NOT_GRANTED";
+						break;
 
-			LLNotificationsUtil::add(error_string, subs);
-			return false;
+					case SOCKS_HOST_CONNECT_FAILED: // Failed to open a TCP channel to the socks server
+						error_string = "SOCKS_HOST_CONNECT_FAILED";
+						break;
+
+					case SOCKS_INVALID_HOST: // Improperly formatted host address or port.
+						error_string = "SOCKS_INVALID_HOST";
+						break;
+
+					default:
+						error_string = "SOCKS_UNKNOWN_STATUS"; // Something strange happened,
+						LL_WARNS("Proxy") << "Unknown return from LLProxy::startProxy(): " << status << LL_ENDL;
+						break;
+				}
+
+				LLNotificationsUtil::add(error_string, subs);
+				proxy_ok = false;
+			}
 		}
 	}
 	else
@@ -2913,7 +2910,7 @@ bool LLStartUp::handleSocksProxy()
 		LLProxy::getInstance()->stopSOCKSProxy(); // ensure no UDP proxy is running and it's all cleaned up
 	}
 
-	return true;
+	return proxy_ok;
 }
 
 bool login_alert_done(const LLSD& notification, const LLSD& response)
-- 
cgit v1.2.3


From 37f88470850cf572f30b0d1dae2f46a8e3b43977 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 4 Aug 2011 11:17:03 -0400
Subject: LLProxy: Added another attempt to download gpu and feature tables
 after successfully setting up a proxy.

Other minor changes:
Clarified why we are using SOCKS5 as the "grid" argument to store proxy credentials.
Added class wide logging to the LLProxy class.
---
 indra/llmessage/llproxy.cpp           |  8 +++-----
 indra/llmessage/llproxy.h             |  1 +
 indra/newview/llfloaterpreference.cpp | 17 ++++++++++-------
 indra/newview/llstartup.cpp           |  9 +++++++--
 4 files changed, 21 insertions(+), 14 deletions(-)

diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index d2e64e60ac..bdffa34fbc 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -85,7 +85,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	socks_auth_request.methods     = getSelectedAuthMethod(); // Send only the selected method.
 
 	result = tcp_handshake(mProxyControlChannel, (char*)&socks_auth_request, sizeof(socks_auth_request), (char*)&socks_auth_response, sizeof(socks_auth_response));
-	if (result != 0)
+	if (result != APR_SUCCESS)
 	{
 		LL_WARNS("Proxy") << "SOCKS authentication request failed, error on TCP control channel : " << result << LL_ENDL;
 		stopSOCKSProxy();
@@ -118,7 +118,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 		result = tcp_handshake(mProxyControlChannel, password_auth, request_size, (char*)&password_reply, sizeof(password_reply));
 		delete[] password_auth;
 
-		if (result != 0)
+		if (result != APR_SUCCESS)
 		{
 			LL_WARNS("Proxy") << "SOCKS authentication failed, error on TCP control channel : " << result << LL_ENDL;
 			stopSOCKSProxy();
@@ -148,7 +148,7 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	//  the client MUST use a port number and address of all zeros. RFC 1928"
 
 	result = tcp_handshake(mProxyControlChannel, (char*)&connect_request, sizeof(connect_request), (char*)&connect_reply, sizeof(connect_reply));
-	if (result != 0)
+	if (result != APR_SUCCESS)
 	{
 		LL_WARNS("Proxy") << "SOCKS connect request failed, error on TCP control channel : " << result << LL_ENDL;
 		stopSOCKSProxy();
@@ -335,7 +335,6 @@ void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
 	applyProxySettings(handle->getEasy());
 }
 
-
 void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 {
 	applyProxySettings(handle->getCurlHandle());
@@ -373,7 +372,6 @@ void LLProxy::applyProxySettings(CURL* handle)
 
 static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
 {
-
 	apr_socket_t* apr_socket = handle->getSocket();
 	apr_status_t rv = APR_SUCCESS;
 
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 68c40561c8..534455a6dd 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -168,6 +168,7 @@ enum LLSocks5AuthType
 
 class LLProxy: public LLSingleton<LLProxy>
 {
+	LOG_CLASS(LLProxy);
 public:
 	LLProxy();
 	~LLProxy();
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index b01dc616a3..61eac7bf14 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -334,17 +334,17 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key)
 	mCommitCallbackRegistrar.add("Pref.ClickEnablePopup",		boost::bind(&LLFloaterPreference::onClickEnablePopup, this));
 	mCommitCallbackRegistrar.add("Pref.ClickDisablePopup",		boost::bind(&LLFloaterPreference::onClickDisablePopup, this));	
 	mCommitCallbackRegistrar.add("Pref.LogPath",				boost::bind(&LLFloaterPreference::onClickLogPath, this));
-	mCommitCallbackRegistrar.add("Pref.HardwareSettings",       boost::bind(&LLFloaterPreference::onOpenHardwareSettings, this));	
-	mCommitCallbackRegistrar.add("Pref.HardwareDefaults",       boost::bind(&LLFloaterPreference::setHardwareDefaults, this));	
-	mCommitCallbackRegistrar.add("Pref.VertexShaderEnable",     boost::bind(&LLFloaterPreference::onVertexShaderEnable, this));	
-	mCommitCallbackRegistrar.add("Pref.WindowedMod",            boost::bind(&LLFloaterPreference::onCommitWindowedMode, this));	
-	mCommitCallbackRegistrar.add("Pref.UpdateSliderText",       boost::bind(&LLFloaterPreference::onUpdateSliderText,this, _1,_2));	
-	mCommitCallbackRegistrar.add("Pref.QualityPerformance",     boost::bind(&LLFloaterPreference::onChangeQuality, this, _2));	
+	mCommitCallbackRegistrar.add("Pref.HardwareSettings",		boost::bind(&LLFloaterPreference::onOpenHardwareSettings, this));
+	mCommitCallbackRegistrar.add("Pref.HardwareDefaults",		boost::bind(&LLFloaterPreference::setHardwareDefaults, this));
+	mCommitCallbackRegistrar.add("Pref.VertexShaderEnable",		boost::bind(&LLFloaterPreference::onVertexShaderEnable, this));
+	mCommitCallbackRegistrar.add("Pref.WindowedMod",			boost::bind(&LLFloaterPreference::onCommitWindowedMode, this));
+	mCommitCallbackRegistrar.add("Pref.UpdateSliderText",		boost::bind(&LLFloaterPreference::onUpdateSliderText,this, _1,_2));
+	mCommitCallbackRegistrar.add("Pref.QualityPerformance",		boost::bind(&LLFloaterPreference::onChangeQuality, this, _2));
 	mCommitCallbackRegistrar.add("Pref.applyUIColor",			boost::bind(&LLFloaterPreference::applyUIColor, this ,_1, _2));
 	mCommitCallbackRegistrar.add("Pref.getUIColor",				boost::bind(&LLFloaterPreference::getUIColor, this ,_1, _2));
 	mCommitCallbackRegistrar.add("Pref.MaturitySettings",		boost::bind(&LLFloaterPreference::onChangeMaturity, this));
 	mCommitCallbackRegistrar.add("Pref.BlockList",				boost::bind(&LLFloaterPreference::onClickBlockList, this));
-	mCommitCallbackRegistrar.add("Pref.Proxy",                    boost::bind(&LLFloaterPreference::onClickProxySettings, this));
+	mCommitCallbackRegistrar.add("Pref.Proxy",					boost::bind(&LLFloaterPreference::onClickProxySettings, this));
 	
 	sSkin = gSavedSettings.getString("SkinCurrent");
 
@@ -2033,6 +2033,9 @@ void LLFloaterPreferenceProxy::onBtnOk()
 		socks_authenticator["type"] = "SOCKS5";
 		socks_authenticator["creds"] = getChild<LLLineEditor>("socks5_password")->getValue().asString();
 
+		// Using "SOCKS5" as the "grid" argument since the same proxy
+		// settings will be used for all grids and because there is no
+		// way to specify the type of credential.
 		LLPointer<LLCredential> socks_cred = gSecAPIHandler->createCredential("SOCKS5", socks_id, socks_authenticator);
 		gSecAPIHandler->saveCredential(socks_cred, true);
 	}
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 25af63c0d3..c5c143963b 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -592,10 +592,10 @@ bool idle_startup()
 		}
 
 		LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
-		
+
 		//-------------------------------------------------
 		// Init the SOCKS 5 proxy and open the control TCP
-		// connection if the user is using SOCKS 5
+		// connection if the user has configured a Proxy
 		// We need to do this early in case the user is using
 		// socks for HTTP so we get the login screen via SOCKS
 		// We don't do anything if proxy setup was
@@ -604,6 +604,11 @@ bool idle_startup()
 		//-------------------------------------------------
 
 		LLStartUp::handleSocksProxy();
+		// If we started a proxy, try to grab the table files again.
+		if (LLProxy::getInstance()->isHTTPProxyEnabled())
+		{
+			LLFeatureManager::getInstance()->fetchHTTPTables();
+		}
 
 		//-------------------------------------------------
 		// Init audio, which may be needed for prefs dialog
-- 
cgit v1.2.3


From 5915da89f06106d0e811c6655144df93d35144f8 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 8 Aug 2011 15:53:06 -0400
Subject: LLProxy cleanup.

Made the socks proxy start first in llstartup.cpp
Moved initialization of the proxy to before the HTTP table fetch
Added Doxygen comments to LLProxy methods.
Removed call to applyProxySettings in llxmlrpctransaction.cpp since the ctor of LLCurlEasyRequest will apply the proxy settings.
---
 indra/llmessage/llproxy.cpp           | 149 ++++++++++++++++++++++++++++++----
 indra/llmessage/llproxy.h             |  99 ++++++++++++++++++----
 indra/newview/llstartup.cpp           | 129 +++++++++++++++--------------
 indra/newview/llstartup.h             |   2 +-
 indra/newview/llxmlrpctransaction.cpp |   4 -
 5 files changed, 285 insertions(+), 98 deletions(-)

diff --git a/indra/llmessage/llproxy.cpp b/indra/llmessage/llproxy.cpp
index bdffa34fbc..3f4a6accbf 100644
--- a/indra/llmessage/llproxy.cpp
+++ b/indra/llmessage/llproxy.cpp
@@ -34,8 +34,6 @@
 #include "llapr.h"
 #include "llcurl.h"
 #include "llhost.h"
-#include "message.h"
-#include "net.h"
 
 // Static class variable instances
 
@@ -44,10 +42,10 @@
 // member is also static
 bool LLProxy::sUDPProxyEnabled = false;
 
-// Some helpful TCP functions
+// Some helpful TCP static functions.
+static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
 static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host); // Open a TCP channel to a given host
 static void tcp_close_channel(LLSocket::ptr_t* handle_ptr); // Close an open TCP channel
-static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen); // Do a TCP data handshake
 
 LLProxy::LLProxy():
 		mHTTPProxyEnabled(false),
@@ -70,9 +68,15 @@ LLProxy::~LLProxy()
 	mHTTPProxyEnabled = false;
 }
 
-// Perform a SOCKS 5 authentication and UDP association to the proxy
-// specified by proxy, and associate UDP port message_port
-S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
+/**
+ * @brief Open the SOCKS 5 TCP control channel.
+ *
+ * Perform a SOCKS 5 authentication and UDP association to 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;
 
@@ -169,6 +173,16 @@ S32 LLProxy::proxyHandshake(LLHost proxy, U32 message_port)
 	return SOCKS_OK;
 }
 
+/**
+ * @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.
+ *
+ *
+ * @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)
 {
 	S32 status = SOCKS_OK;
@@ -198,7 +212,7 @@ S32 LLProxy::startSOCKSProxy(LLHost host)
 
 	if (status == SOCKS_OK)
 	{
-		status = proxyHandshake(mTCPProxy, (U32)gMessageSystem->mPort);
+		status = proxyHandshake(mTCPProxy);
 	}
 	if (status == SOCKS_OK)
 	{
@@ -211,6 +225,13 @@ S32 LLProxy::startSOCKSProxy(LLHost host)
 	return status;
 }
 
+/**
+ * @brief Stop using the SOCKS 5 proxy.
+ *
+ * This will stop sending UDP packets through the SOCKS 5 proxy
+ * and will also stop the HTTP proxy if it is configured to use SOCKS.
+ * The proxy control channel will also be disconnected.
+ */
 void LLProxy::stopSOCKSProxy()
 {
 	sUDPProxyEnabled = false;
@@ -230,6 +251,9 @@ void LLProxy::stopSOCKSProxy()
 	}
 }
 
+/**
+ * @brief Set the proxy's SOCKS authentication method to none.
+ */
 void LLProxy::setAuthNone()
 {
 	LLMutexLock lock(&mProxyMutex);
@@ -237,6 +261,18 @@ void LLProxy::setAuthNone()
 	mAuthMethodSelected = METHOD_NOAUTH;
 }
 
+/**
+ * @brief Set the proxy's SOCKS authentication method to password.
+ *
+ * Check whether the lengths of the supplied username
+ * and password conform to the lengths allowed by the
+ * SOCKS protocol.
+ *
+ * @param 	username The SOCKS username to send.
+ * @param 	password The SOCKS password to send.
+ * @return  Return true if applying the settings was successful. No changes are made if false.
+ *
+ */
 bool LLProxy::setAuthPassword(const std::string &username, const std::string &password)
 {
 	if (username.length() > SOCKSMAXUSERNAMELEN || password.length() > SOCKSMAXPASSWORDLEN ||
@@ -255,6 +291,15 @@ bool LLProxy::setAuthPassword(const std::string &username, const std::string &pa
 	return true;
 }
 
+/**
+ * @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())
@@ -273,15 +318,31 @@ bool LLProxy::enableHTTPProxy(LLHost httpHost, LLHttpProxyType type)
 	return true;
 }
 
+/**
+ * @brief Enable the HTTP proxy without changing the proxy settings.
+ *
+ * This should not be called unless the proxy has already been set up.
+ *
+ * @return Return true only if the current settings are valid and the proxy was enabled.
+ */
 bool LLProxy::enableHTTPProxy()
 {
+	bool ok;
+
 	LLMutexLock lock(&mProxyMutex);
 
-	mHTTPProxyEnabled = true;
+	ok = (mHTTPProxy.isOk());
+	if (ok)
+	{
+		mHTTPProxyEnabled = true;
+	}
 
-	return true;
+	return ok;
 }
 
+/**
+ * @brief Disable the HTTP proxy.
+ */
 void LLProxy::disableHTTPProxy()
 {
 	LLMutexLock lock(&mProxyMutex);
@@ -289,39 +350,59 @@ void LLProxy::disableHTTPProxy()
 	mHTTPProxyEnabled = false;
 }
 
-// Get the HTTP proxy address and port
+/**
+ * @brief Get the HTTP proxy address and port
+ */
+//
 LLHost LLProxy::getHTTPProxy() const
 {
 	LLMutexLock lock(&mProxyMutex);
 	return mHTTPProxy;
 }
 
-// Get the currently selected HTTP proxy type
+/**
+ * @brief Get the currently selected HTTP proxy type
+ */
 LLHttpProxyType LLProxy::getHTTPProxyType() const
 {
 	LLMutexLock lock(&mProxyMutex);
 	return mProxyType;
 }
 
+/**
+ * @brief Get the SOCKS 5 password.
+ */
 std::string LLProxy::getSocksPwd() const
 {
 	LLMutexLock lock(&mProxyMutex);
 	return mSocksPassword;
 }
 
+/**
+ * @brief Get the SOCKS 5 username.
+ */
 std::string LLProxy::getSocksUser() const
 {
 	LLMutexLock lock(&mProxyMutex);
 	return mSocksUsername;
 }
 
-// get the currently selected auth method
+/**
+ * @brief Get the currently selected SOCKS 5 authentication method.
+ *
+ * @return Returns either none or password.
+ */
 LLSocks5AuthType LLProxy::getSelectedAuthMethod() const
 {
 	LLMutexLock lock(&mProxyMutex);
 	return mAuthMethodSelected;
 }
 
+/**
+ * @brief Stop the LLProxy and make certain that any APR pools and classes are deleted before terminating APR.
+ *
+ * Deletes the LLProxy singleton, destroying the APR pool used by the control channel as well as .
+ */
 //static
 void LLProxy::cleanupClass()
 {
@@ -329,7 +410,6 @@ void LLProxy::cleanupClass()
 	deleteSingleton();
 }
 
-// Apply proxy settings to CuRL request if either type of HTTP proxy is enabled.
 void LLProxy::applyProxySettings(LLCurlEasyRequest* handle)
 {
 	applyProxySettings(handle->getEasy());
@@ -340,6 +420,17 @@ void LLProxy::applyProxySettings(LLCurl::Easy* handle)
 	applyProxySettings(handle->getCurlHandle());
 }
 
+/**
+ * @brief Apply proxy settings to a CuRL request if an HTTP proxy is enabled.
+ *
+ * This method has been designed to be safe to call from
+ * any thread in the viewer.  This allows requests in the
+ * texture fetch thread to be aware of the proxy settings.
+ * When the HTTP proxy is enabled, the proxy mutex will
+ * be locked every time this method is called.
+ *
+ * @param handle A pointer to a valid CURL request, before it has been performed.
+ */
 void LLProxy::applyProxySettings(CURL* handle)
 {
 	// Do a faster unlocked check to see if we are supposed to proxy.
@@ -370,6 +461,19 @@ void LLProxy::applyProxySettings(CURL* handle)
 	}
 }
 
+/**
+ * @brief Send one TCP packet and receive one in return.
+ *
+ * This operation is done synchronously with a 1000ms timeout. Therefore, it should not be used when a blocking
+ * operation would impact the operation of the viewer.
+ *
+ * @param handle_ptr 	Pointer to a connected LLSocket of type STREAM_TCP.
+ * @param dataout		Data to send.
+ * @param outlen		Length of dataout.
+ * @param datain		Buffer for received data. Undefined if return value is not APR_SUCCESS.
+ * @param maxinlen		Maximum possible length of received data.  Short reads are allowed.
+ * @return 				Indicates APR status code of exchange. APR_SUCCESS if exchange was successful, -1 if invalid data length was received.
+ */
 static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outlen, char * datain, apr_size_t maxinlen)
 {
 	apr_socket_t* apr_socket = handle->getSocket();
@@ -414,9 +518,18 @@ static S32 tcp_handshake(LLSocket::ptr_t handle, char * dataout, apr_size_t outl
 	return rv;
 }
 
+/**
+ * @brief Open a LLSocket and do a blocking connect to the chosen host.
+ *
+ * Checks for a successful connection, and makes sure the connection is closed if it fails.
+ *
+ * @param pool		APR pool to pass into the LLSocket.
+ * @param host		The host to open the connection to.
+ * @return			The created socket.  Will evaluate as NULL if the connection is unsuccessful.
+ */
 static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
 {
-	LLSocket::ptr_t socket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
+	LLSocket::ptr_t socket = LLSocket::create(pool, LLSocket::STREAM_TCP);
 	bool connected = socket->blockingConnect(host);
 	if (!connected)
 	{
@@ -426,7 +539,11 @@ static LLSocket::ptr_t tcp_open_channel(apr_pool_t* pool, LLHost host)
 	return socket;
 }
 
-// Pass a pointer-to-pointer to avoid changing use_count().
+/**
+ * @brief Close the socket.
+ *
+ * @param handle_ptr A pointer-to-pointer to avoid increasing the use count.
+ */
 static void tcp_close_channel(LLSocket::ptr_t* handle_ptr)
 {
 	LL_DEBUGS("Proxy") << "Resetting proxy LLSocket handle, use_count == " << handle_ptr->use_count() << LL_ENDL;
diff --git a/indra/llmessage/llproxy.h b/indra/llmessage/llproxy.h
index 534455a6dd..29e7e28567 100644
--- a/indra/llmessage/llproxy.h
+++ b/indra/llmessage/llproxy.h
@@ -35,7 +35,7 @@
 #include "llthread.h"
 #include <string>
 
-// Error codes returned from the StartProxy method
+// SOCKS error codes returned from the StartProxy method
 
 #define SOCKS_OK 0
 #define SOCKS_CONNECT_ERROR (-1)
@@ -166,11 +166,86 @@ enum LLSocks5AuthType
 	METHOD_PASSWORD = 0x02 	// Client supports username/password
 };
 
+/**
+ * @brief Manage SOCKS 5 UDP proxy and HTTP proxy.
+ *
+ * This class is responsible for managing two interconnected tasks,
+ * connecting to a SOCKS 5 proxy for use by LLPacketRing to send UDP
+ * packets and managing proxy settings for HTTP requests.
+ *
+ * <h1>Threading:</h1>
+ * Because HTTP requests can be generated in threads outside the
+ * main thread, it is necessary for some of the information stored
+ * by this class to be available to other threads. The members that
+ * need to be read across threads are in a labeled section below.
+ * To protect those members, a mutex, mProxyMutex should be locked
+ * before reading or writing those members.  Methods that can lock
+ * mProxyMutex are in a labeled section below. Those methods should
+ * not be called while the mutex is already locked.
+ *
+ * There is also a LLAtomic type flag (mHTTPProxyEnabled) that is used
+ * to track whether the HTTP proxy is currently enabled. This allows
+ * for faster unlocked checks to see if the proxy is enabled.  This
+ * allows us to cut down on the performance hit when the proxy is
+ * disabled compared to before this class was introduced.
+ *
+ * <h1>UDP Proxying:</h1>
+ * UDP datagrams are proxied via a SOCKS 5 proxy with the UDP associate
+ * command.  To initiate the proxy, a TCP socket connection is opened
+ * to the SOCKS 5 host, and after a handshake exchange, the server
+ * returns a port and address to send the UDP traffic that is to be
+ * proxied to. The LLProxy class tracks this address and port after the
+ * exchange and provides it to LLPacketRing when required to. All UDP
+ * proxy management occurs in the main thread.
+ *
+ * <h1>HTTP Proxying:</h1>
+ * This class allows all viewer HTTP packets to be sent through a proxy.
+ * The user can select whether to send HTTP packets through a standard
+ * "web" HTTP proxy, through a SOCKS 5 proxy, or to not proxy HTTP
+ * communication. This class does not manage the integrated web browser
+ * proxy, which is handled in llviewermedia.cpp.
+ *
+ * The implementation of HTTP proxying is handled by libcurl. LLProxy
+ * is responsible for managing the HTTP proxy options and provides a
+ * thread-safe method to apply those options to a curl request
+ * (LLProxy::applyProxySettings()). This method is overloaded
+ * to accommodate the various abstraction libcurl layers that exist
+ * throughout the viewer (LLCurlEasyRequest, LLCurl::Easy, and CURL).
+ *
+ * If you are working with LLCurl or LLCurlEasyRequest objects,
+ * the configured proxy settings will be applied in the constructors
+ * of those request handles.  If you are working with CURL objects
+ * directly, you will need to pass the handle of the request to
+ * applyProxySettings() before issuing the request.
+ *
+ * To ensure thread safety, all LLProxy members that relate to the HTTP
+ * proxy require the LLProxyMutex to be locked before accessing.
+ */
 class LLProxy: public LLSingleton<LLProxy>
 {
 	LOG_CLASS(LLProxy);
 public:
+	// METHODS THAT DO NOT LOCK mProxyMutex!
+
 	LLProxy();
+
+	// static check for enabled status for UDP packets
+	static bool isSOCKSProxyEnabled() { return sUDPProxyEnabled; }
+
+	// check for enabled status for HTTP packets
+	// mHTTPProxyEnabled is atomic, so no locking is required for thread safety.
+	bool isHTTPProxyEnabled() const { return mHTTPProxyEnabled; }
+
+	// Get the UDP proxy address and port
+	LLHost getUDPProxy() const { return mUDPProxy; }
+
+	// Get the SOCKS 5 TCP control channel address and port
+	LLHost getTCPProxy() const { return mTCPProxy; }
+
+	// END OF NON-LOCKING METHODS
+
+	// METHODS THAT DO LOCK mProxyMutex! DO NOT CALL WHILE mProxyMutex IS LOCKED!
+
 	~LLProxy();
 
 	// Start a connection to the SOCKS 5 proxy
@@ -188,16 +263,9 @@ public:
 	// Set up to use No Auth when connecting to the SOCKS proxy
 	void setAuthNone();
 
-	// get the currently selected auth method
+	// Get the currently selected auth method.
 	LLSocks5AuthType getSelectedAuthMethod() const;
 
-	// static check for enabled status for UDP packets
-	static bool isSOCKSProxyEnabled() { return sUDPProxyEnabled; }
-
-	// check for enabled status for HTTP packets
-	// mHTTPProxyEnabled is atomic, so no locking is required for thread safety.
-	bool isHTTPProxyEnabled() const { return mHTTPProxyEnabled; }
-
 	// Proxy HTTP packets via httpHost, which can be a SOCKS 5 or a HTTP proxy
 	// as specified in type
 	bool enableHTTPProxy(LLHost httpHost, LLHttpProxyType type);
@@ -211,12 +279,6 @@ public:
 	void applyProxySettings(LLCurl::Easy* handle);
 	void applyProxySettings(LLCurlEasyRequest* handle);
 
-	// Get the UDP proxy address and port
-	LLHost getUDPProxy() const { return mUDPProxy; }
-
-	// Get the SOCKS 5 TCP control channel address and port
-	LLHost getTCPProxy() const { return mTCPProxy; }
-
 	// Get the HTTP proxy address and port
 	LLHost getHTTPProxy() const;
 
@@ -226,9 +288,10 @@ public:
 	std::string getSocksPwd() const;
 	std::string getSocksUser() const;
 
+	// END OF LOCKING METHODS
 private:
 	// Open a communication channel to the SOCKS 5 proxy proxy, at port messagePort
-	S32 proxyHandshake(LLHost proxy, U32 messagePort);
+	S32 proxyHandshake(LLHost proxy);
 
 private:
 	// Is the HTTP proxy enabled?
@@ -255,6 +318,8 @@ private:
 	// APR pool for the socket
 	apr_pool_t* mPool;
 
+	// END OF UNSHARED MEMBERS
+
 	// MEMBERS WRITTEN IN MAIN THREAD AND READ IN ANY THREAD. ONLY READ OR WRITE AFTER LOCKING mProxyMutex!
 
 	// HTTP proxy address and port
@@ -270,6 +335,8 @@ private:
 	std::string mSocksUsername;
 	// SOCKS 5 password
 	std::string mSocksPassword;
+
+	// END OF SHARED MEMBERS
 };
 
 #endif
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index c5c143963b..c34f84e2d9 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -387,6 +387,14 @@ bool idle_startup()
 			LLNotificationsUtil::add(gViewerWindow->getInitAlert());
 		}
 			
+		//-------------------------------------------------
+		// Init the SOCKS 5 proxy if the user has configured
+		// one. We need to do this early in case the user
+		// is using SOCKS for HTTP so we get the login
+		// screen and HTTP tables via SOCKS.
+		//-------------------------------------------------
+		LLStartUp::startLLProxy();
+
 		gSavedSettings.setS32("LastFeatureVersion", LLFeatureManager::getInstance()->getVersion());
 		gSavedSettings.setS32("LastGPUClass", LLFeatureManager::getInstance()->getGPUClass());
 
@@ -593,23 +601,6 @@ bool idle_startup()
 
 		LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
 
-		//-------------------------------------------------
-		// Init the SOCKS 5 proxy and open the control TCP
-		// connection if the user has configured a Proxy
-		// We need to do this early in case the user is using
-		// socks for HTTP so we get the login screen via SOCKS
-		// We don't do anything if proxy setup was
-		// unsuccessful, since the user can configure their
-		// proxy settings before starting to log in.
-		//-------------------------------------------------
-
-		LLStartUp::handleSocksProxy();
-		// If we started a proxy, try to grab the table files again.
-		if (LLProxy::getInstance()->isHTTPProxyEnabled())
-		{
-			LLFeatureManager::getInstance()->fetchHTTPTables();
-		}
-
 		//-------------------------------------------------
 		// Init audio, which may be needed for prefs dialog
 		// or audio cues in connection UI.
@@ -828,10 +819,10 @@ bool idle_startup()
 		// Post login screen, we should see if any settings have changed that may
 		// require us to either start/stop or change the socks proxy. As various communications
 		// past this point may require the proxy to be up.
-		if (!LLStartUp::handleSocksProxy())
+		if (!LLStartUp::startLLProxy())
 		{
 			// Proxy start up failed, we should now bail the state machine
-			// handleSocksProxy() will have reported an error to the user
+			// startLLProxy() will have reported an error to the user
 			// already, so we just go back to the login screen. The user
 			// could then change the preferences to fix the issue.
 
@@ -2770,53 +2761,22 @@ void LLStartUp::setStartSLURL(const LLSLURL& slurl)
     }
 }
 
-bool LLStartUp::handleSocksProxy()
+/**
+ * Read all proxy configuration settings and set up both the HTTP proxy and
+ * SOCKS proxy as needed.
+ *
+ * Any errors that are encountered will result in showing the user a notification.
+ * When an error is encountered,
+ *
+ * @return Returns true if setup was successful, false if an error was encountered.
+ */
+bool LLStartUp::startLLProxy()
 {
 	bool proxy_ok = true;
 	std::string httpProxyType = gSavedSettings.getString("Socks5HttpProxyType");
 
-	// Determine the HTTP proxy type (if any)
-	if ((httpProxyType.compare("Web") == 0) && gSavedSettings.getBOOL("BrowserProxyEnabled"))
-	{
-		LLHost http_host;
-		http_host.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
-		http_host.setPort(gSavedSettings.getS32("BrowserProxyPort"));
-		if (!LLProxy::getInstance()->enableHTTPProxy(http_host, LLPROXY_HTTP))
-		{
-			LLSD subs;
-			subs["HOST"] = http_host.getIPString();
-			subs["PORT"] = (S32)http_host.getPort();
-			LLNotificationsUtil::add("PROXY_INVALID_HTTP_HOST", subs);
-			proxy_ok = false;
-		}
-	}
-	else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
-	{
-		LLHost socks_host;
-		socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
-		socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
-		if (!LLProxy::getInstance()->enableHTTPProxy(socks_host, LLPROXY_SOCKS))
-		{
-			LLSD subs;
-			subs["HOST"] = socks_host.getIPString();
-			subs["PORT"] = (S32)socks_host.getPort();
-			LLNotificationsUtil::add("PROXY_INVALID_SOCKS_HOST", subs);
-			proxy_ok = false;
-		}
-	}
-	else if (httpProxyType.compare("None") == 0)
-	{
-		LLProxy::getInstance()->disableHTTPProxy();
-	}
-	else
-	{
-		LL_WARNS("Proxy") << "Invalid HTTP proxy configuration."<< LL_ENDL;
-		gSavedSettings.setString("Socks5HttpProxyType", "None");
-		LLProxy::getInstance()->disableHTTPProxy();
-	}
-
 	// Set up SOCKS proxy (if needed)
-	if (gSavedSettings.getBOOL("Socks5ProxyEnabled") && proxy_ok)
+	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
 	{	
 		// Determine and update LLProxy with the saved authentication system
 		std::string auth_type = gSavedSettings.getString("Socks5AuthType");
@@ -2915,6 +2875,53 @@ bool LLStartUp::handleSocksProxy()
 		LLProxy::getInstance()->stopSOCKSProxy(); // ensure no UDP proxy is running and it's all cleaned up
 	}
 
+	if (proxy_ok)
+	{
+		// Determine the HTTP proxy type (if any)
+		if ((httpProxyType.compare("Web") == 0) && gSavedSettings.getBOOL("BrowserProxyEnabled"))
+		{
+			LLHost http_host;
+			http_host.setHostByName(gSavedSettings.getString("BrowserProxyAddress"));
+			http_host.setPort(gSavedSettings.getS32("BrowserProxyPort"));
+			if (!LLProxy::getInstance()->enableHTTPProxy(http_host, LLPROXY_HTTP))
+			{
+				LLSD subs;
+				subs["HOST"] = http_host.getIPString();
+				subs["PORT"] = (S32)http_host.getPort();
+				LLNotificationsUtil::add("PROXY_INVALID_HTTP_HOST", subs);
+				proxy_ok = false;
+			}
+		}
+		else if ((httpProxyType.compare("Socks") == 0) && gSavedSettings.getBOOL("Socks5ProxyEnabled"))
+		{
+			LLHost socks_host;
+			socks_host.setHostByName(gSavedSettings.getString("Socks5ProxyHost"));
+			socks_host.setPort(gSavedSettings.getU32("Socks5ProxyPort"));
+			if (!LLProxy::getInstance()->enableHTTPProxy(socks_host, LLPROXY_SOCKS))
+			{
+				LLSD subs;
+				subs["HOST"] = socks_host.getIPString();
+				subs["PORT"] = (S32)socks_host.getPort();
+				LLNotificationsUtil::add("PROXY_INVALID_SOCKS_HOST", subs);
+				proxy_ok = false;
+			}
+		}
+		else if (httpProxyType.compare("None") == 0)
+		{
+			LLProxy::getInstance()->disableHTTPProxy();
+		}
+		else
+		{
+			LL_WARNS("Proxy") << "Invalid HTTP proxy configuration."<< LL_ENDL;
+
+			// Set the missing or wrong configuration back to something valid.
+			gSavedSettings.setString("Socks5HttpProxyType", "None");
+			LLProxy::getInstance()->disableHTTPProxy();
+
+			// Leave proxy_ok alone, since this isn't necessarily fatal.
+		}
+	}
+
 	return proxy_ok;
 }
 
diff --git a/indra/newview/llstartup.h b/indra/newview/llstartup.h
index 7292e4d68c..99a644eb9c 100644
--- a/indra/newview/llstartup.h
+++ b/indra/newview/llstartup.h
@@ -113,7 +113,7 @@ public:
 	static void setStartSLURL(const LLSLURL& slurl); 
 	static LLSLURL& getStartSLURL() { return sStartSLURL; } 
 
-	static bool handleSocksProxy(); // Initialize the SOCKS 5 proxy
+	static bool startLLProxy(); // Initialize the SOCKS 5 proxy
 
 private:
 	static LLSLURL sStartSLURL;
diff --git a/indra/newview/llxmlrpctransaction.cpp b/indra/newview/llxmlrpctransaction.cpp
index 7683d4feb5..f483ba5af8 100644
--- a/indra/newview/llxmlrpctransaction.cpp
+++ b/indra/newview/llxmlrpctransaction.cpp
@@ -41,8 +41,6 @@
 #include "llappviewer.h"
 #include "lltrans.h"
 
-#include "llproxy.h"
-
 // Static instance of LLXMLRPCListener declared here so that every time we
 // bring in this code, we instantiate a listener. If we put the static
 // instance of LLXMLRPCListener into llxmlrpclistener.cpp, the linker would
@@ -308,8 +306,6 @@ void LLXMLRPCTransaction::Impl::init(XMLRPC_REQUEST request, bool useGzip)
 		mCurlRequest = new LLCurlEasyRequest();
 	}
 	mErrorCert = NULL;
-	
-	LLProxy::getInstance()->applyProxySettings(mCurlRequest);
 
 //	mCurlRequest->setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
-- 
cgit v1.2.3


From fe14e50a45a450cd7bcdfe73a8bbda03c018053f Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 8 Aug 2011 16:19:39 -0400
Subject: Fixed numerous comment spelling errors in llerror.cpp and llerror.h

---
 indra/llcommon/llerror.cpp |  2 +-
 indra/llcommon/llerror.h   | 14 +++++++-------
 2 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/indra/llcommon/llerror.cpp b/indra/llcommon/llerror.cpp
index bb64152407..c35799bbb9 100644
--- a/indra/llcommon/llerror.cpp
+++ b/indra/llcommon/llerror.cpp
@@ -379,7 +379,7 @@ namespace
 	{
 		/* This pattern, of returning a reference to a static function
 		   variable, is to ensure that this global is constructed before
-		   it is used, no matter what the global initializeation sequence
+		   it is used, no matter what the global initialization sequence
 		   is.
 		   See C++ FAQ Lite, sections 10.12 through 10.14
 		*/
diff --git a/indra/llcommon/llerror.h b/indra/llcommon/llerror.h
index 4a42241c4f..b3e604f8e8 100644
--- a/indra/llcommon/llerror.h
+++ b/indra/llcommon/llerror.h
@@ -39,7 +39,7 @@
 
 	Information for most users:
 	
-	Code can log messages with constuctions like this:
+	Code can log messages with constructions like this:
 	
 		LL_INFOS("StringTag") << "request to fizzbip agent " << agent_id
 			<< " denied due to timeout" << LL_ENDL;
@@ -47,9 +47,9 @@
 	Messages can be logged to one of four increasing levels of concern,
 	using one of four "streams":
 
-		LL_DEBUGS("StringTag")	- debug messages that are normally supressed
-		LL_INFOS("StringTag")	- informational messages that are normall shown
-		LL_WARNS("StringTag")	- warning messages that singal a problem
+		LL_DEBUGS("StringTag")	- debug messages that are normally suppressed
+		LL_INFOS("StringTag")	- informational messages that are normal shown
+		LL_WARNS("StringTag")	- warning messages that signal a problem
 		LL_ERRS("StringTag")	- error messages that are major, unrecoverable failures
 		
 	The later (LL_ERRS("StringTag")) automatically crashes the process after the message
@@ -90,7 +90,7 @@
 	
 		WARN: LLFoo::doSomething: called with a big value for i: 283
 	
-	Which messages are logged and which are supressed can be controled at run
+	Which messages are logged and which are suppressed can be controlled at run
 	time from the live file logcontrol.xml based on function, class and/or 
 	source file.  See etc/logcontrol-dev.xml for details.
 	
@@ -106,7 +106,7 @@ namespace LLError
 	enum ELevel
 	{
 		LEVEL_ALL = 0,
-			// used to indicate that all messagess should be logged
+			// used to indicate that all messages should be logged
 			
 		LEVEL_DEBUG = 0,
 		LEVEL_INFO = 1,
@@ -220,7 +220,7 @@ namespace LLError
 	// See top of file for example of how to use this
 	
 typedef LLError::NoClassInfo _LL_CLASS_TO_LOG;
-	// Outside a class declartion, or in class without LOG_CLASS(), this
+	// Outside a class declaration, or in class without LOG_CLASS(), this
 	// typedef causes the messages to not be associated with any class.
 
 
-- 
cgit v1.2.3


From f9cf9179122d06782f0c968ba84adc1e44dd1e21 Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Thu, 11 Aug 2011 18:16:21 -0600
Subject: fix for SH-2194: viewer UI is visible on the login progress screen

---
 indra/newview/llstartup.cpp       | 32 +++++++++++++++++++++-----------
 indra/newview/llviewertexture.cpp | 22 +++++++++++++++-------
 indra/newview/llviewertexture.h   |  1 +
 3 files changed, 37 insertions(+), 18 deletions(-)

diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index e4bf668275..9855326093 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2557,22 +2557,32 @@ void init_start_screen(S32 location_id)
 	else if(!start_image_bmp->load(temp_str) )
 	{
 		LL_WARNS("AppInit") << "Bitmap load failed" << LL_ENDL;
-		return;
+		gStartTexture = NULL;
 	}
+	else
+	{
+		gStartImageWidth = start_image_bmp->getWidth();
+		gStartImageHeight = start_image_bmp->getHeight();
 
-	gStartImageWidth = start_image_bmp->getWidth();
-	gStartImageHeight = start_image_bmp->getHeight();
+		LLPointer<LLImageRaw> raw = new LLImageRaw;
+		if (!start_image_bmp->decode(raw, 0.0f))
+		{
+			LL_WARNS("AppInit") << "Bitmap decode failed" << LL_ENDL;
+			gStartTexture = NULL;
+		}
+		else
+		{
+			raw->expandToPowerOfTwo();
+			gStartTexture = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE) ;
+		}
+	}
 
-	LLPointer<LLImageRaw> raw = new LLImageRaw;
-	if (!start_image_bmp->decode(raw, 0.0f))
+	if(gStartTexture.isNull())
 	{
-		LL_WARNS("AppInit") << "Bitmap decode failed" << LL_ENDL;
-		gStartTexture = NULL;
-		return;
+		gStartTexture = LLViewerTexture::sBlackImagep ;
+		gStartImageWidth = gStartTexture->getWidth() ;
+		gStartImageHeight = gStartTexture->getHeight() ;
 	}
-
-	raw->expandToPowerOfTwo();
-	gStartTexture = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE) ;
 }
 
 
diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp
index 5fcc57bc91..70509f9a9f 100644
--- a/indra/newview/llviewertexture.cpp
+++ b/indra/newview/llviewertexture.cpp
@@ -66,6 +66,7 @@
 
 // statics
 LLPointer<LLViewerTexture>        LLViewerTexture::sNullImagep = NULL;
+LLPointer<LLViewerTexture>        LLViewerTexture::sBlackImagep = NULL;
 LLPointer<LLViewerFetchedTexture> LLViewerFetchedTexture::sMissingAssetImagep = NULL;
 LLPointer<LLViewerFetchedTexture> LLViewerFetchedTexture::sWhiteImagep = NULL;
 LLPointer<LLViewerFetchedTexture> LLViewerFetchedTexture::sDefaultImagep = NULL;
@@ -295,17 +296,23 @@ LLViewerFetchedTexture* LLViewerTextureManager::getFetchedTextureFromHost(const
 
 void LLViewerTextureManager::init()
 {
-	LLPointer<LLImageRaw> raw = new LLImageRaw(1,1,3);
-	raw->clear(0x77, 0x77, 0x77, 0xFF);
-	LLViewerTexture::sNullImagep = LLViewerTextureManager::getLocalTexture(raw.get(), TRUE) ;
-
-#if 1
-	LLPointer<LLViewerFetchedTexture> imagep = LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT);
-	LLViewerFetchedTexture::sDefaultImagep = imagep;
+	{
+		LLPointer<LLImageRaw> raw = new LLImageRaw(1,1,3);
+		raw->clear(0x77, 0x77, 0x77, 0xFF);
+		LLViewerTexture::sNullImagep = LLViewerTextureManager::getLocalTexture(raw.get(), TRUE) ;
+	}
 
 	const S32 dim = 128;
 	LLPointer<LLImageRaw> image_raw = new LLImageRaw(dim,dim,3);
 	U8* data = image_raw->getData();
+	
+	memset(data, 0, dim * dim * 3) ;
+	LLViewerTexture::sBlackImagep = LLViewerTextureManager::getLocalTexture(image_raw.get(), TRUE) ;
+
+#if 1
+	LLPointer<LLViewerFetchedTexture> imagep = LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT);
+	LLViewerFetchedTexture::sDefaultImagep = imagep;
+	
 	for (S32 i = 0; i<dim; i++)
 	{
 		for (S32 j = 0; j<dim; j++)
@@ -359,6 +366,7 @@ void LLViewerTextureManager::cleanup()
 
 	LLImageGL::sDefaultGLTexture = NULL ;
 	LLViewerTexture::sNullImagep = NULL;
+	LLViewerTexture::sBlackImagep = NULL;
 	LLViewerFetchedTexture::sDefaultImagep = NULL;	
 	LLViewerFetchedTexture::sSmokeImagep = NULL;
 	LLViewerFetchedTexture::sMissingAssetImagep = NULL;
diff --git a/indra/newview/llviewertexture.h b/indra/newview/llviewertexture.h
index c5b8c8923a..de528927b4 100644
--- a/indra/newview/llviewertexture.h
+++ b/indra/newview/llviewertexture.h
@@ -330,6 +330,7 @@ public:
 	static BOOL sUseTextureAtlas ;
 
 	static LLPointer<LLViewerTexture> sNullImagep; // Null texture for non-textured objects.
+	static LLPointer<LLViewerTexture> sBlackImagep;	// Texture to show NOTHING (pure black)
 };
 
 
-- 
cgit v1.2.3


From cff5251f064005f213a905f6eb41b5b7ef8c954b Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Fri, 12 Aug 2011 14:23:43 -0400
Subject: LLProxy: xui string cleanup.

---
 indra/newview/llfloaterpreference.cpp                  |  2 +-
 .../skins/default/xui/en/floater_preferences_proxy.xml |  2 +-
 indra/newview/skins/default/xui/en/notifications.xml   | 18 +++++++++---------
 3 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index 61eac7bf14..bd9efdd409 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -1972,7 +1972,7 @@ void LLFloaterPreferenceProxy::onClose(bool app_quitting)
 		// it will not be updated until next restart.
 		if (LLStartUp::getStartupState()>STATE_LOGIN_WAIT)
 		{
-			LLNotifications::instance().add("ChangeSocks5Settings", LLSD(), LLSD());
+			LLNotifications::instance().add("ChangeProxySettings", LLSD(), LLSD());
 			mSocksSettingsDirty = false; // we have notified the user now be quiet again
 		}
 	}
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index 020ee52c18..fb5f85bf58 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -4,7 +4,7 @@
  height="500"
  layout="topleft"
  name="Proxy Settings Floater"
- help_topic="proxy_settings_floater"
+ help_topic="proxysettings"
  title="Proxy Settings"
  width="500">
 	<check_box
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index 6867305b70..5aa66b2bd3 100644
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -7160,7 +7160,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_NOT_PERMITTED"
    type="alertmodal">
-	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, not allowed by rule set
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, not allowed by rule set.
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7171,7 +7171,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_CONNECT_ERROR"
    type="alertmodal">
-	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, could not open TCP channel
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the connection, could not open TCP channel.
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7182,7 +7182,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_NOT_ACCEPTABLE"
    type="alertmodal">
-	The SOCKS 5 proxy "[HOST]:[PORT]" refused the selected authentication system
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the selected authentication system.
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7193,7 +7193,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_AUTH_FAIL"
    type="alertmodal">
-	The SOCKS 5 proxy "[HOST]:[PORT]" reported your credentials are invalid
+	The SOCKS 5 proxy "[HOST]:[PORT]" reported your credentials are invalid.
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7204,7 +7204,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_UDP_FWD_NOT_GRANTED"
    type="alertmodal">
-	The SOCKS 5 proxy "[HOST]:[PORT]" refused the UDP associate request
+	The SOCKS 5 proxy "[HOST]:[PORT]" refused the UDP associate request.
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7215,7 +7215,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_HOST_CONNECT_FAILED"
    type="alertmodal">
-	Could not connect to SOCKS 5 proxy server "[HOST]:[PORT]"
+	Could not connect to SOCKS 5 proxy server "[HOST]:[PORT]".
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7226,7 +7226,7 @@ Click and drag anywhere on the world to rotate your view
    icon="alertmodal.tga"
    name="SOCKS_UNKNOWN_STATUS"
    type="alertmodal">
-	Unknown SOCKS error with server "[HOST]:[PORT]"
+	Unknown proxy error with server "[HOST]:[PORT]".
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
@@ -7279,9 +7279,9 @@ Click and drag anywhere on the world to rotate your view
 
   <notification
    icon="alertmodal.tga"
-   name="ChangeSocks5Settings"
+   name="ChangeProxySettings"
    type="alert">
-	SOCKS 5 proxy settings take effect after you restart [APP_NAME].
+	Proxy settings take effect after you restart [APP_NAME].
 	<tag>fail</tag>
    <usetemplate
      name="okbutton"
-- 
cgit v1.2.3


From 3743ec176c3c8fc1b93b2133e385331140819d8f Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 15 Aug 2011 13:21:33 -0400
Subject: LLProxy: Removed unneeded call to LLProxy::applyProxySettings, since
 it was already being called.

---
 indra/llmessage/llurlrequest.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/indra/llmessage/llurlrequest.cpp b/indra/llmessage/llurlrequest.cpp
index a186596582..d5400e4169 100644
--- a/indra/llmessage/llurlrequest.cpp
+++ b/indra/llmessage/llurlrequest.cpp
@@ -438,7 +438,6 @@ void LLURLRequest::initialize()
 	LLMemType m1(LLMemType::MTYPE_IO_URL_REQUEST);
 	mState = STATE_INITIALIZED;
 	mDetail = new LLURLRequestDetail;
-	LLProxy::getInstance()->applyProxySettings(mDetail->mCurlRequest);
 	mDetail->mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
 	mDetail->mCurlRequest->setWriteCallback(&downCallback, (void*)this);
 	mDetail->mCurlRequest->setReadCallback(&upCallback, (void*)this);
-- 
cgit v1.2.3


From ff870e977034cc17292aeb8d274ed553c7b2e3e3 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 15 Aug 2011 13:22:23 -0400
Subject: Back out later: Turned on curl verbose logging for debugging
 purposes.

---
 indra/llmessage/llcurl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index bfdf49c74b..9ddf8e2824 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -469,7 +469,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	
 	if (post) setoptString(CURLOPT_ENCODING, "");
 
-	//setopt(CURLOPT_VERBOSE, 1); // useful for debugging
+	setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
 	// Set the CURL options for either Socks or HTTP proxy
-- 
cgit v1.2.3


From 61a7a874aa699d0549eb6aef2ee79ee81a384bdb Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 15 Aug 2011 20:05:28 -0400
Subject: Backed out rev 42d5f5df0a6a. Code was apparently needed afterall.

---
 indra/llmessage/llurlrequest.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/indra/llmessage/llurlrequest.cpp b/indra/llmessage/llurlrequest.cpp
index d5400e4169..a186596582 100644
--- a/indra/llmessage/llurlrequest.cpp
+++ b/indra/llmessage/llurlrequest.cpp
@@ -438,6 +438,7 @@ void LLURLRequest::initialize()
 	LLMemType m1(LLMemType::MTYPE_IO_URL_REQUEST);
 	mState = STATE_INITIALIZED;
 	mDetail = new LLURLRequestDetail;
+	LLProxy::getInstance()->applyProxySettings(mDetail->mCurlRequest);
 	mDetail->mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
 	mDetail->mCurlRequest->setWriteCallback(&downCallback, (void*)this);
 	mDetail->mCurlRequest->setReadCallback(&upCallback, (void*)this);
-- 
cgit v1.2.3


From 797b4df42a17f0674a1ac64946deca50b726e523 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 16 Aug 2011 17:35:16 -0400
Subject: Backed out changeset 694594710de2

---
 indra/llmessage/llurlrequest.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/indra/llmessage/llurlrequest.cpp b/indra/llmessage/llurlrequest.cpp
index a186596582..d5400e4169 100644
--- a/indra/llmessage/llurlrequest.cpp
+++ b/indra/llmessage/llurlrequest.cpp
@@ -438,7 +438,6 @@ void LLURLRequest::initialize()
 	LLMemType m1(LLMemType::MTYPE_IO_URL_REQUEST);
 	mState = STATE_INITIALIZED;
 	mDetail = new LLURLRequestDetail;
-	LLProxy::getInstance()->applyProxySettings(mDetail->mCurlRequest);
 	mDetail->mCurlRequest->setopt(CURLOPT_NOSIGNAL, 1);
 	mDetail->mCurlRequest->setWriteCallback(&downCallback, (void*)this);
 	mDetail->mCurlRequest->setReadCallback(&upCallback, (void*)this);
-- 
cgit v1.2.3


From b5f1ee387848e56cb2cd42195056ff5cd7baa01e Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Tue, 16 Aug 2011 17:00:12 -0600
Subject: fix for SH-2023: Brightness Bump maps don't load when shadows are
 enabled

---
 indra/newview/lldrawpoolbump.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/indra/newview/lldrawpoolbump.cpp b/indra/newview/lldrawpoolbump.cpp
index 6f71c54f79..eb78e28306 100644
--- a/indra/newview/lldrawpoolbump.cpp
+++ b/indra/newview/lldrawpoolbump.cpp
@@ -1078,6 +1078,7 @@ LLViewerTexture* LLBumpImageList::getBrightnessDarknessImage(LLViewerFetchedText
 			{
 				src_image->setBoostLevel(LLViewerTexture::BOOST_BUMP) ;
 				src_image->setLoadedCallback( callback_func, 0, TRUE, FALSE, new LLUUID(src_image->getID()), NULL );
+				src_image->forceToSaveRawImage(0) ;
 			}
 		}
 	}
-- 
cgit v1.2.3


From dfcc0849495d40459bce60d4eb754128d6ea53db Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Wed, 17 Aug 2011 15:16:02 -0600
Subject: fix for SH-1142: HUD objects do not display bumpmaps when Lighting
 and Shadows are enabled.

---
 indra/newview/llspatialpartition.cpp | 9 +++++++++
 indra/newview/llspatialpartition.h   | 2 ++
 indra/newview/llvovolume.cpp         | 7 ++++---
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/indra/newview/llspatialpartition.cpp b/indra/newview/llspatialpartition.cpp
index e23b431457..fd17781a2e 100644
--- a/indra/newview/llspatialpartition.cpp
+++ b/indra/newview/llspatialpartition.cpp
@@ -523,6 +523,11 @@ void LLSpatialGroup::clearDrawMap()
 	mDrawMap.clear();
 }
 
+BOOL LLSpatialGroup::isHUDGroup() 
+{
+	return mSpatialPartition && mSpatialPartition->isHUDPartition() ; 
+}
+
 BOOL LLSpatialGroup::isRecentlyVisible() const
 {
 	return (LLDrawable::getCurrentFrame() - mVisible[LLViewerCamera::sCurCameraID]) < LLDrawable::getMinVisFrameRange() ;
@@ -4155,6 +4160,10 @@ void LLSpatialGroup::drawObjectBox(LLColor4 col)
 	drawBox(mObjectBounds[0], size);
 }
 
+bool LLSpatialPartition::isHUDPartition() 
+{ 
+	return mPartitionType == LLViewerRegion::PARTITION_HUD ;
+} 
 
 BOOL LLSpatialPartition::isVisible(const LLVector3& v)
 {
diff --git a/indra/newview/llspatialpartition.h b/indra/newview/llspatialpartition.h
index 54d5d36f6e..11955540c6 100644
--- a/indra/newview/llspatialpartition.h
+++ b/indra/newview/llspatialpartition.h
@@ -282,6 +282,7 @@ public:
 
 	LLSpatialGroup(OctreeNode* node, LLSpatialPartition* part);
 
+	BOOL isHUDGroup() ;
 	BOOL isDead()							{ return isState(DEAD); }
 	BOOL isState(U32 state) const;	
 	BOOL isOcclusionState(U32 state) const	{ return mOcclusionState[LLViewerCamera::sCurCameraID] & state ? TRUE : FALSE; }
@@ -470,6 +471,7 @@ public:
 	S32 cull(LLCamera &camera, std::vector<LLDrawable *>* results = NULL, BOOL for_select = FALSE); // Cull on arbitrary frustum
 	
 	BOOL isVisible(const LLVector3& v);
+	bool isHUDPartition() ;
 	
 	virtual LLSpatialBridge* asBridge() { return NULL; }
 	virtual BOOL isBridge() { return asBridge() != NULL; }
diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp
index eb3ed3c379..528c7acbc8 100755
--- a/indra/newview/llvovolume.cpp
+++ b/indra/newview/llvovolume.cpp
@@ -4490,6 +4490,7 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::
 		std::sort(faces.begin(), faces.end(), LLFace::CompareDistanceGreater());
 	}
 				
+	bool hud_group = group->isHUDGroup() ;
 	std::vector<LLFace*>::iterator face_iter = faces.begin();
 	
 	LLSpatialGroup::buffer_map_t buffer_map;
@@ -4760,7 +4761,7 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::
 					registerFace(group, facep, LLRenderPass::PASS_INVISI_SHINY);
 					registerFace(group, facep, LLRenderPass::PASS_INVISIBLE);
 				}
-				else if (LLPipeline::sRenderDeferred)
+				else if (LLPipeline::sRenderDeferred && !hud_group)
 				{ //deferred rendering
 					if (te->getFullbright())
 					{ //register in post deferred fullbright shiny pass
@@ -4798,7 +4799,7 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::
 				else if (fullbright || bake_sunlight)
 				{ //fullbright
 					registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT);
-					if (LLPipeline::sRenderDeferred && LLPipeline::sRenderBump && te->getBumpmap())
+					if (LLPipeline::sRenderDeferred && !hud_group && LLPipeline::sRenderBump && te->getBumpmap())
 					{ //if this is the deferred render and a bump map is present, register in post deferred bump
 						registerFace(group, facep, LLRenderPass::PASS_POST_BUMP);
 					}
@@ -4824,7 +4825,7 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::
 			}
 			
 			//not sure why this is here, and looks like it might cause bump mapped objects to get rendered redundantly -- davep 5/11/2010
-			if (!is_alpha && !LLPipeline::sRenderDeferred)
+			if (!is_alpha && (hud_group || !LLPipeline::sRenderDeferred))
 			{
 				llassert((mask & LLVertexBuffer::MAP_NORMAL) || fullbright);
 				facep->setPoolType((fullbright) ? LLDrawPool::POOL_FULLBRIGHT : LLDrawPool::POOL_SIMPLE);
-- 
cgit v1.2.3


From c3327eba03972fdda60a14cc0125bb70298fd3da Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Wed, 17 Aug 2011 15:33:18 -0600
Subject: fix for SH-1069: [REGRESSION] Sometimes bumpmaps load only partially

---
 indra/newview/lldrawpoolbump.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/indra/newview/lldrawpoolbump.cpp b/indra/newview/lldrawpoolbump.cpp
index eb78e28306..0742250b0b 100644
--- a/indra/newview/lldrawpoolbump.cpp
+++ b/indra/newview/lldrawpoolbump.cpp
@@ -155,6 +155,7 @@ void LLStandardBumpmap::addstandard()
 			LLViewerTextureManager::getFetchedTexture(LLUUID(bump_image_id));	
 		gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage->setBoostLevel(LLViewerTexture::BOOST_BUMP) ;
 		gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage->setLoadedCallback(LLBumpImageList::onSourceStandardLoaded, 0, TRUE, FALSE, NULL, NULL );
+		gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage->forceToSaveRawImage(0) ;
 		LLStandardBumpmap::sStandardBumpmapCount++;
 	}
 
-- 
cgit v1.2.3


From fe46a8e012e41ca449096897e4f91551c467cd51 Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Wed, 17 Aug 2011 18:12:25 -0600
Subject: fix for sh-2307: crash at LLImageGL::setCategory(int) line 1890

---
 indra/llrender/llimagegl.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/indra/llrender/llimagegl.cpp b/indra/llrender/llimagegl.cpp
index 9ca3a23d52..4892a292cf 100644
--- a/indra/llrender/llimagegl.cpp
+++ b/indra/llrender/llimagegl.cpp
@@ -1887,6 +1887,7 @@ BOOL LLImageGL::getMask(const LLVector2 &tc)
 
 void LLImageGL::setCategory(S32 category) 
 {
+#if 0 //turn this off temporarily because it is not in use now.
 	if(!gAuditTexture)
 	{
 		return ;
@@ -1907,6 +1908,7 @@ void LLImageGL::setCategory(S32 category)
 			mCategory = -1 ;
 		}
 	}
+#endif
 }
 
 //for debug use 
-- 
cgit v1.2.3


From d79eedcfc3bbd0c72505bcf9bec98532a6fd5feb Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 18 Aug 2011 16:07:33 -0400
Subject: LLProxy: Renamed a setting to better describe what it controls.

---
 indra/newview/app_settings/settings.xml                          | 2 +-
 indra/newview/llstartup.cpp                                      | 9 +++++----
 indra/newview/skins/default/xui/en/floater_preferences_proxy.xml | 2 +-
 3 files changed, 7 insertions(+), 6 deletions(-)

diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index d7536bea7a..7a617bb468 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -809,7 +809,7 @@
       <key>Value</key>
       <integer>0</integer>
     </map>
-    <key>Socks5HttpProxyType</key>
+    <key>HttpProxyType</key>
     <map>
       <key>Comment</key>
       <string>Proxy type to use for HTTP operations</string>
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 3fa51c51f5..e053c4b07a 100644
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -2794,7 +2794,7 @@ void LLStartUp::setStartSLURL(const LLSLURL& slurl)
 bool LLStartUp::startLLProxy()
 {
 	bool proxy_ok = true;
-	std::string httpProxyType = gSavedSettings.getString("Socks5HttpProxyType");
+	std::string httpProxyType = gSavedSettings.getString("HttpProxyType");
 
 	// Set up SOCKS proxy (if needed)
 	if (gSavedSettings.getBOOL("Socks5ProxyEnabled"))
@@ -2822,6 +2822,8 @@ bool LLStartUp::startLLProxy()
 		}
 		else
 		{
+			LL_WARNS("Proxy") << "Invalid SOCKS 5 authentication type."<< LL_ENDL;
+
 			// Unknown or missing setting.
 			gSavedSettings.setString("Socks5AuthType", "None");
 
@@ -2834,7 +2836,6 @@ bool LLStartUp::startLLProxy()
 
 		if (proxy_ok)
 		{
-
 			// Start the proxy and check for errors
 			// If status != SOCKS_OK, stopSOCKSProxy() will already have been called when startSOCKSProxy() returns.
 			LLHost socks_host;
@@ -2933,10 +2934,10 @@ bool LLStartUp::startLLProxy()
 		}
 		else
 		{
-			LL_WARNS("Proxy") << "Invalid HTTP proxy configuration."<< LL_ENDL;
+			LL_WARNS("Proxy") << "Invalid other HTTP proxy configuration."<< LL_ENDL;
 
 			// Set the missing or wrong configuration back to something valid.
-			gSavedSettings.setString("Socks5HttpProxyType", "None");
+			gSavedSettings.setString("HttpProxyType", "None");
 			LLProxy::getInstance()->disableHTTPProxy();
 
 			// Leave proxy_ok alone, since this isn't necessarily fatal.
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index fb5f85bf58..35cd118130 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -214,7 +214,7 @@
 	   Other HTTP traffic proxy:
 	</text>
 	<radio_group
-	 control_name="Socks5HttpProxyType"
+	 control_name="HttpProxyType"
 	 height="60"
 	 layout="topleft"
 	 top_pad="9"
-- 
cgit v1.2.3


From 4fb809eed5fbed458b5be883fba7196a5712aa48 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Thu, 18 Aug 2011 16:10:49 -0400
Subject: Backed out revision cbc793dcd3db to disable libcurl verbose logging.

---
 indra/llmessage/llcurl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp
index 9ddf8e2824..bfdf49c74b 100644
--- a/indra/llmessage/llcurl.cpp
+++ b/indra/llmessage/llcurl.cpp
@@ -469,7 +469,7 @@ void LLCurl::Easy::prepRequest(const std::string& url,
 	
 	if (post) setoptString(CURLOPT_ENCODING, "");
 
-	setopt(CURLOPT_VERBOSE, 1); // useful for debugging
+	//setopt(CURLOPT_VERBOSE, 1); // useful for debugging
 	setopt(CURLOPT_NOSIGNAL, 1);
 
 	// Set the CURL options for either Socks or HTTP proxy
-- 
cgit v1.2.3


From 24a0ec9286170bdcd7fd3989f223d4043c2a133d Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Thu, 18 Aug 2011 17:12:35 -0600
Subject: fix for SH-2315: crash at LLVOCacheEntry::~LLVOCacheEntry() line 138

---
 indra/newview/llviewerregion.cpp |  1 +
 indra/newview/llvocache.cpp      | 18 +++++++++++-------
 2 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/indra/newview/llviewerregion.cpp b/indra/newview/llviewerregion.cpp
index db2dc531db..17f908d73f 100644
--- a/indra/newview/llviewerregion.cpp
+++ b/indra/newview/llviewerregion.cpp
@@ -1193,6 +1193,7 @@ LLViewerRegion::eCacheUpdateResult LLViewerRegion::cacheFullUpdate(LLViewerObjec
 	eCacheUpdateResult result = CACHE_UPDATE_ADDED;
 	if (mImpl->mCacheMap.size() > MAX_OBJECT_CACHE_ENTRIES)
 	{
+		delete mImpl->mCacheMap.begin()->second ;
 		mImpl->mCacheMap.erase(mImpl->mCacheMap.begin());
 		result = CACHE_UPDATE_REPLACED;
 		
diff --git a/indra/newview/llvocache.cpp b/indra/newview/llvocache.cpp
index f0b5b50feb..6d457434b5 100644
--- a/indra/newview/llvocache.cpp
+++ b/indra/newview/llvocache.cpp
@@ -621,16 +621,20 @@ void LLVOCache::readFromCache(U64 handle, const LLUUID& id, LLVOCacheEntry::voca
 				S32 num_entries;
 				success = check_read(&apr_file, &num_entries, sizeof(S32)) ;
 	
-				for (S32 i = 0; success && i < num_entries; i++)
+				if(success)
 				{
-					LLVOCacheEntry* entry = new LLVOCacheEntry(&apr_file);
-					if (!entry->getLocalID())
+					for (S32 i = 0; i < num_entries; i++)
 					{
-						llwarns << "Aborting cache file load for " << filename << ", cache file corruption!" << llendl;
-						delete entry ;
-						success = false ;
+						LLVOCacheEntry* entry = new LLVOCacheEntry(&apr_file);
+						if (!entry->getLocalID())
+						{
+							llwarns << "Aborting cache file load for " << filename << ", cache file corruption!" << llendl;
+							delete entry ;
+							success = false ;
+							break ;
+						}
+						cache_entry_map[entry->getLocalID()] = entry;
 					}
-					cache_entry_map[entry->getLocalID()] = entry;
 				}
 			}
 		}		
-- 
cgit v1.2.3


From 0f1dea30f827f920d2323d9450826f1a4baaa10b Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Fri, 19 Aug 2011 13:48:44 +0300
Subject: STORM-1268 Settings for ignorable dialogs were reset during deferred
 auto-upgrade.

Reason:
In case of deferred upgrade (i.e. when you select "Later...") the defaults for notifications settings are not loaded,
so when the viewer exits after launching the updater, it incorrectly re-saves notifications settings.

Fix:
Initialize settings earlier, so that viewer picks them up in update mode.
---
 indra/newview/llappviewer.cpp | 30 ++++++++++++++++++------------
 1 file changed, 18 insertions(+), 12 deletions(-)

diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp
index d12b971bde..7ad5e92f99 100644
--- a/indra/newview/llappviewer.cpp
+++ b/indra/newview/llappviewer.cpp
@@ -731,6 +731,23 @@ bool LLAppViewer::init()
     initThreads();
 	LL_INFOS("InitInfo") << "Threads initialized." << LL_ENDL ;
 
+	// Initialize settings early so that the defaults for ignorable dialogs are
+	// picked up and then correctly re-saved after launching the updater (STORM-1268).
+	LLUI::settings_map_t settings_map;
+	settings_map["config"] = &gSavedSettings;
+	settings_map["ignores"] = &gWarningSettings;
+	settings_map["floater"] = &gSavedSettings; // *TODO: New settings file
+	settings_map["account"] = &gSavedPerAccountSettings;
+
+	LLUI::initClass(settings_map,
+		LLUIImageList::getInstance(),
+		ui_audio_callback,
+		&LLUI::sGLScaleFactor);
+	LL_INFOS("InitInfo") << "UI initialized." << LL_ENDL ;
+
+	LLNotifications::instance();
+	LL_INFOS("InitInfo") << "Notifications initialized." << LL_ENDL ;
+
     writeSystemInfo();
 
 	// Initialize updater service (now that we have an io pump)
@@ -772,19 +789,8 @@ bool LLAppViewer::init()
 	{
 		LLError::setPrintLocation(true);
 	}
-	
-	// Widget construction depends on LLUI being initialized
-	LLUI::settings_map_t settings_map;
-	settings_map["config"] = &gSavedSettings;
-	settings_map["ignores"] = &gWarningSettings;
-	settings_map["floater"] = &gSavedSettings; // *TODO: New settings file
-	settings_map["account"] = &gSavedPerAccountSettings;
 
-	LLUI::initClass(settings_map,
-		LLUIImageList::getInstance(),
-		ui_audio_callback,
-		&LLUI::sGLScaleFactor);
-	
+
 	// Setup paths and LLTrans after LLUI::initClass has been called
 	LLUI::setupPaths();
 	LLTransUtil::parseStrings("strings.xml", default_trans_args);		
-- 
cgit v1.2.3


From 51c837dda7661ad7b9d90d96e35117eacc7a113a Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Fri, 19 Aug 2011 19:53:44 +0300
Subject: STORM-1543 WIP Fixed dropping nventory offers in busy mode.

When auto-discarding inventory offers we looked up missing Busy button
(i.e. a button having index=3) in the inventory offer notification dialog
template. Failure to find the button resulted in ignoring inventory offers.

Fixed that by "auto-clicking" the existing Discard button.
---
 indra/newview/llviewermessage.cpp | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 321d02aaf1..8177446778 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -1495,6 +1495,13 @@ bool LLOfferInfo::inventory_offer_callback(const LLSD& notification, const LLSD&
 	LLChat chat;
 	std::string log_message;
 	S32 button = LLNotificationsUtil::getSelectedOption(notification, response);
+
+	// The offer notification has no Busy button,
+	// so if we're in busy mode, assume busy response (STORM-1543).
+	if (gAgent.getBusy())
+	{
+		button = IOR_BUSY;
+	}
 	
 	LLInventoryObserver* opener = NULL;
 	LLViewerInventoryCategory* catp = NULL;
@@ -2667,7 +2674,7 @@ void process_improved_im(LLMessageSystem *msg, void **user_data)
 			{
 				// Until throttling is implemented, busy mode should reject inventory instead of silently
 				// accepting it.  SEE SL-39554
-				info->forceResponse(IOR_BUSY);
+				info->forceResponse(IOR_DECLINE);
 			}
 			else
 			{
-- 
cgit v1.2.3


From 1ed945b5a08a40399ff63ed657c66416c3baf7cf Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Fri, 19 Aug 2011 19:58:00 +0300
Subject: STORM-1543 WIP Fixed auto-moving offered inventory items to trash.

It turned out impossible to properly remove an inventory item
from within LLDiscardAgentOffer::done(), because that would lead to
nested LLInventoryModel::notifyObservers() calls.

Fixed that by deferring removal until the next LLAppViewer::idle() iteration.

Also elimiteed duplicated code.
---
 indra/newview/llappviewer.cpp     | 48 +++++++++++++++++++++++++++++++++++++++
 indra/newview/llappviewer.h       |  2 ++
 indra/newview/llviewermessage.cpp | 32 ++------------------------
 3 files changed, 52 insertions(+), 30 deletions(-)

diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp
index d12b971bde..16c2b2d55a 100644
--- a/indra/newview/llappviewer.cpp
+++ b/indra/newview/llappviewer.cpp
@@ -321,6 +321,47 @@ static std::string gLaunchFileOnQuit;
 // Used on Win32 for other apps to identify our window (eg, win_setup)
 const char* const VIEWER_WINDOW_CLASSNAME = "Second Life";
 
+//-- LLDeferredTaskList ------------------------------------------------------
+
+/**
+ * A list of deferred tasks.
+ *
+ * We sometimes need to defer execution of some code until the viewer gets idle,
+ * e.g. removing an inventory item from within notifyObservers() may not work out.
+ *
+ * Tasks added to this list will be executed in the next LLAppViewer::idle() iteration.
+ * All tasks are executed only once.
+ */
+class LLDeferredTaskList:
+	public LLSingleton<LLDeferredTaskList>,
+	private LLDestroyClass<LLDeferredTaskList>
+{
+	LOG_CLASS(LLDeferredTaskList);
+	friend class LLAppViewer;
+	friend class LLDestroyClass<LLDeferredTaskList>;
+	typedef boost::signals2::signal<void()> signal_t;
+
+	void addTask(const signal_t::slot_type& cb)
+	{
+		mSignal.connect(cb);
+	}
+
+	void run()
+	{
+		if (mSignal.empty()) return;
+
+		mSignal();
+		mSignal.disconnect_all_slots();
+	}
+
+	static void destroyClass()
+	{
+		instance().mSignal.disconnect_all_slots();
+	}
+
+	signal_t mSignal;
+};
+
 //----------------------------------------------------------------------------
 
 // List of entries from strings.xml to always replace
@@ -3820,6 +3861,11 @@ bool LLAppViewer::initCache()
 	}
 }
 
+void LLAppViewer::addOnIdleCallback(const boost::function<void()>& cb)
+{
+	LLDeferredTaskList::instance().addTask(cb);
+}
+
 void LLAppViewer::purgeCache()
 {
 	LL_INFOS("AppCache") << "Purging Cache and Texture Cache..." << LL_ENDL;
@@ -4413,6 +4459,8 @@ void LLAppViewer::idle()
 			gAudiop->idle(max_audio_decode_time);
 		}
 	}
+
+	LLDeferredTaskList::instance().run();
 	
 	// Handle shutdown process, for example, 
 	// wait for floaters to close, send quit message,
diff --git a/indra/newview/llappviewer.h b/indra/newview/llappviewer.h
index 61ee6a7cf1..32115e0e7b 100644
--- a/indra/newview/llappviewer.h
+++ b/indra/newview/llappviewer.h
@@ -164,6 +164,8 @@ public:
 	login_completed_signal_t mOnLoginCompleted;
 	boost::signals2::connection setOnLoginCompletedCallback( const login_completed_signal_t::slot_type& cb ) { return mOnLoginCompleted.connect(cb); } 
 
+	void addOnIdleCallback(const boost::function<void()>& cb); // add a callback to fire (once) when idle
+
 	void purgeCache(); // Clear the local cache. 
 	
 	// mute/unmute the system's master audio
diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 8177446778..2c783cd4b6 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -1058,37 +1058,9 @@ public:
 	virtual void done()
 	{
 		LL_DEBUGS("Messaging") << "LLDiscardAgentOffer::done()" << LL_ENDL;
-		const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
-		bool notify = false;
-		if(trash_id.notNull() && mObjectID.notNull())
-		{
-			LLInventoryModel::update_list_t update;
-			LLInventoryModel::LLCategoryUpdate old_folder(mFolderID, -1);
-			update.push_back(old_folder);
-			LLInventoryModel::LLCategoryUpdate new_folder(trash_id, 1);
-			update.push_back(new_folder);
-			gInventory.accountForUpdate(update);
-			gInventory.moveObject(mObjectID, trash_id);
-			LLInventoryObject* obj = gInventory.getObject(mObjectID);
-			if(obj)
-			{
-				// no need to restamp since this is already a freshly
-				// stamped item.
-				obj->updateParentOnServer(FALSE);
-				notify = true;
-			}
-		}
-		else
-		{
-			LL_WARNS("Messaging") << "DiscardAgentOffer unable to find: "
-					<< (trash_id.isNull() ? "trash " : "")
-					<< (mObjectID.isNull() ? "object" : "") << LL_ENDL;
-		}
+
+		LLAppViewer::instance()->addOnIdleCallback(boost::bind(&LLInventoryModel::removeItem, &gInventory, mObjectID));
 		gInventory.removeObserver(this);
-		if(notify)
-		{
-			gInventory.notifyObservers();
-		}
 		delete this;
 	}
 protected:
-- 
cgit v1.2.3


From e0b5ff5c5289f965c943dcba93f0b5d94d1ba1f9 Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Fri, 19 Aug 2011 19:59:13 +0300
Subject: STORM-1543 WIP Minor cleanup.

---
 indra/newview/llviewermessage.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 2c783cd4b6..22966015c8 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -1049,12 +1049,13 @@ void start_new_inventory_observer()
 class LLDiscardAgentOffer : public LLInventoryFetchItemsObserver
 {
 	LOG_CLASS(LLDiscardAgentOffer);
+
 public:
 	LLDiscardAgentOffer(const LLUUID& folder_id, const LLUUID& object_id) :
 		LLInventoryFetchItemsObserver(object_id),
 		mFolderID(folder_id),
 		mObjectID(object_id) {}
-	virtual ~LLDiscardAgentOffer() {}
+
 	virtual void done()
 	{
 		LL_DEBUGS("Messaging") << "LLDiscardAgentOffer::done()" << LL_ENDL;
@@ -1063,6 +1064,7 @@ public:
 		gInventory.removeObserver(this);
 		delete this;
 	}
+
 protected:
 	LLUUID mFolderID;
 	LLUUID mObjectID;
-- 
cgit v1.2.3


From 428c762a3ea6caec277d915b8b175403cf3f52dd Mon Sep 17 00:00:00 2001
From: Xiaohong Bao <bao@lindenlab.com>
Date: Fri, 19 Aug 2011 13:27:51 -0600
Subject: fix for SH-1498: crash at LLImageGL::deleteDeadTextures() line 1429

---
 indra/llrender/llimagegl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/llrender/llimagegl.cpp b/indra/llrender/llimagegl.cpp
index 4892a292cf..7188b0fa44 100644
--- a/indra/llrender/llimagegl.cpp
+++ b/indra/llrender/llimagegl.cpp
@@ -1424,7 +1424,7 @@ void LLImageGL::deleteDeadTextures()
 		{
 			LLTexUnit* tex_unit = gGL.getTexUnit(i);
 
-			if (tex_unit->getCurrTexture() == tex)
+			if (tex_unit && tex_unit->getCurrTexture() == tex)
 			{
 				tex_unit->unbind(tex_unit->getCurrType());
 				stop_glerror();
-- 
cgit v1.2.3


From 5578c285d866488d06f99f5e72e3fb9291d37eca Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Mon, 22 Aug 2011 14:01:18 +0300
Subject: STORM-1543 WIP More cleanup and comments.

---
 indra/newview/llappviewer.cpp     | 21 ++++++++-------------
 indra/newview/llviewermessage.cpp |  4 ++++
 2 files changed, 12 insertions(+), 13 deletions(-)

diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp
index 16c2b2d55a..326b5fd629 100644
--- a/indra/newview/llappviewer.cpp
+++ b/indra/newview/llappviewer.cpp
@@ -332,13 +332,11 @@ const char* const VIEWER_WINDOW_CLASSNAME = "Second Life";
  * Tasks added to this list will be executed in the next LLAppViewer::idle() iteration.
  * All tasks are executed only once.
  */
-class LLDeferredTaskList:
-	public LLSingleton<LLDeferredTaskList>,
-	private LLDestroyClass<LLDeferredTaskList>
+class LLDeferredTaskList: public LLSingleton<LLDeferredTaskList>
 {
 	LOG_CLASS(LLDeferredTaskList);
+
 	friend class LLAppViewer;
-	friend class LLDestroyClass<LLDeferredTaskList>;
 	typedef boost::signals2::signal<void()> signal_t;
 
 	void addTask(const signal_t::slot_type& cb)
@@ -348,15 +346,11 @@ class LLDeferredTaskList:
 
 	void run()
 	{
-		if (mSignal.empty()) return;
-
-		mSignal();
-		mSignal.disconnect_all_slots();
-	}
-
-	static void destroyClass()
-	{
-		instance().mSignal.disconnect_all_slots();
+		if (!mSignal.empty())
+		{
+			mSignal();
+			mSignal.disconnect_all_slots();
+		}
 	}
 
 	signal_t mSignal;
@@ -4460,6 +4454,7 @@ void LLAppViewer::idle()
 		}
 	}
 
+	// Execute deferred tasks.
 	LLDeferredTaskList::instance().run();
 	
 	// Handle shutdown process, for example, 
diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 22966015c8..793abb1c9d 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -1060,6 +1060,10 @@ public:
 	{
 		LL_DEBUGS("Messaging") << "LLDiscardAgentOffer::done()" << LL_ENDL;
 
+		// We're invoked from LLInventoryModel::notifyObservers().
+		// If we now try to remove the inventory item, it will cause a nested
+		// notifyObservers() call, which won't work.
+		// So defer moving the item to trash until viewer gets idle (in a moment).
 		LLAppViewer::instance()->addOnIdleCallback(boost::bind(&LLInventoryModel::removeItem, &gInventory, mObjectID));
 		gInventory.removeObserver(this);
 		delete this;
-- 
cgit v1.2.3


From e7fb4ef9541400b00fb570d5c385eafa7eb60c41 Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Mon, 22 Aug 2011 14:23:34 +0300
Subject: STORM-1542 FIXED Changed search URL back from search-beta to
 search.sl.com.

---
 indra/newview/app_settings/settings.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index 7c01731282..7fb5c4d2dc 100644
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -3993,7 +3993,7 @@
       <key>Type</key>
       <string>String</string>
       <key>Value</key>
-      <string>http://search-beta.secondlife.com/viewer/[CATEGORY]/?q=[QUERY]</string>
+      <string>http://search.secondlife.com/viewer/[CATEGORY]/?q=[QUERY]</string>
     </map>
     <key>WebProfileURL</key>
     <map>
-- 
cgit v1.2.3


From 61f4c953c4eb63fddf553bd114dc6116e6e464b6 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Mon, 22 Aug 2011 20:32:10 -0400
Subject: Fixed a xui widget name mismatch between c++ and xml.

---
 indra/newview/llfloaterpreference.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index bd9efdd409..456f898bfa 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -2095,7 +2095,7 @@ void LLFloaterPreferenceProxy::onChangeSocksSettings()
 	}
 
 	// Check for invalid states for the other HTTP proxy radio
-	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_selection");
+	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("HttpProxyType");
 	if ((otherHttpProxy->getSelectedValue().asString() == "Socks" &&
 			getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
 					otherHttpProxy->getSelectedValue().asString() == "Web" &&
-- 
cgit v1.2.3


From 05e5ea243ea2acc9e86471c884d1a2d39c9c8e60 Mon Sep 17 00:00:00 2001
From: Logan Dethrow <log@lindenlab.com>
Date: Tue, 23 Aug 2011 17:06:38 -0400
Subject: Fixed LLProxy UI constraints.  Fixed some XUI warnings in the Proxy
 Settings Floater.

---
 indra/newview/llfloaterpreference.cpp                            | 2 +-
 indra/newview/skins/default/xui/en/floater_preferences_proxy.xml | 8 ++++----
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index 456f898bfa..d65928e385 100755
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -2095,7 +2095,7 @@ void LLFloaterPreferenceProxy::onChangeSocksSettings()
 	}
 
 	// Check for invalid states for the other HTTP proxy radio
-	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("HttpProxyType");
+	LLRadioGroup* otherHttpProxy = getChild<LLRadioGroup>("other_http_proxy_type");
 	if ((otherHttpProxy->getSelectedValue().asString() == "Socks" &&
 			getChild<LLCheckBoxCtrl>("socks_proxy_enabled")->get() == FALSE )||(
 					otherHttpProxy->getSelectedValue().asString() == "Web" &&
diff --git a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
index 35cd118130..449731ab89 100644
--- a/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
+++ b/indra/newview/skins/default/xui/en/floater_preferences_proxy.xml
@@ -138,7 +138,6 @@
 	 name="socks5_auth_type"
 	 top_pad="10"
 	 width="120"
-	 border="1"
 	 commit_callback.function="Proxy.Change" >
 		<radio_item
 		 height="16"
@@ -215,17 +214,18 @@
 	</text>
 	<radio_group
 	 control_name="HttpProxyType"
+	 name="other_http_proxy_type"
 	 height="60"
 	 layout="topleft"
 	 top_pad="9"
 	 width="120"
-	 border="1"
 	 left_delta="15" 
 	 commit_callback.function="Proxy.Change" >
 		<radio_item
 		 height="16"
 		 label="Do not proxy"
 		 layout="topleft"
+		 name="OtherNoProxy"
 		 value="None"
 		 width="120"
 		 tool_tip="Non-web HTTP traffic will NOT be sent to any proxy."/>
@@ -233,6 +233,7 @@
 		 height="16"
 		 label="Use HTTP Proxy"
 		 layout="topleft"
+		 name="OtherHTTPProxy"
 		 value="Web"
 		 width="120"
 		 enabled_control="BrowserProxyEnabled"
@@ -241,6 +242,7 @@
 		 height="16"
 		 label="Use SOCKS 5 Proxy"
 		 layout="topleft"
+		 name="OtherSocksProxy"
 		 value="Socks"
 		 width="120"
 		 enabled_control="Socks5ProxyEnabled"
@@ -268,6 +270,4 @@
 	 top_delta="0"
 	 width="90"
 	 commit_callback.function="Proxy.Cancel" />
-	 
-	 
 </floater>
-- 
cgit v1.2.3


From c7141025c85ebabc0447a7d7c6f580c2e6c47f74 Mon Sep 17 00:00:00 2001
From: Aaron Stone <stone@lindenlab.com>
Date: Tue, 23 Aug 2011 14:45:42 -0700
Subject: Respect --no-verify-ssl-cert option.

---
 indra/newview/llsechandler_basic.cpp            | 2 ++
 indra/newview/tests/llsechandler_basic_test.cpp | 3 +++
 2 files changed, 5 insertions(+)

diff --git a/indra/newview/llsechandler_basic.cpp b/indra/newview/llsechandler_basic.cpp
index 904bb03270..8d64c8c04f 100644
--- a/indra/newview/llsechandler_basic.cpp
+++ b/indra/newview/llsechandler_basic.cpp
@@ -1005,6 +1005,8 @@ void LLBasicCertificateStore::validate(int validation_policy,
 									   LLPointer<LLCertificateChain> cert_chain,
 									   const LLSD& validation_params)
 {
+	// If --no-verify-ssl-cert was passed on the command line, stop right now.
+	if (gSavedSettings.getBOOL("NoVerifySSLCert")) return;
 
 	if(cert_chain->size() < 1)
 	{
diff --git a/indra/newview/tests/llsechandler_basic_test.cpp b/indra/newview/tests/llsechandler_basic_test.cpp
index daa10819fc..0235400976 100644
--- a/indra/newview/tests/llsechandler_basic_test.cpp
+++ b/indra/newview/tests/llsechandler_basic_test.cpp
@@ -86,6 +86,9 @@ std::string LLControlGroup::getString(const std::string& name)
 	return "";
 }
 
+// Stub for --no-verify-ssl-cert
+BOOL LLControlGroup::getBOOL(const std::string& name) { return FALSE; }
+
 LLSD LLCredential::getLoginParams()
 {
 	LLSD result = LLSD::emptyMap();
-- 
cgit v1.2.3


From a4f132f1b88b151db1e834069bc6e9b49f9c5a17 Mon Sep 17 00:00:00 2001
From: Vadim ProductEngine <vsavchuk@productengine.com>
Date: Fri, 26 Aug 2011 00:19:33 +0300
Subject: STORM-1543 WIP Removed invalid IOR_BUSY response option.

Addressing review feedback.
---
 indra/newview/llviewermessage.cpp | 17 ++---------------
 indra/newview/llviewermessage.h   |  1 -
 2 files changed, 2 insertions(+), 16 deletions(-)

diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 793abb1c9d..64aeb750c6 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -1474,13 +1474,6 @@ bool LLOfferInfo::inventory_offer_callback(const LLSD& notification, const LLSD&
 	std::string log_message;
 	S32 button = LLNotificationsUtil::getSelectedOption(notification, response);
 
-	// The offer notification has no Busy button,
-	// so if we're in busy mode, assume busy response (STORM-1543).
-	if (gAgent.getBusy())
-	{
-		button = IOR_BUSY;
-	}
-	
 	LLInventoryObserver* opener = NULL;
 	LLViewerInventoryCategory* catp = NULL;
 	catp = (LLViewerInventoryCategory*)gInventory.getCategory(mObjectID);
@@ -1512,7 +1505,7 @@ bool LLOfferInfo::inventory_offer_callback(const LLSD& notification, const LLSD&
 	// TODO: when task inventory offers can also be handled the new way, migrate the code that sets these strings here:
 	from_string = chatHistory_string = mFromName;
 	
-	bool busy=FALSE;
+	bool busy = gAgent.getBusy();
 	
 	switch(button)
 	{
@@ -1571,9 +1564,6 @@ bool LLOfferInfo::inventory_offer_callback(const LLSD& notification, const LLSD&
 		}
 		break;
 
-	case IOR_BUSY:
-		//Busy falls through to decline.  Says to make busy message.
-		busy=TRUE;
 	case IOR_MUTE:
 		// MUTE falls through to decline
 	case IOR_DECLINE:
@@ -1719,7 +1709,7 @@ bool LLOfferInfo::inventory_task_offer_callback(const LLSD& notification, const
 		from_string = chatHistory_string = mFromName;
 	}
 	
-	bool busy=FALSE;
+	bool busy = gAgent.getBusy();
 	
 	switch(button)
 	{
@@ -1765,9 +1755,6 @@ bool LLOfferInfo::inventory_task_offer_callback(const LLSD& notification, const
 		}	// end switch (mIM)
 			break;
 			
-		case IOR_BUSY:
-			//Busy falls through to decline.  Says to make busy message.
-			busy=TRUE;
 		case IOR_MUTE:
 			// MUTE falls through to decline
 		case IOR_DECLINE:
diff --git a/indra/newview/llviewermessage.h b/indra/newview/llviewermessage.h
index 9d09d9c01a..d8acd99953 100644
--- a/indra/newview/llviewermessage.h
+++ b/indra/newview/llviewermessage.h
@@ -57,7 +57,6 @@ enum InventoryOfferResponse
 	IOR_ACCEPT,
 	IOR_DECLINE,
 	IOR_MUTE,
-	IOR_BUSY,
 	IOR_SHOW
 };
 
-- 
cgit v1.2.3