Exemple #1
0
 public Session(ConnectionDirection direction, PeerInfo peer)
 {
     Direction = direction;
     Peer      = peer;
     State     = SessionState.New;
     Id        = Guid.NewGuid();
 }
Exemple #2
0
 public void Reset()
 {
     color     = Color.white;
     direction = ConnectionDirection.North;
     position  = 0f;
     weight    = 50f;
 }
Exemple #3
0
        private byte[] GetMACKey(ConnectionDirection direction)
        {
            switch (_endConfig.End)
            {
            case ConnectionEnd.Client:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_blockCipherConfig.ServerMACKey ?? throw new InvalidOperationException("Server MAC key is not initialized"));;

                case ConnectionDirection.Write:
                    return(_blockCipherConfig.ClientMACKey ?? throw new InvalidOperationException("Client MAC key is not initialized"));;

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            case ConnectionEnd.Server:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_blockCipherConfig.ClientMACKey ?? throw new InvalidOperationException("Client MAC key is not initialized"));;

                case ConnectionDirection.Write:
                    return(_blockCipherConfig.ServerMACKey ?? throw new InvalidOperationException("Server MAC key is not initialized"));;

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(_endConfig.End), _endConfig.End, null);
            }
        }
Exemple #4
0
 /// <summary>
 /// Method to change the Connection Direction
 /// </summary>
 /// <param name="node"></param>
 /// <param name="direction"></param>
 private void ConnectionDirectionChange(NodeViewModel node, ConnectionDirection direction)
 {
     foreach (IPort nodeport in (node.Ports as ObservableCollection <IPort>))
     {
         if (direction == ConnectionDirection.Auto)
         {
             nodeport.Constraints         = nodeport.Constraints | PortConstraints.ConnectionDirection;
             nodeport.ConnectionDirection = ConnectionDirection.Auto;
         }
         else if (direction == ConnectionDirection.Left)
         {
             nodeport.Constraints         = nodeport.Constraints | PortConstraints.ConnectionDirection;
             nodeport.ConnectionDirection = ConnectionDirection.Left;
         }
         else if (direction == ConnectionDirection.Top)
         {
             nodeport.Constraints         = nodeport.Constraints | PortConstraints.ConnectionDirection;
             nodeport.ConnectionDirection = ConnectionDirection.Top;
         }
         else if (direction == ConnectionDirection.Right)
         {
             nodeport.Constraints         = nodeport.Constraints | PortConstraints.ConnectionDirection;
             nodeport.ConnectionDirection = ConnectionDirection.Right;
         }
         else if (direction == ConnectionDirection.Bottom)
         {
             nodeport.Constraints         = nodeport.Constraints | PortConstraints.ConnectionDirection;
             nodeport.ConnectionDirection = ConnectionDirection.Bottom;
         }
     }
 }
 public static IStrokeConnection CheckForConnection(Vector3 CenterPosition, float Distance, StrokeCategory Category, Vector3 WorldDirection, ConnectionDirection WorldConnectionDirection, LayerMask Mask, bool ShouldDebug = false, float DebugTime = 1f)
 {
     if (ShouldDebug)
     {
         Debug.DrawRay(CenterPosition, WorldDirection * Distance, Color.red, DebugTime);
     }                                       // check if should debug
     RaycastHit[] CastResults = Physics.RaycastAll(CenterPosition, WorldDirection, Distance, Mask);
     if (CastResults.Length > 0)             // check for object
     {
         for (int i = 0; i < CastResults.Length; i++)
         {
             IStrokeConnection Piece = CastResults[i].collider.transform.GetComponent <IStrokeConnection>(); // get stroke piece component of object
             if (Piece != null && Piece.StrokeCategory == Category)                                          // if is a stroke piece and of the same category
             // Check if has connection
             {
                 ConnectionDirection   InverseWorldDirection = VectorToDirection(-WorldDirection); // calculate inverse direction
                 ConnectionDirection[] WorldPieceConnections = Piece.WorldConnectionDirections;    // get world connection directions of piece
                 for (int x = 0; x < WorldPieceConnections.Length; x++)                            // check for connection match
                 {
                     if (WorldPieceConnections [x] == InverseWorldDirection)                       // found a matching connection
                     {
                         return(Piece);                                                            // return piece
                     }
                 }
             }
         }
     }
     return(null);
 }
