public TorInstance(string _torloc, int _controlPort, int _socksPort, bool useExistingTorPorts = false) { // Assign member variables // state = TorState.Bootstrapping; torloc = _torloc; controlPort = (ushort)_controlPort; socksPort = (ushort)_socksPort; dataDirectory = string.Format("./data/{0}", this.GetHashCode()); System.Console.WriteLine("TorInstance({0:d}) created. Socks: {1:d}", this.GetHashCode(), socksPort); factory = new ProxyClientFactory(); proxy = factory.CreateProxyClient(ProxyType.Socks5, "127.0.0.1", socksPort); if (!useExistingTorPorts) { StartTorThread(); } else { state = TorState.Ready; } }
/// <overloads>this method has 2 overloads</overloads> /// <summary> /// Connects to the specified server and port, when the connection fails /// the next server in the list will be used. /// </summary> /// <param name="addresslist">List of servers to connect to</param> /// <param name="port">Portnumber to connect to</param> /// <exception cref="CouldNotConnectException">The connection failed</exception> /// <exception cref="AlreadyConnectedException">If there is already an active connection</exception> public void Connect(string[] addresslist, int port) { if (_IsConnected) { throw new AlreadyConnectedException("Already connected to: " + Address + ":" + Port); } _AutoRetryAttempt++; #if LOG4NET Logger.Connection.Info(String.Format("connecting... (attempt: {0})", _AutoRetryAttempt)); #endif _AddressList = (string[])addresslist.Clone(); _Port = port; if (OnConnecting != null) { OnConnecting(this, EventArgs.Empty); } try { _TcpClient = new TcpClient(); _TcpClient.NoDelay = true; _TcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); // set timeout, after this the connection will be aborted _TcpClient.ReceiveTimeout = _SocketReceiveTimeout * 1000; _TcpClient.SendTimeout = _SocketSendTimeout * 1000; if (_ProxyType != ProxyType.None) { IProxyClient proxyClient = null; ProxyClientFactory proxyFactory = new ProxyClientFactory(); // HACK: map our ProxyType to Starksoft's ProxyType Starksoft.Net.Proxy.ProxyType proxyType = (Starksoft.Net.Proxy.ProxyType) Enum.Parse( typeof(ProxyType), _ProxyType.ToString(), true ); if (_ProxyUsername == null && _ProxyPassword == null) { proxyClient = proxyFactory.CreateProxyClient( proxyType ); } else { proxyClient = proxyFactory.CreateProxyClient( proxyType, _ProxyHost, _ProxyPort, _ProxyUsername, _ProxyPassword ); } _TcpClient.Connect(_ProxyHost, _ProxyPort); proxyClient.TcpClient = _TcpClient; proxyClient.CreateConnection(Address, port); } else { _TcpClient.Connect(Address, port); } Stream stream = _TcpClient.GetStream(); if (_UseSsl) { RemoteCertificateValidationCallback certValidation; if (_ValidateServerCertificate) { certValidation = ServicePointManager.ServerCertificateValidationCallback; if (certValidation == null) { certValidation = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } #if LOG4NET Logger.Connection.Error( "Connect(): Certificate error: " + sslPolicyErrors ); #endif return false; }; } } else { certValidation = delegate { return true; }; } RemoteCertificateValidationCallback certValidationWithIrcAsSender = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return certValidation(this, certificate, chain, sslPolicyErrors); }; LocalCertificateSelectionCallback selectionCallback = delegate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { if (localCertificates == null || localCertificates.Count == 0) { return null; } return localCertificates[0]; }; SslStream sslStream = new SslStream(stream, false, certValidationWithIrcAsSender, selectionCallback); try { if (_SslClientCertificate != null) { var certs = new X509Certificate2Collection(); certs.Add(_SslClientCertificate); sslStream.AuthenticateAsClient(Address, certs, SslProtocols.Default, false); } else { sslStream.AuthenticateAsClient(Address); } } catch (IOException ex) { #if LOG4NET Logger.Connection.Error( "Connect(): AuthenticateAsClient() failed!" ); #endif throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + ex.Message, ex); } stream = sslStream; } if (EnableUTF8Recode) { _Reader = new StreamReader(stream, new PrimaryOrFallbackEncoding(new UTF8Encoding(false, true), _Encoding)); _Writer = new StreamWriter(stream, new UTF8Encoding(false, false)); } else { _Reader = new StreamReader(stream, _Encoding); _Writer = new StreamWriter(stream, _Encoding); if (_Encoding.GetPreamble().Length > 0) { // HACK: we have an encoding that has some kind of preamble // like UTF-8 has a BOM, this will confuse the IRCd! // Thus we send a \r\n so the IRCd can safely ignore that // garbage. _Writer.WriteLine(); // make sure we flush the BOM+CRLF correctly _Writer.Flush(); } } // Connection was succeful, reseting the connect counter _AutoRetryAttempt = 0; // updating the connection error state, so connecting is possible again IsConnectionError = false; _IsConnected = true; // lets power up our threads _ReadThread.Start(); _WriteThread.Start(); _IdleWorkerThread.Start(); #if LOG4NET Logger.Connection.Info("connected"); #endif if (OnConnected != null) { OnConnected(this, EventArgs.Empty); } } catch (AuthenticationException ex) { #if LOG4NET Logger.Connection.Error("Connect(): Exception", ex); #endif throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + ex.Message, ex); } catch (Exception e) { if (_Reader != null) { try { _Reader.Close(); } catch (ObjectDisposedException) { } } if (_Writer != null) { try { _Writer.Close(); } catch (ObjectDisposedException) { } } if (_TcpClient != null) { _TcpClient.Close(); } _IsConnected = false; IsConnectionError = true; #if LOG4NET Logger.Connection.Info("connection failed: "+e.Message, e); #endif if (e is CouldNotConnectException) { // error was fatal, bail out throw; } if (_AutoRetry && (_AutoRetryLimit == -1 || _AutoRetryLimit == 0 || _AutoRetryLimit <= _AutoRetryAttempt)) { if (OnAutoConnectError != null) { OnAutoConnectError(this, new AutoConnectErrorEventArgs(Address, Port, e)); } #if LOG4NET Logger.Connection.Debug("delaying new connect attempt for "+_AutoRetryDelay+" sec"); #endif Thread.Sleep(_AutoRetryDelay * 1000); _NextAddress(); // FIXME: this is recursion Connect(_AddressList, _Port); } else { throw new CouldNotConnectException("Could not connect to: "+Address+":"+Port+" "+e.Message, e); } } }
// Proxy for FTP public IProxyClient GetProxyClient() { if (IsValidProxy()) { Starksoft.Net.Proxy.ProxyType proxyType; switch (ProxyType) { case ProxyType.HTTP: proxyType = Starksoft.Net.Proxy.ProxyType.Http; break; case ProxyType.SOCKS4: proxyType = Starksoft.Net.Proxy.ProxyType.Socks4; break; case ProxyType.SOCKS4a: proxyType = Starksoft.Net.Proxy.ProxyType.Socks4a; break; case ProxyType.SOCKS5: proxyType = Starksoft.Net.Proxy.ProxyType.Socks5; break; default: proxyType = Starksoft.Net.Proxy.ProxyType.None; break; } ProxyClientFactory proxy = new ProxyClientFactory(); return proxy.CreateProxyClient(proxyType, Host, Port, Username, Password); } return null; }
public IProxyClient GetProxyClient(ProxyInfo myProxyInfo) { if (myProxyInfo != null) { ProxyType proxyType; switch (myProxyInfo.ProxyType) { case Proxy.HTTP: proxyType = ProxyType.Http; break; case Proxy.SOCKS4: proxyType = ProxyType.Socks4; break; case Proxy.SOCKS4a: proxyType = ProxyType.Socks4a; break; case Proxy.SOCKS5: proxyType = ProxyType.Socks5; break; default: proxyType = ProxyType.None; break; } ProxyClientFactory proxy = new ProxyClientFactory(); return proxy.CreateProxyClient(proxyType, myProxyInfo.Host, myProxyInfo.Port, myProxyInfo.UserName, myProxyInfo.Password); } return null; }
/// <summary> /// /// </summary> /// <param name="targetHost"></param> /// <param name="targetPort"></param> /// <returns></returns> TcpClient ConnectViaHTTPProxy( ) { // create an instance of the client proxy factory ProxyClientFactory factory = new ProxyClientFactory(); // use the proxy client factory to generically specify the type of proxy to create // the proxy factory method CreateProxyClient returns an IProxyClient object IProxyClient proxy = factory.CreateProxyClient(ProxyType.Http, ProxyInfo.Host, ProxyInfo.Port, ProxyInfo.UserName, ProxyInfo.Password); // create a connection through the proxy to www.starksoft.com over port 80 return proxy.CreateConnection(Host, Port); }
void ApplyConfig(UserConfig config, XmppServerModel server) { if (String.IsNullOrEmpty(server.Nickname)) { Nicknames = (string[]) config["Connection/Nicknames"]; } else { Nicknames = new string[] { server.Nickname }; } if (server.Username.Contains("@")) { var jid_user = server.Username.Split('@')[0]; var jid_host = server.Username.Split('@')[1]; JabberClient.ConnectServer = server.Hostname; JabberClient.AutoResolveConnectServer = false; JabberClient.Username = jid_user; JabberClient.Server = jid_host; } else { JabberClient.Server = server.Hostname; JabberClient.Username = server.Username; } JabberClient.Port = server.Port; JabberClient.Password = server.Password; var proxySettings = new ProxySettings(); proxySettings.ApplyConfig(config); var protocol = Server.UseEncryption ? "xmpps" : "xmpp"; var serverUri = String.Format("{0}://{1}:{2}", protocol, Server.Hostname, Server.Port); var proxy = proxySettings.GetWebProxy(serverUri); var socket = JabberClient.ClientSocket as ClientSocket; if (proxy == null) { socket.Proxy = null; } else { var builder = CreateMessageBuilder(); builder.AppendEventPrefix(); builder.AppendText(_("Using proxy: {0}:{1}"), proxy.Address.Host, proxy.Address.Port); Session.AddMessageToChat(Chat, builder.ToMessage()); var proxyScheme = proxy.Address.Scheme; var proxyType = Starksoft.Net.Proxy.ProxyType.None; try { proxyType = (Starksoft.Net.Proxy.ProxyType) Enum.Parse( typeof(Starksoft.Net.Proxy.ProxyType), proxy.Address.Scheme, true ); } catch (ArgumentException ex) { #if LOG4NET _Logger.Error("ApplyConfig(): Couldn't parse proxy type: " + proxyScheme, ex); #endif } var proxyFactory = new ProxyClientFactory(); if (String.IsNullOrEmpty(proxySettings.ProxyUsername) && String.IsNullOrEmpty(proxySettings.ProxyPassword)) { socket.Proxy = proxyFactory.CreateProxyClient( proxyType, proxy.Address.Host, proxy.Address.Port ); } else { socket.Proxy = proxyFactory.CreateProxyClient( proxyType, proxy.Address.Host, proxy.Address.Port, proxySettings.ProxyUsername, proxySettings.ProxyPassword ); } } Me = new PersonModel( JabberClient.MyJID.Bare, Nicknames[0], NetworkID, Protocol, this ); Me.IdentityNameColored.ForegroundColor = new TextColor(0, 0, 255); Me.IdentityNameColored.BackgroundColor = TextColor.None; Me.IdentityNameColored.Bold = true; // XMPP specific settings JabberClient.Resource = server.Resource; if (server.UseEncryption) { // HACK: Google Talk doesn't support StartTLS :( if (server.Hostname == "talk.google.com" && server.Port == 5223) { JabberClient.ForceStartTls = false; JabberClient.UseSSL = true; } else { JabberClient.ForceStartTls = true; } } else { JabberClient.ForceStartTls = false; JabberClient.UseStartTLS = true; } if (!server.ValidateServerCertificate) { JabberClient.ClientSocket.OnValidateCertificate += ValidateCertificate; } }
/// <summary> /// Creates the proxy from the values within this object. /// </summary> /// <returns> /// The proxy. /// </returns> public IProxyClient CreateProxy() { var pcf = new ProxyClientFactory(); if (string.IsNullOrWhiteSpace(UserName)) { return pcf.CreateProxyClient(Type, Host, Port); } return pcf.CreateProxyClient(Type, Host, Port, UserName, Password ?? string.Empty); }