Ejemplo n.º 1
0
        public long Read(ServiceCtx Context)
        {
            long Offset = Context.RequestData.ReadInt64();
            long Size   = Context.RequestData.ReadInt64();

            if (Context.Request.ReceiveBuff.Count > 0)
            {
                IpcBuffDesc BuffDesc = Context.Request.ReceiveBuff[0];

                //Use smaller length to avoid overflows.
                if (Size > BuffDesc.Size)
                {
                    Size = BuffDesc.Size;
                }

                byte[] Data = new byte[Size];

                BaseStream.Seek(Offset, SeekOrigin.Begin);
                BaseStream.Read(Data, 0, Data.Length);

                AMemoryHelper.WriteBytes(Context.Memory, BuffDesc.Position, Data);
            }

            return(0);
        }
Ejemplo n.º 2
0
        public long ListAudioDeviceName(ServiceCtx Context)
        {
            string[] DeviceNames = SystemStateMgr.AudioOutputs;

            Context.ResponseData.Write(DeviceNames.Length);

            long Position = Context.Request.ReceiveBuff[0].Position;
            long Size     = Context.Request.ReceiveBuff[0].Size;

            long BasePosition = Position;

            foreach (string Name in DeviceNames)
            {
                byte[] Buffer = Encoding.ASCII.GetBytes(Name + "\0");

                if ((Position - BasePosition) + Buffer.Length > Size)
                {
                    Context.Ns.Log.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!");

                    break;
                }

                AMemoryHelper.WriteBytes(Context.Memory, Position, Buffer);

                Position += Buffer.Length;
            }

            return(0);
        }
Ejemplo n.º 3
0
 /// <summary>
 ///     Write an array of bytes in the remote process.
 /// </summary>
 /// <param name="intPtr">The address where the array is written.</param>
 /// <param name="bytesToWrite">The array of bytes to write.</param>
 public override int Write(IntPtr intPtr, byte[] bytesToWrite)
 {
     using (new AMemoryProtection(Handle, intPtr,
                                  MarshalType <byte> .Size * bytesToWrite.Length))
         AMemoryHelper.WriteBytes(Handle, intPtr, bytesToWrite);
     return(bytesToWrite.Length);
 }
Ejemplo n.º 4
0
        //(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
        public long Recv(ServiceCtx Context)
        {
            int SocketId    = Context.RequestData.ReadInt32();
            int SocketFlags = Context.RequestData.ReadInt32();

            byte[] ReceivedBuffer = new byte[Context.Request.ReceiveBuff[0].Size];

            try
            {
                int BytesRead = Sockets[SocketId].Handle.Receive(ReceivedBuffer);

                //Logging.Debug("Received Buffer:" + Environment.NewLine + Logging.HexDump(ReceivedBuffer));

                AMemoryHelper.WriteBytes(Context.Memory, Context.Request.ReceiveBuff[0].Position, ReceivedBuffer);

                Context.ResponseData.Write(BytesRead);
                Context.ResponseData.Write(0);
            }
            catch (SocketException Ex)
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write(Ex.ErrorCode - 10000);
            }

            return(0);
        }
Ejemplo n.º 5
0
        public static long Read(ServiceCtx Context)
        {
            AmIStorageAccessor Accessor = Context.GetObject <AmIStorageAccessor>();

            AmIStorage Storage = Accessor.Storage;

            long ReadPosition = Context.RequestData.ReadInt64();

            if (Context.Request.RecvListBuff.Count > 0)
            {
                long  Position = Context.Request.RecvListBuff[0].Position;
                short Size     = Context.Request.RecvListBuff[0].Size;

                byte[] Data;

                if (Storage.Data.Length > Size)
                {
                    Data = new byte[Size];

                    Buffer.BlockCopy(Storage.Data, 0, Data, 0, Size);
                }
                else
                {
                    Data = Storage.Data;
                }

                AMemoryHelper.WriteBytes(Context.Memory, Position, Data);
            }

            return(0);
        }
