public static DiscoveryResult DiscoverDevice(int port) {
      IEnumerable<string> ips = getInterfaceAddresses();
      var ret = new DiscoveryResult();
      _localEndPoint = new IPEndPoint(IPAddress.Any, 0);
      _client = new UdpClient(port);

      var p = new ISCPPacket("!xECNQSTN");
      byte[] sendbuf = p.GetBytes();
      foreach (string networkaddress in ips) {
        _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
        _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
        _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
      }
      while (_client.Available > 0) {
        byte[] recv = _client.Receive(ref _localEndPoint);
        Thread.Sleep(100);
        var sb = new StringBuilder();
        foreach (byte t in recv)
          sb.Append(char.ConvertFromUtf32(Convert.ToInt32(string.Format("{0:x2}", t), 16)));
        string stringData = sb.ToString();
        if (stringData.Contains("!1ECN")) {
          int idx = stringData.IndexOf("!1ECN") + 5;
          string[] parts = stringData.Substring(idx).Split('/');
          string mac = parts[3].Substring(0,12);
          string ip = ARP.GetIPInfo(mac).IPAddress;
          ret.IP = ip;
          ret.Port = Convert.ToInt32(parts[1]);
          ret.Region = stringData.Substring(idx + 14, 2);
          ret.MAC = mac;
          ret.Model = stringData.Substring(idx, 7);
        }
      }
      _client.Close();
      return ret;
    }
Esempio n. 2
0
        /// <summary>
        /// Performs discovery on the specified identifier.
        /// </summary>
        /// <param name="identifier">The identifier to perform discovery on.</param>
        /// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
        /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
        /// <returns>
        /// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
        /// </returns>
        public IEnumerable <IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain)
        {
            abortDiscoveryChain = false;
            var uriIdentifier = identifier as UriIdentifier;

            if (uriIdentifier == null)
            {
                return(Enumerable.Empty <IdentifierDiscoveryResult>());
            }

            var endpoints = new List <IdentifierDiscoveryResult>();

            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Discover(requestHandler, uriIdentifier, identifier.IsDiscoverySecureEndToEnd);

            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                        var          xrdsEndpoints = xrds.XrdElements.CreateServiceEndpoints(yadisResult.NormalizedUri, uriIdentifier);

                        // Filter out insecure endpoints if high security is required.
                        if (uriIdentifier.IsDiscoverySecureEndToEnd)
                        {
                            xrdsEndpoints = xrdsEndpoints.Where(se => se.ProviderEndpoint.IsTransportSecure());
                        }
                        endpoints.AddRange(xrdsEndpoints);
                    } catch (XmlException ex) {
                        Logger.Yadis.Error("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
                    }
                }

                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    var htmlEndpoints = new List <IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
                    if (htmlEndpoints.Any())
                    {
                        Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
                        Logger.Yadis.Debug(htmlEndpoints.ToStringDeferred(true));
                        endpoints.AddRange(htmlEndpoints.Where(ep => !uriIdentifier.IsDiscoverySecureEndToEnd || ep.ProviderEndpoint.IsTransportSecure()));
                        if (endpoints.Count == 0)
                        {
                            Logger.Yadis.Info("No HTML discovered endpoints met the security requirements.");
                        }
                    }
                    else
                    {
                        Logger.Yadis.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }
            return(endpoints);
        }
Esempio n. 3
0
        /// <summary>
        /// Searches for an XRDS document at the realm URL, and if found, searches
        /// for a description of a relying party endpoints (OpenId login pages).
        /// </summary>
        /// <param name="allowRedirects">
        /// Whether redirects may be followed when discovering the Realm.
        /// This may be true when creating an unsolicited assertion, but must be
        /// false when performing return URL verification per 2.0 spec section 9.2.1.
        /// </param>
        /// <returns>The details of the endpoints if found, otherwise null.</returns>
        internal IEnumerable <DotNetOpenId.Provider.RelyingPartyReceivingEndpoint> Discover(bool allowRedirects)
        {
            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Yadis.Discover(UriWithWildcardChangedToWww, false);

            if (yadisResult != null)
            {
                if (!allowRedirects && yadisResult.NormalizedUri != yadisResult.RequestUri)
                {
                    // Redirect occurred when it was not allowed.
                    throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                            Strings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri));
                }
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds = new XrdsDocument(yadisResult.ResponseText);
                        return(xrds.FindRelyingPartyReceivingEndpoints());
                    } catch (XmlException ex) {
                        throw new OpenIdException(Strings.InvalidXRDSDocument, ex);
                    }
                }
            }
            return(new RelyingPartyReceivingEndpoint[0]);
        }
Esempio n. 4
0
        internal DiscoveryResult DiscoverInternal(Assembly testAssembly, string testAssemblyPath, string configFilePath)
        {
            var bindingRegistry = GetBindingRegistry(testAssembly, configFilePath);

            var result           = new DiscoveryResult();
            var warningCollector = new WarningCollector();

            _sourceFiles.Clear();
            GetOrCreateSymbolReader(testAssembly, warningCollector, testAssemblyPath);

            result.StepDefinitions =
                GetStepDefinitions(bindingRegistry).Select(sdb =>
                                                           new StepDefinition
            {
                Type           = sdb.StepDefinitionType.ToString(),
                Regex          = sdb.Regex.ToString(),
                Method         = sdb.Method.ToString(),
                ParamTypes     = GetParamTypes(sdb.Method),
                Scope          = GetScope(sdb),
                SourceLocation = GetSourceLocation(sdb.Method, warningCollector)
            })
                .Distinct()     //TODO: SpecFlow discoverers bindings from external assemblies twice -- needs fix
                .ToArray();
            result.SourceFiles     = _sourceFiles.ToDictionary(sf => sf.Value.ToString(), sf => sf.Key);
            result.TypeNames       = _typeNames.ToDictionary(sf => sf.Value.ToString(), sf => sf.Key);
            result.Warnings        = warningCollector.Warnings;
            result.SpecFlowVersion = typeof(IStepDefinitionBinding).Assembly.Location;
            return(result);
        }
        static void OnDoWork(object sender, DoWorkEventArgs args)
        {
            var discovery = args.Argument as Discovery;
            var result    = new DiscoveryResult();

            args.Result = result;

            if (discovery != null)
            {
                try
                {
                    result.Reference = new DiscoveryCompiler(discovery, CodeProvider.Default)
                                       .GenerateReference("temp");
                }
                catch (InvalidOperationException ioe)
                {
                    Debug.WriteLine(ioe.Message);
                    result.FailureReason = ioe.Message;
                    if (ioe.InnerException != null)
                    {
                        result.FailureReason += "\n" + ioe.InnerException.Message;
                    }
                }
            }
        }
Esempio n. 6
0
    public void AddElement(DiscoveryResult discoveryResult)
    {
        ServerListElement serverListElement = GameObject.Instantiate(serverListElementPrefab, transform).GetComponent <ServerListElement>();

        serverListElements.Add(serverListElement);
        serverListElement.Init(discoveryResult);

        UpdateColumnWidths();
    }
        public async Task <DiscoveryResult> DiscoverDevice(int port)
        {
            IEnumerable <string> ips = getInterfaceAddresses();
            var ret = new DiscoveryResult();

            _localEndPoint = new IPEndPoint(IPAddress.Any, 22222);

            _client = new UdpClient(port);
            _client.EnableBroadcast = true;
            _packetService.SetCommand("!xECNQSTN");
            byte[] sendbuf = _packetService.GetBytes();
            foreach (string networkaddress in ips)
            {
                try
                {
                    _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
                    Console.WriteLine("Dobry socket");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Zly socket");
                    Console.WriteLine(e);
                }
            }
            //while (_client.Available > 0)
            while (_client.Available > 0)
            {
                //  var recv = new byte[256];
                // _sock.Receive(recv, recv.Length, SocketFlags.None);
                byte[] recv = _client.Receive(ref _localEndPoint);
                Thread.Sleep(300);
                var sb = new StringBuilder();
                foreach (byte t in recv)
                {
                    sb.Append(char.ConvertFromUtf32(Convert.ToInt32(string.Format("{0:x2}", t), 16)));
                }
                string stringData = sb.ToString();


                if (stringData.Contains("!1ECN"))
                {
                    int      idx   = stringData.IndexOf("!1ECN") + 5;
                    string[] parts = stringData.Substring(idx).Split('/');
                    string   mac   = parts[3].Substring(0, 12);
                    var      ip    = _addressResolutionProtocolService.GetIPInfo(mac);
                    ret.IP     = ip.IpAddress;
                    ret.Port   = Convert.ToInt32(parts[1]);
                    ret.Region = stringData.Substring(idx + 14, 2);
                    ret.MAC    = mac;
                    ret.Model  = stringData.Substring(idx, 7);
                }
            }
            //  _sock.Close();
            _client.Close();
            return(ret);
        }
        internal override IEnumerable <ServiceEndpoint> Discover()
        {
            List <ServiceEndpoint> endpoints = new List <ServiceEndpoint>();
            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Yadis.Discover(this, IsDiscoverySecureEndToEnd);

            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                        var          xrdsEndpoints = xrds.CreateServiceEndpoints(yadisResult.NormalizedUri);
                        // Filter out insecure endpoints if high security is required.
                        if (IsDiscoverySecureEndToEnd)
                        {
                            xrdsEndpoints = Util.Where(xrdsEndpoints, se => se.IsSecure);
                        }
                        endpoints.AddRange(xrdsEndpoints);
                    } catch (XmlException ex) {
                        //Logger.Error("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
                    }
                }
                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    var htmlEndpoints = new List <ServiceEndpoint>(DiscoverFromHtml(yadisResult.NormalizedUri, yadisResult.ResponseText));
                    if (htmlEndpoints.Count > 0)
                    {
                        //Logger.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
                        //Logger.Debug(Util.ToString(htmlEndpoints, true));
                        endpoints.AddRange(Util.Where(htmlEndpoints, ep => !IsDiscoverySecureEndToEnd || ep.IsSecure));
                        if (endpoints.Count == 0)
                        {
                            //Logger.Info("No HTML discovered endpoints met the security requirements.");
                        }
                    }
                    else
                    {
                        //Logger.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    //Logger.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }
            return(endpoints);
        }
