示例#1
0
        internal FtpResponse Connect(int timeout,
                                     string server,
                                     int port)
        {
            CheckDisposed();

            NSTrace.WriteLineVerbose("CC: -> Connect");
            if (null == server)
            {
                throw new ArgumentNullException("server");
            }

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException("port", "Value, specified for the port, is out of valid range.");
            }

            SetProgress(true);
            try
            {
                _socket.ConnectTimeout = timeout;

                string msg = string.Format("CC: Connecting (timeout: {0}, srv: {1}:{2})...", timeout, server, port);
                NSTrace.WriteLineInfo(msg);

                _socket.Connect(server, port);

                msg = string.Format("CC: Reading response...");
                NSTrace.WriteLineInfo(msg);

                _response = _reader.ReadResponse(timeout);

                NSTrace.WriteLineVerbose("CC: <- Connect");
            }
            catch (SocketException e)
            {
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch (Exception)
            {
                CheckDisposed();
                throw;
            }
            catch
            {
                CheckDisposed();
                throw;
            }
            finally
            {
                SetProgress(false);
            }
            OnResponseReceived();
            return(_response);
        }
示例#2
0
        private void btnRequest_Click(object sender, System.EventArgs e)
        {
            SocketEx sock = null;

            try
            {
                Uri reqUri = new Uri(txtURL.Text);

                string host = reqUri.Host;
                int    port = reqUri.Port;
                string path = reqUri.PathAndQuery;

                sock = new SocketEx(_proxyType, _proxyServer, _proxyPort,
                                    _proxyUser, _proxyPwd);

                //configure preauthenticate
                sock.PreAuthenticate = _preAuthenticate;


                sock.Connect(host, port);
                string cmd = "GET " + path + " HTTP/1.0\r\n" +
                             "Host: " + host + "\r\n\r\n";
                sock.Send(_usedEnc.GetBytes(cmd));


                //simple reading loop
                //read while have the data
                try
                {
                    byte[] data = new byte[32 * 1024];
                    while (true)
                    {
                        int dataLen = sock.Receive(data);
                        if (0 == dataLen)
                        {
                            break;
                        }
                        txtRes.Text += _usedEnc.GetString(data, 0, dataLen);
                    }
                }
                catch (Exception ex)
                {
                    txtRes.Text += Environment.NewLine + ex.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught!");
            }

            if (null != sock)
            {
                sock.Close();
            }
        }
示例#3
0
 internal override void Establish(int timeout)
 {
     CheckDisposed();
     try
     {
         _socket.ConnectTimeout = timeout;
         _socket.Connect(_remoteEP);
         _stream = new NetworkStreamEx(_socket);
     }
     catch (SocketException e)
     {
         CheckDisposed();
         CheckTimeoutException(e);
         throw;
     }
     catch
     {
         CheckDisposed();
         throw;
     }
 }
        /// <summary>
        /// Connects to specified NNTP server.
        /// </summary>
        /// <param name="server">NNTP server.</param>
        /// <param name="port">NNTP server port. Defualt NNTP port is 119.</param>
        public void Connect(string server,int port)
        {
            if(m_Connected){
                throw new Exception("NNTP client is already connected, Disconnect first before calling Connect !");
            }

            m_pSocket = new SocketEx();
            m_pSocket.Connect(server,port);
            /*
            if(m_LogCmds && SessionLog != null){
                m_pLogger = new SocketLogger(s,SessionLog);
                m_pLogger.SessionID = Guid.NewGuid().ToString();
                m_pSocket.Logger = m_pLogger;
            }*/

            // Set connected flag
            m_Connected = true;

            // Read server response
            string responseLine = m_pSocket.ReadLine(1000);
            if(!responseLine.StartsWith("200")){
                throw new Exception(responseLine);
            }
        }
示例#5
0
        /// <exception cref="System.IO.IOException"></exception>
        private void Negotiate(int port, ServerMessageBlock resp)
        {
            lock (Sbuf)
            {
                if (port == 139)
                {
                    Ssn139();
                }
                else
                {
                    if (port == -1)
                    {
                        port = SmbConstants.DefaultPort;
                    }
                    // 445
                    Socket = new SocketEx(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                    //TCPローカルポートは、毎回空いているものを使う。
                    //https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
                    Socket.Bind(new IPEndPoint(LocalAddr, 0));

                    Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
                                                  port), // <- 445
                                   SmbConstants.ConnTimeout);

                    Socket.SoTimeOut = SmbConstants.SoTimeout;
                    Out = Socket.GetOutputStream();
                    In  = Socket.GetInputStream();
                }
                if (++Mid == 32000)
                {
                    Mid = 1;
                }
                NegotiateRequest.Mid = Mid;
                int n = NegotiateRequest.Encode(Sbuf, 4);
                Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(NegotiateRequest);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
                Out.Write(Sbuf, 0, 4 + n);
                Out.Flush();
                if (PeekKey() == null)
                {
                    throw new IOException("transport closed in negotiate");
                }
                int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
                if (size < 33 || (4 + size) > Sbuf.Length)
                {
                    throw new IOException("Invalid payload size: " + size);
                }
                Readn(In, Sbuf, 4 + 32, size - 32);
                resp.Decode(Sbuf, 4);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(resp);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
            }
        }
