setting.go 25 KB

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