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

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