Exemple #1
0
    bool IsTimeoutException(SocketException e)
    {
#if CF
       return (e.NativeErrorCode == 10060);
#else
        return (e.SocketErrorCode == SocketError.TimedOut);
#endif
    }
Exemple #2
0
    bool IsWouldBlockException(SocketException e)
    {
#if CF
      return (e.NativeErrorCode == 10035);
#else
      return (e.SocketErrorCode == SocketError.WouldBlock);
#endif
    }
Exemple #3
0
        /// <summary>
        /// Handles the command input from the client.  This
        /// message returns when the client issues the quit command.
        /// </summary>
        private void ProcessCommands(SmtpContext context)
        {
            bool   isRunning = true;
            string inputLine;

            // Loop until the client quits.
            while (isRunning)
            {
                try
                {
                    inputLine = context.ReadLine();
                    if (inputLine == null)
                    {
                        isRunning = false;
                        context.WriteLine(MESSAGE_GOODBYE);
                        context.Close();
                        continue;
                    }

                    string[] inputs = inputLine.Split(" ".ToCharArray());

                    switch (inputs[0].ToLower())
                    {
                    case "helo":
                        this.Helo(context, inputs);
                        break;

                    case "rset":
                        this.Rset(context);
                        break;

                    case "noop":
                        context.WriteLine(MESSAGE_OK);
                        break;

                    case "quit":
                        isRunning = false;
                        context.WriteLine(MESSAGE_GOODBYE);
                        context.Close();
                        break;

                    case "mail":
                        if (inputs[1].ToLower().StartsWith("from"))
                        {
                            this.Mail(context, inputLine.Substring(inputLine.IndexOf(" ")));
                            break;
                        }

                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;

                    case "rcpt":
                        if (inputs[1].ToLower().StartsWith("to"))
                        {
                            this.Rcpt(context, inputLine.Substring(inputLine.IndexOf(" ")));
                            break;
                        }

                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;

                    case "data":
                        this.Data(context);
                        break;

                    default:
                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    SocketException sx = ex as SocketException;

                    if (sx != null && sx.ErrorCode == 10060)
                    {
                        context.WriteLine(MESSAGE_GOODBYE);
                    }

                    // else
                    //    context.WriteLine(MESSAGE_SYSTEM_ERROR);

                    isRunning = false;
                    context.Socket.Dispose();
                }
            }
        }
        public static bool IsSocketExceptionRetryable(SocketException socketException)
        {
            ArgCheck.NotNull(nameof(socketException), socketException);

            switch (socketException.SocketErrorCode)
            {
            case SocketError.AccessDenied:
            case SocketError.ConnectionAborted:
            case SocketError.ConnectionRefused:
            case SocketError.ConnectionReset:
            case SocketError.Disconnecting:
            case SocketError.Fault:
            case SocketError.HostDown:
            case SocketError.HostNotFound:
            case SocketError.HostUnreachable:
            case SocketError.InProgress:
            case SocketError.Interrupted:
            case SocketError.IOPending:
            case SocketError.IsConnected:
            case SocketError.MessageSize:
            case SocketError.NetworkDown:
            case SocketError.NetworkReset:
            case SocketError.NetworkUnreachable:
            case SocketError.NoBufferSpaceAvailable:
            case SocketError.NoData:
            case SocketError.NoRecovery:
            case SocketError.NotConnected:
            case SocketError.NotInitialized:
            case SocketError.NotSocket:
            case SocketError.OperationAborted:
            case SocketError.ProcessLimit:
            case SocketError.ProtocolOption:
            case SocketError.Shutdown:
            case SocketError.SocketError:
            case SocketError.SystemNotReady:
            case SocketError.TimedOut:
            case SocketError.TooManyOpenSockets:
            case SocketError.TryAgain:
            case SocketError.TypeNotFound:
            case SocketError.WouldBlock:
                return(true);

            case SocketError.AddressAlreadyInUse:
            case SocketError.AddressFamilyNotSupported:
            case SocketError.AddressNotAvailable:
            case SocketError.AlreadyInProgress:
            case SocketError.DestinationAddressRequired:
            case SocketError.InvalidArgument:
            case SocketError.OperationNotSupported:
            case SocketError.ProtocolFamilyNotSupported:
            case SocketError.ProtocolNotSupported:
            case SocketError.ProtocolType:
            case SocketError.SocketNotSupported:
            case SocketError.Success:
            case SocketError.VersionNotSupported:
            default:
                break;
            }

            return(false);
        }
Exemple #5
0
        protected override AsyncCompletionResult BeginWriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
                                                                Action <object> callback, object state)
        {
            ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
            bool abortWrite = true;

            try
            {
                lock (ThisLock)
                {
                    Contract.Assert(!_asyncWritePending, "Called BeginWrite twice.");
                    this.ThrowIfClosed();
                    SetWriteTimeout(timeout, false);
                    _asyncWritePending  = true;
                    _asyncWriteCallback = callback;
                    _asyncWriteState    = state;
                }

                Task writeTask = _outputStream.WriteAsync(buffer, offset, size, _sendCts.Token);
                if (immediate)
                {
                    writeTask = writeTask.ContinueWith(s_flushWriteImmedaite, this, CancellationToken.None);
                }

                if (!writeTask.IsCompleted)
                {
                    writeTask.ContinueWith(s_onSendAsyncCompleted, this, CancellationToken.None);
                    abortWrite = false;
                    return(AsyncCompletionResult.Queued);
                }

                writeTask.GetAwaiter().GetResult();
                abortWrite = false;
                return(AsyncCompletionResult.Completed);
            }
            catch (ObjectDisposedException objectDisposedException)
            {
                Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write);
                if (object.ReferenceEquals(exceptionToThrow, objectDisposedException))
                {
                    throw;
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow);
                }
            }
            catch (Exception exception)
            {
                if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
                {
                    SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              ConvertSendException(socketException, TimeSpan.MaxValue));
                }
                throw;
            }
            finally
            {
                if (abortWrite)
                {
                    this.AbortWrite();
                }
            }
        }
        protected void Reload()
        {
            Encryption.RNG.Reload();
            // some logic in configuration updated the config when saving, we need to read it again
            _config = Configuration.Load();
            StatisticsConfiguration = StatisticsStrategyConfiguration.Load();

            if (privoxyRunner == null)
            {
                privoxyRunner = new PrivoxyRunner();
            }
            if (_pacServer == null)
            {
                _pacServer = new PACServer();
                _pacServer.PACFileChanged      += pacServer_PACFileChanged;
                _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged;
            }
            _pacServer.UpdateConfiguration(_config);
            if (gfwListUpdater == null)
            {
                gfwListUpdater = new GFWListUpdater();
                gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted;
                gfwListUpdater.Error           += pacServer_PACUpdateError;
            }

            availabilityStatistics.UpdateConfiguration(this);

            if (_listener != null)
            {
                _listener.Stop();
            }
            // don't put PrivoxyRunner.Start() before pacServer.Stop()
            // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
            // though UseShellExecute is set to true now
            // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
            privoxyRunner.Stop();
            try
            {
                var strategy = GetCurrentStrategy();
                if (strategy != null)
                {
                    strategy.ReloadServers();
                }

                privoxyRunner.Start(_config);

                TCPRelay tcpRelay = new TCPRelay(this, _config);
                UDPRelay udpRelay = new UDPRelay(this);
                List <Listener.IService> services = new List <Listener.IService>();
                services.Add(tcpRelay);
                services.Add(udpRelay);
                services.Add(_pacServer);
                services.Add(new PortForwarder(privoxyRunner.RunningPort));
                _listener = new Listener(services);
                _listener.Start(_config);
            }
            catch (Exception e)
            {
                // translate Microsoft language into human language
                // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
                if (e is SocketException)
                {
                    SocketException se = (SocketException)e;
                    if (se.SocketErrorCode == SocketError.AccessDenied)
                    {
                        e = new Exception(I18N.GetString("Port already in use"), e);
                    }
                }
                Logging.LogUsefulException(e);
                ReportError(e);
            }

            if (ConfigChanged != null)
            {
                ConfigChanged(this, new EventArgs());
            }

            UpdateSystemProxy();
            Utils.ReleaseMemory(true);
        }
