util.go 18 KB

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