setting.go 14 KB

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