setting.go 26 KB

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