Exemple #6
0
 /// <summary>
 ///  Returns true if the directions provided are opposite directions
 /// </summary>
 public static bool IsOppositeDirection(ConnectionDirection dir1, ConnectionDirection dir2)
 {
     return(dir1 == ConnectionDirection.North && dir2 == ConnectionDirection.South ||
            dir1 == ConnectionDirection.South && dir2 == ConnectionDirection.North ||
            dir1 == ConnectionDirection.East && dir2 == ConnectionDirection.West ||
            dir1 == ConnectionDirection.West && dir2 == ConnectionDirection.East);
 }
        public void MakeConnection(NeighbourTrackerNode a, NeighbourTrackerNode b, ConnectionDirection dir)
        {
            if (a == null || b == null)
            {
                return;
            }

            if (!connections.ContainsKey(a))
            {
                connections.Add(a, new List <Connection>());
            }

            connections[a].Add(new Connection(dir, b));

            if (!connections.ContainsKey(b))
            {
                connections.Add(b, new List <Connection>());
            }

            connections[b].Add(new Connection(GetOpposite(dir), a));

            if (!nodeDictionary.ContainsKey(a.keyPoint))
            {
                nodeDictionary.Add(a.keyPoint, a);
            }
            if (!nodeDictionary.ContainsKey(b.keyPoint))
            {
                nodeDictionary.Add(b.keyPoint, b);
            }
        }
Exemple #8
0
 public PortAssigned(NodeIdentifier nodeId, PortDirection port, LinkIdentifier linkId, ConnectionDirection direction)
 {
     NodeId    = nodeId ?? throw new System.ArgumentNullException(nameof(nodeId));
     Port      = port;
     LinkId    = linkId ?? throw new System.ArgumentNullException(nameof(linkId));
     Direction = direction;
 }
