setting.go 30 KB

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