protected void createSockets() { if (sPipeApi == PIPE_API_LS) { const String LOCAL_ADDR = "net.majorkernelpanic.streaming-"; for (int i = 0; i < 10; i++) { try { mSocketId = new Java.Util.Random().NextInt(); mLss = new LocalServerSocket(LOCAL_ADDR + mSocketId); break; } catch (Java.IO.IOException e1) {} } mReceiver = new LocalSocket(); mReceiver.Connect(new LocalSocketAddress(LOCAL_ADDR + mSocketId)); mReceiver.ReceiveBufferSize = 500000; mReceiver.SoTimeout = 3000; mSender = mLss.Accept(); mSender.SendBufferSize = 500000; } else { Log.e(TAG, "parcelFileDescriptors createPipe version = Lollipop"); mParcelFileDescriptors = ParcelFileDescriptor.CreatePipe(); mParcelRead = new ParcelFileDescriptor(mParcelFileDescriptors[0]); mParcelWrite = new ParcelFileDescriptor(mParcelFileDescriptors[1]); } }
private void HandshakeCallback(IAsyncResult ar) { try { int received = LocalSocket.EndReceive(ar); if(received == 0) { Dispose(); return; } switch(LocalBuffer[0]) { case 4: // SOCKS 4 _socksHandler = new Socks4Handler(LocalSocket, HandshakeEnd); break; case 5: // SOCKS 5 _socksHandler = new Socks5Handler(LocalSocket, HandshakeEnd, _authCallback); break; default: Dispose(); return; } _socksHandler.BeginRequestData(); } catch { Dispose(); } }
public void AddMessageRoute_AddsActorRoute() { var actor = ReceiverIdentities.CreateForActor(); var localSocket = new LocalSocket <IMessage>(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = actor, DestinationSocket = localSocket, MessageContracts = new[] { new MessageContract { Message = messageIdentifier } } }; // internalRoutingTable.AddMessageRoute(registration); // var lookupRequest = new InternalRouteLookupRequest { ReceiverIdentity = actor, Message = messageIdentifier }; var socket = internalRoutingTable.FindRoutes(lookupRequest).First(); Assert.AreEqual(localSocket, socket); }
/// <summary> /// Tries to connect to the server. /// Returns if it was successfull. /// </summary> private void TryConnect() { try { int attempts = 0; while (!LocalSocket.Connected) { try { Debug("Connection attempt " + attempts++, DebugType.Warning); LocalSocket.Connect(serverIP, port); } catch (SocketException) { } } Debug($"Connection successfull! Required {attempts} attempts", DebugType.Info); } catch (Exception ex) { Debug("Halting (13)", DebugType.Warning); if (ShowExceptions) { Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } if (AutoRestartOnCrash) { HaltAllThreads(); } } }
public void AddMessageRoute_AddsLocalOrExternalActorRoute(bool keepLocal) { var actor = ReceiverIdentities.CreateForActor(); var localSocket = new LocalSocket <IMessage>(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = actor, DestinationSocket = localSocket, MessageContracts = new[] { new MessageContract { Message = messageIdentifier, KeepRegistrationLocal = keepLocal } } }; // internalRoutingTable.AddMessageRoute(registration); // var route = internalRoutingTable.GetAllRoutes().Actors.First().Actors.First(); Assert.AreEqual(keepLocal, route.LocalRegistration); Assert.IsTrue(Unsafe.ArraysEqual(actor.Identity, route.Identity)); }
protected override void SendRespoce(byte value) { byte[] responce; try { var endPoint = (IPEndPoint)RemoteSocket.LocalEndPoint; byte[] ipBytes = endPoint.Address.GetAddressBytes(); byte[] portBytes = BitConverter.GetBytes((short)endPoint.Port); responce = new byte[] { 5, value, 0, 1, ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3], portBytes[1], portBytes[0] }; } catch (Exception) { responce = new byte[] { 5, 1, 0, 1, 0, 0, 0, 0, 0, 0 }; } try { int sent = LocalSocket.Send(responce); if (sent > 0) { Dispoce(true); return; } Dispoce(false); } catch { Dispoce(false); } }
public LocalSocketTests() { sendingRate = new Mock <IPerformanceCounter>(); receivingRate = new Mock <IPerformanceCounter>(); socket = new LocalSocket <IMessage> { SendRate = sendingRate.Object, ReceiveRate = receivingRate.Object }; }
private void CreateSockets() { receiver = new LocalSocket(); localSocketAddress = new LocalSocketAddress("localServer" + socketId); receiver.Connect(localSocketAddress); receiver.ReceiveBufferSize = 500000; receiver.SendBufferSize = 500000; sender = lss.Accept(); sender.ReceiveBufferSize = 500000; sender.SendBufferSize = 500000; }
internal override void StartHandshake() { try { LocalSocket.BeginReceive(LocalBuffer, 0, 1, SocketFlags.None, HandshakeCallback, null); } catch { Dispose(); } }
public LocalServer() { LocalSocket clientSocket = new LocalSocket(); LocalSocket serverSocket = new LocalSocket(); m_clientSession = new NetSession(clientSocket); m_serverSession = new NetSession(serverSocket); clientSocket.Init(m_serverSession.Out, m_serverSession.In); serverSocket.Init(m_clientSession.Out, m_clientSession.In); m_serverSession.MsgProcesser = ProcessMsg; m_database = new Database(this); m_database.LoadConfigs(); }
public void IfReceiverIdentifierNeitherMessageHubNorActor_AddMessageRouteThrowsException() { var receiverIdentity = new ReceiverIdentifier(Guid.NewGuid().ToByteArray()); var localSocket = new LocalSocket <IMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = receiverIdentity, DestinationSocket = localSocket }; // Assert.Throws <ArgumentException>(() => internalRoutingTable.AddMessageRoute(registration)); }
public static bool SendFd(string sockPath, Java.IO.FileDescriptor fd) { var socket = new LocalSocket(); try { socket.Connect(new LocalSocketAddress(sockPath, LocalSocketAddress.Namespace.Filesystem)); socket.SetFileDescriptorsForSend(new Java.IO.FileDescriptor[] { fd }); socket.OutputStream.Write(new byte[] { 42 }); } catch (Exception e) { Logging.warning("sendfd: " + e.Message); return(false); } finally { socket.Close(); } return(true); }
public HumanGame(LocalSocket socket, ChessFlag flag) { selfFlag = flag; gameWindow = new GameWindow(); gameWindow.Title = "中国象棋-双人"; viewBoard = gameWindow.Board; viewBoard.UpChessFlag = (flag == ChessFlag.BLACK) ? ChessFlag.RED : ChessFlag.BLACK; viewBoard.ClickPos += OnClickPos; board = viewBoard.ChessBoard; this.socket = socket; socket.ReceivedOk += OnReceiveOk; socket.ReceivedMove += OnAnotherMove; if (flag == ChessFlag.RED) { turnSelf = true; } gameWindow.Closed += Exit; }
protected override void SendRespoce(byte value) { try { var result = new byte[] { 0, value, 0, 0, 0, 0, 0, 0 }; int sent = LocalSocket.Send(result); if (value == 0x5a && sent > 0) { Dispoce(true); return; } Dispoce(false); } catch { Dispoce(false); } }
protected void closeSockets() { if (sPipeApi == PIPE_API_LS) { try { mReceiver.Close(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.StackTrace.ToString()); } try { mSender.Close(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.StackTrace.ToString()); } try { mLss.Close(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.StackTrace.ToString()); } mLss = null; mSender = null; mReceiver = null; } else { try { if (mParcelRead != null) { mParcelRead.Close(); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.StackTrace.ToString()); } try { if (mParcelWrite != null) { mParcelWrite.Close(); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.StackTrace.ToString()); } } }
public void AddMessageRoute_AddsLocalOrExternalMessageHubRoute(bool keepLocal) { var messageHub = ReceiverIdentities.CreateForMessageHub(); var localSocket = new LocalSocket <IMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = messageHub, DestinationSocket = localSocket, KeepRegistrationLocal = keepLocal }; // internalRoutingTable.AddMessageRoute(registration); // var route = internalRoutingTable.GetAllRoutes().MessageHubs.First(); Assert.AreEqual(keepLocal, route.LocalRegistration); Assert.AreEqual(messageHub, route.MessageHub); }
/// <summary> /// Receives and adds the next incomming instruction to the incomming-queue. /// </summary> protected void AsyncInstructionReceiveNext() { buffer = new byte[bufferSize]; int received = LocalSocket.Receive(buffer, SocketFlags.None); if (received == 0) { return; } byte[] data = new byte[received]; Array.Copy(buffer, data, received); string text = Encoding.UTF8.GetString(data); Debug("Received Message.", DebugType.Info); try { InstructionBase[] instructionList = InstructionOperations.Parse(this, null, text).ToArray(); foreach (InstructionBase instr in instructionList) { incommingInstructions.Add(instr); } } catch (NetComAuthenticationException ex) { Debug("Authentication-Error.", DebugType.Error); if (ShowExceptions) { Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } } catch (Exception ex) { Debug($"Error occured. ({_logErrorCount})", DebugType.Error); if (ShowExceptions) { Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } _logErrorCount++; } }
public void AddMessageRoute_AddsMessageHubRoute() { var messageHub = ReceiverIdentities.CreateForMessageHub(); var localSocket = new LocalSocket <IMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = messageHub, DestinationSocket = localSocket }; // internalRoutingTable.AddMessageRoute(registration); // var lookupRequest = new InternalRouteLookupRequest { ReceiverIdentity = messageHub }; var socket = internalRoutingTable.FindRoutes(lookupRequest).First(); Assert.AreEqual(localSocket, socket); }
/// <summary> /// Gets called when a connection is established. /// </summary> /// <param name="AR">IAsyncResult</param> private void AcceptCallback(IAsyncResult AR) { try { Socket socket; try { socket = LocalSocket.EndAccept(AR); } catch (ObjectDisposedException) { return; } ConnectedClients.Add(socket); socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, socket); Handler.Debug("New client connected.", DebugType.Info); //SendToClient(socket, new NCILib.PreAuth(this)); Send(new InstructionLibraryEssentials.KeyExchangeServer2Client(this, ConnectedClients[socket])); LocalSocket.BeginAccept(AcceptCallback, null); } catch (Exception ex) { Handler.Debug("Halting (06)", DebugType.Warning); if (HandlerData.ShowExceptions) { Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } if (HandlerData.TryRestartOnCrash) { HaltAllThreads(); } } }
/// <summary> /// Properly closes all connections /// and shuts down the server. /// </summary> public void Shutdown() { try { lock (ConnectedClients) { Handler.Debug("Shutting down all connections...", DebugType.Info); foreach (NetComCData client in ConnectedClients) { try { client.LocalSocket.Shutdown(SocketShutdown.Both); client.LocalSocket.Close(); } catch (Exception ex) { Handler.Debug("Could not close clients socket.", DebugType.Error); if (HandlerData.ShowExceptions) { Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } } } } Handler.Debug("Shutting down server...", DebugType.Info); LocalSocket.Close(); Handler.Debug("Shutdown complete!", DebugType.Info); } catch (Exception ex) { Handler.Debug("Shutdown could not be completed. Some connections might stay opened.", DebugType.Error); if (HandlerData.ShowExceptions) { Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception); } } }
/// <summary> /// Sends the next instruction from the outgoing-queue. /// </summary> protected override void AsyncInstructionSendNext() { base.AsyncInstructionSendNext(); if (!haltActive) { byte[] buffer; buffer = Encoding.UTF8.GetBytes(OutgoingInstructions[0].Encode()); LocalSocket.Send(buffer, 0, buffer.Length, SocketFlags.None); Debug($"Sent Message to {OutgoingInstructions[0].Receiver.ToString()}.", DebugType.Info); Debug(OutgoingInstructions[0].ToString(), DebugType.Info); OutgoingInstructions.RemoveAt(0); } else { Debug("Could not send message. Client is in halt-mode. Waiting for 5 seconds...", DebugType.Error); Thread.Sleep(5000); } }
public void Build() { AssertDependencyResolverSet(); var configurationProvider = new ConfigurationProvider(resolver.Resolve <KinoConfiguration>()); var scaleOutSocketConfiguration = configurationProvider.GetScaleOutConfiguration(); var clusterMembershipConfiguration = configurationProvider.GetClusterMembershipConfiguration(); var clusterHealthMonitorConfiguration = configurationProvider.GetClusterHealthMonitorConfiguration(); var heartBeatSenderConfiguration = configurationProvider.GetHeartBeatSenderConfiguration(); var socketConfiguration = configurationProvider.GetSocketConfiguration(); var rendezvousEndpoints = configurationProvider.GetRendezvousEndpointsConfiguration(); var socketFactory = new SocketFactory(socketConfiguration); var logger = resolver.Resolve <ILogger>(); var roundRobinDestinationList = new RoundRobinDestinationList(logger); var internalRoutingTable = new InternalRoutingTable(roundRobinDestinationList); var externalRoutingTable = new ExternalRoutingTable(roundRobinDestinationList, logger); var localSocketFactory = new LocalSocketFactory(); var routerLocalSocket = new LocalSocket <IMessage>(); var internalRegistrationSocket = new LocalSocket <InternalRouteRegistration>(); #if NET47 var instanceNameResolver = resolver.Resolve <IInstanceNameResolver>() ?? new InstanceNameResolver(); var performanceCounterManager = new PerformanceCounterManager <KinoPerformanceCounters>(instanceNameResolver, logger); #else var performanceCounterManager = default(IPerformanceCounterManager <KinoPerformanceCounters>); #endif var hashCodeProvider = resolver.Resolve <Func <HMAC> >() ?? (() => HMAC.Create("HMACMD5")); var securityProvider = resolver.Resolve <ISecurityProvider>() ?? new SecurityProvider(hashCodeProvider, resolver.Resolve <IDomainScopeResolver>(), resolver.Resolve <IDomainPrivateKeyProvider>()); var heartBeatSenderConfigurationManager = new HeartBeatSenderConfigurationManager(heartBeatSenderConfiguration); var configurationStorage = resolver.Resolve <IConfigurationStorage <RendezvousClusterConfiguration> >() ?? new RendezvousClusterConfigurationReadonlyStorage(rendezvousEndpoints); var rendezvousCluster = new RendezvousCluster(configurationStorage); var scaleoutConfigurationProvider = new ServiceLocator <ScaleOutConfigurationManager, NullScaleOutConfigurationManager, IScaleOutConfigurationManager>(clusterMembershipConfiguration, new ScaleOutConfigurationManager(scaleOutSocketConfiguration), new NullScaleOutConfigurationManager()) .GetService(); var connectedPeerRegistry = new ConnectedPeerRegistry(clusterHealthMonitorConfiguration); var clusterHealthMonitor = new ServiceLocator <ClusterHealthMonitor, NullClusterHealthMonitor, IClusterHealthMonitor>(clusterMembershipConfiguration, new ClusterHealthMonitor(socketFactory, localSocketFactory, securityProvider, routerLocalSocket, connectedPeerRegistry, clusterHealthMonitorConfiguration, logger), new NullClusterHealthMonitor()) .GetService(); var heartBeatSender = new ServiceLocator <HeartBeatSender, NullHeartBeatSender, IHeartBeatSender>(clusterMembershipConfiguration, new HeartBeatSender(socketFactory, heartBeatSenderConfigurationManager, scaleoutConfigurationProvider, logger), new NullHeartBeatSender()) .GetService(); var scaleOutListener = new ServiceLocator <ScaleOutListener, NullScaleOutListener, IScaleOutListener>(clusterMembershipConfiguration, new ScaleOutListener(socketFactory, routerLocalSocket, scaleoutConfigurationProvider, securityProvider, performanceCounterManager, logger), new NullScaleOutListener()) .GetService(); var autoDiscoverSender = new AutoDiscoverySender(rendezvousCluster, socketFactory, clusterMembershipConfiguration, performanceCounterManager, logger); var autoDiscoveryListener = new AutoDiscoveryListener(rendezvousCluster, socketFactory, scaleoutConfigurationProvider, clusterMembershipConfiguration, performanceCounterManager, routerLocalSocket, logger); var routeDiscovery = new RouteDiscovery(autoDiscoverSender, scaleoutConfigurationProvider, clusterMembershipConfiguration, securityProvider, logger); var clusterMonitor = new ServiceLocator <ClusterMonitor, NullClusterMonitor, IClusterMonitor>(clusterMembershipConfiguration, new ClusterMonitor(scaleoutConfigurationProvider, autoDiscoverSender, autoDiscoveryListener, heartBeatSenderConfigurationManager, routeDiscovery, securityProvider, clusterMembershipConfiguration, logger), new NullClusterMonitor()) .GetService(); var clusterServices = new ClusterServices(clusterMonitor, scaleOutListener, heartBeatSender, clusterHealthMonitor); var nodeRoutesRegistrar = new NodeRoutesRegistrar(clusterServices, internalRoutingTable, securityProvider); var internalMessageRouteRegistrationHandler = new InternalMessageRouteRegistrationHandler(clusterMonitor, internalRoutingTable, securityProvider); var serviceMessageHandlers = new IServiceMessageHandler[] { new ClusterMessageRoutesRequestHandler(securityProvider, nodeRoutesRegistrar), new PingHandler(), new ExternalMessageRouteRegistrationHandler(externalRoutingTable, securityProvider, clusterHealthMonitor, logger), new MessageRouteDiscoveryHandler(clusterMonitor, internalRoutingTable, securityProvider, logger), new MessageRouteUnregistrationHandler(clusterHealthMonitor, externalRoutingTable, securityProvider, logger), new NodeMessageRoutesRequestHandler(securityProvider, nodeRoutesRegistrar), new NodeUnregistrationHandler(clusterHealthMonitor, externalRoutingTable, securityProvider), new UnreachableNodeUnregistrationHandler(clusterHealthMonitor, externalRoutingTable) }; var serviceMessageHandlerRegistry = new ServiceMessageHandlerRegistry(serviceMessageHandlers); messageRouter = new MessageRouter(socketFactory, internalRoutingTable, externalRoutingTable, scaleoutConfigurationProvider, clusterServices, serviceMessageHandlerRegistry, performanceCounterManager, securityProvider, routerLocalSocket, internalRegistrationSocket, internalMessageRouteRegistrationHandler, roundRobinDestinationList, logger); var actorHostFactory = new ActorHostFactory(securityProvider, routerLocalSocket, internalRegistrationSocket, localSocketFactory, logger); var callbackHandlerStack = new CallbackHandlerStack(); createMessageHub = (keepLocal) => new MessageHub(callbackHandlerStack, routerLocalSocket, internalRegistrationSocket, localSocketFactory, scaleoutConfigurationProvider, securityProvider, logger, keepLocal); var messageHub = createMessageHub(false); getMessageHub = () => messageHub; actorHostManager = new ActorHostManager(actorHostFactory, logger); internalActorHostManager = new ActorHostManager(actorHostFactory, logger); var internalActor = new MessageRoutesActor(externalRoutingTable, internalRoutingTable); internalActorHostManager.AssignActor(internalActor); // isBuilt = true; }
protected override void onCreate(Bundle savedInstanceState) { // http://unix.stackexchange.com/questions/10050/proc-pid-fd-x-link-number // http://stackoverflow.com/questions/21955273/sharing-shared-memory-file-descriptors-across-android-app-processes-using-binder // http://permalink.gmane.org/gmane.comp.handhelds.android.porting/10904 // http://www.mkyong.com/android/android-activity-from-one-screen-to-another-screen/ // https://groups.google.com/forum/#!topic/android-ndk/sjIiMsLkHCM base.onCreate(savedInstanceState); var sv = new ScrollView(this); var ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); var activity = this; // does it work for us? var fs = default(java.io.FileDescriptor); try { var ls = new LocalSocket(); ls.connect(new LocalSocketAddress("MemoryFileDescriptor0")); var i8 = ls.getInputStream().read(); fs = ls.getAncillaryFileDescriptors().FirstOrDefault(); new Button(this).AttachTo(ll).WithText(new { i8, fs }.ToString()); //var memory0 = new FileInputStream(ls_fd).read(); //new Button(this).AttachTo(ll).WithText(new { memory0 }.ToString()); } catch { } var m = default(MemoryFile); //try { m = new MemoryFile(default(string), 0); } try { m = new MemoryFile("name1", 0x07); } catch { throw; } var m_descriptor = this.getIntent().getIntExtra("m_descriptor", 0); var parentpid = this.getIntent().getIntExtra("pid", 0); //var pfd = (ParcelFileDescriptor)this.getIntent().getParcelableExtra("pfd"); ////var fs = new java.io.FileDescriptor { }; ////var xfields = typeof(java.io.FileDescriptor).GetFields( //// System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ////); ////xfields.WithEach( //// xFileDescriptor_SourceField => //// { //// var xvalue = xFileDescriptor_SourceField.GetValue(fs); //// //if (xFileDescriptor_SourceField.FieldType == typeof(int)) //// if (xFileDescriptor_SourceField.Name == "descriptor") //// { //// xFileDescriptor_SourceField.SetValue(fs, m_descriptor); //// } //// } ////); // need to call native_mmap var t = typeof(MemoryFile); // internal static int native_mmap(java.io.FileDescriptor fd, int length, int mode); //var native_mmap = t.GetMethod("native_mmap", new[] { // typeof(java.io.FileDescriptor), // typeof(int), // typeof(int) // } //); //var methods = t.GetMethods( // System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static //); //var native_mmap = methods.FirstOrDefault(x => x.Name == "native_mmap"); //#region time to patch it? //#endregion //var available = 0; var buffer = new byte[0x07]; //X:\jsc.svn\examples\java\android\Test\TestNewByteArray7\TestNewByteArray7\Class1.cs //try { m.readBytes(buffer, 0, 0, 0x07); } //catch { } //try //{ // //buffer0 = new java.io.FileInputStream(fs).read(); // available = new java.io.FileInputStream(fs).available(); //} //catch //{ } //var parentpidfd = "/proc/" + parentpid + "/fd/" + m_descriptor; //var parentpidfdx = global::System.IO.File.Exists(parentpidfd); //var parentpidf = new java.io.File(parentpidfd); //new Button(this).AttachTo(ll).WithText(new { parentpidfdx }.ToString()); //new Button(this).AttachTo(ll).WithText(new { parentpidfd }.ToString()); //new Button(this).AttachTo(ll).WithText(new { size = parentpidf.length() }.ToString()); //var parentfd = ParcelFileDescriptor.open(parentpidf, ParcelFileDescriptor.MODE_READ_WRITE); var pid = android.os.Process.myPid(); var uid = android.os.Process.myUid(); this.setTitle( new { pid, uid //m_descriptor, //parentpid, ////pfg = pfd.getFd(), ////size = pfd.getStatSize() //parentpidfdx, //parentpidfd }.ToString() ); //new Button(this).AttachTo(ll).WithText("methods: " + new //{ // methods.Length // , // native_mmap //}.ToString()); //methods.WithEach( // SourceMethod => // { // new Button(this).AttachTo(ll).WithText(new { SourceMethod }.ToString()); // } //); Action patch = delegate { }; #region fields var fields = t.GetFields( System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); new Button(this).AttachTo(ll).WithText("fields: " + new { fields.Length }.ToString()); fields.WithEach( SourceField => { //E/AndroidRuntime( 9919): Caused by: java.lang.IllegalAccessException: Cannot access field: java.io.FileDescriptor android.os.MemoryFile.mFD //E/AndroidRuntime( 9919): at java.lang.reflect.Field.get(Native Method) //E/AndroidRuntime( 9919): at java.lang.reflect.Field.get(Field.java:279) //E/AndroidRuntime( 9919): at ScriptCoreLibJava.BCLImplementation.System.Reflection.__FieldInfo.GetValue(__FieldInfo.java:46) var value = SourceField.GetValue(m); var xFileDescriptor = value as java.io.FileDescriptor; if (xFileDescriptor != null) { var xfields = typeof(java.io.FileDescriptor).GetFields( System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); xfields.WithEach( xFileDescriptor_SourceField => { var xvalue = xFileDescriptor_SourceField.GetValue(value); //if (xFileDescriptor_SourceField.FieldType == typeof(int)) if (xFileDescriptor_SourceField.Name == "descriptor") { //m_descriptor = (int)xvalue; patch = delegate { Console.WriteLine("enter patch " + new { SourceField }); //mAddress = native_mmap(mFD, length, modeToProt(mode)); //mOwnsRegion = false; SourceField.SetValue(m, fs); //xFileDescriptor_SourceField.SetValue(value, m_descriptor); value = SourceField.GetValue(m); xvalue = xFileDescriptor_SourceField.GetValue(value); var field_mAddress = fields.FirstOrDefault(xx => xx.Name == "mAddress"); Console.WriteLine("enter patch " + new { xvalue } +" invoke mmap"); var PROT_READ = 0x1; //E/AndroidRuntime( 8047): Caused by: java.lang.IllegalAccessException: access to method denied //E/AndroidRuntime( 8047): at java.lang.reflect.Method.invokeNative(Native Method) //E/AndroidRuntime( 8047): at java.lang.reflect.Method.invoke(Method.java:507) //E/AndroidRuntime( 8047): at ScriptCoreLibJava.BCLImplementation.System.Reflection.__MethodInfo.InternalInvoke(__MethodInfo.java:93) //I/System.Console( 8648): 21c8:0001 enter patch { field_mAddress = int mAddress } invoke native_mmap //I/System.Console( 8936): 22e8:0001 GetFields { Length = 5, IsPublic = false, IsNonPublic = true, IsStatic = fal //I/System.Console( 8936): 22e8:0001 enter patch //I/System.Console( 8936): 22e8:0001 enter patch { field_mAddress = int mAddress, m_descriptor = 39 } invoke mmap //I/System.Console( 8936): 22e8:0001 lib: libs/armeabi_v7a/libTestNDKAsAsset.so //I/System.Console( 8936): 22e8:0001 loadLibrary: TestNDKAsAsset //I/System.Console( 8936): 22e8:0001 exit patch { mAddress = -1 } //var z = ScriptCoreLibNative.SystemHeaders.sys.mman_h.mmap( // null, // length, // PROT_READ | PROT_WRITE, // MAP_SHARED, // fd, // 0 // ); // I/System.Console( 8016): 1f50:0001 enter patch { SourceField = java.io.FileDescriptor mFD } //I/System.Console( 8016): 1f50:0001 enter patch { field_mAddress = long mAddress, xvalue = 32 } invoke mmap //I/System.Console( 8016): 1f50:0001 lib: libs/armeabi_v7a/libTestNDKAsAsset.so //I/System.Console( 8016): 1f50:0001 loadLibrary: TestNDKAsAsset //I/System.Console( 8016): 1f50:0001 exit patch { mAddress = -1 } //I/System.Console( 9792): 2640:0001 enter patch { SourceField = java.io.FileDescriptor mFD } //I/System.Console( 9792): 2640:0001 enter patch { xvalue = 32 } invoke mmap //I/xNativeActivity( 9792): x:\jsc.svn\examples\c\android\Test\TestNDKAsAsset\TestNDKAsAsset\Program.cs:139 mmap -1 errno: 13 Permission denied //I/System.Console( 9792): 2640:0001 exit patch { mAddress = -1 } //E/audit ( 5152): type=1400 msg=audit(1433328685.131:566): avc: denied { mmap_zero } for pid=9792 comm="Activities:foo1" scontext=u:r:untrusted_app:s0 tcontext=u:r:untrusted_app:s0 tclass=memprotect permissive=0 //E/audit ( 5152): SEPF_SM-G925F_5.0.2_0009 //E/audit ( 5152): type=1300 msg=audit(1433328685.131:566): arch=40000028 syscall=192 success=no exit=-13 a0=0 a1=7 a2=3 a3=10 items=0 ppid=2962 ppcomm=main pid=9792 auid=4294967295 uid=10315 gid=10315 euid=10315 suid=10315 fsuid=10315 egid=10315 sgid=10315 fsgid=10315 ses=4294967295 tty=(none) comm="Activities:foo1" exe="/system/bin/app_process32" subj=u:r:untrusted_app:s0 key=(null) //E/audit ( 5152): type=1320 msg=audit(1433328685.131:566): //D/SSRM:n ( 3468): SIOP:: AP = 290, PST = 300, CP = 395, CUR = 268 // https://github.com/realm/realm-java/issues/1037 var mAddress = (int) // ??? TestNDKAsAsset.xActivity.mmap( (int)xvalue, 0x07 ); // https://android.googlesource.com/platform/development/+/858086e/ndk/sources/android/libportable/arch-mips/mmap.c // https://groups.google.com/forum/#!msg/android-ndk/tNYpTsHNQEY/8S7VS2j8f_8J // jint result = (jint)mmap(NULL, length, prot, MAP_SHARED, fd, 0); //native_mmap.Invoke(null, // new object[] // { // value, // 0x07, // PROT_READ // } //); Console.WriteLine("exit patch " + new { mAddress }); field_mAddress.SetValue(m, mAddress); // http://stackoverflow.com/questions/8165216/what-is-the-use-of-memoryfile-in-android // http://osdir.com/ml/Android-Developers/2013-01/msg00793.html }; } new Button(this).AttachTo(ll).WithText(xFileDescriptor_SourceField + new { xvalue }.ToString()); } ); } else { new Button(this).AttachTo(ll).WithText(new { SourceField, value }.ToString()); } } ); #endregion new Button(activity).WithText("Patch n Read!").AttachTo(ll).AtClick( delegate { patch(); //return; //this.finish(); //E/AndroidRuntime( 7526): Caused by: java.lang.NoSuchMethodError: android.app.Activity.finishAndRemoveTask //E/AndroidRuntime( 7526): at TestMultiProcMemoryFile.Activities.SecondaryActivity._onCreate_b__0(SecondaryActivity.java:66) //this.finishAndRemoveTask(); //try { m.readBytes(buffer, 0, 0, 0x07); } //catch { } //var buffer0 = buffer[0]; //this.setTitle( // new { m_descriptor, buffer0 }.ToString() //); } ); this.setContentView(sv); }
private void CreateSockets(){ receiver = new LocalSocket(); localSocketAddress = new LocalSocketAddress("localServer"+socketId); receiver.Connect(localSocketAddress); receiver.ReceiveBufferSize = 500000; receiver.SendBufferSize = 500000; sender = lss.Accept(); sender.ReceiveBufferSize = 500000; sender.SendBufferSize = 500000; }
public void Terminate() { LocalSocket.TryDispose(); RemoteSocket.TryDispose(); }
/// <summary> /// Return a string representation of this object. /// </summary> public override String ToString() { return("UDP packet received at " + ServerTimestamp + " from " + RemoteSocket.ToString() + " to " + LocalSocket.ToString()); }
/// <summary> /// Return a string representation of this object. /// </summary> public override String ToString() { return(LocalSocket.ToString() + " [local] <-> " + RemoteSocket.ToString() + " [remote]"); }