Esempio n. 9
0
        /// <summary>
        /// Performs discovery on the Identifier.
        /// </summary>
        /// <param name="requestHandler">The web request handler to use for discovery.</param>
        /// <returns>
        /// An initialized structure containing the discovered provider endpoint information.
        /// </returns>
        internal override IEnumerable <ServiceEndpoint> Discover(IDirectWebRequestHandler requestHandler)
        {
            List <ServiceEndpoint> endpoints = new List <ServiceEndpoint>();

            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Discover(requestHandler, this, IsDiscoverySecureEndToEnd);

            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                    var          xrdsEndpoints = xrds.CreateServiceEndpoints(yadisResult.NormalizedUri, this);

                    // Filter out insecure endpoints if high security is required.
                    if (IsDiscoverySecureEndToEnd)
                    {
                        xrdsEndpoints = xrdsEndpoints.Where(se => se.IsSecure);
                    }
                    endpoints.AddRange(xrdsEndpoints);
                }

                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    var htmlEndpoints = new List <ServiceEndpoint>(DiscoverFromHtml(yadisResult.NormalizedUri, this, yadisResult.ResponseText));
                    if (htmlEndpoints.Any())
                    {
                        Logger.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
                        Logger.Debug(htmlEndpoints.ToStringDeferred(true));
                        endpoints.AddRange(htmlEndpoints.Where(ep => !IsDiscoverySecureEndToEnd || ep.IsSecure));
                        if (endpoints.Count == 0)
                        {
                            Logger.Info("No HTML discovered endpoints met the security requirements.");
                        }
                    }
                    else
                    {
                        Logger.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    Logger.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }
            return(endpoints);
        }
Esempio n. 10
0
        internal override IEnumerable <ServiceEndpoint> Discover()
        {
            List <ServiceEndpoint> endpoints = new List <ServiceEndpoint>();
            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Yadis.Discover(this, IsDiscoverySecureEndToEnd);

            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                    var          xrdsEndpoints = xrds.CreateServiceEndpoints(yadisResult.NormalizedUri);
                    // Filter out insecure endpoints if high security is required.
                    if (IsDiscoverySecureEndToEnd)
                    {
                        xrdsEndpoints = Util.Where(xrdsEndpoints, se => se.IsSecure);
                    }
                    endpoints.AddRange(xrdsEndpoints);
                }
                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    ServiceEndpoint ep = DiscoverFromHtml(yadisResult.NormalizedUri, yadisResult.ResponseText);
                    if (ep != null)
                    {
                        Logger.Debug("HTML discovery found a service endpoint.");
                        Logger.Debug(ep);
                        if (!IsDiscoverySecureEndToEnd || ep.IsSecure)
                        {
                            endpoints.Add(ep);
                        }
                        else
                        {
                            Logger.Info("Skipping HTML discovered endpoint because it is not secure.");
                        }
                    }
                    else
                    {
                        Logger.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    Logger.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }
            return(endpoints);
        }
        /// <summary>
        /// Gets the information that will be sent in the authentication
        /// request to the OpenID Provider.
        /// </summary>
        /// <param name="discResult">The DiscoveryResult object to use.</param>
        public NameValueCollection BuildAuthorizationData(DiscoveryResult discResult)
        {
            NameValueCollection pms = new NameValueCollection();

            pms["openid.identity"] = discResult.LocalId;

            if (discResult.AuthVersion == ProtocolVersion.V2Dot0)
            {
                pms["openid.claimed_id"] = discResult.ClaimedId;
            }
            else
            {
                pms["esoid.ReturnUrl"] = "esoid.claimed_id=" + HttpUtility.UrlEncode(discResult.ClaimedId);
            }
            return pms;
        }
Esempio n. 12
0
		/// <summary>
		/// Searches for an XRDS document at the realm URL.
		/// </summary>
		/// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param>
		/// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm.
		/// This may be true when creating an unsolicited assertion, but must be
		/// false when performing return URL verification per 2.0 spec section 9.2.1.</param>
		/// <returns>
		/// The XRDS document if found; or <c>null</c> if no service document was discovered.
		/// </returns>
		internal virtual XrdsDocument Discover(IDirectWebRequestHandler requestHandler, bool allowRedirects) {
			// Attempt YADIS discovery
			DiscoveryResult yadisResult = Yadis.Discover(requestHandler, this.UriWithWildcardChangedToWww, false);
			if (yadisResult != null) {
				// Detect disallowed redirects, since realm discovery never allows them for security.
				ErrorUtilities.VerifyProtocol(allowRedirects || yadisResult.NormalizedUri == yadisResult.RequestUri, OpenIdStrings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri);
				if (yadisResult.IsXrds) {
					try {
						return new XrdsDocument(yadisResult.ResponseText);
					} catch (XmlException ex) {
						throw ErrorUtilities.Wrap(ex, XrdsStrings.InvalidXRDSDocument);
					}
				}
			}

			return null;
		}
            internal static async Task <Office365ServiceInfo> CreateAsync()
            {
                // Attempt to build an Office365ServiceInfo object based on cached API endpoint & resource ID information:
                SharePointOneDriveServiceInfo info = new SharePointOneDriveServiceInfo
                {
                    ResourceId  = (string)Office365CommonController.GetFromCache("SharePointOneDriveResourceId"),
                    ApiEndpoint = (string)Office365CommonController.GetFromCache("SharePointOneDriveApiEndpoint")
                };

                // If the Resource ID and API Endpoint are not empty, then the cached information is sufficient:
                if (info.ResourceId != null && info.ApiEndpoint != null)
                {
                    info.AccessToken = Office365CommonController.GetAccessToken(info.ResourceId);
                    return(info);
                }

                // If did not return above, invoke the Discovery Service to obtain the resource ID and API endpoint:
                info._discoveryServiceInfo = new DiscoveryServiceInfo();

                // If no auth header is available for Discovery, return the info as is, with the missing
                //     access token (and possibly a missing ResourceId and ApiEndpoint as well). The caller will need
                //     to do an OAuth redirect anyway.
                if (!info._discoveryServiceInfo.HasValidAccessToken)
                {
                    return(info);
                }

                // If still here, discovery has enough information to obtain the SharePoint OneDrive endpoints:
                DiscoveryResult[] results = await info._discoveryServiceInfo.DiscoverServicesAsync();

                DiscoveryResult myFilesEndpoint = results.First(result => result.Capability == "MyFiles");

                // Update and cache the resource ID and API endpoint:
                info.ResourceId = myFilesEndpoint.ServiceResourceId;
                // NOTE: In the initial Preview release of Service Discovery, the "MyFiles" endpoint URL will always
                //     start with something like "https://contoso-my.sharepoint.com/personal/<username>_contoso_com/_api",
                //     but the path following "/_api" may change over time.  For consistency, it is safer to manually
                //     extract the root path, and then append a call for the location of the Documents folder:
                info.ApiEndpoint = myFilesEndpoint.ServiceEndpointUri.Substring(
                    0, myFilesEndpoint.ServiceEndpointUri.IndexOf("/_api", StringComparison.Ordinal)) +
                                   "/_api/web/getfolderbyserverrelativeurl('Documents')";
                Office365CommonController.SaveInCache("SharePointOneDriveResourceId", info.ResourceId);
                Office365CommonController.SaveInCache("SharePointOneDriveApiEndpoint", info.ApiEndpoint);
                info.AccessToken = Office365CommonController.GetAccessToken(info.ResourceId);
                return(info);
            }
