setting.go 30 KB

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