/// <summary> /// Setup filter and start capture /// Return when an error occurs or StopCapture is called /// </summary> /// <param name="callback">Callback to handle packets</param> /// <param name="ErrorMsg">When return contains the error description</param> public void StartCapture(HandlePacket callback, out string ErrorMsg) { // Check the link layer. We support only Ethernet if (communicator.DataLink.Kind != DataLinkKind.Ethernet) { ErrorMsg = "This program works only on Ethernet networks."; return; } // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } using (PacketDumpFile dumpFile = communicator.OpenDump(DumpFileName)) { try { // start the capture communicator.ReceivePackets(0, delegate(Packet packet) { dumpFile.Dump(packet); callback(packet); }); } catch (Exception ex) { ErrorMsg = ex.Message; } } ErrorMsg = null; }
/// <summary> /// Start an off-line capture /// </summary> /// <param name="file">The dump file name to capture</param> /// <param name="callback">Callback to handle packets</param> /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param> public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile) { PacketCommunicator pc = communicator; try { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file); communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, callback); } catch (Exception) { IsBadDumpFile = true; } finally { if (pc != null) communicator = pc; } }
/// <summary> /// Start an off-line capture /// </summary> /// <param name="file">The dump file name to capture</param> /// <param name="callback">Callback to handle packets</param> /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param> public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile) { PacketCommunicator pc = communicator; try { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file); communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, callback); } catch (Exception) { IsBadDumpFile = true; } finally { if (pc != null) { communicator = pc; } } }
/// <summary> /// Stores a new packet routine /// </summary> /// <param name="type">Packet Type</param> /// <param name="callback">Method to be called when the packet arrives</param> public static void StorePacketRoutine(PackType type, HandlePacket callback) { if (!PackRoutines.ContainsKey(type)) { PackRoutines.Add(type, new List <HandlePacket>()); } PackRoutines[type].Add(callback); }
/// <summary> /// Generates and stores a nonce, then calls the method when the packet is received /// </summary> /// <param name="callback">The method to call</param> /// <returns>A nonce</returns> public static uint WatchNonce(HandlePacket callback) { uint nonce = (uint)_random.Next(0, Int32.MaxValue); Log.Debug("Stored nonce {Nonce} for a pre-defined routine", nonce); NonceWatch.Add(nonce, callback); return(nonce); }
public TCP(HandlePacket _hp, Action _onDisconnect, Action _onConnect, Action <ConnectionError> _onConnectionFailed, Action <int> _SetId) { OnHandlePacket = _hp; OnDisconnect = _onDisconnect; OnConnect = _onConnect; OnConnectionFailed = _onConnectionFailed; SetId = _SetId; recivedData = new Packet(); }
public void Init() { this.broadcast = new UDPSocket(); this.broadcast.ReceivedPacket += Broadcast_ReceivedPacket; this.managedClient = new ManagedClient(); this.managedClient.BufferSize = 2000; this.managedClient.ReceivedPacket += ManagedClient_ReceivedPacket; this.managedClient.Connected += ManagedClient_Connected; this.managedClient.Disconnected += ManagedClient_Disconnected; this.handlePacket = new HandlePacket(this.managedClient.Logger); }
protected void RegisterPacketHandler(Type packetType, HandlePacket handler) { var packet = PacketReader.PacketFromType(packetType); if (m_packetHandlers[packet.Id] != null) { Debug.WriteLine($@"Handler for packet {packet.Id} overwritten", @"Warning"); } //PacketReader.RegisterPacket(packet.Id, packetType); m_packetHandlers[packet.Id] = handler; }
public bool RegisterHandler(Type type, HandlePacket handler) { var handlers = GetHandlers(type); if (handlers?.Contains(handler) ?? false) { return(false); } handlers?.Add(handler); return(true); }
public void RegisterPacketHandler(Type packetType, HandlePacket handler) { var packet = PacketReader.PacketFromType(packetType); if (m_packetHandlers[packet.Id] != null) { Debug.WriteLine($"Handler for packet 0x{packet.Id.ToString("X2")} overwritten", "Warning"); } //PacketReader.RegisterPacket(packet.Id, packetType); m_packetHandlers[packet.Id] = handler; }
// RECIVE // Method for reciving packets on specified device static void Recive(int number, HandlePacket packetHandler) { // Open the device using (PacketCommunicator communicatorX = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Console.WriteLine(""); Console.WriteLine("Listening: "); // start the capture // Callback function invoked by Pcap.Net for every incoming packet communicatorX.ReceivePackets(number, packetHandler); } }
public async void ReadClientData(IAsyncResult ar) { try { int Recevied = client.EndReceive(ar); if (Recevied > 0) { if (BufferRecevied == false) { if (Buffer[0] == 0) { Buffersize = Convert.ToInt64(Encoding.UTF8.GetString(MS.ToArray())); MS = new MemoryStream(); if (Buffersize > 0) { Buffer = new byte[Buffersize - 1]; BufferRecevied = true; } } else { await MS.WriteAsync(Buffer, 0, Buffer.Length); } } else { await MS.WriteAsync(Buffer, 0, Recevied); if (MS.Length == Buffersize) { HandlePacket.Read(this, MS.ToArray()); MS = new MemoryStream(); Buffer = new byte[1]; Buffersize = 0; BufferRecevied = false; } } } client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, ReadClientData, null); } catch { Disconnected(); } }
public unsafe PacketCommunicatorReceiveResult ReceivePackets(int count, HandlePacket callback) { this.AssertMode(PacketCommunicatorMode.Capture); PcapDataLink dataLink = new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); PacketCommunicator.PacketHandler packetHandler = new PacketCommunicator.PacketHandler(callback, dataLink); PacketCommunicator.HandlerDelegate handlerDelegate = new PacketCommunicator.HandlerDelegate(packetHandler.Handle); // ISSUE: cast to a function pointer type __FnPtr <void (byte *, pcap_pkthdr *, byte *)> local = (__FnPtr <void (byte *, pcap_pkthdr *, byte *)>)(IntPtr) Marshal.GetFunctionPointerForDelegate((Delegate)handlerDelegate).ToPointer(); int num = \u003CModule\u003E.pcap_loop(this._pcapDescriptor, count, local, (byte *)0); GC.KeepAlive((object)handlerDelegate); if (num == -2) { return(PacketCommunicatorReceiveResult.BreakLoop); } if (num == -1) { throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); } return(num == 0 && packetHandler.PacketCounter != count ? PacketCommunicatorReceiveResult.Eof : PacketCommunicatorReceiveResult.Ok); }
private void HandlePacket(OpenDirPacket packet) { logger.LogDebug("Processing OpenDir SFTP packet, Id={Id}, Path='{Path}'.", packet.Id, packet.Path); // If they cannot read the directory, respond with a status packet. if (!fileSystem.CanReadDirectory(packet.Path)) { var status = new StatusPacket { Id = packet.Id, StatusCode = StatusPacket.PermissionDenied, ErrorMessage = "permission denied" }; Send(status); } else { // Create a new channel // TODO - use a factory to create the handle, so it can get its own logger var handleId = Interlocked.Increment(ref nextChannelId).ToString(); var handle = new SftpHandle(this, handleId, fileSystem, logger); handles.Add(handleId, handle); handle.OpenDir(packet.Path); var response = new HandlePacket { Id = packet.Id, Handle = handle.Name }; Send(response); } }
public PacketHandler(HandlePacket callback, PcapDataLink dataLink) { this._callback = callback; this._dataLink = dataLink; }
public unsafe PacketCommunicatorReceiveResult ReceiveSomePackets(out int countGot, int maxPackets, HandlePacket callback) { this.AssertMode(PacketCommunicatorMode.Capture); PcapDataLink dataLink = new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); PacketCommunicator.PacketHandler packetHandler = new PacketCommunicator.PacketHandler(callback, dataLink); PacketCommunicator.HandlerDelegate handlerDelegate = new PacketCommunicator.HandlerDelegate(packetHandler.Handle); // ISSUE: cast to a function pointer type __FnPtr <void (byte *, pcap_pkthdr *, byte *)> local = (__FnPtr <void (byte *, pcap_pkthdr *, byte *)>)(IntPtr) Marshal.GetFunctionPointerForDelegate((Delegate)handlerDelegate).ToPointer(); countGot = \u003CModule\u003E.pcap_dispatch(this._pcapDescriptor, maxPackets, local, (byte *)0); GC.KeepAlive((object)handlerDelegate); switch (countGot) { case -2: countGot = 0; return(PacketCommunicatorReceiveResult.BreakLoop); case -1: throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); case 0: if (packetHandler.PacketCounter != 0) { countGot = packetHandler.PacketCounter; return(PacketCommunicatorReceiveResult.Eof); } break; } return(PacketCommunicatorReceiveResult.Ok); }
public async void ReadClientData(IAsyncResult ar) { try { if (!Client.Connected) { Disconnected(); } else { int Recevied = Client.EndReceive(ar); if (Recevied > 0) { if (BufferRecevied == false) { if (Buffer[0] == 0) { Buffersize = Convert.ToInt64(Encoding.UTF8.GetString(MS.ToArray())); MS.Dispose(); MS = new MemoryStream(); if (Buffersize > 0) { Buffer = new byte[Buffersize - 1]; BufferRecevied = true; } } else { await MS.WriteAsync(Buffer, 0, Buffer.Length); } } else { await MS.WriteAsync(Buffer, 0, Recevied); if (MS.Length == Buffersize) { // Read.BeginInvoke(this, MS.ToArray(), null, null); await Task.Run(() => { HandlePacket.Read(this, MS.ToArray()); Settings.Received += MS.ToArray().Length; Buffer = new byte[1]; Buffersize = 0; MS.Dispose(); MS = new MemoryStream(); BufferRecevied = false; }); } else { Buffer = new byte[Buffersize - MS.Length]; } } Client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, ReadClientData, null); } else { Disconnected(); } } } catch { Disconnected(); } }
/// <summary> /// Setup filter and start capture /// Return when an error occurs or StopCapture is called /// </summary> /// <param name="callback">Callback to handle packets</param> /// <param name="ErrorMsg">When return contains the error description</param> public void StartCapture(HandlePacket callback, out string ErrorMsg) { // Check the link layer. We support only Ethernet if (communicator.DataLink.Kind != DataLinkKind.Ethernet) { ErrorMsg = "This program works only on Ethernet networks."; return; } // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } using (PacketDumpFile dumpFile = communicator.OpenDump(DumpFileName)) { try { // start the capture communicator.ReceivePackets(0, delegate(Packet packet) { dumpFile.Dump(packet); callback(packet); }); } catch (Exception ex){ ErrorMsg = ex.Message; } } ErrorMsg = null; }
public bool DeregisterHandler(Type type, HandlePacket handler) { var handlers = GetHandlers(type); return((handlers?.Contains(handler) ?? false) && handlers.Remove(handler)); }
private void ProcessLoop(TcpClient src, TcpClient dst, RC4 i, RC4 o, Queue <Tuple <byte, byte[]> > queue, HandlePacket cb) { try { var rdr = new NReader(src.GetStream()); NWriter writer = dst == null ? null : new NWriter(dst.GetStream()); while (true) { int len = rdr.ReadInt32(); byte id = rdr.ReadByte(); byte[] content = rdr.ReadBytes(len - 5); i.Crypt(content, 0, content.Length); bool send = true; if (id == PacketTable.HELLO) { HelloPacket helloPacket = HelloPacket.Read(new NBufferReader(content)); writer = OnHello(helloPacket); content = NWriter.Write(w => helloPacket.Write(w)); } send = cb(ref id, ref content); if (send) { o.Crypt(content, 0, content.Length); writer.Write(content.Length + 5); writer.Write(id); writer.Write(content); } if (queue.Count > 0) { lock (queue) { Tuple <byte, byte[]> packet; while (queue.Count > 0) { packet = queue.Dequeue(); o.Crypt(packet.Item2, 0, packet.Item2.Length); writer.Write(packet.Item2.Length + 5); writer.Write(packet.Item1); writer.Write(packet.Item2); } } } } } catch { } finally { OnDisconnected(src, dst); } Proxy.Stopped -= Kill; }
public static void DefineOpcodeHandler(Opcodes opcode, HandlePacket handler) { OpcodeHandlers[opcode] = handler; }
public UDP(string _ip, int _port, int _id, HandlePacket _hp) { endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port); OnHandlePacket = _hp; id = _id; }
public static void DefineOpcodeHandler(WorldServerOpCode opcode, HandlePacket handler) { OpcodeHandlers[opcode] = handler; }