Ejemplo n.º 6
0
        public long ListAudioDeviceName(ServiceCtx Context)
        {
            string[] Names = new string[] { "FIXME" };

            Context.ResponseData.Write(Names.Length);

            long Position = Context.Request.ReceiveBuff[0].Position;
            long Size     = Context.Request.ReceiveBuff[0].Size;

            long BasePosition = Position;

            foreach (string Name in Names)
            {
                byte[] Buffer = Encoding.ASCII.GetBytes(Name + '\0');

                if ((Position - BasePosition) + Buffer.Length > Size)
                {
                    break;
                }

                AMemoryHelper.WriteBytes(Context.Memory, Position, Buffer);

                Position += Buffer.Length;
            }

            return(0);
        }
Ejemplo n.º 7
0
        public long GetReleasedAudioOutBuffer(ServiceCtx Context)
        {
            long TempKey = 0;

            if (KeysQueue.Count > 0)
            {
                TempKey = KeysQueue.Dequeue();
            }

            AMemoryHelper.WriteBytes(Context.Memory, Context.Request.ReceiveBuff[0].Position, BitConverter.GetBytes(TempKey));

            Context.ResponseData.Write((int)TempKey);

            if (OpenALInstalled)
            {
                if (AudioCtx == null) //Needed to call the instance of AudioContext()
                {
                    return(0);
                }

                AL.SourcePlay(Source);
                int[] FreeBuffers = AL.SourceUnqueueBuffers(Source, 1);
                AL.DeleteBuffers(FreeBuffers);
            }

            return(0);
        }
Ejemplo n.º 8
0
        public static long GetSettingsItemValue(ServiceCtx Context)
        {
            long ClassPos  = Context.Request.PtrBuff[0].Position;
            long ClassSize = Context.Request.PtrBuff[0].Size;

            long NamePos  = Context.Request.PtrBuff[1].Position;
            long NameSize = Context.Request.PtrBuff[1].Size;

            long ReplyPos  = Context.Request.ReceiveBuff[0].Position;
            long ReplySize = Context.Request.ReceiveBuff[0].Size;

            byte[] Class = AMemoryHelper.ReadBytes(Context.Memory, ClassPos, ClassSize);
            byte[] Name  = AMemoryHelper.ReadBytes(Context.Memory, NamePos, NameSize);

            string AskedSetting = Encoding.ASCII.GetString(Class).Trim('\0') + "!" + Encoding.ASCII.GetString(Name).Trim('\0');

            NxSettings.Settings.TryGetValue(AskedSetting, out object NxSetting);

            if (NxSetting != null)
            {
                byte[] SettingBuffer = new byte[ReplySize];

                if (NxSetting is string StringValue)
                {
                    if (StringValue.Length + 1 > ReplySize)
                    {
                        Context.Ns.Log.PrintError(Logging.LogClass.ServiceSet, $"{AskedSetting} String value size is too big!");
                    }
                    else
                    {
                        SettingBuffer = Encoding.ASCII.GetBytes(StringValue + "\0");
                    }
                }
                if (NxSetting is int IntValue)
                {
                    SettingBuffer = BitConverter.GetBytes(IntValue);
                }
                else if (NxSetting is bool BoolValue)
                {
                    SettingBuffer[0] = BoolValue ? (byte)1 : (byte)0;
                }
                else
                {
                    throw new NotImplementedException(NxSetting.GetType().Name);
                }

                AMemoryHelper.WriteBytes(Context.Memory, ReplyPos, SettingBuffer);

                Context.Ns.Log.PrintDebug(Logging.LogClass.ServiceSet, $"{AskedSetting} set value: {NxSetting} as {NxSetting.GetType()}");
            }
            else
            {
                Context.Ns.Log.PrintError(Logging.LogClass.ServiceSet, $"{AskedSetting} not found!");
            }

            return(0);
        }
