conf.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package conf
  5. import (
  6. "net/mail"
  7. "net/url"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. _ "github.com/go-macaron/cache/memcache"
  15. _ "github.com/go-macaron/cache/redis"
  16. "github.com/go-macaron/session"
  17. _ "github.com/go-macaron/session/redis"
  18. "github.com/mcuadros/go-version"
  19. "github.com/pkg/errors"
  20. "gopkg.in/ini.v1"
  21. log "unknwon.dev/clog/v2"
  22. "github.com/gogs/go-libravatar"
  23. "gogs.io/gogs/internal/assets/conf"
  24. "gogs.io/gogs/internal/osutil"
  25. "gogs.io/gogs/internal/user"
  26. )
  27. func init() {
  28. // Initialize the primary logger until logging service is up.
  29. err := log.NewConsole()
  30. if err != nil {
  31. panic("init console logger: " + err.Error())
  32. }
  33. }
  34. // Asset is a wrapper for getting conf assets.
  35. func Asset(name string) ([]byte, error) {
  36. return conf.Asset(name)
  37. }
  38. // AssetDir is a wrapper for getting conf assets.
  39. func AssetDir(name string) ([]string, error) {
  40. return conf.AssetDir(name)
  41. }
  42. // MustAsset is a wrapper for getting conf assets.
  43. func MustAsset(name string) []byte {
  44. return conf.MustAsset(name)
  45. }
  46. // File is the configuration object.
  47. var File *ini.File
  48. // Init initializes configuration from conf assets and given custom configuration file.
  49. // If `customConf` is empty, it falls back to default location, i.e. "<WORK DIR>/custom".
  50. // It is safe to call this function multiple times with desired `customConf`, but it is
  51. // not concurrent safe.
  52. //
  53. // ⚠️ WARNING: Do not print anything in this function other than wanrings.
  54. func Init(customConf string) error {
  55. var err error
  56. File, err = ini.LoadSources(ini.LoadOptions{
  57. IgnoreInlineComment: true,
  58. }, conf.MustAsset("conf/app.ini"))
  59. if err != nil {
  60. return errors.Wrap(err, "parse 'conf/app.ini'")
  61. }
  62. File.NameMapper = ini.SnackCase
  63. customConf, err = filepath.Abs(customConf)
  64. if err != nil {
  65. return errors.Wrap(err, "get absolute path")
  66. }
  67. if customConf == "" {
  68. customConf = filepath.Join(CustomDir(), "conf/app.ini")
  69. }
  70. CustomConf = customConf
  71. if osutil.IsFile(customConf) {
  72. if err = File.Append(customConf); err != nil {
  73. return errors.Wrapf(err, "append %q", customConf)
  74. }
  75. } else {
  76. log.Warn("Custom config %q not found. Ignore this warning if you're running for the first time", customConf)
  77. }
  78. if err = File.Section(ini.DefaultSection).MapTo(&App); err != nil {
  79. return errors.Wrap(err, "mapping default section")
  80. }
  81. // ***************************
  82. // ----- Server settings -----
  83. // ***************************
  84. if err = File.Section("server").MapTo(&Server); err != nil {
  85. return errors.Wrap(err, "mapping [server] section")
  86. }
  87. if !strings.HasSuffix(Server.ExternalURL, "/") {
  88. Server.ExternalURL += "/"
  89. }
  90. Server.URL, err = url.Parse(Server.ExternalURL)
  91. if err != nil {
  92. return errors.Wrapf(err, "parse '[server] EXTERNAL_URL' %q", err)
  93. }
  94. // Subpath should start with '/' and end without '/', i.e. '/{subpath}'.
  95. Server.Subpath = strings.TrimRight(Server.URL.Path, "/")
  96. Server.SubpathDepth = strings.Count(Server.Subpath, "/")
  97. unixSocketMode, err := strconv.ParseUint(Server.UnixSocketPermission, 8, 32)
  98. if err != nil {
  99. return errors.Wrapf(err, "parse '[server] UNIX_SOCKET_PERMISSION' %q", Server.UnixSocketPermission)
  100. }
  101. if unixSocketMode > 0777 {
  102. unixSocketMode = 0666
  103. }
  104. Server.UnixSocketMode = os.FileMode(unixSocketMode)
  105. if !filepath.IsAbs(Server.AppDataPath) {
  106. Server.AppDataPath = filepath.Join(WorkDir(), Server.AppDataPath)
  107. }
  108. // ************************
  109. // ----- SSH settings -----
  110. // ************************
  111. if err = File.Section("server").MapTo(&SSH); err != nil {
  112. return errors.Wrap(err, "mapping SSH settings from [server] section")
  113. }
  114. if !SSH.Disabled {
  115. SSH.RootPath = filepath.Join(HomeDir(), ".ssh")
  116. SSH.KeyTestPath = os.TempDir()
  117. if !SSH.StartBuiltinServer {
  118. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  119. return errors.Wrap(err, "create SSH root directory")
  120. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  121. return errors.Wrap(err, "create SSH key test directory")
  122. }
  123. } else {
  124. SSH.RewriteAuthorizedKeysAtStart = false
  125. }
  126. // Check if server is eligible for minimum key size check when user choose to enable.
  127. // Windows server and OpenSSH version lower than 5.1 are forced to be disabled because
  128. // the "ssh-keygen" in Windows does not print key type.
  129. // See https://github.com/gogs/gogs/issues/4507.
  130. if SSH.MinimumKeySizeCheck {
  131. sshVersion, err := openSSHVersion()
  132. if err != nil {
  133. return errors.Wrap(err, "get OpenSSH version")
  134. }
  135. if IsWindowsRuntime() || version.Compare(sshVersion, "5.1", "<") {
  136. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  137. 1. Windows server
  138. 2. OpenSSH version is lower than 5.1`)
  139. } else {
  140. SSH.MinimumKeySizes = map[string]int{}
  141. for _, key := range File.Section("ssh.minimum_key_sizes").Keys() {
  142. if key.MustInt() != -1 {
  143. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  144. }
  145. }
  146. }
  147. }
  148. }
  149. transferDeprecated()
  150. // TODO
  151. sec := File.Section("security")
  152. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  153. SecretKey = sec.Key("SECRET_KEY").String()
  154. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  155. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  156. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  157. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  158. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  159. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  160. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  161. // Does not check run user when the install lock is off.
  162. if InstallLock {
  163. currentUser, match := IsRunUserMatchCurrentUser(App.RunUser)
  164. if !match {
  165. log.Fatal("The user configured to run Gogs is %q, but the current user is %q", App.RunUser, currentUser)
  166. }
  167. }
  168. sec = File.Section("attachment")
  169. AttachmentPath = sec.Key("PATH").MustString(filepath.Join(Server.AppDataPath, "attachments"))
  170. if !filepath.IsAbs(AttachmentPath) {
  171. AttachmentPath = path.Join(workDir, AttachmentPath)
  172. }
  173. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  174. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  175. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  176. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  177. TimeFormat = map[string]string{
  178. "ANSIC": time.ANSIC,
  179. "UnixDate": time.UnixDate,
  180. "RubyDate": time.RubyDate,
  181. "RFC822": time.RFC822,
  182. "RFC822Z": time.RFC822Z,
  183. "RFC850": time.RFC850,
  184. "RFC1123": time.RFC1123,
  185. "RFC1123Z": time.RFC1123Z,
  186. "RFC3339": time.RFC3339,
  187. "RFC3339Nano": time.RFC3339Nano,
  188. "Kitchen": time.Kitchen,
  189. "Stamp": time.Stamp,
  190. "StampMilli": time.StampMilli,
  191. "StampMicro": time.StampMicro,
  192. "StampNano": time.StampNano,
  193. }[File.Section("time").Key("FORMAT").MustString("RFC1123")]
  194. // Determine and create root git repository path.
  195. sec = File.Section("repository")
  196. RepoRootPath = sec.Key("ROOT").MustString(filepath.Join(HomeDir(), "gogs-repositories"))
  197. if !filepath.IsAbs(RepoRootPath) {
  198. RepoRootPath = path.Join(workDir, RepoRootPath)
  199. } else {
  200. RepoRootPath = path.Clean(RepoRootPath)
  201. }
  202. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  203. if err = File.Section("repository").MapTo(&Repository); err != nil {
  204. log.Fatal("Failed to map Repository settings: %v", err)
  205. } else if err = File.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  206. log.Fatal("Failed to map Repository.Editor settings: %v", err)
  207. } else if err = File.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  208. log.Fatal("Failed to map Repository.Upload settings: %v", err)
  209. }
  210. if !filepath.IsAbs(Repository.Upload.TempPath) {
  211. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  212. }
  213. sec = File.Section("picture")
  214. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(filepath.Join(Server.AppDataPath, "avatars"))
  215. if !filepath.IsAbs(AvatarUploadPath) {
  216. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  217. }
  218. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(filepath.Join(Server.AppDataPath, "repo-avatars"))
  219. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  220. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  221. }
  222. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  223. case "duoshuo":
  224. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  225. case "gravatar":
  226. GravatarSource = "https://secure.gravatar.com/avatar/"
  227. case "libravatar":
  228. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  229. default:
  230. GravatarSource = source
  231. }
  232. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  233. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  234. if Server.OfflineMode {
  235. DisableGravatar = true
  236. EnableFederatedAvatar = false
  237. }
  238. if DisableGravatar {
  239. EnableFederatedAvatar = false
  240. }
  241. if EnableFederatedAvatar {
  242. LibravatarService = libravatar.New()
  243. parts := strings.Split(GravatarSource, "/")
  244. if len(parts) >= 3 {
  245. if parts[0] == "https:" {
  246. LibravatarService.SetUseHTTPS(true)
  247. LibravatarService.SetSecureFallbackHost(parts[2])
  248. } else {
  249. LibravatarService.SetUseHTTPS(false)
  250. LibravatarService.SetFallbackHost(parts[2])
  251. }
  252. }
  253. }
  254. if err = File.Section("http").MapTo(&HTTP); err != nil {
  255. log.Fatal("Failed to map HTTP settings: %v", err)
  256. } else if err = File.Section("webhook").MapTo(&Webhook); err != nil {
  257. log.Fatal("Failed to map Webhook settings: %v", err)
  258. } else if err = File.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  259. log.Fatal("Failed to map Release.Attachment settings: %v", err)
  260. } else if err = File.Section("markdown").MapTo(&Markdown); err != nil {
  261. log.Fatal("Failed to map Markdown settings: %v", err)
  262. } else if err = File.Section("smartypants").MapTo(&Smartypants); err != nil {
  263. log.Fatal("Failed to map Smartypants settings: %v", err)
  264. } else if err = File.Section("admin").MapTo(&Admin); err != nil {
  265. log.Fatal("Failed to map Admin settings: %v", err)
  266. } else if err = File.Section("cron").MapTo(&Cron); err != nil {
  267. log.Fatal("Failed to map Cron settings: %v", err)
  268. } else if err = File.Section("git").MapTo(&Git); err != nil {
  269. log.Fatal("Failed to map Git settings: %v", err)
  270. } else if err = File.Section("mirror").MapTo(&Mirror); err != nil {
  271. log.Fatal("Failed to map Mirror settings: %v", err)
  272. } else if err = File.Section("api").MapTo(&API); err != nil {
  273. log.Fatal("Failed to map API settings: %v", err)
  274. } else if err = File.Section("ui").MapTo(&UI); err != nil {
  275. log.Fatal("Failed to map UI settings: %v", err)
  276. } else if err = File.Section("prometheus").MapTo(&Prometheus); err != nil {
  277. log.Fatal("Failed to map Prometheus settings: %v", err)
  278. }
  279. if Mirror.DefaultInterval <= 0 {
  280. Mirror.DefaultInterval = 24
  281. }
  282. Langs = File.Section("i18n").Key("LANGS").Strings(",")
  283. Names = File.Section("i18n").Key("NAMES").Strings(",")
  284. dateLangs = File.Section("i18n.datelang").KeysHash()
  285. ShowFooterBranding = File.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  286. ShowFooterTemplateLoadTime = File.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  287. HasRobotsTxt = osutil.IsFile(path.Join(CustomDir(), "robots.txt"))
  288. return nil
  289. }
  290. // MustInit panics if configuration initialization failed.
  291. func MustInit(customConf string) {
  292. err := Init(customConf)
  293. if err != nil {
  294. panic(err)
  295. }
  296. }
  297. // TODO
  298. var (
  299. HTTP struct {
  300. AccessControlAllowOrigin string
  301. }
  302. // Security settings
  303. InstallLock bool
  304. SecretKey string
  305. LoginRememberDays int
  306. CookieUserName string
  307. CookieRememberName string
  308. CookieSecure bool
  309. ReverseProxyAuthUser string
  310. EnableLoginStatusCookie bool
  311. LoginStatusCookieName string
  312. // Database settings
  313. UseSQLite3 bool
  314. UseMySQL bool
  315. UsePostgreSQL bool
  316. UseMSSQL bool
  317. // Repository settings
  318. Repository struct {
  319. AnsiCharset string
  320. ForcePrivate bool
  321. MaxCreationLimit int
  322. MirrorQueueLength int
  323. PullRequestQueueLength int
  324. PreferredLicenses []string
  325. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  326. EnableLocalPathMigration bool
  327. CommitsFetchConcurrency int
  328. EnableRawFileRenderMode bool
  329. // Repository editor settings
  330. Editor struct {
  331. LineWrapExtensions []string
  332. PreviewableFileModes []string
  333. } `ini:"-"`
  334. // Repository upload settings
  335. Upload struct {
  336. Enabled bool
  337. TempPath string
  338. AllowedTypes []string `delim:"|"`
  339. FileMaxSize int64
  340. MaxFiles int
  341. } `ini:"-"`
  342. }
  343. RepoRootPath string
  344. ScriptType string
  345. // Webhook settings
  346. Webhook struct {
  347. Types []string
  348. QueueLength int
  349. DeliverTimeout int
  350. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  351. PagingNum int
  352. }
  353. // Release settigns
  354. Release struct {
  355. Attachment struct {
  356. Enabled bool
  357. TempPath string
  358. AllowedTypes []string `delim:"|"`
  359. MaxSize int64
  360. MaxFiles int
  361. } `ini:"-"`
  362. }
  363. // Markdown sttings
  364. Markdown struct {
  365. EnableHardLineBreak bool
  366. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  367. FileExtensions []string
  368. }
  369. // Smartypants settings
  370. Smartypants struct {
  371. Enabled bool
  372. Fractions bool
  373. Dashes bool
  374. LatexDashes bool
  375. AngledQuotes bool
  376. }
  377. // Admin settings
  378. Admin struct {
  379. DisableRegularOrgCreation bool
  380. }
  381. // Picture settings
  382. AvatarUploadPath string
  383. RepositoryAvatarUploadPath string
  384. GravatarSource string
  385. DisableGravatar bool
  386. EnableFederatedAvatar bool
  387. LibravatarService *libravatar.Libravatar
  388. // Log settings
  389. LogRootPath string
  390. LogModes []string
  391. LogConfigs []interface{}
  392. // Attachment settings
  393. AttachmentPath string
  394. AttachmentAllowedTypes string
  395. AttachmentMaxSize int64
  396. AttachmentMaxFiles int
  397. AttachmentEnabled bool
  398. // Time settings
  399. TimeFormat string
  400. // Cache settings
  401. CacheAdapter string
  402. CacheInterval int
  403. CacheConn string
  404. // Session settings
  405. SessionConfig session.Options
  406. CSRFCookieName string
  407. // Cron tasks
  408. Cron struct {
  409. UpdateMirror struct {
  410. Enabled bool
  411. RunAtStart bool
  412. Schedule string
  413. } `ini:"cron.update_mirrors"`
  414. RepoHealthCheck struct {
  415. Enabled bool
  416. RunAtStart bool
  417. Schedule string
  418. Timeout time.Duration
  419. Args []string `delim:" "`
  420. } `ini:"cron.repo_health_check"`
  421. CheckRepoStats struct {
  422. Enabled bool
  423. RunAtStart bool
  424. Schedule string
  425. } `ini:"cron.check_repo_stats"`
  426. RepoArchiveCleanup struct {
  427. Enabled bool
  428. RunAtStart bool
  429. Schedule string
  430. OlderThan time.Duration
  431. } `ini:"cron.repo_archive_cleanup"`
  432. }
  433. // Git settings
  434. Git struct {
  435. Version string `ini:"-"`
  436. DisableDiffHighlight bool
  437. MaxGitDiffLines int
  438. MaxGitDiffLineCharacters int
  439. MaxGitDiffFiles int
  440. GCArgs []string `ini:"GC_ARGS" delim:" "`
  441. Timeout struct {
  442. Migrate int
  443. Mirror int
  444. Clone int
  445. Pull int
  446. GC int `ini:"GC"`
  447. } `ini:"git.timeout"`
  448. }
  449. // Mirror settings
  450. Mirror struct {
  451. DefaultInterval int
  452. }
  453. // API settings
  454. API struct {
  455. MaxResponseItems int
  456. }
  457. // UI settings
  458. UI struct {
  459. ExplorePagingNum int
  460. IssuePagingNum int
  461. FeedMaxCommitNum int
  462. ThemeColorMetaTag string
  463. MaxDisplayFileSize int64
  464. Admin struct {
  465. UserPagingNum int
  466. RepoPagingNum int
  467. NoticePagingNum int
  468. OrgPagingNum int
  469. } `ini:"ui.admin"`
  470. User struct {
  471. RepoPagingNum int
  472. NewsFeedPagingNum int
  473. CommitsPagingNum int
  474. } `ini:"ui.user"`
  475. }
  476. // Prometheus settings
  477. Prometheus struct {
  478. Enabled bool
  479. EnableBasicAuth bool
  480. BasicAuthUsername string
  481. BasicAuthPassword string
  482. }
  483. // I18n settings
  484. Langs []string
  485. Names []string
  486. dateLangs map[string]string
  487. // Highlight settings are loaded in modules/template/hightlight.go
  488. // Other settings
  489. ShowFooterBranding bool
  490. ShowFooterTemplateLoadTime bool
  491. // Global setting objects
  492. HasRobotsTxt bool
  493. )
  494. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  495. func DateLang(lang string) string {
  496. name, ok := dateLangs[lang]
  497. if ok {
  498. return name
  499. }
  500. return "en"
  501. }
  502. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  503. // actual user that runs the app. The first return value is the actual user name.
  504. // This check is ignored under Windows since SSH remote login is not the main
  505. // method to login on Windows.
  506. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  507. if IsWindowsRuntime() {
  508. return "", true
  509. }
  510. currentUser := user.CurrentUsername()
  511. return currentUser, runUser == currentUser
  512. }
  513. // InitLogging initializes the logging service of the application.
  514. func InitLogging() {
  515. LogRootPath = File.Section("log").Key("ROOT_PATH").MustString(filepath.Join(WorkDir(), "log"))
  516. // Because we always create a console logger as the primary logger at init time,
  517. // we need to remove it in case the user doesn't configure to use it after the
  518. // logging service is initalized.
  519. hasConsole := false
  520. // Iterate over [log.*] sections to initialize individual logger.
  521. LogModes = strings.Split(File.Section("log").Key("MODE").MustString("console"), ",")
  522. LogConfigs = make([]interface{}, len(LogModes))
  523. levelMappings := map[string]log.Level{
  524. "trace": log.LevelTrace,
  525. "info": log.LevelInfo,
  526. "warn": log.LevelWarn,
  527. "error": log.LevelError,
  528. "fatal": log.LevelFatal,
  529. }
  530. type config struct {
  531. Buffer int64
  532. Config interface{}
  533. }
  534. for i, mode := range LogModes {
  535. mode = strings.ToLower(strings.TrimSpace(mode))
  536. secName := "log." + mode
  537. sec, err := File.GetSection(secName)
  538. if err != nil {
  539. log.Fatal("Missing configuration section [%s] for %q logger", secName, mode)
  540. return
  541. }
  542. level := levelMappings[sec.Key("LEVEL").MustString("trace")]
  543. buffer := sec.Key("BUFFER_LEN").MustInt64(100)
  544. c := new(config)
  545. switch mode {
  546. case log.DefaultConsoleName:
  547. hasConsole = true
  548. c = &config{
  549. Buffer: buffer,
  550. Config: log.ConsoleConfig{
  551. Level: level,
  552. },
  553. }
  554. err = log.NewConsole(c.Buffer, c.Config)
  555. case log.DefaultFileName:
  556. logPath := filepath.Join(LogRootPath, "gogs.log")
  557. logDir := filepath.Dir(logPath)
  558. err = os.MkdirAll(logDir, os.ModePerm)
  559. if err != nil {
  560. log.Fatal("Failed to create log directory %q: %v", logDir, err)
  561. return
  562. }
  563. c = &config{
  564. Buffer: buffer,
  565. Config: log.FileConfig{
  566. Level: level,
  567. Filename: logPath,
  568. FileRotationConfig: log.FileRotationConfig{
  569. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  570. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  571. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  572. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  573. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  574. },
  575. },
  576. }
  577. err = log.NewFile(c.Buffer, c.Config)
  578. case log.DefaultSlackName:
  579. c = &config{
  580. Buffer: buffer,
  581. Config: log.SlackConfig{
  582. Level: level,
  583. URL: sec.Key("URL").String(),
  584. },
  585. }
  586. err = log.NewSlack(c.Buffer, c.Config)
  587. case log.DefaultDiscordName:
  588. c = &config{
  589. Buffer: buffer,
  590. Config: log.DiscordConfig{
  591. Level: level,
  592. URL: sec.Key("URL").String(),
  593. Username: sec.Key("USERNAME").String(),
  594. },
  595. }
  596. default:
  597. continue
  598. }
  599. if err != nil {
  600. log.Fatal("Failed to init %s logger: %v", mode, err)
  601. return
  602. }
  603. LogConfigs[i] = c
  604. log.Trace("Log mode: %s (%s)", strings.Title(mode), strings.Title(strings.ToLower(level.String())))
  605. }
  606. if !hasConsole {
  607. log.Remove(log.DefaultConsoleName)
  608. }
  609. }
  610. var Service struct {
  611. ActiveCodeLives int
  612. ResetPwdCodeLives int
  613. RegisterEmailConfirm bool
  614. DisableRegistration bool
  615. ShowRegistrationButton bool
  616. RequireSignInView bool
  617. EnableNotifyMail bool
  618. EnableReverseProxyAuth bool
  619. EnableReverseProxyAutoRegister bool
  620. EnableCaptcha bool
  621. }
  622. func newService() {
  623. sec := File.Section("service")
  624. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  625. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  626. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  627. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  628. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  629. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  630. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  631. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  632. }
  633. func newCacheService() {
  634. CacheAdapter = File.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  635. switch CacheAdapter {
  636. case "memory":
  637. CacheInterval = File.Section("cache").Key("INTERVAL").MustInt(60)
  638. case "redis", "memcache":
  639. CacheConn = strings.Trim(File.Section("cache").Key("HOST").String(), "\" ")
  640. default:
  641. log.Fatal("Unrecognized cache adapter %q", CacheAdapter)
  642. return
  643. }
  644. log.Trace("Cache service is enabled")
  645. }
  646. func newSessionService() {
  647. SessionConfig.Provider = File.Section("session").Key("PROVIDER").In("memory",
  648. []string{"memory", "file", "redis", "mysql"})
  649. SessionConfig.ProviderConfig = strings.Trim(File.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  650. SessionConfig.CookieName = File.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  651. SessionConfig.CookiePath = Server.Subpath
  652. SessionConfig.Secure = File.Section("session").Key("COOKIE_SECURE").MustBool()
  653. SessionConfig.Gclifetime = File.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  654. SessionConfig.Maxlifetime = File.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  655. CSRFCookieName = File.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  656. log.Trace("Session service is enabled")
  657. }
  658. // Mailer represents mail service.
  659. type Mailer struct {
  660. QueueLength int
  661. SubjectPrefix string
  662. Host string
  663. From string
  664. FromEmail string
  665. User, Passwd string
  666. DisableHelo bool
  667. HeloHostname string
  668. SkipVerify bool
  669. UseCertificate bool
  670. CertFile, KeyFile string
  671. UsePlainText bool
  672. AddPlainTextAlt bool
  673. }
  674. var (
  675. MailService *Mailer
  676. )
  677. // newMailService initializes mail service options from configuration.
  678. // No non-error log will be printed in hook mode.
  679. func newMailService() {
  680. sec := File.Section("mailer")
  681. if !sec.Key("ENABLED").MustBool() {
  682. return
  683. }
  684. MailService = &Mailer{
  685. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  686. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + App.BrandName + "] "),
  687. Host: sec.Key("HOST").String(),
  688. User: sec.Key("USER").String(),
  689. Passwd: sec.Key("PASSWD").String(),
  690. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  691. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  692. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  693. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  694. CertFile: sec.Key("CERT_FILE").String(),
  695. KeyFile: sec.Key("KEY_FILE").String(),
  696. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  697. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  698. }
  699. MailService.From = sec.Key("FROM").MustString(MailService.User)
  700. if len(MailService.From) > 0 {
  701. parsed, err := mail.ParseAddress(MailService.From)
  702. if err != nil {
  703. log.Fatal("Failed to parse value %q for '[mailer] FROM': %v", MailService.From, err)
  704. return
  705. }
  706. MailService.FromEmail = parsed.Address
  707. }
  708. if HookMode {
  709. return
  710. }
  711. log.Trace("Mail service is enabled")
  712. }
  713. func newRegisterMailService() {
  714. if !File.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  715. return
  716. } else if MailService == nil {
  717. log.Warn("Email confirmation is not enabled due to the mail service is not available")
  718. return
  719. }
  720. Service.RegisterEmailConfirm = true
  721. log.Trace("Email confirmation is enabled")
  722. }
  723. // newNotifyMailService initializes notification email service options from configuration.
  724. // No non-error log will be printed in hook mode.
  725. func newNotifyMailService() {
  726. if !File.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  727. return
  728. } else if MailService == nil {
  729. log.Warn("Email notification is not enabled due to the mail service is not available")
  730. return
  731. }
  732. Service.EnableNotifyMail = true
  733. if HookMode {
  734. return
  735. }
  736. log.Trace("Email notification is enabled")
  737. }
  738. func NewService() {
  739. newService()
  740. }
  741. func NewServices() {
  742. newService()
  743. newCacheService()
  744. newSessionService()
  745. newMailService()
  746. newRegisterMailService()
  747. newNotifyMailService()
  748. }
  749. // HookMode indicates whether program starts as Git server-side hook callback.
  750. var HookMode bool
  751. // NewPostReceiveHookServices initializes all services that are needed by
  752. // Git server-side post-receive hook callback.
  753. func NewPostReceiveHookServices() {
  754. HookMode = true
  755. newService()
  756. newMailService()
  757. newNotifyMailService()
  758. }