示例#1
0
func (wp *workerPool) workerFunc(ch *workerChan) {
	var c net.Conn

	var err error
	for c = range ch.ch {
		if c == nil {
			break
		}

		if err = wp.WorkerFunc(c); err != nil && err != errHijacked {
			errStr := err.Error()
			if wp.LogAllErrors || !(strings.Contains(errStr, "broken pipe") ||
				strings.Contains(errStr, "reset by peer") ||
				strings.Contains(errStr, "i/o timeout")) {
				wp.Logger.Printf("error when serving connection %q<->%q: %s", c.LocalAddr(), c.RemoteAddr(), err)
			}
		}
		if err != errHijacked {
			c.Close()
		}
		c = nil

		if !wp.release(ch) {
			break
		}
	}

	wp.lock.Lock()
	wp.workersCount--
	wp.lock.Unlock()
}
示例#2
0
// 为连接开启读写两个协程
func (self *TP) cGoConn(conn net.Conn) {
	remoteAddr, connect := NewConnect(conn, self.connBufferLen, self.connWChanCap)

	// 添加连接到节点池
	self.connPool[self.tpClient.serverUID] = connect

	if self.uid == "" {
		// 设置默认UID
		self.uid = conn.LocalAddr().String()
	}

	if !self.short {
		self.send(NewNetData(self.uid, self.tpClient.serverUID, IDENTITY, ""))
		log.Printf(" *     —— 成功连接到服务器:%v ——", remoteAddr)
	} else {
		connect.Short = true
	}

	// 标记连接已经正式生效可用
	self.connPool[self.tpClient.serverUID].Usable = true

	// 开启读写双工协程
	go self.cReader(self.tpClient.serverUID)
	go self.cWriter(self.tpClient.serverUID)
}
示例#3
0
文件: syslog.go 项目: redcatmiss/gcc
// Dial establishes a connection to a log daemon by connecting to
// address raddr on the network net.  Each write to the returned
// writer sends a log message with the given facility, severity and
// tag.
func Dial(network, raddr string, priority Priority, tag string) (w *Writer, err error) {
	if priority < 0 || priority > LOG_LOCAL7|LOG_DEBUG {
		return nil, errors.New("log/syslog: invalid priority")
	}

	if tag == "" {
		tag = os.Args[0]
	}

	hostname, _ := os.Hostname()

	var conn serverConn
	if network == "" {
		conn, err = unixSyslog()
		if hostname == "" {
			hostname = "localhost"
		}
	} else {
		var c net.Conn
		c, err = net.Dial(network, raddr)
		conn = netConn{c}
		if hostname == "" {
			hostname = c.LocalAddr().String()
		}
	}
	if err != nil {
		return nil, err
	}

	return &Writer{priority: priority, tag: tag, hostname: hostname, conn: conn}, nil
}
示例#4
0
func (ms *MsocksServer) Handler(conn net.Conn) {
	log.Notice("connection come from: %s => %s.", conn.RemoteAddr(), conn.LocalAddr())

	ti := time.AfterFunc(AUTH_TIMEOUT*time.Second, func() {
		log.Notice(ErrAuthFailed.Error(), conn.RemoteAddr())
		conn.Close()
	})

	err := ms.OnAuth(conn)
	if err != nil {
		log.Error("%s", err.Error())
		return
	}
	ti.Stop()

	sess := NewSession(conn)
	sess.next_id = 1
	sess.dialer = ms.dialer

	ms.Add(sess)
	defer ms.Remove(sess)
	sess.Run()

	log.Notice("server session %d quit: %s => %s.",
		sess.LocalPort(), conn.RemoteAddr(), conn.LocalAddr())
}
示例#5
0
func handleConnection(i int, conn net.Conn, eclChan chan map[int]*echoClient, msgChan chan<- string) {
	fmt.Printf("Client %d: %v <-> %v\n", i, conn.LocalAddr(), conn.RemoteAddr())

	ptrEchoClient := &echoClient{
		conn: conn,
		ch:   make(chan string, 100),
	}

	clients := <-eclChan
	clients[i] = ptrEchoClient
	eclChan <- clients

	go echo(ptrEchoClient)
	defer ptrEchoClient.conn.Close()

	rb := bufio.NewReader(conn)
	for {
		msg, e := rb.ReadString('\n')
		if e != nil {
			break
		}
		msgChan <- msg
	}

	clients = <-eclChan
	delete(clients, i)
	eclChan <- clients
	fmt.Printf("%d: closed\n", i)
}
示例#6
0
文件: main.go 项目: qhwa/forgic
func handleRequest(conn net.Conn) {
	fmt.Println("served at port", conn.LocalAddr())
	handlers := getHandlers()
	for _, handler := range handlers {
		handler.Do(conn)
	}
}
示例#7
0
文件: mux.go 项目: splack/gonzbee
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)
}
示例#8
0
func handleConn(c net.Conn) {
	fmt.Println("Got connection: ", c.LocalAddr(), "remote ", c.RemoteAddr())
	defer c.Close()
	buf := make([]byte, 1024)
	for {
		// read from the connection
		n, err := c.Read(buf)
		checkIgnore(err)
		if n <= 0 {
			fmt.Println("connection break...")
			return
		}

		if n > 0 {
			//should be a file name
			f, err := os.Open(string(buf[:n]))
			checkIgnore(err)
			if f != nil {
				//send this file to the client
				sendFile(f, c)
				return
			} else {
				c.Write([]byte("error"))
				fmt.Println("Open file error ", err)
				return
			}
		}
	}
}
示例#9
0
func (this *TcpServer) doConnect(conn net.Conn) {
	log.I_NET(conn.RemoteAddr(), " connect to server success")
	if this.manager != nil {
		this.manager.Connected(conn)
	}
	data := make([]byte, 2048)
	defer conn.Close()
	for {
		len, err := conn.Read(data)
		if err == nil {
			read_data := make([]byte, len)
			copy(read_data, data)
			log.D_NET(conn.LocalAddr(), "read from client", conn.RemoteAddr(), "data :", read_data)
			if this.manager != nil {
				this.manager.ReadData(conn, read_data)
			}
		} else {
			log.E_NET("read from client", conn.RemoteAddr(), "error, reason :", err)
			break
		}
	}
	log.I_NET("client ", conn.RemoteAddr(), " close")
	if this.manager != nil {
		this.manager.Disconnected(conn)
	}
}
示例#10
0
func (s *Server) handleTCPConn(conn net.Conn) error {
	ident, ok := s.virtualAddrs.getIdent(conn)
	if !ok {
		return fmt.Errorf("no virtual address available for %s", conn.LocalAddr())
	}

	_, port, err := parseHostPort(conn.LocalAddr().String())
	if err != nil {
		return err
	}

	stream, err := s.dial(ident, tcpTransport, port)
	if err != nil {
		return err
	}

	var wg sync.WaitGroup
	wg.Add(2)

	go s.proxy(&wg, conn, stream)
	go s.proxy(&wg, stream, conn)

	wg.Wait()

	return nonil(stream.Close(), conn.Close())
}
示例#11
0
func handleConn(conn net.Conn, counter *int64) {
	for {
		recordSets, err := fluent.DecodeEntries(conn)
		if err == io.EOF {
			conn.Close()
			return
		} else if err != nil {
			log.Println("decode entries failed", err, conn.LocalAddr())
			conn.Close()
			return
		}
		n := 0
		for _, recordSet := range recordSets {
			n += len(recordSet.Records)
			if !DEBUG {
				continue
			}
			for _, record := range recordSet.Records {
				if DEBUG {
					fmt.Println(record)
				}
			}
		}
		atomic.AddInt64(counter, int64(n))
	}
}
示例#12
0
// Common example disconnect logic
func CommonDisconnect(n net.Conn, conn *stompngo.Connection,
	exampid, tag string,
	l *log.Logger) error {

	// Disconnect from the Stomp server
	e := conn.Disconnect(stompngo.Headers{})
	if e != nil {
		return e
	}
	l.Printf("%stag:%s consess:%v common_disconnect_complete local_addr:%s remote_addr:%s\n",
		exampid, tag, conn.Session(),
		n.LocalAddr().String(), n.RemoteAddr().String())

	// Close the network connection
	e = n.Close()
	if e != nil {
		return e
	}

	// Parting messages
	l.Printf("%stag:%s consess:%v common_disconnect_network_close_complete\n",
		exampid, tag, conn.Session())
	l.Printf("%stag:%s consess:%v common_disconnect_ends\n",
		exampid, tag, conn.Session())

	//
	return nil
}
示例#13
0
func newRCConn(c net.Conn, iface *Interface) (*RCConn, error) {
	// Leave enough room in the completion queue for any operation,
	// including inline sends, to return an error. CQ overruns
	// sometimes cause internal errors in the HCA, which can make the
	// kernel very unhappy.
	qp, err := iface.NewQueuePair(10)
	if err != nil {
		return nil, err
	}

	if err := c.SetDeadline(ioDeadline()); err != nil {
		checkClose(qp)
		return nil, err
	}
	destLid, destQpn, destPsn, err := writeReadQPParams(c, iface.Lid(), qp.Qpn(), qp.Psn())
	if err != nil {
		checkClose(qp)
		return nil, err
	}

	messages, meta := CreateBuffers()

	if err := qp.Setup(destLid, destQpn, destPsn, messages); err != nil {
		checkClose(qp)
		return nil, err
	}

	laddr, raddr := c.LocalAddr(), c.RemoteAddr()

	rcc := &RCConn{iface, laddr, raddr, qp, math.MaxInt64, true, messages, meta, false}
	return rcc, nil
}
示例#14
0
func sendServerUnavailable(conn net.Conn) {
	log.Printf("[serv] server unavailable %s %s", conn.LocalAddr(), conn.RemoteAddr())
	connAck := &mqtt.ConnAck{
		ReturnCode: mqtt.RetCodeServerUnavailable,
	}
	connAck.Encode(conn)
}
示例#15
0
文件: main.go 项目: khia/httpcache
// Determine if `conn` has been transparently redirected to us. If so, fix `req`
// to reflect the intended destination
func fixTransparentReq(conn net.Conn, req *http.Request) {
	target := GetOriginalAddr(conn)

	is_tls := false
	if tlsConn, ok := conn.(*tls.Conn); ok {
		is_tls = true
		f, err := tlsConn.GetFdCopy()
		if err != nil {
			panic(err)
		}
		defer f.Close()
		target = GetAddrFromFile(f)
	}

	is_transparent := target.String() != conn.LocalAddr().String()

	if is_transparent {
		// It's a transparent proxy
		req.URL.Host = req.Host

		// TODO(pwaller): Port numbers?

		if is_tls {
			req.URL.Scheme = "https"
			req.URL.Host += ":443"
		} else {
			req.URL.Scheme = "http"
		}
	}
}
示例#16
0
func sendBadUsernameOrPassword(conn net.Conn) {
	log.Printf("[serv] bad username / password %s %s", conn.LocalAddr(), conn.RemoteAddr())
	connAck := &mqtt.ConnAck{
		ReturnCode: mqtt.RetCodeBadUsernameOrPassword,
	}
	connAck.Encode(conn)
}
示例#17
0
// ServeConn takes an inbound conn and proxies it to a backend.
func (p *ReverseProxy) ServeConn(ctx context.Context, dconn net.Conn) {
	transport := p.transport
	if transport == nil {
		panic("router: nil transport for proxy")
	}
	defer dconn.Close()

	clientGone := dconn.(http.CloseNotifier).CloseNotify()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel() // finish cancellation goroutine

	go func() {
		select {
		case <-clientGone:
			cancel() // client went away, cancel request
		case <-ctx.Done():
		}
	}()

	l := p.Logger.New("client_addr", dconn.RemoteAddr(), "host_addr", dconn.LocalAddr(), "proxy", "tcp")

	uconn, err := transport.Connect(ctx, l)
	if err != nil {
		return
	}
	defer uconn.Close()

	joinConns(uconn, dconn)
}
示例#18
0
func (e *Endpoint) serveConn(conn net.Conn, wg *sync.WaitGroup) {
	defer conn.Close()
	defer wg.Done()
	var err error
	reader := bufio.NewReader(conn)
	_, err = proxyProtocol.ConsumeProxyLine(reader)
	if err != nil {
		return
	}
	first, err := reader.Peek(1)
	for err == nil && (first[0] == ' ' || first[0] == '\t' || first[0] == '\n' || first[0] == '\r') {
		reader.ReadByte()
		first, err = reader.Peek(1)
	}
	if err != nil {
		return
	}
	if first[0] == '{' || first[0] == '[' {
		// writing shouldn't be buffered
		e.config.Hub.serveConn(newReadWriter(reader, conn), ConnContext{LocalAddr: conn.LocalAddr(), RemoteAddr: conn.RemoteAddr()})
	} else {
		logger.Printf("Got: %s; not a valid json, will pass to HTTP handler.\n", first)
		handleUpgrade(newReadWriter(reader, conn), e.config.UpgradingFileServerAddr)
	}
}
示例#19
0
func handleForwardConn(conn net.Conn) {
	defer conn.Close()
	for {
		recordSets, err := fluent.DecodeEntries(conn)
		if err == io.EOF {
			return
		} else if err != nil {
			log.Println("decode entries failed", err, conn.LocalAddr())
			return
		}
		for _, recordSet := range recordSets {
			atomic.AddInt64(&Counter, int64(len(recordSet.Records)))
			if DumpCh != nil {
				select {
				case DumpCh <- recordSet:
				default:
					log.Printf("[warn] %d records dropped for dump file. tag: %s", len(recordSet.Records), recordSet.Tag)
				}
			}
			for tag, channels := range MessageCh {
				if !matchTag(tag, recordSet.Tag) {
					continue
				}
				for _, ch := range channels {
					select {
					case ch <- recordSet:
					default:
						log.Printf("[warn] %d records dropped for http client.", len(recordSet.Records))
					}
				}
			}
		}
	}
}
示例#20
0
func (f *InForward) handleConn(conn net.Conn) {
	defer func() {
		f.monitorCh <- &ReceiverStat{
			Connections: -1,
		}
	}()
	for {
		recordSets, err := fluent.DecodeEntries(conn)
		if err == io.EOF {
			conn.Close()
			return
		} else if err != nil {
			log.Println("[error] Decode entries failed", err, conn.LocalAddr())
			conn.Close()
			return
		}
		m := int64(0)
		d := int64(0)
		for _, recordSet := range recordSets {
			rs := &recordSet
			d += f.messageQueue.Enqueue(rs)
			m += int64(len(rs.Records))
		}
		f.monitorCh <- &ReceiverStat{
			Messages: m,
			Disposed: d,
			Buffered: int64(f.messageQueue.Len()),
		}
	}
}
示例#21
0
func Wrap(conn net.Conn, context *Context) *Connection {
	reader := bufio.NewReader(conn)
	writer := bufio.NewWriter(conn)
	res := &Connection{reader, writer, conn, conn.LocalAddr().String(), conn.RemoteAddr().String(), context, 0}
	context.activeConnections[conn.LocalAddr().String()] = res
	return res
}
示例#22
0
func (srv *Server) handlerConn(conn net.Conn) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("work failed:", err)
		}
	}()
	// 是这里调用关闭还是 Handler() 负责?
	defer conn.Close()

	if tcpConn, ok := conn.(SetLingerer); ok == true {
		// 设置关闭连接时最多等待多少秒
		tcpConn.SetLinger(5)
	}
	conn.SetDeadline(time.Now().Add(handlerNewTimeout))

	h, _, err := srv.hNewer.New(conn)
	if h == nil {
		log.Printf("无法识别请求的协议类型,远端地址:%v,近端地址:%v,详细错误:%v", conn.RemoteAddr(), conn.LocalAddr(), err)
		return
	}

	conn.SetDeadline(time.Now().Add(handlerBaseTimeout))
	if err := h.Handle(); err != nil {
		if err != io.EOF {
			log.Printf("协议处理错误:", err)
		}
	}
}
示例#23
0
func (wp *workerPool) workerFunc(ch *workerChan) {
	defer func() {
		if r := recover(); r != nil {
			wp.Logger.Printf("panic: %s\nStack trace:\n%s", r, debug.Stack())
		}
	}()

	var c net.Conn
	var err error
	for c = range ch.ch {
		if c == nil {
			break
		}
		if err = wp.WorkerFunc(c); err != nil && err != errHijacked {
			errStr := err.Error()
			if !strings.Contains(errStr, "broken pipe") && !strings.Contains(errStr, "reset by peer") {
				wp.Logger.Printf("error when serving connection %q<->%q: %s", c.LocalAddr(), c.RemoteAddr(), err)
			}
		}
		if err != errHijacked {
			c.Close()
		}
		c = nil

		if !wp.release(ch) {
			break
		}
	}
}
示例#24
0
// Sends a file across the network to a peer.
// @param string fileName - The name of the file to send to the peer. It will have path from root
// of Lynx Directory.
// @param net.Conn conn - The socket over which we will send the file
// @return error - An error can be produced when trying open a file or write over
// the network - otherwise error will be nil.
func sendFile(fileName string, conn net.Conn) error {
	//fmt.Println(fileName)

	// Can use read when implementing chunking
	fBytes, err := ioutil.ReadFile(lynxutil.HomePath + fileName)

	// Begin Compression
	var b bytes.Buffer
	gz := gzip.NewWriter(&b)
	gz.Write(fBytes)
	gz.Close()
	// End Compression

	// Begin Encryption
	var cipherFile []byte
	// The key length can be 32, 24, 16  bytes (OR in bits: 128, 192 or 256)
	//key := []byte("abcdefghijklmnopqrstuvwxyz123456")
	publicKey := lynxutil.Peer{IP: conn.LocalAddr().String()}.Key + lynxutil.PrivateKey
	key := []byte(publicKey)
	if cipherFile, err = mycrypt.Encrypt(key, b.Bytes()); err != nil {
		return err
	}
	// End Encryption

	n, err := conn.Write(cipherFile)
	if err != nil {
		return err
	}

	fmt.Println(n, "Bytes were sent")

	return nil // No Errors Occured If We Reached Here
}
示例#25
0
// connect makes a connection to the syslog server.
// It must be called with w.mu held.
func (w *Writer) connect() (err error) {
	if w.conn != nil {
		// ignore err from close, it makes sense to continue anyway
		w.conn.close()
		w.conn = nil
	}

	if w.network == "" {
		w.conn, err = localSyslog()
		if err != nil {
			return err
		}
		if w.hostname == "" {
			w.hostname = "localhost"
		}
	} else {
		var c net.Conn
		c, err = dial(w.network, w.raddr, w.tlsCfg)
		if err == nil {
			w.conn = &netConn{conn: c}
			if w.hostname == "" {
				w.hostname = c.LocalAddr().String()
			}
		}
	}
	return
}
示例#26
0
func (this *BaseTcpOperation) OpRawData(conn net.Conn, data []byte) (result bool, id int, version byte, serverType byte, dataType byte, dataLen int, rawData []byte) {
	this.copyBuf(data)

	for true {

		exist, id, version, serverType, dataType, oLen, rawData := protocol.ParseRawProtocol(this.buf, this.buf_len)
		if exist {
			if protocol.IsPingByType(dataType) {
				log.I_NET(conn.LocalAddr(), "write to client", conn.RemoteAddr(), "pong")
				conn.Write(protocol.NewPongProtocol(id))
				this.FinishOneProtocol()
			} else if protocol.IsPongByType(dataType) {
				log.I_NET("client", conn.LocalAddr(), "read from server", conn.RemoteAddr(), " pong")
				this.FinishOneProtocol()
			} else {

				d := make([]byte, oLen)
				copy(d, rawData)

				this.FinishOneProtocol()
				return true, id, version, serverType, dataType, oLen, d
			}
		} else {
			return false, 0, 0, 0, 0, 0, nil
		}
	}
	return false, 0, 0, 0, 0, 0, nil
}
示例#27
0
文件: client.go 项目: Weeker/gost
func handleSocks5(conn net.Conn, methods []uint8) {
	if err := selectMethod(conn, methods...); err != nil {
		log.Println(err)
		return
	}

	req, err := gosocks5.ReadRequest(conn)
	if err != nil {
		return
	}

	//log.Println(req)
	sconn, err := makeTunnel()
	if err != nil {
		gosocks5.NewReply(gosocks5.Failure, nil).Write(conn)
		log.Println(err)
		return
	}
	defer sconn.Close()

	switch req.Cmd {
	case gosocks5.CmdConnect, gosocks5.CmdBind:
		if err := req.Write(sconn); err != nil {
			return
		}
		Transport(conn, sconn)
	case gosocks5.CmdUdp:
		if err := req.Write(sconn); err != nil {
			return
		}
		rep, err := gosocks5.ReadReply(sconn)
		if err != nil || rep.Rep != gosocks5.Succeeded {
			return
		}

		uconn, err := net.ListenUDP("udp", nil)
		if err != nil {
			log.Println(err)
			gosocks5.NewReply(gosocks5.Failure, nil).Write(conn)
			return
		}
		defer uconn.Close()

		addr := ToSocksAddr(uconn.LocalAddr())
		addr.Host, _, _ = net.SplitHostPort(conn.LocalAddr().String())
		log.Println("udp:", addr)

		rep = gosocks5.NewReply(gosocks5.Succeeded, addr)
		if err := rep.Write(conn); err != nil {
			log.Println(err)
			return
		}

		go cliTunnelUDP(uconn, sconn)

		// block, waiting for client exit
		ioutil.ReadAll(conn)
	}
}
示例#28
0
文件: server.go 项目: aledbf/builder
// sshConnection generates the SSH_CONNECTION environment variable.
//
// This is untested on UNIX sockets.
func sshConnection(conn net.Conn) string {
	remote := conn.RemoteAddr().String()
	local := conn.LocalAddr().String()
	rhost, rport, _ := net.SplitHostPort(remote)
	lhost, lport, _ := net.SplitHostPort(local)

	return fmt.Sprintf("%s %s %s %s", rhost, rport, lhost, lport)
}
示例#29
0
文件: smtp.go 项目: str4d/i2p-tools
func (s *Server) newSession(conn net.Conn) *session {
	return &session{
		srv:   s,
		conn:  textproto.NewConn(conn),
		raddr: conn.RemoteAddr(),
		laddr: conn.LocalAddr(),
	}
}
示例#30
0
func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) {
	ctx, cancel = context.WithCancel(context.Background())
	ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr())
	if hs := opts.baseConfig(); hs != nil {
		ctx = context.WithValue(ctx, http.ServerContextKey, hs)
	}
	return
}