setting.go 24 KB

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