Exemple #7
0
        public void Ctor_Raw_NotSupported_ExpectedError(AddressFamily addressFamily, ProtocolType protocolType)
        {
            SocketException e = Assert.Throws <SocketException>(() => new Socket(addressFamily, SocketType.Raw, protocolType));

            Assert.Contains(e.SocketErrorCode, new[] { SocketError.AccessDenied, SocketError.ProtocolNotSupported });
        }
 private bool IsWouldBlockException(SocketException e)
 {
     return (e.SocketErrorCode == SocketError.WouldBlock);
 }
Exemple #9
0
        protected override bool InnerStart()
        {
            try
            {
                serverSocket = new Socket(config.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // serverSocket.SetSocketOption(SocketOptionLevel.IP, (SocketOptionName)27, 0);
                serverSocket.Bind(EndPoint);
                serverSocket.Listen(config.Backlog);

                serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

                Logger.Info("监听已启动:{0}", EndPoint.ToString());
            }
            catch (Exception e)
            {
                Logger.Error("启动监听时发生异常:{0}", e.ToString());
                return(false);
            }

            maxConntectedSemaphore = new Semaphore(config.MaxConnectionNumber, config.MaxConnectionNumber);

            Status = Dynamic.Net.Base.NetServerStatus.Started;
            StartupCompleted();

            IsRunning = true;
            while (Status == Dynamic.Net.Base.NetServerStatus.Started)
            {
                try
                {
                    maxConntectedSemaphore.WaitOne();

                    if (Status != Dynamic.Net.Base.NetServerStatus.Started)
                    {
                        maxConntectedSemaphore.Release();
                        break;
                    }

                    SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                    acceptEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(acceptEventArg_Completed);

                    if (!serverSocket.AcceptAsync(acceptEventArg))
                    {
                        aceptClient(acceptEventArg);
                    }
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (NullReferenceException)
                {
                    break;
                }
                catch (Exception e)
                {
                    SocketException se = e as SocketException;
                    Logger.Error("客户端连接异常:{0}", e.ToString());
                    maxConntectedSemaphore.Release();
                    break;
                }
            }

            IsRunning = false;

            return(true);
        }
Exemple #10
0
        public Server(List <IPEndPoint> endpoints, ServerSettings settings, ModData modData, ServerType type)
        {
            Log.AddChannel("server", "server.log", true);

            SocketException lastException   = null;
            var             checkReadServer = new List <Socket>();

            foreach (var endpoint in endpoints)
            {
                var listener = new TcpListener(endpoint);
                try
                {
                    try
                    {
                        listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 1);
                    }
                    catch (Exception ex)
                    {
                        if (ex is SocketException || ex is ArgumentException)
                        {
                            Log.Write("server", "Failed to set socket option on {0}: {1}", endpoint.ToString(), ex.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    listener.Start();
                    listeners.Add(listener);
                    checkReadServer.Add(listener.Server);
                }
                catch (SocketException ex)
                {
                    lastException = ex;
                    Log.Write("server", "Failed to listen on {0}: {1}", endpoint.ToString(), ex.Message);
                }
            }

            if (listeners.Count == 0)
            {
                throw lastException;
            }

            Type     = type;
            Settings = settings;

            Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name);

            ModData = modData;

            playerDatabase = modData.Manifest.Get <PlayerDatabase>();

            randomSeed = (int)DateTime.Now.ToBinary();

            if (type != ServerType.Local && settings.EnableGeoIP)
            {
                GeoIP.Initialize();
            }

            if (UPnP.Status == UPnPStatus.Enabled)
            {
                UPnP.ForwardPort(Settings.ListenPort, Settings.ListenPort).Wait();
            }

            foreach (var trait in modData.Manifest.ServerTraits)
            {
                serverTraits.Add(modData.ObjectCreator.CreateObject <ServerTrait>(trait));
            }

            serverTraits.TrimExcess();

            LobbyInfo = new Session
            {
                GlobalSettings =
                {
                    RandomSeed         = randomSeed,
                    Map                = settings.Map,
                    ServerName         = settings.Name,
                    EnableSingleplayer = settings.EnableSingleplayer || Type != ServerType.Dedicated,
                    EnableSyncReports  = settings.EnableSyncReports,
                    GameUid            = Guid.NewGuid().ToString(),
                    Dedicated          = Type == ServerType.Dedicated
                }
            };

            new Thread(_ =>
            {
                foreach (var t in serverTraits.WithInterface <INotifyServerStart>())
                {
                    t.ServerStarted(this);
                }

                Log.Write("server", "Initial mod: {0}", ModData.Manifest.Id);
                Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map);

                while (true)
                {
                    var checkRead = new List <Socket>();
                    if (State == ServerState.WaitingPlayers)
                    {
                        checkRead.AddRange(checkReadServer);
                    }

                    checkRead.AddRange(Conns.Select(c => c.Socket));
                    checkRead.AddRange(PreConns.Select(c => c.Socket));

                    // Block for at most 1 second in order to guarantee a minimum tick rate for ServerTraits
                    // Decrease this to 100ms to improve responsiveness if we are waiting for an authentication query
                    var localTimeout = waitingForAuthenticationCallback > 0 ? 100000 : 1000000;
                    if (checkRead.Count > 0)
                    {
                        Socket.Select(checkRead, null, null, localTimeout);
                    }

                    if (State == ServerState.ShuttingDown)
                    {
                        EndGame();
                        break;
                    }

                    foreach (var s in checkRead)
                    {
                        var serverIndex = checkReadServer.IndexOf(s);
                        if (serverIndex >= 0)
                        {
                            AcceptConnection(listeners[serverIndex]);
                            continue;
                        }

                        var preConn = PreConns.SingleOrDefault(c => c.Socket == s);
                        if (preConn != null)
                        {
                            preConn.ReadData(this);
                            continue;
                        }

                        var conn = Conns.SingleOrDefault(c => c.Socket == s);
                        conn?.ReadData(this);
                    }

                    delayedActions.PerformActions(0);

                    // PERF: Dedicated servers need to drain the action queue to remove references blocking the GC from cleaning up disposed objects.
                    if (Type == ServerType.Dedicated)
                    {
                        Game.PerformDelayedActions();
                    }

                    foreach (var t in serverTraits.WithInterface <ITick>())
                    {
                        t.Tick(this);
                    }

                    if (State == ServerState.ShuttingDown)
                    {
                        EndGame();
                        if (UPnP.Status == UPnPStatus.Enabled)
                        {
                            UPnP.RemovePortForward().Wait();
                        }
                        break;
                    }
                }

                foreach (var t in serverTraits.WithInterface <INotifyServerShutdown>())
                {
                    t.ServerShutdown(this);
                }

                PreConns.Clear();
                Conns.Clear();

                foreach (var listener in listeners)
                {
                    try { listener.Stop(); }
                    catch { }
                }
            })
            {
                IsBackground = true
            }.Start();
        }
Exemple #11
0
 public static bool wouldBlock(SocketException ex)
 {
     return(socketErrorCode(ex) == SocketError.WouldBlock);
 }
Exemple #12
0
 public static bool interrupted(SocketException ex)
 {
     return(socketErrorCode(ex) == SocketError.Interrupted);
 }
Exemple #13
0
 void HandleSocketException(SocketException exn)
 {
     error = exn.ErrorCode + ": " + exn.SocketErrorCode.ToString();
 }
Exemple #14
0
 public DSCClientErrorEventArgs(SocketException e)
 {
     this.exception = e;
 }
Exemple #15
0
 public static bool RecvTruncated(SocketException ex) => SocketErrorCode(ex) == SocketError.MessageSize;
Exemple #16
0
 public static SocketError SocketErrorCode(SocketException ex) => ex.SocketErrorCode;
        /// <summary>
        /// Listen for messages from the websocket. Once they are received they are parsed and the WebSocketMessageReceived event is raised.
        /// </summary>
        /// <returns>The task of listening for messages from the websocket.</returns>
        private async Task ListenForMessagesInternalAsync()
        {
            this.receivingMessagesTask = Task.Run(async() =>
            {
                try
                {
                    ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[MaxChunkSizeInBytes]);

                    // Once close message is sent do not try to get any more messages as WDP will abort the web socket connection.
                    while (this.websocket.State == WebSocketState.Open)
                    {
                        // Receive single message in chunks.
                        using (var ms = new MemoryStream())
                        {
                            WebSocketReceiveResult result;

                            do
                            {
                                result = await this.websocket.ReceiveAsync(buffer, CancellationToken.None);

                                if (result.MessageType == WebSocketMessageType.Close)
                                {
                                    await this.websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                                    return;
                                }

                                if (result.Count > MaxChunkSizeInBytes)
                                {
                                    throw new InvalidOperationException("Buffer not large enough");
                                }

                                ms.Write(buffer.Array, buffer.Offset, result.Count);
                            }while (!result.EndOfMessage);

                            ms.Seek(0, SeekOrigin.Begin);

                            if (result.MessageType == WebSocketMessageType.Text)
                            {
                                Stream stream = new MemoryStream();

                                await ms.CopyToAsync(stream);

                                // Ensure we return with the stream pointed at the origin.
                                stream.Position = 0;

                                this.ConvertStreamToMessage(stream);
                            }
                        }
                    }
                }
                catch (WebSocketException e)
                {
                    // If WDP aborted the web socket connection ignore the exception.
                    SocketException socketException = e.InnerException?.InnerException as SocketException;
                    if (socketException != null)
                    {
                        if (socketException.NativeErrorCode == WSAECONNRESET)
                        {
                            return;
                        }
                    }

                    throw;
                }
                finally
                {
                    this.IsListeningForMessages = false;
                }
            });

            await this.receivingMessagesTask;
        }
Exemple #18
0
		private unsafe static IPAddress InternalParse(string ipString, bool tryParse)
		{
			if (ipString == null)
			{
				if (tryParse)
				{
					return null;
				}
				throw new ArgumentNullException("ipString");
			}
			else
			{
				if (ipString.IndexOf(':') != -1)
				{
					SocketException innerException;
					if (Socket.OSSupportsIPv6)
					{
						byte[] array = new byte[16];
						SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetworkV6, 28);
						if (OSSOCK.WSAStringToAddress(ipString, AddressFamily.InterNetworkV6, IntPtr.Zero, socketAddress.m_Buffer, ref socketAddress.m_Size) == SocketError.Success)
						{
							for (int i = 0; i < 16; i++)
							{
								array[i] = socketAddress[i + 8];
							}
							long scopeid = (long)(((int)socketAddress[27] << 24) + ((int)socketAddress[26] << 16) + ((int)socketAddress[25] << 8) + (int)socketAddress[24]);
							return new IPAddress(array, scopeid);
						}
						if (tryParse)
						{
							return null;
						}
						innerException = new SocketException();
					}
					else
					{
						int start = 0;
						if (ipString[0] != '[')
						{
							ipString += ']';
						}
						else
						{
							start = 1;
						}
						int length = ipString.Length;
						fixed (char* name = ipString)
						{
							if (IPv6AddressHelper.IsValidStrict(name, start, ref length) || length != ipString.Length)
							{
								ushort[] array2 = new ushort[8];
								string text = null;
								fixed (ushort* ptr = array2)
								{
									IPv6AddressHelper.Parse(ipString, ptr, 0, ref text);
								}
								IPAddress result;
								if (text == null || text.Length == 0)
								{
									result = new IPAddress(array2, 0u);
								}
								else
								{
									text = text.Substring(1);
									uint scopeid2;
									if (!uint.TryParse(text, NumberStyles.None, null, out scopeid2))
									{
										goto IL_193;
									}
									result = new IPAddress(array2, scopeid2);
								}
								return result;
							}
						IL_193: ;
						}
						if (tryParse)
						{
							return null;
						}
						innerException = new SocketException(SocketError.InvalidArgument);
					}
					throw new FormatException("dns_bad_ip_address" + innerException);
				}
				Socket.InitializeSockets();
				int length2 = ipString.Length;
				long num;
				fixed (char* name2 = ipString)
				{
					num = IPv4AddressHelper.ParseNonCanonical(name2, 0, ref length2, true);
				}
				if (num != -1L && length2 == ipString.Length)
				{
					num = ((num & 255L) << 24 | ((num & 65280L) << 8 | ((num & 16711680L) >> 8 | (num & 1095216660480) >> 24)));
					return new IPAddress(num);
				}
				if (tryParse)
				{
					return null;
				}
				throw new FormatException("dns_bad_ip_address");
			}
		}
