netclientutils.go 5.0 KB

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