netconn.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2013 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution, and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Seth Hoenig
  11. * Allan Stockdill-Mander
  12. * Mike Robertson
  13. */
  14. package mqtt
  15. import (
  16. "crypto/tls"
  17. "errors"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "time"
  23. "golang.org/x/net/proxy"
  24. )
  25. //
  26. // This just establishes the network connection; once established the type of connection should be irrelevant
  27. //
  28. // openConnection opens a network connection using the protocol indicated in the URL.
  29. // Does not carry out any MQTT specific handshakes.
  30. func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header, websocketOptions *WebsocketOptions) (net.Conn, error) {
  31. switch uri.Scheme {
  32. case "ws":
  33. conn, err := NewWebsocket(uri.String(), nil, timeout, headers, websocketOptions)
  34. return conn, err
  35. case "wss":
  36. conn, err := NewWebsocket(uri.String(), tlsc, timeout, headers, websocketOptions)
  37. return conn, err
  38. case "mqtt", "tcp":
  39. allProxy := os.Getenv("all_proxy")
  40. if len(allProxy) == 0 {
  41. conn, err := net.DialTimeout("tcp", uri.Host, timeout)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return conn, nil
  46. }
  47. proxyDialer := proxy.FromEnvironment()
  48. conn, err := proxyDialer.Dial("tcp", uri.Host)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return conn, nil
  53. case "unix":
  54. conn, err := net.DialTimeout("unix", uri.Host, timeout)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return conn, nil
  59. case "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
  60. allProxy := os.Getenv("all_proxy")
  61. if len(allProxy) == 0 {
  62. conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return conn, nil
  67. }
  68. proxyDialer := proxy.FromEnvironment()
  69. conn, err := proxyDialer.Dial("tcp", uri.Host)
  70. if err != nil {
  71. return nil, err
  72. }
  73. tlsConn := tls.Client(conn, tlsc)
  74. err = tlsConn.Handshake()
  75. if err != nil {
  76. _ = conn.Close()
  77. return nil, err
  78. }
  79. return tlsConn, nil
  80. }
  81. return nil, errors.New("unknown protocol")
  82. }