protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            ID = "EditConfigBox";

            SharedBasePage requestPage = Page as SharedBasePage;
            SiteConfig     siteConfig  = requestPage.SiteConfig;

            if (!IsPostBack)
            {
                textContact.Text                       = siteConfig.Contact;
                textCopyright.Text                     = siteConfig.Copyright;
                textPassword.Text                      = passwordPlaceHolder;
                textConfirmPassword.Text               = passwordPlaceHolder;
                textFrontPageCategory.Text             = siteConfig.FrontPageCategory;
                textFrontPageDayCount.Text             = siteConfig.FrontPageDayCount.ToString();
                textFrontPageEntryCount.Text           = siteConfig.FrontPageEntryCount.ToString();
                textEntriesPerPage.Text                = siteConfig.EntriesPerPage.ToString();
                textContentLookaheadDays.Text          = siteConfig.ContentLookaheadDays.ToString();
                textMainMaxDaysInRss.Text              = siteConfig.RssDayCount.ToString();
                textMainMaxEntriesInRss.Text           = siteConfig.RssMainEntryCount.ToString();
                textOtherMaxEntriesInRss.Text          = siteConfig.RssEntryCount.ToString();
                checkAlwaysIncludeContentInRSS.Checked = siteConfig.AlwaysIncludeContentInRSS;
                checkEnableRSSItemFooter.Checked       = siteConfig.EnableRssItemFooters;
                textRSSItemFooter.Text                 = siteConfig.RssItemFooter;
                checkPop3Enabled.Checked               = siteConfig.EnablePop3;
                textPop3Interval.Text                  = siteConfig.Pop3Interval.ToString();
                textPop3Server.Text                    = siteConfig.Pop3Server;
                textPop3SubjectPrefix.Text             = siteConfig.Pop3SubjectPrefix;
                textPop3Username.Text                  = siteConfig.Pop3Username;
                textPop3Password.Text                  = passwordPlaceHolder;
                textPop3PasswordRepeat.Text            = passwordPlaceHolder;
                textRoot.Text                                       = siteConfig.Root;
                textSmtpServer.Text                                 = siteConfig.SmtpServer;
                textSmtpPort.Text                                   = siteConfig.SmtpPort.ToString();
                checkUseSSLForSMTP.Checked                          = siteConfig.UseSSLForSMTP;
                textNotificationEmailAddress.Text                   = siteConfig.NotificationEMailAddress;
                textSubtitle.Text                                   = siteConfig.Subtitle;
                textSmtpServer.Text                                 = siteConfig.SmtpServer;
                checkEnableCoComment.Checked                        = siteConfig.EnableCoComment;
                checkComments.Checked                               = siteConfig.SendCommentsByEmail;
                checkPingbacks.Checked                              = siteConfig.SendPingbacksByEmail;
                checkReferrals.Checked                              = siteConfig.SendReferralsByEmail;
                checkPosts.Checked                                  = siteConfig.SendPostsByEmail;
                checkTrackbacks.Checked                             = siteConfig.SendTrackbacksByEmail;
                checkShowCommentCounters.Checked                    = siteConfig.ShowCommentCount;
                checkEnableAutoPingback.Checked                     = siteConfig.EnableAutoPingback;
                checkEnableBloggerApi.Checked                       = siteConfig.EnableBloggerApi;
                checkEnableComments.Checked                         = siteConfig.EnableComments;
                checkEnableCommentApi.Checked                       = siteConfig.EnableCommentApi;
                checkShowCommentsWhenViewingEntry.Checked           = siteConfig.ShowCommentsWhenViewingEntry;
                checkEnableConfigEditService.Checked                = siteConfig.EnableConfigEditService;
                checkEnableEditService.Checked                      = siteConfig.EnableEditService;
                checkEnableAutoSave.Checked                         = siteConfig.EnableAutoSave;
                checkEnablePingbackService.Checked                  = siteConfig.EnablePingbackService;
                checkEnableTrackbackService.Checked                 = siteConfig.EnableTrackbackService;
                checkEnableClickThrough.Checked                     = siteConfig.EnableClickThrough;
                checkEnableAggregatorBugging.Checked                = siteConfig.EnableAggregatorBugging;
                checkXssEnabled.Checked                             = siteConfig.EnableXSSUpstream;
                textXssEndpoint.Text                                = siteConfig.XSSUpstreamEndpoint;
                textXssInterval.Text                                = siteConfig.XSSUpstreamInterval.ToString();
                textXssPassword.Text                                = passwordPlaceHolder;
                textXssPasswordRepeat.Text                          = passwordPlaceHolder;
                textXssUsername.Text                                = siteConfig.XSSUpstreamUsername;
                textXssRssFilename.Text                             = siteConfig.XSSRSSFilename;
                checkPop3InlineAttachedPictures.Checked             = siteConfig.Pop3InlineAttachedPictures;
                textPop3AttachedPicturesPictureThumbnailHeight.Text = siteConfig.Pop3InlinedAttachedPicturesThumbHeight.ToString();
                mailDeletionAll.Checked                             = siteConfig.Pop3DeleteAllMessages;
                mailDeletionProcessed.Checked                       = !siteConfig.Pop3DeleteAllMessages;
                logIgnoredEmails.Checked                            = siteConfig.Pop3LogIgnoredEmails;
                checkShowItemDescriptionInAggregatedViews.Checked   = siteConfig.ShowItemDescriptionInAggregatedViews;
                checkEnableStartPageCaching.Checked                 = siteConfig.EnableStartPageCaching;
                checkEnableBlogrollDescription.Checked              = siteConfig.EnableBlogrollDescription;
                checkEntryTitleAsLink.Checked                       = siteConfig.EntryTitleAsLink;
                checkEnableUrlRewriting.Checked                     = siteConfig.EnableUrlRewriting;
                checkEnableCrosspost.Checked                        = siteConfig.EnableCrossposts;
                checkCategoryAllEntries.Checked                     = siteConfig.CategoryAllEntries;
                checkReferralUrlBlacklist.Checked                   = siteConfig.EnableReferralUrlBlackList;
                textReferralBlacklist.Text                          = siteConfig.ReferralUrlBlackList;
                checkCaptchaEnabled.Checked                         = siteConfig.EnableCaptcha;
                checkReferralBlacklist404s.Checked                  = siteConfig.EnableReferralUrlBlackList404s;
                textRSSChannelImage.Text                            = siteConfig.ChannelImageUrl;
                checkEnableTitlePermaLink.Checked                   = siteConfig.EnableTitlePermaLink;
                checkEnableTitlePermaLinkUnique.Checked             = siteConfig.EnableTitlePermaLinkUnique;
                checkEnableTitlePermaLinkSpaces.Checked             = siteConfig.EnableTitlePermaLinkSpaces;
                checkEnableEncryptLoginPassword.Checked             = siteConfig.EncryptLoginPassword;
                checkEnableSmtpAuthentication.Checked               = siteConfig.EnableSmtpAuthentication;
                textSmtpUsername.Text                               = siteConfig.SmtpUserName;
                textSmtpPassword.Text                               = passwordPlaceHolder;
                textRssLanguage.Text                                = siteConfig.RssLanguage;
                checkEnableSearchHighlight.Checked                  = siteConfig.EnableSearchHighlight;
                checkEnableEntryReferral.Checked                    = siteConfig.EnableEntryReferrals;
                textFeedBurnerName.Text                             = siteConfig.FeedBurnerName;
                checkUseFeedScheme.Checked                          = siteConfig.UseFeedSchemeForSyndication;
                checkLogBlockedReferrals.Checked                    = siteConfig.LogBlockedReferrals;

                //populate the title space replacement options
                dropDownTitlePermalinkReplacementCharacter.Items.Clear();//in casee someone adds them in the ascx
                foreach (string s in TitleMapperModule.TitlePermalinkSpaceReplacementOptions)
                {
                    dropDownTitlePermalinkReplacementCharacter.Items.Add(s);
                }
                dropDownTitlePermalinkReplacementCharacter.SelectedValue = siteConfig.TitlePermalinkSpaceReplacement;

                checkSpamBlockingEnabled.Checked = siteConfig.EnableSpamBlockingService;
                textSpamBlockingApiKey.Text      = siteConfig.SpamBlockingServiceApiKey;
                optionSpamHandling.SelectedValue = siteConfig.EnableSpamModeration ? SPAM_OPTION_SAVE : SPAM_OPTION_DELETE;

                // setup the checkbox list to select which tags to allow
                checkBoxListAllowedTags.DataSource     = siteConfig.AllowedTags;
                checkBoxListAllowedTags.DataTextField  = "Name";
                checkBoxListAllowedTags.DataValueField = "Name";

                // enable comment moderation
                checkCommentsRequireApproval.Checked = siteConfig.CommentsRequireApproval;

                // allow html and comments
                checkAllowHtml.Checked = siteConfig.CommentsAllowHtml;

                // populate from config - Gravatar
                GravatarPopulateForm();

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                checkAttemptToHtmlTidyContent.Checked = siteConfig.HtmlTidyContent;
                checkResolveCommenterIP.Checked       = siteConfig.ResolveCommenterIP;

                //if ( siteConfig.EnableCommentDays )
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //}
                //else
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                //if ( siteConfig.EnableCommentDays )
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //}
                //else
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // email daily report
                checkDailyReport.Text    = resmgr.GetString("text_daily_activity_report");
                checkDailyReport.Checked = siteConfig.EnableDailyReportEmail;

                WindowsTimeZoneCollection timeZones = WindowsTimeZone.TimeZones;
                foreach (WindowsTimeZone tz in timeZones)
                {
                    listTimeZones.Items.Add(new ListItem(tz.DisplayName, tz.ZoneIndex.ToString()));
                }
                listTimeZones.SelectedValue = siteConfig.DisplayTimeZoneIndex.ToString();
                checkUseUTC.Checked         = !siteConfig.AdjustDisplayTimeZone;

                //FIX: hardcoded path
                ThemeDictionary themes = BlogTheme.Load(SiteUtilities.MapPath("themes"));
                foreach (BlogTheme theme in themes.Values)
                {
                    // setting the selected item like this instead of
                    // using    listThemes.SelectedValue = siteConfig.Theme;
                    // prevents the page from breaking.

                    ListItem item = new ListItem(theme.Title, theme.Name);
                    if (item.Value == siteConfig.Theme)
                    {
                        item.Selected = true;
                    }
                    listThemes.Items.Add(item);
                }

                textTitle.Text = siteConfig.Title;

                checkBoxListPingServices.DataSource     = PingServiceCollection;
                checkBoxListPingServices.DataTextField  = "Hyperlink";
                checkBoxListPingServices.DataValueField = "Endpoint";

                drpEntryEditControl.Items.Clear();
                foreach (string potentialAssembly in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll"))
                {
                    try
                    {
                        Assembly a = Assembly.LoadFrom(potentialAssembly);
                        foreach (Type potentialType in a.GetTypes())
                        {
                            if (potentialType.BaseType == typeof(EditControlAdapter))
                            {
                                drpEntryEditControl.Items.Add(new ListItem(potentialType.Name, potentialType.AssemblyQualifiedName));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //swallow
                    }
                }

                //Reasonable default
                if (string.IsNullOrEmpty(siteConfig.EntryEditControl))
                {
                    siteConfig.EntryEditControl = typeof(TinyMCEAdapter).AssemblyQualifiedName;
                }
                DataBind();

                ListItem li = drpEntryEditControl.Items.FindByText(siteConfig.EntryEditControl);
                if (li != null)
                {
                    li.Selected = true;
                }
                else
                {
                    drpEntryEditControl.SelectedIndex = 0;
                }

                foreach (PingService ps in siteConfig.PingServices)
                {
                    checkBoxListPingServices.Items.FindByValue(ps.Endpoint).Selected = true;
                }

                foreach (ValidTag tag in siteConfig.AllowedTags)
                {
                    checkBoxListAllowedTags.Items.FindByValue(tag.Name).Selected = tag.IsAllowed;
                }

                //check for Smtp permission
                if (SecurityManager.IsGranted(new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort)))
                {
                    phSmtpTrustWarning.Visible = false;
                }
                else
                {
                    phSmtpTrustWarning.Visible = true;
                }

                //check for Socket permission
                SocketPermission sp;
                if (String.IsNullOrEmpty(textPop3Server.Text))
                {
                    sp = new SocketPermission(PermissionState.Unrestricted);
                }
                else
                {
                    sp = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, textPop3Server.Text, 110);
                }

                if (SecurityManager.IsGranted(sp))
                {
                    phPop3TrustWarning.Visible = false;
                }
                else
                {
                    phPop3TrustWarning.Visible = true;
                }

                // georss stuff
                checkEnableGeoRss.Checked     = siteConfig.EnableGeoRss;
                textGoogleMapsApi.Text        = siteConfig.GoogleMapsApiKey;
                textDefaultLatitude.Text      = siteConfig.DefaultLatitude.ToString(CultureInfo.InvariantCulture);
                textDefaultLongitude.Text     = siteConfig.DefaultLongitude.ToString(CultureInfo.InvariantCulture);
                checkEnableGoogleMaps.Checked = siteConfig.EnableGoogleMaps;
                checkEnableDefaultLatLongForNonGeoCodedPosts.Checked = siteConfig.EnableDefaultLatLongForNonGeoCodedPosts;

                // OpenId
                chkAllowOpenIdAdmin.Checked          = siteConfig.AllowOpenIdAdmin;
                chkAllowOpenIdCommenter.Checked      = siteConfig.AllowOpenIdComments;
                chkBypassSpamOpenIdCommenter.Checked = siteConfig.BypassSpamOpenIdComment;
            } // end if !postback

            //enable list controls that may have been enabled client-side
            //in 2.0 if they are not enable we won't get there postback data
            checkBoxListAllowedTags.Enabled = true;
            dropGravatarRating.Enabled      = true;
        }
