static void Ns_OnPacket(object sender, IPProtocolType protocolType, EthernetPacket packet) { NetworkSniffer ns = (NetworkSniffer)sender; IPv4Packet ip = (IPv4Packet)packet.PayloadPacket; TcpPacket t = (TcpPacket)ip.PayloadPacket; // Si el paquete recibido es el de respuesta OK del mysql if (t.PayloadData.SequenceEqual(ResponseOk)) { Parent = packet; // Replicamos el paquete, enviando el payload de la fila, si, antes de recibir el SELECT LastSequenceId = (uint)(t.SequenceNumber + t.PayloadData.Length); ip.Id++; t.SequenceNumber = LastSequenceId; t.OptionsCollection.Clear(); t.PayloadData = Payload; t.Ack = true; t.Psh = true; ip.UpdateCalculatedValues(); t.UpdateCalculatedValues(); ip.UpdateIPChecksum(); t.UpdateTCPChecksum(); ns.Send(packet); LastSequenceId = (uint)(t.SequenceNumber + t.PayloadData.Length); Console.WriteLine(t.ToString(StringOutputType.Verbose)); } else { // Si el paquete contiene el valor SELECT string ascii = Encoding.ASCII.GetString(t.PayloadData); if (Parent != null && ascii.Contains("SELECT")) { // Ya no actuamos mas ns.OnPacket -= Ns_OnPacket; ip = (IPv4Packet)Parent.PayloadPacket; t = (TcpPacket)ip.PayloadPacket; // Enviamos un ACK del paquete recibido, para darle por bueno t.SequenceNumber = LastSequenceId; t.AcknowledgmentNumber = t.AcknowledgmentNumber; t.PayloadData = new byte[] { }; ip.Id++; t.Ack = true; t.Psh = false; ip.UpdateCalculatedValues(); t.UpdateCalculatedValues(); ip.UpdateIPChecksum(); t.UpdateTCPChecksum(); ns.Send(packet); Console.WriteLine(t.ToString(StringOutputType.Verbose)); } } }
/// <summary> /// add a new packet to the end of our packets list /// NOTE: we drop 0 length packets as there is no easy way to /// represent a unique offset inside of a zero length /// packet /// </summary> /// <param name="newPacket"> /// A <see cref="TcpPacket"/> /// </param> public void AppendPacket(TcpPacket newPacket) { #if PERFORMANCE_CRITICAL_LOGGING log.Debug(""); #endif // if we are initialized we should validate the new packet if (FirstPacket != null) { var newIpPacket = (IPPacket)newPacket.ParentPacket; var firstIpPacket = (IPPacket)FirstPacket.ParentPacket; // does this packets settings match that of the stream? if (!firstIpPacket.SourceAddress.Equals(newIpPacket.SourceAddress) || !FirstPacket.SourcePort.Equals(newPacket.SourcePort) || !firstIpPacket.DestinationAddress.Equals(newIpPacket.DestinationAddress) || !FirstPacket.DestinationPort.Equals(newPacket.DestinationPort)) { string error = "newPacket does not belong to this stream, FirstPacket was " + FirstPacket.ToString() + ", newPacket is " + newPacket.ToString(); Log.Error(error); throw new TcpStreamPacketNotPartOfStreamException(error); } } else // store the first packet { #if PERFORMANCE_CRITICAL_LOGGING log.DebugFormat("storing FirstPacket of {0}", newPacket); #endif _firstPacket = newPacket; } // NOTE: we purposely retrieve these values here for optimization purposes var payloadData = newPacket.PayloadData; int payloadLength = payloadData.Length; #if PERFORMANCE_CRITICAL_LOGGING log.DebugFormat("payloadLength {0}", payloadLength); #endif // we drop zero length packets, see the documentation for this method if (payloadLength == 0) { #if PERFORMANCE_CRITICAL_LOGGING log.Debug("dropping zero length packet"); #endif return; } // add the packet info to the end of the array var newPacketInfo = new PacketInfo(newPacket.SequenceNumber, payloadLength, base.Length); packets.AddLast(newPacketInfo); // get the current position long position = base.Position; // seek to the end of the stream base.Seek(0, SeekOrigin.End); // write the packet data to the end of the stream base.Write(payloadData, 0, payloadLength); // seek back to the previous position base.Position = position; #if false log.Debug("Packet list:"); LinkedListNode <PacketInfo> pos = packets.First; while (pos != null) { log.DebugFormat("\tseq: {0}, length: {1}, offset: {2}", pos.Value.seq, pos.Value.length, pos.Value.offset); pos = pos.Next; } pos = GetCurrentPosition(); if (pos != null) { log.DebugFormat("\tCurrent packet is seq: {0}, length: {1}, offset: {2}", pos.Value.seq, pos.Value.length, pos.Value.offset); } #endif }
public void Receive(TransportFile file) { TaskFactory taskFactory = new TaskFactory(); taskFactory.StartNew(() => { LoggerFactory.Debug("start receive file:id={0}", file.ID); string tmpPath = file.SavePath + "." + Path.GetRandomFileName().Replace(".", "") + ".lamim"; FileStream fs = null; try { fs = new FileStream(tmpPath, FileMode.Create); } catch (Exception e) { OnError(Errors.FileOpenError, "打开文件失败:" + tmpPath, file, e); return; } LoggerFactory.Debug("opened file:" + tmpPath); LoggerFactory.Debug("try connect remote:remote={0}, port={1}", file.Remote, file.Port); TcpClient tcpClient = null; NetworkStream ns = null; try { tcpClient = new TcpClient(AddressFamily.InterNetwork) { ReceiveBufferSize = this.ReceiveBufferSize }; tcpClient.Connect(file.Remote, file.Port); ns = tcpClient.GetStream(); } catch (Exception e) { OnError(Errors.NetworkError, "连接失败", file, e); return; } LoggerFactory.Debug("conneted remote:remote={0}, port={1}", file.Remote, file.Port); LoggerFactory.Debug("encode packet, request file:id={0}", file.ID); TcpPacket packet = null; EncodeResult result = null; try { //发送要接受的文件ID TcpPacketRequestFileTransportExtend extend = new TcpPacketRequestFileTransportExtend { EncryptKey = file.PublicKey, FileID = file.ID }; packet = new TcpPacket { Command = TcpPacket.CMD_REQUEST_FILE_TRANSPORT, Extend = extend }; IPacketEncoder encoder = PacketEncoderFactory.CreateEncoder(packet); result = encoder.Encode(null); } catch (Exception e) { OnError(Errors.EncodeError, "请求文件ID包加密失败。" + packet.ToString(), file, e); return; } LoggerFactory.Debug("send packet, request file:id={0}", file.ID); try { ns.Write(result.Fragments[0], 0, result.Fragments[0].Length); } catch (Exception e) { OnError(Errors.NetworkError, "请求文件ID包发送失败", file, e); return; } LoggerFactory.Debug("receive file start:id={0}", file.ID); try { int len = 0; file.StartTransport(); long lastProgressTicks = file.NowTransportTicks; byte[] buff = new byte[this.ReceiveBufferSize]; while ((len = ns.Read(buff, 0, buff.Length)) != 0) { fs.Write(buff, 0, len); file.Transported(len); if (file.TransportedLength == file.File.Length || (DateTime.Now.Ticks - lastProgressTicks) > this._progressChangeInterval) //避免进度太频繁,500ms一次 { OnProgressChanged(file); lastProgressTicks = file.NowTransportTicks; } } LoggerFactory.Debug("receive file end:id={0}", file.ID); } catch (Exception e) { OnError(Errors.NetworkError, "文件接收失败", file, e); } finally { LoggerFactory.Debug("close connect and save file:id={0}", file.ID); //关闭连接 ns.Close(); tcpClient.Close(); fs.Flush(true); fs.Close(); if (LanFile.Rename(tmpPath, file.SavePath)) { //发送接收完毕 OnCompleted(file); } else { OnError(Errors.FileWriteError, "文件写入失败", file, null); } } LoggerFactory.Debug("end receive file:id={0}", file.ID); }); }
private void lbxCapturedPacketList_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { gbxPacketInfo.Visibility = Visibility.Visible; Packet packet = lbxCapturedPacketList.SelectedItem as Packet; Console.WriteLine(packet.GetType()); TcpPacket tcp = (TcpPacket)packet.Extract(typeof(TcpPacket)); IpPacket ip = (IpPacket)packet.Extract(typeof(IpPacket)); EthernetPacket ethernet = (EthernetPacket)packet.Extract(typeof(EthernetPacket)); UdpPacket udp = (UdpPacket)packet.Extract(typeof(UdpPacket)); ICMPv4Packet icmpv4 = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); ICMPv6Packet icmpv6 = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); ICMPv6Packet igmp = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); PPPoEPacket PPPoE = (PPPoEPacket)packet.Extract(typeof(PPPoEPacket)); PPPPacket pppp = (PPPPacket)packet.Extract(typeof(PPPPacket)); LLDPPacket LLDP = (LLDPPacket)packet.Extract(typeof(LLDPPacket)); WakeOnLanPacket WOL = (WakeOnLanPacket)packet.Extract(typeof(WakeOnLanPacket)); if (tcp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = tcp.ToString(StringOutputType.Verbose); })); } if (ip != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = ip.ToString(StringOutputType.Verbose); })); } if (ethernet != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = ethernet.ToString(StringOutputType.Verbose); })); } if (udp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = udp.ToString(StringOutputType.Verbose); })); } if (icmpv4 != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = icmpv4.ToString(StringOutputType.Verbose); })); } if (icmpv6 != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = icmpv6.ToString(StringOutputType.Verbose); })); } if (igmp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = igmp.ToString(StringOutputType.Verbose); })); } if (PPPoE != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = PPPoE.ToString(StringOutputType.Verbose); })); } if (pppp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = pppp.ToString(StringOutputType.Verbose); })); } if (LLDP != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = LLDP.ToString(StringOutputType.Verbose); })); } if (WOL != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = WOL.ToString(StringOutputType.Verbose); })); } } catch (Exception ex) { Console.WriteLine("{0} Exception caught.", ex); } }