您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

setting.go 13KB

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