setting.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package setting
  5. import (
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/Unknwon/goconfig"
  14. "github.com/gogits/cache"
  15. "github.com/gogits/session"
  16. "github.com/gogits/gogs/modules/bin"
  17. "github.com/gogits/gogs/modules/log"
  18. )
  19. type Scheme string
  20. const (
  21. HTTP Scheme = "http"
  22. HTTPS Scheme = "https"
  23. )
  24. var (
  25. // App settings.
  26. AppVer string
  27. AppName string
  28. AppLogo string
  29. AppUrl string
  30. // Server settings.
  31. Protocol Scheme
  32. Domain string
  33. HttpAddr, HttpPort string
  34. SshPort int
  35. OfflineMode bool
  36. DisableRouterLog bool
  37. CertFile, KeyFile string
  38. StaticRootPath string
  39. // Security settings.
  40. InstallLock bool
  41. SecretKey string
  42. LogInRememberDays int
  43. CookieUserName string
  44. CookieRememberName string
  45. ReverseProxyAuthUser string
  46. // Webhook settings.
  47. WebhookTaskInterval int
  48. WebhookDeliverTimeout int
  49. // Repository settings.
  50. RepoRootPath string
  51. ScriptType string
  52. // Picture settings.
  53. PictureService string
  54. DisableGravatar bool
  55. // Log settings.
  56. LogRootPath string
  57. LogModes []string
  58. LogConfigs []string
  59. // Attachment settings.
  60. AttachmentPath string
  61. AttachmentAllowedTypes string
  62. AttachmentMaxSize int64
  63. AttachmentMaxFiles int
  64. AttachmentEnabled bool
  65. // Cache settings.
  66. Cache cache.Cache
  67. CacheAdapter string
  68. CacheConfig string
  69. EnableRedis bool
  70. EnableMemcache bool
  71. // Session settings.
  72. SessionProvider string
  73. SessionConfig *session.Config
  74. SessionManager *session.Manager
  75. // Global setting objects.
  76. Cfg *goconfig.ConfigFile
  77. CustomPath string // Custom directory path.
  78. ProdMode bool
  79. RunUser string
  80. )
  81. func ExecPath() (string, error) {
  82. file, err := exec.LookPath(os.Args[0])
  83. if err != nil {
  84. return "", err
  85. }
  86. p, err := filepath.Abs(file)
  87. if err != nil {
  88. return "", err
  89. }
  90. return p, nil
  91. }
  92. // WorkDir returns absolute path of work directory.
  93. func WorkDir() (string, error) {
  94. execPath, err := ExecPath()
  95. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  96. }
  97. // NewConfigContext initializes configuration context.
  98. // NOTE: do not print any log except error.
  99. func NewConfigContext() {
  100. workDir, err := WorkDir()
  101. if err != nil {
  102. log.Fatal("Fail to get work directory: %v", err)
  103. }
  104. data, err := bin.Asset("conf/app.ini")
  105. if err != nil {
  106. log.Fatal("Fail to read 'conf/app.ini': %v", err)
  107. }
  108. Cfg, err = goconfig.LoadFromData(data)
  109. if err != nil {
  110. log.Fatal("Fail to parse 'conf/app.ini': %v", err)
  111. }
  112. CustomPath = os.Getenv("GOGS_CUSTOM")
  113. if len(CustomPath) == 0 {
  114. CustomPath = path.Join(workDir, "custom")
  115. }
  116. cfgPath := path.Join(CustomPath, "conf/app.ini")
  117. if com.IsFile(cfgPath) {
  118. if err = Cfg.AppendFiles(cfgPath); err != nil {
  119. log.Fatal("Fail to load custom 'conf/app.ini': %v", err)
  120. }
  121. } else {
  122. log.Warn("No custom 'conf/app.ini' found")
  123. }
  124. AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
  125. AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
  126. AppUrl = Cfg.MustValue("server", "ROOT_URL", "http://localhost:3000")
  127. Protocol = HTTP
  128. if Cfg.MustValue("server", "PROTOCOL") == "https" {
  129. Protocol = HTTPS
  130. CertFile = Cfg.MustValue("server", "CERT_FILE")
  131. KeyFile = Cfg.MustValue("server", "KEY_FILE")
  132. }
  133. Domain = Cfg.MustValue("server", "DOMAIN", "localhost")
  134. HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0")
  135. HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000")
  136. SshPort = Cfg.MustInt("server", "SSH_PORT", 22)
  137. OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE")
  138. DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG")
  139. StaticRootPath = Cfg.MustValue("server", "STATIC_ROOT_PATH", workDir)
  140. LogRootPath = Cfg.MustValue("log", "ROOT_PATH", path.Join(workDir, "log"))
  141. InstallLock = Cfg.MustBool("security", "INSTALL_LOCK")
  142. SecretKey = Cfg.MustValue("security", "SECRET_KEY")
  143. LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
  144. CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
  145. CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
  146. ReverseProxyAuthUser = Cfg.MustValue("security", "REVERSE_PROXY_AUTHENTICATION_USER", "X-WEBAUTH-USER")
  147. AttachmentPath = Cfg.MustValue("attachment", "PATH", "files/attachments")
  148. AttachmentAllowedTypes = Cfg.MustValue("attachment", "ALLOWED_TYPES", "*/*")
  149. AttachmentMaxSize = Cfg.MustInt64("attachment", "MAX_SIZE", 32)
  150. AttachmentMaxFiles = Cfg.MustInt("attachment", "MAX_FILES", 10)
  151. AttachmentEnabled = Cfg.MustBool("attachment", "ENABLE", true)
  152. if err = os.MkdirAll(AttachmentPath, os.ModePerm); err != nil {
  153. log.Fatal("Could not create directory %s: %s", AttachmentPath, err)
  154. }
  155. RunUser = Cfg.MustValue("", "RUN_USER")
  156. curUser := os.Getenv("USER")
  157. if len(curUser) == 0 {
  158. curUser = os.Getenv("USERNAME")
  159. }
  160. // Does not check run user when the install lock is off.
  161. if InstallLock && RunUser != curUser {
  162. log.Fatal("Expect user(%s) but current user is: %s", RunUser, curUser)
  163. }
  164. // Determine and create root git reposiroty path.
  165. homeDir, err := com.HomeDir()
  166. if err != nil {
  167. log.Fatal("Fail to get home directory: %v", err)
  168. }
  169. RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
  170. if !filepath.IsAbs(RepoRootPath) {
  171. RepoRootPath = filepath.Join(workDir, RepoRootPath)
  172. } else {
  173. RepoRootPath = filepath.Clean(RepoRootPath)
  174. }
  175. if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  176. log.Fatal("Fail to create repository root path(%s): %v", RepoRootPath, err)
  177. }
  178. ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
  179. PictureService = Cfg.MustValueRange("picture", "SERVICE", "server",
  180. []string{"server"})
  181. DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR")
  182. }
  183. var Service struct {
  184. RegisterEmailConfirm bool
  185. DisableRegistration bool
  186. RequireSignInView bool
  187. EnableCacheAvatar bool
  188. EnableNotifyMail bool
  189. EnableReverseProxyAuth bool
  190. LdapAuth bool
  191. ActiveCodeLives int
  192. ResetPwdCodeLives int
  193. }
  194. func newService() {
  195. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  196. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  197. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION")
  198. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
  199. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
  200. Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
  201. }
  202. var logLevels = map[string]string{
  203. "Trace": "0",
  204. "Debug": "1",
  205. "Info": "2",
  206. "Warn": "3",
  207. "Error": "4",
  208. "Critical": "5",
  209. }
  210. func newLogService() {
  211. log.Info("%s %s", AppName, AppVer)
  212. // Get and check log mode.
  213. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  214. LogConfigs = make([]string, len(LogModes))
  215. for i, mode := range LogModes {
  216. mode = strings.TrimSpace(mode)
  217. modeSec := "log." + mode
  218. if _, err := Cfg.GetSection(modeSec); err != nil {
  219. log.Fatal("Unknown log mode: %s", mode)
  220. }
  221. // Log level.
  222. levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
  223. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  224. level, ok := logLevels[levelName]
  225. if !ok {
  226. log.Fatal("Unknown log level: %s", levelName)
  227. }
  228. // Generate log configuration.
  229. switch mode {
  230. case "console":
  231. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  232. case "file":
  233. logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
  234. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  235. LogConfigs[i] = fmt.Sprintf(
  236. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  237. logPath,
  238. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  239. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  240. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  241. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  242. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  243. case "conn":
  244. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  245. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
  246. Cfg.MustBool(modeSec, "RECONNECT"),
  247. Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
  248. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  249. case "smtp":
  250. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  251. Cfg.MustValue(modeSec, "USER", "[email protected]"),
  252. Cfg.MustValue(modeSec, "PASSWD", "******"),
  253. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  254. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  255. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  256. case "database":
  257. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  258. Cfg.MustValue(modeSec, "DRIVER"),
  259. Cfg.MustValue(modeSec, "CONN"))
  260. }
  261. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  262. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  263. }
  264. }
  265. func newCacheService() {
  266. CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
  267. if EnableRedis {
  268. log.Info("Redis Enabled")
  269. }
  270. if EnableMemcache {
  271. log.Info("Memcache Enabled")
  272. }
  273. switch CacheAdapter {
  274. case "memory":
  275. CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
  276. case "redis", "memcache":
  277. CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
  278. default:
  279. log.Fatal("Unknown cache adapter: %s", CacheAdapter)
  280. }
  281. var err error
  282. Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
  283. if err != nil {
  284. log.Fatal("Init cache system failed, adapter: %s, config: %s, %v\n",
  285. CacheAdapter, CacheConfig, err)
  286. }
  287. log.Info("Cache Service Enabled")
  288. }
  289. func newSessionService() {
  290. SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
  291. []string{"memory", "file", "redis", "mysql"})
  292. SessionConfig = new(session.Config)
  293. SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
  294. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  295. SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
  296. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  297. SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  298. SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  299. SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
  300. "sha1", []string{"sha1", "sha256", "md5"})
  301. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  302. if SessionProvider == "file" {
  303. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  304. }
  305. var err error
  306. SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
  307. if err != nil {
  308. log.Fatal("Init session system failed, provider: %s, %v",
  309. SessionProvider, err)
  310. }
  311. log.Info("Session Service Enabled")
  312. }
  313. // Mailer represents mail service.
  314. type Mailer struct {
  315. Name string
  316. Host string
  317. From string
  318. User, Passwd string
  319. }
  320. type OauthInfo struct {
  321. ClientId, ClientSecret string
  322. Scopes string
  323. AuthUrl, TokenUrl string
  324. }
  325. // Oauther represents oauth service.
  326. type Oauther struct {
  327. GitHub, Google, Tencent,
  328. Twitter, Weibo bool
  329. OauthInfos map[string]*OauthInfo
  330. }
  331. var (
  332. MailService *Mailer
  333. OauthService *Oauther
  334. )
  335. func newMailService() {
  336. // Check mailer setting.
  337. if !Cfg.MustBool("mailer", "ENABLED") {
  338. return
  339. }
  340. MailService = &Mailer{
  341. Name: Cfg.MustValue("mailer", "NAME", AppName),
  342. Host: Cfg.MustValue("mailer", "HOST"),
  343. User: Cfg.MustValue("mailer", "USER"),
  344. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  345. }
  346. MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User)
  347. log.Info("Mail Service Enabled")
  348. }
  349. func newRegisterMailService() {
  350. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  351. return
  352. } else if MailService == nil {
  353. log.Warn("Register Mail Service: Mail Service is not enabled")
  354. return
  355. }
  356. Service.RegisterEmailConfirm = true
  357. log.Info("Register Mail Service Enabled")
  358. }
  359. func newNotifyMailService() {
  360. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  361. return
  362. } else if MailService == nil {
  363. log.Warn("Notify Mail Service: Mail Service is not enabled")
  364. return
  365. }
  366. Service.EnableNotifyMail = true
  367. log.Info("Notify Mail Service Enabled")
  368. }
  369. func newWebhookService() {
  370. WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1)
  371. WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5)
  372. }
  373. func NewServices() {
  374. newService()
  375. newLogService()
  376. newCacheService()
  377. newSessionService()
  378. newMailService()
  379. newRegisterMailService()
  380. newNotifyMailService()
  381. newWebhookService()
  382. }