Exemplo n.º 1
0
func exchangeHello(c net.Conn, h protocol.HelloMessage) (protocol.HelloMessage, error) {
	if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil {
		return protocol.HelloMessage{}, err
	}
	defer c.SetDeadline(time.Time{})

	header := make([]byte, 8)
	msg := h.MustMarshalXDR()

	binary.BigEndian.PutUint32(header[:4], protocol.HelloMessageMagic)
	binary.BigEndian.PutUint32(header[4:], uint32(len(msg)))

	if _, err := c.Write(header); err != nil {
		return protocol.HelloMessage{}, err
	}

	if _, err := c.Write(msg); err != nil {
		return protocol.HelloMessage{}, err
	}

	if _, err := io.ReadFull(c, header); err != nil {
		return protocol.HelloMessage{}, err
	}

	if binary.BigEndian.Uint32(header[:4]) != protocol.HelloMessageMagic {
		return protocol.HelloMessage{}, fmt.Errorf("incorrect magic")
	}

	msgSize := binary.BigEndian.Uint32(header[4:])
	if msgSize > 1024 {
		return protocol.HelloMessage{}, fmt.Errorf("hello message too big")
	}

	buf := make([]byte, msgSize)

	var hello protocol.HelloMessage

	if _, err := io.ReadFull(c, buf); err != nil {
		return protocol.HelloMessage{}, err
	}

	if err := hello.UnmarshalXDR(buf); err != nil {
		return protocol.HelloMessage{}, err
	}

	return hello, nil
}
Exemplo n.º 2
0
func TestDeviceRename(t *testing.T) {
	hello := protocol.HelloMessage{
		ClientName:    "syncthing",
		ClientVersion: "v0.9.4",
	}
	defer os.Remove("tmpconfig.xml")

	rawCfg := config.New(device1)
	rawCfg.Devices = []config.DeviceConfiguration{
		{
			DeviceID: device1,
		},
	}
	cfg := config.Wrap("tmpconfig.xml", rawCfg)

	db := db.OpenMemory()
	m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)

	if cfg.Devices()[device1].Name != "" {
		t.Errorf("Device already has a name")
	}

	conn := Connection{
		&net.TCPConn{},
		&FakeConnection{
			id:          device1,
			requestData: []byte("some data to return"),
		},
		ConnectionTypeDirectAccept,
	}

	m.AddConnection(conn, hello)

	m.ServeBackground()

	if cfg.Devices()[device1].Name != "" {
		t.Errorf("Device already has a name")
	}

	m.Close(device1, protocol.ErrTimeout)
	hello.DeviceName = "tester"
	m.AddConnection(conn, hello)

	if cfg.Devices()[device1].Name != "tester" {
		t.Errorf("Device did not get a name")
	}

	m.Close(device1, protocol.ErrTimeout)
	hello.DeviceName = "tester2"
	m.AddConnection(conn, hello)

	if cfg.Devices()[device1].Name != "tester" {
		t.Errorf("Device name got overwritten")
	}

	cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
	if err != nil {
		t.Error(err)
		return
	}
	if cfgw.Devices()[device1].Name != "tester" {
		t.Errorf("Device name not saved in config")
	}

	m.Close(device1, protocol.ErrTimeout)

	opts := cfg.Options()
	opts.OverwriteNames = true
	cfg.SetOptions(opts)

	hello.DeviceName = "tester2"
	m.AddConnection(conn, hello)

	if cfg.Devices()[device1].Name != "tester2" {
		t.Errorf("Device name not overwritten")
	}
}