Beispiel #2
0
        public async Task ConnectToSocketServerAsync(string RPiIPAddress, int portNumber)
        {
            IPAddress clientIPAddress = null;

            if (!IPAddress.TryParse(_computerIPAddress.ToString(), out clientIPAddress))
            {
                throw new FormatException("Invalid Computer IP Address");
            }
            IPAddress serverIPAddress = null;

            if (!IPAddress.TryParse(RPiIPAddress, out serverIPAddress))
            {
                throw new FormatException("Invalid RPi IP Address");
            }

            try
            {
                // Create one SocketPermission for socket access restrictions
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,         // Connection permission
                    TransportType.Tcp,             // Defines transport types
                    _computerIPAddress.ToString(), // Gets the IP addresses
                    SocketPermission.AllPorts      // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry(clientIPAddress.ToString());

                // Gets first IP address associated with a localhost
                IPAddress ipAddr = ipHost.AddressList.Where(ip => ip.IsIPv4MappedToIPv6 == false &&
                                                            ip.IsIPv6LinkLocal == false && ip.IsIPv6Multicast == false && ip.IsIPv6SiteLocal == false &&
                                                            ip.IsIPv6Teredo == false).FirstOrDefault(); //get the IPv4 address

                //// Creates a network endpoint
                //IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 51717);

                IPEndPoint ipRemoteEndPoint = CreateIPEndPoint(string.Format("{0}:{1}", serverIPAddress.ToString(), portNumber));

                // Create one Socket object to setup Tcp connection
                if (_senderSock == null)
                {
                    _senderSock = new Socket(
                        ipAddr.AddressFamily, // Specifies the addressing scheme
                        SocketType.Stream,    // The type of socket
                        ProtocolType.Tcp      // Specifies the protocols
                        )
                    {
                        NoDelay = false   // Using the Nagle algorithm
                    };
                }

                // Establishes a connection to a remote host
                await _senderSock.ConnectAsync(ipRemoteEndPoint);

                Debug.WriteLine("Socket connected to " + _senderSock.RemoteEndPoint.ToString());
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.ToString());
            }
        }