Esempio n. 14
0
            internal async static Task <Office365ServiceInfo> CreateAsync()
            {
                // Attempt to build an Office365ServiceInfo object based on cached API endpoint & resource ID information:
                Office365ServiceInfo info = new SharePointOneDriveServiceInfo()
                {
                    ResourceId  = (string)Office365Helper.GetFromCache("SharePointOneDriveResourceId"),
                    ApiEndpoint = (string)Office365Helper.GetFromCache("SharePointOneDriveApiEndpoint")
                };

                // If the cached Resource ID and API Endpoint are not empty, then use them:
                if ((info.ResourceId != null) && (info.ApiEndpoint != null))
                {
                    info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                    return(info);
                }

                // If did not return above, invoke the Discovery Service to obtain the resource ID and API endpoint:
                DiscoveryServiceInfo discoveryServiceInfo = await DiscoveryServiceInfo.CreateAsync();

                if (!discoveryServiceInfo.HasValidAccessToken)
                {
                    // Cannot communicated with Service Discovery, so return the empty SharePointOneDriveServiceInfo as is.
                    //     The missing access token will let the caller know that the service is not ready to be used.
                    return(info);
                }

                DiscoveryResult[] results = await discoveryServiceInfo.DiscoverServicesAsync();

                DiscoveryResult myFilesEndpoint = results.First(result => result.Capability == "MyFiles");

                // Update and cache the resource ID and API endpoint:
                info.ResourceId = myFilesEndpoint.ServiceResourceId;
                // NOTE: In the initial Preview release of Service Discovery, the "MyFiles" endpoint URL will always
                //     start with something like "https://contoso-my.sharepoint.com/personal/<username>_contoso_com/_api",
                //     but the path following "/_api" may change over time.  For consistency, it is safer to manually
                //     extract the root path, and then append a call for the location of the Documents folder:
                info.ApiEndpoint = myFilesEndpoint.ServiceEndpointUri.Substring(
                    0, myFilesEndpoint.ServiceEndpointUri.IndexOf("/_api", StringComparison.Ordinal)) +
                                   "/_api/web/getfolderbyserverrelativeurl('Documents')";
                Office365Helper.SaveInCache("SharePointOneDriveResourceId", info.ResourceId);
                Office365Helper.SaveInCache("SharePointOneDriveApiEndpoint", info.ApiEndpoint);
                info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                return(info);
            }
Esempio n. 15
0
    public void Init(DiscoveryResult discoveryResult)
    {
        hostedByColumnText.text = discoveryResult.HostName;
        playersColumnText.text  = discoveryResult.ConnectedPlayers + " / " + discoveryResult.NumberOfPlayers;
        lapsColumnText.text     = discoveryResult.Laps.ToString();
        connectButton.onClick.AddListener(() =>
        {
            GameSession.serverSession = null;

            GameSession.clientSession = new ClientSession
            {
                remoteServerIpAddress = discoveryResult.RemoteServerIpAddress,
                remoteServerPort      = discoveryResult.RemoteServerPort
            };

            SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);
        });
    }
        private static void OnDoWork(object sender, DoWorkEventArgs args)
        {
            var discovery = args.Argument as Discovery;
            var result = new DiscoveryResult();
            args.Result = result;

            if (discovery != null)
            {
                try
                {
                    result.Reference = new DiscoveryCompiler(discovery, CodeProvider.Default)
                        .GenerateReference("temp");
                }
                catch (InvalidOperationException ioe)
                {
                    result.FailureReason = ioe.Message;
                }
            }
        }
        public static DiscoveryResult DiscoverDevice(int port)
        {
            IEnumerable <string> ips = getInterfaceAddresses();
            var ret = new DiscoveryResult();

            _localEndPoint = new IPEndPoint(IPAddress.Any, 0);
            _client        = new UdpClient(port);

            var p = new ISCPPacket("!xECNQSTN");

            byte[] sendbuf = p.GetBytes();
            foreach (string networkaddress in ips)
            {
                _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
                _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
                _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
            }
            while (_client.Available > 0)
            {
                byte[] recv = _client.Receive(ref _localEndPoint);
                Thread.Sleep(100);
                var sb = new StringBuilder();
                foreach (byte t in recv)
                {
                    sb.Append(char.ConvertFromUtf32(Convert.ToInt32(string.Format("{0:x2}", t), 16)));
                }
                string stringData = sb.ToString();
                if (stringData.Contains("!1ECN"))
                {
                    int      idx   = stringData.IndexOf("!1ECN") + 5;
                    string[] parts = stringData.Substring(idx).Split('/');
                    string   mac   = parts[3].Substring(0, 12);
                    string   ip    = ARP.GetIPInfo(mac).IPAddress;
                    ret.IP     = ip;
                    ret.Port   = Convert.ToInt32(parts[1]);
                    ret.Region = stringData.Substring(idx + 14, 2);
                    ret.MAC    = mac;
                    ret.Model  = stringData.Substring(idx, 7);
                }
            }
            _client.Close();
            return(ret);
        }
Esempio n. 18
0
        /// <summary>
        /// Add a forwarding rule to the router using UPnP
        /// </summary>
        public bool ForwardPort(int port, string description)
        {
            if (!CheckAvailability())
            {
                return(false);
            }

            var client = NetUtility.GetSelfAddresses();

            if (client == null)
            {
                return(false);
            }

            bool success = false;

            lock (m_discoveryResults) {
                for (int i = 0; i < m_discoveryResults.Count; i++)
                {
                    ref DiscoveryResult result = ref m_discoveryResults.Data[i];

                    try {
                        SOAPRequest(result.ServiceUrl,
                                    "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:" + result.ServiceName + ":1\">" +
                                    "<NewRemoteHost></NewRemoteHost>" +
                                    "<NewExternalPort>" + port.ToString() + "</NewExternalPort>" +
                                    "<NewProtocol>" + ProtocolType.Udp.ToString().ToUpper(System.Globalization.CultureInfo.InvariantCulture) + "</NewProtocol>" +
                                    "<NewInternalPort>" + port.ToString() + "</NewInternalPort>" +
                                    "<NewInternalClient>" + client.ToString() + "</NewInternalClient>" +
                                    "<NewEnabled>1</NewEnabled>" +
                                    "<NewPortMappingDescription>" + description + "</NewPortMappingDescription>" +
                                    "<NewLeaseDuration>0</NewLeaseDuration>" +
                                    "</u:AddPortMapping>",
                                    "AddPortMapping", result.ServiceName);

                        success = true;
                        m_peer.LogDebug("Sent UPnP port forward request");
                    } catch (Exception ex) {
                        m_peer.LogVerbose("UPnP port forward failed: " + ex.Message);
                    }
                }
            }
Esempio n. 19
0
        /// <summary>
        /// Searches for an XRDS document at the realm URL, and if found, searches
        /// for a description of a relying party endpoints (OpenId login pages).
        /// </summary>
        /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param>
        /// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm.
        /// This may be true when creating an unsolicited assertion, but must be
        /// false when performing return URL verification per 2.0 spec section 9.2.1.</param>
        /// <returns>
        /// The details of the endpoints if found, otherwise null.
        /// </returns>
        internal IEnumerable <RelyingPartyEndpointDescription> Discover(IDirectWebRequestHandler requestHandler, bool allowRedirects)
        {
            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Discover(requestHandler, this.UriWithWildcardChangedToWww, false);

            if (yadisResult != null)
            {
                // Detect disallowed redirects, since realm discovery never allows them for security.
                ErrorUtilities.VerifyProtocol(allowRedirects || yadisResult.NormalizedUri == yadisResult.RequestUri, OpenIdStrings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri);
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds = new XrdsDocument(yadisResult.ResponseText);
                        return(xrds.FindRelyingPartyReceivingEndpoints());
                    } catch (XmlException ex) {
                        throw ErrorUtilities.Wrap(ex, XrdsStrings.InvalidXRDSDocument);
                    }
                }
            }
            return(Enumerable.Empty <RelyingPartyEndpointDescription>());
        }
