// sendSshKeepAlive is a helper which sends a [email protected] request
// on the specified SSH connections and returns true of the request succeeds
// within a specified timeout.
func sendSshKeepAlive(
	sshClient *ssh.Client, conn net.Conn, timeout time.Duration) error {

	errChannel := make(chan error, 2)
	if timeout > 0 {
		time.AfterFunc(timeout, func() {
			errChannel <- TimeoutError{}
		})
	}

	go func() {
		// Random padding to frustrate fingerprinting
		_, _, err := sshClient.SendRequest(
			"*****@*****.**", true,
			MakeSecureRandomPadding(0, TUNNEL_SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES))
		errChannel <- err
	}()

	err := <-errChannel
	if err != nil {
		sshClient.Close()
		conn.Close()
	}

	return ContextError(err)
}
Beispiel #2
1
// handleRawConn is run in its own goroutine and handles a just-accepted
// connection that has not had any I/O performed on it yet.
func (s *Server) handleRawConn(rawConn net.Conn) {
	conn, authInfo, err := s.useTransportAuthenticator(rawConn)
	if err != nil {
		s.mu.Lock()
		s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
		s.mu.Unlock()
		grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
		rawConn.Close()
		return
	}

	s.mu.Lock()
	if s.conns == nil {
		s.mu.Unlock()
		conn.Close()
		return
	}
	s.mu.Unlock()

	if s.opts.useHandlerImpl {
		s.serveUsingHandler(conn)
	} else {
		s.serveNewHTTP2Transport(conn, authInfo)
	}
}
Beispiel #3
1
// NewClient returns a new Client instance connected to an IMAP server via conn.
// The function waits for the server to send a greeting message, and then
// requests server capabilities if they weren't included in the greeting. An
// error is returned if either operation fails or does not complete before the
// timeout, which must be positive to have any effect. If an error is returned,
// it is the caller's responsibility to close the connection.
func NewClient(conn net.Conn, host string, timeout time.Duration) (c *Client, err error) {
	log := newDebugLog(DefaultLogger, DefaultLogMask)
	cch := make(chan chan<- *response, 1)

	c = &Client{
		Caps:          make(map[string]bool),
		CommandConfig: defaultCommands(),
		host:          host,
		state:         unknown,
		tag:           *newTagGen(0),
		cmds:          make(map[string]*Command),
		t:             newTransport(conn, log),
		debugLog:      log,
	}
	c.r = newReader(c.t, MemoryReader{}, string(c.tag.id))
	c.Logf(LogConn, "Connected to %v (Tag=%s)", conn.RemoteAddr(), c.tag.id)

	if err = c.greeting(timeout); err != nil {
		c.Logln(LogConn, "Greeting error:", err)
		return nil, err
	}
	c.cch = cch
	go c.receiver(cch)
	runtime.Gosched()
	return
}
Beispiel #4
1
func (p *Peer) Accept(conn net.Conn) (_err error) {
	defer conn.Close()

	p.logFields(SERVE, log.Fields{
		"remoteAddr": conn.RemoteAddr(),
	}).Debug("accepted connection")
	defer func() {
		if _err != nil {
			p.logErr(SERVE, _err).Error()
		}
	}()

	var failResp string
	if p.readAcquire() {
		defer p.wg.Done()
	} else {
		failResp = "sync not available, currently mutating"
	}

	remoteConfig, err := p.handleConfig(conn, SERVE, failResp)
	if err != nil {
		return errgo.Mask(err)
	}

	if failResp == "" {
		return p.interactWithClient(conn, remoteConfig, cf.NewBitstring(0))
	}
	return nil
}
Beispiel #5
1
func (s *Server) onConn(c net.Conn) {
	conn := s.newClientConn(c) //新建一个conn

	defer func() {
		err := recover()
		if err != nil {
			const size = 4096
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)] //获得当前goroutine的stacktrace
			golog.Error("server", "onConn", "error", 0,
				"remoteAddr", c.RemoteAddr().String(),
				"stack", string(buf),
			)
		}

		conn.Close()
	}()

	if allowConnect := conn.IsAllowConnect(); allowConnect == false {
		err := mysql.NewError(mysql.ER_ACCESS_DENIED_ERROR, "ip address access denied by kingshard.")
		conn.writeError(err)
		conn.Close()
		return
	}
	if err := conn.Handshake(); err != nil {
		golog.Error("server", "onConn", err.Error(), 0)
		c.Close()
		return
	}

	conn.Run()
}
Beispiel #6
1
func handleClient(p1, p2 net.Conn) {
	log.Println("stream opened")
	defer log.Println("stream closed")
	defer p1.Close()
	defer p2.Close()

	// start tunnel
	p1die := make(chan struct{})
	go func() {
		io.Copy(p1, p2)
		close(p1die)
	}()

	p2die := make(chan struct{})
	go func() {
		io.Copy(p2, p1)
		close(p2die)
	}()

	// wait for tunnel termination
	select {
	case <-p1die:
	case <-p2die:
	}
}
Beispiel #7
0
func (p *multiplexer) connectToDest(frm *frame, key string, tun *Conn) {
	defer func() {
		ex.CatchException(recover())
	}()
	var (
		dstConn net.Conn
		err     error
		target  = string(frm.data)
	)
	dstConn, err = net.DialTimeout("tcp", target, GENERAL_SO_TIMEOUT)
	frm.length = 0
	if err != nil {
		p.router.removePreRegistered(key)
		log.Errorf("Cannot connect to [%s] for %s error: %s\n", target, key, err)
		frm.action = FRAME_ACTION_OPEN_N
		tunWrite2(tun, frm)
	} else {
		if log.V(1) {
			log.Infoln("OPEN", target, "for", key)
		}
		dstConn.SetReadDeadline(ZERO_TIME)
		edge := p.router.register(key, target, tun, dstConn, false) // write edge
		frm.action = FRAME_ACTION_OPEN_Y
		if tunWrite2(tun, frm) == nil {
			p.relay(edge, tun, frm.sid) // read edge
		} else { // send open_y failed
			SafeClose(tun)
		}
	}
}
Beispiel #8
0
/*
 * This function is called by the main to handle the chat functionality of new connection
 * The function reads the user name and saves it, then waits for user messages and broadcast them
 */