Beispiel #3
0
        public void SetupPermissions()
        {
            var permission = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, Dns.GetHostName(), 11000);

            permission.Demand();
        }
        // --
        // -- Constructor
        // --
        public CommunicationService()
        {
            try
            {
                permission = new SocketPermission(
                    NetworkAccess.Accept,     // Allowed to accept connections
                    TransportType.Tcp,        // Defines transport types
                    "",                       // The IP addresses of local host
                    SocketPermission.AllPorts // Specifies all ports
                    );

                XmlAccess.parseConfiguration();

                //Console.WriteLine("Enabled : " + enabled);
                Console.WriteLine(this.ipAddr);
                // Sets port
                this.port = 4510;


                // Listening Socket object
                sListener = null;

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost
                // FIXME the localhost ip adress is not alway in this place in the array
                for (int i = 0; i < ipHost.AddressList.Length; i++)
                {
                    if (ipHost.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        this.ipAddr = ipHost.AddressList[i];
                    }
                }

                // Creates a network endpoint
                ipEndPoint = new IPEndPoint(ipAddr, port);


                // Create one Socket object to listen the incoming connection
                sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );

                // Associates a Socket with a local endpoint
                sListener.Bind(ipEndPoint);
            }
            catch (Exception exc) { Console.WriteLine("Communicationservice : " + exc); }


            try
            {
                // Length of the pending connections queue
                sListener.Listen(10);

                // Begins an asynchronous operation to accept an attempt
                AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
                sListener.BeginAccept(aCallback, sListener);
            }
            catch (Exception exc) { Console.WriteLine("Communicationservice listen : " + exc); }
        }
Beispiel #5
0
    static void Main(string[] args)
    {
        // Creates one SocketPermission object for access restrictions
        SocketPermission permission = new SocketPermission(
            NetworkAccess.Accept,     // Allowed to accept connections
            TransportType.Tcp,        // Defines transport types
            "",                       // The IP addresses of local host
            SocketPermission.AllPorts // Specifies all ports
            );

        // Listening Socket object
        Socket sListener = null;

        try
        {
            // Ensures the code to have permission to access a Socket
            permission.Demand();

            // Resolves a host name to an IPHostEntry instance
            IPHostEntry ipHost = Dns.GetHostEntry("");

            // Gets first IP address associated with a localhost
            IPAddress ipAddr = ipHost.AddressList[0];

            // Creates a network endpoint
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);

            // Create one Socket object to listen the incoming connection
            sListener = new Socket(
                ipAddr.AddressFamily,
                SocketType.Stream,
                ProtocolType.Tcp
                );

            // Associates a Socket with a local endpoint
            sListener.Bind(ipEndPoint);

            // Places a Socket in a listening state and specifies the maximum
            // Length of the pending connections queue
            sListener.Listen(10);

            Console.WriteLine("Waiting for a connection on port {0}",
                ipEndPoint);

            // Begins an asynchronous operation to accept an attempt
            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
            sListener.BeginAccept(aCallback, sListener);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.ToString());
            return;
        }

        Console.WriteLine("Press the Enter key to exit ...");
        Console.ReadLine();

        if (sListener.Connected)
        {
            sListener.Shutdown(SocketShutdown.Receive);
            sListener.Close();
        }
    }
        public static Socket Connect(string str)
        {
            IPAddress ipAddr = null;

            try
            {
                // Create one SocketPermission for socket access restrictions
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission
                    TransportType.Tcp,        // Defines transport types
                    "",                       // Gets the IP addresses
                    SocketPermission.AllPorts // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                //IPHostEntry ipHost = Dns.GetHostEntry("");
                IPHostEntry ipHost = Dns.GetHostEntry(str);  //o Dns.Resolve("host.contoso.com");
                //IPHostEntry ipHost = Dns.GetHostEntry("localhost");  //o Dns.Resolve("host.contoso.com");

                // Gets first IP address associated with a localhost
                ipAddr = ipHost.AddressList[0];

                //check if alredy connected
                if (serverConnected.Contains(ipAddr))
                {
                    throw new Exception("Impossible to connect to server already connected");
                }
                else
                {
                    serverConnected.Add(ipAddr);
                }

                // Creates a network endpoint
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);

                // Create one Socket object to setup Tcp connection
                Socket senderSock = new Socket(
                    ipAddr.AddressFamily, // Specifies the addressing scheme
                    SocketType.Stream,    // The type of socket
                    ProtocolType.Tcp      // Specifies the protocols
                    );

                senderSock.NoDelay = false;   // Using the Nagle algorithm,serve???

                // Establishes a connection to a remote host
                senderSock.Connect(ipEndPoint);

                //MessageBox.Show("Client connected to : " + ipEndPoint, "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information);
                return(senderSock);
            }
            catch (Exception ex)
            {
                if (ex.Message != "Impossible to connect to server already connected" && ipAddr != null)
                {
                    removeFromList(ipAddr);
                }
                throw;
            }
        }
Beispiel #7
0
    public static void MySocketPermission()
    {
//<Snippet1>
//<Snippet2>

        // Creates a SocketPermission restricting access to and from all URIs.
        SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

        // The socket to which this permission will apply will allow connections from www.contoso.com.
        mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com", 11000);

        // Creates a SocketPermission which will allow the target Socket to connect with www.southridgevideo.com.
        SocketPermission mySocketPermission2 =
            new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "www.southridgevideo.com", 11002);

        // Creates a SocketPermission from the union of two SocketPermissions.
        SocketPermission mySocketPermissionUnion =
            (SocketPermission)mySocketPermission1.Union(mySocketPermission2);

        // Checks to see if the union was successfully created by using the IsSubsetOf method.
        if (mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) &&
            mySocketPermission2.IsSubsetOf(mySocketPermissionUnion))
        {
            Console.WriteLine("This union contains permissions from both mySocketPermission1 and mySocketPermission2");

            // Prints the allowable accept URIs to the console.
            Console.WriteLine("This union accepts connections on :");

            IEnumerator myEnumerator = mySocketPermissionUnion.AcceptList;
            while (myEnumerator.MoveNext())
            {
                Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
            }

            // Prints the allowable connect URIs to the console.
            Console.WriteLine("This union permits connections to :");

            myEnumerator = mySocketPermissionUnion.ConnectList;
            while (myEnumerator.MoveNext())
            {
                Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
            }
        }

//</Snippet2>
//<Snippet3>

        // Creates a SocketPermission from the intersect of two SocketPermissions.
        SocketPermission mySocketPermissionIntersect =
            (SocketPermission)mySocketPermission1.Intersect(mySocketPermissionUnion);

        // mySocketPermissionIntersect should now contain the permissions of mySocketPermission1.
        if (mySocketPermission1.IsSubsetOf(mySocketPermissionIntersect))
        {
            Console.WriteLine("This is expected");
        }
        // mySocketPermissionIntersect should not contain the permissios of mySocketPermission2.
        if (mySocketPermission2.IsSubsetOf(mySocketPermissionIntersect))
        {
            Console.WriteLine("This should not print");
        }


//</Snippet3>

//<Snippet4>
// Creates a copy of the intersect SocketPermission.
        SocketPermission mySocketPermissionIntersectCopy =
            (SocketPermission)mySocketPermissionIntersect.Copy();

        if (mySocketPermissionIntersectCopy.Equals(mySocketPermissionIntersect))
        {
            Console.WriteLine("Copy successfull");
        }

//</Snippet4>

        // Converts a SocketPermission to XML format and then immediately converts it back to a SocketPermission.
        mySocketPermission1.FromXml(mySocketPermission1.ToXml());


        // Checks to see if permission for this socket resource is unrestricted.  If it is, then there is no need to
        // demand that permissions be enforced.
        if (mySocketPermissionUnion.IsUnrestricted())
        {
            //Do nothing.  There are no restrictions.
        }
        else
        {
            // Enforces the permissions found in mySocketPermissionUnion on any Socket Resources used below this statement.
            mySocketPermissionUnion.Demand();
        }

        IPHostEntry myIpHostEntry   = Dns.Resolve("www.contoso.com");
        IPEndPoint  myLocalEndPoint = new IPEndPoint(myIpHostEntry.AddressList[0], 11000);

        Socket s = new Socket(myLocalEndPoint.Address.AddressFamily,
                              SocketType.Stream,
                              ProtocolType.Tcp);

        try{
            s.Connect(myLocalEndPoint);
        }
        catch (Exception e) {
            Console.WriteLine("Exception Thrown: " + e.ToString());
        }

        // Perform all socket operations in here.

        s.Close();
