bridgestate.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "fmt"
  22. "io"
  23. "net/http"
  24. "runtime/debug"
  25. "time"
  26. "maunium.net/go/mautrix/id"
  27. )
  28. type BridgeStateEvent string
  29. const (
  30. StateUnconfigured BridgeStateEvent = "UNCONFIGURED"
  31. StateRunning BridgeStateEvent = "RUNNING"
  32. StateConnecting BridgeStateEvent = "CONNECTING"
  33. StateBackfilling BridgeStateEvent = "BACKFILLING"
  34. StateConnected BridgeStateEvent = "CONNECTED"
  35. StateTransientDisconnect BridgeStateEvent = "TRANSIENT_DISCONNECT"
  36. StateBadCredentials BridgeStateEvent = "BAD_CREDENTIALS"
  37. StateUnknownError BridgeStateEvent = "UNKNOWN_ERROR"
  38. StateLoggedOut BridgeStateEvent = "LOGGED_OUT"
  39. )
  40. type BridgeErrorCode string
  41. const (
  42. WALoggedOut BridgeErrorCode = "wa-logged-out"
  43. WAMainDeviceGone BridgeErrorCode = "wa-main-device-gone"
  44. WAUnknownLogout BridgeErrorCode = "wa-unknown-logout"
  45. WANotConnected BridgeErrorCode = "wa-not-connected"
  46. WAConnecting BridgeErrorCode = "wa-connecting"
  47. WAKeepaliveTimeout BridgeErrorCode = "wa-keepalive-timeout"
  48. WAPhoneOffline BridgeErrorCode = "wa-phone-offline"
  49. WAConnectionFailed BridgeErrorCode = "wa-connection-failed"
  50. )
  51. var bridgeHumanErrors = map[BridgeErrorCode]string{
  52. WALoggedOut: "You were logged out from another device. Relogin to continue using the bridge.",
  53. WAMainDeviceGone: "Your phone was logged out from WhatsApp. Relogin to continue using the bridge.",
  54. WAUnknownLogout: "You were logged out for an unknown reason. Relogin to continue using the bridge.",
  55. WANotConnected: "You're not connected to WhatsApp",
  56. WAConnecting: "Reconnecting to WhatsApp...",
  57. WAKeepaliveTimeout: "The WhatsApp web servers are not responding. The bridge will try to reconnect.",
  58. WAPhoneOffline: "Your phone hasn't been seen in over 12 days. The bridge is currently connected, but will get disconnected if you don't open the app soon.",
  59. WAConnectionFailed: "Connecting to the WhatsApp web servers failed.",
  60. }
  61. type BridgeState struct {
  62. StateEvent BridgeStateEvent `json:"state_event"`
  63. Timestamp int64 `json:"timestamp"`
  64. TTL int `json:"ttl"`
  65. Source string `json:"source,omitempty"`
  66. Error BridgeErrorCode `json:"error,omitempty"`
  67. Message string `json:"message,omitempty"`
  68. UserID id.UserID `json:"user_id,omitempty"`
  69. RemoteID string `json:"remote_id,omitempty"`
  70. RemoteName string `json:"remote_name,omitempty"`
  71. Reason string `json:"reason,omitempty"`
  72. Info map[string]interface{} `json:"info,omitempty"`
  73. }
  74. type GlobalBridgeState struct {
  75. RemoteStates map[string]BridgeState `json:"remoteState"`
  76. BridgeState BridgeState `json:"bridgeState"`
  77. }
  78. func (pong BridgeState) fill(user *User) BridgeState {
  79. if user != nil {
  80. pong.UserID = user.MXID
  81. pong.RemoteID = fmt.Sprintf("%s_a%d_d%d", user.JID.User, user.JID.Agent, user.JID.Device)
  82. pong.RemoteName = fmt.Sprintf("+%s", user.JID.User)
  83. }
  84. pong.Timestamp = time.Now().Unix()
  85. pong.Source = "bridge"
  86. if len(pong.Error) > 0 {
  87. pong.TTL = 60
  88. pong.Message = bridgeHumanErrors[pong.Error]
  89. } else {
  90. pong.TTL = 240
  91. }
  92. return pong
  93. }
  94. func (pong *BridgeState) shouldDeduplicate(newPong *BridgeState) bool {
  95. if pong == nil || pong.StateEvent != newPong.StateEvent || pong.Error != newPong.Error {
  96. return false
  97. }
  98. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  99. }
  100. func (br *WABridge) sendBridgeState(ctx context.Context, state *BridgeState) error {
  101. var body bytes.Buffer
  102. if err := json.NewEncoder(&body).Encode(&state); err != nil {
  103. return fmt.Errorf("failed to encode bridge state JSON: %w", err)
  104. }
  105. req, err := http.NewRequestWithContext(ctx, http.MethodPost, br.Config.Homeserver.StatusEndpoint, &body)
  106. if err != nil {
  107. return fmt.Errorf("failed to prepare request: %w", err)
  108. }
  109. req.Header.Set("Authorization", "Bearer "+br.Config.AppService.ASToken)
  110. req.Header.Set("Content-Type", "application/json")
  111. resp, err := http.DefaultClient.Do(req)
  112. if err != nil {
  113. return fmt.Errorf("failed to send request: %w", err)
  114. }
  115. defer resp.Body.Close()
  116. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  117. respBody, _ := io.ReadAll(resp.Body)
  118. if respBody != nil {
  119. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  120. }
  121. return fmt.Errorf("unexpected status code %d sending bridge state update: %s", resp.StatusCode, respBody)
  122. }
  123. return nil
  124. }
  125. func (br *WABridge) sendGlobalBridgeState(state BridgeState) {
  126. if len(br.Config.Homeserver.StatusEndpoint) == 0 {
  127. return
  128. }
  129. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  130. defer cancel()
  131. if err := br.sendBridgeState(ctx, &state); err != nil {
  132. br.Log.Warnln("Failed to update global bridge state:", err)
  133. } else {
  134. br.Log.Debugfln("Sent new global bridge state %+v", state)
  135. }
  136. }
  137. func (user *User) bridgeStateLoop() {
  138. defer func() {
  139. err := recover()
  140. if err != nil {
  141. user.log.Errorfln("Bridge state loop panicked: %v\n%s", err, debug.Stack())
  142. }
  143. }()
  144. for state := range user.bridgeStateQueue {
  145. user.immediateSendBridgeState(state)
  146. }
  147. }
  148. func (user *User) immediateSendBridgeState(state BridgeState) {
  149. retryIn := 2
  150. for {
  151. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  152. user.log.Debugfln("Not sending bridge state %s as it's a duplicate", state.StateEvent)
  153. return
  154. }
  155. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  156. err := user.bridge.sendBridgeState(ctx, &state)
  157. cancel()
  158. if err != nil {
  159. user.log.Warnfln("Failed to update bridge state: %v, retrying in %d seconds", err, retryIn)
  160. time.Sleep(time.Duration(retryIn) * time.Second)
  161. retryIn *= 2
  162. if retryIn > 64 {
  163. retryIn = 64
  164. }
  165. } else {
  166. user.prevBridgeStatus = &state
  167. user.log.Debugfln("Sent new bridge state %+v", state)
  168. return
  169. }
  170. }
  171. }
  172. func (user *User) sendBridgeState(state BridgeState) {
  173. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  174. return
  175. }
  176. state = state.fill(user)
  177. if len(user.bridgeStateQueue) >= 8 {
  178. user.log.Warnln("Bridge state queue is nearly full, discarding an item")
  179. select {
  180. case <-user.bridgeStateQueue:
  181. default:
  182. }
  183. }
  184. select {
  185. case user.bridgeStateQueue <- state:
  186. default:
  187. user.log.Errorfln("Bridge state queue is full, dropped new state")
  188. }
  189. }
  190. func (user *User) GetPrevBridgeState() BridgeState {
  191. if user.prevBridgeStatus != nil {
  192. return *user.prevBridgeStatus
  193. }
  194. return BridgeState{}
  195. }
  196. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  197. if !prov.bridge.AS.CheckServerToken(w, r) {
  198. return
  199. }
  200. userID := r.URL.Query().Get("user_id")
  201. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  202. var global BridgeState
  203. global.StateEvent = StateRunning
  204. var remote BridgeState
  205. if user.IsConnected() {
  206. if user.Client.IsLoggedIn() {
  207. remote.StateEvent = StateConnected
  208. } else if user.Session != nil {
  209. remote.StateEvent = StateConnecting
  210. remote.Error = WAConnecting
  211. } // else: unconfigured
  212. } else if user.Session != nil {
  213. remote.StateEvent = StateBadCredentials
  214. remote.Error = WANotConnected
  215. } // else: unconfigured
  216. global = global.fill(nil)
  217. resp := GlobalBridgeState{
  218. BridgeState: global,
  219. RemoteStates: map[string]BridgeState{},
  220. }
  221. if len(remote.StateEvent) > 0 {
  222. remote = remote.fill(user)
  223. resp.RemoteStates[remote.RemoteID] = remote
  224. }
  225. user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
  226. jsonResponse(w, http.StatusOK, &resp)
  227. if len(resp.RemoteStates) > 0 {
  228. user.prevBridgeStatus = &remote
  229. }
  230. }