netclientutils.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package netclientutils
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "math/rand"
  9. "net"
  10. "net/http"
  11. "os"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "golang.zx2c4.com/wireguard/wgctrl"
  17. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  18. "google.golang.org/grpc"
  19. "google.golang.org/grpc/credentials"
  20. )
  21. const NO_DB_RECORD = "no result found"
  22. const NO_DB_RECORDS = "could not find any records"
  23. const LINUX_APP_DATA_PATH = "/etc/netclient"
  24. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
  25. const WINDOWS_SVC_NAME = "netclient"
  26. const NETCLIENT_DEFAULT_PORT = 51821
  27. const DEFAULT_GC_PERCENT = 10
  28. func Log(message string) {
  29. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  30. log.Println("[netclient]", message)
  31. }
  32. func IsWindows() bool {
  33. return runtime.GOOS == "windows"
  34. }
  35. func IsMac() bool {
  36. return runtime.GOOS == "macos"
  37. }
  38. func IsLinux() bool {
  39. return runtime.GOOS == "linux"
  40. }
  41. // == database returned nothing error ==
  42. func IsEmptyRecord(err error) bool {
  43. if err == nil {
  44. return false
  45. }
  46. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  47. }
  48. //generate an access key value
  49. func GenPass() string {
  50. var seededRand *rand.Rand = rand.New(
  51. rand.NewSource(time.Now().UnixNano()))
  52. length := 16
  53. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  54. b := make([]byte, length)
  55. for i := range b {
  56. b[i] = charset[seededRand.Intn(len(charset))]
  57. }
  58. return string(b)
  59. }
  60. func GetPublicIP() (string, error) {
  61. iplist := []string{"http://ip.client.gravitl.com", "https://ifconfig.me", "http://api.ipify.org", "http://ipinfo.io/ip"}
  62. endpoint := ""
  63. var err error
  64. for _, ipserver := range iplist {
  65. resp, err := http.Get(ipserver)
  66. if err != nil {
  67. continue
  68. }
  69. defer resp.Body.Close()
  70. if resp.StatusCode == http.StatusOK {
  71. bodyBytes, err := ioutil.ReadAll(resp.Body)
  72. if err != nil {
  73. continue
  74. }
  75. endpoint = string(bodyBytes)
  76. break
  77. }
  78. }
  79. if err == nil && endpoint == "" {
  80. err = errors.New("public address not found")
  81. }
  82. return endpoint, err
  83. }
  84. func GetMacAddr() ([]string, error) {
  85. ifas, err := net.Interfaces()
  86. if err != nil {
  87. return nil, err
  88. }
  89. var as []string
  90. for _, ifa := range ifas {
  91. a := ifa.HardwareAddr.String()
  92. if a != "" {
  93. as = append(as, a)
  94. }
  95. }
  96. return as, nil
  97. }
  98. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  99. peersString := ""
  100. if keepalive <= 0 {
  101. keepalive = 20
  102. }
  103. for _, peer := range peers {
  104. newAllowedIps := []string{}
  105. for _, allowedIP := range peer.AllowedIPs {
  106. newAllowedIps = append(newAllowedIps, allowedIP.String())
  107. }
  108. peersString += fmt.Sprintf(`[Peer]
  109. PublicKey = %s
  110. AllowedIps = %s
  111. Endpoint = %s
  112. PersistentKeepAlive = %s
  113. `,
  114. peer.PublicKey.String(),
  115. strings.Join(newAllowedIps, ","),
  116. peer.Endpoint.String(),
  117. strconv.Itoa(int(keepalive)),
  118. )
  119. }
  120. return peersString, nil
  121. }
  122. func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  123. peersString, err := parsePeers(perskeepalive, peers)
  124. listenPortString := ""
  125. if mtu <= 0 {
  126. mtu = 1280
  127. }
  128. if listenPort != "" {
  129. listenPortString += "ListenPort = " + listenPort
  130. }
  131. if err != nil {
  132. return "", err
  133. }
  134. config := fmt.Sprintf(`[Interface]
  135. Address = %s
  136. PrivateKey = %s
  137. MTU = %s
  138. %s
  139. %s
  140. `,
  141. address+"/32",
  142. privatekey,
  143. strconv.Itoa(int(mtu)),
  144. listenPortString,
  145. peersString)
  146. return config, nil
  147. }
  148. func GetLocalIP(localrange string) (string, error) {
  149. _, localRange, err := net.ParseCIDR(localrange)
  150. if err != nil {
  151. return "", err
  152. }
  153. ifaces, err := net.Interfaces()
  154. if err != nil {
  155. return "", err
  156. }
  157. var local string
  158. found := false
  159. for _, i := range ifaces {
  160. if i.Flags&net.FlagUp == 0 {
  161. continue // interface down
  162. }
  163. if i.Flags&net.FlagLoopback != 0 {
  164. continue // loopback interface
  165. }
  166. addrs, err := i.Addrs()
  167. if err != nil {
  168. return "", err
  169. }
  170. for _, addr := range addrs {
  171. var ip net.IP
  172. switch v := addr.(type) {
  173. case *net.IPNet:
  174. if !found {
  175. ip = v.IP
  176. local = ip.String()
  177. found = localRange.Contains(ip)
  178. }
  179. case *net.IPAddr:
  180. if !found {
  181. ip = v.IP
  182. local = ip.String()
  183. found = localRange.Contains(ip)
  184. }
  185. }
  186. }
  187. }
  188. if !found || local == "" {
  189. return "", errors.New("Failed to find local IP in range " + localrange)
  190. }
  191. return local, nil
  192. }
  193. func GetFreePort(rangestart int32) (int32, error) {
  194. if rangestart == 0 {
  195. rangestart = NETCLIENT_DEFAULT_PORT
  196. }
  197. wgclient, err := wgctrl.New()
  198. if err != nil {
  199. return 0, err
  200. }
  201. devices, err := wgclient.Devices()
  202. if err != nil {
  203. return 0, err
  204. }
  205. for x := rangestart; x <= 65535; x++ {
  206. conflict := false
  207. for _, i := range devices {
  208. if int32(i.ListenPort) == x {
  209. conflict = true
  210. break
  211. }
  212. }
  213. if conflict {
  214. continue
  215. }
  216. return int32(x), nil
  217. }
  218. return rangestart, err
  219. }
  220. // == OS PATH FUNCTIONS ==
  221. func GetHomeDirWindows() string {
  222. if IsWindows() {
  223. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  224. if home == "" {
  225. home = os.Getenv("USERPROFILE")
  226. }
  227. return home
  228. }
  229. return os.Getenv("HOME")
  230. }
  231. func GetNetclientPath() string {
  232. if IsWindows() {
  233. return WINDOWS_APP_DATA_PATH
  234. } else {
  235. return LINUX_APP_DATA_PATH
  236. }
  237. }
  238. func GetNetclientPathSpecific() string {
  239. if IsWindows() {
  240. return WINDOWS_APP_DATA_PATH + "\\"
  241. } else {
  242. return LINUX_APP_DATA_PATH + "/"
  243. }
  244. }
  245. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  246. var requestOpts grpc.DialOption
  247. requestOpts = grpc.WithInsecure()
  248. if isSecure == "on" {
  249. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  250. requestOpts = grpc.WithTransportCredentials(h2creds)
  251. }
  252. return requestOpts
  253. }