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

420 lines
12 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. ReverseProxyAuthUid 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. ReverseProxyAuthUid = Cfg.MustValue("security", "REVERSE_PROXY_AUTHENTICATION_UID", "X-WEBAUTH-UID")
  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 err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  157. log.Fatal("Fail to create repository root path(%s): %v", RepoRootPath, err)
  158. }
  159. ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
  160. PictureService = Cfg.MustValueRange("picture", "SERVICE", "server",
  161. []string{"server"})
  162. DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR")
  163. }
  164. var Service struct {
  165. RegisterEmailConfirm bool
  166. DisableRegistration bool
  167. RequireSignInView bool
  168. EnableCacheAvatar bool
  169. EnableNotifyMail bool
  170. EnableReverseProxyAuth bool
  171. LdapAuth bool
  172. ActiveCodeLives int
  173. ResetPwdCodeLives int
  174. }
  175. func newService() {
  176. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  177. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  178. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION")
  179. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
  180. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
  181. Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
  182. }
  183. var logLevels = map[string]string{
  184. "Trace": "0",
  185. "Debug": "1",
  186. "Info": "2",
  187. "Warn": "3",
  188. "Error": "4",
  189. "Critical": "5",
  190. }
  191. func newLogService() {
  192. log.Info("%s %s", AppName, AppVer)
  193. // Get and check log mode.
  194. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  195. LogConfigs = make([]string, len(LogModes))
  196. for i, mode := range LogModes {
  197. mode = strings.TrimSpace(mode)
  198. modeSec := "log." + mode
  199. if _, err := Cfg.GetSection(modeSec); err != nil {
  200. log.Fatal("Unknown log mode: %s", mode)
  201. }
  202. // Log level.
  203. levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
  204. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  205. level, ok := logLevels[levelName]
  206. if !ok {
  207. log.Fatal("Unknown log level: %s", levelName)
  208. }
  209. // Generate log configuration.
  210. switch mode {
  211. case "console":
  212. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  213. case "file":
  214. logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
  215. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  216. LogConfigs[i] = fmt.Sprintf(
  217. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  218. logPath,
  219. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  220. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  221. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  222. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  223. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  224. case "conn":
  225. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  226. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
  227. Cfg.MustBool(modeSec, "RECONNECT"),
  228. Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
  229. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  230. case "smtp":
  231. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  232. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  233. Cfg.MustValue(modeSec, "PASSWD", "******"),
  234. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  235. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  236. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  237. case "database":
  238. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  239. Cfg.MustValue(modeSec, "DRIVER"),
  240. Cfg.MustValue(modeSec, "CONN"))
  241. }
  242. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  243. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  244. }
  245. }
  246. func newCacheService() {
  247. CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
  248. if EnableRedis {
  249. log.Info("Redis Enabled")
  250. }
  251. if EnableMemcache {
  252. log.Info("Memcache Enabled")
  253. }
  254. switch CacheAdapter {
  255. case "memory":
  256. CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
  257. case "redis", "memcache":
  258. CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
  259. default:
  260. log.Fatal("Unknown cache adapter: %s", CacheAdapter)
  261. }
  262. var err error
  263. Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
  264. if err != nil {
  265. log.Fatal("Init cache system failed, adapter: %s, config: %s, %v\n",
  266. CacheAdapter, CacheConfig, err)
  267. }
  268. log.Info("Cache Service Enabled")
  269. }
  270. func newSessionService() {
  271. SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
  272. []string{"memory", "file", "redis", "mysql"})
  273. SessionConfig = new(session.Config)
  274. SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
  275. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  276. SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
  277. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  278. SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  279. SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  280. SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
  281. "sha1", []string{"sha1", "sha256", "md5"})
  282. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  283. if SessionProvider == "file" {
  284. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  285. }
  286. var err error
  287. SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
  288. if err != nil {
  289. log.Fatal("Init session system failed, provider: %s, %v",
  290. SessionProvider, err)
  291. }
  292. log.Info("Session Service Enabled")
  293. }
  294. // Mailer represents mail service.
  295. type Mailer struct {
  296. Name string
  297. Host string
  298. From string
  299. User, Passwd string
  300. }
  301. type OauthInfo struct {
  302. ClientId, ClientSecret string
  303. Scopes string
  304. AuthUrl, TokenUrl string
  305. }
  306. // Oauther represents oauth service.
  307. type Oauther struct {
  308. GitHub, Google, Tencent,
  309. Twitter, Weibo bool
  310. OauthInfos map[string]*OauthInfo
  311. }
  312. var (
  313. MailService *Mailer
  314. OauthService *Oauther
  315. )
  316. func newMailService() {
  317. // Check mailer setting.
  318. if !Cfg.MustBool("mailer", "ENABLED") {
  319. return
  320. }
  321. MailService = &Mailer{
  322. Name: Cfg.MustValue("mailer", "NAME", AppName),
  323. Host: Cfg.MustValue("mailer", "HOST"),
  324. User: Cfg.MustValue("mailer", "USER"),
  325. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  326. }
  327. MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User)
  328. log.Info("Mail Service Enabled")
  329. }
  330. func newRegisterMailService() {
  331. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  332. return
  333. } else if MailService == nil {
  334. log.Warn("Register Mail Service: Mail Service is not enabled")
  335. return
  336. }
  337. Service.RegisterEmailConfirm = true
  338. log.Info("Register Mail Service Enabled")
  339. }
  340. func newNotifyMailService() {
  341. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  342. return
  343. } else if MailService == nil {
  344. log.Warn("Notify Mail Service: Mail Service is not enabled")
  345. return
  346. }
  347. Service.EnableNotifyMail = true
  348. log.Info("Notify Mail Service Enabled")
  349. }
  350. func newWebhookService() {
  351. WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1)
  352. WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5)
  353. }
  354. func NewServices() {
  355. newService()
  356. newLogService()
  357. newCacheService()
  358. newSessionService()
  359. newMailService()
  360. newRegisterMailService()
  361. newNotifyMailService()
  362. newWebhookService()
  363. }