Exemple #9
0
 public MapConnection(PokeEngine engine, Map parent, ConnectionDirection direction, int id, int offset)
     : base(engine, id)
 {
     this.direction = direction;
     this.parent    = parent;
     this.offset    = offset;
 }
        private byte[] GetImplicitNonce(ConnectionDirection direction)
        {
            switch (_endConfig.End)
            {
            case ConnectionEnd.Client:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_aeadConfig.ServerIV ?? throw new InvalidOperationException("Server AEAD IV is not initialized"));

                case ConnectionDirection.Write:
                    return(_aeadConfig.ClientIV ?? throw new InvalidOperationException("Client AEAD IV is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            case ConnectionEnd.Server:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_aeadConfig.ClientIV ?? throw new InvalidOperationException("Client AEAD IV is not initialized"));

                case ConnectionDirection.Write:
                    return(_aeadConfig.ServerIV ?? throw new InvalidOperationException("Server AEAD IV is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(_endConfig.End), _endConfig.End, null);
            }
        }
Exemple #11
0
        private byte[] GetKey(ConnectionEnd end, ConnectionDirection direction)
        {
            switch (end)
            {
            case ConnectionEnd.Client:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_keyConfig.Server ?? throw new InvalidOperationException("Server key is not initialized"));

                case ConnectionDirection.Write:
                    return(_keyConfig.Client ?? throw new InvalidOperationException("Client key is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            case ConnectionEnd.Server:
                switch (direction)
                {
                case ConnectionDirection.Read:
                    return(_keyConfig.Client ?? throw new InvalidOperationException("Client key is not initialized"));

                case ConnectionDirection.Write:
                    return(_keyConfig.Server ?? throw new InvalidOperationException("Server key is not initialized"));

                default:
                    throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(end), end, null);
            }
        }
Exemple #12
0
        private void AddConnectionWith(PointerDCN <T> typedNode, ConnectionDirection direction)
        {
            Helpers <T> .Verify_AddConnectionWith_ConditionsAreSatisfied(typedNode, this);

            this.InternalAddNodeConnectionRequest(typedNode, direction);
            typedNode.InternalAddNodeConnectionRequest(this, direction.Invert());
        }
Exemple #13
0
        private ICipherParameters GetParameters(ConnectionDirection direction)
        {
            var end = _endConfig.End;
            var cipherParameterFactory = _cipherSuitesProvider.ResolveCipherParameterFactory(_cipherSuiteConfig.CipherSuite);

            return(cipherParameterFactory.Create(end, direction));
        }
        public static Vector3 DirectionToVector(ConnectionDirection Dir)
        {
            switch (Dir)
            {
            case ConnectionDirection.Back:
                return(Vector3.back);

                break;

            case ConnectionDirection.Right:
                return(Vector3.right);

                break;

            case ConnectionDirection.Front:
                return(Vector3.forward);

                break;

            case ConnectionDirection.Left:
                return(Vector3.left);

                break;

            default:
                return(Vector3.forward);

                break;
            }
        }
Exemple #15
0
 public ConnectionStream(String userName, String hashKey, ConnectionDirection direction, int delayBetweenAPIRequests)
 {
     Connections             = new List <ConnectionEntry>();
     UserName                = userName;
     HashKey                 = hashKey;
     Direction               = direction;
     DelayBetweenAPIRequests = delayBetweenAPIRequests;
 }
Exemple #16
0
        private void RemoveConnectionWith(ArrayDCN <T> typedNode, ConnectionDirection direction)
        {
            if (Helpers <T> .CheckWhether_RemoveConnectionWith_IsNeeded(typedNode, this))
            {
                return;
            }

            ParentCollection.DisconnectNodes(this, typedNode, direction);
        }
Exemple #17
0
        internal Field(Model.Field modelField, PropertyMatcherViewModel viewModel, ConnectionDirection direction)
        {
            ModelField = modelField;
            ViewModel  = viewModel;
            Direction  = direction;

            _selectionStatus = SelectionStatus.NotSelected;
            Disconnect       = new DisconnectCommand(this);
        }
Exemple #18
0
        public ICipherParameters Create(ConnectionEnd end, ConnectionDirection direction)
        {
            var key = GetKey(end, direction);

            SecurityAssert.NotNull(key);
            SecurityAssert.Assert(key.Length > 0);

            return(new AESKeyParameter(key));
        }
 public static ConnectionDirection[] VectorsToDirections(Vector3[] Vectors)
 {
     ConnectionDirection[] Dirs = new ConnectionDirection[Vectors.Length];
     for (int i = 0; i < Vectors.Length; i++)
     {
         Dirs [i] = VectorToDirection(Vectors[i]);
     }
     return(Dirs);
 }
Exemple #20
0
        private void InitializeChannel(IChannel channel, ConnectionDirection connectionDirection, NodeId remoteId = null, string remoteHost = null, int?remotePort = null, INodeStats nodeStats = null)
        {
            if (connectionDirection == ConnectionDirection.In)
            {
                Metrics.IncomingConnections++;
            }
            else
            {
                Metrics.OutgoingConnections++;
            }

            P2PSession session = new P2PSession(
                LocalNodeId,
                remoteId,
                _localPort,
                connectionDirection,
                _serializationService,
                _synchronizationManager,
                _nodeStatsProvider,
                nodeStats,
                _logManager, channel, _perfService, _blockTree, _transactionPool, _timestamp);

            if (connectionDirection == ConnectionDirection.Out)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Initializing {connectionDirection.ToString().ToUpper()} channel{(connectionDirection == ConnectionDirection.Out ? $": {remoteId}@{remoteHost}:{remotePort}" : string.Empty)}");
                }

                // this is the first moment we get confirmed publicKey of remote node in case of outgoing connections
                session.RemoteNodeId = remoteId;
                session.RemoteHost   = remoteHost;
                session.RemotePort   = remotePort;
            }

            SessionCreated?.Invoke(this, new SessionEventArgs(session));

            HandshakeRole role             = connectionDirection == ConnectionDirection.In ? HandshakeRole.Recipient : HandshakeRole.Initiator;
            var           handshakeHandler = new NettyHandshakeHandler(_encryptionHandshakeService, session, role, remoteId, _logManager);

            IChannelPipeline pipeline = channel.Pipeline;

            pipeline.AddLast(new LoggingHandler(connectionDirection.ToString().ToUpper(), DotNetty.Handlers.Logging.LogLevel.TRACE));
            pipeline.AddLast("enc-handshake-dec", new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, ushort.MaxValue, 0, 2, 0, 0, true));
            pipeline.AddLast("enc-handshake-handler", handshakeHandler);

            channel.CloseCompletion.ContinueWith(async x =>
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Channel disconnected: {session.RemoteNodeId}");
                }

                await session.DisconnectAsync(DisconnectReason.ClientQuitting, DisconnectType.Remote);
                SessionClosing?.Invoke(this, new SessionEventArgs(session));
            });
        }
            internal PerSocketDirectionStats(bool sendOrReceive, ConnectionDirection direction)
            {
                StatisticNameFormat batchSizeStatName      = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_PER_SOCKET_DIRECTION;
                StatisticNameFormat batchHistogramStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION;

                averageBatchSize        = AverageValueStatistic.FindOrCreate(new StatisticName(batchSizeStatName, Enum.GetName(typeof(ConnectionDirection), direction)));
                batchSizeBytesHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(
                    new StatisticName(batchHistogramStatName, Enum.GetName(typeof(ConnectionDirection), direction)),
                    NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
            }
Exemple #22
0
        private void RemoveConnectionWith(PointerDCN <T> typedNode, ConnectionDirection direction)
        {
            if (Helpers <T> .CheckWhether_RemoveConnectionWith_IsNeeded(typedNode, this))
            {
                return;
            }

            this.InternalRemoveNodeConnectionRequest(typedNode, direction);
            typedNode.InternalRemoveNodeConnectionRequest(this, direction.Invert());
        }
Exemple #23
0
        private IDigest GetMAC(ConnectionDirection direction)
        {
            var digest = _cipherSuitesProvider.ResolveHashAlgorithm(_cipherSuiteConfig.CipherSuite);

            var key = GetMACKey(direction);

            SecurityAssert.NotNull(key);
            SecurityAssert.Assert(key.Length > 0);

            return(new HMAC(digest, key));
        }
Exemple #24
0
    /// <summary>
    /// Finds the shortest surface distance in the case of the points being on connected Faces.
    /// This method is separate from CalculateShortestSurfaceDistance only for readability purposes.
    /// </summary>
    private static int ConnectedFaceDistance(GridPoint start, GridPoint end)
    {
        ConnectionDirection dir1 = GetConnectionDirection(start.face, end.face);
        ConnectionDirection dir2 = GetConnectionDirection(start.face, end.face);

        if (dir1 == dir2) // rotate 180
        {
            end.RotateGrid90CW();
            end.RotateGrid90CW();
        }
        else if (!IsOppositeDirection(dir1, dir2))
        { // rotate 90, but in which direction ???
            if (dir1 == ConnectionDirection.North && dir2 == ConnectionDirection.East ||
                dir1 == ConnectionDirection.East && dir2 == ConnectionDirection.South ||
                dir1 == ConnectionDirection.South && dir2 == ConnectionDirection.West ||
                dir1 == ConnectionDirection.West && dir2 == ConnectionDirection.North)
            {
                end.RotateGrid90CW();
            }
            else
            {
                end.RotateGrid90CCW();
            }
        }
        switch (dir1)
        {
        case ConnectionDirection.North:
            end.y += gridSize;
            break;

        case ConnectionDirection.East:
            end.x += gridSize;
            break;

        case ConnectionDirection.South:
            start.y += gridSize;
            break;

        case ConnectionDirection.West:
            start.x += gridSize;
            break;

        case ConnectionDirection.None:
            throw new Exception("Calculating shortest surface distance should've been detected as Case 3 (opposite faces) but somehow got Case 2");

        default:
            throw new Exception("Uh-oh");
        }



        return(CalculateShortestDistance(start, end));
    }
Exemple #25
0
        public long GetThenIncrement(ConnectionDirection direction)
        {
            switch (direction)
            {
            case ConnectionDirection.Read:
                return(GetReadThenIncrement());

            case ConnectionDirection.Write:
                return(GetWriteThenIncrement());

            default:
                throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
            }
        }
        internal static ConnectionDirection Invert(this ConnectionDirection direction)
        {
            switch (direction)
            {
            case ConnectionDirection.To:
                return(ConnectionDirection.From);

            case ConnectionDirection.From:
                return(ConnectionDirection.To);

            default:
                return(direction);
            }
        }
 public void ThreadSafeNotifyOfAdjustedEdge(Vector3 keypoint, ConnectionDirection dir, int lodJump)
 {
     lock (adjustedEdges)
     {
         if (adjustedEdges.ContainsKey(keypoint))
         {
             adjustedEdges[keypoint].Add(new ConnectionType(dir, lodJump));
         }
         else
         {
             adjustedEdges.Add(keypoint, new List <ConnectionType>());
             adjustedEdges[keypoint].Add(new ConnectionType(dir, lodJump));
         }
     }
 }
Exemple #28
0
 /// <summary>
 /// Parse connection information.
 /// </summary>
 /// <param name="direction">In or out connections.</param>
 private void ParseConnections(ConnectionDirection direction)
 {
     try
     {
         ConnectionStream cs = new ConnectionStream(Profile.UserName, HashKey, direction, DelayBetweenAPIRequests);
         cs.Read();
         if (cs.Connections != null && cs.Connections.Count > 0)
         {
             Profile.Connections.AddRange(cs.Connections);
         }
     }
     catch (Exception e)
     {
     }
 }
        private ICipherParameters GetParameters(ConnectionDirection direction, byte[] aad, byte[] nonceExplicit)
        {
            var end = _endConfig.End;
            var cipherParameterFactory = _cipherSuitesProvider.ResolveCipherParameterFactory(_cipherSuiteConfig.CipherSuite);

            var innerParameters = cipherParameterFactory.Create(end, direction);

            var nonceImplicit = GetImplicitNonce(direction);

            SecurityAssert.NotNull(nonceImplicit);
            SecurityAssert.Assert(nonceImplicit.Length > 0);

            var nonce = new byte[nonceImplicit.Length + nonceExplicit.Length];

            Array.Copy(nonceImplicit, 0, nonce, 0, nonceImplicit.Length);
            Array.Copy(nonceExplicit, 0, nonce, nonceImplicit.Length, nonceExplicit.Length);

            return(new AADParameter(new IVParameter(innerParameters, nonce), aad));
        }
        public ICipherParameters Create(ConnectionEnd end, ConnectionDirection direction)
        {
            if (_certificateConfig.Certificate is null)
            {
                throw new InvalidOperationException("Certificate is not initialized");
            }

            var publicKey = (RSAPublicKey)_certificateConfig.Certificate.SubjectPublicKey;

            switch (end)
            {
            case ConnectionEnd.Client:
                return(new RSAPublicKeyParameter(publicKey));

            case ConnectionEnd.Server:
                return(new RSAPrivateKeyParameter((RSAPrivateKey)_certificateManager.GetPrivateKey(publicKey)));

            default:
                throw new ArgumentOutOfRangeException(nameof(end), end, null);
            }
        }
Exemple #31
0
		public MapConnection(PokeEngine engine, Map parent, ConnectionDirection direction, int id, int offset)
			: base(engine, id) {
			this.direction = direction;
			this.parent = parent;
			this.offset = offset;
		}
        public void GetFileList(Queue.QueueEntry entry)
        {
            //try to download a filelist that the peer offers by his supports
            //it would be fine to have these converted on the spot to our standard filelist format (files.xml.bz2)
            this.queue_entry = entry;
            this.source = entry.Sources[0];//filelist queue entry have exactly one source , no more no less
            direction = ConnectionDirection.Download;
            long start_pos = 1;
            if (File.Exists(queue_entry.OutputFilename))
            {
                File.Delete(queue_entry.OutputFilename);//delete old filelist if happen to be there
            }

            string filename = "MyList.DcLst";
            if (CheckForExtension("XmlBZList"))
                filename = "files.xml.bz2";
            else if (CheckForExtension("BZList"))
                filename = "MyList.bz2";

            source.Filename = filename;

            if (CheckForExtension("ADCGet"))
            {
                start_pos = start_pos - 1;
                SendCommand("ADCGET", "file " + source.Filename + " " + start_pos + " -1");
                Console.WriteLine("Trying to adc-fetch filelist(" + filename + ") from: '" + entry.Sources[0].UserName + "'");
            }
            else
            {
                SendCommand("Get", filename + "$" + start_pos);
                Console.WriteLine("Trying to fetch filelist(" + filename + ") from: '" + entry.Sources[0].UserName + "'");
            }
        }
Exemple #33
0
		public MapConnection(PokeEngine engine, Map Parent, ConnectionDirection direction, int id)
			: base(engine, id) {

		}
        public void StartDownload()
        {
            direction = ConnectionDirection.Download;
            long start_pos = 1;
            if (File.Exists(queue_entry.OutputFilename))
            {
                FileInfo fi = new FileInfo(queue_entry.OutputFilename);
                if (fi.Length >= queue_entry.Filesize)
                {//abort , file is complete or something else may happened here
                    Disconnect();
                    return;
                }
                start_pos = fi.Length + 1;
                bytes_already_downloaded = fi.Length;
                stream = new FileStream(queue_entry.OutputFilename, FileMode.Append, FileAccess.Write, System.IO.FileShare.ReadWrite);
            }
            else start_pos = 1;

            if (CheckForExtension("ADCGet"))
            {
                start_pos = start_pos - 1;
                if (CheckForExtension("TTHF") && queue_entry.HasTTH)
                    SendCommand("ADCGET", "file TTH/" + queue_entry.TTH + " " + start_pos + " " + (queue_entry.Filesize - start_pos));
                else SendCommand("ADCGET", "file " + source.Filename + " " + start_pos + " " + (queue_entry.Filesize - start_pos));
                Console.WriteLine("Trying to adc-fetch file: '" + source.Filename + "' starting from pos:" + start_pos);
            }
            else
            {
                SendCommand("Get", source.Filename + "$" + start_pos);
                Console.WriteLine("Trying to fetch file: '" + source.Filename + "' starting from pos:" + start_pos);
            }
        }
        public void GetTTHL(Queue.QueueEntry entry)
        {
            //try to download a tthl block if peer offers this via supports
            this.queue_entry = entry;
            //this.source = entry.Sources[0];
            //this.source = source;
            direction = ConnectionDirection.Download;
            long start_pos = 0;
            if (File.Exists(queue_entry.OutputFilename + ".tthl"))
            {
                File.Delete(queue_entry.OutputFilename + ".tthl");//delete old tthl file if happen to be there
            }

            bytes_already_downloaded = 0;
            /*if (File.Exists(queue_entry.OutputFilename))
            {
                FileInfo fi = new FileInfo(queue_entry.OutputFilename);
                if (fi.Length >= queue_entry.Filesize)
                {//abort , file is complete or something else may happened here
                    Disconnect();
                    return;
                }
                start_pos = fi.Length + 1;
                bytes_already_downloaded = fi.Length;
                stream = new FileStream(queue_entry.OutputFilename, FileMode.Append, FileAccess.Write, System.IO.FileShare.ReadWrite);
            }
            else start_pos = 1;
            */

            if (CheckForExtension("ADCGet") && CheckForExtension("TTHL") && CheckForExtension("TTHF") && queue_entry.HasTTH)
            {
                SendCommand("ADCGET", "tthl TTH/" + queue_entry.TTH + " " + start_pos + " -1");
                //SendCommand("ADCGET", "tthl " + source.Filename + " " + start_pos + " -1");
                //Console.WriteLine("Trying to adc-fetch tthl file(" + entry.OutputFilename + ".tthl) from: '" + source.UserName + "'");
                Console.WriteLine("Trying to adc-fetch tthl for file(" + entry.OutputFilename + ")");
            }
            else
            {
                Console.WriteLine("Trying to fetch tthl for file(" + entry.OutputFilename+") from: '" + source.UserName + "' that doesn't support it");
            }
        }
        public bool StartUpload()
        {
            direction = ConnectionDirection.Upload; //TODO enhance Direction handling -> esp uploading if we have nothing to to download from the user
            if (!string.IsNullOrEmpty(upload_filename))
            {
                if (upload_file_list_data != null)
                {
                    upload_length = upload_file_list_data.Length;
                    stream = new MemoryStream(upload_file_list_data);
                    stream.Seek(upload_offset, SeekOrigin.Begin);
                }
                else
                {
                    if (File.Exists(upload_filename))
                    {
                        FileInfo fi = new FileInfo(upload_filename);
                        if (fi.Length < upload_offset)
                        {//abort , file is complete or something else may happened here
                            Console.WriteLine("error requesting data at offset: " + fi.Length + " after file end: " + upload_offset);
                            Disconnect();
                            return (false);
                        }
                        if (fi.Length < upload_offset + upload_length || upload_length == -1)
                        {//abort , file is complete or something else may happened here
                            upload_length = fi.Length - upload_offset;
                        }
                        //Console.WriteLine("Trying to open file: "+f);
                        try
                        {
                            stream = new FileStream(upload_filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.ReadWrite);
                            stream.Seek(upload_offset, SeekOrigin.Begin);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("exception opening file: " + ex.Message);
                            SendFileNotAvailableError();
                            return (false);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Requested file not found: " + upload_filename);
                        SendFileNotAvailableError();
                        return (false);
                    }
                }
                if (CheckForExtension("ADCGet"))
                {

                    string send_parameters = "file " + upload_request_filename + " " + upload_offset + " " + upload_length;
                    Console.WriteLine("adc send parameters : " + send_parameters);
                    SendCommand("ADCSND", send_parameters);
                    Console.WriteLine("Trying to adc-upload file: '" + upload_filename + "' starting from pos:" + upload_offset + " length: " + upload_length);
                    StartUploadTransfer();
                }
                else
                {
                    SendCommand("FileLength", upload_length.ToString());
                    Console.WriteLine("Trying to upload file: '" + upload_filename + "' starting from pos:" + upload_offset + " length: " + upload_length);
                }
                return (true);
            }
            return (false);
        }
        private void DecideDirection()
        {
            if (direction == ConnectionDirection.Unknown && his_direction_wish != ConnectionDirection.Unknown)
            {//only decide once
                if (handshake_my_value < handshake_his_value)
                    direction = his_direction_wish;
                else direction = ConnectionDirection.Download;

                try
                {
                    if (HandShakeCompleted != null)
                        HandShakeCompleted(this);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception in Handshake Event: " + ex.Message);
                }

            }
        }
        /// <summary>
        /// internal function to interpret a command received from the remote peer
        /// </summary>
        /// <param name="received_command"></param>
        /// <returns>
        /// only returns true if a download transfer was started
        /// by $ADCSND
        /// </returns>
        private bool InterpretCommand(string received_command)
        {
            int command_end = received_command.IndexOf(" ");
            if (command_end == -1) command_end = received_command.Length;

            if (command_end != -1)
            {
                string parameter = "";
                string[] parameters ={ };
                string command = received_command.Substring(1);
                if (command_end != received_command.Length)
                {
                    command = received_command.Substring(1, command_end - 1);
                    parameter = received_command.Substring(command_end + 1);
                    parameters = parameter.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                }
                //Console.WriteLine("Command: '" + command + "' ,Parameter(" + parameters.Length + "): '" + parameter + "'");

                switch (command)
                {
                    case "Direction":
                        //Console.WriteLine("Direction command received: " + parameter);
                        handshake_his_value = int.Parse(parameters[1]);
                        if (parameters[0] == "Download") //turns arround in terms of our perception of the direction.
                            his_direction_wish = ConnectionDirection.Upload;
                        else his_direction_wish = ConnectionDirection.Download;
                        DecideDirection();
                        break;

                    case "MyNick":
                        peer_nick = parameters[0];
                        //Console.WriteLine("peer nick: "+peer_nick);
                        //handshake complete
                        break;

                    case "Supports":
                        //Console.WriteLine("Supports command received: " + parameter);
                        supports = (string[])parameters.Clone();
                        break;

                    case "MaxedOut":
                        error_code = ErrorCodes.NoFreeSlots;
                        Disconnect();
                        break;
                    case "Error":
                        error_code = ErrorCodes.NoErrorYet;
                        if (parameter == "File not found" || parameter == "File Not Available")
                            error_code = ErrorCodes.FileNotAvailable;
                        Disconnect();
                        break;

                    case "GetListLen":
                        //Console.WriteLine("GetListLen command received: " + parameter);
                        break;
                    //TODO check for correct direction ..else skip ,same for startdownload
                    case "ADCGET":
                    case "Get":
                        if (command == "ADCGET")
                        {
                            Console.WriteLine("ADCGET command received: " + parameter);
                            upload_request_filename = parameters[1];
                            try
                            {
                                upload_offset = long.Parse(parameters[2]);
                                upload_length = long.Parse(parameters[3]);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("error parsing offsets: " + ex.Message);
                            }
                        }
                        else if (command == "Get")
                        {
                            Console.WriteLine("Get command received: " + parameter);
                            int offset_start = parameter.LastIndexOf("$");
                            if (offset_start == -1)
                                break; //no offset given skip this request
                            long offset = 1;
                            string filename = parameter.Substring(0, offset_start);
                            try
                            {
                                offset = long.Parse(parameter.Substring(offset_start + 1));
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("error parsing offset: " + ex.Message);
                            }
                            upload_request_filename = filename;
                            upload_offset = offset - 1; //we want to send the first byte too , right ?
                            upload_length = -1;
                        }
                        FileRequestAnswer answer = FileRequestAnswer.FileNotAvailable;
                        if (upload_request_filename == "MyList.DcLst" || upload_request_filename == "MyList.bz2")
                        {//not supported right now,maybe never
                            SendFileNotAvailableError();
                            error_code = ErrorCodes.FileNotAvailable;
                            Disconnect();
                        }
                        else if (upload_request_filename == "files.xml.bz2")
                        {
                            if (FileListRequestReceived != null)
                                answer = FileListRequestReceived(this);
                        }
                        else
                        {
                            if (FileRequestReceived != null)
                                answer = FileRequestReceived(this);
                        }
                        //give back answer and maybe disconnect if needed or start upload

                        if (answer == FileRequestAnswer.LetsGo)
                        {
                            Console.WriteLine("Ok lets go , upload something.");
                            if (!StartUpload())
                            {
                                Console.WriteLine("Upload starting failed.Disconnecting...");
                                Disconnect();
                            }
                        }
                        else if (answer == FileRequestAnswer.FileNotAvailable)
                        {
                            Console.WriteLine("Sorry file not found replied.");
                            SendFileNotAvailableError();
                            Disconnect();
                        }
                        else if (answer == FileRequestAnswer.NoFreeSlots)
                        {
                            Console.WriteLine("Sorry no free slot for you.");
                            SendMaxedOut();
                            Disconnect();
                        }
                        break;

                    case "Send":
                        Console.WriteLine("Send command received: " + parameter);
                        StartUploadTransfer();
                        break;

                    case "ADCSND":
                        Console.WriteLine("ADCSEND command received: " + parameter);
                        try
                        {
                            long temp_upload_offset = long.Parse(parameters[2]);
                            long temp_upload_length = long.Parse(parameters[3]);
                            if (queue_entry.Type == Queue.QueueEntry.EntryType.File && !queue_entry.WantTTHL && (temp_upload_length + temp_upload_offset) != queue_entry.Filesize) Disconnect();//fail safe to secure downloads a bit
                            if (queue_entry.Type == Queue.QueueEntry.EntryType.FileList)
                                queue_entry.Filesize = temp_upload_offset + temp_upload_length;
                            if (queue_entry.Type == Queue.QueueEntry.EntryType.File && queue_entry.WantTTHL)
                                tthl_size = temp_upload_length;
                        }
                        catch (Exception ex) { Console.WriteLine("Error parsing file length: " + ex.Message); }
                        StartDownloadTransfer();
                        return (true);
                    //break;

                    case "FileLength":
                        Console.WriteLine("FileLength command received: " + parameter);
                        try
                        {
                            long filelength = long.Parse(parameters[0]);
                            if (queue_entry.Type == Queue.QueueEntry.EntryType.File && filelength != queue_entry.Filesize) Disconnect();//fail safe to secure downloads a bit
                            if (queue_entry.Type == Queue.QueueEntry.EntryType.FileList)
                                queue_entry.Filesize = filelength;
                        }
                        catch (Exception ex) { Console.WriteLine("Error parsing file length: " + ex.Message); }
                        StartDownloadTransfer();
                        break;

                    case "Key":
                        //Console.WriteLine("Key command received: " + parameter);
                        //Random rnd = new Random();
                        //SendCommand("Direction","Download "+rnd.Next(49999).ToString());
                        //SendCommand("GetListLen");

                        /*
                        try
                        {
                            if (HandShakeCompleted != null)
                                HandShakeCompleted(this);

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception in Handshake Event: " + ex.Message);
                        }
                        */

                        //SendCommand("Get", "extras series\\Extras - S01E05 [digitaldistractions].avi$1");
                        //SendCommand("Get", "MyList.DcLst$1");
                        //SendCommand("Get", "files.xml.bz2$1");
                        //out_stream = System.IO.File.Create("temp.avi");
                        //out_stream = new FileStream("temp.avi", FileMode.Create, FileAccess.Write, System.IO.FileShare.ReadWrite);
                        //SendCommand("Send");
                        break;

                    case "Lock":
                        //Console.WriteLine("Lock Command received: " + parameter);
                        if (parameters.Length > 1)
                        {
                            string key = parameters[0];
                            //Console.WriteLine("Key: " + key);
                            if (key.StartsWith("EXTENDEDPROTOCOL"))
                            {
                                is_extended_protocol = true;
                                //Console.WriteLine("Peer is using the dc++ protocol enhancements.");
                                SendCommand("Supports", "MiniSlots XmlBZList TTHL TTHF ADCGet");
                                //SendCommand("Supports", "MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG ");
                                //SendCommand("Supports", "MiniSlots XmlBZList TTHL TTHF GetZBlock ZLIG ");
                                //SendCommand("Supports", "BZList TTHL TTHF GetZBlock´ZLIG ");
                            }

                            string decoded_key = L2K(key);
                            Random rnd = new Random();
                            handshake_my_value = rnd.Next(32767);
                            //StartHandShake();
                            if (direction == ConnectionDirection.Upload)
                                SendCommand("Direction", "Upload " + handshake_my_value.ToString());
                            else SendCommand("Direction", "Download " + handshake_my_value.ToString());

                            DecideDirection();

                            //Console.WriteLine("SendingDecoded key: " + decoded_key);
                            SendCommand("Key", decoded_key);

                        }
                        break;

                    default:
                        Console.WriteLine("Unknown Command received: " + command + ", Parameter: " + parameter);
                        break;
                }
            }
            else Console.WriteLine("Error interpreting command: " + received_command);
            return (false);
        }
Exemple #39
0
    public void Move(Vector2 moveDirection)
    {
        float distance = velocity*Time.deltaTime;
        moveDirection.Normalize();

        while (distance > 0)
        {
          ConnectionDirection c;

          if (currentPos.position == 0) { c = new ConnectionDirection(currentPos.Connection, false); }
          else if (currentPos.position == 1) { c = new ConnectionDirection(currentPos.Connection, true); }
          else
          {
        c = BestDirection(moveDirection, new List<ConnectionDirection>(){
          new ConnectionDirection( currentPos.Connection, true),
          new ConnectionDirection( currentPos.Connection, false)
        });

        if (c == null) //standing still
        {
          break;

        }else{ //move in the middle of a connection
          float l = Vector2.Distance(c.con.Point1.position, c.con.Point2.position) / c.con.movementIndex;
          float marge = ((Mathf.Clamp(c.direction, 0, 1) - currentPos.position) * c.direction);
          float moved = Mathf.Min(l * marge, distance);

          currentPos.position += moved / l * c.direction;
          distance -= moved;
          continue;
        }
          }

          TrackPoint p = (c.direction < 0) ? c.con.Point1 : c.con.Point2;

          List<TrackConnection>connections = p.AllConnections;
          List<ConnectionDirection> possibleCD = new List<ConnectionDirection>();
          for (int i = 0; i < connections.Count; i++)
            {
              possibleCD.Add(new ConnectionDirection(connections[i], (connections[i].Point1 == p)));
            }
          c = BestDirection(moveDirection, possibleCD);

          if (c == null) { //standing still

        break;

          } else {

        currentPos.Connection = c.con;
        currentPos.position = Mathf.Clamp(-c.direction, 0, 1);

        float l = Vector2.Distance(c.con.Point1.position, c.con.Point2.position) / c.con.movementIndex;
        float marge = ((Mathf.Clamp(c.direction, 0, 1) - currentPos.position) * c.direction);
        float moved = Mathf.Min(l * marge, distance);

        currentPos.position += moved / l * c.direction;
        distance -= moved;

          }

        }
    }
Exemple #40
0
		public ConnectionInfo(ConnectionDirection dir, int id, int offset) {
			this.dir = dir;
			this.id = id;
			this.offset = offset;
		}