setting.go 30 KB

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