setting.go 24 KB

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