setting.go 25 KB

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