setting.go 25 KB

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