bridgestate.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. "errors"
  22. "fmt"
  23. "io/ioutil"
  24. "net/http"
  25. "strings"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Rhymen/go-whatsapp"
  29. log "maunium.net/go/maulogger/v2"
  30. "maunium.net/go/mautrix/id"
  31. )
  32. type BridgeStateEvent string
  33. const (
  34. StateStarting BridgeStateEvent = "STARTING"
  35. StateUnconfigured BridgeStateEvent = "UNCONFIGURED"
  36. StateRunning BridgeStateEvent = "RUNNING"
  37. StateConnecting BridgeStateEvent = "CONNECTING"
  38. StateBackfilling BridgeStateEvent = "BACKFILLING"
  39. StateConnected BridgeStateEvent = "CONNECTED"
  40. StateTransientDisconnect BridgeStateEvent = "TRANSIENT_DISCONNECT"
  41. StateBadCredentials BridgeStateEvent = "BAD_CREDENTIALS"
  42. StateUnknownError BridgeStateEvent = "UNKNOWN_ERROR"
  43. StateLoggedOut BridgeStateEvent = "LOGGED_OUT"
  44. )
  45. type BridgeErrorCode string
  46. const (
  47. WANotLoggedIn BridgeErrorCode = "wa-logged-out"
  48. WANotConnected BridgeErrorCode = "wa-not-connected"
  49. WAConnecting BridgeErrorCode = "wa-connecting"
  50. WATimeout BridgeErrorCode = "wa-timeout"
  51. WAServerTimeout BridgeErrorCode = "wa-server-timeout"
  52. WAPingFalse BridgeErrorCode = "wa-ping-false"
  53. WAPingError BridgeErrorCode = "wa-ping-error"
  54. )
  55. var bridgeHumanErrors = map[BridgeErrorCode]string{
  56. WANotLoggedIn: "You're not logged into WhatsApp",
  57. WANotConnected: "You're not connected to WhatsApp",
  58. WAConnecting: "Trying to reconnect to WhatsApp. Please make sure WhatsApp is running on your phone and connected to the internet.",
  59. WATimeout: "WhatsApp on your phone is not responding. Please make sure it is running and connected to the internet.",
  60. WAServerTimeout: "The WhatsApp web servers are not responding. The bridge will try to reconnect.",
  61. WAPingFalse: "WhatsApp returned an error, reconnecting. Please make sure WhatsApp is running on your phone and connected to the internet.",
  62. WAPingError: "WhatsApp returned an unknown error",
  63. }
  64. type BridgeState struct {
  65. StateEvent BridgeStateEvent `json:"state_event"`
  66. Timestamp int64 `json:"timestamp"`
  67. TTL int `json:"ttl"`
  68. Source string `json:"source,omitempty"`
  69. Error BridgeErrorCode `json:"error,omitempty"`
  70. Message string `json:"message,omitempty"`
  71. UserID id.UserID `json:"user_id,omitempty"`
  72. RemoteID string `json:"remote_id,omitempty"`
  73. RemoteName string `json:"remote_name,omitempty"`
  74. }
  75. type GlobalBridgeState struct {
  76. RemoteStates map[string]BridgeState `json:"remoteState"`
  77. BridgeState BridgeState `json:"bridgeState"`
  78. }
  79. func (pong BridgeState) fill(user *User) BridgeState {
  80. if user != nil {
  81. pong.UserID = user.MXID
  82. pong.RemoteID = strings.TrimSuffix(user.JID, whatsapp.NewUserSuffix)
  83. pong.RemoteName = fmt.Sprintf("+%s", pong.RemoteID)
  84. }
  85. pong.Timestamp = time.Now().Unix()
  86. pong.Source = "bridge"
  87. if len(pong.Error) > 0 {
  88. pong.TTL = 60
  89. pong.Message = bridgeHumanErrors[pong.Error]
  90. } else {
  91. pong.TTL = 240
  92. }
  93. return pong
  94. }
  95. func (pong *BridgeState) shouldDeduplicate(newPong *BridgeState) bool {
  96. if pong == nil || pong.StateEvent != newPong.StateEvent || pong.Error != newPong.Error {
  97. return false
  98. }
  99. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  100. }
  101. func (user *User) setupAdminTestHooks() {
  102. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  103. return
  104. }
  105. user.Conn.AdminTestHook = func(err error) {
  106. if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  107. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WATimeout})
  108. } else if errors.Is(err, whatsapp.ErrWebsocketKeepaliveFailed) {
  109. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WAServerTimeout})
  110. } else if errors.Is(err, whatsapp.ErrPingFalse) {
  111. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WAPingFalse})
  112. } else if err == nil {
  113. user.sendBridgeState(BridgeState{StateEvent: StateConnected})
  114. } else {
  115. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WAPingError})
  116. }
  117. }
  118. user.Conn.CountTimeoutHook = func(wsKeepaliveErrorCount int) {
  119. if wsKeepaliveErrorCount > 0 {
  120. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WAServerTimeout})
  121. } else {
  122. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WATimeout})
  123. }
  124. }
  125. }
  126. func (bridge *Bridge) createBridgeStateRequest(ctx context.Context, state *BridgeState) (req *http.Request, err error) {
  127. var body bytes.Buffer
  128. if err = json.NewEncoder(&body).Encode(&state); err != nil {
  129. return nil, fmt.Errorf("failed to encode bridge state JSON: %w", err)
  130. }
  131. req, err = http.NewRequestWithContext(ctx, http.MethodPost, bridge.Config.Homeserver.StatusEndpoint, &body)
  132. if err != nil {
  133. return
  134. }
  135. req.Header.Set("Authorization", "Bearer "+bridge.Config.AppService.ASToken)
  136. req.Header.Set("Content-Type", "application/json")
  137. return
  138. }
  139. func sendPreparedBridgeStateRequest(logger log.Logger, req *http.Request) bool {
  140. resp, err := http.DefaultClient.Do(req)
  141. if err != nil {
  142. logger.Warnln("Failed to send bridge state update:", err)
  143. return false
  144. }
  145. defer resp.Body.Close()
  146. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  147. respBody, _ := ioutil.ReadAll(resp.Body)
  148. if respBody != nil {
  149. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  150. }
  151. logger.Warnfln("Unexpected status code %d sending bridge state update: %s", resp.StatusCode, respBody)
  152. return false
  153. }
  154. return true
  155. }
  156. func (bridge *Bridge) sendGlobalBridgeState(state BridgeState) {
  157. if len(bridge.Config.Homeserver.StatusEndpoint) == 0 {
  158. return
  159. }
  160. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  161. defer cancel()
  162. if req, err := bridge.createBridgeStateRequest(ctx, &state); err != nil {
  163. bridge.Log.Warnln("Failed to prepare global bridge state update request:", err)
  164. } else if ok := sendPreparedBridgeStateRequest(bridge.Log, req); ok {
  165. bridge.Log.Debugfln("Sent new global bridge state %+v", state)
  166. }
  167. }
  168. func (user *User) sendBridgeState(state BridgeState) {
  169. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  170. return
  171. }
  172. state = state.fill(user)
  173. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  174. return
  175. }
  176. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  177. defer cancel()
  178. if req, err := user.bridge.createBridgeStateRequest(ctx, &state); err != nil {
  179. user.log.Warnln("Failed to prepare bridge state update request:", err)
  180. } else if ok := sendPreparedBridgeStateRequest(user.log, req); ok {
  181. user.prevBridgeStatus = &state
  182. user.log.Debugfln("Sent new bridge state %+v", state)
  183. }
  184. }
  185. var bridgeStatePingID uint32 = 0
  186. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  187. if !prov.bridge.AS.CheckServerToken(w, r) {
  188. return
  189. }
  190. userID := r.URL.Query().Get("user_id")
  191. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  192. var global BridgeState
  193. global.StateEvent = StateRunning
  194. var remote BridgeState
  195. if user.Conn != nil {
  196. if user.Conn.IsConnected() && user.Conn.IsLoggedIn() {
  197. pingID := atomic.AddUint32(&bridgeStatePingID, 1)
  198. user.log.Debugfln("Pinging WhatsApp mobile due to bridge status /ping API request (ID %d)", pingID)
  199. err := user.Conn.AdminTestWithSuppress(true)
  200. if errors.Is(r.Context().Err(), context.Canceled) {
  201. user.log.Warnfln("Ping request %d was canceled before we responded (response was %v)", pingID, err)
  202. user.prevBridgeStatus = nil
  203. return
  204. }
  205. user.log.Debugfln("Ping %d response: %v", pingID, err)
  206. remote.StateEvent = StateTransientDisconnect
  207. if err == whatsapp.ErrPingFalse {
  208. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  209. go user.HandleError(err)
  210. remote.Error = WAPingFalse
  211. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  212. remote.Error = WATimeout
  213. } else if errors.Is(err, whatsapp.ErrWebsocketKeepaliveFailed) {
  214. remote.Error = WAServerTimeout
  215. } else if err != nil {
  216. remote.Error = WAPingError
  217. } else {
  218. remote.StateEvent = StateConnected
  219. }
  220. } else if user.Conn.IsLoginInProgress() && user.Session != nil {
  221. remote.StateEvent = StateConnecting
  222. remote.Error = WAConnecting
  223. } else if !user.Conn.IsConnected() && user.Session != nil {
  224. remote.StateEvent = StateBadCredentials
  225. remote.Error = WANotConnected
  226. } // else: unconfigured
  227. } else if user.Session != nil {
  228. remote.StateEvent = StateBadCredentials
  229. remote.Error = WANotConnected
  230. } // else: unconfigured
  231. global = global.fill(nil)
  232. resp := GlobalBridgeState{
  233. BridgeState: global,
  234. RemoteStates: map[string]BridgeState{},
  235. }
  236. if len(remote.StateEvent) > 0 {
  237. remote = remote.fill(user)
  238. resp.RemoteStates[remote.RemoteID] = remote
  239. }
  240. user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
  241. jsonResponse(w, http.StatusOK, &resp)
  242. if len(resp.RemoteStates) > 0 {
  243. user.prevBridgeStatus = &remote
  244. }
  245. }