setting.go 29 KB

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