provisioning.go 13 KB

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