setting.go 25 KB

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