Ejemplo n.º 9
0
        public long OpenAudioOut(ServiceCtx Context)
        {
            IAalOutput AudioOut = Context.Ns.AudioOut;

            string DeviceName = AMemoryHelper.ReadAsciiString(
                Context.Memory,
                Context.Request.SendBuff[0].Position,
                Context.Request.SendBuff[0].Size);

            if (DeviceName == string.Empty)
            {
                DeviceName = "FIXME";
            }

            long DeviceNamePosition = Context.Request.ReceiveBuff[0].Position;
            long DeviceNameSize     = Context.Request.ReceiveBuff[0].Size;

            byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(DeviceName);

            if (DeviceName.Length <= DeviceNameSize)
            {
                AMemoryHelper.WriteBytes(Context.Memory, DeviceNamePosition, DeviceNameBuffer);
            }

            int SampleRate = Context.RequestData.ReadInt32();
            int Channels   = Context.RequestData.ReadInt32();

            Channels = (ushort)(Channels >> 16);

            if (SampleRate == 0)
            {
                SampleRate = 48000;
            }

            if (Channels < 1 || Channels > 2)
            {
                Channels = 2;
            }

            KEvent ReleaseEvent = new KEvent();

            ReleaseCallback Callback = () =>
            {
                ReleaseEvent.WaitEvent.Set();
            };

            int Track = AudioOut.OpenTrack(SampleRate, Channels, Callback, out AudioFormat Format);

            MakeObject(Context, new IAudioOut(AudioOut, ReleaseEvent, Track));

            Context.ResponseData.Write(SampleRate);
            Context.ResponseData.Write(Channels);
            Context.ResponseData.Write((int)Format);
            Context.ResponseData.Write((int)PlaybackState.Stopped);

            return(0);
        }
Ejemplo n.º 10
0
        public long ListAudioOuts(ServiceCtx Context)
        {
            long Position = Context.Request.ReceiveBuff[0].Position;

            AMemoryHelper.WriteBytes(Context.Memory, Position, Encoding.ASCII.GetBytes("iface"));

            Context.ResponseData.Write(1);

            return(0);
        }
Ejemplo n.º 11
0
        private void WriteData(
            long Position,
            byte[]      Data,
            MemoryType Type,
            AMemoryPerm Perm)
        {
            Memory.Manager.Map(Position, Data.Length, (int)Type, AMemoryPerm.Write);

            AMemoryHelper.WriteBytes(Memory, Position, Data);

            Memory.Manager.Reprotect(Position, Data.Length, Perm);
        }
Ejemplo n.º 12
0
        public long GetActiveAudioDeviceName(ServiceCtx Context)
        {
            string Name = "FIXME";

            long Position = Context.Request.ReceiveBuff[0].Position;
            long Size     = Context.Request.ReceiveBuff[0].Size;

            byte[] Buffer = Encoding.ASCII.GetBytes(Name + '\0');

            AMemoryHelper.WriteBytes(Context.Memory, Position, Buffer);

            return(0);
        }
Ejemplo n.º 13
0
        public long OpenLayer(ServiceCtx Context)
        {
            long LayerId = Context.RequestData.ReadInt64();
            long UserId  = Context.RequestData.ReadInt64();

            long ParcelPtr = Context.Request.ReceiveBuff[0].Position;

            byte[] Parcel = MakeIGraphicsBufferProducer(ParcelPtr);

            AMemoryHelper.WriteBytes(Context.Memory, ParcelPtr, Parcel);

            Context.ResponseData.Write((long)Parcel.Length);

            return(0);
        }
