Esempio n. 1
0
 public void WriteVector2(string name, Vector2 value)
 {
     ValidateOrGenerateSchema(name, NetworkSchema.FieldType.Vector2, 32);
     m_Output.WriteUInt32(NetworkUtils.FloatToUInt32(value.x));
     m_Output.WriteUInt32(NetworkUtils.FloatToUInt32(value.y));
 }
 public Neuron(ActivationTypes activationType)
 {
     this.Function = NetworkUtils.GetActivation(activationType);
 }
Esempio n. 3
0
    public bool Init(string[] args)
    {
        // Set up statemachine for ServerGame
        m_StateMachine = new StateMachine <ServerState>();
        m_StateMachine.Add(ServerState.Idle, null, UpdateIdleState, null);
        m_StateMachine.Add(ServerState.Loading, null, UpdateLoadingState, null);
        m_StateMachine.Add(ServerState.Active, EnterActiveState, UpdateActiveState, LeaveActiveState);

        m_StateMachine.SwitchTo(ServerState.Idle);

        m_NetworkTransport = new SocketTransport(serverPort.IntValue);
        GameDebug.Log("Listening on " + string.Join(", ", NetworkUtils.GetLocalInterfaceAddresses()) + " on port " + serverPort.IntValue);
        m_NetworkServer = new NetworkServer(m_NetworkTransport);

        if (Game.game.clientFrontend != null)
        {
            var serverPanel = Game.game.clientFrontend.serverPanel;
            serverPanel.SetPanelActive(true);
            serverPanel.serverInfo.text += "Listening on:\n";
            foreach (var a in NetworkUtils.GetLocalInterfaceAddresses())
            {
                serverPanel.serverInfo.text += a + ":" + serverPort.IntValue + "\n";
            }
        }

        m_NetworkServer.UpdateClientInfo();
        m_NetworkServer.clientInfo.compressionModel = m_Model;

        if (serverServerName.Value == "")
        {
            serverServerName.Value = MakeServername();
        }

        m_ServerQueryProtocolServer = new SQP.SQPServer(NetworkConfig.serverSQPPort.IntValue);


#if UNITY_EDITOR
        Game.game.levelManager.UnloadLevel();
        World.DisposeAllWorlds();
#endif
        m_GameWorld = new GameWorld("ServerWorld");

        m_NetworkStatistics = new NetworkStatisticsServer(m_NetworkServer);

        m_ChatSystem = new ChatSystemServer(m_Clients, m_NetworkServer);

        GameDebug.Log("Network server initialized");

        Console.AddCommand("load", CmdLoad, "Load a named scene", this.GetHashCode());
        Console.AddCommand("unload", CmdUnload, "Unload current scene", this.GetHashCode());
        Console.AddCommand("respawn", CmdRespawn, "Respawn character (usage : respawn playername|playerId)", this.GetHashCode());
        Console.AddCommand("servername", CmdSetServerName, "Set name of the server", this.GetHashCode());
        Console.AddCommand("beginnetworkprofile", CmdBeginNetworkProfile, "begins a network profile", this.GetHashCode());
        Console.AddCommand("endnetworkprofile", CmdEndNetworkProfile, "Ends a network profile and analyzes. [optional] filepath for model data", this.GetHashCode());
        Console.AddCommand("loadcompressionmodel", CmdLoadNetworkCompressionModel, "Loads a network compression model from a filepath", this.GetHashCode());
        Console.AddCommand("list", CmdList, "List clients", this.GetHashCode());

        CmdLoad(args);
        Game.SetMousePointerLock(false);

        m_ServerStartTime = Time.time;

        GameDebug.Log("Server initialized");
        Console.SetOpen(false);
        return(true);
    }
Esempio n. 4
0
    public override void OnServerDisconnect(NetworkConnection connection)
    {
        NetworkUtils.unassignAllObjectFromPlayer(connection);

        base.OnServerDisconnect(connection);
    }
