示例#1
0
        private void BeginSend()
        {
            if (_Running == 0)
            {
                return;
            }

            RawData raw;

            if (!_SendingQueue.TryDequeue(out raw))
            {
                System.Threading.Interlocked.Exchange(ref _Writing, 0);
                return;
            }

            UDPSocket  socket   = _Socket;
            IPEndPoint remoteEP = (IPEndPoint)raw.EndPoint;

            if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
            {
                if (_SocketIPv4 != null)
                {
                    // use the separated socket of IPv4 to deal with IPv4 conversions.
                    socket = _SocketIPv4;
                }
                else if (_Socket.Socket.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    remoteEP = new IPEndPoint(IPAddressExtensions.MapToIPv6(remoteEP.Address), remoteEP.Port);
                }
            }

            BeginSend(socket, raw.Data, remoteEP);
        }
        /// <summary>
        /// Gets the first <see cref="System.Net.NetworkInformation.NetworkInterface"/> which has the given address bound.
        /// </summary>
        /// <param name="localAddress">The address which should be bound to the interface.</param>
        /// <returns>The <see cref="System.Net.NetworkInformation.NetworkInterface"/> associated with the address or the default if none were found.</returns>
        public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface(System.Net.IPAddress localAddress)
        {
            if (localAddress == null)
            {
                throw new System.ArgumentNullException();
            }

            bool isMulticast = IPAddressExtensions.IsMulticast(localAddress);

            //Iterate all NetworkInterfaves
            foreach (System.Net.NetworkInformation.NetworkInterface networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                //Only look for interfaces which are UP
                if (networkInterface.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
                {
                    continue;
                }

                if (isMulticast)
                {
                    if (false == networkInterface.SupportsMulticast)
                    {
                        continue;
                    }

                    //Check for the Multicast Address to be bound on the networkInterface
                    foreach (System.Net.NetworkInformation.MulticastIPAddressInformation ip in networkInterface.GetIPProperties().MulticastAddresses)
                    {
                        //If equal return
                        if (System.Net.IPAddress.Equals(localAddress, ip.Address))
                        {
                            return(networkInterface);
                        }
                    }
                }
                else
                {
                    //Check for the Unicast Address to be bound on the networkInterface
                    foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
                    {
                        //If equal return
                        if (System.Net.IPAddress.Equals(localAddress, ip.Address))
                        {
                            return(networkInterface);
                        }
                    }

                    //Check for the Anycast Address to be bound on the networkInterface
                    //if(s.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in networkInterface.GetIPProperties().AnycastAddresses)
                    //{
                    //    if (System.Net.IPAddress.Equals(localEndPoint.Address, ip.Address))
                    //    {
                    //        return networkInterface;
                    //    }
                    //}
                }
            }

            return(default(System.Net.NetworkInformation.NetworkInterface));
        }
        public static bool IsMulticast(this System.Net.IPAddress ipAddress)
        {
            if (ipAddress == null)
            {
                return(false);
            }

            byte[] addressBytes;

            switch (ipAddress.AddressFamily)
            {
            case System.Net.Sockets.AddressFamily.InterNetwork:
            {
#if UNSAFE
                unsafe
                {
                    //Read bits as a byte
                    byte prop = (byte)(long *)ipAddress.Address;

                    //Return the result of the evaluation
                    return(prop >= 224 && prop <= 239);
                }
#elif NATIVE
                byte highIP = System.Runtime.InteropServices.Marshal.ReadByte(ipAddress.Address, 0);

                return(highIP >= 224 && highIP <= 239);
#else
                byte highIP = (byte)(ipAddress.Address & byte.MaxValue);         // ipAddress.GetAddressBytes()[0];

                return(highIP >= 224 && highIP <= 239);
#endif
            }

            case System.Net.Sockets.AddressFamily.InterNetworkV6:
            {
                //Check for a ipv6 multicast address
                if (ipAddress.IsIPv6Multicast)
                {
                    return(true);
                }

                //could use out overload and check in place or pass out to MapToIpv4...

                //Check if mapped to v6 from v4 and unmap
                if (IPAddressExtensions.IsIPv4MappedToIPv6(ipAddress, out addressBytes)) //(ipAddress.IsIPv4MappedToIPv6)
                {
                    ipAddress = IPAddressExtensions.MapToIPv4(addressBytes);             //ipAddress.MapToIPv4();

                    //handle as v4
                    goto case System.Net.Sockets.AddressFamily.InterNetwork;
                }

                return(false);
            }

            default: return(false);
            }
        }
示例#4
0
        public static uint UserIp(this HttpRequest request)
        {
            if (request == null)
            {
                return(0);
            }

            // test with: http://www.countryipblocks.net/tools/ip-octet-binary-and-decimal-calculators/
            var ipAddress = request.UserIpAddress();

            return(IPAddressExtensions.IPv4ToUInt(ipAddress));
        }
示例#5
0
 private bool BelongsToSubnetwork(SNP SNPstart, SNP SNPend)
 {
     //sprawdza, czy ma taka pare na liscie
     foreach (SubnetworkAddress subAddress in ContainedSubnetworksAddresses)
     {
         if (IPAddressExtensions.IsInSameSubnet(IPAddress.Parse(SNPstart.Address), IPAddress.Parse(SNPend.Address), subAddress.subnetMask))
         {
             return(true);
         }
     }
     return(false);
 }
示例#6
0
        static ServiceStackHandlerBase()
        {
            try
            {
                IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses().ForEach((x, y) => NetworkInterfaceIpv4Addresses[x.GetAddressBytes()] = y.GetAddressBytes());

                NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses().ConvertAll(x => x.GetAddressBytes()).ToArray();
            }
            catch (Exception ex)
            {
                Log.Warn("Failed to retrieve IP Addresses, some security restriction features may not work: " + ex.Message, ex);
            }
        }
示例#7
0
        public static CSocket GetSocketToDomain(string address)
        {
            IPAddress         ipAddress = IPAddress.Parse(address);
            SubnetworkAddress found     = null;

            foreach (SubnetworkAddress domainAddress in SocketsToAnotherDomains.Keys)
            {
                if (IPAddressExtensions.IsInSameSubnet(ipAddress, domainAddress.subnetAddress, domainAddress.subnetMask))
                {
                    found = domainAddress;
                }
            }
            return(createSocketToOtherDomain(found));
        }
示例#8
0
 public void PerformAutoconnect()
 {
     if (MyFakes.ENABLE_CONNECT_COMMAND_LINE && m_args.Contains("+connect"))
     {
         int index = m_args.ToList().IndexOf("+connect");
         if ((index + 1) < m_args.Length)
         {
             if (IPAddressExtensions.TryParseEndpoint(m_args[index + 1], out MySandboxGame.ConnectToServer))
             {
                 Console.WriteLine(GameInfo.GameName + " " + MyFinalBuildConstants.APP_VERSION_STRING);
                 Console.WriteLine("Obfuscated: " + MyObfuscation.Enabled + ", Platform: " + (MyEnvironment.Is64BitProcess ? " 64-bit" : " 32-bit"));
                 Console.WriteLine("Connecting to: " + m_args[index + 1]);
             }
         }
     }
 }
示例#9
0
        private SubnetworkAddress findSubnetworkWhereIsContained(IPAddress isContained)
        {
            IPAddress         subnetAddress = null;
            IPAddress         subnetMask    = null;
            SubnetworkAddress subnetworkAddressWhereIsContained = null;

            foreach (SubnetworkAddress address in subnetworks)
            {
                subnetAddress = address.subnetAddress;
                subnetMask    = address.subnetMask;
                if (IPAddressExtensions.IsInSameSubnet(subnetAddress, isContained, subnetMask))
                {
                    subnetworkAddressWhereIsContained = address;
                }
            }
            return(subnetworkAddressWhereIsContained);
        }
        static EndpointHandlerBase()
        {
            try
            {
                IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses().ForEach((x, y) => NetworkInterfaceIpv4Addresses[x.GetAddressBytes()] = y.GetAddressBytes());

                NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses().ConvertAll(x => x.GetAddressBytes()).ToArray();
            }
            catch (Exception ex)
            {
                Log.Warn("Failed to retrieve IP Addresses, some security restriction features may not work: " + ex.Message, ex,
                         new Dictionary <string, string>()
                {
                    { "ErrorCode", "FXD300062" }
                });
            }
        }
示例#11
0
        public void Send(byte[] data, System.Net.EndPoint ep)
        {
            Server     socket   = _Server;
            IPEndPoint remoteEP = (IPEndPoint)ep;

            if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
            {
                if (_ServerIPv4 != null)
                {
                    // use the separated socket of IPv4 to deal with IPv4 conversions.
                    socket = _ServerIPv4;
                }
                else if (_Server.LocalEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    remoteEP = new IPEndPoint(IPAddressExtensions.MapToIPv6(remoteEP.Address), remoteEP.Port);
                }
            }
            socket.Send(remoteEP, data);
        }
示例#12
0
        private bool ConnectionRequestOut(SNP pathBegin, SNP pathEnd)
        {
            LogClass.WhiteLog("[CC] Sending ConnectionRequestOut between ports: " + pathBegin.Address + " and " + pathEnd.Address);
            //wysyla do cc poziom niżej wiadomosc connection request
            IPAddress subnetworkAddress     = null;
            IPAddress subnetworkAddressMask = null;

            foreach (SubnetworkAddress sub in ContainedSubnetworksAddresses)
            {
                if (IPAddressExtensions.IsInSameSubnet(sub.subnetAddress, IPAddress.Parse(pathBegin.Address), sub.subnetMask))
                {
                    subnetworkAddress     = sub.subnetAddress;
                    subnetworkAddressMask = sub.subnetMask;
                }
            }
            SubnetworkAddress subnetAddress = new SubnetworkAddress(subnetworkAddress.ToString(), subnetworkAddressMask.ToString());

            return(SubnetworkServer.SendConnectionRequest(pathBegin, pathEnd, subnetAddress));
        }
示例#13
0
        public bool DeleteConnectionRequestOut(SNP pathBegin, SNP pathEnd)
        {
            LogClass.Log("[DEBUG] sending delete connection request out between " + pathBegin.Address + " and " + pathEnd.Address);
            //wysyla do cc poziom niżej wiadomosc usuwaj jak szalony konik
            IPAddress subnetworkAddress     = null;
            IPAddress subnetworkAddressMask = null;

            foreach (SubnetworkAddress sub in ContainedSubnetworksAddresses)
            {
                if (IPAddressExtensions.IsInSameSubnet(sub.subnetAddress, IPAddress.Parse(pathBegin.Address), sub.subnetMask))
                {
                    subnetworkAddress     = sub.subnetAddress;
                    subnetworkAddressMask = sub.subnetMask;
                }
            }
            SubnetworkAddress subnetAddress = new SubnetworkAddress(subnetworkAddress.ToString(), subnetworkAddressMask.ToString());

            SubnetworkServer.SendConnectionRequest(pathBegin, pathEnd, subnetAddress);
            return(true);
        }
示例#14
0
        private void EndReceive(UDPSocket socket, byte[] buffer, int offset, int count, System.Net.EndPoint ep)
        {
            if (count > 0)
            {
                byte[] bytes = new byte[count];
                Buffer.BlockCopy(buffer, 0, bytes, 0, count);

                if (ep.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    IPEndPoint ipep = (IPEndPoint)ep;
                    if (IPAddressExtensions.IsIPv4MappedToIPv6(ipep.Address))
                    {
                        ipep.Address = IPAddressExtensions.MapToIPv4(ipep.Address);
                    }
                }

                FireDataReceived(bytes, ep);
            }

            BeginReceive(socket);
        }
示例#15
0
        public bool PeerCoordinationIn(SNP pathBegin, string pathEnd)
        {
            LogClass.Log("[DEBUG] incoming peercoordination from" + pathBegin.Address + " to " + pathEnd);
            string[] existingConnKey     = new string[] { pathBegin.Address, pathEnd };
            string   beginAddressForDict = pathBegin.Address;
            //Lista SNP dla tworzonego aktualnie polaczenia
            List <SNP> SNPList = new List <SNP>();

            //sprawdza, z ktorej domeny przyszedl SNP i podmienia jego adres na adres swojego SNPP brzegowego
            foreach (SubnetworkAddress domainAddress in OtherDomainSNPPAddressTranslation.Keys)
            {
                if (IPAddressExtensions.IsInSameSubnet(IPAddress.Parse(pathBegin.Address), domainAddress.subnetAddress, domainAddress.subnetMask))
                {
                    Tuple <IPAddress, IPAddress> foundTranslation = OtherDomainSNPPAddressTranslation[domainAddress].Find(x => x.Item1.ToString() == pathBegin.Address);
                    IPAddress translatedAddress = foundTranslation.Item2;
                    Console.WriteLine("TRANSALATED FROM" + pathBegin.Address + " TO " + translatedAddress.ToString());
                    pathBegin.Address = translatedAddress.ToString();
                }
            }
            Console.WriteLine("DEFENITELY TRANSALATED TO " + pathBegin.Address);
            //przepustowosc bierzemy z przekazanego SNP

            SNPList.Add(new SNP(pathBegin.Label, pathBegin.Address, pathBegin.OccupiedCapacity, null, null));
            SNPList.Add(new SNP(0, pathEnd, pathBegin.OccupiedCapacity, pathBegin.PathBegin, pathBegin.PathEnd));

            //Zapamietaj SNPlist z polaczeniem mdzy takimi adresami
            existingConnections.Add(existingConnKey, SNPList);

            List <SNPP> SNPPList = RouteTableQuery(pathBegin.Address, pathEnd, pathBegin.OccupiedCapacity);

            for (int index = 0; index < SNPPList.Count; index += 2)
            {
                SNPP             SNPPpathBegin = SNPPList[index];
                SNPP             SNPPpathEnd   = SNPPList[index + 1];
                Tuple <SNP, SNP> SNPpair       = LinkConnectionRequest(SNPPpathBegin, SNPPpathEnd, pathBegin.OccupiedCapacity);
                SNPList.Add(SNPpair.Item1);
                SNPList.Add(SNPpair.Item2);
            }

            //Wysłanie ConnectionRequesta do podsieci, jeżeli na liscie SNP zajdą się 2 adresy brzegowe tej podsieci
            List <SNP> connected = new List <SNP>();

            for (int index = 0; index < SNPList.Count - 1; index++)
            {
                SNP SNPpathBegin = SNPList[index];
                for (int jndex = index + 1; jndex < SNPList.Count; jndex++)
                {
                    SNP SNPpathEnd = SNPList[jndex];

                    if (BelongsToSubnetwork(SNPpathBegin, SNPpathEnd))
                    {
                        LogClass.WhiteLog("[DEBUG] Sending ConnectionRequest between" + SNPpathBegin.Address + SNPpathEnd.Deleting + "and" + SNPpathEnd.Address + SNPpathBegin.Deleting);
                        if (ConnectionRequestOut(SNPpathBegin, SNPpathEnd))
                        {
                            connected.Add(SNPpathBegin);
                            connected.Add(SNPpathEnd);
                            LogClass.Log("Subnetwork Connection set properly.");
                        }
                        else
                        {
                            connected.ForEach(x => x.Deleting = true);
                            for (int i = 0; i < connected.Count; i += 2)
                            {
                                DeleteLinkConnectionRequest(connected.ElementAt(i), connected.ElementAt(i + 1));
                            }

                            for (int i = 0; i < connected.Count; i += 2)
                            {
                                ConnectionRequestOut(connected.ElementAt(i), connected.ElementAt(i + 1));
                                LogClass.WhiteLog("[DEBUG] Sending DeleteConnectionRequest between" + SNPpathBegin.Address + SNPpathEnd.Deleting + "and" + SNPpathEnd.Address + SNPpathBegin.Deleting);
                            }
                            SubnetworkServer.callIgnoreLinkInRC(SNPpathBegin);
                            SubnetworkServer.callIgnoreLinkInRC(SNPpathEnd);

                            LogClass.Log("Epic fail.");
                            return(false);
                        }
                    }
                }
            }

            return(true);  //Jesli polaczenie zestawiono poprawnie
        }
示例#16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });

            // Cache
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = "localhost";
                options.InstanceName  = "Meeting:";
            });
            services.AddMemoryCache();

            // Cors
            var corsSettings = Configuration.GetSection("CorsSettings").Get <CorsSettings>();

            services.AddCors(options => options.AddPolicy("DefaultPolicy",
                                                          builder => builder.WithOrigins(corsSettings.Origins).AllowAnyMethod().AllowAnyHeader().AllowCredentials())
                             );

            // Authentication
            services.AddSingleton <ITokenService, TokenService>();
            var tokenValidationSettings = Configuration.GetSection("TokenValidationSettings").Get <TokenValidationSettings>();

            services.AddSingleton(tokenValidationSettings);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer    = tokenValidationSettings.ValidIssuer,
                    ValidateIssuer = true,

                    ValidAudience    = tokenValidationSettings.ValidAudience,
                    ValidateAudience = true,

                    IssuerSigningKey         = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey),
                    ValidateIssuerSigningKey = true,

                    ValidateLifetime = tokenValidationSettings.ValidateLifetime,
                    ClockSkew        = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds),
                };

                // We have to hook the OnMessageReceived event in order to
                // allow the JWT authentication handler to read the access
                // token from the query string when a WebSocket or
                // Server-Sent Events request comes in.
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        //_logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}");
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    },
                    OnChallenge = async context =>
                    {
                        //_logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}");
                        var body = Encoding.UTF8.GetBytes("{\"code\": 400, \"message\": \"Authentication Challenge\"}");
                        context.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                        context.Response.ContentType = "application/json";
                        await context.Response.Body.WriteAsync(body, 0, body.Length);
                        context.HandleResponse();
                    }
                };
            });

            // SignalR
            services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            })
            .AddJsonProtocol(options => {
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
                options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });
            services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider)));

            // Consul
            var consulSettings = Configuration.GetSection("ConsulSettings").Get <ConsulSettings>();

            services.AddSingleton(consulSettings);

            // Mediasoup
            var mediasoupStartupSettings = Configuration.GetSection("MediasoupStartupSettings").Get <MediasoupStartupSettings>();
            var mediasoupSettings        = Configuration.GetSection("MediasoupSettings").Get <MediasoupSettings>();
            var workerSettings           = mediasoupSettings.WorkerSettings;
            var routerSettings           = mediasoupSettings.RouterSettings;
            var webRtcTransportSettings  = mediasoupSettings.WebRtcTransportSettings;
            var plainTransportSettings   = mediasoupSettings.PlainTransportSettings;
            var meetingServerSettings    = Configuration.GetSection("MeetingServerSettings").Get <MeetingServerSettings>();

            services.AddMediasoup(options =>
            {
                // MediasoupStartupSettings
                if (mediasoupStartupSettings != null)
                {
                    options.MediasoupStartupSettings.MediasoupVersion = mediasoupStartupSettings.MediasoupVersion;
                    options.MediasoupStartupSettings.WorkerPath       = mediasoupStartupSettings.WorkerPath;
                    options.MediasoupStartupSettings.NumberOfWorkers  = !mediasoupStartupSettings.NumberOfWorkers.HasValue || mediasoupStartupSettings.NumberOfWorkers <= 0 ? Environment.ProcessorCount : mediasoupStartupSettings.NumberOfWorkers;
                }

                // WorkerSettings
                if (workerSettings != null)
                {
                    options.MediasoupSettings.WorkerSettings.LogLevel            = workerSettings.LogLevel;
                    options.MediasoupSettings.WorkerSettings.LogTags             = workerSettings.LogTags;
                    options.MediasoupSettings.WorkerSettings.RtcMinPort          = workerSettings.RtcMinPort;
                    options.MediasoupSettings.WorkerSettings.RtcMaxPort          = workerSettings.RtcMaxPort;
                    options.MediasoupSettings.WorkerSettings.DtlsCertificateFile = workerSettings.DtlsCertificateFile;
                    options.MediasoupSettings.WorkerSettings.DtlsPrivateKeyFile  = workerSettings.DtlsPrivateKeyFile;
                }

                // RouteSettings
                if (routerSettings != null && !routerSettings.RtpCodecCapabilities.IsNullOrEmpty())
                {
                    options.MediasoupSettings.RouterSettings = routerSettings;

                    // Fix RtpCodecCapabilities[x].Parameters 。从配置文件反序列化时将数字转换成了字符串,这里进行修正。
                    foreach (var codec in routerSettings.RtpCodecCapabilities.Where(m => m.Parameters != null))
                    {
                        foreach (var key in codec.Parameters.Keys.ToArray())
                        {
                            var value = codec.Parameters[key];
                            if (value != null && Int32.TryParse(value.ToString(), out var intValue))
                            {
                                codec.Parameters[key] = intValue;
                            }
                        }
                    }
                }

                // WebRtcTransportSettings
                if (webRtcTransportSettings != null)
                {
                    options.MediasoupSettings.WebRtcTransportSettings.ListenIps = webRtcTransportSettings.ListenIps;
                    options.MediasoupSettings.WebRtcTransportSettings.InitialAvailableOutgoingBitrate = webRtcTransportSettings.InitialAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MinimumAvailableOutgoingBitrate = webRtcTransportSettings.MinimumAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MaxSctpMessageSize = webRtcTransportSettings.MaxSctpMessageSize;

                    // 如果没有设置 ListenIps 则获取本机所有的 IPv4 地址进行设置。
                    var listenIps = options.MediasoupSettings.WebRtcTransportSettings.ListenIps;
                    if (listenIps.IsNullOrEmpty())
                    {
                        var localIPv4IPAddresses = IPAddressExtensions.GetLocalIPAddresses(AddressFamily.InterNetwork).Where(m => m != IPAddress.Loopback);
                        if (EnumerableExtensions.IsNullOrEmpty(localIPv4IPAddresses))
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        listenIps = (from ip in localIPv4IPAddresses
                                     let ipString = ip.ToString()
                                                    select new TransportListenIp
                        {
                            Ip = ipString,
                            AnnouncedIp = ipString
                        }).ToArray();
                        options.MediasoupSettings.WebRtcTransportSettings.ListenIps = listenIps;
                    }
                    else
                    {
                        var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                        if (localIPv4IPAddress == null)
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        foreach (var listenIp in listenIps)
                        {
                            if (listenIp.AnnouncedIp.IsNullOrWhiteSpace())
                            {
                                // 如果没有设置 AnnouncedIp:
                                // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                                listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                            }
                        }
                    }
                }

                // PlainTransportSettings
                if (plainTransportSettings != null)
                {
                    options.MediasoupSettings.PlainTransportSettings.ListenIp           = plainTransportSettings.ListenIp;
                    options.MediasoupSettings.PlainTransportSettings.MaxSctpMessageSize = plainTransportSettings.MaxSctpMessageSize;

                    var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                    if (localIPv4IPAddress == null)
                    {
                        throw new ArgumentException("无法获取本机 IPv4 配置 PlainTransport。");
                    }

                    var listenIp = options.MediasoupSettings.PlainTransportSettings.ListenIp;
                    if (listenIp == null)
                    {
                        listenIp = new TransportListenIp
                        {
                            Ip          = localIPv4IPAddress.ToString(),
                            AnnouncedIp = localIPv4IPAddress.ToString(),
                        };
                        options.MediasoupSettings.PlainTransportSettings.ListenIp = listenIp;
                    }
                    else if (listenIp.AnnouncedIp.IsNullOrWhiteSpace())
                    {
                        // 如果没有设置 AnnouncedIp:
                        // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                        listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                    }
                }
            });

            // Meeting server
            services.AddMeetingServer(options =>
            {
                options.ServeMode = meetingServerSettings.ServeMode;
            });

            // Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title   = "Meeting API",
                    Version = "v1"
                });
            });
        }
        protected void Initialize(IPEndPoint serverEndpoint)
        {
            m_groupId = MySandboxGame.ConfigDedicated.GroupID;

            ServerStarted = false;

            HostName = "Dedicated server";

            SyncLayer.RegisterMessageImmediate <ConnectedClientDataMsg>(this.OnConnectedClient, MyMessagePermissions.ToServer | MyMessagePermissions.FromServer);
            SyncLayer.RegisterMessageImmediate <AllMembersDataMsg>(OnAllMembersData, MyMessagePermissions.ToServer | MyMessagePermissions.FromServer);

            m_membersCollection = new MemberCollection(m_members);
            SetMemberLimit(MaxPlayers);

            SteamSDK.Peer2Peer.SessionRequest   += Peer2Peer_SessionRequest;
            SteamSDK.Peer2Peer.ConnectionFailed += Peer2Peer_ConnectionFailed;
            ClientLeft += MyDedicatedServer_ClientLeft;

            SteamSDK.SteamServerAPI.Instance.GameServer.ServersConnected           += GameServer_ServersConnected;
            SteamSDK.SteamServerAPI.Instance.GameServer.ServersConnectFailure      += GameServer_ServersConnectFailure;
            SteamSDK.SteamServerAPI.Instance.GameServer.ServersDisconnected        += GameServer_ServersDisconnected;
            SteamSDK.SteamServerAPI.Instance.GameServer.PolicyResponse             += GameServer_PolicyResponse;
            SteamSDK.SteamServerAPI.Instance.GameServer.ValidateAuthTicketResponse += GameServer_ValidateAuthTicketResponse;
            SteamSDK.SteamServerAPI.Instance.GameServer.UserGroupStatus            += GameServer_UserGroupStatus;

            ServerStartResult startResult = SteamSDK.SteamServerAPI.Instance.GameServer.Start(
                serverEndpoint,
                (ushort)MySandboxGame.ConfigDedicated.SteamPort,
                SteamSDK.ServerMode.eServerModeAuthenticationAndSecure,
                MyFinalBuildConstants.APP_VERSION.ToString(),
                MyFakes.DEDICATED_SERVER_USE_SOCKET_SHARE);

            switch (startResult)
            {
            case ServerStartResult.PortAlreadyUsed:
                ServerInitError = "Error starting Steam dedicated server: Server port " + (ushort)MySandboxGame.ConfigDedicated.ServerPort + " already in use";
                MyLog.Default.WriteLineAndConsole(ServerInitError);
                break;

            case ServerStartResult.UnknownError:
                ServerInitError = "Error starting Steam dedicated server";
                MyLog.Default.WriteLineAndConsole(ServerInitError);
                break;
            }

            if (startResult != ServerStartResult.OK)
            {
                return;
            }

            // This has to be exact name of app like this to show in Server Browser
            SteamSDK.SteamServerAPI.Instance.GameServer.SetModDir(MyPerGameSettings.SteamGameServerGameDir);

            SteamSDK.SteamServerAPI.Instance.GameServer.ProductName     = MyPerGameSettings.SteamGameServerProductName;
            SteamSDK.SteamServerAPI.Instance.GameServer.GameDescription = MyPerGameSettings.SteamGameServerDescription;
            SteamSDK.SteamServerAPI.Instance.GameServer.SetDedicated(true);

            string serverName = MySandboxGame.ConfigDedicated.ServerName;

            if (String.IsNullOrWhiteSpace(serverName))
            {
                serverName = "Unnamed server";
            }

            SteamSDK.SteamServerAPI.Instance.GameServer.SetServerName(serverName);
            SteamSDK.SteamServerAPI.Instance.GameServer.LogOnAnonymous();


            SteamSDK.SteamServerAPI.Instance.GameServer.EnableHeartbeats(true);

            if (m_groupId != 0 && SteamServerAPI.Instance.GetAccountType(m_groupId) != AccountType.Clan)
            {
                MyLog.Default.WriteLineAndConsole("Specified group ID is invalid: " + m_groupId);
            }

            UInt32 ip = 0;
            UInt64 id = 0;

            int timeout = 100;

            while (ip == 0 && timeout > 0)
            {
                SteamSDK.SteamServerAPI.Instance.GameServer.RunCallbacks();

                Thread.Sleep(100);
                timeout--;

                ip = SteamSDK.SteamServerAPI.Instance.GameServer.GetPublicIP();
                id = SteamSDK.SteamServerAPI.Instance.GameServer.GetSteamID();
            }

            MySandboxGame.Services.SteamService.UserId = id;

            if (ip == 0)
            {
                MyLog.Default.WriteLineAndConsole("Error: No IP assigned.");
                return;
            }

            var ipAddress = IPAddressExtensions.FromIPv4NetworkOrder(ip);

            ServerId = MySteam.Server.GetSteamID();
            m_members.Add(ServerId);
            m_memberData.Add(ServerId, new MyConnectedClientData()
            {
                Name = "Server", IsAdmin = true
            });

            SyncLayer.RegisterClientEvents(this);

            MyLog.Default.WriteLineAndConsole("Server successfully started");
            MyLog.Default.WriteLineAndConsole("Product name: " + SteamSDK.SteamServerAPI.Instance.GameServer.ProductName);
            MyLog.Default.WriteLineAndConsole("Desc: " + SteamSDK.SteamServerAPI.Instance.GameServer.GameDescription);
            MyLog.Default.WriteLineAndConsole("Public IP: " + ipAddress.ToString());
            MyLog.Default.WriteLineAndConsole("Steam ID: " + id.ToString());

            ServerStarted = true;
        }
        //Todo, cleanup and allow existing Rtp and Rtcp socket.

        /// <summary>
        /// Will create a <see cref="RtpClient"/> based on the given parameters
        /// </summary>
        /// <param name="sessionDescription"></param>
        /// <param name="sharedMemory"></param>
        /// <param name="incomingEvents"></param>
        /// <param name="rtcpEnabled"></param>
        /// <returns></returns>
        public static RtpClient FromSessionDescription(Sdp.SessionDescription sessionDescription, Common.MemorySegment sharedMemory = null, bool incomingEvents = true, bool rtcpEnabled = true, System.Net.Sockets.Socket existingSocket = null, int?rtpPort = null, int?rtcpPort = null, int remoteSsrc = 0, int minimumSequentialRtpPackets = 2, bool connect = true, System.Action <System.Net.Sockets.Socket> configure = null)
        {
            if (Common.IDisposedExtensions.IsNullOrDisposed(sessionDescription))
            {
                throw new System.ArgumentNullException("sessionDescription");
            }

            Sdp.Lines.SessionConnectionLine connectionLine = new Sdp.Lines.SessionConnectionLine(sessionDescription.ConnectionLine);

            System.Net.IPAddress remoteIp = System.Net.IPAddress.Parse(connectionLine.Host), localIp;

            System.Net.NetworkInformation.NetworkInterface localInterface;

            //If the socket is NOT null and IS BOUND use the localIp of the same address family
            if (object.ReferenceEquals(existingSocket, null).Equals(false) && existingSocket.IsBound)
            {
                //If the socket is IP based
                if (existingSocket.LocalEndPoint is System.Net.IPEndPoint)
                {
                    //Take the localIp from the LocalEndPoint
                    localIp = (existingSocket.LocalEndPoint as System.Net.IPEndPoint).Address;
                }
                else
                {
                    throw new System.NotSupportedException("Please create an issue for your use case.");
                }
            }
            else // There is no socket existing.
            {
                //If the remote address is the broadcast address or the remote address is multicast
                if (System.Net.IPAddress.Broadcast.Equals(remoteIp) || IPAddressExtensions.IsMulticast(remoteIp))
                {
                    //This interface should be the interface you plan on using for the Rtp communication
                    localIp = SocketExtensions.GetFirstMulticastIPAddress(remoteIp.AddressFamily, out localInterface);
                }
                else
                {
                    //This interface should be the interface you plan on using for the Rtp communication
                    localIp = SocketExtensions.GetFirstUnicastIPAddress(remoteIp.AddressFamily, out localInterface);
                }
            }

            RtpClient client = new RtpClient(sharedMemory, incomingEvents);

            byte lastChannel = 0;

            //Todo, check for session level ssrc
            //if (remoteSsrc.Equals(0))
            //{
            //    //Sdp.SessionDescriptionLine ssrcLine = sessionDescription.SsrcGroupLine; // SsrcLine @ the session level could imply Group
            //}

            //For each MediaDescription in the SessionDescription
            foreach (Media.Sdp.MediaDescription md in sessionDescription.MediaDescriptions)
            {
                //Make a RtpClient.TransportContext from the MediaDescription being parsed.
                TransportContext tc = TransportContext.FromMediaDescription(sessionDescription, lastChannel++, lastChannel++, md,
                                                                            rtcpEnabled, remoteSsrc, minimumSequentialRtpPackets,
                                                                            localIp, remoteIp, //The localIp and remoteIp
                                                                            rtpPort, rtcpPort, //The remote ports to receive data from
                                                                            connect, existingSocket, configure);

                //Try to add the context
                try
                {
                    client.AddContext(tc);
                }
                catch (System.Exception ex)
                {
                    TaggedExceptionExtensions.RaiseTaggedException(tc, "See Tag, Could not add the created TransportContext.", ex);
                }
            }

            //Return the participant
            return(client);
        }
 /// <summary>
 /// Create a new TCP server instance bound to the first found IP address for the local host
 /// </summary>
 /// <param name="BufferType">Instance to indicate the buffer type</param>
 /// <param name="Port">Port to use for server, default: 23 (Telnet)</param>
 /// <param name="Protocol">Protocol to use for the server, default: TCP (RFC793)</param>
 public BufferedInternetServer(T BufferType, UInt16 Port = (UInt16)DefaultPorts.Telnet, RFCProtocol Protocol = RFCProtocol.TCP) : base()
 {
     PacketType = BufferType;
     InitBuffer();
     CreateServer(IPAddressExtensions.LocalIPAddress(), Port, Protocol);
 }
 /// <summary>
 /// Create a new server instance bound to the first found IP address for the local host
 /// </summary>
 /// <param name="Port">Port to use for server, default: 23 (Telnet)</param>
 /// <param name="Protocol">Protocol to use for the server, default: Telnet (RFC854)</param>
 public LineBasedTCPServer(UInt16 Port = (UInt16)DefaultPorts.Telnet, RFCProtocol Protocol = RFCProtocol.Telnet) : base(IPAddressExtensions.LocalIPAddress(), Port, Protocol)
 {
 }
