/// <summary>
        /// Unregisters any previously registered program index map info and registers the provided map info.
        /// </summary>
        /// <param name="programIndexMapInfo">A buffer containing the program map info to register.</param>
        /// <param name="programCount">The number of programs to register. The provided buffer must be
        /// large enough to hold this many <see cref="ProgramIndexMapInfo"/> entries.</param>
        /// <returns><see cref="Result.Success"/>: The operation was successful.<br/>
        /// <see cref="ResultFs.PermissionDenied"/>: Insufficient permissions.<br/>
        /// <see cref="ResultFs.InvalidSize"/>: The buffer was too small to hold the specified
        /// number of <see cref="ProgramIndexMapInfo"/> entries.</returns>
        public Result RegisterProgramIndexMapInfo(InBuffer programIndexMapInfo, int programCount)
        {
            // Verify the caller's permissions
            Result rc = GetProgramInfo(out ProgramInfo programInfo, ProcessId);

            if (rc.IsFailure())
            {
                return(rc);
            }

            if (!programInfo.AccessControl.CanCall(OperationType.RegisterProgramIndexMapInfo))
            {
                return(ResultFs.PermissionDenied.Log());
            }

            // Return early if the program count is 0 so we leave any previously
            // registered entries as they were
            if (programCount == 0)
            {
                return(Result.Success);
            }

            // Verify that the provided buffer is large enough to hold "programCount" entries
            ReadOnlySpan <ProgramIndexMapInfo>
            mapInfo = MemoryMarshal.Cast <byte, ProgramIndexMapInfo>(programIndexMapInfo.Buffer);

            if (mapInfo.Length < programCount)
            {
                return(ResultFs.InvalidSize.Log());
            }

            // Register the map info
            return(ServiceImpl.RegisterProgramIndexMapInfo(mapInfo.Slice(0, programCount)));
        }
Exemple #2
0
        protected override void Check()
        {
            // Check file header
            if (InReader.ReadUInt64() != 0x4d4144464e455443)
            {
                throw new FileLoadException($"Failed to verify header of \"{InPath}\".");
            }

            // Skip ahead
            _ = InBuffer.Seek(2, SeekOrigin.Current);
        }
Exemple #3
0
        /// <returns><see cref="Result.Success"/>: The operation was successful.<br/>
        /// <see cref="ResultFs.InvalidArgument"/>: The process ID is already registered.<br/>
        /// <see cref="ResultFs.PermissionDenied"/>: Insufficient permissions.</returns>
        /// <inheritdoc cref="ProgramRegistryManager.RegisterProgram"/>
        public Result RegisterProgram(ulong processId, ProgramId programId, StorageId storageId,
                                      InBuffer accessControlData, InBuffer accessControlDescriptor)
        {
            if (!ProgramInfo.IsInitialProgram(_processId))
            {
                return(ResultFs.PermissionDenied.Log());
            }

            return(Globals.ServiceImpl.RegisterProgramInfo(processId, programId, storageId, accessControlData.Buffer,
                                                           accessControlDescriptor.Buffer));
        }
