config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/hex"
  5. "flag"
  6. "fmt"
  7. "math"
  8. "os"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. )
  13. func intEnvConfig(i *int, name string) {
  14. if env, err := strconv.Atoi(os.Getenv(name)); err == nil {
  15. *i = env
  16. }
  17. }
  18. func floatEnvConfig(i *float64, name string) {
  19. if env, err := strconv.ParseFloat(os.Getenv(name), 64); err == nil {
  20. *i = env
  21. }
  22. }
  23. func megaIntEnvConfig(f *int, name string) {
  24. if env, err := strconv.ParseFloat(os.Getenv(name), 64); err == nil {
  25. *f = int(env * 1000000)
  26. }
  27. }
  28. func strEnvConfig(s *string, name string) {
  29. if env := os.Getenv(name); len(env) > 0 {
  30. *s = env
  31. }
  32. }
  33. func strSliceEnvConfig(s *[]string, name string) {
  34. if env := os.Getenv(name); len(env) > 0 {
  35. parts := strings.Split(env, ",")
  36. for i, p := range parts {
  37. parts[i] = strings.TrimSpace(p)
  38. }
  39. *s = parts
  40. return
  41. }
  42. *s = []string{}
  43. }
  44. func boolEnvConfig(b *bool, name string) {
  45. if env, err := strconv.ParseBool(os.Getenv(name)); err == nil {
  46. *b = env
  47. }
  48. }
  49. func hexEnvConfig(b *[]securityKey, name string) error {
  50. var err error
  51. if env := os.Getenv(name); len(env) > 0 {
  52. parts := strings.Split(env, ",")
  53. keys := make([]securityKey, len(parts))
  54. for i, part := range parts {
  55. if keys[i], err = hex.DecodeString(part); err != nil {
  56. return fmt.Errorf("%s expected to be hex-encoded strings. Invalid: %s\n", name, part)
  57. }
  58. }
  59. *b = keys
  60. }
  61. return nil
  62. }
  63. func hexFileConfig(b *[]securityKey, filepath string) error {
  64. if len(filepath) == 0 {
  65. return nil
  66. }
  67. f, err := os.Open(filepath)
  68. if err != nil {
  69. return fmt.Errorf("Can't open file %s\n", filepath)
  70. }
  71. keys := []securityKey{}
  72. scanner := bufio.NewScanner(f)
  73. for scanner.Scan() {
  74. part := scanner.Text()
  75. if len(part) == 0 {
  76. continue
  77. }
  78. if key, err := hex.DecodeString(part); err == nil {
  79. keys = append(keys, key)
  80. } else {
  81. return fmt.Errorf("%s expected to contain hex-encoded strings. Invalid: %s\n", filepath, part)
  82. }
  83. }
  84. if err := scanner.Err(); err != nil {
  85. return fmt.Errorf("Failed to read file %s: %s", filepath, err)
  86. }
  87. *b = keys
  88. return nil
  89. }
  90. func presetEnvConfig(p presets, name string) error {
  91. if env := os.Getenv(name); len(env) > 0 {
  92. presetStrings := strings.Split(env, ",")
  93. for _, presetStr := range presetStrings {
  94. if err := parsePreset(p, presetStr); err != nil {
  95. return fmt.Errorf(err.Error())
  96. }
  97. }
  98. }
  99. return nil
  100. }
  101. func presetFileConfig(p presets, filepath string) error {
  102. if len(filepath) == 0 {
  103. return nil
  104. }
  105. f, err := os.Open(filepath)
  106. if err != nil {
  107. return fmt.Errorf("Can't open file %s\n", filepath)
  108. }
  109. scanner := bufio.NewScanner(f)
  110. for scanner.Scan() {
  111. if err := parsePreset(p, scanner.Text()); err != nil {
  112. return fmt.Errorf(err.Error())
  113. }
  114. }
  115. if err := scanner.Err(); err != nil {
  116. return fmt.Errorf("Failed to read presets file: %s", err)
  117. }
  118. return nil
  119. }
  120. type config struct {
  121. Network string
  122. Bind string
  123. ReadTimeout int
  124. WriteTimeout int
  125. KeepAliveTimeout int
  126. DownloadTimeout int
  127. Concurrency int
  128. MaxClients int
  129. TTL int
  130. CacheControlPassthrough bool
  131. SoReuseport bool
  132. MaxSrcDimension int
  133. MaxSrcResolution int
  134. MaxSrcFileSize int
  135. MaxAnimationFrames int
  136. MaxSvgCheckBytes int
  137. JpegProgressive bool
  138. PngInterlaced bool
  139. PngQuantize bool
  140. PngQuantizationColors int
  141. Quality int
  142. GZipCompression int
  143. StripMetadata bool
  144. EnableWebpDetection bool
  145. EnforceWebp bool
  146. EnableClientHints bool
  147. UseLinearColorspace bool
  148. DisableShrinkOnLoad bool
  149. Keys []securityKey
  150. Salts []securityKey
  151. AllowInsecure bool
  152. SignatureSize int
  153. Secret string
  154. AllowOrigin string
  155. UserAgent string
  156. IgnoreSslVerification bool
  157. DevelopmentErrorsMode bool
  158. AllowedSources []string
  159. LocalFileSystemRoot string
  160. S3Enabled bool
  161. S3Region string
  162. S3Endpoint string
  163. GCSEnabled bool
  164. GCSKey string
  165. ETagEnabled bool
  166. BaseURL string
  167. Presets presets
  168. OnlyPresets bool
  169. WatermarkData string
  170. WatermarkPath string
  171. WatermarkURL string
  172. WatermarkOpacity float64
  173. NewRelicAppName string
  174. NewRelicKey string
  175. PrometheusBind string
  176. BugsnagKey string
  177. BugsnagStage string
  178. HoneybadgerKey string
  179. HoneybadgerEnv string
  180. SentryDSN string
  181. SentryEnvironment string
  182. SentryRelease string
  183. ReportDownloadingErrors bool
  184. FreeMemoryInterval int
  185. DownloadBufferSize int
  186. GZipBufferSize int
  187. BufferPoolCalibrationThreshold int
  188. }
  189. var conf = config{
  190. Network: "tcp",
  191. Bind: ":8080",
  192. ReadTimeout: 10,
  193. WriteTimeout: 10,
  194. KeepAliveTimeout: 10,
  195. DownloadTimeout: 5,
  196. Concurrency: runtime.NumCPU() * 2,
  197. TTL: 3600,
  198. MaxSrcResolution: 16800000,
  199. MaxAnimationFrames: 1,
  200. MaxSvgCheckBytes: 32 * 1024,
  201. SignatureSize: 32,
  202. PngQuantizationColors: 256,
  203. Quality: 80,
  204. StripMetadata: true,
  205. UserAgent: fmt.Sprintf("imgproxy/%s", version),
  206. Presets: make(presets),
  207. WatermarkOpacity: 1,
  208. BugsnagStage: "production",
  209. HoneybadgerEnv: "production",
  210. SentryEnvironment: "production",
  211. SentryRelease: fmt.Sprintf("imgproxy/%s", version),
  212. ReportDownloadingErrors: true,
  213. FreeMemoryInterval: 10,
  214. BufferPoolCalibrationThreshold: 1024,
  215. }
  216. func configure() error {
  217. keyPath := flag.String("keypath", "", "path of the file with hex-encoded key")
  218. saltPath := flag.String("saltpath", "", "path of the file with hex-encoded salt")
  219. presetsPath := flag.String("presets", "", "path of the file with presets")
  220. flag.Parse()
  221. if port := os.Getenv("PORT"); len(port) > 0 {
  222. conf.Bind = fmt.Sprintf(":%s", port)
  223. }
  224. strEnvConfig(&conf.Network, "IMGPROXY_NETWORK")
  225. strEnvConfig(&conf.Bind, "IMGPROXY_BIND")
  226. intEnvConfig(&conf.ReadTimeout, "IMGPROXY_READ_TIMEOUT")
  227. intEnvConfig(&conf.WriteTimeout, "IMGPROXY_WRITE_TIMEOUT")
  228. intEnvConfig(&conf.KeepAliveTimeout, "IMGPROXY_KEEP_ALIVE_TIMEOUT")
  229. intEnvConfig(&conf.DownloadTimeout, "IMGPROXY_DOWNLOAD_TIMEOUT")
  230. intEnvConfig(&conf.Concurrency, "IMGPROXY_CONCURRENCY")
  231. intEnvConfig(&conf.MaxClients, "IMGPROXY_MAX_CLIENTS")
  232. intEnvConfig(&conf.TTL, "IMGPROXY_TTL")
  233. boolEnvConfig(&conf.CacheControlPassthrough, "IMGPROXY_CACHE_CONTROL_PASSTHROUGH")
  234. boolEnvConfig(&conf.SoReuseport, "IMGPROXY_SO_REUSEPORT")
  235. intEnvConfig(&conf.MaxSrcDimension, "IMGPROXY_MAX_SRC_DIMENSION")
  236. megaIntEnvConfig(&conf.MaxSrcResolution, "IMGPROXY_MAX_SRC_RESOLUTION")
  237. intEnvConfig(&conf.MaxSrcFileSize, "IMGPROXY_MAX_SRC_FILE_SIZE")
  238. intEnvConfig(&conf.MaxSvgCheckBytes, "IMGPROXY_MAX_SVG_CHECK_BYTES")
  239. if _, ok := os.LookupEnv("IMGPROXY_MAX_GIF_FRAMES"); ok {
  240. logWarning("`IMGPROXY_MAX_GIF_FRAMES` is deprecated and will be removed in future versions. Use `IMGPROXY_MAX_ANIMATION_FRAMES` instead")
  241. intEnvConfig(&conf.MaxAnimationFrames, "IMGPROXY_MAX_GIF_FRAMES")
  242. }
  243. intEnvConfig(&conf.MaxAnimationFrames, "IMGPROXY_MAX_ANIMATION_FRAMES")
  244. strSliceEnvConfig(&conf.AllowedSources, "IMGPROXY_ALLOWED_SOURCES")
  245. boolEnvConfig(&conf.JpegProgressive, "IMGPROXY_JPEG_PROGRESSIVE")
  246. boolEnvConfig(&conf.PngInterlaced, "IMGPROXY_PNG_INTERLACED")
  247. boolEnvConfig(&conf.PngQuantize, "IMGPROXY_PNG_QUANTIZE")
  248. intEnvConfig(&conf.PngQuantizationColors, "IMGPROXY_PNG_QUANTIZATION_COLORS")
  249. intEnvConfig(&conf.Quality, "IMGPROXY_QUALITY")
  250. intEnvConfig(&conf.GZipCompression, "IMGPROXY_GZIP_COMPRESSION")
  251. boolEnvConfig(&conf.StripMetadata, "IMGPROXY_STRIP_METADATA")
  252. boolEnvConfig(&conf.EnableWebpDetection, "IMGPROXY_ENABLE_WEBP_DETECTION")
  253. boolEnvConfig(&conf.EnforceWebp, "IMGPROXY_ENFORCE_WEBP")
  254. boolEnvConfig(&conf.EnableClientHints, "IMGPROXY_ENABLE_CLIENT_HINTS")
  255. boolEnvConfig(&conf.UseLinearColorspace, "IMGPROXY_USE_LINEAR_COLORSPACE")
  256. boolEnvConfig(&conf.DisableShrinkOnLoad, "IMGPROXY_DISABLE_SHRINK_ON_LOAD")
  257. if err := hexEnvConfig(&conf.Keys, "IMGPROXY_KEY"); err != nil {
  258. return err
  259. }
  260. if err := hexEnvConfig(&conf.Salts, "IMGPROXY_SALT"); err != nil {
  261. return err
  262. }
  263. intEnvConfig(&conf.SignatureSize, "IMGPROXY_SIGNATURE_SIZE")
  264. if err := hexFileConfig(&conf.Keys, *keyPath); err != nil {
  265. return err
  266. }
  267. if err := hexFileConfig(&conf.Salts, *saltPath); err != nil {
  268. return err
  269. }
  270. strEnvConfig(&conf.Secret, "IMGPROXY_SECRET")
  271. strEnvConfig(&conf.AllowOrigin, "IMGPROXY_ALLOW_ORIGIN")
  272. strEnvConfig(&conf.UserAgent, "IMGPROXY_USER_AGENT")
  273. boolEnvConfig(&conf.IgnoreSslVerification, "IMGPROXY_IGNORE_SSL_VERIFICATION")
  274. boolEnvConfig(&conf.DevelopmentErrorsMode, "IMGPROXY_DEVELOPMENT_ERRORS_MODE")
  275. strEnvConfig(&conf.LocalFileSystemRoot, "IMGPROXY_LOCAL_FILESYSTEM_ROOT")
  276. boolEnvConfig(&conf.S3Enabled, "IMGPROXY_USE_S3")
  277. strEnvConfig(&conf.S3Region, "IMGPROXY_S3_REGION")
  278. strEnvConfig(&conf.S3Endpoint, "IMGPROXY_S3_ENDPOINT")
  279. boolEnvConfig(&conf.GCSEnabled, "IMGPROXY_USE_GCS")
  280. strEnvConfig(&conf.GCSKey, "IMGPROXY_GCS_KEY")
  281. boolEnvConfig(&conf.ETagEnabled, "IMGPROXY_USE_ETAG")
  282. strEnvConfig(&conf.BaseURL, "IMGPROXY_BASE_URL")
  283. if err := presetEnvConfig(conf.Presets, "IMGPROXY_PRESETS"); err != nil {
  284. return err
  285. }
  286. if err := presetFileConfig(conf.Presets, *presetsPath); err != nil {
  287. return err
  288. }
  289. boolEnvConfig(&conf.OnlyPresets, "IMGPROXY_ONLY_PRESETS")
  290. strEnvConfig(&conf.WatermarkData, "IMGPROXY_WATERMARK_DATA")
  291. strEnvConfig(&conf.WatermarkPath, "IMGPROXY_WATERMARK_PATH")
  292. strEnvConfig(&conf.WatermarkURL, "IMGPROXY_WATERMARK_URL")
  293. floatEnvConfig(&conf.WatermarkOpacity, "IMGPROXY_WATERMARK_OPACITY")
  294. strEnvConfig(&conf.NewRelicAppName, "IMGPROXY_NEW_RELIC_APP_NAME")
  295. strEnvConfig(&conf.NewRelicKey, "IMGPROXY_NEW_RELIC_KEY")
  296. strEnvConfig(&conf.PrometheusBind, "IMGPROXY_PROMETHEUS_BIND")
  297. strEnvConfig(&conf.BugsnagKey, "IMGPROXY_BUGSNAG_KEY")
  298. strEnvConfig(&conf.BugsnagStage, "IMGPROXY_BUGSNAG_STAGE")
  299. strEnvConfig(&conf.HoneybadgerKey, "IMGPROXY_HONEYBADGER_KEY")
  300. strEnvConfig(&conf.HoneybadgerEnv, "IMGPROXY_HONEYBADGER_ENV")
  301. strEnvConfig(&conf.SentryDSN, "IMGPROXY_SENTRY_DSN")
  302. strEnvConfig(&conf.SentryEnvironment, "IMGPROXY_SENTRY_ENVIRONMENT")
  303. strEnvConfig(&conf.SentryRelease, "IMGPROXY_SENTRY_RELEASE")
  304. boolEnvConfig(&conf.ReportDownloadingErrors, "IMGPROXY_REPORT_DOWNLOADING_ERRORS")
  305. intEnvConfig(&conf.FreeMemoryInterval, "IMGPROXY_FREE_MEMORY_INTERVAL")
  306. intEnvConfig(&conf.DownloadBufferSize, "IMGPROXY_DOWNLOAD_BUFFER_SIZE")
  307. intEnvConfig(&conf.GZipBufferSize, "IMGPROXY_GZIP_BUFFER_SIZE")
  308. intEnvConfig(&conf.BufferPoolCalibrationThreshold, "IMGPROXY_BUFFER_POOL_CALIBRATION_THRESHOLD")
  309. if len(conf.Keys) != len(conf.Salts) {
  310. return fmt.Errorf("Number of keys and number of salts should be equal. Keys: %d, salts: %d", len(conf.Keys), len(conf.Salts))
  311. }
  312. if len(conf.Keys) == 0 {
  313. logWarning("No keys defined, so signature checking is disabled")
  314. conf.AllowInsecure = true
  315. }
  316. if len(conf.Salts) == 0 {
  317. logWarning("No salts defined, so signature checking is disabled")
  318. conf.AllowInsecure = true
  319. }
  320. if conf.SignatureSize < 1 || conf.SignatureSize > 32 {
  321. return fmt.Errorf("Signature size should be within 1 and 32, now - %d\n", conf.SignatureSize)
  322. }
  323. if len(conf.Bind) == 0 {
  324. return fmt.Errorf("Bind address is not defined")
  325. }
  326. if conf.ReadTimeout <= 0 {
  327. return fmt.Errorf("Read timeout should be greater than 0, now - %d\n", conf.ReadTimeout)
  328. }
  329. if conf.WriteTimeout <= 0 {
  330. return fmt.Errorf("Write timeout should be greater than 0, now - %d\n", conf.WriteTimeout)
  331. }
  332. if conf.KeepAliveTimeout < 0 {
  333. return fmt.Errorf("KeepAlive timeout should be greater than or equal to 0, now - %d\n", conf.KeepAliveTimeout)
  334. }
  335. if conf.DownloadTimeout <= 0 {
  336. return fmt.Errorf("Download timeout should be greater than 0, now - %d\n", conf.DownloadTimeout)
  337. }
  338. if conf.Concurrency <= 0 {
  339. return fmt.Errorf("Concurrency should be greater than 0, now - %d\n", conf.Concurrency)
  340. }
  341. if conf.MaxClients <= 0 {
  342. conf.MaxClients = conf.Concurrency * 10
  343. }
  344. if conf.TTL <= 0 {
  345. return fmt.Errorf("TTL should be greater than 0, now - %d\n", conf.TTL)
  346. }
  347. if conf.MaxSrcDimension < 0 {
  348. return fmt.Errorf("Max src dimension should be greater than or equal to 0, now - %d\n", conf.MaxSrcDimension)
  349. } else if conf.MaxSrcDimension > 0 {
  350. logWarning("IMGPROXY_MAX_SRC_DIMENSION is deprecated and can be removed in future versions. Use IMGPROXY_MAX_SRC_RESOLUTION")
  351. }
  352. if conf.MaxSrcResolution <= 0 {
  353. return fmt.Errorf("Max src resolution should be greater than 0, now - %d\n", conf.MaxSrcResolution)
  354. }
  355. if conf.MaxSrcFileSize < 0 {
  356. return fmt.Errorf("Max src file size should be greater than or equal to 0, now - %d\n", conf.MaxSrcFileSize)
  357. }
  358. if conf.MaxAnimationFrames <= 0 {
  359. return fmt.Errorf("Max animation frames should be greater than 0, now - %d\n", conf.MaxAnimationFrames)
  360. }
  361. if conf.PngQuantizationColors < 2 {
  362. return fmt.Errorf("Png quantization colors should be greater than 1, now - %d\n", conf.PngQuantizationColors)
  363. } else if conf.PngQuantizationColors > 256 {
  364. return fmt.Errorf("Png quantization colors can't be greater than 256, now - %d\n", conf.PngQuantizationColors)
  365. }
  366. if conf.Quality <= 0 {
  367. return fmt.Errorf("Quality should be greater than 0, now - %d\n", conf.Quality)
  368. } else if conf.Quality > 100 {
  369. return fmt.Errorf("Quality can't be greater than 100, now - %d\n", conf.Quality)
  370. }
  371. if conf.GZipCompression < 0 {
  372. return fmt.Errorf("GZip compression should be greater than or equal to 0, now - %d\n", conf.GZipCompression)
  373. } else if conf.GZipCompression > 9 {
  374. return fmt.Errorf("GZip compression can't be greater than 9, now - %d\n", conf.GZipCompression)
  375. }
  376. if conf.GZipCompression > 0 {
  377. logWarning("GZip compression is deprecated and can be removed in future versions")
  378. }
  379. if conf.IgnoreSslVerification {
  380. logWarning("Ignoring SSL verification is very unsafe")
  381. }
  382. if conf.LocalFileSystemRoot != "" {
  383. stat, err := os.Stat(conf.LocalFileSystemRoot)
  384. if err != nil {
  385. return fmt.Errorf("Cannot use local directory: %s", err)
  386. }
  387. if !stat.IsDir() {
  388. return fmt.Errorf("Cannot use local directory: not a directory")
  389. }
  390. if conf.LocalFileSystemRoot == "/" {
  391. logWarning("Exposing root via IMGPROXY_LOCAL_FILESYSTEM_ROOT is unsafe")
  392. }
  393. }
  394. if _, ok := os.LookupEnv("IMGPROXY_USE_GCS"); !ok && len(conf.GCSKey) > 0 {
  395. logWarning("Set IMGPROXY_USE_GCS to true since it may be required by future versions to enable GCS support")
  396. conf.GCSEnabled = true
  397. }
  398. if conf.WatermarkOpacity <= 0 {
  399. return fmt.Errorf("Watermark opacity should be greater than 0")
  400. } else if conf.WatermarkOpacity > 1 {
  401. return fmt.Errorf("Watermark opacity should be less than or equal to 1")
  402. }
  403. if len(conf.PrometheusBind) > 0 && conf.PrometheusBind == conf.Bind {
  404. return fmt.Errorf("Can't use the same binding for the main server and Prometheus")
  405. }
  406. if conf.FreeMemoryInterval <= 0 {
  407. return fmt.Errorf("Free memory interval should be greater than zero")
  408. }
  409. if conf.DownloadBufferSize < 0 {
  410. return fmt.Errorf("Download buffer size should be greater than or equal to 0")
  411. } else if conf.DownloadBufferSize > math.MaxInt32 {
  412. return fmt.Errorf("Download buffer size can't be greater than %d", math.MaxInt32)
  413. }
  414. if conf.GZipBufferSize < 0 {
  415. return fmt.Errorf("GZip buffer size should be greater than or equal to 0")
  416. } else if conf.GZipBufferSize > math.MaxInt32 {
  417. return fmt.Errorf("GZip buffer size can't be greater than %d", math.MaxInt32)
  418. }
  419. if conf.BufferPoolCalibrationThreshold < 64 {
  420. return fmt.Errorf("Buffer pool calibration threshold should be greater than or equal to 64")
  421. }
  422. return nil
  423. }