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 23KB

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