public override Result DecodeRequest()
        {
            var decodeRequest = base.DecodeRequest();

            if (decodeRequest.Failure)
            {
                return(decodeRequest);
            }

            var nextReadIndex = 1;

            var localIpLen = BitConverter.ToInt32(RequestBytes, nextReadIndex);

            nextReadIndex += Constants.SizeOfInt32InBytes;

            var localIp = Encoding.UTF8.GetString(RequestBytes, nextReadIndex, localIpLen);

            nextReadIndex += localIpLen + Constants.SizeOfInt32InBytes;

            PortNumber     = BitConverter.ToInt32(RequestBytes, nextReadIndex);
            nextReadIndex += Constants.SizeOfInt32InBytes + Constants.SizeOfInt32InBytes;

            var platformBytes = BitConverter.ToInt32(RequestBytes, nextReadIndex).ToString();

            Platform       = (ServerPlatform)Enum.Parse(typeof(ServerPlatform), platformBytes);
            nextReadIndex += Constants.SizeOfInt32InBytes;

            var publicIpLen = BitConverter.ToInt32(RequestBytes, nextReadIndex);

            nextReadIndex += Constants.SizeOfInt32InBytes;

            var publicIp = Encoding.UTF8.GetString(RequestBytes, nextReadIndex, publicIpLen);

            nextReadIndex += publicIpLen;

            var transferFolderPathLen = BitConverter.ToInt32(RequestBytes, nextReadIndex);

            nextReadIndex += Constants.SizeOfInt32InBytes;

            TransferFolderPath = Encoding.UTF8.GetString(RequestBytes, nextReadIndex, transferFolderPathLen);

            LocalIpAddress  = IPAddress.None;
            PublicIpAddress = IPAddress.None;

            var parseLocalIp = NetworkUtilities.ParseSingleIPv4Address(localIp);

            if (parseLocalIp.Success)
            {
                LocalIpAddress = parseLocalIp.Value;
            }

            var parsePublicIp = NetworkUtilities.ParseSingleIPv4Address(publicIp);

            if (parsePublicIp.Success)
            {
                PublicIpAddress = parsePublicIp.Value;
            }

            return(Result.Ok());
        }
Пример #2
0
        public async Task <HostRecord> CreateHostRecordAsync(string HostName, string Ipv4Address, string HostMac = null)
        {
            // https://10.10.10.10/wapi/v2.9/record:host

            //Validations (4)
            // This area perform validations to the information provided to the function.
            // Check#1 - Validate input to ensure that thereis a hostname and an Ipv4Address
            if (String.IsNullOrEmpty(HostName) || string.IsNullOrEmpty(Ipv4Address))
            {
                return(default(HostRecord));
            }
            // Check#2 - Ensure that the host is not already in the DNS registry

            var hostAlreadyExists = await GetHostRecordAsync(HostName);

            if (hostAlreadyExists != null)
            {
                return(hostAlreadyExists); //record for that hostname already exists, return the existing record
            }
            // Check#3 - Validate the ipV4 address sent is a valid IP address
            if ((NetworkUtilities.ParseSingleIPv4Address(Ipv4Address).Value.ToString()) != Ipv4Address)
            {
                throw new ArgumentException($"The value of {Ipv4Address} is invalid. Check your values and try again.");
            }
            // Check#4 - Validate the ipV4 address is in one of the managed Ip Subnets in the InfoBlox API
            if (!IsIpv4AddressInSubnetsRange(Ipv4Address))
            {
                throw new ArgumentException($"The value of {Ipv4Address} is not within the range of the subnets managed by the InfoBlox Grid. Check your values and try again.");
            }

            //If everything is good so far... let's go ahead and make us a HostRecord!

            //Add spices to the recipe

            //Single line model construct. Pick your poison by uncommenting the chosen method. ;-)
            //HostRecord newHost = new HostRecord() { Name = HostName, Ipv4Addresses = new Ipv4Address[] { new Ipv4Address() { Value = Ipv4Address } } };

            //Multi-line model construct. Pick your poison by uncommenting the chosen method. ;-)
            HostRecordPost newHost = new HostRecordPost();

            newHost.Name          = HostName;
            newHost.Ipv4Addresses = new Ipv4AddressPost[] { new Ipv4AddressPost()
                                                            {
                                                                Value = Ipv4Address
                                                            } };

            //return newHost.ToJson();
            string apifunction    = "record:host";
            string apipath        = $"{helperConfig.ApiRoute}/{helperConfig.ApiVersion}/{apifunction}";
            string requestcontent = newHost.ToJson();

            string content = await IBXCallApi(HttpMethod : HttpMethod.Post, ApiFunction : apifunction, ApiPath : apipath, RequestContent : requestcontent);

            HostRecord createdHostRecord = await GetHostRecordAsync(HostName);

            return(createdHostRecord);
        }