Ejemplo n.º 14
0
        public static long GetFirmwareVersion2(ServiceCtx Context)
        {
            long ReplyPos  = Context.Request.RecvListBuff[0].Position;
            long ReplySize = Context.Request.RecvListBuff[0].Size;

            byte MajorFWVersion = 0x03;
            byte MinorFWVersion = 0x00;
            byte MicroFWVersion = 0x00;
            byte Unknown        = 0x00; //Build?

            int RevisionNumber = 0x0A;

            string Platform   = "NX";
            string UnknownHex = "7fbde2b0bba4d14107bf836e4643043d9f6c8e47";
            string Version    = "3.0.0";
            string Build      = "NintendoSDK Firmware for NX 3.0.0-10.0";

            //http://switchbrew.org/index.php?title=System_Version_Title
            using (MemoryStream MS = new MemoryStream(0x100))
            {
                BinaryWriter Writer = new BinaryWriter(MS);

                Writer.Write(MajorFWVersion);
                Writer.Write(MinorFWVersion);
                Writer.Write(MicroFWVersion);
                Writer.Write(Unknown);

                Writer.Write(RevisionNumber);

                Writer.Write(Encoding.ASCII.GetBytes(Platform));

                MS.Seek(0x28, SeekOrigin.Begin);
                Writer.Write(Encoding.ASCII.GetBytes(UnknownHex));

                MS.Seek(0x68, SeekOrigin.Begin);
                Writer.Write(Encoding.ASCII.GetBytes(Version));

                MS.Seek(0x80, SeekOrigin.Begin);
                Writer.Write(Encoding.ASCII.GetBytes(Build));

                AMemoryHelper.WriteBytes(Context.Memory, ReplyPos, MS.ToArray());
            }

            return(0);
        }
Ejemplo n.º 15
0
        public long CreateStrayLayer(ServiceCtx Context)
        {
            long LayerFlags = Context.RequestData.ReadInt64();
            long DisplayId  = Context.RequestData.ReadInt64();

            long ParcelPtr = Context.Request.ReceiveBuff[0].Position;

            Display Disp = Displays.GetData <Display>((int)DisplayId);

            byte[] Parcel = MakeIGraphicsBufferProducer(ParcelPtr);

            AMemoryHelper.WriteBytes(Context.Memory, ParcelPtr, Parcel);

            Context.ResponseData.Write(0L);
            Context.ResponseData.Write((long)Parcel.Length);

            return(0);
        }
Ejemplo n.º 16
0
        public long GetActiveAudioDeviceNameAuto(ServiceCtx Context)
        {
            string Name = Context.Ns.Os.SystemState.ActiveAudioOutput;

            (long Position, long Size) = Context.Request.GetBufferType0x22();

            byte[] DeviceNameBuffer = Encoding.UTF8.GetBytes(Name + '\0');

            if ((ulong)DeviceNameBuffer.Length <= (ulong)Size)
            {
                AMemoryHelper.WriteBytes(Context.Memory, Position, DeviceNameBuffer);
            }
            else
            {
                Context.Ns.Log.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!");
            }

            return(0);
        }
Ejemplo n.º 17
0
        public long Read(ServiceCtx Context)
        {
            long Position = Context.Request.ReceiveBuff[0].Position;

            long Zero   = Context.RequestData.ReadInt64();
            long Offset = Context.RequestData.ReadInt64();
            long Size   = Context.RequestData.ReadInt64();

            byte[] Data = new byte[Size];

            BaseStream.Seek(Offset, SeekOrigin.Begin);
            int ReadSize = BaseStream.Read(Data, 0, (int)Size);

            AMemoryHelper.WriteBytes(Context.Memory, Position, Data);

            Context.ResponseData.Write((long)ReadSize);

            return(0);
        }
Ejemplo n.º 18
0
        public long GetActiveAudioDeviceName(ServiceCtx Context)
        {
            string Name = Context.Ns.Os.SystemState.ActiveAudioOutput;

            long Position = Context.Request.ReceiveBuff[0].Position;
            long Size     = Context.Request.ReceiveBuff[0].Size;

            byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(Name + "\0");

            if ((ulong)DeviceNameBuffer.Length <= (ulong)Size)
            {
                AMemoryHelper.WriteBytes(Context.Memory, Position, DeviceNameBuffer);
            }
            else
            {
                Context.Ns.Log.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!");
            }

            return(0);
        }
