util.go 5.3 KB

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