setting.go 25 KB

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