setting.go 28 KB

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