/// <summary> /// Initializes a new instance of the <see cref="EstablishUdpResponse"/> class. /// </summary> /// <param name="udpPort">The port to use for UDP communication.</param> /// <param name="request">The handled <see cref="EstablishUdpRequest"/>.</param> internal EstablishUdpResponse(int udpPort, RequestPacket request) : base(request) { UdpPort = udpPort; }
/// <summary> /// Central function for sending a request and reading the response. /// </summary> /// <param name="request"></param> /// <returns></returns> private ResponsePacket SendRequest( RequestPacket request) { LogCentral.Current.LogDebug(string.Format("Sending the following message to SpamAssassin:")); LogCentral.Current.LogDebug(request.RawPacket); using (Socket spamAssassinSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ) { // Firewall: allow incoming and outgoing requests // iptables -A INPUT -j ACCEPT // iptables -A OUTPUT -j ACCEPT spamAssassinSocket.Connect(serverName, serverPort); byte[] messageBuffer = System.Text.Encoding.ASCII.GetBytes(request.RawPacket); spamAssassinSocket.Send(messageBuffer); spamAssassinSocket.Shutdown(SocketShutdown.Send); int received; string receivedMessage = string.Empty; do { byte[] receiveBuffer = new byte[1024]; // spamd -D --listen 192.168.1.11 --allowed-ips=192.168.1.0/24 --allow-tell received = spamAssassinSocket.Receive(receiveBuffer); LogCentral.Current.LogDebug( string.Format( "Received {0} bytes from SpamAssassin.", received)); receivedMessage += Encoding.ASCII.GetString( receiveBuffer, 0, received); }while (received > 0); try { if (spamAssassinSocket.Connected) { spamAssassinSocket.Shutdown(SocketShutdown.Both); } } catch (System.Exception ex) { System.Console.WriteLine("Error !"); System.Console.WriteLine(ex.Message); } if (request.Command != SpamAssassinCommands.Skip && !receivedMessage.StartsWith( "SPAMD", StringComparison.InvariantCultureIgnoreCase)) { LogCentral.Current.LogWarn( "The received message does not start with 'SPAMD'."); } ResponsePacket response = new ResponsePacket( this, request, receivedMessage.Trim()); return(response); } }
/// <summary> /// Central function for sending a request and reading the response /// </summary> /// <param name="request"></param> /// <returns></returns> private ResponsePacket SendRequest(RequestPacket request) { using (var spamAssassinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { spamAssassinSocket.Connect(ServerName, ServerPort); var messageBuffer = Encoding.ASCII.GetBytes(request.RawPacket); spamAssassinSocket.Send(messageBuffer); spamAssassinSocket.Shutdown(SocketShutdown.Send); int received; var receivedMessage = string.Empty; do { var receiveBuffer = new byte[1024]; received = spamAssassinSocket.Receive(receiveBuffer); receivedMessage += Encoding.ASCII.GetString(receiveBuffer, 0, received); } while (received > 0); spamAssassinSocket.Shutdown(SocketShutdown.Both); if (request.Command != SpamAssassinCommands.Skip && !receivedMessage.StartsWith("SPAMD", StringComparison.InvariantCultureIgnoreCase)) { //TODO: Something } return new ResponsePacket(this, request, receivedMessage.Trim()); } }
public CalculationResponse(int Result, RequestPacket request) : base(request) { this.Result = Result; }
public void SyncTicks() { ServerTick = Environment.TickCount; Send(RequestPacket.TickSync(ServerTick)); }
public override void Handle(LoginSession session, PacketReader packet) { HandleCommon(session, packet); session.Send(RequestPacket.Login()); }
public override byte[] EncodeReturnValue(object returnValue, object[] parameters, RequestPacket response, RpcMethodMetadata metdata) { return(((IMessage)returnValue).ToByteArray()); }
private async Task HandleRequest(string json, ILogger logger) { var startTimestamp = Stopwatch.GetTimestamp(); var request = RequestPacket.Parse(json); if (logger.IsEnabled(LogLevel.Debug)) { LogRequest(json, logger, LogLevel.Debug); } var response = request.Reply(); try { if (!request.Command.StartsWith("/")) { request.Command = $"/{request.Command}"; } // hand off request to next layer if (_endpointHandlers.TryGetValue(request.Command, out var handler)) { var result = await handler.Value.Handle(request); response.Body = result; return; } throw new NotSupportedException($"Command '{request.Command}' is not supported."); } catch (Exception e) { if (e is AggregateException aggregateEx) { e = aggregateEx.Flatten().InnerException; } // updating the response object here so that the ResponseStream // prints the latest state when being closed response.Success = false; response.Message = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default); } finally { // response gets logged when Debug or more detailed log level is enabled // or when we have unsuccessful response (exception) if (logger.IsEnabled(LogLevel.Debug) || !response.Success) { // if logging is at Debug level, request would have already been logged // however not for higher log levels, so we want to explicitly log the request too if (!logger.IsEnabled(LogLevel.Debug)) { LogRequest(json, logger, LogLevel.Warning); } var currentTimestamp = Stopwatch.GetTimestamp(); var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp))); LogResponse(response.ToString(), logger, response.Success, elapsed); } // actually write it _writer.WriteLine(response); } }
public ResponsePacket OnPeerCoordination(RequestPacket requestPacket) { throw new System.NotImplementedException(); }
public override Task <object> Handle(RequestPacket context) { return(_action(context)); }
public PlayerResponsePacket(string ResponseJson, RequestPacket request) : base(request) { Response = ResponseJson; }
public ResponsePacket OnRouteTableQuery(RequestPacket requestPacket) { // Get RouteTableQuery_req packet params int connectionId = requestPacket.Id; string srcPort = requestPacket.SrcPort; string dstPort = requestPacket.DstPort; int slotsNumber = requestPacket.SlotsNumber; RequestPacket.Est est = requestPacket.Establish; if (est == RequestPacket.Est.Teardown) { LOG.Info($"Received RC::RouteTableQuery_req(Teardown, connectionId = {connectionId}, srcPort = {srcPort}," + $" dstPort = {dstPort}, slotsNumber = {slotsNumber})"); // The best idea will be to store the actual responses in a table / dict and when the Teardown RouteTableQuery // arrives, we just match connectionId, srcPort, dstPort, slotsNumber and if they are the same, just return // the same ResponsePacket. // e.g. instead of just returning ResponsePacket, do this: // ResponsePacket responsePacket = new ResponsePacket.Builder().<blablabla>.Build(); // _responsePackets[requestPacket] = responsePacket; // return responsePacket; // // and then when the Teardown comes, just do: LOG.Info($"Sending RC::RouteTableQuery_res(Teardown, connectionId = {connectionId})"); var teardownResponsePacket = _responsePackets[GetUniqueRcId(connectionId, srcPort, dstPort, slotsNumber)].Dequeue(); if (teardownResponsePacket == null) { LOG.Error("Could not find such connection"); return(new ResponsePacket.Builder().SetRes(ResponsePacket.ResponseType.Refused).Build()); } _connections.RemoveAll(connection => connectionId == connection.Id); return(teardownResponsePacket); } LOG.Info($"Received RC::RouteTableQuery_req(connectionId = {connectionId}, srcPort = {srcPort}," + $" dstPort = {dstPort}, slotsNumber = {slotsNumber})"); // Set dstZone depending on destination domain string secondDomainPortPattern = "3xx"; string dstZone; if (Checkers.PortMatches(secondDomainPortPattern, dstPort) > -1) // TODO: Check for matches value { dstZone = "012,021"; LOG.Trace($"Destination port belongs to other zone. Possible leaving ports: {dstZone}"); } else { dstZone = dstPort; LOG.Trace($"Destination port belongs to the same zone. Leaving port: {dstZone}"); } string gateway = GetBestGateway(srcPort, dstPort) ?? "0"; (int, int)slots = (0, 0); // Check whether we don't already have a registered connection with given connectionId if (!_connections.Exists(connection => connection.Id == connectionId)) { try { slots = CreateSlots(gateway, slotsNumber); } catch (Exception e) { LOG.Info(e.Message); return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.ResourcesProblem) .Build()); } _connections.Add(new Connection(connectionId, slots)); LOG.Trace($"Allocated slots {slots} for new connection with id {connectionId}"); } else { slots = _connections.Find(connection => connection.Id == connectionId).Slots; LOG.Trace($"There is already registered connection with id {connectionId}. Allocated slots: {slots}"); } ResponsePacket responsePacket = new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.Ok) .SetId(connectionId) .SetGateway(gateway) .SetSlots(slots) .SetDstZone(dstZone) .Build(); RequestPacket requestPacketWhenTeardown = requestPacket; requestPacketWhenTeardown.Establish = RequestPacket.Est.Teardown; string uniqueRcId = GetUniqueRcId(connectionId, srcPort, dstPort, slotsNumber); if (_responsePackets.ContainsKey(uniqueRcId)) { LOG.Trace($"_responsePacketsTable contains key: {uniqueRcId}"); } else { _responsePackets[uniqueRcId] = new Queue <ResponsePacket>(); } _responsePackets[uniqueRcId].Enqueue(responsePacket); LOG.Info($"Sending RC::RouteTableQuery_res" + $"(connectionId = {connectionId}, gateway = {gateway}," + $" slots = {slots.ToString()}, dstZone = {dstZone})"); return(responsePacket); }
public ResponsePacket OnNetworkTopology(RequestPacket requestPacket) { throw new System.NotImplementedException(); }
public ResponsePacket OnConnectionRequest(RequestPacket requestPacket) { int id = requestPacket.Id; string src = requestPacket.SrcPort; string dst = requestPacket.DstPort; int sl = requestPacket.SlotsNumber; RequestPacket.Est est = requestPacket.Establish; LOG.Info($"Received CC::ConnectionRequest_req(id = {id}, src = {src}, dst = {dst}, sl = {sl}, teardown = {est})"); LOG.Info($"Send RC::RouteTableQuery_req(id = {id}, src = {src}, dst = {dst}, sl = {sl}, teardown = {est})"); ResponsePacket routeTableQueryResponse = _rcRouteTableQueryClient.Get(new RequestPacket.Builder() .SetEst(est) .SetId(id) .SetSrcPort(src) .SetDstPort(dst) .SetSlotsNumber(sl) .Build()); if (routeTableQueryResponse.Res == ResponsePacket.ResponseType.ResourcesProblem) { LOG.Info("Received RC::RouteTableQuery_res(res = ResourcesProblem)"); LOG.Info("Send ConnectionRequest_res(res = ResourcesProblem)"); return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.ResourcesProblem) .Build()); } int rtqrId = routeTableQueryResponse.Id; string rtqrGateway = routeTableQueryResponse.Gateway; (int, int)rtqrSlots = routeTableQueryResponse.Slots; string dstZone = routeTableQueryResponse.DstZone; string gatewayOrEnd = rtqrGateway; LOG.Info($"Received RC::RouteTableQuery_res(id = {rtqrId}, gateway = {rtqrGateway}, slots = {rtqrSlots}, dstZone = {dstZone})"); if (dst != rtqrGateway) { string allocDealloc = est == RequestPacket.Est.Establish ? "allocate" : "deallocate"; LOG.Info($"Send LRM::LinkConnectionRequest_req(slots = {rtqrSlots}, {allocDealloc}, who = CC)"); ResponsePacket linkConnectionRequestResponse = _lrmLinkConnectionRequestClients[rtqrGateway].Get( new RequestPacket.Builder() .SetEst(est) .SetSlots(rtqrSlots) .SetShouldAllocate(true) .SetWhoRequests(RequestPacket.Who.Cc) .Build()); if (linkConnectionRequestResponse.Res == ResponsePacket.ResponseType.Refused) { LOG.Info("Received LRM::LinkConnectionRequest_res(res = Refused)"); LOG.Info("Send CC::ConnectionRequest_res(res = Refused)"); return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.Refused) .Build()); } gatewayOrEnd = linkConnectionRequestResponse.End; LOG.Info($"Received LRM::LinkConnectionRequest_res(end = {gatewayOrEnd})"); } else { ResponsePacket.ResponseType resp; if (est == RequestPacket.Est.Teardown) { LOG.Debug("Dst == Gateway, LRM will be handled by the layers above"); LOG.Info($"Delete FIB row [inPort = {src}, slots = ({rtqrSlots.Item1}, {rtqrSlots.Item2}), outPort = {rtqrGateway}]"); ResponsePacket deleteFibResponseDst = _nnFibInsertClient.Get(new ManagementPacket.Builder() .SetCommandType("delete") .SetCommandData($"{src} {rtqrSlots.Item1} {rtqrSlots.Item2} {rtqrGateway}") .Build()); resp = deleteFibResponseDst.Res; } else { LOG.Debug("Dst == Gateway, LRM will be handled by the layers above"); LOG.Info($"Insert FIB row [inPort = {src}, slots = ({rtqrSlots.Item1}, {rtqrSlots.Item2}), outPort = {rtqrGateway}]"); ResponsePacket insertFibResponseDst = _nnFibInsertClient.Get(new ManagementPacket.Builder() .SetCommandType("add") .SetCommandData($"{src} {rtqrSlots.Item1} {rtqrSlots.Item2} {rtqrGateway}") .Build()); resp = insertFibResponseDst.Res; } if (resp == ResponsePacket.ResponseType.Ok) { LOG.Info($"Send CC::PeerCoordination_res(OK, slots = {rtqrSlots})"); return(new ResponsePacket.Builder().SetRes(ResponsePacket.ResponseType.Ok).SetSlots(rtqrSlots) .Build()); } } // gateway == dstZone && dstZone != dst -- TODO Not implemented ResponsePacket.ResponseType res; if (est == RequestPacket.Est.Teardown) { LOG.Info($"Delete FIB row [inPort = {src}, slots = ({rtqrSlots.Item1}, {rtqrSlots.Item2}), outPort = {rtqrGateway}]"); ResponsePacket deleteFibResponse = _nnFibInsertClient.Get(new ManagementPacket.Builder() .SetCommandType("delete") .SetCommandData($"{src} {rtqrSlots.Item1} {rtqrSlots.Item2} {rtqrGateway}") .Build()); res = deleteFibResponse.Res; } else { LOG.Info($"Insert FIB row [inPort = {src}, slots = ({rtqrSlots.Item1}, {rtqrSlots.Item2}), outPort = {rtqrGateway}]"); ResponsePacket insertFibResponse = _nnFibInsertClient.Get(new ManagementPacket.Builder() .SetCommandType("add") .SetCommandData($"{src} {rtqrSlots.Item1} {rtqrSlots.Item2} {rtqrGateway}") .Build()); res = insertFibResponse.Res; } if (res == ResponsePacket.ResponseType.Ok) { LOG.Info($"Send CC::PeerCoordination_req(id = {id}, src = {gatewayOrEnd}, dst = {dst}, slots = {rtqrSlots}, teardown = {est})"); ResponsePacket peerCoordinationResponse = _ccPeerCoordinationClients[GetCcName(gatewayOrEnd)].Get( new RequestPacket.Builder() .SetEst(est) .SetId(id) .SetSrcPort(gatewayOrEnd) .SetDstPort(dst) .SetSlots(rtqrSlots) .Build()); LOG.Info($"Received CC::PeerCoordination_res(res = {ResponsePacket.ResponseTypeToString(peerCoordinationResponse.Res)})"); if (peerCoordinationResponse.Res == ResponsePacket.ResponseType.Ok) { LOG.Info($"Send CC::ConnectionRequest_res(res = OK, nextZonePort = NULL, slots = {rtqrSlots})"); return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.Ok) .SetNextZonePort("") .SetSlots(rtqrSlots) .Build()); } // else LOG.Info($"Send CC::ConnectionRequest_res(res = Refused, nextZonePort = NULL, slots = {rtqrSlots})"); return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.Refused) .SetNextZonePort("") .SetSlots(rtqrSlots) .Build()); } LOG.Info("Send CC::ConnectionRequest_res(res = Refused)"); // else return(new ResponsePacket.Builder() .SetRes(ResponsePacket.ResponseType.Refused) .Build()); }
public override byte[] EncodeMethodParameters(object[] parameters, RequestPacket request, RpcMethodMetadata metdata) { return(((IMessage)parameters[0]).ToByteArray()); }
private void UnregisterAssembly(RequestPacket requestPacket, HttpListenerResponse response) { //Not Implemented }
public abstract Task <object> Handle(RequestPacket packet);
public ResponsePacket OnCallRequestReceived(RequestPacket requestPacket) { // Get ConnectionRequest_req packet params GenericPacket.PacketType type = requestPacket.Type; string srcName = requestPacket.SrcName; string dstName = requestPacket.DstName; int slotsNumber = requestPacket.SlotsNumber; LOG.Info($"Received NCC::CallRequest_req" + $"(srcName = {srcName}, dstName = {dstName}, slotsNumber = {slotsNumber})"); // < C A L L A D M I S S I O N C O N T R O L > LOG.Info("Call Admission Control"); // P O L I C Y // Randomize chance of rejecting ConnectionRequest_req by Policy component int chanceToRejectRequestInPolicy = _rnd.Next(0, 100); if (chanceToRejectRequestInPolicy > 5) { LOG.Info("ConnectionRequest meets conditions of Policy component"); } else { return(new Builder() .SetRes(ResponseType.AuthProblem) .Build()); } // D I R E C T O R Y // Find srcName and dstName ports in clientPortAliases dictionary string srcPort = null; string dstPort = null; foreach (string clientPortName in _clientPortAliases.Keys) { if (clientPortName == srcName) { srcPort = _clientPortAliases[clientPortName]; } if (clientPortName == dstName) { dstPort = _clientPortAliases[clientPortName]; } } // If Directory couldn't find dstPort send NCC::CallRequest_res(res=No client); if (dstPort == null) { LOG.Info($"Directory could not find port for user {dstName}"); LOG.Info($"NCC::CallRequest_res(res = {ResponseTypeToString(ResponseType.NoClient)})"); return(new Builder() .SetRes(ResponseType.NoClient) .Build()); } LOG.Info($"Directory found port: {dstPort} for client: {dstName}"); LOG.Info($"Call Admission Control ended succesfully"); // </ C A L L A D M I S S I O N C O N T R O L > //TODO [ASON] Ask dstClient if he wants to connect with srcClient // If CAC is passed, create a connection int connectionId = int.Parse($"{_domain[1]}{_connectionCounter++}{srcPort}{dstPort}"); LOG.Trace($"connectionId: {connectionId}"); Connection newConnection = new Connection(connectionId, srcName, srcPort, dstName, dstPort, slotsNumber); _connections.Add(newConnection); // Output active connections LOG.Info("Active Connections: "); foreach (Connection con in _connections) { LOG.Info(con.ToString); } // Check if dstPort is from NCC's domain or outside the domain string dstDomain = GetDomainFromPort(dstPort); bool outsideDomain = dstDomain != _domain; ResponseType res; //aux var for storing OneShotClients responses if (outsideDomain) { // Inter domain connections only // Ask second domain NCC // Send NCC::CallCoordination(srcName, dstName, sl) LOG.Info("Send NCC::CallCoordination_req" + $"(srcName = {newConnection.SrcName}, dstName = {newConnection.DstName}, sl = {newConnection.SlotsNumber})"); ResponsePacket nccCallCoordinationResponse = _nccCallCoordinationClient.Get(new RequestPacket.Builder() .SetSrcName(newConnection.SrcName) .SetDstName(newConnection.DstName) .SetSlotsNumber(newConnection.SlotsNumber) .Build()); res = nccCallCoordinationResponse.Res; LOG.Info($"Received NCC::CallCoordination_res(res = {res})"); // If second domain NCC refused the call we should also refuse it if (res != ResponseType.Ok) { LOG.Info($"Second domain refused the call"); LOG.Info($"Send NCC::CallRequest_res(res = {ResponseTypeToString(ResponseType.AuthProblem)})"); return(new Builder() .SetRes(ResponseType.Refused) .Build()); } } // Order domain CC to set a Connection // Send CC:ConnectionRequest(id, src, dst, sl) LOG.Info("Send CC:ConnectionRequest_req" + $"(id = {connectionId}, src = {newConnection.SrcPortAlias}, dst = {newConnection.DstPortAlias}, sl = {newConnection.SlotsNumber})"); RequestPacket ccConnectionRequestPacket = new RequestPacket.Builder() .SetId(newConnection.Id) .SetSrcPort(newConnection.SrcPortAlias) .SetDstPort(newConnection.DstPortAlias) .SetSlotsNumber(newConnection.SlotsNumber) .Build(); ResponsePacket connectionRequestResponse = _ccConnectionRequestClient.Get(ccConnectionRequestPacket); LOG.Info($"Received CC:ConnectionRequest_res(res = {connectionRequestResponse.Res})"); res = connectionRequestResponse.Res; (int, int)slots = connectionRequestResponse.Slots; // Check domain CC response switch (res) { case ResponseType.Ok: { _ccConnectionRequests[newConnection.Id] = ccConnectionRequestPacket; LOG.Info($"Send NCC::CallRequest_res(res = OK, id = {newConnection.Id}, slots = {slots})"); return(new Builder() .SetRes(ResponseType.Ok) .SetId(newConnection.Id) .SetSlots(slots) .Build()); } case ResponseType.ResourcesProblem: { LOG.Info("Send NCC:CallRequest_res(res = ResourcesProblem)"); return(new Builder() .SetRes(ResponseType.ResourcesProblem) .Build()); } default: { LOG.Info("Send NCC::CallRequest_res(res = Network Problem)"); return(new Builder() .SetRes(ResponseType.NetworkProblem) .Build()); } } }
public ResponsePacket(SpamAssassinProtocolBase owner, RequestPacket associatedRequestPackage, string rawPacket) : base(owner) { RawPacket = rawPacket; AssociatedRequestPackage = associatedRequestPackage; ParseRawPacket(rawPacket); }
/// <summary> /// Initializes a new instance of the <see cref="ResponsePacket"/> class. /// </summary> /// <param name="packet">The <see cref="RequestPacket"/> that is being handled.</param> public ResponsePacket(RequestPacket packet) { ID = packet.ID; }
public Task <ResponsePacket> Request(RequestPacket packet, CancellationToken cancellationToken = default(CancellationToken)) { return(_connection.Request(packet, cancellationToken)); }