Пример #3
0
        public async Task <HostRecord> UpdateHostRecordAsync(string HostName, HostRecordPost changedRecord)
        {
            // https://10.10.10.10/wapi/v2.9/record:host

            //Validations (4)
            // This area perform validations to the information provided to the function.
            // Check#1 - Validate input to ensure that thereis a hostname and Host object to update
            if (String.IsNullOrEmpty(HostName) || (changedRecord is null))
            {
                return(default(HostRecord));
            }
            // Check#2 - Ensure that the host is already in the DNS registry
            var hostAlreadyExists = await GetHostRecordAsync(HostName);

            if (hostAlreadyExists is null)
            {
                throw new ArgumentException($"The hostname  {HostName} is does not exist in the server or is invalid. Check your values and try again.");
            }
            // Check#3 - Validate the ipV4 address sent is a valid IP address
            string ipv4AddressToValidate = changedRecord.Ipv4Addresses[0].Value;

            if ((NetworkUtilities.ParseSingleIPv4Address(ipv4AddressToValidate).Value.ToString()) != ipv4AddressToValidate)
            {
                throw new ArgumentException($"The value of {ipv4AddressToValidate} is invalid. Check your values and try again.");
            }
            // Check#4 - Validate the ipV4 address is in one of the managed Ip Subnets in the InfoBlox API
            if (!IsIpv4AddressInSubnetsRange(ipv4AddressToValidate))
            {
                throw new ArgumentException($"The value of {ipv4AddressToValidate} is not within the range of the subnets managed by the InfoBlox Grid. Check your values and try again.");
            }

            //If everything is good so far... let's go ahead and prepare the info for the HostRecord!


            string apifunction    = "record:host";
            string refhost        = hostAlreadyExists.BaseRef;
            string apipath        = $"{helperConfig.ApiRoute}/{helperConfig.ApiVersion}/{apifunction}/{refhost}";
            string requestcontent = changedRecord.ToJson();

            string content = await IBXCallApi(HttpMethod : HttpMethod.Put, ApiFunction : apifunction, ApiPath : apipath, RequestContent : requestcontent);

            HostRecord createdHostRecord = await GetHostRecordAsync(changedRecord.Name);

            return(createdHostRecord);
        }
Пример #4
0
        public async Task <HostRecord> GetHostRecordByIPAddressAsync(string Ipv4Address)
        {
            //https://10.10.10.10/wapi/v2.9/ipv4address?status=USED&ip_address=10.10.10.10

            HostRecord createdHostRecord = new HostRecord();

            if (!String.IsNullOrEmpty(Ipv4Address))
            {
                // Check#2 - Validate the ipV4 address sent is a valid IP address
                if ((NetworkUtilities.ParseSingleIPv4Address(Ipv4Address).Value.ToString()) != Ipv4Address)
                {
                    throw new ArgumentException($"The value of {Ipv4Address} is invalid. Check your values and try again.");
                }
                // Check#3 - Validate the ipV4 address is in one of the managed Ip Subnets in the InfoBlox API
                if (!IsIpv4AddressInSubnetsRange(Ipv4Address))
                {
                    throw new ArgumentException($"The value of {Ipv4Address} is not within the range of the subnets managed by the InfoBlox Grid. Check your values and try again.");
                }

                string apifunction = "ipv4address";
                string apicommand  = $"status=USED&ip_address={Ipv4Address}";
                string apipath     = $"{helperConfig.ApiRoute}/{helperConfig.ApiVersion}/{apifunction}";

                string content = await IBXCallApi(HttpMethod : HttpMethod.Get, ApiFunction : apifunction, ApiPath : apipath, ApiCommand : apicommand);

                var returnedSearchResults = IPSearchResults.FromJson(content);

                if (returnedSearchResults.Count > 0)
                {
                    string hostname = (from item in returnedSearchResults
                                       select item.Names[0]).FirstOrDefault();

                    createdHostRecord = await GetHostRecordAsync(hostname);
                }
            }

            return(createdHostRecord);
        }
