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

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