setting.go 30 KB

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