setting.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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"
  19. _ "github.com/go-macaron/cache/redis"
  20. "github.com/go-macaron/session"
  21. _ "github.com/go-macaron/session/redis"
  22. "gopkg.in/ini.v1"
  23. "github.com/gogits/go-libravatar"
  24. "github.com/gogits/gogs/modules/bindata"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/user"
  27. )
  28. type Scheme string
  29. const (
  30. SCHEME_HTTP Scheme = "http"
  31. SCHEME_HTTPS Scheme = "https"
  32. SCHEME_FCGI Scheme = "fcgi"
  33. SCHEME_UNIX_SOCKET Scheme = "unix"
  34. )
  35. type LandingPage string
  36. const (
  37. LANDING_PAGE_HOME LandingPage = "/"
  38. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  39. )
  40. var (
  41. // Build information should only be set by -ldflags.
  42. BuildTime string
  43. BuildGitHash string
  44. // App settings
  45. AppVer string
  46. AppName string
  47. AppUrl string
  48. AppSubUrl string
  49. AppSubUrlDepth int // Number of slashes
  50. AppPath string
  51. AppDataPath string
  52. // Server settings
  53. Protocol Scheme
  54. Domain string
  55. HTTPAddr, 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. 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. ReverseProxyAuthUser string
  87. // Database settings
  88. UseSQLite3 bool
  89. UseMySQL bool
  90. UsePostgreSQL bool
  91. UseTiDB bool
  92. // Webhook settings
  93. Webhook struct {
  94. QueueLength int
  95. DeliverTimeout int
  96. SkipTLSVerify bool
  97. Types []string
  98. PagingNum int
  99. }
  100. // Repository settings
  101. Repository struct {
  102. AnsiCharset string
  103. ForcePrivate bool
  104. MaxCreationLimit int
  105. MirrorQueueLength int
  106. PullRequestQueueLength int
  107. PreferredLicenses []string
  108. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  109. EnableLocalPathMigration 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, Names []string
  219. dateLangs map[string]string
  220. // Highlight settings are loaded in modules/template/hightlight.go
  221. // Other settings
  222. ShowFooterBranding bool
  223. ShowFooterVersion bool
  224. ShowFooterTemplateLoadTime bool
  225. SupportMiniWinService 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("GOGS_WORK_DIR")
  265. if len(wd) > 0 {
  266. return wd, nil
  267. }
  268. i := strings.LastIndex(AppPath, "/")
  269. if i == -1 {
  270. return AppPath, nil
  271. }
  272. return AppPath[:i], nil
  273. }
  274. func forcePathSeparator(path string) {
  275. if strings.Contains(path, "\\") {
  276. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  277. }
  278. }
  279. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  280. // actual user that runs the app. The first return value is the actual user name.
  281. // This check is ignored under Windows since SSH remote login is not the main
  282. // method to login on Windows.
  283. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  284. if IsWindows {
  285. return "", true
  286. }
  287. currentUser := user.CurrentUsername()
  288. return currentUser, runUser == currentUser
  289. }
  290. // NewContext initializes configuration context.
  291. // NOTE: do not print any log except error.
  292. func NewContext() {
  293. workDir, err := WorkDir()
  294. if err != nil {
  295. log.Fatal(4, "Fail to get work directory: %v", err)
  296. }
  297. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  298. if err != nil {
  299. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  300. }
  301. CustomPath = os.Getenv("GOGS_CUSTOM")
  302. if len(CustomPath) == 0 {
  303. CustomPath = workDir + "/custom"
  304. }
  305. if len(CustomConf) == 0 {
  306. CustomConf = CustomPath + "/conf/app.ini"
  307. }
  308. if com.IsFile(CustomConf) {
  309. if err = Cfg.Append(CustomConf); err != nil {
  310. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  311. }
  312. } else {
  313. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  314. }
  315. Cfg.NameMapper = ini.AllCapsUnderscore
  316. homeDir, err := com.HomeDir()
  317. if err != nil {
  318. log.Fatal(4, "Fail to get home directory: %v", err)
  319. }
  320. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  321. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  322. forcePathSeparator(LogRootPath)
  323. sec := Cfg.Section("server")
  324. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  325. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  326. if AppUrl[len(AppUrl)-1] != '/' {
  327. AppUrl += "/"
  328. }
  329. // Check if has app suburl.
  330. url, err := url.Parse(AppUrl)
  331. if err != nil {
  332. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
  333. }
  334. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  335. // This value is empty if site does not have sub-url.
  336. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  337. AppSubUrlDepth = strings.Count(AppSubUrl, "/")
  338. Protocol = SCHEME_HTTP
  339. if sec.Key("PROTOCOL").String() == "https" {
  340. Protocol = SCHEME_HTTPS
  341. CertFile = sec.Key("CERT_FILE").String()
  342. KeyFile = sec.Key("KEY_FILE").String()
  343. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  344. Protocol = SCHEME_FCGI
  345. } else if sec.Key("PROTOCOL").String() == "unix" {
  346. Protocol = SCHEME_UNIX_SOCKET
  347. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  348. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  349. if err != nil || UnixSocketPermissionParsed > 0777 {
  350. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  351. }
  352. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  353. }
  354. Domain = sec.Key("DOMAIN").MustString("localhost")
  355. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  356. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  357. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  358. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  359. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  360. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  361. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  362. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  363. switch sec.Key("LANDING_PAGE").MustString("home") {
  364. case "explore":
  365. LandingPageURL = LANDING_PAGE_EXPLORE
  366. default:
  367. LandingPageURL = LANDING_PAGE_HOME
  368. }
  369. SSH.RootPath = path.Join(homeDir, ".ssh")
  370. SSH.KeyTestPath = os.TempDir()
  371. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  372. log.Fatal(4, "Fail to map SSH settings: %v", err)
  373. }
  374. // When disable SSH, start builtin server value is ignored.
  375. if SSH.Disabled {
  376. SSH.StartBuiltinServer = false
  377. }
  378. if !SSH.Disabled && !SSH.StartBuiltinServer {
  379. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  380. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  381. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  382. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  383. }
  384. }
  385. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  386. SSH.MinimumKeySizes = map[string]int{}
  387. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  388. for _, key := range minimumKeySizes {
  389. if key.MustInt() != -1 {
  390. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  391. }
  392. }
  393. sec = Cfg.Section("security")
  394. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  395. SecretKey = sec.Key("SECRET_KEY").String()
  396. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  397. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  398. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  399. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  400. sec = Cfg.Section("attachment")
  401. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  402. if !filepath.IsAbs(AttachmentPath) {
  403. AttachmentPath = path.Join(workDir, AttachmentPath)
  404. }
  405. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  406. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  407. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  408. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  409. TimeFormat = map[string]string{
  410. "ANSIC": time.ANSIC,
  411. "UnixDate": time.UnixDate,
  412. "RubyDate": time.RubyDate,
  413. "RFC822": time.RFC822,
  414. "RFC822Z": time.RFC822Z,
  415. "RFC850": time.RFC850,
  416. "RFC1123": time.RFC1123,
  417. "RFC1123Z": time.RFC1123Z,
  418. "RFC3339": time.RFC3339,
  419. "RFC3339Nano": time.RFC3339Nano,
  420. "Kitchen": time.Kitchen,
  421. "Stamp": time.Stamp,
  422. "StampMilli": time.StampMilli,
  423. "StampMicro": time.StampMicro,
  424. "StampNano": time.StampNano,
  425. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  426. RunUser = Cfg.Section("").Key("RUN_USER").String()
  427. // Does not check run user when the install lock is off.
  428. if InstallLock {
  429. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  430. if !match {
  431. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  432. }
  433. }
  434. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  435. // Determine and create root git repository path.
  436. sec = Cfg.Section("repository")
  437. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  438. forcePathSeparator(RepoRootPath)
  439. if !filepath.IsAbs(RepoRootPath) {
  440. RepoRootPath = path.Join(workDir, RepoRootPath)
  441. } else {
  442. RepoRootPath = path.Clean(RepoRootPath)
  443. }
  444. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  445. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  446. log.Fatal(4, "Fail to map Repository settings: %v", err)
  447. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  448. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  449. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  450. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  451. }
  452. if !filepath.IsAbs(Repository.Upload.TempPath) {
  453. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  454. }
  455. sec = Cfg.Section("picture")
  456. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  457. forcePathSeparator(AvatarUploadPath)
  458. if !filepath.IsAbs(AvatarUploadPath) {
  459. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  460. }
  461. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  462. case "duoshuo":
  463. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  464. case "gravatar":
  465. GravatarSource = "https://secure.gravatar.com/avatar/"
  466. case "libravatar":
  467. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  468. default:
  469. GravatarSource = source
  470. }
  471. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  472. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  473. if OfflineMode {
  474. DisableGravatar = true
  475. EnableFederatedAvatar = false
  476. }
  477. if DisableGravatar {
  478. EnableFederatedAvatar = false
  479. }
  480. if EnableFederatedAvatar {
  481. LibravatarService = libravatar.New()
  482. parts := strings.Split(GravatarSource, "/")
  483. if len(parts) >= 3 {
  484. if parts[0] == "https:" {
  485. LibravatarService.SetUseHTTPS(true)
  486. LibravatarService.SetSecureFallbackHost(parts[2])
  487. } else {
  488. LibravatarService.SetUseHTTPS(false)
  489. LibravatarService.SetFallbackHost(parts[2])
  490. }
  491. }
  492. }
  493. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  494. log.Fatal(4, "Fail to map HTTP settings: %v", err)
  495. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  496. log.Fatal(4, "Fail to map UI settings: %v", err)
  497. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  498. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  499. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  500. log.Fatal(4, "Fail to map Cron settings: %v", err)
  501. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  502. log.Fatal(4, "Fail to map Git settings: %v", err)
  503. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  504. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  505. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  506. log.Fatal(4, "Fail to map API settings: %v", err)
  507. }
  508. if Mirror.DefaultInterval <= 0 {
  509. Mirror.DefaultInterval = 24
  510. }
  511. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  512. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  513. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  514. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  515. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  516. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  517. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  518. }
  519. var Service struct {
  520. ActiveCodeLives int
  521. ResetPwdCodeLives int
  522. RegisterEmailConfirm bool
  523. DisableRegistration bool
  524. ShowRegistrationButton bool
  525. RequireSignInView bool
  526. EnableNotifyMail bool
  527. EnableReverseProxyAuth bool
  528. EnableReverseProxyAutoRegister bool
  529. EnableCaptcha bool
  530. }
  531. func newService() {
  532. sec := Cfg.Section("service")
  533. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  534. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  535. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  536. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  537. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  538. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  539. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  540. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  541. }
  542. var logLevels = map[string]string{
  543. "Trace": "0",
  544. "Debug": "1",
  545. "Info": "2",
  546. "Warn": "3",
  547. "Error": "4",
  548. "Critical": "5",
  549. }
  550. func newLogService() {
  551. log.Info("%s %s", AppName, AppVer)
  552. if len(BuildTime) > 0 {
  553. log.Info("Build Time: %s", BuildTime)
  554. log.Info("Build Git Hash: %s", BuildGitHash)
  555. }
  556. // Get and check log mode.
  557. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  558. LogConfigs = make([]string, len(LogModes))
  559. for i, mode := range LogModes {
  560. mode = strings.TrimSpace(mode)
  561. sec, err := Cfg.GetSection("log." + mode)
  562. if err != nil {
  563. log.Fatal(4, "Unknown log mode: %s", mode)
  564. }
  565. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  566. // Log level.
  567. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  568. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  569. validLevels)
  570. level, ok := logLevels[levelName]
  571. if !ok {
  572. log.Fatal(4, "Unknown log level: %s", levelName)
  573. }
  574. // Generate log configuration.
  575. switch mode {
  576. case "console":
  577. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  578. case "file":
  579. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  580. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  581. panic(err.Error())
  582. }
  583. LogConfigs[i] = fmt.Sprintf(
  584. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  585. logPath,
  586. sec.Key("LOG_ROTATE").MustBool(true),
  587. sec.Key("MAX_LINES").MustInt(1000000),
  588. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  589. sec.Key("DAILY_ROTATE").MustBool(true),
  590. sec.Key("MAX_DAYS").MustInt(7))
  591. case "conn":
  592. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  593. sec.Key("RECONNECT_ON_MSG").MustBool(),
  594. sec.Key("RECONNECT").MustBool(),
  595. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  596. sec.Key("ADDR").MustString(":7020"))
  597. case "smtp":
  598. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  599. sec.Key("USER").MustString("example@example.com"),
  600. sec.Key("PASSWD").MustString("******"),
  601. sec.Key("HOST").MustString("127.0.0.1:25"),
  602. strings.Replace(sec.Key("RECEIVERS").MustString(""), ",", `","`, -1),
  603. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  604. case "database":
  605. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  606. sec.Key("DRIVER").String(),
  607. sec.Key("CONN").String())
  608. }
  609. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  610. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  611. }
  612. }
  613. func newCacheService() {
  614. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  615. switch CacheAdapter {
  616. case "memory":
  617. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  618. case "redis", "memcache":
  619. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  620. default:
  621. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  622. }
  623. log.Info("Cache Service Enabled")
  624. }
  625. func newSessionService() {
  626. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  627. []string{"memory", "file", "redis", "mysql"})
  628. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  629. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  630. SessionConfig.CookiePath = AppSubUrl
  631. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  632. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  633. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  634. log.Info("Session Service Enabled")
  635. }
  636. // Mailer represents mail service.
  637. type Mailer struct {
  638. QueueLength int
  639. Name string
  640. Host string
  641. From string
  642. FromEmail string
  643. User, Passwd string
  644. DisableHelo bool
  645. HeloHostname string
  646. SkipVerify bool
  647. UseCertificate bool
  648. CertFile, KeyFile string
  649. EnableHTMLAlternative bool
  650. }
  651. var (
  652. MailService *Mailer
  653. )
  654. func newMailService() {
  655. sec := Cfg.Section("mailer")
  656. // Check mailer setting.
  657. if !sec.Key("ENABLED").MustBool() {
  658. return
  659. }
  660. MailService = &Mailer{
  661. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  662. Name: sec.Key("NAME").MustString(AppName),
  663. Host: sec.Key("HOST").String(),
  664. User: sec.Key("USER").String(),
  665. Passwd: sec.Key("PASSWD").String(),
  666. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  667. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  668. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  669. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  670. CertFile: sec.Key("CERT_FILE").String(),
  671. KeyFile: sec.Key("KEY_FILE").String(),
  672. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  673. }
  674. MailService.From = sec.Key("FROM").MustString(MailService.User)
  675. parsed, err := mail.ParseAddress(MailService.From)
  676. if err != nil {
  677. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  678. }
  679. MailService.FromEmail = parsed.Address
  680. log.Info("Mail Service Enabled")
  681. }
  682. func newRegisterMailService() {
  683. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  684. return
  685. } else if MailService == nil {
  686. log.Warn("Register Mail Service: Mail Service is not enabled")
  687. return
  688. }
  689. Service.RegisterEmailConfirm = true
  690. log.Info("Register Mail Service Enabled")
  691. }
  692. func newNotifyMailService() {
  693. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  694. return
  695. } else if MailService == nil {
  696. log.Warn("Notify Mail Service: Mail Service is not enabled")
  697. return
  698. }
  699. Service.EnableNotifyMail = true
  700. log.Info("Notify Mail Service Enabled")
  701. }
  702. func newWebhookService() {
  703. sec := Cfg.Section("webhook")
  704. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  705. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  706. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  707. Webhook.Types = []string{"gogs", "slack"}
  708. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  709. }
  710. func NewServices() {
  711. newService()
  712. newLogService()
  713. newCacheService()
  714. newSessionService()
  715. newMailService()
  716. newRegisterMailService()
  717. newNotifyMailService()
  718. newWebhookService()
  719. }