/
forward.go
71 lines (59 loc) · 1.91 KB
/
forward.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package forward
import (
"fmt"
"io"
"net"
"github.com/danielpaulus/go-ios/ios"
log "github.com/sirupsen/logrus"
)
type iosproxy struct {
tcpConn net.Conn
deviceConn ios.DeviceConnectionInterface
}
//Forward forwards every connection made to the hostPort to whatever service runs inside an app on the device on phonePort.
func Forward(device ios.DeviceEntry, hostPort uint16, phonePort uint16) error {
log.Infof("Start listening on port %d forwarding to port %d on device", hostPort, phonePort)
l, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", hostPort))
go connectionAccept(l, device.DeviceID, phonePort)
if err != nil {
return err
}
return nil
}
func connectionAccept(l net.Listener, deviceID int, phonePort uint16) {
for {
clientConn, err := l.Accept()
if err != nil {
log.Errorf("Error accepting new connection %v", err)
continue
}
log.WithFields(log.Fields{"conn": fmt.Sprintf("%#v", clientConn)}).Info("new client connected")
go startNewProxyConnection(clientConn, deviceID, phonePort)
}
}
func startNewProxyConnection(clientConn net.Conn, deviceID int, phonePort uint16) {
usbmuxConn, err := ios.NewUsbMuxConnectionSimple()
if err != nil {
log.Errorf("could not connect to usbmuxd: %+v", err)
clientConn.Close()
return
}
muxError := usbmuxConn.Connect(deviceID, phonePort)
if muxError != nil {
log.WithFields(log.Fields{"conn": fmt.Sprintf("%#v", clientConn), "err": muxError, "phonePort": phonePort}).Infof("could not connect to phone")
clientConn.Close()
return
}
log.WithFields(log.Fields{"conn": fmt.Sprintf("%#v", clientConn), "phonePort": phonePort}).Infof("Connected to port")
deviceConn := usbmuxConn.ReleaseDeviceConnection()
//proxyConn := iosproxy{clientConn, deviceConn}
go func() {
io.Copy(clientConn, deviceConn.Reader())
}()
go func() {
io.Copy(deviceConn.Writer(), clientConn)
}()
}
func (proxyConn *iosproxy) Close() {
proxyConn.tcpConn.Close()
}