util.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. // Package util provides some common utility methods
  2. package util
  3. import (
  4. "bytes"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "html/template"
  16. "io"
  17. "io/fs"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "regexp"
  25. "runtime"
  26. "strings"
  27. "time"
  28. "github.com/google/uuid"
  29. "github.com/lithammer/shortuuid/v3"
  30. "github.com/rs/xid"
  31. "golang.org/x/crypto/ssh"
  32. "github.com/drakkan/sftpgo/v2/logger"
  33. )
  34. const (
  35. logSender = "util"
  36. osWindows = "windows"
  37. )
  38. var (
  39. emailRegex = regexp.MustCompile("^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
  40. // this can be set at build time
  41. additionalSharedDataSearchPath = ""
  42. )
  43. // Contains reports whether v is present in elems.
  44. func Contains[T comparable](elems []T, v T) bool {
  45. for _, s := range elems {
  46. if v == s {
  47. return true
  48. }
  49. }
  50. return false
  51. }
  52. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  53. // if a matching prefix is found
  54. func IsStringPrefixInSlice(obj string, list []string) bool {
  55. for i := 0; i < len(list); i++ {
  56. if strings.HasPrefix(obj, list[i]) {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  63. func RemoveDuplicates(obj []string, trim bool) []string {
  64. if len(obj) == 0 {
  65. return obj
  66. }
  67. seen := make(map[string]bool)
  68. validIdx := 0
  69. for _, item := range obj {
  70. if trim {
  71. item = strings.TrimSpace(item)
  72. }
  73. if !seen[item] {
  74. seen[item] = true
  75. obj[validIdx] = item
  76. validIdx++
  77. }
  78. }
  79. return obj[:validIdx]
  80. }
  81. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  82. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  83. return t.UnixMilli()
  84. }
  85. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  86. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  87. return time.Unix(0, msec*1000000)
  88. }
  89. // GetDurationAsString returns a string representation for a time.Duration
  90. func GetDurationAsString(d time.Duration) string {
  91. d = d.Round(time.Second)
  92. h := d / time.Hour
  93. d -= h * time.Hour
  94. m := d / time.Minute
  95. d -= m * time.Minute
  96. s := d / time.Second
  97. if h > 0 {
  98. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  99. }
  100. return fmt.Sprintf("%02d:%02d", m, s)
  101. }
  102. // ByteCountSI returns humanized size in SI (decimal) format
  103. func ByteCountSI(b int64) string {
  104. return byteCount(b, 1000)
  105. }
  106. // ByteCountIEC returns humanized size in IEC (binary) format
  107. func ByteCountIEC(b int64) string {
  108. return byteCount(b, 1024)
  109. }
  110. func byteCount(b int64, unit int64) string {
  111. if b < unit {
  112. return fmt.Sprintf("%d B", b)
  113. }
  114. div, exp := unit, 0
  115. for n := b / unit; n >= unit; n /= unit {
  116. div *= unit
  117. exp++
  118. }
  119. if unit == 1000 {
  120. return fmt.Sprintf("%.1f %cB",
  121. float64(b)/float64(div), "KMGTPE"[exp])
  122. }
  123. return fmt.Sprintf("%.1f %ciB",
  124. float64(b)/float64(div), "KMGTPE"[exp])
  125. }
  126. // GetIPFromRemoteAddress returns the IP from the remote address.
  127. // If the given remote address cannot be parsed it will be returned unchanged
  128. func GetIPFromRemoteAddress(remoteAddress string) string {
  129. ip, _, err := net.SplitHostPort(remoteAddress)
  130. if err == nil {
  131. return ip
  132. }
  133. return remoteAddress
  134. }
  135. // NilIfEmpty returns nil if the input string is empty
  136. func NilIfEmpty(s string) *string {
  137. if s == "" {
  138. return nil
  139. }
  140. return &s
  141. }
  142. // GetStringFromPointer returns the string value or empty if nil
  143. func GetStringFromPointer(val *string) string {
  144. if val == nil {
  145. return ""
  146. }
  147. return *val
  148. }
  149. // GetIntFromPointer returns the int value or zero
  150. func GetIntFromPointer(val *int64) int64 {
  151. if val == nil {
  152. return 0
  153. }
  154. return *val
  155. }
  156. // GetTimeFromPointer returns the time value or now
  157. func GetTimeFromPointer(val *time.Time) time.Time {
  158. if val == nil {
  159. return time.Now()
  160. }
  161. return *val
  162. }
  163. // GenerateRSAKeys generate rsa private and public keys and write the
  164. // private key to specified file and the public key to the specified
  165. // file adding the .pub suffix
  166. func GenerateRSAKeys(file string) error {
  167. if err := createDirPathIfMissing(file, 0700); err != nil {
  168. return err
  169. }
  170. key, err := rsa.GenerateKey(rand.Reader, 4096)
  171. if err != nil {
  172. return err
  173. }
  174. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  175. if err != nil {
  176. return err
  177. }
  178. defer o.Close()
  179. priv := &pem.Block{
  180. Type: "RSA PRIVATE KEY",
  181. Bytes: x509.MarshalPKCS1PrivateKey(key),
  182. }
  183. if err := pem.Encode(o, priv); err != nil {
  184. return err
  185. }
  186. pub, err := ssh.NewPublicKey(&key.PublicKey)
  187. if err != nil {
  188. return err
  189. }
  190. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  191. }
  192. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  193. // private key to specified file and the public key to the specified
  194. // file adding the .pub suffix
  195. func GenerateECDSAKeys(file string) error {
  196. if err := createDirPathIfMissing(file, 0700); err != nil {
  197. return err
  198. }
  199. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  200. if err != nil {
  201. return err
  202. }
  203. keyBytes, err := x509.MarshalECPrivateKey(key)
  204. if err != nil {
  205. return err
  206. }
  207. priv := &pem.Block{
  208. Type: "EC PRIVATE KEY",
  209. Bytes: keyBytes,
  210. }
  211. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  212. if err != nil {
  213. return err
  214. }
  215. defer o.Close()
  216. if err := pem.Encode(o, priv); err != nil {
  217. return err
  218. }
  219. pub, err := ssh.NewPublicKey(&key.PublicKey)
  220. if err != nil {
  221. return err
  222. }
  223. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  224. }
  225. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  226. // private key to specified file and the public key to the specified
  227. // file adding the .pub suffix
  228. func GenerateEd25519Keys(file string) error {
  229. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  230. if err != nil {
  231. return err
  232. }
  233. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  234. if err != nil {
  235. return err
  236. }
  237. priv := &pem.Block{
  238. Type: "PRIVATE KEY",
  239. Bytes: keyBytes,
  240. }
  241. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  242. if err != nil {
  243. return err
  244. }
  245. defer o.Close()
  246. if err := pem.Encode(o, priv); err != nil {
  247. return err
  248. }
  249. pub, err := ssh.NewPublicKey(pubKey)
  250. if err != nil {
  251. return err
  252. }
  253. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  254. }
  255. // GetDirsForVirtualPath returns all the directory for the given path in reverse order
  256. // for example if the path is: /1/2/3/4 it returns:
  257. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  258. func GetDirsForVirtualPath(virtualPath string) []string {
  259. if virtualPath == "" || virtualPath == "." {
  260. virtualPath = "/"
  261. } else {
  262. if !path.IsAbs(virtualPath) {
  263. virtualPath = CleanPath(virtualPath)
  264. }
  265. }
  266. dirsForPath := []string{virtualPath}
  267. for {
  268. if virtualPath == "/" {
  269. break
  270. }
  271. virtualPath = path.Dir(virtualPath)
  272. dirsForPath = append(dirsForPath, virtualPath)
  273. }
  274. return dirsForPath
  275. }
  276. // CleanPath returns a clean POSIX (/) absolute path to work with
  277. func CleanPath(p string) string {
  278. return CleanPathWithBase("/", p)
  279. }
  280. // CleanPathWithBase returns a clean POSIX (/) absolute path to work with.
  281. // The specified base will be used if the provided path is not absolute
  282. func CleanPathWithBase(base, p string) string {
  283. p = filepath.ToSlash(p)
  284. if !path.IsAbs(p) {
  285. p = path.Join(base, p)
  286. }
  287. return path.Clean(p)
  288. }
  289. // LoadTemplate parses the given template paths.
  290. // It behaves like template.Must but it writes a log before exiting.
  291. // You can optionally provide a base template (e.g. to define some custom functions)
  292. func LoadTemplate(base *template.Template, paths ...string) *template.Template {
  293. var t *template.Template
  294. var err error
  295. if base != nil {
  296. base, err = base.Clone()
  297. if err == nil {
  298. t, err = base.ParseFiles(paths...)
  299. }
  300. } else {
  301. t, err = template.ParseFiles(paths...)
  302. }
  303. if err != nil {
  304. logger.ErrorToConsole("error loading required template: %v", err)
  305. logger.Error(logSender, "", "error loading required template: %v", err)
  306. panic(err)
  307. }
  308. return t
  309. }
  310. // IsFileInputValid returns true this is a valid file name.
  311. // This method must be used before joining a file name, generally provided as
  312. // user input, with a directory
  313. func IsFileInputValid(fileInput string) bool {
  314. cleanInput := filepath.Clean(fileInput)
  315. if cleanInput == "." || cleanInput == ".." {
  316. return false
  317. }
  318. return true
  319. }
  320. // FindSharedDataPath searches for the specified directory name in searchDir
  321. // and in system-wide shared data directories.
  322. // If name is an absolute path it is returned unmodified.
  323. func FindSharedDataPath(name, searchDir string) string {
  324. if !IsFileInputValid(name) {
  325. return ""
  326. }
  327. if name != "" && !filepath.IsAbs(name) {
  328. searchList := []string{searchDir}
  329. if additionalSharedDataSearchPath != "" {
  330. searchList = append(searchList, additionalSharedDataSearchPath)
  331. }
  332. if runtime.GOOS != osWindows {
  333. searchList = append(searchList, "/usr/share/sftpgo")
  334. searchList = append(searchList, "/usr/local/share/sftpgo")
  335. }
  336. searchList = RemoveDuplicates(searchList, false)
  337. for _, basePath := range searchList {
  338. res := filepath.Join(basePath, name)
  339. _, err := os.Stat(res)
  340. if err == nil {
  341. logger.Debug(logSender, "", "found share data path for name %#v: %#v", name, res)
  342. return res
  343. }
  344. }
  345. return filepath.Join(searchDir, name)
  346. }
  347. return name
  348. }
  349. // CleanDirInput sanitizes user input for directories.
  350. // On Windows it removes any trailing `"`.
  351. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  352. // This will only help if the invalid path is the last argument, for example in this command:
  353. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  354. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  355. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  356. func CleanDirInput(dirInput string) string {
  357. if runtime.GOOS == osWindows {
  358. for strings.HasSuffix(dirInput, "\"") {
  359. dirInput = strings.TrimSuffix(dirInput, "\"")
  360. }
  361. }
  362. return filepath.Clean(dirInput)
  363. }
  364. func createDirPathIfMissing(file string, perm os.FileMode) error {
  365. dirPath := filepath.Dir(file)
  366. if _, err := os.Stat(dirPath); errors.Is(err, fs.ErrNotExist) {
  367. err = os.MkdirAll(dirPath, perm)
  368. if err != nil {
  369. return err
  370. }
  371. }
  372. return nil
  373. }
  374. // GenerateRandomBytes generates the secret to use for JWT auth
  375. func GenerateRandomBytes(length int) []byte {
  376. b := make([]byte, length)
  377. _, err := io.ReadFull(rand.Reader, b)
  378. if err == nil {
  379. return b
  380. }
  381. b = xid.New().Bytes()
  382. for len(b) < length {
  383. b = append(b, xid.New().Bytes()...)
  384. }
  385. return b[:length]
  386. }
  387. // GenerateUniqueID retuens an unique ID
  388. func GenerateUniqueID() string {
  389. u, err := uuid.NewRandom()
  390. if err != nil {
  391. return xid.New().String()
  392. }
  393. return shortuuid.DefaultEncoder.Encode(u)
  394. }
  395. // HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
  396. // and Unix-domain sockets
  397. func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
  398. var listener net.Listener
  399. var err error
  400. if filepath.IsAbs(address) && runtime.GOOS != osWindows {
  401. if !IsFileInputValid(address) {
  402. return fmt.Errorf("invalid socket address %#v", address)
  403. }
  404. err = createDirPathIfMissing(address, os.ModePerm)
  405. if err != nil {
  406. logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
  407. logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
  408. }
  409. os.Remove(address)
  410. listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
  411. } else {
  412. CheckTCP4Port(port)
  413. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  414. }
  415. if err != nil {
  416. return err
  417. }
  418. logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
  419. defer listener.Close()
  420. if isTLS {
  421. return srv.ServeTLS(listener, "", "")
  422. }
  423. return srv.Serve(listener)
  424. }
  425. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  426. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  427. var ciphers []uint16
  428. for _, name := range RemoveDuplicates(cipherNames, false) {
  429. for _, c := range tls.CipherSuites() {
  430. if c.Name == strings.TrimSpace(name) {
  431. ciphers = append(ciphers, c.ID)
  432. }
  433. }
  434. }
  435. return ciphers
  436. }
  437. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  438. // This can be verified using openssl x509 -in cert.crt -text -noout
  439. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  440. if len(tlsCert.Raw) == 0 {
  441. return "", errors.New("invalid x509 certificate, no der contents")
  442. }
  443. publicKeyBlock := pem.Block{
  444. Type: "CERTIFICATE",
  445. Bytes: tlsCert.Raw,
  446. }
  447. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  448. }
  449. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  450. // This is a ugly hack to avoid to bind on an already used port.
  451. // It is required on Windows only. Upstream does not consider this
  452. // behaviour a bug:
  453. // https://github.com/golang/go/issues/45150
  454. func CheckTCP4Port(port int) {
  455. if runtime.GOOS != osWindows {
  456. return
  457. }
  458. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  459. if err != nil {
  460. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  461. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  462. os.Exit(1)
  463. }
  464. listener.Close()
  465. }
  466. // IsByteArrayEmpty return true if the byte array is empty or a new line
  467. func IsByteArrayEmpty(b []byte) bool {
  468. if len(b) == 0 {
  469. return true
  470. }
  471. if bytes.Equal(b, []byte("\n")) {
  472. return true
  473. }
  474. if bytes.Equal(b, []byte("\r\n")) {
  475. return true
  476. }
  477. return false
  478. }
  479. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  480. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  481. if len(pubKey) == 0 {
  482. return "", nil
  483. }
  484. k, err := ssh.ParsePublicKey(pubKey)
  485. if err != nil {
  486. return "", err
  487. }
  488. return string(ssh.MarshalAuthorizedKey(k)), nil
  489. }
  490. // GetRealIP returns the ip address as result of parsing either the
  491. // X-Real-IP header or the X-Forwarded-For header
  492. func GetRealIP(r *http.Request, header string, depth int) string {
  493. if header == "" {
  494. return ""
  495. }
  496. var ipAddresses []string
  497. for _, h := range r.Header.Values(header) {
  498. for _, ipStr := range strings.Split(h, ",") {
  499. ipStr = strings.TrimSpace(ipStr)
  500. ipAddresses = append(ipAddresses, ipStr)
  501. }
  502. }
  503. idx := len(ipAddresses) - 1 - depth
  504. if idx >= 0 {
  505. ip := strings.TrimSpace(ipAddresses[idx])
  506. if ip == "" || net.ParseIP(ip) == nil {
  507. return ""
  508. }
  509. return ip
  510. }
  511. return ""
  512. }
  513. // GetHTTPLocalAddress returns the local address for an http.Request
  514. // or empty if it cannot be determined
  515. func GetHTTPLocalAddress(r *http.Request) string {
  516. if r == nil {
  517. return ""
  518. }
  519. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  520. if ok {
  521. return localAddr.String()
  522. }
  523. return ""
  524. }
  525. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  526. // IP is equal or is contained within the allowed list
  527. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  528. res := make([]func(net.IP) bool, len(allowed))
  529. for i, allowFrom := range allowed {
  530. if strings.LastIndex(allowFrom, "/") > 0 {
  531. _, ipRange, err := net.ParseCIDR(allowFrom)
  532. if err != nil {
  533. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  534. }
  535. res[i] = ipRange.Contains
  536. } else {
  537. allowed := net.ParseIP(allowFrom)
  538. if allowed == nil {
  539. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  540. }
  541. res[i] = allowed.Equal
  542. }
  543. }
  544. return res, nil
  545. }
  546. // GetRedactedURL returns the url redacting the password if any
  547. func GetRedactedURL(rawurl string) string {
  548. if !strings.HasPrefix(rawurl, "http") {
  549. return rawurl
  550. }
  551. u, err := url.Parse(rawurl)
  552. if err != nil {
  553. return rawurl
  554. }
  555. return u.Redacted()
  556. }
  557. // PrependFileInfo prepends a file info to a slice in an efficient way.
  558. // We, optimistically, assume that the slice has enough capacity
  559. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  560. files = append(files, nil)
  561. copy(files[1:], files)
  562. files[0] = info
  563. return files
  564. }
  565. // GetTLSVersion returns the TLS version for integer:
  566. // - 12 means TLS 1.2
  567. // - 13 means TLS 1.3
  568. // default is TLS 1.2
  569. func GetTLSVersion(val int) uint16 {
  570. switch val {
  571. case 13:
  572. return tls.VersionTLS13
  573. default:
  574. return tls.VersionTLS12
  575. }
  576. }
  577. // IsEmailValid returns true if the specified email address is valid
  578. func IsEmailValid(email string) bool {
  579. return emailRegex.MatchString(email)
  580. }