util.go 25 KB

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