setting.go 30 KB

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