util.go 17 KB

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