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/assets/conf"
  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. 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. ShowHTTPGit bool `ini:"SHOW_HTTP_GIT"`
  113. EnableLocalPathMigration bool
  114. CommitsFetchConcurrency int
  115. EnableRawFileRenderMode bool
  116. RawCaptchaMinFileSize int64
  117. CaptchaMinFileSize int64
  118. AutoInit bool
  119. // Repository editor settings
  120. Editor struct {
  121. LineWrapExtensions []string
  122. PreviewableFileModes []string
  123. } `ini:"-"`
  124. // Repository upload settings
  125. Upload struct {
  126. Enabled bool
  127. TempPath string
  128. AllowedTypes []string `delim:"|"`
  129. FileMaxSize int64
  130. AnnexFileMinSize int64
  131. MaxFiles int
  132. } `ini:"-"`
  133. }
  134. RepoRootPath string
  135. ScriptType string
  136. // Webhook settings
  137. Webhook struct {
  138. Types []string
  139. QueueLength int
  140. DeliverTimeout int
  141. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  142. PagingNum int
  143. }
  144. // Release settigns
  145. Release struct {
  146. Attachment struct {
  147. Enabled bool
  148. TempPath string
  149. AllowedTypes []string `delim:"|"`
  150. MaxSize int64
  151. MaxFiles int
  152. } `ini:"-"`
  153. }
  154. // Markdown sttings
  155. Markdown struct {
  156. EnableHardLineBreak bool
  157. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  158. FileExtensions []string
  159. }
  160. // Smartypants settings
  161. Smartypants struct {
  162. Enabled bool
  163. Fractions bool
  164. Dashes bool
  165. LatexDashes bool
  166. AngledQuotes bool
  167. }
  168. // Admin settings
  169. Admin struct {
  170. DisableRegularOrgCreation bool
  171. }
  172. // Picture settings
  173. AvatarUploadPath string
  174. RepositoryAvatarUploadPath string
  175. GravatarSource string
  176. DisableGravatar bool
  177. EnableFederatedAvatar bool
  178. LibravatarService *libravatar.Libravatar
  179. // Log settings
  180. LogRootPath string
  181. LogModes []string
  182. LogConfigs []interface{}
  183. // Attachment settings
  184. AttachmentPath string
  185. AttachmentAllowedTypes string
  186. AttachmentMaxSize int64
  187. AttachmentMaxFiles int
  188. AttachmentEnabled bool
  189. // Time settings
  190. TimeFormat string
  191. // Cache settings
  192. CacheAdapter string
  193. CacheInterval int
  194. CacheConn string
  195. // Session settings
  196. SessionConfig session.Options
  197. CSRFCookieName string
  198. // Cron tasks
  199. Cron struct {
  200. UpdateMirror struct {
  201. Enabled bool
  202. RunAtStart bool
  203. Schedule string
  204. } `ini:"cron.update_mirrors"`
  205. RepoHealthCheck struct {
  206. Enabled bool
  207. RunAtStart bool
  208. Schedule string
  209. Timeout time.Duration
  210. Args []string `delim:" "`
  211. } `ini:"cron.repo_health_check"`
  212. CheckRepoStats struct {
  213. Enabled bool
  214. RunAtStart bool
  215. Schedule string
  216. } `ini:"cron.check_repo_stats"`
  217. RepoArchiveCleanup struct {
  218. Enabled bool
  219. RunAtStart bool
  220. Schedule string
  221. OlderThan time.Duration
  222. } `ini:"cron.repo_archive_cleanup"`
  223. }
  224. // Git settings
  225. Git struct {
  226. Version string `ini:"-"`
  227. DisableDiffHighlight bool
  228. MaxGitDiffLines int
  229. MaxGitDiffLineCharacters int
  230. MaxGitDiffFiles int
  231. GCArgs []string `ini:"GC_ARGS" delim:" "`
  232. Timeout struct {
  233. Migrate int
  234. Mirror int
  235. Clone int
  236. Pull int
  237. GC int `ini:"GC"`
  238. } `ini:"git.timeout"`
  239. }
  240. // Mirror settings
  241. Mirror struct {
  242. DefaultInterval int
  243. }
  244. // API settings
  245. API struct {
  246. MaxResponseItems int
  247. }
  248. // UI settings
  249. UI struct {
  250. ExplorePagingNum int
  251. IssuePagingNum int
  252. FeedMaxCommitNum int
  253. ThemeColorMetaTag string
  254. MaxDisplayFileSize int64
  255. MaxLineHighlight int
  256. Admin struct {
  257. UserPagingNum int
  258. RepoPagingNum int
  259. NoticePagingNum int
  260. OrgPagingNum int
  261. } `ini:"ui.admin"`
  262. User struct {
  263. RepoPagingNum int
  264. NewsFeedPagingNum int
  265. CommitsPagingNum int
  266. } `ini:"ui.user"`
  267. }
  268. // Prometheus settings
  269. Prometheus struct {
  270. Enabled bool
  271. EnableBasicAuth bool
  272. BasicAuthUsername string
  273. BasicAuthPassword string
  274. }
  275. // I18n settings
  276. Langs []string
  277. Names []string
  278. dateLangs map[string]string
  279. // Highlight settings are loaded in modules/template/hightlight.go
  280. // Other settings
  281. ShowFooterBranding 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. }, conf.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. LoadAssetsFromDisk = sec.Key("LOAD_ASSETS_FROM_DISK").MustBool()
  454. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  455. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  456. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  457. switch sec.Key("LANDING_PAGE").MustString("home") {
  458. case "explore":
  459. LandingPageURL = LANDING_PAGE_EXPLORE
  460. default:
  461. LandingPageURL = LANDING_PAGE_HOME
  462. }
  463. SSH.RootPath = path.Join(homeDir, ".ssh")
  464. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  465. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  466. SSH.KeyTestPath = os.TempDir()
  467. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  468. log.Fatal(2, "Failed to map SSH settings: %v", err)
  469. }
  470. if SSH.Disabled {
  471. SSH.StartBuiltinServer = false
  472. SSH.MinimumKeySizeCheck = false
  473. }
  474. if !SSH.Disabled && !SSH.StartBuiltinServer {
  475. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  476. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  477. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  478. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  479. }
  480. }
  481. if SSH.StartBuiltinServer {
  482. SSH.RewriteAuthorizedKeysAtStart = false
  483. }
  484. // Check if server is eligible for minimum key size check when user choose to enable.
  485. // Windows server and OpenSSH version lower than 5.1 (https://gogs.io/gogs/issues/4507)
  486. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  487. if SSH.MinimumKeySizeCheck &&
  488. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  489. SSH.MinimumKeySizeCheck = false
  490. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  491. 1. Windows server
  492. 2. OpenSSH version is lower than 5.1`)
  493. }
  494. if SSH.MinimumKeySizeCheck {
  495. SSH.MinimumKeySizes = map[string]int{}
  496. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  497. if key.MustInt() != -1 {
  498. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  499. }
  500. }
  501. }
  502. sec = Cfg.Section("security")
  503. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  504. SecretKey = sec.Key("SECRET_KEY").String()
  505. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  506. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  507. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  508. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  509. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  510. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  511. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  512. sec = Cfg.Section("attachment")
  513. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  514. if !filepath.IsAbs(AttachmentPath) {
  515. AttachmentPath = path.Join(workDir, AttachmentPath)
  516. }
  517. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  518. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  519. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  520. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  521. TimeFormat = map[string]string{
  522. "ANSIC": time.ANSIC,
  523. "UnixDate": time.UnixDate,
  524. "RubyDate": time.RubyDate,
  525. "RFC822": time.RFC822,
  526. "RFC822Z": time.RFC822Z,
  527. "RFC850": time.RFC850,
  528. "RFC1123": time.RFC1123,
  529. "RFC1123Z": time.RFC1123Z,
  530. "RFC3339": time.RFC3339,
  531. "RFC3339Nano": time.RFC3339Nano,
  532. "Kitchen": time.Kitchen,
  533. "Stamp": time.Stamp,
  534. "StampMilli": time.StampMilli,
  535. "StampMicro": time.StampMicro,
  536. "StampNano": time.StampNano,
  537. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  538. RunUser = Cfg.Section("").Key("RUN_USER").String()
  539. // Does not check run user when the install lock is off.
  540. if InstallLock {
  541. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  542. if !match {
  543. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  544. }
  545. }
  546. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  547. // Determine and create root git repository path.
  548. sec = Cfg.Section("repository")
  549. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  550. forcePathSeparator(RepoRootPath)
  551. if !filepath.IsAbs(RepoRootPath) {
  552. RepoRootPath = path.Join(workDir, RepoRootPath)
  553. } else {
  554. RepoRootPath = path.Clean(RepoRootPath)
  555. }
  556. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  557. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  558. log.Fatal(2, "Failed to map Repository settings: %v", err)
  559. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  560. log.Fatal(2, "Failed to map Repository.Editor settings: %v", err)
  561. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  562. log.Fatal(2, "Failed to map Repository.Upload settings: %v", err)
  563. }
  564. if !filepath.IsAbs(Repository.Upload.TempPath) {
  565. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  566. }
  567. sec = Cfg.Section("picture")
  568. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  569. forcePathSeparator(AvatarUploadPath)
  570. if !filepath.IsAbs(AvatarUploadPath) {
  571. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  572. }
  573. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "repo-avatars"))
  574. forcePathSeparator(RepositoryAvatarUploadPath)
  575. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  576. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  577. }
  578. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  579. case "duoshuo":
  580. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  581. case "gravatar":
  582. GravatarSource = "https://secure.gravatar.com/avatar/"
  583. case "libravatar":
  584. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  585. default:
  586. GravatarSource = source
  587. }
  588. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  589. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  590. if OfflineMode {
  591. DisableGravatar = true
  592. EnableFederatedAvatar = false
  593. }
  594. if DisableGravatar {
  595. EnableFederatedAvatar = false
  596. }
  597. if EnableFederatedAvatar {
  598. LibravatarService = libravatar.New()
  599. parts := strings.Split(GravatarSource, "/")
  600. if len(parts) >= 3 {
  601. if parts[0] == "https:" {
  602. LibravatarService.SetUseHTTPS(true)
  603. LibravatarService.SetSecureFallbackHost(parts[2])
  604. } else {
  605. LibravatarService.SetUseHTTPS(false)
  606. LibravatarService.SetFallbackHost(parts[2])
  607. }
  608. }
  609. }
  610. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  611. log.Fatal(2, "Failed to map HTTP settings: %v", err)
  612. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  613. log.Fatal(2, "Failed to map Webhook settings: %v", err)
  614. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  615. log.Fatal(2, "Failed to map Release.Attachment settings: %v", err)
  616. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  617. log.Fatal(2, "Failed to map Markdown settings: %v", err)
  618. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  619. log.Fatal(2, "Failed to map Smartypants settings: %v", err)
  620. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  621. log.Fatal(2, "Failed to map Admin settings: %v", err)
  622. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  623. log.Fatal(2, "Failed to map Cron settings: %v", err)
  624. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  625. log.Fatal(2, "Failed to map Git settings: %v", err)
  626. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  627. log.Fatal(2, "Failed to map Mirror settings: %v", err)
  628. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  629. log.Fatal(2, "Failed to map API settings: %v", err)
  630. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  631. log.Fatal(2, "Failed to map UI settings: %v", err)
  632. } else if err = Cfg.Section("prometheus").MapTo(&Prometheus); err != nil {
  633. log.Fatal(2, "Failed to map Prometheus settings: %v", err)
  634. } else if err = Cfg.Section("search").MapTo(&Search); err != nil {
  635. log.Fatal(2, "Failed to map Search settings: %v", err)
  636. } else if err = Cfg.Section("doi").MapTo(&DOI); err != nil {
  637. log.Fatal(2, "Failed to map DOI settings: %v", err)
  638. } else if err = Cfg.Section("cliconfig").MapTo(&CLIConfig); err != nil {
  639. log.Fatal(2, "Failed to map Client config settings: %v", err)
  640. } else if err = Cfg.Section("dav").MapTo(&WebDav); err != nil {
  641. log.Fatal(2, "Failed to map WebDav settings: %v", err)
  642. }
  643. if Mirror.DefaultInterval <= 0 {
  644. Mirror.DefaultInterval = 24
  645. }
  646. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  647. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  648. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  649. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").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 commit: %s", BuildCommit)
  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, AppVersion)
  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.Trace("Cache service is 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.Trace("Session service is 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.Trace("Mail service is 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("Email confirmation is not enabled due to the mail service is not available")
  840. return
  841. }
  842. Service.RegisterEmailConfirm = true
  843. log.Trace("Email confirmation is 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("Email notification is not enabled due to the mail service is not available")
  852. return
  853. }
  854. Service.EnableNotifyMail = true
  855. if HookMode {
  856. return
  857. }
  858. log.Trace("Email notification is 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. }