protected void sendToBrother(SelectionKey key, ByteBuffer buffer) { if (isTunnelEstablished() && buffer.HasRemaining) { mBrotherTunnel.getWriteDataFromBrother(buffer); } }
public SettingsWindow() { InitializeComponent(); ViewModel = new SettingsWindowViewModel(); this.Bind(ViewModel, x => x.Settings.AlwaysOnTop, x => x.AlwaysOnTop.IsChecked); this.Bind(ViewModel, x => x.Settings.CopyLinks, x => x.CopyLinks.IsChecked); this.Bind(ViewModel, x => x.Settings.RunOnStartup, x => x.RunOnStartup.IsChecked); this.Bind(ViewModel, x => x.Settings.StartMinimized, x => x.StartMinimized.IsChecked); this.Bind(ViewModel, x => x.Settings.Notifications, x => x.Notifications.IsChecked); this.Bind(ViewModel, x => x.Settings.ImageFormat, x => x.ImageFormat.SelectedItem); this.Bind(ViewModel, x => x.Settings.ImageQuality, x => x.QualitySlider.Value); this.OneWayBind(ViewModel, x => x.Settings.ScreenKey, x => x.ScreenKey.Text, null, null, new HotKeyToStringConverter()); this.OneWayBind(ViewModel, x => x.Settings.SelectionKey, x => x.SelectionKey.Text, null, null, new HotKeyToStringConverter()); this.BindCommand(ViewModel, x => x.CloseCommand, x => x.ButtonClose); this.WhenAnyObservable(x => x.ViewModel.CloseCommand).Subscribe(_ => Close()); this.WhenAnyObservable(x => x.ViewModel.Settings.Changed).Subscribe(e => TextStatus.Text = "Settings Saved"); this.WhenAnyObservable(x => x.ViewModel.ExceptionCommand).Subscribe(x => { var ex = x as Exception; MessageBox.Show(ex.Message, App.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error); }); ScreenKey.Events().PreviewKeyUp.Subscribe(e => { var hk = ProcessKey(e); ViewModel.KeyCommand.Execute(Tuple.Create("ScreenKey", hk)); }); SelectionKey.Events().PreviewKeyUp.Subscribe(e => { var hk = ProcessKey(e); ViewModel.KeyCommand.Execute(Tuple.Create("SelectionKey", hk)); }); }
// -- Utility methods for the key set -- private void AddKey(SelectionKey k) { Debug.Assert(Thread.holdsLock(KeyLock)); int i = 0; if ((Keys != null) && (KeyCount < Keys.Length)) { // Find empty element of key array for (i = 0; i < Keys.Length; i++) { if (Keys[i] == null) { break; } } } else if (Keys == null) { Keys = new SelectionKey[3]; } else { // Grow key array int n = Keys.Length * 2; SelectionKey[] ks = new SelectionKey[n]; for (i = 0; i < Keys.Length; i++) { ks[i] = Keys[i]; } Keys = ks; i = KeyCount; } Keys[i] = k; KeyCount++; }
public void onReadable(SelectionKey key) { try { var buffer = ByteBuffer.Allocate(FirewallVpnService.MUTE_SIZE); buffer.Clear(); int bytesRead = mInnerChannel.Read(buffer); if (bytesRead > 0) { buffer.Flip(); afterReceived(buffer); sendToBrother(key, buffer); } else if (bytesRead < 0) { Dispose(); } } catch (Exception ex) { Debug.Fail($"onReadable catch an exception: {ex.ToString()}"); Dispose(); } }
public override int GetHashCode() { unchecked { return(((SelectionKey?.GetHashCode() ?? 0) * 397) ^ Price.GetHashCode()); } }
void onAccepted(SelectionKey key, Context context) { TcpTunnel localTunnel = null; try { var localChannel = mServerSocketChannel.Accept(); localTunnel = TunnelFactory.wrap(localChannel, mSelector); short portKey = (short)localChannel.Socket().Port; var destAddress = getDestAddress(localChannel); if (destAddress != null) { TcpTunnel remoteTunnel = TunnelFactory.createTunnelByConfig(destAddress, mSelector, portKey, context); remoteTunnel.isHttpsRequest = localTunnel.isHttpsRequest; remoteTunnel.setBrotherTunnel(localTunnel); localTunnel.setBrotherTunnel(remoteTunnel); remoteTunnel.connect(destAddress); } } catch (Exception ex) { Debug.Fail($"TcpProxyServer onAccepted catch an exception: {ex}"); if (localTunnel != null) { localTunnel.dispose(); } } }
internal virtual void Cancel(SelectionKey k) // package-private { lock (CancelledKeys_Renamed) { CancelledKeys_Renamed.Add(k); } }
/* * Process activity from one of the debugger sockets. This could be a new * connection or a data packet. */ private void processDebuggerActivity(SelectionKey key) { Debugger dbg = (Debugger)key.attachment(); try { if (key.acceptable) { try { acceptNewDebugger(dbg, null); } catch (IOException ioe) { Log.w("ddms", "debugger accept() failed"); Console.WriteLine(ioe.ToString()); Console.Write(ioe.StackTrace); } } else if (key.readable) { processDebuggerData(key); } else { Log.d("ddm-debugger", "key in unknown state"); } } catch (CancelledKeyException) { // key has been cancelled we can ignore that. } }
private void ProcessConnect(SelectionKey key, List <SelectionKey> keyIterator) { TCB tcb = (TCB)key.Attachment(); Packet referencePacket = tcb.referencePacket; try { if (tcb.channel.FinishConnect()) { if (keyIterator[0] != null) { keyIterator.RemoveAt(0); } tcb.status = TCBStatus.SYN_RECEIVED; // TODO: Set MSS for receiving larger packets from the device ByteBuffer responseBuffer = ByteBufferPool.acquire(); referencePacket.updateTCPBuffer(responseBuffer, (byte)(Packet.TCPHeader.SYN | Packet.TCPHeader.ACK), tcb.mySequenceNum, tcb.myAcknowledgementNum, 0); outputQueue.Offer(responseBuffer); tcb.mySequenceNum++; // SYN counts as a byte //key.InterestOps(Operations.Read); key.InterestOps(); } } catch (IOException e) { Log.Error(TAG, "Connection error: " + tcb.ipAndPort, e); ByteBuffer responseBuffer = ByteBufferPool.acquire(); referencePacket.updateTCPBuffer(responseBuffer, (byte)Packet.TCPHeader.RST, 0, tcb.myAcknowledgementNum, 0); outputQueue.Offer(responseBuffer); TCB.CloseTCB(tcb); } }
public void onWritable(SelectionKey key) { try { if (!needWriteData.TryDequeue(out ByteBuffer mSendRemainBuffer)) { return; } write(mSendRemainBuffer); if (needWriteData.Count == 0) { try { mSelector.Wakeup(); mInnerChannel.Register(mSelector, Operations.Read, this); } catch (ClosedChannelException ex) { ex.PrintStackTrace(); } } } catch (Exception ex) { Debug.Fail($"onWritable catch an exception: {ex.ToString()}"); Dispose(); } }
/* * We have incoming data from the debugger. Forward it to the client. */ private void processDebuggerData(SelectionKey key) { Debugger dbg = (Debugger)key.attachment(); try { /* * Read pending data. */ dbg.read(); /* * See if we have a full packet in the buffer. It's possible we have * more than one packet, so we have to loop. */ JdwpPacket packet = dbg.jdwpPacket; while (packet != null) { Log.v("ddms", "Forwarding dbg req 0x" + packet.id.toHexString() + " to " + dbg.client); dbg.forwardPacketToClient(packet); packet = dbg.jdwpPacket; } } catch (IOException) { /* * Close data connection; automatically un-registers dbg from * selector. The failure could be caused by the debugger going away, * or by the client going away and failing to accept our data. * Either way, the debugger connection does not need to exist any * longer. We also need to recycle the connection to the client, so * that the VM sees the debugger disconnect. For a DDM-aware client * this won't be necessary, and we can just send a "debugger * disconnected" message. */ Log.d("ddms", "Closing connection to debugger " + dbg); dbg.closeData(); Client client = dbg.client; if (client.ddmAware) { // TODO: soft-disconnect DDM-aware clients Log.d("ddms", " (recycling client connection as well)"); // we should drop the client, but also attempt to reopen it. // This is done by the DeviceMonitor. client.deviceImpl.monitor.addClientToDropAndReopen(client, DebugPortManager.DebugPortProvider.NO_STATIC_PORT); } else { Log.d("ddms", " (recycling client connection as well)"); // we should drop the client, but also attempt to reopen it. // This is done by the DeviceMonitor. client.deviceImpl.monitor.addClientToDropAndReopen(client, DebugPortManager.DebugPortProvider.NO_STATIC_PORT); } } }
// 10 seconds. /// <summary> /// Waits on the channel with the given timeout using one of the /// cached selectors. /// </summary> /// <remarks> /// Waits on the channel with the given timeout using one of the /// cached selectors. It also removes any cached selectors that are /// idle for a few seconds. /// </remarks> /// <param name="channel"/> /// <param name="ops"/> /// <param name="timeout"/> /// <returns/> /// <exception cref="System.IO.IOException"/> internal virtual int Select(SelectableChannel channel, int ops, long timeout) { SocketIOWithTimeout.SelectorPool.SelectorInfo info = Get(channel); SelectionKey key = null; int ret = 0; try { while (true) { long start = (timeout == 0) ? 0 : Time.Now(); key = channel.Register(info.selector, ops); ret = info.selector.Select(timeout); if (ret != 0) { return(ret); } if (Thread.CurrentThread().IsInterrupted()) { throw new ThreadInterruptedException("Interrupted while waiting for " + "IO on channel " + channel + ". " + timeout + " millis timeout left."); } /* Sometimes select() returns 0 much before timeout for * unknown reasons. So select again if required. */ if (timeout > 0) { timeout -= Time.Now() - start; if (timeout <= 0) { return(0); } } } } finally { if (key != null) { key.Cancel(); } //clear the canceled key. try { info.selector.SelectNow(); } catch (IOException e) { Log.Info("Unexpected Exception while clearing selector : ", e); // don't put the selector back. info.Close(); return(ret); } Release(info); } }
protected virtual void doRegister() { if (windowsChannel() == null) { return; } _selectionKey = windowsChannel().register(((NioEventLoop)(eventLoop())).unwrappedSelector(), this); }
private void handleRead(SelectionKey key) { // Log.d("MIDIPort2","handleRead"); DatagramChannel c = (DatagramChannel)key.channel(); UDPBuffer b = (UDPBuffer)key.attachment(); try { b.buffer.clear(); b.socketAddress = c.receive(b.buffer); EventBus.getDefault().post(new PacketEvent(new DatagramPacket(b.buffer.array(), b.buffer.capacity(), b.socketAddress))); } catch (IOException e) { e.printStackTrace(); } }
internal virtual void RemoveKey(SelectionKey k) // package-private { lock (KeyLock) { for (int i = 0; i < Keys.Length; i++) { if (Keys[i] == k) { Keys[i] = null; KeyCount--; } ((AbstractSelectionKey)k).invalidate(); } } }
private void handleWrite(SelectionKey key) { if (!outboundQueue.isEmpty()) { // Log.d("MIDIPort2","handleWrite "+ outboundQueue.size()); try { DatagramChannel c = (DatagramChannel)key.channel(); DatagramPacket d = outboundQueue.poll(); c.send(ByteBuffer.wrap(d.getData()), d.getSocketAddress()); } catch (IOException e) { e.printStackTrace(); } } }
public void onKeyReady(SelectionKey key) { if (key.IsReadable) { onReadable(key); } else if (key.IsWritable) { onWritable(key); } else if (key.IsConnectable) { onConnectable(); } }
// -- Closing -- /// <summary> /// Closes this channel. /// /// <para> This method, which is specified in the {@link /// AbstractInterruptibleChannel} class and is invoked by the {@link /// java.nio.channels.Channel#close close} method, in turn invokes the /// <seealso cref="#implCloseSelectableChannel implCloseSelectableChannel"/> method in /// order to perform the actual work of closing this channel. It then /// cancels all of this channel's keys. </para> /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected final void implCloseChannel() throws java.io.IOException protected internal sealed override void ImplCloseChannel() { ImplCloseSelectableChannel(); lock (KeyLock) { int count = (Keys == null) ? 0 : Keys.Length; for (int i = 0; i < count; i++) { SelectionKey k = Keys[i]; if (k != null) { k.Cancel(); } } } }
private void HandleRead(SelectionKey key) { try { c = (DatagramChannel)key.Channel(); b = (UDPBuffer)key.Attachment(); b.buffer.Clear(); b.socketAddress = c.Receive(b.buffer); b.buffer.Flip(); b.buffer.Get(buff, 0, b.buffer.Limit()); MessagingCenter.Send <PacketEvent>(new PacketEvent(new Java.Net.DatagramPacket(buff, b.buffer.Limit(), b.socketAddress)), "PacketEvent"); } catch (Exception e) { throw new IOException(e.StackTrace); } }
/* * We have some activity on the "debug selected" port. Handle it. */ private void processDebugSelectedActivity(SelectionKey key) { Debug.Assert(key.acceptable); ServerSocketChannel acceptChan = (ServerSocketChannel)key.channel(); /* * Find the debugger associated with the currently-selected client. */ if (mSelectedClient != null) { Debugger dbg = mSelectedClient.debugger; if (dbg != null) { Log.d("ddms", "Accepting connection on 'debug selected' port"); try { acceptNewDebugger(dbg, acceptChan); } catch (IOException) { // client should be gone, keep going } return; } } Log.w("ddms", "Connection on 'debug selected' port, but none selected"); try { SocketChannel chan = acceptChan.accept(); chan.close(); } catch (IOException) { // not expected; client should be gone, keep going } catch (NotYetBoundException) { displayDebugSelectedBindError(mDebugSelectedPort); } }
private void HandleWrite(SelectionKey key) { if (!(outboundQueue.Count == 0)) { if (DEBUG) { Log.Debug("MIDIPort2", "handleWrite " + outboundQueue.Count); } try { DatagramChannel c = (DatagramChannel)key.Channel(); DatagramPacket d = outboundQueue.Dequeue(); if (d != null) { c.Send(ByteBuffer.Wrap(d.GetData()), d.SocketAddress); } } catch (IOException e) { throw new IOException(e.StackTrace); } } }
public void Run() { while (isListening) { try { selector.select(); Set <SelectionKey> readyKeys = selector.selectedKeys(); if (readyKeys.isEmpty()) { break; } else { Iterator <SelectionKey> keyIter = readyKeys.iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); keyIter.remove(); if (!key.isValid()) { continue; } if (key.isReadable()) { handleRead(key); } if (key.isWritable()) { handleWrite(key); } } } } catch (IOException e) { e.printStackTrace(); } } }
/// <summary> /// Registers this channel with the given selector, returning a selection key. /// /// <para> This method first verifies that this channel is open and that the /// given initial interest set is valid. /// /// </para> /// <para> If this channel is already registered with the given selector then /// the selection key representing that registration is returned after /// setting its interest set to the given value. /// /// </para> /// <para> Otherwise this channel has not yet been registered with the given /// selector, so the <seealso cref="AbstractSelector#register register"/> method of /// the selector is invoked while holding the appropriate locks. The /// resulting key is added to this channel's key set before being returned. /// </para> /// </summary> /// <exception cref="ClosedSelectorException"> {@inheritDoc} /// </exception> /// <exception cref="IllegalBlockingModeException"> {@inheritDoc} /// </exception> /// <exception cref="IllegalSelectorException"> {@inheritDoc} /// </exception> /// <exception cref="CancelledKeyException"> {@inheritDoc} /// </exception> /// <exception cref="IllegalArgumentException"> {@inheritDoc} </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public final SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException public sealed override SelectionKey Register(Selector sel, int ops, Object att) { lock (RegLock) { if (!Open) { throw new ClosedChannelException(); } if ((ops & ~ValidOps()) != 0) { throw new IllegalArgumentException(); } if (Blocking_Renamed) { throw new IllegalBlockingModeException(); } SelectionKey k = FindKey(sel); if (k != null) { k.InterestOps(ops); k.Attach(att); } if (k == null) { // New registration lock (KeyLock) { if (!Open) { throw new ClosedChannelException(); } k = ((AbstractSelector)sel).Register(this, ops, att); AddKey(k); } } return(k); } }
/* * Something happened. Figure out what. */ private void processClientActivity(SelectionKey key) { Client client = (Client)key.attachment(); try { if (key.readable == false || key.valid == false) { Log.d("ddms", "Invalid key from " + client + ". Dropping client."); dropClient(client, true); // notify return; } client.read(); /* * See if we have a full packet in the buffer. It's possible we have * more than one packet, so we have to loop. */ JdwpPacket packet = client.jdwpPacket; while (packet != null) { if (packet.ddmPacket) { // unsolicited DDM request - hand it off Debug.Assert(!packet.reply); callHandler(client, packet, null); packet.consume(); } else if (packet.reply && client.isResponseToUs(packet.id) != null) { // reply to earlier DDM request ChunkHandler handler = client.isResponseToUs(packet.id); if (packet.error) { client.packetFailed(packet); } else if (packet.empty) { Log.d("ddms", "Got empty reply for 0x" + packet.id.toHexString() + " from " + client); } else { callHandler(client, packet, handler); } packet.consume(); client.removeRequestId(packet.id); } else { Log.v("ddms", "Forwarding client " + (packet.reply ? "reply" : "event") + " 0x" + packet.id.toHexString() + " to " + client.debugger); client.forwardPacketToDebugger(packet); } // find next packet = client.jdwpPacket; } } catch (CancelledKeyException) { // key was canceled probably due to a disconnected client before we could // read stuff coming from the client, so we drop it. dropClient(client, true); // notify } catch (IOException) { // something closed down, no need to print anything. The client is simply dropped. dropClient(client, true); // notify } catch (Exception ex) { Log.e("ddms", ex); /* close the client; automatically un-registers from selector */ dropClient(client, true); // notify if (ex is OverflowException) { Log.w("ddms", "Client data packet exceeded maximum buffer size " + client); } else { // don't know what this is, display it Log.e("ddms", ex); } } }
private void processInput(SelectionKey key, List <SelectionKey> keyIterator) { System.Console.WriteLine("TCP In"); try { if (keyIterator[0] != null) { keyIterator.RemoveAt(0); } ByteBuffer receiveBuffer = ByteBufferPool.acquire(); // Leave space for the header receiveBuffer.Position(HEADER_SIZE); TCB tcb = (TCB)key.Attachment(); lock (tcb) { Packet referencePacket = tcb.referencePacket; SocketChannel inputChannel = (SocketChannel)key.Channel(); int readBytes; try { readBytes = inputChannel.Read(receiveBuffer); } catch (IOException e) { Log.Error(TAG, "Network read error: " + tcb.ipAndPort, e); referencePacket.updateTCPBuffer(receiveBuffer, (byte)Packet.TCPHeader.RST, 0, tcb.myAcknowledgementNum, 0); outputQueue.Offer(receiveBuffer); TCB.CloseTCB(tcb); return; } if (readBytes == -1) { // End of stream, stop waiting until we push more data //key.InterestOps(0); key.InterestOps(); tcb.waitingForNetworkData = false; if (tcb.status != TCBStatus.CLOSE_WAIT) { ByteBufferPool.Release(receiveBuffer); return; } tcb.status = TCBStatus.LAST_ACK; referencePacket.updateTCPBuffer(receiveBuffer, (byte)Packet.TCPHeader.FIN, tcb.mySequenceNum, tcb.myAcknowledgementNum, 0); tcb.mySequenceNum++; // FIN counts as a byte } else { // XXX: We should ideally be splitting segments by MTU/MSS, but this seems to work without referencePacket.updateTCPBuffer(receiveBuffer, (byte)(Packet.TCPHeader.PSH | Packet.TCPHeader.ACK), tcb.mySequenceNum, tcb.myAcknowledgementNum, readBytes); tcb.mySequenceNum += readBytes; // Next sequence number receiveBuffer.Position(HEADER_SIZE + readBytes); } } outputQueue.Offer(receiveBuffer); } catch (Java.Lang.Exception ex) { System.Console.WriteLine(ex.Message); } }
public void setCurSelectionKey(SelectionKey lastKey) { curSelectionKey = lastKey; }