Esempio n. 5
0
        public void Enter(SyncSession session, DistrictEnterRequest request)
        {
            if (!_globalRelay.Session.Contains(new() { Account = request.Account, Key = request.SessionKey }).Result)
            {
                NetworkUtils.DropBadAction();
            }

            {
                AccountModel model = GetAccountModel(request.Account);
                session.Account = new(model);
            }

            {
                CharacterModel model = GetCharacterModel(request.Character, request.Account);

                session.Character      = new(model);
                session.Profile        = new(model.Profile);
                session.Stats          = new();
                session.SpecialOptions = new();
                session.Gestures       = model.Gestures;

                using ItemContext context = _itemFactory.CreateDbContext();
                session.Storages          = new(model, _tables, context);
            }

            if (!_channels.TryJoin(session))
            {
                NetworkUtils.DropBadAction();
            }

            if (!_sync.Characters.TryAdd(session.Character.Id, session))
            {
                NetworkUtils.DropBadAction();
            }

            session.Permission = HandlerPermission.Authorized;

            session.SendAsync(new SWorldCurrentDataResponse());
            session.SendAsync(new WorldVersionResponse()
            {
                Id   = 0,
                Main = 1,
                Sub  = 837,
                Data = 16888
            });

            if (_tables.BattlePass.Count > 0)
            {
                PassInfoTableEntity entity = _tables.BattlePass.Values.First();
                session.SendAsync(new BattlePassLoadResponse()
                {
                    Id         = entity.Id,
                    HavePoint  = 2000,
                    NextReward = 3,
                    StartDate  = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                    EndDate    = DateTimeOffset.UtcNow.AddMonths(1).ToUnixTimeSeconds(),
                    IsPremium  = 1
                });
            }

            session.SendAsync(new DayEventBoosterResponse()
            {
                Values = _dayEventBoosters.Select(s => new DayEventBoosterResponse.Entity()
                {
                    Id   = s.Id,
                    Maze = s.Maze.Id
                }).ToArray()
            });

            // CharacterSuperArmorGage
            // LOGLV 2 : 454.747 :: eSUB_CMD_BOOSTER_ADD 2

            session.SendAsync(new DistrictEnterResponse()
            {
                Place = new()
                {
                    Location = _instance.Location.Id,
                    Position = session.Character.Place.Position,
                    Rotation = session.Character.Place.Rotation,
                }
            });
Esempio n. 6
0
        unsafe void ReadSnapshot(int sequence, ref RawInputStream input, ISnapshotConsumer consumer)
        {
            var haveBaseline = input.ReadRawBits(1) == 1;
            var baseSequence = (int)input.ReadPackedIntDelta(sequence - 1, NetworkConfig.baseSequenceContext);

            bool enableNetworkPrediction = input.ReadRawBits(1) != 0;

            int baseSequence1 = 0;
            int baseSequence2 = 0;

            if (enableNetworkPrediction)
            {
                baseSequence1 = (int)input.ReadPackedIntDelta(baseSequence - 1, NetworkConfig.baseSequence1Context);
                baseSequence2 = (int)input.ReadPackedIntDelta(baseSequence1 - 1, NetworkConfig.baseSequence2Context);
            }

            var snapshotInfo = snapshots.Acquire(sequence);

            snapshotInfo.serverTime = (int)input.ReadPackedIntDelta(haveBaseline ? snapshots[baseSequence].serverTime : 0, NetworkConfig.serverTimeContext);
            //GameDebug.Log("baseSequence : " + baseSequence + "server time:" + (haveBaseline ? snapshots[baseSequence].serverTime.ToString() : ""));

            var temp = (int)input.ReadRawBits(8);

            serverSimTime = temp * 0.1f;

            // Only update time if received in-order..
            // TODO consider dropping out of order snapshots
            // TODO detecting out-of-order on pack sequences
            if (snapshotInfo.serverTime > serverTime)
            {
                serverTime           = snapshotInfo.serverTime;
                snapshotReceivedTime = NetworkUtils.stopwatch.ElapsedMilliseconds;
            }
            else
            {
                GameDebug.Log(string.Format("NetworkClient. Dropping out of order snaphot. Server time:{0} snapshot time:{1}", serverTime, snapshotInfo.serverTime));
            }

            // Read schemas
            var schemaCount = input.ReadPackedUInt(NetworkConfig.schemaCountContext);

            for (int schemaIndex = 0; schemaIndex < schemaCount; ++schemaIndex)
            {
                var typeId = (ushort)input.ReadPackedUInt(NetworkConfig.schemaTypeIdContext);

                var entityType = new EntityTypeInfo()
                {
                    typeId = typeId
                };
                entityType.schema = NetworkSchema.ReadSchema(ref input);
                //counters.AddSectionStats("snapShotSchemas", input.GetBitPosition2(), new Color(0.0f, (schemaIndex & 1) == 1 ? 0.5f : 1.0f, 1.0f));
                entityType.baseline = new uint[NetworkConfig.maxEntitySnapshotDataSize];
                NetworkSchema.CopyFieldsToBuffer(entityType.schema, ref input, entityType.baseline);

                if (!entityTypes.ContainsKey(typeId))
                {
                    entityTypes.Add(typeId, entityType);
                }

                //counters.AddSectionStats("snapShotSchemas", input.GetBitPosition2(), new Color(1.0f, (schemaIndex & 1) == 1 ? 0.5f : 1.0f, 1.0f));
            }

            // Remove any despawning entities that belong to older base sequences
            for (int i = 0; i < entities.Count; i++)
            {
                var e = entities[i];
                if (e.type == null)
                {
                    continue;
                }
                if (e.despawnSequence > 0 && e.despawnSequence <= baseSequence)
                {
                    e.Reset();
                }
            }

            // Read new spawns
            m_TempSpawnList.Clear();
            var previousId = 1;
            var spawnCount = input.ReadPackedUInt(NetworkConfig.spawnCountContext);

            for (var spawnIndex = 0; spawnIndex < spawnCount; ++spawnIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                // Register the entity
                var typeId = (ushort)input.ReadPackedUInt(NetworkConfig.spawnTypeIdContext);    //TODO: use another encoding
                GameDebug.Assert(entityTypes.ContainsKey(typeId), "Spawn request with unknown type id {0}", typeId);

                byte fieldMask = (byte)input.ReadRawBits(8);

                // TODO need an max entity id for safety
                while (id >= entities.Count)
                {
                    entities.Add(new EntityInfo());
                }

                // Incoming spawn of different type than what we have for this id, so immediately nuke
                // the one we have to make room for the incoming
                if (entities[id].type != null && entities[id].type.typeId != typeId)
                {
                    // This should only ever happen in case of no baseline as normally the server will
                    // not reuse an id before all clients have acknowledged its despawn.
                    GameDebug.Assert(haveBaseline == false, "Spawning entity but we already have with different type?");
                    GameDebug.Log("REPLACING old entity: " + id + " because snapshot gave us new type for this id");
                    despawns.Add(id);
                    entities[id].Reset();
                }

                // We can receive spawn information in several snapshots before our ack
                // has reached the server. Only pass on spawn to game layer once
                if (entities[id].type == null)
                {
                    var e = entities[id];
                    e.type      = entityTypes[typeId];
                    e.fieldMask = fieldMask;
                    spawns.Add(id);
                }

                m_TempSpawnList.Add(id);
            }

            //counters.AddSectionStats("snapShotSpawns", input.GetBitPosition2(), new Color(0, 0.58f, 0));

            // Read despawns
            var despawnCount = input.ReadPackedUInt(NetworkConfig.despawnCountContext);

            // If we have no baseline, we need to clear all entities that are not being spawned
            if (!haveBaseline)
            {
                GameDebug.Assert(despawnCount == 0, "There should not be any despawns in a non-baseline snapshot");
                for (int i = 0, c = entities.Count; i < c; ++i)
                {
                    var e = entities[i];
                    if (e.type == null)
                    {
                        continue;
                    }
                    if (m_TempSpawnList.Contains(i))
                    {
                        continue;
                    }
                    GameDebug.Log("NO BL SO PRUNING Stale entity: " + i);
                    despawns.Add(i);
                    e.Reset();
                }
            }

            for (var despawnIndex = 0; despawnIndex < despawnCount; ++despawnIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                // we may see despawns many times, only handle if we still have the entity
                GameDebug.Assert(id < entities.Count, "Getting despawn for id {0} but we only know about entities up to {1}", id, entities.Count);
                if (entities[id].type == null)
                {
                    continue;
                }

                var entity = entities[id];

                // Already in the process of being despawned. This happens with same-snapshot spawn/despawn cases
                if (entity.despawnSequence > 0)
                {
                    continue;
                }

                // If we are spawning and despawning in same snapshot, delay actual deletion of
                // entity as we need it around to be able to read the update part of the snapshot
                if (m_TempSpawnList.Contains(id))
                {
                    entity.despawnSequence = sequence; // keep until baseSequence >= despawnSequence
                }
                else
                {
                    entity.Reset(); // otherwise remove right away; no further updates coming, not even in this snap
                }
                // Add to despawns list so we can request despawn from game later
                GameDebug.Assert(!despawns.Contains(id), "Double despawn in same snaphot? {0}", id);
                despawns.Add(id);
            }

            // Predict all active entities
            for (var id = 0; id < entities.Count; id++)
            {
                var info = entities[id];
                if (info.type == null)
                {
                    continue;
                }

                // NOTE : As long as the server haven't gotten the spawn acked, it will keep sending
                // delta relative to 0, so we need to check if the entity was in the spawn list to determine
                // if the delta is relative to the last update or not

                int baseline0Time = 0;

                uint[] baseline0 = info.type.baseline;
                GameDebug.Assert(baseline0 != null, "Unable to find schema baseline for type {0}", info.type.typeId);

                if (haveBaseline && !m_TempSpawnList.Contains(id))
                {
                    baseline0 = info.baselines.FindMax(baseSequence);
                    GameDebug.Assert(baseline0 != null, "Unable to find baseline for seq {0} for id {1}", baseSequence, id);
                    baseline0Time = snapshots[baseSequence].serverTime;
                }

                if (enableNetworkPrediction)
                {
                    uint num_baselines = 1; // 1 because either we have schema baseline or we have a real baseline
                    int  baseline1Time = 0;
                    int  baseline2Time = 0;

                    uint[] baseline1 = null;
                    uint[] baseline2 = null;
                    if (baseSequence1 != baseSequence)
                    {
                        baseline1 = info.baselines.FindMax(baseSequence1);
                        if (baseline1 != null)
                        {
                            num_baselines = 2;
                            baseline1Time = snapshots[baseSequence1].serverTime;
                        }
                        if (baseSequence2 != baseSequence1)
                        {
                            baseline2 = info.baselines.FindMax(baseSequence2);
                            if (baseline2 != null)
                            {
                                num_baselines = 3;
                                baseline2Time = snapshots[baseSequence2].serverTime;
                            }
                        }
                    }

                    // TODO are these clears needed?
                    for (int i = 0, c = info.fieldsChangedPrediction.Length; i < c; ++i)
                    {
                        info.fieldsChangedPrediction[i] = 0;
                    }
                    for (int i = 0; i < NetworkConfig.maxEntitySnapshotDataSize; i++)
                    {
                        info.prediction[i] = 0;

                        fixed(uint *prediction = info.prediction, baseline0p = baseline0, baseline1p = baseline1, baseline2p = baseline2)
                        {
                            NetworkPrediction.PredictSnapshot(prediction, info.fieldsChangedPrediction, info.type.schema, num_baselines, (uint)baseline0Time, baseline0p, (uint)baseline1Time, baseline1p, (uint)baseline2Time, baseline2p, (uint)snapshotInfo.serverTime, info.fieldMask);
                        }
                }
                else
                {
                    var f = info.fieldsChangedPrediction;
                    for (var i = 0; i < f.Length; ++i)
                    {
                        f[i] = 0;
                    }
                    for (int i = 0, c = info.type.schema.GetByteSize() / 4; i < c; ++i)
                    {
                        info.prediction[i] = baseline0[i];
                    }
                }
            }

            // Read updates
            var updateCount = input.ReadPackedUInt(NetworkConfig.updateCountContext);

            for (var updateIndex = 0; updateIndex < updateCount; ++updateIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                var info = entities[id];

                uint hash = 0;
                // Copy prediction to temp buffer as we now overwrite info.prediction with fully unpacked
                // state by applying incoming delta to prediction.
                for (int i = 0, c = info.type.schema.GetByteSize() / 4; i < c; ++i)
                {
                    tempSnapshotBuffer[i] = info.prediction[i];
                }

                DeltaReader.Read(ref input, info.type.schema, info.prediction, tempSnapshotBuffer, info.fieldsChangedPrediction, info.fieldMask, ref hash);
            }

            //if (enableNetworkPrediction)
            //    counters.AddSectionStats("snapShotUpdatesPredict", input.GetBitPosition2(), haveBaseline ? new Color(0.09f, 0.38f, 0.93f) : Color.cyan);
            //else
            //    counters.AddSectionStats("snapShotUpdatesNoPredict", input.GetBitPosition2(), haveBaseline ? new Color(0.09f, 0.38f, 0.93f) : Color.cyan);

            uint snapshotHash = 0; // sum of hash for all (updated or not) entity snapshots
            uint numEnts      = 0;

            for (int id = 0; id < entities.Count; id++)
            {
                var info = entities[id];
                if (info.type == null)
                {
                    continue;
                }

                // Skip despawned that have not also been spawned in this snapshot
                if (info.despawnSequence > 0 && !spawns.Contains(id))
                {
                    continue;
                }

                // If just spawned or if new snapshot is different from the last we deserialized,
                // we need to deserialize. Otherwise just ignore; no reason to deserialize the same
                // values again
                int schemaSize = info.type.schema.GetByteSize();
                if (info.baselines.GetSize() == 0 || NetworkUtils.MemCmp(info.prediction, 0, info.lastUpdate, 0, schemaSize) != 0)
                {
                    var data = info.baselines.Insert(sequence);
                    for (int i = 0; i < schemaSize / 4; ++i)
                        data[i] = info.prediction[i]; }
                    if (sequence > info.lastUpdateSequence)
                    {
                        if (!updates.Contains(id))
                        {
                            updates.Add(id);
                        }

                        for (int i = 0; i < schemaSize / 4; ++i)
                        {
                            info.lastUpdate[i] = info.prediction[i];
                        }
                        info.lastUpdateSequence = sequence;
                    }
                }

                //if (enableHashing && info.despawnSequence == 0) {
                //    snapshotHash += NetworkUtils.SimpleHash(info.prediction, schemaSize);
                //    numEnts++;
                //}
            }
        protected void ProcessSolicitTransaction(string transactionId)
        {
            using (INodeProcessorMutex mutex = GetMutex(transactionId)) {
                if (!mutex.IsAcquired)
                {
                    LOG.Debug("Exiting ProcessSolicitTransaction(), could not acquire mutex");
                    return;                     // Another thread is already working on this transaction, get out of here
                }
                // Make sure the transaction has not been processed yet
                string transactionModifiedBy;
                if (!TransactionManager.IsUnprocessed(transactionId, out transactionModifiedBy))
                {
                    LOG.Debug("Exiting ProcessSolicitTransaction(), transaction {0} has already been processed",
                              transactionId);
                    return;
                }
                Activity activity = new Activity(NodeMethod.Solicit, null, null, ActivityType.Info, transactionId,
                                                 NetworkUtils.GetLocalIp(),
                                                 "Start processing solicit transaction: \"{0}\"", transactionId);
                activity.ModifiedById = transactionModifiedBy;
                try
                {
                    TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Pending,
                                                            "Processing solicit transaction", false);

                    // Get the request processing service
                    string      requestId, flowName, operation;
                    DataService solicitService =
                        TransactionManager.GetSolicitServiceForTransaction(transactionId, out flowName, out operation, out requestId);
                    if ((solicitService == null) || !solicitService.IsActive)
                    {
                        throw new ArgumentException(string.Format("A valid solicit service was not found for the transaction \"{0}\"",
                                                                  transactionId));
                    }
                    TimeSpan          processLength;
                    ISolicitProcessor plugin;
                    using (IPluginDisposer disposer = PluginLoader.LoadSolicitProcessor(solicitService, out plugin))
                    {
                        TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Processing,
                                                                string.Format("Processing request with transaction id \"{0}\"",
                                                                              transactionId), true);
                        DateTime startTime = DateTime.Now;
                        activity.Append("Set transaction status to Processing");
                        activity.AppendFormat("Processing Solicit transaction for flow \"{0}\" and operation \"{1}\" using plugin \"{2}\"",
                                              flowName, operation, plugin.GetType().FullName);

                        try
                        {
                            plugin.ProcessSolicit(requestId);
                        }
                        finally
                        {
                            activity.Append(plugin.GetAuditLogEvents());
                        }
                        processLength = DateTime.Now - startTime;
                    }

                    activity.AppendFormat("Process time: {0}", processLength.ToString());

                    TransactionStatus transactionStatus =
                        TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Completed,
                                                                string.Format("Completed solicit request with transaction id \"{0}\"",
                                                                              transactionId), true);
                    activity.AppendFormat("Transaction status set to \"{0}\"", transactionStatus.Status.ToString());

                    activity.AppendFormat(TransactionManager.DoTransactionNotifications(transactionId));
                }
                catch (Exception e) {
                    TransactionStatus transactionStatus =
                        TransactionManager.SetTransactionStatusIfNotStatus(transactionId, CommonTransactionStatusCode.Failed,
                                                                           e.Message, CommonTransactionStatusCode.Received, true);

                    activity.AppendFormat("Transaction status set to \"{0}\"", transactionStatus.Status.ToString());
                    activity.Append(ExceptionUtils.ToShortString(e));
                    activity.Type = ActivityType.Error;
                    activity.AppendFormat(TransactionManager.DoTransactionNotifications(transactionId));
                    LOG.Error("ProcessSolicitTransaction() threw an exception.", e);
                }
                finally {
                    ActivityManager.Log(activity);
                }
            }
        }
        /// <summary>
        /// Open and return a new Connection.
        /// </summary>
        /// <returns>
        /// A newly opened Connection.
        /// </returns>
        protected override Connection OpenConnection()
        {
            IAddressProvider provider = RemoteAddressProvider;

            Debug.Assert(provider != null);

            // Default value for Coherence is 0, which is an infinite timeout.
            // Default value for .NET IAsyncResult.WaitOne infinite timeout is -1.
            // So, convert the Coherence infinite value to .NET Timeout.Infinite.
            Int32 cMillis = (Int32)ConnectTimeout;

            cMillis = cMillis <= 0 ? Timeout.Infinite : cMillis;

            // open a new connection
            var         addresses    = new StringBuilder().Append('[');
            IEnumerator enmrRedirect = null;
            IEnumerator enmrSubport  = null;
            IPEndPoint  addrNext     = null;
            Int32       subportNext  = -1;
            Exception   cause        = null;

            for ( ; ;)
            {
                var connection = (TcpConnection)InstantiateConnection();

                IPEndPoint addr;
                Int32      subport;
                if (enmrRedirect == null || addrNext == null)
                {
                    addr    = provider.NextAddress;
                    subport = Subport;

                    // reset redirection information
                    enmrRedirect = null;
                    enmrSubport  = null;
                }
                else
                {
                    addr     = addrNext;
                    addrNext = enmrRedirect.MoveNext() ?
                               (IPEndPoint)enmrRedirect.Current : null;

                    subport     = subportNext;
                    subportNext = enmrSubport.MoveNext() ?
                                  (Int32)enmrSubport.Current : -1;

                    // update redirection information
                    connection.IsRedirect = true;
                }

                if (addr == null)
                {
                    break;
                }

                string address = NetworkUtils.ToString(addr, subport);
                if (RemoteAddressProvider is ConfigurableAddressProvider)
                {
                    StreamProvider.RemoteAddress = ((ConfigurableAddressProvider)RemoteAddressProvider).RemoteHostAddress;
                }

                if (addresses.Length > 1)
                {
                    addresses.Append(", ");
                }
                addresses.Append(address);

                // create and configure a new client
                TcpClient client = InstantiateClient();
                try
                {
                    if (enmrRedirect == null)
                    {
                        CacheFactory.Log("Connecting Socket to " + address,
                                         CacheFactory.LogLevel.Debug);
                    }
                    else
                    {
                        CacheFactory.Log("Redirecting Socket to " + address,
                                         CacheFactory.LogLevel.Debug);
                    }

                    IAsyncResult result = client.BeginConnect(addr.Address, addr.Port, null, null);
                    result.AsyncWaitHandle.WaitOne(cMillis);
                    if (!client.Connected)
                    {
                        CacheFactory.Log("Error connecting TcpClient to "
                                         + address + ": connection timeout", CacheFactory.LogLevel.Info);
                        NetworkUtils.Close(client);
                        continue;
                    }

                    CacheFactory.Log("Connected TcpClient to " + address,
                                     CacheFactory.LogLevel.Info);
                    connection.Client = client;
                }
                catch (Exception e)
                {
                    cause = e;
                    CacheFactory.Log("Error connecting TcpClient to "
                                     + address + ": " + e, CacheFactory.LogLevel.Info);

                    NetworkUtils.Close(client);

                    // if we aren't current redirecting, or we've tried the last redirect
                    // address, reject the last address supplied by the address provider
                    if (enmrRedirect == null || addrNext == null)
                    {
                        provider.Reject(e);
                    }
                    continue;
                }

                // write out subport info
                if (subport != -1)
                {
                    bool   secure = connection.IsSecure;
                    Stream stream = connection.Stream = StreamProvider.GetStream(client);
                    if (secure)
                    {
                        Monitor.Enter(stream);
                    }

                    try
                    {
                        NetworkUtils.WriteSubport(stream, subport);
                    }
                    catch (Exception e)
                    {
                        CacheFactory.Log("Error connecting TcpClient to "
                                         + address + ": " + e, CacheFactory.LogLevel.Info);
                        throw new ConnectionException(e);
                    }
                    finally
                    {
                        if (secure)
                        {
                            Monitor.Exit(stream);
                        }
                    }
                }

                try
                {
                    connection.Open();
                }
                catch (Exception e)
                {
                    if (enmrRedirect == null && connection.IsRedirect)
                    {
                        IList list = connection.RedirectList;

                        // create an IPEndPoint list from from the redirect list
                        var listRedirect = new ArrayList(list.Count);
                        var listSubport  = new ArrayList(list.Count);
                        foreach (var o in list)
                        {
                            var ao     = (Object[])o;
                            var s      = (String)ao[0];
                            var port32 = new Port32((Int32)ao[1]);
                            try
                            {
                                listRedirect.Add(new IPEndPoint(NetworkUtils.GetHostAddress(s, ConnectTimeout),
                                                                port32.Baseport));
                                listSubport.Add(port32.Subport);
                            }
                            catch (Exception)
                            {
                                // invalid or unresolvable address
                                CacheFactory.Log("Skipping unresolvable address \"" + s + "\".",
                                                 CacheFactory.LogLevel.Info);
                            }
                        }
                        enmrRedirect = listRedirect.GetEnumerator();
                        enmrSubport  = listSubport.GetEnumerator();
                        if (enmrRedirect.MoveNext() && enmrSubport.MoveNext())
                        {
                            addrNext    = (IPEndPoint)enmrRedirect.Current;
                            subportNext = (Int32)enmrSubport.Current;
                        }
                        else
                        {
                            addrNext    = null;
                            subportNext = -1;
                        }
                    }
                    else
                    {
                        CacheFactory.Log("Error establishing a connection with " + address + ": " + e,
                                         CacheFactory.LogLevel.Info);

                        // if we aren't current redirecting, or we've tried the last redirect
                        // address, reject the last address supplied by the address provider
                        if (enmrRedirect == null || addrNext == null)
                        {
                            provider.Reject(e);
                        }
                    }
                    continue;
                }

                provider.Accept();
                return(connection);
            }
            addresses.Append(']');

            String message = "could not establish a connection "
                             + "to one of the following addresses: " + addresses
                             + "; make sure the \"remote-addresses\" configuration "
                             + "element contains an address and port of a running "
                             + "TcpAcceptor";

            throw cause == null ? new ConnectionException(message)
                    : new ConnectionException(message, cause);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            Console.WriteLine("ChatClient (c) 2017 James Forshaw");
            Console.WriteLine("WARNING: Don't use this for a real chat system!!!");

            CommandLineApplication app      = new CommandLineApplication(false);
            CommandArgument        username = app.Argument("username", "Specify the username to use for the connection.");
            CommandArgument        server   = app.Argument("server", "Specify server hostname.");
            CommandOption          socks    = app.Option(
                "-s | --socks <host:port>",
                "Specify a SOCKS v4 server to connect to.",
                CommandOptionType.SingleValue);
            CommandOption xor = app.Option(
                "-x | --xor", "Enable simple XOR \"encryption\"",
                CommandOptionType.NoValue);
            CommandOption tls = app.Option(
                "-l | --tls", "Enable TLS",
                CommandOptionType.NoValue);
            CommandOption tls_verify = app.Option(
                "-k | --verify", "Verify TLS Server Certificate",
                CommandOptionType.NoValue);
            CommandOption udp = app.Option(
                "-u | --udp", "Use UDP",
                CommandOptionType.NoValue);
            CommandOption buffered = app.Option(
                "-b", "Buffer writes.",
                CommandOptionType.NoValue);
            CommandOption color_enable = app.Option(
                "--color", "Enable console color output.",
                CommandOptionType.NoValue);
            CommandOption text = app.Option(
                "-t | --text", "Use text based protocol instead of binary",
                CommandOptionType.NoValue);
            CommandOption port = app.Option(
                "-p | --port <port>",
                "Specify the base port for connection.",
                CommandOptionType.SingleValue);

            app.ShowInHelpText = true;
            app.HelpOption("-? | -h | --help");
            app.OnExecute(() =>
            {
                try
                {
                    if (String.IsNullOrWhiteSpace(server.Value) || String.IsNullOrWhiteSpace(username.Value))
                    {
                        app.ShowHelp();
                        return(1);
                    }

                    if (udp.HasValue() && (tls.HasValue() || xor.HasValue() || socks.HasValue()))
                    {
                        WriteError("Can't use both UDP with TLS, XOR or SOCKS options");
                        return(1);
                    }

                    _color_enable   = color_enable.HasValue();
                    int server_port = ParsePort(port);

                    Console.WriteLine("Connecting to {0}:{1}", server.Value, tls.HasValue() ? server_port + 1 : server_port);
                    DnsEndPoint server_ep = new DnsEndPoint(server.Value, server_port);
                    DnsEndPoint socks_ep  = null;
                    if (socks.HasValue())
                    {
                        socks_ep = NetworkUtils.ParseEndpoint(socks.Value());
                    }

                    using (ChatConnection conn = Connect(server_ep, socks_ep, text.HasValue(),
                                                         tls.HasValue(), tls_verify.HasValue(), buffered.HasValue(), udp.HasValue()).GetAwaiter().GetResult())
                    {
                        MainLoop(conn, username.Value, xor.HasValue());
                    }
                }
                catch (Exception ex)
                {
                    WriteError("Error: {0}", ex.Message);
                }

                return(0);
            });
            app.Execute(args);
        }