//</Snippet1>
    }
    public String GetDate()
    {
// <Snippet1>
// <Snippet2>
// <Snippet3>
// <Snippet4>
// <Snippet5>
// <Snippet6>
        SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

        // Create a 'SocketPermission' object for two ip addresses.
        SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
        SecurityElement  securityElement1  = socketPermission2.ToXml();
        // 'SocketPermission' object for 'Connect' permission
        SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
        // Format to specify ip address are <ip-address>#<port>#<transport-type>
        // First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
        // for 'All'ports for the ip-address.
        SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
        // Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
        // for 'All' ports for the ip-address.
        SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");

        securityElement2.AddChild(securityElement3);
        securityElement2.AddChild(securityElement4);
        securityElement1.AddChild(securityElement2);

        // Obtain a 'SocketPermission' object using 'FromXml' method.
        socketPermission2.FromXml(securityElement1);

        Console.WriteLine("\nDisplays the result of FromXml method : \n");
        Console.WriteLine(socketPermission2.ToString());

        // Create another 'SocketPermission' object with two ip addresses.
        // First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All' ports for the ip-address.
        SocketPermission socketPermission3 =
            new SocketPermission(NetworkAccess.Connect,
                                 TransportType.All,
                                 "192.168.144.238",
                                 SocketPermission.AllPorts);

        // Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for 'All' ports for the ip-address.
        socketPermission3.AddPermission(NetworkAccess.Connect,
                                        TransportType.All,
                                        "192.168.144.239",
                                        SocketPermission.AllPorts);

        Console.WriteLine("Displays the result of AddPermission method : \n");
        Console.WriteLine(socketPermission3.ToString());

        // Find the intersection between two 'SocketPermission' objects.
        socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

        Console.WriteLine("Displays the result of Intersect method :\n ");
        Console.WriteLine(socketPermission1.ToString());

        // Demand that the calling method have the requsite socket permission.
        socketPermission1.Demand();
// </Snippet6>
// </Snippet5>
// </Snippet4>
// </Snippet3>
// </Snippet2>
// </Snippet1>
        // Get the current date from the remote date server.
        try {
            int    bytesReceived;
            byte[] getByte = new byte[100];
            serverSocket.Connect(new IPEndPoint(serverAddress, serverPort));
            bytesReceived = serverSocket.Receive(getByte, getByte.Length, 0);
            return(asciiEncoding.GetString(getByte, 0, bytesReceived));
        }
        catch (Exception e)
        {
            Console.WriteLine("\nException raised : {0}", e.Message);
            return("");
        }
    }