Пример #5
0
        public static IPAddress GetIpAddressFromUser(AppState state, string prompt)
        {
            var ipAddress = IPAddress.None;

            while (ipAddress.Equals(IPAddress.None))
            {
                DisplayLocalServerInfo(state);
                Console.WriteLine(prompt);
                var input = Console.ReadLine();

                var parseIpResult = NetworkUtilities.ParseSingleIPv4Address(input);
                if (parseIpResult.Failure)
                {
                    var errorMessage = $"Unable tp parse IPv4 address from input string: {parseIpResult.Error}";
                    Console.WriteLine(errorMessage);
                    continue;
                }

                ipAddress = parseIpResult.Value;
            }

            return(ipAddress);
        }
        async Task <Result <Socket> > AcceptConnectionFromRemoteServerAsync(CancellationToken token)
        {
            Result <Socket> acceptConnection;

            try
            {
                acceptConnection = await _listenSocket.AcceptTaskAsync(token).ConfigureAwait(false);
            }
            catch (TaskCanceledException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }
            catch (SocketException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }

            if (acceptConnection.Failure)
            {
                ReportError(acceptConnection.Error);
                return(Result.Fail <Socket>(acceptConnection.Error));
            }

            var socket = acceptConnection.Value;
            var remoteServerIpString  = socket.RemoteEndPoint.ToString().Split(':')[0];
            var remoteServerIpAddress = NetworkUtilities.ParseSingleIPv4Address(remoteServerIpString).Value;

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType             = EventType.ConnectionAccepted,
                RemoteServerIpAddress = remoteServerIpAddress
            });

            return(Result.Ok(socket));
        }
Пример #7
0
 public ServerInfo(string ipAddress, int portNumber) : this()
 {
     SessionIpAddress = NetworkUtilities.ParseSingleIPv4Address(ipAddress).Value;
     PortNumber       = portNumber;
 }