Exemple #19
0
        private void ProcessCommands(SmtpContext context)
        {
            bool   isRunning = true;
            String inputLine;

            while (isRunning)
            {
                try
                {
                    inputLine = context.ReadLine();

                    // TODO: remove this if gmail google is running
                    if (inputLine == null)
                    {
                        isRunning = false;
                        context.WriteLine(MESSAGE_GOODBYE);
                        context.Close();
                        break;
                    }

                    String[] inputs = inputLine.Split(' ');

                    switch (inputs[0].ToLower())
                    {
                    case "helo":
                        Helo(context, inputs);
                        break;

                    case "ehlo":
                        Ehlo(context, inputs);
                        break;

                    case "rset":
                        Rset(context);
                        break;

                    case "noop":
                        context.WriteLine(MESSAGE_OK);
                        break;

                    case "vrfy":
                        Vrfy(context, inputLine.Substring(5));
                        break;

                    case "quit":
                        isRunning = false;

                        context.WriteLine(MESSAGE_GOODBYE);
                        context.Close();
                        break;

                    case "mail":
                        // TODO: move the input line to Mail(...)
                        if (inputs[1].ToLower().StartsWith("from"))
                        {
                            Mail(context, inputLine.Substring(inputLine.IndexOf(":")));
                            break;
                        }
                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;

                    case "rcpt":
                        if (inputs[1].ToLower().StartsWith("to"))
                        {
                            Rcpt(context, inputLine.Substring(inputLine.IndexOf(":")));
                            break;
                        }
                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;

                    case "data":
                        Data(context);
                        break;

                    default:
                        context.WriteLine(MESSAGE_UNKNOWN_COMMAND);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    SocketException sx = ex as SocketException;

                    if (sx != null && sx.ErrorCode == 10060)
                    {
                        context.WriteLine(MESSAGE_GOODBYE);
                    }
                    else
                    {
                        context.WriteLine(MESSAGE_SYSTEM_ERROR);
                    }

                    isRunning = false;
                    context.Close();
                }
            }
        }
Exemple #20
0
    private void _OnError(SocketException ex)
    {
		if (OnError != null) {
			this.OnError(this, new DSCClientErrorEventArgs(ex));
		}
    }
Exemple #21
0
 public static NetMQException Create([NotNull] SocketException innerException)
 {
     return(Create(innerException.SocketErrorCode, innerException));
 }
        static internal bool ConnectToEndPoint(int port, string address, out Socket socket, out SocketException exception)
        {
            socket    = null;
            exception = null;
            short           _numberOfTries = 1;
            bool            _isConnected   = false;
            SocketException _exception     = null;

            while (_numberOfTries <= 3)
            {
                Socket _peerSocket             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                System.Threading.Thread thread = new System.Threading.Thread(() => ConnectToParticularEndpoint(ref _isConnected, ref _exception, ref _peerSocket, address, port));
                thread.Name         = "Attempt connection to " + address;
                thread.IsBackground = true;
                thread.Start();
                thread.Join(1000);

                //connected
                if (_isConnected)
                {
                    socket = _peerSocket;
                    return(true);
                }

                //Some other exception occurs
                if (_exception != null && _exception.ErrorCode != 10061 && _exception.ErrorCode != 10065 && _exception.ErrorCode != 10060 && _exception.ErrorCode != 10064)
                {
                    exception = _exception;
                    return(false);
                }
            }
            return(false);
        }
Exemple #23
0
        public void Socket_CreateUnixDomainSocket_Throws_OnWindows()
        {
            SocketException e = Assert.Throws <SocketException>(() => new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified));

            Assert.Equal(SocketError.AddressFamilyNotSupported, e.SocketErrorCode);
        }
        protected void Reload()
        {
            if (_port_map_listener != null)
            {
                foreach (Listener l in _port_map_listener)
                {
                    l.Stop();
                }
                _port_map_listener = null;
            }
            // some logic in configuration updated the config when saving, we need to read it again
            _config = MergeGetConfiguration(_config);
            _config.FlushPortMapCache();
            ReloadIPRange();

#if !_CONSOLE
            if (polipoRunner == null)
            {
                polipoRunner = new HttpProxyRunner();
            }
#endif
            if (_pacServer == null)
            {
                _pacServer = new PACServer();
                _pacServer.PACFileChanged += pacServer_PACFileChanged;
            }
            _pacServer.UpdateConfiguration(_config);
            if (gfwListUpdater == null)
            {
                gfwListUpdater = new GFWListUpdater();
                gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted;
                gfwListUpdater.Error           += pacServer_PACUpdateError;
            }

            // don't put polipoRunner.Start() before pacServer.Stop()
            // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
            // though UseShellExecute is set to true now
            // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
            bool _firstRun = firstRun;
            for (int i = 1; i <= 5; ++i)
            {
                _firstRun = false;
                try
                {
                    if (_listener != null && !_listener.isConfigChange(_config))
                    {
                        Local local = new Local(_config, _transfer, _rangeSet);
                        _listener.GetServices()[0] = local;
#if !_CONSOLE
                        if (polipoRunner.HasExited())
                        {
                            polipoRunner.Stop();
                            polipoRunner.Start(_config);

                            _listener.GetServices()[3] = new HttpPortForwarder(polipoRunner.RunningPort, _config);
                        }
#endif
                    }
                    else
                    {
                        if (_listener != null)
                        {
                            _listener.Stop();
                            _listener = null;
                        }

#if !_CONSOLE
                        polipoRunner.Stop();
                        polipoRunner.Start(_config);
#endif

                        Local local = new Local(_config, _transfer, _rangeSet);
                        List <Listener.Service> services = new List <Listener.Service>();
                        services.Add(local);
                        services.Add(_pacServer);
                        services.Add(new APIServer(this, _config));
#if !_CONSOLE
                        services.Add(new HttpPortForwarder(polipoRunner.RunningPort, _config));
#endif
                        _listener = new Listener(services);
                        _listener.Start(_config, 0);
                    }
                    break;
                }
                catch (Exception e)
                {
                    // translate Microsoft language into human language
                    // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
                    if (e is SocketException)
                    {
                        SocketException se = (SocketException)e;
                        if (se.SocketErrorCode == SocketError.AccessDenied)
                        {
                            e = new Exception(I18N.GetString("Port already in use") + string.Format(" {0}", _config.localPort), e);
                        }
                    }
                    Logging.LogUsefulException(e);
                    if (!_firstRun)
                    {
                        ReportError(e);
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000 * i * i);
                    }
                    if (_listener != null)
                    {
                        _listener.Stop();
                        _listener = null;
                    }
                }
            }

            _port_map_listener = new List <Listener>();
            foreach (KeyValuePair <int, PortMapConfigCache> pair in _config.GetPortMapCache())
            {
                try
                {
                    Local local = new Local(_config, _transfer, _rangeSet);
                    List <Listener.Service> services = new List <Listener.Service>();
                    services.Add(local);
                    Listener listener = new Listener(services);
                    listener.Start(_config, pair.Key);
                    _port_map_listener.Add(listener);
                }
                catch (Exception e)
                {
                    // translate Microsoft language into human language
                    // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
                    if (e is SocketException)
                    {
                        SocketException se = (SocketException)e;
                        if (se.SocketErrorCode == SocketError.AccessDenied)
                        {
                            e = new Exception(I18N.GetString("Port already in use") + string.Format(" {0}", pair.Key), e);
                        }
                    }
                    Logging.LogUsefulException(e);
                    ReportError(e);
                }
            }

            ConfigChanged?.Invoke(this, new EventArgs());

            UpdateSystemProxy();
            Util.Utils.ReleaseMemory();
        }
