util.go 22 KB

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