Esempio n. 20
0
        /// <summary>
        /// Searches for an XRDS document at the realm URL.
        /// </summary>
        /// <param name="hostFactories">The host factories.</param>
        /// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm.
        /// This may be true when creating an unsolicited assertion, but must be
        /// false when performing return URL verification per 2.0 spec section 9.2.1.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The XRDS document if found; or <c>null</c> if no service document was discovered.
        /// </returns>
        internal virtual async Task <XrdsDocument> DiscoverAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken)
        {
            // Attempt YADIS discovery
            DiscoveryResult yadisResult = await Yadis.DiscoverAsync(hostFactories, this.UriWithWildcardChangedToWww, false, cancellationToken);

            if (yadisResult != null)
            {
                // Detect disallowed redirects, since realm discovery never allows them for security.
                ErrorUtilities.VerifyProtocol(allowRedirects || yadisResult.NormalizedUri == yadisResult.RequestUri, OpenIdStrings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri);
                if (yadisResult.IsXrds)
                {
                    try {
                        return(new XrdsDocument(yadisResult.ResponseText));
                    } catch (XmlException ex) {
                        throw ErrorUtilities.Wrap(ex, XrdsStrings.InvalidXRDSDocument);
                    }
                }
            }

            return(null);
        }
Esempio n. 21
0
            internal async static Task <Office365ServiceInfo> CreateAsync()
            {
                // Attempt to build an Office365ServiceInfo object based on cached API endpoint & resource ID information:
                Office365ServiceInfo info = new OneDriveServiceInfo()
                {
                    ResourceId  = (string)Office365Helper.GetFromCache("OneDriveResourceId"),
                    ApiEndpoint = (string)Office365Helper.GetFromCache("OneDriveApiEndpoint")
                };

                // If the cached Resource ID and API Endpoint are not empty, then use them:
                if ((info.ResourceId != null) && (info.ApiEndpoint != null))
                {
                    info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                    return(info);
                }

                // If did not return above, invoke the Discovery Service to obtain the resource ID and API endpoint:
                DiscoveryServiceInfo discoveryServiceInfo = await DiscoveryServiceInfo.CreateAsync();

                if (!discoveryServiceInfo.HasValidAccessToken)
                {
                    // Cannot communicated with Service Discovery, so return the empty SharePointOneDriveServiceInfo as is.
                    //     The missing access token will let the caller know that the service is not ready to be used.
                    return(info);
                }

                DiscoveryResult[] results = await discoveryServiceInfo.DiscoverServicesAsync();

                DiscoveryResult myFilesEndpoint = results.First(result => result.Capability == "MyFiles");

                // Update and cache the resource ID and API endpoint:
                info.ResourceId  = myFilesEndpoint.ServiceResourceId;
                info.ApiEndpoint = myFilesEndpoint.ServiceEndpointUri;
                Office365Helper.SaveInCache("OneDriveResourceId", info.ResourceId);
                Office365Helper.SaveInCache("OneDriveApiEndpoint", info.ApiEndpoint);
                info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                return(info);
            }
        internal DiscoveryResult DiscoverInternal(Assembly testAssembly, string testAssemblyPath, string configFilePath)
        {
            try
            {
                var bindingRegistry = GetBindingRegistry(testAssembly, configFilePath);

                var result           = new DiscoveryResult();
                var warningCollector = new WarningCollector();

                _sourceFiles.Clear();
                GetOrCreateSymbolReader(testAssembly, warningCollector, testAssemblyPath);

                result.StepDefinitions =
                    GetStepDefinitions(bindingRegistry)
                    .Select(sdb => CreateStepDefinition(sdb, warningCollector))
                    .Distinct()     //TODO: SpecFlow discoverers bindings from external assemblies twice -- needs fix
                    .ToArray();
                result.SourceFiles     = _sourceFiles.ToDictionary(sf => sf.Value.ToString(), sf => sf.Key);
                result.TypeNames       = _typeNames.ToDictionary(sf => sf.Value.ToString(), sf => sf.Key);
                result.Warnings        = warningCollector.Warnings;
                result.SpecFlowVersion = typeof(IStepDefinitionBinding).Assembly.Location;
                return(result);
            }
            catch (Exception ex) when(GetRegexError(ex) != null)
            {
                var regexError = GetRegexError(ex);

                return(new DiscoveryResult()
                {
                    SpecFlowVersion = typeof(IStepDefinitionBinding).Assembly.Location,
                    StepDefinitions = new[] {
                        new StepDefinition
                        {
                            Method = "Unknown method",
                            Error = $"Step definition regular expression error: {regexError.Message}"
                        }
                    }
                });
            }
        }
        private static void OnDoWork(object sender, DoWorkEventArgs args)
        {
            var discovery = args.Argument as Discovery;
            var result    = new DiscoveryResult();

            args.Result = result;

            if (discovery == null)
            {
                return;
            }

            try
            {
                result.Reference = new DiscoveryCompiler(discovery, CodeProvider.Default)
                                   .GenerateReference("temp");
            }
            catch (InvalidOperationException ioe)
            {
                result.FailureReason = ioe.Message;
            }
        }
        public async Task <DiscoveryResult> Discover(TerminalDTO terminal, bool isUserInitiated)
        {
            TerminalDO existentTerminal = null;

            if (!string.IsNullOrWhiteSpace(terminal.Name) && !string.IsNullOrWhiteSpace(terminal.Version))
            {
                // TODO: @alexavrutin: This comparison is not going to work in the long term.
                // Terminal names are not guaranateed to be unique. Consider changing to Endpoint.
                existentTerminal = _terminal.GetAll().FirstOrDefault(x => !string.Equals(x.Name, terminal.Name, StringComparison.OrdinalIgnoreCase) && x.Version == terminal.Version);

                if (existentTerminal != null)
                {
                    Logger.Info($"Discovering of terminal Name: {terminal.Name}, Version: {terminal.Version} was requested...");
                }
            }

            if (existentTerminal == null)
            {
                if (string.IsNullOrWhiteSpace(terminal.Endpoint))
                {
                    var message = "No endpoint was specified for discovery request";
                    Logger.Warn(message);
                    return(DiscoveryResult.Error(message));
                }

                Logger.Info($"Discovering of  terminal at '{terminal.Endpoint}' was requested...");

                existentTerminal = _terminal.GetAll().FirstOrDefault(x => string.Equals(NormalizeUrl(x.Endpoint), NormalizeUrl(terminal.Endpoint), StringComparison.OrdinalIgnoreCase));
            }

            if (existentTerminal == null)
            {
                var message = $"Discovery for terminal '{terminal.Endpoint}' failed: the provided Endpoint is not found in the Endpoint field of any of the existing Terminal entries.";
                Logger.Info(message);
                return(DiscoveryResult.Error(message));
            }

            return(await DiscoverInternal(existentTerminal, isUserInitiated));
        }