Esempio n. 10
0
        private async void StartUpload()
        {
            bool upload = await UserDialogs.Instance.ConfirmAsync(new ConfirmConfig
            {
                Message    = AppResources.Uploads_dataWarning,
                OkText     = AppResources.Uploads_dataWarningContinue,
                CancelText = AppResources.Dialog_cancel
            });

            if (!upload)
            {
                return;
            }

            List <PendingPhotoUpload> selected = WrappedItems.Where(item => item.IsSelected)
                                                 .Select(wrappedItem => wrappedItem.Item).ToList();

            // If none are selected, upload all
            if (selected == null || selected.Count == 0)
            {
                selected = WrappedItems.Select(wrappedItem => wrappedItem.Item).ToList();
            }

            UserDialogs.Instance.ShowLoading();

            foreach (PendingPhotoUpload ph in selected)
            {
                byte[] data = DependencyService.Get <ISaveAndLoad>().LoadFromFile(ph.LocalPhotoLoc);

                UserCondition thisCond = JsonConvert.DeserializeObject <UserCondition>(ph.UserConditionJson);

                ServerResponse <string[]> resp = await NetworkUtils.UploadFile(data, string.Format("{0}/{1}/", App.user.Id, thisCond.Id), Guid.NewGuid() + ".jpg");

                if (resp.Response == null || !resp.Response.IsSuccessStatusCode)
                {
                    UserDialogs.Instance.HideLoading();
                    UserDialogs.Instance.Alert(AppResources.PhotoEdit_uploadErr, AppResources.Dialog_error);
                    return;
                }

                Photo toPost = new Photo
                {
                    Url              = resp.Data[0],
                    ThumbUrl         = resp.Data[1],
                    CreatedAt        = ph.CreatedAt,
                    Notes            = ph.Notes,
                    PhotoDescription = ph.PhotoDescription,
                    Treatment        = ph.Treatment,
                    Rating           = ph.Rating,
                    UserCondition    = thisCond
                };

                // post photo
                ServerResponse <Photo> photoResp = await NetworkUtils.PostRequest <Photo>("api/Photo", JsonConvert.SerializeObject(toPost));

                if (photoResp.Response == null || !photoResp.Response.IsSuccessStatusCode)
                {
                    UserDialogs.Instance.HideLoading();
                    UserDialogs.Instance.Alert(AppResources.PhotoEdit_uploadErr, AppResources.Dialog_error);
                    return;
                }
                else
                {
                    DependencyService.Get <ISaveAndLoad>().DeleteLocalCopy(ph.LocalPhotoLoc);
                    App.db.DeleteUpload(ph.Id);
                    SetContent();
                }
            }

            UserDialogs.Instance.HideLoading();
            App.ShouldUpdate        = true;
            GalleryPage.NeedsUpdate = true;

            UserDialogs.Instance.ShowSuccess(AppResources.ChangePass_successTitle);
        }
Esempio n. 11
0
        // Start the node
        static public void start(bool verboseConsoleOutput)
        {
            // First create the data folder if it does not already exist
            checkDataFolder();

            renameStorageFiles(); // this function will be here temporarily for the next few version, then it will be removed to keep a cleaner code base

            // debug
            if (Config.networkDumpFile != "")
            {
                NetDump.Instance.start(Config.networkDumpFile);
            }

            NetworkUtils.configureNetwork();

            char node_type = 'M'; // TODO TODO TODO TODO change this to 'W' or 'C' after the upgrade

            if (Config.disableMiner)
            {
                node_type = 'M';
            }

            // Check if we're in worker-only mode
            if (Config.workerOnly)
            {
                // Enable miner
                Config.disableMiner = false;
                node_type           = 'W';
                CoreConfig.simultaneousConnectedNeighbors = 4;
            }

            // Generate presence list
            PresenceList.generatePresenceList(Config.publicServerIP, node_type);

            // Initialize storage
            Storage.prepareStorage();

            ActivityStorage.prepareStorage();

            // Initialize the block chain
            blockChain = new BlockChain();

            //runDiffTests();
            //return;

            // Create the block processor and sync
            blockProcessor = new BlockProcessor();
            blockSync      = new BlockSync();

            // Start the HTTP JSON API server
            apiServer = new APIServer();

            if (IXICore.Platform.onMono() == false && !Config.disableWebStart)
            {
                System.Diagnostics.Process.Start("http://localhost:" + Config.apiPort);
            }

            miner = new Miner();

            // Start the network queue
            NetworkQueue.start();

            // prepare stats screen
            Config.verboseConsoleOutput = verboseConsoleOutput;
            Logging.consoleOutput       = verboseConsoleOutput;
            Logging.flush();
            if (Config.verboseConsoleOutput == false)
            {
                statsConsoleScreen.clearScreen();
            }

            // Distribute genesis funds
            IxiNumber genesisFunds = new IxiNumber(Config.genesisFunds);

            // Check if this is a genesis node
            if (genesisFunds > (long)0)
            {
                Logging.info(String.Format("Genesis {0} specified. Starting operation.", genesisFunds));

                distributeGenesisFunds(genesisFunds);

                genesisNode = true;
                blockProcessor.resumeOperation();
                serverStarted = true;
                if (!isMasterNode())
                {
                    Logging.info("Network server is not enabled in modes other than master node.");
                }
                else
                {
                    NetworkServer.beginNetworkOperations();
                }
            }
            else
            {
                if (File.Exists(Config.genesisFile))
                {
                    Block genesis = new Block(Crypto.stringToHash(File.ReadAllText(Config.genesisFile)));
                    blockChain.setGenesisBlock(genesis);
                }
                ulong lastLocalBlockNum = Meta.Storage.getLastBlockNum();
                if (lastLocalBlockNum > 6)
                {
                    lastLocalBlockNum = lastLocalBlockNum - 6;
                }
                if (Config.lastGoodBlock > 0 && Config.lastGoodBlock < lastLocalBlockNum)
                {
                    lastLocalBlockNum = Config.lastGoodBlock;
                }
                if (lastLocalBlockNum > 0)
                {
                    Block b = blockChain.getBlock(lastLocalBlockNum, true);
                    if (b != null)
                    {
                        CoreConfig.minRedactedWindowSize = CoreConfig.getRedactedWindowSize(b.version);
                        CoreConfig.redactedWindowSize    = CoreConfig.getRedactedWindowSize(b.version);
                    }
                }

                if (Config.recoverFromFile)
                {
                    Block b = Meta.Storage.getBlock(lastLocalBlockNum);
                    blockSync.onHelloDataReceived(b.blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getUniqueSignatureCount(), lastLocalBlockNum);
                }
                else
                {
                    ulong blockNum = WalletStateStorage.restoreWalletState(lastLocalBlockNum);
                    if (blockNum > 0)
                    {
                        Block b = blockChain.getBlock(blockNum, true);
                        if (b != null)
                        {
                            blockSync.onHelloDataReceived(blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getUniqueSignatureCount(), lastLocalBlockNum);
                        }
                        else
                        {
                            walletState.clear();
                        }
                    }
                    else
                    {
                        blockSync.lastBlockToReadFromStorage = lastLocalBlockNum;
                    }

                    // Start the server for ping purposes
                    serverStarted = true;
                    if (!isMasterNode())
                    {
                        Logging.info("Network server is not enabled in modes other than master node.");
                    }
                    else
                    {
                        NetworkServer.beginNetworkOperations();
                    }

                    // Start the network client manager
                    NetworkClientManager.start();
                }
            }

            PresenceList.startKeepAlive();

            TLC = new ThreadLiveCheck();
            // Start the maintenance thread
            maintenanceThread      = new Thread(performMaintenance);
            maintenanceThread.Name = "Node_Maintenance_Thread";
            maintenanceThread.Start();
        }