示例#6
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Ssn139()
        {
            Name calledName = new Name(Address.FirstCalledName(), 0x20, null);

            do
            {
                Socket = new SocketEx(AddressFamily.InterNetwork,
                                      SocketType.Stream,
                                      ProtocolType.Tcp);

                //TCPローカルポートは、毎回空いているものを使う。
                //https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
                Socket.Bind(new IPEndPoint(LocalAddr, 0));

                Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
                                              139),
                               SmbConstants.ConnTimeout);

                Socket.SoTimeOut = SmbConstants.SoTimeout;

                Out = Socket.GetOutputStream();
                In  = Socket.GetInputStream();
                SessionServicePacket ssp = new SessionRequestPacket(calledName,
                                                                    NbtAddress.GetLocalName());
                Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
                if (Readn(In, Sbuf, 0, 4) < 4)
                {
                    try
                    {
                        //Socket.`Close` method deleted
                        //Socket.Close();
                        Socket.Dispose();
                    }
                    catch (IOException)
                    {
                    }
                    throw new SmbException("EOF during NetBIOS session request");
                }
                switch (Sbuf[0] & 0xFF)
                {
                case SessionServicePacket.PositiveSessionResponse:
                {
                    if (Log.Level >= 4)
                    {
                        Log.WriteLine("session established ok with " + Address);
                    }
                    return;
                }

                case SessionServicePacket.NegativeSessionResponse:
                {
                    int errorCode = In.Read() & 0xFF;
                    switch (errorCode)
                    {
                    case NbtException.CalledNotPresent:
                    case NbtException.NotListeningCalled:
                    {
                        //Socket.`Close` method deleted
                        //Socket.Close();
                        Socket.Dispose();
                        break;
                    }

                    default:
                    {
                        Disconnect(true);
                        throw new NbtException(NbtException.ErrSsnSrvc,
                                               errorCode);
                    }
                    }
                    break;
                }

                case -1:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc,
                                           NbtException.ConnectionRefused);
                }

                default:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, 0);
                }
                }
            }while ((calledName.name = Address.NextCalledName()) != null);
            throw new IOException("Failed to establish session with " + Address);
        }