Esempio n. 25
0
        /// <summary>
        /// Returns the URL to which the User Agent should be redirected for the initial authentication request.
        /// </summary>
        /// <param name="props">RequestProperties object holding the current state.</param>
        /// <param name="discResult">The DiscoveryResult object created from the previous discovery process.</param>
        /// <param name="immediate">Whether or not an Immediate Mode request is being generated.</param>
        /// <returns>The complete URL to which the User Agent should be redirected.</returns>
        internal static Uri GetRedirectURL(StateContainer props, DiscoveryResult discResult, bool immediate)
        {
            if (props == null) { throw new ArgumentNullException("props"); }
            if (discResult == null) { throw new ArgumentNullException("discResult"); }

            NameValueCollection pms = new NameValueCollection();

            if (immediate)
            {
                pms["openid.mode"] = "checkid_immediate";
            }
            else
            {
                pms["openid.mode"] = "checkid_setup";
            }

            string returl = props.ReturnToUrl.AbsoluteUri;

            switch (props.AuthMode)
            {
                case AuthenticationMode.Stateful:
                    Association assoc = props.AssociationManager.FindByServer(discResult.ServerUrl.AbsoluteUri);

                    Random r = new Random();
                    props.Nonce = r.Next();

                    switch (discResult.AuthVersion)
                    {
                        case ProtocolVersion.V1Dot1:
                            pms["openid.assoc_handle"] = assoc.Handle;
                            pms["openid.trust_root"] = props.TrustRoot;

                            break;
                        case ProtocolVersion.V2Dot0:
                            pms["openid.ns"] = ProtocolUri.OpenId2Dot0.AbsoluteUri;
                            pms["openid.assoc_handle"] = assoc.Handle;
                            pms["openid.realm"] = props.TrustRoot;
                            break;
                    }
                    break;
                case AuthenticationMode.Stateless:
                    switch (discResult.AuthVersion)
                    {
                        case ProtocolVersion.V1Dot1:
                            pms["openid.trust_root"] = props.TrustRoot;
                            break;
                        case ProtocolVersion.V2Dot0:
                            pms["openid.ns"] = ProtocolUri.OpenId2Dot0.AbsoluteUri;
                            pms["openid.realm"] = props.TrustRoot;
                            break;
                    }
                    break;
            }

            foreach (IExtension e in props.ExtensionPlugIns)
            {
                NameValueCollection authdata = e.BuildAuthorizationData(discResult);
                foreach (string key in authdata.Keys)
                {
                    if (key == "esoid.ReturnUrl")
                    {
                        if (returl.Contains("?"))
                        {
                            returl += "&" + authdata[key];
                        }
                        else
                        {
                            returl += "?" + authdata[key];
                        }
                    }
                    else
                    {
                        pms[key] = authdata[key];
                    }
                }
            }

            pms["openid.return_to"] = Utility.AddExtraVariables(returl, props);
            return Utility.MakeGetURL(discResult.ServerUrl, pms);
        }
        //private async Task<StandardFr8TerminalCM> SendDiscoveryRequest(string terminalUrl, Dictionary<string, string> headers = null)
        //{
        //    // Use a custom HttpClient to query the terminal with a low timeout (10 sec)
        //    var innerClient = new HttpClient();
        //    innerClient.Timeout = new TimeSpan(0, 0, 10);
        //    try
        //    {
        //        var response = await innerClient.GetAsync(new Uri(terminalUrl + "/discover", UriKind.Absolute));
        //        response.EnsureSuccessStatusCode();
        //        var responseContent = await response.Content.ReadAsStringAsync();
        //        return JsonConvert.DeserializeObject<StandardFr8TerminalCM>(responseContent);
        //    }
        //    catch (Exception) // Expect an exception if the request failed
        //    {
        //        throw;
        //    }
        //}

        private async Task <DiscoveryResult> DiscoverInternal(TerminalDO terminalDo, bool isUserInitiated)
        {
            var terminalUrl = terminalDo.Endpoint;

            Logger.Info($"Starting discovering terminal at '{terminalUrl}'. Reporting about self as the Hub at '{_serverUrl}'.");


            string secret = null;

            if (terminalDo.ParticipationState == ParticipationState.Blocked)
            {
                var message = $"Discovery for terminal '{terminalUrl}' will not happen because the terminal is blocked.";

                Logger.Info(message);
                return(DiscoveryResult.Error(message));
            }

            if (terminalDo.ParticipationState == ParticipationState.Deleted)
            {
                var message = $"Discovery for terminal '{terminalUrl}' will not happen because the terminal is deleted.";
                Logger.Info(message);
                return(DiscoveryResult.Error(message));
            }

            if (!string.IsNullOrWhiteSpace(terminalDo?.Secret))
            {
                secret = terminalDo.Secret;
            }

            if (secret == null)
            {
                Logger.Info($"Generating new secret for terminal at '{terminalUrl}'");
                secret = Guid.NewGuid().ToString("N");
            }

            var headers = new Dictionary <string, string>
            {
                { "Fr8HubCallbackSecret", secret },
                { "Fr8HubCallBackUrl", _serverUrl }
            };

            StandardFr8TerminalCM terminalRegistrationInfo = null;

            try
            {
                terminalRegistrationInfo = await SendDiscoveryRequest(terminalUrl, headers);
            }
            catch (Exception ex)
            {
                Logger.Warn("Failed to call terminal discovery endpoint", ex);

                _eventReporter.ActivityTemplateTerminalRegistrationError($"Failed terminal service: {terminalUrl}. Error Message: {ex.Message} ", ex.GetType().Name);
                terminalRegistrationInfo = null;
            }

            if (terminalRegistrationInfo == null || terminalRegistrationInfo.Definition == null || terminalRegistrationInfo.Activities == null)
            {
                // Discovery failed
                var message = $"Terminal at '{terminalUrl}'  didn't return a valid response to the discovery request.";

                Logger.Warn(message);
                // Set terminal status inactive
                terminalDo.OperationalState = OperationalState.Inactive;

                try
                {
                    _terminal.RegisterOrUpdate(terminalDo, isUserInitiated);
                }
                catch (Exception ex)
                {
                    Logger.Error("Failed to update information about the terminal.", ex);
                }

                return(DiscoveryResult.Error(message));
            }

            terminalDo.Secret             = secret;
            terminalDo.OperationalState   = OperationalState.Active;
            terminalDo.AuthenticationType = terminalRegistrationInfo.Definition.AuthenticationType;
            terminalDo.Description        = terminalRegistrationInfo.Definition.Description;
            terminalDo.Label          = terminalRegistrationInfo.Definition.Label;
            terminalDo.Name           = terminalRegistrationInfo.Definition.Name;
            terminalDo.Version        = terminalRegistrationInfo.Definition.Version;
            terminalDo.TerminalStatus = terminalRegistrationInfo.Definition.TerminalStatus;

            if (string.IsNullOrWhiteSpace(terminalDo.Label))
            {
                terminalDo.Label = terminalDo.Name;
            }

            try
            {
                terminalDo = _terminal.RegisterOrUpdate(terminalDo, isUserInitiated);
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to update information about the terminal.", ex);
                return(DiscoveryResult.Error($"Internal error updating the information about the terminal at '{terminalUrl}'"));
            }

            var activityTemplates = terminalRegistrationInfo.Activities.Select(Mapper.Map <ActivityTemplateDO>).ToList();
            var result            = new DiscoveryResult(true, null);

            foreach (var curItem in activityTemplates)
            {
                Logger.Info($"Registering activity '{curItem.Name}' from terminal at '{terminalUrl}'");

                try
                {
                    curItem.Terminal   = terminalDo;
                    curItem.TerminalId = terminalDo.Id;

                    _activityTemplateService.RegisterOrUpdate(curItem);
                    result.SucceededTemplates.Add(curItem);
                }
                catch (Exception ex)
                {
                    _eventReporter.ActivityTemplateTerminalRegistrationError($"Failed to register activity {curItem.Name} of version {curItem.Version} for terminal {terminalDo.Name}. Error Message: {ex.Message}", ex.GetType().Name);

                    Logger.Warn($"Failed to register activity {curItem.Name} of version {curItem.Version} for terminal {terminalDo.Name}", ex);
                    result.FailedTemplates.Add(curItem);
                }
            }

            _activityTemplateService.RemoveInactiveActivities(terminalDo, activityTemplates);

            Logger.Info($"Successfully discovered terminal at '{terminalUrl}'.");

            return(result);
        }
Esempio n. 27
0
        private DiscoveryResult DiscoverTestsFromSingleDiscoverer(
            LazyExtension <ITestDiscoverer, ITestDiscovererCapabilities> discoverer,
            IEnumerable <string> sources,
            DiscoveryContext context,
            TestCaseDiscoverySink discoverySink,
            IMessageLogger logger,
            CancellationToken cancellationToken)
        {
            var result = new DiscoveryResult();

            if (DiscovererEnumerator.TryToLoadDiscoverer(discoverer, logger, out var discovererType) == false)
            {
                // Fail to instantiate the discoverer type.
                return(result);
            }

            // on instantiated successfully, get tests
            try
            {
                EqtTrace.Verbose(
                    "DiscovererEnumerator.DiscoverTestsFromSingleDiscoverer: Loading tests for {0}",
                    discoverer.Value.GetType().FullName);

                var currentTotalTests = this.discoveryResultCache.TotalDiscoveredTests;
                var newTimeStart      = DateTime.UtcNow;

                this.testPlatformEventSource.AdapterDiscoveryStart(discoverer.Metadata.DefaultExecutorUri.AbsoluteUri);
                foreach (var testSource in sources)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        EqtTrace.Info("DiscovererEnumerator.DiscoverTestsFromSingleDiscoverer: Cancellation Requested. Aborting the discovery");
                        break;
                    }

                    discoverer.Value.DiscoverTests(new[] { testSource }, context, logger, discoverySink);
                }

                var totalAdapterRunTime = DateTime.UtcNow - newTimeStart;
                this.testPlatformEventSource.AdapterDiscoveryStop(this.discoveryResultCache.TotalDiscoveredTests - currentTotalTests);

                // Record Total Tests Discovered By each Discoverer.
                var totalTestsDiscoveredByCurrentDiscoverer = this.discoveryResultCache.TotalDiscoveredTests - currentTotalTests;
                this.requestData.MetricsCollection.Add(
                    string.Format("{0}.{1}", TelemetryDataConstants.TotalTestsByAdapter,
                                  discoverer.Metadata.DefaultExecutorUri), totalTestsDiscoveredByCurrentDiscoverer);

                result.TotalAdaptersUsed++;

                EqtTrace.Verbose("DiscovererEnumerator.DiscoverTestsFromSingleDiscoverer: Done loading tests for {0}",
                                 discoverer.Value.GetType().FullName);

                var discovererFromDeprecatedLocations = DiscovererEnumerator.IsDiscovererFromDeprecatedLocations(discoverer);
                if (discovererFromDeprecatedLocations)
                {
                    logger.SendMessage(TestMessageLevel.Warning,
                                       string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.DeprecatedAdapterPath));
                }

                // Collecting Data Point for Time Taken to Discover Tests by each Adapter
                this.requestData.MetricsCollection.Add($"{TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter}.{discoverer.Metadata.DefaultExecutorUri}", totalAdapterRunTime.TotalSeconds);
                result.TotalTimeSpentInAdapaters += totalAdapterRunTime.TotalSeconds;
            }
            catch (Exception e)
            {
                var message = string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.ExceptionFromLoadTests, discovererType.Name, e.Message);

                logger.SendMessage(TestMessageLevel.Error, message);
                EqtTrace.Error("DiscovererEnumerator.DiscoverTestsFromSingleDiscoverer: {0} ", e);
            }

            return(result);
        }
