provisioning.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "bufio"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "net"
  24. "net/http"
  25. "strings"
  26. "time"
  27. "github.com/gorilla/websocket"
  28. "github.com/Rhymen/go-whatsapp"
  29. log "maunium.net/go/maulogger/v2"
  30. "maunium.net/go/mautrix/id"
  31. )
  32. type ProvisioningAPI struct {
  33. bridge *Bridge
  34. log log.Logger
  35. }
  36. func (prov *ProvisioningAPI) Init() {
  37. prov.log = prov.bridge.Log.Sub("Provisioning")
  38. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  39. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  40. r.Use(prov.AuthMiddleware)
  41. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  42. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  43. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  44. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  45. r.HandleFunc("/delete_connection", prov.DeleteConnection).Methods(http.MethodPost)
  46. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  47. r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
  48. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.AsmuxPing).Methods(http.MethodPost)
  49. }
  50. type responseWrap struct {
  51. http.ResponseWriter
  52. statusCode int
  53. }
  54. var _ http.Hijacker = (*responseWrap)(nil)
  55. func (rw *responseWrap) WriteHeader(statusCode int) {
  56. rw.ResponseWriter.WriteHeader(statusCode)
  57. rw.statusCode = statusCode
  58. }
  59. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  60. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  61. if !ok {
  62. return nil, nil, errors.New("response does not implement http.Hijacker")
  63. }
  64. return hijacker.Hijack()
  65. }
  66. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  67. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  68. auth := r.Header.Get("Authorization")
  69. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  70. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  71. for _, part := range authParts {
  72. part = strings.TrimSpace(part)
  73. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  74. auth = part[len("net.maunium.whatsapp.auth-"):]
  75. break
  76. }
  77. }
  78. } else if strings.HasPrefix(auth, "Bearer ") {
  79. auth = auth[len("Bearer "):]
  80. }
  81. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  82. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  83. "error": "Invalid auth token",
  84. "errcode": "M_FORBIDDEN",
  85. })
  86. return
  87. }
  88. userID := r.URL.Query().Get("user_id")
  89. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  90. start := time.Now()
  91. wWrap := &responseWrap{w, 200}
  92. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  93. duration := time.Now().Sub(start).Seconds()
  94. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  95. })
  96. }
  97. type Error struct {
  98. Success bool `json:"success"`
  99. Error string `json:"error"`
  100. ErrCode string `json:"errcode"`
  101. }
  102. type Response struct {
  103. Success bool `json:"success"`
  104. Status string `json:"status"`
  105. }
  106. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  107. user := r.Context().Value("user").(*User)
  108. if user.Session == nil && user.Conn == nil {
  109. jsonResponse(w, http.StatusNotFound, Error{
  110. Error: "Nothing to purge: no session information stored and no active connection.",
  111. ErrCode: "no session",
  112. })
  113. return
  114. }
  115. user.DeleteConnection()
  116. user.SetSession(nil)
  117. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  118. }
  119. func (prov *ProvisioningAPI) DeleteConnection(w http.ResponseWriter, r *http.Request) {
  120. user := r.Context().Value("user").(*User)
  121. if user.Conn == nil {
  122. jsonResponse(w, http.StatusNotFound, Error{
  123. Error: "You don't have a WhatsApp connection.",
  124. ErrCode: "not connected",
  125. })
  126. return
  127. }
  128. user.DeleteConnection()
  129. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp and connection deleted"})
  130. }
  131. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  132. user := r.Context().Value("user").(*User)
  133. if user.Conn == nil {
  134. jsonResponse(w, http.StatusNotFound, Error{
  135. Error: "You don't have a WhatsApp connection.",
  136. ErrCode: "no connection",
  137. })
  138. return
  139. }
  140. err := user.Conn.Disconnect()
  141. if err == whatsapp.ErrNotConnected {
  142. jsonResponse(w, http.StatusNotFound, Error{
  143. Error: "You were not connected",
  144. ErrCode: "not connected",
  145. })
  146. return
  147. } else if err != nil {
  148. user.log.Warnln("Error while disconnecting:", err)
  149. jsonResponse(w, http.StatusInternalServerError, Error{
  150. Error: fmt.Sprintf("Unknown error while disconnecting: %v", err),
  151. ErrCode: err.Error(),
  152. })
  153. return
  154. }
  155. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  156. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  157. }
  158. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  159. user := r.Context().Value("user").(*User)
  160. if user.Conn == nil {
  161. if user.Session == nil {
  162. jsonResponse(w, http.StatusForbidden, Error{
  163. Error: "No existing connection and no session. Please log in first.",
  164. ErrCode: "no session",
  165. })
  166. } else {
  167. user.Connect(false)
  168. jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
  169. }
  170. return
  171. }
  172. user.log.Debugln("Received /reconnect request, disconnecting")
  173. wasConnected := true
  174. err := user.Conn.Disconnect()
  175. if err == whatsapp.ErrNotConnected {
  176. wasConnected = false
  177. } else if err != nil {
  178. user.log.Warnln("Error while disconnecting:", err)
  179. }
  180. user.log.Debugln("Restoring session for /reconnect")
  181. err = user.Conn.Restore(true, r.Context())
  182. user.log.Debugfln("Restore session for /reconnect responded with %v", err)
  183. if err == whatsapp.ErrInvalidSession {
  184. if user.Session != nil {
  185. user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  186. user.Conn.SetSession(*user.Session)
  187. err = user.Conn.Restore(true, r.Context())
  188. } else {
  189. jsonResponse(w, http.StatusForbidden, Error{
  190. Error: "You're not logged in",
  191. ErrCode: "not logged in",
  192. })
  193. return
  194. }
  195. }
  196. if err == whatsapp.ErrLoginInProgress {
  197. jsonResponse(w, http.StatusConflict, Error{
  198. Error: "A login or reconnection is already in progress.",
  199. ErrCode: "login in progress",
  200. })
  201. return
  202. } else if err == whatsapp.ErrAlreadyLoggedIn {
  203. jsonResponse(w, http.StatusConflict, Error{
  204. Error: "You were already connected.",
  205. ErrCode: err.Error(),
  206. })
  207. return
  208. }
  209. if err != nil {
  210. user.log.Warnln("Error while reconnecting:", err)
  211. jsonResponse(w, http.StatusInternalServerError, Error{
  212. Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
  213. ErrCode: err.Error(),
  214. })
  215. user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  216. err = user.Conn.Disconnect()
  217. if err != nil {
  218. user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  219. }
  220. return
  221. }
  222. user.ConnectionErrors = 0
  223. user.PostLogin()
  224. var msg string
  225. if wasConnected {
  226. msg = "Reconnected successfully."
  227. } else {
  228. msg = "Connected successfully."
  229. }
  230. jsonResponse(w, http.StatusOK, Response{true, msg})
  231. }
  232. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  233. user := r.Context().Value("user").(*User)
  234. wa := map[string]interface{}{
  235. "has_session": user.Session != nil,
  236. "management_room": user.ManagementRoom,
  237. "jid": user.JID,
  238. "conn": nil,
  239. "ping": nil,
  240. }
  241. if user.Conn != nil {
  242. wa["conn"] = map[string]interface{}{
  243. "is_connected": user.Conn.IsConnected(),
  244. "is_logged_in": user.Conn.IsLoggedIn(),
  245. "is_login_in_progress": user.Conn.IsLoginInProgress(),
  246. }
  247. user.log.Debugln("Pinging WhatsApp mobile due to /ping API request")
  248. err := user.Conn.AdminTest()
  249. var errStr string
  250. if err == whatsapp.ErrPingFalse {
  251. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  252. go user.HandleError(err)
  253. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  254. user.Conn.CountTimeout()
  255. }
  256. if err != nil {
  257. errStr = err.Error()
  258. }
  259. wa["ping"] = map[string]interface{}{
  260. "ok": err == nil,
  261. "err": errStr,
  262. }
  263. user.log.Debugfln("Admin test response for /ping: %v (conn: %t, login: %t, in progress: %t)",
  264. err, user.Conn.IsConnected(), user.Conn.IsLoggedIn(), user.Conn.IsLoginInProgress())
  265. }
  266. resp := map[string]interface{}{
  267. "mxid": user.MXID,
  268. "admin": user.Admin,
  269. "whitelisted": user.Whitelisted,
  270. "relaybot_whitelisted": user.RelaybotWhitelisted,
  271. "whatsapp": wa,
  272. }
  273. jsonResponse(w, http.StatusOK, resp)
  274. }
  275. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  276. w.Header().Add("Content-Type", "application/json")
  277. w.WriteHeader(status)
  278. _ = json.NewEncoder(w).Encode(response)
  279. }
  280. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  281. user := r.Context().Value("user").(*User)
  282. if user.Session == nil {
  283. jsonResponse(w, http.StatusNotFound, Error{
  284. Error: "You're not logged in",
  285. ErrCode: "not logged in",
  286. })
  287. return
  288. }
  289. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  290. if user.Conn == nil {
  291. if !force {
  292. jsonResponse(w, http.StatusNotFound, Error{
  293. Error: "You're not connected",
  294. ErrCode: "not connected",
  295. })
  296. }
  297. } else {
  298. err := user.Conn.Logout()
  299. if err != nil {
  300. user.log.Warnln("Error while logging out:", err)
  301. if !force {
  302. jsonResponse(w, http.StatusInternalServerError, Error{
  303. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  304. ErrCode: err.Error(),
  305. })
  306. return
  307. }
  308. }
  309. user.DeleteConnection()
  310. }
  311. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  312. user.removeFromJIDMap()
  313. // TODO this causes a foreign key violation, which should be fixed
  314. //ce.User.JID = ""
  315. user.SetSession(nil)
  316. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  317. }
  318. var upgrader = websocket.Upgrader{
  319. CheckOrigin: func(r *http.Request) bool {
  320. return true
  321. },
  322. Subprotocols: []string{"net.maunium.whatsapp.login"},
  323. }
  324. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  325. userID := r.URL.Query().Get("user_id")
  326. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  327. c, err := upgrader.Upgrade(w, r, nil)
  328. if err != nil {
  329. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  330. return
  331. }
  332. defer c.Close()
  333. if !user.Connect(true) {
  334. user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  335. _ = c.WriteJSON(Error{
  336. Error: "Failed to connect to WhatsApp",
  337. ErrCode: "connection error",
  338. })
  339. return
  340. }
  341. qrChan := make(chan string, 3)
  342. go func() {
  343. for code := range qrChan {
  344. if code == "stop" {
  345. return
  346. }
  347. _ = c.WriteJSON(map[string]interface{}{
  348. "code": code,
  349. })
  350. }
  351. }()
  352. go func() {
  353. // Read everything so SetCloseHandler() works
  354. for {
  355. _, _, err = c.ReadMessage()
  356. if err != nil {
  357. break
  358. }
  359. }
  360. }()
  361. ctx, cancel := context.WithCancel(context.Background())
  362. c.SetCloseHandler(func(code int, text string) error {
  363. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  364. cancel()
  365. return nil
  366. })
  367. user.log.Debugln("Starting login via provisioning API")
  368. session, jid, err := user.Conn.Login(qrChan, ctx, user.bridge.Config.Bridge.LoginQRRegenCount)
  369. qrChan <- "stop"
  370. if err != nil {
  371. var msg string
  372. if errors.Is(err, whatsapp.ErrAlreadyLoggedIn) {
  373. msg = "You're already logged in"
  374. } else if errors.Is(err, whatsapp.ErrLoginInProgress) {
  375. msg = "You have a login in progress already."
  376. } else if errors.Is(err, whatsapp.ErrLoginTimedOut) {
  377. msg = "QR code scan timed out. Please try again."
  378. } else if errors.Is(err, whatsapp.ErrInvalidWebsocket) {
  379. msg = "WhatsApp connection error. Please try again."
  380. // TODO might need to make sure it reconnects?
  381. } else {
  382. msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  383. }
  384. user.log.Warnln("Failed to log in:", err)
  385. _ = c.WriteJSON(Error{
  386. Error: msg,
  387. ErrCode: err.Error(),
  388. })
  389. return
  390. }
  391. user.log.Debugln("Successful login as", jid, "via provisioning API")
  392. user.ConnectionErrors = 0
  393. user.JID = strings.Replace(jid, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, 1)
  394. user.addToJIDMap()
  395. user.SetSession(&session)
  396. _ = c.WriteJSON(map[string]interface{}{
  397. "success": true,
  398. "jid": user.JID,
  399. })
  400. user.PostLogin()
  401. }