Exemple #25
0
        public string Call()
        {
            String message      = "";
            String errorMessage = "";

            var handler = new HttpClientHandler();

            handler.AllowAutoRedirect = false;
            String hostName = url;

            try
            {
                Uri uri = new Uri(url);
                hostName = uri.Host;
                HttpClient client = new HttpClient(handler);
                client.BaseAddress = uri;
                HttpResponseMessage response = client.GetAsync(uri.AbsolutePath).Result;                  // Blocking call!
                this.response = response.Content.ReadAsStringAsync().Result;
                if (response.IsSuccessStatusCode)
                {
                    message = String.Format("Success: {0} bytes (HTTP {1})", response.Content.ReadAsStringAsync().Result.Length, response.StatusCode);
                }
                else
                {
                    errorMessage = String.Format("HTTP Response: {0} ({1})", response.StatusCode, (int)response.StatusCode);
                }
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) =>
                {
                    do
                    {
                        if (ex is WebException)
                        {
                            WebException wex = ex as WebException;
                            switch (wex.Status)
                            {
                            // The SSL/TLS connection could not be established.
                            case WebExceptionStatus.SecureChannelFailure:
                                List <string> protocols = new List <string>();
                                if ((ServicePointManager.SecurityProtocol & SecurityProtocolType.Ssl3) != 0)
                                {
                                    protocols.Add("SSL 3");
                                }
                                if ((ServicePointManager.SecurityProtocol & SecurityProtocolType.Tls) != 0)
                                {
                                    protocols.Add("TLS 1.0");
                                }
                                if ((ServicePointManager.SecurityProtocol & SecurityProtocolType.Tls11) != 0)
                                {
                                    protocols.Add("TLS 1.1");
                                }
                                if ((ServicePointManager.SecurityProtocol & SecurityProtocolType.Tls12) != 0)
                                {
                                    protocols.Add("TLS 1.2");
                                }
                                errorMessage = String.Format("Could not establish SSL/TLS connection (supported protocols: {0})", String.Join(", ", protocols));
                                break;

                            case WebExceptionStatus.TrustFailure:
                                errorMessage = String.Format("SSL Certificate for '{0}' invalid", hostName);
                                break;

                            case WebExceptionStatus.NameResolutionFailure:
                                errorMessage = String.Format("Invalid domain name '{0}'", hostName);
                                break;

                            default:
                                errorMessage = wex.Status.ToString();
                                break;
                            }
                        }
                        else if (ex is SocketException)
                        {
                            SocketException sex = ex as SocketException;
                            errorMessage        = sex.Message;
                        }
                        else if (ex is IOException)
                        {
                            IOException ioex = ex as IOException;
                            errorMessage     = ioex.Message;
                        }

                        ex = ex.InnerException;
                    } while (ex != null);
                    return(true);
                });
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            if (errorMessage != "")
            {
                throw new Exception(errorMessage);
            }
            return(message);
        }
        internal override void HandleConnectionForciblyClosed(NetConnection connection, SocketException sex)
        {
            if (m_serverConnection == null)
            {
                return;
            }

            if (m_serverConnection.Status == NetConnectionStatus.Connecting)
            {
                // failed to connect; server is not listening
                m_serverConnection.Disconnect("Failed to connect; server is not listening", 0, false, true);
                return;
            }

            m_connectRequested = false;
            m_serverConnection.Disconnect("Connection forcibly closed by server", 0, false, true);
            return;
        }
