provisioning.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. log "maunium.net/go/maulogger/v2"
  29. "github.com/Rhymen/go-whatsapp"
  30. "maunium.net/go/mautrix/id"
  31. whatsappExt "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  32. )
  33. type ProvisioningAPI struct {
  34. bridge *Bridge
  35. log log.Logger
  36. }
  37. func (prov *ProvisioningAPI) Init() {
  38. prov.log = prov.bridge.Log.Sub("Provisioning")
  39. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  40. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  41. r.Use(prov.AuthMiddleware)
  42. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  43. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  44. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  45. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  46. r.HandleFunc("/delete_connection", prov.DeleteConnection).Methods(http.MethodPost)
  47. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  48. r.HandleFunc("/reconnect", prov.Reconnect).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.Disconnect()
  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.Disconnect()
  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. sess, 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. } else {
  155. user.SetSession(&sess)
  156. }
  157. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  158. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  159. }
  160. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  161. user := r.Context().Value("user").(*User)
  162. if user.Conn == nil {
  163. if user.Session == nil {
  164. jsonResponse(w, http.StatusForbidden, Error{
  165. Error: "No existing connection and no session. Please log in first.",
  166. ErrCode: "no session",
  167. })
  168. } else {
  169. user.Connect(false)
  170. jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
  171. }
  172. return
  173. }
  174. user.log.Debugln("Received /reconnect request, disconnecting")
  175. wasConnected := true
  176. sess, err := user.Conn.Disconnect()
  177. if err == whatsapp.ErrNotConnected {
  178. wasConnected = false
  179. } else if err != nil {
  180. user.log.Warnln("Error while disconnecting:", err)
  181. } else {
  182. user.SetSession(&sess)
  183. }
  184. user.log.Debugln("Restoring session for /reconnect")
  185. err = user.Conn.Restore(true)
  186. user.log.Debugfln("Restore session for /reconnect responded with %v", err)
  187. if err == whatsapp.ErrInvalidSession {
  188. if user.Session != nil {
  189. user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  190. sess, err = user.Conn.RestoreWithSession(*user.Session)
  191. if err == nil {
  192. user.SetSession(&sess)
  193. }
  194. } else {
  195. jsonResponse(w, http.StatusForbidden, Error{
  196. Error: "You're not logged in",
  197. ErrCode: "not logged in",
  198. })
  199. return
  200. }
  201. } else if err == whatsapp.ErrLoginInProgress {
  202. jsonResponse(w, http.StatusConflict, Error{
  203. Error: "A login or reconnection is already in progress.",
  204. ErrCode: "login in progress",
  205. })
  206. return
  207. } else if err == whatsapp.ErrAlreadyLoggedIn {
  208. jsonResponse(w, http.StatusConflict, Error{
  209. Error: "You were already connected.",
  210. ErrCode: err.Error(),
  211. })
  212. return
  213. }
  214. if err != nil {
  215. user.log.Warnln("Error while reconnecting:", err)
  216. if errors.Is(err, whatsapp.ErrRestoreSessionTimeout) {
  217. jsonResponse(w, http.StatusForbidden, Error{
  218. Error: "Reconnection timed out. Is WhatsApp on your phone reachable?",
  219. ErrCode: err.Error(),
  220. })
  221. } else {
  222. jsonResponse(w, http.StatusForbidden, Error{
  223. Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
  224. ErrCode: err.Error(),
  225. })
  226. }
  227. user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  228. sess, err := user.Conn.Disconnect()
  229. if err != nil {
  230. user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  231. } else {
  232. user.SetSession(&sess)
  233. }
  234. return
  235. }
  236. user.ConnectionErrors = 0
  237. user.PostLogin()
  238. var msg string
  239. if wasConnected {
  240. msg = "Reconnected successfully."
  241. } else {
  242. msg = "Connected successfully."
  243. }
  244. jsonResponse(w, http.StatusOK, Response{true, msg})
  245. }
  246. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  247. user := r.Context().Value("user").(*User)
  248. wa := map[string]interface{}{
  249. "has_session": user.Session != nil,
  250. "management_room": user.ManagementRoom,
  251. "jid": user.JID,
  252. "conn": nil,
  253. "ping": nil,
  254. }
  255. if user.Conn != nil {
  256. wa["conn"] = map[string]interface{}{
  257. "is_connected": user.Conn.IsConnected(),
  258. "is_logged_in": user.Conn.IsLoggedIn(),
  259. "is_login_in_progress": user.Conn.IsLoginInProgress(),
  260. }
  261. user.log.Debugln("Pinging WhatsApp mobile due to /ping API request")
  262. err := user.Conn.AdminTest()
  263. var errStr string
  264. if err != nil {
  265. errStr = err.Error()
  266. }
  267. wa["ping"] = map[string]interface{}{
  268. "ok": err == nil,
  269. "err": errStr,
  270. }
  271. user.log.Debugfln("Admin test response for /ping: %v (conn: %t, login: %t, in progress: %t)",
  272. err, user.Conn.IsConnected(), user.Conn.IsLoggedIn(), user.Conn.IsLoginInProgress())
  273. }
  274. resp := map[string]interface{}{
  275. "mxid": user.MXID,
  276. "admin": user.Admin,
  277. "whitelisted": user.Whitelisted,
  278. "relaybot_whitelisted": user.RelaybotWhitelisted,
  279. "whatsapp": wa,
  280. }
  281. jsonResponse(w, http.StatusOK, resp)
  282. }
  283. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  284. w.Header().Add("Content-Type", "application/json")
  285. w.WriteHeader(status)
  286. _ = json.NewEncoder(w).Encode(response)
  287. }
  288. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  289. user := r.Context().Value("user").(*User)
  290. if user.Session == nil {
  291. jsonResponse(w, http.StatusNotFound, Error{
  292. Error: "You're not logged in",
  293. ErrCode: "not logged in",
  294. })
  295. return
  296. }
  297. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  298. if user.Conn == nil {
  299. if !force {
  300. jsonResponse(w, http.StatusNotFound, Error{
  301. Error: "You're not connected",
  302. ErrCode: "not connected",
  303. })
  304. }
  305. } else {
  306. err := user.Conn.Logout()
  307. if err != nil {
  308. user.log.Warnln("Error while logging out:", err)
  309. if !force {
  310. jsonResponse(w, http.StatusInternalServerError, Error{
  311. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  312. ErrCode: err.Error(),
  313. })
  314. return
  315. }
  316. }
  317. user.Disconnect()
  318. }
  319. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  320. user.removeFromJIDMap()
  321. // TODO this causes a foreign key violation, which should be fixed
  322. //ce.User.JID = ""
  323. user.SetSession(nil)
  324. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  325. }
  326. var upgrader = websocket.Upgrader{
  327. CheckOrigin: func(r *http.Request) bool {
  328. return true
  329. },
  330. Subprotocols: []string{"net.maunium.whatsapp.login"},
  331. }
  332. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  333. userID := r.URL.Query().Get("user_id")
  334. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  335. c, err := upgrader.Upgrade(w, r, nil)
  336. if err != nil {
  337. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  338. return
  339. }
  340. defer c.Close()
  341. if !user.Connect(true) {
  342. user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  343. _ = c.WriteJSON(Error{
  344. Error: "Failed to connect to WhatsApp",
  345. ErrCode: "connection error",
  346. })
  347. return
  348. }
  349. qrChan := make(chan string, 3)
  350. go func() {
  351. for code := range qrChan {
  352. if code == "stop" {
  353. return
  354. }
  355. _ = c.WriteJSON(map[string]interface{}{
  356. "code": code,
  357. })
  358. }
  359. }()
  360. go func() {
  361. // Read everything so SetCloseHandler() works
  362. for {
  363. _, _, err = c.ReadMessage()
  364. if err != nil {
  365. break
  366. }
  367. }
  368. }()
  369. ctx, cancel := context.WithCancel(context.Background())
  370. c.SetCloseHandler(func(code int, text string) error {
  371. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  372. cancel()
  373. return nil
  374. })
  375. user.log.Debugln("Starting login via provisioning API")
  376. session, err := user.Conn.LoginWithRetry(qrChan, ctx, user.bridge.Config.Bridge.LoginQRRegenCount)
  377. qrChan <- "stop"
  378. if err != nil {
  379. var msg string
  380. if errors.Is(err, whatsapp.ErrAlreadyLoggedIn) {
  381. msg = "You're already logged in"
  382. } else if errors.Is(err, whatsapp.ErrLoginInProgress) {
  383. msg = "You have a login in progress already."
  384. } else if errors.Is(err, whatsapp.ErrLoginTimedOut) {
  385. msg = "QR code scan timed out. Please try again."
  386. } else if errors.Is(err, whatsapp.ErrInvalidWebsocket) {
  387. msg = "WhatsApp connection error. Please try again."
  388. user.Disconnect()
  389. } else {
  390. msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  391. }
  392. user.log.Warnln("Failed to log in:", err)
  393. _ = c.WriteJSON(Error{
  394. Error: msg,
  395. ErrCode: err.Error(),
  396. })
  397. return
  398. }
  399. user.log.Debugln("Successful login via provisioning API")
  400. user.ConnectionErrors = 0
  401. user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
  402. user.addToJIDMap()
  403. user.SetSession(&session)
  404. _ = c.WriteJSON(map[string]interface{}{
  405. "success": true,
  406. "jid": user.JID,
  407. })
  408. user.PostLogin()
  409. }