client.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Package apns2 is a go Apple Push Notification Service (APNs) provider that
  2. // allows you to send remote notifications to your iOS, tvOS, and OS X
  3. // apps, using the new APNs HTTP/2 network protocol.
  4. package apns2
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "net/http"
  15. "strconv"
  16. "time"
  17. "go-common/library/log"
  18. "go-common/library/stat"
  19. "go-common/library/stat/prom"
  20. "golang.org/x/net/http2"
  21. "golang.org/x/net/proxy"
  22. )
  23. const (
  24. // HostDevelopment dev host.
  25. HostDevelopment = "https://api.development.push.apple.com"
  26. // HostProduction pro host.
  27. HostProduction = "https://api.push.apple.com"
  28. // StatusCodeSuccess success.
  29. StatusCodeSuccess = 200
  30. // StatusCodeBadReq bad req.
  31. StatusCodeBadReq = 400
  32. // StatusCodeCerErr There was an error with the certificate.
  33. StatusCodeCerErr = 403
  34. // StatusCodeMethodErr The request used a bad :method value. Only POST requests are supported.
  35. StatusCodeMethodErr = 405
  36. // StatusCodeNotForTopic The device token is not form the topic.
  37. StatusCodeNotForTopic = 400
  38. // StatusCodeNoActive The device token is no longer active for the topic.
  39. StatusCodeNoActive = 410
  40. // StatusCodePayloadTooLarge The notification payload was too large.
  41. StatusCodePayloadTooLarge = 413
  42. // StatusCodeTooManyReq The server received too many requests for the same device token.
  43. StatusCodeTooManyReq = 429
  44. // StatusCodeServerErr Internal server error
  45. StatusCodeServerErr = 500
  46. // StatusCodeServerUnavailable The server is shutting down and unavailable.
  47. StatusCodeServerUnavailable = 503
  48. )
  49. // DefaultHost is a mutable var for testing purposes
  50. var DefaultHost = HostDevelopment
  51. // Client represents a connection with the APNs
  52. type Client struct {
  53. HTTPClient *http.Client
  54. Certificate tls.Certificate
  55. Host string
  56. BoundID string
  57. Stats stat.Stat
  58. }
  59. // func init() {
  60. // proxy.RegisterDialerType("http", func(*url.URL, proxy.Dialer) (proxy.Dialer, error) {
  61. // return &net.Dialer{}, nil
  62. // })
  63. // }
  64. // NewClient returns a new Client with an underlying http.Client configured with
  65. // the correct APNs HTTP/2 transport settings. It does not connect to the APNs
  66. // until the first Notification is sent via the Push method.
  67. //
  68. // As per the Apple APNs Provider API, you should keep a handle on this client
  69. // so that you can keep your connections with APNs open across multiple
  70. // notifications; don’t repeatedly open and close connections. APNs treats rapid
  71. // connection and disconnection as a denial-of-service attack.
  72. func NewClient(certificate tls.Certificate, timeout time.Duration) *Client {
  73. tlsConfig := &tls.Config{
  74. Certificates: []tls.Certificate{certificate},
  75. ClientAuth: tls.NoClientCert,
  76. }
  77. if len(certificate.Certificate) > 0 {
  78. tlsConfig.BuildNameToCertificate()
  79. }
  80. transport := &http2.Transport{
  81. TLSClientConfig: tlsConfig,
  82. }
  83. // transport := &http.Transport{
  84. // TLSClientConfig: tlsConfig,
  85. // Proxy: func(_ *http.Request) (*url.URL, error) {
  86. // return url.Parse("http://10.28.10.11:80")
  87. // },
  88. // DialContext: (&net.Dialer{
  89. // Timeout: 30 * time.Second,
  90. // KeepAlive: 30 * time.Second,
  91. // DualStack: true,
  92. // }).DialContext,
  93. // MaxIdleConns: 100,
  94. // IdleConnTimeout: 90 * time.Second,
  95. // TLSHandshakeTimeout: 10 * time.Second,
  96. // ExpectContinueTimeout: 1 * time.Second,
  97. // }
  98. return &Client{
  99. HTTPClient: &http.Client{Transport: transport, Timeout: timeout},
  100. Certificate: certificate,
  101. Host: DefaultHost,
  102. Stats: prom.HTTPClient,
  103. }
  104. }
  105. // NewClientWithProxy returns a new Client with sock5 proxy.
  106. func NewClientWithProxy(certificate tls.Certificate, timeout time.Duration, proxyAddr string) *Client {
  107. tlsConfig := &tls.Config{
  108. Certificates: []tls.Certificate{certificate},
  109. ClientAuth: tls.NoClientCert,
  110. }
  111. if len(certificate.Certificate) > 0 {
  112. tlsConfig.BuildNameToCertificate()
  113. }
  114. return &Client{
  115. HTTPClient: &http.Client{Transport: proxyTransport(proxyAddr, tlsConfig, timeout), Timeout: timeout},
  116. Certificate: certificate,
  117. Host: DefaultHost,
  118. Stats: prom.HTTPClient,
  119. }
  120. }
  121. func proxyTransport(proxyAddr string, config *tls.Config, timeout time.Duration) *http2.Transport {
  122. return &http2.Transport{
  123. DialTLS: func(network, addr string, cfg *tls.Config) (nc net.Conn, err error) {
  124. dialer := &net.Dialer{Timeout: timeout / 2}
  125. var proxyDialer proxy.Dialer
  126. if proxyDialer, err = proxy.SOCKS5("tcp", proxyAddr, nil, dialer); err != nil {
  127. log.Error("proxy.SOCKS5(%s) error(%v)", proxyAddr, err)
  128. return nil, err
  129. }
  130. // u, _ := url.Parse("http://10.28.10.11:80")
  131. // proxyDialer, err = proxy.FromURL(u, dialer)
  132. var conn net.Conn
  133. if conn, err = proxyDialer.Dial(network, addr); err != nil {
  134. log.Error("proxyDialer.Dial(%s,%s) error(%v)", network, addr, err)
  135. if conn, err = dialer.Dial(network, addr); err != nil {
  136. log.Error("dialer.Dial(%s,%s) error(%v)", network, addr, err)
  137. return nil, err
  138. }
  139. }
  140. tlsConn := tls.Client(conn, cfg)
  141. if err = tlsConn.Handshake(); err != nil {
  142. log.Error("tlsConn.Handshake() error(%v)", err)
  143. return nil, err
  144. }
  145. if !cfg.InsecureSkipVerify {
  146. if err = tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  147. log.Error("tlsConn.VerifyHostname(%s) error(%v)", cfg.ServerName, err)
  148. return nil, err
  149. }
  150. }
  151. state := tlsConn.ConnectionState()
  152. if state.NegotiatedProtocol != http2.NextProtoTLS {
  153. err = fmt.Errorf("http2: unexpected ALPN protocol(%s) expect(%s)", state.NegotiatedProtocol, http2.NextProtoTLS)
  154. return nil, err
  155. }
  156. if !state.NegotiatedProtocolIsMutual {
  157. err = errors.New("http2: could not negotiate protocol mutually")
  158. return nil, err
  159. }
  160. return tlsConn, nil
  161. },
  162. TLSClientConfig: config,
  163. }
  164. }
  165. // Development sets the Client to use the APNs development push endpoint.
  166. func (c *Client) Development() *Client {
  167. c.Host = HostDevelopment
  168. return c
  169. }
  170. // Production sets the Client to use the APNs production push endpoint.
  171. func (c *Client) Production() *Client {
  172. c.Host = HostProduction
  173. return c
  174. }
  175. // Push sends a Notification to the APNs gateway. If the underlying http.Client
  176. // is not currently connected, this method will attempt to reconnect
  177. // transparently before sending the notification.
  178. func (c *Client) Push(deviceToken string, payload *Payload, overTime int64) (response *Response, err error) {
  179. if c.Stats != nil {
  180. now := time.Now()
  181. defer func() {
  182. c.Stats.Timing(c.Host, int64(time.Since(now)/time.Millisecond))
  183. log.Info("apns stats timing: %v", int64(time.Since(now)/time.Millisecond))
  184. if err != nil {
  185. c.Stats.Incr(c.Host, "failed")
  186. }
  187. }()
  188. }
  189. var (
  190. req *http.Request
  191. res *http.Response
  192. t = time.NewTimer(c.HTTPClient.Timeout)
  193. errCh = make(chan error, 1)
  194. url = fmt.Sprintf("%v/3/device/%v", c.Host, deviceToken)
  195. )
  196. if req, err = http.NewRequest("POST", url, bytes.NewBuffer(payload.Marshal())); err != nil {
  197. log.Error("http.NewRequest(%s) error(%v)", url, err)
  198. return
  199. }
  200. req.Header.Set("apns-topic", c.BoundID)
  201. req.Header.Set("apns-expiration", strconv.FormatInt(overTime, 10))
  202. req.Header.Set("apns-collapse-id", payload.TaskID)
  203. go func() {
  204. res, err = c.HTTPClient.Do(req)
  205. errCh <- err
  206. }()
  207. select {
  208. case <-t.C:
  209. err = errors.New("http.Do timeout")
  210. return
  211. case err = <-errCh:
  212. if err != nil {
  213. log.Error("c.HTTPClient.Do() error(%v)", err)
  214. return
  215. }
  216. }
  217. defer res.Body.Close()
  218. response = &Response{StatusCode: res.StatusCode, ApnsID: res.Header.Get("apns-id")}
  219. var bs []byte
  220. bs, err = ioutil.ReadAll(res.Body)
  221. if err != nil {
  222. log.Error("ioutil.ReadAll() error(%v)", err)
  223. return
  224. } else if len(bs) == 0 {
  225. return
  226. }
  227. if e := json.Unmarshal(bs, &response); e != nil {
  228. if e != io.EOF {
  229. log.Error("json decode body(%s) error(%v)", string(bs), e)
  230. }
  231. }
  232. return
  233. }
  234. // MockPush mock push.
  235. func (c *Client) MockPush(deviceToken string, payload *Payload, overTime int64) (response *Response, err error) {
  236. if c.Stats != nil {
  237. now := time.Now()
  238. defer func() {
  239. c.Stats.Timing(c.Host, int64(time.Since(now)/time.Millisecond))
  240. // log.Info("mock apns stats timing: %v", int64(time.Since(now)/time.Millisecond))
  241. if err != nil {
  242. c.Stats.Incr(c.Host, "apple push mock")
  243. }
  244. }()
  245. }
  246. time.Sleep(200 * time.Millisecond)
  247. response = &Response{StatusCode: StatusCodeSuccess}
  248. return
  249. }