setting.go 25 KB

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