void Inject(NetworkSniffer sniffer, TcpStream stream, Packet[] packets) { WriteInfo("Injecting packets"); foreach (EthernetPacket p in packets) { // Override ethernet p.DestinationHwAddress = stream.DestinationHwAddress; p.SourceHwAddress = stream.SourceHwAddress; p.UpdateCalculatedValues(); IpPacket ip = (IpPacket)p.PayloadPacket; ip.SourceAddress = stream.Source.Address; ip.DestinationAddress = stream.Destination.Address; ip.UpdateCalculatedValues(); if (ip.Protocol != IPProtocolType.TCP) { continue; } TcpPacket tcp = (TcpPacket)ip.PayloadPacket; tcp.SourcePort = (ushort)stream.Source.Port; tcp.DestinationPort = (ushort)stream.Destination.Port; tcp.UpdateCalculatedValues(); // Send sniffer.Send(p); } }
/// <summary> /// Initialize new <see cref="Libuv2kConnection"/>. /// </summary> /// <param name="noDelay"></param> /// <param name="client"></param> public Libuv2kConnection(bool noDelay, TcpStream client = null) { _cancellationToken = new CancellationTokenSource(); if (client == null) { _clientLoop = new Loop(); _client = new TcpStream(_clientLoop); _ = UniTask.RunOnThreadPool(Tick, false, _cancellationToken.Token); } else { _client = client; // setup callbacks client.onMessage = OnLibuvClientMessage; client.onError = OnLibuvClientError; client.onClosed = OnLibuvClientClosed; } _ = UniTask.RunOnThreadPool(ProcessOutgoingMessages, false, _cancellationToken.Token); _client.NoDelay(noDelay); }
public bool PreRun() { string DBUser = null; string Hash = null; string Seed = null; TcpStream dump = TcpStream.FromFile(TCPStreamFile.FullName); if (dump.Count < 2) { return(false); } crack(dump[0].Data, dump[1].Data, out Hash, out Seed, out DBUser); if (!string.IsNullOrEmpty(DBUser)) { WriteInfo("User found", DBUser, ConsoleColor.Green); } string _sh = HexToString(Hash, true); byte[] bhash_all = _Codec.GetBytes(_sh); if (bhash_all.Length != 21) { return(false); } string _seed = HexToString(Seed, true); bseed = _Codec.GetBytes(_seed); bhash = new byte[bhash_all.Length - 1]; Array.Copy(bhash_all, 1, bhash, 0, bhash.Length); return(true); }
private async Task ReceiveMessagesOnSubscribeOnAddress() { if (!IsConnected) { return; } while (IsConnected) { var responseSb = new StringBuilder(); var buffer = new byte[Buffersize]; var bytes = await TcpStream.ReadAsync(buffer, 0, buffer.Length); if (bytes <= 0) { continue; } do { responseSb.Append(Encoding.UTF8.GetString(buffer, 0, bytes)); }while (TcpStream.DataAvailable); var message = responseSb.ToString(); if (message.Contains("\"result\": null,")) { Console.WriteLine("Received ping message"); continue; } var response = !string.IsNullOrEmpty(message) ? JsonConvert.DeserializeObject <BlockchainScriphashSubscribeResponse>(message) : null; if (response != null) { OnReceiveMessageOnAddress?.Invoke(this, response.Params[0]); } } }
/// <summary> /// Send a message to an address via TCP /// </summary> /// <returns>Returns client-side success as bool</returns> public bool SendMsgTcp(string nMsg, MsgType nType = MsgType.MSG) { if (Ready) { if (Connected) { TcpSend = AssemblePacket(Encoding.ASCII.GetBytes(nMsg), nType); if (TcpSend != null && TcpSend.Length > 0) { TcpStream.Write(TcpSend, 0, TcpSend.Length); LocalConsole.Instance.Log("Sent " + nMsg + " (length:" + TcpSend.Length + ")", true); return(true); } else { LocalConsole.Instance.Log("Invalid message data to send"); return(false); } } else { LocalConsole.Instance.Log("Not currently connected to a server"); return(false); } } else { LocalConsole.Instance.Log("HubrisNet is not ready"); return(false); } }
void ClientConnect(string hostname, ushort port) { if (client != null) { return; } // libuv doesn't resolve host name, and it needs ipv4. if (LibuvUtils.ResolveToIPV4(hostname, out IPAddress address)) { // connect client IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort); IPEndPoint remoteEndPoint = new IPEndPoint(address, port); Debug.Log("Libuv connecting to: " + address + ":" + port); client = new TcpStream(clientLoop); client.NoDelay(NoDelay); client.onClientConnect = OnLibuvClientConnected; client.onMessage = OnLibuvClientMessage; client.onError = OnLibuvClientError; client.onClosed = OnLibuvClientClosed; client.ConnectTo(localEndPoint, remoteEndPoint); } else { Debug.LogWarning("Libuv Connect: no IPv4 found for hostname: " + hostname); } }
public void Performance() { captureFilename = capturePre + captureFN; // open the offline file var dev = new CaptureFileReaderDevice(captureFilename); dev.Open(); Assert.True(dev != null, "failed to open " + captureFilename); TcpStream tcpStream = new TcpStream(); int i = 1; // to match the packet numbering in wireshark RawCapture rawCapture; const int packetsToAppend = 100000; while ((rawCapture = dev.GetNextPacket()) != null) { var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); var tcpPacket = p.Extract <TcpPacket>(); for (int x = 0; x < packetsToAppend; x++) { tcpStream.AppendPacket(tcpPacket); // advance to the next packet tcpStream.AdvanceToNextPacket(); tcpStream = tcpStream.TrimUnusedPackets(); } i++; } dev.Close(); }
// segment is valid until function returns. void OnLibuvClientMessage(TcpStream handle, ArraySegment <byte> segment) { //Debug.Log("libuv cl: data=" + BitConverter.ToString(segment.Array, segment.Offset, segment.Count)); // Mirror event OnClientDataReceived.Invoke(segment, Channels.Reliable); }
void OnLibuvServerError(TcpStream handle, Exception error) { Debug.Log($"libuv sv: error {error}"); connections.Remove((int)handle.UserToken); // TODO invoke OnDisconnected or does OnLibuvClosed get called anyway? }
// server callbacks //////////////////////////////////////////////////// void OnLibuvServerConnected(TcpStream handle, Exception error) { // setup callbacks for the new connection handle.onMessage = OnLibuvServerMessage; handle.onError = OnLibuvServerError; handle.onClosed = OnLibuvServerClosed; // close if errors (AFTER setting up onClosed callback!) if (error != null) { Debug.Log($"libuv sv: client connection failed {error}"); handle.Dispose(); return; } // assign a connectionId via UserToken. // this is better than using handle.InternalHandle.ToInt32() because // the InternalHandle isn't available in OnLibuvClosed anymore. handle.UserToken = nextConnectionId++; connections[(int)handle.UserToken] = handle; Debug.Log("libuv sv: client connected with connectionId=" + (int)handle.UserToken); // dotsnet event OnServerConnected.Invoke((int)handle.UserToken); }
private void ListenForClientMessages(object connectedClient) { TcpClient client = connectedClient as TcpClient; TcpStream stream = new TcpStream(client.GetStream()); while (true) { string chars = stream.Receive(); MessageHandshakeSocket data = JsonConvert.DeserializeObject <MessageHandshakeSocket>(chars); Packet packet = null; if (data.ServiceId == default(Guid)) { packet = JsonConvert.DeserializeObject <Packet>(chars); } if (OnClientConnected != null && packet == null) { MessageHandshakeSocket mhs = data as MessageHandshakeSocket; mhs.Client = client; OnClientConnected(mhs); } else if (OnMessageReceived != null) { OnMessageReceived(packet); } } }
void rec(byte[] data, int length) { IPHeader ipHeader = new IPHeader(data, length); IPacket packet = ipHeader.ParseData(); if (OnPacket != null) { OnPacket(ipHeader.ProtocolType, packet); } if (OnTcpStream != null && ipHeader.ProtocolType == ProtocolType.Tcp) { TcpHeader tcp = (TcpHeader)packet; if (AllowTcpPacket(tcp)) { TcpStream stream = TcpStream.GetStream(_TcpStreams, tcp); if (stream != null) { if (stream.IsClossed) { _TcpStreams.Remove(stream); } OnTcpStream(stream); } } } Receive(); }
/// <summary> /// Stores specified message header + specified lines of body to the specified stream. /// </summary> /// <param name="sequenceNumber">Message 1 based sequence number.</param> /// <param name="stream">Stream where to store data.</param> /// <param name="lineCount">Number of lines of message body to get.</param> internal void GetTopOfMessage(int sequenceNumber, Stream stream, int lineCount) { TcpStream.WriteLine("TOP " + sequenceNumber + " " + lineCount); // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.StartsWith("+OK")) { SmartStream.ReadPeriodTerminatedAsyncOP readTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(stream, 999999999, SizeExceededAction.ThrowException); TcpStream.ReadPeriodTerminated(readTermOP, false); if (readTermOP.Error != null) { throw readTermOP.Error; } LogAddWrite(readTermOP.BytesStored, readTermOP.BytesStored + " bytes read."); } else { throw new POP3_ClientException(line); } }
void OnLibuvClientError(TcpStream handle, Exception error) { Debug.Log($"libuv cl: read error {error}"); handle.CloseHandle(); // Mirror event OnClientDisconnected.Invoke(); }
/// <summary> /// Callback when connection has closed. /// </summary> /// <param name="handle">The stream handle in which closed connection to.</param> private void OnLibuvClientClosed(TcpStream handle) { Libuv2kNGLogger.Log("libuv client callback: closed connection"); handle.Dispose(); // set client to null so we can't send to an old reference anymore _client = null; }
public void OnTcpStream(object sender, TcpStream stream, bool isNew, ConcurrentQueue<object> queue) { if (stream == null) return; stream.DumpToFile( DumpFolder.FullName + Path.DirectorySeparatorChar + stream.Source.ToString().Replace(":", ",") + " - " + stream.Destination.ToString().Replace(":", ",") + ".dump"); }
public override void ServerStop() { if (server != null) { server.Dispose(); server = null; connections.Clear(); Debug.Log("libuv sv: TCP stopped!"); } }
public override IByteStream GetSocketStream() { CheckDisposed(); if (stream == null) { stream = new TcpStream(this); } return(stream); }
private void Ping(object state) { if (!IsConnected) { return; } var requestData = new ServerPingRequest().GetRequestData(); TcpStream.Write(requestData, 0, requestData.Length); }
/// <summary> /// Sends and logs specified line to connected host. /// </summary> /// <param name="line">Line to send.</param> protected void WriteLine(string line) { if (line == null) { throw new ArgumentNullException("line"); } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); }
// test that we can seek a tcpStream beyond the length of the stream // then back into the range of the stream and then read // a known value public void TestTcpStreamSeeking() { captureFilename = capturePre + captureFN; // open the offline file var dev = new CaptureFileReaderDevice(captureFilename); dev.Open(); Assert.True(dev != null, "failed to open " + captureFilename); TcpStream tcpStream = new TcpStream(); int i = 1; // to match the packet numbering in wireshark PacketCapture e; GetPacketStatus status; while ((status = dev.GetNextPacket(out e)) == GetPacketStatus.PacketRead) { var rawCapture = e.GetPacket(); var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); var tcpPacket = p.Extract <TcpPacket>(); // we only want the 4th packet since that is the first packet with a payload if (i == 4) { tcpStream.AppendPacket(tcpPacket); } i++; } dev.Close(); // what is the length of the stream? long length = tcpStream.Length; Console.WriteLine("length is {0}", length); // seek to the end of the stream tcpStream.Seek(0, System.IO.SeekOrigin.End); // retrieve the position long position = tcpStream.Position; Console.WriteLine("position is {0}", position); // seek to the start of the stream tcpStream.Seek(0, System.IO.SeekOrigin.Begin); // retrieve the position long position2 = tcpStream.Position; Console.WriteLine("position2 is {0}", position2); }
void s_OnTcpStream(TcpStream stream) { if (stream == null) { return; } stream.DumpToFile(DumpFolder.FullName + System.IO.Path.DirectorySeparatorChar + stream.Source.ToString().Replace(":", ",") + " - " + stream.Destination.ToString().Replace(":", ",") + ".dump"); }
// OnClosed is called after we closed the stream void OnLibuvClientClosed(TcpStream handle) { // important: clear the connection BEFORE calling the Mirror event // otherwise Mirror OnDisconnected might try to send to a closed // connection which we didn't clear yet. do it first. client = null; // Mirror event Debug.Log("libuv cl: closed connection"); OnClientDisconnected.Invoke(); }
// OnClosed is called after we closed the stream void OnLibuvClientClosed(TcpStream handle) { Debug.Log("libuv cl: closed connection"); handle.Dispose(); // set client to null so we can't send to an old reference anymore client = null; // Mirror event OnClientDisconnected.Invoke(); }
// TODO: this should probably better return class instance for the purpose of using its methods, e.g. ToString, but then we lose the FieldMeta descriptions public List <ParsedEvent> ParseStream(TcpStream tcpStream, ParseMode parseMode = ParseMode.Root, long startingStreamPosition = 0) { var events = new List <ParsedEvent>(); var stream = new MemoryStream(); lock (tcpStream) { var position = tcpStream.Position; tcpStream.Position = startingStreamPosition; tcpStream.CopyTo(stream); tcpStream.Position = position; } _br = new BinaryReader(stream); _br.BaseStream.Position = 0; while (_br.BaseStream.Position < _br.BaseStream.Length) { try { var positionBeforeRead = _br.BaseStream.Position; var newParsedEvent = new ParsedEvent { Offset = positionBeforeRead + startingStreamPosition, Sender = tcpStream.Sender, ParseMode = parseMode }; var packetData = ReadEvent(out var opCode, parseMode); if (packetData.Count == 0) { break; } newParsedEvent.OpCode = opCode; newParsedEvent.Length = _br.BaseStream.Position - positionBeforeRead; newParsedEvent.Data = packetData; newParsedEvent.Time = tcpStream.PacketAtOffset(startingStreamPosition + _br.BaseStream.Position).Time; events.Add(newParsedEvent); } catch (Exception e) { // Safe exit break; } } _br.Dispose(); _br = null; return(events); }
private void Dispose(bool disposing) { if (!disposing) { return; } _timer?.Dispose(); TcpClient?.Dispose(); TcpStream?.Dispose(); Disconnect(); }
void OnLibuvServerClosed(TcpStream handle) { Debug.Log($"libuv sv: closed client {handle}"); // important: remove the connection BEFORE calling the DOTSNET event // otherwise DOTSNET OnDisconnected Unspawn might try to send to a // disposed connection which we didn't remove yet. do it first. connections.Remove((int)handle.UserToken); handle.Dispose(); // Mirror event OnServerDisconnected.Invoke((int)handle.UserToken); }
/// <summary> /// Shut down the server. /// </summary> public void Shutdown() { if (_server != null) { _cancellationToken.Cancel(); _server?.Dispose(); _server = null; Libuv2kNGLogger.Log("libuv server: TCP stopped!"); _serverLoop?.Dispose(); } }
void OnLibuvServerMessage(TcpStream handle, ArraySegment <byte> segment) { // valid connection? if (connections.ContainsKey((int)handle.UserToken)) { // DOTSNET event OnServerDataReceived.Invoke((int)handle.UserToken, segment, Channels.Reliable); } else { Debug.LogError("libuv sv: invalid connectionid: " + (int)handle.UserToken); } }
/// <summary> /// Callback when connection receives a new message. /// </summary> /// <param name="handle">The stream handle we used to connect with server with.</param> /// <param name="segment">The data that has come in with it.</param> private void OnLibuvClientMessage(TcpStream handle, ArraySegment <byte> segment) { Libuv2kNGLogger.Log($"libuv client callback received: data= {BitConverter.ToString(segment.Array)}"); byte[] data = new byte[segment.Count]; Array.Copy(segment.Array, segment.Offset, data, 0, segment.Count); _queuedIncomingData.Enqueue(new Message { Data = data }); }
void s_OnTcpStream(TcpStream stream) { if (stream == null) return; stream.DumpToFile(DumpFolder.FullName + System.IO.Path.DirectorySeparatorChar + stream.Source.ToString().Replace(":", ",") + " - " + stream.Destination.ToString().Replace(":", ",") + ".dump"); }