setting.go 24 KB

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