Пример #1
0
func main() {
	addr, _ := net.ResolveTCPAddr("0.0.0.0:9009")
	go func() {
		l, _ := net.ListenTCP("tcp", addr)
		conn, _ := l.AcceptTCP()
		println("accepted")
		go func(c io.ReadWriter) {
			buf := make([]byte, N)
			b := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
			if n, e := b.Read(buf); e != nil || n < N {
				println("read", n, e.String())
				return
			}
			if n, e := b.Write(buf); n < N || e != nil {
				println("write", n, e.String())
			}
			b.Flush()
			time.Sleep(1)
		}(conn)
	}()
	time.Sleep(1e9)
	c, _ := net.DialTCP("tcp", nil, addr)
	println("connected")
	f := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
	b := make([]byte, N)
	if n, e := f.Write(b); n < N || e != nil {
		panic("write failed")
	}
	f.Flush()
	if n, e := f.Read(b); e != nil || n < N {
		println("read 2", n, e.String())
	}
}
Пример #2
0
func main() {
	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*baidu.com$"))).
		HandleConnect(goproxy.AlwaysReject)
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
		HandleConnect(goproxy.AlwaysMitm)
	// enable curl -p for all hosts on port 80
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := net.Dial("tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)
				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})
	proxy.Verbose = true
	log.Fatal(http.ListenAndServe(":8080", proxy))
}
Пример #3
0
func wshandler(ws *websocket.Conn) {
	flag.Parse()
	var mqcon net.Conn
	var err error
	if *bs {
		conf := tls.Config{InsecureSkipVerify: *bsinsec}
		if *bcert != "" && *bkey != "" {
			Cert, err := tls.LoadX509KeyPair(*bcert, *bkey)
			if err != nil {
				fmt.Println("LoadX509KeyPair:", err)
				return
			}
			conf.Certificates = []tls.Certificate{Cert}
		}
		mqcon, err = tls.Dial("tcp", *bhost+":"+*bport, &conf)
	} else {
		mqcon, err = net.Dial("tcp", *bhost+":"+*bport)
	}

	if err != nil {
		fmt.Println("mqcon error:", err.Error())
		ws.Close()
		return
	}
	ws.PayloadType = websocket.BinaryFrame

	bmqcon := bufio.NewReadWriter(bufio.NewReader(mqcon), bufio.NewWriter(mqcon))
	bws := bufio.NewReadWriter(bufio.NewReader(ws), bufio.NewWriter(ws))

	go func() {
		for {
			msg, err := mqtt.DecodeOneMessage(bmqcon, nil)
			//			fmt.Println("brok->", msg)
			if err != nil {
				mqcon.Close()
				return
			}
			wbuffer := new(bytes.Buffer)
			msg.Encode(wbuffer)
			bws.Write(wbuffer.Bytes())
			bws.Flush()
			wbuffer.Truncate(wbuffer.Len())
		}
	}()
	for {
		msg, err := mqtt.DecodeOneMessage(bws, nil)
		//		fmt.Println("webs->", msg)
		if err != nil {
			ws.Close()
			return
		}
		msg.Encode(bmqcon)
		bmqcon.Flush()
	}
}
Пример #4
0
func (s *Server) newConn(rwc net.Conn) (c *conn, err error) {
	c = new(conn)
	c.server = s
	c.conn = rwc
	c.rwc = bufio.NewReadWriter(bufio.NewReaderSize(rwc, 1048576), bufio.NewWriter(rwc))
	return c, nil
}
Пример #5
0
func newConn(rwc net.Conn) *conn {
	return &conn{
		rwc:  rwc,
		buf:  bufio.NewReadWriter(bufio.NewReader(rwc), bufio.NewWriter(rwc)),
		done: make(chan bool, 1),
	}
}
Пример #6
0
// NewClient creates a new WebSocket client connection over rwc.
func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
	br := bufio.NewReader(rwc)
	bw := bufio.NewWriter(rwc)
	switch config.Version {
	case ProtocolVersionHixie75:
		err = hixie75ClientHandshake(config, br, bw)
	case ProtocolVersionHixie76, ProtocolVersionHybi00:
		err = hixie76ClientHandshake(config, br, bw)
	case ProtocolVersionHybi08, ProtocolVersionHybi13:
		err = hybiClientHandshake(config, br, bw)
	default:
		err = ErrBadProtocolVersion
	}
	if err != nil {
		return
	}
	buf := bufio.NewReadWriter(br, bw)
	switch config.Version {
	case ProtocolVersionHixie75, ProtocolVersionHixie76, ProtocolVersionHybi00:
		ws = newHixieClientConn(config, buf, rwc)
	case ProtocolVersionHybi08, ProtocolVersionHybi13:
		ws = newHybiClientConn(config, buf, rwc)
	}
	return
}
Пример #7
0
func pubWorker(n int, tcpAddr string, batchSize int, batch [][]byte, topic string) {
	conn, err := net.DialTimeout("tcp", tcpAddr, time.Second)
	if err != nil {
		panic(err.Error())
	}
	conn.Write(nsq.MagicV2)
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	num := n / runtime.GOMAXPROCS(0) / batchSize
	for i := 0; i < num; i += 1 {
		cmd, _ := nsq.MultiPublish(topic, batch)
		err := cmd.Write(rw)
		if err != nil {
			panic(err.Error())
		}
		err = rw.Flush()
		if err != nil {
			panic(err.Error())
		}
		resp, err := nsq.ReadResponse(rw)
		if err != nil {
			panic(err.Error())
		}
		_, data, _ := nsq.UnpackResponse(resp)
		if !bytes.Equal(data, []byte("OK")) {
			panic("invalid response")
		}
	}
}
Пример #8
0
// protoRead reads binary blobs with the following format:
//
//    COMMAND ' ' CHANNEL ' ' SIZE PAYLOAD
func (s *Server) handleRequest(conn net.Conn) {
	r := bufio.NewReader(conn)
	rw := bufio.NewReadWriter(r, nil)

	var payloadSize int64
	err := binary.Read(rw, binary.BigEndian, &payloadSize)

	var buf bytes.Buffer
	io.CopyN(&buf, rw, payloadSize)

	body := buf.Bytes()

	blobs := bytes.SplitN(body, []byte(" "), 2)
	command := string(blobs[0])
	channel := string(blobs[1])
	payload := blobs[2]

	reply, err := s.processCommand(command, channel, payload)
	if err != nil {
		fmt.Println("Error processing command:", err)
		return
	}

	conn.Write([]byte(reply))
	// Close the connection when you're done with it.
	conn.Close()
}
Пример #9
0
func newConn(rwc io.ReadWriteCloser) *Conn {
	return &Conn{
		stream: bufio.NewReadWriter(
			bufio.NewReader(rwc),
			bufio.NewWriter(rwc)),
	}
}
Пример #10
0
func readData(client net.Conn) {
	b := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
	i := 0
	var err error
	var tx *sql.Tx
	for {
		if i == 0 {
			tx, err = pg.Begin()
			if err != nil {
				log.Printf("error=true action=begin message=%v", err)
			}
			i += 1
		} else if i == (*checkpoint + 1) {
			//checkpoint is set by flag
			// we inc checkpoint for the case when it is set to 1
			err = tx.Commit()
			if err != nil {
				log.Printf("error=true action=commit message=%v", err)
			}
			log.Printf("action=commit")
			i = 0
		} else {
			line, err := b.ReadString('\n')
			if err != nil {
				break
			}
			handleInput(*tx, line)
			i += 1
		}
	}
}
Пример #11
0
func TestAuthFailed(t *testing.T) {
	server := strings.Join(strings.Split(authFailedServer, "\n"), "\r\n")
	client := strings.Join(strings.Split(authFailedClient, "\n"), "\r\n")
	var cmdbuf bytes.Buffer
	bcmdbuf := bufio.NewWriter(&cmdbuf)
	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)
	c, err := NewClient(fake, "fake.host")
	if err != nil {
		t.Fatalf("NewClient: %v", err)
	}
	defer c.Close()

	c.tls = true
	c.serverName = "smtp.google.com"
	err = c.Auth(PlainAuth("", "user", "pass", "smtp.google.com"))

	if err == nil {
		t.Error("Auth: expected error; got none")
	} else if err.Error() != "535 Invalid credentials\nplease see www.example.com" {
		t.Errorf("Auth: got error: %v, want: %s", err, "535 Invalid credentials\nplease see www.example.com")
	}

	bcmdbuf.Flush()
	actualcmds := cmdbuf.String()
	if client != actualcmds {
		t.Errorf("Got:\n%s\nExpected:\n%s", actualcmds, client)
	}
}
Пример #12
0
// Send the given email messages using this Mailer.
func (m *Mailer) SendTestMessage(basicServer string, messages ...*Message) (actualcmds string, err error) {
	if m.Auth == nil {
		m.Auth = smtp.PlainAuth(m.UserName, m.UserName, m.Password, m.Server)
	}

	server := strings.Join(strings.Split(basicServer, "\n"), "\r\n")
	var cmdbuf bytes.Buffer
	bcmdbuf := bufio.NewWriter(&cmdbuf)
	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)

	defer func() {
		bcmdbuf.Flush()
		actualcmds = cmdbuf.String()
	}()

	c, err := smtp.NewClient(fake, "fake.host")
	if err != nil {
		return
	}
	defer c.Quit()

	for _, message := range messages {
		m.fillDefault(message)
		if err = Send(c, message); err != nil {
			return
		}
	}

	return
}
Пример #13
0
func (s *Server) newConn(originalConn net.Conn) *conn {
	c := new(conn)
	c.server = s
	c.conn = originalConn
	c.rw = bufio.NewReadWriter(bufio.NewReader(originalConn), bufio.NewWriter(originalConn))
	return c
}
Пример #14
0
Файл: rbot.go Проект: raylu/rbot
func identd(port string) {
	identd, err := net.Listen("tcp", "0.0.0.0:"+port)
	if err != nil {
		fmt.Println("Failed to start identd on port", port)
		return
	}
	defer identd.Close()
	fmt.Println("Started identd on port", port)

	for {
		conn, err := identd.Accept()
		if err != nil {
			fmt.Println("Failed to accept identd connection")
			continue
		}

		io := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
		line, err := io.Reader.ReadString('\n')
		if err != nil || len(line) < 2 {
			conn.Close()
			fmt.Println("Failed to read identd request")
			continue
		}
		line = line[:len(line)-2]
		line = fmt.Sprintf("%s : ERROR : NO-USER\r\n", line)
		io.Writer.WriteString(line)
		time.Sleep(1000000000) // 1 second
		conn.Close()
	}
}
Пример #15
0
// NewAOF ...
func NewAOF(path string) *AOF {
	file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0600)
	utils.PanicOnError(err)
	rdr := bufio.NewReader(file)
	wtr := bufio.NewWriter(file)
	return &AOF{file, bufio.NewReadWriter(rdr, wtr), sync.RWMutex{}}
}
Пример #16
0
// Hijack takes a net.Conn and the host name to create the SSL
// certificate for and returns a tls.Conn that can read and write
// to the given host over TLS.
func (mitm *MITM) Hijack(conn net.Conn, host string) (*tls.Conn, *bufio.ReadWriter, error) {
	// Ensure the certificate we create is valid within a window of time to allow
	// for clock skew.
	start := time.Now().Add(-mitm.Validity)
	end := time.Now().Add(mitm.Validity)

	tpl, err := NewTemplate(mitm.Organization, host, start, end, mitm.PublicKey)
	if err != nil {
		return nil, nil, err
	}

	cb, err := x509.CreateCertificate(rand.Reader, tpl, mitm.Authority, mitm.PublicKey, mitm.PrivateKey)
	if err != nil {
		return nil, nil, err
	}

	config := &tls.Config{
		Certificates: []tls.Certificate{
			{
				PrivateKey:  mitm.PrivateKey,
				Certificate: [][]byte{cb},
			},
		},
	}

	tlsConn := tls.Server(conn, config)
	r := bufio.NewReader(tlsConn)
	w := bufio.NewWriter(tlsConn)

	return tlsConn, bufio.NewReadWriter(r, w), nil
}
Пример #17
0
func (rw *hijackResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	rw.hijacked = true

	br := bufio.NewReader(rw.conn)
	bw := bufio.NewWriter(rw.conn)
	return rw.conn, bufio.NewReadWriter(br, bw), nil
}
Пример #18
0
func TestBulkBytes(t *testing.T) {
	b := &bytes.Buffer{}
	c := &redisConnection{
		nc:  nil,
		rw:  bufio.NewReadWriter(bufio.NewReader(b), bufio.NewWriter(b)),
		buf: make([]byte, 24),
	}
	by := []byte{1, 2, 3, 4}
	if err := c.writeBulkBytes(by); err != nil {
		t.Fatalf("Error during writeBulkBytes: %s", err)
	}
	if err := c.writeBulkBytes(by); err != nil {
		t.Fatalf("Error during writeBulkBytes: %s", err)
	}
	c.rw.Flush()
	if o, err := c.readBulkBytes(); err != nil {
		t.Fatalf("Error during readBulkBytes: %s", err)
	} else if !bytes.Equal(o, by) {
		t.Fatalf("write/readBulkBytes returned wrong balue %+v expected %+v", o, by)
	}
	if o, err := c.readBulkBytes(); err != nil {
		t.Fatalf("Error during readBulkBytes: %s", err)
	} else if !bytes.Equal(o, by) {
		t.Fatalf("write/readBulkBytes returned wrong balue %+v expected %+v", o, by)
	}
}
Пример #19
0
func TestReadDataPacketOK(t *testing.T) {
	byteBuf := []byte("DATA 1 46\r\n{\"action\":\"foo\",\"version\":1,\"envelope\":\"json\"}END\r\n")
	byteReader := bufio.NewReader(bytes.NewReader(byteBuf))
	byteRdrWrtr := bufio.NewReadWriter(byteReader, nil)

	packet, err := ReadPacket(byteRdrWrtr)
	if err != nil {
		t.Errorf("got err `%s`", err)
		t.FailNow()
	}
	if packet.packetType != DATA {
		t.Errorf("packetType was not parsed correctly. packet.packetType: `%d`", packet.packetType)
		t.FailNow()
	}
	expectedBody := []byte(`{"action":"foo","version":1,"envelope":"json"}`)
	if !bytes.Equal(packet.body, expectedBody) {
		t.Errorf("bad packet body parse. expected `%s`, got: `%s`", expectedBody, packet.body)
		t.FailNow()
	}

	emptyHeader := PacketHeader{}
	if packet.packetHeader != emptyHeader {
		t.Errorf("packet header should not be set")
		t.FailNow()
	}
}
Пример #20
0
func newClient(socket net.Conn, version, maxBatch int) (client *Client, err error) {
	readWriter := bufio.NewReadWriter(bufio.NewReader(socket), bufio.NewWriter(socket))

	heloRequest := &HeloRequest{
		Version:  version,
		MaxBatch: maxBatch,
	}
	if _, err = heloRequest.WriteTo(readWriter); err != nil {
		return nil, err
	}
	if err = readWriter.Flush(); err != nil {
		return nil, err
	}

	heloReply := &HeloReply{}
	if _, err = heloReply.ReadFrom(readWriter); err != nil {
		return nil, err
	}

	if heloReply.Version != version {
		if err = socket.Close(); err != nil {
			return nil, err
		}
		return nil, ErrUnsupportedVersion
	}

	client = &Client{
		Version:    version,
		socket:     socket,
		readWriter: readWriter,
	}
	return
}
Пример #21
0
func plumbWebsocket(w http.ResponseWriter, r *http.Request, route **Route) error {
	hj, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
		return errors.New("no-hijack")
	}
	conn, bufrw, err := hj.Hijack()
	conn2, err := net.Dial("tcp", r.URL.Host)
	if err != nil {
		http.Error(w, "couldn't connect to backend server", http.StatusServiceUnavailable)
		return errors.New("dead-backend")
	}
	err = r.Write(conn2)
	if err != nil {
		log.Warning("writing WebSocket request to backend server failed: %v", err)
		return errors.New("dead-backend")
	}
	CopyBidir(conn, bufrw, conn2, bufio.NewReadWriter(bufio.NewReader(conn2), bufio.NewWriter(conn2)), route)
	err = conn.Close()

	if err != nil {
		log.Warning("Could not close stream", err)
	}
	err = conn2.Close()
	if err != nil {
		log.Warning("Could not close stream", err)
	}
	return nil
}
Пример #22
0
func execute(t *testing.T, sServer, sClient string, processFn processFunc) {
	server := strings.Join(strings.Split(baseHelloServer+sServer, "\n"), "\r\n")
	client := strings.Join(strings.Split(baseHelloClient+sClient, "\n"), "\r\n")

	var cmdbuf bytes.Buffer

	bcmdbuf := bufio.NewWriter(&cmdbuf)

	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)

	c, err := NewClient(fake)

	if err != nil {
		t.Fatalf("NewClient: %v", err)
	}

	defer c.Close()

	processFn(t, c)

	bcmdbuf.Flush()

	actualcmds := cmdbuf.String()

	if client != actualcmds {
		t.Errorf("Got:\n[%s]\nExpected:\n[%s]", actualcmds, client)
	}
}
Пример #23
0
func TestSequence(t *testing.T) {
	client := strings.Join(strings.Split(testClient, "\n"), "\r\n")

	var outbuf bytes.Buffer
	writer := bufio.NewWriter(&outbuf)
	reader := bufio.NewReader(strings.NewReader(client))
	cxn := &faker{ReadWriter: bufio.NewReadWriter(reader, writer)}

	// Server(reader, writer)
	var evt EventInfo
	conn := NewConn(cxn, Config{}, nil)
	pos := 0
	for {
		evt = conn.Next()
		ts := testStream[pos]
		if evt.What != ts.what || evt.Cmd != ts.cmd {
			t.Fatalf("Sequence mismatch at step %d: expected %v %v got %v %v\n",
				pos, ts.what, ts.cmd, evt.What, evt.Cmd)
		}
		pos++
		if evt.What == DONE {
			break
		}
	}
}
Пример #24
0
func HandleClient(client net.Conn) {
	clientIo := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))

	for {
		line, isPrefix, err := clientIo.ReadLine()
		if isPrefix {
			// unreached end of line
			log.Printf("<<%s>>\n", err)
		}

		if err != nil {
			// handle error
			log.Printf("<<%s>>\n", err)
			break
		}

		sz, err := clientIo.WriteString(fmt.Sprintf("%s\n", line))
		if err != nil || sz == 0 {
			// handle error
			log.Printf("<<%s>>\n", err)
			break
		}

		clientIo.Flush()
	}

	client.Close()
	log.Print("client closed.\n")
}
Пример #25
0
func New(addr string, user string, pass string) (cli *BaseXClient, err error) {
	cli = &BaseXClient{
		bufPool: &sync.Pool{
			New: func() interface{} {
				return bytes.NewBuffer(nil)
			},
		},
	}

	cli.con, err = net.Dial("tcp", addr)
	if err != nil {
		cli = nil
		return
	}

	cli.ReadWriter = bufio.NewReadWriter(bufio.NewReader(cli.con), bufio.NewWriter(cli.con))
	ts := cli.ReadString()

	var ok bool
	cli.send(user)
	if i := strings.Index(ts, ":"); i != -1 {
		ok = cli.login(user, pass, string(ts[:i]), string(ts[i+1:]))
	} else {
		ok = cli.loginLegacy(pass, ts)
	}

	if !ok {
		err = errors.New("Login error")
		cli = nil
	}

	return
}
Пример #26
0
func TestNewClient(t *testing.T) {
	newClientServer = strings.Join(strings.Split(newClientServer, "\n"), "\r\n")
	newClientClient = strings.Join(strings.Split(newClientClient, "\n"), "\r\n")

	var cmdbuf bytes.Buffer
	bcmdbuf := bufio.NewWriter(&cmdbuf)
	out := func() string {
		bcmdbuf.Flush()
		return cmdbuf.String()
	}
	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(newClientServer)), bcmdbuf)
	c, err := NewClient(fake, "fake.host")
	if err != nil {
		t.Fatalf("NewClient: %v\n(after %v)", err, out())
	}
	if ok, args := c.Extension("aUtH"); !ok || args != "LOGIN PLAIN" {
		t.Fatalf("Expected AUTH supported")
	}
	if ok, _ := c.Extension("DSN"); ok {
		t.Fatalf("Shouldn't support DSN")
	}
	if err := c.Quit(); err != nil {
		t.Fatalf("QUIT failed: %s", err)
	}

	actualcmds := out()
	if newClientClient != actualcmds {
		t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, newClientClient)
	}
}
Пример #27
0
func (p *Proxy) handleLoop(conn net.Conn) {
	p.conns.Add(1)
	defer p.conns.Done()
	defer conn.Close()

	s, err := newSession()
	if err != nil {
		log.Errorf("martian: failed to create session: %v", err)
		return
	}

	ctx, err := withSession(s)
	if err != nil {
		log.Errorf("martian: failed to create context: %v", err)
		return
	}

	brw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	for {
		deadline := time.Now().Add(p.timeout)
		conn.SetDeadline(deadline)

		if err := p.handle(ctx, conn, brw); isCloseable(err) {
			log.Debugf("martian: closing connection: %v", conn.RemoteAddr())
			return
		}
	}
}
Пример #28
0
func TestNewClient2(t *testing.T) {
	newClient2Server = strings.Join(strings.Split(newClient2Server, "\n"), "\r\n")
	newClient2Client = strings.Join(strings.Split(newClient2Client, "\n"), "\r\n")

	var cmdbuf bytes.Buffer
	bcmdbuf := bufio.NewWriter(&cmdbuf)
	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(newClient2Server)), bcmdbuf)
	c, err := NewClient(fake, "fake.host")
	if err != nil {
		t.Fatalf("NewClient: %v", err)
	}
	if ok, _ := c.Extension("DSN"); ok {
		t.Fatalf("Shouldn't support DSN")
	}
	if err := c.Quit(); err != nil {
		t.Fatalf("QUIT failed: %s", err)
	}

	bcmdbuf.Flush()
	actualcmds := cmdbuf.String()
	if newClient2Client != actualcmds {
		t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, newClient2Client)
	}
}
Пример #29
0
// connect is the method used to maintain a connection to the serial device.
func (g *GarageFeed) connect() {
	for {
		// Try to connect to the path.
		serial, err := os.OpenFile(g.path, os.O_RDWR|syscall.O_NOCTTY, 0666)
		if err != nil {
			g.delay += 1
			sec := g.delay * g.delay
			log.Printf("feed: got err=%s on `%s`, %d retry", err, g.path, sec)
			time.Sleep(time.Duration(sec) * time.Second)
			continue
		}

		// Success; set up bufio.ReadWriter.
		log.Printf("feed: ready")
		g.delay = 0
		rw := bufio.NewReadWriter(bufio.NewReader(serial), bufio.NewWriter(serial))

		// Close the serial port; this will eventually die for some reason.
		for {
			var result string
			req := <-g.requests
			result, err = g.run(req, rw)
			if err != nil {
				req.result <- err
				break
			}
			req.result <- result
		}
		log.Printf("feed: shutdown, err=%s", err)
		serial.Close()
	}
}
Пример #30
0
// Verify that the server (e.g. the buildlet dialing the coordinator)
// going away unblocks all connections active back to it.
func TestServerEOFKillsConns(t *testing.T) {
	pr, pw := io.Pipe()
	var out bytes.Buffer
	d := NewDialer(bufio.NewReadWriter(
		bufio.NewReader(pr),
		bufio.NewWriter(&out),
	), ioutil.NopCloser(nil))

	c, err := d.Dial()
	if err != nil {
		t.Fatal(err)
	}

	readErr := make(chan error, 1)
	go func() {
		_, err := c.Read([]byte{0})
		readErr <- err
	}()
	pw.Close()

	select {
	case err := <-readErr:
		if err == nil {
			t.Fatal("got nil read error; want non-nil")
		}
	case <-time.After(2 * time.Second):
		t.Error("timeout waiting for Read")
	}

	select {
	case <-d.Done():
	case <-time.After(2 * time.Second):
		t.Error("timeout waiting for Done channel")
	}
}