setting.go 25 KB

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