Exemple #27
0
        private void ConnectImpl(string host, int port, int timeout, Action <NetHandler, Exception> callback)
        {
            if (!running)
            {
                throw new ObjectDisposedException(ToString());
            }
            Stopwatch clock = new Stopwatch();

            clock.Start();
            Dns.BeginGetHostAddresses(host, delegate(IAsyncResult ar)
            {
                clock.Stop();
                timeout -= (int)clock.ElapsedMilliseconds;
                try
                {
                    IPAddress[] iplist = Dns.EndGetHostAddresses(ar);
                    if (timeout > 0)
                    {
                        AddressFamily family = AddressFamily.InterNetwork;
                        for (int i = 0; i < iplist.Length; ++i)
                        {
                            if (iplist[i].AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                family = AddressFamily.InterNetworkV6;
                                break;
                            }
                        }
                        NetHandlerImpl socket = new NetHandlerImpl(family, this);
                        Timer timer           = new Timer(delegate(object state)
                        {
                            socket.Socket.Close();
                        }, null, Timeout.Infinite, Timeout.Infinite);
                        socket.Socket.BeginConnect(iplist, port, delegate(IAsyncResult result)
                        {
                            try
                            {
                                timer.Dispose();
                            }
                            catch
                            {
                            }
                            Exception exception = null;
                            try
                            {
                                socket.Socket.EndConnect(result);
                                socket.Socket.Blocking = false;
                                socket.OnConnected();
                            }
                            catch (ObjectDisposedException)
                            {
                                exception = new SocketException((int)SocketError.TimedOut);
                            }
                            catch (Exception e)
                            {
                                exception = e;
                                socket.Socket.Close();
                            }
                            callback(exception == null ? socket : null, exception);
                        }, null);
                        timer.Change(timeout, Timeout.Infinite);
                    }
                    else
                    {
                        callback(null, new SocketException((int)SocketError.TimedOut));
                    }
                }
                catch (Exception e)
                {
                    callback(null, e);
                }
            }, null);
        }
        public static bool LogSocketException(string remarks, string server, Exception e)
        {
            UpdateLogFile();
            // just log useful exceptions, not all of them
            if (e is ObfsException)
            {
                ObfsException oe = (ObfsException)e;
                Error("Proxy server [" + remarks + "(" + server + ")] "
                      + oe.Message);
                return(true);
            }
            else if (e is NullReferenceException)
            {
                return(true);
            }
            else if (e is ObjectDisposedException)
            {
                // ignore
                return(true);
            }
            else if (e is SocketException)
            {
                SocketException se = (SocketException)e;
                if ((uint)se.SocketErrorCode == 0x80004005)
                {
                    // already closed
                    return(true);
                }
                else if (se.ErrorCode == 11004)
                {
                    Logging.Log(LogLevel.Warn, "Proxy server [" + remarks + "(" + server + ")] "
                                + "DNS lookup failed");
                    return(true);
                }
                else if (se.SocketErrorCode == SocketError.HostNotFound)
                {
                    Logging.Log(LogLevel.Warn, "Proxy server [" + remarks + "(" + server + ")] "
                                + "Host not found");
                    return(true);
                }
                else if (se.SocketErrorCode == SocketError.ConnectionRefused)
                {
                    Logging.Log(LogLevel.Warn, "Proxy server [" + remarks + "(" + server + ")] "
                                + "connection refused");
                    return(true);
                }
                else if (se.SocketErrorCode == SocketError.NetworkUnreachable)
                {
                    Logging.Log(LogLevel.Warn, "Proxy server [" + remarks + "(" + server + ")] "
                                + "network unreachable");
                    return(true);
                }
                else if (se.SocketErrorCode == SocketError.TimedOut)
                {
                    //Logging.Log(LogLevel.Warn, "Proxy server [" + remarks + "(" + server + ")] "
                    //    + "connection timeout");
                    return(true);
                }
                else if (se.SocketErrorCode == SocketError.Shutdown)
                {
                    return(true);
                }
                else
                {
                    Logging.Log(LogLevel.Info, "Proxy server [" + remarks + "(" + server + ")] "
                                + Convert.ToString(se.SocketErrorCode) + ":" + se.Message);

                    Debug(ToString(new StackTrace().GetFrames()));

                    return(true);
                }
            }
            return(false);
        }
