bridgestate.go 7.3 KB

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