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.

setting.go 13KB

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