示例#7
0
        /// <summary>
        /// Connects to sepcified host.
        /// </summary>
        /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param>
        /// <param name="host">Host name or IP address.</param>
        /// <param name="port">Port where to connect.</param>
        /// <param name="ssl">Specifies if to connected via SSL. Default SMTP port is 25 and SSL port is 465.</param>
        public void Connect(IPEndPoint localEndpoint, string host, int port, bool ssl)
        {
            m_pSocket = new SocketEx();
            if (localEndpoint != null)
            {
                m_pSocket.Bind(localEndpoint);
            }

            // Create logger
            if (SessionLog != null)
            {
                m_pLogger = new SocketLogger(m_pSocket.RawSocket, SessionLog);
                m_pLogger.SessionID = Guid.NewGuid().ToString();
                m_pSocket.Logger = m_pLogger;
            }

            if (host.IndexOf("@") == -1)
            {
                m_pSocket.Connect(host, port, ssl);
            }
            else
            {
                //---- Parse e-domain -------------------------------//
                string domain = host;

                // eg. Ivx <*****@*****.**>
                if (domain.IndexOf("<") > -1 && domain.IndexOf(">") > -1)
                {
                    domain = domain.Substring(domain.IndexOf("<") + 1,
                                              domain.IndexOf(">") - domain.IndexOf("<") - 1);
                }

                if (domain.IndexOf("@") > -1)
                {
                    domain = domain.Substring(domain.LastIndexOf("@") + 1);
                }

                if (domain.Trim().Length == 0)
                {
                    if (m_pLogger != null)
                    {
                        m_pLogger.AddTextEntry("Destination address '" + host + "' is invalid, aborting !");
                    }
                    throw new Exception("Destination address '" + host + "' is invalid, aborting !");
                }

                //--- Get MX record -------------------------------------------//
                Dns_Client dns = new Dns_Client();
                Dns_Client.DnsServers = m_pDnsServers;
                DnsServerResponse dnsResponse = dns.Query(domain, QTYPE.MX);

                bool connected = false;
                switch (dnsResponse.ResponseCode)
                {
                    case RCODE.NO_ERROR:
                        DNS_rr_MX[] mxRecords = dnsResponse.GetMXRecords();

                        // Try all available hosts by MX preference order, if can't connect specified host.
                        foreach (DNS_rr_MX mx in mxRecords)
                        {
                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Connecting with mx record to: " + mx.Host);
                                }
                                m_pSocket.Connect(mx.Host, port, ssl);
                                connected = true;
                                break;
                            }
                            catch (Exception x)
                            {
                                // Just skip and let for to try next host.									
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Failed connect to: " + mx.Host + " error:" +
                                                           x.Message);
                                }
                            }
                        }

                        // None of MX didn't connect
                        if (mxRecords.Length > 0 && !connected)
                        {
                            throw new Exception("Destination email server is down");
                        }

                        /* Rfc 2821 5
						 If no MX records are found, but an A RR is found, the A RR is treated as
						 if it was associated with an implicit MX RR, with a preference of 0,
						 pointing to that host.
						*/
                        if (!connected)
                        {
                            // Try to connect with A record
                            IPAddress[] ipEntry = null;
                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("No mx record, trying to get A record for: " +
                                                           domain);
                                }
                                ipEntry = Dns_Client.Resolve(domain);
                            }
                            catch
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                                }
                                throw new Exception("Invalid domain,no MX or A record: " + domain);
                            }

                            try
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Connecting with A record to:" + domain);
                                }
                                m_pSocket.Connect(domain, port, ssl);
                            }
                            catch
                            {
                                if (m_pLogger != null)
                                {
                                    m_pLogger.AddTextEntry("Failed connect to:" + domain);
                                }
                                throw new Exception("Destination email server is down");
                            }
                        }
                        break;

                    case RCODE.NAME_ERROR:
                        if (m_pLogger != null)
                        {
                            m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                        }
                        throw new Exception("Invalid domain,no MX or A record: " + domain);

                    case RCODE.SERVER_FAILURE:
                        if (m_pLogger != null)
                        {
                            m_pLogger.AddTextEntry("Dns server unvailable.");
                        }
                        throw new Exception("Dns server unvailable.");
                }
            }

            /*
			 * Notes: Greeting may be single or multiline response.
			 *		
			 * Examples:
			 *		220<SP>SMTP server ready<CRLF> 
			 * 
			 *		220-SMTP server ready<CRLF>
			 *		220-Addtitional text<CRLF>
			 *		220<SP>final row<CRLF>
			 * 
			*/

            // Read server response
            string responseLine = m_pSocket.ReadLine(1000);
            while (!responseLine.StartsWith("220 "))
            {
                // If lisne won't start with 220, then its error response
                if (!responseLine.StartsWith("220"))
                {
                    throw new Exception(responseLine);
                }

                responseLine = m_pSocket.ReadLine(1000);
            }

            m_Connected = true;
        }
