setting.go 30 KB

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