util.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. // Copyright (C) 2019 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.Unix(0, 0)
  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, 0770)
  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. if err == nil {
  536. // should a chmod err be fatal?
  537. if errChmod := os.Chmod(address, 0770); errChmod != nil {
  538. logger.Warn(logSender, "", "unable to set the Unix-domain socket group writable: %v", errChmod)
  539. }
  540. }
  541. } else {
  542. CheckTCP4Port(port)
  543. listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
  544. }
  545. if err != nil {
  546. return err
  547. }
  548. logger.Info(logSender, "", "server listener registered, address: %s TLS enabled: %t", listener.Addr().String(), isTLS)
  549. defer listener.Close()
  550. if isTLS {
  551. return srv.ServeTLS(listener, "", "")
  552. }
  553. return srv.Serve(listener)
  554. }
  555. // GetTLSCiphersFromNames returns the TLS ciphers from the specified names
  556. func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
  557. var ciphers []uint16
  558. for _, name := range RemoveDuplicates(cipherNames, false) {
  559. for _, c := range tls.CipherSuites() {
  560. if c.Name == strings.TrimSpace(name) {
  561. ciphers = append(ciphers, c.ID)
  562. }
  563. }
  564. }
  565. if len(ciphers) == 0 {
  566. // return a secure default
  567. return defaultTLSCiphers
  568. }
  569. return ciphers
  570. }
  571. // GetALPNProtocols returns the ALPN protocols, any invalid protocol will be
  572. // silently ignored. If no protocol or no valid protocol is provided the default
  573. // is http/1.1, h2
  574. func GetALPNProtocols(protocols []string) []string {
  575. var result []string
  576. for _, p := range protocols {
  577. switch p {
  578. case "http/1.1", "h2":
  579. result = append(result, p)
  580. }
  581. }
  582. if len(result) == 0 {
  583. return []string{"http/1.1", "h2"}
  584. }
  585. return result
  586. }
  587. // EncodeTLSCertToPem returns the specified certificate PEM encoded.
  588. // This can be verified using openssl x509 -in cert.crt -text -noout
  589. func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
  590. if len(tlsCert.Raw) == 0 {
  591. return "", errors.New("invalid x509 certificate, no der contents")
  592. }
  593. publicKeyBlock := pem.Block{
  594. Type: "CERTIFICATE",
  595. Bytes: tlsCert.Raw,
  596. }
  597. return string(pem.EncodeToMemory(&publicKeyBlock)), nil
  598. }
  599. // CheckTCP4Port quits the app if bind on the given IPv4 port fails.
  600. // This is a ugly hack to avoid to bind on an already used port.
  601. // It is required on Windows only. Upstream does not consider this
  602. // behaviour a bug:
  603. // https://github.com/golang/go/issues/45150
  604. func CheckTCP4Port(port int) {
  605. if runtime.GOOS != osWindows {
  606. return
  607. }
  608. listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
  609. if err != nil {
  610. logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
  611. logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
  612. os.Exit(1)
  613. }
  614. listener.Close()
  615. }
  616. // IsByteArrayEmpty return true if the byte array is empty or a new line
  617. func IsByteArrayEmpty(b []byte) bool {
  618. if len(b) == 0 {
  619. return true
  620. }
  621. if bytes.Equal(b, []byte("\n")) {
  622. return true
  623. }
  624. if bytes.Equal(b, []byte("\r\n")) {
  625. return true
  626. }
  627. return false
  628. }
  629. // GetSSHPublicKeyAsString returns an SSH public key serialized as string
  630. func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
  631. if len(pubKey) == 0 {
  632. return "", nil
  633. }
  634. k, err := ssh.ParsePublicKey(pubKey)
  635. if err != nil {
  636. return "", err
  637. }
  638. return string(ssh.MarshalAuthorizedKey(k)), nil
  639. }
  640. // GetRealIP returns the ip address as result of parsing the specified
  641. // header and using the specified depth
  642. func GetRealIP(r *http.Request, header string, depth int) string {
  643. if header == "" {
  644. return ""
  645. }
  646. var ipAddresses []string
  647. for _, h := range r.Header.Values(header) {
  648. for _, ipStr := range strings.Split(h, ",") {
  649. ipStr = strings.TrimSpace(ipStr)
  650. ipAddresses = append(ipAddresses, ipStr)
  651. }
  652. }
  653. idx := len(ipAddresses) - 1 - depth
  654. if idx >= 0 {
  655. ip := strings.TrimSpace(ipAddresses[idx])
  656. if ip == "" || net.ParseIP(ip) == nil {
  657. return ""
  658. }
  659. return ip
  660. }
  661. return ""
  662. }
  663. // GetHTTPLocalAddress returns the local address for an http.Request
  664. // or empty if it cannot be determined
  665. func GetHTTPLocalAddress(r *http.Request) string {
  666. if r == nil {
  667. return ""
  668. }
  669. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  670. if ok {
  671. return localAddr.String()
  672. }
  673. return ""
  674. }
  675. // ParseAllowedIPAndRanges returns a list of functions that allow to find if an
  676. // IP is equal or is contained within the allowed list
  677. func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
  678. res := make([]func(net.IP) bool, len(allowed))
  679. for i, allowFrom := range allowed {
  680. if strings.LastIndex(allowFrom, "/") > 0 {
  681. _, ipRange, err := net.ParseCIDR(allowFrom)
  682. if err != nil {
  683. return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
  684. }
  685. res[i] = ipRange.Contains
  686. } else {
  687. allowed := net.ParseIP(allowFrom)
  688. if allowed == nil {
  689. return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
  690. }
  691. res[i] = allowed.Equal
  692. }
  693. }
  694. return res, nil
  695. }
  696. // GetRedactedURL returns the url redacting the password if any
  697. func GetRedactedURL(rawurl string) string {
  698. if !strings.HasPrefix(rawurl, "http") {
  699. return rawurl
  700. }
  701. u, err := url.Parse(rawurl)
  702. if err != nil {
  703. return rawurl
  704. }
  705. return u.Redacted()
  706. }
  707. // PrependFileInfo prepends a file info to a slice in an efficient way.
  708. // We, optimistically, assume that the slice has enough capacity
  709. func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
  710. files = append(files, nil)
  711. copy(files[1:], files)
  712. files[0] = info
  713. return files
  714. }
  715. // GetTLSVersion returns the TLS version for integer:
  716. // - 12 means TLS 1.2
  717. // - 13 means TLS 1.3
  718. // default is TLS 1.2
  719. func GetTLSVersion(val int) uint16 {
  720. switch val {
  721. case 13:
  722. return tls.VersionTLS13
  723. default:
  724. return tls.VersionTLS12
  725. }
  726. }
  727. // IsEmailValid returns true if the specified email address is valid
  728. func IsEmailValid(email string) bool {
  729. return emailRegex.MatchString(email)
  730. }
  731. // SanitizeDomain return the specified domain name in a form suitable to save as file
  732. func SanitizeDomain(domain string) string {
  733. return strings.NewReplacer(":", "_", "*", "_", ",", "_", " ", "_").Replace(domain)
  734. }
  735. // PanicOnError calls panic if err is not nil
  736. func PanicOnError(err error) {
  737. if err != nil {
  738. panic(fmt.Errorf("unexpected error: %w", err))
  739. }
  740. }
  741. // GetAbsolutePath returns an absolute path using the current dir as base
  742. // if name defines a relative path
  743. func GetAbsolutePath(name string) (string, error) {
  744. if name == "" {
  745. return name, errors.New("input path cannot be empty")
  746. }
  747. if filepath.IsAbs(name) {
  748. return name, nil
  749. }
  750. curDir, err := os.Getwd()
  751. if err != nil {
  752. return name, err
  753. }
  754. return filepath.Join(curDir, name), nil
  755. }
  756. // GetACMECertificateKeyPair returns the path to the ACME TLS crt and key for the specified domain
  757. func GetACMECertificateKeyPair(domain string) (string, string) {
  758. if CertsBasePath == "" {
  759. return "", ""
  760. }
  761. domain = SanitizeDomain(domain)
  762. return filepath.Join(CertsBasePath, domain+".crt"), filepath.Join(CertsBasePath, domain+".key")
  763. }
  764. // GetLastIPForPrefix returns the last IP for the given prefix
  765. // https://github.com/go4org/netipx/blob/8449b0a6169f5140fb0340cb4fc0de4c9b281ef6/netipx.go#L173
  766. func GetLastIPForPrefix(p netip.Prefix) netip.Addr {
  767. if !p.IsValid() {
  768. return netip.Addr{}
  769. }
  770. a16 := p.Addr().As16()
  771. var off uint8
  772. var bits uint8 = 128
  773. if p.Addr().Is4() {
  774. off = 12
  775. bits = 32
  776. }
  777. for b := uint8(p.Bits()); b < bits; b++ {
  778. byteNum, bitInByte := b/8, 7-(b%8)
  779. a16[off+byteNum] |= 1 << uint(bitInByte)
  780. }
  781. if p.Addr().Is4() {
  782. return netip.AddrFrom16(a16).Unmap()
  783. }
  784. return netip.AddrFrom16(a16) // doesn't unmap
  785. }
  786. // JSONEscape returns the JSON escaped format for the input string
  787. func JSONEscape(val string) string {
  788. if val == "" {
  789. return val
  790. }
  791. b, err := json.Marshal(val)
  792. if err != nil {
  793. return ""
  794. }
  795. return string(b[1 : len(b)-1])
  796. }
  797. // ReadConfigFromFile reads a configuration parameter from the specified file
  798. func ReadConfigFromFile(name, configDir string) (string, error) {
  799. if !IsFileInputValid(name) {
  800. return "", fmt.Errorf("invalid file input: %q", name)
  801. }
  802. if configDir == "" {
  803. if !filepath.IsAbs(name) {
  804. return "", fmt.Errorf("%q must be an absolute file path", name)
  805. }
  806. } else {
  807. if name != "" && !filepath.IsAbs(name) {
  808. name = filepath.Join(configDir, name)
  809. }
  810. }
  811. val, err := os.ReadFile(name)
  812. if err != nil {
  813. return "", err
  814. }
  815. return strings.TrimSpace(string(val)), nil
  816. }