Beispiel #9
0
        public void Run()
        {
            while (MainForm.LThread != null && MainForm.MainThread.IsAlive)
            {
                do
                {
                    object[] retobj = Networking.ReceiveUpdates();
                    if (retobj == null)                          //2014.12.05.
                    {
                        return;                                  //2014.12.05. - Leállt a program
                    }
                    byte[]     resp     = (byte[])retobj[0];     //2014.10.24.
                    IPEndPoint remoteEP = (IPEndPoint)retobj[1]; //2014.10.24.
                    if (resp == null)
                    {
                        break;
                    }
                    byte isresponse;                                                                                              //2014.09.15.
                    Networking.UpdateType updatetype;                                                                             //2014.09.15.
                    int    keyversion;                                                                                            //2014.09.15.
                    int    port;                                                                                                  //2014.12.19.
                    int    userid;                                                                                                //2014.09.15.
                    byte[] data;                                                                                                  //2014.09.15.
                    Networking.ParsePacket(resp, out isresponse, out updatetype, out keyversion, out port, out userid, out data); //2014.09.15.
                    //if (!UserInfo.IPs.Any(entry=>entry.IP==remoteEP) && updatetype != Networking.UpdateType.LoginUser) //2014.10.24.
                    //if (!UserInfo.IPs.Any(entry => entry.IP == remoteEP) && updatetype != Networking.UpdateType.LoginUser) //2014.11.23
                    if (!UserInfo.IPs.Any(entry => entry.Address.Equals(remoteEP.Address)) && //2014.12.19. - A port nem ugyanaz, ráadásul a == nem hívja meg a .Equals metódust
                        updatetype != Networking.UpdateType.LoginUser

                        /*&& updatetype != Networking.UpdateType.CheckConn
                        *  && updatetype != Networking.UpdateType.RequestConn
                        *  && updatetype != Networking.UpdateType.MakeConn
                        *  && updatetype != Networking.UpdateType.MakeConn2*/)
                    {
                        break;
                    }
                    //bool x = UserInfo.IPs.Single().IP.Address.Equals(remoteEP.Address);
                    if (updatetype == Networking.UpdateType.ListUpdate)
                    {
                        //Networking.ParseUpdateInfo(new byte[][] { data }); //2014.09.15.
                        Networking.ParseUpdateInfo(new byte[][] { resp }); //2014.12.22. - A funkció az egész packet-re számít, nem csak a data-ra
                    }
                    else if (updatetype == Networking.UpdateType.UpdateMessages)
                    {
                        string[]        response = Networking.GetStrings(data, 0);
                        string[]        tmp      = response[0].Split(',');
                        List <UserInfo> tmp2     = new List <UserInfo>();
                        tmp2.Add(UserInfo.Select(userid));                                       //Adja hozzá a küldőt is
                        tmp2.AddRange(tmp.Select(entry => UserInfo.Select(Int32.Parse(entry)))); //2014.10.24.
                        //if (tmp2.All(entry => !UserInfo.Select(entry).IsPartner)) //2014.10.24.
                        if (tmp2.All(entry => !entry.IsPartner))                                 //2014.10.31.
                        {
                            break;                                                               //Ha a beszélgetésben nincs ismerőse, akkor nem foglalkozik vele
                        }
                        var cf = ChatPanel.GetChatFormByUsers(tmp2);
                        if (cf == null)
                        {
                            Program.MainF.Invoke((MethodInvoker) delegate
                            {
                                ChatPanel.ChatWindows.Add(new ChatPanel());
                                cf = ChatPanel.ChatWindows[ChatPanel.ChatWindows.Count - 1];
                                cf.ChatPartners.AddRange(tmp2);
                                cf.Init();
                            });
                        }
                        //0 - Résztvevők; 1 - Üzenet; 2 - Üzenetküldés időpontja
                        string[] cmd = response[1].Split(' ');
                        switch (cmd[0])
                        {
                        case "//sendfile":
                            string[]  ipportname   = cmd[1].Split(':');
                            IPAddress ipAddr       = IPAddress.Parse(ipportname[0]);
                            var       permission   = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);
                            var       ipEndPoint   = new IPEndPoint(ipAddr, Int32.Parse(ipportname[1]));
                            var       receiverSock = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            receiverSock.Connect(ipEndPoint);
                            var ns = new NetworkStream(receiverSock);
                            var fs = new FileStream(ipportname[2], FileMode.Create);
                            break;
                        }
                        cf.TMessage = "\n" + ((userid == CurrentUser.UserID) ? CurrentUser.Name : UserInfo.Select(userid).Name) + " " + Language.Translate("said") + " (" + Program.UnixTimeToDateTime(response[2]).ToString("yyyy.MM.dd. HH:mm:ss") + "):\n" + response[1] + "\n";
                        Program.MainF.Invoke(new LoginForm.MyDelegate(cf.SetThreadValues));
                    }
                    else if (updatetype == Networking.UpdateType.LoginUser)
                    {
                        string tmpresp = Networking.SendRequest("checkuser", userid.ToString(), 0, true); //2014.09.19.
                        if (tmpresp == "Fail")
                        {
                            break; //Nem küld el neki semmit, hanem újra várja a packet-eket
                        }
                        else if (tmpresp != "Success")
                        {
                            MessageBox.Show("LoginUser:\n" + tmpresp);
                            break;
                        }

                        //int iplen = BitConverter.ToInt32(data, 0);
                        //string ip = Encoding.Unicode.GetString(data, 4, iplen);
                        //IPAddress ip = IPAddress.Parse(Encoding.Unicode.GetString(data, 4, iplen));

                        /*if (!Storage.Settings["ips"].Contains(ip))
                         *  Storage.Settings["ips"] += ";" + ip;*/
                        //var ep = new IPEndPoint(ip, UserInfo.GetPortForIP(ip)); //2014.11.15.
                        //var ep = new IPEndPoint(ip, port); //2014.12.19.
                        var ep = new IPEndPoint(remoteEP.Address, port);
                        //if (!UserInfo.IPs.Any(entry=>entry.IP==ep))
                        if (!UserInfo.IPs.Any(entry => entry == ep))
                        {
                            UserInfo.IPs.Add(ep);
                        }
                        string retstr = "";
                        //for (int i = 4 + iplen; i + 8 < resp.Length; i += 8)
                        for (int i = 0; i + 8 < data.Length; i += 8)
                        {
                            int uid   = BitConverter.ToInt32(data, i);
                            int utime = BitConverter.ToInt32(data, i + 4);
                            if (Storage.LoggedInSettings.ContainsKey("userinfo_" + uid + "_updatetime") && Int32.Parse(Storage.LoggedInSettings["userinfo_" + uid + "_updatetime"]) > utime)
                            {
                                retstr += uid + "_name=" + Storage.LoggedInSettings["userinfo_" + uid + "_name"] + "\n";
                                retstr += uid + "_message=" + Storage.LoggedInSettings["userinfo_" + uid + "_message"] + "\n";
                                retstr += uid + "_state=" + Storage.LoggedInSettings["userinfo_" + uid + "_state"] + "\n";
                                retstr += uid + "_username="******"userinfo_" + uid + "_username"] + "\n";
                                retstr += uid + "_email=" + Storage.LoggedInSettings["userinfo_" + uid + "_email"] + "\n";
                                retstr += uid + "_ispartner=" + Storage.LoggedInSettings["userinfo_" + uid + "_ispartner"] + "\n";
                                //retstr += uid + "_lastupdate=" + Program.DateTimeToUnixTime(DateTime.Now);
                                if (uid != CurrentUser.UserID)                                                                    //2014.11.29.
                                {
                                    retstr += uid + "_lastupdate=" + Storage.LoggedInSettings["userinfo_" + uid + "_lastupdate"]; //2014.11.29. - Arra az időpontra állítsa, amikor ő kapta a frissítést, így ez elvileg az eredeti frissítés időpontját mutatja kb. - Ezért a sajátját biztosan frissen kell tartani
                                }
                                else
                                {
                                    retstr += uid + "_lastupdate=" + Program.DateTimeToUnixTime(DateTime.Now);
                                }
                                //if (i + 1 != (resp.Length - 9) / 8)
                                if (i + 16 < data.Length)
                                {
                                    retstr += "\n";
                                }
                            }
                        }
                        UserInfo.Select(userid).State = 1;
                        Networking.SendUpdate(Networking.UpdateType.LoginUser, Encoding.Unicode.GetBytes(retstr), true);
                    }
                    else if (updatetype == Networking.UpdateType.LogoutUser)
                    { //2014.08.31. 0:32
                        int    len   = BitConverter.ToInt32(data, 0);
                        string ipstr = Encoding.Unicode.GetString(data, 4, len);
                        //Storage.Settings["ips"] = Storage.Settings["ips"].Remove(Storage.Settings["ips"].IndexOf(ipstr), ipstr.Length); //2014.09.22.
                        //var ip = IPAddress.Parse(ipstr);
                        string[] ips = ipstr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        var      ip  = ips.Select(entry => IPAddress.Parse(entry));
                        //UserInfo.IPs.RemoveWhere(entry => entry.IP.Address == ip && entry.IP.Port == UserInfo.GetPortForIP(entry.IP.Address)); //2014.11.15.
                        UserInfo.IPs.RemoveWhere(entry => entry.Address == ip && entry.Port == port); //2014.11.15. - Port: 2014.12.19.
                    }
                    else if (updatetype == Networking.UpdateType.SetKey)                              //2014.09.09.
                    {                                                                                 //2014.09.22.
                        CurrentUser.KeyIndex = BitConverter.ToInt32(data, 0);
                    }
                    else if (updatetype == Networking.UpdateType.GetImage) //2014.11.01. 0:53
                    {
                        string      tmp           = Path.GetTempPath();
                        List <byte> sendb         = new List <byte>();
                        int         user          = BitConverter.ToInt32(data, 0);
                        int         picupdatetime = BitConverter.ToInt32(data, 4);
                        //int thispicupdatetime = UserInfo.Select(user).PicUpdateTime;
                        int      thispicupdatetime = 0;
                        UserInfo userinfo          = UserInfo.Select(user);
                        if (userinfo != null)
                        {
                            thispicupdatetime = UserInfo.Select(user).PicUpdateTime;
                        }
                        if (thispicupdatetime > picupdatetime)
                        {
                            sendb.AddRange(BitConverter.GetBytes(thispicupdatetime));
                            sendb.AddRange(File.ReadAllBytes(tmp + "\\MSGer.tk\\pictures\\" + user + ".png"));
                        }
                        Networking.SendUpdate(Networking.UpdateType.GetImage, sendb.ToArray(), true); //2014.11.23.
                    }

                    /*else if (updatetype == Networking.UpdateType.CheckConn)
                     * { //2014.11.23.
                     *  Networking.SendUpdate(Networking.UpdateType.CheckConn, new byte[] { 0x01 }, true, new IPEndPoint(remoteEP.Address, port));
                     * }
                     * else if (updatetype == Networking.UpdateType.RequestConn)
                     * { //2014.11.23.
                     *  string[] s = Encoding.Unicode.GetString(data).Split(':');
                     *  var secondEP = new IPEndPoint(IPAddress.Parse(s[0]), Int32.Parse(s[1]));
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn, Encoding.Unicode.GetBytes(secondEP.ToString()), false, remoteEP); //Elküldi, hogy próbálkozzon kapcsolódni
                     *  Networking.SendUpdate(Networking.UpdateType.RequestConn, new byte[] { 0x01 }, true); //Majd válaszol, hogy ő is próbálkozhat
                     * }
                     * else if (updatetype == Networking.UpdateType.MakeConn)
                     * { //2014.11.23.
                     *  string[] s = Encoding.Unicode.GetString(data).Split(':');
                     *  var secondEP = new IPEndPoint(IPAddress.Parse(s[0]), Int32.Parse(s[1]));
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn2, new byte[] { 0x01 }, false, secondEP); //Próbálkoziks
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn, new byte[] { 0x01 }, true); //Válaszol, hogy ne várjon rá a szerver
                     * }
                     * else if (updatetype == Networking.UpdateType.MakeConn2)
                     * { //2014.11.23.
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn2, new byte[] { 0x01 }, true); //Végzett
                     * }*/
                } while (false);
            }
        }
Beispiel #10
0
        public Client()
        {
            var perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);

            perm.Demand();
        }
