setting.go 24 KB

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