func XSISubscribeCH(Config ConfigT, def DefHead) (net.Conn, string) { var CPOST string = "POST /com.broadsoft.async/com.broadsoft.xsi-events/v2.0/channel HTTP/1.1" var CSET string = ConcatStr("", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Channel xmlns=\"http://schema.broadsoft.com/xsi\"><channelSetId>", def.CHANID, "</channelSetId><priority>1</priority><weight>100</weight><expires>", Config.Main.Expires, "</expires></Channel>") var CLEN string = ConcatStr("", "Content-Length: ", strconv.Itoa(len(CSET))) var dialer net.Dialer dialer.Timeout = time.Second chandesc, err := dialer.Dial("tcp", ConcatStr(":", Config.Main.Host, Config.Main.HTTPPort)) if err != nil { LogErr(err, "chan dial") } fmt.Fprintf(chandesc, "%s\n%s\n%s\n%s\n%s\n\n%s\n", CPOST, def.AUTHORIZATION, def.HOSTH, CLEN, def.CTYPE, CSET) chanreader := bufio.NewReader(chandesc) status, err := chanreader.ReadString('\n') if err != nil { LogErr(err, "chan read") } if !strings.Contains(status, "200") { LogErr(nil, "chan status", status) } //get new chan id data := make([]byte, 1024) _, err = chanreader.Read(data) chanID := GetChanID(data) return chandesc, chanID }
func NewClient(originURL, targetURL string, settings map[string]interface{}) (c *websocket.Conn, response *http.Response, err error) { u, err := url.Parse(targetURL) if err != nil { return nil, nil, err } dialer := net.Dialer{} timeoutInterface, ok := settings["Timeout"] if ok { dialer.Timeout = timeoutInterface.(time.Duration) } keepAliveInterface, ok := settings["KeepAlive"] if ok { dialer.KeepAlive = keepAliveInterface.(time.Duration) } rawConn, err := dialer.Dial("tcp", u.Host) if err != nil { logrus.WithFields(logrus.Fields{ "Error": err.Error(), }).Errorf("TCP connection error when dialing %v", u.Host) return nil, nil, err } wsHeaders := http.Header{ "Origin": {originURL}, // your milage may differ "Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"}, } return websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024) }
// Connects to a Riak server. func (c *Client) Connect() error { d := new(net.Dialer) if c.connTimeout > 0 { d.Timeout = c.connTimeout } return c.tcpConnect(d) }
// dialContext connects to the address on the named network. func dialContext(ctx context.Context, network, address string) (net.Conn, error) { var dialer net.Dialer if deadline, ok := ctx.Deadline(); ok { dialer.Timeout = deadline.Sub(time.Now()) } return dialer.Dial(network, address) }
// 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) }
func Dial(addr string) (*wrap, error) { co, err := GenerateEmptyConfig() if err != nil { return nil, err } d := net.Dialer{} d.Timeout = 3 * time.Second c, err := tls.DialWithDialer(&d, "tcp", addr, co) return Wrap(c), err }
// DialTimeoutWithTLS acts like DialWithTLS but takes a timeout. func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) { var dialer net.Dialer dialer.Timeout = timeout conn = new(Conn) conn.Conn, err = tls.DialWithDialer(&dialer, network, address, tlsConfig) if err != nil { return nil, err } return conn, nil }
func (d *Dialer) dialSerial(network, addr string, ips []net.IP, port string) (net.Conn, error) { dialer := net.Dialer{ Timeout: d.Timeout, Deadline: d.Deadline, KeepAlive: d.KeepAlive, LocalAddr: d.LocalAddr, } // Ensure the deadline is set when a timeout is set, so that the total // amount of time used does not exceed the timeout even when multiple // requests are made. if dialer.Timeout > 0 { newDeadline := time.Now().Add(dialer.Timeout) if dialer.Deadline.IsZero() || newDeadline.Before(d.Deadline) { dialer.Deadline = newDeadline } } // Ensure that the timeout for each operation is small enough that // if connecting to the first address times out, the other addresses // will be tried. if !dialer.Deadline.IsZero() { totalTime := dialer.Deadline.Sub(time.Now()) newTimeout := totalTime / time.Duration(len(ips)) if newTimeout < 2*time.Second { newTimeout = 2 * time.Second } if dialer.Timeout == 0 || newTimeout < dialer.Timeout { dialer.Timeout = newTimeout } } var firstErr error for _, ip := range ips { conn, err := dialer.Dial(network, net.JoinHostPort(ip.String(), port)) if err != nil { if firstErr == nil { firstErr = err } continue } return conn, nil } if firstErr == nil { firstErr = fmt.Errorf("dialer.Dial no IP addresses found: %s", addr) } return nil, firstErr }
func testip_once(ip string, options *ScanOptions, record *ScanRecord) bool { start := time.Now() var end time.Time pingRTT := (options.Config.ScanMinPingRTT + options.Config.ScanMaxPingRTT) / 2 if options.Config.VerifyPing { err := Ping(ip, options.Config.ScanMaxPingRTT) if err != nil { log.Printf("####error ip:%s for %v", ip, err) return false } end = time.Now() if nil == err { if options.Config.ScanMinPingRTT > 0 && end.Sub(start) < options.Config.ScanMinPingRTT { return false } pingRTT = end.Sub(start) } } record.PingRTT = record.PingRTT + pingRTT addr := net.JoinHostPort(ip, "443") var config tls.Config config.InsecureSkipVerify = true dialer := new(net.Dialer) dialer.Timeout = options.Config.ScanMaxSSLRTT conn, err := tls.DialWithDialer(dialer, "tcp", addr, &config) if err != nil { //log.Printf("####ssl dial:%v", err) return false } end = time.Now() sslRTT := end.Sub(start) if options.Config.ScanMinSSLRTT > 0 && sslRTT < options.Config.ScanMinSSLRTT { conn.Close() return false } success := true record.httpVerifyTimeout = options.Config.ScanMaxSSLRTT - sslRTT if options.Config.scanIP { success = test_conn(conn, options, record) } else { success = find_match_hosts(conn, options, record) } //end = time.Now() conn.Close() if success { record.SSLRTT = record.SSLRTT + sslRTT } return success }
func (w *tlsWriter) Connect() error { w.mu.Lock() defer w.mu.Unlock() if w.conn != nil { // ignore err from close, it makes sense to continue anyway w.conn.Close() w.conn = nil } dialer := new(net.Dialer) dialer.Timeout = 500 * time.Millisecond c, err := tls.DialWithDialer(dialer, "tcp", w.host, w.tlsConfig) if err == nil { w.conn = c } return err }
func ConnectSrv(Config ConfigT) net.Conn { var dialer net.Dialer dialer.Timeout = time.Second dialer.KeepAlive = time.Minute chandesc, err := dialer.Dial("tcp", ConcatStr(":", Config.Main.Server, Config.Main.Port)) if err != nil { LogErr(err, "serv dial") return nil } else { var send string = Config.Main.CCID for _, target := range Config.Main.TargetID { send = ConcatStr(" ", send, target) } fmt.Fprintf(chandesc, "%s", send) return chandesc } }
// call sends an RPC to the rpcname handler on server srv // with arguments args, waits for the reply, and leaves the // reply in reply. the reply argument should be a pointer // to a reply structure. // // the return value is true if the server responded, and false // if call() was not able to contact the server. in particular, // the replys contents are only valid if call() returned true. func call(srv string, name string, clientAddr *string, args interface{}, reply interface{}) bool { var d net.Dialer if clientAddr != nil { // need to specify the port at 0 // let the kernel choose a random port addr, _ := net.ResolveTCPAddr("tcp", ip(*clientAddr)+":0") d.LocalAddr = addr // also set the timeout d.Timeout = timeOut } // tcp dial conn, err := d.Dial("tcp", srv) if err != nil { err1 := err.(*net.OpError) if err1.Err != syscall.ENOENT && err1.Err != syscall.ECONNREFUSED { fmt.Printf("paxos Dial(%s) failed: %v\n", srv, err1) } return false } client := rpc.NewClient(conn) defer conn.Close() defer client.Close() // rpc call rpcErrChan := make(chan error) go func() { rpcErrChan <- client.Call(name, args, reply) }() select { case <-time.After(timeOut): return false case err := <-rpcErrChan: if err == nil { return true } fmt.Println(err) return false } }
// Client takes a Config struct and returns a new Conn ready to have // handlers added and connect to a server. func Client(cfg *Config) *Conn { if cfg == nil { cfg = NewConfig("__idiot__") } if cfg.Me == nil || cfg.Me.Nick == "" || cfg.Me.Ident == "" { cfg.Me = &state.Nick{Nick: "__idiot__"} cfg.Me.Ident = "goirc" cfg.Me.Name = "Powered by GoIRC" } dialer := new(net.Dialer) dialer.Timeout = cfg.Timeout if cfg.LocalAddr != "" { if !hasPort(cfg.LocalAddr) { cfg.LocalAddr += ":0" } local, err := net.ResolveTCPAddr("tcp", cfg.LocalAddr) if err == nil { dialer.LocalAddr = local } else { logging.Error("irc.Client(): Cannot resolve local address %s: %s", cfg.LocalAddr, err) } } conn := &Conn{ cfg: cfg, dialer: dialer, in: make(chan *Line, 32), out: make(chan string, 32), intHandlers: handlerSet(), fgHandlers: handlerSet(), bgHandlers: handlerSet(), stRemovers: make([]Remover, 0, len(stHandlers)), lastsent: time.Now(), } conn.addIntHandlers() return conn }
func connectTls(ctx *Context) (net.Conn, error) { if ctx.TlsConfig == nil { ctx.TlsConfig = new(tls.Config) } if ctx.TlsConfig.NextProtos == nil { ctx.TlsConfig.NextProtos = append(ctx.TlsConfig.NextProtos, "h2-14", "h2-15", "h2-16", "h2") } dialer := new(net.Dialer) dialer.Timeout = ctx.Timeout conn, err := tls.DialWithDialer(dialer, "tcp", ctx.Authority(), ctx.TlsConfig) if err != nil { return nil, err } cs := conn.ConnectionState() if !cs.NegotiatedProtocolIsMutual { return nil, fmt.Errorf("HTTP/2 protocol was not negotiated") } return conn, err }
func OCIPsend(Config ConfigT, COMMAND string, args ...string) string { var SESSION string = randSeq(10) var HEAD string = ConcatStr("", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><BroadsoftDocument protocol = \"OCI\" xmlns=\"C\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><sessionId xmlns=\"\">", SESSION, "</sessionId>") var dialer net.Dialer dialer.Timeout = time.Second chandesc, err := dialer.Dial("tcp", ConcatStr(":", Config.Main.Host, Config.Main.OCIPPort)) if err != nil { LogErr(err, "OCIP connection") } chandesc.SetReadDeadline(time.Now().Add(time.Second)) AUTH := ConcatStr("", "<command xsi:type=\"AuthenticationRequest\" xmlns=\"\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><userId>", Config.Main.User, "</userId></command></BroadsoftDocument>") fmt.Fprintf(chandesc, "%s%s", HEAD, AUTH) chanreader := bufio.NewReader(chandesc) status, err := chanreader.ReadString('\n') status, err = chanreader.ReadString('\n') ocip := ParseOCIP([]byte(status)) responce := MakeDigest(Config.Main.Password, ocip.Nonce) LOGIN := ConcatStr("", "<command xsi:type=\"LoginRequest14sp4\" xmlns=\"\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><userId>", Config.Main.User, "</userId><signedPassword>", responce, "</signedPassword></command></BroadsoftDocument>") fmt.Fprintf(chandesc, "%s%s", HEAD, LOGIN) status, err = chanreader.ReadString('\n') status, err = chanreader.ReadString('\n') var ARGS string separated := strings.Split(strings.Join(args, "="), "=") if len(separated) > 1 { for i := 0; i < len(separated); i = i + 2 { ARGS = ConcatStr("", ARGS, "<", separated[i], ">", separated[i+1], "</", separated[i], ">") } } REQ := ConcatStr("", "<command xsi:type=\"", COMMAND, "\" xmlns=\"\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">", ARGS, "</command></BroadsoftDocument>") fmt.Fprintf(chandesc, "%s%s", HEAD, REQ) status, err = chanreader.ReadString('\n') status, err = chanreader.ReadString('\n') LOGOUT := ConcatStr("", "<command xsi:type=\"LogoutRequest\" xmlns=\"\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><userId>", Config.Main.User, "</userId></command></BroadsoftDocument>") fmt.Fprintf(chandesc, "%s%s", HEAD, LOGOUT) chandesc.Close() return status }
func (d *driver) Open(dsn string) (drv.Conn, error) { u, err := url.Parse(dsn) if err != nil { return nil, err } params := u.Query() var ( username = "" password = "" db = "" ) if u.User != nil { username = u.User.Username() if tmp, ok := u.User.Password(); ok { password = tmp } } if tmp := params.Get("db"); tmp != "" { db = tmp } var ( dialer net.Dialer ) if tmp, err := time.ParseDuration(params.Get("timeout")); err == nil { dialer.Timeout = tmp } var ( prot string addr string ) prot = u.Scheme switch prot { case "tcp": addr = u.Host case "unix": addr = u.Path default: return nil, &UnknownProtocolError{prot: prot} } nc, err := dialer.Dial(prot, addr) if err != nil { return nil, err } c := newConn(nc) // We have to complete the handshake before we can use the connection. err = c.handshake(username, password, db) if err != nil { return nil, err } return c, nil }