conf.go 25 KB

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