setting.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. "net/mail"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. _ "github.com/go-macaron/cache/memcache"
  18. _ "github.com/go-macaron/cache/redis"
  19. "github.com/go-macaron/session"
  20. _ "github.com/go-macaron/session/redis"
  21. log "gopkg.in/clog.v1"
  22. "gopkg.in/ini.v1"
  23. "github.com/gogits/go-libravatar"
  24. "github.com/gogits/gogs/modules/bindata"
  25. "github.com/gogits/gogs/modules/user"
  26. )
  27. type Scheme string
  28. const (
  29. SCHEME_HTTP Scheme = "http"
  30. SCHEME_HTTPS Scheme = "https"
  31. SCHEME_FCGI Scheme = "fcgi"
  32. SCHEME_UNIX_SOCKET Scheme = "unix"
  33. )
  34. type LandingPage string
  35. const (
  36. LANDING_PAGE_HOME LandingPage = "/"
  37. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  38. )
  39. var (
  40. // Build information should only be set by -ldflags.
  41. BuildTime string
  42. BuildGitHash string
  43. // App settings
  44. AppVer string
  45. AppName string
  46. AppUrl string
  47. AppSubUrl string
  48. AppSubUrlDepth int // Number of slashes
  49. AppPath string
  50. AppDataPath string
  51. // Server settings
  52. Protocol Scheme
  53. Domain string
  54. HTTPAddr, HTTPPort string
  55. LocalURL string
  56. OfflineMode bool
  57. DisableRouterLog bool
  58. CertFile, KeyFile string
  59. StaticRootPath string
  60. EnableGzip bool
  61. LandingPageURL LandingPage
  62. UnixSocketPermission uint32
  63. HTTP struct {
  64. AccessControlAllowOrigin string
  65. }
  66. SSH struct {
  67. Disabled bool `ini:"DISABLE_SSH"`
  68. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  69. Domain string `ini:"SSH_DOMAIN"`
  70. Port int `ini:"SSH_PORT"`
  71. ListenHost string `ini:"SSH_LISTEN_HOST"`
  72. ListenPort int `ini:"SSH_LISTEN_PORT"`
  73. RootPath string `ini:"SSH_ROOT_PATH"`
  74. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  75. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  76. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  77. MinimumKeySizeCheck bool `ini:"-"`
  78. MinimumKeySizes map[string]int `ini:"-"`
  79. }
  80. // Security settings
  81. InstallLock bool
  82. SecretKey string
  83. LogInRememberDays int
  84. CookieUserName string
  85. CookieRememberName string
  86. ReverseProxyAuthUser string
  87. // Database settings
  88. UseSQLite3 bool
  89. UseMySQL bool
  90. UsePostgreSQL bool
  91. UseTiDB bool
  92. // Webhook settings
  93. Webhook struct {
  94. QueueLength int
  95. DeliverTimeout int
  96. SkipTLSVerify bool
  97. Types []string
  98. PagingNum int
  99. }
  100. // Repository settings
  101. Repository struct {
  102. AnsiCharset string
  103. ForcePrivate bool
  104. MaxCreationLimit int
  105. MirrorQueueLength int
  106. PullRequestQueueLength int
  107. PreferredLicenses []string
  108. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  109. EnableLocalPathMigration bool
  110. // Repository editor settings
  111. Editor struct {
  112. LineWrapExtensions []string
  113. PreviewableFileModes []string
  114. } `ini:"-"`
  115. // Repository upload settings
  116. Upload struct {
  117. Enabled bool
  118. TempPath string
  119. AllowedTypes []string `delim:"|"`
  120. FileMaxSize int64
  121. MaxFiles int
  122. } `ini:"-"`
  123. }
  124. RepoRootPath string
  125. ScriptType string
  126. // UI settings
  127. UI struct {
  128. ExplorePagingNum int
  129. IssuePagingNum int
  130. FeedMaxCommitNum int
  131. ThemeColorMetaTag string
  132. MaxDisplayFileSize int64
  133. Admin struct {
  134. UserPagingNum int
  135. RepoPagingNum int
  136. NoticePagingNum int
  137. OrgPagingNum int
  138. } `ini:"ui.admin"`
  139. User struct {
  140. RepoPagingNum int
  141. } `ini:"ui.user"`
  142. }
  143. // Markdown sttings
  144. Markdown struct {
  145. EnableHardLineBreak bool
  146. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  147. FileExtensions []string
  148. }
  149. // Picture settings
  150. AvatarUploadPath string
  151. GravatarSource string
  152. DisableGravatar bool
  153. EnableFederatedAvatar bool
  154. LibravatarService *libravatar.Libravatar
  155. // Log settings
  156. LogRootPath string
  157. LogModes []string
  158. LogConfigs []interface{}
  159. // Attachment settings
  160. AttachmentPath string
  161. AttachmentAllowedTypes string
  162. AttachmentMaxSize int64
  163. AttachmentMaxFiles int
  164. AttachmentEnabled bool
  165. // Time settings
  166. TimeFormat string
  167. // Cache settings
  168. CacheAdapter string
  169. CacheInterval int
  170. CacheConn string
  171. // Session settings
  172. SessionConfig session.Options
  173. CSRFCookieName = "_csrf"
  174. // Cron tasks
  175. Cron struct {
  176. UpdateMirror struct {
  177. Enabled bool
  178. RunAtStart bool
  179. Schedule string
  180. } `ini:"cron.update_mirrors"`
  181. RepoHealthCheck struct {
  182. Enabled bool
  183. RunAtStart bool
  184. Schedule string
  185. Timeout time.Duration
  186. Args []string `delim:" "`
  187. } `ini:"cron.repo_health_check"`
  188. CheckRepoStats struct {
  189. Enabled bool
  190. RunAtStart bool
  191. Schedule string
  192. } `ini:"cron.check_repo_stats"`
  193. }
  194. // Git settings
  195. Git struct {
  196. DisableDiffHighlight bool
  197. MaxGitDiffLines int
  198. MaxGitDiffLineCharacters int
  199. MaxGitDiffFiles int
  200. GCArgs []string `delim:" "`
  201. Timeout struct {
  202. Migrate int
  203. Mirror int
  204. Clone int
  205. Pull int
  206. GC int `ini:"GC"`
  207. } `ini:"git.timeout"`
  208. }
  209. // Mirror settings
  210. Mirror struct {
  211. DefaultInterval int
  212. }
  213. // API settings
  214. API struct {
  215. MaxResponseItems int
  216. }
  217. // I18n settings
  218. Langs, Names []string
  219. dateLangs map[string]string
  220. // Highlight settings are loaded in modules/template/hightlight.go
  221. // Other settings
  222. ShowFooterBranding bool
  223. ShowFooterVersion bool
  224. ShowFooterTemplateLoadTime bool
  225. SupportMiniWinService bool
  226. // Global setting objects
  227. Cfg *ini.File
  228. CustomPath string // Custom directory path
  229. CustomConf string
  230. ProdMode bool
  231. RunUser string
  232. IsWindows bool
  233. HasRobotsTxt bool
  234. )
  235. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  236. func DateLang(lang string) string {
  237. name, ok := dateLangs[lang]
  238. if ok {
  239. return name
  240. }
  241. return "en"
  242. }
  243. // execPath returns the executable path.
  244. func execPath() (string, error) {
  245. file, err := exec.LookPath(os.Args[0])
  246. if err != nil {
  247. return "", err
  248. }
  249. return filepath.Abs(file)
  250. }
  251. func init() {
  252. IsWindows = runtime.GOOS == "windows"
  253. log.New(log.CONSOLE, log.ConsoleConfig{})
  254. var err error
  255. if AppPath, err = execPath(); err != nil {
  256. log.Fatal(4, "Fail to get app path: %v\n", err)
  257. }
  258. // Note: we don't use path.Dir here because it does not handle case
  259. // which path starts with two "/" in Windows: "//psf/Home/..."
  260. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  261. }
  262. // WorkDir returns absolute path of work directory.
  263. func WorkDir() (string, error) {
  264. wd := os.Getenv("GOGS_WORK_DIR")
  265. if len(wd) > 0 {
  266. return wd, nil
  267. }
  268. i := strings.LastIndex(AppPath, "/")
  269. if i == -1 {
  270. return AppPath, nil
  271. }
  272. return AppPath[:i], nil
  273. }
  274. func forcePathSeparator(path string) {
  275. if strings.Contains(path, "\\") {
  276. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  277. }
  278. }
  279. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  280. // actual user that runs the app. The first return value is the actual user name.
  281. // This check is ignored under Windows since SSH remote login is not the main
  282. // method to login on Windows.
  283. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  284. if IsWindows {
  285. return "", true
  286. }
  287. currentUser := user.CurrentUsername()
  288. return currentUser, runUser == currentUser
  289. }
  290. // NewContext initializes configuration context.
  291. // NOTE: do not print any log except error.
  292. func NewContext() {
  293. workDir, err := WorkDir()
  294. if err != nil {
  295. log.Fatal(4, "Fail to get work directory: %v", err)
  296. }
  297. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  298. if err != nil {
  299. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  300. }
  301. CustomPath = os.Getenv("GOGS_CUSTOM")
  302. if len(CustomPath) == 0 {
  303. CustomPath = workDir + "/custom"
  304. }
  305. if len(CustomConf) == 0 {
  306. CustomConf = CustomPath + "/conf/app.ini"
  307. }
  308. if com.IsFile(CustomConf) {
  309. if err = Cfg.Append(CustomConf); err != nil {
  310. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  311. }
  312. } else {
  313. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  314. }
  315. Cfg.NameMapper = ini.AllCapsUnderscore
  316. homeDir, err := com.HomeDir()
  317. if err != nil {
  318. log.Fatal(4, "Fail to get home directory: %v", err)
  319. }
  320. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  321. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  322. forcePathSeparator(LogRootPath)
  323. sec := Cfg.Section("server")
  324. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  325. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  326. if AppUrl[len(AppUrl)-1] != '/' {
  327. AppUrl += "/"
  328. }
  329. // Check if has app suburl.
  330. url, err := url.Parse(AppUrl)
  331. if err != nil {
  332. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
  333. }
  334. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  335. // This value is empty if site does not have sub-url.
  336. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  337. AppSubUrlDepth = strings.Count(AppSubUrl, "/")
  338. Protocol = SCHEME_HTTP
  339. if sec.Key("PROTOCOL").String() == "https" {
  340. Protocol = SCHEME_HTTPS
  341. CertFile = sec.Key("CERT_FILE").String()
  342. KeyFile = sec.Key("KEY_FILE").String()
  343. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  344. Protocol = SCHEME_FCGI
  345. } else if sec.Key("PROTOCOL").String() == "unix" {
  346. Protocol = SCHEME_UNIX_SOCKET
  347. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  348. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  349. if err != nil || UnixSocketPermissionParsed > 0777 {
  350. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  351. }
  352. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  353. }
  354. Domain = sec.Key("DOMAIN").MustString("localhost")
  355. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  356. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  357. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  358. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  359. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  360. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  361. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  362. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  363. switch sec.Key("LANDING_PAGE").MustString("home") {
  364. case "explore":
  365. LandingPageURL = LANDING_PAGE_EXPLORE
  366. default:
  367. LandingPageURL = LANDING_PAGE_HOME
  368. }
  369. SSH.RootPath = path.Join(homeDir, ".ssh")
  370. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  371. SSH.KeyTestPath = os.TempDir()
  372. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  373. log.Fatal(4, "Fail to map SSH settings: %v", err)
  374. }
  375. // When disable SSH, start builtin server value is ignored.
  376. if SSH.Disabled {
  377. SSH.StartBuiltinServer = false
  378. }
  379. if !SSH.Disabled && !SSH.StartBuiltinServer {
  380. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  381. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  382. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  383. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  384. }
  385. }
  386. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  387. SSH.MinimumKeySizes = map[string]int{}
  388. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  389. for _, key := range minimumKeySizes {
  390. if key.MustInt() != -1 {
  391. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  392. }
  393. }
  394. sec = Cfg.Section("security")
  395. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  396. SecretKey = sec.Key("SECRET_KEY").String()
  397. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  398. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  399. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  400. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  401. sec = Cfg.Section("attachment")
  402. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  403. if !filepath.IsAbs(AttachmentPath) {
  404. AttachmentPath = path.Join(workDir, AttachmentPath)
  405. }
  406. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  407. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  408. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  409. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  410. TimeFormat = map[string]string{
  411. "ANSIC": time.ANSIC,
  412. "UnixDate": time.UnixDate,
  413. "RubyDate": time.RubyDate,
  414. "RFC822": time.RFC822,
  415. "RFC822Z": time.RFC822Z,
  416. "RFC850": time.RFC850,
  417. "RFC1123": time.RFC1123,
  418. "RFC1123Z": time.RFC1123Z,
  419. "RFC3339": time.RFC3339,
  420. "RFC3339Nano": time.RFC3339Nano,
  421. "Kitchen": time.Kitchen,
  422. "Stamp": time.Stamp,
  423. "StampMilli": time.StampMilli,
  424. "StampMicro": time.StampMicro,
  425. "StampNano": time.StampNano,
  426. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  427. RunUser = Cfg.Section("").Key("RUN_USER").String()
  428. // Does not check run user when the install lock is off.
  429. if InstallLock {
  430. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  431. if !match {
  432. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  433. }
  434. }
  435. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  436. // Determine and create root git repository path.
  437. sec = Cfg.Section("repository")
  438. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  439. forcePathSeparator(RepoRootPath)
  440. if !filepath.IsAbs(RepoRootPath) {
  441. RepoRootPath = path.Join(workDir, RepoRootPath)
  442. } else {
  443. RepoRootPath = path.Clean(RepoRootPath)
  444. }
  445. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  446. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  447. log.Fatal(4, "Fail to map Repository settings: %v", err)
  448. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  449. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  450. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  451. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  452. }
  453. if !filepath.IsAbs(Repository.Upload.TempPath) {
  454. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  455. }
  456. sec = Cfg.Section("picture")
  457. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  458. forcePathSeparator(AvatarUploadPath)
  459. if !filepath.IsAbs(AvatarUploadPath) {
  460. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  461. }
  462. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  463. case "duoshuo":
  464. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  465. case "gravatar":
  466. GravatarSource = "https://secure.gravatar.com/avatar/"
  467. case "libravatar":
  468. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  469. default:
  470. GravatarSource = source
  471. }
  472. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  473. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  474. if OfflineMode {
  475. DisableGravatar = true
  476. EnableFederatedAvatar = false
  477. }
  478. if DisableGravatar {
  479. EnableFederatedAvatar = false
  480. }
  481. if EnableFederatedAvatar {
  482. LibravatarService = libravatar.New()
  483. parts := strings.Split(GravatarSource, "/")
  484. if len(parts) >= 3 {
  485. if parts[0] == "https:" {
  486. LibravatarService.SetUseHTTPS(true)
  487. LibravatarService.SetSecureFallbackHost(parts[2])
  488. } else {
  489. LibravatarService.SetUseHTTPS(false)
  490. LibravatarService.SetFallbackHost(parts[2])
  491. }
  492. }
  493. }
  494. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  495. log.Fatal(4, "Fail to map HTTP settings: %v", err)
  496. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  497. log.Fatal(4, "Fail to map UI settings: %v", err)
  498. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  499. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  500. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  501. log.Fatal(4, "Fail to map Cron settings: %v", err)
  502. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  503. log.Fatal(4, "Fail to map Git settings: %v", err)
  504. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  505. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  506. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  507. log.Fatal(4, "Fail to map API settings: %v", err)
  508. }
  509. if Mirror.DefaultInterval <= 0 {
  510. Mirror.DefaultInterval = 24
  511. }
  512. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  513. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  514. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  515. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  516. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  517. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  518. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  519. }
  520. var Service struct {
  521. ActiveCodeLives int
  522. ResetPwdCodeLives int
  523. RegisterEmailConfirm bool
  524. DisableRegistration bool
  525. ShowRegistrationButton bool
  526. RequireSignInView bool
  527. EnableNotifyMail bool
  528. EnableReverseProxyAuth bool
  529. EnableReverseProxyAutoRegister bool
  530. EnableCaptcha bool
  531. }
  532. func newService() {
  533. sec := Cfg.Section("service")
  534. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  535. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  536. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  537. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  538. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  539. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  540. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  541. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  542. }
  543. func newLogService() {
  544. if len(BuildTime) > 0 {
  545. log.Info("Build Time: %s", BuildTime)
  546. log.Info("Build Git Hash: %s", BuildGitHash)
  547. }
  548. // Because we always create a console logger as primary logger before all settings are loaded,
  549. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  550. hasConsole := false
  551. // Get and check log modes.
  552. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  553. LogConfigs = make([]interface{}, len(LogModes))
  554. levelNames := map[string]log.LEVEL{
  555. "trace": log.TRACE,
  556. "info": log.INFO,
  557. "warn": log.WARN,
  558. "error": log.ERROR,
  559. "fatal": log.FATAL,
  560. }
  561. for i, mode := range LogModes {
  562. mode = strings.ToLower(strings.TrimSpace(mode))
  563. sec, err := Cfg.GetSection("log." + mode)
  564. if err != nil {
  565. log.Fatal(4, "Unknown logger mode: %s", mode)
  566. }
  567. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  568. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  569. v = strings.ToLower(v)
  570. if com.IsSliceContainsStr(validLevels, v) {
  571. return v
  572. }
  573. return "trace"
  574. })
  575. level := levelNames[name]
  576. // Generate log configuration.
  577. switch log.MODE(mode) {
  578. case log.CONSOLE:
  579. hasConsole = true
  580. LogConfigs[i] = log.ConsoleConfig{
  581. Level: level,
  582. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  583. }
  584. case log.FILE:
  585. logPath := path.Join(LogRootPath, "gogs.log")
  586. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  587. log.Fatal(4, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  588. }
  589. LogConfigs[i] = log.FileConfig{
  590. Level: level,
  591. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  592. Filename: logPath,
  593. FileRotationConfig: log.FileRotationConfig{
  594. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  595. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  596. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  597. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  598. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  599. },
  600. }
  601. case log.SLACK:
  602. LogConfigs[i] = log.SlackConfig{
  603. Level: level,
  604. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  605. URL: sec.Key("URL").String(),
  606. }
  607. }
  608. log.New(log.MODE(mode), LogConfigs[i])
  609. log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(name))
  610. }
  611. // Make sure everyone gets version info printed.
  612. log.Info("%s %s", AppName, AppVer)
  613. if !hasConsole {
  614. log.Delete(log.CONSOLE)
  615. }
  616. }
  617. func newCacheService() {
  618. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  619. switch CacheAdapter {
  620. case "memory":
  621. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  622. case "redis", "memcache":
  623. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  624. default:
  625. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  626. }
  627. log.Info("Cache Service Enabled")
  628. }
  629. func newSessionService() {
  630. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  631. []string{"memory", "file", "redis", "mysql"})
  632. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  633. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  634. SessionConfig.CookiePath = AppSubUrl
  635. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  636. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  637. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  638. log.Info("Session Service Enabled")
  639. }
  640. // Mailer represents mail service.
  641. type Mailer struct {
  642. QueueLength int
  643. Name string
  644. Host string
  645. From string
  646. FromEmail string
  647. User, Passwd string
  648. DisableHelo bool
  649. HeloHostname string
  650. SkipVerify bool
  651. UseCertificate bool
  652. CertFile, KeyFile string
  653. EnableHTMLAlternative bool
  654. }
  655. var (
  656. MailService *Mailer
  657. )
  658. func newMailService() {
  659. sec := Cfg.Section("mailer")
  660. // Check mailer setting.
  661. if !sec.Key("ENABLED").MustBool() {
  662. return
  663. }
  664. MailService = &Mailer{
  665. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  666. Name: sec.Key("NAME").MustString(AppName),
  667. Host: sec.Key("HOST").String(),
  668. User: sec.Key("USER").String(),
  669. Passwd: sec.Key("PASSWD").String(),
  670. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  671. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  672. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  673. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  674. CertFile: sec.Key("CERT_FILE").String(),
  675. KeyFile: sec.Key("KEY_FILE").String(),
  676. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  677. }
  678. MailService.From = sec.Key("FROM").MustString(MailService.User)
  679. parsed, err := mail.ParseAddress(MailService.From)
  680. if err != nil {
  681. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  682. }
  683. MailService.FromEmail = parsed.Address
  684. log.Info("Mail Service Enabled")
  685. }
  686. func newRegisterMailService() {
  687. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  688. return
  689. } else if MailService == nil {
  690. log.Warn("Register Mail Service: Mail Service is not enabled")
  691. return
  692. }
  693. Service.RegisterEmailConfirm = true
  694. log.Info("Register Mail Service Enabled")
  695. }
  696. func newNotifyMailService() {
  697. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  698. return
  699. } else if MailService == nil {
  700. log.Warn("Notify Mail Service: Mail Service is not enabled")
  701. return
  702. }
  703. Service.EnableNotifyMail = true
  704. log.Info("Notify Mail Service Enabled")
  705. }
  706. func newWebhookService() {
  707. sec := Cfg.Section("webhook")
  708. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  709. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  710. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  711. Webhook.Types = []string{"gogs", "slack"}
  712. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  713. }
  714. func NewService() {
  715. newService()
  716. }
  717. func NewServices() {
  718. newService()
  719. newLogService()
  720. newCacheService()
  721. newSessionService()
  722. newMailService()
  723. newRegisterMailService()
  724. newNotifyMailService()
  725. newWebhookService()
  726. }