/// <summary>Handler for messages on the control channel.</summary> byte[] ControlReply(byte[] IMsg, int IOf, int IOc, out int OOf, out int OOc) { int MsgT = GetInt(IMsg, IOf); MessageType Type = (MessageType)MsgT; int Reference; switch (Type) { case MessageType.Handshake: OOf = IOf; OOc = IOc; return(IMsg); case MessageType.OpenReference: byte[] IV = EncryptWrapper.RequestIV(); Reference = GetInt(IMsg, IOf + 4); CreateChannel(Reference, IV); OOf = 0; OOc = IV.Length; return(IV); case MessageType.CloseReference: Reference = GetInt(IMsg, IOf + 4); ControlChannel.UnregisterCallback(Reference); lock (DataChannels) DataChannels.Remove(Reference); OOf = IOf; OOc = IOc; return(IMsg); } OOf = 0; OOc = 0; return(new byte[0]); }
public override bool Init(ControlChannel controlClient, TransferMode mode) { var command = "LIST" + (string.IsNullOrWhiteSpace(infoTargetName) ? string.Empty : " " + infoTargetName); _dataClient = PrepareDataChannel(controlClient, mode, command); return true; }
override public void Connect(string user, string pass) { ControlChannel ctrl = new ControlChannel(m_host); ctrl.Server = m_server; ctrl.Port = m_port; ctrl.Connect(); try { ctrl.FtpCommand("USER " + user); if (ctrl.LastResponse.Code == FtpResponse.UserAcceptedWaitingPass) { ctrl.FtpCommand("PASS " + pass); } if (ctrl.LastResponse.Code != FtpResponse.UserLoggedIn) { throw new FtpException("Failed to login.", ctrl.LastResponse); } m_host.State = new SessionConnected(m_host, ctrl); ((SessionConnected)m_host.State).InitRootDirectory(); } catch { ctrl.Close(); throw; } }
public override bool Init(ControlChannel controlClient, TransferMode mode) { var command = "LIST" + (string.IsNullOrWhiteSpace(infoTargetName) ? string.Empty : " " + infoTargetName); _dataClient = PrepareDataChannel(controlClient, mode, command); return(true); }
public override async Task Process(ControlChannel controlClient) { var operation = DownloadData(_dataClient); await _deferredResponse; if (!operation.IsCompleted) { await Task.Delay(1000); _cancelToken.Cancel(); } }
/// <summary>Sends an open reference request to the remote peer and creates the associated channel.</summary> void SendOpenReference(int Reference) { int RT = (int)MessageType.OpenReference; byte[] data = new byte[8] { (byte)(RT % 256), (byte)(RT / 256 % 256), (byte)(RT / 65536 % 256), (byte)(RT / 16777216 % 256), (byte)(Reference % 256), (byte)(Reference / 256 % 256), (byte)(Reference / 65536 % 256), (byte)(Reference / 16777216 % 256) }; byte[] IV = ControlChannel.SendReceive(1, data, 8); CreateChannel(Reference, IV); }
/// <summary>Send a handshake to check the channel.</summary> void SendHandshake() { int HT = (int)MessageType.Handshake; byte[] Hdata = new byte[4] { (byte)(HT % 256), (byte)(HT / 256 % 256), (byte)(HT / 65536 % 256), (byte)(HT / 16777216 % 256) }; byte[] Reply = ControlChannel.SendReceive(1, Hdata, 4); if (!((Reply[0] == Hdata[0]) & (Reply[1] == Hdata[1]) & (Reply[2] == Hdata[2]) & (Reply[3] == Hdata[3]))) { throw new System.Net.ProtocolViolationException("Handshake failed"); } }
public override async Task Process(ControlChannel controlClient) { _stream = _fileInfo.OpenRead(); await UploadData(_dataClient, _stream); if (_dataClient != null) { _dataClient.Client.Close(5); } await _deferredResponse; }
protected TcpClient PrepareDataChannel(ControlChannel controlChannel, TransferMode mode, string operationCommand) { if (mode == TransferMode.Active) { // ACTIVE mode var dataListener = new TcpListener(new IPEndPoint(controlChannel.LocalEndPoint.Address, 0)); dataListener.Start(); var endPoint = (IPEndPoint)dataListener.LocalEndpoint; var addressBytes = endPoint.Address.MapToIPv4().GetAddressBytes(); string response; var respCode = controlChannel.SendCommand($"PORT {addressBytes[0]},{addressBytes[1]},{addressBytes[2]},{addressBytes[3]},{endPoint.Port >> 8},{endPoint.Port & 0xff}", out response, ReturnCodes.ActionCompleted); TcpClient dataClient = null; if (respCode < 300) { _deferredResponse = controlChannel.SendCommandDeferred(operationCommand); dataClient = dataListener.AcceptTcpClient(); dataListener.Stop(); } return dataClient; } else { string response; var returnCode = controlChannel.SendCommand($"PASV", out response, ReturnCodes.EnteringPassiveMode); if (returnCode == (int)ReturnCodes.EnteringPassiveMode) { // extract address & port from response var mx = Regex.Match(response, @"\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3}"); //mx.Success var values = mx.Value.Split(',').Select(val => Convert.ToByte(val)).ToArray(); var addressBytes = values.Take(4).ToArray(); var ep = new IPEndPoint(new IPAddress(addressBytes), (values[4] << 8) + values[5]); _dataClient = new TcpClient(new IPEndPoint(controlChannel.LocalEndPoint.Address, 0)); _dataClient.Connect(ep); _deferredResponse = controlChannel.SendCommandDeferred(operationCommand); return _dataClient; } else { Console.WriteLine("Passive mode failed, attempt with active mode"); return PrepareDataChannel(controlChannel, TransferMode.Active, operationCommand); } } }
protected TcpClient PrepareDataChannel(ControlChannel controlChannel, TransferMode mode, string operationCommand) { if (mode == TransferMode.Active) { // ACTIVE mode var dataListener = new TcpListener(new IPEndPoint(controlChannel.LocalEndPoint.Address, 0)); dataListener.Start(); var endPoint = (IPEndPoint)dataListener.LocalEndpoint; var addressBytes = endPoint.Address.MapToIPv4().GetAddressBytes(); string response; var respCode = controlChannel.SendCommand($"PORT {addressBytes[0]},{addressBytes[1]},{addressBytes[2]},{addressBytes[3]},{endPoint.Port >> 8},{endPoint.Port & 0xff}", out response, ReturnCodes.ActionCompleted); TcpClient dataClient = null; if (respCode < 300) { _deferredResponse = controlChannel.SendCommandDeferred(operationCommand); dataClient = dataListener.AcceptTcpClient(); dataListener.Stop(); } return(dataClient); } else { string response; var returnCode = controlChannel.SendCommand($"PASV", out response, ReturnCodes.EnteringPassiveMode); if (returnCode == (int)ReturnCodes.EnteringPassiveMode) { // extract address & port from response var mx = Regex.Match(response, @"\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3}"); //mx.Success var values = mx.Value.Split(',').Select(val => Convert.ToByte(val)).ToArray(); var addressBytes = values.Take(4).ToArray(); var ep = new IPEndPoint(new IPAddress(addressBytes), (values[4] << 8) + values[5]); _dataClient = new TcpClient(new IPEndPoint(controlChannel.LocalEndPoint.Address, 0)); _dataClient.Connect(ep); _deferredResponse = controlChannel.SendCommandDeferred(operationCommand); return(_dataClient); } else { Console.WriteLine("Passive mode failed, attempt with active mode"); return(PrepareDataChannel(controlChannel, TransferMode.Active, operationCommand)); } } }
public override bool Init(ControlChannel controlClient, TransferMode mode) { if (Directory.Exists(_fileInfo.DirectoryName) && _fileInfo.Exists) { //file with given name already exists Console.WriteLine($"ERROR: {_fileInfo.FullName} already exists"); return false; } var command = $"RETR {_serverFileName}"; _dataClient = PrepareDataChannel(controlClient, mode, command); return true; }
/// <summary> /// /// </summary> /// <returns></returns> private async Task WaitForChannelsAsync() { Task <ChannelOpen> video = WaitForChannelOpenAsync(NanoChannel.Video); Task <ChannelOpen> audio = WaitForChannelOpenAsync(NanoChannel.Audio); Task <ChannelOpen> chatAudio = WaitForChannelOpenAsync(NanoChannel.ChatAudio); Task <ChannelOpen> control = WaitForChannelOpenAsync(NanoChannel.Control); await Task.WhenAll(video, audio, chatAudio, control); Video = new VideoChannel(_transport, video.Result, FireVideoFrameAvailable); Audio = new AudioChannel(_transport, audio.Result, FireAudioFrameAvailable); ChatAudio = new ChatAudioChannel(_transport, chatAudio.Result); Control = new ControlChannel(_transport, control.Result); }
public override bool Init(ControlChannel controlClient, TransferMode mode) { if (Directory.Exists(_fileInfo.DirectoryName) && _fileInfo.Exists) { //file with given name already exists Console.WriteLine($"ERROR: {_fileInfo.FullName} already exists"); return(false); } var command = $"RETR {_serverFileName}"; _dataClient = PrepareDataChannel(controlClient, mode, command); return(true); }
/// <summary> /// Establishes the connection to the control socket, which allows us to send important kernel messages like shutdown. /// <remarks>Given the nature of these commands, this channel is only available to the overall kernel manager, and not each /// individual client.</remarks> /// </summary> private void CreateControlChannel() { if (ControlChannel != null) { throw new Exception("The channel has already been initialized"); } ControlChannel = ChannelFactory.CreateChannel(ChannelNames.Control); ControlChannel.Start(); ControlThread = new Thread(() => EventLoop(ControlChannel)) { Name = "Control Channel" }; ControlThread.Start(); }
void UpdateChangeLinkEnable() { LightElementVM master = MasterSelectedItem; ControlChannel detail = DetailSelectedItem; if (master != null && DetailSelectedItem != null) { if (master.DirectChild) { master.ChangeLinkEnable = true; return; } if (!master.IsLinked && detail.LE_Count == 0) { master.ChangeLinkEnable = true; return; } if (!master.IsLinked && detail.LE_Count > 0 && detail.Multilink && master.Model.PointType == detail.PointType) { master.ChangeLinkEnable = true; return; } if (master.IsLinked && !detail.DirectParent) { master.ChangeLinkEnable = false; return; } } else { if (master != null) { master.ChangeLinkEnable = false; } } }
/// <summary> /// Send a request over the control channel to shut down the kernel /// </summary> /// <returns>True if successful, False otherwise</returns> private bool SendShutdownRequest() { if (ControlChannel == null) { return(false); } else { try { var message = ClientSession.CreateMessage(MessageType.ShutdownRequest); message.Content = new ExpandoObject(); message.Content.restart = false; ControlChannel.Send(message); // Wait up to SHUTDOWN_WAIT_TIME seconds for a response. We are going to poll in small increments // to see if we have gotten a response. int waitCycles = SHUTDOWN_WAIT_TIME / WAIT_CYCLE_DURATION; for (int index = 0; index < waitCycles; index++) { lock (ShutdownSync) { if (ShutdownSuccess) { return(true); } } Thread.Sleep(WAIT_CYCLE_DURATION); } } catch (Exception exc) { Logger.Write("Exception when trying to shut down {0}", exc.Message); return(false); } } return(false); }
override public void Connect(string user, string pass) { ControlChannel ctrl = new ControlChannel(m_host); ctrl.Server = m_server; ctrl.Port = m_port; ctrl.Connect(); try { ctrl.FtpCommand("USER " + user); if (ctrl.LastResponse.Code == FtpResponse.UserAcceptedWaitingPass) ctrl.FtpCommand("PASS " + pass); if (ctrl.LastResponse.Code != FtpResponse.UserLoggedIn) throw new FtpException("Failed to login.", ctrl.LastResponse); m_host.State = new SessionConnected(m_host, ctrl); ((SessionConnected)m_host.State).InitRootDirectory(); } catch { ctrl.Close(); throw; } }
public abstract Task Process(ControlChannel controlClient);
public abstract bool Init(ControlChannel controlClient, TransferMode mode);
public Session(string filename) { this.filename = filename; engine_identity = System.Guid.NewGuid().ToString(); string json; if (this.filename != "") { json = File.ReadAllText(this.filename); config = decode(json); Console.Error.WriteLine(String.Format("config: {0}", config ["transport"])); Console.Error.WriteLine(String.Format("config: {0}", config ["ip"])); Console.Error.WriteLine(String.Format("config: {0}", config ["hb_port"])); } else { config = dict("key", System.Guid.NewGuid().ToString(), "signature_scheme", "hmac-sha256", "transport", "tcp", "ip", "127.0.0.1", "hb_port", "0", "shell_port", "0", "iopub_port", "0", "control_port", "0", "stdin_port", "0"); } auth = new Authorization(config ["key"].ToString(), config ["signature_scheme"].ToString()); hb_channel = new HeartBeatChannel(this, auth, config ["transport"].ToString(), config ["ip"].ToString(), config ["hb_port"].ToString()); shell_channel = new ShellChannel(this, auth, config ["transport"].ToString(), config ["ip"].ToString(), config ["shell_port"].ToString()); iopub_channel = new IOPubChannel(this, auth, config ["transport"].ToString(), config ["ip"].ToString(), config ["iopub_port"].ToString()); control_channel = new ControlChannel(this, auth, config ["transport"].ToString(), config ["ip"].ToString(), config ["control_port"].ToString()); stdin_channel = new StdInChannel(this, auth, config ["transport"].ToString(), config ["ip"].ToString(), config ["stdin_port"].ToString()); if (this.filename == "") { config ["hb_port"] = hb_channel.port; config ["shell_port"] = shell_channel.port; config ["iopub_port"] = iopub_channel.port; config ["control_port"] = control_channel.port; config ["stdin_port"] = stdin_channel.port; string kernelname = String.Format("kernel-{0}.json", System.Diagnostics.Process.GetCurrentProcess().Id); string ipython_config = ("{{\n" + " \"hb_port\": {0},\n" + " \"shell_port\": {1},\n" + " \"iopub_port\": {2},\n" + " \"control_port\": {3},\n" + " \"stdin_port\": {4},\n" + " \"ip\": \"{5}\",\n" + " \"signature_scheme\": \"{6}\",\n" + " \"key\": \"{7}\",\n" + " \"transport\": \"{8}\"\n" + "}}"); ipython_config = String.Format(ipython_config, config ["hb_port"], config ["shell_port"], config ["iopub_port"], config ["control_port"], config ["stdin_port"], config ["ip"], config ["signature_scheme"], config ["key"], config ["transport"]); System.IO.StreamWriter sw = new System.IO.StreamWriter(this.filename); sw.Write(ipython_config); sw.Close(); Console.Error.WriteLine("IPython config file written to:"); Console.Error.WriteLine(" \"{0}\"", this.filename); Console.Error.WriteLine("To exit, you will have to explicitly quit this process, by either sending"); Console.Error.WriteLine("\"quit\" from a client, or using Ctrl-\\ in UNIX-like environments."); Console.Error.WriteLine("To read more about this, see https://github.com/ipython/ipython/issues/2049"); Console.Error.WriteLine("To connect another client to this kernel, use:"); Console.Error.WriteLine(" --existing {0} --profile calico", kernelname); } }