util.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/binary"
  6. "github.com/cnlh/nps/lib/crypt"
  7. "github.com/cnlh/nps/lib/lg"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. )
  16. //Judging Compression Mode
  17. func GetCompressType(compress string) (int, int) {
  18. switch compress {
  19. case "":
  20. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  21. case "snappy":
  22. return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
  23. default:
  24. lg.Fatalln("数据压缩格式错误")
  25. }
  26. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  27. }
  28. //Get the corresponding IP address through domain name
  29. func GetHostByName(hostname string) string {
  30. if !DomainCheck(hostname) {
  31. return hostname
  32. }
  33. ips, _ := net.LookupIP(hostname)
  34. if ips != nil {
  35. for _, v := range ips {
  36. if v.To4() != nil {
  37. return v.String()
  38. }
  39. }
  40. }
  41. return ""
  42. }
  43. //Check the legality of domain
  44. func DomainCheck(domain string) bool {
  45. var match bool
  46. IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
  47. NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
  48. match, _ = regexp.MatchString(IsLine, domain)
  49. if !match {
  50. match, _ = regexp.MatchString(NotLine, domain)
  51. }
  52. return match
  53. }
  54. //Check if the Request request is validated
  55. func CheckAuth(r *http.Request, user, passwd string) bool {
  56. s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
  57. if len(s) != 2 {
  58. return false
  59. }
  60. b, err := base64.StdEncoding.DecodeString(s[1])
  61. if err != nil {
  62. return false
  63. }
  64. pair := strings.SplitN(string(b), ":", 2)
  65. if len(pair) != 2 {
  66. return false
  67. }
  68. return pair[0] == user && pair[1] == passwd
  69. }
  70. //get bool by str
  71. func GetBoolByStr(s string) bool {
  72. switch s {
  73. case "1", "true":
  74. return true
  75. }
  76. return false
  77. }
  78. //get str by bool
  79. func GetStrByBool(b bool) string {
  80. if b {
  81. return "1"
  82. }
  83. return "0"
  84. }
  85. //int
  86. func GetIntNoErrByStr(str string) int {
  87. i, _ := strconv.Atoi(str)
  88. return i
  89. }
  90. //Get verify value
  91. func Getverifyval(vkey string) string {
  92. return crypt.Md5(vkey)
  93. }
  94. //Change headers and host of request
  95. func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
  96. if host != "" {
  97. r.Host = host
  98. }
  99. if header != "" {
  100. h := strings.Split(header, "\n")
  101. for _, v := range h {
  102. hd := strings.Split(v, ":")
  103. if len(hd) == 2 {
  104. r.Header.Set(hd[0], hd[1])
  105. }
  106. }
  107. }
  108. addr = strings.Split(addr, ":")[0]
  109. r.Header.Set("X-Forwarded-For", addr)
  110. r.Header.Set("X-Real-IP", addr)
  111. }
  112. //Read file content by file path
  113. func ReadAllFromFile(filePath string) ([]byte, error) {
  114. f, err := os.Open(filePath)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return ioutil.ReadAll(f)
  119. }
  120. // FileExists reports whether the named file or directory exists.
  121. func FileExists(name string) bool {
  122. if _, err := os.Stat(name); err != nil {
  123. if os.IsNotExist(err) {
  124. return false
  125. }
  126. }
  127. return true
  128. }
  129. //Judge whether the TCP port can open normally
  130. func TestTcpPort(port int) bool {
  131. l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
  132. defer func() {
  133. if l != nil {
  134. l.Close()
  135. }
  136. }()
  137. if err != nil {
  138. return false
  139. }
  140. return true
  141. }
  142. //Judge whether the UDP port can open normally
  143. func TestUdpPort(port int) bool {
  144. l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
  145. defer func() {
  146. if l != nil {
  147. l.Close()
  148. }
  149. }()
  150. if err != nil {
  151. return false
  152. }
  153. return true
  154. }
  155. //Write length and individual byte data
  156. //Length prevents sticking
  157. //# Characters are used to separate data
  158. func BinaryWrite(raw *bytes.Buffer, v ...string) {
  159. buffer := new(bytes.Buffer)
  160. var l int32
  161. for _, v := range v {
  162. l += int32(len([]byte(v))) + int32(len([]byte(CONN_DATA_SEQ)))
  163. binary.Write(buffer, binary.LittleEndian, []byte(v))
  164. binary.Write(buffer, binary.LittleEndian, []byte(CONN_DATA_SEQ))
  165. }
  166. binary.Write(raw, binary.LittleEndian, l)
  167. binary.Write(raw, binary.LittleEndian, buffer.Bytes())
  168. }
  169. func InArr(arr []string, val string) bool {
  170. for _, v := range arr {
  171. if v == val {
  172. return true
  173. }
  174. }
  175. return false
  176. }
  177. func InIntArr(arr []int, val int) bool {
  178. for _, v := range arr {
  179. if v == val {
  180. return true
  181. }
  182. }
  183. return false
  184. }
  185. func GetPorts(p string) []int {
  186. var ps []int
  187. arr := strings.Split(p, ",")
  188. for _, v := range arr {
  189. fw := strings.Split(v, "-")
  190. if len(fw) == 2 {
  191. if IsPort(fw[0]) && IsPort(fw[1]) {
  192. start, _ := strconv.Atoi(fw[0])
  193. end, _ := strconv.Atoi(fw[1])
  194. for i := start; i <= end; i++ {
  195. ps = append(ps, i)
  196. }
  197. } else {
  198. continue
  199. }
  200. } else if IsPort(v) {
  201. p, _ := strconv.Atoi(v)
  202. ps = append(ps, p)
  203. }
  204. }
  205. return ps
  206. }
  207. func IsPort(p string) bool {
  208. pi, err := strconv.Atoi(p)
  209. if err != nil {
  210. return false
  211. }
  212. if pi > 65536 || pi < 1 {
  213. return false
  214. }
  215. return true
  216. }
  217. func FormatAddress(s string) string {
  218. if strings.Contains(s, ":") {
  219. return s
  220. }
  221. return "127.0.0.1:" + s
  222. }
  223. func GetIpByAddr(addr string) string {
  224. arr := strings.Split(addr, ":")
  225. return arr[0]
  226. }