Exemple #1
0
        /// <summary>
        /// Queries the SOCKS5 proxy for its desired authentication mechanism
        /// </summary>
        private Socks5AuthType GetSocks5AuthMethod()
        {
            Socks5AuthType retval = Socks5AuthType.AuthMethodRejected;
            int            reqlength = 4, sent = 0;

            byte[] request = new byte[reqlength];
            request[0] = 0x05;
            request[1] = 0x02;
            request[2] = 0x00;
            request[3] = 0x02;

            try
            {
                while (sent < reqlength)
                {
                    sent += socket.Write(request, sent, reqlength - sent);
                }

                int    replength = 2, received = 0;
                byte[] reply = new byte[replength];
                while (received < replength)
                {
                    received += socket.Read(reply, received, replength - received);
                }

                retval = (Socks5AuthType)reply[1];
            }
            catch (Exception sockex)
            {
                Logging.WriteString("Caught exception in GetSocks5AuthMethod: {0}", sockex);
            }
            return(retval);
        }
Exemple #2
0
        private void OnHTTPResponse(IAsyncResult result)
        {
            AsyncHttpResponse state = (AsyncHttpResponse)result.AsyncState;
            var success             = false;

            try
            {
                state.Request.EndGetResponse(result);
                success = true;
            }
            catch (WebException)
            {
                if (state.AssociatedAccount.Protocol == "https")
                {
                    // try to fetch certificate
                    try
                    {
                        var tls = new TLSHandshake();
                        tls.SetServerNameExtension(state.AssociatedAccount.Hostname);
                        var socket = new StreamSocket();
                        socket.Connect(state.AssociatedAccount.Hostname, state.AssociatedAccount.GetPort(true));
                        socket.Write(tls.CreateClientHello());

                        DateTime startTime = DateTime.Now;
                        while (true)
                        {
                            var data = socket.Read();
                            if (data.Length > 0)
                            {
                                var cert = tls.FindPacket(data, TLSHandshake.TLS_HANDSHAKE_CERTIFICATE);
                                if (cert.Length > 0)
                                {
                                    var details = tls.GetCertificateDetails(cert);
                                    if (details.Count > 0)
                                    {
                                        var certDetails = details[0];
                                        if (certDetails.ContainsKey("CN"))
                                        {
                                            Dispatcher.BeginInvoke(() =>
                                            {
                                                MessageBox.Show("EditAccountPage_Connection_Rejected".Translate(state.AssociatedAccount.Hostname, certDetails["CN"], certDetails["ValidAfter"], certDetails["ValidTo"]), "EditAccountPage_Connection_Rejected_Caption".Translate(), MessageBoxButton.OK);
                                                _overlay.Hide();
                                            });
                                            return;
                                        }
                                    }
                                    break;
                                }
                            }

                            if (DateTime.Now.Subtract(startTime).TotalSeconds > 5)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // Host not reachable, no SSL host or TLS version not supported
                    }
                }
            }
            catch (Exception)
            {
                // HTTPWebRequest has failed
            }

            if (success)
            {
                // Testing DAV
                //TODO: Add your additional connection test statement here
                // To complete the test all fragments must have been fired.
                EventCollector collector = new EventCollector()
                {
                    Complete = () =>
                    {
                        OnConnectTestComplete(success, state.AssociatedAccount);
                    }
                };
                collector.WaitFor(state.AssociatedAccount.WebDAVPath);
                collector.WaitFor(state.AssociatedAccount.CalDAVPath);

                // define paths to test
                Queue <string> pathsToTest = new Queue <string>();
                pathsToTest.Enqueue(state.AssociatedAccount.WebDAVPath);
                pathsToTest.Enqueue(state.AssociatedAccount.CalDAVPath);

                // create master instance
                WebDAV davTest = new WebDAV(state.AssociatedAccount.GetUri(), state.AssociatedAccount.GetCredentials());

                // call tests
                while (pathsToTest.Count > 0)
                {
                    var path = pathsToTest.Dequeue();
                    davTest.StartRequest(DAVRequestHeader.CreateListing(path), path, (requestResult, userObj) =>
                    {
                        if (requestResult.Status != ServerStatus.MultiStatus)
                        {
                            // all other states are fail states
                            success = false;
                            Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("EditAccountPage_CheckingConnection_DAVTestFailed".Translate(userObj, requestResult.StatusText), "Error_Caption".Translate(), MessageBoxButton.OK);
                            });
                        }
                        collector.Raise(userObj);
                    });
                }
            }
            else
            {
                OnConnectTestComplete(success, state.AssociatedAccount);
            }
        }
        private void OnHTTPResponse(IAsyncResult result)
        {
            AsyncHttpResponse state = (AsyncHttpResponse)result.AsyncState;
            var success             = false;

            try
            {
                state.Request.EndGetResponse(result);
                success = true;
            }
            catch (WebException)
            {
                if (state.AssociatedAccount.Protocol == "https")
                {
                    // try to fetch certificate
                    try
                    {
                        var tls = new TLSHandshake();
                        tls.SetServerNameExtension(state.AssociatedAccount.Hostname);
                        var socket = new StreamSocket();
                        socket.Connect(state.AssociatedAccount.Hostname, TLSHandshake.TLS_HTTP_PORT);
                        socket.Write(tls.CreateClientHello());

                        DateTime startTime = DateTime.Now;
                        while (true)
                        {
                            var data = socket.Read();
                            if (data.Length > 0)
                            {
                                var cert = tls.FindPacket(data, TLSHandshake.TLS_HANDSHAKE_CERTIFICATE);
                                if (cert.Length > 0)
                                {
                                    var details = tls.GetCertificateDetails(cert);
                                    if (details.Count > 0)
                                    {
                                        var certDetails = details[0];
                                        if (certDetails.ContainsKey("CN"))
                                        {
                                            Dispatcher.BeginInvoke(() =>
                                            {
                                                MessageBox.Show("EditAccountPage_Connection_Rejected".Translate(state.AssociatedAccount.Hostname, certDetails["CN"], certDetails["ValidAfter"], certDetails["ValidTo"]), "EditAccountPage_Connection_Rejected_Caption".Translate(), MessageBoxButton.OK);
                                                overlayFadeOut.Begin();
                                            });
                                            return;
                                        }
                                    }
                                    break;
                                }
                            }

                            if (DateTime.Now.Subtract(startTime).TotalSeconds > 5)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // Host not reachable, no SSL host or TLS version not supported
                    }
                }
            }
            catch (Exception)
            {
                // HTTPWebRequest has failed
            }

            Dispatcher.BeginInvoke(() =>
            {
                if (success)
                {
                    overlayFadeOut.Begin();
                    StoreAccount(state.AssociatedAccount);
                }
                else
                {
                    overlayFadeOut.Begin();
                    OnConnectFailed(state.AssociatedAccount);
                }
            });
        }
Exemple #4
0
        /// <summary>
        /// Processes the asynchronous receipt of a FLAP
        /// </summary>
        /// <param name="res">The <see cref="IAsyncResult"/> of a BeginReceive call</param>
        private void ProcessFLAP(IAsyncResult res)
        {
            int bytesreceived = 0;
            int receiveindex  = 0;

            byte[] flapbuffer = null;

            try
            {
                lock (socket)
                {
                    bytesreceived = socket.EndRead(res);
                    if (bytesreceived == 0)
                    {
                        throw new Exception("Socket receive returned 0 bytes read");
                    }

                    flapbuffer = (byte[])res.AsyncState;

                    receiveindex = bytesreceived;
                    while (receiveindex < flapbuffer.Length)
                    {
                        bytesreceived = socket.Read(flapbuffer, receiveindex, flapbuffer.Length - receiveindex);
                        if (bytesreceived == 0)
                        {
                            throw new Exception("Socket receive returned 0 bytes read");
                        }
                        receiveindex += bytesreceived;
                    }
                }
            }
            catch (Exception ex)
            {
                if (!isDisconnecting)
                {
                    Logging.WriteString("Receive error in ProcessFLAP: {0}, connection {1}", ex.Message, ID);
                    DisconnectFromServer(true);
                }
                return;
            }

            if (flapbuffer[0] == 0xFF)
            {
                int badcount = 0;
                for (badcount = 0; badcount < flapbuffer.Length && flapbuffer[badcount] == 0xFF; badcount++)
                {
                    ;
                }

                // SOMEHOW there are two bytes of 0xFF occuring when requesting
                // SNAC family 0x10 and receiving SNAC(01,03).  So that has to stop
                for (int i = badcount; i < flapbuffer.Length; i++)
                {
                    flapbuffer[i - badcount] = flapbuffer[i];
                }

                socket.Read(flapbuffer, flapbuffer.Length - badcount, badcount);
            }

            // Get the FLAP header out of the async result
            FLAPHeader flap   = GetFLAPHeader(flapbuffer);
            ByteStream stream = ReadPacket(flap.DataSize);

            if (stream == null)
            {
                return;
            }

            // The full packet is here, so we can chuck it out for processing
            DataPacket dp;

            switch (flap.Channel)
            {
            case 0x01:     // New connection negotiation
                // This will not occur, FLAP 0x01 is handled in ConnectToServer
                break;

            case 0x02:     //  SNAC data
                if (stream.GetByteCount() < 10)
                {
                    break;     // Don't return, don't disconnect, just keep on keeping on
                }

                dp                  = stream.CreateDataPacket();
                dp.FLAP             = flap;
                dp.ParentConnection = this;
                dp.ParentSession    = parent;
                Processor.Enqueue(dp);
                break;

            case 0x03:     // FLAP error
                // Session error:  FLAP error, bailing out
                Logging.WriteString("Received error FLAP");
                DisconnectFromServer(true);
                return;

            case 0x04:     // Close connection negotiation
                //KSD-SYSTEMS - added at 27.11.2009
                if (stream.GetByteCount() > 10)
                {
                    dp = stream.CreateDataPacket();
                    if (((SNACFamily)dp.SNAC.FamilyServiceID) == SNACFamily.PrivacyManagementService)
                    {
                        PrivacyManagementService sub = (PrivacyManagementService)dp.SNAC.FamilySubtypeID;
                        if (sub == PrivacyManagementService.ServiceParametersRequest)
                        {
                            parent.OnError(ServerErrorCode.ExternalClientRequest, dp);
                        }
                    }
                }

                Logging.WriteString("Received close connection FLAP");
                DisconnectFromServer(false);
                return;

            case 0x05:     // Keepalive packet
                Logging.WriteString("Received keepalive FLAP");
                SendKeepalive(null);
                break;

            default:
                break;
            }

            // Shine on, you crazy connection
            keepAliveTimer.Change(60000, Timeout.Infinite);
            ReadHeader();
        }