Beispiel #11
0
    public String GetDate()
    {
        SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

        // Create a 'SocketPermission' object for two ip addresses.
        SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
        SecurityElement  securityElement4  = socketPermission2.ToXml();
        // 'SocketPermission' object for 'Connect' permission
        SecurityElement securityElement1 = new SecurityElement("ConnectAccess");
        // Format to specify ip address are <ip-address>#<port>#<transport-type>
        // First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All' ports for the ip-address.
        SecurityElement securityElement2 = new SecurityElement("URI", "192.168.144.238#-1#3");
        // Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and for 'All' ports for the ip-address.
        SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.240#-1#3");

        securityElement1.AddChild(securityElement2);
        securityElement1.AddChild(securityElement3);
        securityElement4.AddChild(securityElement1);

        // Obtain a 'SocketPermission' object using 'FromXml' method.
        socketPermission2.FromXml(securityElement4);

        // Create another 'SocketPermission' object with two ip addresses.
        // First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All' ports for the ip-address.
        SocketPermission socketPermission3 =
            new SocketPermission(NetworkAccess.Connect,
                                 TransportType.All,
                                 "192.168.144.238",
                                 SocketPermission.AllPorts);

        // Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for 'All' ports for the ip-address.
        socketPermission3.AddPermission(NetworkAccess.Connect,
                                        TransportType.All,
                                        "192.168.144.239",
                                        SocketPermission.AllPorts);

        Console.WriteLine("\nChecks the Socket permissions using IsUnrestricted method : ");
        if (socketPermission1.IsUnrestricted())
        {
            Console.WriteLine("Socket permission is unrestricted");
        }
        else
        {
            Console.WriteLine("Socket permission is restricted");
        }

        Console.WriteLine();

        Console.WriteLine("Display result of ConnectList property : \n");
        IEnumerator enumerator = socketPermission3.ConnectList;

        while (enumerator.MoveNext())
        {
            Console.WriteLine("The hostname is       : {0}", ((EndpointPermission)enumerator.Current).Hostname);
            Console.WriteLine("The port is           : {0}", ((EndpointPermission)enumerator.Current).Port);
            Console.WriteLine("The Transport type is : {0}", ((EndpointPermission)enumerator.Current).Transport);
        }
        Console.WriteLine("");

        Console.WriteLine("Display Security Elements :\n ");
        PrintSecurityElement(socketPermission2.ToXml(), 0);

        // Get a 'SocketPermission' object which is a union of two other 'SocketPermission' objects.
        socketPermission1 = (SocketPermission)socketPermission3.Union(socketPermission2);

        // Demand that the calling method have the socket permission.
        socketPermission1.Demand();

        // Get the current date from the remote date server.
        try {
            int    bytesReceived;
            byte[] getByte = new byte[100];
            serverSocket.Connect(new IPEndPoint(serverAddress, serverPort));
            bytesReceived = serverSocket.Receive(getByte, getByte.Length, 0);
            return(asciiEncoding.GetString(getByte, 0, bytesReceived));
        }
        catch (Exception e)
        {
            Console.WriteLine("\nException raised : {0}", e.Message);
            return("");
        }
    }
        public ApplicationApplet()
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222

            //- javac
            //"C:\Program Files (x86)\Java\jdk1.7.0_45\bin\javac.exe" -classpath "W:\jDOSBoxAppletWithWarcraft.ApplicationApplet\web\java";release -d release java\jDOSBoxAppletWithWarcraft\ApplicationApplet.java
            //java\jDOSBoxAppletWithWarcraft\ApplicationApplet.java:40: error: cannot assign a value to final variable C_IPX
            //        Config.C_IPX = true;
            //              ^

            // http://jdosbox.sourceforge.net/change.html
            //jdos.misc.setup.Config.C_IPX = true;
            Console.WriteLine(
                new { jdos.misc.setup.Config.C_IPX }
                );

            // http://www.coderanch.com/t/486585/Applets/java/applet-socketpermissions
            // fk, java applets, you are useless!??
            // https://www.java.net/node/666745

            // http://www.experts-exchange.com/Programming/Languages/Java/Q_27992073.html
            // http://www.experts-exchange.com/Programming/Languages/Java/Q_27992073.html

            // https://bugs.openjdk.java.net/browse/JDK-4093502
            var s = new SocketPermission(
                "localhost:213", "listen,resolve"
                );

            Console.WriteLine("SocketPermission getActions " + s.getActions());

            //java.lang.System.getSecurityManager().
            //s.
            //s.
            //java.security.AccessControlException: access denied ("java.net.SocketPermission" "127.0.0.1:4000" "connect,resolve")
            //    at java.security.AccessControlContext.checkPermission(Unknown Source)
            //    at java.security.AccessController.checkPermission(Unknown Source)
            //    at java.lang.SecurityManager.checkPermission(Unknown Source)
            //    at java.lang.SecurityManager.checkConnect(Unknown Source)
            //    at sun.plugin2.applet.SecurityManagerHelper.checkConnectHelper(Unknown Source)
            //    at sun.plugin2.applet.AWTAppletSecurityManager.checkConnect(Unknown Source)
            //    at java.net.DatagramSocket.send(Unknown Source)
            //    at jdos.hardware.IPX.ConnectToServer(IPX.java:956)
            //    at jdos.hardware.IPX.access$1700(IPX.java:25)
            //    at jdos.hardware.IPX$IPXNET.Run(IPX.java:1119)
            //    at jdos.misc.Program$1.call(Program.java:76)
            //    at jdos.Dosbox$1.call(Dosbox.java:75)
            //    at jdos.Dosbox.DOSBOX_RunMachine(Dosbox.java:205)
            //    at jdos.cpu.Callback.CALLBACK_RunRealInt(Callback.java:158)
            //    at jdos.shell.Dos_shell.Execute(Dos_shell.java:755)
            //    at jdos.shell.Dos_shell.DoCommand(Dos_shell.java:633)
            //    at jdos.shell.Dos_shell.ParseLine(Dos_shell.java:173)
            //    at jdos.shell.Dos_shell.Run(Dos_shell.java:98)
            //    at jdos.shell.Shell$5.call(Shell.java:398)
            //    at jdos.misc.setup.Config.StartUp(Config.java:97)
            //    at jdos.gui.MainBase.main(MainBase.java:523)
            //    at jdos.gui.MainApplet.run(MainApplet.java:269)
            //    at java.lang.Thread.run(Unknown Source)
            //IPX: Unable to connect to server
            //IPXSERVER: Connect from 192.168.43.252

            //IPXSERVER: enter IPX_StartServer
            //IPXSERVER: enter IPX_StartServer before getByName
            //IPXSERVER: enter IPX_StartServer before DatagramSocket
            //java.security.AccessControlException: access denied ("java.net.SocketPermission" "localhost:213" "listen,resolve")


            //this.i
            // http://www.vogons.org/viewtopic.php?p=227202

            //You must sign the applet so it can connect to a host other than the one it was loaded from, and either you must use a non-self-signed-certificate or the user must accept the certificate when prompted.
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222
            // http://stackoverflow.com/questions/15074834/java-applet-socket-permission
            // http://stackoverflow.com/questions/10083332/java-applet-accesscontrolexception-access-denied-socketpermission-where-do
            // http://www.khattam.info/solved-java-security-accesscontrolexception-access-denied-java-net-socketpermission-host-connectresolve-2010-03-24.html

            // https://bbs.archlinux.org/viewtopic.php?id=142474
        }
Beispiel #13
0
 public void SetupPermissions()
 {
     _permissions = new SocketPermission(NetworkAccess.Accept,
                                         TransportType.Tcp, "", SocketPermission.AllPorts);
 }
        }// ValidateData

        internal override IPermission GetCurrentPermission()
        {
            // Change cells so we get data committed to the grid
            m_dg.CurrentCell = new DataGridCell(0, 1);
            m_dg.CurrentCell = new DataGridCell(0, 0);

            SocketPermission perm = null;

            if (m_radUnrestricted.Checked == true)
            {
                perm = new SocketPermission(PermissionState.Unrestricted);
            }
            else
            {
                perm = new SocketPermission(PermissionState.None);

                for (int i = 0; i < m_dt.Rows.Count; i++)
                {
                    // Make sure we have a socket permission to add
                    if (m_dg[i, 0] != DBNull.Value && ((String)m_dg[i, 0]).Length > 0)
                    {
                        String sHostname = (String)m_dg[i, 0];
                        int    nPort     = 0;
                        if (m_dg[i, 1] != DBNull.Value && ((String)m_dg[i, 1]).Length > 0)
                        {
                            try
                            {
                                nPort = Int32.Parse((String)m_dg[i, 1]);
                                // Verify the port is valid... note, this is the same logic that
                                // SocketPermission uses

                                if ((nPort >= UInt16.MaxValue || nPort < 0) && nPort != SocketPermission.AllPorts)
                                {
                                    throw new Exception();
                                }
                            }
                            catch (Exception)
                            {
                                MessageBox(String.Format(CResourceStore.GetString("SocketPerm:isbadport"), m_dg[i, 1]),
                                           CResourceStore.GetString("SocketPerm:isbadportTitle"),
                                           MB.ICONEXCLAMATION);
                                return(null);
                            }
                        }
                        else
                        {
                            MessageBox(CResourceStore.GetString("SocketPerm:NeedPort"),
                                       CResourceStore.GetString("SocketPerm:NeedPortTitle"),
                                       MB.ICONEXCLAMATION);
                            return(null);
                        }

                        TransportType tt = 0;

                        if ((bool)m_dg[i, 3])
                        {
                            tt |= TransportType.Tcp;
                        }
                        if ((bool)m_dg[i, 4])
                        {
                            tt |= TransportType.Udp;
                        }

                        NetworkAccess na;
                        if (((String)m_dg[i, 2]).Equals(CResourceStore.GetString("SocketPermission:Accept")))
                        {
                            na = NetworkAccess.Accept;
                        }
                        else
                        {
                            na = NetworkAccess.Connect;
                        }

                        perm.AddPermission(na, tt, sHostname, nPort);
                    }
                    else
                    {
                        // Check to see if they filled out any other fields without filling out
                        // the site field
                        if ((m_dg[i, 1] != DBNull.Value && ((String)m_dg[i, 1]).Length > 0) ||
                            (bool)m_dg[i, 3] || (bool)m_dg[i, 3])
                        {
                            MessageBox(CResourceStore.GetString("SocketPerm:NeedSite"),
                                       CResourceStore.GetString("SocketPerm:NeedSiteTitle"),
                                       MB.ICONEXCLAMATION);
                            return(null);
                        }
                    }
                }
            }
            return(perm);
        }// GetCurrentPermission
