util.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package lib
  2. import (
  3. "encoding/base64"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "regexp"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. )
  14. const (
  15. COMPRESS_NONE_ENCODE = iota
  16. COMPRESS_NONE_DECODE
  17. COMPRESS_SNAPY_ENCODE
  18. COMPRESS_SNAPY_DECODE
  19. VERIFY_EER = "vkey"
  20. WORK_MAIN = "main"
  21. WORK_CHAN = "chan"
  22. RES_SIGN = "sign"
  23. RES_MSG = "msg0"
  24. RES_CLOSE = "clse"
  25. NEW_CONN = "conn" //新连接标志
  26. CONN_SUCCESS = "sucs"
  27. CONN_TCP = "tcp"
  28. CONN_UDP = "udp"
  29. UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
  30. Content-Type: text/plain; charset=utf-8
  31. WWW-Authenticate: Basic realm="easyProxy"
  32. 401 Unauthorized`
  33. IO_EOF = "PROXYEOF"
  34. ConnectionFailBytes = `HTTP/1.1 404 Not Found
  35. `
  36. )
  37. //判断压缩方式
  38. func GetCompressType(compress string) (int, int) {
  39. switch compress {
  40. case "":
  41. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  42. case "snappy":
  43. return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
  44. default:
  45. Fatalln("数据压缩格式错误")
  46. }
  47. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  48. }
  49. //通过host获取对应的ip地址
  50. func GetHostByName(hostname string) string {
  51. if !DomainCheck(hostname) {
  52. return hostname
  53. }
  54. ips, _ := net.LookupIP(hostname)
  55. if ips != nil {
  56. for _, v := range ips {
  57. if v.To4() != nil {
  58. return v.String()
  59. }
  60. }
  61. }
  62. return ""
  63. }
  64. //检查是否是域名
  65. func DomainCheck(domain string) bool {
  66. var match bool
  67. IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
  68. NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
  69. match, _ = regexp.MatchString(IsLine, domain)
  70. if !match {
  71. match, _ = regexp.MatchString(NotLine, domain)
  72. }
  73. return match
  74. }
  75. //检查basic认证
  76. func CheckAuth(r *http.Request, user, passwd string) bool {
  77. s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
  78. if len(s) != 2 {
  79. return false
  80. }
  81. b, err := base64.StdEncoding.DecodeString(s[1])
  82. if err != nil {
  83. return false
  84. }
  85. pair := strings.SplitN(string(b), ":", 2)
  86. if len(pair) != 2 {
  87. return false
  88. }
  89. return pair[0] == user && pair[1] == passwd
  90. }
  91. //get bool by str
  92. func GetBoolByStr(s string) bool {
  93. switch s {
  94. case "1", "true":
  95. return true
  96. }
  97. return false
  98. }
  99. //get str by bool
  100. func GetStrByBool(b bool) string {
  101. if b {
  102. return "1"
  103. }
  104. return "0"
  105. }
  106. //int
  107. func GetIntNoErrByStr(str string) int {
  108. i, _ := strconv.Atoi(str)
  109. return i
  110. }
  111. //简单的一个校验值
  112. func Getverifyval(vkey string) string {
  113. return Md5(vkey)
  114. }
  115. func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
  116. if host != "" {
  117. r.Host = host
  118. }
  119. if header != "" {
  120. h := strings.Split(header, "\n")
  121. for _, v := range h {
  122. hd := strings.Split(v, ":")
  123. if len(hd) == 2 {
  124. r.Header.Set(hd[0], hd[1])
  125. }
  126. }
  127. }
  128. addr = strings.Split(addr, ":")[0]
  129. r.Header.Set("X-Forwarded-For", addr)
  130. r.Header.Set("X-Real-IP", addr)
  131. }
  132. func ReadAllFromFile(filePath string) ([]byte, error) {
  133. f, err := os.Open(filePath)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return ioutil.ReadAll(f)
  138. }
  139. // FileExists reports whether the named file or directory exists.
  140. func FileExists(name string) bool {
  141. if _, err := os.Stat(name); err != nil {
  142. if os.IsNotExist(err) {
  143. return false
  144. }
  145. }
  146. return true
  147. }
  148. func GetRunPath() string {
  149. var path string
  150. if path = GetInstallPath(); !FileExists(path) {
  151. return "./"
  152. }
  153. return path
  154. }
  155. func GetInstallPath() string {
  156. var path string
  157. if IsWindows() {
  158. path = `C:\Program Files\nps`
  159. } else {
  160. path = "/etc/nps"
  161. }
  162. return path
  163. }
  164. func GetAppPath() string {
  165. if path, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  166. return path
  167. }
  168. return os.Args[0]
  169. }
  170. func IsWindows() bool {
  171. if runtime.GOOS == "windows" {
  172. return true
  173. }
  174. return false
  175. }
  176. func GetLogPath() string {
  177. var path string
  178. if IsWindows() {
  179. path = "./"
  180. } else {
  181. path = "/tmp"
  182. }
  183. return path
  184. }
  185. func GetPidPath() string {
  186. var path string
  187. if IsWindows() {
  188. path = "./"
  189. } else {
  190. path = "/tmp"
  191. }
  192. return path
  193. }
  194. func TestTcpPort(port int) bool {
  195. l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
  196. defer l.Close()
  197. if err != nil {
  198. return false
  199. }
  200. return true
  201. }