You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 25KB

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