util.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. "io"
  29. "io/fs"
  30. "math"
  31. "net"
  32. "net/http"
  33. "net/url"
  34. "os"
  35. "path"
  36. "path/filepath"
  37. "regexp"
  38. "runtime"
  39. "strconv"
  40. "strings"
  41. "time"
  42. "unicode"
  43. "github.com/google/uuid"
  44. "github.com/lithammer/shortuuid/v3"
  45. "github.com/rs/xid"
  46. "golang.org/x/crypto/ssh"
  47. "github.com/drakkan/sftpgo/v2/internal/logger"
  48. )
  49. const (
  50. logSender = "util"
  51. osWindows = "windows"
  52. )
  53. var (
  54. 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}])))\\.?$")
  55. // this can be set at build time
  56. additionalSharedDataSearchPath = ""
  57. )
  58. // IEC Sizes.
  59. // kibis of bits
  60. const (
  61. oneByte = 1 << (iota * 10)
  62. kiByte
  63. miByte
  64. giByte
  65. tiByte
  66. piByte
  67. eiByte
  68. )
  69. // SI Sizes.
  70. const (
  71. iByte = 1
  72. kbByte = iByte * 1000
  73. mByte = kbByte * 1000
  74. gByte = mByte * 1000
  75. tByte = gByte * 1000
  76. pByte = tByte * 1000
  77. eByte = pByte * 1000
  78. )
  79. var bytesSizeTable = map[string]uint64{
  80. "b": oneByte,
  81. "kib": kiByte,
  82. "kb": kbByte,
  83. "mib": miByte,
  84. "mb": mByte,
  85. "gib": giByte,
  86. "gb": gByte,
  87. "tib": tiByte,
  88. "tb": tByte,
  89. "pib": piByte,
  90. "pb": pByte,
  91. "eib": eiByte,
  92. "eb": eByte,
  93. // Without suffix
  94. "": oneByte,
  95. "ki": kiByte,
  96. "k": kbByte,
  97. "mi": miByte,
  98. "m": mByte,
  99. "gi": giByte,
  100. "g": gByte,
  101. "ti": tiByte,
  102. "t": tByte,
  103. "pi": piByte,
  104. "p": pByte,
  105. "ei": eiByte,
  106. "e": eByte,
  107. }
  108. // Contains reports whether v is present in elems.
  109. func Contains[T comparable](elems []T, v T) bool {
  110. for _, s := range elems {
  111. if v == s {
  112. return true
  113. }
  114. }
  115. return false
  116. }
  117. // Remove removes an element from a string slice and
  118. // returns the modified slice
  119. func Remove(elems []string, val string) []string {
  120. for idx, v := range elems {
  121. if v == val {
  122. elems[idx] = elems[len(elems)-1]
  123. return elems[:len(elems)-1]
  124. }
  125. }
  126. return elems
  127. }
  128. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  129. // if a matching prefix is found
  130. func IsStringPrefixInSlice(obj string, list []string) bool {
  131. for i := 0; i < len(list); i++ {
  132. if strings.HasPrefix(obj, list[i]) {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // RemoveDuplicates returns a new slice removing any duplicate element from the initial one
  139. func RemoveDuplicates(obj []string, trim bool) []string {
  140. if len(obj) == 0 {
  141. return obj
  142. }
  143. seen := make(map[string]bool)
  144. validIdx := 0
  145. for _, item := range obj {
  146. if trim {
  147. item = strings.TrimSpace(item)
  148. }
  149. if !seen[item] {
  150. seen[item] = true
  151. obj[validIdx] = item
  152. validIdx++
  153. }
  154. }
  155. return obj[:validIdx]
  156. }
  157. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  158. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  159. return t.UnixMilli()
  160. }
  161. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  162. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  163. return time.Unix(0, msec*1000000)
  164. }
  165. // GetDurationAsString returns a string representation for a time.Duration
  166. func GetDurationAsString(d time.Duration) string {
  167. d = d.Round(time.Second)
  168. h := d / time.Hour
  169. d -= h * time.Hour
  170. m := d / time.Minute
  171. d -= m * time.Minute
  172. s := d / time.Second
  173. if h > 0 {
  174. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  175. }
  176. return fmt.Sprintf("%02d:%02d", m, s)
  177. }
  178. // ByteCountSI returns humanized size in SI (decimal) format
  179. func ByteCountSI(b int64) string {
  180. return byteCount(b, 1000, true)
  181. }
  182. // ByteCountIEC returns humanized size in IEC (binary) format
  183. func ByteCountIEC(b int64) string {
  184. return byteCount(b, 1024, false)
  185. }
  186. func byteCount(b int64, unit int64, maxPrecision bool) string {
  187. if b <= 0 && maxPrecision {
  188. return strconv.FormatInt(b, 10)
  189. }
  190. if b < unit {
  191. return fmt.Sprintf("%d B", b)
  192. }
  193. div, exp := unit, 0
  194. for n := b / unit; n >= unit; n /= unit {
  195. div *= unit
  196. exp++
  197. }
  198. var val string
  199. if maxPrecision {
  200. val = strconv.FormatFloat(float64(b)/float64(div), 'f', -1, 64)
  201. } else {
  202. val = fmt.Sprintf("%.1f", float64(b)/float64(div))
  203. }
  204. if unit == 1000 {
  205. return fmt.Sprintf("%s %cB", val, "KMGTPE"[exp])
  206. }
  207. return fmt.Sprintf("%s %ciB", val, "KMGTPE"[exp])
  208. }
  209. // ParseBytes parses a string representation of bytes into the number
  210. // of bytes it represents.
  211. //
  212. // ParseBytes("42 MB") -> 42000000, nil
  213. // ParseBytes("42 mib") -> 44040192, nil
  214. //
  215. // copied from here:
  216. //
  217. // https://github.com/dustin/go-humanize/blob/master/bytes.go
  218. //
  219. // with minor modifications
  220. func ParseBytes(s string) (int64, error) {
  221. s = strings.TrimSpace(s)
  222. lastDigit := 0
  223. hasComma := false
  224. for _, r := range s {
  225. if !(unicode.IsDigit(r) || r == '.' || r == ',') {
  226. break
  227. }
  228. if r == ',' {
  229. hasComma = true
  230. }
  231. lastDigit++
  232. }
  233. num := s[:lastDigit]
  234. if hasComma {
  235. num = strings.Replace(num, ",", "", -1)
  236. }
  237. f, err := strconv.ParseFloat(num, 64)
  238. if err != nil {
  239. return 0, err
  240. }
  241. extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
  242. if m, ok := bytesSizeTable[extra]; ok {
  243. f *= float64(m)
  244. if f >= math.MaxInt64 {
  245. return 0, fmt.Errorf("value too large: %v", s)
  246. }
  247. if f < 0 {
  248. return 0, fmt.Errorf("negative value not allowed: %v", s)
  249. }
  250. return int64(f), nil
  251. }
  252. return 0, fmt.Errorf("unhandled size name: %v", extra)
  253. }
  254. // GetIPFromRemoteAddress returns the IP from the remote address.
  255. // If the given remote address cannot be parsed it will be returned unchanged
  256. func GetIPFromRemoteAddress(remoteAddress string) string {
  257. ip, _, err := net.SplitHostPort(remoteAddress)
  258. if err == nil {
  259. return ip
  260. }
  261. return remoteAddress
  262. }
  263. // NilIfEmpty returns nil if the input string is empty
  264. func NilIfEmpty(s string) *string {
  265. if s == "" {
  266. return nil
  267. }
  268. return &s
  269. }
  270. // GetStringFromPointer returns the string value or empty if nil
  271. func GetStringFromPointer(val *string) string {
  272. if val == nil {
  273. return ""
  274. }
  275. return *val
  276. }
  277. // GetIntFromPointer returns the int value or zero
  278. func GetIntFromPointer(val *int64) int64 {
  279. if val == nil {
  280. return 0
  281. }
  282. return *val
  283. }
  284. // GetTimeFromPointer returns the time value or now
  285. func GetTimeFromPointer(val *time.Time) time.Time {
  286. if val == nil {
  287. return time.Unix(0, 0)
  288. }
  289. return *val
  290. }
  291. // GenerateRSAKeys generate rsa private and public keys and write the
  292. // private key to specified file and the public key to the specified
  293. // file adding the .pub suffix
  294. func GenerateRSAKeys(file string) error {
  295. if err := createDirPathIfMissing(file, 0700); err != nil {
  296. return err
  297. }
  298. key, err := rsa.GenerateKey(rand.Reader, 4096)
  299. if err != nil {
  300. return err
  301. }
  302. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  303. if err != nil {
  304. return err
  305. }
  306. defer o.Close()
  307. priv := &pem.Block{
  308. Type: "RSA PRIVATE KEY",
  309. Bytes: x509.MarshalPKCS1PrivateKey(key),
  310. }
  311. if err := pem.Encode(o, priv); err != nil {
  312. return err
  313. }
  314. pub, err := ssh.NewPublicKey(&key.PublicKey)
  315. if err != nil {
  316. return err
  317. }
  318. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  319. }
  320. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  321. // private key to specified file and the public key to the specified
  322. // file adding the .pub suffix
  323. func GenerateECDSAKeys(file string) error {
  324. if err := createDirPathIfMissing(file, 0700); err != nil {
  325. return err
  326. }
  327. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  328. if err != nil {
  329. return err
  330. }
  331. keyBytes, err := x509.MarshalECPrivateKey(key)
  332. if err != nil {
  333. return err
  334. }
  335. priv := &pem.Block{
  336. Type: "EC PRIVATE KEY",
  337. Bytes: keyBytes,
  338. }
  339. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  340. if err != nil {
  341. return err
  342. }
  343. defer o.Close()
  344. if err := pem.Encode(o, priv); err != nil {
  345. return err
  346. }
  347. pub, err := ssh.NewPublicKey(&key.PublicKey)
  348. if err != nil {
  349. return err
  350. }
  351. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  352. }
  353. // GenerateEd25519Keys generate ed25519 private and public keys and write the
  354. // private key to specified file and the public key to the specified
  355. // file adding the .pub suffix
  356. func GenerateEd25519Keys(file string) error {
  357. pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
  358. if err != nil {
  359. return err
  360. }
  361. keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
  362. if err != nil {
  363. return err
  364. }
  365. priv := &pem.Block{
  366. Type: "PRIVATE KEY",
  367. Bytes: keyBytes,
  368. }
  369. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  370. if err != nil {
  371. return err
  372. }
  373. defer o.Close()
  374. if err := pem.Encode(o, priv); err != nil {
  375. return err
  376. }
  377. pub, err := ssh.NewPublicKey(pubKey)
  378. if err != nil {
  379. return err
  380. }
  381. return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  382. }
  383. // GetDirsForVirtualPath returns all the directory for the given path in reverse order
  384. // for example if the path is: /1/2/3/4 it returns:
  385. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  386. func GetDirsForVirtualPath(virtualPath string) []string {
  387. if virtualPath == "" || virtualPath == "." {
  388. virtualPath = "/"
  389. } else {
  390. if !path.IsAbs(virtualPath) {
  391. virtualPath = CleanPath(virtualPath)
  392. }
  393. }
  394. dirsForPath := []string{virtualPath}
  395. for {
  396. if virtualPath == "/" {
  397. break
  398. }
  399. virtualPath = path.Dir(virtualPath)
  400. dirsForPath = append(dirsForPath, virtualPath)
  401. }
  402. return dirsForPath
  403. }
  404. // CleanPath returns a clean POSIX (/) absolute path to work with
  405. func CleanPath(p string) string {
  406. return CleanPathWithBase("/", p)
  407. }
  408. // CleanPathWithBase returns a clean POSIX (/) absolute path to work with.
  409. // The specified base will be used if the provided path is not absolute
  410. func CleanPathWithBase(base, p string) string {
  411. p = filepath.ToSlash(p)
  412. if !path.IsAbs(p) {
  413. p = path.Join(base, p)
  414. }
  415. return path.Clean(p)
  416. }
  417. // IsFileInputValid returns true this is a valid file name.
  418. // This method must be used before joining a file name, generally provided as
  419. // user input, with a directory
  420. func IsFileInputValid(fileInput string) bool {
  421. cleanInput := filepath.Clean(fileInput)
  422. if cleanInput == "." || cleanInput == ".." {
  423. return false
  424. }
  425. return true
  426. }
  427. // CleanDirInput sanitizes user input for directories.
  428. // On Windows it removes any trailing `"`.
  429. // We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
  430. // This will only help if the invalid path is the last argument, for example in this command:
  431. // sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
  432. // the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
  433. // since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
  434. func CleanDirInput(dirInput string) string {
  435. if runtime.GOOS == osWindows {
  436. for strings.HasSuffix(dirInput, "\"") {
  437. dirInput = strings.TrimSuffix(dirInput, "\"")
  438. }
  439. }
  440. return filepath.Clean(dirInput)
  441. }
  442. func createDirPathIfMissing(file string, perm os.FileMode) error {
  443. dirPath := filepath.Dir(file)
  444. if _, err := os.Stat(dirPath); errors.Is(err, fs.ErrNotExist) {
  445. err = os.MkdirAll(dirPath, perm)
  446. if err != nil {
  447. return err
  448. }
  449. }
  450. return nil
  451. }
  452. // GenerateRandomBytes generates the secret to use for JWT auth
  453. func GenerateRandomBytes(length int) []byte {
  454. b := make([]byte, length)
  455. _, err := io.ReadFull(rand.Reader, b)
  456. if err == nil {
  457. return b
  458. }
  459. b = xid.New().Bytes()
  460. for len(b) < length {
  461. b = append(b, xid.New().Bytes()...)
  462. }
  463. return b[:length]
  464. }
  465. // GenerateUniqueID retuens an unique ID
  466. func GenerateUniqueID() string {
  467. u, err := uuid.NewRandom()
  468. if err != nil {
  469. return xid.New().String()
  470. }
  471. return shortuuid.DefaultEncoder.Encode(u)
  472. }
  473. // HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
  474. // and Unix-domain sockets
  475. func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
  476. var listener net.Listener
  477. var err error
  478. if filepath.IsAbs(address) && runtime.GOOS != osWindows {
  479. if !IsFileInputValid(address) {
  480. return fmt.Errorf("invalid socket address %#v", address)
  481. }
  482. err = createDirPathIfMissing(address, os.ModePerm)
  483. if err != nil {
  484. logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
  485. logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
  486. }
  487. os.Remove(address)
  488. listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
  489. } else {
  490. CheckTCP4Port(port)
  491. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  492. }
  493. if err != nil {
  494. return err
  495. }
  496. logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
  497. defer listener.Close()
  498. if isTLS {
  499. return srv.ServeTLS(listener, "", "")
  500. }
  501. return srv.Serve(listener)
  502. }
  503. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  504. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  505. var ciphers []uint16
  506. for _, name := range RemoveDuplicates(cipherNames, false) {
  507. for _, c := range tls.CipherSuites() {
  508. if c.Name == strings.TrimSpace(name) {
  509. ciphers = append(ciphers, c.ID)
  510. }
  511. }
  512. }
  513. return ciphers
  514. }
  515. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  516. // This can be verified using openssl x509 -in cert.crt -text -noout
  517. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  518. if len(tlsCert.Raw) == 0 {
  519. return "", errors.New("invalid x509 certificate, no der contents")
  520. }
  521. publicKeyBlock := pem.Block{
  522. Type: "CERTIFICATE",
  523. Bytes: tlsCert.Raw,
  524. }
  525. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  526. }
  527. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  528. // This is a ugly hack to avoid to bind on an already used port.
  529. // It is required on Windows only. Upstream does not consider this
  530. // behaviour a bug:
  531. // https://github.com/golang/go/issues/45150
  532. func CheckTCP4Port(port int) {
  533. if runtime.GOOS != osWindows {
  534. return
  535. }
  536. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  537. if err != nil {
  538. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  539. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  540. os.Exit(1)
  541. }
  542. listener.Close()
  543. }
  544. // IsByteArrayEmpty return true if the byte array is empty or a new line
  545. func IsByteArrayEmpty(b []byte) bool {
  546. if len(b) == 0 {
  547. return true
  548. }
  549. if bytes.Equal(b, []byte("\n")) {
  550. return true
  551. }
  552. if bytes.Equal(b, []byte("\r\n")) {
  553. return true
  554. }
  555. return false
  556. }
  557. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  558. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  559. if len(pubKey) == 0 {
  560. return "", nil
  561. }
  562. k, err := ssh.ParsePublicKey(pubKey)
  563. if err != nil {
  564. return "", err
  565. }
  566. return string(ssh.MarshalAuthorizedKey(k)), nil
  567. }
  568. // GetRealIP returns the ip address as result of parsing either the
  569. // X-Real-IP header or the X-Forwarded-For header
  570. func GetRealIP(r *http.Request, header string, depth int) string {
  571. if header == "" {
  572. return ""
  573. }
  574. var ipAddresses []string
  575. for _, h := range r.Header.Values(header) {
  576. for _, ipStr := range strings.Split(h, ",") {
  577. ipStr = strings.TrimSpace(ipStr)
  578. ipAddresses = append(ipAddresses, ipStr)
  579. }
  580. }
  581. idx := len(ipAddresses) - 1 - depth
  582. if idx >= 0 {
  583. ip := strings.TrimSpace(ipAddresses[idx])
  584. if ip == "" || net.ParseIP(ip) == nil {
  585. return ""
  586. }
  587. return ip
  588. }
  589. return ""
  590. }
  591. // GetHTTPLocalAddress returns the local address for an http.Request
  592. // or empty if it cannot be determined
  593. func GetHTTPLocalAddress(r *http.Request) string {
  594. if r == nil {
  595. return ""
  596. }
  597. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  598. if ok {
  599. return localAddr.String()
  600. }
  601. return ""
  602. }
  603. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  604. // IP is equal or is contained within the allowed list
  605. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  606. res := make([]func(net.IP) bool, len(allowed))
  607. for i, allowFrom := range allowed {
  608. if strings.LastIndex(allowFrom, "/") > 0 {
  609. _, ipRange, err := net.ParseCIDR(allowFrom)
  610. if err != nil {
  611. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  612. }
  613. res[i] = ipRange.Contains
  614. } else {
  615. allowed := net.ParseIP(allowFrom)
  616. if allowed == nil {
  617. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  618. }
  619. res[i] = allowed.Equal
  620. }
  621. }
  622. return res, nil
  623. }
  624. // GetRedactedURL returns the url redacting the password if any
  625. func GetRedactedURL(rawurl string) string {
  626. if !strings.HasPrefix(rawurl, "http") {
  627. return rawurl
  628. }
  629. u, err := url.Parse(rawurl)
  630. if err != nil {
  631. return rawurl
  632. }
  633. return u.Redacted()
  634. }
  635. // PrependFileInfo prepends a file info to a slice in an efficient way.
  636. // We, optimistically, assume that the slice has enough capacity
  637. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  638. files = append(files, nil)
  639. copy(files[1:], files)
  640. files[0] = info
  641. return files
  642. }
  643. // GetTLSVersion returns the TLS version for integer:
  644. // - 12 means TLS 1.2
  645. // - 13 means TLS 1.3
  646. // default is TLS 1.2
  647. func GetTLSVersion(val int) uint16 {
  648. switch val {
  649. case 13:
  650. return tls.VersionTLS13
  651. default:
  652. return tls.VersionTLS12
  653. }
  654. }
  655. // IsEmailValid returns true if the specified email address is valid
  656. func IsEmailValid(email string) bool {
  657. return emailRegex.MatchString(email)
  658. }
  659. // PanicOnError calls panic if err is not nil
  660. func PanicOnError(err error) {
  661. if err != nil {
  662. panic(fmt.Errorf("unexpected error: %w", err))
  663. }
  664. }
  665. // GetAbsolutePath returns an absolute path using the current dir as base
  666. // if name defines a relative path
  667. func GetAbsolutePath(name string) (string, error) {
  668. if name == "" {
  669. return name, errors.New("input path cannot be empty")
  670. }
  671. if filepath.IsAbs(name) {
  672. return name, nil
  673. }
  674. curDir, err := os.Getwd()
  675. if err != nil {
  676. return name, err
  677. }
  678. return filepath.Join(curDir, name), nil
  679. }