Ejemplo n.º 19
0
        public static long GetAvailableLanguageCodes(ServiceCtx Context)
        {
            int PtrBuffSize = Context.RequestData.ReadInt32();

            if (Context.Request.RecvListBuff.Count > 0)
            {
                long  Position = Context.Request.RecvListBuff[0].Position;
                short Size     = Context.Request.RecvListBuff[0].Size;

                //This should return an array of ints with values matching the LanguageCode enum.
                foreach (long value in new long[] { 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L })
                {
                    AMemoryHelper.WriteBytes(Context.Memory, Position += 8, BitConverter.GetBytes(value));
                }
            }

            Context.ResponseData.Write(LangCodesCount);

            return(0);
        }
Ejemplo n.º 20
0
        public long Read(ServiceCtx Context)
        {
            long Position = Context.Request.ReceiveBuff[0].Position;

            long Zero   = Context.RequestData.ReadInt64();
            long Offset = Context.RequestData.ReadInt64();
            long Size   = Context.RequestData.ReadInt64();

            byte[] Data = new byte[Size];

            int ReadSize = BaseStream.Read(Data, 0, (int)Size);

            AMemoryHelper.WriteBytes(Context.Memory, Position, Data);

            //TODO: Use ReadSize, we need to return the size that was REALLY read from the file.
            //This is a workaround because we are doing something wrong and the game expects to read
            //data from a file that doesn't yet exists -- and breaks if it can't read anything.
            Context.ResponseData.Write((long)Size);

            return(0);
        }
Ejemplo n.º 21
0
        public static long GetAvailableLanguageCodes(ServiceCtx Context)
        {
            int PtrBuffSize = Context.RequestData.ReadInt32();

            if (Context.Request.RecvListBuff.Count > 0)
            {
                long  Position = Context.Request.RecvListBuff[0].Position;
                short Size     = Context.Request.RecvListBuff[0].Size;

                //This should return an array of ints with values matching the LanguageCode enum.
                byte[] Data = new byte[Size];

                Data[0] = 0;
                Data[1] = 1;

                AMemoryHelper.WriteBytes(Context.Memory, Position, Data);
            }

            Context.ResponseData.Write(LangCodesCount);

            return(0);
        }
Ejemplo n.º 22
0
        public long Read(ServiceCtx Context)
        {
            long BufferPosition = Context.Request.ReceiveBuff[0].Position;
            long BufferLen      = Context.Request.ReceiveBuff[0].Size;
            long MaxDirectories = BufferLen / Marshal.SizeOf(typeof(DirectoryEntry));

            if (MaxDirectories > DirectoryEntries.Count - LastItem)
            {
                MaxDirectories = DirectoryEntries.Count - LastItem;
            }

            int CurrentIndex;

            for (CurrentIndex = 0; CurrentIndex < MaxDirectories; CurrentIndex++)
            {
                int CurrentItem = LastItem + CurrentIndex;

                byte[] DirectoryEntry = new byte[Marshal.SizeOf(typeof(DirectoryEntry))];
                IntPtr Ptr            = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(DirectoryEntry)));
                Marshal.StructureToPtr(DirectoryEntries[CurrentItem], Ptr, true);
                Marshal.Copy(Ptr, DirectoryEntry, 0, Marshal.SizeOf(typeof(DirectoryEntry)));
                Marshal.FreeHGlobal(Ptr);

                AMemoryHelper.WriteBytes(Context.Memory, BufferPosition + Marshal.SizeOf(typeof(DirectoryEntry)) * CurrentIndex, DirectoryEntry);
            }

            if (LastItem < DirectoryEntries.Count)
            {
                LastItem += CurrentIndex;
                Context.ResponseData.Write((long)CurrentIndex); // index = number of entries written this call.
            }
            else
            {
                Context.ResponseData.Write((long)0);
            }

            return(0);
        }
