util.go 24 KB

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