setting.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. "net/mail"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "time"
  16. _ "github.com/go-macaron/cache/memcache"
  17. _ "github.com/go-macaron/cache/redis"
  18. "github.com/go-macaron/session"
  19. _ "github.com/go-macaron/session/redis"
  20. "github.com/mcuadros/go-version"
  21. "github.com/unknwon/com"
  22. log "gopkg.in/clog.v1"
  23. "gopkg.in/ini.v1"
  24. "github.com/gogs/go-libravatar"
  25. "gogs.io/gogs/internal/assets/conf"
  26. "gogs.io/gogs/internal/process"
  27. "gogs.io/gogs/internal/user"
  28. )
  29. type Scheme string
  30. const (
  31. SCHEME_HTTP Scheme = "http"
  32. SCHEME_HTTPS Scheme = "https"
  33. SCHEME_FCGI Scheme = "fcgi"
  34. SCHEME_UNIX_SOCKET Scheme = "unix"
  35. )
  36. type LandingPage string
  37. const (
  38. LANDING_PAGE_HOME LandingPage = "/"
  39. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  40. )
  41. var (
  42. // Build information should only be set by -ldflags.
  43. BuildTime string
  44. BuildCommit string
  45. // App settings
  46. AppVersion string
  47. AppName string
  48. AppURL string
  49. AppSubURL string
  50. AppSubURLDepth int // Number of slashes
  51. AppPath string
  52. AppDataPath string
  53. HostAddress string // AppURL without protocol and slashes
  54. // Server settings
  55. Protocol Scheme
  56. Domain string
  57. HTTPAddr string
  58. HTTPPort string
  59. LocalURL string
  60. OfflineMode bool
  61. DisableRouterLog bool
  62. CertFile string
  63. KeyFile string
  64. TLSMinVersion string
  65. LoadAssetsFromDisk bool
  66. StaticRootPath string
  67. EnableGzip bool
  68. LandingPageURL LandingPage
  69. UnixSocketPermission uint32
  70. HTTP struct {
  71. AccessControlAllowOrigin string
  72. }
  73. SSH struct {
  74. Disabled bool `ini:"DISABLE_SSH"`
  75. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  76. Domain string `ini:"SSH_DOMAIN"`
  77. Port int `ini:"SSH_PORT"`
  78. ListenHost string `ini:"SSH_LISTEN_HOST"`
  79. ListenPort int `ini:"SSH_LISTEN_PORT"`
  80. RootPath string `ini:"SSH_ROOT_PATH"`
  81. RewriteAuthorizedKeysAtStart bool `ini:"REWRITE_AUTHORIZED_KEYS_AT_START"`
  82. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  83. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  84. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  85. MinimumKeySizeCheck bool `ini:"MINIMUM_KEY_SIZE_CHECK"`
  86. MinimumKeySizes map[string]int `ini:"-"`
  87. }
  88. // Security settings
  89. InstallLock bool
  90. SecretKey string
  91. LoginRememberDays int
  92. CookieUserName string
  93. CookieRememberName string
  94. CookieSecure bool
  95. ReverseProxyAuthUser string
  96. EnableLoginStatusCookie bool
  97. LoginStatusCookieName string
  98. // Database settings
  99. UseSQLite3 bool
  100. UseMySQL bool
  101. UsePostgreSQL bool
  102. UseMSSQL bool
  103. // Repository settings
  104. Repository struct {
  105. AnsiCharset string
  106. ForcePrivate bool
  107. MaxCreationLimit int
  108. MirrorQueueLength int
  109. PullRequestQueueLength int
  110. PreferredLicenses []string
  111. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  112. EnableLocalPathMigration bool
  113. CommitsFetchConcurrency int
  114. EnableRawFileRenderMode bool
  115. // Repository editor settings
  116. Editor struct {
  117. LineWrapExtensions []string
  118. PreviewableFileModes []string
  119. } `ini:"-"`
  120. // Repository upload settings
  121. Upload struct {
  122. Enabled bool
  123. TempPath string
  124. AllowedTypes []string `delim:"|"`
  125. FileMaxSize int64
  126. MaxFiles int
  127. } `ini:"-"`
  128. }
  129. RepoRootPath string
  130. ScriptType string
  131. // Webhook settings
  132. Webhook struct {
  133. Types []string
  134. QueueLength int
  135. DeliverTimeout int
  136. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  137. PagingNum int
  138. }
  139. // Release settigns
  140. Release struct {
  141. Attachment struct {
  142. Enabled bool
  143. TempPath string
  144. AllowedTypes []string `delim:"|"`
  145. MaxSize int64
  146. MaxFiles int
  147. } `ini:"-"`
  148. }
  149. // Markdown sttings
  150. Markdown struct {
  151. EnableHardLineBreak bool
  152. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  153. FileExtensions []string
  154. }
  155. // Smartypants settings
  156. Smartypants struct {
  157. Enabled bool
  158. Fractions bool
  159. Dashes bool
  160. LatexDashes bool
  161. AngledQuotes bool
  162. }
  163. // Admin settings
  164. Admin struct {
  165. DisableRegularOrgCreation bool
  166. }
  167. // Picture settings
  168. AvatarUploadPath string
  169. RepositoryAvatarUploadPath string
  170. GravatarSource string
  171. DisableGravatar bool
  172. EnableFederatedAvatar bool
  173. LibravatarService *libravatar.Libravatar
  174. // Log settings
  175. LogRootPath string
  176. LogModes []string
  177. LogConfigs []interface{}
  178. // Attachment settings
  179. AttachmentPath string
  180. AttachmentAllowedTypes string
  181. AttachmentMaxSize int64
  182. AttachmentMaxFiles int
  183. AttachmentEnabled bool
  184. // Time settings
  185. TimeFormat string
  186. // Cache settings
  187. CacheAdapter string
  188. CacheInterval int
  189. CacheConn string
  190. // Session settings
  191. SessionConfig session.Options
  192. CSRFCookieName string
  193. // Cron tasks
  194. Cron struct {
  195. UpdateMirror struct {
  196. Enabled bool
  197. RunAtStart bool
  198. Schedule string
  199. } `ini:"cron.update_mirrors"`
  200. RepoHealthCheck struct {
  201. Enabled bool
  202. RunAtStart bool
  203. Schedule string
  204. Timeout time.Duration
  205. Args []string `delim:" "`
  206. } `ini:"cron.repo_health_check"`
  207. CheckRepoStats struct {
  208. Enabled bool
  209. RunAtStart bool
  210. Schedule string
  211. } `ini:"cron.check_repo_stats"`
  212. RepoArchiveCleanup struct {
  213. Enabled bool
  214. RunAtStart bool
  215. Schedule string
  216. OlderThan time.Duration
  217. } `ini:"cron.repo_archive_cleanup"`
  218. }
  219. // Git settings
  220. Git struct {
  221. Version string `ini:"-"`
  222. DisableDiffHighlight bool
  223. MaxGitDiffLines int
  224. MaxGitDiffLineCharacters int
  225. MaxGitDiffFiles int
  226. GCArgs []string `ini:"GC_ARGS" delim:" "`
  227. Timeout struct {
  228. Migrate int
  229. Mirror int
  230. Clone int
  231. Pull int
  232. GC int `ini:"GC"`
  233. } `ini:"git.timeout"`
  234. }
  235. // Mirror settings
  236. Mirror struct {
  237. DefaultInterval int
  238. }
  239. // API settings
  240. API struct {
  241. MaxResponseItems int
  242. }
  243. // UI settings
  244. UI struct {
  245. ExplorePagingNum int
  246. IssuePagingNum int
  247. FeedMaxCommitNum int
  248. ThemeColorMetaTag string
  249. MaxDisplayFileSize int64
  250. Admin struct {
  251. UserPagingNum int
  252. RepoPagingNum int
  253. NoticePagingNum int
  254. OrgPagingNum int
  255. } `ini:"ui.admin"`
  256. User struct {
  257. RepoPagingNum int
  258. NewsFeedPagingNum int
  259. CommitsPagingNum int
  260. } `ini:"ui.user"`
  261. }
  262. // Prometheus settings
  263. Prometheus struct {
  264. Enabled bool
  265. EnableBasicAuth bool
  266. BasicAuthUsername string
  267. BasicAuthPassword string
  268. }
  269. // I18n settings
  270. Langs []string
  271. Names []string
  272. dateLangs map[string]string
  273. // Highlight settings are loaded in modules/template/hightlight.go
  274. // Other settings
  275. ShowFooterBranding bool
  276. ShowFooterVersion bool
  277. ShowFooterTemplateLoadTime bool
  278. SupportMiniWinService bool
  279. // Global setting objects
  280. Cfg *ini.File
  281. CustomPath string // Custom directory path
  282. CustomConf string
  283. ProdMode bool
  284. RunUser string
  285. IsWindows bool
  286. HasRobotsTxt bool
  287. )
  288. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  289. func DateLang(lang string) string {
  290. name, ok := dateLangs[lang]
  291. if ok {
  292. return name
  293. }
  294. return "en"
  295. }
  296. // execPath returns the executable path.
  297. func execPath() (string, error) {
  298. file, err := exec.LookPath(os.Args[0])
  299. if err != nil {
  300. return "", err
  301. }
  302. return filepath.Abs(file)
  303. }
  304. func init() {
  305. IsWindows = runtime.GOOS == "windows"
  306. log.New(log.CONSOLE, log.ConsoleConfig{})
  307. var err error
  308. if AppPath, err = execPath(); err != nil {
  309. log.Fatal(2, "Fail to get app path: %v\n", err)
  310. }
  311. // Note: we don't use path.Dir here because it does not handle case
  312. // which path starts with two "/" in Windows: "//psf/Home/..."
  313. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  314. }
  315. // WorkDir returns absolute path of work directory.
  316. func WorkDir() (string, error) {
  317. wd := os.Getenv("GOGS_WORK_DIR")
  318. if len(wd) > 0 {
  319. return wd, nil
  320. }
  321. i := strings.LastIndex(AppPath, "/")
  322. if i == -1 {
  323. return AppPath, nil
  324. }
  325. return AppPath[:i], nil
  326. }
  327. func forcePathSeparator(path string) {
  328. if strings.Contains(path, "\\") {
  329. log.Fatal(2, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  330. }
  331. }
  332. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  333. // actual user that runs the app. The first return value is the actual user name.
  334. // This check is ignored under Windows since SSH remote login is not the main
  335. // method to login on Windows.
  336. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  337. if IsWindows {
  338. return "", true
  339. }
  340. currentUser := user.CurrentUsername()
  341. return currentUser, runUser == currentUser
  342. }
  343. // getOpenSSHVersion parses and returns string representation of OpenSSH version
  344. // returned by command "ssh -V".
  345. func getOpenSSHVersion() string {
  346. // Note: somehow version is printed to stderr
  347. _, stderr, err := process.Exec("getOpenSSHVersion", "ssh", "-V")
  348. if err != nil {
  349. log.Fatal(2, "Fail to get OpenSSH version: %v - %s", err, stderr)
  350. }
  351. // Trim unused information: https://gogs.io/gogs/issues/4507#issuecomment-305150441
  352. version := strings.TrimRight(strings.Fields(stderr)[0], ",1234567890")
  353. version = strings.TrimSuffix(strings.TrimPrefix(version, "OpenSSH_"), "p")
  354. return version
  355. }
  356. // NewContext initializes configuration context.
  357. // NOTE: do not print any log except error.
  358. func NewContext() {
  359. workDir, err := WorkDir()
  360. if err != nil {
  361. log.Fatal(2, "Fail to get work directory: %v", err)
  362. }
  363. Cfg, err = ini.LoadSources(ini.LoadOptions{
  364. IgnoreInlineComment: true,
  365. }, conf.MustAsset("conf/app.ini"))
  366. if err != nil {
  367. log.Fatal(2, "Fail to parse 'conf/app.ini': %v", err)
  368. }
  369. CustomPath = os.Getenv("GOGS_CUSTOM")
  370. if len(CustomPath) == 0 {
  371. CustomPath = workDir + "/custom"
  372. }
  373. if len(CustomConf) == 0 {
  374. CustomConf = CustomPath + "/conf/app.ini"
  375. }
  376. if com.IsFile(CustomConf) {
  377. if err = Cfg.Append(CustomConf); err != nil {
  378. log.Fatal(2, "Fail to load custom conf '%s': %v", CustomConf, err)
  379. }
  380. } else {
  381. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  382. }
  383. Cfg.NameMapper = ini.AllCapsUnderscore
  384. homeDir, err := com.HomeDir()
  385. if err != nil {
  386. log.Fatal(2, "Fail to get home directory: %v", err)
  387. }
  388. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  389. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  390. forcePathSeparator(LogRootPath)
  391. sec := Cfg.Section("server")
  392. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs")
  393. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  394. if AppURL[len(AppURL)-1] != '/' {
  395. AppURL += "/"
  396. }
  397. // Check if has app suburl.
  398. url, err := url.Parse(AppURL)
  399. if err != nil {
  400. log.Fatal(2, "Invalid ROOT_URL '%s': %s", AppURL, err)
  401. }
  402. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  403. // This value is empty if site does not have sub-url.
  404. AppSubURL = strings.TrimSuffix(url.Path, "/")
  405. AppSubURLDepth = strings.Count(AppSubURL, "/")
  406. HostAddress = url.Host
  407. Protocol = SCHEME_HTTP
  408. if sec.Key("PROTOCOL").String() == "https" {
  409. Protocol = SCHEME_HTTPS
  410. CertFile = sec.Key("CERT_FILE").String()
  411. KeyFile = sec.Key("KEY_FILE").String()
  412. TLSMinVersion = sec.Key("TLS_MIN_VERSION").String()
  413. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  414. Protocol = SCHEME_FCGI
  415. } else if sec.Key("PROTOCOL").String() == "unix" {
  416. Protocol = SCHEME_UNIX_SOCKET
  417. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  418. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  419. if err != nil || UnixSocketPermissionParsed > 0777 {
  420. log.Fatal(2, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  421. }
  422. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  423. }
  424. Domain = sec.Key("DOMAIN").MustString("localhost")
  425. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  426. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  427. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  428. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  429. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  430. LoadAssetsFromDisk = sec.Key("LOAD_ASSETS_FROM_DISK").MustBool()
  431. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  432. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  433. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  434. switch sec.Key("LANDING_PAGE").MustString("home") {
  435. case "explore":
  436. LandingPageURL = LANDING_PAGE_EXPLORE
  437. default:
  438. LandingPageURL = LANDING_PAGE_HOME
  439. }
  440. SSH.RootPath = path.Join(homeDir, ".ssh")
  441. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  442. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  443. SSH.KeyTestPath = os.TempDir()
  444. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  445. log.Fatal(2, "Fail to map SSH settings: %v", err)
  446. }
  447. if SSH.Disabled {
  448. SSH.StartBuiltinServer = false
  449. SSH.MinimumKeySizeCheck = false
  450. }
  451. if !SSH.Disabled && !SSH.StartBuiltinServer {
  452. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  453. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  454. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  455. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  456. }
  457. }
  458. if SSH.StartBuiltinServer {
  459. SSH.RewriteAuthorizedKeysAtStart = false
  460. }
  461. // Check if server is eligible for minimum key size check when user choose to enable.
  462. // Windows server and OpenSSH version lower than 5.1 (https://gogs.io/gogs/issues/4507)
  463. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  464. if SSH.MinimumKeySizeCheck &&
  465. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  466. SSH.MinimumKeySizeCheck = false
  467. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  468. 1. Windows server
  469. 2. OpenSSH version is lower than 5.1`)
  470. }
  471. if SSH.MinimumKeySizeCheck {
  472. SSH.MinimumKeySizes = map[string]int{}
  473. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  474. if key.MustInt() != -1 {
  475. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  476. }
  477. }
  478. }
  479. sec = Cfg.Section("security")
  480. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  481. SecretKey = sec.Key("SECRET_KEY").String()
  482. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  483. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  484. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  485. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  486. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  487. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  488. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  489. sec = Cfg.Section("attachment")
  490. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  491. if !filepath.IsAbs(AttachmentPath) {
  492. AttachmentPath = path.Join(workDir, AttachmentPath)
  493. }
  494. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  495. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  496. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  497. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  498. TimeFormat = map[string]string{
  499. "ANSIC": time.ANSIC,
  500. "UnixDate": time.UnixDate,
  501. "RubyDate": time.RubyDate,
  502. "RFC822": time.RFC822,
  503. "RFC822Z": time.RFC822Z,
  504. "RFC850": time.RFC850,
  505. "RFC1123": time.RFC1123,
  506. "RFC1123Z": time.RFC1123Z,
  507. "RFC3339": time.RFC3339,
  508. "RFC3339Nano": time.RFC3339Nano,
  509. "Kitchen": time.Kitchen,
  510. "Stamp": time.Stamp,
  511. "StampMilli": time.StampMilli,
  512. "StampMicro": time.StampMicro,
  513. "StampNano": time.StampNano,
  514. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  515. RunUser = Cfg.Section("").Key("RUN_USER").String()
  516. // Does not check run user when the install lock is off.
  517. if InstallLock {
  518. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  519. if !match {
  520. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  521. }
  522. }
  523. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  524. // Determine and create root git repository path.
  525. sec = Cfg.Section("repository")
  526. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  527. forcePathSeparator(RepoRootPath)
  528. if !filepath.IsAbs(RepoRootPath) {
  529. RepoRootPath = path.Join(workDir, RepoRootPath)
  530. } else {
  531. RepoRootPath = path.Clean(RepoRootPath)
  532. }
  533. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  534. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  535. log.Fatal(2, "Fail to map Repository settings: %v", err)
  536. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  537. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  538. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  539. log.Fatal(2, "Fail to map Repository.Upload settings: %v", err)
  540. }
  541. if !filepath.IsAbs(Repository.Upload.TempPath) {
  542. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  543. }
  544. sec = Cfg.Section("picture")
  545. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  546. forcePathSeparator(AvatarUploadPath)
  547. if !filepath.IsAbs(AvatarUploadPath) {
  548. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  549. }
  550. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "repo-avatars"))
  551. forcePathSeparator(RepositoryAvatarUploadPath)
  552. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  553. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  554. }
  555. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  556. case "duoshuo":
  557. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  558. case "gravatar":
  559. GravatarSource = "https://secure.gravatar.com/avatar/"
  560. case "libravatar":
  561. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  562. default:
  563. GravatarSource = source
  564. }
  565. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  566. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  567. if OfflineMode {
  568. DisableGravatar = true
  569. EnableFederatedAvatar = false
  570. }
  571. if DisableGravatar {
  572. EnableFederatedAvatar = false
  573. }
  574. if EnableFederatedAvatar {
  575. LibravatarService = libravatar.New()
  576. parts := strings.Split(GravatarSource, "/")
  577. if len(parts) >= 3 {
  578. if parts[0] == "https:" {
  579. LibravatarService.SetUseHTTPS(true)
  580. LibravatarService.SetSecureFallbackHost(parts[2])
  581. } else {
  582. LibravatarService.SetUseHTTPS(false)
  583. LibravatarService.SetFallbackHost(parts[2])
  584. }
  585. }
  586. }
  587. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  588. log.Fatal(2, "Failed to map HTTP settings: %v", err)
  589. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  590. log.Fatal(2, "Failed to map Webhook settings: %v", err)
  591. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  592. log.Fatal(2, "Failed to map Release.Attachment settings: %v", err)
  593. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  594. log.Fatal(2, "Failed to map Markdown settings: %v", err)
  595. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  596. log.Fatal(2, "Failed to map Smartypants settings: %v", err)
  597. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  598. log.Fatal(2, "Failed to map Admin settings: %v", err)
  599. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  600. log.Fatal(2, "Failed to map Cron settings: %v", err)
  601. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  602. log.Fatal(2, "Failed to map Git settings: %v", err)
  603. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  604. log.Fatal(2, "Failed to map Mirror settings: %v", err)
  605. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  606. log.Fatal(2, "Failed to map API settings: %v", err)
  607. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  608. log.Fatal(2, "Failed to map UI settings: %v", err)
  609. } else if err = Cfg.Section("prometheus").MapTo(&Prometheus); err != nil {
  610. log.Fatal(2, "Failed to map Prometheus settings: %v", err)
  611. }
  612. if Mirror.DefaultInterval <= 0 {
  613. Mirror.DefaultInterval = 24
  614. }
  615. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  616. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  617. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  618. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  619. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  620. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  621. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  622. }
  623. var Service struct {
  624. ActiveCodeLives int
  625. ResetPwdCodeLives int
  626. RegisterEmailConfirm bool
  627. DisableRegistration bool
  628. ShowRegistrationButton bool
  629. RequireSignInView bool
  630. EnableNotifyMail bool
  631. EnableReverseProxyAuth bool
  632. EnableReverseProxyAutoRegister bool
  633. EnableCaptcha bool
  634. }
  635. func newService() {
  636. sec := Cfg.Section("service")
  637. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  638. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  639. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  640. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  641. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  642. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  643. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  644. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  645. }
  646. func newLogService() {
  647. if len(BuildTime) > 0 {
  648. log.Trace("Build time: %s", BuildTime)
  649. log.Trace("Build commit: %s", BuildCommit)
  650. }
  651. // Because we always create a console logger as primary logger before all settings are loaded,
  652. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  653. hasConsole := false
  654. // Get and check log modes.
  655. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  656. LogConfigs = make([]interface{}, len(LogModes))
  657. levelNames := map[string]log.LEVEL{
  658. "trace": log.TRACE,
  659. "info": log.INFO,
  660. "warn": log.WARN,
  661. "error": log.ERROR,
  662. "fatal": log.FATAL,
  663. }
  664. for i, mode := range LogModes {
  665. mode = strings.ToLower(strings.TrimSpace(mode))
  666. sec, err := Cfg.GetSection("log." + mode)
  667. if err != nil {
  668. log.Fatal(2, "Unknown logger mode: %s", mode)
  669. }
  670. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  671. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  672. v = strings.ToLower(v)
  673. if com.IsSliceContainsStr(validLevels, v) {
  674. return v
  675. }
  676. return "trace"
  677. })
  678. level := levelNames[name]
  679. // Generate log configuration.
  680. switch log.MODE(mode) {
  681. case log.CONSOLE:
  682. hasConsole = true
  683. LogConfigs[i] = log.ConsoleConfig{
  684. Level: level,
  685. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  686. }
  687. case log.FILE:
  688. logPath := path.Join(LogRootPath, "gogs.log")
  689. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  690. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  691. }
  692. LogConfigs[i] = log.FileConfig{
  693. Level: level,
  694. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  695. Filename: logPath,
  696. FileRotationConfig: log.FileRotationConfig{
  697. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  698. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  699. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  700. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  701. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  702. },
  703. }
  704. case log.SLACK:
  705. LogConfigs[i] = log.SlackConfig{
  706. Level: level,
  707. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  708. URL: sec.Key("URL").String(),
  709. }
  710. case log.DISCORD:
  711. LogConfigs[i] = log.DiscordConfig{
  712. Level: level,
  713. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  714. URL: sec.Key("URL").String(),
  715. Username: sec.Key("USERNAME").String(),
  716. }
  717. }
  718. log.New(log.MODE(mode), LogConfigs[i])
  719. log.Trace("Log mode: %s (%s)", strings.Title(mode), strings.Title(name))
  720. }
  721. // Make sure everyone gets version info printed.
  722. log.Info("%s %s", AppName, AppVersion)
  723. if !hasConsole {
  724. log.Delete(log.CONSOLE)
  725. }
  726. }
  727. func newCacheService() {
  728. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  729. switch CacheAdapter {
  730. case "memory":
  731. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  732. case "redis", "memcache":
  733. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  734. default:
  735. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  736. }
  737. log.Trace("Cache service is enabled")
  738. }
  739. func newSessionService() {
  740. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  741. []string{"memory", "file", "redis", "mysql"})
  742. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  743. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  744. SessionConfig.CookiePath = AppSubURL
  745. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  746. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  747. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  748. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  749. log.Trace("Session service is enabled")
  750. }
  751. // Mailer represents mail service.
  752. type Mailer struct {
  753. QueueLength int
  754. SubjectPrefix string
  755. Host string
  756. From string
  757. FromEmail string
  758. User, Passwd string
  759. DisableHelo bool
  760. HeloHostname string
  761. SkipVerify bool
  762. UseCertificate bool
  763. CertFile, KeyFile string
  764. UsePlainText bool
  765. AddPlainTextAlt bool
  766. }
  767. var (
  768. MailService *Mailer
  769. )
  770. // newMailService initializes mail service options from configuration.
  771. // No non-error log will be printed in hook mode.
  772. func newMailService() {
  773. sec := Cfg.Section("mailer")
  774. if !sec.Key("ENABLED").MustBool() {
  775. return
  776. }
  777. MailService = &Mailer{
  778. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  779. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  780. Host: sec.Key("HOST").String(),
  781. User: sec.Key("USER").String(),
  782. Passwd: sec.Key("PASSWD").String(),
  783. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  784. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  785. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  786. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  787. CertFile: sec.Key("CERT_FILE").String(),
  788. KeyFile: sec.Key("KEY_FILE").String(),
  789. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  790. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  791. }
  792. MailService.From = sec.Key("FROM").MustString(MailService.User)
  793. if len(MailService.From) > 0 {
  794. parsed, err := mail.ParseAddress(MailService.From)
  795. if err != nil {
  796. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  797. }
  798. MailService.FromEmail = parsed.Address
  799. }
  800. if HookMode {
  801. return
  802. }
  803. log.Trace("Mail service is enabled")
  804. }
  805. func newRegisterMailService() {
  806. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  807. return
  808. } else if MailService == nil {
  809. log.Warn("Email confirmation is not enabled due to the mail service is not available")
  810. return
  811. }
  812. Service.RegisterEmailConfirm = true
  813. log.Trace("Email confirmation is enabled")
  814. }
  815. // newNotifyMailService initializes notification email service options from configuration.
  816. // No non-error log will be printed in hook mode.
  817. func newNotifyMailService() {
  818. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  819. return
  820. } else if MailService == nil {
  821. log.Warn("Email notification is not enabled due to the mail service is not available")
  822. return
  823. }
  824. Service.EnableNotifyMail = true
  825. if HookMode {
  826. return
  827. }
  828. log.Trace("Email notification is enabled")
  829. }
  830. func NewService() {
  831. newService()
  832. }
  833. func NewServices() {
  834. newService()
  835. newLogService()
  836. newCacheService()
  837. newSessionService()
  838. newMailService()
  839. newRegisterMailService()
  840. newNotifyMailService()
  841. }
  842. // HookMode indicates whether program starts as Git server-side hook callback.
  843. var HookMode bool
  844. // NewPostReceiveHookServices initializes all services that are needed by
  845. // Git server-side post-receive hook callback.
  846. func NewPostReceiveHookServices() {
  847. HookMode = true
  848. newService()
  849. newMailService()
  850. newNotifyMailService()
  851. }