2016-01-15 15:54:27 +00:00
|
|
|
package adb
|
2015-04-12 20:34:20 +00:00
|
|
|
|
|
|
|
import (
|
2015-12-30 08:00:03 +00:00
|
|
|
"io"
|
2015-04-12 20:34:20 +00:00
|
|
|
"net"
|
|
|
|
"runtime"
|
2015-07-11 21:32:04 +00:00
|
|
|
|
2020-07-13 06:18:10 +00:00
|
|
|
"goadb/internal/errors"
|
|
|
|
"goadb/wire"
|
2015-07-11 21:32:04 +00:00
|
|
|
)
|
|
|
|
|
2016-01-10 21:33:22 +00:00
|
|
|
// Dialer knows how to create connections to an adb server.
|
2015-04-12 20:34:20 +00:00
|
|
|
type Dialer interface {
|
2016-01-10 21:33:22 +00:00
|
|
|
Dial(address string) (*wire.Conn, error)
|
2015-04-12 20:34:20 +00:00
|
|
|
}
|
|
|
|
|
2016-01-10 21:33:22 +00:00
|
|
|
type tcpDialer struct{}
|
2015-05-04 01:07:03 +00:00
|
|
|
|
2015-04-12 20:34:20 +00:00
|
|
|
// Dial connects to the adb server on the host and port set on the netDialer.
|
|
|
|
// The zero-value will connect to the default, localhost:5037.
|
2016-01-10 21:33:22 +00:00
|
|
|
func (tcpDialer) Dial(address string) (*wire.Conn, error) {
|
2015-07-12 06:18:58 +00:00
|
|
|
netConn, err := net.Dial("tcp", address)
|
2015-04-12 20:34:20 +00:00
|
|
|
if err != nil {
|
2016-05-22 17:49:32 +00:00
|
|
|
return nil, errors.WrapErrorf(err, errors.ServerNotAvailable, "error dialing %s", address)
|
2015-04-12 20:34:20 +00:00
|
|
|
}
|
|
|
|
|
2015-12-30 08:00:03 +00:00
|
|
|
// net.Conn can't be closed more than once, but wire.Conn will try to close both sender and scanner
|
|
|
|
// so we need to wrap it to make it safe.
|
|
|
|
safeConn := wire.MultiCloseable(netConn)
|
2015-04-12 20:34:20 +00:00
|
|
|
|
|
|
|
// Prevent leaking the network connection, not sure if TCPConn does this itself.
|
2015-12-30 08:00:03 +00:00
|
|
|
// Note that the network connection may still be in use after the conn isn't (scanners/senders
|
|
|
|
// can give their underlying connections to other scanner/sender types), so we can't
|
|
|
|
// set the finalizer on conn.
|
|
|
|
runtime.SetFinalizer(safeConn, func(conn io.ReadWriteCloser) {
|
2015-04-12 20:34:20 +00:00
|
|
|
conn.Close()
|
|
|
|
})
|
|
|
|
|
2015-12-30 08:00:03 +00:00
|
|
|
return &wire.Conn{
|
|
|
|
Scanner: wire.NewScanner(safeConn),
|
|
|
|
Sender: wire.NewSender(safeConn),
|
|
|
|
}, nil
|
2015-04-12 20:34:20 +00:00
|
|
|
}
|