You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. "crypto/rand"
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "net/mail"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "code.gitea.io/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/user"
  23. "github.com/Unknwon/com"
  24. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  25. _ "github.com/go-macaron/cache/redis"
  26. "github.com/go-macaron/session"
  27. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  28. _ "github.com/kardianos/minwinsvc" // import minwinsvc for windows services
  29. "gopkg.in/ini.v1"
  30. "strk.kbt.io/projects/go/libravatar"
  31. )
  32. // Scheme describes protocol types
  33. type Scheme string
  34. // enumerates all the scheme types
  35. const (
  36. HTTP Scheme = "http"
  37. HTTPS Scheme = "https"
  38. FCGI Scheme = "fcgi"
  39. UnixSocket Scheme = "unix"
  40. )
  41. // LandingPage describes the default page
  42. type LandingPage string
  43. // enumerates all the landing page types
  44. const (
  45. LandingPageHome LandingPage = "/"
  46. LandingPageExplore LandingPage = "/explore"
  47. )
  48. // settings
  49. var (
  50. // AppVer settings
  51. AppVer string
  52. AppName string
  53. AppURL string
  54. AppSubURL string
  55. AppSubURLDepth int // Number of slashes
  56. AppPath string
  57. AppDataPath string
  58. // Server settings
  59. Protocol Scheme
  60. Domain string
  61. HTTPAddr string
  62. HTTPPort string
  63. LocalURL string
  64. OfflineMode bool
  65. DisableRouterLog bool
  66. CertFile string
  67. KeyFile string
  68. StaticRootPath string
  69. EnableGzip bool
  70. LandingPageURL LandingPage
  71. UnixSocketPermission uint32
  72. SSH struct {
  73. Disabled bool `ini:"DISABLE_SSH"`
  74. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  75. Domain string `ini:"SSH_DOMAIN"`
  76. Port int `ini:"SSH_PORT"`
  77. ListenHost string `ini:"SSH_LISTEN_HOST"`
  78. ListenPort int `ini:"SSH_LISTEN_PORT"`
  79. RootPath string `ini:"SSH_ROOT_PATH"`
  80. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  81. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  82. MinimumKeySizeCheck bool `ini:"-"`
  83. MinimumKeySizes map[string]int `ini:"-"`
  84. }
  85. LFS struct {
  86. StartServer bool `ini:"LFS_START_SERVER"`
  87. ContentPath string `ini:"LFS_CONTENT_PATH"`
  88. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  89. JWTSecretBytes []byte `ini:"-"`
  90. }
  91. // Security settings
  92. InstallLock bool
  93. SecretKey string
  94. LogInRememberDays int
  95. CookieUserName string
  96. CookieRememberName string
  97. ReverseProxyAuthUser string
  98. MinPasswordLength int
  99. // Database settings
  100. UseSQLite3 bool
  101. UseMySQL bool
  102. UseMSSQL bool
  103. UsePostgreSQL bool
  104. UseTiDB bool
  105. // Webhook settings
  106. Webhook = struct {
  107. QueueLength int
  108. DeliverTimeout int
  109. SkipTLSVerify bool
  110. Types []string
  111. PagingNum int
  112. }{
  113. QueueLength: 1000,
  114. DeliverTimeout: 5,
  115. SkipTLSVerify: false,
  116. PagingNum: 10,
  117. }
  118. // Repository settings
  119. Repository = struct {
  120. AnsiCharset string
  121. ForcePrivate bool
  122. MaxCreationLimit int
  123. MirrorQueueLength int
  124. PullRequestQueueLength int
  125. PreferredLicenses []string
  126. DisableHTTPGit bool
  127. // Repository editor settings
  128. Editor struct {
  129. LineWrapExtensions []string
  130. PreviewableFileModes []string
  131. } `ini:"-"`
  132. // Repository upload settings
  133. Upload struct {
  134. Enabled bool
  135. TempPath string
  136. AllowedTypes []string `delim:"|"`
  137. FileMaxSize int64
  138. MaxFiles int
  139. } `ini:"-"`
  140. }{
  141. AnsiCharset: "",
  142. ForcePrivate: false,
  143. MaxCreationLimit: -1,
  144. MirrorQueueLength: 1000,
  145. PullRequestQueueLength: 1000,
  146. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  147. DisableHTTPGit: false,
  148. // Repository editor settings
  149. Editor: struct {
  150. LineWrapExtensions []string
  151. PreviewableFileModes []string
  152. }{
  153. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  154. PreviewableFileModes: []string{"markdown"},
  155. },
  156. // Repository upload settings
  157. Upload: struct {
  158. Enabled bool
  159. TempPath string
  160. AllowedTypes []string `delim:"|"`
  161. FileMaxSize int64
  162. MaxFiles int
  163. }{
  164. Enabled: true,
  165. TempPath: "data/tmp/uploads",
  166. AllowedTypes: []string{},
  167. FileMaxSize: 3,
  168. MaxFiles: 5,
  169. },
  170. }
  171. RepoRootPath string
  172. ScriptType = "bash"
  173. // UI settings
  174. UI = struct {
  175. ExplorePagingNum int
  176. IssuePagingNum int
  177. FeedMaxCommitNum int
  178. ThemeColorMetaTag string
  179. MaxDisplayFileSize int64
  180. Admin struct {
  181. UserPagingNum int
  182. RepoPagingNum int
  183. NoticePagingNum int
  184. OrgPagingNum int
  185. } `ini:"ui.admin"`
  186. User struct {
  187. RepoPagingNum int
  188. } `ini:"ui.user"`
  189. }{
  190. ExplorePagingNum: 20,
  191. IssuePagingNum: 10,
  192. FeedMaxCommitNum: 5,
  193. ThemeColorMetaTag: `#6cc644`,
  194. MaxDisplayFileSize: 8388608,
  195. Admin: struct {
  196. UserPagingNum int
  197. RepoPagingNum int
  198. NoticePagingNum int
  199. OrgPagingNum int
  200. }{
  201. UserPagingNum: 50,
  202. RepoPagingNum: 50,
  203. NoticePagingNum: 25,
  204. OrgPagingNum: 50,
  205. },
  206. User: struct {
  207. RepoPagingNum int
  208. }{
  209. RepoPagingNum: 15,
  210. },
  211. }
  212. // Markdown sttings
  213. Markdown = struct {
  214. EnableHardLineBreak bool
  215. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  216. FileExtensions []string
  217. }{
  218. EnableHardLineBreak: false,
  219. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  220. }
  221. // Picture settings
  222. AvatarUploadPath string
  223. GravatarSource string
  224. DisableGravatar bool
  225. EnableFederatedAvatar bool
  226. LibravatarService *libravatar.Libravatar
  227. // Log settings
  228. LogRootPath string
  229. LogModes []string
  230. LogConfigs []string
  231. // Attachment settings
  232. AttachmentPath string
  233. AttachmentAllowedTypes string
  234. AttachmentMaxSize int64
  235. AttachmentMaxFiles int
  236. AttachmentEnabled bool
  237. // Time settings
  238. TimeFormat string
  239. // Cache settings
  240. CacheAdapter string
  241. CacheInterval int
  242. CacheConn string
  243. // Session settings
  244. SessionConfig session.Options
  245. CSRFCookieName = "_csrf"
  246. // Cron tasks
  247. Cron = struct {
  248. UpdateMirror struct {
  249. Enabled bool
  250. RunAtStart bool
  251. Schedule string
  252. } `ini:"cron.update_mirrors"`
  253. RepoHealthCheck struct {
  254. Enabled bool
  255. RunAtStart bool
  256. Schedule string
  257. Timeout time.Duration
  258. Args []string `delim:" "`
  259. } `ini:"cron.repo_health_check"`
  260. CheckRepoStats struct {
  261. Enabled bool
  262. RunAtStart bool
  263. Schedule string
  264. } `ini:"cron.check_repo_stats"`
  265. }{
  266. UpdateMirror: struct {
  267. Enabled bool
  268. RunAtStart bool
  269. Schedule string
  270. }{
  271. Schedule: "@every 10m",
  272. },
  273. RepoHealthCheck: struct {
  274. Enabled bool
  275. RunAtStart bool
  276. Schedule string
  277. Timeout time.Duration
  278. Args []string `delim:" "`
  279. }{
  280. Schedule: "@every 24h",
  281. Timeout: 60 * time.Second,
  282. Args: []string{},
  283. },
  284. CheckRepoStats: struct {
  285. Enabled bool
  286. RunAtStart bool
  287. Schedule string
  288. }{
  289. RunAtStart: true,
  290. Schedule: "@every 24h",
  291. },
  292. }
  293. // Git settings
  294. Git = struct {
  295. DisableDiffHighlight bool
  296. MaxGitDiffLines int
  297. MaxGitDiffLineCharacters int
  298. MaxGitDiffFiles int
  299. GCArgs []string `delim:" "`
  300. Timeout struct {
  301. Migrate int
  302. Mirror int
  303. Clone int
  304. Pull int
  305. GC int `ini:"GC"`
  306. } `ini:"git.timeout"`
  307. }{
  308. DisableDiffHighlight: false,
  309. MaxGitDiffLines: 1000,
  310. MaxGitDiffLineCharacters: 500,
  311. MaxGitDiffFiles: 100,
  312. GCArgs: []string{},
  313. Timeout: struct {
  314. Migrate int
  315. Mirror int
  316. Clone int
  317. Pull int
  318. GC int `ini:"GC"`
  319. }{
  320. Migrate: 600,
  321. Mirror: 300,
  322. Clone: 300,
  323. Pull: 300,
  324. GC: 60,
  325. },
  326. }
  327. // Mirror settings
  328. Mirror = struct {
  329. DefaultInterval int
  330. }{
  331. DefaultInterval: 8,
  332. }
  333. // API settings
  334. API = struct {
  335. MaxResponseItems int
  336. }{
  337. MaxResponseItems: 50,
  338. }
  339. // I18n settings
  340. Langs []string
  341. Names []string
  342. dateLangs map[string]string
  343. // Highlight settings are loaded in modules/template/hightlight.go
  344. // Other settings
  345. ShowFooterBranding bool
  346. ShowFooterVersion bool
  347. ShowFooterTemplateLoadTime bool
  348. // Global setting objects
  349. Cfg *ini.File
  350. CustomPath string // Custom directory path
  351. CustomConf string
  352. ProdMode bool
  353. RunUser string
  354. IsWindows bool
  355. HasRobotsTxt bool
  356. )
  357. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  358. func DateLang(lang string) string {
  359. name, ok := dateLangs[lang]
  360. if ok {
  361. return name
  362. }
  363. return "en"
  364. }
  365. // execPath returns the executable path.
  366. func execPath() (string, error) {
  367. file, err := exec.LookPath(os.Args[0])
  368. if err != nil {
  369. return "", err
  370. }
  371. return filepath.Abs(file)
  372. }
  373. func init() {
  374. IsWindows = runtime.GOOS == "windows"
  375. log.NewLogger(0, "console", `{"level": 0}`)
  376. var err error
  377. if AppPath, err = execPath(); err != nil {
  378. log.Fatal(4, "fail to get app path: %v\n", err)
  379. }
  380. // Note: we don't use path.Dir here because it does not handle case
  381. // which path starts with two "/" in Windows: "//psf/Home/..."
  382. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  383. }
  384. // WorkDir returns absolute path of work directory.
  385. func WorkDir() (string, error) {
  386. wd := os.Getenv("GITEA_WORK_DIR")
  387. if len(wd) > 0 {
  388. return wd, nil
  389. }
  390. // Use GOGS_WORK_DIR if available, for backward compatibility
  391. // TODO: drop in 1.1.0 ?
  392. wd = os.Getenv("GOGS_WORK_DIR")
  393. if len(wd) > 0 {
  394. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  395. please consider changing to GITEA_WORK_DIR`)
  396. return wd, nil
  397. }
  398. i := strings.LastIndex(AppPath, "/")
  399. if i == -1 {
  400. return AppPath, nil
  401. }
  402. return AppPath[:i], nil
  403. }
  404. func forcePathSeparator(path string) {
  405. if strings.Contains(path, "\\") {
  406. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  407. }
  408. }
  409. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  410. // actual user that runs the app. The first return value is the actual user name.
  411. // This check is ignored under Windows since SSH remote login is not the main
  412. // method to login on Windows.
  413. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  414. if IsWindows {
  415. return "", true
  416. }
  417. currentUser := user.CurrentUsername()
  418. return currentUser, runUser == currentUser
  419. }
  420. // NewContext initializes configuration context.
  421. // NOTE: do not print any log except error.
  422. func NewContext() {
  423. workDir, err := WorkDir()
  424. if err != nil {
  425. log.Fatal(4, "Fail to get work directory: %v", err)
  426. }
  427. Cfg = ini.Empty()
  428. if err != nil {
  429. log.Fatal(4, "Fail to parse 'app.ini': %v", err)
  430. }
  431. CustomPath = os.Getenv("GITEA_CUSTOM")
  432. if len(CustomPath) == 0 {
  433. // For backward compatibility
  434. // TODO: drop in 1.1.0 ?
  435. CustomPath = os.Getenv("GOGS_CUSTOM")
  436. if len(CustomPath) == 0 {
  437. CustomPath = workDir + "/custom"
  438. } else {
  439. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  440. please consider changing to GITEA_CUSTOM`)
  441. }
  442. }
  443. if len(CustomConf) == 0 {
  444. CustomConf = CustomPath + "/conf/app.ini"
  445. }
  446. if com.IsFile(CustomConf) {
  447. if err = Cfg.Append(CustomConf); err != nil {
  448. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  449. }
  450. } else {
  451. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  452. }
  453. Cfg.NameMapper = ini.AllCapsUnderscore
  454. homeDir, err := com.HomeDir()
  455. if err != nil {
  456. log.Fatal(4, "Fail to get home directory: %v", err)
  457. }
  458. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  459. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  460. forcePathSeparator(LogRootPath)
  461. sec := Cfg.Section("server")
  462. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  463. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  464. if AppURL[len(AppURL)-1] != '/' {
  465. AppURL += "/"
  466. }
  467. // Check if has app suburl.
  468. url, err := url.Parse(AppURL)
  469. if err != nil {
  470. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  471. }
  472. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  473. // This value is empty if site does not have sub-url.
  474. AppSubURL = strings.TrimSuffix(url.Path, "/")
  475. AppSubURLDepth = strings.Count(AppSubURL, "/")
  476. Protocol = HTTP
  477. if sec.Key("PROTOCOL").String() == "https" {
  478. Protocol = HTTPS
  479. CertFile = sec.Key("CERT_FILE").String()
  480. KeyFile = sec.Key("KEY_FILE").String()
  481. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  482. Protocol = FCGI
  483. } else if sec.Key("PROTOCOL").String() == "unix" {
  484. Protocol = UnixSocket
  485. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  486. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  487. if err != nil || UnixSocketPermissionParsed > 0777 {
  488. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  489. }
  490. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  491. }
  492. Domain = sec.Key("DOMAIN").MustString("localhost")
  493. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  494. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  495. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  496. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  497. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  498. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  499. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  500. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  501. switch sec.Key("LANDING_PAGE").MustString("home") {
  502. case "explore":
  503. LandingPageURL = LandingPageExplore
  504. default:
  505. LandingPageURL = LandingPageHome
  506. }
  507. SSH.RootPath = path.Join(homeDir, ".ssh")
  508. SSH.KeyTestPath = os.TempDir()
  509. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  510. log.Fatal(4, "Fail to map SSH settings: %v", err)
  511. }
  512. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  513. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  514. // When disable SSH, start builtin server value is ignored.
  515. if SSH.Disabled {
  516. SSH.StartBuiltinServer = false
  517. }
  518. if !SSH.Disabled && !SSH.StartBuiltinServer {
  519. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  520. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  521. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  522. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  523. }
  524. }
  525. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  526. SSH.MinimumKeySizes = map[string]int{}
  527. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  528. for _, key := range minimumKeySizes {
  529. if key.MustInt() != -1 {
  530. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  531. }
  532. }
  533. if err = Cfg.Section("server").MapTo(&LFS); err != nil {
  534. log.Fatal(4, "Fail to map LFS settings: %v", err)
  535. }
  536. if LFS.StartServer {
  537. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  538. log.Fatal(4, "Fail to create '%s': %v", LFS.ContentPath, err)
  539. }
  540. LFS.JWTSecretBytes = make([]byte, 32)
  541. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  542. if err != nil || n != 32 {
  543. //Generate new secret and save to config
  544. _, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
  545. if err != nil {
  546. log.Fatal(4, "Error reading random bytes: %s", err)
  547. }
  548. LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
  549. // Save secret
  550. cfg := ini.Empty()
  551. if com.IsFile(CustomConf) {
  552. // Keeps custom settings if there is already something.
  553. if err := cfg.Append(CustomConf); err != nil {
  554. log.Error(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  555. }
  556. }
  557. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  558. os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm)
  559. if err := cfg.SaveTo(CustomConf); err != nil {
  560. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  561. return
  562. }
  563. }
  564. //Disable LFS client hooks if installed for the current OS user
  565. //Needs at least git v2.1.2
  566. binVersion, err := git.BinVersion()
  567. if err != nil {
  568. log.Fatal(4, "Error retrieving git version: %s", err)
  569. }
  570. splitVersion := strings.SplitN(binVersion, ".", 3)
  571. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  572. if err != nil {
  573. log.Fatal(4, "Error parsing git major version: %s", err)
  574. }
  575. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  576. if err != nil {
  577. log.Fatal(4, "Error parsing git minor version: %s", err)
  578. }
  579. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  580. if err != nil {
  581. log.Fatal(4, "Error parsing git revision version: %s", err)
  582. }
  583. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  584. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  585. LFS.StartServer = false
  586. log.Error(4, "LFS server support needs at least Git v2.1.2")
  587. } else {
  588. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  589. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  590. }
  591. }
  592. sec = Cfg.Section("security")
  593. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  594. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  595. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  596. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  597. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  598. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  599. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  600. sec = Cfg.Section("attachment")
  601. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  602. if !filepath.IsAbs(AttachmentPath) {
  603. AttachmentPath = path.Join(workDir, AttachmentPath)
  604. }
  605. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  606. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  607. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  608. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  609. TimeFormat = map[string]string{
  610. "ANSIC": time.ANSIC,
  611. "UnixDate": time.UnixDate,
  612. "RubyDate": time.RubyDate,
  613. "RFC822": time.RFC822,
  614. "RFC822Z": time.RFC822Z,
  615. "RFC850": time.RFC850,
  616. "RFC1123": time.RFC1123,
  617. "RFC1123Z": time.RFC1123Z,
  618. "RFC3339": time.RFC3339,
  619. "RFC3339Nano": time.RFC3339Nano,
  620. "Kitchen": time.Kitchen,
  621. "Stamp": time.Stamp,
  622. "StampMilli": time.StampMilli,
  623. "StampMicro": time.StampMicro,
  624. "StampNano": time.StampNano,
  625. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  626. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  627. // Does not check run user when the install lock is off.
  628. if InstallLock {
  629. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  630. if !match {
  631. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  632. }
  633. }
  634. // Determine and create root git repository path.
  635. sec = Cfg.Section("repository")
  636. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  637. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  638. forcePathSeparator(RepoRootPath)
  639. if !filepath.IsAbs(RepoRootPath) {
  640. RepoRootPath = path.Join(workDir, RepoRootPath)
  641. } else {
  642. RepoRootPath = path.Clean(RepoRootPath)
  643. }
  644. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  645. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  646. log.Fatal(4, "Fail to map Repository settings: %v", err)
  647. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  648. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  649. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  650. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  651. }
  652. if !filepath.IsAbs(Repository.Upload.TempPath) {
  653. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  654. }
  655. sec = Cfg.Section("picture")
  656. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  657. forcePathSeparator(AvatarUploadPath)
  658. if !filepath.IsAbs(AvatarUploadPath) {
  659. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  660. }
  661. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  662. case "duoshuo":
  663. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  664. case "gravatar":
  665. GravatarSource = "https://secure.gravatar.com/avatar/"
  666. case "libravatar":
  667. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  668. default:
  669. GravatarSource = source
  670. }
  671. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  672. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  673. if OfflineMode {
  674. DisableGravatar = true
  675. EnableFederatedAvatar = false
  676. }
  677. if DisableGravatar {
  678. EnableFederatedAvatar = false
  679. }
  680. if EnableFederatedAvatar {
  681. LibravatarService = libravatar.New()
  682. parts := strings.Split(GravatarSource, "/")
  683. if len(parts) >= 3 {
  684. if parts[0] == "https:" {
  685. LibravatarService.SetUseHTTPS(true)
  686. LibravatarService.SetSecureFallbackHost(parts[2])
  687. } else {
  688. LibravatarService.SetUseHTTPS(false)
  689. LibravatarService.SetFallbackHost(parts[2])
  690. }
  691. }
  692. }
  693. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  694. log.Fatal(4, "Fail to map UI settings: %v", err)
  695. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  696. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  697. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  698. log.Fatal(4, "Fail to map Cron settings: %v", err)
  699. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  700. log.Fatal(4, "Fail to map Git settings: %v", err)
  701. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  702. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  703. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  704. log.Fatal(4, "Fail to map API settings: %v", err)
  705. }
  706. if Mirror.DefaultInterval <= 0 {
  707. Mirror.DefaultInterval = 24
  708. }
  709. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  710. if len(Langs) == 0 {
  711. Langs = defaultLangs
  712. }
  713. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  714. if len(Names) == 0 {
  715. Names = defaultLangNames
  716. }
  717. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  718. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  719. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  720. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  721. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  722. }
  723. // Service settings
  724. var Service struct {
  725. ActiveCodeLives int
  726. ResetPwdCodeLives int
  727. RegisterEmailConfirm bool
  728. DisableRegistration bool
  729. ShowRegistrationButton bool
  730. RequireSignInView bool
  731. EnableNotifyMail bool
  732. EnableReverseProxyAuth bool
  733. EnableReverseProxyAutoRegister bool
  734. EnableCaptcha bool
  735. }
  736. func newService() {
  737. sec := Cfg.Section("service")
  738. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  739. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  740. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  741. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  742. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  743. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  744. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  745. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  746. }
  747. var logLevels = map[string]string{
  748. "Trace": "0",
  749. "Debug": "1",
  750. "Info": "2",
  751. "Warn": "3",
  752. "Error": "4",
  753. "Critical": "5",
  754. }
  755. func newLogService() {
  756. log.Info("Gitea v%s", AppVer)
  757. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  758. LogConfigs = make([]string, len(LogModes))
  759. for i, mode := range LogModes {
  760. mode = strings.TrimSpace(mode)
  761. sec, err := Cfg.GetSection("log." + mode)
  762. if err != nil {
  763. sec, _ = Cfg.NewSection("log." + mode)
  764. }
  765. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  766. // Log level.
  767. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  768. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  769. validLevels)
  770. level, ok := logLevels[levelName]
  771. if !ok {
  772. log.Fatal(4, "Unknown log level: %s", levelName)
  773. }
  774. // Generate log configuration.
  775. switch mode {
  776. case "console":
  777. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  778. case "file":
  779. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  780. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  781. panic(err.Error())
  782. }
  783. LogConfigs[i] = fmt.Sprintf(
  784. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  785. logPath,
  786. sec.Key("LOG_ROTATE").MustBool(true),
  787. sec.Key("MAX_LINES").MustInt(1000000),
  788. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  789. sec.Key("DAILY_ROTATE").MustBool(true),
  790. sec.Key("MAX_DAYS").MustInt(7))
  791. case "conn":
  792. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  793. sec.Key("RECONNECT_ON_MSG").MustBool(),
  794. sec.Key("RECONNECT").MustBool(),
  795. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  796. sec.Key("ADDR").MustString(":7020"))
  797. case "smtp":
  798. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  799. sec.Key("USER").MustString("example@example.com"),
  800. sec.Key("PASSWD").MustString("******"),
  801. sec.Key("HOST").MustString("127.0.0.1:25"),
  802. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  803. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  804. case "database":
  805. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  806. sec.Key("DRIVER").String(),
  807. sec.Key("CONN").String())
  808. }
  809. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  810. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  811. }
  812. }
  813. func newCacheService() {
  814. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  815. switch CacheAdapter {
  816. case "memory":
  817. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  818. case "redis", "memcache":
  819. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  820. default:
  821. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  822. }
  823. log.Info("Cache Service Enabled")
  824. }
  825. func newSessionService() {
  826. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  827. []string{"memory", "file", "redis", "mysql"})
  828. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  829. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  830. SessionConfig.CookiePath = AppSubURL
  831. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  832. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  833. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  834. log.Info("Session Service Enabled")
  835. }
  836. // Mailer represents mail service.
  837. type Mailer struct {
  838. // Mailer
  839. QueueLength int
  840. Name string
  841. From string
  842. FromEmail string
  843. EnableHTMLAlternative bool
  844. // SMTP sender
  845. Host string
  846. User, Passwd string
  847. DisableHelo bool
  848. HeloHostname string
  849. SkipVerify bool
  850. UseCertificate bool
  851. CertFile, KeyFile string
  852. // Sendmail sender
  853. UseSendmail bool
  854. SendmailPath string
  855. }
  856. var (
  857. // MailService the global mailer
  858. MailService *Mailer
  859. )
  860. func newMailService() {
  861. sec := Cfg.Section("mailer")
  862. // Check mailer setting.
  863. if !sec.Key("ENABLED").MustBool() {
  864. return
  865. }
  866. MailService = &Mailer{
  867. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  868. Name: sec.Key("NAME").MustString(AppName),
  869. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  870. Host: sec.Key("HOST").String(),
  871. User: sec.Key("USER").String(),
  872. Passwd: sec.Key("PASSWD").String(),
  873. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  874. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  875. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  876. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  877. CertFile: sec.Key("CERT_FILE").String(),
  878. KeyFile: sec.Key("KEY_FILE").String(),
  879. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  880. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  881. }
  882. MailService.From = sec.Key("FROM").MustString(MailService.User)
  883. parsed, err := mail.ParseAddress(MailService.From)
  884. if err != nil {
  885. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  886. }
  887. MailService.FromEmail = parsed.Address
  888. log.Info("Mail Service Enabled")
  889. }
  890. func newRegisterMailService() {
  891. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  892. return
  893. } else if MailService == nil {
  894. log.Warn("Register Mail Service: Mail Service is not enabled")
  895. return
  896. }
  897. Service.RegisterEmailConfirm = true
  898. log.Info("Register Mail Service Enabled")
  899. }
  900. func newNotifyMailService() {
  901. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  902. return
  903. } else if MailService == nil {
  904. log.Warn("Notify Mail Service: Mail Service is not enabled")
  905. return
  906. }
  907. Service.EnableNotifyMail = true
  908. log.Info("Notify Mail Service Enabled")
  909. }
  910. func newWebhookService() {
  911. sec := Cfg.Section("webhook")
  912. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  913. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  914. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  915. Webhook.Types = []string{"gogs", "slack"}
  916. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  917. }
  918. // NewServices initializes the services
  919. func NewServices() {
  920. newService()
  921. newLogService()
  922. newCacheService()
  923. newSessionService()
  924. newMailService()
  925. newRegisterMailService()
  926. newNotifyMailService()
  927. newWebhookService()
  928. }