setting.go 24 KB

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