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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/macaron-contrib/oauth2"
  17. "github.com/macaron-contrib/session"
  18. "gopkg.in/ini.v1"
  19. "github.com/gogits/gogs/modules/bindata"
  20. "github.com/gogits/gogs/modules/log"
  21. // "github.com/gogits/gogs/modules/ssh"
  22. )
  23. type Scheme string
  24. const (
  25. HTTP Scheme = "http"
  26. HTTPS Scheme = "https"
  27. FCGI Scheme = "fcgi"
  28. )
  29. type LandingPage string
  30. const (
  31. LANDING_PAGE_HOME LandingPage = "/"
  32. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  33. )
  34. var (
  35. // App settings.
  36. AppVer string
  37. AppName string
  38. AppUrl string
  39. AppSubUrl string
  40. // Server settings.
  41. Protocol Scheme
  42. Domain string
  43. HttpAddr, HttpPort string
  44. DisableSSH bool
  45. SSHPort int
  46. SSHDomain string
  47. OfflineMode bool
  48. DisableRouterLog bool
  49. CertFile, KeyFile string
  50. StaticRootPath string
  51. EnableGzip bool
  52. LandingPageUrl LandingPage
  53. // Security settings.
  54. InstallLock bool
  55. SecretKey string
  56. LogInRememberDays int
  57. CookieUserName string
  58. CookieRememberName string
  59. ReverseProxyAuthUser string
  60. // Database settings.
  61. UseSQLite3 bool
  62. UseMySQL bool
  63. UsePostgreSQL bool
  64. // Webhook settings.
  65. Webhook struct {
  66. TaskInterval int
  67. DeliverTimeout int
  68. SkipTLSVerify bool
  69. }
  70. // Repository settings.
  71. RepoRootPath string
  72. ScriptType string
  73. // Picture settings.
  74. PictureService string
  75. AvatarUploadPath string
  76. GravatarSource string
  77. DisableGravatar bool
  78. // Log settings.
  79. LogRootPath string
  80. LogModes []string
  81. LogConfigs []string
  82. // Attachment settings.
  83. AttachmentPath string
  84. AttachmentAllowedTypes string
  85. AttachmentMaxSize int64
  86. AttachmentMaxFiles int
  87. AttachmentEnabled bool
  88. // Time settings.
  89. TimeFormat string
  90. // Cache settings.
  91. CacheAdapter string
  92. CacheInternal int
  93. CacheConn string
  94. EnableRedis bool
  95. EnableMemcache bool
  96. // Session settings.
  97. SessionConfig session.Options
  98. // Git settings.
  99. Git struct {
  100. MaxGitDiffLines int
  101. GcArgs []string `delim:" "`
  102. Fsck struct {
  103. Enable bool
  104. Interval int
  105. Args []string `delim:" "`
  106. } `ini:"git.fsck"`
  107. }
  108. // I18n settings.
  109. Langs, Names []string
  110. // Other settings.
  111. ShowFooterBranding bool
  112. // Global setting objects.
  113. Cfg *ini.File
  114. CustomPath string // Custom directory path.
  115. CustomConf string
  116. ProdMode bool
  117. RunUser string
  118. IsWindows bool
  119. HasRobotsTxt bool
  120. )
  121. func init() {
  122. IsWindows = runtime.GOOS == "windows"
  123. log.NewLogger(0, "console", `{"level": 0}`)
  124. }
  125. func ExecPath() (string, error) {
  126. file, err := exec.LookPath(os.Args[0])
  127. if err != nil {
  128. return "", err
  129. }
  130. p, err := filepath.Abs(file)
  131. if err != nil {
  132. return "", err
  133. }
  134. return p, nil
  135. }
  136. // WorkDir returns absolute path of work directory.
  137. func WorkDir() (string, error) {
  138. execPath, err := ExecPath()
  139. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  140. }
  141. func forcePathSeparator(path string) {
  142. if strings.Contains(path, "\\") {
  143. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  144. }
  145. }
  146. // NewConfigContext initializes configuration context.
  147. // NOTE: do not print any log except error.
  148. func NewConfigContext() {
  149. workDir, err := WorkDir()
  150. if err != nil {
  151. log.Fatal(4, "Fail to get work directory: %v", err)
  152. }
  153. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  154. if err != nil {
  155. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  156. }
  157. CustomPath = os.Getenv("GOGS_CUSTOM")
  158. if len(CustomPath) == 0 {
  159. CustomPath = path.Join(workDir, "custom")
  160. }
  161. if len(CustomConf) == 0 {
  162. CustomConf = path.Join(CustomPath, "conf/app.ini")
  163. }
  164. if com.IsFile(CustomConf) {
  165. if err = Cfg.Append(CustomConf); err != nil {
  166. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  167. }
  168. } else {
  169. log.Warn("Custom config (%s) not found, ignore this if you're running first time", CustomConf)
  170. }
  171. Cfg.NameMapper = ini.AllCapsUnderscore
  172. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  173. forcePathSeparator(LogRootPath)
  174. sec := Cfg.Section("server")
  175. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  176. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  177. if AppUrl[len(AppUrl)-1] != '/' {
  178. AppUrl += "/"
  179. }
  180. // Check if has app suburl.
  181. url, err := url.Parse(AppUrl)
  182. if err != nil {
  183. log.Fatal(4, "Invalid ROOT_URL(%s): %s", AppUrl, err)
  184. }
  185. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  186. Protocol = HTTP
  187. if sec.Key("PROTOCOL").String() == "https" {
  188. Protocol = HTTPS
  189. CertFile = sec.Key("CERT_FILE").String()
  190. KeyFile = sec.Key("KEY_FILE").String()
  191. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  192. Protocol = FCGI
  193. }
  194. Domain = sec.Key("DOMAIN").MustString("localhost")
  195. HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  196. HttpPort = sec.Key("HTTP_PORT").MustString("3000")
  197. DisableSSH = sec.Key("DISABLE_SSH").MustBool()
  198. SSHDomain = sec.Key("SSH_DOMAIN").MustString(Domain)
  199. SSHPort = sec.Key("SSH_PORT").MustInt(22)
  200. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  201. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  202. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  203. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  204. switch sec.Key("LANDING_PAGE").MustString("home") {
  205. case "explore":
  206. LandingPageUrl = LANDING_PAGE_EXPLORE
  207. default:
  208. LandingPageUrl = LANDING_PAGE_HOME
  209. }
  210. sec = Cfg.Section("security")
  211. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  212. SecretKey = sec.Key("SECRET_KEY").String()
  213. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  214. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  215. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  216. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  217. sec = Cfg.Section("attachment")
  218. AttachmentPath = sec.Key("PATH").MustString("data/attachments")
  219. if !filepath.IsAbs(AttachmentPath) {
  220. AttachmentPath = path.Join(workDir, AttachmentPath)
  221. }
  222. AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png")
  223. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32)
  224. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10)
  225. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  226. TimeFormat = map[string]string{
  227. "ANSIC": time.ANSIC,
  228. "UnixDate": time.UnixDate,
  229. "RubyDate": time.RubyDate,
  230. "RFC822": time.RFC822,
  231. "RFC822Z": time.RFC822Z,
  232. "RFC850": time.RFC850,
  233. "RFC1123": time.RFC1123,
  234. "RFC1123Z": time.RFC1123Z,
  235. "RFC3339": time.RFC3339,
  236. "RFC3339Nano": time.RFC3339Nano,
  237. "Kitchen": time.Kitchen,
  238. "Stamp": time.Stamp,
  239. "StampMilli": time.StampMilli,
  240. "StampMicro": time.StampMicro,
  241. "StampNano": time.StampNano,
  242. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  243. RunUser = Cfg.Section("").Key("RUN_USER").String()
  244. curUser := os.Getenv("USER")
  245. if len(curUser) == 0 {
  246. curUser = os.Getenv("USERNAME")
  247. }
  248. // Does not check run user when the install lock is off.
  249. if InstallLock && RunUser != curUser {
  250. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  251. }
  252. // Determine and create root git repository path.
  253. homeDir, err := com.HomeDir()
  254. if err != nil {
  255. log.Fatal(4, "Fail to get home directory: %v", err)
  256. }
  257. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  258. sec = Cfg.Section("repository")
  259. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  260. forcePathSeparator(RepoRootPath)
  261. if !filepath.IsAbs(RepoRootPath) {
  262. RepoRootPath = path.Join(workDir, RepoRootPath)
  263. } else {
  264. RepoRootPath = path.Clean(RepoRootPath)
  265. }
  266. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  267. sec = Cfg.Section("picture")
  268. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  269. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")
  270. forcePathSeparator(AvatarUploadPath)
  271. if !filepath.IsAbs(AvatarUploadPath) {
  272. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  273. }
  274. switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") {
  275. case "duoshuo":
  276. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  277. default:
  278. GravatarSource = "//1.gravatar.com/avatar/"
  279. }
  280. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  281. if OfflineMode {
  282. DisableGravatar = true
  283. }
  284. if err = Cfg.Section("git").MapTo(&Git); err != nil {
  285. log.Fatal(4, "Fail to map Git settings: %v", err)
  286. }
  287. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  288. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  289. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  290. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  291. }
  292. var Service struct {
  293. ActiveCodeLives int
  294. ResetPwdCodeLives int
  295. RegisterEmailConfirm bool
  296. DisableRegistration bool
  297. ShowRegistrationButton bool
  298. RequireSignInView bool
  299. EnableCacheAvatar bool
  300. EnableNotifyMail bool
  301. EnableReverseProxyAuth bool
  302. EnableReverseProxyAutoRegister bool
  303. DisableMinimumKeySizeCheck bool
  304. }
  305. func newService() {
  306. sec := Cfg.Section("service")
  307. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  308. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  309. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  310. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  311. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  312. Service.EnableCacheAvatar = sec.Key("ENABLE_CACHE_AVATAR").MustBool()
  313. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  314. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  315. Service.DisableMinimumKeySizeCheck = sec.Key("DISABLE_MINIMUM_KEY_SIZE_CHECK").MustBool()
  316. }
  317. var logLevels = map[string]string{
  318. "Trace": "0",
  319. "Debug": "1",
  320. "Info": "2",
  321. "Warn": "3",
  322. "Error": "4",
  323. "Critical": "5",
  324. }
  325. func newLogService() {
  326. log.Info("%s %s", AppName, AppVer)
  327. // Get and check log mode.
  328. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  329. LogConfigs = make([]string, len(LogModes))
  330. for i, mode := range LogModes {
  331. mode = strings.TrimSpace(mode)
  332. sec, err := Cfg.GetSection("log." + mode)
  333. if err != nil {
  334. log.Fatal(4, "Unknown log mode: %s", mode)
  335. }
  336. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  337. // Log level.
  338. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  339. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  340. validLevels)
  341. level, ok := logLevels[levelName]
  342. if !ok {
  343. log.Fatal(4, "Unknown log level: %s", levelName)
  344. }
  345. // Generate log configuration.
  346. switch mode {
  347. case "console":
  348. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  349. case "file":
  350. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  351. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  352. LogConfigs[i] = fmt.Sprintf(
  353. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  354. logPath,
  355. sec.Key("LOG_ROTATE").MustBool(true),
  356. sec.Key("MAX_LINES").MustInt(1000000),
  357. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  358. sec.Key("DAILY_ROTATE").MustBool(true),
  359. sec.Key("MAX_DAYS").MustInt(7))
  360. case "conn":
  361. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  362. sec.Key("RECONNECT_ON_MSG").MustBool(),
  363. sec.Key("RECONNECT").MustBool(),
  364. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  365. sec.Key("ADDR").MustString(":7020"))
  366. case "smtp":
  367. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  368. sec.Key("USER").MustString("example@example.com"),
  369. sec.Key("PASSWD").MustString("******"),
  370. sec.Key("HOST").MustString("127.0.0.1:25"),
  371. sec.Key("RECEIVERS").MustString("[]"),
  372. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  373. case "database":
  374. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  375. sec.Key("DRIVER").String(),
  376. sec.Key("CONN").String())
  377. }
  378. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  379. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  380. }
  381. }
  382. func newCacheService() {
  383. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  384. if EnableRedis {
  385. log.Info("Redis Enabled")
  386. }
  387. if EnableMemcache {
  388. log.Info("Memcache Enabled")
  389. }
  390. switch CacheAdapter {
  391. case "memory":
  392. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  393. case "redis", "memcache":
  394. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  395. default:
  396. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  397. }
  398. log.Info("Cache Service Enabled")
  399. }
  400. func newSessionService() {
  401. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  402. []string{"memory", "file", "redis", "mysql"})
  403. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  404. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  405. SessionConfig.CookiePath = AppSubUrl
  406. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  407. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  408. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  409. log.Info("Session Service Enabled")
  410. }
  411. // Mailer represents mail service.
  412. type Mailer struct {
  413. Name string
  414. Host string
  415. From string
  416. User, Passwd string
  417. SkipVerify bool
  418. UseCertificate bool
  419. CertFile, KeyFile string
  420. }
  421. type OauthInfo struct {
  422. oauth2.Options
  423. AuthUrl, TokenUrl string
  424. }
  425. // Oauther represents oauth service.
  426. type Oauther struct {
  427. GitHub, Google, Tencent,
  428. Twitter, Weibo bool
  429. OauthInfos map[string]*OauthInfo
  430. }
  431. var (
  432. MailService *Mailer
  433. OauthService *Oauther
  434. )
  435. func newMailService() {
  436. sec := Cfg.Section("mailer")
  437. // Check mailer setting.
  438. if !sec.Key("ENABLED").MustBool() {
  439. return
  440. }
  441. MailService = &Mailer{
  442. Name: sec.Key("NAME").MustString(AppName),
  443. Host: sec.Key("HOST").String(),
  444. User: sec.Key("USER").String(),
  445. Passwd: sec.Key("PASSWD").String(),
  446. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  447. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  448. CertFile: sec.Key("CERT_FILE").String(),
  449. KeyFile: sec.Key("KEY_FILE").String(),
  450. }
  451. MailService.From = sec.Key("FROM").MustString(MailService.User)
  452. log.Info("Mail Service Enabled")
  453. }
  454. func newRegisterMailService() {
  455. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  456. return
  457. } else if MailService == nil {
  458. log.Warn("Register Mail Service: Mail Service is not enabled")
  459. return
  460. }
  461. Service.RegisterEmailConfirm = true
  462. log.Info("Register Mail Service Enabled")
  463. }
  464. func newNotifyMailService() {
  465. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  466. return
  467. } else if MailService == nil {
  468. log.Warn("Notify Mail Service: Mail Service is not enabled")
  469. return
  470. }
  471. Service.EnableNotifyMail = true
  472. log.Info("Notify Mail Service Enabled")
  473. }
  474. func newWebhookService() {
  475. sec := Cfg.Section("webhook")
  476. Webhook.TaskInterval = sec.Key("TASK_INTERVAL").MustInt(1)
  477. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  478. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  479. }
  480. func NewServices() {
  481. newService()
  482. newLogService()
  483. newCacheService()
  484. newSessionService()
  485. newMailService()
  486. newRegisterMailService()
  487. newNotifyMailService()
  488. newWebhookService()
  489. // ssh.Listen("2222")
  490. }