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.

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