Esempio n. 28
0
        public async Task <DiscoveryResult> Discover(TargetType targetType = TargetType.All, short ttl = 2)
        {
            List <IPAddress> addressList = new List <IPAddress>();

            addressList.AddRange(NetworkInterface.GetAllNetworkInterfaces()
                                 .Where(a => a.NetworkInterfaceType != NetworkInterfaceType.Loopback && a.OperationalStatus == OperationalStatus.Up)
                                 .SelectMany(a => a.GetIPProperties().UnicastAddresses)
                                 .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork || a.Address.AddressFamily == AddressFamily.InterNetworkV6)
                                 .Select(a => a.Address));

            DiscoveryResult result = new DiscoveryResult();
            List <Task>     tasks  = new List <Task>();

            foreach (var a in addressList)
            {
                var task = Task.Run(async() =>
                {
                    var dstAddress = a.AddressFamily == AddressFamily.InterNetwork
                                                ? Core.Ssdp.EndPoint.SiteLocal
                                                        : a.AddressFamily == AddressFamily.InterNetworkV6
                                                                ? Core.Ssdp.EndPoint.SiteLocalV6
                                                                        : null;

                    var message = new Message(dstAddress, MessageType.Search)
                                  .Mx(TimeSpan.FromSeconds(3))
                                  .St(targetType);

                    var messageBin = message.ToByteArray();

                    using (var client = new Socket(a.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
                    {
                        client.Ttl = ttl;
                        client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        client.Bind(new IPEndPoint(a, 0));

                        var bufferIn = new ArraySegment <byte>(new byte[2048]);

                        var remoteEp = a.AddressFamily == AddressFamily.InterNetwork
                                                        ? new IPEndPoint(IPAddress.Any, 0)
                                                                : a.AddressFamily == AddressFamily.InterNetworkV6
                                                                        ? new IPEndPoint(IPAddress.IPv6Any, 0)
                                                                                : null;

                        var receiveTask = client.ReceiveFromAsync(bufferIn, SocketFlags.None, remoteEp);

                        var bufferOut = new ArraySegment <byte>(messageBin);
                        client.SendTo(bufferOut.Array, dstAddress);
                        client.SendTo(bufferOut.Array, dstAddress);

                        while (true)
                        {
                            if (!receiveTask.Wait((int)(message.Mx().TotalMilliseconds *ttl)))
                            {
                                return;
                            }

                            var taskResult = await receiveTask;

                            try
                            {
                                result.Add(a, bufferIn.Take(taskResult.ReceivedBytes).ToArray(), taskResult.RemoteEndPoint);
                            }
                            catch (Exception x)
                            {
                            }

                            receiveTask = client.ReceiveFromAsync(bufferIn, SocketFlags.None, remoteEp);
                        }
                    }
                });

                tasks.Add(task);
            }

            await Task.WhenAll(tasks);

            m_discoveryResult = result;

            return(result);
        }
        /// <summary>
        /// Name-Value data to be sent to Identity Provider during
        /// initial authentication request.
        /// </summary>
        /// <param name="discResult">The DiscoveryResult object to use.</param>
        public NameValueCollection BuildAuthorizationData(DiscoveryResult discResult)
        {
            NameValueCollection pms = new NameValueCollection();
            pms["openid.ns.pape"] = NamespaceUri.AbsoluteUri;
            pms["openid.pape.max_auth_age"] = MaxAge.ToString(CultureInfo.InvariantCulture);

            List<string> list = new List<string>();
            foreach (Uri u in _PreferredPolicies)
            {
                list.Add(u.AbsoluteUri);
            }
            pms["openid.pape.preferred_auth_policies"] = String.Join(" ", list.ToArray());
            return pms;
        }
        /// <summary>
        /// Performs discovery on the specified identifier.
        /// </summary>
        /// <param name="identifier">The identifier to perform discovery on.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
        /// </returns>
        public async Task <IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken)
        {
            Requires.NotNull(identifier, "identifier");
            Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired);
            cancellationToken.ThrowIfCancellationRequested();

            var uriIdentifier = identifier as UriIdentifier;

            if (uriIdentifier == null)
            {
                return(new IdentifierDiscoveryServiceResult(Enumerable.Empty <IdentifierDiscoveryResult>()));
            }

            var endpoints = new List <IdentifierDiscoveryResult>();

            // Attempt YADIS discovery
            DiscoveryResult yadisResult = await Yadis.DiscoverAsync(this.HostFactories, uriIdentifier, identifier.IsDiscoverySecureEndToEnd, cancellationToken);

            cancellationToken.ThrowIfCancellationRequested();
            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                        var          xrdsEndpoints = xrds.XrdElements.CreateServiceEndpoints(yadisResult.NormalizedUri, uriIdentifier);

                        // Filter out insecure endpoints if high security is required.
                        if (uriIdentifier.IsDiscoverySecureEndToEnd)
                        {
                            xrdsEndpoints = xrdsEndpoints.Where(se => se.ProviderEndpoint.IsTransportSecure());
                        }
                        endpoints.AddRange(xrdsEndpoints);
                    } catch (XmlException ex) {
                        Logger.Yadis.ErrorException("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
                    }
                }

                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    await yadisResult.TryRevertToHtmlResponseAsync();

                    var htmlEndpoints = new List <IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
                    if (htmlEndpoints.Any())
                    {
                        Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
                        Logger.Yadis.Debug(htmlEndpoints.ToStringDeferred(true).ToString());
                        endpoints.AddRange(htmlEndpoints.Where(ep => !uriIdentifier.IsDiscoverySecureEndToEnd || ep.ProviderEndpoint.IsTransportSecure()));
                        if (endpoints.Count == 0)
                        {
                            Logger.Yadis.Info("No HTML discovered endpoints met the security requirements.");
                        }
                    }
                    else
                    {
                        Logger.Yadis.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }

            return(new IdentifierDiscoveryServiceResult(endpoints));
        }