示例#8
0
        /// <exception cref="System.IO.IOException"></exception>
        private void Negotiate(int port, ServerMessageBlock resp)
        {
            lock (Sbuf)
            {
                if (port == 139)
                {
                    Ssn139();
                }
                else
                {
                    if (port == -1)
                    {
                        port = SmbConstants.DefaultPort;
                    }
                    // 445
                    Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    if (LocalAddr != null)
                    {
                        Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
                    }

                    Socket.Connect(Address.GetHostAddress(), port);
                    //Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), port), SmbConstants.ConnTimeout);
                    Socket.SoTimeOut = SmbConstants.SoTimeout;
                    Out = Socket.GetOutputStream();
                    In  = Socket.GetInputStream();
                }
                if (++Mid == 32000)
                {
                    Mid = 1;
                }
                NegotiateRequest.Mid = Mid;
                int n = NegotiateRequest.Encode(Sbuf, 4);
                Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(NegotiateRequest);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
                Out.Write(Sbuf, 0, 4 + n);
                Out.Flush();
                if (PeekKey() == null)
                {
                    throw new IOException("transport closed in negotiate");
                }
                int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
                if (size < 33 || (4 + size) > Sbuf.Length)
                {
                    throw new IOException("Invalid payload size: " + size);
                }
                Readn(In, Sbuf, 4 + 32, size - 32);
                resp.Decode(Sbuf, 4);
                if (Log.Level >= 4)
                {
                    Log.WriteLine(resp);
                    if (Log.Level >= 6)
                    {
                        Hexdump.ToHexdump(Log, Sbuf, 4, n);
                    }
                }
            }
        }
示例#9
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Ssn139()
        {
            Name calledName = new Name(Address.FirstCalledName(), 0x20, null
                                       );

            do
            {
                Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (LocalAddr != null)
                {
                    Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
                }
                Socket.Connect(Address.GetHostAddress(), 139);
                //Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout);
                Socket.SoTimeOut = SmbConstants.SoTimeout;

                Out = Socket.GetOutputStream();
                In  = Socket.GetInputStream();
                SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName
                                                                        ());
                Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
                if (Readn(In, Sbuf, 0, 4) < 4)
                {
                    try
                    {
                        Socket.Dispose();
                    }
                    catch (IOException)
                    {
                    }
                    throw new SmbException("EOF during NetBIOS session request");
                }
                switch (Sbuf[0] & 0xFF)
                {
                case SessionServicePacket.PositiveSessionResponse:
                {
                    if (Log.Level >= 4)
                    {
                        Log.WriteLine("session established ok with " + Address);
                    }
                    return;
                }

                case SessionServicePacket.NegativeSessionResponse:
                {
                    int errorCode = In.Read() & 0xFF;
                    switch (errorCode)
                    {
                    case NbtException.CalledNotPresent:
                    case NbtException.NotListeningCalled:
                    {
                        Socket.Dispose();
                        break;
                    }

                    default:
                    {
                        Disconnect(true);
                        throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
                    }
                    }
                    break;
                }

                case -1:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
                                           );
                }

                default:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, 0);
                }
                }
            }while ((calledName.name = Address.NextCalledName()) != null);
            throw new IOException("Failed to establish session with " + Address);
        }
