setting.go 13 KB

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