setting.go 25 KB

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