setting.go 23 KB

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