Exemple #4
0
        public Result OutputAccessLogToSdCard(InBuffer textBuffer)
        {
            Result rc = GetProgramInfo(out ProgramInfo programInfo);

            if (rc.IsFailure())
            {
                return(rc);
            }

            return(_serviceImpl.OutputAccessLogToSdCard(textBuffer.Buffer, programInfo.ProgramIdValue, _processId));
        }
        /// <summary>
        /// Берет фрагмент из очереди и начинает его обслуживание
        /// </summary>
        protected void StartService()
        {
            //Берем фрагмент из очереди
            var new_f = InBuffer.Take();

            //Направляем этот фрагмент на свободный обслуживающий прибор, определив время обслуживания
            new_f.TimeStartService = Info.GetCurentTime();
            new_f.TimeLeave        = new_f.TimeStartService + ServiceTime.NextValue();
            //Увеличиваем число поступивших на прибор требований
            NumberOfArrivedDemads++;
            //Добавление фрагмента на прибор
            ListOfFragments.Add(new Label(new_f.TimeLeave, NumberOfArrivedDemads), new_f);

            UpdateActionTime();
        }
        public Result Write(long offset, InBuffer source, long size, WriteOption option)
        {
            if (offset < 0)
            {
                return(ResultFs.InvalidOffset.Log());
            }

            if (source.Size < 0)
            {
                return(ResultFs.InvalidSize.Log());
            }

            // Note: Thread priority is temporarily increased when writing in FS

            return(BaseFile.Write(offset, source.Buffer.Slice(0, (int)size), option));
        }
        /// <summary>
        /// Unregisters any previously registered program index map info and registers the provided map info.
        /// </summary>
        /// <param name="fs">The <see cref="FileSystemClient"/> to use.</param>
        /// <param name="mapInfo">The program index map info entries to register.</param>
        /// <returns><see cref="Result.Success"/>: The operation was successful.<br/>
        /// <see cref="ResultFs.PermissionDenied"/>: Insufficient permissions.</returns>
        public static Result RegisterProgramIndexMapInfo(this FileSystemClient fs,
                                                         ReadOnlySpan <ProgramIndexMapInfo> mapInfo)
        {
            if (mapInfo.IsEmpty)
            {
                return(Result.Success);
            }

            using ReferenceCountedDisposable <IFileSystemProxy> fsProxy = fs.Impl.GetFileSystemProxyServiceObject();

            var mapInfoBuffer = new InBuffer(MemoryMarshal.Cast <ProgramIndexMapInfo, byte>(mapInfo));

            Result rc = fsProxy.Target.RegisterProgramIndexMapInfo(mapInfoBuffer, mapInfo.Length);

            fs.Impl.AbortIfNeeded(rc);
            return(rc);
        }
Exemple #8
0
        public WaveIn(int Device, WAVEFORMATEX Format, int BufferSize)
        {
            Log.Global.WriteLine(MessageType.Info, "Opening wave in device '{0}'.", Device);

            // Construct waveIn
            MmException.CheckThrow(Winmm.waveInOpen(out waveIn, Device, ref Format, callback.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInOpenFlags.CALLBACK_EVENT));

            // Create buffers.
            buffers = new List<InBuffer>();
            for (int i = 0; i < 4; ++i)
            {
                InBuffer b = new InBuffer(waveIn, Format, BufferSize);
                b.Record();
                buffers.Add(b);
            }

            MmException.CheckThrow(Winmm.waveInStart(waveIn));
        }
Exemple #9
0
        /// <summary>
        /// Get the last bottle from the ingoing buffer
        /// </summary>
        /// <returns></returns>
        private Bottle GetBottleFromIngoingBuffer()
        {
            Monitor.Enter(InBuffer.Lock);
            try
            {
                if (InBuffer.GetItemsInBuffer() == 0)
                {
                    Monitor.PulseAll(InBuffer.Lock);
                    Monitor.Wait(inBuffer.Lock);
                }

                return(InBuffer.RemoveLastBottle());
            }
            finally
            {
                Monitor.Exit(InBuffer.Lock);
            }
        }
        /// <summary>
        /// Передача управления базовой системе
        /// </summary>
        public override void Activate()
        {
            //Единственное действие это окончание обслуживания
            var key   = ListOfFragments.Keys.Min();
            var value = ListOfFragments[key];

            //Удаляем из списка обслуживаемых фрамгентов
            ListOfFragments.Remove(key);
            //Прибор свободен, пытаемся взять на обслуживание новый фрагмент
            if (InBuffer.Length() > 0)
            {
                StartService();
            }
            else
            {
                //Обновляем время активации
                UpdateActionTime();
            }
            //Отправляем обслуженный фрагмент в другие узлы
            Route(value);
        }
Exemple #11
0
        private byte[] ReadIndexedChunk(byte?obfuscator)
        {
            int chunkSize = InReader.ReadInt32();

            if (chunkSize > 0)
            {
                byte[] chunk = new byte[chunkSize];
                InBuffer.Read(chunk, 0, chunkSize);
                if (obfuscator != null)
                {
                    for (int i = 0; i < chunkSize; i++)
                    {
                        chunk[i] ^= obfuscator.Value;
                    }
                }
                return(chunk);
            }
            else
            {
                throw new NullFileChunkException("Failed to load file chunk.");
            }
        }
