-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
manager.go
160 lines (144 loc) · 4 KB
/
manager.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package manager
import (
"crypto/hmac"
"fmt"
"net/http"
"runtime"
"sync"
"github.com/keybase/client/go/kbhttp"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
context "golang.org/x/net/context"
)
type SrvTokenMode int
const (
SrvTokenModeDefault = iota
SrvTokenModeUnchecked // use with caution!
)
type srvEndpoint struct {
tokenMode SrvTokenMode
serve func(w http.ResponseWriter, req *http.Request)
}
type Srv struct {
libkb.Contextified
httpSrv *kbhttp.Srv
endpoints map[string]srvEndpoint
token string
startMu sync.Mutex
}
func NewSrv(g *libkb.GlobalContext) *Srv {
h := &Srv{
Contextified: libkb.NewContextified(g),
endpoints: make(map[string]srvEndpoint),
}
h.initHTTPSrv()
h.startHTTPSrv()
g.PushShutdownHook(func(mctx libkb.MetaContext) error {
h.httpSrv.Stop()
return nil
})
go h.monitorAppState()
return h
}
func (r *Srv) debug(ctx context.Context, msg string, args ...interface{}) {
r.G().Log.CDebugf(ctx, "Srv: %s", fmt.Sprintf(msg, args...))
}
func (r *Srv) initHTTPSrv() {
startPort := r.G().GetEnv().GetAttachmentHTTPStartPort()
r.httpSrv = kbhttp.NewSrv(r.G().GetLog(), kbhttp.NewRandomPortRangeListenerSource(startPort, 18000))
}
func (r *Srv) startHTTPSrv() {
r.startMu.Lock()
defer r.startMu.Unlock()
ctx := context.Background()
token, _ := libkb.RandHexString("", 32)
maxTries := 2
success := false
for i := 0; i < maxTries; i++ {
if err := r.httpSrv.Start(); err != nil {
if err == kbhttp.ErrPinnedPortInUse {
// If we hit this, just try again and get a different port.
// The advantage is that backing in and out of the thread will restore attachments,
// whereas if we do nothing you need to bkg/foreground.
r.debug(ctx, "startHTTPSrv: pinned port taken error, re-initializing and trying again")
r.initHTTPSrv()
continue
}
r.debug(ctx, "startHTTPSrv: failed to start HTTP server: %s", err)
break
}
success = true
break
}
if !success {
r.debug(ctx, "startHTTPSrv: exhausted attempts to start HTTP server, giving up")
return
}
for endpoint, serveDesc := range r.endpoints {
r.HandleFunc(endpoint, serveDesc.tokenMode, serveDesc.serve)
}
addr, err := r.httpSrv.Addr()
if err != nil {
r.debug(ctx, "startHTTPSrv: failed to get address after start?: %s", err)
} else {
r.debug(ctx, "startHTTPSrv: start success: addr: %s", addr)
}
r.token = token
r.debug(ctx, "startHTTPSrv: addr: %s token: %s", addr, r.token)
r.G().NotifyRouter.HandleHTTPSrvInfoUpdate(ctx, keybase1.HttpSrvInfo{
Address: addr,
Token: r.token,
})
}
func (r *Srv) monitorAppState() {
ctx := context.Background()
r.debug(ctx, "monitorAppState: starting up")
state := keybase1.MobileAppState_FOREGROUND
// We don't need this on Android
if runtime.GOOS == "android" {
return
}
for {
state = <-r.G().MobileAppState.NextUpdate(&state)
switch state {
case keybase1.MobileAppState_FOREGROUND, keybase1.MobileAppState_BACKGROUNDACTIVE:
r.startHTTPSrv()
case keybase1.MobileAppState_BACKGROUND, keybase1.MobileAppState_INACTIVE:
r.httpSrv.Stop()
}
}
}
func (r *Srv) HandleFunc(endpoint string, tokenMode SrvTokenMode,
serve func(w http.ResponseWriter, req *http.Request)) {
r.httpSrv.HandleFunc("/"+endpoint, func(w http.ResponseWriter, req *http.Request) {
switch tokenMode {
case SrvTokenModeDefault:
if !hmac.Equal([]byte(req.URL.Query().Get("token")), []byte(r.token)) {
r.debug(context.Background(), "HandleFunc: token failed: %s != %s",
req.URL.Query().Get("token"), r.token)
w.WriteHeader(http.StatusForbidden)
return
}
case SrvTokenModeUnchecked:
// serve needs to authenticate on its own
}
serve(w, req)
})
r.endpoints[endpoint] = srvEndpoint{
tokenMode: tokenMode,
serve: serve,
}
}
func (r *Srv) Active() bool {
return r.httpSrv.Active()
}
func (r *Srv) Addr() (string, error) {
r.startMu.Lock()
defer r.startMu.Unlock()
return r.httpSrv.Addr()
}
func (r *Srv) Token() string {
r.startMu.Lock()
defer r.startMu.Unlock()
return r.token
}