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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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. "github.com/Unknwon/com"
  18. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  19. _ "github.com/go-macaron/cache/redis"
  20. "github.com/go-macaron/session"
  21. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  22. _ "github.com/kardianos/minwinsvc" // import minwinsvc for windows services
  23. "gopkg.in/ini.v1"
  24. "strk.kbt.io/projects/go/libravatar"
  25. "code.gitea.io/gitea/modules/bindata"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/user"
  28. )
  29. // Scheme describes protocol types
  30. type Scheme string
  31. // enumerates all the scheme types
  32. const (
  33. HTTP Scheme = "http"
  34. HTTPS Scheme = "https"
  35. FCGI Scheme = "fcgi"
  36. UnixSocket Scheme = "unix"
  37. )
  38. // LandingPage describes the default page
  39. type LandingPage string
  40. // enumerates all the landing page types
  41. const (
  42. LandingPageHome LandingPage = "/"
  43. LandingPageExplore LandingPage = "/explore"
  44. )
  45. // settings
  46. var (
  47. // AppVer settings
  48. AppVer string
  49. AppName string
  50. AppURL string
  51. AppSubURL string
  52. AppSubURLDepth int // Number of slashes
  53. AppPath string
  54. AppDataPath string
  55. // Server settings
  56. Protocol Scheme
  57. Domain string
  58. HTTPAddr string
  59. HTTPPort string
  60. LocalURL string
  61. OfflineMode bool
  62. DisableRouterLog bool
  63. CertFile string
  64. KeyFile string
  65. StaticRootPath string
  66. EnableGzip bool
  67. LandingPageURL LandingPage
  68. UnixSocketPermission uint32
  69. SSH struct {
  70. Disabled bool `ini:"DISABLE_SSH"`
  71. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  72. Domain string `ini:"SSH_DOMAIN"`
  73. Port int `ini:"SSH_PORT"`
  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, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  306. if err != nil {
  307. log.Fatal(4, "Fail to parse 'conf/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. // When disable SSH, start builtin server value is ignored.
  391. if SSH.Disabled {
  392. SSH.StartBuiltinServer = false
  393. }
  394. if !SSH.Disabled && !SSH.StartBuiltinServer {
  395. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  396. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  397. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  398. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  399. }
  400. }
  401. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  402. SSH.MinimumKeySizes = map[string]int{}
  403. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  404. for _, key := range minimumKeySizes {
  405. if key.MustInt() != -1 {
  406. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  407. }
  408. }
  409. sec = Cfg.Section("security")
  410. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  411. SecretKey = sec.Key("SECRET_KEY").String()
  412. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  413. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  414. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  415. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  416. sec = Cfg.Section("attachment")
  417. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  418. if !filepath.IsAbs(AttachmentPath) {
  419. AttachmentPath = path.Join(workDir, AttachmentPath)
  420. }
  421. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  422. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  423. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  424. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  425. TimeFormat = map[string]string{
  426. "ANSIC": time.ANSIC,
  427. "UnixDate": time.UnixDate,
  428. "RubyDate": time.RubyDate,
  429. "RFC822": time.RFC822,
  430. "RFC822Z": time.RFC822Z,
  431. "RFC850": time.RFC850,
  432. "RFC1123": time.RFC1123,
  433. "RFC1123Z": time.RFC1123Z,
  434. "RFC3339": time.RFC3339,
  435. "RFC3339Nano": time.RFC3339Nano,
  436. "Kitchen": time.Kitchen,
  437. "Stamp": time.Stamp,
  438. "StampMilli": time.StampMilli,
  439. "StampMicro": time.StampMicro,
  440. "StampNano": time.StampNano,
  441. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  442. RunUser = Cfg.Section("").Key("RUN_USER").String()
  443. // Does not check run user when the install lock is off.
  444. if InstallLock {
  445. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  446. if !match {
  447. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  448. }
  449. }
  450. // Determine and create root git repository path.
  451. sec = Cfg.Section("repository")
  452. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  453. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  454. forcePathSeparator(RepoRootPath)
  455. if !filepath.IsAbs(RepoRootPath) {
  456. RepoRootPath = path.Join(workDir, RepoRootPath)
  457. } else {
  458. RepoRootPath = path.Clean(RepoRootPath)
  459. }
  460. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  461. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  462. log.Fatal(4, "Fail to map Repository settings: %v", err)
  463. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  464. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  465. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  466. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  467. }
  468. if !filepath.IsAbs(Repository.Upload.TempPath) {
  469. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  470. }
  471. sec = Cfg.Section("picture")
  472. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  473. forcePathSeparator(AvatarUploadPath)
  474. if !filepath.IsAbs(AvatarUploadPath) {
  475. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  476. }
  477. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  478. case "duoshuo":
  479. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  480. case "gravatar":
  481. GravatarSource = "https://secure.gravatar.com/avatar/"
  482. case "libravatar":
  483. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  484. default:
  485. GravatarSource = source
  486. }
  487. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  488. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  489. if OfflineMode {
  490. DisableGravatar = true
  491. EnableFederatedAvatar = false
  492. }
  493. if DisableGravatar {
  494. EnableFederatedAvatar = false
  495. }
  496. if EnableFederatedAvatar {
  497. LibravatarService = libravatar.New()
  498. parts := strings.Split(GravatarSource, "/")
  499. if len(parts) >= 3 {
  500. if parts[0] == "https:" {
  501. LibravatarService.SetUseHTTPS(true)
  502. LibravatarService.SetSecureFallbackHost(parts[2])
  503. } else {
  504. LibravatarService.SetUseHTTPS(false)
  505. LibravatarService.SetFallbackHost(parts[2])
  506. }
  507. }
  508. }
  509. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  510. log.Fatal(4, "Fail to map UI settings: %v", err)
  511. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  512. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  513. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  514. log.Fatal(4, "Fail to map Cron settings: %v", err)
  515. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  516. log.Fatal(4, "Fail to map Git settings: %v", err)
  517. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  518. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  519. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  520. log.Fatal(4, "Fail to map API settings: %v", err)
  521. }
  522. if Mirror.DefaultInterval <= 0 {
  523. Mirror.DefaultInterval = 24
  524. }
  525. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  526. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  527. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  528. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  529. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  530. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  531. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  532. }
  533. // Service settings
  534. var Service struct {
  535. ActiveCodeLives int
  536. ResetPwdCodeLives int
  537. RegisterEmailConfirm bool
  538. DisableRegistration bool
  539. ShowRegistrationButton bool
  540. RequireSignInView bool
  541. EnableNotifyMail bool
  542. EnableReverseProxyAuth bool
  543. EnableReverseProxyAutoRegister bool
  544. EnableCaptcha bool
  545. }
  546. func newService() {
  547. sec := Cfg.Section("service")
  548. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  549. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  550. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  551. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  552. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  553. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  554. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  555. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  556. }
  557. var logLevels = map[string]string{
  558. "Trace": "0",
  559. "Debug": "1",
  560. "Info": "2",
  561. "Warn": "3",
  562. "Error": "4",
  563. "Critical": "5",
  564. }
  565. func newLogService() {
  566. log.Info("%s %s", AppName, AppVer)
  567. // Get and check log mode.
  568. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  569. LogConfigs = make([]string, len(LogModes))
  570. for i, mode := range LogModes {
  571. mode = strings.TrimSpace(mode)
  572. sec, err := Cfg.GetSection("log." + mode)
  573. if err != nil {
  574. log.Fatal(4, "Unknown log mode: %s", mode)
  575. }
  576. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  577. // Log level.
  578. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  579. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  580. validLevels)
  581. level, ok := logLevels[levelName]
  582. if !ok {
  583. log.Fatal(4, "Unknown log level: %s", levelName)
  584. }
  585. // Generate log configuration.
  586. switch mode {
  587. case "console":
  588. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  589. case "file":
  590. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  591. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  592. panic(err.Error())
  593. }
  594. LogConfigs[i] = fmt.Sprintf(
  595. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  596. logPath,
  597. sec.Key("LOG_ROTATE").MustBool(true),
  598. sec.Key("MAX_LINES").MustInt(1000000),
  599. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  600. sec.Key("DAILY_ROTATE").MustBool(true),
  601. sec.Key("MAX_DAYS").MustInt(7))
  602. case "conn":
  603. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  604. sec.Key("RECONNECT_ON_MSG").MustBool(),
  605. sec.Key("RECONNECT").MustBool(),
  606. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  607. sec.Key("ADDR").MustString(":7020"))
  608. case "smtp":
  609. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  610. sec.Key("USER").MustString("example@example.com"),
  611. sec.Key("PASSWD").MustString("******"),
  612. sec.Key("HOST").MustString("127.0.0.1:25"),
  613. sec.Key("RECEIVERS").MustString("[]"),
  614. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  615. case "database":
  616. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  617. sec.Key("DRIVER").String(),
  618. sec.Key("CONN").String())
  619. }
  620. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  621. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  622. }
  623. }
  624. func newCacheService() {
  625. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  626. switch CacheAdapter {
  627. case "memory":
  628. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  629. case "redis", "memcache":
  630. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  631. default:
  632. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  633. }
  634. log.Info("Cache Service Enabled")
  635. }
  636. func newSessionService() {
  637. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  638. []string{"memory", "file", "redis", "mysql"})
  639. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  640. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  641. SessionConfig.CookiePath = AppSubURL
  642. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  643. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  644. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  645. log.Info("Session Service Enabled")
  646. }
  647. // Mailer represents mail service.
  648. type Mailer struct {
  649. QueueLength int
  650. Name string
  651. Host string
  652. From string
  653. FromEmail string
  654. User, Passwd string
  655. DisableHelo bool
  656. HeloHostname string
  657. SkipVerify bool
  658. UseCertificate bool
  659. CertFile, KeyFile string
  660. EnableHTMLAlternative bool
  661. }
  662. var (
  663. // MailService the global mailer
  664. MailService *Mailer
  665. )
  666. func newMailService() {
  667. sec := Cfg.Section("mailer")
  668. // Check mailer setting.
  669. if !sec.Key("ENABLED").MustBool() {
  670. return
  671. }
  672. MailService = &Mailer{
  673. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  674. Name: sec.Key("NAME").MustString(AppName),
  675. Host: sec.Key("HOST").String(),
  676. User: sec.Key("USER").String(),
  677. Passwd: sec.Key("PASSWD").String(),
  678. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  679. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  680. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  681. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  682. CertFile: sec.Key("CERT_FILE").String(),
  683. KeyFile: sec.Key("KEY_FILE").String(),
  684. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  685. }
  686. MailService.From = sec.Key("FROM").MustString(MailService.User)
  687. parsed, err := mail.ParseAddress(MailService.From)
  688. if err != nil {
  689. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  690. }
  691. MailService.FromEmail = parsed.Address
  692. log.Info("Mail Service Enabled")
  693. }
  694. func newRegisterMailService() {
  695. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  696. return
  697. } else if MailService == nil {
  698. log.Warn("Register Mail Service: Mail Service is not enabled")
  699. return
  700. }
  701. Service.RegisterEmailConfirm = true
  702. log.Info("Register Mail Service Enabled")
  703. }
  704. func newNotifyMailService() {
  705. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  706. return
  707. } else if MailService == nil {
  708. log.Warn("Notify Mail Service: Mail Service is not enabled")
  709. return
  710. }
  711. Service.EnableNotifyMail = true
  712. log.Info("Notify Mail Service Enabled")
  713. }
  714. func newWebhookService() {
  715. sec := Cfg.Section("webhook")
  716. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  717. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  718. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  719. Webhook.Types = []string{"gogs", "slack"}
  720. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  721. }
  722. // NewServices initializes the services
  723. func NewServices() {
  724. newService()
  725. newLogService()
  726. newCacheService()
  727. newSessionService()
  728. newMailService()
  729. newRegisterMailService()
  730. newNotifyMailService()
  731. newWebhookService()
  732. }