Esempio n. 31
0
        /// <summary>
        /// Creates the redirect URL for the OpenID authentication request.
        /// </summary>
        /// <param name="immediate">Create an immediate-mode request URL.</param>
        /// <param name="autoRedirect">Automatically redirect the current HTTP session to the OpenID Provider.</param>
        /// <returns>The redirect URL string that should be launched by the user's web browser.</returns>
        /// <remarks>
        /// <para>
        /// Use Immediate mode to get an immediate response back from the OpenID Provider.
        /// This means the OpenID Provider will not prompt the user in any way, but will
        /// redirect the user's browser back with an authentication response.  If the user
        /// is not currently logged in to the Provider, a "SetupNeeded" response will be
        /// received here at the client.
        /// </para>
        /// <para>
        /// Set autoRedirect to true to automatically perform an HTTP redirect on the user's
        /// browser.  This option is only valid in an ASP.NET environment.  For all other
        /// environments, setting this value will have no effect.
        /// </para>
        /// </remarks>
        public virtual Uri CreateRequest(bool immediate, bool autoRedirect)
        {
            Tracer.Write("Beginning standard authentication check");

            // If the OpenID Provider was not found, return an error.
            if (ProviderUrl == null)
            {
                StateContainer.ErrorState = ErrorCondition.NoServersFound;
                Tracer.Write("No OpenID Provider found.");
                return null;
            }

            // Set to defaults if LastDiscoveryResult is not set by
            // an inheriting class.
            if (LastDiscoveryResult == null)
            {
                LastDiscoveryResult = new DiscoveryResult();
                LastDiscoveryResult.AuthVersion = ProtocolVersion.V2Dot0;
                LastDiscoveryResult.ServerUrl = ProviderUrl;
            }

            // Adjust the AuthenticationMode setting based on
            // the discovered Provider URL
            StateContainer.AuthMode = Quirks.CheckOpenIDMode(ProviderUrl.AbsoluteUri, StateContainer.AuthMode);

            // Perform Stateful (smart) authentication
            if (StateContainer.AuthMode == AuthenticationMode.Stateful)
            {
                if (ProviderUrl != null)
                {
                    if (Utility.BuildAssociation(ProviderUrl, StateContainer.AssociationManager, LastDiscoveryResult.AuthVersion) == true)
                    {
                        Uri redirectUrl = Utility.GetRedirectURL(StateContainer, LastDiscoveryResult, immediate);
                        Tracer.Write("Returning Stateful URL - " + redirectUrl.AbsoluteUri);
                        if (autoRedirect) { Redirect(redirectUrl); }
                        return redirectUrl;
                    }
                    else
                    {
                        StateContainer.AuthMode = AuthenticationMode.Stateless;
                        Tracer.Write("Stateful key exchange failed, forcing Dumb mode and re-running authentication");
                    }
                }
            }

            // Perform Stateless (dumb) authentication
            if (StateContainer.AuthMode == AuthenticationMode.Stateless)
            {
                if (ProviderUrl != null)
                {
                    Uri redirectUrl = Utility.GetRedirectURL(StateContainer, LastDiscoveryResult, immediate);
                    Tracer.Write("Returning stateless URL - " + redirectUrl.AbsoluteUri);
                    if (autoRedirect) { Redirect(redirectUrl); }
                    return redirectUrl;
                }
            }
            return null;
        }
Esempio n. 32
0
        /// <summary>
        /// Retrieve the URL of the OpenID Provider using configured discovery plugins
        /// </summary>
        /// <returns>The URL of the OpenID Provider</returns>
        internal static DiscoveryResult GetProviderUrl(string identity, IList<IDiscovery> discoveryPlugIns)
        {
            if (String.IsNullOrEmpty(identity)) { throw new ArgumentNullException("identity"); }
            if (discoveryPlugIns == null) { throw new ArgumentNullException("discoveryPlugIns"); }

            DiscoveryResult dr = new DiscoveryResult();

            Tracer.Warn("Creating HTTP Request.");

            DiscoveryResult[] systems = null;
            string actualLocation = null;

            NormalizationEntry ne = Utility.Normalize(identity, discoveryPlugIns);
            if (ne == null) { return null; }

            string response = Utility.MakeRequest(ne.DiscoveryUrl, out actualLocation);

            if (String.IsNullOrEmpty(response)) { return null; }

            dr.ClaimedId = Utility.Normalize(actualLocation, discoveryPlugIns).NormalizedId;

            Tracer.Write("HTTP Request successful.  Passing to discovery plugins.");

            for (int i = 0; i < discoveryPlugIns.Count; i++)
            {
                IDiscovery disc = (IDiscovery)discoveryPlugIns[i];
                Tracer.Write("Trying plugin " + disc.Name);
                systems = disc.Discover(response);
                if (systems != null)
                {
                    Tracer.Write("Plugin discovered endpoint.");
                    dr.AuthVersion = disc.Version;
                    break;
                }
            }

            if (systems == null)
            {
                Tracer.Write("Plugins did not discover endpoint.");
                return null;
            }

            if (systems.Length == 0)
            {
                Tracer.Write("No servers found.");
                return null;
            }

            DiscoveryResult entry = systems[0];

            if (entry.LocalId != null)
            {
                Tracer.Write("Delegated OpenID.");
                dr.LocalId = entry.LocalId;
            }
            dr.ServerUrl = entry.ServerUrl;
            Tracer.Write("Discovery successful - " + dr.ServerUrl.AbsoluteUri);

            if (dr.LocalId == null)
            {
                dr.LocalId = actualLocation;
            }
            return dr;
        }
 /// <summary>
 /// Dictionary&lt;string, string&gt; containing key-value pairs that will be passed
 /// during initial authentication request to Identity Provider.
 /// </summary>
 /// <param name="discResult">The DiscoveryResult object to use.</param>
 public NameValueCollection BuildAuthorizationData(DiscoveryResult discResult)
 {
     NameValueCollection pms = new NameValueCollection();
     int fieldcount = _OptionalFields.Count + _RequiredFields.Count;
     if (PolicyUrl != null)
     {
         fieldcount++;
     }
     if (fieldcount > 0)
     {
         if (discResult.AuthVersion == ProtocolVersion.V2Dot0)
         {
             pms["openid.ns.sreg"] = _Namespace.AbsoluteUri;
         }
         if (RequiredFields != null)
         {
             pms[_Prefix + "required"] = RequiredFields;
         }
         if (OptionalFields != null)
         {
             pms[_Prefix + "optional"] = OptionalFields;
         }
         if (PolicyUrl != null)
         {
             pms[_Prefix + "policy_url"] = PolicyUrl.AbsoluteUri;
         }
     }
     return pms;
 }
Esempio n. 34
0
        /// <summary>
        /// Parse HTTP response for OpenID Identity Providers.
        /// </summary>
        /// <param name="content">HTTP response content to parse.</param>
        /// <returns>An array of DiscoveryResult objects.</returns>
        public DiscoveryResult[] Discover(string content)
        {
            if (!content.Contains("<?xml"))
            {
                return null;
            }
            int xmlbegin = content.IndexOf("<?xml", StringComparison.Ordinal);
            string fixedcontent = content.Substring(xmlbegin);

            XmlDocument xd = new XmlDocument();
            try
            {
                xd.LoadXml(fixedcontent);
            }
            catch (XmlException xe)
            {
                Tracer.Write("XML decode failed: " + xe.Message);
                return null;
            }

            foreach (IExtension ext in Parent.ExtensionPlugIns)
            {
                IXrdsConsumer ixc = ext as IXrdsConsumer;
                if (ixc != null)
                {
                    ixc.ProcessXrds(xd);
                }
            }

            XmlNamespaceManager nsmanager = new XmlNamespaceManager(xd.NameTable);
            nsmanager.AddNamespace("openid", "http://openid.net/xmlns/1.0");
            nsmanager.AddNamespace("xrds", "xri://$xrds");
            nsmanager.AddNamespace("xrd", "xri://$xrd*($v*2.0)");

            XmlNode rootnode = xd.DocumentElement;

            List<DiscoveryResult> entries = new List<DiscoveryResult>();

            XmlNodeList xmlServices = rootnode.SelectNodes("/xrds:XRDS/xrd:XRD/xrd:Service", nsmanager);
            foreach (XmlNode node in xmlServices)
            {
                DiscoveryResult entry = new DiscoveryResult();
                entry.AuthVersion = ProtocolVersion.Invalid;

                foreach (XmlAttribute attr in node.Attributes)
                {
                    switch (attr.Name.ToUpperInvariant())
                    {
                        case "PRIORITY":
                            entry.Priority = Convert.ToInt32(attr.Value, CultureInfo.InvariantCulture);
                            break;
                        default:
                            break;
                    }
                }

                foreach (XmlNode servicenode in node.ChildNodes)
                {
                    string val = null;
                    if (servicenode.HasChildNodes)
                    {
                        val = servicenode.ChildNodes[0].Value;
                    }
                    if (val != null)
                    {
                        switch (servicenode.Name)
                        {
                            case "Type":
                                if (val.Contains("http://specs.openid.net/auth/2."))
                                {
                                    entry.AuthVersion = ProtocolVersion.V2Dot0;
                                }
                                else if (val.Contains("http://openid.net/signon/1."))
                                {
                                    if (entry.AuthVersion != ProtocolVersion.V2Dot0)
                                    {
                                        entry.AuthVersion = ProtocolVersion.V1Dot1;
                                    }
                                }
                                break;
                            case "URI":
                                entry.ServerUrl = new Uri(val);
                                break;
                            case "openid:Delegate":
                                entry.LocalId = val;
                                break;
                            case "LocalID":
                                entry.LocalId = val;
                                break;
                            default:
                                break;
                        }
                    }
                }
                if (entry.ServerUrl != null && entry.AuthVersion != ProtocolVersion.Invalid)
                {
                    entries.Add(entry);
                }
            }

            if (entries.Count > 0)
            {
                DiscoveryResultComparer comp = new DiscoveryResultComparer();
                entries.Sort(comp);
                _PV = entries[0].AuthVersion;
                return entries.ToArray();
            }
            return null;
        }
