config.go 8.8 KB

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