Esempio n. 12
0
        public RequestHandler()
            : base("api")
        {
#pragma warning disable CS1998

            Get("/", async(x, ct) =>
            {
                return(Response.AsJson(new MainResponse <String>("Welcome to AndroidAPI")));
            });

            //IPADDRESS
            Get("/ipaddress", async(x, ct) =>
            {
                string ipAddress = NetworkUtils.GetExternalIPAddress();
                if (ipAddress == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "unable_get_ipaddress")));
                }

                return(Response.AsJson(new MainResponse <String>(ipAddress)));
            });

            //REGISTER
            Post("/register", async(x, ct) =>
            {
                var bodyJson = JObject.Parse(this.Request.Body.AsString());

                string serialId = bodyJson["serial_id"]?.ToString();
                string userName = bodyJson["user_name"]?.ToString();

                if (serialId == null || userName == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                if (userName.Length < 4)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "short_username_length")));
                }

                int adminCount = LocalUser.GetAdministratorsCountFromDB();

                if (adminCount == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                if (adminCount >= 1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "admin_already_exists")));
                }

                if (serialId != DotNetEnv.Env.GetString("SERIAL_ID"))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "wrong_serial_id")));
                }

                //INSERT NEW ADMINISTRATOR ACCOUNT, return random password...
                byte[] newPasswordBytes = RandomGenerator.GenerateRandomBytes(32);

                long status = LocalUser.InsertNewAdministratorToDB(new LocalUser
                {
                    Name = userName,
                    Role = "ADMIN"
                }, newPasswordBytes);

                if (status > 0)
                {
                    return(Response.AsJson(new MainResponse <RegisterResponse>(new RegisterResponse()
                    {
                        Password = Convert.ToBase64String(newPasswordBytes),
                        Id = status
                    })));
                }
                else if (status == -2)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "name_already_in_use")));
                }
                else if (status == -3)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "member_is_already_an_admin")));
                }
                else
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }
            });

            /*
             * Login Administrator GET Request.
             * Returns a String on content field with the new generated random session_id.
             */
            Get("/login", async(x, ct) =>
            {
                string userName = this.Request.Query["user_name"];
                string password = this.Request.Query["password"];

                if (userName == null || password == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                if (userName.Length < 4)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "short_username_length")));
                }

                /*
                 * Check if the user and password are in the database and, if it's not there,
                 * return an error message
                 */
                LocalUser user = LocalUser.GetAdministratorFromDB(userName, password);
                if (user == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "wrong_user_password")));
                }

                /*
                 * If everything is good so far:
                 *   - Save the IPAddress(UserHostAddress) and the last time the administrator has logged in.
                 *   - Remove, if there's any, the previous active session from the same user.
                 *   - Create a new SessionID(GUID) and save the user into UsersManager.
                 *   - Return as response the new generated SessionID for this user.
                 */
                user.IPAddress   = this.Request.UserHostAddress.ToString().Split(':')[0];
                user.TimeCreated = Time.GetTime();

                UsersManager.RemoveUserByUserName(userName);
                UsersManager.AddUser(user);

                return(Response.AsJson(new MainResponse <string>(user.SessionID)));
            });

            //ADMIN
            Post("/admin", async(x, ct) =>
            {
                var bodyJson = JObject.Parse(this.Request.Body.AsString());

                string sessionId    = bodyJson["session_id"]?.ToString();
                string userIdString = bodyJson["user_id"]?.ToString();
                uint userId         = 0;

                if (sessionId == null || userIdString == null || !uint.TryParse(userIdString, out userId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);
                if (status == 0 && member.IsOwner)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "member_is_already_an_admin")));
                }
                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                LocalUser newUser = new LocalUser()
                {
                    IsOwner      = false,
                    UserID       = member.UserID,
                    ProfilePhoto = member.ProfilePhoto,
                    Name         = member.Name,
                    Role         = member.Role,
                    TimeCreated  = Time.GetTime() - UsersManager.MAX_LIVE_TIME + 5 * 60 * 1000, //5min live time
                };

                UsersManager.AddUser(newUser);
                return(Response.AsJson(new MainResponse <String>(newUser.SessionID)));
            });

            Get("/admin/confirm", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];

                if (sessionId == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckSignUp(sessionId, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                byte[] newPasswordBytes = RandomGenerator.GenerateRandomBytes(32);

                int status = LocalUser.InsertNewAdministratorToDBFromExistingUser(user, newPasswordBytes);

                if (status == 1)
                {
                    user.IsOwner             = true;
                    user.TimeRegisteredLocal = DateTime.Now;
                    Log.InsertNewLog(user.UserID, "user_to_owner");
                    return(Response.AsJson(new MainResponse <AdminConfirmResponse>(new AdminConfirmResponse()
                    {
                        Password = Convert.ToBase64String(newPasswordBytes),
                        Id = user.UserID,
                        Name = user.Name
                    })));
                }
                else if (status == -3)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "member_is_already_an_admin")));
                }
                else if (status == -4)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "member_id_not_found")));
                }
                else
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }
            });

            //USER
            Post("/user", async(x, ct) =>
            {
                var bodyJson = JObject.Parse(this.Request.Body.AsString());

                string sessionId = bodyJson["session_id"]?.ToString();
                string userName  = bodyJson["user_name"]?.ToString();
                string userRole  = bodyJson["user_role"]?.ToString();

                if (sessionId == null || userName == null || userRole == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                if (userName.Length < 4)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "short_username_length")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                long userId = LocalUser.InsertNewMemberToDB(new User()
                {
                    Name    = userName,
                    IsOwner = false,
                    Role    = userRole
                });

                if (userId > 0)
                {
                    //SEND LOCKING DEVICE THE USERID AND WAIT UNTIL THE LOCKING DEVICE RETURNS THAT THE PROCESS IS GOING TO START
                    //IF NOT I SHOULD RETURN locker_device_not_found AND DELETE USER FROM DATABASE

                    /*List<string> responses = null;
                     * try
                     * {
                     *  responses = await Program.LockerDevicesManager.SendMessageToAllDevicesBlocking("create_user|" + userId + "|");
                     * }
                     * catch (Exception)
                     * {
                     *
                     * }
                     *
                     * if (responses != null && responses.Count > 0)*/
                    return(Response.AsJson(new MainResponse <long>(userId)));

                    /*LocalUser.DeleteUserFromDB(userId);
                     * return Response.AsJson(new MainResponse<byte>(true, "locker_device_not_found"));*/
                }
                if (userId == -2)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "name_already_in_use")));
                }
                return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
            });

            Post("/user/biometric", async(x, ct) =>
            {
                var bodyJson = JObject.Parse(this.Request.Body.AsString());

                string sessionId    = bodyJson["session_id"]?.ToString();
                string userIdString = bodyJson["user_id"]?.ToString();
                uint userId         = 0;

                if (sessionId == null || userIdString == null || !uint.TryParse(userIdString, out userId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);

                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                List <string> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.SendMessageToAllDevicesBlocking("create_user|" + userId + "|");
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0)
                {
                    return(Response.AsJson(new MainResponse <string>("biometric_process_has_begun")));
                }

                //LocalUser.DeleteUserFromDB(userId);
                return(Response.AsJson(new MainResponse <byte>(true, "locker_device_not_found")));
            });

            Get("/user/{id}/images", async(x, ct) =>
            {
                string sessionId    = this.Request.Query["session_id"];
                string userIdString = x.id.ToString();
                uint userId         = 0;

                if (sessionId == null || userIdString == null || !UInt32.TryParse(userIdString, out userId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);

                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }


                List <string> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.SendMessageToAllDevicesBlocking("get_photo_list|" + member.UserID + "|");
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0 && responses[0] != null)
                {
                    if (!responses[0].StartsWith("error"))
                    {
                        List <string> images = new List <string>();
                        string message       = responses[0];
                        string value;
                        while ((value = getStringFirstValue(message, out message)) != String.Empty)
                        {
                            images.Add(LocalUser.URL_USER_IMAGE + userId + LocalUser.URL_USER_FACE_IMAGE + value);
                        }
                        return(Response.AsJson(new MainResponse <List <string> >(images)));
                    }
                    return(Response.AsJson(new MainResponse <byte>(true, "no_images_found")));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "locker_device_not_found")));
            });

            Get("/user/{id}/face/{photo}", async(x, ct) =>
            {
                string sessionId     = this.Request.Query["session_id"];
                string userIdString  = x.id.ToString();
                string photoIdString = x.photo.ToString();
                uint userId          = 0;
                int photoId          = 0;

                if (sessionId == null || userIdString == null || !UInt32.TryParse(userIdString, out userId) || photoIdString == null || !Int32.TryParse(photoIdString, out photoId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);

                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                List <byte[]> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.GetImageUserRecognition(userId, photoId);
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0)
                {
                    return(Response.FromByteArray(responses[0], "image/png"));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "no_image_found")));
            });

            Get("/user/{id}/profile/image", async(x, ct) =>
            {
                string sessionId    = this.Request.Query["session_id"];
                string userIdString = x.id.ToString();
                uint userId         = 0;

                if (sessionId == null || userIdString == null || !UInt32.TryParse(userIdString, out userId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);

                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                string imageFormat = member.ProfilePhotoFormat;
                byte[] image       = ProfilePhoto.GetProfilePhoto(userId, member.ProfilePhotoFormat == "image/jpeg" ? "jpg" : "png", out imageFormat);

                return(Response.FromByteArray(image, imageFormat));
            });

            Post("/user/{id}/profile/image", async(x, ct) =>
            {
                string sessionId    = this.Request.Query["session_id"];
                string userIdString = x.id.ToString();
                uint userId         = 0;

                if (sessionId == null || userIdString == null || !UInt32.TryParse(userIdString, out userId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                LocalUser member = null;

                int status = LocalUser.GetUserFromDB(userId, out member);

                if (status == -1)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                var file = this.Request.Files.FirstOrDefault();

                if (file != null)
                {
                    if (file.ContentType != "image/jpeg" && file.ContentType != "image/png")
                    {
                        return(Response.AsJson(new MainResponse <byte>(true, "no_file_uploaded")));
                    }

                    byte[] image = null;
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            file.Value.CopyTo(ms);
                            image = ms.ToArray();
                        }
                    }
                    catch (Exception)
                    {
                    }

                    if (image == null)
                    {
                        return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                    }

                    if (!LocalUser.UpdateImageFormatUserFromDB(userId, file.ContentType == "image/jpeg" ? 1 : 2))
                    {
                        return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                    }


                    ProfilePhoto.AddProfilePhoto(image, userId, file.ContentType == "image/jpeg" ? "jpg" : "png");
                    return(Response.AsJson(new MainResponse <string>("image_uploaded")));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "no_file_uploaded")));
            });

            //USERS
            Get("/users", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];
                if (sessionId == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                List <User> users;
                int status = LocalUser.GetUsersFromDB(out users);

                if (status < 0)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                return(Response.AsJson(new MainResponse <List <User> >(users)));
            });

            //CAMERA
            Get("/video", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];
                if (sessionId == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                string ipAddress = NetworkUtils.GetExternalIPAddress();
                if (ipAddress == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "unable_get_ipaddress")));
                }

                if (Program.VideoClientsManager.AddIPAddress(user.IPAddress) && Time.GetTime() - user.TimeCreated >= 5 * 60 * 1000)
                {
                    user.TimeCreated += 5 * 60 * 1000;
                }

                //tcp/h264://192.168.1.154:8082
                //return Response.AsJson(new MainResponse<String>("tcp/h264://" + ipAddress + ":" + DotNetEnv.Env.GetInt("TCP_VIDEO_LISTENER_PORT").ToString()));

                List <byte[]> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.GetLiveImageFromLockingDevices();
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0)
                {
                    return(Response.FromByteArray(responses[0], "image/jpeg"));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "no_live_image_available")));
            });

            //DOOR
            Get("/door", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];
                if (sessionId == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                List <string> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.SendMessageToAllDevicesBlocking("open_door");
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0)
                {
                    Log.InsertNewLog(user.UserID, "button_open_door");
                    return(Response.AsJson(new MainResponse <List <string> >(responses)));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "locker_device_not_found")));
            });

            Get("/reset", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];
                string serialId  = this.Request.Query["serial_id"];
                if ((sessionId == null || sessionId == string.Empty) && (serialId == null || serialId == string.Empty))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                if (sessionId != null && sessionId != string.Empty)
                {
                    LocalUser user;
                    if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                    {
                        return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                    }
                }
                else
                {
                    if (serialId != DotNetEnv.Env.GetString("SERIAL_ID"))
                    {
                        return(Response.AsJson(new MainResponse <byte>(true, "wrong_serial_id")));
                    }
                }

                List <string> responses = null;
                try
                {
                    responses = await Program.LockerDevicesManager.SendMessageToAllDevicesBlocking("reset");
                }
                catch (Exception)
                {
                }

                if (responses != null && responses.Count > 0)
                {
                    //CLEAR DATABASE
                    LocalUser.WipeDatabase();
                    UsersManager.ClearUsers();
                    return(Response.AsJson(new MainResponse <List <string> >(responses)));
                }

                return(Response.AsJson(new MainResponse <byte>(true, "locker_device_not_found")));
            });

            //LOGS & NOTIFICATIONS
            Get("/logs", async(x, ct) =>
            {
                string sessionId       = this.Request.Query["session_id"];
                string beginDateString = this.Request.Query["begin_date"];
                string endDateString   = this.Request.Query["end_date"];

                DateTime beginDate = DateTime.UtcNow;
                DateTime endDate   = DateTime.UtcNow;

                if (sessionId == null || beginDateString == null || endDateString == null || !DateTime.TryParseExact(beginDateString, "dd/MM/yyyy-HH:mm:ss", null, DateTimeStyles.AssumeUniversal, out beginDate) || !DateTime.TryParseExact(endDateString, "dd/MM/yyyy-HH:mm:ss", null, DateTimeStyles.AssumeUniversal, out endDate))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                beginDate = beginDate.ToLocalTime();
                endDate   = endDate.ToLocalTime();

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                List <Log> logs;
                int status = Log.GetLogs(beginDate, endDate, out logs);

                if (status < 0)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                return(Response.AsJson(new MainResponse <List <Log> >(logs)));
            });

            Get("/notifications", async(x, ct) =>
            {
                string sessionId = this.Request.Query["session_id"];
                if (sessionId == null)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                List <Log> logs;
                int status = Log.GetNotifications(user, out logs);

                if (status < 0)
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }

                return(Response.AsJson(new MainResponse <List <Log> >(logs)));
            });

            Put("/notification/{id}", async(x, ct) =>
            {
                string sessionId            = this.Request.Query["session_id"];
                string notificationIdString = x.id.ToString();
                uint notificationId         = 0;

                if (sessionId == null || notificationIdString == null || !UInt32.TryParse(notificationIdString, out notificationId))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "missing_request_parameters")));
                }

                LocalUser user;
                if (!UsersManager.CheckLogIn(sessionId, this.Request.UserHostAddress, out user))
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "expired_session_id")));
                }

                if (Log.MarkNotificationAsRead(user, notificationId))
                {
                    return(Response.AsJson(new MainResponse <string>("")));
                }
                else
                {
                    return(Response.AsJson(new MainResponse <byte>(true, "database_error")));
                }
            });