Пример #8
0
            int fileTransferRetryLimit,                 // 15, 16
            long lockoutExpireTimeInTicks) ReadRequestBytes(byte[] requestBytes)
        {
            var  remoteServerIpString       = string.Empty;
            var  remoteServerLocalIpString  = string.Empty;
            var  remoteServerPublicIpString = string.Empty;
            var  remoteServerPortNumber     = 0;
            var  remoteServerPlatform       = ServerPlatform.None;
            var  textMessage              = string.Empty;
            var  fileInfoList             = new FileInfoList();
            var  fileName                 = string.Empty;
            long fileSizeInBytes          = 0;
            var  localFolderPath          = string.Empty;
            var  remoteFolderPath         = string.Empty;
            long fileTransferResponseCode = 0;
            var  remoteServerTransferId   = 0;
            var  fileTransferRetryCounter = 0;
            var  fileTransferRetryLimit   = 0;
            long lockoutExpireTimeInTicks = 0;

            switch (ReadRequestType(requestBytes))
            {
            case RequestType.None:
                break;

            case RequestType.ServerInfoResponse:

                (remoteServerLocalIpString,
                 remoteServerPortNumber,
                 remoteServerPlatform,
                 remoteServerPublicIpString,
                 remoteFolderPath) = ReadServerInfoResponse(requestBytes);

                break;

            case RequestType.MessageRequest:

                (remoteServerIpString,
                 remoteServerPortNumber,
                 textMessage) = ReadRequestWithStringValue(requestBytes);

                break;

            case RequestType.InboundFileTransferRequest:

                (fileTransferResponseCode,
                 remoteServerTransferId,
                 fileTransferRetryCounter,
                 fileTransferRetryLimit,
                 fileName,
                 fileSizeInBytes,
                 remoteFolderPath,
                 localFolderPath,
                 remoteServerIpString,
                 remoteServerPortNumber) = ReadInboundFileTransferRequest(requestBytes);

                break;

            case RequestType.OutboundFileTransferRequest:

                (remoteServerTransferId,
                 fileName,
                 localFolderPath,
                 remoteServerIpString,
                 remoteServerPortNumber,
                 remoteFolderPath) = ReadOutboundFileTransferRequest(requestBytes);

                break;

            case RequestType.FileListRequest:

                (remoteServerIpString,
                 remoteServerPortNumber,
                 localFolderPath) = ReadRequestWithStringValue(requestBytes);

                break;

            case RequestType.FileListResponse:

                (remoteServerIpString,
                 remoteServerPortNumber,
                 remoteFolderPath,
                 fileInfoList) = ReadFileListResponse(requestBytes);

                break;

            case RequestType.ServerInfoRequest:
            case RequestType.RequestedFolderIsEmpty:
            case RequestType.RequestedFolderDoesNotExist:
            case RequestType.ShutdownServerCommand:

                (remoteServerIpString,
                 remoteServerPortNumber) = ReadServerInfo(requestBytes);

                break;

            case RequestType.FileTransferAccepted:
            case RequestType.FileTransferRejected:
            case RequestType.FileTransferStalled:
            case RequestType.FileTransferComplete:
            case RequestType.RetryOutboundFileTransfer:

                (remoteServerIpString,
                 remoteServerPortNumber,
                 fileTransferResponseCode,
                 remoteServerTransferId) = ReadFileTransferResponse(requestBytes);

                break;

            case RequestType.RequestedFileDoesNotExist:

                long fileTransferIdInt64;

                (remoteServerIpString,
                 remoteServerPortNumber,
                 fileTransferIdInt64,
                 _) = ReadFileTransferResponse(requestBytes);

                remoteServerTransferId = Convert.ToInt32(fileTransferIdInt64);

                break;

            case RequestType.RetryLimitExceeded:

                (remoteServerIpString,
                 remoteServerPortNumber,
                 remoteServerTransferId,
                 fileTransferRetryLimit,
                 lockoutExpireTimeInTicks) = ReadRetryLimitExceededRequest(requestBytes);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var remoteServerIpAddress = string.IsNullOrEmpty(remoteServerIpString)
                ? IPAddress.None
                : NetworkUtilities.ParseSingleIPv4Address(remoteServerIpString).Value;

            var remoteServerLocalIpAddress = string.IsNullOrEmpty(remoteServerLocalIpString)
                ? IPAddress.None
                : NetworkUtilities.ParseSingleIPv4Address(remoteServerLocalIpString).Value;

            var remoteServerPublicIpAddress = string.IsNullOrEmpty(remoteServerPublicIpString)
                ? IPAddress.None
                : NetworkUtilities.ParseSingleIPv4Address(remoteServerPublicIpString).Value;

            return(remoteServerIpAddress,
                   remoteServerLocalIpAddress,
                   remoteServerPublicIpAddress,
                   remoteServerPortNumber,
                   remoteServerPlatform,
                   textMessage,
                   fileInfoList,
                   fileName,
                   fileSizeInBytes,
                   localFolderPath,
                   remoteFolderPath,
                   fileTransferResponseCode,
                   remoteServerTransferId,
                   fileTransferRetryCounter,
                   fileTransferRetryLimit,
                   lockoutExpireTimeInTicks);
        }