Ejemplo n.º 23
0
        public long ListAudioOuts(ServiceCtx Context)
        {
            long Position = Context.Request.ReceiveBuff[0].Position;
            long Size     = Context.Request.ReceiveBuff[0].Size;

            int NameCount = 0;

            byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(DefaultAudioOutput + "\0");

            if ((ulong)DeviceNameBuffer.Length <= (ulong)Size)
            {
                AMemoryHelper.WriteBytes(Context.Memory, Position, DeviceNameBuffer);

                NameCount++;
            }
            else
            {
                Context.Ns.Log.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!");
            }

            Context.ResponseData.Write(NameCount);

            return(0);
        }
Ejemplo n.º 24
0

        
Ejemplo n.º 25
0
        public long Read(ServiceCtx Context)
        {
            //TODO: Error conditions.
            long ReadPosition = Context.RequestData.ReadInt64();

            (long Position, long Size) = Context.Request.GetBufferType0x22();

            byte[] Data;

            if (Storage.Data.Length > Size)
            {
                Data = new byte[Size];

                Buffer.BlockCopy(Storage.Data, 0, Data, 0, (int)Size);
            }
            else
            {
                Data = Storage.Data;
            }

            AMemoryHelper.WriteBytes(Context.Memory, Position, Data);

            return(0);
        }
Ejemplo n.º 26
0
        //(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<sockaddr, 0x22, 0> addr)
        public long Accept(ServiceCtx Context)
        {
            int SocketId = Context.RequestData.ReadInt32();

            long AddrBufferPtr = Context.Request.ReceiveBuff[0].Position;

            Socket HandleAccept = null;

            Task TimeOut = Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleAccept = Sockets[SocketId].Handle.Accept();
                }
                catch (SocketException Ex)
                {
                    Context.ResponseData.Write(-1);
                    Context.ResponseData.Write(Ex.ErrorCode - 10000);
                }
            });

            TimeOut.Wait(10000);

            if (HandleAccept != null)
            {
                BsdSocket NewBsdSocket = new BsdSocket
                {
                    IpAddress = ((IPEndPoint)Sockets[SocketId].Handle.LocalEndPoint).Address,
                    RemoteEP  = ((IPEndPoint)Sockets[SocketId].Handle.LocalEndPoint),
                    Handle    = HandleAccept
                };

                Sockets.Add(NewBsdSocket);

                using (MemoryStream MS = new MemoryStream())
                {
                    BinaryWriter Writer = new BinaryWriter(MS);

                    Writer.Write((byte)0);

                    Writer.Write((byte)NewBsdSocket.Handle.AddressFamily);

                    Writer.Write((short)((IPEndPoint)NewBsdSocket.Handle.LocalEndPoint).Port);

                    byte[] IpAddress = NewBsdSocket.IpAddress.GetAddressBytes();

                    Writer.Write(IpAddress);

                    AMemoryHelper.WriteBytes(Context.Memory, AddrBufferPtr, MS.ToArray());

                    Context.ResponseData.Write(Sockets.Count - 1);
                    Context.ResponseData.Write(0);
                    Context.ResponseData.Write(MS.Length);
                }
            }
            else
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write((int)BsdError.Timeout);
            }

            return(0);
        }
