setting.go 25 KB

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