config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/hex"
  5. "flag"
  6. "fmt"
  7. "log"
  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 boolEnvConfig(b *bool, name string) {
  34. *b = false
  35. if env, err := strconv.ParseBool(os.Getenv(name)); err == nil {
  36. *b = env
  37. }
  38. }
  39. func hexEnvConfig(b *[]securityKey, name string) {
  40. var err error
  41. if env := os.Getenv(name); len(env) > 0 {
  42. parts := strings.Split(env, ",")
  43. keys := make([]securityKey, len(parts))
  44. for i, part := range parts {
  45. if keys[i], err = hex.DecodeString(part); err != nil {
  46. log.Fatalf("%s expected to be hex-encoded strings. Invalid: %s\n", name, part)
  47. }
  48. }
  49. *b = keys
  50. }
  51. }
  52. func hexFileConfig(b *[]securityKey, filepath string) {
  53. if len(filepath) == 0 {
  54. return
  55. }
  56. f, err := os.Open(filepath)
  57. if err != nil {
  58. log.Fatalf("Can't open file %s\n", filepath)
  59. }
  60. keys := []securityKey{}
  61. scanner := bufio.NewScanner(f)
  62. for scanner.Scan() {
  63. part := scanner.Text()
  64. if len(part) == 0 {
  65. continue
  66. }
  67. if key, err := hex.DecodeString(part); err == nil {
  68. keys = append(keys, key)
  69. } else {
  70. log.Fatalf("%s expected to contain hex-encoded strings. Invalid: %s\n", filepath, part)
  71. }
  72. }
  73. if err := scanner.Err(); err != nil {
  74. log.Fatalf("Failed to read file %s: %s", filepath, err)
  75. }
  76. *b = keys
  77. }
  78. func presetEnvConfig(p presets, name string) {
  79. if env := os.Getenv(name); len(env) > 0 {
  80. presetStrings := strings.Split(env, ",")
  81. for _, presetStr := range presetStrings {
  82. if err := parsePreset(p, presetStr); err != nil {
  83. log.Fatalln(err)
  84. }
  85. }
  86. }
  87. }
  88. func presetFileConfig(p presets, filepath string) {
  89. if len(filepath) == 0 {
  90. return
  91. }
  92. f, err := os.Open(filepath)
  93. if err != nil {
  94. log.Fatalf("Can't open file %s\n", filepath)
  95. }
  96. scanner := bufio.NewScanner(f)
  97. for scanner.Scan() {
  98. if err := parsePreset(p, scanner.Text()); err != nil {
  99. log.Fatalln(err)
  100. }
  101. }
  102. if err := scanner.Err(); err != nil {
  103. log.Fatalf("Failed to read presets file: %s", err)
  104. }
  105. }
  106. type config struct {
  107. Bind string
  108. ReadTimeout int
  109. WaitTimeout int
  110. WriteTimeout int
  111. DownloadTimeout int
  112. Concurrency int
  113. MaxClients int
  114. TTL int
  115. MaxSrcDimension int
  116. MaxSrcResolution int
  117. MaxGifFrames int
  118. JpegProgressive bool
  119. PngInterlaced bool
  120. Quality int
  121. GZipCompression int
  122. EnableWebpDetection bool
  123. EnforceWebp bool
  124. EnableClientHints bool
  125. Keys []securityKey
  126. Salts []securityKey
  127. AllowInsecure bool
  128. SignatureSize int
  129. Secret string
  130. AllowOrigin string
  131. UserAgent string
  132. IgnoreSslVerification bool
  133. LocalFileSystemRoot string
  134. S3Enabled bool
  135. S3Region string
  136. S3Endpoint string
  137. GCSKey string
  138. ETagEnabled bool
  139. BaseURL string
  140. Presets presets
  141. WatermarkData string
  142. WatermarkPath string
  143. WatermarkURL string
  144. WatermarkOpacity float64
  145. NewRelicAppName string
  146. NewRelicKey string
  147. PrometheusBind string
  148. BugsnagKey string
  149. BugsnagStage string
  150. HoneybadgerKey string
  151. HoneybadgerEnv string
  152. }
  153. var conf = config{
  154. Bind: ":8080",
  155. ReadTimeout: 10,
  156. WriteTimeout: 10,
  157. DownloadTimeout: 5,
  158. Concurrency: runtime.NumCPU() * 2,
  159. TTL: 3600,
  160. IgnoreSslVerification: false,
  161. MaxSrcResolution: 16800000,
  162. MaxGifFrames: 1,
  163. AllowInsecure: false,
  164. SignatureSize: 32,
  165. Quality: 80,
  166. GZipCompression: 5,
  167. UserAgent: fmt.Sprintf("imgproxy/%s", version),
  168. ETagEnabled: false,
  169. S3Enabled: false,
  170. WatermarkOpacity: 1,
  171. BugsnagStage: "production",
  172. HoneybadgerEnv: "production",
  173. }
  174. func init() {
  175. keyPath := flag.String("keypath", "", "path of the file with hex-encoded key")
  176. saltPath := flag.String("saltpath", "", "path of the file with hex-encoded salt")
  177. presetsPath := flag.String("presets", "", "path of the file with presets")
  178. showVersion := flag.Bool("v", false, "show version")
  179. flag.Parse()
  180. if *showVersion {
  181. fmt.Println(version)
  182. os.Exit(0)
  183. }
  184. if port := os.Getenv("PORT"); len(port) > 0 {
  185. conf.Bind = fmt.Sprintf(":%s", port)
  186. }
  187. strEnvConfig(&conf.Bind, "IMGPROXY_BIND")
  188. intEnvConfig(&conf.ReadTimeout, "IMGPROXY_READ_TIMEOUT")
  189. intEnvConfig(&conf.WriteTimeout, "IMGPROXY_WRITE_TIMEOUT")
  190. intEnvConfig(&conf.DownloadTimeout, "IMGPROXY_DOWNLOAD_TIMEOUT")
  191. intEnvConfig(&conf.Concurrency, "IMGPROXY_CONCURRENCY")
  192. intEnvConfig(&conf.MaxClients, "IMGPROXY_MAX_CLIENTS")
  193. intEnvConfig(&conf.TTL, "IMGPROXY_TTL")
  194. intEnvConfig(&conf.MaxSrcDimension, "IMGPROXY_MAX_SRC_DIMENSION")
  195. megaIntEnvConfig(&conf.MaxSrcResolution, "IMGPROXY_MAX_SRC_RESOLUTION")
  196. intEnvConfig(&conf.MaxGifFrames, "IMGPROXY_MAX_GIF_FRAMES")
  197. boolEnvConfig(&conf.JpegProgressive, "IMGPROXY_JPEG_PROGRESSIVE")
  198. boolEnvConfig(&conf.PngInterlaced, "IMGPROXY_PNG_INTERLACED")
  199. intEnvConfig(&conf.Quality, "IMGPROXY_QUALITY")
  200. intEnvConfig(&conf.GZipCompression, "IMGPROXY_GZIP_COMPRESSION")
  201. boolEnvConfig(&conf.EnableWebpDetection, "IMGPROXY_ENABLE_WEBP_DETECTION")
  202. boolEnvConfig(&conf.EnforceWebp, "IMGPROXY_ENFORCE_WEBP")
  203. boolEnvConfig(&conf.EnableClientHints, "IMGPROXY_ENABLE_CLIENT_HINTS")
  204. hexEnvConfig(&conf.Keys, "IMGPROXY_KEY")
  205. hexEnvConfig(&conf.Salts, "IMGPROXY_SALT")
  206. intEnvConfig(&conf.SignatureSize, "IMGPROXY_SIGNATURE_SIZE")
  207. hexFileConfig(&conf.Keys, *keyPath)
  208. hexFileConfig(&conf.Salts, *saltPath)
  209. strEnvConfig(&conf.Secret, "IMGPROXY_SECRET")
  210. strEnvConfig(&conf.AllowOrigin, "IMGPROXY_ALLOW_ORIGIN")
  211. strEnvConfig(&conf.UserAgent, "IMGPROXY_USER_AGENT")
  212. boolEnvConfig(&conf.IgnoreSslVerification, "IMGPROXY_IGNORE_SSL_VERIFICATION")
  213. strEnvConfig(&conf.LocalFileSystemRoot, "IMGPROXY_LOCAL_FILESYSTEM_ROOT")
  214. boolEnvConfig(&conf.S3Enabled, "IMGPROXY_USE_S3")
  215. strEnvConfig(&conf.S3Region, "IMGPROXY_S3_REGION")
  216. strEnvConfig(&conf.S3Endpoint, "IMGPROXY_S3_ENDPOINT")
  217. strEnvConfig(&conf.GCSKey, "IMGPROXY_GCS_KEY")
  218. boolEnvConfig(&conf.ETagEnabled, "IMGPROXY_USE_ETAG")
  219. strEnvConfig(&conf.BaseURL, "IMGPROXY_BASE_URL")
  220. conf.Presets = make(presets)
  221. presetEnvConfig(conf.Presets, "IMGPROXY_PRESETS")
  222. presetFileConfig(conf.Presets, *presetsPath)
  223. strEnvConfig(&conf.WatermarkData, "IMGPROXY_WATERMARK_DATA")
  224. strEnvConfig(&conf.WatermarkPath, "IMGPROXY_WATERMARK_PATH")
  225. strEnvConfig(&conf.WatermarkURL, "IMGPROXY_WATERMARK_URL")
  226. floatEnvConfig(&conf.WatermarkOpacity, "IMGPROXY_WATERMARK_OPACITY")
  227. strEnvConfig(&conf.NewRelicAppName, "IMGPROXY_NEW_RELIC_APP_NAME")
  228. strEnvConfig(&conf.NewRelicKey, "IMGPROXY_NEW_RELIC_KEY")
  229. strEnvConfig(&conf.PrometheusBind, "IMGPROXY_PROMETHEUS_BIND")
  230. strEnvConfig(&conf.BugsnagKey, "IMGPROXY_BUGSNAG_KEY")
  231. strEnvConfig(&conf.BugsnagStage, "IMGPROXY_BUGSNAG_STAGE")
  232. strEnvConfig(&conf.HoneybadgerKey, "IMGPROXY_HONEYBADGER_KEY")
  233. strEnvConfig(&conf.HoneybadgerEnv, "IMGPROXY_HONEYBADGER_ENV")
  234. if len(conf.Keys) != len(conf.Salts) {
  235. log.Fatalf("Number of keys and number of salts should be equal. Keys: %d, salts: %d", len(conf.Keys), len(conf.Salts))
  236. }
  237. if len(conf.Keys) == 0 {
  238. warning("No keys defined, so signature checking is disabled")
  239. conf.AllowInsecure = true
  240. }
  241. if len(conf.Salts) == 0 {
  242. warning("No salts defined, so signature checking is disabled")
  243. conf.AllowInsecure = true
  244. }
  245. if conf.SignatureSize < 1 || conf.SignatureSize > 32 {
  246. log.Fatalf("Signature size should be within 1 and 32, now - %d\n", conf.SignatureSize)
  247. }
  248. if len(conf.Bind) == 0 {
  249. log.Fatalln("Bind address is not defined")
  250. }
  251. if conf.ReadTimeout <= 0 {
  252. log.Fatalf("Read timeout should be greater than 0, now - %d\n", conf.ReadTimeout)
  253. }
  254. if conf.WriteTimeout <= 0 {
  255. log.Fatalf("Write timeout should be greater than 0, now - %d\n", conf.WriteTimeout)
  256. }
  257. if conf.DownloadTimeout <= 0 {
  258. log.Fatalf("Download timeout should be greater than 0, now - %d\n", conf.DownloadTimeout)
  259. }
  260. if conf.Concurrency <= 0 {
  261. log.Fatalf("Concurrency should be greater than 0, now - %d\n", conf.Concurrency)
  262. }
  263. if conf.MaxClients <= 0 {
  264. conf.MaxClients = conf.Concurrency * 10
  265. }
  266. if conf.TTL <= 0 {
  267. log.Fatalf("TTL should be greater than 0, now - %d\n", conf.TTL)
  268. }
  269. if conf.MaxSrcDimension < 0 {
  270. log.Fatalf("Max src dimension should be greater than or equal to 0, now - %d\n", conf.MaxSrcDimension)
  271. } else if conf.MaxSrcDimension > 0 {
  272. warning("IMGPROXY_MAX_SRC_DIMENSION is deprecated and can be removed in future versions. Use IMGPROXY_MAX_SRC_RESOLUTION")
  273. }
  274. if conf.MaxSrcResolution <= 0 {
  275. log.Fatalf("Max src resolution should be greater than 0, now - %d\n", conf.MaxSrcResolution)
  276. }
  277. if conf.MaxGifFrames <= 0 {
  278. log.Fatalf("Max GIF frames should be greater than 0, now - %d\n", conf.MaxGifFrames)
  279. }
  280. if conf.Quality <= 0 {
  281. log.Fatalf("Quality should be greater than 0, now - %d\n", conf.Quality)
  282. } else if conf.Quality > 100 {
  283. log.Fatalf("Quality can't be greater than 100, now - %d\n", conf.Quality)
  284. }
  285. if conf.GZipCompression < 0 {
  286. log.Fatalf("GZip compression should be greater than or quual to 0, now - %d\n", conf.GZipCompression)
  287. } else if conf.GZipCompression > 9 {
  288. log.Fatalf("GZip compression can't be greater than 9, now - %d\n", conf.GZipCompression)
  289. }
  290. if conf.IgnoreSslVerification {
  291. warning("Ignoring SSL verification is very unsafe")
  292. }
  293. if conf.LocalFileSystemRoot != "" {
  294. stat, err := os.Stat(conf.LocalFileSystemRoot)
  295. if err != nil {
  296. log.Fatalf("Cannot use local directory: %s", err)
  297. } else {
  298. if !stat.IsDir() {
  299. log.Fatalf("Cannot use local directory: not a directory")
  300. }
  301. }
  302. if conf.LocalFileSystemRoot == "/" {
  303. log.Print("Exposing root via IMGPROXY_LOCAL_FILESYSTEM_ROOT is unsafe")
  304. }
  305. }
  306. if err := checkPresets(conf.Presets); err != nil {
  307. log.Fatalln(err)
  308. }
  309. if conf.WatermarkOpacity <= 0 {
  310. log.Fatalln("Watermark opacity should be greater than 0")
  311. } else if conf.WatermarkOpacity > 1 {
  312. log.Fatalln("Watermark opacity should be less than or equal to 1")
  313. }
  314. if len(conf.PrometheusBind) > 0 && conf.PrometheusBind == conf.Bind {
  315. log.Fatalln("Can't use the same binding for the main server and Prometheus")
  316. }
  317. initDownloading()
  318. initNewrelic()
  319. initPrometheus()
  320. initErrorsReporting()
  321. initVips()
  322. }