Ejemplo n.º 27
0
        public static void IpcCall(
            Switch Ns,
            Process Process,
            AMemory Memory,
            KSession Session,
            IpcMessage Request,
            long CmdPtr)
        {
            IpcMessage Response = new IpcMessage();

            using (MemoryStream Raw = new MemoryStream(Request.RawData))
            {
                BinaryReader ReqReader = new BinaryReader(Raw);

                if (Request.Type == IpcMessageType.Request)
                {
                    Response.Type = IpcMessageType.Response;

                    using (MemoryStream ResMS = new MemoryStream())
                    {
                        BinaryWriter ResWriter = new BinaryWriter(ResMS);

                        ServiceCtx Context = new ServiceCtx(
                            Ns,
                            Process,
                            Memory,
                            Session,
                            Request,
                            Response,
                            ReqReader,
                            ResWriter);

                        Session.Service.CallMethod(Context);

                        Response.RawData = ResMS.ToArray();
                    }
                }
                else if (Request.Type == IpcMessageType.Control)
                {
                    long Magic = ReqReader.ReadInt64();
                    long CmdId = ReqReader.ReadInt64();

                    switch (CmdId)
                    {
                    case 0:
                    {
                        Request = FillResponse(Response, 0, Session.Service.ConvertToDomain());

                        break;
                    }

                    case 3:
                    {
                        Request = FillResponse(Response, 0, 0x500);

                        break;
                    }

                    //TODO: Whats the difference between IpcDuplicateSession/Ex?
                    case 2:
                    case 4:
                    {
                        int Unknown = ReqReader.ReadInt32();

                        int Handle = Process.HandleTable.OpenHandle(Session);

                        Response.HandleDesc = IpcHandleDesc.MakeMove(Handle);

                        Request = FillResponse(Response, 0);

                        break;
                    }

                    default: throw new NotImplementedException(CmdId.ToString());
                    }
                }
                else if (Request.Type == IpcMessageType.CloseSession)
                {
                    //TODO
                }
                else
                {
                    throw new NotImplementedException(Request.Type.ToString());
                }

                AMemoryHelper.WriteBytes(Memory, CmdPtr, Response.GetBytes(CmdPtr));
            }
        }
Ejemplo n.º 28
0
        public void WriteBytes(long Position, byte[] Data)
        {
            Position = GetPhysicalAddress(Position);

            AMemoryHelper.WriteBytes(Memory, Position, Data);
        }
Ejemplo n.º 29
0
        //(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<sockaddr, 0x22, 0> addr)
        public long Accept(ServiceCtx Context)
        {
            int  SocketId      = Context.RequestData.ReadInt32();
            long AddrBufferPtr = Context.Request.ReceiveBuff[0].Position;

            Socket HandleAccept = null;

            var TimeOut = Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleAccept = Sockets[SocketId].Handle.Accept();
                }
                catch (SocketException Ex)
                {
                    Context.ResponseData.Write(-1);
                    Context.ResponseData.Write(Ex.ErrorCode - 10000);
                }
            });

            TimeOut.Wait(10000);

            if (HandleAccept != null)
            {
                SocketBsd NewBSDSocket = new SocketBsd
                {
                    IpAddress = ((IPEndPoint)Sockets[SocketId].Handle.LocalEndPoint).Address,
                    RemoteEP  = ((IPEndPoint)Sockets[SocketId].Handle.LocalEndPoint),
                    Handle    = HandleAccept
                };

                Sockets.Add(NewBSDSocket);

                using (MemoryStream MS = new MemoryStream())
                {
                    BinaryWriter Writer = new BinaryWriter(MS);

                    Writer.Write((byte)0);
                    Writer.Write((byte)Sockets[Sockets.Count - 1].Handle.AddressFamily);
                    Writer.Write((Int16)((IPEndPoint)Sockets[Sockets.Count - 1].Handle.LocalEndPoint).Port);

                    string[] IpAdress = Sockets[Sockets.Count - 1].IpAddress.ToString().Split('.');
                    Writer.Write(byte.Parse(IpAdress[0]));
                    Writer.Write(byte.Parse(IpAdress[1]));
                    Writer.Write(byte.Parse(IpAdress[2]));
                    Writer.Write(byte.Parse(IpAdress[3]));

                    AMemoryHelper.WriteBytes(Context.Memory, AddrBufferPtr, MS.ToArray());

                    Context.ResponseData.Write(Sockets.Count - 1);
                    Context.ResponseData.Write(0);
                    Context.ResponseData.Write(MS.Length);
                }
            }
            else
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write((int)BsdError.ETIMEDOUT);
            }

            return(0);
        }
