Esempio n. 1
0
        public void CallWithputReply(RpcCallMessage callProcedure)
        {
            CallMessage = callProcedure;
            byte[] mes      = callProcedure.ToBytes();
            byte[] finalmes = new byte[sizeof(uint) + mes.Length];
            Buffer.BlockCopy(NetUtils.ToBigEndianBytes(xid), 0, finalmes, 0, 4);
            Buffer.BlockCopy(mes, 0, finalmes, 4, mes.Length);
            switch (ConnectionType)
            {
            case ProtocolType.Tcp:
                if (!RpcSocket.Connected)
                {
                    RpcSocket.Connect(RemoteEndPoint);
                }
                RpcSocket.Send(finalmes);
                break;

            case ProtocolType.Udp:
                RpcSocket.SendTo(finalmes, RemoteEndPoint);
                break;

            default:
                throw new Exception(ConnectionType.ToString() +
                                    " protocol have not realization of function Call().");
            }
        }
Esempio n. 2
0
    /// <summary>
    /// UPnP notification of a port being open.
    /// </summary>

    void OnPortOpened(UPnP up, int port, ProtocolType protocol, bool success)
    {
        if (success)
        {
            Tools.Print("UPnP: " + protocol.ToString().ToUpper() + " port " + port + " was opened successfully.");
        }
        else
        {
            Tools.Print("UPnP: Unable to open " + protocol.ToString().ToUpper() + " port " + port);
        }
    }
