setting.go 26 KB

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