request.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright (c) 2021 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package whatsmeow
  7. import (
  8. "context"
  9. "fmt"
  10. "strconv"
  11. "time"
  12. waBinary "go.mau.fi/whatsmeow/binary"
  13. "go.mau.fi/whatsmeow/types"
  14. )
  15. func (cli *Client) generateRequestID() string {
  16. return cli.uniqueID + strconv.FormatUint(cli.idCounter.Add(1), 10)
  17. }
  18. var xmlStreamEndNode = &waBinary.Node{Tag: "xmlstreamend"}
  19. func isDisconnectNode(node *waBinary.Node) bool {
  20. return node == xmlStreamEndNode || node.Tag == "stream:error"
  21. }
  22. // isAuthErrorDisconnect checks if the given disconnect node is an error that shouldn't cause retrying.
  23. func isAuthErrorDisconnect(node *waBinary.Node) bool {
  24. if node.Tag != "stream:error" {
  25. return false
  26. }
  27. code, _ := node.Attrs["code"].(string)
  28. conflict, _ := node.GetOptionalChildByTag("conflict")
  29. conflictType := conflict.AttrGetter().OptionalString("type")
  30. if code == "401" || conflictType == "replaced" || conflictType == "device_removed" {
  31. return true
  32. }
  33. return false
  34. }
  35. func (cli *Client) clearResponseWaiters(node *waBinary.Node) {
  36. cli.responseWaitersLock.Lock()
  37. for _, waiter := range cli.responseWaiters {
  38. select {
  39. case waiter <- node:
  40. default:
  41. close(waiter)
  42. }
  43. }
  44. cli.responseWaiters = make(map[string]chan<- *waBinary.Node)
  45. cli.responseWaitersLock.Unlock()
  46. }
  47. func (cli *Client) waitResponse(reqID string) chan *waBinary.Node {
  48. ch := make(chan *waBinary.Node, 1)
  49. cli.responseWaitersLock.Lock()
  50. cli.responseWaiters[reqID] = ch
  51. cli.responseWaitersLock.Unlock()
  52. return ch
  53. }
  54. func (cli *Client) cancelResponse(reqID string, ch chan *waBinary.Node) {
  55. cli.responseWaitersLock.Lock()
  56. close(ch)
  57. delete(cli.responseWaiters, reqID)
  58. cli.responseWaitersLock.Unlock()
  59. }
  60. func (cli *Client) receiveResponse(ctx context.Context, data *waBinary.Node) bool {
  61. id, ok := data.Attrs["id"].(string)
  62. if !ok || (data.Tag != "iq" && data.Tag != "ack") {
  63. return false
  64. }
  65. cli.responseWaitersLock.Lock()
  66. waiter, ok := cli.responseWaiters[id]
  67. if !ok {
  68. cli.responseWaitersLock.Unlock()
  69. return false
  70. }
  71. delete(cli.responseWaiters, id)
  72. cli.responseWaitersLock.Unlock()
  73. select {
  74. case waiter <- data:
  75. case <-ctx.Done():
  76. }
  77. return true
  78. }
  79. type infoQueryType string
  80. const (
  81. iqSet infoQueryType = "set"
  82. iqGet infoQueryType = "get"
  83. )
  84. type infoQuery struct {
  85. Namespace string
  86. Type infoQueryType
  87. To types.JID
  88. Target types.JID
  89. ID string
  90. SMaxID string
  91. Content interface{}
  92. Timeout time.Duration
  93. NoRetry bool
  94. }
  95. func (cli *Client) sendIQAsyncAndGetData(ctx context.Context, query *infoQuery) (<-chan *waBinary.Node, []byte, error) {
  96. if cli == nil {
  97. return nil, nil, ErrClientIsNil
  98. }
  99. if len(query.ID) == 0 {
  100. query.ID = cli.generateRequestID()
  101. }
  102. waiter := cli.waitResponse(query.ID)
  103. attrs := waBinary.Attrs{
  104. "id": query.ID,
  105. "xmlns": query.Namespace,
  106. "type": string(query.Type),
  107. }
  108. if query.SMaxID != "" {
  109. attrs["smax_id"] = query.SMaxID
  110. }
  111. if !query.To.IsEmpty() {
  112. attrs["to"] = query.To
  113. }
  114. if !query.Target.IsEmpty() {
  115. attrs["target"] = query.Target
  116. }
  117. data, err := cli.sendNodeAndGetData(ctx, waBinary.Node{
  118. Tag: "iq",
  119. Attrs: attrs,
  120. Content: query.Content,
  121. })
  122. if err != nil {
  123. cli.cancelResponse(query.ID, waiter)
  124. return nil, data, err
  125. }
  126. return waiter, data, nil
  127. }
  128. func (cli *Client) sendIQAsync(ctx context.Context, query infoQuery) (<-chan *waBinary.Node, error) {
  129. ch, _, err := cli.sendIQAsyncAndGetData(ctx, &query)
  130. return ch, err
  131. }
  132. const defaultRequestTimeout = 75 * time.Second
  133. func (cli *Client) sendIQ(ctx context.Context, query infoQuery) (*waBinary.Node, error) {
  134. if query.Timeout == 0 {
  135. query.Timeout = defaultRequestTimeout
  136. }
  137. resChan, data, err := cli.sendIQAsyncAndGetData(ctx, &query)
  138. if err != nil {
  139. return nil, err
  140. }
  141. select {
  142. case res := <-resChan:
  143. if isDisconnectNode(res) {
  144. if query.NoRetry {
  145. return nil, &DisconnectedError{Action: "info query", Node: res}
  146. }
  147. res, err = cli.retryFrame(ctx, "info query", query.ID, data, res, query.Timeout)
  148. if err != nil {
  149. return nil, err
  150. }
  151. }
  152. resType, _ := res.Attrs["type"].(string)
  153. if res.Tag != "iq" || (resType != "result" && resType != "error") {
  154. return res, &IQError{RawNode: res}
  155. } else if resType == "error" {
  156. return res, parseIQError(res)
  157. }
  158. return res, nil
  159. case <-ctx.Done():
  160. return nil, ctx.Err()
  161. case <-time.After(query.Timeout):
  162. return nil, ErrIQTimedOut
  163. }
  164. }
  165. func (cli *Client) retryFrame(
  166. ctx context.Context,
  167. reqType,
  168. id string,
  169. data []byte,
  170. origResp *waBinary.Node,
  171. timeout time.Duration,
  172. ) (*waBinary.Node, error) {
  173. if isAuthErrorDisconnect(origResp) {
  174. cli.Log.Debugf("%s (%s) was interrupted by websocket disconnection (%s), not retrying as it looks like an auth error", id, reqType, origResp.XMLString())
  175. return nil, &DisconnectedError{Action: reqType, Node: origResp}
  176. }
  177. cli.Log.Debugf("%s (%s) was interrupted by websocket disconnection (%s), waiting for reconnect to retry...", id, reqType, origResp.XMLString())
  178. if !cli.WaitForConnection(5 * time.Second) {
  179. cli.Log.Debugf("Websocket didn't reconnect within 5 seconds of failed %s (%s)", reqType, id)
  180. return nil, &DisconnectedError{Action: reqType, Node: origResp}
  181. }
  182. cli.socketLock.RLock()
  183. sock := cli.socket
  184. cli.socketLock.RUnlock()
  185. if sock == nil {
  186. return nil, ErrNotConnected
  187. }
  188. respChan := cli.waitResponse(id)
  189. err := sock.SendFrame(ctx, data)
  190. if err != nil {
  191. cli.cancelResponse(id, respChan)
  192. return nil, err
  193. }
  194. var resp *waBinary.Node
  195. timeoutChan := make(<-chan time.Time, 1)
  196. if timeout > 0 {
  197. timeoutChan = time.After(timeout)
  198. }
  199. select {
  200. case resp = <-respChan:
  201. case <-ctx.Done():
  202. return nil, ctx.Err()
  203. case <-timeoutChan:
  204. // FIXME this error isn't technically correct (but works for now - the timeout param is only used from sendIQ)
  205. return nil, ErrIQTimedOut
  206. }
  207. if isDisconnectNode(resp) {
  208. cli.Log.Debugf("Retrying %s %s was interrupted by websocket disconnection (%v), not retrying anymore", reqType, id, resp.XMLString())
  209. return nil, &DisconnectedError{Action: fmt.Sprintf("%s (retry)", reqType), Node: resp}
  210. }
  211. return resp, nil
  212. }