setting.go 29 KB

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