setting.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. ShowFooterTemplateLoadTime bool
  277. SupportMiniWinService bool
  278. // Global setting objects
  279. Cfg *ini.File
  280. CustomPath string // Custom directory path
  281. CustomConf string
  282. ProdMode bool
  283. RunUser string
  284. IsWindows bool
  285. HasRobotsTxt bool
  286. )
  287. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  288. func DateLang(lang string) string {
  289. name, ok := dateLangs[lang]
  290. if ok {
  291. return name
  292. }
  293. return "en"
  294. }
  295. // execPath returns the executable path.
  296. func execPath() (string, error) {
  297. file, err := exec.LookPath(os.Args[0])
  298. if err != nil {
  299. return "", err
  300. }
  301. return filepath.Abs(file)
  302. }
  303. func init() {
  304. IsWindows = runtime.GOOS == "windows"
  305. log.New(log.CONSOLE, log.ConsoleConfig{})
  306. var err error
  307. if AppPath, err = execPath(); err != nil {
  308. log.Fatal(2, "Fail to get app path: %v\n", err)
  309. }
  310. // Note: we don't use path.Dir here because it does not handle case
  311. // which path starts with two "/" in Windows: "//psf/Home/..."
  312. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  313. }
  314. // WorkDir returns absolute path of work directory.
  315. func WorkDir() (string, error) {
  316. wd := os.Getenv("GOGS_WORK_DIR")
  317. if len(wd) > 0 {
  318. return wd, nil
  319. }
  320. i := strings.LastIndex(AppPath, "/")
  321. if i == -1 {
  322. return AppPath, nil
  323. }
  324. return AppPath[:i], nil
  325. }
  326. func forcePathSeparator(path string) {
  327. if strings.Contains(path, "\\") {
  328. log.Fatal(2, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  329. }
  330. }
  331. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  332. // actual user that runs the app. The first return value is the actual user name.
  333. // This check is ignored under Windows since SSH remote login is not the main
  334. // method to login on Windows.
  335. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  336. if IsWindows {
  337. return "", true
  338. }
  339. currentUser := user.CurrentUsername()
  340. return currentUser, runUser == currentUser
  341. }
  342. // getOpenSSHVersion parses and returns string representation of OpenSSH version
  343. // returned by command "ssh -V".
  344. func getOpenSSHVersion() string {
  345. // Note: somehow version is printed to stderr
  346. _, stderr, err := process.Exec("getOpenSSHVersion", "ssh", "-V")
  347. if err != nil {
  348. log.Fatal(2, "Fail to get OpenSSH version: %v - %s", err, stderr)
  349. }
  350. // Trim unused information: https://gogs.io/gogs/issues/4507#issuecomment-305150441
  351. version := strings.TrimRight(strings.Fields(stderr)[0], ",1234567890")
  352. version = strings.TrimSuffix(strings.TrimPrefix(version, "OpenSSH_"), "p")
  353. return version
  354. }
  355. // NewContext initializes configuration context.
  356. // NOTE: do not print any log except error.
  357. func NewContext() {
  358. workDir, err := WorkDir()
  359. if err != nil {
  360. log.Fatal(2, "Fail to get work directory: %v", err)
  361. }
  362. Cfg, err = ini.LoadSources(ini.LoadOptions{
  363. IgnoreInlineComment: true,
  364. }, conf.MustAsset("conf/app.ini"))
  365. if err != nil {
  366. log.Fatal(2, "Fail to parse 'conf/app.ini': %v", err)
  367. }
  368. CustomPath = os.Getenv("GOGS_CUSTOM")
  369. if len(CustomPath) == 0 {
  370. CustomPath = workDir + "/custom"
  371. }
  372. if len(CustomConf) == 0 {
  373. CustomConf = CustomPath + "/conf/app.ini"
  374. }
  375. if com.IsFile(CustomConf) {
  376. if err = Cfg.Append(CustomConf); err != nil {
  377. log.Fatal(2, "Fail to load custom conf '%s': %v", CustomConf, err)
  378. }
  379. } else {
  380. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  381. }
  382. Cfg.NameMapper = ini.AllCapsUnderscore
  383. homeDir, err := com.HomeDir()
  384. if err != nil {
  385. log.Fatal(2, "Fail to get home directory: %v", err)
  386. }
  387. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  388. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  389. forcePathSeparator(LogRootPath)
  390. sec := Cfg.Section("server")
  391. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs")
  392. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  393. if AppURL[len(AppURL)-1] != '/' {
  394. AppURL += "/"
  395. }
  396. // Check if has app suburl.
  397. url, err := url.Parse(AppURL)
  398. if err != nil {
  399. log.Fatal(2, "Invalid ROOT_URL '%s': %s", AppURL, err)
  400. }
  401. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  402. // This value is empty if site does not have sub-url.
  403. AppSubURL = strings.TrimSuffix(url.Path, "/")
  404. AppSubURLDepth = strings.Count(AppSubURL, "/")
  405. HostAddress = url.Host
  406. Protocol = SCHEME_HTTP
  407. if sec.Key("PROTOCOL").String() == "https" {
  408. Protocol = SCHEME_HTTPS
  409. CertFile = sec.Key("CERT_FILE").String()
  410. KeyFile = sec.Key("KEY_FILE").String()
  411. TLSMinVersion = sec.Key("TLS_MIN_VERSION").String()
  412. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  413. Protocol = SCHEME_FCGI
  414. } else if sec.Key("PROTOCOL").String() == "unix" {
  415. Protocol = SCHEME_UNIX_SOCKET
  416. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  417. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  418. if err != nil || UnixSocketPermissionParsed > 0777 {
  419. log.Fatal(2, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  420. }
  421. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  422. }
  423. Domain = sec.Key("DOMAIN").MustString("localhost")
  424. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  425. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  426. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  427. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  428. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  429. LoadAssetsFromDisk = sec.Key("LOAD_ASSETS_FROM_DISK").MustBool()
  430. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  431. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  432. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  433. switch sec.Key("LANDING_PAGE").MustString("home") {
  434. case "explore":
  435. LandingPageURL = LANDING_PAGE_EXPLORE
  436. default:
  437. LandingPageURL = LANDING_PAGE_HOME
  438. }
  439. SSH.RootPath = path.Join(homeDir, ".ssh")
  440. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  441. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  442. SSH.KeyTestPath = os.TempDir()
  443. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  444. log.Fatal(2, "Fail to map SSH settings: %v", err)
  445. }
  446. if SSH.Disabled {
  447. SSH.StartBuiltinServer = false
  448. SSH.MinimumKeySizeCheck = false
  449. }
  450. if !SSH.Disabled && !SSH.StartBuiltinServer {
  451. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  452. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  453. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  454. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  455. }
  456. }
  457. if SSH.StartBuiltinServer {
  458. SSH.RewriteAuthorizedKeysAtStart = false
  459. }
  460. // Check if server is eligible for minimum key size check when user choose to enable.
  461. // Windows server and OpenSSH version lower than 5.1 (https://gogs.io/gogs/issues/4507)
  462. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  463. if SSH.MinimumKeySizeCheck &&
  464. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  465. SSH.MinimumKeySizeCheck = false
  466. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  467. 1. Windows server
  468. 2. OpenSSH version is lower than 5.1`)
  469. }
  470. if SSH.MinimumKeySizeCheck {
  471. SSH.MinimumKeySizes = map[string]int{}
  472. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  473. if key.MustInt() != -1 {
  474. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  475. }
  476. }
  477. }
  478. sec = Cfg.Section("security")
  479. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  480. SecretKey = sec.Key("SECRET_KEY").String()
  481. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  482. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  483. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  484. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  485. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  486. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  487. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  488. sec = Cfg.Section("attachment")
  489. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  490. if !filepath.IsAbs(AttachmentPath) {
  491. AttachmentPath = path.Join(workDir, AttachmentPath)
  492. }
  493. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  494. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  495. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  496. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  497. TimeFormat = map[string]string{
  498. "ANSIC": time.ANSIC,
  499. "UnixDate": time.UnixDate,
  500. "RubyDate": time.RubyDate,
  501. "RFC822": time.RFC822,
  502. "RFC822Z": time.RFC822Z,
  503. "RFC850": time.RFC850,
  504. "RFC1123": time.RFC1123,
  505. "RFC1123Z": time.RFC1123Z,
  506. "RFC3339": time.RFC3339,
  507. "RFC3339Nano": time.RFC3339Nano,
  508. "Kitchen": time.Kitchen,
  509. "Stamp": time.Stamp,
  510. "StampMilli": time.StampMilli,
  511. "StampMicro": time.StampMicro,
  512. "StampNano": time.StampNano,
  513. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  514. RunUser = Cfg.Section("").Key("RUN_USER").String()
  515. // Does not check run user when the install lock is off.
  516. if InstallLock {
  517. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  518. if !match {
  519. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  520. }
  521. }
  522. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  523. // Determine and create root git repository path.
  524. sec = Cfg.Section("repository")
  525. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  526. forcePathSeparator(RepoRootPath)
  527. if !filepath.IsAbs(RepoRootPath) {
  528. RepoRootPath = path.Join(workDir, RepoRootPath)
  529. } else {
  530. RepoRootPath = path.Clean(RepoRootPath)
  531. }
  532. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  533. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  534. log.Fatal(2, "Fail to map Repository settings: %v", err)
  535. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  536. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  537. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  538. log.Fatal(2, "Fail to map Repository.Upload settings: %v", err)
  539. }
  540. if !filepath.IsAbs(Repository.Upload.TempPath) {
  541. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  542. }
  543. sec = Cfg.Section("picture")
  544. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  545. forcePathSeparator(AvatarUploadPath)
  546. if !filepath.IsAbs(AvatarUploadPath) {
  547. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  548. }
  549. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "repo-avatars"))
  550. forcePathSeparator(RepositoryAvatarUploadPath)
  551. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  552. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  553. }
  554. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  555. case "duoshuo":
  556. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  557. case "gravatar":
  558. GravatarSource = "https://secure.gravatar.com/avatar/"
  559. case "libravatar":
  560. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  561. default:
  562. GravatarSource = source
  563. }
  564. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  565. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  566. if OfflineMode {
  567. DisableGravatar = true
  568. EnableFederatedAvatar = false
  569. }
  570. if DisableGravatar {
  571. EnableFederatedAvatar = false
  572. }
  573. if EnableFederatedAvatar {
  574. LibravatarService = libravatar.New()
  575. parts := strings.Split(GravatarSource, "/")
  576. if len(parts) >= 3 {
  577. if parts[0] == "https:" {
  578. LibravatarService.SetUseHTTPS(true)
  579. LibravatarService.SetSecureFallbackHost(parts[2])
  580. } else {
  581. LibravatarService.SetUseHTTPS(false)
  582. LibravatarService.SetFallbackHost(parts[2])
  583. }
  584. }
  585. }
  586. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  587. log.Fatal(2, "Failed to map HTTP settings: %v", err)
  588. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  589. log.Fatal(2, "Failed to map Webhook settings: %v", err)
  590. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  591. log.Fatal(2, "Failed to map Release.Attachment settings: %v", err)
  592. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  593. log.Fatal(2, "Failed to map Markdown settings: %v", err)
  594. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  595. log.Fatal(2, "Failed to map Smartypants settings: %v", err)
  596. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  597. log.Fatal(2, "Failed to map Admin settings: %v", err)
  598. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  599. log.Fatal(2, "Failed to map Cron settings: %v", err)
  600. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  601. log.Fatal(2, "Failed to map Git settings: %v", err)
  602. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  603. log.Fatal(2, "Failed to map Mirror settings: %v", err)
  604. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  605. log.Fatal(2, "Failed to map API settings: %v", err)
  606. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  607. log.Fatal(2, "Failed to map UI settings: %v", err)
  608. } else if err = Cfg.Section("prometheus").MapTo(&Prometheus); err != nil {
  609. log.Fatal(2, "Failed to map Prometheus settings: %v", err)
  610. }
  611. if Mirror.DefaultInterval <= 0 {
  612. Mirror.DefaultInterval = 24
  613. }
  614. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  615. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  616. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  617. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  618. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  619. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  620. }
  621. var Service struct {
  622. ActiveCodeLives int
  623. ResetPwdCodeLives int
  624. RegisterEmailConfirm bool
  625. DisableRegistration bool
  626. ShowRegistrationButton bool
  627. RequireSignInView bool
  628. EnableNotifyMail bool
  629. EnableReverseProxyAuth bool
  630. EnableReverseProxyAutoRegister bool
  631. EnableCaptcha bool
  632. }
  633. func newService() {
  634. sec := Cfg.Section("service")
  635. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  636. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  637. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  638. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  639. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  640. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  641. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  642. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  643. }
  644. func newLogService() {
  645. if len(BuildTime) > 0 {
  646. log.Trace("Build time: %s", BuildTime)
  647. log.Trace("Build commit: %s", BuildCommit)
  648. }
  649. // Because we always create a console logger as primary logger before all settings are loaded,
  650. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  651. hasConsole := false
  652. // Get and check log modes.
  653. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  654. LogConfigs = make([]interface{}, len(LogModes))
  655. levelNames := map[string]log.LEVEL{
  656. "trace": log.TRACE,
  657. "info": log.INFO,
  658. "warn": log.WARN,
  659. "error": log.ERROR,
  660. "fatal": log.FATAL,
  661. }
  662. for i, mode := range LogModes {
  663. mode = strings.ToLower(strings.TrimSpace(mode))
  664. sec, err := Cfg.GetSection("log." + mode)
  665. if err != nil {
  666. log.Fatal(2, "Unknown logger mode: %s", mode)
  667. }
  668. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  669. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  670. v = strings.ToLower(v)
  671. if com.IsSliceContainsStr(validLevels, v) {
  672. return v
  673. }
  674. return "trace"
  675. })
  676. level := levelNames[name]
  677. // Generate log configuration.
  678. switch log.MODE(mode) {
  679. case log.CONSOLE:
  680. hasConsole = true
  681. LogConfigs[i] = log.ConsoleConfig{
  682. Level: level,
  683. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  684. }
  685. case log.FILE:
  686. logPath := path.Join(LogRootPath, "gogs.log")
  687. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  688. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  689. }
  690. LogConfigs[i] = log.FileConfig{
  691. Level: level,
  692. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  693. Filename: logPath,
  694. FileRotationConfig: log.FileRotationConfig{
  695. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  696. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  697. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  698. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  699. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  700. },
  701. }
  702. case log.SLACK:
  703. LogConfigs[i] = log.SlackConfig{
  704. Level: level,
  705. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  706. URL: sec.Key("URL").String(),
  707. }
  708. case log.DISCORD:
  709. LogConfigs[i] = log.DiscordConfig{
  710. Level: level,
  711. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  712. URL: sec.Key("URL").String(),
  713. Username: sec.Key("USERNAME").String(),
  714. }
  715. }
  716. log.New(log.MODE(mode), LogConfigs[i])
  717. log.Trace("Log mode: %s (%s)", strings.Title(mode), strings.Title(name))
  718. }
  719. // Make sure everyone gets version info printed.
  720. log.Info("%s %s", AppName, AppVersion)
  721. if !hasConsole {
  722. log.Delete(log.CONSOLE)
  723. }
  724. }
  725. func newCacheService() {
  726. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  727. switch CacheAdapter {
  728. case "memory":
  729. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  730. case "redis", "memcache":
  731. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  732. default:
  733. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  734. }
  735. log.Trace("Cache service is enabled")
  736. }
  737. func newSessionService() {
  738. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  739. []string{"memory", "file", "redis", "mysql"})
  740. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  741. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  742. SessionConfig.CookiePath = AppSubURL
  743. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  744. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  745. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  746. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  747. log.Trace("Session service is enabled")
  748. }
  749. // Mailer represents mail service.
  750. type Mailer struct {
  751. QueueLength int
  752. SubjectPrefix string
  753. Host string
  754. From string
  755. FromEmail string
  756. User, Passwd string
  757. DisableHelo bool
  758. HeloHostname string
  759. SkipVerify bool
  760. UseCertificate bool
  761. CertFile, KeyFile string
  762. UsePlainText bool
  763. AddPlainTextAlt bool
  764. }
  765. var (
  766. MailService *Mailer
  767. )
  768. // newMailService initializes mail service options from configuration.
  769. // No non-error log will be printed in hook mode.
  770. func newMailService() {
  771. sec := Cfg.Section("mailer")
  772. if !sec.Key("ENABLED").MustBool() {
  773. return
  774. }
  775. MailService = &Mailer{
  776. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  777. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  778. Host: sec.Key("HOST").String(),
  779. User: sec.Key("USER").String(),
  780. Passwd: sec.Key("PASSWD").String(),
  781. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  782. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  783. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  784. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  785. CertFile: sec.Key("CERT_FILE").String(),
  786. KeyFile: sec.Key("KEY_FILE").String(),
  787. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  788. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  789. }
  790. MailService.From = sec.Key("FROM").MustString(MailService.User)
  791. if len(MailService.From) > 0 {
  792. parsed, err := mail.ParseAddress(MailService.From)
  793. if err != nil {
  794. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  795. }
  796. MailService.FromEmail = parsed.Address
  797. }
  798. if HookMode {
  799. return
  800. }
  801. log.Trace("Mail service is enabled")
  802. }
  803. func newRegisterMailService() {
  804. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  805. return
  806. } else if MailService == nil {
  807. log.Warn("Email confirmation is not enabled due to the mail service is not available")
  808. return
  809. }
  810. Service.RegisterEmailConfirm = true
  811. log.Trace("Email confirmation is enabled")
  812. }
  813. // newNotifyMailService initializes notification email service options from configuration.
  814. // No non-error log will be printed in hook mode.
  815. func newNotifyMailService() {
  816. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  817. return
  818. } else if MailService == nil {
  819. log.Warn("Email notification is not enabled due to the mail service is not available")
  820. return
  821. }
  822. Service.EnableNotifyMail = true
  823. if HookMode {
  824. return
  825. }
  826. log.Trace("Email notification is enabled")
  827. }
  828. func NewService() {
  829. newService()
  830. }
  831. func NewServices() {
  832. newService()
  833. newLogService()
  834. newCacheService()
  835. newSessionService()
  836. newMailService()
  837. newRegisterMailService()
  838. newNotifyMailService()
  839. }
  840. // HookMode indicates whether program starts as Git server-side hook callback.
  841. var HookMode bool
  842. // NewPostReceiveHookServices initializes all services that are needed by
  843. // Git server-side post-receive hook callback.
  844. func NewPostReceiveHookServices() {
  845. HookMode = true
  846. newService()
  847. newMailService()
  848. newNotifyMailService()
  849. }