#pragma warning restore CS1998
        }
Esempio n. 13
0
        public /*synchronized*/ void downloadBook(DownloadQueue downloadQueue)
        {
            List <BookMixAToc.MixToc.Chapters> list = downloadQueue.list;
            string bookId       = downloadQueue.bookId;
            int    start        = downloadQueue.start; // 起始章节
            int    end          = downloadQueue.end;   // 结束章节
            int    failureCount = 0;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    Thread.Sleep(1000);
                }
                catch (InterruptedException e) { }
                for (int i = start; i <= end && i <= list.Count(); i++)
                {
                    if (canceled)
                    {
                        break;
                    }
                    // 网络异常,取消下载
                    if (!NetworkUtils.isAvailable(AppUtils.getAppContext()))
                    {
                        downloadQueue.isCancel = true;
                        Post(new DownloadMessage(bookId, GetString(Resource.String.book_read_download_error), true));
                        failureCount = -1;
                        break;
                    }
                    if (!downloadQueue.isFinish && !downloadQueue.isCancel)
                    {
                        // 章节文件不存在,则下载,否则跳过
                        if (CacheManager.GetChapterFile(bookId, i) == null)
                        {
                            BookMixAToc.MixToc.Chapters chapters = list[i - 1];
                            string url = chapters.link;
                            int ret    = download(url, bookId, chapters.title, i, list.Count());
                            if (ret != 1)
                            {
                                failureCount++;
                            }
                        }
                        else
                        {
                            Post(new DownloadProgress(bookId, Java.Lang.String.Format(
                                                          GetString(Resource.String.book_read_alreday_download), list[i - 1].title, i, list.Count()),
                                                      true));
                        }
                    }
                }
                try
                {
                    Thread.Sleep(500);
                }
                catch (InterruptedException e)
                {
                }
                return(failureCount);
            }).ContinueWith(task =>
            {
                downloadQueue.isFinish = true;
                if (failureCount > -1)
                {
                    // 完成通知
                    Post(new DownloadMessage(bookId,
                                             Java.Lang.String.Format(GetString(Resource.String.book_read_download_complete), failureCount), true));
                }
                // 下载完成,从队列里移除
                downloadQueues.Remove(downloadQueue);
                // 释放 空闲状态
                isBusy = false;
                if (!canceled)
                {
                    // post一个空事件,通知继续执行下一个任务
                    Post(new DownloadQueue());
                }
                else
                {
                    downloadQueues.Clear();
                }
                canceled = false;
                LogUtils.i(bookId + "缓存完成,失败" + failureCount + "章");
            });
        }
