public override void Run() { DomainSocket conn = null; try { conn = preConnectedSockets != null ? preConnectedSockets[0] : serv.Accept(); byte[] in1 = new byte[clientMsg1.Length]; TestDomainSocket.ReadStrategy reader = System.Activator.CreateInstance(readStrategyClass ); reader.Init(conn); reader.ReadFully(in1, 0, in1.Length); Assert.True(Arrays.Equals(clientMsg1, in1)); TestDomainSocket.WriteStrategy writer = System.Activator.CreateInstance(writeStrategyClass ); writer.Init(conn); writer.Write(serverMsg1); InputStream connInputStream = conn.GetInputStream(); int in2 = connInputStream.Read(); Assert.Equal((int)clientMsg2, in2); conn.Close(); } catch (Exception e) { threadResults.AddItem(e); NUnit.Framework.Assert.Fail(e.Message); } threadResults.AddItem(new TestDomainSocket.Success()); }
/// <summary> /// Test that we can create a socket and close it, even if it hasn't been /// opened. /// </summary> /// <exception cref="System.IO.IOException"/> public virtual void TestSocketCreateAndClose() { DomainSocket serv = DomainSocket.BindAndListen(new FilePath(sockDir.GetDir(), "test_sock_create_and_close" ).GetAbsolutePath()); serv.Close(); }
/// <summary> /// Test that we get an AsynchronousCloseException when the DomainSocket /// we're using is closed during a read or write operation. /// </summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> private void TestAsyncCloseDuringIO(bool closeDuringWrite) { string TestPath = new FilePath(sockDir.GetDir(), "testAsyncCloseDuringIO(" + closeDuringWrite + ")").GetAbsolutePath(); DomainSocket serv = DomainSocket.BindAndListen(TestPath); ExecutorService exeServ = Executors.NewFixedThreadPool(2); Callable <Void> serverCallable = new _Callable_180(serv, closeDuringWrite); // The server just continues either writing or reading until someone // asynchronously closes the client's socket. At that point, all our // reads return EOF, and writes get a socket error. Future <Void> serverFuture = exeServ.Submit(serverCallable); DomainSocket clientConn = DomainSocket.Connect(serv.GetPath()); Callable <Void> clientCallable = new _Callable_213(closeDuringWrite, clientConn); // The client writes or reads until another thread // asynchronously closes the socket. At that point, we should // get ClosedChannelException, or possibly its subclass // AsynchronousCloseException. Future <Void> clientFuture = exeServ.Submit(clientCallable); Thread.Sleep(500); clientConn.Close(); serv.Close(); clientFuture.Get(2, TimeUnit.Minutes); serverFuture.Get(2, TimeUnit.Minutes); }
public override void Run() { try { DomainSocket client = preConnectedSockets != null ? preConnectedSockets[1] : DomainSocket .Connect(TestPath); TestDomainSocket.WriteStrategy writer = System.Activator.CreateInstance(writeStrategyClass ); writer.Init(client); writer.Write(clientMsg1); TestDomainSocket.ReadStrategy reader = System.Activator.CreateInstance(readStrategyClass ); reader.Init(client); byte[] in1 = new byte[serverMsg1.Length]; reader.ReadFully(in1, 0, in1.Length); Assert.True(Arrays.Equals(serverMsg1, in1)); OutputStream clientOutputStream = client.GetOutputStream(); clientOutputStream.Write(clientMsg2); client.Close(); } catch (Exception e) { threadResults.AddItem(e); } threadResults.AddItem(new TestDomainSocket.Success()); }
public override void Run() { try { DomainSocket client = DomainSocket.Connect(TestPath); OutputStream clientOutputStream = client.GetOutputStream(); InputStream clientInputStream = client.GetInputStream(); clientOutputStream.Write(clientMsg1); DomainSocket domainConn = (DomainSocket)client; byte[] in1 = new byte[serverMsg1.Length]; FileInputStream[] recvFis = new FileInputStream[passedFds.Length]; int r = domainConn.RecvFileInputStreams(recvFis, in1, 0, in1.Length - 1); Assert.True(r > 0); IOUtils.ReadFully(clientInputStream, in1, r, in1.Length - r); Assert.True(Arrays.Equals(serverMsg1, in1)); for (int i = 0; i < passedFds.Length; i++) { NUnit.Framework.Assert.IsNotNull(recvFis[i]); passedFiles[i].CheckInputStream(recvFis[i]); } foreach (FileInputStream fis in recvFis) { fis.Close(); } client.Close(); } catch (System.Exception e) { threadResults.AddItem(e); } threadResults.AddItem(new TestDomainSocket.Success()); }
/// <summary>Test setting some server options.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestServerOptions() { string TestPath = new FilePath(sockDir.GetDir(), "test_sock_server_options").GetAbsolutePath (); DomainSocket serv = DomainSocket.BindAndListen(TestPath); try { // Let's set a new receive buffer size int bufSize = serv.GetAttribute(DomainSocket.ReceiveBufferSize); int newBufSize = bufSize / 2; serv.SetAttribute(DomainSocket.ReceiveBufferSize, newBufSize); int nextBufSize = serv.GetAttribute(DomainSocket.ReceiveBufferSize); Assert.Equal(newBufSize, nextBufSize); // Let's set a server timeout int newTimeout = 1000; serv.SetAttribute(DomainSocket.ReceiveTimeout, newTimeout); int nextTimeout = serv.GetAttribute(DomainSocket.ReceiveTimeout); Assert.Equal(newTimeout, nextTimeout); try { serv.Accept(); NUnit.Framework.Assert.Fail("expected the accept() to time out and fail"); } catch (SocketTimeoutException e) { GenericTestUtils.AssertExceptionContains("accept(2) error: ", e); } } finally { serv.Close(); NUnit.Framework.Assert.IsFalse(serv.IsOpen()); } }
public void Run() { try { for (int i = 0; i < SocketNum; i++) { DomainSocket[] pair = DomainSocket.Socketpair(); watcher.Add(pair[1], new _Handler_128(handled)); Lock.Lock(); try { pairs.AddItem(pair); } finally { Lock.Unlock(); } } } catch (Exception e) { TestDomainSocketWatcher.Log.Error(e); throw new RuntimeException(e); } }
public _Thread_597(DomainSocket serv, byte[] clientMsg1, FileDescriptor[] passedFds , byte[] serverMsg1, ArrayBlockingQueue <System.Exception> threadResults) { this.serv = serv; this.clientMsg1 = clientMsg1; this.passedFds = passedFds; this.serverMsg1 = serverMsg1; this.threadResults = threadResults; }
/// <summary>Test that domain sockets are closed when the watcher is closed.</summary> /// <exception cref="System.Exception"/> public virtual void TestCloseSocketOnWatcherClose() { DomainSocketWatcher watcher = NewDomainSocketWatcher(10000000); DomainSocket[] pair = DomainSocket.Socketpair(); watcher.Add(pair[1], new _Handler_103()); watcher.Close(); Uninterruptibles.JoinUninterruptibly(watcher.watcherThread); NUnit.Framework.Assert.IsFalse(pair[1].IsOpen()); }
/// <summary>Test that attempting to connect to an invalid path doesn't work.</summary> /// <exception cref="System.IO.IOException"/> public virtual void TestInvalidOperations() { try { DomainSocket.Connect(new FilePath(sockDir.GetDir(), "test_sock_invalid_operation" ).GetAbsolutePath()); } catch (IOException e) { GenericTestUtils.AssertExceptionContains("connect(2) error: ", e); } }
/// <summary>Test that we can get notifications out a DomainSocketWatcher.</summary> /// <exception cref="System.Exception"/> public virtual void TestDeliverNotifications() { DomainSocketWatcher watcher = NewDomainSocketWatcher(10000000); DomainSocket[] pair = DomainSocket.Socketpair(); CountDownLatch latch = new CountDownLatch(1); watcher.Add(pair[1], new _Handler_73(latch)); pair[0].Close(); latch.Await(); watcher.Close(); }
/// <summary> /// Test that if one thread is blocking in a read or write operation, another /// thread can close the socket and stop the accept. /// </summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestSocketAcceptAndClose() { string TestPath = new FilePath(sockDir.GetDir(), "test_sock_accept_and_close").GetAbsolutePath (); DomainSocket serv = DomainSocket.BindAndListen(TestPath); ExecutorService exeServ = Executors.NewSingleThreadExecutor(); Callable <Void> callable = new _Callable_149(serv); Future <Void> future = exeServ.Submit(callable); Thread.Sleep(500); serv.Close(); future.Get(2, TimeUnit.Minutes); }
public _Thread_435(DomainSocket[] preConnectedSockets, DomainSocket serv, byte[] clientMsg1, Type readStrategyClass, Type writeStrategyClass, byte[] serverMsg1, byte clientMsg2, ArrayBlockingQueue <Exception> threadResults) { this.preConnectedSockets = preConnectedSockets; this.serv = serv; this.clientMsg1 = clientMsg1; this.readStrategyClass = readStrategyClass; this.writeStrategyClass = writeStrategyClass; this.serverMsg1 = serverMsg1; this.clientMsg2 = clientMsg2; this.threadResults = threadResults; }
/// <summary> /// Send callback and return whether or not the domain socket was closed as a /// result of processing. /// </summary> /// <param name="caller">reason for call</param> /// <param name="entries">mapping of file descriptor to entry</param> /// <param name="fdSet">set of file descriptors</param> /// <param name="fd">file descriptor</param> /// <returns>true if the domain socket was closed as a result of processing</returns> private bool SendCallback(string caller, SortedDictionary <int, DomainSocketWatcher.Entry > entries, DomainSocketWatcher.FdSet fdSet, int fd) { if (Log.IsTraceEnabled()) { Log.Trace(this + ": " + caller + " starting sendCallback for fd " + fd); } DomainSocketWatcher.Entry entry = entries[fd]; Preconditions.CheckNotNull(entry, this + ": fdSet contained " + fd + ", which we were " + "not tracking."); DomainSocket sock = entry.GetDomainSocket(); if (entry.GetHandler().Handle(sock)) { if (Log.IsTraceEnabled()) { Log.Trace(this + ": " + caller + ": closing fd " + fd + " at the request of the handler." ); } if (Collections.Remove(toRemove, fd) != null) { if (Log.IsTraceEnabled()) { Log.Trace(this + ": " + caller + " : sendCallback processed fd " + fd + " in toRemove." ); } } try { sock.refCount.UnreferenceCheckClosed(); } catch (IOException) { Preconditions.CheckArgument(false, this + ": file descriptor " + sock.fd + " was closed while " + "still in the poll(2) loop."); } IOUtils.Cleanup(Log, sock); fdSet.Remove(fd); return(true); } else { if (Log.IsTraceEnabled()) { Log.Trace(this + ": " + caller + ": sendCallback not " + "closing fd " + fd); } return(false); } }
/// <exception cref="System.IO.IOException"/> public DomainSocketWatcher(int interruptCheckPeriodMs, string src) { watcherThread = new Thread(new _Runnable_451(this)); if (loadingFailureReason != null) { throw new NotSupportedException(loadingFailureReason); } Preconditions.CheckArgument(interruptCheckPeriodMs > 0); this.interruptCheckPeriodMs = interruptCheckPeriodMs; notificationSockets = DomainSocket.Socketpair(); watcherThread.SetDaemon(true); watcherThread.SetName(src + " DomainSocketWatcher"); watcherThread.SetUncaughtExceptionHandler(new _UncaughtExceptionHandler_252()); watcherThread.Start(); }
/// <exception cref="System.IO.IOException"/> public override void Write(byte[] b, int off, int len) { this._enclosing.refCount.Reference(); bool exc = true; try { DomainSocket.WriteArray0(this._enclosing.fd, b, off, len); exc = false; } finally { this._enclosing.Unreference(exc); } }
/// <summary>Test that we get a read result of -1 on EOF.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestSocketReadEof() { string TestPath = new FilePath(sockDir.GetDir(), "testSocketReadEof").GetAbsolutePath (); DomainSocket serv = DomainSocket.BindAndListen(TestPath); ExecutorService exeServ = Executors.NewSingleThreadExecutor(); Callable <Void> callable = new _Callable_109(serv); Future <Void> future = exeServ.Submit(callable); DomainSocket conn = DomainSocket.Connect(serv.GetPath()); Thread.Sleep(50); conn.Close(); serv.Close(); future.Get(2, TimeUnit.Minutes); }
/// <exception cref="System.IO.IOException"/> public override int Read(byte[] b, int off, int len) { this._enclosing.refCount.Reference(); bool exc = true; try { int nRead = DomainSocket.ReadArray0(this._enclosing.fd, b, off, len); exc = false; return(nRead); } finally { this._enclosing.Unreference(exc); } }
/// <summary>Run validateSocketPathSecurity</summary> /// <param name="str">The path to validate</param> /// <param name="prefix">A prefix to skip validation for</param> /// <exception cref="System.IO.IOException"/> private static void TestValidateSocketPath(string str, string prefix) { int skipComponents = 1; FilePath prefixFile = new FilePath(prefix); while (true) { prefixFile = prefixFile.GetParentFile(); if (prefixFile == null) { break; } skipComponents++; } DomainSocket.ValidateSocketPathSecurity0(str, skipComponents); }
/// <exception cref="System.IO.IOException"/> public override int Available() { this._enclosing.refCount.Reference(); bool exc = true; try { int nAvailable = DomainSocket.Available0(this._enclosing.fd); exc = false; return(nAvailable); } finally { this._enclosing.Unreference(exc); } }
/// <summary>Test file descriptor passing.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestFdPassing() { string TestPath = new FilePath(sockDir.GetDir(), "test_sock").GetAbsolutePath(); byte[] clientMsg1 = new byte[] { unchecked ((int)(0x11)), unchecked ((int)(0x22)), unchecked ((int)(0x33)), unchecked ((int)(0x44)), unchecked ((int)(0x55)), unchecked ( (int)(0x66)) }; byte[] serverMsg1 = new byte[] { unchecked ((int)(0x31)), unchecked ((int)(0x30)), unchecked ((int)(0x32)), unchecked ((int)(0x34)), unchecked ((int)(0x31)), unchecked ( (int)(0x33)), unchecked ((int)(0x44)), unchecked ((int)(0x1)), unchecked ((int)(0x1 )), unchecked ((int)(0x1)), unchecked ((int)(0x1)), unchecked ((int)(0x1)) }; ArrayBlockingQueue <System.Exception> threadResults = new ArrayBlockingQueue <System.Exception >(2); DomainSocket serv = DomainSocket.BindAndListen(TestPath); TestDomainSocket.PassedFile[] passedFiles = new TestDomainSocket.PassedFile[] { new TestDomainSocket.PassedFile(1), new TestDomainSocket.PassedFile(2) }; FileDescriptor[] passedFds = new FileDescriptor[passedFiles.Length]; for (int i = 0; i < passedFiles.Length; i++) { passedFds[i] = passedFiles[i].GetInputStream().GetFD(); } Thread serverThread = new _Thread_597(serv, clientMsg1, passedFds, serverMsg1 , threadResults); // Run server serverThread.Start(); Thread clientThread = new _Thread_620(TestPath, clientMsg1, serverMsg1, passedFds , passedFiles, threadResults); clientThread.Start(); for (int i_1 = 0; i_1 < 2; i_1++) { System.Exception t = threadResults.Take(); if (!(t is TestDomainSocket.Success)) { NUnit.Framework.Assert.Fail(t.Message + ExceptionUtils.GetStackTrace(t)); } } serverThread.Join(120000); clientThread.Join(120000); serv.Close(); foreach (TestDomainSocket.PassedFile pf in passedFiles) { pf.Cleanup(); } }
/// <exception cref="System.IO.IOException"/> public override int Read() { this._enclosing.refCount.Reference(); bool exc = true; try { byte[] b = new byte[1]; int ret = DomainSocket.ReadArray0(this._enclosing.fd, b, 0, 1); exc = false; return((ret >= 0) ? b[0] : -1); } finally { this._enclosing.Unreference(exc); } }
/// <summary>Add a socket.</summary> /// <param name="sock"> /// The socket to add. It is an error to re-add a socket that /// we are already watching. /// </param> /// <param name="handler"> /// The handler to associate with this socket. This may be /// called any time after this function is called. /// </param> public void Add(DomainSocket sock, DomainSocketWatcher.Handler handler) { Lock.Lock(); try { if (closed) { handler.Handle(sock); IOUtils.Cleanup(Log, sock); return; } DomainSocketWatcher.Entry entry = new DomainSocketWatcher.Entry(sock, handler); try { sock.refCount.Reference(); } catch (ClosedChannelException) { // If the socket is already closed before we add it, invoke the // handler immediately. Then we're done. handler.Handle(sock); return; } toAdd.AddItem(entry); Kick(); while (true) { try { processedCond.Await(); } catch (Exception) { Thread.CurrentThread().Interrupt(); } if (!toAdd.Contains(entry)) { break; } } } finally { Lock.Unlock(); } }
/// <exception cref="System.IO.IOException"/> public override void Write(int val) { this._enclosing.refCount.Reference(); bool exc = true; try { byte[] b = new byte[1]; b[0] = unchecked ((byte)val); DomainSocket.WriteArray0(this._enclosing.fd, b, 0, 1); exc = false; } finally { this._enclosing.Unreference(exc); } }
public Void Call() { DomainSocket serverConn = null; try { serverConn = serv.Accept(); byte[] buf = new byte[100]; for (int i = 0; i < buf.Length; i++) { buf[i] = 0; } if (closeDuringWrite) { try { while (true) { serverConn.GetOutputStream().Write(buf); } } catch (IOException) { } } else { do { }while (serverConn.GetInputStream().Read(buf, 0, buf.Length) != -1); } } catch (IOException e) { throw new RuntimeException("unexpected IOException", e); } finally { IOUtils.Cleanup(DomainSocket.Log, serverConn); } return(null); }
/// <exception cref="System.Exception"/> public virtual void TestShutdown() { AtomicInteger bytesRead = new AtomicInteger(0); AtomicBoolean failed = new AtomicBoolean(false); DomainSocket[] socks = DomainSocket.Socketpair(); Runnable reader = new _Runnable_737(socks, bytesRead, failed); Thread readerThread = new Thread(reader); readerThread.Start(); socks[0].GetOutputStream().Write(1); socks[0].GetOutputStream().Write(2); socks[0].GetOutputStream().Write(3); Assert.True(readerThread.IsAlive()); socks[0].Shutdown(); readerThread.Join(); NUnit.Framework.Assert.IsFalse(failed.Get()); Assert.Equal(3, bytesRead.Get()); IOUtils.Cleanup(null, socks); }
/// <summary>Test file descriptor path security.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestFdPassingPathSecurity() { TemporarySocketDirectory tmp = new TemporarySocketDirectory(); try { string prefix = tmp.GetDir().GetAbsolutePath(); Shell.ExecCommand(new string[] { "mkdir", "-p", prefix + "/foo/bar/baz" }); Shell.ExecCommand(new string[] { "chmod", "0700", prefix + "/foo/bar/baz" }); Shell.ExecCommand(new string[] { "chmod", "0700", prefix + "/foo/bar" }); Shell.ExecCommand(new string[] { "chmod", "0707", prefix + "/foo" }); Shell.ExecCommand(new string[] { "mkdir", "-p", prefix + "/q1/q2" }); Shell.ExecCommand(new string[] { "chmod", "0700", prefix + "/q1" }); Shell.ExecCommand(new string[] { "chmod", "0700", prefix + "/q1/q2" }); TestValidateSocketPath(prefix + "/q1/q2", prefix); try { TestValidateSocketPath(prefix + "/foo/bar/baz", prefix); } catch (IOException e) { GenericTestUtils.AssertExceptionContains("/foo' is world-writable. " + "Its permissions are 0707. Please fix this or select a " + "different socket path.", e); } try { TestValidateSocketPath(prefix + "/nope", prefix); } catch (IOException e) { GenericTestUtils.AssertExceptionContains("failed to stat a path " + "component: " , e); } // Root should be secure DomainSocket.ValidateSocketPathSecurity0("/foo", 1); } finally { tmp.Close(); } }
public override void Run() { DomainSocket conn = null; try { conn = serv.Accept(); byte[] in1 = new byte[clientMsg1.Length]; InputStream connInputStream = conn.GetInputStream(); IOUtils.ReadFully(connInputStream, in1, 0, in1.Length); Assert.True(Arrays.Equals(clientMsg1, in1)); DomainSocket domainConn = (DomainSocket)conn; domainConn.SendFileDescriptors(passedFds, serverMsg1, 0, serverMsg1.Length); conn.Close(); } catch (System.Exception e) { threadResults.AddItem(e); NUnit.Framework.Assert.Fail(e.Message); } threadResults.AddItem(new TestDomainSocket.Success()); }
/// <summary>Test a simple client/server interaction.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> internal virtual void TestClientServer1(Type writeStrategyClass, Type readStrategyClass , DomainSocket[] preConnectedSockets) { string TestPath = new FilePath(sockDir.GetDir(), "test_sock_client_server1").GetAbsolutePath (); byte[] clientMsg1 = new byte[] { unchecked ((int)(0x1)), unchecked ((int)(0x2)), unchecked ( (int)(0x3)), unchecked ((int)(0x4)), unchecked ((int)(0x5)), unchecked ((int)(0x6)) }; byte[] serverMsg1 = new byte[] { unchecked ((int)(0x9)), unchecked ((int)(0x8)), unchecked ( (int)(0x7)), unchecked ((int)(0x6)), unchecked ((int)(0x5)) }; byte clientMsg2 = unchecked ((int)(0x45)); ArrayBlockingQueue <Exception> threadResults = new ArrayBlockingQueue <Exception>(2 ); DomainSocket serv = (preConnectedSockets != null) ? null : DomainSocket.BindAndListen (TestPath); Thread serverThread = new _Thread_435(preConnectedSockets, serv, clientMsg1 , readStrategyClass, writeStrategyClass, serverMsg1, clientMsg2, threadResults); // Run server serverThread.Start(); Thread clientThread = new _Thread_463(preConnectedSockets, TestPath, writeStrategyClass , clientMsg1, readStrategyClass, serverMsg1, clientMsg2, threadResults); clientThread.Start(); for (int i = 0; i < 2; i++) { Exception t = threadResults.Take(); if (!(t is TestDomainSocket.Success)) { NUnit.Framework.Assert.Fail(t.Message + ExceptionUtils.GetStackTrace(t)); } } serverThread.Join(120000); clientThread.Join(120000); if (serv != null) { serv.Close(); } }
/// <exception cref="System.IO.IOException"/> public virtual int Read(ByteBuffer dst) { this._enclosing.refCount.Reference(); bool exc = true; try { int nread = 0; if (dst.IsDirect()) { nread = DomainSocket.ReadByteBufferDirect0(this._enclosing.fd, dst, dst.Position( ), dst.Remaining()); } else { if (dst.HasArray()) { nread = DomainSocket.ReadArray0(this._enclosing.fd, ((byte[])dst.Array()), dst.Position () + dst.ArrayOffset(), dst.Remaining()); } else { throw new Exception("we don't support " + "using ByteBuffers that aren't either direct or backed by " + "arrays"); } } if (nread > 0) { dst.Position(dst.Position() + nread); } exc = false; return(nread); } finally { this._enclosing.Unreference(exc); } }