/// <summary> /// Load from xml text /// </summary> /// <param name="xml"></param> /// <returns></returns> public static Datagram LoadXML(string xml) { XmlDocument data = new XmlDocument(); data.LoadXml(xml); Datagram datagram = new Datagram(data.DocumentElement.Name, data.DocumentElement.InnerText); foreach (XmlAttribute curr in data.DocumentElement.Attributes) { datagram.Parameters.Add(curr.Name, curr.Value); } return datagram; }
public HttpParser Token(out Datagram token) { if (!Success) { token = null; return this; } int tokenLength = Range.TakeWhile(value => value.IsToken()).Count(); if (tokenLength == 0) { token = null; return Fail(); } token = new Datagram(_buffer, _offset, tokenLength); _offset += token.Length; return this; }
public void DatagramToMemoryStreamTest() { Datagram tcpPayload = new Datagram(new byte[] {1, 2, 3}); Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new TcpLayer(), new PayloadLayer {Data = tcpPayload}); using (MemoryStream stream = packet.Ethernet.IpV4.Tcp.Payload.ToMemoryStream()) { Assert.IsTrue(stream.CanRead, "CanRead"); Assert.IsTrue(stream.CanSeek, "CanSeek"); Assert.IsFalse(stream.CanTimeout, "CanTimeout"); Assert.IsFalse(stream.CanWrite, "CanWrite"); Assert.AreEqual(tcpPayload.Length, stream.Length); for (int i = 0; i != tcpPayload.Length; ++i) { Assert.AreEqual(i, stream.Position); Assert.AreEqual(i + 1, stream.ReadByte()); } } }
/// <summary> /// Initializes using an address family, data, and offset to the first octet of the active entry in Source Route Entry to be examined. /// </summary> /// <param name="addressFamily">The Address Family field contains a two octet value which indicates the syntax and semantics of the Routing Information field.</param> /// <param name="data">The data of the entry source route.</param> /// <param name="offset">The SRE Offset field indicates the octet offset from the start of the Routing Information field to the first octet of the active entry in Source Route Entry to be examined.</param> public GreSourceRouteEntryUnknown(GreSourceRouteEntryAddressFamily addressFamily, Datagram data, int offset) { _addressFamily = addressFamily; _data = data; _offset = offset; }
public HttpParser ReasonPhrase(out Datagram reasonPhrase) { if (!Success) { reasonPhrase = null; return this; } int count = 0; foreach (byte b in Range) { if (!b.IsControl() || b == AsciiBytes.HorizontalTab) ++count; else break; } // Console.WriteLine(count); int reasonPhraseLength = Range.TakeWhile(value => !value.IsControl() || value == AsciiBytes.HorizontalTab).Count(); reasonPhrase = new Datagram(_buffer, _offset, reasonPhraseLength); _offset += reasonPhraseLength; return this; }
internal override void ReadRDATA(Internal.ByteReader reader) { RDATA = reader.ReadBytes(Base.RDLENGTH); }
private void SendData(string network, string data, Configuration.Priority priority = Configuration.Priority.Normal) { Datagram line = new Datagram("RAW", data); string Pr = "Normal"; switch (priority) { case Configuration.Priority.High: Pr = "High"; break; case Configuration.Priority.Low: Pr = "Low"; break; } line.Parameters.Add("network", network); line.Parameters.Add("priority", Pr); Deliver(line); }
/// <summary> /// Send a datagram to server /// </summary> /// <param name="message"></param> public void Deliver(Datagram message) { Send(message.ToDocumentXmlText()); }
private void Udp_OnData(Datagram datagram) { _receiver.ReceivePacket(datagram.Data); }
/// <summary> /// 将数据包序列化为json格式 /// </summary> /// <param name="datagram"></param> /// <returns></returns> public static String toJsonDatagram(Datagram datagram) { return(JsonConvert.SerializeObject(datagram)); }
/// <summary> /// 从数据包中获取传输对象类型 /// </summary> /// <param name="jsonDatagram"></param> /// <returns></returns> public static String getType(String jsonDatagram) { Datagram datagram = JsonConvert.DeserializeObject <Datagram>(jsonDatagram); return(datagram.Type); }
/// <summary> /// 从数据包中获取请求 /// </summary> /// <param name="jsonDatagram"></param> /// <returns></returns> public static String getRequest(String jsonDatagram) { Datagram datagram = JsonConvert.DeserializeObject <Datagram>(jsonDatagram); return(datagram.Request); }
private Response(Datagram data, DateTime timestamp) { _Data = data; Timestamp = timestamp; }
internal static Response Create(Datagram data, DateTime timestamp) { Response response = new Response(data, timestamp); using (MemoryStream ms = new MemoryStream()) { ms.Write(data, 0, data.Length); ms.Seek(0L, SeekOrigin.Begin); ((Internal.IResponseReader)response).ReadResponse(new Internal.ByteReader(ms)); } return response; }
private void SendDatagram(IPEndPoint senderEndpoint, Datagram datagram) { PlayerNetworkSession session; if (_playerSessions.TryGetValue(senderEndpoint, out session)) { if (datagram.MessageParts.Count != 0) { //if (!isResend) { datagram.Header.datagramSequenceNumber = Interlocked.Increment(ref session.DatagramSequenceNumber); } byte[] data = datagram.Encode(); if (!session.Player.IsBot) { if (!session.WaitingForAcksQueue.TryAdd(datagram.Header.datagramSequenceNumber.IntValue(), datagram)) { Log.Warn(string.Format("Datagram sequence unexpectedly existed in the ACK/NAK queue already {0}", datagram.Header.datagramSequenceNumber.IntValue())); } } datagram.TransmissionCount++; SendData(data, senderEndpoint, session.SyncRoot); datagram.Timer.Restart(); } if (session.Player.IsBot) { foreach (MessagePart part in datagram.MessageParts) { part.PutPool(); } datagram.PutPool(); } } }
protected override bool CompareField(XElement field, Datagram datagram) { IcmpDatagram icmpDatagram = (IcmpDatagram)datagram; switch (field.Name()) { case "icmp.type": field.AssertShowDecimal((byte)icmpDatagram.MessageType); field.AssertNoFields(); break; case "icmp.code": field.AssertShowDecimal(icmpDatagram.Code); field.AssertNoFields(); break; case "icmp.checksum_bad": field.AssertShowDecimal(!icmpDatagram.IsChecksumCorrect); field.AssertNoFields(); break; case "icmp.checksum": field.AssertShowDecimal(icmpDatagram.Checksum); field.AssertNoFields(); break; case "data": var icmpIpV4PayloadDatagram = icmpDatagram as IcmpIpV4PayloadDatagram; if (icmpIpV4PayloadDatagram != null) { if (!new[] { IpV4Protocol.IpComp, // TODO: Support IpComp. IpV4Protocol.Ax25, // TODO: Support Ax25. IpV4Protocol.FibreChannel, // TODO: Support FibreChannel. }.Contains(icmpIpV4PayloadDatagram.IpV4.Protocol)) { if (icmpIpV4PayloadDatagram.IpV4.Protocol == IpV4Protocol.Udp) { // Uncomment this when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10990 is fixed. // field.AssertDataField(casted1.IpV4.Udp.Payload); } else { // TODO: Remove this condition when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10991 and https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10992 are fixed. if (!(icmpIpV4PayloadDatagram is IcmpParameterProblemDatagram || icmpIpV4PayloadDatagram is IcmpRedirectDatagram)) { field.AssertDataField(icmpIpV4PayloadDatagram.IpV4.Payload); } } } } else { field.AssertDataField(icmpDatagram.Payload); } break; case "": switch (icmpDatagram.MessageType) { case IcmpMessageType.ParameterProblem: if (field.Show() != "Unknown session type") { field.AssertShow("Pointer: " + ((IcmpParameterProblemDatagram)icmpDatagram).Pointer); } break; case IcmpMessageType.RouterAdvertisement: IcmpRouterAdvertisementDatagram routerAdvertisementDatagram = (IcmpRouterAdvertisementDatagram)icmpDatagram; string fieldName = field.Show().Split(':')[0]; switch (fieldName) { case "Number of addresses": field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.NumberOfAddresses); break; case "Address entry size": field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.AddressEntrySize); break; case "Lifetime": TimeSpan actualLifetime = routerAdvertisementDatagram.Lifetime; StringBuilder actualLifetimeString = new StringBuilder(fieldName + ": "); if (actualLifetime.Hours != 0) { actualLifetimeString.Append(actualLifetime.Hours + " hour"); if (actualLifetime.Hours != 1) { actualLifetimeString.Append('s'); } } if (actualLifetime.Minutes != 0) { if (actualLifetime.Hours != 0) { actualLifetimeString.Append(", "); } actualLifetimeString.Append(actualLifetime.Minutes + " minute"); if (actualLifetime.Minutes != 1) { actualLifetimeString.Append('s'); } } if (actualLifetime.Seconds != 0) { if (actualLifetime.Hours != 0 || actualLifetime.Minutes != 0) { actualLifetimeString.Append(", "); } actualLifetimeString.Append(actualLifetime.Seconds + " second"); if (actualLifetime.Seconds != 1) { actualLifetimeString.Append('s'); } } break; case "Router address": field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex].RouterAddress); break; case "Preference level": field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex++].RouterAddressPreference); break; default: throw new InvalidOperationException("Invalid icmp " + icmpDatagram.MessageType + " field " + fieldName); } break; } field.AssertNoFields(); break; case "icmp.ident": ushort identifier = ((IcmpIdentifiedDatagram)icmpDatagram).Identifier; field.AssertShowDecimal(field.Showname().StartsWith("Identifier (BE): ") ? identifier : identifier.ReverseEndianity()); field.AssertNoFields(); break; case "icmp.seq": field.AssertShowDecimal(((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber); field.AssertNoFields(); break; case "icmp.seq_le": byte[] sequenceNumberBuffer = new byte[sizeof(ushort)]; sequenceNumberBuffer.Write(0, ((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber, Endianity.Big); ushort lowerEndianSequenceNumber = sequenceNumberBuffer.ReadUShort(0, Endianity.Small); field.AssertShowDecimal(lowerEndianSequenceNumber); field.AssertNoFields(); break; case "icmp.redir_gw": field.AssertShow(((IcmpRedirectDatagram)icmpDatagram).GatewayInternetAddress.ToString()); field.AssertNoFields(); break; case "icmp.mtu": field.AssertShowDecimal(((IcmpDestinationUnreachableDatagram)icmpDatagram).NextHopMaximumTransmissionUnit); field.AssertNoFields(); break; case "l2tp.l2_spec_def": field.AssertShow(""); field.AssertNoFields(); break; case "icmp.resp_to": case "icmp.resptime": break; // TODO: Remove this case when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10939 is fixed. case "icmp.length": break; default: if (!field.Name().StartsWith("lt2p.") && field.Name() != "pweth" && !field.Name().StartsWith("pweth.")) { throw new InvalidOperationException("Invalid icmp field " + field.Name()); } break; } return(true); }
public async void SendDatagram(string header, Dictionary<string, string> values, EndPoint endpoint, EndPoint localAddress, bool isBroadcast, int sendCount) { var msg = new SsdpMessageBuilder().BuildMessage(header, values); var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging; for (var i = 0; i < sendCount; i++) { if (i > 0) { await Task.Delay(500).ConfigureAwait(false); } var dgram = new Datagram(endpoint, localAddress, _logger, msg, isBroadcast, enableDebugLogging); dgram.Send(); } }
protected override bool CompareField(XElement field, Datagram datagram) { GreDatagram greDatagram = (GreDatagram)datagram; switch (field.Name()) { case "gre.flags_and_version": XElement[] innerFields = field.Fields().ToArray(); MoreAssert.IsInRange(8, 9, innerFields.Length); int currentInnerFieldIndex = 0; innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.ChecksumPresent); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.RoutingPresent); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.KeyPresent); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.SequenceNumberPresent); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.StrictSourceRoute); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.RecursionControl); if (innerFields.Length == 9) { innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.AcknowledgmentSequenceNumberPresent); innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.FutureUseBits); } else { byte futureUseBitsValue = (byte)((greDatagram.AcknowledgmentSequenceNumberPresent.ToInt() << 4) | greDatagram.FutureUseBits); innerFields[currentInnerFieldIndex++].AssertShowDecimal(futureUseBitsValue); } innerFields[currentInnerFieldIndex].AssertShowDecimal((byte)greDatagram.Version); break; case "data.len": field.AssertShowDecimal( greDatagram.Payload.Length + (greDatagram.AcknowledgmentSequenceNumberPresent && (greDatagram.Version != GreVersion.EnhancedGre || !greDatagram.SequenceNumberPresent) ? 4 : 0), "GRE data.len"); field.AssertNoFields(); break; case "gre.checksum": field.AssertShowHex(greDatagram.Checksum); field.AssertNoFields(); break; case "gre.key.payload_length": field.AssertShowDecimal(greDatagram.KeyPayloadLength); field.AssertNoFields(); break; case "gre.key.call_id": field.AssertShowDecimal(greDatagram.KeyCallId); field.AssertNoFields(); break; case "gre.ack_number": field.AssertShowDecimal(greDatagram.AcknowledgmentSequenceNumber); field.AssertNoFields(); break; case "gre.sequence_number": field.AssertShowDecimal(greDatagram.SequenceNumber); field.AssertNoFields(); break; case "gre.offset": field.AssertShowDecimal(greDatagram.RoutingOffset); field.AssertNoFields(); break; case "gre.routing": field.AssertShow(""); field.AssertNoFields(); break; case "gre.routing.address_family": if (_routingEntryIndex == greDatagram.Routing.Count) field.AssertShowDecimal(0); else field.AssertShowDecimal((ushort)greDatagram.Routing[_routingEntryIndex].AddressFamily); field.AssertNoFields(); break; case "gre.routing.sre_offset": if (_routingEntryIndex == greDatagram.Routing.Count) field.AssertShowDecimal(0); else field.AssertShowDecimal(greDatagram.Routing[_routingEntryIndex].PayloadOffset); field.AssertNoFields(); break; case "gre.routing.src_length": if (_routingEntryIndex == greDatagram.Routing.Count) field.AssertShowDecimal(0); else field.AssertShowDecimal(greDatagram.Routing[_routingEntryIndex].PayloadLength); field.AssertNoFields(); break; case "gre.routing.information": if (_routingEntryIndex != greDatagram.Routing.Count) { switch (greDatagram.Routing[_routingEntryIndex].AddressFamily) { case GreSourceRouteEntryAddressFamily.IpSourceRoute: field.AssertValue(((GreSourceRouteEntryIp)greDatagram.Routing[_routingEntryIndex]).Addresses); break; case GreSourceRouteEntryAddressFamily.AsSourceRoute: field.AssertValue(((GreSourceRouteEntryAs)greDatagram.Routing[_routingEntryIndex]).AsNumbers); break; default: field.AssertValue(((GreSourceRouteEntryUnknown)greDatagram.Routing[_routingEntryIndex]).Data); break; } ++_routingEntryIndex; } field.AssertNoFields(); break; case "gre.proto": field.AssertShowHex((ushort)greDatagram.ProtocolType); field.AssertNoFields(); break; case "gre.key": field.AssertShowHex(greDatagram.Key); field.AssertNoFields(); break; case "data": case "data.data": field.AssertDataField(greDatagram.Payload); break; default: Assert.Fail("Invalid field name: " + field.Name()); break; } return true; }
public EthernetPayloadDatagrams(Datagram payload) { _payload = payload; }
private void DataReceived_Handler(byte[] data) { this.RoundTime = (int)DateTime.Now.Subtract(this.LastRecieveDatTime.Value).TotalMilliseconds; this.SendInterval = this.TimeOut - this.RoundTime; if (this.SendInterval < 0) { this.TimeOutCount += 1; } Datagram objDatagram = DatagramResolver.ResolveResponse(data); if (objDatagram != null) { if (objDatagram.Type == DatagramTypeEnum.HeartbeatResponse) { this.SendHeartbeatCount += 1; DataCounter.AddHeartbeat(); } if (objDatagram.Type == DatagramTypeEnum.LoginResponse) { this.SendLoginCount += 1; DataCounter.AddLogin(); } if (objDatagram.Type == DatagramTypeEnum.BlacklistQueryResponse) { BlacklistQueryResponse response = objDatagram as BlacklistQueryResponse; this.TargetDownloadBlacklist = response.BlacklistCount.ToInt16(); this.DownloadBlacklistCount = 0; DataCounter.AddBlacklistQuery(); DataCounter.AddSingleBlacklistDownload(this.TargetDownloadBlacklist); if (this.TargetDownloadBlacklist > 0) { this.IsFinishDownloadBlacklist = false; this.SendBlacklist(); } } if (objDatagram.Type == DatagramTypeEnum.BlacklistDownloadResponse) { this.DownloadBlacklistCount += 1; DataCounter.AddRealBlacklistDownload(); if (this.DownloadBlacklistCount >= this.TargetDownloadBlacklist) { this.IsFinishDownloadBlacklist = true; } else { this.SendBlacklist(); } } if (objDatagram.Type == DatagramTypeEnum.CurrencyResponse) { this.SendCurrencyCount += 1; this.SendSingleDataCurrencyCount += 1; DataCounter.AddCurrency(); if (this.SendCurrencyCount < this.TargetCurrencyCount) { if (this.SendSingleDataCurrencyCount == this.TargetSingleDayCurrencyCount) { this.SendDayCount += 1; this.SendSingleDataCurrencyCount = 0; } if (this.FixedSendSpeed && this.SendInterval > 0) { Thread.Sleep(this.SendInterval); } this.SendCurrency(); } } } }
/// <summary> /// Send a message to network /// </summary> /// <param name="text">Text of message</param> /// <param name="to">Who is supposed to receive it</param> /// <param name="network">Network where it is sent</param> /// <param name="_priority">Priority</param> /// <param name="pmsg">Whether it is supposed to be considered a private message</param> /// <returns></returns> public override int Message(string text, string to, Network network, Configuration.Priority _priority = Configuration.Priority.Normal, bool pmsg = false) { Datagram message = new Datagram("MESSAGE", text); if (network != null && NetworkList.Contains(network)) { message.Parameters.Add("network", network.ServerName); message.Parameters.Add("priority", _priority.ToString()); message.Parameters.Add("to", to); Deliver(message); } else { Core.DebugLog("Invalid network for message to: " + to); } return 0; }
public void WritePacket(Datagram datagramDiscardable, string?comment = null) { Packet pkt = datagramDiscardable.ToPacket(); WritePacket(ref pkt, PCapUtil.ConvertSystemTimeToTimeStampUsec(datagramDiscardable.TimeStamp), comment); }
private void OnNewData(Datagram datagram) { _dataStorage.Add(datagram); }
private void OnDataCaptured(Datagram datagram) { }
public HttpParser FieldContent(out IEnumerable<byte> fieldContent) { int originalOffset = Offset; fieldContent = null; while (Success) { fieldContent = new Datagram(_buffer, originalOffset, Offset - originalOffset); if (IsNext(AsciiBytes.Space) || IsNext(AsciiBytes.CarriageReturn) || IsNext(AsciiBytes.HorizontalTab) || IsNext(AsciiBytes.Linefeed)) break; if (IsNext(AsciiBytes.DoubleQuotationMark)) { Datagram quotedString; QuotedString(out quotedString); } else { var text = Range.TakeWhile(value => value > 0x20 && value != AsciiBytes.DoubleQuotationMark); if (!text.Any()) return Fail(); _offset += text.Count(); } } return this; }
protected override bool CompareField(XElement field, Datagram datagram) { IgmpDatagram igmpDatagram = (IgmpDatagram)datagram; switch (field.Name()) { case "igmp.version": if (field.Show() == "0") { return(false); // TODO: support IGMP version 0. } field.AssertShowDecimal(igmpDatagram.Version); break; case "igmp.type": field.AssertShowHex((byte)igmpDatagram.MessageType); break; case "igmp.checksum": field.AssertShowHex(igmpDatagram.Checksum); break; case "igmp.maddr": field.AssertShow(igmpDatagram.GroupAddress.ToString()); break; case "igmp.max_resp": field.AssertShowDecimal((int)((igmpDatagram.MaxResponseTime.TotalSeconds + 0.05) * 10)); break; case "igmp.checksum_bad": field.AssertShowDecimal(!igmpDatagram.IsChecksumCorrect); break; case "igmp.num_grp_recs": field.AssertShowDecimal(igmpDatagram.NumberOfGroupRecords); break; case "": switch (igmpDatagram.MessageType) { case IgmpMessageType.MembershipReportVersion3: CompareIgmpGroupRecord(field, igmpDatagram.GroupRecords[_groupRecordIndex++]); break; case IgmpMessageType.MembershipQuery: CompareDatagram(field, null, igmpDatagram); break; case IgmpMessageType.MulticastTraceRouteResponse: // todo support IGMP traceroute http://www.ietf.org/proceedings/48/I-D/idmr-traceroute-ipm-07.txt. break; default: if (typeof(IgmpMessageType).GetEnumValues <IgmpMessageType>().Contains(igmpDatagram.MessageType)) { throw new InvalidOperationException("Invalid message type " + igmpDatagram.MessageType); } field.AssertValue(igmpDatagram.Skip(1)); // field.AssertShow(igmpDatagram.Skip(1)); break; } break; case "igmp.s": field.AssertShowDecimal(igmpDatagram.IsSuppressRouterSideProcessing); break; case "igmp.qrv": field.AssertShowDecimal(igmpDatagram.QueryRobustnessVariable); break; case "igmp.qqic": field.AssertShowDecimal(igmpDatagram.QueryIntervalCode); break; case "igmp.num_src": field.AssertShowDecimal(igmpDatagram.NumberOfSources); break; case "igmp.saddr": field.AssertShow(igmpDatagram.SourceAddresses[_sourceAddressIndex++].ToString()); break; case "igmp.identifier": // todo support IGMP version 0 and IGMP identifier. break; case "igmp.mtrace.max_hops": case "igmp.mtrace.saddr": case "igmp.mtrace.raddr": case "igmp.mtrace.rspaddr": case "igmp.mtrace.resp_ttl": case "igmp.mtrace.q_id": // todo support IGMP traceroute http://www.ietf.org/proceedings/48/I-D/idmr-traceroute-ipm-07.txt. Assert.AreEqual(IgmpMessageType.MulticastTraceRouteResponse, igmpDatagram.MessageType); break; default: throw new InvalidOperationException("Invalid igmp field " + field.Name()); } return(true); }
public void InvalidGreTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; Random random = new Random(); for (int i = 0; i != 100; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre); ipV4Layer.HeaderChecksum = null; GreLayer greLayer = random.NextGreLayer(); greLayer.Checksum = null; greLayer.Routing = new List<GreSourceRouteEntry> { new GreSourceRouteEntryAs(new List<ushort> {123}.AsReadOnly(), 0), new GreSourceRouteEntryIp(new List<IpV4Address> {random.NextIpV4Address()}.AsReadOnly(), 0) }.AsReadOnly(); PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer); Packet packet = packetBuilder.Build(DateTime.Now); Assert.IsTrue(packet.IsValid || new[] {EthernetType.IpV4, EthernetType.Arp, EthernetType.VLanTaggedFrame}.Contains(greLayer.ProtocolType), "IsValid. ProtoclType=" + greLayer.ProtocolType); GreDatagram gre = packet.Ethernet.IpV4.Gre; // Remove a byte from routing Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray()); packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsNull(packet.Ethernet.IpV4.Gre.Payload); Assert.IsFalse(packet.IsValid); // SreLength is too big byte[] buffer = gre.ToArray(); buffer[buffer.Length - 1] = 200; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset is too big buffer = gre.ToArray(); buffer[gre.Length - 10] = 100; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset isn't aligned to ip buffer = gre.ToArray(); buffer[gre.Length - 10] = 3; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset isn't aligned to as buffer = gre.ToArray(); buffer[gre.Length - 16] = 1; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); } }
protected override bool CompareField(XElement field, Datagram datagram) { IpV6Datagram ipV6Datagram = (IpV6Datagram)datagram; SkipAuthenticationHeaders(ipV6Datagram); int optionsIndex = 0; switch (field.Name()) { case "ipv6.version": field.AssertShowDecimal(ipV6Datagram.Version); foreach (XElement subfield in field.Fields()) { switch (subfield.Name()) { case "ip.version": subfield.AssertShowDecimal(ipV6Datagram.Version); break; default: throw new InvalidOperationException(string.Format("Invalid ipv6 version subfield {0}", subfield.Name())); } } break; case "ipv6.class": field.AssertShowDecimal(ipV6Datagram.TrafficClass); break; case "ipv6.flow": field.AssertShowDecimal(ipV6Datagram.FlowLabel); field.AssertNoFields(); break; case "ipv6.plen": field.AssertShowDecimal(ipV6Datagram.PayloadLength); field.AssertNoFields(); break; case "ipv6.nxt": field.AssertShowDecimal((byte)ipV6Datagram.NextHeader); field.AssertNoFields(); break; case "ipv6.hlim": field.AssertShowDecimal(ipV6Datagram.HopLimit); field.AssertNoFields(); break; case "ipv6.src": case "ipv6.src_host": field.AssertShow(ipV6Datagram.Source.GetWiresharkString()); field.AssertNoFields(); break; case "ipv6.src_6to4_gw_ipv4": case "ipv6.src_6to4_sla_id": case "ipv6.6to4_gw_ipv4": case "ipv6.6to4_sla_id": field.AssertNoFields(); break; case "ipv6.dst": case "ipv6.dst_host": field.AssertShow(ipV6Datagram.CurrentDestination.GetWiresharkString()); field.AssertNoFields(); break; case "ipv6.addr": case "ipv6.host": Assert.IsTrue(field.Show() == ipV6Datagram.Source.GetWiresharkString() || field.Show() == ipV6Datagram.CurrentDestination.GetWiresharkString()); field.AssertNoFields(); break; case "ipv6.hop_opt": if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count) { Assert.IsFalse(ipV6Datagram.ExtensionHeaders.IsValid); int maxLength = ipV6Datagram.Length - IpV6Datagram.HeaderLength - ipV6Datagram.ExtensionHeaders.BytesLength; if (field.Fields().Any(subfield => subfield.Name() == "ipv6.opt.length")) { int length = int.Parse(field.Fields().First(subfield => subfield.Name() == "ipv6.opt.length").Show()); MoreAssert.IsBigger(maxLength, length); } else { Assert.AreEqual(6, maxLength); } } else { IpV6ExtensionHeaderHopByHopOptions hopByHopOptions = (IpV6ExtensionHeaderHopByHopOptions)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex]; IncrementCurrentExtensionHeaderIndex(ipV6Datagram); CompareOptions(field, ref optionsIndex, ipV6Datagram, hopByHopOptions); } break; case "ipv6.routing_hdr": if (!ipV6Datagram.IsValid) { return(false); } IpV6ExtensionHeaderRouting routing = (IpV6ExtensionHeaderRouting)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex]; IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks routingProtocolLowPowerAndLossyNetworks = routing as IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks; int routingProtocolLowPowerAndLossyNetworksAddressIndex = 0; IncrementCurrentExtensionHeaderIndex(ipV6Datagram); int sourceRouteAddressIndex = 0; foreach (var headerField in field.Fields()) { switch (headerField.Name()) { case "": headerField.AssertNoFields(); ValidateExtensionHeaderUnnamedField(routing, headerField); break; case "ipv6.routing_hdr.type": headerField.AssertNoFields(); headerField.AssertShowDecimal((byte)routing.RoutingType); break; case "ipv6.routing_hdr.left": headerField.AssertNoFields(); headerField.AssertShowDecimal(routing.SegmentsLeft); break; case "ipv6.mipv6_home_address": headerField.AssertNoFields(); IpV6ExtensionHeaderRoutingHomeAddress routingHomeAddress = (IpV6ExtensionHeaderRoutingHomeAddress)routing; headerField.AssertShow(routingHomeAddress.HomeAddress.ToString("x")); break; case "ipv6.routing_hdr.addr": headerField.AssertNoFields(); IpV6ExtensionHeaderRoutingSourceRoute routingSourceRoute = (IpV6ExtensionHeaderRoutingSourceRoute)routing; headerField.AssertShow(routingSourceRoute.Addresses[sourceRouteAddressIndex++].ToString("x")); break; case "ipv6.routing_hdr.rpl.cmprI": headerField.AssertNoFields(); headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForNonLastAddresses); break; case "ipv6.routing_hdr.rpl.cmprE": headerField.AssertNoFields(); headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForLastAddress); break; case "ipv6.routing_hdr.rpl.pad": headerField.AssertNoFields(); headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.PadSize); break; case "ipv6.routing_hdr.rpl.reserved": headerField.AssertNoFields(); headerField.AssertShowDecimal(0); break; case "ipv6.routing_hdr.rpl.segments": if (headerField.Fields().Any()) { headerField.AssertNumFields(1); headerField.Fields().First().AssertName("_ws.expert"); } // TODO: Remove this condition when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11803 is fixed. if (routingProtocolLowPowerAndLossyNetworks.Addresses.Count > 0) { headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.Addresses.Count); } break; case "ipv6.routing_hdr.rpl.address": headerField.AssertNoFields(); // TODO: Remove this condition when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11803 is fixed. if (routingProtocolLowPowerAndLossyNetworks.Addresses.Count > 0) { IpV6Address actualAddress = new IpV6Address(UInt128.Parse(headerField.Value(), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); Assert.AreEqual(routingProtocolLowPowerAndLossyNetworks.Addresses[routingProtocolLowPowerAndLossyNetworksAddressIndex], actualAddress); } break; case "ipv6.routing_hdr.rpl.full_address": headerField.AssertNoFields(); // TODO: Uncomment the following code when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10673 is fixed. // // TODO: Remove this condition when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11803 is fixed. // if (routingProtocolLowPowerAndLossyNetworks.Addresses.Count > 0) // { // IpV6Address actualFullAddress = new IpV6Address(headerField.Show()); // // IpV6Address destinationAddress = ipV6Datagram.CurrentDestination; // for (int i = 0; i < _currentExtensionHeaderIndex; ++i) // { // IpV6ExtensionHeaderRoutingHomeAddress ipV6ExtensionHeaderRoutingHomeAddress = // ipV6Datagram.ExtensionHeaders[i] as IpV6ExtensionHeaderRoutingHomeAddress; // if (ipV6ExtensionHeaderRoutingHomeAddress != null) // destinationAddress = ipV6ExtensionHeaderRoutingHomeAddress.HomeAddress; // // IpV6ExtensionHeaderRoutingSourceRoute ipV6ExtensionHeaderRoutingSourceRoute = // ipV6Datagram.ExtensionHeaders[i] as IpV6ExtensionHeaderRoutingSourceRoute; // if (ipV6ExtensionHeaderRoutingSourceRoute != null && ipV6ExtensionHeaderRoutingSourceRoute.Addresses.Any()) // destinationAddress = ipV6ExtensionHeaderRoutingSourceRoute.Addresses.Last(); // } // // int commonPrefixLength = // routingProtocolLowPowerAndLossyNetworksAddressIndex == routingProtocolLowPowerAndLossyNetworks.Addresses.Count - 1 // ? routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForLastAddress // : routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForNonLastAddresses; // // byte[] destinationAddressBytes = new byte[IpV6Address.SizeOf]; // destinationAddressBytes.Write(0, destinationAddress, Endianity.Big); // // byte[] routingAddressBytes = new byte[IpV6Address.SizeOf]; // routingAddressBytes.Write(0, routingProtocolLowPowerAndLossyNetworks.Addresses[routingProtocolLowPowerAndLossyNetworksAddressIndex], Endianity.Big); // // byte[] fullAddressBytes = destinationAddressBytes.Subsegment(0, commonPrefixLength).Concat(routingAddressBytes.Subsegment(commonPrefixLength, IpV6Address.SizeOf - commonPrefixLength)).ToArray(); // IpV6Address expectedFullAddress = fullAddressBytes.ReadIpV6Address(0, Endianity.Big); // // Assert.AreEqual(expectedFullAddress, actualFullAddress); // } ++routingProtocolLowPowerAndLossyNetworksAddressIndex; break; default: throw new InvalidOperationException("Invalid IPv6 routing source route field " + headerField.Name()); } } break; case "ipv6.dst_opt": if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count) { int expectedExtensionHeaderLength = (int.Parse(field.Fields().Skip(1).First().Value(), NumberStyles.HexNumber) + 1) * 8; int actualMaxPossibleLength = ipV6Datagram.RealPayloadLength - ipV6Datagram.ExtensionHeaders.Take(_currentExtensionHeaderIndex).Sum( extensionHeader => extensionHeader.Length); MoreAssert.IsSmaller(expectedExtensionHeaderLength, actualMaxPossibleLength); return(false); } IpV6ExtensionHeaderDestinationOptions destinationOptions = (IpV6ExtensionHeaderDestinationOptions)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex]; IncrementCurrentExtensionHeaderIndex(ipV6Datagram); CompareOptions(field, ref optionsIndex, ipV6Datagram, destinationOptions); break; case "ipv6.shim6": // TODO: Implement Shim6. IpV4Protocol nextHeader = _currentExtensionHeaderIndex > 0 ? ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex - 1].NextHeader.Value : ipV6Datagram.NextHeader; Assert.IsTrue(nextHeader == IpV4Protocol.Shim6); break; case "ipv6.unknown_hdr": Assert.AreEqual(ipV6Datagram.ExtensionHeaders.Count(), _currentExtensionHeaderIndex); // TODO: Fix according to https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=9996 return(false); case "ipv6.src_sa_mac": case "ipv6.dst_sa_mac": case "ipv6.sa_mac": case "ipv6.dst_6to4_gw_ipv4": case "ipv6.dst_6to4_sla_id": // TODO: Understand how these are calculated. break; case "": switch (field.Show()) { case "Fragmentation Header": if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count && !ipV6Datagram.IsValid) { return(false); } IpV6ExtensionHeaderFragmentData fragmentData = (IpV6ExtensionHeaderFragmentData)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex]; IncrementCurrentExtensionHeaderIndex(ipV6Datagram); foreach (var headerField in field.Fields()) { switch (headerField.Name()) { case "ipv6.fragment.nxt": headerField.AssertValue((byte)fragmentData.NextHeader.Value); break; case "ipv6.fragment.offset": headerField.AssertShowDecimal(fragmentData.FragmentOffset); break; case "ipv6.fragment.more": headerField.AssertShowDecimal(fragmentData.MoreFragments); break; case "ipv6.fragment.id": headerField.AssertShowDecimal(fragmentData.Identification); break; case "ipv6.fragment.reserved_octet": case "ipv6.fragment.reserved_bits": headerField.AssertShowDecimal(0); break; default: throw new InvalidOperationException("Invalid ipv6 fragmentation field " + headerField.Name()); } } break; default: throw new InvalidOperationException(string.Format("Invalid ipv6 field {0}", field.Show())); } break; default: throw new InvalidOperationException(string.Format("Invalid ipv6 field {0}", field.Name())); } return(true); }
public EthernetPayloadDatagrams(Datagram payload) { _payload = payload; }
internal static void Write(byte[] buffer, ref int offset, IgmpRecordType recordType, Datagram auxiliaryData, IpV4Address multicastAddress, ReadOnlyCollection<IpV4Address> sourceAddresses) { buffer.Write(offset + Offset.RecordType, (byte)recordType); buffer.Write(offset + Offset.AuxiliaryDataLength, (byte)(auxiliaryData.Length / 4)); int numSourceAddresses = sourceAddresses.Count; buffer.Write(offset + Offset.NumberOfSources, (ushort)numSourceAddresses, Endianity.Big); buffer.Write(offset + Offset.MulticastAddress, multicastAddress, Endianity.Big); for (int i = 0; i != numSourceAddresses; ++i) buffer.Write(offset + Offset.SourceAddresses + IpV4Address.SizeOf * i, sourceAddresses[i], Endianity.Big); offset += HeaderLength + numSourceAddresses * IpV4Address.SizeOf; buffer.Write(ref offset, auxiliaryData); }
internal HttpDatagram(byte[] buffer, int offset, int length, HttpVersion version, HttpHeader header, Datagram body) : base(buffer, offset, length) { Version = version; Header = header; Body = body; }
private void SendDatagram(IPEndPoint senderEndpoint, Datagram datagram) { SendDatagram(senderEndpoint, datagram, false); }
private void SendDatagram(IPEndPoint senderEndpoint, Datagram datagram) { SendDatagram(senderEndpoint, datagram, false); }
private void SendDatagram(IPEndPoint senderEndpoint, Datagram datagram, bool isResend) { if (datagram.MessageParts.Count != 0) { Log.Debug("<\tSend Datagram #" + datagram.Header.datagramSequenceNumber.IntValue()); byte[] data = datagram.Encode(); datagram.Timer.Restart(); SendData(data, senderEndpoint); } }
public void DatagramCalculateIsValidTest() { Datagram data = new Datagram(new byte[] { 1, 2, 3 }); Assert.IsTrue(data.IsValid); }
protected override bool Ignore(Datagram datagram) { HttpDatagram httpDatagram = (HttpDatagram)datagram; return(httpDatagram.Header != null && httpDatagram.Header.ContentLength != null && httpDatagram.Header.TransferEncoding != null); }
protected override bool CompareField(XElement field, Datagram parentDatagram, Datagram datagram) { IpDatagram ipDatagram = (IpDatagram)parentDatagram; UdpDatagram udpDatagram = (UdpDatagram)datagram; switch (field.Name()) { case "udp.srcport": field.AssertShowDecimal(udpDatagram.SourcePort); break; case "udp.dstport": field.AssertShowDecimal(udpDatagram.DestinationPort); break; case "udp.port": Assert.IsTrue(ushort.Parse(field.Show()) == udpDatagram.SourcePort || ushort.Parse(field.Show()) == udpDatagram.DestinationPort); break; case "udp.length": field.AssertShowDecimal(udpDatagram.TotalLength); break; case "udp.checksum": field.AssertShowDecimal(udpDatagram.Checksum); if (udpDatagram.Checksum != 0) { foreach (var checksumField in field.Fields()) { switch (checksumField.Name()) { case "udp.checksum_good": checksumField.AssertShowDecimal(ipDatagram.IsTransportChecksumCorrect); break; case "udp.checksum_bad": if (checksumField.Show() == "1") { Assert.IsFalse(ipDatagram.IsTransportChecksumCorrect); } else { checksumField.AssertShowDecimal(0); } break; } } } break; case "udp.checksum_coverage": field.AssertShowDecimal(udpDatagram.TotalLength); break; case "udp.stream": break; default: throw new InvalidOperationException("Invalid udp field " + field.Name()); } return(true); }
protected override bool CompareField(XElement field, Datagram datagram) { HttpDatagram httpDatagram = (HttpDatagram)datagram; if (field.Name() == "data" || field.Name() == "data.data") { if (field.Name() == "data") { field.AssertNoShow(); } MoreAssert.AreSequenceEqual(httpDatagram.Subsegment(0, _data.Length / 2), HexEncoding.Instance.GetBytes(_data.ToString())); // TODO: Uncomment once https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7065 is fixed. // if (!IsBadHttpResponse(httpDatagram)) // field.AssertValue(httpDatagram.Subsegment(_data.Length / 2, httpDatagram.Length - _data.Length / 2)); return(false); } string fieldShow = field.Show(); string httpFieldName; switch (field.Name()) { case "http.request": field.AssertShowDecimal(httpDatagram.IsRequest); break; case "http.response": field.AssertShowDecimal(httpDatagram.IsResponse); break; case "": if (fieldShow == "HTTP chunked response") { throw new InvalidOperationException("HTTP chunked response"); } _data.Append(field.Value()); if (fieldShow == @"\r\n") { break; } if (_isFirstEmptyName) { CompareHttpFirstLine(field, httpDatagram); _isFirstEmptyName = false; } else if (fieldShow.StartsWith("Content-encoded entity body")) { break; } else { fieldShow = EncodingExtensions.Iso88591.GetString(HexEncoding.Instance.GetBytes(field.Value())); fieldShow = fieldShow.Substring(0, fieldShow.Length - 2); int colonIndex = fieldShow.IndexOf(':'); MoreAssert.IsBiggerOrEqual(0, colonIndex, "Can't find colon in field with empty name"); if (httpDatagram.Header == null) { if (httpDatagram.IsRequest) { Assert.IsNull(httpDatagram.Version); } else { Assert.IsTrue(IsBadHttp(httpDatagram)); } break; } httpFieldName = fieldShow.Substring(0, colonIndex); if (!field.Value().EndsWith("0d0a")) { Assert.IsNull(httpDatagram.Header[httpFieldName]); } else { string fieldValue = fieldShow.Substring(colonIndex + 1).SkipWhile(c => c == ' ').TakeWhile(c => c != '\\').SequenceToString(); string expectedFieldValue = httpDatagram.Header[httpFieldName].ValueString; Assert.IsTrue(expectedFieldValue.Contains(fieldValue), string.Format("{0} <{1}> doesn't contain <{2}>", field.Name(), expectedFieldValue, fieldValue)); } } break; case "data.len": field.AssertShowDecimal(httpDatagram.Length - _data.Length / 2); break; case "http.host": case "http.user_agent": case "http.accept": case "http.accept_language": case "http.accept_encoding": case "http.connection": case "http.cookie": case "http.cache_control": case "http.content_encoding": case "http.date": case "http.referer": case "http.last_modified": case "http.server": case "http.set_cookie": case "http.location": _data.Append(field.Value()); httpFieldName = field.Name().Substring(5).Replace('_', '-'); HttpField httpField = httpDatagram.Header[httpFieldName]; if (!field.Value().EndsWith("0d0a")) { Assert.IsNull(httpField); } else { string fieldValue = field.Show().Replace("\\\"", "\""); string expectedFieldValue = httpField.ValueString; Assert.IsTrue(expectedFieldValue.Contains(fieldValue), string.Format("{0} <{1}> doesn't contain <{2}>", field.Name(), expectedFieldValue, fieldValue)); } break; case "http.content_length_header": _data.Append(field.Value()); if (!IsBadHttp(httpDatagram)) { if (!field.Value().EndsWith("0d0a")) { Assert.IsNull(httpDatagram.Header.ContentLength); } else { field.AssertShowDecimal(httpDatagram.Header.ContentLength.ContentLength.Value); } } break; case "http.content_type": _data.Append(field.Value()); string[] mediaType = fieldShow.Split(new[] { ';', ' ', '/' }, StringSplitOptions.RemoveEmptyEntries); if (!IsBadHttp(httpDatagram)) { if (!field.Value().EndsWith("0d0a")) { Assert.IsNull(httpDatagram.Header.ContentType); } else { Assert.AreEqual(httpDatagram.Header.ContentType.MediaType, mediaType[0]); Assert.AreEqual(httpDatagram.Header.ContentType.MediaSubtype, mediaType[1]); int fieldShowParametersStart = fieldShow.IndexOf(';'); if (fieldShowParametersStart == -1) { Assert.IsFalse(httpDatagram.Header.ContentType.Parameters.Any()); } else { string expected = httpDatagram.Header.ContentType.Parameters.Select(pair => pair.Key + '=' + pair.Value.ToWiresharkLiteral()). SequenceToString(';'); Assert.AreEqual(expected, fieldShow.Substring(fieldShowParametersStart + 1)); } } } break; case "http.transfer_encoding": _data.Append(field.Value()); if (!IsBadHttp(httpDatagram)) { Assert.AreEqual(fieldShow.ToWiresharkLowerLiteral(), httpDatagram.Header.TransferEncoding.TransferCodings.SequenceToString(',').ToLowerInvariant().ToWiresharkLiteral()); } break; case "http.request.full_uri": Assert.AreEqual(fieldShow, ("http://" + httpDatagram.Header["Host"].ValueString + ((HttpRequestDatagram)httpDatagram).Uri).ToWiresharkLiteral()); break; default: throw new InvalidOperationException("Invalid HTTP field " + field.Name()); } return(true); }
/// <summary> /// Create a remote connection to server /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns></returns> public override bool ConnectTo(string server, int port) { // remove space while (server.StartsWith(" ", StringComparison.Ordinal)) { server = server.Substring(1); } // in case that server is invalid, we ignore the request if (string.IsNullOrEmpty(server)) { return false; } // We also ignore it if we aren't connected to services if (ConnectionStatus == Status.Connected) { SystemWindow.scrollback.InsertText("Connecting to " + server, Client.ContentLine.MessageStyle.User, true); Datagram request = new Datagram("CONNECT", server); request.Parameters.Add("port", port.ToString()); Deliver(request); } return true; }
protected override bool CompareField(XElement field, Datagram datagram) { IpV4Datagram ipV4Datagram = (IpV4Datagram)datagram; switch (field.Name()) { case "ip.version": field.AssertShowDecimal(ipV4Datagram.Version); break; case "ip.hdr_len": field.AssertShowDecimal(ipV4Datagram.HeaderLength); break; case "ip.dsfield": field.AssertShowDecimal((int)ipV4Datagram.TypeOfService); break; case "ip.len": field.AssertShowDecimal(ipV4Datagram.TotalLength); break; case "ip.id": field.AssertShowHex(ipV4Datagram.Identification); break; case "ip.flags": field.AssertShowHex((byte)((ushort)ipV4Datagram.Fragmentation.Options >> 13)); break; case "ip.frag_offset": field.AssertShowDecimal(ipV4Datagram.Fragmentation.Offset); break; case "ip.ttl": field.AssertShowDecimal(ipV4Datagram.Ttl); break; case "ip.proto": field.AssertShowDecimal((byte)ipV4Datagram.Protocol); break; case "ip.checksum": field.AssertShowHex(ipV4Datagram.HeaderChecksum); foreach (var checksumField in field.Fields()) { switch (checksumField.Name()) { case "ip.checksum_good": checksumField.AssertShowDecimal(ipV4Datagram.IsHeaderChecksumCorrect); break; case "ip.checksum_bad": if (ipV4Datagram.Length < IpV4Datagram.HeaderMinimumLength || ipV4Datagram.Length < ipV4Datagram.HeaderLength) { break; } checksumField.AssertShowDecimal(!ipV4Datagram.IsHeaderChecksumCorrect); break; } } break; case "ip.src": case "ip.src_host": field.AssertShow(ipV4Datagram.Source.ToString()); break; case "ip.dst": case "ip.dst_host": if (field.Show() != ipV4Datagram.Destination.ToString()) { // TODO: Remove this fallback once https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7043 is fixed. field.AssertShow(ipV4Datagram.CurrentDestination.ToString()); Assert.IsTrue(ipV4Datagram.Options.IsBadForWireshark(), string.Format("Expected destination: {0}. Destination: {1}. Current destination: {2}.", field.Show(), ipV4Datagram.Destination, ipV4Datagram.CurrentDestination)); } break; case "ip.addr": case "ip.host": Assert.IsTrue(field.Show() == ipV4Datagram.Source.ToString() || field.Show() == ipV4Datagram.Destination.ToString() || // TODO: Remove this fallback once https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7043 is fixed. field.Show() == ipV4Datagram.CurrentDestination.ToString() && ipV4Datagram.Options.IsBadForWireshark(), string.Format("Expected ip: {0}. ", field.Show()) + (ipV4Datagram.IsValid ? string.Format("Source: {0}. Destination: {1}. Current destination: {2}.", ipV4Datagram.Source, ipV4Datagram.Destination, ipV4Datagram.CurrentDestination) : "")); break; case "": CompareIpV4Options(field, ipV4Datagram.Options); break; default: throw new InvalidOperationException("Invalid ip field " + field.Name()); } return(true); }
/// <summary> /// Disconnect from a specific network on bouncer side /// </summary> /// <param name="network"></param> public void Disconnect(Network network) { Transfer("QUIT :" + network.Quit, Configuration.Priority.High, network); Datagram request = new Datagram("REMOVE", network.ServerName); Deliver(request); }
/// <summary> /// Sends a received order to the dispatcher /// </summary> public void SendOrder(Order order) { SendData(Datagram.CreateOrder(order)); }
/// <summary> /// Send a raw data to irc server you pick, you should always fill in network, or current network will be used /// </summary> /// <param name="text">Message</param> /// <param name="priority">priority</param> /// <param name="network">This value must be filled in - it's not required because some old functions do not provide it</param> public override void Transfer(string text, Configuration.Priority priority = Configuration.Priority.Normal, Network network = null) { if (network == null) { if (Core.SelectedNetwork != null && NetworkList.Contains(Core.SelectedNetwork)) { Datagram data = new Datagram("RAW", text); data.Parameters.Add("network", Core.SelectedNetwork.ServerName); Deliver(data); return; } } else { if (NetworkList.Contains(network)) { Datagram data = new Datagram("RAW", text); data.Parameters.Add("network", network.ServerName); Deliver(data); } else { Core.DebugLog("Network is not a part of this services connection " + network.ServerName); } } }
/// <summary> /// Sends status update to the dispatcher /// </summary> public void SendStatus(State status) { SendData(Datagram.CreateStatus(status)); }
private void Start() { try { Core.SystemForm.Chat.scrollback.InsertText(messages.get("loading-server", Core.SelectedLanguage, new List<string> { this.Server }), Client.ContentLine.MessageStyle.System); Core.SystemForm.Status("Connecting to " + Server); if (!SSL) { _networkStream = new System.Net.Sockets.TcpClient(Server, Port).GetStream(); _StreamWriter = new System.IO.StreamWriter(_networkStream); _StreamReader = new System.IO.StreamReader(_networkStream, Encoding.UTF8); } if (SSL) { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Server, Port); _networkSsl = new System.Net.Security.SslStream(client.GetStream(), false, new System.Net.Security.RemoteCertificateValidationCallback(Protocol.ValidateServerCertificate), null); _networkSsl.AuthenticateAsClient(Server); _StreamWriter = new System.IO.StreamWriter(_networkSsl); _StreamReader = new System.IO.StreamReader(_networkSsl, Encoding.UTF8); } Connected = true; Deliver(new Datagram("PING")); Deliver(new Datagram("LOAD")); Datagram login = new Datagram("AUTH", ""); login.Parameters.Add("user", nick); login.Parameters.Add("pw", password); Deliver(login); Deliver(new Datagram("GLOBALNICK")); Deliver(new Datagram("NETWORKLIST")); Deliver(new Datagram("STATUS")); keep = new System.Threading.Thread(_Ping); Core.SystemThreads.Add(keep); keep.Name = "pinger thread"; keep.Start(); } catch (System.Threading.ThreadAbortException) { return; } catch (Exception b) { Core.SystemForm.Chat.scrollback.InsertText(b.Message, Client.ContentLine.MessageStyle.System); return; } string text = ""; try { sBuffer = new Services.Buffer(this); Core.SystemForm.Status(getInfo()); while (!_StreamReader.EndOfStream && Connected) { text = _StreamReader.ReadLine(); Core.trafficscanner.Insert(Server, " >> " + text); while (Core.IsBlocked) { System.Threading.Thread.Sleep(100); } if (Valid(text)) { // if this return false the thread must be stopped now if (!Process(text)) { return; } continue; } } } catch (System.IO.IOException fail) { if (IsConnected && !disconnecting) { // we need to wrap this in another exception handler because the following functions are easy to throw some try { Core.SystemForm.Chat.scrollback.InsertText("Quit: " + fail.Message, Client.ContentLine.MessageStyle.System); Core.DebugLog("Clearing the sBuffer to prevent corrupted data being written"); sBuffer = null; Disconnect(); } catch (Exception f1) { Core.handleException(f1); } } } catch (System.Threading.ThreadAbortException) { Core.KillThread(System.Threading.Thread.CurrentThread, true); return; } catch (Exception fail) { if (IsConnected) { Core.handleException(fail); } Core.KillThread(System.Threading.Thread.CurrentThread); } }
/// <summary> /// Sends to the dispatcher an order that has just been served /// </summary> public void SendServed(Order served) { SendData(Datagram.CreateServed(served)); }
public bool StartServer() { Datagram.CreateObject().PutPool(); if (_listener != null) { return(false); // Already started } try { Log.Info("Initializing..."); InacvitityTimeout = Config.GetProperty("InactivityTimeout", 8500); if (Endpoint == null) { var ip = IPAddress.Parse(Config.GetProperty("ip", "0.0.0.0")); int port = Config.GetProperty("port", 19132); Endpoint = new IPEndPoint(ip, port); } ForwardAllPlayers = Config.GetProperty("ForwardAllPlayers", false); if (ForwardAllPlayers) { var ip = IPAddress.Parse(Config.GetProperty("ForwardIP", "127.0.0.1")); int port = Config.GetProperty("ForwardPort", 19132); ForwardTarget = new IPEndPoint(ip, port); } Log.Info("Loading plugins..."); PluginManager = new PluginManager(); PluginManager.LoadPlugins(); Log.Info("Plugins loaded!"); // Bootstrap server PluginManager.ExecuteStartup(this); MotdProvider = MotdProvider ?? new MotdProvider(); IsSecurityEnabled = Config.GetProperty("EnableSecurity", false); if (IsSecurityEnabled) { // http://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity UserManager = UserManager ?? new UserManager <User>(new DefaultUserStore()); RoleManager = RoleManager ?? new RoleManager <Role>(new DefaultRoleStore()); } GreylistManager = GreylistManager ?? new GreylistManager(this); SessionManager = SessionManager ?? new SessionManager(); LevelManager = LevelManager ?? new LevelManager(); PlayerFactory = PlayerFactory ?? new PlayerFactory(); PluginManager.EnablePlugins(this, LevelManager); // Cache - remove LevelManager.GetLevel(null, "Default"); _listener = new UdpClient(Endpoint); if (IsRunningOnMono()) { _listener.Client.ReceiveBufferSize = 1024 * 1024 * 3; _listener.Client.SendBufferSize = 4096; } else { //_listener.Client.ReceiveBufferSize = 1600*40000; _listener.Client.ReceiveBufferSize = int.MaxValue; //_listener.Client.SendBufferSize = 1600*40000; _listener.Client.SendBufferSize = int.MaxValue; _listener.DontFragment = false; _listener.EnableBroadcast = false; // SIO_UDP_CONNRESET (opcode setting: I, T==3) // Windows: Controls whether UDP PORT_UNREACHABLE messages are reported. // - Set to TRUE to enable reporting. // - Set to FALSE to disable reporting. uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; _listener.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); // //WARNING: We need to catch errors here to remove the code above. // } _ackTimer = new Timer(SendAckQueue, null, 0, 50); _cleanerTimer = new Timer(Update, null, 10, Timeout.Infinite); _listener.BeginReceive(ReceiveCallback, _listener); // Measure latency through system //_internalPingTimer = new Timer(delegate(object state) //{ // var playerSession = _playerSessions.Values.FirstOrDefault(); // if (playerSession != null) // { // var ping = new InternalPing(); // ping.Timer.Start(); // HandlePackage(ping, playerSession); // } //}, null, 1000, 1000); ServerInfo = new ServerInfo(LevelManager, _playerSessions) { MaxNumberOfPlayers = Config.GetProperty("MaxNumberOfPlayers", 1000) }; ServerInfo.MaxNumberOfConcurrentConnects = Config.GetProperty("MaxNumberOfConcurrentConnects", ServerInfo.MaxNumberOfPlayers); Log.Info("Server open for business on port " + Endpoint.Port + " ..."); return(true); } catch (Exception e) { Log.Error("Error during startup!", e); StopServer(); } return(false); }
/// <summary> /// Creates a new connect UDP request class instance /// </summary> public ConnectUdpRequest(Datagram datagram) { Data = datagram.Data; IpEndPoint = datagram.IpEndPoint; }
private void SendDatagram(PlayerNetworkSession session, Datagram datagram) { if (datagram.MessageParts.Count != 0) { datagram.Header.datagramSequenceNumber = Interlocked.Increment(ref Session.DatagramSequenceNumber); byte[] data = datagram.Encode(); datagram.Timer.Restart(); SendData(data, _serverEndpoint); } }
public void Endpoint_payload_fragment_combination_tests( [CombinatorialValues(AddressType.Ipv4, AddressType.Ipv6, AddressType.DomainName)] AddressType addressType, bool isFragment, bool hasPayload, bool testInsufficientBuffer) { EndPoint endPoint; byte[] expectedEndPointBytes; switch (addressType) { case AddressType.Ipv4: endPoint = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 127); expectedEndPointBytes = new byte[] { 1, 2, 3, 4, 0, 127 }; break; case AddressType.Ipv6: endPoint = new IPEndPoint(IPAddress.Parse("::1"), 127); expectedEndPointBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 127 }; break; case AddressType.DomainName: endPoint = new DnsEndPoint("google.com", 127); var addressByteCount = Encoding.ASCII.GetByteCount("google.com"); expectedEndPointBytes = new[] { (byte)addressByteCount } .Concat(Encoding.ASCII.GetBytes("google.com")) .Concat(new byte[] { 0, 127 }) .ToArray(); break; default: throw new AssertionFailedException($"Unknown address type: {addressType}"); } var datagram = new Datagram( new DatagramHeader(isFragment ? (byte)2 : (byte)0, isFragment, endPoint), hasPayload ? new ArraySegment <byte>(new byte[] { 1, 2, 3, 4 }) : new ArraySegment <byte>()); // Intentional bytes of empty space before the actual space const int emptySpacePrefix = 1; var buffer = new byte[emptySpacePrefix + 2 + 1 + 1 + expectedEndPointBytes.Length + datagram.Payload.Count]; int bufferLengthToCompare = buffer.Length - emptySpacePrefix; if (testInsufficientBuffer) { bufferLengthToCompare--; datagram .Invoking(d => d.WriteTo(new ArraySegment <byte>(buffer, emptySpacePrefix, bufferLengthToCompare))) .Should().Throw <ArgumentException>().And.Message.Should().ContainEquivalentOf("insufficient"); return; } datagram.WriteTo(new ArraySegment <byte>(buffer, emptySpacePrefix, bufferLengthToCompare)); var expectedBytes = Enumerable.Repeat((byte)0, emptySpacePrefix) .Concat(new byte[] { 0, 0, isFragment ? (byte)130 : (byte)0, (byte)addressType }) .Concat(expectedEndPointBytes) .Concat(datagram.Payload) .ToArray(); buffer.Should().Equal(expectedBytes); }
public HttpParser QuotedString(out Datagram quotedString) { quotedString = null; int startOffset = _offset; // Parse first " if (!Bytes(AsciiBytes.DoubleQuotationMark).Success) return this; // This cannot happen, since we call this method only when we have '"'. while (IsNext()) { byte next = Next(); // Parse last " if (next == AsciiBytes.DoubleQuotationMark) { ++_offset; quotedString = new Datagram(_buffer, startOffset, _offset - startOffset); return this; } // Parse \char if (next == AsciiBytes.BackSlash && IsNextNext() && NextNext().IsChar()) _offset += 2; else { // parse text int original = _offset; SkipLws(); if (original == _offset) { // text isn't LWS - parse a byte that isn't control if (!next.IsControl()) ++_offset; else return Fail(); // illegal byte } } } // no " found return Fail(); }
public void DatagramReceived(object sender, Datagram dg) { _logger.LogInformation("[" + dg.Ip + ":" + dg.Port + "]: " + Encoding.UTF8.GetString(dg.Data)); }
private void SendDatagram(PlayerNetworkSession session, Datagram datagram) { SendDatagram(session, datagram, true); }
protected abstract bool CompareField(XElement field, Datagram parentDatagram, Datagram datagram);
private void SendDatagram(IPEndPoint senderEndpoint, Datagram datagram) { PlayerNetworkSession session; if (_playerSessions.TryGetValue(senderEndpoint, out session)) { if (datagram.MessageParts.Count != 0) { //if (!isResend) { datagram.Header.datagramSequenceNumber = Interlocked.Increment(ref session.DatagramSequenceNumber); } byte[] data = datagram.Encode(); SendData(data, senderEndpoint, session.SyncRoot); datagram.TransmissionCount++; datagram.Timer.Restart(); if (!session.Player.IsBot) { session.WaitingForAcksQueue.TryAdd(datagram.Header.datagramSequenceNumber, datagram); } } if (session.Player.IsBot) { foreach (MessagePart part in datagram.MessageParts) { part.PutPool(); } datagram.PutPool(); } } }
protected virtual bool Ignore(Datagram datagram) { return(false); }
private void SendDatagram(PlayerNetworkSession session, Datagram datagram) { if (datagram.MessageParts.Count == 0) { datagram.PutPool(); Log.WarnFormat("Failed to resend #{0}", datagram.Header.datagramSequenceNumber.IntValue()); return; } datagram.Header.datagramSequenceNumber = Interlocked.Increment(ref session.DatagramSequenceNumber); datagram.TransmissionCount++; byte[] data = datagram.Encode(); datagram.Timer.Restart(); if (!session.WaitingForAcksQueue.TryAdd(datagram.Header.datagramSequenceNumber.IntValue(), datagram)) { Log.Warn(string.Format("Datagram sequence unexpectedly existed in the ACK/NAK queue already {0}", datagram.Header.datagramSequenceNumber.IntValue())); } lock (session.SyncRoot) { SendData(data, session.EndPoint); } }
public IgmpGroupRecord(IgmpRecordType recordType, IpV4Address multicastAddress, ReadOnlyCollection <IpV4Address> sourceAddresses, Datagram auxiliaryData) { if (auxiliaryData == null) { throw new ArgumentNullException("auxiliaryData"); } if (auxiliaryData.Length % 4 != 0) { throw new ArgumentException("Auxiliary data length must divide by 4 and can't be " + (object)auxiliaryData.Length, "auxiliaryData"); } this.RecordType = recordType; this.MulticastAddress = multicastAddress; this.SourceAddresses = sourceAddresses; this.AuxiliaryData = auxiliaryData; }
public void DatagramCalculateIsValidTest() { Datagram data = new Datagram(new byte[]{1,2,3}); Assert.IsTrue(data.IsValid); }
public IgmpGroupRecord(IgmpRecordType recordType, IpV4Address multicastAddress, IList <IpV4Address> sourceAddresses, Datagram auxiliaryData) : this(recordType, multicastAddress, new ReadOnlyCollection <IpV4Address>(sourceAddresses), auxiliaryData) { }