Esempio n. 14
0
    unsafe static public void Write(ref RawOutputStream output, NetworkSchema schema, uint *inputData, uint *baselineData, byte[] fieldsChangedPrediction, byte fieldMask, ref uint entity_hash)
    {
        GameDebug.Assert(baselineData != null);

        int numFields = schema.numFields;

        GameDebug.Assert(fieldsChangedPrediction.Length >= numFields / 8, "Not enough bits in fieldsChangedPrediction for all fields");

        for (int i = 0, l = fieldsNotPredicted.Length; i < l; ++i)
        {
            fieldsNotPredicted[i] = 0;
        }

        int index = 0;

        // calculate bitmask of fields that need to be encoded
        for (int fieldIndex = 0; fieldIndex < numFields; ++fieldIndex)
        {
            var field = schema.fields[fieldIndex];

            // Skip fields that are masked out
            bool masked = (field.fieldMask & fieldMask) != 0;

            byte fieldByteOffset = (byte)((uint)fieldIndex >> 3);
            byte fieldBitOffset  = (byte)((uint)fieldIndex & 0x7);

            switch (field.fieldType)
            {
            case NetworkSchema.FieldType.Bool: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value);
                    if (value != baseline)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }

                break;
            }

            case NetworkSchema.FieldType.Int: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value);
                    if (value != baseline)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.UInt: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value);
                    if (value != baseline)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Float: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value);
                    if (value != baseline)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Vector2: {
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy);
                    if (vx != bx || vy != by)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Vector3: {
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                uint vz = inputData[index];
                uint bz = baselineData[index];
                index++;

                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vz);
                    if (vx != bx || vy != by || vz != bz)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }


            case NetworkSchema.FieldType.Quaternion: {
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                uint vz = inputData[index];
                uint bz = baselineData[index];
                index++;

                uint vw = inputData[index];
                uint bw = baselineData[index];
                index++;



                if (!masked)
                {
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vz);
                    entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vw);
                    if (vx != bx || vy != by || vz != bz || vw != bw)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                break;
            }


            case NetworkSchema.FieldType.String:
            case NetworkSchema.FieldType.ByteArray: {
                if (!masked)
                {
                    entity_hash += 0;         // TODO client side has no easy way to hash strings. enable this when possible: NetworkUtils.SimpleHash(valueBuffer, valueLength);
                    bool same = true;
                    for (int i = 0; i < field.arraySize; i++)
                    {
                        if (inputData[index + i] != baselineData[index + i])
                        {
                            same = false;
                            break;
                        }
                    }
                    if (!same)
                    {
                        fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset);
                    }
                }
                index += field.arraySize / 4 + 1;
            }
            break;
            }
        }

        index = 0;

        int skipContext = schema.id * NetworkConfig.maxContextsPerSchema + NetworkConfig.firstSchemaContext;

        // Client needs fieldsNotPredicted. We send the delta between it and fieldsChangedPrediction
        {
            for (int i = 0; i * 8 < numFields; i++)
            {
                byte deltaFields = (byte)(fieldsNotPredicted[i] ^ fieldsChangedPrediction[i]);
                output.WritePackedNibble((uint)(deltaFields & 0xF), skipContext + i * 2);
                output.WritePackedNibble((uint)((deltaFields >> 4) & 0xF), skipContext + i * 2 + 1);
            }
        }

        int startBitPosition = 0;

        for (int fieldIndex = 0; fieldIndex < numFields; ++fieldIndex)
        {
            var field             = schema.fields[fieldIndex];
            int fieldStartContext = field.startContext;
            startBitPosition = output.GetBitPosition2();

            byte fieldByteOffset = (byte)((uint)fieldIndex >> 3);
            byte fieldBitOffset  = (byte)((uint)fieldIndex & 0x7);
            var  notPredicted    = ((fieldsNotPredicted[fieldByteOffset] & (1 << fieldBitOffset)) != 0);

            switch (field.fieldType)
            {
            case NetworkSchema.FieldType.Bool: {
                uint value = inputData[index];
                index++;

                if (notPredicted)
                {
                    output.WriteRawBits(value, 1);
                    NetworkSchema.AddStatsToFieldBool(field, (value != 0), false, output.GetBitPosition2() - startBitPosition);
                }
                break;
            }

            case NetworkSchema.FieldType.Int: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(value, baseline, fieldStartContext);
                        NetworkSchema.AddStatsToFieldInt(field, (int)value, (int)baseline, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(value, field.bits);
                        NetworkSchema.AddStatsToFieldInt(field, (int)value, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.UInt: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(value, baseline, fieldStartContext);
                        NetworkSchema.AddStatsToFieldUInt(field, value, baseline, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(value, field.bits);
                        NetworkSchema.AddStatsToFieldUInt(field, value, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Float: {
                uint value    = inputData[index];
                uint baseline = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(value, baseline, fieldStartContext);
                        NetworkSchema.AddStatsToFieldFloat(field, value, baseline, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(value, field.bits);
                        NetworkSchema.AddStatsToFieldFloat(field, value, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Vector2: {
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0);
                        output.WritePackedUIntDelta(vy, by, fieldStartContext + 1);
                        NetworkSchema.AddStatsToFieldVector2(field, vx, vy, bx, by, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(vx, field.bits);
                        output.WriteRawBits(vy, field.bits);
                        NetworkSchema.AddStatsToFieldVector2(field, vx, vy, 0, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }

            case NetworkSchema.FieldType.Vector3: {
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                uint vz = inputData[index];
                uint bz = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0);
                        output.WritePackedUIntDelta(vy, by, fieldStartContext + 1);
                        output.WritePackedUIntDelta(vz, bz, fieldStartContext + 2);
                        NetworkSchema.AddStatsToFieldVector3(field, vx, vy, vz, bx, by, bz, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(vx, field.bits);
                        output.WriteRawBits(vy, field.bits);
                        output.WriteRawBits(vz, field.bits);
                        NetworkSchema.AddStatsToFieldVector3(field, vx, vy, vz, 0, 0, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }


            case NetworkSchema.FieldType.Quaternion: {
                // TODO : Figure out what to do with quaternions
                uint vx = inputData[index];
                uint bx = baselineData[index];
                index++;

                uint vy = inputData[index];
                uint by = baselineData[index];
                index++;

                uint vz = inputData[index];
                uint bz = baselineData[index];
                index++;

                uint vw = inputData[index];
                uint bw = baselineData[index];
                index++;

                if (notPredicted)
                {
                    if (field.delta)
                    {
                        output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0);
                        output.WritePackedUIntDelta(vy, by, fieldStartContext + 1);
                        output.WritePackedUIntDelta(vz, bz, fieldStartContext + 2);
                        output.WritePackedUIntDelta(vw, bw, fieldStartContext + 3);
                        NetworkSchema.AddStatsToFieldQuaternion(field, vx, vy, vz, vw, bx, by, bz, bw, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        output.WriteRawBits(vx, field.bits);
                        output.WriteRawBits(vy, field.bits);
                        output.WriteRawBits(vz, field.bits);
                        output.WriteRawBits(vw, field.bits);
                        NetworkSchema.AddStatsToFieldQuaternion(field, vx, vy, vz, vw, 0, 0, 0, 0, output.GetBitPosition2() - startBitPosition);
                    }
                }
                break;
            }


            case NetworkSchema.FieldType.String:
            case NetworkSchema.FieldType.ByteArray: {
                uint valueLength = inputData[index];
                index++;

                if (notPredicted)
                {
                    output.WritePackedUInt(valueLength, fieldStartContext);
                    byte *bytes = (byte *)(inputData + index);
                    output.WriteRawBytes(bytes, (int)valueLength);

                    if (field.fieldType == NetworkSchema.FieldType.String)
                    {
                        NetworkSchema.AddStatsToFieldString(field, bytes, (int)valueLength, output.GetBitPosition2() - startBitPosition);
                    }
                    else
                    {
                        NetworkSchema.AddStatsToFieldByteArray(field, bytes, (int)valueLength, output.GetBitPosition2() - startBitPosition);
                    }
                }
                index += field.arraySize / 4;
            }
            break;
            }
        }
    }
Esempio n. 15
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Network);

            Task.Run(() =>
            {
                FindViewById <TextView>(Resource.Id.textView1).Text = "Host Name: " + NetworkUtils.GetHostName();
            });
            FindViewById <TextView>(Resource.Id.textView2).Text = "IP: " + NetworkUtils.GetIPAddress();
            FindViewById <TextView>(Resource.Id.textView3).Text = "Mac eth: " + NetworkUtils.GetMacAddress("eth0");
            FindViewById <TextView>(Resource.Id.textView4).Text = "Mac wlan: " + NetworkUtils.GetMacAddress("wlan0");
            FindViewById <TextView>(Resource.Id.textView5).Text = "Mac null: " + NetworkUtils.GetMacAddress();
            var interfaces = string.Empty;

            foreach (var inter in NetworkUtils.GetAllNetworkInterfaces())
            {
                interfaces += inter.NetworkInterface + ", ";
            }
            FindViewById <TextView>(Resource.Id.textView6).Text = "Interfaces: " + interfaces;
        }
Esempio n. 16
0
        public void Connect(string serverAddress, string port)
        {
            try
            {
                if (!wsDict.ContainsKey("ws://" + serverAddress + ":" + port + "/Blockchain"))
                {
                    WebSocket ws = new WebSocket($"ws://" + serverAddress + ":" + port + "/Blockchain");

                    // Remove StackTrace
                    //   ws.Log.Output = (_, __) => { };

                    // Listen messages from server
                    ws.OnMessage += (sender, e) =>
                    {
                        if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_verification"))
                        {
                            SaveTheVerificationAnswer(NetworkUtils.SplitPacket(e.Data, 1), NetworkUtils.SplitPacket(e.Data, 2));
                        }
                        if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_block"))
                        {
                            SaveTheAddBlockVerificationAnswer(NetworkUtils.SplitPacket(e.Data, 1));
                        }
                        if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_chain"))
                        {
                            sendNewChainMethod(JsonConvert.DeserializeObject <List <Block> >(NetworkUtils.SplitPacket(e.Data, 1)));
                        }
                    };

                    // Listen connection and delete it from dictionary if connection is closed.
                    ws.OnClose += (sender, e) => {
                        WebSocket SenderWebSocket = (WebSocket)sender;
                        Close(SenderWebSocket.Url.ToString());
                    };

                    // Show message when error occured.
                    ws.OnError += (sender, e) => {
                    };

                    ws.Connect();
                    ws.Send("packet_connect" + NetworkUtils.packetSeparator + clientIpAddress + NetworkUtils.packetSeparator + clientPort);
                    wsDict.Add(ws.Url.ToString(), ws);
                }
            } catch (Exception ex)
            {
            }
        }
 private void Initialize()
 {
     client       = new WlanClient();
     networkUtils = new NetworkUtils();
     InitializePingSender();
 }
        private static void FilterRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;

            if ((app == null) || (app.Context == null) || (app.Context.Items == null))
            {
                return;
            }
            var request = app.Context.Request;

            if (!Initialize.ProcessHttpModule(request, true, true))
            {
                return;
            }

            //Carry out first time initialization tasks
            Initialize.Init(app);

            //only do this if we havn't already attempted an install.  This prevents PreSendRequestHeaders from
            //trying to add this item way to late.  We only want the first run through to do anything.
            //also, we use the context to store whether or not we've attempted an add, as it's thread-safe and
            //scoped to the request.  An instance of this module can service multiple requests at the same time,
            //so we cannot use a member variable.
            if (!app.Context.Items.Contains(InstalledKey))
            {
                //log the install attempt in the HttpContext
                //must do this first as several IF statements
                //below skip full processing of this method
                app.Context.Items.Add(InstalledKey, true);
                var settings = RequestFilterSettings.GetSettings();
                if ((settings == null || settings.Rules.Count == 0 || !settings.Enabled))
                {
                    return;
                }
                foreach (var rule in settings.Rules)
                {
                    //Added ability to determine the specific value types for addresses
                    //this check was necessary so that your rule could deal with IPv4 or IPv6
                    //To use this mode, add ":IPv4" or ":IPv6" to your servervariable name.
                    var varArray = rule.ServerVariable.Split(':');
                    var varVal   = request.ServerVariables[varArray[0]];
                    if (varArray[0].EndsWith("_ADDR", StringComparison.InvariantCultureIgnoreCase) && varArray.Length > 1)
                    {
                        switch (varArray[1])
                        {
                        case "IPv4":
                            varVal = NetworkUtils.GetAddress(varVal, AddressType.IPv4);
                            break;

                        case "IPv6":
                            varVal = NetworkUtils.GetAddress(varVal, AddressType.IPv4);
                            break;
                        }
                    }
                    if ((!string.IsNullOrEmpty(varVal)))
                    {
                        if ((rule.Matches(varVal)))
                        {
                            rule.Execute();
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        // Returns a random new potential neighbor. Returns null if no new neighbor is found.
        public static string scanForNeighbor()
        {
            string connectToAddress = null;

            // Find only masternodes
            while (connectToAddress == null)
            {
                bool   addr_valid = true;
                string address    = PeerStorage.getRandomMasterNodeAddress();

                if (address == "")
                {
                    break;
                }

                // Next, check if we're connecting to a self address of this node
                string[] server = address.Split(':');

                if (server.Length < 2)
                {
                    break;
                }

                // Resolve the hostname first
                string resolved_server_name           = NetworkUtils.resolveHostname(server[0]);
                string resolved_server_name_with_port = resolved_server_name + ":" + server[1];

                // Check if we are already connected to this address
                lock (networkClients)
                {
                    foreach (NetworkClient client in networkClients)
                    {
                        if (client.getFullAddress(true).Equals(resolved_server_name_with_port, StringComparison.Ordinal))
                        {
                            // Address is already in the client list
                            addr_valid = false;
                            break;
                        }
                    }
                }

                // Check if node is already in the server list
                string[] connectedClients = NetworkServer.getConnectedClients(true);
                for (int i = 0; i < connectedClients.Length; i++)
                {
                    if (connectedClients[i].Equals(resolved_server_name_with_port, StringComparison.Ordinal))
                    {
                        // Address is already in the client list
                        addr_valid = false;
                        break;
                    }
                }

                if (addr_valid == false)
                {
                    continue;
                }

                // Check against connecting clients list as well
                lock (connectingClients)
                {
                    foreach (string client in connectingClients)
                    {
                        if (resolved_server_name_with_port.Equals(client, StringComparison.Ordinal))
                        {
                            // Address is already in the connecting client list
                            addr_valid = false;
                            break;
                        }
                    }
                }

                if (addr_valid == false)
                {
                    continue;
                }

                // Get all self addresses and run through them
                List <string> self_addresses = CoreNetworkUtils.GetAllLocalIPAddresses();
                foreach (string self_address in self_addresses)
                {
                    // Don't connect to self
                    if (resolved_server_name.Equals(self_address, StringComparison.Ordinal))
                    {
                        if (server[1].Equals(string.Format("{0}", Config.serverPort), StringComparison.Ordinal))
                        {
                            addr_valid = false;
                        }
                    }
                }

                // If the address is valid, add it to the candidates
                if (addr_valid)
                {
                    connectToAddress = address;
                }
            }

            return(connectToAddress);
        }
Esempio n. 20
0
    private void _StartGame(Player player, byte[] data)
    {
        //结果
        StartGame result = new StartGame();

        StartGame receive = NetworkUtils.Deserialize <StartGame>(data);

        //逻辑检测(有该房间)
        if (Server.RoomDict.ContainsKey(receive.RoomId))
        {
            //玩家模式开始游戏
            if (Server.RoomDict[receive.RoomId].playerList.Contains(player) &&
                Server.RoomDict[receive.RoomId].playerList.Count == Room.MAX_PLAYER_AMOUNT)
            {
                //游戏开始
                Server.RoomDict[receive.RoomId].State = Room.RoomState.Gaming;

                Console.WriteLine($"玩家:{player.Name}开始游戏成功");

                //遍历该房间玩家
                foreach (var each in Server.RoomDict[receive.RoomId].playerList)
                {
                    //开始游戏者先手
                    if (each == player)
                    {
                        result.Suc   = true;
                        result.First = true;
                        data         = NetworkUtils.Serialize(result);
                        each.Send(MessageType.StartGame, data);
                    }
                    else
                    {
                        result.Suc   = true;
                        result.First = false;
                        data         = NetworkUtils.Serialize(result);
                        each.Send(MessageType.StartGame, data);
                    }
                }

                //如果有观察者
                if (Server.RoomDict[receive.RoomId].OBs.Count > 0)
                {
                    result.Suc   = true;
                    result.Watch = true;
                    data         = NetworkUtils.Serialize(result);
                    //向观战者发送信息
                    foreach (var each in Server.RoomDict[receive.RoomId].OBs)
                    {
                        each.Send(MessageType.StartGame, data);
                    }
                }
            }
            else
            {
                Console.WriteLine($"玩家:{player.Name}开始游戏失败");
                //向玩家发送失败操作结果
                data = NetworkUtils.Serialize(result);
                player.Send(MessageType.StartGame, data);
            }
        }
        else
        {
            Console.WriteLine($"玩家:{player.Name}开始游戏失败");
            //向玩家发送失败操作结果
            data = NetworkUtils.Serialize(result);
            player.Send(MessageType.StartGame, data);
        }
    }
Esempio n. 21
0
        public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            Hashtable requestData = (Hashtable)request.Params[0];

            if (m_Proxy && request.Params[3] != null)
            {
                IPEndPoint ep = NetworkUtils.GetClientIPFromXFF((string)request.Params[3]);
                if (ep != null)
                {
                    // Bang!
                    remoteClient = ep;
                }
            }

            if (requestData != null)
            {
                if (((requestData.ContainsKey("first") && requestData["first"] != null &&
                      requestData.ContainsKey("last") && requestData["last"] != null) ||
                     requestData.ContainsKey("username") && requestData["username"] != null) &&
                    ((requestData.ContainsKey("passwd") && requestData["passwd"] != null) ||
                     (requestData.ContainsKey("web_login_key") && requestData["web_login_key"] != null)))
                {
                    string first    = requestData.ContainsKey("first") ? requestData["first"].ToString() : "";
                    string last     = requestData.ContainsKey("last") ? requestData["last"].ToString() : "";
                    string name     = requestData.ContainsKey("username") ? requestData["username"].ToString() : "";
                    string passwd   = "";
                    string authType = "UserAccount";
                    if (!requestData.ContainsKey("web_login_key"))
                    {
                        passwd = requestData["passwd"].ToString();
                    }
                    else
                    {
                        passwd   = requestData["web_login_key"].ToString();
                        authType = "WebLoginKey";
                    }
                    string startLocation = string.Empty;
                    UUID   scopeID       = UUID.Zero;
                    if (requestData["scope_id"] != null)
                    {
                        scopeID = new UUID(requestData["scope_id"].ToString());
                    }
                    if (requestData.ContainsKey("start"))
                    {
                        startLocation = requestData["start"].ToString();
                    }

                    string clientVersion = "Unknown";
                    if (requestData.Contains("version") && requestData["version"] != null)
                    {
                        clientVersion = requestData["version"].ToString();
                    }

                    //MAC BANNING START
                    string mac = (string)requestData["mac"];
                    if (mac == "")
                    {
                        return(FailedXMLRPCResponse("Bad Viewer Connection."));
                    }

                    string channel = "Unknown";
                    if (requestData.Contains("channel") && requestData["channel"] != null)
                    {
                        channel = requestData["channel"].ToString();
                    }

                    if (channel == "")
                    {
                        return(FailedXMLRPCResponse("Bad Viewer Connection."));
                    }

                    string id0 = "Unknown";
                    if (requestData.Contains("id0") && requestData["id0"] != null)
                    {
                        id0 = requestData["id0"].ToString();
                    }

                    LoginResponse reply = null;


                    string loginName = (name == "" || name == null) ? first + " " + last : name;
                    reply = m_LocalService.Login(UUID.Zero, loginName, "UserAccount", passwd, startLocation, scopeID, clientVersion, channel,
                                                 mac, id0, remoteClient, requestData);
                    XmlRpcResponse response = new XmlRpcResponse {
                        Value = reply.ToHashtable()
                    };
                    return(response);
                }
            }

            return(FailedXMLRPCResponse());
        }
Esempio n. 22
0
    private void _PlayChess(Player player, byte[] data)
    {
        //结果
        PlayChess result = new PlayChess();

        PlayChess receive = NetworkUtils.Deserialize <PlayChess>(data);

        //逻辑检测(有该房间)
        if (Server.RoomDict.ContainsKey(receive.RoomId))
        {
            //该房间中的玩家有资格下棋
            if (Server.RoomDict[receive.RoomId].playerList.Contains(player) &&
                Server.RoomDict[receive.RoomId].State == Room.RoomState.Gaming &&
                receive.Chess == Server.RoomDict[receive.RoomId].gamePlay.Turn)
            {
                //判断结果
                Chess chess = Server.RoomDict[receive.RoomId].gamePlay.Calculate(receive.X, receive.Y);
                //检测操作:如果游戏结束
                bool over = _ChessResult(chess, result);

                if (result.Suc)
                {
                    result.Chess = receive.Chess;
                    result.X     = receive.X;
                    result.Y     = receive.Y;

                    Console.WriteLine($"玩家:{player.Name}下棋成功");

                    //向该房间中玩家与观察者广播结果
                    data = NetworkUtils.Serialize(result);
                    foreach (var each in Server.RoomDict[receive.RoomId].playerList)
                    {
                        each.Send(MessageType.PlayChess, data);
                    }
                    foreach (var each in Server.RoomDict[receive.RoomId].OBs)
                    {
                        each.Send(MessageType.PlayChess, data);
                    }

                    if (over)
                    {
                        Console.WriteLine("游戏结束,房间关闭");
                        Server.RoomDict[receive.RoomId].Close();
                    }
                }
                else
                {
                    Console.WriteLine($"玩家:{player.Name}下棋失败");
                    //向玩家发送失败操作结果
                    data = NetworkUtils.Serialize(result);
                    player.Send(MessageType.PlayChess, data);
                }
            }
            else
            {
                Console.WriteLine($"玩家:{player.Name}下棋失败");
                //向玩家发送失败操作结果
                data = NetworkUtils.Serialize(result);
                player.Send(MessageType.PlayChess, data);
            }
        }
        else
        {
            Console.WriteLine($"玩家:{player.Name}下棋失败");
            //向玩家发送失败操作结果
            data = NetworkUtils.Serialize(result);
            player.Send(MessageType.PlayChess, data);
        }
    }
Esempio n. 23
0
        // Connects to a specified node, with the syntax host:port
        // Returns the connected stream client
        // Returns null if connection failed
        public static NetworkClient connectTo(string host, byte[] wallet_address)
        {
            if (host == null || host.Length < 3)
            {
                Logging.error(String.Format("Invalid host address {0}", host));
                return(null);
            }

            string[] server = host.Split(':');
            if (server.Count() < 2)
            {
                Logging.warn(string.Format("Cannot connect to invalid hostname: {0}", host));
                return(null);
            }

            // Resolve the hostname first
            string resolved_server_name = NetworkUtils.resolveHostname(server[0]);

            // Skip hostnames we can't resolve
            if (resolved_server_name.Length < 1)
            {
                Logging.warn(string.Format("Cannot resolve IP for {0}, skipping connection.", server[0]));
                return(null);
            }

            string resolved_host = string.Format("{0}:{1}", resolved_server_name, server[1]);

            if (NetworkServer.isRunning())
            {
                // Verify against the publicly disclosed ip
                // Don't connect to self
                if (resolved_server_name.Equals(IxianHandler.publicIP, StringComparison.Ordinal))
                {
                    if (server[1].Equals(string.Format("{0}", IxianHandler.publicPort), StringComparison.Ordinal))
                    {
                        Logging.info(string.Format("Skipping connection to public self seed node {0}", host));
                        return(null);
                    }
                }

                // Get all self addresses and run through them
                List <string> self_addresses = CoreNetworkUtils.GetAllLocalIPAddresses();
                foreach (string self_address in self_addresses)
                {
                    // Don't connect to self
                    if (resolved_server_name.Equals(self_address, StringComparison.Ordinal))
                    {
                        if (server[1].Equals(string.Format("{0}", IxianHandler.publicPort), StringComparison.Ordinal))
                        {
                            Logging.info(string.Format("Skipping connection to self seed node {0}", host));
                            return(null);
                        }
                    }
                }
            }

            lock (connectingClients)
            {
                foreach (string client in connectingClients)
                {
                    if (resolved_host.Equals(client, StringComparison.Ordinal))
                    {
                        // We're already connecting to this client
                        return(null);
                    }
                }

                // The the client to the connecting clients list
                connectingClients.Add(resolved_host);
            }

            // Check if node is already in the client list
            lock (streamClients)
            {
                foreach (NetworkClient client in streamClients)
                {
                    if (client.getFullAddress(true).Equals(resolved_host, StringComparison.Ordinal))
                    {
                        // Address is already in the client list
                        return(null);
                    }
                }
            }


            // Connect to the specified node
            NetworkClient new_client = new NetworkClient();
            // Recompose the connection address from the resolved IP and the original port
            bool result = new_client.connectToServer(resolved_server_name, Convert.ToInt32(server[1]), wallet_address);

            // Add this node to the client list if connection was successfull
            if (result == true)
            {
                // Add this node to the client list
                lock (streamClients)
                {
                    streamClients.Add(new_client);
                }
            }

            // Remove this node from the connecting clients list
            lock (connectingClients)
            {
                connectingClients.Remove(resolved_host);
            }

            return(new_client);
        }
Esempio n. 24
0
        public static byte[] SendPacket(String username, String password, byte[] MD5A, byte[] MD5B, byte[] IP)
        {
            Packet packet = new Packet();

            try
            {
                // 构建数据包
                packet += new byte[]
                {
                    (byte)Code.LoginAuth, 0x01,
                    0x00, (byte)(username.Length + 20)
                };
                // MD5A
                packet += MD5A;
                // 用户名
                packet += NetworkUtils.GetUsernameB(username);
                // ControlCheckStatus, AdapterNum
                packet += new byte[] {
                    0x20, 0x04
                };
                // Mac xor MD5A
                packet += PacketUtils.MACXorMD5A(Constants.MAC, MD5A);
                // MD5B
                packet += MD5B;
                // NICCount
                packet += (byte)0x01;
                // 本机IP地址
                packet += IP;
                // 其他填空IP地址
                packet += new byte[] {
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00
                };
                // MD5C
                packet += PacketUtils.MD5C(packet);
                // IPDog
                packet += new byte[] {
                    0x01,
                    0x00, 0x00, 0x00, 0x00
                };
                packet += NetworkUtils.GetHostNameB();
                packet += new byte[]
                {
                    // DNS
                    0x0a, 0x0a, 0x0a, 0x0a,
                    // DHCP
                    0x00, 0x00, 0x00, 0x00,
                    // 备用 DNS
                    0x08, 0x08, 0x08, 0x08,
                    // WINSIP1
                    0x00, 0x00, 0x00, 0x00,
                    // WINSIP2
                    0x00, 0x00, 0x00, 0x00,
                    // OSVersionInfoSize
                    0x94, 0x00, 0x00, 0x00,
                    // OS major
                    0x06, 0x00, 0x00, 0x00,
                    // OS minor
                    0x02, 0x00, 0x00, 0x00,
                    // OS build
                    0xf0, 0x23, 0x00, 0x00,
                    // PlatformID
                    0x02, 0x00, 0x00, 0x00,
                    // servicepack
                    0x44, 0x72, 0x43, 0x4f,
                    0x4d, 0x00, 0xcf, 0x07,
                    0x6a, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x31, 0x63, 0x32, 0x31,
                    0x30, 0x63, 0x39, 0x39,
                    0x35, 0x38, 0x35, 0x66,
                    0x64, 0x32, 0x32, 0x61,
                    0x64, 0x30, 0x33, 0x64,
                    0x33, 0x35, 0x63, 0x39,
                    0x35, 0x36, 0x39, 0x31,
                    0x31, 0x61, 0x65, 0x65,
                    0x63, 0x31, 0x65, 0x62,
                    0x34, 0x34, 0x39, 0x62,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    // ClientVerInfoAndInternetMode
                    0x6a, 0x00, 0x00,
                    // 密码长度
                    (byte)(password.Length > 16 ? 16 : password.Length)
                };
                // ROR
                packet += PacketUtils.ROR(MD5A, password);
                // AuthExtDataOption
                packet += new byte[] {
                    0x02, 0x0c
                };
                // Checksum
                packet += PacketUtils.CheckSum(packet);
                // AutoLogout(?), Broadcast mode(?)
                packet += new byte[] {
                    0x00, 0x00
                };
                // MAC
                packet += Constants.MAC;
                packet += new byte[] {
                    PacketUtils.RandomByte(), PacketUtils.RandomByte()
                };
            }
            catch (Exception e)
            {
                Constants.logger.log(e.Message);
            }
            // Log
            Constants.logger.log("Preparing for LoginAuth Packet:\n" + BitConverter.ToString(packet));
            return(NetworkUtils.SendUDPDatagram(packet));
        }
Esempio n. 25
0
 private void _GameInfo(Player player, byte[] data)
 {
     GameInfo result  = new GameInfo();
     GameInfo receive = NetworkUtils.Deserialize <GameInfo>(data);
 }
Esempio n. 26
0
        void ReadSnapshot <TInputStream>(int sequence, ref TInputStream input) where TInputStream : NetworkCompression.IInputStream
        {
            //input.SetStatsType(NetworkCompressionReader.Type.SnapshotSchema);
            counters.snapshotsIn++;

            // Snapshot may be delta compressed against one or more baselines
            // Baselines are indicated by sequence number of the package it was in
            var baseSequence = (int)input.ReadPackedIntDelta(sequence - 1, NetworkConfig.baseSequenceContext);

            bool enableNetworkPrediction = input.ReadRawBits(1) != 0;
            bool enableHashing           = input.ReadRawBits(1) != 0;

            int baseSequence1 = 0;
            int baseSequence2 = 0;

            if (enableNetworkPrediction)
            {
                baseSequence1 = (int)input.ReadPackedIntDelta(baseSequence - 1, NetworkConfig.baseSequence1Context);
                baseSequence2 = (int)input.ReadPackedIntDelta(baseSequence1 - 1, NetworkConfig.baseSequence2Context);
            }

            if (clientDebug.IntValue > 2)
            {
                if (enableNetworkPrediction)
                {
                    GameDebug.Log((baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "(" + sequence + ")  " + baseSequence + " - " + baseSequence1 + " - " + baseSequence2);
                }
                else
                {
                    GameDebug.Log((baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "(" + sequence + ")  " + baseSequence);
                }
            }

            if (baseSequence == 0)
            {
                counters.fullSnapshotsIn++;
            }

            GameDebug.Assert(baseSequence == 0 ||
                             (sequence > baseSequence && sequence - baseSequence < NetworkConfig.snapshotDeltaCacheSize), "Attempting snapshot encoding with invalid baseline: {0}:{1}", sequence, baseSequence);

            var snapshotInfo = snapshots.Acquire(sequence);

            snapshotInfo.serverTime = (int)input.ReadPackedIntDelta(baseSequence != 0 ? snapshots[baseSequence].serverTime : 0, NetworkConfig.serverTimeContext);

            var temp = (int)input.ReadRawBits(8);

            serverSimTime = temp * 0.1f;

            // Only update time if received in-order..
            // TODO consider dropping out of order snapshots
            // TODO detecting out-of-order on pack sequences
            if (snapshotInfo.serverTime > serverTime)
            {
                serverTime           = snapshotInfo.serverTime;
                snapshotReceivedTime = NetworkUtils.stopwatch.ElapsedMilliseconds;
            }
            else
            {
                GameDebug.Log(string.Format("NetworkClient. Dropping out of order snaphot. Server time:{0} snapshot time:{1}", serverTime, snapshotInfo.serverTime));
            }

            // Read schemas
            var schemaCount = input.ReadPackedUInt(NetworkConfig.schemaCountContext);

            for (int schemaIndex = 0; schemaIndex < schemaCount; ++schemaIndex)
            {
                var typeId = (ushort)input.ReadPackedUInt(NetworkConfig.schemaTypeIdContext);

                var entityType = new EntityTypeInfo()
                {
                    typeId = typeId
                };
                entityType.schema   = NetworkSchema.ReadSchema(ref input);
                entityType.baseline = new byte[NetworkConfig.maxEntitySnapshotDataSize];
                NetworkSchema.CopyFieldsToBuffer(entityType.schema, ref input, entityType.baseline);

                if (!entityTypes.ContainsKey(typeId))
                {
                    entityTypes.Add(typeId, entityType);
                }
            }

            // Remove any despawning entities that belong to older base sequences
            for (int i = 0; i < entities.Count; i++)
            {
                var e = entities[i];
                if (e.type == null)
                {
                    continue;
                }
                if (e.despawnSequence > 0 && e.despawnSequence <= baseSequence)
                {
                    e.Reset();
                }
            }

            // Read new spawns
            m_TempSpawnList.Clear();
            var previousId = 1;
            var spawnCount = input.ReadPackedUInt(NetworkConfig.spawnCountContext);

            for (var spawnIndex = 0; spawnIndex < spawnCount; ++spawnIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                // Register the entity
                var typeId = (ushort)input.ReadPackedUInt(NetworkConfig.spawnTypeIdContext);    //TODO: use another encoding
                GameDebug.Assert(entityTypes.ContainsKey(typeId), "Spawn request with unknown type id {0}", typeId);

                byte fieldMask = (byte)input.ReadRawBits(8);

                // Check if we already registered the entity since we can receive spawn information
                // in several snapshots before the client has ack a package containing the spawn

                // TODO (petera) need an max entity id for safety
                while (id >= entities.Count)
                {
                    entities.Add(new EntityInfo());
                }

                if (entities[id].type == null)
                {
                    var e = entities[id];
                    e.type      = entityTypes[typeId];
                    e.fieldMask = fieldMask;
                    spawns.Add(id);
                }

                m_TempSpawnList.Add(id);
            }

            // Read despawns
            var despawnCount = input.ReadPackedUInt(NetworkConfig.despawnCountContext);

            for (var despawnIndex = 0; despawnIndex < despawnCount; ++despawnIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                // we may see despawns many times, only handle if we still have the entity
                GameDebug.Assert(id < entities.Count, "Getting despawn for id {0} but we only know about entities up to {1}", id, entities.Count);
                if (entities[id].type == null)
                {
                    continue;
                }

                var entity = entities[id];

                // Already in the process of being despawned. This happens with same-snapshot spawn/despawn cases
                if (entity.despawnSequence > 0)
                {
                    continue;
                }

                // If we are spawning and despawning in same snapshot, delay actual deletion of
                // entity as we need it around to be able to read the update part of the snapshot
                if (m_TempSpawnList.Contains(id))
                {
                    entity.despawnSequence = sequence; // keep until baseSequence >= despawnSequence
                }
                else
                {
                    entity.Reset(); // otherwise remove right away; no further updates coming, not even in this snap
                }
                // Add to despawns list so we can request despawn from game later
                GameDebug.Assert(!despawns.Contains(id), "Double despawn in same snaphot? {0}", id);
                despawns.Add(id);
            }

            // Predict all active entities
            for (var id = 0; id < entities.Count; id++)
            {
                var info = entities[id];
                if (info.type == null)
                {
                    continue;
                }

                // NOTE : As long as the server haven't gotten the spawn acked, it will keep sending
                // delta relative to 0, so we need to check if the entity was in the spawn list to determine
                // if the delta is relative to the last update or not

                int baseline0Time = 0;

                byte[] baseline0 = info.type.baseline;
                GameDebug.Assert(baseline0 != null, "Unable to find schema baseline for type {0}", info.type.typeId);

                if (baseSequence != 0 && !m_TempSpawnList.Contains(id))
                {
                    baseline0 = info.baselines.FindMax(baseSequence);
                    GameDebug.Assert(baseline0 != null, "Unable to find baseline for seq {0} for id {1}", baseSequence, id);
                    baseline0Time = snapshots[baseSequence].serverTime;
                }

                if (enableNetworkPrediction)
                {
                    uint num_baselines = 1; // 1 because either we have schema baseline or we have a real baseline
                    int  baseline1Time = 0;
                    int  baseline2Time = 0;

                    byte[] baseline1 = null;
                    byte[] baseline2 = null;
                    if (baseSequence1 != baseSequence)
                    {
                        baseline1 = info.baselines.FindMax(baseSequence1);
                        if (baseline1 != null)
                        {
                            num_baselines = 2;
                            baseline1Time = snapshots[baseSequence1].serverTime;
                        }
                        if (baseSequence2 != baseSequence1)
                        {
                            baseline2 = info.baselines.FindMax(baseSequence2);
                            if (baseline2 != null)
                            {
                                num_baselines = 3;
                                baseline2Time = snapshots[baseSequence2].serverTime;
                            }
                        }
                    }

                    // TODO (petera) are these clears needed?
                    for (int i = 0, c = info.fieldsChangedPrediction.Length; i < c; ++i)
                    {
                        info.fieldsChangedPrediction[i] = 0;
                    }
                    for (int i = 0; i < NetworkConfig.maxEntitySnapshotDataSize; i++)
                    {
                        info.prediction[i] = 0;
                    }

                    NetworkPrediction.PredictSnapshot(info.prediction, info.fieldsChangedPrediction, info.type.schema, num_baselines, (uint)baseline0Time, baseline0, (uint)baseline1Time, baseline1, (uint)baseline2Time, baseline2, (uint)snapshotInfo.serverTime, info.fieldMask);
                }
                else
                {
                    var f = info.fieldsChangedPrediction;
                    for (var i = 0; i < f.Length; ++i)
                    {
                        f[i] = 0;
                    }
                    NetworkUtils.MemCopy(baseline0, 0, info.prediction, 0, info.type.schema.GetByteSize());
                }
            }

            // Read updates
            var updateCount = input.ReadPackedUInt(NetworkConfig.updateCountContext);

            for (var updateIndex = 0; updateIndex < updateCount; ++updateIndex)
            {
                var id = (int)input.ReadPackedIntDelta(previousId, NetworkConfig.idContext);
                previousId = id;

                var info = entities[id];

                uint hash = 0;
                // Copy prediction to temp buffer as we now overwrite info.prediction with fully unpacked
                // state by applying incoming delta to prediction.
                NetworkUtils.MemCopy(info.prediction, 0, tempSnapshotBuffer, 0, info.type.schema.GetByteSize());

                DeltaReader.Read(ref input, info.type.schema, info.prediction, tempSnapshotBuffer, info.fieldsChangedPrediction, info.fieldMask, ref hash);
                if (enableHashing)
                {
                    uint hashCheck = input.ReadRawBits(32);

                    if (hash != hashCheck)
                    {
                        GameDebug.Log("Hash check fail for entity " + id);
                        if (enableNetworkPrediction)
                        {
                            GameDebug.Assert(false, "Snapshot (" + snapshotInfo.serverTime + ") " + (baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "  " + baseSequence + " - " + baseSequence1 + " - " + baseSequence2 + ". Sche: " + schemaCount + " Spwns: " + spawnCount + " Desp: " + despawnCount + " Upd: " + updateCount);
                        }
                        else
                        {
                            GameDebug.Assert(false, "Snapshot (" + snapshotInfo.serverTime + ") " + (baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "  " + baseSequence + ". Sche: " + schemaCount + " Spwns: " + spawnCount + " Desp: " + despawnCount + " Upd: " + updateCount);
                        }
                    }
                }
            }

            uint snapshotHash = 0; // sum of hash for all (updated or not) entity snapshots
            uint numEnts      = 0;

            for (int id = 0; id < entities.Count; id++)
            {
                var info = entities[id];
                if (info.type == null)
                {
                    continue;
                }

                // Skip despawned that have not also been spawned in this snapshot
                if (info.despawnSequence > 0 && !spawns.Contains(id))
                {
                    continue;
                }

                // If just spawned or if new snapshot is different from the last we deserialized,
                // we need to deserialize. Otherwise just ignore; no reason to deserialize the same
                // values again
                int schemaSize = info.type.schema.GetByteSize();
                if (info.baselines.GetSize() == 0 || NetworkUtils.MemCmp(info.prediction, 0, info.lastUpdate, 0, schemaSize) != 0)
                {
                    var data = info.baselines.Insert(sequence);
                    NetworkUtils.MemCopy(info.prediction, 0, data, 0, schemaSize);
                    if (sequence > info.lastUpdateSequence)
                    {
                        if (!updates.Contains(id))
                        {
                            updates.Add(id);
                        }

                        NetworkUtils.MemCopy(info.prediction, 0, info.lastUpdate, 0, schemaSize);
                        info.lastUpdateSequence = sequence;
                    }
                }

                if (enableHashing && info.despawnSequence == 0)
                {
                    snapshotHash += NetworkUtils.SimpleHash(info.prediction, schemaSize);
                    numEnts++;
                }
            }


            if (clientDebug.IntValue > 1)
            {
                if (clientDebug.IntValue > 2 || spawnCount > 0 || despawnCount > 0 || schemaCount > 0 || baseSequence == 0)
                {
                    string entityIds = "";
                    for (var i = 0; i < entities.Count; i++)
                    {
                        entityIds += entities[i].type == null ? ",-" : ("," + i);
                    }
                    string despawnIds = string.Join(",", despawns);
                    string spawnIds   = string.Join(",", spawns);
                    string updateIds  = string.Join(",", updates);

                    if (enableNetworkPrediction)
                    {
                        GameDebug.Log((baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "  " + baseSequence + " - " + baseSequence1 + " - " + baseSequence2 + ". Sche: " + schemaCount + " Spwns: " + spawnCount + "(" + spawnIds + ") Desp: " + despawnCount + "(" + despawnIds + ") Upd: " + updateCount + "(" + updateIds + ")  Ents:" + entities.Count + " EntityIds:" + entityIds);
                    }
                    else
                    {
                        GameDebug.Log((baseSequence > 0 ? "Snap [BL]" : "Snap [  ]") + "  " + baseSequence + ". Sche: " + schemaCount + " Spwns: " + spawnCount + "(" + spawnIds + ") Desp: " + despawnCount + "(" + despawnIds + ") Upd: " + updateCount + "(" + updateIds + ")  Ents:" + entities.Count + " EntityIds:" + entityIds);
                    }
                }
            }

            if (enableHashing)
            {
                uint numEntsCheck = input.ReadRawBits(32);
                if (numEntsCheck != numEnts)
                {
                    GameDebug.Log("SYNC PROBLEM: server num ents: " + numEntsCheck + " us:" + numEnts);
                    GameDebug.Assert(false);
                }
            }
        }
Esempio n. 27
0
 private void Lag(float currentPing)
 {
     NetworkUtils.GetAveragePing(currentPing, out _ping, _pings);
 }
Esempio n. 28
0
 public float ReadFloat()
 {
     ValidateSchema(NetworkSchema.FieldType.Float, 32, false);
     return(NetworkUtils.UInt32ToFloat(m_Input[m_Position++]));
 }
Esempio n. 29
0
 public bool IsGamePaused()
 {
     return(!NetworkUtils.IsDedicated() && PauseHook.IsPaused);
 }
Esempio n. 30
0
 public void WriteFloat(string name, float value)
 {
     ValidateOrGenerateSchema(name, NetworkSchema.FieldType.Float, 32, false);
     m_Output.WriteUInt32(NetworkUtils.FloatToUInt32(value));
 }