Debian Codegraph @

client/service/service.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 service
18
19 import (
20 "bytes"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io/ioutil"
25 "net/http"
26 "net/url"
27 "os"
28
29 "github.com/godbus/dbus/v5"
30
31 "gitlab.com/ubports/development/core/lomiri-push-service/bus"
32 "gitlab.com/ubports/development/core/lomiri-push-service/click"
33 "gitlab.com/ubports/development/core/lomiri-push-service/logger"
34 "gitlab.com/ubports/development/core/lomiri-push-service/nih"
35 )
36
37 // PushServiceSetup encapsulates the params for setting up a PushService.
38 type PushServiceSetup struct {
39 RegURL *url.URL
40 DeviceId string
41 InstalledChecker click.InstalledChecker
42 }
43
44 // PushService is the dbus api
45 type PushService struct {
46 DBusService
47 regURL *url.URL
48 deviceId string
49 httpCli http.Client
50 }
51
52 var (
53 PushServiceBusAddress = bus.Address{
54 Interface: "com.lomiri.PushNotifications",
55 Path: "/com/lomiri/PushNotifications",
56 Name: "com.lomiri.PushNotifications",
57 }
58 )
59
60 // NewPushService() builds a new service and returns it.
61 func NewPushService(setup *PushServiceSetup, log logger.Logger) *PushService {
62 var svc = &PushService{}
63 svc.Log = log
64 svc.Bus = bus.SessionBus.Endpoint(PushServiceBusAddress, log)
65 svc.installedChecker = setup.InstalledChecker
66 svc.regURL = setup.RegURL
67 svc.deviceId = setup.DeviceId
68 return svc
69 }
70
71 // getParsedUrl() returns the POST URL at registration HTTP endpoint for op
72 func (svc *PushService) getParsedUrl(op string) (string) {
73 if svc.regURL == nil {
74 return ""
75 }
76 purl, err := svc.regURL.Parse(op)
77 if err != nil {
78 panic("op to getParsedUrl was invalid")
79 }
80 url := purl.String()
81 return url
82 }
83
84 func (svc *PushService) Start() error {
85 return svc.DBusService.Start(bus.DispatchMap{
86 "Register": svc.register,
87 "Unregister": svc.unregister,
88 }, PushServiceBusAddress, nil)
89 }
90
91 var (
92 ErrBadServer = errors.New("bad server")
93 ErrBadRequest = errors.New("bad request")
94 ErrBadToken = errors.New("bad token")
95 ErrBadAuth = errors.New("bad auth")
96 )
97
98 type registrationRequest struct {
99 DeviceId string `json:"deviceid"`
100 AppId string `json:"appid"`
101 }
102
103 type registrationReply struct {
104 Token string `json:"token"` // the bit we're after
105 Ok bool `json:"ok"` // only ever true or absent
106 Error string `json:"error"` // these two only used for debugging
107 Message string `json:"message"` //
108 }
109
110 func (svc *PushService) manageReg(op, appId string) (*registrationReply, error) {
111 req_body, err := json.Marshal(registrationRequest{svc.deviceId, appId})
112 if err != nil {
113 return nil, fmt.Errorf("unable to marshal register request body: %v", err)
114 }
115
116 url := svc.getParsedUrl(op)
117
118 req, err := http.NewRequest("POST", url, bytes.NewReader(req_body))
119 if err != nil {
120 panic(fmt.Errorf("unable to build register request: %v", err))
121 }
122 req.Header.Add("Content-Type", "application/json")
123
124 resp, err := svc.httpCli.Do(req)
125 if err != nil {
126 return nil, fmt.Errorf("unable to request registration: %v", err)
127 }
128 defer resp.Body.Close()
129 if resp.StatusCode != http.StatusOK {
130 svc.Log.Errorf("register endpoint replied %d", resp.StatusCode)
131 switch {
132 case resp.StatusCode >= http.StatusInternalServerError:
133 // XXX retry on 503
134 return nil, ErrBadServer
135 case resp.StatusCode == http.StatusUnauthorized:
136 return nil, ErrBadAuth
137 default:
138 return nil, ErrBadRequest
139 }
140 }
141 // errors below here Can't Happen (tm).
142 body, err := ioutil.ReadAll(resp.Body)
143 if err != nil {
144 svc.Log.Errorf("during ReadAll() of response body: %v", err)
145 return nil, err
146 }
147
148 var reply registrationReply
149 err = json.Unmarshal(body, &reply)
150 if err != nil {
151 svc.Log.Errorf("during Unmarshal of response body: %v", err)
152 return nil, fmt.Errorf("unable to unmarshal register response: %v", err)
153 }
154
155 return &reply, nil
156 }
157
158 func (svc *PushService) register(msg dbus.Message, id string) (string, *dbus.Error) {
159 app, err := svc.grabDBusPackageAndAppId(&msg, id)
160 if err != nil {
161 return "", MakeDBusNoObjectErrorWithReason(
162 msg.Headers[dbus.FieldPath].Value().(string), err)
163 }
164
165 rawAppId := string(nih.Quote([]byte(app.Original())))
166 rv := os.Getenv("PUSH_REG_" + rawAppId)
167 if rv != "" {
168 return rv, nil
169 }
170
171 reply, err := svc.manageReg("/register", app.Original())
172 if err != nil {
173 return "", dbus.MakeFailedError(err)
174 }
175
176 if !reply.Ok || reply.Token == "" {
177 svc.Log.Errorf("unexpected response: %#v", reply)
178 return "", dbus.MakeFailedError(ErrBadToken)
179 }
180
181 return reply.Token, nil
182 }
183
184 func (svc *PushService) unregister(msg dbus.Message, id string) *dbus.Error {
185 app, err := svc.grabDBusPackageAndAppId(&msg, id)
186 if err != nil {
187 return MakeDBusNoObjectErrorWithReason(
188 msg.Headers[dbus.FieldPath].Value().(string), err)
189 }
190
191 err = svc.Unregister(app.Original())
192 if err != nil {
193 dbus.MakeFailedError(err)
194 }
195 return nil
196 }
197
198 func (svc *PushService) Unregister(appId string) error {
199 _, err := svc.manageReg("/unregister", appId)
200 return err
201 }