config.go 14 KB

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