Ejemplo n.º 30
0
        public static void IpcCall(
            Switch Ns,
            AMemory Memory,
            HSession Session,
            IpcMessage Request,
            int ThreadId,
            long CmdPtr,
            int HndId)
        {
            IpcMessage Response = new IpcMessage(Request.IsDomain && Request.Type == IpcMessageType.Request);

            using (MemoryStream Raw = new MemoryStream(Request.RawData))
            {
                BinaryReader ReqReader = new BinaryReader(Raw);

                if (Request.Type == IpcMessageType.Request)
                {
                    string ServiceName = Session.Service.GetType().Name;

                    ServiceProcessRequest ProcReq = null;

                    bool IgnoreNullPR = false;

                    string DbgServiceName = string.Empty;

                    if (Session is HDomain Dom)
                    {
                        if (Request.DomCmd == IpcDomCmd.SendMsg)
                        {
                            long Magic = ReqReader.ReadInt64();
                            int  CmdId = (int)ReqReader.ReadInt64();

                            object Obj = Dom.GetObject(Request.DomObjId);

                            if (Obj is HDomain)
                            {
                                Session.Service.Commands.TryGetValue(CmdId, out ProcReq);

                                DbgServiceName = $"{ProcReq?.Method.Name ?? CmdId.ToString()}";
                            }
                            else if (Obj != null)
                            {
                                ((IIpcService)Obj).Commands.TryGetValue(CmdId, out ProcReq);

                                DbgServiceName = $"{Obj.GetType().Name} {ProcReq?.Method.Name ?? CmdId.ToString()}";
                            }
                        }
                        else if (Request.DomCmd == IpcDomCmd.DeleteObj)
                        {
                            Dom.DeleteObject(Request.DomObjId);

                            Response = FillResponse(Response, 0);

                            IgnoreNullPR = true;
                        }
                    }
                    else
                    {
                        long Magic = ReqReader.ReadInt64();
                        int  CmdId = (int)ReqReader.ReadInt64();

                        if (Session is HSessionObj)
                        {
                            object Obj = ((HSessionObj)Session).Obj;

                            ((IIpcService)Obj).Commands.TryGetValue(CmdId, out ProcReq);

                            DbgServiceName = $"{Obj.GetType().Name} {ProcReq?.Method.Name ?? CmdId.ToString()}";
                        }
                        else
                        {
                            Session.Service.Commands.TryGetValue(CmdId, out ProcReq);

                            DbgServiceName = $"{ProcReq?.Method.Name ?? CmdId.ToString()}";
                        }
                    }

                    DbgServiceName = $"Tid {ThreadId} {ServiceName} {DbgServiceName}";

                    Logging.Debug($"IpcMessage: {DbgServiceName}");

                    if (ProcReq != null)
                    {
                        using (MemoryStream ResMS = new MemoryStream())
                        {
                            BinaryWriter ResWriter = new BinaryWriter(ResMS);

                            ServiceCtx Context = new ServiceCtx(
                                Ns,
                                Memory,
                                Session,
                                Request,
                                Response,
                                ReqReader,
                                ResWriter);

                            long Result = ProcReq(Context);

                            Response = FillResponse(Response, Result, ResMS.ToArray());
                        }
                    }
                    else if (!IgnoreNullPR)
                    {
                        throw new NotImplementedException(DbgServiceName);
                    }
                }
                else if (Request.Type == IpcMessageType.Control)
                {
                    long Magic = ReqReader.ReadInt64();
                    long CmdId = ReqReader.ReadInt64();

                    switch (CmdId)
                    {
                    case 0: Request = IpcConvertSessionToDomain(Ns, Session, Response, HndId); break;

                    case 3: Request = IpcQueryBufferPointerSize(Response);                     break;

                    case 2:     //IpcDuplicateSession, differences is unknown.
                    case 4: Request = IpcDuplicateSessionEx(Ns, Session, Response, ReqReader); break;

                    default: throw new NotImplementedException(CmdId.ToString());
                    }
                }
                else if (Request.Type == IpcMessageType.Unknown2)
                {
                    //TODO
                }
                else
                {
                    throw new NotImplementedException(Request.Type.ToString());
                }

                AMemoryHelper.WriteBytes(Memory, CmdPtr, Response.GetBytes(CmdPtr));
            }
        }