Debian Codegraph @

server/acceptance/acceptanceclient.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 acceptance contains the acceptance client.
18 package acceptance
19
20 import (
21 _ "crypto/sha512" // support sha384/512 certs
22 "crypto/tls"
23 "encoding/json"
24 "fmt"
25 "net"
26 "strings"
27 "sync"
28 "time"
29
30 "gitlab.com/ubports/development/core/lomiri-push-service/protocol"
31 )
32
33 var wireVersionBytes = []byte{protocol.ProtocolWireVersion}
34
35 // ClienSession holds a client<->server session and its configuration.
36 type ClientSession struct {
37 // configuration
38 DeviceId string
39 Model string
40 ImageChannel string
41 BuildNumber int32
42 ServerAddr string
43 ExchangeTimeout time.Duration
44 ReportPings bool
45 Levels map[string]int64
46 TLSConfig *tls.Config
47 Prefix string // prefix for events
48 Auth string
49 cookie string
50 cookieLock sync.RWMutex
51 ReportSetParams bool
52 DontClose bool
53 SlowStart time.Duration
54 // connection
55 Connection net.Conn
56 }
57
58 // GetCookie gets the current cookie.
59 func (sess *ClientSession) GetCookie() string {
60 sess.cookieLock.RLock()
61 defer sess.cookieLock.RUnlock()
62 return sess.cookie
63 }
64
65 // SetCookie sets the current cookie.
66 func (sess *ClientSession) SetCookie(cookie string) {
67 sess.cookieLock.Lock()
68 defer sess.cookieLock.Unlock()
69 sess.cookie = cookie
70 }
71
72 // Dial connects to a server using the configuration in the
73 // ClientSession and sets up the connection.
74 func (sess *ClientSession) Dial() error {
75 conn, err := net.DialTimeout("tcp", sess.ServerAddr, sess.ExchangeTimeout)
76 if err != nil {
77 return err
78 }
79 sess.TLSWrapAndSet(conn)
80 return nil
81 }
82
83 // TLSWrapAndSet wraps a socket connection in tls and sets it as
84 // session.Connection. For use instead of Dial().
85 func (sess *ClientSession) TLSWrapAndSet(conn net.Conn) {
86 var tlsConfig *tls.Config
87 if sess.TLSConfig != nil {
88 tlsConfig = sess.TLSConfig
89 } else {
90 tlsConfig = &tls.Config{}
91 }
92 sess.Connection = tls.Client(conn, tlsConfig)
93 }
94
95 type serverMsg struct {
96 Type string `json:"T"`
97 protocol.BroadcastMsg
98 protocol.NotificationsMsg
99 protocol.ConnWarnMsg
100 protocol.SetParamsMsg
101 }
102
103 // Run the session with the server, emits a stream of events.
104 func (sess *ClientSession) Run(events chan<- string) error {
105 conn := sess.Connection
106 if !sess.DontClose {
107 defer conn.Close()
108 }
109 time.Sleep(sess.SlowStart)
110 conn.SetDeadline(time.Now().Add(sess.ExchangeTimeout))
111 _, err := conn.Write(wireVersionBytes)
112 if err != nil {
113 return err
114 }
115 proto := protocol.NewProtocol0(conn)
116 info := map[string]interface{}{
117 "device": sess.Model,
118 "channel": sess.ImageChannel,
119 }
120 if sess.BuildNumber != -1 {
121 info["build_number"] = sess.BuildNumber
122 }
123 err = proto.WriteMessage(protocol.ConnectMsg{
124 Type: "connect",
125 DeviceId: sess.DeviceId,
126 Levels: sess.Levels,
127 Info: info,
128 Authorization: sess.Auth,
129 Cookie: sess.GetCookie(),
130 })
131 if err != nil {
132 return err
133 }
134 var connAck protocol.ConnAckMsg
135 err = proto.ReadMessage(&connAck)
136 if err != nil {
137 return err
138 }
139 pingInterval, err := time.ParseDuration(connAck.Params.PingInterval)
140 if err != nil {
141 return err
142 }
143 events <- fmt.Sprintf("%sconnected %v", sess.Prefix, conn.LocalAddr())
144 var recv serverMsg
145 for {
146 deadAfter := pingInterval + sess.ExchangeTimeout
147 conn.SetDeadline(time.Now().Add(deadAfter))
148 err = proto.ReadMessage(&recv)
149 if err != nil {
150 return err
151 }
152 switch recv.Type {
153 case "ping":
154 conn.SetDeadline(time.Now().Add(sess.ExchangeTimeout))
155 err := proto.WriteMessage(protocol.PingPongMsg{Type: "pong"})
156 if err != nil {
157 return err
158 }
159 if sess.ReportPings {
160 events <- sess.Prefix + "ping"
161 }
162 case "notifications":
163 conn.SetDeadline(time.Now().Add(sess.ExchangeTimeout))
164 err := proto.WriteMessage(protocol.AckMsg{Type: "ack"})
165 if err != nil {
166 return err
167 }
168 parts := make([]string, len(recv.Notifications))
169 for i, notif := range recv.Notifications {
170 pack, err := json.Marshal(&notif.Payload)
171 if err != nil {
172 return err
173 }
174 parts[i] = fmt.Sprintf("app:%v payload:%s;", notif.AppId, pack)
175 }
176 events <- fmt.Sprintf("%sunicast %s", sess.Prefix, strings.Join(parts, " "))
177 case "broadcast":
178 conn.SetDeadline(time.Now().Add(sess.ExchangeTimeout))
179 err := proto.WriteMessage(protocol.AckMsg{Type: "ack"})
180 if err != nil {
181 return err
182 }
183 pack, err := json.Marshal(recv.Payloads)
184 if err != nil {
185 return err
186 }
187 events <- fmt.Sprintf("%sbroadcast chan:%v app:%v topLevel:%d payloads:%s", sess.Prefix, recv.ChanId, recv.AppId, recv.TopLevel, pack)
188 case "warn", "connwarn":
189 events <- fmt.Sprintf("%sconnwarn %s", sess.Prefix, recv.Reason)
190 case "connbroken":
191 events <- fmt.Sprintf("%sconnbroken %s", sess.Prefix, recv.Reason)
192 case "setparams":
193 sess.SetCookie(recv.SetCookie)
194 if sess.ReportSetParams {
195 events <- sess.Prefix + "setparams"
196 }
197 }
198 }
199 return nil
200 }