Esempio n. 35
0
 /// <summary>
 /// Build the authentication arguments that will be sent with the OpenID
 /// request.
 /// </summary>
 /// <param name="discResult">Discovery result data.</param>
 /// <returns>A populated dictionary containing the request arguments.</returns>
 public NameValueCollection BuildAuthorizationData(DiscoveryResult discResult)
 {
     NameValueCollection dict = new NameValueCollection();
     dict.Add("openid.ns.oauth", NamespaceUri.AbsoluteUri);
     dict.Add(prefix + "consumer", OAuthClient.ConsumerKey);
     dict.Add(prefix + "scope", Scope);
     return dict;
 }
Esempio n. 36
0
 /// <summary>
 /// When Directed Identity is enabled, populate the LastDiscoveryResult
 /// variable with fake discovery data.
 /// </summary>
 /// <remarks>
 /// This is needed, as discovery does not occur in Directed Identity 
 /// mode.
 /// </remarks>
 private void SetupDirectedIdentity()
 {
     identity = ProtocolUri.IdentifierSelect.AbsoluteUri;
     LastDiscoveryResult = new DiscoveryResult();
     LastDiscoveryResult.AuthVersion = ProtocolVersion.V2Dot0;
     LastDiscoveryResult.ClaimedId = ProtocolUri.IdentifierSelect.AbsoluteUri;
     LastDiscoveryResult.LocalId = ProtocolUri.IdentifierSelect.AbsoluteUri;
     LastDiscoveryResult.ServerUrl = ProviderUrl;
 }
Esempio n. 37
0
        /// <summary>
        /// Parse HTTP response for OpenID Identity Providers.
        /// </summary>
        /// <param name="content">HTTP response content to parse.</param>
        /// <returns>An array of DiscoveryResult objects.</returns>
        public DiscoveryResult[] Discover(string content)
        {
            List<string> supportedVersions = new List<string>();

            string newcontent = Utility.RemoveHtmlComments(content);

            Regex rx_linktag1 = new Regex("<link[^>]*rel=[\"']([^\"']+)[\"'][^>]*href=[\"']([^\"']+)[\"'][^>]*");
            Regex rx_linktag2 = new Regex("<link[^>]*href=[\"']([^\"']+)[\"'][^>]*rel=[\"']([^\"']+)[\"'][^>]*");

            MatchCollection m1 = rx_linktag1.Matches(newcontent);
            MatchCollection m2 = rx_linktag2.Matches(newcontent);
            List<string[]> links = new List<string[]>();

            foreach (Match m in m1)
            {
                string[] l = { m.Groups[1].Value, m.Groups[2].Value };
                links.Add(l);
            }
            foreach (Match m in m2)
            {
                string[] l = { m.Groups[2].Value, m.Groups[1].Value };
                links.Add(l);
            }

            DiscoveryResult de1 = new DiscoveryResult();
            de1.AuthVersion = ProtocolVersion.V1Dot1;
            DiscoveryResult de2 = new DiscoveryResult();
            de2.AuthVersion = ProtocolVersion.V2Dot0;

            foreach (string[] link in links)
            {
                string relattr = link[0];
                string hrefattr = link[1];

                Uri u = null;

                if (relattr.Contains("openid2.provider"))
                {
                    Uri.TryCreate(hrefattr, UriKind.Absolute, out u);
                    if (u != null)
                    {
                        de2.ServerUrl = u;
                        supportedVersions.Add("2.0");
                    }
                }
                else if (relattr.Contains("openid.server"))
                {
                    Uri.TryCreate(hrefattr, UriKind.Absolute, out u);
                    if (u != null)
                    {
                        de1.ServerUrl = u;
                        supportedVersions.Add("1.x");
                    }
                }
                else if (relattr.Contains("openid2.local_id"))
                {
                    de2.LocalId = hrefattr;
                    supportedVersions.Add("2.0");
                }
                else if (relattr.Contains("openid.delegate"))
                {
                    de1.LocalId = hrefattr;
                    supportedVersions.Add("1.x");
                }
            }

            if (supportedVersions.Contains("2.0"))
            {
                _PV = ProtocolVersion.V2Dot0;
            }
            else if (supportedVersions.Contains("1.x"))
            {
                _PV = ProtocolVersion.V1Dot1;
            }

            List<DiscoveryResult> list = new List<DiscoveryResult>();

            if (de2.ServerUrl != null)
            {
                list.Add(de2);
            }
            if (de1.ServerUrl != null)
            {
                list.Add(de1);
            }

            if (list.Count == 0) { return null; }
            return list.ToArray();
        }
Esempio n. 38
0
 public DiscoveredChunk(Vector3 cPos, DiscoveryResult res)
 {
     this.res = res;
     chunkPos = cPos;
 }
 /// <summary>
 /// Gets the key-value data to be sent to Identity Provider during
 /// authentication request.
 /// </summary>
 /// <param name="discResult">DiscoveryResult object to use.</param>
 public NameValueCollection BuildAuthorizationData(DiscoveryResult discResult)
 {
     NameValueCollection pms = new NameValueCollection();
     pms["openid.ns.ax"] = NamespaceUri.AbsoluteUri;
     switch (Mode)
     {
         case AttributeExchangeMode.Fetch:
             pms[prefix + "mode"] = "fetch_request";
             List<string> required = new List<string>();
             List<string> if_available = new List<string>();
             foreach (AttributeExchangeItem aei in _RequestData)
             {
                 pms[prefix + "type." + aei.Alias] = aei.IdUri.AbsoluteUri;
                 if (aei.Count > 1)
                 {
                     pms[prefix + "count." + aei.Alias] = aei.Count.ToString(CultureInfo.InvariantCulture);
                 }
                 if (aei.Required == true)
                 {
                     required.Add(aei.Alias);
                 }
                 else
                 {
                     if_available.Add(aei.Alias);
                 }
             }
             if (required.Count > 0) { pms[prefix + "required"] = String.Join(",", required.ToArray()); }
             if (if_available.Count > 0) { pms[prefix + "if_available"] = String.Join(",", if_available.ToArray()); }
             if (UpdateUrl != null)
             {
                 pms[prefix + "update_url"] = UpdateUrl.AbsoluteUri;
             }
             break;
         case AttributeExchangeMode.Store:
             pms[prefix + "mode"] = "store_request";
             foreach (AttributeExchangeItem aei in _RequestData)
             {
                 pms[prefix + "type." + aei.Alias] = aei.IdUri.AbsoluteUri;
                 if (aei.Values != null)
                 {
                     if (aei.Count == 1)
                     {
                         pms[prefix + "value." + aei.Alias] = aei.Values[0];
                     }
                     else if (aei.Count > 1)
                     {
                         pms[prefix + "count." + aei.Alias] = aei.Count.ToString(CultureInfo.InvariantCulture);
                         for (int i = 0; i < aei.Count; i++)
                         {
                             pms[prefix + "value." + aei.Alias + "." + i.ToString(CultureInfo.InvariantCulture)] = aei.Values[i];
                         }
                     }
                 }
             }
             break;
     }
     return pms;
 }
Esempio n. 40
0
 /// <summary>
 /// Returns a new <see cref="OpenIdUser"/> object with a pre-set claimed identity.
 /// </summary>
 /// <param name="discResult">The DiscoveryResult object created from the previous discovery process.</param>
 public OpenIdUser(DiscoveryResult discResult)
 {
     _LastDiscoveryResult = discResult;
 }
 protected virtual void Handle(DiscoveryResult <ITestService> discoveryResult) => AddServices(discoveryResult);
Esempio n. 42
0
        private static int GetCount(NetworkAdapterInfo info, DiscoveryResult[] discoveryResult, out DiscoveryResult result)
        {
            List <DiscoveryResult> devices = GetRoutingDevices(discoveryResult);
            int index = 0;

            result = null;

            foreach (DiscoveryResult device in devices)
            {
                if (device.NetworkAdapterInfo.Equals(info))
                {
                    index++;
                    result = device;
                }
            }
            return(index);
        }