Beispiel #15
0
        public void Connect(string address, int port)
        {
            Audit.WriteLine("Connect " + address + " -- " + port);
            Disconnect();
            mState = State.Waiting;
            //
            // permissions
            SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

            mySocketPermission1.AddPermission(NetworkAccess.Connect, TransportType.All, "localhost", 8800);
            mySocketPermission1.Demand();

            //
            // Actually connect
            //
            // count .s, numeric and 3 .s =ipaddress
            bool ipaddress = false;
            bool text      = false;
            int  count     = 0;
            int  i;

            for (i = 0; i < address.Length; i++)
            {
                if (address[i] == '.')
                {
                    count++;
                }
                else
                {
                    if (address[i] < '0' || address[i] > '9')
                    {
                        text = true;
                    }
                }
            }
            if (count == 3 && text == false)
            {
                ipaddress = true;
            }

            if (!ipaddress)
            {
                Audit.WriteLine("Dns.Resolve " + address);
                IPHostEntry IPHost  = Dns.GetHostEntry(address);
                string []   aliases = IPHost.Aliases;
                IPAddress[] addr    = IPHost.AddressList;
                iep = new IPEndPoint(addr[0], port);
            }
            else
            {
                Audit.WriteLine("Use address " + address + " as ip");
                iep = new IPEndPoint(IPAddress.Parse(address), port);
            }


            try
            {
                // Create New Socket
                mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // Create New EndPoint
                // This is a non blocking IO
                mSocket.Blocking = false;
                // set some random options
                //
                //mSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                //
                // Assign Callback function to read from Asyncronous Socket
                callbackProc = new AsyncCallback(ConnectCallback);
                // Begin Asyncronous Connection
                mSocket.BeginConnect(iep, callbackProc, mSocket);
            }
            catch (Exception eeeee)
            {
                Audit.WriteLine("e=" + eeeee);
                throw;
                //				st_changed(STCALLBACK.ST_CONNECT, false);
            }
        }
Beispiel #16
0
        public async Task Attach(CancellationToken cancellationToken)
        {
            System.Diagnostics.Debug.Assert(CurrentState == State.Idle);

            SocketPermission permission = new SocketPermission(
                NetworkAccess.Connect,
                TransportType.Tcp,
                kServerHostname,
                kServerPort);

            permission.Demand();

            IPAddress  ipAddress  = new IPAddress(new byte[] { 127, 0, 0, 1 });
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, kServerPort);

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                ProtocolType.Tcp);
            socket.Blocking          = false;
            socket.NoDelay           = true;
            socket.ReceiveBufferSize = 1024 * 1024;
            socket.SendBufferSize    = 1024 * 1024;
            socket.ReceiveTimeout    = 0;
            socket.SendTimeout       = 0;

            OnStateChanged(State.Attaching);

            while (true)
            {
                Task task = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, ipEndPoint, null);
                try {
                    await task.WithCancellation(cancellationToken);
                } catch (OperationCanceledException) {
                    socket.Close();
                    socket = null;
                    OnStateChanged(State.Idle);
                    return;
                } catch (SocketException e) {
                    if (e.SocketErrorCode == SocketError.ConnectionRefused)
                    {
                        // Not found - emulator may still be starting.
                        System.Diagnostics.Debug.WriteLine("Connection refused; trying again...");
                        continue;
                    }
                    OnStateChanged(State.Idle);
                    return;
                }
                break;
            }

            // Start recv pump.
            Dispatch.Issue(() => ReceivePump());

            var fbb = BeginRequest();

            AttachRequest.StartAttachRequest(fbb);
            int requestDataOffset = AttachRequest.EndAttachRequest(fbb);
            var response          = await CommitRequest(fbb, RequestData.AttachRequest, requestDataOffset);

            System.Diagnostics.Debug.Assert(response.ResponseDataType ==
                                            ResponseData.AttachResponse);
            var attachResponse = new AttachResponse();

            response.GetResponseData(attachResponse);

            // Open mmap to share memory.
            memoryHandle = FileMapping.OpenFileMapping(
                FileMapAccess.FILE_MAP_ALL_ACCESS, false, attachResponse.MemoryFile);
            if (memoryHandle.IsInvalid)
            {
                System.Diagnostics.Debug.Fail("Unable to open target memory");
                Detach();
                return;
            }

            // Open mmap to code cache.
            codeCacheHandle =
                FileMapping.OpenFileMapping(FileMapAccess.FILE_MAP_ALL_ACCESS, false,
                                            attachResponse.CodeCacheFile);
            if (codeCacheHandle.IsInvalid)
            {
                System.Diagnostics.Debug.Fail("Unable to open target code cache");
                Detach();
                return;
            }
            codeCachePtr = FileMapping.MapViewOfFileEx(
                codeCacheHandle, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0,
                attachResponse.CodeCacheSize, attachResponse.CodeCacheBase);

            // Setup the memory system. This maps the emulator memory into our address
            // space.
            if (!Memory.InitializeMapping(memoryHandle))
            {
                Detach();
                return;
            }

            OnStateChanged(State.Attached);
        }
