You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 12 kB

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