setting.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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
  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. PullRequestQueueLength int
  101. }
  102. RepoRootPath string
  103. ScriptType string
  104. // Repo editor settings
  105. Editor struct {
  106. LineWrapExtensions []string
  107. PreviewTabApis []string
  108. }
  109. // UI settings
  110. UI struct {
  111. ExplorePagingNum int
  112. IssuePagingNum int
  113. FeedMaxCommitNum int
  114. ThemeColorMetaTag string
  115. MaxDisplayFileSize int64
  116. Admin struct {
  117. UserPagingNum int
  118. RepoPagingNum int
  119. NoticePagingNum int
  120. OrgPagingNum int
  121. } `ini:"ui.admin"`
  122. User struct {
  123. RepoPagingNum int
  124. } `ini:"ui.user"`
  125. }
  126. // Markdown sttings
  127. Markdown struct {
  128. EnableHardLineBreak bool
  129. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  130. MdFileExtensions []string
  131. }
  132. // Picture settings
  133. AvatarUploadPath string
  134. GravatarSource string
  135. DisableGravatar bool
  136. EnableFederatedAvatar bool
  137. LibravatarService *libravatar.Libravatar
  138. // Log settings
  139. LogRootPath string
  140. LogModes []string
  141. LogConfigs []string
  142. // Attachment settings
  143. AttachmentPath string
  144. AttachmentAllowedTypes string
  145. AttachmentMaxSize int64
  146. AttachmentMaxFiles int
  147. AttachmentEnabled bool
  148. // Repo Upload settings
  149. UploadTempPath string
  150. UploadAllowedTypes string
  151. UploadMaxSize int64
  152. UploadMaxFiles int
  153. UploadEnabled bool
  154. // Time settings
  155. TimeFormat string
  156. // Cache settings
  157. CacheAdapter string
  158. CacheInterval int
  159. CacheConn string
  160. // Session settings
  161. SessionConfig session.Options
  162. CSRFCookieName = "_csrf"
  163. // Cron tasks
  164. Cron struct {
  165. UpdateMirror struct {
  166. Enabled bool
  167. RunAtStart bool
  168. Schedule string
  169. } `ini:"cron.update_mirrors"`
  170. RepoHealthCheck struct {
  171. Enabled bool
  172. RunAtStart bool
  173. Schedule string
  174. Timeout time.Duration
  175. Args []string `delim:" "`
  176. } `ini:"cron.repo_health_check"`
  177. CheckRepoStats struct {
  178. Enabled bool
  179. RunAtStart bool
  180. Schedule string
  181. } `ini:"cron.check_repo_stats"`
  182. }
  183. // Git settings
  184. Git struct {
  185. DisableDiffHighlight bool
  186. MaxGitDiffLines int
  187. MaxGitDiffLineCharacters int
  188. MaxGitDiffFiles int
  189. GCArgs []string `delim:" "`
  190. Timeout struct {
  191. Migrate int
  192. Mirror int
  193. Clone int
  194. Pull int
  195. GC int `ini:"GC"`
  196. } `ini:"git.timeout"`
  197. }
  198. // Mirror settings
  199. Mirror struct {
  200. DefaultInterval int
  201. }
  202. // API settings
  203. API struct {
  204. MaxResponseItems int
  205. }
  206. // I18n settings
  207. Langs, Names []string
  208. dateLangs map[string]string
  209. // Highlight settings are loaded in modules/template/hightlight.go
  210. // Other settings
  211. ShowFooterBranding bool
  212. ShowFooterVersion bool
  213. SupportMiniWinService bool
  214. // Global setting objects
  215. Cfg *ini.File
  216. CustomPath string // Custom directory path
  217. CustomConf string
  218. ProdMode bool
  219. RunUser string
  220. IsWindows bool
  221. HasRobotsTxt bool
  222. )
  223. func DateLang(lang string) string {
  224. name, ok := dateLangs[lang]
  225. if ok {
  226. return name
  227. }
  228. return "en"
  229. }
  230. // execPath returns the executable path.
  231. func execPath() (string, error) {
  232. file, err := exec.LookPath(os.Args[0])
  233. if err != nil {
  234. return "", err
  235. }
  236. return filepath.Abs(file)
  237. }
  238. func init() {
  239. IsWindows = runtime.GOOS == "windows"
  240. log.NewLogger(0, "console", `{"level": 0}`)
  241. var err error
  242. if AppPath, err = execPath(); err != nil {
  243. log.Fatal(4, "fail to get app path: %v\n", err)
  244. }
  245. // Note: we don't use path.Dir here because it does not handle case
  246. // which path starts with two "/" in Windows: "//psf/Home/..."
  247. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  248. }
  249. // WorkDir returns absolute path of work directory.
  250. func WorkDir() (string, error) {
  251. wd := os.Getenv("GOGS_WORK_DIR")
  252. if len(wd) > 0 {
  253. return wd, nil
  254. }
  255. i := strings.LastIndex(AppPath, "/")
  256. if i == -1 {
  257. return AppPath, nil
  258. }
  259. return AppPath[:i], nil
  260. }
  261. func forcePathSeparator(path string) {
  262. if strings.Contains(path, "\\") {
  263. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  264. }
  265. }
  266. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  267. // actual user that runs the app. The first return value is the actual user name.
  268. // This check is ignored under Windows since SSH remote login is not the main
  269. // method to login on Windows.
  270. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  271. if IsWindows {
  272. return "", true
  273. }
  274. currentUser := user.CurrentUsername()
  275. return currentUser, runUser == currentUser
  276. }
  277. // NewContext initializes configuration context.
  278. // NOTE: do not print any log except error.
  279. func NewContext() {
  280. workDir, err := WorkDir()
  281. if err != nil {
  282. log.Fatal(4, "Fail to get work directory: %v", err)
  283. }
  284. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  285. if err != nil {
  286. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  287. }
  288. CustomPath = os.Getenv("GOGS_CUSTOM")
  289. if len(CustomPath) == 0 {
  290. CustomPath = workDir + "/custom"
  291. }
  292. if len(CustomConf) == 0 {
  293. CustomConf = CustomPath + "/conf/app.ini"
  294. }
  295. if com.IsFile(CustomConf) {
  296. if err = Cfg.Append(CustomConf); err != nil {
  297. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  298. }
  299. } else {
  300. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  301. }
  302. Cfg.NameMapper = ini.AllCapsUnderscore
  303. homeDir, err := com.HomeDir()
  304. if err != nil {
  305. log.Fatal(4, "Fail to get home directory: %v", err)
  306. }
  307. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  308. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  309. forcePathSeparator(LogRootPath)
  310. sec := Cfg.Section("server")
  311. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  312. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  313. if AppUrl[len(AppUrl)-1] != '/' {
  314. AppUrl += "/"
  315. }
  316. // Check if has app suburl.
  317. url, err := url.Parse(AppUrl)
  318. if err != nil {
  319. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
  320. }
  321. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  322. // This value is empty if site does not have sub-url.
  323. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  324. AppSubUrlDepth = strings.Count(AppSubUrl, "/")
  325. Protocol = HTTP
  326. if sec.Key("PROTOCOL").String() == "https" {
  327. Protocol = HTTPS
  328. CertFile = sec.Key("CERT_FILE").String()
  329. KeyFile = sec.Key("KEY_FILE").String()
  330. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  331. Protocol = FCGI
  332. } else if sec.Key("PROTOCOL").String() == "unix" {
  333. Protocol = UNIX_SOCKET
  334. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  335. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  336. if err != nil || UnixSocketPermissionParsed > 0777 {
  337. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  338. }
  339. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  340. }
  341. Domain = sec.Key("DOMAIN").MustString("localhost")
  342. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  343. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  344. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  345. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  346. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  347. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  348. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  349. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  350. switch sec.Key("LANDING_PAGE").MustString("home") {
  351. case "explore":
  352. LandingPageUrl = LANDING_PAGE_EXPLORE
  353. default:
  354. LandingPageUrl = LANDING_PAGE_HOME
  355. }
  356. SSH.RootPath = path.Join(homeDir, ".ssh")
  357. SSH.KeyTestPath = os.TempDir()
  358. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  359. log.Fatal(4, "Fail to map SSH settings: %v", err)
  360. }
  361. // When disable SSH, start builtin server value is ignored.
  362. if SSH.Disabled {
  363. SSH.StartBuiltinServer = false
  364. }
  365. if !SSH.Disabled && !SSH.StartBuiltinServer {
  366. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  367. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  368. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  369. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  370. }
  371. }
  372. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  373. SSH.MinimumKeySizes = map[string]int{}
  374. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  375. for _, key := range minimumKeySizes {
  376. if key.MustInt() != -1 {
  377. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  378. }
  379. }
  380. sec = Cfg.Section("security")
  381. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  382. SecretKey = sec.Key("SECRET_KEY").String()
  383. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  384. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  385. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  386. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  387. sec = Cfg.Section("attachment")
  388. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  389. if !filepath.IsAbs(AttachmentPath) {
  390. AttachmentPath = path.Join(workDir, AttachmentPath)
  391. }
  392. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  393. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  394. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  395. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  396. TimeFormat = map[string]string{
  397. "ANSIC": time.ANSIC,
  398. "UnixDate": time.UnixDate,
  399. "RubyDate": time.RubyDate,
  400. "RFC822": time.RFC822,
  401. "RFC822Z": time.RFC822Z,
  402. "RFC850": time.RFC850,
  403. "RFC1123": time.RFC1123,
  404. "RFC1123Z": time.RFC1123Z,
  405. "RFC3339": time.RFC3339,
  406. "RFC3339Nano": time.RFC3339Nano,
  407. "Kitchen": time.Kitchen,
  408. "Stamp": time.Stamp,
  409. "StampMilli": time.StampMilli,
  410. "StampMicro": time.StampMicro,
  411. "StampNano": time.StampNano,
  412. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  413. RunUser = Cfg.Section("").Key("RUN_USER").String()
  414. // Does not check run user when the install lock is off.
  415. if InstallLock {
  416. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  417. if !match {
  418. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  419. }
  420. }
  421. // Determine and create root git repository path.
  422. sec = Cfg.Section("repository")
  423. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  424. forcePathSeparator(RepoRootPath)
  425. if !filepath.IsAbs(RepoRootPath) {
  426. RepoRootPath = path.Join(workDir, RepoRootPath)
  427. } else {
  428. RepoRootPath = path.Clean(RepoRootPath)
  429. }
  430. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  431. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  432. log.Fatal(4, "Fail to map Repository settings: %v", err)
  433. }
  434. sec = Cfg.Section("upload")
  435. UploadTempPath = sec.Key("UPLOAD_TEMP_PATH").MustString(path.Join(AppDataPath, "tmp/uploads"))
  436. if !filepath.IsAbs(UploadTempPath) {
  437. UploadTempPath = path.Join(workDir, UploadTempPath)
  438. }
  439. UploadAllowedTypes = strings.Replace(sec.Key("UPLOAD_ALLOWED_TYPES").MustString(""), "|", ",", -1)
  440. UploadMaxSize = sec.Key("UPLOAD_FILE_MAX_SIZE").MustInt64(32)
  441. UploadMaxFiles = sec.Key("UPLOAD_MAX_FILES").MustInt(10)
  442. UploadEnabled = sec.Key("ENABLE_UPLOADS").MustBool(true)
  443. sec = Cfg.Section("picture")
  444. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  445. forcePathSeparator(AvatarUploadPath)
  446. if !filepath.IsAbs(AvatarUploadPath) {
  447. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  448. }
  449. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  450. case "duoshuo":
  451. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  452. case "gravatar":
  453. GravatarSource = "https://secure.gravatar.com/avatar/"
  454. default:
  455. GravatarSource = source
  456. }
  457. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  458. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  459. if OfflineMode {
  460. DisableGravatar = true
  461. EnableFederatedAvatar = false
  462. }
  463. if DisableGravatar {
  464. EnableFederatedAvatar = false
  465. }
  466. if EnableFederatedAvatar {
  467. LibravatarService = libravatar.New()
  468. parts := strings.Split(GravatarSource, "/")
  469. if len(parts) >= 3 {
  470. if parts[0] == "https:" {
  471. LibravatarService.SetUseHTTPS(true)
  472. LibravatarService.SetSecureFallbackHost(parts[2])
  473. } else {
  474. LibravatarService.SetUseHTTPS(false)
  475. LibravatarService.SetFallbackHost(parts[2])
  476. }
  477. }
  478. }
  479. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  480. log.Fatal(4, "Fail to map UI settings: %v", err)
  481. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  482. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  483. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  484. log.Fatal(4, "Fail to map Cron settings: %v", err)
  485. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  486. log.Fatal(4, "Fail to map Git settings: %v", err)
  487. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  488. log.Fatal(4, "Fail to map API settings: %v", err)
  489. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  490. log.Fatal(4, "Fail to map API settings: %v", err)
  491. } else if err = Cfg.Section("editor").MapTo(&Editor); err != nil {
  492. log.Fatal(4, "Fail to map Editor settings: %v", err)
  493. }
  494. if Mirror.DefaultInterval <= 0 {
  495. Mirror.DefaultInterval = 24
  496. }
  497. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  498. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  499. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  500. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  501. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  502. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  503. Markdown.MdFileExtensions = Cfg.Section("markdown").Key("MD_FILE_EXTENSIONS").Strings(",")
  504. Editor.LineWrapExtensions = Cfg.Section("editor").Key("LINE_WRAP_EXTENSIONS").Strings(",")
  505. Editor.PreviewTabApis = Cfg.Section("editor").Key("PREVIEW_TAB_APIS").Strings(",")
  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("[email protected]"),
  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. }