Beispiel #17
0
        public bool Open(int ASocketHandle)
        {
            if (OSUtils.IsWindows)
            {
                try
                {
                    NativeMethods.WSAData WSA    = new NativeMethods.WSAData();
                    SocketError           Result = NativeMethods.WSAStartup((short)0x0202, out WSA);
                    if (Result != SocketError.Success)
                    {
                        throw new SocketException(NativeMethods.WSAGetLastError());
                    }

                    SocketPermission SP = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted);
                    SP.Demand();

                    SocketInformation SI = new SocketInformation();
                    SI.Options             = SocketInformationOptions.Connected;
                    SI.ProtocolInformation = new byte[Marshal.SizeOf(typeof(NativeMethods.WSAPROTOCOL_INFO))];

                    Result = SocketError.Success;
                    unsafe
                    {
                        fixed(byte *pinnedBuffer = SI.ProtocolInformation)
                        {
                            Result = NativeMethods.WSADuplicateSocket(new IntPtr(ASocketHandle), (uint)Process.GetCurrentProcess().Id, pinnedBuffer);
                        }
                    }

                    if (Result != SocketError.Success)
                    {
                        throw new SocketException(NativeMethods.WSAGetLastError());
                    }

                    return(Open(new Socket(SI)));
                }
                catch (SocketException sex)
                {
                    RMLog.Exception(sex, "SocketException in TcpConnection::Open().  ErrorCode=" + sex.ErrorCode.ToString());
                    return(false);
                }
                catch (Exception ex)
                {
                    RMLog.Exception(ex, "Exception in TcpConnection::Open()");
                    return(false);
                }
            }
            else
            {
                RMLog.Error("MONO cannot open an existing socket handle");
                return(false);
                //try
                //{
                //    SocketInformation SI = new SocketInformation();
                //    SI.Options = SocketInformationOptions.Connected;
                //    SI.ProtocolInformation = new byte[24];

                //    // From Mono's Socket.cs DuplicateAndClose() SI.ProtocolInformation = Mono.DataConverter.Pack("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, isbound ? 1 : 0, (long)socket);
                //    byte[] B1 = BitConverter.GetBytes((int)AddressFamily.InterNetwork);
                //    byte[] B2 = BitConverter.GetBytes((int)SocketType.Stream);
                //    byte[] B3 = BitConverter.GetBytes((int)ProtocolType.Tcp);
                //    byte[] B4 = BitConverter.GetBytes((int)1);
                //    byte[] B5 = BitConverter.GetBytes((long)ASocketHandle);
                //    Array.Copy(B1, 0, SI.ProtocolInformation, 0, B1.Length);
                //    Array.Copy(B2, 0, SI.ProtocolInformation, 4, B2.Length);
                //    Array.Copy(B3, 0, SI.ProtocolInformation, 8, B3.Length);
                //    Array.Copy(B4, 0, SI.ProtocolInformation, 12, B4.Length);
                //    Array.Copy(B5, 0, SI.ProtocolInformation, 16, B5.Length);

                //    return Open(new Socket(SI));
                //}
                //catch (SocketException sex)
                //{
                //    RMLog.Exception(sex, "SocketException in TcpConnection::Open().  ErrorCode=" + sex.ErrorCode.ToString());
                //    return false;
                //}
                //catch (Exception ex)
                //{
                //    RMLog.Exception(ex, "Exception in TcpConnection::Open()");
                //    return false;
                //}
            }
        }
    static void Main(string[] args)
    {
        // Creates one SocketPermission object for access restrictions
        SocketPermission permission = new SocketPermission(
            NetworkAccess.Accept,     // Allowed to accept connections
            TransportType.Tcp,        // Defines transport types
            "",                       // The IP addresses of local host
            SocketPermission.AllPorts // Specifies all ports
            );

        // Listening Socket object
        Socket sListener = null;

        try
        {
            // Ensures the code to have permission to access a Socket
            permission.Demand();

            // Resolves a host name to an IPHostEntry instance
            IPHostEntry ipHost = Dns.GetHostEntry("");

            // Gets first IP address associated with a localhost
            IPAddress ipAddr = ipHost.AddressList[0];

            // Creates a network endpoint
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);

            // Create one Socket object to listen the incoming connection
            sListener = new Socket(
                ipAddr.AddressFamily,
                SocketType.Stream,
                ProtocolType.Tcp
                );

            // Associates a Socket with a local endpoint
            sListener.Bind(ipEndPoint);

            // Places a Socket in a listening state and specifies the maximum
            // Length of the pending connections queue
            sListener.Listen(10);

            Console.WriteLine("Waiting for a connection on port {0}",
                              ipEndPoint);

            // Begins an asynchronous operation to accept an attempt
            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
            sListener.BeginAccept(aCallback, sListener);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.ToString());
            return;
        }

        Console.WriteLine("Press the Enter key to exit ...");
        Console.ReadLine();

        if (sListener.Connected)
        {
            sListener.Shutdown(SocketShutdown.Receive);
            sListener.Close();
        }
    }
Beispiel #19
0
    static void Main(string[] args)
    {
        // Receiving byte array
        byte[] bytes = new byte[1024];
        try
        {
            // Create one SocketPermission for socket access restrictions
            SocketPermission permission = new SocketPermission(
                NetworkAccess.Connect,    // Connection permission
                TransportType.Tcp,        // Defines transport types
                "",                       // Gets the IP addresses
                SocketPermission.AllPorts // All ports
                );

            // Ensures the code to have permission to access a Socket
            permission.Demand();

            // Resolves a host name to an IPHostEntry instance
            IPHostEntry ipHost = Dns.GetHostEntry("");

            // Gets first IP address associated with a localhost
            IPAddress ipAddr = ipHost.AddressList[0];

            // Creates a network endpoint
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);

            // Create one Socket object to setup Tcp connection
            Socket sender = new Socket(
                ipAddr.AddressFamily,// Specifies the addressing scheme
                SocketType.Stream,   // The type of socket
                ProtocolType.Tcp     // Specifies the protocols
                );

            sender.NoDelay = true;   // Using the Nagle algorithm

            // Establishes a connection to a remote host
            sender.Connect(ipEndPoint);
            Console.WriteLine("Socket connected to {0}",
                sender.RemoteEndPoint.ToString());

            // Sending message
            //<Client Quit> is the sign for end of data
            string theMessage = "Hello World!";
            byte[] msg =
                Encoding.Unicode.GetBytes(theMessage +"<Client Quit>");

            // Sends data to a connected Socket.
            int bytesSend = sender.Send(msg);

            // Receives data from a bound Socket.
            int bytesRec = sender.Receive(bytes);

            // Converts byte array to string
            theMessage = Encoding.Unicode.GetString(bytes, 0, bytesRec);

            // Continues to read the data till data isn't available
            while (sender.Available > 0)
            {
                bytesRec = sender.Receive(bytes);
                theMessage += Encoding.Unicode.GetString(bytes, 0, bytesRec);
            }
            Console.WriteLine("The server reply: {0}", theMessage);

            // Disables sends and receives on a Socket.
            sender.Shutdown(SocketShutdown.Both);

            //Closes the Socket connection and releases all resources
            sender.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.ToString());
        }
    }
Beispiel #20
0
        /// <summary>
        /// Returns true if two CodeSource's have the "same" location.
        /// </summary>
        /// <param name="that"> CodeSource to compare against </param>
        private bool MatchLocation(CodeSource that)
        {
            if (Location_Renamed == null)
            {
                return(true);
            }

            if ((that == null) || (that.Location_Renamed == null))
            {
                return(false);
            }

            if (Location_Renamed.Equals(that.Location_Renamed))
            {
                return(true);
            }

            if (!Location_Renamed.Protocol.EqualsIgnoreCase(that.Location_Renamed.Protocol))
            {
                return(false);
            }

            int thisPort = Location_Renamed.Port;

            if (thisPort != -1)
            {
                int thatPort = that.Location_Renamed.Port;
                int port     = thatPort != -1 ? thatPort : that.Location_Renamed.DefaultPort;
                if (thisPort != port)
                {
                    return(false);
                }
            }

            if (Location_Renamed.File.EndsWith("/-"))
            {
                // Matches the directory and (recursively) all files
                // and subdirectories contained in that directory.
                // For example, "/a/b/-" implies anything that starts with
                // "/a/b/"
                String thisPath = Location_Renamed.File.Substring(0, Location_Renamed.File.Length() - 1);
                if (!that.Location_Renamed.File.StartsWith(thisPath))
                {
                    return(false);
                }
            }
            else if (Location_Renamed.File.EndsWith("/*"))
            {
                // Matches the directory and all the files contained in that
                // directory.
                // For example, "/a/b/*" implies anything that starts with
                // "/a/b/" but has no further slashes
                int last = that.Location_Renamed.File.LastIndexOf('/');
                if (last == -1)
                {
                    return(false);
                }
                String thisPath = Location_Renamed.File.Substring(0, Location_Renamed.File.Length() - 1);
                String thatPath = that.Location_Renamed.File.Substring(0, last + 1);
                if (!thatPath.Equals(thisPath))
                {
                    return(false);
                }
            }
            else
            {
                // Exact matches only.
                // For example, "/a/b" and "/a/b/" both imply "/a/b/"
                if ((!that.Location_Renamed.File.Equals(Location_Renamed.File)) && (!that.Location_Renamed.File.Equals(Location_Renamed.File + "/")))
                {
                    return(false);
                }
            }

            if (Location_Renamed.Ref != null && !Location_Renamed.Ref.Equals(that.Location_Renamed.Ref))
            {
                return(false);
            }

            String thisHost = Location_Renamed.Host;
            String thatHost = that.Location_Renamed.Host;

            if (thisHost != null)
            {
                if (("".Equals(thisHost) || "localhost".Equals(thisHost)) && ("".Equals(thatHost) || "localhost".Equals(thatHost)))
                {
                    // ok
                }
                else if (!thisHost.Equals(thatHost))
                {
                    if (thatHost == null)
                    {
                        return(false);
                    }
                    if (this.Sp == null)
                    {
                        this.Sp = new SocketPermission(thisHost, "resolve");
                    }
                    if (that.Sp == null)
                    {
                        that.Sp = new SocketPermission(thatHost, "resolve");
                    }
                    if (!this.Sp.Implies(that.Sp))
                    {
                        return(false);
                    }
                }
            }
            // everything matches
            return(true);
        }