provisioning.go 13 KB

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