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 11 kB

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