Exemple #12
0
        protected override void Decrypt()
        {
            try
            {
                // Read key
                byte[] keyChunk = ReadIndexedChunk(0x64);
                byte[] key      = AesEcbDecrypt(keyChunk, rootKey);

                // Build main key
                for (uint i = 0; i < MainKey.Length; i++)
                {
                    MainKey[i] = Convert.ToByte(i);
                }
                for (uint trgIndex = 0, swpIndex, lastIndex = 0, srcOffset = 17, srcIndex = srcOffset; trgIndex < MainKey.Length; trgIndex++)
                {
                    byte swap = MainKey[trgIndex];
                    swpIndex = (swap + lastIndex + key[srcIndex++]) & 0xff;
                    if (srcIndex >= key.Length)
                    {
                        srcIndex = srcOffset;
                    }
                    MainKey[trgIndex] = MainKey[swpIndex];
                    MainKey[swpIndex] = swap;
                    lastIndex         = swpIndex;
                }
            }
            catch (NullFileChunkException e)
            {
                throw new FileLoadException(e.Message);
            }

            try
            {
                // Read metadata
                byte[] metaChunk = ReadIndexedChunk(0x63);
                int    skipCount = 22;
                for (int i = 0; i < metaChunk.LongLength; i++)
                {
                    if (metaChunk[i] == 58)
                    {
                        skipCount = i + 1;
                        break;
                    }
                }

                // Resolve metadata
                PropMetadata = JsonConvert.DeserializeObject <NetEaseMetadata>(
                    Encoding.UTF8.GetString(
                        AesEcbDecrypt(
                            Convert.FromBase64String(
                                Encoding.UTF8.GetString(
                                    metaChunk.Skip(skipCount).ToArray())
                                ),
                            jsonKey)
                        .Skip(6).ToArray())
                    );
                StdMetadata = new Metadata(PropMetadata);
            }
            catch (NullFileChunkException)
            {
                Logger.Warn("Missing metadata in {Path}", InPath);
            }

            // Skip ahead
            _ = InBuffer.Seek(9, SeekOrigin.Current);

            // Get cover data
            try
            {
                // Plan A: Read cover from file
                CoverBuffer.Write(ReadIndexedChunk(null));
            }
            catch (NullFileChunkException)
            {
                Logger.Warn("Failed to load cover from {Path}, trying to get from server...", InPath);

                // Plan B: get image from server
                try
                {
                    string coverUri = PropMetadata.AlbumPic;
                    if (!Uri.IsWellFormedUriString(coverUri, UriKind.Absolute))
                    {
                        Logger.Error("No cover URI was found in {Path}", InPath);
                        throw;
                    }
                    using WebClient webClient = new WebClient();
                    CoverBuffer.Write(webClient.DownloadData(coverUri));
                }
                catch (Exception)
                {
                    Logger.Error("Failed to download cover image for {Path}", InPath);
                }
            }
            CoverMime = MediaType.GetStreamMime(CoverBuffer);
            if (CoverMime.Substring(0, 5) != "image")
            {
                CoverBuffer.Dispose();
                CoverMime = null;
            }

            // Read music
            for (int chunkSize = 0x8000; ;)
            {
                byte[] mainChunk = ReadFixedChunk(ref chunkSize);

                for (int i = 0; i < chunkSize; i++)
                {
                    int j = (i + 1) & 0xff;
                    mainChunk[i] ^= MainKey[(MainKey[j] + MainKey[(MainKey[j] + j) & 0xff]) & 0xff];
                }

                if (chunkSize < 0x8000)
                {
                    OutBuffer.Write(mainChunk.Take(chunkSize).ToArray());
                    break;
                }
                else
                {
                    OutBuffer.Write(mainChunk);
                }
            }
            MusicMime = MediaType.GetStreamMime(OutBuffer);
        }
Exemple #13
0
 public virtual void Dispose()
 {
     InBuffer.Dispose();
     OutBuffer.Dispose();
     CoverBuffer.Dispose();
 }
 /// <summary>
 /// Возвращает число фрагментов в базовой системе (очередь + приборы)
 /// </summary>
 /// <returns></returns>
 public int NumberOfFragments()
 {
     return(ListOfFragments.Count + InBuffer.Length());
 }
Exemple #15
0
 protected override void Decrypt()
 {
     OutBuffer.Write(header);
     OutBuffer.Write(InBuffer.GetBuffer().Skip(8).ToArray());
 }
 public Result RegisterProgram(ulong processId, ProgramId programId, StorageId storageId,
                               InBuffer accessControlData, InBuffer accessControlDescriptor)
 {
     return(ResultFs.PortAcceptableCountLimited.Log());
 }
Exemple #17
0
 protected byte[] ReadFixedChunk(ref int size)
 {
     byte[] chunk = new byte[size];
     size = InBuffer.Read(chunk, 0, size);
     return(chunk);
 }