示例#21
0
        //  Main method
        static void Main(string[] args)
        {
            if (args.Contains("-report"))
            {
                MyErrorReporter.Report(args[1], args[2], "SE", MyErrorReporter.APP_ERROR_MESSAGE);
                return;
            }

            if (MyFakes.ENABLE_CONNECT_COMMAND_LINE && args.Contains("+connect"))
            {
                int index = args.ToList().IndexOf("+connect");
                if ((index + 1) < args.Length)
                {
                    if (IPAddressExtensions.TryParseEndpoint(args[index + 1], out MySandboxGame.ConnectToServer))
                    {
                        Console.WriteLine("Space engineers " + MyFinalBuildConstants.APP_VERSION_STRING);
                        Console.WriteLine("Obfuscated: " + MyObfuscation.Enabled + ", Platform: " + (Environment.Is64BitProcess ? " 64-bit" : " 32-bit"));
                        Console.WriteLine("Connecting to: " + args[index + 1]);
                    }
                }
            }

            MySingleProgramInstance spi = new MySingleProgramInstance(MyFileSystem.MainAssemblyName);

            if (spi.IsSingleInstance == false)
            {
                MyErrorReporter.ReportAppAlreadyRunning("Space Engineers");
                return;
            }

            MyInitializer.InvokeBeforeRun(
                AppId,
                "SpaceEngineers",
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

            MyInitializer.InitCheckSum();

            if (!args.Contains("-nosplash"))
            {
                InitSplashScreen();
            }

            // This won't crash with BadFormatExpection when 64-bit game started as 32-bit process, it will show message
            // Will uncomment when it's possible to test it
            if (!Environment.Is64BitProcess && AssemblyExtensions.TryGetArchitecture("SteamSDK.dll") == ProcessorArchitecture.Amd64)
            {
                string text = "Space Engineers cannot be started in 64-bit mode, ";
                text += "because 64-bit version of .NET framework is not available or is broken." + Environment.NewLine + Environment.NewLine;
                text += "Do you want to open website with more information about this particular issue?" + Environment.NewLine + Environment.NewLine;
                text += "Press Yes to open website with info" + Environment.NewLine;
                text += "Press No to run in 32-bit mode (smaller potential of Space Engineers!)" + Environment.NewLine;
                text += "Press Cancel to close this dialog";

                var result = Sandbox.MyMessageBox.Show(IntPtr.Zero, text, ".NET Framework 64-bit error", Sandbox.MessageBoxOptions.YesNoCancel);
                if (result == MessageBoxResult.Yes)
                {
                    MyBrowserHelper.OpenInternetBrowser("http://www.spaceengineersgame.com/64-bit-start-up-issue.html");
                }
                else if (result == MessageBoxResult.No)
                {
                    var    entry  = Assembly.GetEntryAssembly().Location;
                    string x86Exe = Path.Combine(new FileInfo(entry).Directory.Parent.FullName, "Bin", Path.GetFileName(entry));

                    ProcessStartInfo pi = new ProcessStartInfo();
                    pi.FileName         = x86Exe;
                    pi.WorkingDirectory = Path.GetDirectoryName(x86Exe);
                    pi.Arguments        = "-fallback";
                    pi.UseShellExecute  = false;
                    pi.WindowStyle      = ProcessWindowStyle.Normal;
                    var p = Process.Start(pi);
                }
                return;
            }


            if (MyFakes.DETECT_LEAKS)
            {
                //Slow down
                SharpDX.Configuration.EnableObjectTracking = true;
                //SharpDX.Diagnostics.ObjectTracker.OnObjectCreated += new SharpDX.Diagnostics.ObjectTracker.ComObjectDelegate(OnResourceCreated);
                //SharpDX.Diagnostics.ObjectTracker.OnObjectReleased += new SharpDX.Diagnostics.ObjectTracker.ComObjectDelegate(OnResourceDestroyed);
                //SharpDX.Diagnostics.ObjectTracker.OnObjectTrack += new SharpDX.Diagnostics.ObjectTracker.ComObjectDelegate(OnObjectTrack);
                //SharpDX.Diagnostics.ObjectTracker.OnObjectUnTrack += new SharpDX.Diagnostics.ObjectTracker.ComObjectDelegate(OnObjectUnTrack);
            }

            RunInternal(args);

            if (MyFakes.DETECT_LEAKS)
            {
                var o = SharpDX.Diagnostics.ObjectTracker.FindActiveObjects();
                System.Diagnostics.Debug.Assert(o.Count == 0, "Unreleased DX objects!");
                Console.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
            }

#if PROFILING
            MyPerformanceTimer.WriteToLog();
#endif
            MyInitializer.InvokeAfterRun();
        }
示例#22
0
 private void ReloadIPAddresses()
 {
     cmbIPAddress.Items.Clear();
     cmbIPAddress.Items.AddRange(IPAddressExtensions.LocalIPAddresses().ToArray());
 }
示例#23
0
 public static bool IsMulticast(this System.Net.IPEndPoint endPoint)
 {
     return(IPAddressExtensions.IsMulticast(endPoint.Address));
 }
示例#24
0
        protected void Initialize(IPEndPoint serverEndpoint)
        {
            this.m_groupId     = MySandboxGame.ConfigDedicated.GroupID;
            this.ServerStarted = false;
            this.HostName      = "Dedicated server";
            this.SetMemberLimit(this.MaxPlayers);
            MyGameService.Peer2Peer.SessionRequest   += new Action <ulong>(this.Peer2Peer_SessionRequest);
            MyGameService.Peer2Peer.ConnectionFailed += new Action <ulong, string>(this.Peer2Peer_ConnectionFailed);
            base.ClientLeft += new Action <ulong, MyChatMemberStateChangeEnum>(this.MyDedicatedServer_ClientLeft);
            MyGameService.GameServer.PlatformConnected          += new Action(this.GameServer_ServersConnected);
            MyGameService.GameServer.PlatformConnectionFailed   += new Action <string>(this.GameServer_ServersConnectFailure);
            MyGameService.GameServer.PlatformDisconnected       += new Action <string>(this.GameServer_ServersDisconnected);
            MyGameService.GameServer.PolicyResponse             += new Action <sbyte>(this.GameServer_PolicyResponse);
            MyGameService.GameServer.ValidateAuthTicketResponse += new Action <ulong, JoinResult, ulong>(this.GameServer_ValidateAuthTicketResponse);
            MyGameService.GameServer.UserGroupStatusResponse    += new Action <ulong, ulong, bool, bool>(this.GameServer_UserGroupStatus);
            string serverName = MySandboxGame.ConfigDedicated.ServerName;

            if (string.IsNullOrWhiteSpace(serverName))
            {
                serverName = "Unnamed server";
            }
            MyGameService.GameServer.SetServerName(serverName);
            MyGameService.Peer2Peer.SetServer(true);
            if (MyGameService.GameServer.Start(serverEndpoint, (ushort)MySandboxGame.ConfigDedicated.SteamPort, MyFinalBuildConstants.APP_VERSION.ToString()))
            {
                MyGameService.GameServer.SetModDir(MyPerGameSettings.SteamGameServerGameDir);
                MyGameService.GameServer.ProductName     = MyPerGameSettings.SteamGameServerProductName;
                MyGameService.GameServer.GameDescription = MyPerGameSettings.SteamGameServerDescription;
                MyGameService.GameServer.SetDedicated(true);
                if (!string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.ServerPasswordHash) && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.ServerPasswordSalt))
                {
                    MyGameService.GameServer.SetPasswordProtected(true);
                    this.IsPasswordProtected = true;
                }
                MyGameService.GameServer.LogOnAnonymous();
                MyGameService.GameServer.EnableHeartbeats(true);
                if ((this.m_groupId != 0) && (MyGameService.GetServerAccountType(this.m_groupId) != MyGameServiceAccountType.Clan))
                {
                    MyLog.Default.WriteLineAndConsole("Specified group ID is invalid: " + this.m_groupId);
                }
                uint  ip       = 0;
                ulong serverId = 0UL;
                int   num3     = 100;
                while ((ip == 0) && (num3 > 0))
                {
                    MyGameService.GameServer.Update();
                    Thread.Sleep(100);
                    num3--;
                    ip       = MyGameService.GameServer.GetPublicIP();
                    serverId = MyGameService.GameServer.ServerId;
                }
                MyGameService.UserId = serverId;
                if (ip == 0)
                {
                    MyLog.Default.WriteLineAndConsole("Error: No IP assigned.");
                }
                else
                {
                    IPAddress address = IPAddressExtensions.FromIPv4NetworkOrder(ip);
                    base.ServerId = MyGameService.GameServer.ServerId;
                    base.ReplicationLayer.SetLocalEndpoint(new EndpointId(MyGameService.GameServer.ServerId));
                    this.m_members.Add(base.ServerId);
                    MyMultiplayerBase.MyConnectedClientData data = new MyMultiplayerBase.MyConnectedClientData {
                        Name    = MyTexts.GetString(MySpaceTexts.ChatBotName),
                        IsAdmin = true
                    };
                    this.MemberDataAdd(base.ServerId, data);
                    base.SyncLayer.RegisterClientEvents(this);
                    MyLog.Default.WriteLineAndConsole("Server successfully started");
                    MyLog.Default.WriteLineAndConsole("Product name: " + MyGameService.GameServer.ProductName);
                    MyLog.Default.WriteLineAndConsole("Desc: " + MyGameService.GameServer.GameDescription);
                    MyLog.Default.WriteLineAndConsole("Public IP: " + address.ToString());
                    MyLog.Default.WriteLineAndConsole("Steam ID: " + serverId.ToString());
                    this.ServerStarted = true;
                }
            }
        }
        /// <summary>
        /// Validates ActivityInformation structure by itself. This function does not touch database and does not validate
        /// anything that depends on the context.
        /// </summary>
        /// <param name="Activity">Description of the activity to validate.</param>
        /// <param name="OwnerIdentityPublicKey">Public key of the activity's owner identity.</param>
        /// <param name="MessageBuilder">Network message builder of the client who sent this activity description.</param>
        /// <param name="RequestMessage">Full request message from client.</param>
        /// <param name="ErrorPrefix">Prefix to add to the validation error details.</param>
        /// <param name="ErrorResponse">If the function fails, this is filled with error response message that is ready to be sent to the client.</param>
        /// <returns>true if the activity information is valid, false otherwise.</returns>
        public static bool ValidateActivityInformation(ActivityInformation Activity, byte[] OwnerIdentityPublicKey, ProxMessageBuilder MessageBuilder, ProxProtocolMessage RequestMessage, string ErrorPrefix, out ProxProtocolMessage ErrorResponse)
        {
            log.Trace("()");

            bool res = false;

            ErrorResponse = null;
            string details = null;

            if (Activity == null)
            {
                Activity = new ActivityInformation();
            }
            if (Activity.ProfileServerContact == null)
            {
                Activity.ProfileServerContact = new ServerContactInfo();
            }

            SemVer version = new SemVer(Activity.Version);

            // Currently only supported version is 1.0.0.
            if (!version.Equals(SemVer.V100))
            {
                log.Debug("Unsupported version '{0}'.", version);
                details = "version";
            }


            if (details == null)
            {
                uint activityId = Activity.Id;

                // 0 is not a valid activity identifier.
                if (activityId == 0)
                {
                    log.Debug("Invalid activity ID '{0}'.", activityId);
                    details = "id";
                }
            }

            if (details == null)
            {
                byte[] pubKey      = Activity.OwnerPublicKey.ToByteArray();
                bool   pubKeyValid = (0 < pubKey.Length) && (pubKey.Length <= ProtocolHelper.MaxPublicKeyLengthBytes) && ByteArrayComparer.Equals(OwnerIdentityPublicKey, pubKey);
                if (!pubKeyValid)
                {
                    log.Debug("Invalid public key '{0}' does not match identity public key '{1}'.", pubKey.ToHex(), OwnerIdentityPublicKey.ToHex());
                    details = "ownerPublicKey";
                }
            }


            if (details == null)
            {
                ServerContactInfo sci    = Activity.ProfileServerContact;
                bool      networkIdValid = sci.NetworkId.Length == ProtocolHelper.NetworkIdentifierLength;
                IPAddress ipAddress      = IPAddressExtensions.IpFromBytes(sci.IpAddress.ToByteArray());
                bool      ipAddressValid = (ipAddress != null) && (Config.Configuration.TestModeEnabled || !ipAddress.IsReservedOrLocal());
                bool      portValid      = (1 <= sci.PrimaryPort) && (sci.PrimaryPort <= 65535);

                if (!networkIdValid || !ipAddressValid || !portValid)
                {
                    log.Debug("Profile server contact's network ID is {0}, IP address is {1}, port is {2}.", networkIdValid ? "valid" : "invalid", ipAddressValid ? "valid" : "invalid", portValid ? "valid" : "invalid");

                    if (!networkIdValid)
                    {
                        details = "profileServerContact.networkId";
                    }
                    else if (!ipAddressValid)
                    {
                        details = "profileServerContact.ipAddress";
                    }
                    else if (!portValid)
                    {
                        details = "profileServerContact.primaryPort";
                    }
                }
            }

            if (details == null)
            {
                string activityType = Activity.Type;
                if (activityType == null)
                {
                    activityType = "";
                }

                int  byteLen           = Encoding.UTF8.GetByteCount(activityType);
                bool activityTypeValid = (0 < byteLen) && (byteLen <= ProxMessageBuilder.MaxActivityTypeLengthBytes);
                if (!activityTypeValid)
                {
                    log.Debug("Activity type too long or zero length ({0} bytes, limit is {1}).", byteLen, ProxMessageBuilder.MaxActivityTypeLengthBytes);
                    details = "type";
                }
            }

            if (details == null)
            {
                GpsLocation locLat  = new GpsLocation(Activity.Latitude, 0);
                GpsLocation locLong = new GpsLocation(0, Activity.Longitude);
                if (!locLat.IsValid())
                {
                    log.Debug("Latitude '{0}' is not a valid GPS latitude value.", Activity.Latitude);
                    details = "latitude";
                }
                else if (!locLong.IsValid())
                {
                    log.Debug("Longitude '{0}' is not a valid GPS longitude value.", Activity.Longitude);
                    details = "longitude";
                }
            }

            if (details == null)
            {
                uint precision      = Activity.Precision;
                bool precisionValid = (0 <= precision) && (precision <= ProxMessageBuilder.MaxLocationPrecision);
                if (!precisionValid)
                {
                    log.Debug("Precision '{0}' is not an integer between 0 and {1}.", precision, ProxMessageBuilder.MaxLocationPrecision);
                    details = "precision";
                }
            }


            if (details == null)
            {
                DateTime?startTime      = ProtocolHelper.UnixTimestampMsToDateTime(Activity.StartTime);
                DateTime?expirationTime = ProtocolHelper.UnixTimestampMsToDateTime(Activity.ExpirationTime);

                if (startTime == null)
                {
                    log.Debug("Invalid activity start time timestamp '{0}'.", Activity.StartTime);
                    details = "startTime";
                }
                else if (expirationTime == null)
                {
                    log.Debug("Invalid activity expiration time timestamp '{0}'.", Activity.ExpirationTime);
                    details = "expirationTime";
                }
                else
                {
                    if (startTime > expirationTime)
                    {
                        log.Debug("Activity expiration time has to be greater than or equal to its start time.");
                        details = "expirationTime";
                    }
                    else if (expirationTime.Value > DateTime.UtcNow.AddHours(ActivityBase.MaxActivityLifeTimeHours))
                    {
                        log.Debug("Activity expiration time {0} is more than {1} hours in the future.", expirationTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), ActivityBase.MaxActivityLifeTimeHours);
                        details = "expirationTime";
                    }
                }
            }

            if (details == null)
            {
                string extraData = Activity.ExtraData;
                if (extraData == null)
                {
                    extraData = "";
                }


                // Extra data is semicolon separated 'key=value' list, max ActivityBase.MaxActivityExtraDataLengthBytes bytes long.
                int byteLen = Encoding.UTF8.GetByteCount(extraData);
                if (byteLen > ProxMessageBuilder.MaxActivityExtraDataLengthBytes)
                {
                    log.Debug("Extra data too large ({0} bytes, limit is {1}).", byteLen, ProxMessageBuilder.MaxActivityExtraDataLengthBytes);
                    details = "extraData";
                }
            }

            if (details == null)
            {
                res = true;
            }
            else
            {
                ErrorResponse = MessageBuilder.CreateErrorInvalidValueResponse(RequestMessage, ErrorPrefix + details);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
示例#26
0
        public bool DeleteConnection(string pathBegin, string pathEnd)
        {
            List <SNP> SNPList = null;

            LogClass.Log("[DEBUG] deleting connection between" + pathBegin + " to " + pathEnd);
            //new string[] { pathBegin, pathEnd }
            foreach (string[] key in existingConnections.Keys)
            {
                if ((key[0] == pathBegin && key[1] == pathEnd) || (key[1] == pathBegin && key[0] == pathEnd))
                {
                    SNPList = existingConnections[key];
                }
            }

            //w kazdym SNP ustaw "deleting" na true
            SNPList.ForEach(x => x.Deleting = true);

            string PathEndAddressFromDifferentDomain = null;

            //usuniecie alokacji w LRM
            for (int index = 0; index < SNPList.Count; index += 2)
            {
                SNP SNPpathBegin = SNPList[index];
                SNP SNPpathEnd   = SNPList[index + 1];
                DeleteLinkConnectionRequest(SNPpathBegin, SNPpathEnd);
            }

            //Wysłanie DeleteConnectionRequesta do podsieci, jeżeli na liscie SNP znajdą się 2 adresy brzegowe tej podsieci

            for (int index = 0; index < SNPList.Count - 1; index++)
            {
                SNP SNPpathBegin = SNPList[index];
                for (int jndex = index + 1; jndex < SNPList.Count; jndex++)
                {
                    SNP SNPpathEnd = SNPList[jndex];
                    if (BelongsToSubnetwork(SNPpathBegin, SNPpathEnd))
                    {
                        if (ConnectionRequestOut(SNPpathBegin, SNPpathEnd))
                        {
                            LogClass.Log("Deleting " + SNPpathBegin.Address + " - " + SNPpathEnd.Address + " successful.");
                        }
                        else
                        {
                            LogClass.Log("Epic fail xD");
                            return(false);
                        }
                    }
                }
            }

            //sprawdzamy, czy adres koncowy jest w naszej domenie
            if (!IPAddressExtensions.IsInSameSubnet(IPAddress.Parse(pathEnd), IPAddress.Parse(SubnetworkAddress), IPAddress.Parse(SubnetworkMask)))
            {
                PathEndAddressFromDifferentDomain = pathEnd;

                //TODO: sprawdz, czy ktorys z SNP ma adres SNPP brzegowego tej domeny
                SNP lastSNPinThisDomain = null;
                foreach (SNP snp in SNPList)
                {
                    foreach (List <Tuple <IPAddress, IPAddress> > list in OtherDomainSNPPAddressTranslation.Values)
                    {
                        foreach (Tuple <IPAddress, IPAddress> tuple in list)
                        {
                            if (tuple.Item1.ToString() == snp.Address)
                            {
                                lastSNPinThisDomain = snp;
                            }
                        }
                    }
                }

                if (DeletePeerCoordinationOut(lastSNPinThisDomain, PathEndAddressFromDifferentDomain))
                {
                    LogClass.Log("DeletePeerCoordination OK.");
                }
                else
                {
                    LogClass.Log("PeerCoordination FAIL.");
                };
            }
            return(true);  //Jesli polaczenie zestawiono poprawnie
        }
        static EndpointHandlerBase()
        {
            IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses().ForEach((x, y) => NetworkInterfaceIpv4Addresses[x.GetAddressBytes()] = y.GetAddressBytes());

            NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses().ConvertAll(x => x.GetAddressBytes()).ToArray();
        }
示例#28
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // Tubumu.Meeting.Server 不是 AbpModule,故手工注册。
            context.Services.AddTransient <MeetingHub>();

            var configuration = BuildConfiguration();

            // Mediasoup
            var mediasoupStartupSettings = configuration.GetSection("MediasoupStartupSettings").Get <MediasoupStartupSettings>();
            var mediasoupSettings        = configuration.GetSection("MediasoupSettings").Get <MediasoupSettings>();
            var workerSettings           = mediasoupSettings.WorkerSettings;
            var routerSettings           = mediasoupSettings.RouterSettings;
            var webRtcTransportSettings  = mediasoupSettings.WebRtcTransportSettings;
            var plainTransportSettings   = mediasoupSettings.PlainTransportSettings;

            context.Services.AddMediasoup(options =>
            {
                // MediasoupStartupSettings
                if (mediasoupStartupSettings != null)
                {
                    options.MediasoupStartupSettings.MediasoupVersion = mediasoupStartupSettings.MediasoupVersion;
                    options.MediasoupStartupSettings.WorkerPath       = mediasoupStartupSettings.WorkerPath;
                    options.MediasoupStartupSettings.NumberOfWorkers  = !mediasoupStartupSettings.NumberOfWorkers.HasValue || mediasoupStartupSettings.NumberOfWorkers <= 0 ? Environment.ProcessorCount : mediasoupStartupSettings.NumberOfWorkers;
                }

                // WorkerSettings
                if (workerSettings != null)
                {
                    options.MediasoupSettings.WorkerSettings.LogLevel            = workerSettings.LogLevel;
                    options.MediasoupSettings.WorkerSettings.LogTags             = workerSettings.LogTags;
                    options.MediasoupSettings.WorkerSettings.RtcMinPort          = workerSettings.RtcMinPort;
                    options.MediasoupSettings.WorkerSettings.RtcMaxPort          = workerSettings.RtcMaxPort;
                    options.MediasoupSettings.WorkerSettings.DtlsCertificateFile = workerSettings.DtlsCertificateFile;
                    options.MediasoupSettings.WorkerSettings.DtlsPrivateKeyFile  = workerSettings.DtlsPrivateKeyFile;
                }

                // RouteSettings
                if (routerSettings != null && !routerSettings.RtpCodecCapabilities.IsNullOrEmpty())
                {
                    options.MediasoupSettings.RouterSettings = routerSettings;

                    // Fix RtpCodecCapabilities[x].Parameters 。从配置文件反序列化时将数字转换成了字符串,这里进行修正。
                    foreach (var codec in routerSettings.RtpCodecCapabilities.Where(m => m.Parameters != null))
                    {
                        foreach (var key in codec.Parameters.Keys.ToArray())
                        {
                            var value = codec.Parameters[key];
                            if (value != null && Int32.TryParse(value.ToString(), out var intValue))
                            {
                                codec.Parameters[key] = intValue;
                            }
                        }
                    }
                }

                // WebRtcTransportSettings
                if (webRtcTransportSettings != null)
                {
                    options.MediasoupSettings.WebRtcTransportSettings.ListenIps = webRtcTransportSettings.ListenIps;
                    options.MediasoupSettings.WebRtcTransportSettings.InitialAvailableOutgoingBitrate = webRtcTransportSettings.InitialAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MinimumAvailableOutgoingBitrate = webRtcTransportSettings.MinimumAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MaxSctpMessageSize = webRtcTransportSettings.MaxSctpMessageSize;

                    // 如果没有设置 ListenIps 则获取本机所有的 IPv4 地址进行设置。
                    var listenIps = options.MediasoupSettings.WebRtcTransportSettings.ListenIps;
                    if (listenIps.IsNullOrEmpty())
                    {
                        var localIPv4IPAddresses = IPAddressExtensions.GetLocalIPAddresses(AddressFamily.InterNetwork).Where(m => m != IPAddress.Loopback);
                        if (localIPv4IPAddresses.IsNullOrEmpty())
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        listenIps = (from ip in localIPv4IPAddresses
                                     let ipString = ip.ToString()
                                                    select new TransportListenIp
                        {
                            Ip = ipString,
                            AnnouncedIp = ipString
                        }).ToArray();
                        options.MediasoupSettings.WebRtcTransportSettings.ListenIps = listenIps;
                    }
                    else
                    {
                        var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                        if (localIPv4IPAddress == null)
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        foreach (var listenIp in listenIps)
                        {
                            if (string.IsNullOrWhiteSpace(listenIp.AnnouncedIp))
                            {
                                // 如果没有设置 AnnouncedIp:
                                // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                                listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                            }
                        }
                    }
                }

                // PlainTransportSettings
                if (plainTransportSettings != null)
                {
                    options.MediasoupSettings.PlainTransportSettings.ListenIp           = plainTransportSettings.ListenIp;
                    options.MediasoupSettings.PlainTransportSettings.MaxSctpMessageSize = plainTransportSettings.MaxSctpMessageSize;

                    var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                    if (localIPv4IPAddress == null)
                    {
                        throw new ArgumentException("无法获取本机 IPv4 配置 PlainTransport。");
                    }

                    var listenIp = options.MediasoupSettings.PlainTransportSettings.ListenIp;
                    if (listenIp == null)
                    {
                        listenIp = new TransportListenIp
                        {
                            Ip          = localIPv4IPAddress.ToString(),
                            AnnouncedIp = localIPv4IPAddress.ToString(),
                        };
                        options.MediasoupSettings.PlainTransportSettings.ListenIp = listenIp;
                    }
                    else if (string.IsNullOrWhiteSpace(listenIp.AnnouncedIp))
                    {
                        // 如果没有设置 AnnouncedIp:
                        // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                        listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                    }
                }
            });

            // Meeting server
            context.Services.AddMeetingServer(options =>
            {
                options.ServeMode = ServeMode.Open;
            });

            // SignalR
            context.Services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            })
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
                options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });
        }
