setting.go 25 KB

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