func (s *Server) acceptUDP() { // Looping for new messages for { buf := make([]byte, MAX_MSG_SIZE) n, adr, err := s.udpsock.ReadFrom(buf) if s.comm.running { if err != nil { log.Error("Error while reading UDP (read %d) from %s: %s\n", n, adr, err) } else { abcon := net.Conn(s.udpsock) connection := NewConnection(s.comm.pool, P_UDP, D_Inbound, abcon) read := io.Reader(bytes.NewBuffer(buf)) msg := s.comm.NewMessage() msg.connection = connection err := msg.readMessage(read) if err != nil { log.Error("Couldn't handle message received from UDP because of errors: %s %s\n", msg, err) } else { go s.comm.handleMessage(msg) } } } else { log.Info("Dropping connection because communications have been paused") } } }
// 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 }
// HandleStartTLS is the companion to StartTLS, and will do the connection upgrade. It assumes // that the TLS command byte has already been read. Like StartTLS it returns the peer name, or // an error func (p *Protocol) HandleStartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) { var ( err error tlsConn *tls.Conn ) // Build the config config := new(tls.Config) config.ClientAuth = tls.RequireAndVerifyClientCert // Setup the tls connection if err := p.tlsSetup(config, identity, caCertificate); err != nil { return "", err } // Upgrade the connection to TLS // TODO: Add a deadline here? tlsConn = tls.Server(p.conn, config) if err = tlsConn.Handshake(); err != nil { return "", err } // Capture the connection state cs := tlsConn.ConnectionState() // And replace the original connection p.conn = net.Conn(tlsConn) p.setupBuffers() // Send an Ack p.Ack() return cs.PeerCertificates[0].Subject.CommonName, nil }
// StartTLS takes an identity and an authority certificate and upgrades the net.Conn on the protocol to TLS // It returns the CommonName from the peer certitifcate, or an error func (p *Protocol) StartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) { var ( err error tlsConn *tls.Conn ) if err = p.WriteBytesWithDeadline([]byte{TLS}); err != nil { return "", err } // Build the config config := new(tls.Config) config.ServerName = p.serverName // Setup the tls connection if err = p.tlsSetup(config, identity, caCertificate); err != nil { return "", err } // Upgrade the connection to TLS // TODO: Add a deadline here? tlsConn = tls.Client(p.conn, config) if err = tlsConn.Handshake(); err != nil { return "", err } // Capture the connection state cs := tlsConn.ConnectionState() // And replace the original connection p.conn = net.Conn(tlsConn) p.setupBuffers() return cs.PeerCertificates[0].Subject.CommonName, nil }
// SNIHost will try preempt the TLS handshake and try to sniff the // Server Name Indication. It returns `Host()` for non CONNECT // requests, so it is always safe to call. If it sniffed // successfully, but didn't find anything, it is possible to return an // empty string. func (ctx *ProxyCtx) SNIHost() string { if ctx.Method != "CONNECT" { return ctx.Host() } if ctx.sniffedTLS { return ctx.sniHost } ctx.Conn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n")) tlsConn, err := vhost.TLS(ctx.Conn) ctx.Conn = net.Conn(tlsConn) ctx.sniffedTLS = true if err != nil { ctx.Logf("Failed to sniff SNI (falling back to request Host): %s", err) return ctx.Host() } // TODO: make sure we put a ":port" on the `host` if there was one previously... sniHost := tlsConn.Host() if sniHost != "" { ctx.SetDestinationHost(inheritPort(sniHost, ctx.Host())) ctx.sniHost = ctx.Host() } return ctx.sniHost }
func TestIssue292(t *testing.T) { // The util/conn.Manager won't attempt to reconnect to the provided endpoint // if the endpoint is initially unavailable (e.g. dial tcp :8080: // getsockopt: connection refused). If the endpoint is up when // conn.NewManager is called and then goes down/up, it reconnects just fine. var ( tickc = make(chan time.Time) after = func(time.Duration) <-chan time.Time { return tickc } dialconn = net.Conn(nil) dialerr = errors.New("fail") dialer = func(string, string) (net.Conn, error) { return dialconn, dialerr } mgr = NewManager(dialer, "netw", "addr", after, log.NewNopLogger()) ) if conn := mgr.Take(); conn != nil { t.Fatal("first Take should have yielded nil conn, but didn't") } dialconn, dialerr = &mockConn{}, nil select { case tickc <- time.Now(): case <-time.After(time.Second): t.Fatal("manager isn't listening for a tick, despite a failed dial") } if !within(time.Second, func() bool { return mgr.Take() != nil }) { t.Fatal("second Take should have yielded good conn, but didn't") } }
func (t *TCP) startTLS() (el element.Element, err error) { var tlsConn *tls.Conn if t.mode == stream.Initiating { err = t.WriteElement(element.StartTLS) if err != nil { return } el, err = t.Next() if err != nil || el.Tag != element.TLSProceed.Tag { return } tlsConn = tls.Client(t.Conn, t.conf) } else { err = t.WriteElement(element.TLSProceed) if err != nil { return } tlsConn = tls.Server(t.Conn, t.conf) } err = tlsConn.Handshake() if err != nil { return } conn := net.Conn(tlsConn) t.Conn = conn t.Decoder = xml.NewDecoder(conn) el = element.Element{} err = stream.ErrRequireRestart t.secure = true log.Println("Done upgrading connection") return }
func (server *TcpServer) Start() (err error) { for { var conn *net.TCPConn if conn, err = server.TCPListener.AcceptTCP(); err != nil { return err } if server.keepAlive != nil { if err := conn.SetKeepAlive(server.keepAlive.(bool)); err != nil { return err } } if server.keepAlivePeriod != nil { if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok { if err := kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil { return err } } } if server.linger != nil { if err := conn.SetLinger(server.linger.(int)); err != nil { return err } } if server.noDelay != nil { if err := conn.SetNoDelay(server.noDelay.(bool)); err != nil { return err } } if server.readBuffer != nil { if err := conn.SetReadBuffer(server.readBuffer.(int)); err != nil { return err } } if server.writerBuffer != nil { if err := conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil { return err } } if server.deadline != nil { if err := conn.SetDeadline(server.deadline.(time.Time)); err != nil { return err } } if server.readDeadline != nil { if err := conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil { return err } } if server.writerDeadline != nil { if err := conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil { return err } } if server.config != nil { server.ServeTCP(tls.Client(conn, server.config)) } else { server.ServeTCP(conn) } } }
func (l *Listener) Accept() (c net.Conn, err error) { l.m.Lock() defer l.m.Unlock() if l.err == nil { l.err = errAccepted return net.Conn(l.client), nil } return nil, l.err }
func (p *Pool) GetMsgConnection(node *cluster.Node) *Connection { // TODO: IMPLEMENT THE POOLING adr := net.UDPAddr{node.Address, int(node.UdpPort)} con, err := net.DialUDP("udp", nil, &adr) // TODO: should use local address instead of nil (implicitly local) if err != nil { log.Error("NETPOOL: Couldn't create a connection\n", err) return nil } abcon := net.Conn(con) connection := NewConnection(p, P_UDP, D_Outbound, abcon) return connection }
// Upgrades a client connection to TLS func (server *server) upgradeToTLS(client *client) bool { tlsConn := tls.Server(client.conn, server.tlsConfig) err := tlsConn.Handshake() if err != nil { log.WithError(err).Warn("[%s] Failed TLS handshake", client.RemoteAddress) return false } client.conn = net.Conn(tlsConn) client.bufin = newSMTPBufferedReader(client.conn) client.bufout = bufio.NewWriter(client.conn) client.TLS = true return true }
func TestRePConn2(t *testing.T) { c, err := net.Dial("tcp", "www.baidu.com:80") if err != nil { t.Errorf("连接错误:%v", err) } if _, err := c.Write([]byte("GET / HTTP/1.0\r\nHOST:www.baidu.com\r\n\r\n")); err != nil { t.Errorf("写错误:", err) } tConn := TConn{c} preconn := NewPreConn(tConn) preconn.NewPre() // 第一次读取 b1 := make([]byte, 16384) if n, err := preconn.Read(b1); err != nil { t.Errorf("读错误:%v", err) } else { b1 = b1[:n] } preconn.ResetPreOffset() // 预读的实现是只要缓冲区有数据,即使不够也会直接返回而不是阻塞在Read里面 // 所以这里应该是相同的长度。 b2 := make([]byte, 16384) if n, err := preconn.Read(b2); err != nil { t.Errorf("读错误:", err) } else { b2 = b2[:n] } if bytes.Equal(b1, b2) != true { t.Errorf("预读会退结果不相等") } preconn.ResetPreOffset() conn := net.Conn(preconn) b2 = b2[:16384] if n, err := conn.Read(b2); err != nil { t.Errorf("读错误:%v", err) } else { b2 = b2[:n] } if bytes.Equal(b1, b2) != true { t.Errorf("预读会退结果不相等") } }
func notify(path, msg string) error { addr := net.UnixAddr{ Net: netType, Name: path, } conn, err := net.DialUnix(netType, nil, &addr) if err != nil { return err } defer net.Conn(conn).Close() _, err = conn.Write([]byte(msg)) return err }
// Reconnect forces a new connection to the gateway // If a connection exists it is closed before the creation of a new one func (c *PersistentClient) Reconnect() error { var cert tls.Certificate var err error if c.isConnected == true { c.Close() } if len(c.client.certificateBase64) == 0 && len(c.client.keyBase64) == 0 { // The user did not specify raw block contents, so check the filesystem. cert, err = tls.LoadX509KeyPair(c.client.certificateFile, c.client.keyFile) } else { // The user provided the raw block contents, so use that. cert, err = tls.X509KeyPair([]byte(c.client.certificateBase64), []byte(c.client.keyBase64)) } if err != nil { return err } gatewayParts := strings.Split(c.client.gateway, ":") conf := &tls.Config{ Certificates: []tls.Certificate{cert}, ServerName: gatewayParts[0], } if c.ip == "" { // If the ip is not provided pick one ip, err := pickGatewayIP(gatewayParts[0]) if err != nil { return err } c.ip = ip } conn, err := net.Dial("tcp", c.ip+":"+gatewayParts[1]) if err != nil { return err } tlsConn := tls.Client(conn, conf) err = tlsConn.Handshake() if err != nil { conn.Close() return err } c.mu.Lock() c.conn = net.Conn(tlsConn) c.isConnected = true c.mu.Unlock() log.Printf("Address of %s is %s", c.client.gateway, c.conn.RemoteAddr().String()) return nil }
func (c *Conn) upgradeSnappy() error { conn := net.Conn(c.conn) if c.tlsConn != nil { conn = c.tlsConn } c.r = snappystream.NewReader(conn, snappystream.SkipVerifyChecksum) c.w = snappystream.NewWriter(conn) frameType, data, err := ReadUnpackedResponse(c) if err != nil { return err } if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) { return errors.New("invalid response from Snappy upgrade") } return nil }
// NewDirectHTTPRPCClient creates a rpc http client func NewDirectHTTPRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, path string, timeout time.Duration) (*rpc.Client, error) { if path == "" { path = rpc.DefaultRPCPath } 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, "tcp", address, c.TLSConfig) //or conn:= tls.Client(netConn, &config) conn = net.Conn(tlsConn) } else { conn, err = net.DialTimeout("tcp", address, timeout) } if err != nil { return nil, err } io.WriteString(conn, "CONNECT "+path+" HTTP/1.0\n\n") // Require successful HTTP response // before switching to RPC protocol. resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"}) if err == nil && resp.Status == connected { if c == nil || c.PluginContainer == nil { return rpc.NewClientWithCodec(clientCodecFunc(conn)), nil } return rpc.NewClientWithCodec(newClientCodecWrapper(c.PluginContainer, clientCodecFunc(conn))), nil } if err == nil { err = errors.New("unexpected HTTP response: " + resp.Status) } conn.Close() return nil, &net.OpError{ Op: "dial-http", Net: network + " " + address, Addr: nil, Err: err, } }
func (c *Conn) upgradeDeflate(level int) error { conn := net.Conn(c.conn) if c.tlsConn != nil { conn = c.tlsConn } fw, _ := flate.NewWriter(conn, level) c.r = flate.NewReader(conn) c.w = fw frameType, data, err := ReadUnpackedResponse(c) if err != nil { return err } if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) { return errors.New("invalid response from Deflate upgrade") } return nil }
func obfs_accept(listener net.Listener) (net.Conn, error) { c, err := listener.Accept() if err != nil { return nil, err } conn := net.Conn(nil) donechan := make(chan error) eee := error(nil) go func() { conn, err = Kiriobfs_handshake_server(c) eee = err donechan <- err }() select { case <-donechan: return conn, eee case <-time.After(time.Second * time.Duration(10)): return nil, errors.New("timed out") } }
// ServeTCP ... func (service *TcpService) ServeTCP(conn *net.TCPConn) (err error) { if service.keepAlive != nil { if err = conn.SetKeepAlive(service.keepAlive.(bool)); err != nil { return err } } if service.keepAlivePeriod != nil { if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok { if err = kap.SetKeepAlivePeriod(service.keepAlivePeriod.(time.Duration)); err != nil { return err } } } if service.linger != nil { if err = conn.SetLinger(service.linger.(int)); err != nil { return err } } if service.noDelay != nil { if err = conn.SetNoDelay(service.noDelay.(bool)); err != nil { return err } } if service.readBuffer != nil { if err = conn.SetReadBuffer(service.readBuffer.(int)); err != nil { return err } } if service.writeBuffer != nil { if err = conn.SetWriteBuffer(service.writeBuffer.(int)); err != nil { return err } } if service.config != nil { tlsConn := tls.Server(conn, service.config) tlsConn.Handshake() return service.Serve(tlsConn) } return service.Serve(conn) }
func (s *SMTPClientSession) Handler() { defer s.Close() start := time.Now().UnixNano() for { switch s.state { case INIT: s.addResponse("220 protonuke: Less for outcasts, more for weirdos.") s.state = COMMANDS case COMMANDS: input, err := s.readSmtp() input = strings.Trim(input, "\r\n") cmd := strings.ToUpper(input) if err != nil { log.Debugln(err) return } switch { case strings.HasPrefix(cmd, "HELO"): s.addResponse("250 You're all so great and we're gonna keep you listening all day") case strings.HasPrefix(cmd, "EHLO"): r := "250-" + myFQDN + " Serving mail almost makes you wish for a nuclear winter\r\n" r += "250-8BITMIME\r\n250-STARTTLS\r\n250 HELP" s.addResponse(r) case strings.HasPrefix(cmd, "MAIL FROM:"): if len(input) > 10 { s.mail_from = input[10:] } s.addResponse("250 Ok") case strings.HasPrefix(cmd, "RCPT TO:"): if len(input) > 8 { s.rcpt_to = append(s.rcpt_to, input[8:]) } s.addResponse("250 Ok") case strings.HasPrefix(cmd, "DATA"): s.addResponse("354 End data with <CR><LF>.<CR><LF>") s.state = DATA case strings.HasPrefix(cmd, "STARTTLS") && !s.tls_on: s.addResponse("220 They asked what do you know about theoretical physics? I said I had a theoretical degree in physics.") s.state = STARTTLS case strings.HasPrefix(cmd, "QUIT"): s.addResponse("221 Beware the Battle Cattle!") s.state = QUIT case strings.HasPrefix(cmd, "NOOP"): s.addResponse("250 Is it time?") case strings.HasPrefix(cmd, "RSET"): s.mail_from = "" s.rcpt_to = []string{} s.addResponse("250 I forgot to remember to forget") default: s.addResponse("500 unrecognized command") } case DATA: input, err := s.readSmtp() if err != nil { log.Debugln(err) } s.data = input log.Debugln("Got email message:") log.Debugln(s) s.addResponse("250 Ok: Now that is a delivery service you can count on") s.state = COMMANDS case STARTTLS: // I'm just going to pull this from GoGuerrilla, thanks guys var tlsConn *tls.Conn tlsConn = tls.Server(s.conn, TLSconfig) err := tlsConn.Handshake() // not necessary to call here, but might as well if err == nil { s.conn = net.Conn(tlsConn) s.bufin = bufio.NewReader(s.conn) s.bufout = bufio.NewWriter(s.conn) s.tls_on = true } else { log.Debugln("Could not TLS handshake:", err) } s.state = COMMANDS case QUIT: stop := time.Now().UnixNano() log.Info("smtp %v %vns", s.conn.RemoteAddr(), uint64(stop-start)) return } size, _ := s.bufout.WriteString(s.response) s.bufout.Flush() s.response = s.response[size:] } }
// Kirisurf_handshake_client returns a socket obfuscating the socket sock after // initiating the client-side handshake. func Kiriobfs_handshake_client(sock net.Conn) (net.Conn, error) { // generate our keypair our_keypair := kicrypt.UniformDH_genpair() scatch := make(chan bool, 16) //send our key c, err := sock.Write(our_keypair.PublicBytes()) LOG(LOG_DEBUG, "Sent our %d-byte key", c) if err != nil { return nil, errors.New("error encountered when sending uniformdh pubkey") } //send 16384 bytes of garbage go func() { for i := 0; i < 64; i++ { buf := make([]byte, 256) rand.Reader.Read(buf) c, err := sock.Write(buf) if err != nil && c == c { return } } scatch <- true }() // read their key buf := make([]byte, 192) _, ecd := io.ReadFull(sock, buf) if ecd != nil { return nil, ecd } LOG(LOG_DEBUG, "Read their %d-byte key", 192) theirpub := big.NewInt(0).SetBytes(buf) //read 16384 bytes of garbage from remote go func() { buf := make([]byte, 16384) _, err := io.ReadFull(sock, buf) if err != nil { return } scatch <- true }() //synchronize <-scatch <-scatch LOG(LOG_DEBUG, "All garbage-related things done.") //shared secret shared_secret := kicrypt.UniformDH_gensecret(our_keypair.Private, theirpub) up_key := kicrypt.KeyedHash(shared_secret, "kiriobfs/up") down_key := kicrypt.KeyedHash(shared_secret, "kiriobfs/down") LOG(LOG_DEBUG, "Shared secret derived.") //RC4 initialization var toret Kiriobfs_state toret.RC4_state_r, err = rc4.NewCipher(down_key) toret.RC4_state_w, err = rc4.NewCipher(up_key) toret.underlying = sock throwaway := make([]byte, 8192) toret.RC4_state_r.XORKeyStream(throwaway, throwaway) toret.RC4_state_w.XORKeyStream(throwaway, throwaway) //Actual garbage blarg := make([]byte, 2) rand.Reader.Read(blarg) bllen := big.NewInt(0).SetBytes(blarg).Int64() toret.Write(blarg) toret.Write(make([]byte, bllen)) LOG(LOG_DEBUG, "Encrypted junk sent.") //Read the actual garbage glarg := make([]byte, 2) io.ReadFull(net.Conn(toret), glarg) glwerg := make([]byte, big.NewInt(0).SetBytes(glarg).Int64()) io.ReadFull(net.Conn(toret), glwerg) return net.Conn(toret), nil }
func handleClient(client *Client) { defer closeClient(client) // defer closeClient(client) greeting := "220 " + gConfig["GSMTP_HOST_NAME"] + " SMTP Guerrilla-SMTPd #" + strconv.FormatInt(client.clientId, 10) + " (" + strconv.Itoa(len(sem)) + ") " + time.Now().Format(time.RFC1123Z) advertiseTls := "250-STARTTLS\r\n" for i := 0; i < 100; i++ { switch client.state { case 0: responseAdd(client, greeting) client.state = 1 case 1: input, err := readSmtp(client) if err != nil { logln(1, fmt.Sprintf("Read error: %v", err)) if err == io.EOF { // client closed the connection already return } if neterr, ok := err.(net.Error); ok && neterr.Timeout() { // too slow, timeout return } break } input = strings.Trim(input, " \n\r") cmd := strings.ToUpper(input) switch { case strings.Index(cmd, "HELO") == 0: if len(input) > 5 { client.helo = input[5:] } responseAdd(client, "250 "+gConfig["GSMTP_HOST_NAME"]+" Hello ") case strings.Index(cmd, "EHLO") == 0: if len(input) > 5 { client.helo = input[5:] } responseAdd(client, "250-"+gConfig["GSMTP_HOST_NAME"]+" Hello "+client.helo+"["+client.address+"]"+"\r\n"+"250-SIZE "+gConfig["GSMTP_MAX_SIZE"]+"\r\n"+advertiseTls+"250 HELP") case strings.Index(cmd, "MAIL FROM:") == 0: if len(input) > 10 { client.mail_from = input[10:] } responseAdd(client, "250 Ok") case strings.Index(cmd, "XCLIENT") == 0: // Nginx sends this // XCLIENT ADDR=212.96.64.216 NAME=[UNAVAILABLE] client.address = input[13:] client.address = client.address[0:strings.Index(client.address, " ")] fmt.Println("client address:[" + client.address + "]") responseAdd(client, "250 OK") case strings.Index(cmd, "RCPT TO:") == 0: if len(input) > 8 { client.rcpt_to = input[8:] } responseAdd(client, "250 Accepted") case strings.Index(cmd, "NOOP") == 0: responseAdd(client, "250 OK") case strings.Index(cmd, "RSET") == 0: client.mail_from = "" client.rcpt_to = "" responseAdd(client, "250 OK") case strings.Index(cmd, "DATA") == 0: responseAdd(client, "354 Enter message, ending with \".\" on a line by itself") client.state = 2 case (strings.Index(cmd, "STARTTLS") == 0) && !client.tls_on: responseAdd(client, "220 Ready to start TLS") // go to start TLS state client.state = 3 case strings.Index(cmd, "QUIT") == 0: responseAdd(client, "221 Bye") killClient(client) default: responseAdd(client, fmt.Sprintf("500 unrecognized command")) client.errors++ if client.errors > 3 { responseAdd(client, fmt.Sprintf("500 Too many unrecognized commands")) killClient(client) } } case 2: var err error client.data, err = readSmtp(client) if err == nil { // to do: timeout when adding to SaveMailChan // place on the channel so that one of the save mail workers can pick it up SaveMailChan <- client // wait for the save to complete status := <-client.savedNotify if status == 1 { responseAdd(client, "250 OK : queued as "+client.hash) } else { responseAdd(client, "554 Error: transaction failed, blame it on the weather") } } else { logln(1, fmt.Sprintf("DATA read error: %v", err)) } client.state = 1 case 3: // upgrade to TLS var tlsConn *tls.Conn tlsConn = tls.Server(client.conn, TLSconfig) err := tlsConn.Handshake() // not necessary to call here, but might as well if err == nil { client.conn = net.Conn(tlsConn) client.bufin = bufio.NewReader(client.conn) client.bufout = bufio.NewWriter(client.conn) client.tls_on = true } else { logln(1, fmt.Sprintf("Could not TLS handshake:%v", err)) } advertiseTls = "" client.state = 1 } // Send a response back to the client err := responseWrite(client) if err != nil { if err == io.EOF { // client closed the connection already return } if neterr, ok := err.(net.Error); ok && neterr.Timeout() { // too slow, timeout return } } if client.kill_time > 1 { return } } }
func main() { flag.Parse() checkDns = make(chan *dnsQueryReq) checkDnsRes = make(chan *dnsQueryBack) go dnsLoop() if *bShowVersion { fmt.Printf("%.2f\n", common.Version) return } if !*bVerbose { log.SetOutput(ioutil.Discard) } if *serveName == "" && *linkName == "" { println("you must assign reg or link") return } if *serveName != "" && *linkName != "" { println("you must assign reg or link, not both of them") return } if *localAddr == "" { println("you must assign the local addr") return } if *serveName != "" { clientType = 0 } else { clientType = 1 } if *bEncrypt { if clientType != 1 { println("only link size need encrypt") return } } go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) n := 0 for { <-c log.Println("received signal,shutdown") bForceQuit = true if remoteConn != nil { remoteConn.Close() } n++ if n > 5 { log.Println("force shutdown") os.Exit(-1) } } }() loop := func() bool { if bForceQuit { return true } g_ClientMap = make(map[string]*Client) g_ClientMapKey = make(map[string]*cipher.Block) g_Id2UDPSession = make(map[string]*UDPMakeSession) //var err error if *bUseSSL { _remoteConn, err := tls.Dial("tcp", *serverAddr, &tls.Config{InsecureSkipVerify: true}) if err != nil { println("connect remote err:" + err.Error()) return false } remoteConn = net.Conn(_remoteConn) } else { _remoteConn, err := net.DialTimeout("tcp", *serverAddr, 10*time.Second) if err != nil { println("connect remote err:" + err.Error()) return false } remoteConn = _remoteConn } println("connect to server succeed") go connect() q := make(chan bool) go func() { c := time.NewTicker(time.Second * 10) out: for { select { case <-c.C: if remoteConn != nil { common.Write(remoteConn, "-1", "ping", "") } case <-q: break out } } c.Stop() }() common.Read(remoteConn, handleResponse) q <- true for clientId, client := range g_ClientMap { log.Println("client shutdown", clientId) client.Quit() } if remoteConn != nil { remoteConn.Close() } if bForceQuit { return true } return false } if clientType == 0 { for { if loop() { break } time.Sleep(10 * time.Second) } } else { loop() } log.Println("service shutdown") }
func main() { flag.Usage = Usage flag.Parse() args := flag.Args() if len(args) < 2 { flag.Usage() os.Exit(1) } jr := NewJobRequest() jr.Op = "queue" jr.Score = args[0] if *AllOf { jr.Scope = "all" } else { jr.Scope = "one" } var k int for k = 1; k < len(args); k++ { if args[k] == "!" { break } insertionpoint := 0 if nil == jr.Players { jr.Players = make([]string, 1) } else { insertionpoint = len(jr.Players) newplayers := make([]string, insertionpoint+1) copy(newplayers, jr.Players) jr.Players = newplayers } jr.Players[insertionpoint] = args[k] } if k < len(args) { // skip the ! k++ if (len(args)-(k))%2 != 0 { fmt.Fprintf(os.Stderr, "Error: Odd number of param arguments.\n") os.Exit(1) } for ; k < len(args); k += 2 { jr.Params[args[k]] = args[k+1] } } raddr, err := net.ResolveUnixAddr("unix", *AudienceSock) if err != nil { fmt.Fprintf(os.Stderr, "Failed to resolve sockaddr: %s\n", err) os.Exit(1) } conn, err := net.DialUnix("unix", nil, raddr) if err != nil { fmt.Fprintf(os.Stderr, "Failed to connect to sockaddr: %s\n", err) os.Exit(1) } defer conn.Close() nc := net.Conn(conn) r, _ := nc.(io.Reader) w, _ := nc.(io.Writer) dec := json.NewDecoder(r) enc := json.NewEncoder(w) // send the message err = enc.Encode(jr) if err != nil { fmt.Fprintf(os.Stderr, "Failed to marshal & send: %s\n", err) os.Exit(1) } response := new([2]interface{}) err = dec.Decode(response) if err != nil { fmt.Fprintf(os.Stderr, "Error decoding response: %s\n", err) os.Exit(1) } // coerce field 0 back into a string. rerr, ok := response[0].(string) if ok { if rerr == "OK" { // all OK! get the JobID jobid, _ := response[1].(float64) fmt.Printf("%d\n", uint64(jobid)) os.Exit(0) } else { fmt.Fprintf(os.Stderr, "Server Error: %s\n", rerr) os.Exit(1) } } else { fmt.Fprintf(os.Stderr, "Couldn't unmarshal response correctly.\n") os.Exit(1) } }
func (server *TcpServer) handle() (err error) { defer func() { if e := recover(); e != nil && err == nil { err = fmt.Errorf("%v", e) } }() if server.listener == nil { return nil } var conn *net.TCPConn if conn, err = server.listener.AcceptTCP(); err != nil { return err } if server.keepAlive != nil { if err = conn.SetKeepAlive(server.keepAlive.(bool)); err != nil { return err } } if server.keepAlivePeriod != nil { if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok { if err = kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil { return err } } } if server.linger != nil { if err = conn.SetLinger(server.linger.(int)); err != nil { return err } } if server.noDelay != nil { if err = conn.SetNoDelay(server.noDelay.(bool)); err != nil { return err } } if server.readBuffer != nil { if err = conn.SetReadBuffer(server.readBuffer.(int)); err != nil { return err } } if server.writerBuffer != nil { if err = conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil { return err } } if server.deadline != nil { if err = conn.SetDeadline(server.deadline.(time.Time)); err != nil { return err } } if server.readDeadline != nil { if err = conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil { return err } } if server.writerDeadline != nil { if err = conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil { return err } } if server.config != nil { server.ServeTCP(tls.Client(conn, server.config)) } else { server.ServeTCP(conn) } return nil }
func (l listener) close() error { net.Conn(l.conn).Close() return os.RemoveAll(l.tempDir) }
func (service *TcpService) ServeTCP(conn *net.TCPConn) (err error) { if service.keepAlive != nil { if err = conn.SetKeepAlive(service.keepAlive.(bool)); err != nil { return err } } if service.keepAlivePeriod != nil { if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok { if err = kap.SetKeepAlivePeriod(service.keepAlivePeriod.(time.Duration)); err != nil { return err } } } if service.linger != nil { if err = conn.SetLinger(service.linger.(int)); err != nil { return err } } if service.noDelay != nil { if err = conn.SetNoDelay(service.noDelay.(bool)); err != nil { return err } } if service.readBuffer != nil { if err = conn.SetReadBuffer(service.readBuffer.(int)); err != nil { return err } } if service.writeBuffer != nil { if err = conn.SetWriteBuffer(service.writeBuffer.(int)); err != nil { return err } } if service.timeout != nil { if err = conn.SetDeadline(time.Now().Add(service.timeout.(time.Duration))); err != nil { return err } } go func(conn net.Conn) { if service.config != nil { tlsConn := tls.Server(conn, service.config) tlsConn.Handshake() conn = tlsConn } var data []byte var err error for { if service.readTimeout != nil { err = conn.SetReadDeadline(time.Now().Add(service.readTimeout.(time.Duration))) } if err == nil { data, err = receiveDataOverTcp(conn) } if err == nil { data = service.Handle(data, conn) if service.writeTimeout != nil { err = conn.SetWriteDeadline(time.Now().Add(service.writeTimeout.(time.Duration))) } if err == nil { err = sendDataOverTcp(conn, data) } } if err != nil { conn.Close() break } } }(conn) return nil }
func main() { flag.Usage = Usage flag.Parse() if flag.NArg() != 1 { flag.Usage() os.Exit(1) } sr := NewStatusRequest() var err error sr.Id, err = strconv.ParseUint(flag.Arg(0), 10, 64) if nil != err { fmt.Fprintf(os.Stderr, "Failed to parse JobID: %s\n", err) os.Exit(1) } raddr, err := net.ResolveUnixAddr("unix", *AudienceSock) if err != nil { fmt.Fprintf(os.Stderr, "Failed to resolve sockaddr: %s\n", err) os.Exit(1) } conn, err := net.DialUnix("unix", nil, raddr) if err != nil { fmt.Fprintf(os.Stderr, "Failed to connect to sockaddr: %s\n", err) os.Exit(1) } defer conn.Close() nc := net.Conn(conn) r, _ := nc.(io.Reader) w, _ := nc.(io.Writer) dec := json.NewDecoder(r) enc := json.NewEncoder(w) // send the message err = enc.Encode(sr) if err != nil { fmt.Fprintf(os.Stderr, "Failed to marshal & send: %s\n", err) os.Exit(1) } response := new([2]interface{}) sresp := new(StatusResponse) response[1] = sresp err = dec.Decode(response) if err != nil { // OK, the problem here is that an in the request will throw a null in the second field. // This will cause Decode to softfault. We'll ignore these softfaults. utye, ok := err.(*json.UnmarshalTypeError) if ok { fmt.Fprintf(os.Stderr, "Unmarshalling error: %s of Type %s\n", utye.Value, utye.Type) } else { ufe, ok := err.(*json.UnmarshalFieldError) if ok { fmt.Fprintf(os.Stderr, "Error decoding response: UFE %s of Type %s\n", ufe.Key, ufe.Type) os.Exit(1) } ute, ok := err.(*json.UnsupportedTypeError) if ok { fmt.Fprintf(os.Stderr, "Error decoding response: UTE of Type %s\n", ute.Type) os.Exit(1) } fmt.Fprintf(os.Stderr, "Error decoding response: %s\n", err) os.Exit(1) } } // coerce field 0 back into a string. rerr, ok := response[0].(string) if ok { if rerr == "OK" { // all OK, process the sresp. fmt.Printf("Aggregate: %s\n", *sresp.Status) os.Exit(0) } else { fmt.Fprintf(os.Stderr, "Server Error: %s\n", rerr) os.Exit(1) } } else { fmt.Fprintf(os.Stderr, "Couldn't unmarshal response correctly.\n") os.Exit(1) } }
// Check executes a TCP healthcheck. func (hc *TCPChecker) Check(timeout time.Duration) *Result { msg := fmt.Sprintf("TCP connect to %s", hc.addr()) start := time.Now() if timeout == time.Duration(0) { timeout = defaultTCPTimeout } deadline := start.Add(timeout) tcpConn, err := dialTCP(hc.network(), hc.addr(), timeout, hc.Mark) if err != nil { msg = fmt.Sprintf("%s; failed to connect", msg) return complete(start, msg, false, err) } conn := net.Conn(tcpConn) defer conn.Close() // Negotiate TLS if this is required. if hc.Secure { // TODO(jsing): We probably should allow the server name to // be specified via configuration... host, _, err := net.SplitHostPort(hc.addr()) if err != nil { msg = msg + "; failed to split host" return complete(start, msg, false, err) } tlsConfig := &tls.Config{ InsecureSkipVerify: !hc.TLSVerify, ServerName: host, } tlsConn := tls.Client(conn, tlsConfig) if err := tlsConn.Handshake(); err != nil { return complete(start, msg, false, err) } conn = tlsConn } if hc.Send == "" && hc.Receive == "" { return complete(start, msg, true, err) } err = conn.SetDeadline(deadline) if err != nil { msg = fmt.Sprintf("%s; failed to set deadline", msg) return complete(start, msg, false, err) } if hc.Send != "" { err = writeFull(conn, []byte(hc.Send)) if err != nil { msg = fmt.Sprintf("%s; failed to send request", msg) return complete(start, msg, false, err) } } if hc.Receive != "" { buf := make([]byte, len(hc.Receive)) n, err := io.ReadFull(conn, buf) if err != nil { msg = fmt.Sprintf("%s; failed to read response", msg) return complete(start, msg, false, err) } got := string(buf[0:n]) if got != hc.Receive { msg = fmt.Sprintf("%s; unexpected response - %q", msg, got) return complete(start, msg, false, err) } } return complete(start, msg, true, err) }
func (a *netListenerAdaptor) Accept() (net.Conn, error) { str, err := a.Session.Accept() return net.Conn(str), err }