Exemple #29
0
 /// <summary>
 /// Internal for re-use by CommandAvailabilityPublisher
 /// </summary>
 internal static void ReportSocketExceptionAndExit(SocketException exception, WebSocketServer server)
 {
     ErrorReport.NotifyUserOfProblem(exception, SocketExceptionMsg, Environment.NewLine, server.Port);
     Application.Exit();
 }
Exemple #30
0
 public static bool ConnectionRefused(SocketException ex) => SocketErrorCode(ex) == SocketError.ConnectionRefused;
Exemple #31
0
 /// <summary>
 /// Event triggered if a network error occurs while communicating with
 /// the LoginServer.
 /// </summary>
 /// <param name="Exception"></param>
 private void m_LoginClient_OnNetworkError(SocketException Exc)
 {
     MessageBox.Show(Exc.ToString());
     Application.Exit();
 }
Exemple #32
0
 public static bool OperationAborted(SocketException ex) => SocketErrorCode(ex) == SocketError.OperationAborted;
Exemple #33
0
 internal ServerInfoEventArgs(ServerEndPoint serverEndPoint, SocketException error)
     : base(serverEndPoint)
 {
     SocketError = error.SocketErrorCode;
     Exception   = error;
 }
 private bool IsTimeoutException(SocketException e)
 {
     return (e.SocketErrorCode == SocketError.TimedOut);
 }
