net.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package util
  17. import (
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/88250/gulu"
  25. "github.com/88250/lute/ast"
  26. "github.com/gin-gonic/gin"
  27. "github.com/imroc/req/v3"
  28. "github.com/siyuan-note/httpclient"
  29. "github.com/siyuan-note/logging"
  30. )
  31. func ValidOptionalPort(port string) bool {
  32. if port == "" {
  33. return true
  34. }
  35. if port[0] != ':' {
  36. return false
  37. }
  38. for _, b := range port[1:] {
  39. if b < '0' || b > '9' {
  40. return false
  41. }
  42. }
  43. return true
  44. }
  45. func IsLocalHostname(hostname string) bool {
  46. if "localhost" == hostname || strings.HasSuffix(hostname, ".localhost") {
  47. return true
  48. }
  49. if ip := net.ParseIP(hostname); nil != ip {
  50. return ip.IsLoopback()
  51. }
  52. return false
  53. }
  54. func IsLocalHost(host string) bool {
  55. if hostname, _, err := net.SplitHostPort(strings.TrimSpace(host)); nil != err {
  56. return false
  57. } else {
  58. return IsLocalHostname(hostname)
  59. }
  60. }
  61. func IsLocalOrigin(origin string) bool {
  62. if url, err := url.Parse(origin); nil == err {
  63. return IsLocalHostname(url.Hostname())
  64. }
  65. return false
  66. }
  67. func IsOnline(checkURL string, skipTlsVerify bool) bool {
  68. _, err := url.Parse(checkURL)
  69. if nil != err {
  70. logging.LogWarnf("invalid check URL [%s]", checkURL)
  71. return false
  72. }
  73. if "" == checkURL {
  74. return false
  75. }
  76. if isOnline(checkURL, skipTlsVerify) {
  77. return true
  78. }
  79. logging.LogWarnf("network is offline [checkURL=%s]", checkURL)
  80. return false
  81. }
  82. func IsPortOpen(port string) bool {
  83. timeout := time.Second
  84. conn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", port), timeout)
  85. if nil != err {
  86. return false
  87. }
  88. if nil != conn {
  89. conn.Close()
  90. return true
  91. }
  92. return false
  93. }
  94. func isOnline(checkURL string, skipTlsVerify bool) (ret bool) {
  95. c := req.C().SetTimeout(3 * time.Second)
  96. if skipTlsVerify {
  97. c.EnableInsecureSkipVerify()
  98. }
  99. c.SetUserAgent(UserAgent)
  100. for i := 0; i < 2; i++ {
  101. resp, err := c.R().Get(checkURL)
  102. if resp.GetHeader("Location") != "" {
  103. return true
  104. }
  105. switch err.(type) {
  106. case *url.Error:
  107. if err.(*url.Error).URL != checkURL {
  108. // DNS 重定向
  109. logging.LogWarnf("network is online [DNS redirect, checkURL=%s, retURL=%s]", checkURL, err.(*url.Error).URL)
  110. return true
  111. }
  112. }
  113. ret = nil == err
  114. if ret {
  115. break
  116. }
  117. time.Sleep(1 * time.Second)
  118. logging.LogWarnf("check url [%s] is online failed: %s", checkURL, err)
  119. }
  120. return
  121. }
  122. func GetRemoteAddr(req *http.Request) string {
  123. ret := req.Header.Get("X-forwarded-for")
  124. ret = strings.TrimSpace(ret)
  125. if "" == ret {
  126. ret = req.Header.Get("X-Real-IP")
  127. }
  128. ret = strings.TrimSpace(ret)
  129. if "" == ret {
  130. return req.RemoteAddr
  131. }
  132. return strings.Split(ret, ",")[0]
  133. }
  134. func JsonArg(c *gin.Context, result *gulu.Result) (arg map[string]interface{}, ok bool) {
  135. arg = map[string]interface{}{}
  136. if err := c.BindJSON(&arg); nil != err {
  137. result.Code = -1
  138. result.Msg = "parses request failed"
  139. return
  140. }
  141. ok = true
  142. return
  143. }
  144. func InvalidIDPattern(idArg string, result *gulu.Result) bool {
  145. if ast.IsNodeIDPattern(idArg) {
  146. return false
  147. }
  148. result.Code = -1
  149. result.Msg = "invalid ID argument"
  150. return true
  151. }
  152. func IsValidURL(str string) bool {
  153. _, err := url.Parse(str)
  154. return nil == err
  155. }
  156. func initHttpClient() {
  157. http.DefaultClient = httpclient.GetCloudFileClient2Min()
  158. http.DefaultTransport = httpclient.NewTransport(false)
  159. }
  160. func ParsePort(portString string) (uint16, error) {
  161. if port, err := strconv.ParseUint(portString, 10, 16); err != nil {
  162. logging.LogErrorf("parse port [%s] failed: %s", portString, err)
  163. return 0, err
  164. } else {
  165. return uint16(port), nil
  166. }
  167. }