bridgestate.go 9.1 KB

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