setting.go 12 KB

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