Exemple #35
0
 private void HandleSocketException(SocketException e)
 {
     Logger.WriteLine("Socket Exception: {0}, Disconnecting", TraceEventType.Error, e);
     this.HandleDisconnect();
     //this.OnUnknownError(new ErrorEventArgs(e));
 }
	public static void Connect()
	{

		//Starts the C# server to send string data to
		Process.Start("Server");
		//Find own local IP address
		IPHostEntry host;
		string localIP = "";
		host = Dns.GetHostEntry(Dns.GetHostName());
		foreach (IPAddress ip in host.AddressList)
		{
			if (ip.AddressFamily == AddressFamily.InterNetwork)
			{
				localIP = ip.ToString();
				break;
			}
		}
		byte[] data = new byte[1024];
		string input, stringData;
		IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 137);
		
		Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		
		
		try
		{
			
			server.Connect(ipep);
		}
		catch (SocketException e)
		{
			UnityEngine.Debug.Log("Unable to connect to the server.");
			UnityEngine.Debug.Log(e.ToString());
			
			return;
		}
		
		int recv = server.Receive(data);
		stringData = Encoding.ASCII.GetString(data, 0, recv);
		UnityEngine.Debug.Log(stringData);
		int i = 0;
		while (true)
		{ 
			 i = i + 1;
			input = "Client Side: " + i;
			server.Send(Encoding.ASCII.GetBytes(input));
			data = new byte[1024];
			try
			{
				recv = server.Receive(data);
				
				stringData = Encoding.ASCII.GetString(data, 0, recv);
				UnityEngine.Debug.Log(ipep.Address + ": " + stringData);
				if (i == 5)
				{
					
					string msg = "Closing connection";
					server.Send(Encoding.ASCII.GetBytes(msg));
					break;
				}

			}
			catch
			{
				UnityEngine.Debug.Log("Server disconnected.");
				break;
			}
			
		}

		SocketException ee = new SocketException();
		try
		{


			server.Shutdown(SocketShutdown.Both);
			
			UnityEngine.Debug.Log (ee);

			UnityEngine.Debug.Log ("Server.close() worked??");
		}
		catch{
			UnityEngine.Debug.Log("Disconnecting from server");
		      }
		finally{
			server.Close();
				}



		}
 public SocketClosedByAccidentEventArgs(SocketException ex)
 {
     Exception = ex;
 }