Esempio n. 3
0
    public virtual bool Start()
    {
        if (tConfig.ip.Length == 0)
        {
            Log("Ip 地址不能为空,暂时只支持 IPV4  配置IP地址为:{0}", tConfig.ip);
            return(false);
        }
        //创建连接终点
        endPoint = new IPEndPoint(IPAddress.Parse(tConfig.ip), tConfig.port);
        switch (protocolType)
        {
        case ProtocolType.Tcp:
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            break;

        case ProtocolType.Udp:
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            break;

        default:
            Log("暂不支持 除TCP UDP 之外的连接,你选择的连接为:{0}", protocolType.ToString());
            return(false);
        }
        sendBuff = new byte[bufferSize];

        recvBuff = new byte[bufferSize];


        Log("{0} Socket 创建成功! 准备多线程连接", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        return(true);
    }
Esempio n. 4
0
        public void Attach(IPEndPoint local, ProtocolType PType)
        {
            this.endpoint_local = local;
            this.TotalBytesSent = 0L;
            this.LocalEP        = local;
            this.Init();
            this.MainSocket = null;
            if (PType == ProtocolType.Tcp)
            {
                this.MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, PType);
            }
            if (PType == ProtocolType.Udp)
            {
                this.MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, PType);
                this.MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            }
            if (this.MainSocket == null)
            {
                throw new Exception(PType.ToString() + " not supported");
            }
            this.MainSocket.Bind(local);
            PropertyInfo property = this.MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");

            if (property != null)
            {
                property.SetValue(this.MainSocket, true, null);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Translate PortQry data to query result.
        /// </summary>
        /// <param name="address">Address value.</param>
        /// <param name="protocol">Protocol value.</param>
        /// <param name="port">Port number.</param>
        /// <param name="output">Process output.</param>
        /// <returns>Query result.</returns>
        private QueryResult GetQueryStatus(string address, ProtocolType protocol, string port, string output)
        {
            var resolvedIp   = this.TryGetIpAddress(output);
            var resolvedName = this.TryGetName(output);
            var portType     = this.TryGetPort(output);

            if (!string.IsNullOrEmpty(resolvedIp))
            {
                address = $"({address}) {resolvedIp}";
            }

            if (!string.IsNullOrEmpty(resolvedName))
            {
                address = $"({resolvedName}) {address}";
            }

            var status = this.GetStatus(output);

            // If port types does not match - set error.
            if (!string.IsNullOrEmpty(portType))
            {
                if (portType != protocol.ToString())
                {
                    status = PortStatus.ERROR;
                }
            }

            return(new QueryResult(address, protocol, port, status));
        }
Esempio n. 6
0
        /// <summary>
        /// Attaches this AsyncSocket to a new Socket instance, using the given info.
        /// </summary>
        /// <param name="local">Local interface to use</param>
        /// <param name="PType">Protocol Type</param>
        public void Attach(IPEndPoint local, ProtocolType PType)
        {
            endpoint_local = local;
            TotalBytesSent = 0;
            LocalEP        = (EndPoint)local;
            Init();

            MainSocket = null;

            if (PType == ProtocolType.Tcp)
            {
                MainSocket = new Socket(local.AddressFamily, SocketType.Stream, PType);
            }

            if (PType == ProtocolType.Udp)
            {
                MainSocket = new Socket(local.AddressFamily, SocketType.Dgram, PType);
                MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            }

            if (MainSocket != null)
            {
                MainSocket.Bind(local);
                System.Reflection.PropertyInfo pi = MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");
                if (pi != null)
                {
                    pi.SetValue(MainSocket, true, null);
                }
            }
            else
            {
                throw (new Exception(PType.ToString() + " not supported"));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Initialize and start new TcpClientHandler
        /// </summary>
        /// <param name="client">TcpClient to Handle</param>
        public MemTcpClient(TcpClient client, ProtocolType protocol)
        {
            _logManager = new LogManager(client.Client.RemoteEndPoint.ToString());
            _logManager.Info("MemTcpClient", "\tNew client connected on protocol :" + protocol.ToString());
            
            _client = client;
            _stream = _client.GetStream();

            _executionManager = new SequentialExecutionManager(_logManager);

            _inputBuffer = new byte[MAX_BUFFER_SIZE];
            _inputDataStream = new DataStream();

            _protocol = protocol;
            if (protocol == ProtocolType.Text)
            {
                _parser = new TextProtocolParser(_inputDataStream, this, _logManager);
                _responseManager = new TextResponseManager(_stream, _logManager);
            }
            else
            {
                _parser = new BinaryProtocolParser(_inputDataStream, this, _logManager);
                _responseManager = new BinaryResponseManager(_stream, _logManager);
            }
            _responseManager.MemTcpClient = this;

            _parser.CommandConsumer = _executionManager;
            _executionManager.CommandConsumer = _responseManager;
        }
Esempio n. 8
0
        /// <summary>
        /// Returns a string that represents this <see cref="BroPort"/>.
        /// </summary>
        /// <returns>
        /// A string that represents this <see cref="BroPort"/>.
        /// </returns>
        public override string ToString()
        {
            if (ProtocolType != ProtocolType.Unknown)
            {
                return(string.Format("[{0}/{1}]", m_port.port_num, ProtocolType.ToString().ToLowerInvariant()));
            }

            return(string.Format("[{0}/iproto({1})]", m_port.port_num, RawProtocolType));
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a SRV lookup for <code>[name1.[nameN]].[baseDomain].</code> and aggregates the results
        /// of returned host name, port and list of <see cref="IPAddress"/>s.
        /// </summary>
        /// <remarks>
        /// List of IPAddresses can be empty if no matching additional records are returned.
        /// In case no result was found, an empty list will be returned.
        /// </remarks>
        /// <param name="query">The lookup instance.</param>
        /// <param name="baseDomain">The base domain, will be attached to the end of the query string.</param>
        /// <param name="names">List of tokens to identify the service. Will be concatinated in the given order.</param>
        /// <returns></returns>
        public static Task <ServiceHostEntry[]> ResolveServiceAsync(this IDnsQuery query, string baseDomain, string serviceName, ProtocolType protocol)
        {
            if (protocol == ProtocolType.Unspecified || protocol == ProtocolType.Unknown)
            {
                return(ResolveServiceAsync(query, baseDomain, serviceName, null));
            }

            return(ResolveServiceAsync(query, baseDomain, serviceName, protocol.ToString()));
        }
Esempio n. 10
0
 public static void DeleteForwardingRule(int port, ProtocolType protocol)
 {
     if (string.IsNullOrEmpty(_serviceUrl))
         throw new Exception("No UPnP service available or Discover() has not been called");
     string body = String.Format("<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                     "<NewRemoteHost></NewRemoteHost><NewExternalPort>{0}</NewExternalPort>"+
                     "<NewProtocol>{1}</NewProtocol></u:DeletePortMapping>", port, protocol.ToString().ToUpper() );
     SOAPRequest(_serviceUrl, body, "DeletePortMapping");
 }
Esempio n. 11
0
 public static void ForwardPort(int port, ProtocolType protocol, string description)
 {
     if ( string.IsNullOrEmpty(_serviceUrl) )
         throw new Exception("No UPnP service available or Discover() has not been called");
     XmlDocument xdoc = SOAPRequest(_serviceUrl, "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
         "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + port.ToString() + "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
         "<NewInternalPort>" + port.ToString() + "</NewInternalPort><NewInternalClient>" + GetLocalIP() +
         "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" + description +
     "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>", "AddPortMapping");
 }
Esempio n. 12
0
 public static void DeleteForwardingRule(int port, ProtocolType protocol)
 {
     if (string.IsNullOrEmpty(_serviceUrl))
     {
         throw new Exception("No UPnP service available or Discover() has not been called");
     }
     SOAPRequest(_serviceUrl,
                 "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewRemoteHost></NewRemoteHost><NewExternalPort>" +
                 port + "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() +
                 "</NewProtocol></u:DeletePortMapping>", "DeletePortMapping");
 }
Esempio n. 13
0
        public PortMappingEntry GetSpecificPortMappingEntry(ProtocolType protocol, int externalPort)
        {
            string SOAP = "<u:GetSpecificPortMappingEntry xmlns:u=\"urn:schemas-upnp-org:service:WANPPPConnection:1\">" +
                          "<NewRemoteHost></NewRemoteHost>" +
                          "<NewExternalPort>" + externalPort + "</NewExternalPort>" +
                          "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                          "</u:GetSpecificPortMappingEntry>";

            HttpWebResponse response;

            try
            {
                response = SOAPRequest(SOAP, "GetSpecificPortMappingEntry");
            }
            catch (InternetGatewayDeviceException ex)
            {
                switch (ex.ErrorCode)
                {
                case 714:
                    //The specified value does not exists in the array
                    return(null);

                default:
                    throw;
                }
            }

            int statusCode = Convert.ToInt32(response.StatusCode);

            switch (statusCode)
            {
            case 200:
                //success
                XmlDocument xResp = new XmlDocument();
                xResp.Load(response.GetResponseStream());

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xResp.NameTable);

                XmlNode node1 = xResp.SelectSingleNode("//NewInternalPort/text()", nsMgr);
                XmlNode node2 = xResp.SelectSingleNode("//NewInternalClient/text()", nsMgr);
                XmlNode node3 = xResp.SelectSingleNode("//NewEnabled/text()", nsMgr);
                XmlNode node4 = xResp.SelectSingleNode("//NewPortMappingDescription/text()", nsMgr);
                XmlNode node5 = xResp.SelectSingleNode("//NewLeaseDuration/text()", nsMgr);

                return(new PortMappingEntry(Convert.ToInt32(node1.Value), IPAddress.Parse(node2.Value), Convert.ToBoolean(Convert.ToInt32(node3.Value)), node4.Value, Convert.ToInt32(node5.Value)));

            case 714:
                //The specified value does not exists in the array
                return(null);

            default:
                throw new InternetGatewayDeviceException(statusCode, "UPnP device returned an error: (" + statusCode + ") " + response.StatusDescription);
            }
        }
 private static string GetUPnPProtocolString(ProtocolType type)
 {
     if (type == ProtocolType.Tcp)
     {
         return("TCP");
     }
     if (type == ProtocolType.Udp)
     {
         return("UDP");
     }
     throw new ArgumentException(type.ToString());
 }
Esempio n. 15
0
        /// <summary>
        /// Asynchronously submit a request to forward a port to this computer.
        /// </summary>
        /// <param name="callback">An optional callback invoked when the operation is complete.</param>
        /// <param name="state">An optional state parameter supplied to the callback.</param>
        /// <returns>Returns an object which must be passed to EndAddForwardingRule.</returns>
        public static IAsyncResult BeginAddForwardingRule(int port, ProtocolType protocol, string description, AsyncCallback callback = null, object state = null)
        {
            if (!IsAvailable)
            {
                throw new ApplicationException("No UPnP devices have been discovered.");
            }

            var ar = new AsyncResult {
                AsyncWaitHandle = new ManualResetEvent(false), AsyncState = state
            };
            XNamespace ns = ControlNamespace;
            IPAddress  address;

            try
            {
                address = Dns.GetHostAddresses(Dns.GetHostName()).Where((ip) => ip.AddressFamily == AddressFamily.InterNetwork).First();
            }
            catch
            {
                throw new ApplicationException("Could not determine IP address.");
            }

            var elem = new XElement(ns + "AddPortMapping", new XAttribute(XNamespace.Xmlns + "u", ns.NamespaceName),
                                    new XElement("NewRemoteHost"),
                                    new XElement("NewExternalPort", port.ToString()),
                                    new XElement("NewProtocol", protocol.ToString().ToUpperInvariant()),
                                    new XElement("NewInternalPort", port.ToString()),
                                    new XElement("NewInternalClient", address.ToString()),
                                    new XElement("NewEnabled", "1"),
                                    new XElement("NewPortMappingDescription", description),
                                    new XElement("NewLeaseDuration", "0"));

            ThreadPool.QueueUserWorkItem((o) =>
            {
                try
                {
                    SoapRequest(_controlUrl, elem, "AddPortMapping");
                    ar.IsSuccessful = true;
                    System.Diagnostics.Debug.WriteLine("Started forwarding port " + port);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }

                ((ManualResetEvent)ar.AsyncWaitHandle).Set();
                if (callback != null)
                {
                    callback(ar);
                }
            }, null);
            return(ar);
        }
        public static bool DeleteForwardingRule(int port, ProtocolType protocol)
        {
            if (string.IsNullOrEmpty(_serviceUrl)) return false;

            XmlDocument xdoc = SOAPRequest(_serviceUrl,
            "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
            "<NewRemoteHost></NewRemoteHost>" +
            "<NewExternalPort>" + port.ToString() + "</NewExternalPort>" +
            "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
            "</u:DeletePortMapping>", "DeletePortMapping");
            return (xdoc != null);
        }
Esempio n. 17
0
 public void DeleteForwardingRule(int port, ProtocolType protocol)
 {
     if (string.IsNullOrEmpty(_serviceUrl))
         throw new Exception("No UPnP service available or Discover() has not been called");
     XmlDocument xdoc = SOAPRequest(_serviceUrl,
     "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
     "<NewRemoteHost>" +
     "</NewRemoteHost>" +
     "<NewExternalPort>"+ port+"</NewExternalPort>" +
     "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
     "</u:DeletePortMapping>", "DeletePortMapping");
 }
Esempio n. 18
0
 public void DeleteForwardingRule(int port, ProtocolType protocol)
 {
     if (UPnPReady)
     {
         SOAPRequest(_serviceUrl,
                     "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                     "<NewRemoteHost>" +
                     "</NewRemoteHost>" +
                     "<NewExternalPort>" + port + "</NewExternalPort>" +
                     "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                     "</u:DeletePortMapping>", "DeletePortMapping");
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Get information about a known port. Null if not found.
        /// </summary>
        /// <param name="port">Port number.</param>
        /// <param name="protocolType">Protocol type (TCP or UDP only!).</param>
        /// <returns></returns>
        public static KnownPort GetKnownPort(Int32 port, ProtocolType protocolType)
        {
            if (protocolType != ProtocolType.Tcp && protocolType != ProtocolType.Udp)
            {
                throw new ArgumentException("The protocol must be TCP OR UDP.");
            }

            var line = default(String);
            //https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv
            var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Hto3.NetworkHelpers.Resources.service-names-port-numbers.csv");

            using (var streamReader = new StreamReader(resourceStream, Encoding.UTF8, false, 1024))
            {
                var portFormat = $",{port},";
                var protFormat = $",{protocolType.ToString().ToLower()},";

                do
                {
                    line = streamReader.ReadLine();
                }while
                (
                    line != null
                    &&
                    !(
                        line.Contains(portFormat)
                        &&
                        line.Contains(protFormat)
                        )
                );
            }

            if (line == null)
            {
                return(null);
            }

            var lineValues = line.Split(',');

            if (lineValues.Length < 4)
            {
                return(null);
            }

            if (lineValues[3] == "Unassigned")
            {
                return(null);
            }

            return(new KnownPort(lineValues[0], port, protocolType, lineValues[3]));
        }
Esempio n. 20
0
		public string ExpandVariables( string input )
		{
			string result = input;

			result = result.Replace( "$(Port)", Convert.ToString(Number) );
			result = result.Replace( "$(PortAddressFamily)", AddressFamily.ToString() );
			result = result.Replace( "$(PortSocketType)", SocketType.ToString() );
			result = result.Replace( "$(PortProtocolType)", ProtocolType.ToString() );
			//result = result.Replace( "$(HostName)", Owner.Address );
			result = result.Replace( "$(Now)", DateTime.Now.ToString() );
			result = result.Replace( "$(ErrorMessage)", Exception!=null?Exception.Message:"(no exception)" );

			return result;
		}
Esempio n. 21
0
        public DebuggeeScript(string pathToTestFiles, ProtocolType protocolType)
        {
            DebuggeeScriptDummyText =
                @"using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using NetcoreDbgTest;
using NetcoreDbgTest.Script;
using Xunit;
using Newtonsoft.Json;

using NetcoreDbgTest." + protocolType.ToString() + @";

namespace NetcoreDbgTest.Script
{
}

namespace NetcoreDbgTestCore
{
    public class GeneratedScript {
        public static void ExecuteCheckPoints() {}
    }
}";

            // we may have list of files separated by ';' symbol
            string[]          pathToFiles = pathToTestFiles.Split(';');
            List <SyntaxTree> trees       = new List <SyntaxTree>();

            foreach (string pathToFile in pathToFiles)
            {
                if (String.IsNullOrEmpty(pathToFile))
                {
                    continue;
                }
                string     testSource = File.ReadAllText(pathToFile);
                SyntaxTree testTree   = CSharpSyntaxTree.ParseText(testSource)
                                        .WithFilePath(pathToFile);
                trees.Add(testTree);
            }

            TestLabelsInfo     = CollectTestLabelsInfo(trees, protocolType);
            ScriptDeclarations = CollectScriptDeclarations(trees);
            SyntaxTree         = BuildTree();
            Compilation compilation    = CompileTree(SyntaxTree);
            Assembly    scriptAssembly = MakeAssembly(compilation);

            generatedScriptClass = scriptAssembly.GetType("NetcoreDbgTestCore.GeneratedScript");
            Breakpoints          = TestLabelsInfo.Breakpoints;
        }
Esempio n. 22
0
 public static void ForwardPort(int port, ProtocolType protocol, string description)
 {
     if (string.IsNullOrEmpty(_serviceUrl))
     {
         throw new Exception("No UPnP service available or Discover() has not been called");
     }
     SOAPRequest(_serviceUrl,
                 "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewRemoteHost></NewRemoteHost><NewExternalPort>" +
                 port + "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() +
                 "</NewProtocol><NewInternalPort>" + port + "</NewInternalPort><NewInternalClient>" +
                 Dns.GetHostAddresses(Dns.GetHostName())[0] +
                 "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" + description +
                 "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>",
                 "AddPortMapping");
 }
Esempio n. 23
0
        public static bool DeleteForwardingRule(int port, ProtocolType protocol)
        {
            if (string.IsNullOrEmpty(_serviceUrl))
            {
                return(false);
            }

            XmlDocument xdoc = SOAPRequest(_serviceUrl,
                                           "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                                           "<NewRemoteHost></NewRemoteHost>" +
                                           "<NewExternalPort>" + port.ToString() + "</NewExternalPort>" +
                                           "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                                           "</u:DeletePortMapping>", "DeletePortMapping");

            return(xdoc != null);
        }
Esempio n. 24
0
        public NatHelperReponseCodes DeleteForwardingRule(int port, ProtocolType protocol)
        {
            XmlDocument xResponse = null;
            string txtError = null;
            string SOAPbody = "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:" + ServiceName + ":1\">" +
                    "<NewRemoteHost>" +
                    "</NewRemoteHost>" +
                    "<NewExternalPort>" + port + "</NewExternalPort>" +
                    "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                    "</u:DeletePortMapping>";
            string SOAPfunction = "DeletePortMapping";

            return TrySubmitSOAPRequest(SOAPbody,
                SOAPfunction,
                ref txtError,
                ref xResponse);
        }
Esempio n. 25
0
        public NatHelperReponseCodes DeleteForwardingRule(int port, ProtocolType protocol)
        {
            XmlDocument xResponse = null;
            string      txtError  = null;
            string      SOAPbody  = "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:" + ServiceName + ":1\">" +
                                    "<NewRemoteHost>" +
                                    "</NewRemoteHost>" +
                                    "<NewExternalPort>" + port + "</NewExternalPort>" +
                                    "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                                    "</u:DeletePortMapping>";
            string SOAPfunction = "DeletePortMapping";

            return(TrySubmitSOAPRequest(SOAPbody,
                                        SOAPfunction,
                                        ref txtError,
                                        ref xResponse));
        }
Esempio n. 26
0
 public void ExportTo(ConfigNode node)
 {
     node["ssh-host"]  = _sshHost;
     node["ssh-port"]  = _sshPort.ToString();
     node["account"]   = _sshAccount;
     node["auth-type"] = _authType.ToString();
     if (_authType == AuthenticationType.PublicKey)
     {
         node["keyfile"] = _privateKeyFile;
     }
     node["protocol"]    = _protocol.ToString();
     node["listen-port"] = _listenPort.ToString();
     node["dest-host"]   = _destinationHost;
     node["dest-port"]   = _destinationPort.ToString();
     node["allows-foreign-connection"] = _allowsForeignConnection.ToString();
     node["ipv6"] = _useIPv6.ToString();
 }
Esempio n. 27
0
        public static async Task DeleteForwardingRuleAsync(int port, ProtocolType protocol)
        {
            TR.Enter();
            if (string.IsNullOrEmpty(_serviceUrl))
            {
                TR.Exit();
                throw new Exception("No UPnP service available or Discover() has not been called");
            }
            XmlDocument xdoc = await SOAPRequestAsync(_serviceUrl,
                                                      "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                                                      "<NewRemoteHost>" +
                                                      "</NewRemoteHost>" +
                                                      "<NewExternalPort>" + port + "</NewExternalPort>" +
                                                      "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                                                      "</u:DeletePortMapping>", "DeletePortMapping");

            TR.Exit();
        }
Esempio n. 28
0
        public static void Validate(
            ProtocolType protocolType,
            string address,
            int port)
        {
            if (protocolType != ProtocolType.Tcp &&
                protocolType != ProtocolType.Udp &&
                protocolType != ProtocolType.IP)
            {
                throw new ArgumentOutOfRangeException(nameof(protocolType), "Only TCP/IP/UDP protocols are available. IP only for Unix domain sockets");
            }

            if (string.IsNullOrWhiteSpace(address))
            {
                throw new ArgumentNullException(nameof(address));
            }

            if (protocolType == ProtocolType.IP)
            {
                if (port != 0)
                {
                    throw new ArgumentException(
                              $"Port must be 0 when Unix domain socket is used",
                              nameof(port));
                }

                return;
            }

            if (port <= IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(port),
                          port,
                          $"Port must be in ({IPEndPoint.MinPort}; {IPEndPoint.MaxPort}) range.");
            }

            string endpoint = $"{protocolType.ToString().ToLower()}://{address}:{port}";

            if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri))
            {
                throw new InvalidOperationException($"{endpoint} must be a valid absolute URI.");
            }
        }
Esempio n. 29
0
        public static void ForwardPort(int port, ProtocolType protocol, string description)
        {
            if (string.IsNullOrEmpty(_serviceUrl))
            {
                throw new Exception("No UPnP service available or Discover() has not been called");
            }

            IPHostEntry ipEntry = Dns.GetHostByName(Dns.GetHostName());
            IPAddress   addr    = ipEntry.AddressList[0];

            XmlDocument xdoc = SOAPRequest(_serviceUrl,
                                           "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewRemoteHost xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\"></NewRemoteHost><NewExternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                                           port.ToString() + "</NewExternalPort><NewProtocol xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                                           protocol.ToString().ToUpper() + "</NewProtocol><NewInternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                                           port.ToString() + "</NewInternalPort><NewInternalClient xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                                           addr + "</NewInternalClient><NewEnabled xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"boolean\">1</NewEnabled><NewPortMappingDescription xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                                           description + "</NewPortMappingDescription><NewLeaseDuration xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui4\">0</NewLeaseDuration></m:AddPortMapping>",
                                           "AddPortMapping");
        }
Esempio n. 30
0
        public static async Task <bool> AddForwardingRuleAsync(int port, ProtocolType protocol, string description, object state = null)
        {
            if (!IsAvailable)
            {
                throw new ApplicationException("No UPnP devices have been discovered");
            }

            XNamespace ns = ControlNamespace;
            IPAddress  address;

            try
            {
                address = (await Dns.GetHostAddressesAsync(Dns.GetHostName())).First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            }
            catch
            {
                throw new ApplicationException("Could not determine IPAddress");
            }

            var elem = new XElement(ns + "AddPortMapping", new XAttribute(XNamespace.Xmlns + "u", ns.NamespaceName),
                                    new XElement("NewRemoteHost"),
                                    new XElement("NewExternalPort", port.ToString()),
                                    new XElement("NewProtocol", protocol.ToString().ToUpperInvariant()),
                                    new XElement("NewInternalPort", port.ToString()),
                                    new XElement("NewInternalClient", address.ToString()),
                                    new XElement("NewEnabled", "1"),
                                    new XElement("NewPortMappingDescription", description),
                                    new XElement("NewLeaseDuration", "0"));

            try
            {
                await SoapRequestAsync(_controlUrl, elem, "AddPortMapping");

                System.Diagnostics.Debug.WriteLine("Started forwarding port " + port);
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return(false);
        }
Esempio n. 31
0
        // TODO: Finish adding TCP Support
        /// <summary>
        ///
        /// </summary>
        /// <param name="dnsServer"></param>
        /// <param name="host"></param>
        /// <param name="queryType"></param>
        /// <param name="queryClass"></param>
        /// <param name="protocol"></param>
        /// <returns>A <see cref="T:DnDns.Net.Dns.DnsQueryResponse"></see> instance that contains the Dns Answer for the request query.</returns>
        /// <PermissionSet>
        ///     <IPermission class="System.Net.DnsPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        /// </PermissionSet>
        public DnsQueryResponse Resolve(string dnsServer, string host, NsType queryType, NsClass queryClass, ProtocolType protocol)
        {
            byte[] bDnsQuery = this.BuildDnsRequest(host, queryType, queryClass, protocol);

            // Connect to DNS server and get the record for the current server.
            IPHostEntry ipe  = System.Net.Dns.GetHostEntry(dnsServer);
            IPAddress   ipa  = ipe.AddressList[0];
            IPEndPoint  ipep = new IPEndPoint(ipa, (int)UdpServices.Domain);

            byte[] recvBytes = null;

            switch (protocol)
            {
            case ProtocolType.Tcp:
            {
                recvBytes = this.ResolveTcp(bDnsQuery, ipep);
                break;
            }

            case ProtocolType.Udp:
            {
                recvBytes = this.ResolveUdp(bDnsQuery, ipep);
                break;
            }

            default:
            {
                throw new InvalidOperationException("Invalid Protocol: " + protocol.ToString());
            }
            }

            Trace.Assert(recvBytes != null, "Failed to retrieve data from the remote DNS server.");

            DnsQueryResponse dnsQR = new DnsQueryResponse();

            dnsQR.ParseResponse(recvBytes);

            return(dnsQR);
        }
        private bool GetDeviceObject(ref DeviceInfo deviceInfoObject, ref DeviceTypeInfo deviceTypeObject, ref NetworkDeviceInfo netMacObject, ProtocolType pType, string deviceCode)
        {
            string ipstr = "";
            List <NetworkDeviceInfo> lstNet = new List <NetworkDeviceInfo>();

            deviceInfoObject = Cache.CacheManager.GetItemByKey <DeviceInfo>(deviceCode, true);//得到对应的分站对象
            if (deviceInfoObject == null)
            {
                LogHelper.Info("未找到分站【" + deviceCode + "】:" + pType.ToString());
                return(false);
            }
            Point  = deviceInfoObject.Point; //用于外部显示分站号
            ipstr  = deviceInfoObject.Jckz2; //获取IP
            lstNet = Cache.CacheManager.Query <NetworkDeviceInfo>(p => (p.IP == ipstr) && (p.Upflag == "0"), true);
            if (lstNet.Count > 0)
            {
                netMacObject = lstNet[0];
            }
            else
            {
                LogHelper.Info("未找到分站【" + deviceCode + "】对应的网络地址【" + deviceInfoObject.Jckz2 + "】:" + pType.ToString());
                return(false);
            }
            lock (Cache.LockWorkNet)//用缓存的连接号进行更新
            {
                CacheNetWork curnet = Cache.LstWorkNet.Find(delegate(CacheNetWork p) { return(p.IP == ipstr); });
                if (curnet != null)
                {
                    netMacObject.NetID = curnet.NetID;
                }
            }
            deviceTypeObject = Cache.CacheManager.GetItemByKey <DeviceTypeInfo>(deviceInfoObject.Devid, true);//按照devid搜索对象
            if (deviceTypeObject == null)
            {
                LogHelper.Info("未找到分站【" + deviceCode + "】对应的设备类型【" + deviceInfoObject.Devid + "】:" + pType.ToString());
                return(false);
            }
            return(true);
        }
Esempio n. 33
0
    /// <summary>
    /// Forward a port
    /// </summary>
    /// <param name="internalPort">Port number on LAN interface</param>
    /// <param name="externalPort">Port number on WAN interface</param>
    /// <param name="protocol">Protocol (TCP or UDP)</param>
    /// <param name="description">Describe service behind this forwading rule</param>
    /// <param name="internalIp">LAN ip</param>
    public void ForwardPort(int internalPort, int externalPort, ProtocolType protocol, string description, IPAddress internalIp)
    {
        if (string.IsNullOrEmpty(_serviceUrl))
        {
            throw new Exception("No UPnP service available or Discover() has not been called");
        }

        if (internalIp == null || internalIp.ToString() == IPAddress.Any.ToString())
        {
            foreach (var ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.GetAddressBytes().Length == 4)
                {
                    internalIp = ip;
                    break;
                }
            }

            if (internalIp == null)
            {
                throw new Exception("LAN IP not found !");
            }
        }

        _GetSOAPRequest(
            _serviceUrl,
            "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
            "<NewRemoteHost></NewRemoteHost>" +
            "<NewExternalPort>" + externalPort + "</NewExternalPort>" +
            "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
            "<NewInternalPort>" + internalPort + "</NewInternalPort>" +
            "<NewInternalClient>" + internalIp + "</NewInternalClient>" +
            "<NewEnabled>1</NewEnabled>" +
            "<NewPortMappingDescription>" + description + "</NewPortMappingDescription>" +
            "<NewLeaseDuration>0</NewLeaseDuration>" +
            "</u:AddPortMapping>",
            "AddPortMapping");
    }
Esempio n. 34
0
        public RpcClient(IPEndPoint localEndPoint, ProtocolType connectionType, IPEndPoint remoteEndPoint)
        {
            LocalEndPoint  = localEndPoint;
            RemoteEndPoint = remoteEndPoint;
            ReplyMessages  = new Dictionary <EndPoint, RpcReplyMessage>();
            Random r = new Random(DateTime.Now.Millisecond);

            xid            = (uint)r.Next(65536);
            ConnectionType = connectionType;
            if (RemoteEndPoint.Address == IPAddress.Broadcast && connectionType == ProtocolType.Tcp)
            {
                throw new ArgumentException("Can not create Broadcast TCP connection.");
            }
            switch (connectionType)
            {
            case ProtocolType.Tcp:
                RpcSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, connectionType);
                break;

            case ProtocolType.Udp:
                RpcSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, connectionType);
                break;

            default:
                throw new ArgumentException(connectionType.ToString() + " not supported.");
            }
            if (RemoteEndPoint.Address == IPAddress.Broadcast)
            {
                RpcSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            }
            RpcSocket.ReceiveTimeout = 1000;
            RpcSocket.Bind(LocalEndPoint);
            RpcSocket.Ttl = 1;
            if (ConnectionType == ProtocolType.Tcp)
            {
                RpcSocket.Connect(RemoteEndPoint);
            }
        }
Esempio n. 35
0
        public static bool ForwardPort(int port, ProtocolType protocol, string description)
        {
            if (string.IsNullOrEmpty(_serviceUrl))
            {
                throw new Exception("No UPnP service available or Discover() has not been called");
            }
            string body = String.Format("<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                                        "<NewRemoteHost></NewRemoteHost><NewExternalPort>{0}</NewExternalPort>" +
                                        "<NewProtocol>{1}</NewProtocol><NewInternalPort>{0}</NewInternalPort>" +
                                        "<NewInternalClient>{2}</NewInternalClient><NewEnabled>1</NewEnabled>" +
                                        "<NewPortMappingDescription>{3}</NewPortMappingDescription>" +
                                        "<NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>",
                                        port, protocol.ToString().ToUpper(), Dns.GetHostAddresses(Dns.GetHostName())[0], description);

            if (SOAPRequest(_serviceUrl, body, "AddPortMapping") != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 36
0
        public void DeletePortMapping(ProtocolType protocol, int externalPort)
        {
            string SOAP = "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANPPPConnection:1\">" +
                          "<NewRemoteHost></NewRemoteHost>" +
                          "<NewExternalPort>" + externalPort + "</NewExternalPort>" +
                          "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                          "</u:DeletePortMapping>";

            HttpWebResponse response = SOAPRequest(SOAP, "DeletePortMapping");

            int statusCode = Convert.ToInt32(response.StatusCode);

            switch (statusCode)
            {
            case 200:     //success
                break;

            case 714:
                throw new InternetGatewayDeviceException("UPnP device returned an error: (" + statusCode + ") The specified value does not exists in the array.");

            default:
                throw new InternetGatewayDeviceException("UPnP device returned an error: (" + statusCode + ") " + response.StatusDescription);
            }
        }
Esempio n. 37
0
 public static bool ForwardPort(int port, ProtocolType protocol, string description)
 {
     if (string.IsNullOrEmpty(_serviceUrl))
         throw new Exception("No UPnP service available or Discover() has not been called");
     string body = String.Format("<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">"+
                     "<NewRemoteHost></NewRemoteHost><NewExternalPort>{0}</NewExternalPort>"+
                     "<NewProtocol>{1}</NewProtocol><NewInternalPort>{0}</NewInternalPort>" +
                     "<NewInternalClient>{2}</NewInternalClient><NewEnabled>1</NewEnabled>" +
                     "<NewPortMappingDescription>{3}</NewPortMappingDescription>"+
                     "<NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>",
                     port, protocol.ToString().ToUpper(),Dns.GetHostAddresses(Dns.GetHostName())[0], description);
     if (SOAPRequest(_serviceUrl, body, "AddPortMapping") != null)
         return true;
     else
         return false;
 }
Esempio n. 38
0
        public static async Task<bool> AddForwardingRuleAsync(int port, ProtocolType protocol, string description, object state = null)
        {
            if(!IsAvailable)
            {
                throw new ApplicationException("No UPnP devices have been discovered");
            }

            XNamespace ns = ControlNamespace;
            IPAddress address;

            try
            {
                address = (await Dns.GetHostAddressesAsync(Dns.GetHostName())).First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            }
            catch
            {
                throw new ApplicationException("Could not determine IPAddress");        
            }

            var elem = new XElement(ns + "AddPortMapping", new XAttribute(XNamespace.Xmlns + "u", ns.NamespaceName),
                new XElement("NewRemoteHost"),
                new XElement("NewExternalPort", port.ToString()),
                new XElement("NewProtocol", protocol.ToString().ToUpperInvariant()),
                new XElement("NewInternalPort", port.ToString()),
                new XElement("NewInternalClient", address.ToString()),
                new XElement("NewEnabled", "1"),
                new XElement("NewPortMappingDescription", description),
                new XElement("NewLeaseDuration", "0"));

            try
            {
                await SoapRequestAsync(_controlUrl, elem, "AddPortMapping");
                System.Diagnostics.Debug.WriteLine("Started forwarding port " + port);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return false;
        }
Esempio n. 39
0
 /// <summary>
 /// Deletes the forwarding rule for the specific port
 /// </summary>
 /// <param name="port">The port.</param>
 /// <param name="protocol">The protocol.</param>
 public static void DeleteForwardingRule(int port, ProtocolType protocol)
 {
     XmlDocument xdoc = SOAPRequest(
     "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
     "<NewRemoteHost></NewRemoteHost>" +
     "<NewExternalPort>" + port.ToString() + "</NewExternalPort>" +
     "<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
     "</u:DeletePortMapping>", "DeletePortMapping");
 }
Esempio n. 40
0
        /// <summary>
        /// Forwards an external port to the same internal port
        /// </summary>
        /// <param name="port">The port to map (both external and internal)</param>
        /// <param name="protocol">The protocol type to map</param>
        /// <param name="description">The description of this mapping</param>
        public static void CreateForwardingRule(int port, ProtocolType protocol, string description)
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress addr = ipEntry.AddressList[0];

            XmlDocument xdoc = SOAPRequest(
                "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewRemoteHost xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\"></NewRemoteHost><NewExternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                port.ToString() + "</NewExternalPort><NewProtocol xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                protocol.ToString().ToUpper() + "</NewProtocol><NewInternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                port.ToString() + "</NewInternalPort><NewInternalClient xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                addr + "</NewInternalClient><NewEnabled xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"boolean\">1</NewEnabled><NewPortMappingDescription xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                description + "</NewPortMappingDescription><NewLeaseDuration xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui4\">0</NewLeaseDuration></m:AddPortMapping>",
                "AddPortMapping");
        }
Esempio n. 41
0
        public static void ForwardPort(int port, ProtocolType protocol, string description)
        {
            if (string.IsNullOrEmpty(_serviceUrl))
                throw new Exception("No UPnP service available or Discover() has not been called");

            IPHostEntry ipEntry = Dns.GetHostByName(Dns.GetHostName());
            IPAddress addr = ipEntry.AddressList[0];

            XmlDocument xdoc = SOAPRequest(_serviceUrl,
                "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewRemoteHost xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\"></NewRemoteHost><NewExternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                port.ToString() + "</NewExternalPort><NewProtocol xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                protocol.ToString().ToUpper() + "</NewProtocol><NewInternalPort xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui2\">" +
                port.ToString() + "</NewInternalPort><NewInternalClient xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                addr + "</NewInternalClient><NewEnabled xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"boolean\">1</NewEnabled><NewPortMappingDescription xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"string\">" +
                description + "</NewPortMappingDescription><NewLeaseDuration xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"ui4\">0</NewLeaseDuration></m:AddPortMapping>",
                "AddPortMapping");
        }
Esempio n. 42
0
 public static string ProtocolToString(ProtocolType protocol)
 {
     return protocol.ToString();
 }
Esempio n. 43
0
 public static string ToString(ProtocolType value)
 {
     if( value==ProtocolType.Condition )
         return "condition";
     else if( value==ProtocolType.Device )
         return "device";
     else if( value==ProtocolType.Drug )
         return "drug";
     else if( value==ProtocolType.Study )
         return "study";
     else
         throw new ArgumentException("Unrecognized ProtocolType value: " + value.ToString());
 }
Esempio n. 44
0
        // Port Freigabe eintragen
        public bool AddPortMapping(ushort internalPort, ushort externalPort, ProtocolType protocolType, string description)
        {
            // Discover() ausgeführt?
            if (string.IsNullOrEmpty(m_ServiceURL))
                throw new Exception("Discover() has not been called");

            try
            {
                // lokale IPv4 Adresse bestimmen
                IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
                IPAddress internalClient = null;
                foreach (IPAddress address in addresses)
                {
                    if (address.AddressFamily == AddressFamily.InterNetwork)
                        internalClient = address;
                }

                // Request abschicken und Antwort empfangen
                XmlDocument response = SOAPRequest(m_ServiceURL,
                    "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" + 
                    "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + externalPort.ToString() + "</NewExternalPort><NewProtocol>" + protocolType.ToString().ToUpper() + "</NewProtocol>" + 
                    "<NewInternalPort>" + internalPort.ToString() + "</NewInternalPort><NewInternalClient>" + internalClient.ToString() + 
                    "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" + description + 
                    "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>", 
                    "AddPortMapping");

                return true;
            }
            catch (Exception e)
            {
                if (e is WebException)
                {
                    WebException we = (WebException)e;

                    HttpWebResponse wr = (HttpWebResponse)we.Response;

                    if (wr.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        throw new Exception("Changes of the security settings over UPnP are not allowed. Check your UPnP Router settings!");
                    }
                }
                
                throw e;
            }

        }
Esempio n. 45
0
        // Port Freigabe löschen
        public bool DeletePortMapping(ushort externalPort, ProtocolType protocolType)
        {
            // Discover() ausgeführt?
            if (string.IsNullOrEmpty(m_ServiceURL))
                throw new Exception("Discover() has not been called");

            try
            {
                // Request abschicken und Antwort empfangen
                XmlDocument xdoc = SOAPRequest(m_ServiceURL,
                    "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" + 
                    "<NewRemoteHost></NewRemoteHost>" + "<NewExternalPort>" + externalPort.ToString() + "</NewExternalPort>" + 
                    "<NewProtocol>" + protocolType.ToString().ToUpper() + "</NewProtocol>" +
                    "</u:DeletePortMapping>", 
                    "DeletePortMapping");

                return true;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
Esempio n. 46
0
		/// <summary>
		/// Asynchronously submit a request to delete a previously added port forwarding rule.
		/// </summary>
		/// <param name="callback">An optional callback invoked when the operation is complete.</param>
		/// <param name="state">An optional state parameter supplied to the callback.</param>
		/// <returns>Returns an object which must be passed to EndDeleteForwardingRule.</returns>
		public static IAsyncResult BeginDeleteForwardingRule(int port, ProtocolType protocol, AsyncCallback callback = null, object state = null)
		{
			if (!IsAvailable)
			{
				throw new ApplicationException("No UPnP devices have been discovered.");
			}

			var ar = new AsyncResult { AsyncWaitHandle = new ManualResetEvent(false), AsyncState = state };
			XNamespace ns = ControlNamespace;
			IPAddress address;

			try
			{
				address = Dns.GetHostAddresses(Dns.GetHostName()).Where((ip) => ip.AddressFamily == AddressFamily.InterNetwork).First();
			}
			catch
			{
				throw new ApplicationException("Could not determine IP address.");
			}

			var elem = new XElement(ns + "DeletePortMapping", new XAttribute(XNamespace.Xmlns + "u", ns.NamespaceName),
				new XElement("NewRemoteHost"),
				new XElement("NewExternalPort", port.ToString()),
				new XElement("NewProtocol", protocol.ToString().ToUpperInvariant()));

			ThreadPool.QueueUserWorkItem((o) =>
			{
				try
				{
					SoapRequest(_controlUrl, elem, "DeletePortMapping");
					ar.IsSuccessful = true;
					System.Diagnostics.Debug.WriteLine("Stopped forwarding port " + port);
				}
				catch (Exception ex)
				{
					System.Diagnostics.Debug.WriteLine(ex.ToString());
				}

				((ManualResetEvent)ar.AsyncWaitHandle).Set();
				if (callback != null)
				{
					callback(ar);
				}
			}, null);
			return ar;
		}
Esempio n. 47
0
File: UPnP.cs Progetto: JyBP/SupChat
        /*
                 public static void ForwardPort(int port, ProtocolType protocol, string description)
                 {
                    if (string.IsNullOrEmpty(_serviceUrl))
                       throw new Exception("No UPnP service available or Discover() has not been called");
                     XmlDocument xdoc = SOAPRequest(_serviceUrl, "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                         "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + port.ToString() + "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                        "<NewInternalPort>" + port.ToString() + "</NewInternalPort><NewInternalClient>" + Dns.GetHostAddresses(Dns.GetHostName())[0].ToString() +
                        "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" + description +
                    "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>", "AddPortMapping");
                 }
                 */
        public static string ForwardPort(int port, ProtocolType protocol, string description)
        {
            if (string.IsNullOrEmpty(_serviceUrl))
                throw new Exception("No UPnP service available or Discover() has not been called");
            foreach (var ipAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if(Program.debug)
                    WriteLineInFile("debug.txt", ipAddress.ToString());

                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    try
                    {
                        var request = "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                                      "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + port.ToString() +
                                      "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() +
                                      "</NewProtocol>" + "<NewInternalPort>" + port.ToString() + "</NewInternalPort><NewInternalClient>" +
                                      ipAddress.ToString() + "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" +
                                      description + "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>";

                        if (Program.debug)
                        {
                            WriteLineInFile("debug.txt", "Trying To write:");
                            WriteLineInFile("debug.txt", request.ToString());
                        }

                        XmlDocument xdoc = SOAPRequest(_serviceUrl, request, "AddPortMapping");
                        return request.ToString();
                        //break;
                    }
                    catch (WebException) { }
                }
            }
            return "fail forward upnp";
        }
Esempio n. 48
0
	/// <summary>
	/// Forward a port
	/// </summary>
	/// <param name="internalPort">Port number on LAN interface</param>
	/// <param name="externalPort">Port number on WAN interface</param>
	/// <param name="protocol">Protocol (TCP or UDP)</param>
	/// <param name="description">Describe service behind this forwading rule</param>
	/// <param name="internalIp">LAN ip</param>
	public void ForwardPort(int internalPort, int externalPort, ProtocolType protocol, string description, IPAddress internalIp)
	{
		if (string.IsNullOrEmpty(_serviceUrl))
			throw new Exception("No UPnP service available or Discover() has not been called");

		if (internalIp == null || internalIp.ToString() == IPAddress.Any.ToString())
		{
			foreach (var ip in Dns.GetHostAddresses(Dns.GetHostName()))
				if (ip.GetAddressBytes().Length == 4)
			{
				internalIp = ip;
				break;
			}
			if (internalIp == null)
				throw new Exception("LAN IP not found !");
		}
		_GetSOAPRequest(
			_serviceUrl,
			"<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
			"<NewRemoteHost></NewRemoteHost>" +
			"<NewExternalPort>" + externalPort + "</NewExternalPort>" +
			"<NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
			"<NewInternalPort>" + internalPort + "</NewInternalPort>" +
			"<NewInternalClient>" + internalIp + "</NewInternalClient>" +
			"<NewEnabled>1</NewEnabled>" +
			"<NewPortMappingDescription>" + description + "</NewPortMappingDescription>" +
			"<NewLeaseDuration>0</NewLeaseDuration>" +
			"</u:AddPortMapping>",
			"AddPortMapping");
	}
Esempio n. 49
0
        public NatHelperReponseCodes ForwardPort(int port, string localIP, ProtocolType protocol, string description)
        {
            XmlDocument xResponse = null;
            string txtError = null;
            string SOAPbody = "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:" + ServiceName + ":1\">" +
                    "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + port.ToString() + "</NewExternalPort><NewProtocol>" + protocol.ToString().ToUpper() + "</NewProtocol>" +
                    "<NewInternalPort>" + port.ToString() + "</NewInternalPort><NewInternalClient>" + localIP +
                    "</NewInternalClient><NewEnabled>1</NewEnabled><NewPortMappingDescription>" + description +
                    "</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:AddPortMapping>";
            string SOAPfunction = "AddPortMapping";

            return TrySubmitSOAPRequest(SOAPbody,
                SOAPfunction,
                ref txtError,
                ref xResponse);
        }
Esempio n. 50
0
        /// <summary>
        /// Attaches this AsyncSocket to a new Socket instance, using the given info.
        /// </summary>
        /// <param name="local">Local interface to use</param>
        /// <param name="PType">Protocol Type</param>
        public void Attach(IPEndPoint local, ProtocolType PType)
        {
            endpoint_local = local;
            TotalBytesSent = 0;
            LocalEP = (EndPoint)local;
            Init();

            MainSocket = null;

            if (PType == ProtocolType.Tcp)
            {
                MainSocket = new Socket(local.AddressFamily, SocketType.Stream, PType);
            }

            if (PType == ProtocolType.Udp)
            {
                MainSocket = new Socket(local.AddressFamily, SocketType.Dgram, PType);
                MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            }

            if (MainSocket != null)
            {
                MainSocket.Bind(local);
                System.Reflection.PropertyInfo pi = MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");
                if (pi != null)
                {
                    pi.SetValue(MainSocket, true, null);
                }
            }
            else
            {
                throw (new Exception(PType.ToString() + " not supported"));
            }
        }
Esempio n. 51
0
        // TODO: Finish adding TCP Support
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dnsServer"></param>
        /// <param name="host"></param>
        /// <param name="queryType"></param>
        /// <param name="queryClass"></param>
        /// <param name="protocol"></param>
        /// <returns>A <see cref="T:DnDns.Net.Dns.DnsQueryResponse"></see> instance that contains the Dns Answer for the request query.</returns>
        /// <PermissionSet>
        ///     <IPermission class="System.Net.DnsPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        /// </PermissionSet>
        public DnsQueryResponse Resolve(string dnsServer, string host, NsType queryType, NsClass queryClass, ProtocolType protocol)
        {
            byte[] bDnsQuery = this.BuildDnsRequest(host, queryType, queryClass, protocol);

            // Connect to DNS server and get the record for the current server.
            IPHostEntry ipe = System.Net.Dns.GetHostEntry(dnsServer);
            IPAddress ipa = ipe.AddressList[0];
            IPEndPoint ipep = new IPEndPoint(ipa, (int)UdpServices.Domain);

            byte[] recvBytes = null;

            switch (protocol)
            {
                case ProtocolType.Tcp:
                    {
                        recvBytes = this.ResolveTcp(bDnsQuery, ipep);
                        break;
                    }
                case ProtocolType.Udp:
                    {
                        recvBytes = this.ResolveUdp(bDnsQuery, ipep);
                        break;
                    }
                default:
                    {
                        throw new InvalidOperationException("Invalid Protocol: " + protocol.ToString());
                    }
            }

            Trace.Assert(recvBytes != null, "Failed to retrieve data from the remote DNS server.");

            DnsQueryResponse dnsQR = new DnsQueryResponse();

            dnsQR.ParseResponse(recvBytes);

            return dnsQR;
        }