util.go 23 KB

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