Exemple #38
0
 private void exception(Ice.Current current)
 {
     if(current.operation.Equals("ice_ids"))
     {
         throw new Test.TestIntfUserException();
     }
     else if(current.operation.Equals("requestFailedException"))
     {
         throw new ObjectNotExistException();
     }
     else if(current.operation.Equals("unknownUserException"))
     {
         UnknownUserException ex = new UnknownUserException();
         ex.unknown = "reason";
         throw ex;
     }
     else if(current.operation.Equals("unknownLocalException"))
     {
         UnknownLocalException ex = new UnknownLocalException();
         ex.unknown = "reason";
         throw ex;
     }
     else if(current.operation.Equals("unknownException"))
     {
         UnknownException ex = new UnknownException();
         ex.unknown = "reason";
         throw ex;
     }
     else if(current.operation.Equals("userException"))
     {
         throw new TestIntfUserException();
     }
     else if(current.operation.Equals("localException"))
     {
         SocketException ex = new SocketException();
         ex.error = 0;
         throw ex;
     }
     else if(current.operation.Equals("csException"))
     {
         throw new System.Exception("message");
     }
     else if(current.operation.Equals("unknownExceptionWithServantException"))
     {
         throw new UnknownException("reason");
     }
     else if(current.operation.Equals("impossibleException"))
     {
         throw new Test.TestIntfUserException(); // Yes, it really is meant to be TestIntfException.
     }
     else if(current.operation.Equals("intfUserException"))
     {
         throw new Test.TestImpossibleException(); // Yes, it really is meant to be TestImpossibleException.
     }
     else if(current.operation.Equals("asyncResponse"))
     {
         throw new Test.TestImpossibleException();
     }
     else if(current.operation.Equals("asyncException"))
     {
         throw new Test.TestImpossibleException();
     }
 }
        public void Exception_HostNotFound_Success()
        {
            var ex = new  SocketException((int)SocketError.HostNotFound);

            Assert.Equal(-1, ex.Message.IndexOf("Device"));
        }
 public SocketOperationResult(SocketException exception)
 {
     SocketError      = exception;
     BytesTransferred = 0;
 }
Exemple #41
0
 /// <summary>
 /// Gets if the specified exception can safely be ignored.
 /// </summary>
 private static bool _CanIgnore(SocketException Exception)
 {
     return Exception.SocketErrorCode == SocketError.ConnectionReset;
 }