Debian Codegraph @

client/client.go

raw
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 client implements the Push Notifications client-side
18 // daemon.
19 package client
20
21 import (
22 "crypto/sha256"
23 "encoding/base64"
24 "encoding/hex"
25 "encoding/json"
26 "encoding/pem"
27 "errors"
28 "fmt"
29 "io/ioutil"
30 "net/url"
31 "os"
32 "strings"
33
34 "gitlab.com/ubports/development/core/lomiri-push-service/bus"
35 "gitlab.com/ubports/development/core/lomiri-push-service/bus/connectivity"
36 "gitlab.com/ubports/development/core/lomiri-push-service/bus/networkmanager"
37 "gitlab.com/ubports/development/core/lomiri-push-service/bus/systemimage"
38 "gitlab.com/ubports/development/core/lomiri-push-service/click"
39 "gitlab.com/ubports/development/core/lomiri-push-service/client/service"
40 "gitlab.com/ubports/development/core/lomiri-push-service/client/session"
41 "gitlab.com/ubports/development/core/lomiri-push-service/client/session/seenstate"
42 "gitlab.com/ubports/development/core/lomiri-push-service/config"
43 "gitlab.com/ubports/development/core/lomiri-push-service/identifier"
44 "gitlab.com/ubports/development/core/lomiri-push-service/launch_helper"
45 "gitlab.com/ubports/development/core/lomiri-push-service/logger"
46 "gitlab.com/ubports/development/core/lomiri-push-service/poller"
47 "gitlab.com/ubports/development/core/lomiri-push-service/protocol"
48 "gitlab.com/ubports/development/core/lomiri-push-service/util"
49 )
50
51 const (
52 SI_NO_SERVICE_ERROR = "org.freedesktop.DBus.Error.ServiceUnknown: The name com.ubports.SystemImage was not provided by any .service files"
53 )
54
55 // ClientConfig holds the client configuration
56 type ClientConfig struct {
57 connectivity.ConnectivityConfig // q.v.
58 // A reasonably large timeout for receive/answer pairs
59 ExchangeTimeout config.ConfigTimeDuration `json:"exchange_timeout"`
60 // A timeout to use when trying to connect to the server
61 ConnectTimeout config.ConfigTimeDuration `json:"connect_timeout"`
62 // The server to connect to or url to query for hosts to connect to
63 Addr string
64 // Host list management
65 HostsCachingExpiryTime config.ConfigTimeDuration `json:"hosts_cache_expiry"` // potentially refresh host list after
66 ExpectAllRepairedTime config.ConfigTimeDuration `json:"expect_all_repaired"` // worth retrying all servers after
67 // The PEM-encoded server certificate
68 CertPEMFile string `json:"cert_pem_file"`
69 SessionURL string `json:"session_url"`
70 RegistrationURL string `json:"registration_url"`
71 // The logging level (one of "debug", "info", "error")
72 LogLevel logger.ConfigLogLevel `json:"log_level"`
73 // fallback values for simplified notification usage
74 FallbackVibration *launch_helper.Vibration `json:"fallback_vibration"`
75 FallbackSound string `json:"fallback_sound"`
76 // times for the poller
77 PollInterval config.ConfigTimeDuration `json:"poll_interval"`
78 PollSettle config.ConfigTimeDuration `json:"poll_settle"`
79 PollNetworkWait config.ConfigTimeDuration `json:"poll_net_wait"`
80 PollPolldWait config.ConfigTimeDuration `json:"poll_polld_wait"`
81 PollDoneWait config.ConfigTimeDuration `json:"poll_done_wait"`
82 PollBusyWait config.ConfigTimeDuration `json:"poll_busy_wait"`
83 }
84
85 // PushService is the interface we use of service.PushService.
86 type PushService interface {
87 // Start starts the service.
88 Start() error
89 // Unregister unregisters the token for appId.
90 Unregister(appId string) error
91 }
92
93 type PostalService interface {
94 // Starts the service
95 Start() error
96 // Post converts a push message into a presentable notification
97 // and a postal message, presents the former and stores the
98 // latter in the application's mailbox.
99 Post(app *click.AppId, nid string, payload json.RawMessage)
100 // IsRunning() returns whether the service is running
101 IsRunning() bool
102 // Stop() stops the service
103 Stop()
104 }
105
106 // PushClient is the Push Notifications client-side daemon.
107 type PushClient struct {
108 leveldbPath string
109 configPath string
110 config ClientConfig
111 log logger.Logger
112 pem []byte
113 idder identifier.Id
114 deviceId string
115 connectivityEndp bus.Endpoint
116 systemImageEndp bus.Endpoint
117 systemImageInfo *systemimage.InfoResult
118 connCh chan bool
119 session session.ClientSession
120 sessionConnectedCh chan uint32
121 pushService PushService
122 postalService PostalService
123 unregisterCh chan *click.AppId
124 trackAddressees map[string]*click.AppId
125 installedChecker click.InstalledChecker
126 poller poller.Poller
127 // session-side channels
128 broadcastCh chan *session.BroadcastNotification
129 notificationsCh chan session.AddressedNotification
130 }
131
132 // Creates a new Push Notifications client-side daemon that will use
133 // the given configuration file.
134 func NewPushClient(configPath string, leveldbPath string) *PushClient {
135 return &PushClient{
136 configPath: configPath,
137 leveldbPath: leveldbPath,
138 broadcastCh: make(chan *session.BroadcastNotification),
139 notificationsCh: make(chan session.AddressedNotification),
140 }
141 }
142
143 var newIdentifier = identifier.New
144
145 // configure loads its configuration, and sets it up.
146 func (client *PushClient) configure() error {
147 _, err := os.Stat(client.configPath)
148 if err != nil {
149 return fmt.Errorf("config: %v", err)
150 }
151 err = config.ReadFiles(&client.config, client.configPath, "<flags>")
152 if err != nil {
153 return fmt.Errorf("config: %v", err)
154 }
155 // ignore spaces
156 client.config.Addr = strings.Replace(client.config.Addr, " ", "", -1)
157 if client.config.Addr == "" {
158 return errors.New("no hosts specified")
159 }
160
161 // later, we'll be specifying more logging options in the config file
162 client.log = logger.NewSimpleLogger(os.Stderr, client.config.LogLevel.Level())
163
164 clickUser, err := click.User()
165 if err != nil {
166 return fmt.Errorf("libclick: %v", err)
167 }
168 // overridden for testing
169 client.installedChecker = clickUser
170
171 client.unregisterCh = make(chan *click.AppId, 10)
172
173 // overridden for testing
174 client.idder, err = newIdentifier()
175 if err != nil {
176 return err
177 }
178 client.connectivityEndp = bus.SystemBus.Endpoint(networkmanager.BusAddress, client.log)
179 client.systemImageEndp = bus.SystemBus.Endpoint(systemimage.BusAddress, client.log)
180
181 client.connCh = make(chan bool, 1)
182 client.sessionConnectedCh = make(chan uint32, 1)
183
184 if client.config.CertPEMFile != "" {
185 client.pem, err = ioutil.ReadFile(client.config.CertPEMFile)
186 if err != nil {
187 return fmt.Errorf("reading PEM file: %v", err)
188 }
189 // sanity check
190 p, _ := pem.Decode(client.pem)
191 if p == nil {
192 return fmt.Errorf("no PEM found in PEM file")
193 }
194 }
195
196 return nil
197 }
198
199 // deriveSessionConfig dervies the session configuration from the client configuration bits.
200 func (client *PushClient) deriveSessionConfig(info map[string]interface{}) session.ClientSessionConfig {
201 return session.ClientSessionConfig{
202 ConnectTimeout: client.config.ConnectTimeout.TimeDuration(),
203 ExchangeTimeout: client.config.ExchangeTimeout.TimeDuration(),
204 HostsCachingExpiryTime: client.config.HostsCachingExpiryTime.TimeDuration(),
205 ExpectAllRepairedTime: client.config.ExpectAllRepairedTime.TimeDuration(),
206 PEM: client.pem,
207 Info: info,
208 AddresseeChecker: client,
209 BroadcastCh: client.broadcastCh,
210 NotificationsCh: client.notificationsCh,
211 }
212 }
213
214 // derivePushServiceSetup derives the service setup from the client configuration bits.
215 func (client *PushClient) derivePushServiceSetup() (*service.PushServiceSetup, error) {
216 setup := new(service.PushServiceSetup)
217 purl, err := url.Parse(client.config.RegistrationURL)
218 if err != nil {
219 return nil, fmt.Errorf("cannot parse registration url: %v", err)
220 }
221 setup.RegURL = purl
222 setup.DeviceId = client.deviceId
223 setup.InstalledChecker = client.installedChecker
224 return setup, nil
225 }
226
227 // derivePostalServiceSetup derives the service setup from the client configuration bits.
228 func (client *PushClient) derivePostalServiceSetup() *service.PostalServiceSetup {
229 return &service.PostalServiceSetup{
230 InstalledChecker: client.installedChecker,
231 FallbackVibration: client.config.FallbackVibration,
232 FallbackSound: client.config.FallbackSound,
233 }
234 }
235
236 // derivePollerSetup derives the Poller setup from the client configuration bits.
237 func (client *PushClient) derivePollerSetup() *poller.PollerSetup {
238 return &poller.PollerSetup{
239 Times: poller.Times{
240 AlarmInterval: client.config.PollInterval.TimeDuration(),
241 SessionStateSettle: client.config.PollSettle.TimeDuration(),
242 NetworkWait: client.config.PollNetworkWait.TimeDuration(),
243 PolldWait: client.config.PollPolldWait.TimeDuration(),
244 DoneWait: client.config.PollDoneWait.TimeDuration(),
245 BusyWait: client.config.PollBusyWait.TimeDuration(),
246 },
247 Log: client.log,
248 SessionStateGetter: client.session,
249 }
250 }
251
252 // getDeviceId gets the identifier for the device
253 func (client *PushClient) getDeviceId() error {
254 baseId := client.idder.String()
255 b, err := hex.DecodeString(baseId)
256 if err != nil {
257 return fmt.Errorf("machine-id should be hex: %v", err)
258 }
259 h := sha256.Sum224(b)
260 client.deviceId = base64.StdEncoding.EncodeToString(h[:])
261 return nil
262 }
263
264 // takeTheBus starts the connection(s) to D-Bus and sets up associated event channels
265 func (client *PushClient) takeTheBus() error {
266 cs := connectivity.New(client.connectivityEndp,
267 client.config.ConnectivityConfig, client.log)
268 go cs.Track(client.connCh)
269 util.NewAutoRedialer(client.systemImageEndp).Redial()
270 sysimg := systemimage.New(client.systemImageEndp, client.log)
271 info, err := sysimg.Information()
272
273 if err != nil {
274 /* SI is not running, so don't fail but rather provide unknown/empty details. See lp:1628522 */
275 if err.Error() == SI_NO_SERVICE_ERROR {
276 info = &systemimage.InfoResult{
277 BuildNumber: 0,
278 Device: "unknown",
279 Channel: "",
280 LastUpdate: "",
281 }
282 } else {
283 return err
284 }
285 }
286 client.systemImageInfo = info
287 return nil
288 }
289
290 // initSessionAndPoller creates the session and the poller objects
291 func (client *PushClient) initSessionAndPoller() error {
292 info := map[string]interface{}{
293 "device": client.systemImageInfo.Device,
294 "channel": client.systemImageInfo.Channel,
295 "build_number": client.systemImageInfo.BuildNumber,
296 }
297 sess, err := session.NewSession(client.config.Addr,
298 client.deriveSessionConfig(info), client.deviceId,
299 client.seenStateFactory, client.log)
300 if err != nil {
301 return err
302 }
303 client.session = sess
304 sess.KeepConnection()
305 client.poller = poller.New(client.derivePollerSetup())
306 return nil
307 }
308
309 // runPoller starts and runs the poller
310 func (client *PushClient) runPoller() error {
311 if err := client.poller.Start(); err != nil {
312 return err
313 }
314 if err := client.poller.Run(); err != nil {
315 return err
316 }
317 return nil
318 }
319
320 // seenStateFactory returns a SeenState for the session
321 func (client *PushClient) seenStateFactory() (seenstate.SeenState, error) {
322 if client.leveldbPath == "" {
323 return seenstate.NewSeenState()
324 } else {
325 return seenstate.NewSqliteSeenState(client.leveldbPath)
326 }
327 }
328
329 // StartAddresseeBatch starts a batch of checks for addressees.
330 func (client *PushClient) StartAddresseeBatch() {
331 client.trackAddressees = make(map[string]*click.AppId, 10)
332 }
333
334 // CheckForAddressee check for the addressee presence.
335 func (client *PushClient) CheckForAddressee(notif *protocol.Notification) *click.AppId {
336 appId := notif.AppId
337 parsed, ok := client.trackAddressees[appId]
338 if ok {
339 return parsed
340 }
341 parsed, err := click.ParseAndVerifyAppId(appId, client.installedChecker)
342 switch err {
343 default:
344 client.log.Debugf("notification %#v for invalid app id %#v.", notif.MsgId, notif.AppId)
345 case click.ErrMissingApp:
346 client.log.Debugf("notification %#v for missing app id %#v.", notif.MsgId, notif.AppId)
347 client.unregisterCh <- parsed
348 parsed = nil
349 case nil:
350 }
351 client.trackAddressees[appId] = parsed
352 return parsed
353 }
354
355 // handleUnregister deals with tokens of uninstalled apps
356 func (client *PushClient) handleUnregister(app *click.AppId) {
357 if !client.installedChecker.Installed(app, false) {
358 // xxx small chance of race here, in case the app gets
359 // reinstalled and registers itself before we finish
360 // the unregister; we need click and app launching
361 // collaboration to do better. we redo the hasPackage
362 // check here just before to keep the race window as
363 // small as possible
364 err := client.pushService.Unregister(app.Original()) // XXX WIP
365 if err != nil {
366 client.log.Errorf("unregistering %s: %s", app, err)
367 } else {
368 client.log.Debugf("unregistered token for %s", app)
369 }
370 }
371 }
372
373 // filterBroadcastNotification finds out if the notification is about an actual
374 // upgrade for the device. It expects msg.Decoded entries to look
375 // like:
376 //
377 // {
378 // "IMAGE-CHANNEL/DEVICE-MODEL": [BUILD-NUMBER, CHANNEL-ALIAS]
379 // ...
380 // }
381 func (client *PushClient) filterBroadcastNotification(msg *session.BroadcastNotification) bool {
382 n := len(msg.Decoded)
383 if n == 0 {
384 return false
385 }
386 // they are all for us, consider last
387 last := msg.Decoded[n-1]
388 tag := fmt.Sprintf("%s/%s", client.systemImageInfo.Channel, client.systemImageInfo.Device)
389 entry, ok := last[tag]
390 if !ok {
391 return false
392 }
393 pair, ok := entry.([]interface{})
394 if !ok {
395 return false
396 }
397 if len(pair) < 1 {
398 return false
399 }
400 _, ok = pair[0].(float64)
401 // ok means it sanity checks, let the helper check for build number etc
402 return ok
403 }
404
405 // handleBroadcastNotification deals with receiving a broadcast notification
406 func (client *PushClient) handleBroadcastNotification(msg *session.BroadcastNotification) error {
407 if !client.filterBroadcastNotification(msg) {
408 client.log.Debugf("not posting broadcast notification %d; filtered.", msg.TopLevel)
409 return nil
410 }
411 // marshal the last decoded msg to json
412 payload, err := json.Marshal(msg.Decoded[len(msg.Decoded)-1])
413 if err != nil {
414 client.log.Errorf("while posting broadcast notification %d: %v", msg.TopLevel, err)
415 return err
416 }
417 appId, _ := click.ParseAppId("_lomiri-system-settings")
418 client.postalService.Post(appId, "", payload)
419 client.log.Debugf("posted broadcast notification %d.", msg.TopLevel)
420 return nil
421 }
422
423 // handleUnicastNotification deals with receiving a unicast notification
424 func (client *PushClient) handleUnicastNotification(anotif session.AddressedNotification) error {
425 app := anotif.To
426 msg := anotif.Notification
427 client.postalService.Post(app, msg.MsgId, msg.Payload)
428 client.log.Debugf("posted unicast notification %s for %s.", msg.MsgId, msg.AppId)
429 return nil
430 }
431
432 func (client *PushClient) handeConnNotification(conn bool) {
433 client.session.HasConnectivity(conn)
434 client.poller.HasConnectivity(conn)
435 }
436
437 // doLoop connects events with their handlers
438 func (client *PushClient) doLoop(connhandler func(bool), bcasthandler func(*session.BroadcastNotification) error, ucasthandler func(session.AddressedNotification) error, unregisterhandler func(*click.AppId)) {
439 for {
440 select {
441 case state := <-client.connCh:
442 connhandler(state)
443 case bcast := <-client.broadcastCh:
444 bcasthandler(bcast)
445 case aucast := <-client.notificationsCh:
446 ucasthandler(aucast)
447 case count := <-client.sessionConnectedCh:
448 client.log.Debugf("session connected after %d attempts", count)
449 case app := <-client.unregisterCh:
450 unregisterhandler(app)
451 }
452 }
453 }
454
455 // doStart calls each of its arguments in order, returning the first non-nil
456 // error (or nil at the end)
457 func (client *PushClient) doStart(fs ...func() error) error {
458 for _, f := range fs {
459 if err := f(); err != nil {
460 return err
461 }
462 }
463 return nil
464 }
465
466 // Loop calls doLoop with the "real" handlers
467 func (client *PushClient) Loop() {
468 client.doLoop(client.handeConnNotification,
469 client.handleBroadcastNotification,
470 client.handleUnicastNotification,
471 client.handleUnregister,
472 )
473 }
474
475 func (client *PushClient) setupPushService() error {
476 setup, err := client.derivePushServiceSetup()
477 if err != nil {
478 return err
479 }
480
481 client.pushService = service.NewPushService(setup, client.log)
482 return nil
483 }
484
485 func (client *PushClient) startPushService() error {
486 if err := client.pushService.Start(); err != nil {
487 return err
488 }
489 return nil
490 }
491
492 func (client *PushClient) setupPostalService() error {
493 setup := client.derivePostalServiceSetup()
494 client.postalService = service.NewPostalService(setup, client.log)
495 return nil
496 }
497
498 func (client *PushClient) startPostalService() error {
499 if err := client.postalService.Start(); err != nil {
500 return err
501 }
502 return nil
503 }
504
505 // Start calls doStart with the "real" starters
506 func (client *PushClient) Start() error {
507 return client.doStart(
508 client.configure,
509 client.getDeviceId,
510 client.setupPushService,
511 client.setupPostalService,
512 client.startPushService,
513 client.startPostalService,
514 client.takeTheBus,
515 client.initSessionAndPoller,
516 client.runPoller,
517 )
518 }