示例#29
0
        // % % % % % % % % % % % % % % % % % % % % % % % % % //
        // %%%%%%%%%%%%%%%%% GŁOWNA METODA %%%%%%%%%%%%%%%%% //
        // % % % % % % % % % % % % % % % % % % % % % % % % % //

        public bool ConnectionRequestFromNCC(string pathBegin, string pathEnd, int capacity)
        {
            string PathEndAddressFromDifferentDomain = null;

            string[] existingConnKey = new string[] { pathBegin, pathEnd };
            //Lista SNP dla tworzonego aktualnie polaczenia
            List <SNP> SNPList = new List <SNP>();

            //zakladamy, ze adres poczatkowy zawsze jest w naszej domenie, jezeli dostalismy requesta od NCC
            //dodaj SNP z labelem 0 dla poczatku sciezki
            SNPList.Add(new SNP(0, pathBegin, capacity, pathBegin, pathEnd));

            //sprawdzamy, czy adres koncowy jest w naszej domenie
            if (!IPAddressExtensions.IsInSameSubnet(IPAddress.Parse(pathEnd), IPAddress.Parse(SubnetworkAddress), IPAddress.Parse(SubnetworkMask)))
            {
                PathEndAddressFromDifferentDomain = pathEnd;

                //sprawdza, czy adres docelowy jest w innej podsieci i podmienia
                foreach (SubnetworkAddress domainAddress in OtherDomainSNPPAddressTranslation.Keys)
                {
                    if (!IPAddressExtensions.IsInSameSubnet(IPAddress.Parse(pathEnd), domainAddress.subnetAddress, domainAddress.subnetMask))
                    {
                        Random random = new Random();
                        List <Tuple <IPAddress, IPAddress> > translationsList = OtherDomainSNPPAddressTranslation[domainAddress];
                        Tuple <IPAddress, IPAddress>         foundTranslation = translationsList[random.Next(translationsList.Count)];
                        IPAddress translatedAddress = foundTranslation.Item1;
                        pathEnd = translatedAddress.ToString();
                    }
                }
            }

            LogClass.WhiteLog("[CC] RouteTableQuery called between: " + pathBegin + " and: " + pathEnd);
            List <SNPP> SNPPList = RouteTableQuery(pathBegin, pathEnd, capacity);

            if (SNPPList.Count > 0)
            {
                //dodaj SNP z labelem 0 dla konca sciezki
                if (PathEndAddressFromDifferentDomain == null)
                {
                    SNPList.Add(new SNP(0, pathEnd, capacity, pathBegin, pathEnd));
                }
                else
                {
                    SNPP fakeSNPP = new SNPP(pathEnd, 0);
                    SNPPList.Add(fakeSNPP);
                    SNPPList.Add(fakeSNPP);
                }

                for (int index = 0; index < SNPPList.Count; index += 2)
                {
                    SNPP             SNPPpathBegin = SNPPList[index];
                    SNPP             SNPPpathEnd   = SNPPList[index + 1];
                    Tuple <SNP, SNP> SNPpair       = LinkConnectionRequest(SNPPpathBegin, SNPPpathEnd, capacity);
                    if (SNPpair.Item1 != SNPpair.Item2)
                    {
                        SNPList.Add(SNPpair.Item1);
                        SNPList.Add(SNPpair.Item2);
                    }
                    else
                    {
                        SNPList.Add(SNPpair.Item1);
                    }
                }

                //Zapamietaj SNPlist z polaczeniem mdzy takimi adresami
                existingConnections.Add(existingConnKey, SNPList);

                //Wysłanie ConnectionRequesta do podsieci, jeżeli na liscie SNP zajdą się 2 adresy brzegowe tej podsieci

                for (int index = 0; index < SNPList.Count - 1; index++)
                {
                    SNP SNPpathBegin = SNPList[index];
                    for (int jndex = index + 1; jndex < SNPList.Count; jndex++)
                    {
                        SNP SNPpathEnd = SNPList[jndex];

                        if (BelongsToSubnetwork(SNPpathBegin, SNPpathEnd))
                        {
                            if (ConnectionRequestOut(SNPpathBegin, SNPpathEnd))
                            {
                                LogClass.Log("Subnetwork Connection set properly.");
                            }
                            else
                            {
                                LogClass.Log("Epic fail.");
                                return(false);
                            }
                        }
                    }
                }

                //Wyslanie PeerCoordination jezeli zestawiane polaczenie przebiega przez 2 domeny

                if (PathEndAddressFromDifferentDomain != null)
                {
                    //TODO: sprawdz, czy ktorys z SNP ma adres SNPP brzegowego tej domeny
                    SNP lastSNPinThisDomain = null;
                    foreach (SNP snp in SNPList)
                    {
                        foreach (List <Tuple <IPAddress, IPAddress> > list in OtherDomainSNPPAddressTranslation.Values)
                        {
                            foreach (Tuple <IPAddress, IPAddress> tuple in list)
                            {
                                if (tuple.Item1.ToString() == snp.Address)
                                {
                                    lastSNPinThisDomain           = snp;
                                    lastSNPinThisDomain.PathBegin = pathBegin;
                                    lastSNPinThisDomain.PathEnd   = PathEndAddressFromDifferentDomain;
                                }
                            }
                        }
                    }


                    if (PeerCoordinationOut(lastSNPinThisDomain, PathEndAddressFromDifferentDomain))
                    {
                        LogClass.Log("PeerCoordination OK.");
                    }
                    else
                    {
                        LogClass.Log("PeerCoordination FAIL.");
                    };
                }
            }
            if (SNPPList.Count > 0)
            {
                return(true);  //Jesli polaczenie zestawiono poprawnie
            }
            else
            {
                return(false);
            }
        }
示例#30
-1
        public void Send(byte[] data, System.Net.EndPoint ep)
        {
            DTLS.Client socket   = _Client;
            IPEndPoint  remoteEP = (IPEndPoint)ep;

            if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
            {
                if (_ClientIPv4 != null)
                {
                    // use the separated socket of IPv4 to deal with IPv4 conversions.
                    socket = _ClientIPv4;
                }
                else if (_Client.LocalEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    remoteEP = new IPEndPoint(IPAddressExtensions.MapToIPv6(remoteEP.Address), remoteEP.Port);
                }
            }
            if (!_Connected)
            {
                socket.ConnectToServer(remoteEP);
                _Connected = true;
            }

            socket.Send(data);
        }