| 1 |
/* |
| 2 |
Copyright 2013-2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
// Package session handles the minutiae of interacting with |
| 18 |
// the Push Notifications server. |
| 19 |
package session |
| 20 |
|
| 21 |
import ( |
| 22 |
_ "crypto/sha512" // support sha384/512 certs |
| 23 |
"crypto/tls" |
| 24 |
"crypto/x509" |
| 25 |
"encoding/json" |
| 26 |
"encoding/pem" |
| 27 |
"errors" |
| 28 |
"fmt" |
| 29 |
"math/rand" |
| 30 |
"net" |
| 31 |
"strings" |
| 32 |
"sync" |
| 33 |
"sync/atomic" |
| 34 |
"time" |
| 35 |
|
| 36 |
"gitlab.com/ubports/development/core/lomiri-push-service/click" |
| 37 |
"gitlab.com/ubports/development/core/lomiri-push-service/client/gethosts" |
| 38 |
"gitlab.com/ubports/development/core/lomiri-push-service/client/session/seenstate" |
| 39 |
"gitlab.com/ubports/development/core/lomiri-push-service/logger" |
| 40 |
"gitlab.com/ubports/development/core/lomiri-push-service/protocol" |
| 41 |
"gitlab.com/ubports/development/core/lomiri-push-service/util" |
| 42 |
) |
| 43 |
|
| 44 |
type sessCmd uint8 |
| 45 |
|
| 46 |
const ( |
| 47 |
cmdDisconnect sessCmd = iota |
| 48 |
cmdConnect |
| 49 |
cmdResetCookie |
| 50 |
) |
| 51 |
|
| 52 |
var ( |
| 53 |
wireVersionBytes = []byte{protocol.ProtocolWireVersion} |
| 54 |
) |
| 55 |
|
| 56 |
type BroadcastNotification struct { |
| 57 |
TopLevel int64 |
| 58 |
Decoded []map[string]interface{} |
| 59 |
} |
| 60 |
|
| 61 |
type serverMsg struct { |
| 62 |
Type string `json:"T"` |
| 63 |
protocol.BroadcastMsg |
| 64 |
protocol.NotificationsMsg |
| 65 |
protocol.ConnBrokenMsg |
| 66 |
protocol.SetParamsMsg |
| 67 |
} |
| 68 |
|
| 69 |
// parseServerAddrSpec recognizes whether spec is a HTTP URL to get |
| 70 |
// hosts from or a |-separated list of host:port pairs. |
| 71 |
func parseServerAddrSpec(spec string) (hostsEndpoint string, fallbackHosts []string) { |
| 72 |
if strings.HasPrefix(spec, "http") { |
| 73 |
return spec, nil |
| 74 |
} |
| 75 |
return "", strings.Split(spec, "|") |
| 76 |
} |
| 77 |
|
| 78 |
// ClientSessionState is a way to broadly track the progress of the session |
| 79 |
type ClientSessionState uint32 |
| 80 |
|
| 81 |
const ( |
| 82 |
Error ClientSessionState = iota |
| 83 |
Pristine |
| 84 |
Disconnected |
| 85 |
Connected |
| 86 |
Started |
| 87 |
Running |
| 88 |
Shutdown |
| 89 |
Unknown |
| 90 |
) |
| 91 |
|
| 92 |
func (s ClientSessionState) String() string { |
| 93 |
if s >= Unknown { |
| 94 |
return fmt.Sprintf("??? (%d)", s) |
| 95 |
} |
| 96 |
return [Unknown]string{ |
| 97 |
"Error", |
| 98 |
"Pristine", |
| 99 |
"Disconnected", |
| 100 |
"Connected", |
| 101 |
"Started", |
| 102 |
"Running", |
| 103 |
"Shutdown", |
| 104 |
}[s] |
| 105 |
} |
| 106 |
|
| 107 |
type hostGetter interface { |
| 108 |
Get() (*gethosts.Host, error) |
| 109 |
} |
| 110 |
|
| 111 |
// AddresseeChecking can check if a notification can be delivered. |
| 112 |
type AddresseeChecking interface { |
| 113 |
StartAddresseeBatch() |
| 114 |
CheckForAddressee(*protocol.Notification) *click.AppId |
| 115 |
} |
| 116 |
|
| 117 |
// AddressedNotification carries both a protocol.Notification and a parsed |
| 118 |
// AppId addressee. |
| 119 |
type AddressedNotification struct { |
| 120 |
To *click.AppId |
| 121 |
Notification *protocol.Notification |
| 122 |
} |
| 123 |
|
| 124 |
// ClientSessionConfig groups the client session configuration. |
| 125 |
type ClientSessionConfig struct { |
| 126 |
ConnectTimeout time.Duration |
| 127 |
ExchangeTimeout time.Duration |
| 128 |
HostsCachingExpiryTime time.Duration |
| 129 |
ExpectAllRepairedTime time.Duration |
| 130 |
PEM []byte |
| 131 |
Info map[string]interface{} |
| 132 |
AddresseeChecker AddresseeChecking |
| 133 |
BroadcastCh chan *BroadcastNotification |
| 134 |
NotificationsCh chan AddressedNotification |
| 135 |
} |
| 136 |
|
| 137 |
// ClientSession holds a client<->server session and its configuration. |
| 138 |
type ClientSession interface { |
| 139 |
ResetCookie() |
| 140 |
State() ClientSessionState |
| 141 |
HasConnectivity(bool) |
| 142 |
KeepConnection() error |
| 143 |
StopKeepConnection() |
| 144 |
} |
| 145 |
|
| 146 |
type clientSession struct { |
| 147 |
// configuration |
| 148 |
DeviceId string |
| 149 |
ClientSessionConfig |
| 150 |
SeenState seenstate.SeenState |
| 151 |
Protocolator func(net.Conn) protocol.Protocol |
| 152 |
// hosts |
| 153 |
getHost hostGetter |
| 154 |
fallbackHosts []string |
| 155 |
deliveryHostsTimestamp time.Time |
| 156 |
deliveryHosts []string |
| 157 |
lastAttemptTimestamp time.Time |
| 158 |
leftToTry int |
| 159 |
tryHost int |
| 160 |
// hook for testing |
| 161 |
timeSince func(time.Time) time.Duration |
| 162 |
// connection |
| 163 |
connLock sync.RWMutex |
| 164 |
Connection net.Conn |
| 165 |
Log logger.Logger |
| 166 |
TLS *tls.Config |
| 167 |
proto protocol.Protocol |
| 168 |
pingInterval time.Duration |
| 169 |
retrier util.AutoRedialer |
| 170 |
cookie string |
| 171 |
// status |
| 172 |
stateLock sync.RWMutex |
| 173 |
state ClientSessionState |
| 174 |
// autoredial knobs |
| 175 |
shouldDelayP *uint32 |
| 176 |
lastAutoRedial time.Time |
| 177 |
redialDelay func(*clientSession) time.Duration |
| 178 |
redialJitter func(time.Duration) time.Duration |
| 179 |
redialDelays []time.Duration |
| 180 |
redialDelaysIdx int |
| 181 |
// connection events, and cookie reset requests, come in over here |
| 182 |
cmdCh chan sessCmd |
| 183 |
// last seen connection event is here |
| 184 |
lastConn bool |
| 185 |
// connection events are handled by this |
| 186 |
connHandler func(bool) |
| 187 |
// autoredial goes over here (xxx spurious goroutine involved) |
| 188 |
doneCh chan uint32 |
| 189 |
// main loop errors out through here (possibly another spurious goroutine) |
| 190 |
errCh chan error |
| 191 |
// main loop errors are handled by this |
| 192 |
errHandler func(error) |
| 193 |
// look, a stopper! |
| 194 |
stopCh chan struct{} |
| 195 |
} |
| 196 |
|
| 197 |
func redialDelay(sess *clientSession) time.Duration { |
| 198 |
if sess.ShouldDelay() { |
| 199 |
t := sess.redialDelays[sess.redialDelaysIdx] |
| 200 |
if len(sess.redialDelays) > sess.redialDelaysIdx+1 { |
| 201 |
sess.redialDelaysIdx++ |
| 202 |
} |
| 203 |
return t + sess.redialJitter(t) |
| 204 |
} else { |
| 205 |
sess.redialDelaysIdx = 0 |
| 206 |
return 0 |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
func NewSession(serverAddrSpec string, conf ClientSessionConfig, |
| 211 |
deviceId string, seenStateFactory func() (seenstate.SeenState, error), |
| 212 |
log logger.Logger) (*clientSession, error) { |
| 213 |
seenState, err := seenStateFactory() |
| 214 |
if err != nil { |
| 215 |
return nil, err |
| 216 |
} |
| 217 |
var getHost hostGetter |
| 218 |
log.Infof("using addr: %v", serverAddrSpec) |
| 219 |
hostsEndpoint, fallbackHosts := parseServerAddrSpec(serverAddrSpec) |
| 220 |
if hostsEndpoint != "" { |
| 221 |
getHost = gethosts.New(deviceId, hostsEndpoint, conf.ExchangeTimeout) |
| 222 |
} |
| 223 |
var shouldDelay uint32 = 0 |
| 224 |
sess := &clientSession{ |
| 225 |
ClientSessionConfig: conf, |
| 226 |
getHost: getHost, |
| 227 |
fallbackHosts: fallbackHosts, |
| 228 |
DeviceId: deviceId, |
| 229 |
Log: log, |
| 230 |
Protocolator: protocol.NewProtocol0, |
| 231 |
SeenState: seenState, |
| 232 |
TLS: &tls.Config{}, |
| 233 |
state: Pristine, |
| 234 |
timeSince: time.Since, |
| 235 |
shouldDelayP: &shouldDelay, |
| 236 |
redialDelay: redialDelay, // NOTE there are tests that use calling sess.redialDelay as an indication of calling autoRedial! |
| 237 |
redialDelays: util.Timeouts(), |
| 238 |
} |
| 239 |
sess.redialJitter = sess.Jitter |
| 240 |
if sess.PEM != nil { |
| 241 |
cp := x509.NewCertPool() |
| 242 |
ok := cp.AppendCertsFromPEM(sess.PEM) |
| 243 |
if !ok { |
| 244 |
return nil, errors.New("could not parse certificate") |
| 245 |
} |
| 246 |
sess.TLS.RootCAs = cp |
| 247 |
block, _ := pem.Decode(sess.PEM) |
| 248 |
if block == nil { |
| 249 |
panic(fmt.Errorf("unexpected error reparsing certificate")) |
| 250 |
} |
| 251 |
cert, err := x509.ParseCertificate(block.Bytes) |
| 252 |
if err != nil { |
| 253 |
panic(fmt.Errorf("unexpected error reparsing certificate: %v", err)) |
| 254 |
} |
| 255 |
// good guess |
| 256 |
var serverName string |
| 257 |
if len(cert.DNSNames) > 0 { |
| 258 |
serverName = cert.DNSNames[0] |
| 259 |
} else { |
| 260 |
serverName = cert.Subject.CommonName |
| 261 |
} |
| 262 |
sess.TLS.ServerName = serverName |
| 263 |
} |
| 264 |
sess.doneCh = make(chan uint32, 1) |
| 265 |
sess.stopCh = make(chan struct{}) |
| 266 |
sess.cmdCh = make(chan sessCmd) |
| 267 |
sess.errCh = make(chan error, 1) |
| 268 |
|
| 269 |
// to be overridden by tests |
| 270 |
sess.connHandler = sess.handleConn |
| 271 |
sess.errHandler = sess.handleErr |
| 272 |
|
| 273 |
return sess, nil |
| 274 |
} |
| 275 |
|
| 276 |
func (sess *clientSession) ShouldDelay() bool { |
| 277 |
return atomic.LoadUint32(sess.shouldDelayP) != 0 |
| 278 |
} |
| 279 |
|
| 280 |
func (sess *clientSession) setShouldDelay() { |
| 281 |
atomic.StoreUint32(sess.shouldDelayP, uint32(1)) |
| 282 |
} |
| 283 |
|
| 284 |
func (sess *clientSession) clearShouldDelay() { |
| 285 |
atomic.StoreUint32(sess.shouldDelayP, uint32(0)) |
| 286 |
} |
| 287 |
|
| 288 |
func (sess *clientSession) State() ClientSessionState { |
| 289 |
sess.stateLock.RLock() |
| 290 |
defer sess.stateLock.RUnlock() |
| 291 |
return sess.state |
| 292 |
} |
| 293 |
|
| 294 |
func (sess *clientSession) setState(state ClientSessionState) { |
| 295 |
sess.stateLock.Lock() |
| 296 |
defer sess.stateLock.Unlock() |
| 297 |
sess.Log.Debugf("session.setState: %s -> %s", sess.state, state) |
| 298 |
sess.state = state |
| 299 |
} |
| 300 |
|
| 301 |
func (sess *clientSession) setConnection(conn net.Conn) { |
| 302 |
sess.connLock.Lock() |
| 303 |
defer sess.connLock.Unlock() |
| 304 |
sess.Connection = conn |
| 305 |
} |
| 306 |
|
| 307 |
func (sess *clientSession) getConnection() net.Conn { |
| 308 |
sess.connLock.RLock() |
| 309 |
defer sess.connLock.RUnlock() |
| 310 |
return sess.Connection |
| 311 |
} |
| 312 |
|
| 313 |
func (sess *clientSession) setCookie(cookie string) { |
| 314 |
sess.connLock.Lock() |
| 315 |
defer sess.connLock.Unlock() |
| 316 |
sess.cookie = cookie |
| 317 |
} |
| 318 |
|
| 319 |
func (sess *clientSession) getCookie() string { |
| 320 |
sess.connLock.RLock() |
| 321 |
defer sess.connLock.RUnlock() |
| 322 |
return sess.cookie |
| 323 |
} |
| 324 |
|
| 325 |
func (sess *clientSession) ResetCookie() { |
| 326 |
sess.cmdCh <- cmdResetCookie |
| 327 |
} |
| 328 |
|
| 329 |
func (sess *clientSession) resetCookie() { |
| 330 |
sess.stopRedial() |
| 331 |
sess.doClose(true) |
| 332 |
} |
| 333 |
|
| 334 |
// getHosts sets deliveryHosts possibly querying a remote endpoint |
| 335 |
func (sess *clientSession) getHosts() error { |
| 336 |
if sess.getHost != nil { |
| 337 |
if sess.deliveryHosts != nil && sess.timeSince(sess.deliveryHostsTimestamp) < sess.HostsCachingExpiryTime { |
| 338 |
return nil |
| 339 |
} |
| 340 |
host, err := sess.getHost.Get() |
| 341 |
if err != nil { |
| 342 |
sess.Log.Errorf("getHosts: %v", err) |
| 343 |
sess.setState(Error) |
| 344 |
return err |
| 345 |
} |
| 346 |
sess.deliveryHostsTimestamp = time.Now() |
| 347 |
sess.deliveryHosts = host.Hosts |
| 348 |
if sess.TLS != nil { |
| 349 |
sess.TLS.ServerName = host.Domain |
| 350 |
} |
| 351 |
} else { |
| 352 |
sess.deliveryHosts = sess.fallbackHosts |
| 353 |
} |
| 354 |
return nil |
| 355 |
} |
| 356 |
|
| 357 |
func (sess *clientSession) resetHosts() { |
| 358 |
sess.deliveryHosts = nil |
| 359 |
} |
| 360 |
|
| 361 |
// startConnectionAttempt/nextHostToTry help connect iterating over candidate hosts |
| 362 |
|
| 363 |
func (sess *clientSession) startConnectionAttempt() { |
| 364 |
if sess.timeSince(sess.lastAttemptTimestamp) > sess.ExpectAllRepairedTime { |
| 365 |
sess.tryHost = 0 |
| 366 |
} |
| 367 |
sess.leftToTry = len(sess.deliveryHosts) |
| 368 |
if sess.leftToTry == 0 { |
| 369 |
panic("should have got hosts from config or remote at this point") |
| 370 |
} |
| 371 |
sess.lastAttemptTimestamp = time.Now() |
| 372 |
} |
| 373 |
|
| 374 |
func (sess *clientSession) nextHostToTry() string { |
| 375 |
if sess.leftToTry == 0 { |
| 376 |
return "" |
| 377 |
} |
| 378 |
res := sess.deliveryHosts[sess.tryHost] |
| 379 |
sess.tryHost = (sess.tryHost + 1) % len(sess.deliveryHosts) |
| 380 |
sess.leftToTry-- |
| 381 |
return res |
| 382 |
} |
| 383 |
|
| 384 |
// we reached the Started state, we can retry with the same host if we |
| 385 |
// have to retry again |
| 386 |
func (sess *clientSession) started() { |
| 387 |
sess.tryHost-- |
| 388 |
if sess.tryHost == -1 { |
| 389 |
sess.tryHost = len(sess.deliveryHosts) - 1 |
| 390 |
} |
| 391 |
sess.setState(Started) |
| 392 |
} |
| 393 |
|
| 394 |
// connect to a server using the configuration in the ClientSession |
| 395 |
// and set up the connection. |
| 396 |
func (sess *clientSession) connect() error { |
| 397 |
sess.setShouldDelay() |
| 398 |
sess.startConnectionAttempt() |
| 399 |
var err error |
| 400 |
var conn net.Conn |
| 401 |
for { |
| 402 |
host := sess.nextHostToTry() |
| 403 |
if host == "" { |
| 404 |
sess.setState(Error) |
| 405 |
return fmt.Errorf("connect: %s", err) |
| 406 |
} |
| 407 |
sess.Log.Debugf("trying to connect to: %v", host) |
| 408 |
conn, err = net.DialTimeout("tcp", host, sess.ConnectTimeout) |
| 409 |
if err == nil { |
| 410 |
break |
| 411 |
} |
| 412 |
} |
| 413 |
sess.setConnection(tls.Client(conn, sess.TLS)) |
| 414 |
sess.setState(Connected) |
| 415 |
return nil |
| 416 |
} |
| 417 |
|
| 418 |
func (sess *clientSession) stopRedial() { |
| 419 |
if sess.retrier != nil { |
| 420 |
sess.retrier.Stop() |
| 421 |
sess.retrier = nil |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
func (sess *clientSession) autoRedial() { |
| 426 |
sess.stopRedial() |
| 427 |
if time.Since(sess.lastAutoRedial) < 2*time.Second { |
| 428 |
sess.setShouldDelay() |
| 429 |
} |
| 430 |
// xxx should we really wait on the caller goroutine? |
| 431 |
delay := sess.redialDelay(sess) |
| 432 |
sess.Log.Debugf("session redial delay: %v, wait", delay) |
| 433 |
time.Sleep(delay) |
| 434 |
sess.Log.Debugf("session redial delay: %v, cont", delay) |
| 435 |
if sess.retrier != nil { |
| 436 |
panic("session AutoRedial: unexpected non-nil retrier.") |
| 437 |
} |
| 438 |
sess.retrier = util.NewAutoRedialer(sess) |
| 439 |
sess.lastAutoRedial = time.Now() |
| 440 |
go func(retrier util.AutoRedialer) { |
| 441 |
sess.Log.Debugf("session autoredialier launching Redial goroutine") |
| 442 |
// if the redialer has been stopped before calling Redial(), it'll return 0. |
| 443 |
sess.doneCh <- retrier.Redial() |
| 444 |
}(sess.retrier) |
| 445 |
} |
| 446 |
|
| 447 |
func (sess *clientSession) doClose(resetCookie bool) { |
| 448 |
sess.connLock.Lock() |
| 449 |
defer sess.connLock.Unlock() |
| 450 |
if resetCookie { |
| 451 |
sess.cookie = "" |
| 452 |
} |
| 453 |
sess.closeConnection() |
| 454 |
sess.setState(Disconnected) |
| 455 |
} |
| 456 |
|
| 457 |
func (sess *clientSession) closeConnection() { |
| 458 |
// *must be called with connLock held* |
| 459 |
if sess.Connection != nil { |
| 460 |
sess.Connection.Close() |
| 461 |
// we ignore Close errors, on purpose (the thinking being that |
| 462 |
// the connection isn't really usable, and you've got nothing |
| 463 |
// you could do to recover at this stage). |
| 464 |
sess.Connection = nil |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
// handle "ping" messages |
| 469 |
func (sess *clientSession) handlePing() error { |
| 470 |
err := sess.proto.WriteMessage(protocol.PingPongMsg{Type: "pong"}) |
| 471 |
if err == nil { |
| 472 |
sess.Log.Debugf("ping.") |
| 473 |
sess.clearShouldDelay() |
| 474 |
} else { |
| 475 |
sess.setState(Error) |
| 476 |
sess.Log.Errorf("unable to pong: %s", err) |
| 477 |
} |
| 478 |
return err |
| 479 |
} |
| 480 |
|
| 481 |
func (sess *clientSession) decodeBroadcast(bcast *serverMsg) *BroadcastNotification { |
| 482 |
decoded := make([]map[string]interface{}, 0) |
| 483 |
for _, p := range bcast.Payloads { |
| 484 |
var v map[string]interface{} |
| 485 |
err := json.Unmarshal(p, &v) |
| 486 |
if err != nil { |
| 487 |
sess.Log.Debugf("expected map in broadcast: %v", err) |
| 488 |
continue |
| 489 |
} |
| 490 |
decoded = append(decoded, v) |
| 491 |
} |
| 492 |
return &BroadcastNotification{ |
| 493 |
TopLevel: bcast.TopLevel, |
| 494 |
Decoded: decoded, |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
// handle "broadcast" messages |
| 499 |
func (sess *clientSession) handleBroadcast(bcast *serverMsg) error { |
| 500 |
err := sess.SeenState.SetLevel(bcast.ChanId, bcast.TopLevel) |
| 501 |
if err != nil { |
| 502 |
sess.setState(Error) |
| 503 |
sess.Log.Errorf("unable to set level: %v", err) |
| 504 |
sess.proto.WriteMessage(protocol.AckMsg{"nak"}) |
| 505 |
return err |
| 506 |
} |
| 507 |
// the server assumes if we ack the broadcast, we've updated |
| 508 |
// our levels. Hence the order. |
| 509 |
err = sess.proto.WriteMessage(protocol.AckMsg{"ack"}) |
| 510 |
if err != nil { |
| 511 |
sess.setState(Error) |
| 512 |
sess.Log.Errorf("unable to ack broadcast: %s", err) |
| 513 |
return err |
| 514 |
} |
| 515 |
sess.clearShouldDelay() |
| 516 |
sess.Log.Debugf("broadcast chan:%v app:%v topLevel:%d payloads:%s", |
| 517 |
bcast.ChanId, bcast.AppId, bcast.TopLevel, bcast.Payloads) |
| 518 |
if bcast.ChanId == protocol.SystemChannelId { |
| 519 |
// the system channel id, the only one we care about for now |
| 520 |
sess.Log.Debugf("sending bcast over") |
| 521 |
sess.BroadcastCh <- sess.decodeBroadcast(bcast) |
| 522 |
sess.Log.Debugf("sent bcast over") |
| 523 |
} else { |
| 524 |
sess.Log.Errorf("what is this weird channel, %#v?", bcast.ChanId) |
| 525 |
} |
| 526 |
return nil |
| 527 |
} |
| 528 |
|
| 529 |
// handle "notifications" messages |
| 530 |
func (sess *clientSession) handleNotifications(ucast *serverMsg) error { |
| 531 |
notifs, err := sess.SeenState.FilterBySeen(ucast.Notifications) |
| 532 |
if err != nil { |
| 533 |
sess.setState(Error) |
| 534 |
sess.Log.Errorf("unable to record msgs seen: %v", err) |
| 535 |
sess.proto.WriteMessage(protocol.AckMsg{"nak"}) |
| 536 |
return err |
| 537 |
} |
| 538 |
// the server assumes if we ack the broadcast, we've updated |
| 539 |
// our state. Hence the order. |
| 540 |
err = sess.proto.WriteMessage(protocol.AckMsg{"ack"}) |
| 541 |
if err != nil { |
| 542 |
sess.setState(Error) |
| 543 |
sess.Log.Errorf("unable to ack notifications: %s", err) |
| 544 |
return err |
| 545 |
} |
| 546 |
sess.clearShouldDelay() |
| 547 |
sess.AddresseeChecker.StartAddresseeBatch() |
| 548 |
for i := range notifs { |
| 549 |
notif := ¬ifs[i] |
| 550 |
to := sess.AddresseeChecker.CheckForAddressee(notif) |
| 551 |
if to == nil { |
| 552 |
continue |
| 553 |
} |
| 554 |
sess.Log.Debugf("unicast app:%v msg:%s payload:%s", |
| 555 |
notif.AppId, notif.MsgId, notif.Payload) |
| 556 |
sess.Log.Debugf("sending ucast over") |
| 557 |
sess.NotificationsCh <- AddressedNotification{to, notif} |
| 558 |
sess.Log.Debugf("sent ucast over") |
| 559 |
} |
| 560 |
return nil |
| 561 |
} |
| 562 |
|
| 563 |
// handle "connbroken" messages |
| 564 |
func (sess *clientSession) handleConnBroken(connBroken *serverMsg) error { |
| 565 |
sess.setState(Error) |
| 566 |
reason := connBroken.Reason |
| 567 |
err := fmt.Errorf("server broke connection: %s", reason) |
| 568 |
sess.Log.Errorf("%s", err) |
| 569 |
switch reason { |
| 570 |
case protocol.BrokenHostMismatch: |
| 571 |
sess.resetHosts() |
| 572 |
} |
| 573 |
return err |
| 574 |
} |
| 575 |
|
| 576 |
// handle "setparams" messages |
| 577 |
func (sess *clientSession) handleSetParams(setParams *serverMsg) error { |
| 578 |
if setParams.SetCookie != "" { |
| 579 |
sess.setCookie(setParams.SetCookie) |
| 580 |
} |
| 581 |
return nil |
| 582 |
} |
| 583 |
|
| 584 |
// loop runs the session with the server, emits a stream of events. |
| 585 |
func (sess *clientSession) loop() error { |
| 586 |
var err error |
| 587 |
var recv serverMsg |
| 588 |
sess.setState(Running) |
| 589 |
for { |
| 590 |
deadAfter := sess.pingInterval + sess.ExchangeTimeout |
| 591 |
sess.proto.SetDeadline(time.Now().Add(deadAfter)) |
| 592 |
err = sess.proto.ReadMessage(&recv) |
| 593 |
if err != nil { |
| 594 |
sess.Log.Debugf("session aborting with error on read.") |
| 595 |
sess.setState(Error) |
| 596 |
return err |
| 597 |
} |
| 598 |
switch recv.Type { |
| 599 |
case "ping": |
| 600 |
err = sess.handlePing() |
| 601 |
case "broadcast": |
| 602 |
err = sess.handleBroadcast(&recv) |
| 603 |
case "notifications": |
| 604 |
err = sess.handleNotifications(&recv) |
| 605 |
case "connbroken": |
| 606 |
err = sess.handleConnBroken(&recv) |
| 607 |
case "setparams": |
| 608 |
err = sess.handleSetParams(&recv) |
| 609 |
case "warn": |
| 610 |
// XXX: current message "warn" should be "connwarn" |
| 611 |
fallthrough |
| 612 |
case "connwarn": |
| 613 |
sess.Log.Errorf("server sent warning: %s", recv.Reason) |
| 614 |
} |
| 615 |
if err != nil { |
| 616 |
sess.Log.Debugf("session aborting with error from handler.") |
| 617 |
return err |
| 618 |
} |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
// Call this when you've connected and want to start looping. |
| 623 |
func (sess *clientSession) start() error { |
| 624 |
conn := sess.getConnection() |
| 625 |
err := conn.SetDeadline(time.Now().Add(sess.ExchangeTimeout)) |
| 626 |
if err != nil { |
| 627 |
sess.setState(Error) |
| 628 |
sess.Log.Errorf("unable to start: set deadline: %s", err) |
| 629 |
return err |
| 630 |
} |
| 631 |
_, err = conn.Write(wireVersionBytes) |
| 632 |
// The Writer docs: Write must return a non-nil error if it returns |
| 633 |
// n < len(p). So, no need to check number of bytes written, hooray. |
| 634 |
if err != nil { |
| 635 |
sess.setState(Error) |
| 636 |
sess.Log.Errorf("unable to start: write version: %s", err) |
| 637 |
return err |
| 638 |
} |
| 639 |
proto := sess.Protocolator(conn) |
| 640 |
proto.SetDeadline(time.Now().Add(sess.ExchangeTimeout)) |
| 641 |
levels, err := sess.SeenState.GetAllLevels() |
| 642 |
if err != nil { |
| 643 |
sess.setState(Error) |
| 644 |
sess.Log.Errorf("unable to start: get levels: %v", err) |
| 645 |
return err |
| 646 |
} |
| 647 |
err = proto.WriteMessage(protocol.ConnectMsg{ |
| 648 |
Type: "connect", |
| 649 |
DeviceId: sess.DeviceId, |
| 650 |
Cookie: sess.getCookie(), |
| 651 |
Levels: levels, |
| 652 |
Info: sess.Info, |
| 653 |
}) |
| 654 |
if err != nil { |
| 655 |
sess.setState(Error) |
| 656 |
sess.Log.Errorf("unable to start: connect: %s", err) |
| 657 |
return err |
| 658 |
} |
| 659 |
var connAck protocol.ConnAckMsg |
| 660 |
err = proto.ReadMessage(&connAck) |
| 661 |
if err != nil { |
| 662 |
sess.setState(Error) |
| 663 |
sess.Log.Errorf("unable to start: connack: %s", err) |
| 664 |
return err |
| 665 |
} |
| 666 |
if connAck.Type != "connack" { |
| 667 |
sess.setState(Error) |
| 668 |
return fmt.Errorf("expecting CONNACK, got %#v", connAck.Type) |
| 669 |
} |
| 670 |
pingInterval, err := time.ParseDuration(connAck.Params.PingInterval) |
| 671 |
if err != nil { |
| 672 |
sess.setState(Error) |
| 673 |
sess.Log.Errorf("unable to start: parse ping interval: %s", err) |
| 674 |
return err |
| 675 |
} |
| 676 |
sess.proto = proto |
| 677 |
sess.pingInterval = pingInterval |
| 678 |
sess.Log.Debugf("connected %v.", conn.RemoteAddr()) |
| 679 |
sess.started() // deals with choosing which host to retry with as well |
| 680 |
return nil |
| 681 |
} |
| 682 |
|
| 683 |
// run calls connect, and if it works it calls start, and if it works |
| 684 |
// it runs loop in a goroutine, and ships its return value over ErrCh. |
| 685 |
func (sess *clientSession) run(closer func(bool), hostGetter, connecter, starter, looper func() error) error { |
| 686 |
closer(false) |
| 687 |
if err := hostGetter(); err != nil { |
| 688 |
return err |
| 689 |
} |
| 690 |
err := connecter() |
| 691 |
if err == nil { |
| 692 |
err = starter() |
| 693 |
if err == nil { |
| 694 |
go func() { sess.errCh <- looper() }() |
| 695 |
} |
| 696 |
} |
| 697 |
return err |
| 698 |
} |
| 699 |
|
| 700 |
// This Jitter returns a random time.Duration somewhere in [-spread, spread]. |
| 701 |
func (sess *clientSession) Jitter(spread time.Duration) time.Duration { |
| 702 |
if spread < 0 { |
| 703 |
panic("spread must be non-negative") |
| 704 |
} |
| 705 |
n := int64(spread) |
| 706 |
return time.Duration(rand.Int63n(2*n+1) - n) |
| 707 |
} |
| 708 |
|
| 709 |
// Dial takes the session from newly created (or newly disconnected) |
| 710 |
// to running the main loop. |
| 711 |
func (sess *clientSession) Dial() error { |
| 712 |
if sess.Protocolator == nil { |
| 713 |
// a missing protocolator means you've willfully overridden |
| 714 |
// it; returning an error here would prompt AutoRedial to just |
| 715 |
// keep on trying. |
| 716 |
panic("can't Dial() without a protocol constructor.") |
| 717 |
} |
| 718 |
return sess.run(sess.doClose, sess.getHosts, sess.connect, sess.start, sess.loop) |
| 719 |
} |
| 720 |
|
| 721 |
func (sess *clientSession) shutdown() { |
| 722 |
sess.Log.Infof("session shutting down.") |
| 723 |
sess.connLock.Lock() |
| 724 |
defer sess.connLock.Unlock() |
| 725 |
sess.stopRedial() |
| 726 |
sess.closeConnection() |
| 727 |
} |
| 728 |
|
| 729 |
func (sess *clientSession) doKeepConnection() { |
| 730 |
for { |
| 731 |
select { |
| 732 |
case cmd := <-sess.cmdCh: |
| 733 |
switch cmd { |
| 734 |
case cmdConnect: |
| 735 |
sess.connHandler(true) |
| 736 |
case cmdDisconnect: |
| 737 |
sess.connHandler(false) |
| 738 |
case cmdResetCookie: |
| 739 |
sess.resetCookie() |
| 740 |
} |
| 741 |
case <-sess.stopCh: |
| 742 |
sess.shutdown() |
| 743 |
return |
| 744 |
case n := <-sess.doneCh: |
| 745 |
// if n == 0, the redialer aborted. If you do |
| 746 |
// anything other than log it, keep that in mind. |
| 747 |
sess.Log.Debugf("connected after %d attempts.", n) |
| 748 |
case err := <-sess.errCh: |
| 749 |
sess.errHandler(err) |
| 750 |
} |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
func (sess *clientSession) handleConn(hasConn bool) { |
| 755 |
sess.lastConn = hasConn |
| 756 |
|
| 757 |
// Note this does not depend on the current state! That's because Dial |
| 758 |
// starts with doClose, which gets you to Disconnected even if you're |
| 759 |
// connected, and you can call Close when Disconnected without it |
| 760 |
// losing its stuff. |
| 761 |
if hasConn { |
| 762 |
sess.autoRedial() |
| 763 |
} else { |
| 764 |
sess.stopRedial() |
| 765 |
sess.doClose(false) |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
func (sess *clientSession) handleErr(err error) { |
| 770 |
sess.Log.Errorf("session error'ed out with %v", err) |
| 771 |
// State() == Error mostly defends interrupting an ongoing |
| 772 |
// autoRedial if we went quickly already through hasConn = |
| 773 |
// false => hasConn = true |
| 774 |
if sess.State() == Error && sess.lastConn { |
| 775 |
sess.autoRedial() |
| 776 |
} |
| 777 |
} |
| 778 |
|
| 779 |
func (sess *clientSession) KeepConnection() error { |
| 780 |
sess.stateLock.Lock() |
| 781 |
defer sess.stateLock.Unlock() |
| 782 |
if sess.state != Pristine { |
| 783 |
return errors.New("don't call KeepConnection() on a non-pristine session.") |
| 784 |
} |
| 785 |
sess.state = Disconnected |
| 786 |
|
| 787 |
go sess.doKeepConnection() |
| 788 |
|
| 789 |
return nil |
| 790 |
} |
| 791 |
|
| 792 |
func (sess *clientSession) StopKeepConnection() { |
| 793 |
sess.setState(Shutdown) |
| 794 |
close(sess.stopCh) |
| 795 |
} |
| 796 |
|
| 797 |
func (sess *clientSession) HasConnectivity(hasConn bool) { |
| 798 |
if hasConn { |
| 799 |
sess.cmdCh <- cmdConnect |
| 800 |
} else { |
| 801 |
sess.cmdCh <- cmdDisconnect |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
func init() { |
| 806 |
rand.Seed(time.Now().Unix()) // good enough for us (we're not using it for crypto) |
| 807 |
} |