func handleConnection(client net.Conn) {
	reader := bufio.NewReader(client)
	//receive the user name
	buff := make([]byte, 512)
	clientNameb, _ := client.Read(buff)
	clientName := string(buff[0:clientNameb])
	newSession.names = append(newSession.names, clientName)
	newSession.connections = append(newSession.connections, client)

	for {
		//receive the user message
		line, err := reader.ReadBytes('\n')
		if err != nil {
			break
		}
		//broadcast client message
		message := clientName + ":" + string(line)
		for _, currentClient := range newSession.connections {
			if currentClient != nil {
				currentClient.Write([]byte(message))
			}
		}

	}
}
Beispiel #9
0
/*
	Close a network connection.
*/
func closeConn(t *testing.T, n net.Conn) error {
	err := n.Close()
	if err != nil {
		t.Errorf("Unexpected n.Close() error: %v\n", err)
	}
	return err
}
Beispiel #10
0
func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 2分钟无接收信息超时
	//func (c *TCPConn) SetReadDeadline(t time.Time) error
	//func (c *TCPConn) SetWriteDeadline(t time.Time) error

	defer conn.Close()

	for {
		request := make([]byte, 128)
		//128 位读取信息
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

	}
}
Beispiel #11
0
func (this *StorageClient) storageDeleteFile(tc *TrackerClient, storeServ *StorageServer, remoteFilename string) error {
	var (
		conn   net.Conn
		reqBuf []byte
		err    error
	)

	conn, err = this.pool.Get()
	defer conn.Close()
	if err != nil {
		return err
	}

	th := &trackerHeader{}
	th.cmd = STORAGE_PROTO_CMD_DELETE_FILE
	fileNameLen := len(remoteFilename)
	th.pkgLen = int64(FDFS_GROUP_NAME_MAX_LEN + fileNameLen)
	th.sendHeader(conn)

	req := &deleteFileRequest{}
	req.groupName = storeServ.groupName
	req.remoteFilename = remoteFilename
	reqBuf, err = req.marshal()
	if err != nil {
		return err
	}
	TcpSendData(conn, reqBuf)

	th.recvHeader(conn)
	if th.status != 0 {
		return Errno{int(th.status)}
	}
	return nil
}
Beispiel #12
0
func (cmd *cmdSync) PSyncPipeCopy(c net.Conn, br *bufio.Reader, bw *bufio.Writer, offset int64, copyto io.Writer) (int64, error) {
	defer c.Close()
	var nread atomic2.Int64
	go func() {
		defer c.Close()
		for {
			time.Sleep(time.Second * 5)
			if err := sendPSyncAck(bw, offset+nread.Get()); err != nil {
				return
			}
		}
	}()

	var p = make([]byte, 8192)
	for {
		n, err := br.Read(p)
		if err != nil {
			return nread.Get(), nil
		}
		if _, err := copyto.Write(p[:n]); err != nil {
			return nread.Get(), err
		}
		nread.Add(int64(n))
	}
}
Beispiel #13
0
// handleConnection handles an incoming connection
func (p *Provider) handleConnection(conn net.Conn) {
	// Create an RPC server to handle inbound
	pe := &providerEndpoint{p: p}
	rpcServer := rpc.NewServer()
	rpcServer.RegisterName("Client", pe)
	rpcCodec := msgpackrpc.NewCodec(false, false, conn)

	defer func() {
		if !pe.hijacked() {
			conn.Close()
		}
	}()

	for !p.IsShutdown() {
		if err := rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				p.logger.Printf("[ERR] scada-client: RPC error: %v", err)
			}
			return
		}

		// Handle potential hijack in Client.Connect
		if pe.hijacked() {
			cb := pe.getHijack()
			cb(conn)
			return
		}
	}
}
Beispiel #14
0
func handle(conn net.Conn) {
	defer conn.Close()

	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		ln := scanner.Text()
		fs := strings.Fields(ln)
		// skip blank lines
		if len(fs) < 2 {
			continue
		}

		switch fs[0] {
		case "GET":
			key := fs[1]
			value := data[key]
			fmt.Fprintf(conn, "%s\n", value)
		case "SET":
			if len(fs) != 3 {
				io.WriteString(conn, "EXPECTED VALUE\n")
				continue
			}
			key := fs[1]
			value := fs[2]
			data[key] = value
		case "DEL":
		default:
			io.WriteString(conn, "INVALID COMMAND "+fs[0]+"\n")
		}
	}
}
Beispiel #15
0
func HandleIncomingSSHConn(nConn net.Conn, config *ssh.ServerConfig) {
	DoneCh := make(chan bool)
	go TimeoutConnection(DoneCh, nConn)
	_, chans, reqs, err := ssh.NewServerConn(nConn, config)
	if err == nil {
		DoneCh <- true
	}
	// Right now that we are out of annoying people land.

	defer nConn.Close()
	go HandleSSHrequests(reqs)

	for newChannel := range chans {
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			log.Printf("WARNING - Rejecting %s Because they asked for a chan type %s that I don't have", nConn.RemoteAddr().String(), newChannel.ChannelType())
			continue
		}

		channel, requests, err := newChannel.Accept()
		if err != nil {
			log.Printf("WARNING - Was unable to Accept channel with %s", nConn.RemoteAddr().String())
			return
		}
		go HandleSSHrequests(requests)
		go ServeDOSTerm(channel)
	}

}
Beispiel #16
0
func (f *forwarder) connect() {
	if f.c != nil {
		return
	}

	rate := time.Tick(200 * time.Millisecond)
	for {
		var c net.Conn
		var err error

		if f.Config.TlsConfig != nil {
			c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig)
		} else {
			c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout)
		}

		if err != nil {
			f.cErrors.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error")
			f.disconnect()
		} else {
			f.cSuccesses.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success")
			f.c = c
			return
		}
		<-rate
	}
}
Beispiel #17
0
func (cons *Socket) processConnection(conn net.Conn) {
	cons.AddWorker()
	defer cons.WorkerDone()
	defer conn.Close()

	buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)

	for cons.IsActive() && !cons.IsFuseBurned() {
		conn.SetReadDeadline(time.Now().Add(cons.readTimeout))
		err := buffer.ReadAll(conn, cons.Enqueue)
		if err == nil {
			if err = cons.sendAck(conn, true); err == nil {
				continue // ### continue, all is well ###
			}
		}

		// Silently exit on disconnect/close
		if !cons.IsActive() || shared.IsDisconnectedError(err) {
			return // ### return, connection closed ###
		}

		// Ignore timeout related errors
		if netErr, isNetErr := err.(net.Error); isNetErr && netErr.Timeout() {
			continue // ### return, ignore timeouts ###
		}

		Log.Error.Print("Socket transfer failed: ", err)
		cons.sendAck(conn, false)

		// Parser errors do not drop the connection
		if err != shared.BufferDataInvalid {
			return // ### return, close connections ###
		}
	}
}
// Dial and scrape the basic service parameters
func (s *BasicService) dialAndScrape() (net.Conn, error) {
	if s.Timeout == 0 {
		log.Warnln("0 deadline set for service. This is probably not what you want as services will flap.")
	}

	// Set absolute deadline
	deadline := time.Now().Add(time.Duration(s.Timeout))

	// Dialer deadline
	dialer := net.Dialer{
		Deadline: deadline,
	}

	var err error
	var conn net.Conn

	conn, err = dialer.Dial(s.Protocol, fmt.Sprintf("%s:%d", s.Host().Hostname, s.Port()))
	if err != nil {
		s.portOpen = FAILED
	} else {
		s.portOpen = SUCCESS
	}

	if conn != nil {
		// Connection deadline
		conn.SetDeadline(deadline)
	}

	return conn, err
}
Beispiel #19
0
func (t *Telnet) recv(c net.Conn) (int, error) {
	buf := make([]byte, 512)

	count := 0
	for {
		err := c.SetReadDeadline(time.Now().Add(time.Millisecond * 500))
		if err != nil {
			return count, fmt.Errorf("setting read deadline: %v\n", err)
		}

		n, err := c.Read(buf)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				return count, nil
			}
			return count, fmt.Errorf("read error: %v\n", err)
		}

		for i := 0; i < n; i++ {
			if cnt := t.decodeCommand(buf[i:n]); cnt > 0 {
				i += cnt
				continue
			}

			t.debugf("%2.2x %c\n", buf[i], buf[i])
		}

		count += n

		if time.Now().After(t.deadline) {
			return count, errors.New("deadline exceeded")
		}
	}
}
Beispiel #20
0
func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) {
	defer finish.Unlock()
	defer close(output)
	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create decrypt reader: %v", err)
		return
	}

	buffer, err := v2net.ReadFrom(decryptResponseReader, nil)
	if err != nil {
		log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", buffer.Len(), err)
		return
	}
	if buffer.Len() < 4 || !bytes.Equal(buffer.Value[:4], request.ResponseHeader[:]) {
		log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
		return
	}
	log.Info("VMessOut received %d bytes from %s", buffer.Len()-4, conn.RemoteAddr().String())

	buffer.SliceFrom(4)
	output <- buffer

	if !isUDP {
		v2net.ReaderToChan(output, decryptResponseReader)
	}

	return
}
Beispiel #21
0
func (c *tlsCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ AuthInfo, err error) {
	// borrow some code from tls.DialWithDialer
	var errChannel chan error
	if timeout != 0 {
		errChannel = make(chan error, 2)
		time.AfterFunc(timeout, func() {
			errChannel <- timeoutError{}
		})
	}
	if c.config.ServerName == "" {
		colonPos := strings.LastIndex(addr, ":")
		if colonPos == -1 {
			colonPos = len(addr)
		}
		c.config.ServerName = addr[:colonPos]
	}
	conn := tls.Client(rawConn, &c.config)
	if timeout == 0 {
		err = conn.Handshake()
	} else {
		go func() {
			errChannel <- conn.Handshake()
		}()
		err = <-errChannel
	}
	if err != nil {
		rawConn.Close()
		return nil, nil, err
	}
	// TODO(zhaoq): Omit the auth info for client now. It is more for
	// information than anything else.
	return conn, nil, nil
}
Beispiel #22
0
func SetupFTPS(logStruct *FTPLog, connection net.Conn) (bool, error) {
	buffer := make([]byte, 1024)

	connection.Write([]byte("AUTH TLS\r\n"))
	respLen, err := util.ReadUntilRegex(connection, buffer, ftpEndRegex)
	if err != nil {
		return false, err
	}

	logStruct.AuthTLSResp = string(buffer[0:respLen])
	retCode := ftpEndRegex.FindStringSubmatch(logStruct.AuthTLSResp)[1]
	if strings.HasPrefix(retCode, "2") {
		return true, nil
	} else {
		connection.Write([]byte("AUTH SSL\r\n"))
		respLen, err := util.ReadUntilRegex(connection, buffer, ftpEndRegex)
		if err != nil {
			return false, err
		}

		logStruct.AuthSSLResp = string(buffer[0:respLen])
		retCode := ftpEndRegex.FindStringSubmatch(logStruct.AuthSSLResp)[1]

		if strings.HasPrefix(retCode, "2") {
			return true, nil
		}
	}

	return false, nil
}
Beispiel #23
0
func (c *Client) handle(conn net.Conn, ws *WorkServer) {
	defer conn.Close()

	reader := gob.NewDecoder(conn)

	c.ClientInfo = new(Hyades.ClientInfo)
	err := reader.Decode(c.ClientInfo)
	if err != nil {
		c.FrameWorkError(err)
		return
	}
	c.Owner.Stats.Announced(c.ClientInfo)

	log.Println(c.ClientInfo.ComputerName, " Connected")

	c.Owner.Stats.Connected()
	defer c.Owner.Stats.Disconnected(c.ClientInfo)

	lc := logicsocket.Wrap(conn)

	workConn := lc.NewConnection(WORK)
	go c.ServiceWork(workConn)

	heartbeatConn := lc.NewConnection(HEARTBEAT)
	c.ServiceHeartBeat(heartbeatConn)

}
Beispiel #24
0
func handleClient(conn net.Conn) {
	var buf [512]byte
	for {
		n, err := conn.Read(buf[0:])
		if err != nil {
			return
		}
		line := string(buf[0:n])

		//*******LOGIC*************************************************************************************
		m := map[string]string{"google.com": "8.8.8.8", "cedille.etsmtl.ca": "142.137.247.120"}

		for key, value := range m {
			// for each pair in the map, print key and value
			if line == key {
				fmt.Println(value)
			} else {
				fmt.Println("not mapped")
			}
		}
		//*******END OF LOGIC******************************************************************************
		_, err2 := conn.Write(buf[0:n])
		if err2 != nil {
			return
		}
	}
}
Beispiel #25
0
func handShake(conn net.Conn) (err error) {
	const (
		idVer     = 0
		idNmethod = 1
	)
	// version identification and method selection message in theory can have
	// at most 256 methods, plus version and nmethod field in total 258 bytes
	// the current rfc defines only 3 authentication methods (plus 2 reserved),
	// so it won't be such long in practice

	buf := make([]byte, 258)

	var n int
	// make sure we get the nmethod field
	if n, err = io.ReadAtLeast(conn, buf, idNmethod+1); err != nil {
		return
	}
	if buf[idVer] != socksVer5 {
		return errVer
	}
	nmethod := int(buf[idNmethod])
	msgLen := nmethod + 2
	if n == msgLen { // handshake done, common case
		// do nothing, jump directly to send confirmation
	} else if n < msgLen { // has more methods to read, rare case
		if _, err = io.ReadFull(conn, buf[n:msgLen]); err != nil {
			return
		}
	} else { // error, should not get extra data
		return errAuthExtraData
	}
	// send confirmation: version 5, no authentication required
	_, err = conn.Write([]byte{socksVer5, 0})
	return
}
Beispiel #26
0
// Receive the file in blocks
func Receive(conn net.Conn, filePath string) {
	// Defer closing the Connection handle
	defer conn.Close()

	// Open output file
	fout, err := os.Create(filePath)
	if err != nil {
		log.Println("create ", filePath, "failed...", err)
		log.Fatal(err)
	}

	// Defer closing the output file handle
	defer fout.Close()

	// File Writer Buffer init.
	w := bufio.NewWriter(fout)
	inBuffer := make([]byte, blockSize)

	for {
		numRead, err := conn.Read(inBuffer)

		if err != nil || numRead == 0 {
			log.Print("Encountered the end of file", numRead, err)
			break
		}

		numWritten, _ := w.Write(inBuffer[:numRead])

		log.Println(numRead, "bytes received", numWritten, "bytes written")
		w.Flush()
	}
}
Beispiel #27
0
func (c *Client) do(method, path string, doOptions doOptions) ([]byte, int, error) {
	var params io.Reader
	if doOptions.data != nil || doOptions.forceJSON {
		buf, err := json.Marshal(doOptions.data)
		if err != nil {
			return nil, -1, err
		}
		params = bytes.NewBuffer(buf)
	}
	if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
		err := c.checkAPIVersion()
		if err != nil {
			return nil, -1, err
		}
	}
	req, err := http.NewRequest(method, c.getURL(path), params)
	if err != nil {
		return nil, -1, err
	}
	req.Header.Set("User-Agent", userAgent)
	if doOptions.data != nil {
		req.Header.Set("Content-Type", "application/json")
	} else if method == "POST" {
		req.Header.Set("Content-Type", "plain/text")
	}
	var resp *http.Response
	protocol := c.endpointURL.Scheme
	address := c.endpointURL.Path
	if protocol == "unix" {
		var dial net.Conn
		dial, err = net.Dial(protocol, address)
		if err != nil {
			return nil, -1, err
		}
		defer dial.Close()
		breader := bufio.NewReader(dial)
		err = req.Write(dial)
		if err != nil {
			return nil, -1, err
		}
		resp, err = http.ReadResponse(breader, req)
	} else {
		resp, err = c.HTTPClient.Do(req)
	}
	if err != nil {
		if strings.Contains(err.Error(), "connection refused") {
			return nil, -1, ErrConnectionRefused
		}
		return nil, -1, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, -1, err
	}
	if resp.StatusCode < 200 || resp.StatusCode >= 400 {
		return nil, resp.StatusCode, newError(resp.StatusCode, body)
	}
	return body, resp.StatusCode, nil
}
Beispiel #28
0
func handleConnection(client net.Conn) {
	defer client.Close()

	// sock version
	ver := make([]byte, 1)
	if n, _ := client.Read(ver); n != 1 {
		log.Println("MethodRequest packet is too short")
		return
	}

	var proxy SockProxy

	switch ver[0] {
	case 0x04:
		proxy = new(Sock4)
	case 0x05:
		proxy = new(Sock5)
	default:
		log.Println("invalid socks version:", ver)
		return
	}

	if err := proxy.Proxy(client); err != nil {
		log.Println("Proxy error:", err)
		return
	}

	return
}
Beispiel #29
0
func (s *Server) onConn(c net.Conn) {
	defer s.wg.Done()

	h := newHandler(s)
	conn, err := server.NewConn(c, s.user, s.password, h)
	if err != nil {
		log.Errorf("new connection error %s", err.Error())
		c.Close()
		return
	}

	h.conn = conn

	for {
		select {
		case <-s.quit:
			// Proxy quited, close conection
			conn.Close()
			return
		default:
			break
		}

		err = conn.HandleCommand()
		if err != nil {
			log.Errorf("handle command error %s", err.Error())
			return
		}
	}
}
Beispiel #30
0
func ConnHandle(conn net.Conn) {

	defer conn.Close()

	backlog := make(chan []byte, 10)

	go LogicHandle(conn, backlog)

	header := make([]byte, 1)

	for {

		n, err := io.ReadFull(conn, header)

		if n == 0 && err == io.EOF {
			fmt.Printf("client closed \n")
			break
		} else if err != nil {
			fmt.Println("error receving header:", err)
			break
		}

		backlog <- header

	}
}