示例#10
0
        public TrackerResponse MakeWebRequest(Uri uriQuest, string httpProtocol, string headers)
        {
            Encoding encoder = Encoding.GetEncoding(0x4e4);

            Socket = new SocketEx(Proxy, ProxyServer, ProxyPort, ProxyUser, ProxyPassword);
            Socket.SetTimeout(0x30d40);
            Socket.PreAuthenticate = false;
            log.Info($"Connecting to {uriQuest.Host}:{uriQuest.Port}");
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    Socket.Connect(uriQuest.Host, uriQuest.Port);
                    log.Info("Connected Successfully");
                    break;
                }
                catch (Exception ex)
                {
                    log.Warn(ex);
                    log.Warn("Failed connection attempt: " + i);
                }
            }
            if (!Socket.Connected)
            {
                log.Error("Unable to connect. Quitting...");
                return(null);
            }
            log.Info("======== Sending Command to Tracker ========");
            string cmd = "GET " + uriQuest.PathAndQuery + " " + httpProtocol + "\r\n" + headers.Replace("{host}", uriQuest.Host) + "\r\n";

            Socket.Send(encoder.GetBytes(cmd));

            try
            {
                byte[] data = new byte[32 * 1024];
                using (MemoryStream memStream = new MemoryStream())
                {
                    int dataLen = Socket.Receive(data);
                    while (dataLen > 0)
                    {
                        memStream.Write(data, 0, dataLen);
                        dataLen = Socket.Receive(data);
                    }

                    if (memStream.Length == 0)
                    {
                        log.Info("Error : Tracker Response is empty");
                        return(null);
                    }

                    TrackerResponse trackerResponse = new TrackerResponse(memStream);
                    memStream.Close();
                    Socket.Close();

                    if (trackerResponse.doRedirect)
                    {
                        return(MakeWebRequest(new Uri(trackerResponse.RedirectionURL), httpProtocol, headers));
                    }

                    log.Info("======== Tracker Response ========");
                    log.Info(trackerResponse.Headers.ToString());
                    if (trackerResponse.Dico == null)
                    {
                        log.Warn("*** Failed to decode tracker response :");
                        log.Warn(trackerResponse.Body);
                    }

                    return(trackerResponse);
                }
            }
            catch (Exception ex)
            {
                Socket.Close();
                log.Error(ex);
                return(null);
            }
        }
        /// <summary>
        /// Connects to specified host.
        /// </summary>
        /// <param name="host">Host name.</param>
        /// <param name="port">Port.</param>
        public void Connect(string host,int port)
        {
            m_pSocket = new SocketEx();
            m_pSocket.Connect(host,port);

            string reply = m_pSocket.ReadLine();
            while(!reply.StartsWith("220 ")){
                reply = m_pSocket.ReadLine();
            }

            m_Connected = true;
        }
        /// <summary>
        /// Connects to IMAP server.
        /// </summary>		
        /// <param name="host">Host name.</param>
        /// <param name="port">Port number. Default IMAP port is 143 and SSL port is 993.</param>
        /// <param name="ssl">Specifies if to connected via SSL.</param>
        public void Connect(string host,int port,bool ssl)
        {
            if(!m_Connected){
                m_pSocket = new SocketEx();
                m_pSocket.Connect(host,port,ssl);

                string reply = m_pSocket.ReadLine();
                reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag

                if(!reply.ToUpper().StartsWith("OK")){
                    m_pSocket.Disconnect();
                    m_pSocket = null;
                    throw new Exception("Server returned:" + reply);
                }

                m_Connected = true;
                // Clear path separator, so next access will get it.
                m_PathSeparator  = '\0';
            }
        }
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner SIP_TransportLayer.</param>
            /// <param name="remoteEP">Remote end point.</param>
            /// <param name="ssl">Specifies if SSL pipe.</param>
            public SipTcpPipe(SIP_TransportLayer owner,IPEndPoint remoteEP,bool ssl)
            {
                m_pTLayer = owner;

                m_pSocket = new SocketEx();
                m_pSocket.Connect(remoteEP,true);
                if(ssl){
                    m_Transport = SIP_Transport.TLS;
                    m_pSocket.SwitchToSSL_AsClient();
                }
                else{
                    m_Transport = SIP_Transport.TLS;
                }

                // Add this to TCP pipes collection.
                m_pTLayer.m_pTcpReceiviePipes.Add(this);

                Start();
            }